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 AssociatedConst(ast::Name),
45 impl ObjectSafetyViolation {
46 pub fn error_msg(&self) -> Cow<'static, str> {
48 ObjectSafetyViolation::SizedSelf =>
49 "the trait cannot require that `Self : Sized`".into(),
50 ObjectSafetyViolation::SupertraitSelf =>
51 "the trait cannot use `Self` as a type parameter \
52 in the supertraits or where-clauses".into(),
53 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod) =>
54 format!("method `{}` has no receiver", name).into(),
55 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelf) =>
56 format!("method `{}` references the `Self` type \
57 in its arguments or return type", name).into(),
58 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic) =>
59 format!("method `{}` has generic type parameters", name).into(),
60 ObjectSafetyViolation::AssociatedConst(name) =>
61 format!("the trait cannot contain associated consts like `{}`", name).into(),
66 /// Reasons a method might not be object-safe.
67 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
68 pub enum MethodViolationCode {
72 /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self`
75 /// e.g., `fn foo<A>()`
79 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
80 pub fn is_object_safe(self, trait_def_id: DefId) -> bool {
81 // Because we query yes/no results frequently, we keep a cache:
82 let def = self.trait_def(trait_def_id);
84 let result = def.object_safety().unwrap_or_else(|| {
85 let result = self.object_safety_violations(trait_def_id).is_empty();
87 // Record just a yes/no result in the cache; this is what is
88 // queried most frequently. Note that this may overwrite a
89 // previous result, but always with the same thing.
90 def.set_object_safety(result);
95 debug!("is_object_safe({:?}) = {}", trait_def_id, result);
100 /// Returns the object safety violations that affect
101 /// astconv - currently, Self in supertraits. This is needed
102 /// because `object_safety_violations` can't be used during
104 pub fn astconv_object_safety_violations(self, trait_def_id: DefId)
105 -> Vec<ObjectSafetyViolation>
107 let mut violations = vec![];
109 for def_id in traits::supertrait_def_ids(self, trait_def_id) {
110 if self.predicates_reference_self(def_id, true) {
111 violations.push(ObjectSafetyViolation::SupertraitSelf);
115 debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}",
122 pub fn object_safety_violations(self, trait_def_id: DefId)
123 -> Vec<ObjectSafetyViolation>
125 traits::supertrait_def_ids(self, trait_def_id)
126 .flat_map(|def_id| self.object_safety_violations_for_trait(def_id))
130 fn object_safety_violations_for_trait(self, trait_def_id: DefId)
131 -> Vec<ObjectSafetyViolation>
133 // Check methods for violations.
134 let mut violations: Vec<_> = self.associated_items(trait_def_id)
135 .filter(|item| item.kind == ty::AssociatedKind::Method)
137 self.object_safety_violation_for_method(trait_def_id, &item)
138 .map(|code| ObjectSafetyViolation::Method(item.name, code))
141 // Check the trait itself.
142 if self.trait_has_sized_self(trait_def_id) {
143 violations.push(ObjectSafetyViolation::SizedSelf);
145 if self.predicates_reference_self(trait_def_id, false) {
146 violations.push(ObjectSafetyViolation::SupertraitSelf);
149 violations.extend(self.associated_items(trait_def_id)
150 .filter(|item| item.kind == ty::AssociatedKind::Const)
151 .map(|item| ObjectSafetyViolation::AssociatedConst(item.name)));
153 debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
160 fn predicates_reference_self(
163 supertraits_only: bool) -> bool
165 let trait_ref = ty::Binder(ty::TraitRef {
166 def_id: trait_def_id,
167 substs: Substs::identity_for_item(self, trait_def_id)
169 let predicates = if supertraits_only {
170 self.super_predicates_of(trait_def_id)
172 self.predicates_of(trait_def_id)
177 .map(|predicate| predicate.subst_supertrait(self, &trait_ref))
180 ty::Predicate::Trait(ref data) => {
181 // In the case of a trait predicate, we can skip the "self" type.
182 data.skip_binder().input_types().skip(1).any(|t| t.has_self_ty())
184 ty::Predicate::Projection(..) |
185 ty::Predicate::WellFormed(..) |
186 ty::Predicate::ObjectSafe(..) |
187 ty::Predicate::TypeOutlives(..) |
188 ty::Predicate::RegionOutlives(..) |
189 ty::Predicate::ClosureKind(..) |
190 ty::Predicate::Subtype(..) |
191 ty::Predicate::Equate(..) => {
198 fn trait_has_sized_self(self, trait_def_id: DefId) -> bool {
199 self.generics_require_sized_self(trait_def_id)
202 fn generics_require_sized_self(self, def_id: DefId) -> bool {
203 let sized_def_id = match self.lang_items.sized_trait() {
204 Some(def_id) => def_id,
205 None => { return false; /* No Sized trait, can't require it! */ }
208 // Search for a predicate like `Self : Sized` amongst the trait bounds.
209 let free_substs = self.construct_free_substs(def_id,
210 self.region_maps.node_extent(ast::DUMMY_NODE_ID));
211 let predicates = self.predicates_of(def_id);
212 let predicates = predicates.instantiate(self, free_substs).predicates;
213 elaborate_predicates(self, predicates)
216 ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
217 trait_pred.0.self_ty().is_self()
219 ty::Predicate::Projection(..) |
220 ty::Predicate::Trait(..) |
221 ty::Predicate::Equate(..) |
222 ty::Predicate::Subtype(..) |
223 ty::Predicate::RegionOutlives(..) |
224 ty::Predicate::WellFormed(..) |
225 ty::Predicate::ObjectSafe(..) |
226 ty::Predicate::ClosureKind(..) |
227 ty::Predicate::TypeOutlives(..) => {
234 /// Returns `Some(_)` if this method makes the containing trait not object safe.
235 fn object_safety_violation_for_method(self,
237 method: &ty::AssociatedItem)
238 -> Option<MethodViolationCode>
240 // Any method that has a `Self : Sized` requisite is otherwise
241 // exempt from the regulations.
242 if self.generics_require_sized_self(method.def_id) {
246 self.virtual_call_violation_for_method(trait_def_id, method)
249 /// We say a method is *vtable safe* if it can be invoked on a trait
250 /// object. Note that object-safe traits can have some
251 /// non-vtable-safe methods, so long as they require `Self:Sized` or
252 /// otherwise ensure that they cannot be used when `Self=Trait`.
253 pub fn is_vtable_safe_method(self,
255 method: &ty::AssociatedItem)
258 // Any method that has a `Self : Sized` requisite can't be called.
259 if self.generics_require_sized_self(method.def_id) {
263 self.virtual_call_violation_for_method(trait_def_id, method).is_none()
266 /// Returns `Some(_)` if this method cannot be called on a trait
267 /// object; this does not necessarily imply that the enclosing trait
268 /// is not object safe, because the method might have a where clause
270 fn virtual_call_violation_for_method(self,
272 method: &ty::AssociatedItem)
273 -> Option<MethodViolationCode>
275 // The method's first parameter must be something that derefs (or
276 // autorefs) to `&self`. For now, we only accept `self`, `&self`
278 if !method.method_has_self_argument {
279 return Some(MethodViolationCode::StaticMethod);
282 // The `Self` type is erased, so it should not appear in list of
283 // arguments or return type apart from the receiver.
284 let ref sig = self.type_of(method.def_id).fn_sig();
285 for input_ty in &sig.skip_binder().inputs()[1..] {
286 if self.contains_illegal_self_type_reference(trait_def_id, input_ty) {
287 return Some(MethodViolationCode::ReferencesSelf);
290 if self.contains_illegal_self_type_reference(trait_def_id, sig.output().skip_binder()) {
291 return Some(MethodViolationCode::ReferencesSelf);
294 // We can't monomorphize things like `fn foo<A>(...)`.
295 if !self.generics_of(method.def_id).types.is_empty() {
296 return Some(MethodViolationCode::Generic);
302 fn contains_illegal_self_type_reference(self,
307 // This is somewhat subtle. In general, we want to forbid
308 // references to `Self` in the argument and return types,
309 // since the value of `Self` is erased. However, there is one
310 // exception: it is ok to reference `Self` in order to access
311 // an associated type of the current trait, since we retain
312 // the value of those associated types in the object type
316 // trait SuperTrait {
320 // trait Trait : SuperTrait {
322 // fn foo(&self, x: Self) // bad
323 // fn foo(&self) -> Self // bad
324 // fn foo(&self) -> Option<Self> // bad
325 // fn foo(&self) -> Self::Y // OK, desugars to next example
326 // fn foo(&self) -> <Self as Trait>::Y // OK
327 // fn foo(&self) -> Self::X // OK, desugars to next example
328 // fn foo(&self) -> <Self as SuperTrait>::X // OK
332 // However, it is not as simple as allowing `Self` in a projected
333 // type, because there are illegal ways to use `Self` as well:
336 // trait Trait : SuperTrait {
338 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
342 // Here we will not have the type of `X` recorded in the
343 // object type, and we cannot resolve `Self as SomeOtherTrait`
344 // without knowing what `Self` is.
346 let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
347 let mut error = false;
350 ty::TyParam(ref param_ty) => {
351 if param_ty.is_self() {
355 false // no contained types to walk
358 ty::TyProjection(ref data) => {
359 // This is a projected type `<Foo as SomeTrait>::X`.
361 // Compute supertraits of current trait lazily.
362 if supertraits.is_none() {
363 let trait_ref = ty::Binder(ty::TraitRef {
364 def_id: trait_def_id,
365 substs: Substs::identity_for_item(self, trait_def_id)
367 supertraits = Some(traits::supertraits(self, trait_ref).collect());
370 // Determine whether the trait reference `Foo as
371 // SomeTrait` is in fact a supertrait of the
372 // current trait. In that case, this type is
373 // legal, because the type `X` will be specified
374 // in the object type. Note that we can just use
375 // direct equality here because all of these types
376 // are part of the formal parameter listing, and
377 // hence there should be no inference variables.
378 let projection_trait_ref = ty::Binder(data.trait_ref.clone());
379 let is_supertrait_of_current_trait =
380 supertraits.as_ref().unwrap().contains(&projection_trait_ref);
382 if is_supertrait_of_current_trait {
383 false // do not walk contained types, do not report error, do collect $200
385 true // DO walk contained types, POSSIBLY reporting an error
389 _ => true, // walk contained types, if any