]> git.proxmox.com Git - rustc.git/blame - src/librustc/middle/traits/object_safety.rs
Imported Upstream version 1.8.0+dfsg1
[rustc.git] / src / librustc / middle / traits / object_safety.rs
CommitLineData
1a4d82fc
JJ
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.
4//
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.
10
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,
14//! they must:
15//!
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
19
20use super::supertraits;
21use super::elaborate_predicates;
22
e9174d1e 23use middle::def_id::DefId;
85aaf69f 24use middle::subst::{self, SelfSpace, TypeSpace};
1a4d82fc 25use middle::traits;
9cc50fc6 26use middle::ty::{self, ToPolyTraitRef, Ty, TypeFoldable};
1a4d82fc
JJ
27use std::rc::Rc;
28use syntax::ast;
1a4d82fc 29
e9174d1e 30#[derive(Clone, Debug, PartialEq, Eq, Hash)]
1a4d82fc
JJ
31pub enum ObjectSafetyViolation<'tcx> {
32 /// Self : Sized declared on the trait
33 SizedSelf,
34
85aaf69f
SL
35 /// Supertrait reference references `Self` an in illegal location
36 /// (e.g. `trait Foo : Bar<Self>`)
37 SupertraitSelf,
38
1a4d82fc
JJ
39 /// Method has something illegal
40 Method(Rc<ty::Method<'tcx>>, MethodViolationCode),
41}
42
43/// Reasons a method might not be object-safe.
e9174d1e 44#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1a4d82fc 45pub enum MethodViolationCode {
1a4d82fc
JJ
46 /// e.g., `fn foo()`
47 StaticMethod,
48
49 /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self`
50 ReferencesSelf,
51
52 /// e.g., `fn foo<A>()`
53 Generic,
54}
55
56pub fn is_object_safe<'tcx>(tcx: &ty::ctxt<'tcx>,
e9174d1e 57 trait_def_id: DefId)
1a4d82fc
JJ
58 -> bool
59{
60 // Because we query yes/no results frequently, we keep a cache:
c1a9b12d 61 let def = tcx.lookup_trait_def(trait_def_id);
1a4d82fc 62
d9579d0f
AL
63 let result = def.object_safety().unwrap_or_else(|| {
64 let result = object_safety_violations(tcx, trait_def_id).is_empty();
1a4d82fc 65
d9579d0f
AL
66 // Record just a yes/no result in the cache; this is what is
67 // queried most frequently. Note that this may overwrite a
68 // previous result, but always with the same thing.
69 def.set_object_safety(result);
1a4d82fc 70
d9579d0f
AL
71 result
72 });
1a4d82fc 73
62682a34 74 debug!("is_object_safe({:?}) = {}", trait_def_id, result);
1a4d82fc
JJ
75
76 result
77}
78
b039eaaf
SL
79/// Returns the object safety violations that affect
80/// astconv - currently, Self in supertraits. This is needed
81/// because `object_safety_violations` can't be used during
82/// type collection.
83pub fn astconv_object_safety_violations<'tcx>(tcx: &ty::ctxt<'tcx>,
84 trait_def_id: DefId)
85 -> Vec<ObjectSafetyViolation<'tcx>>
86{
87 let mut violations = vec![];
88
89 if supertraits_reference_self(tcx, trait_def_id) {
90 violations.push(ObjectSafetyViolation::SupertraitSelf);
91 }
92
93 debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
94 trait_def_id,
95 violations);
96
97 violations
98}
99
1a4d82fc 100pub fn object_safety_violations<'tcx>(tcx: &ty::ctxt<'tcx>,
e9174d1e 101 trait_def_id: DefId)
1a4d82fc
JJ
102 -> Vec<ObjectSafetyViolation<'tcx>>
103{
c34b1796 104 traits::supertrait_def_ids(tcx, trait_def_id)
62682a34 105 .flat_map(|def_id| object_safety_violations_for_trait(tcx, def_id))
1a4d82fc
JJ
106 .collect()
107}
108
109fn object_safety_violations_for_trait<'tcx>(tcx: &ty::ctxt<'tcx>,
e9174d1e 110 trait_def_id: DefId)
1a4d82fc
JJ
111 -> Vec<ObjectSafetyViolation<'tcx>>
112{
113 // Check methods for violations.
114 let mut violations: Vec<_> =
c1a9b12d 115 tcx.trait_items(trait_def_id).iter()
e9174d1e 116 .filter_map(|item| {
1a4d82fc
JJ
117 match *item {
118 ty::MethodTraitItem(ref m) => {
7453a54e 119 object_safety_violation_for_method(tcx, trait_def_id, &m)
1a4d82fc 120 .map(|code| ObjectSafetyViolation::Method(m.clone(), code))
1a4d82fc 121 }
e9174d1e 122 _ => None,
1a4d82fc
JJ
123 }
124 })
125 .collect();
126
127 // Check the trait itself.
128 if trait_has_sized_self(tcx, trait_def_id) {
129 violations.push(ObjectSafetyViolation::SizedSelf);
130 }
85aaf69f
SL
131 if supertraits_reference_self(tcx, trait_def_id) {
132 violations.push(ObjectSafetyViolation::SupertraitSelf);
133 }
1a4d82fc 134
62682a34
SL
135 debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
136 trait_def_id,
137 violations);
1a4d82fc
JJ
138
139 violations
140}
141
b039eaaf
SL
142pub fn supertraits_reference_self<'tcx>(tcx: &ty::ctxt<'tcx>,
143 trait_def_id: DefId)
144 -> bool
85aaf69f 145{
c1a9b12d 146 let trait_def = tcx.lookup_trait_def(trait_def_id);
85aaf69f 147 let trait_ref = trait_def.trait_ref.clone();
c34b1796 148 let trait_ref = trait_ref.to_poly_trait_ref();
c1a9b12d 149 let predicates = tcx.lookup_super_predicates(trait_def_id);
85aaf69f 150 predicates
c34b1796 151 .predicates
85aaf69f 152 .into_iter()
c34b1796 153 .map(|predicate| predicate.subst_supertrait(tcx, &trait_ref))
85aaf69f
SL
154 .any(|predicate| {
155 match predicate {
156 ty::Predicate::Trait(ref data) => {
157 // In the case of a trait predicate, we can skip the "self" type.
9346a6ac
AL
158 data.0.trait_ref.substs.types.get_slice(TypeSpace)
159 .iter()
160 .cloned()
b039eaaf 161 .any(|t| t.has_self_ty())
85aaf69f
SL
162 }
163 ty::Predicate::Projection(..) |
e9174d1e
SL
164 ty::Predicate::WellFormed(..) |
165 ty::Predicate::ObjectSafe(..) |
85aaf69f
SL
166 ty::Predicate::TypeOutlives(..) |
167 ty::Predicate::RegionOutlives(..) |
168 ty::Predicate::Equate(..) => {
169 false
170 }
171 }
172 })
173}
174
1a4d82fc 175fn trait_has_sized_self<'tcx>(tcx: &ty::ctxt<'tcx>,
e9174d1e 176 trait_def_id: DefId)
1a4d82fc 177 -> bool
c34b1796 178{
c1a9b12d
SL
179 let trait_def = tcx.lookup_trait_def(trait_def_id);
180 let trait_predicates = tcx.lookup_predicates(trait_def_id);
c34b1796
AL
181 generics_require_sized_self(tcx, &trait_def.generics, &trait_predicates)
182}
183
184fn generics_require_sized_self<'tcx>(tcx: &ty::ctxt<'tcx>,
185 generics: &ty::Generics<'tcx>,
186 predicates: &ty::GenericPredicates<'tcx>)
187 -> bool
1a4d82fc 188{
1a4d82fc
JJ
189 let sized_def_id = match tcx.lang_items.sized_trait() {
190 Some(def_id) => def_id,
191 None => { return false; /* No Sized trait, can't require it! */ }
192 };
193
194 // Search for a predicate like `Self : Sized` amongst the trait bounds.
9cc50fc6
SL
195 let free_substs = tcx.construct_free_substs(generics,
196 tcx.region_maps.node_extent(ast::DUMMY_NODE_ID));
c34b1796 197 let predicates = predicates.instantiate(tcx, &free_substs).predicates.into_vec();
1a4d82fc
JJ
198 elaborate_predicates(tcx, predicates)
199 .any(|predicate| {
200 match predicate {
201 ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
b039eaaf 202 trait_pred.0.self_ty().is_self()
1a4d82fc
JJ
203 }
204 ty::Predicate::Projection(..) |
205 ty::Predicate::Trait(..) |
206 ty::Predicate::Equate(..) |
207 ty::Predicate::RegionOutlives(..) |
e9174d1e
SL
208 ty::Predicate::WellFormed(..) |
209 ty::Predicate::ObjectSafe(..) |
1a4d82fc
JJ
210 ty::Predicate::TypeOutlives(..) => {
211 false
212 }
213 }
214 })
215}
216
c34b1796
AL
217/// Returns `Some(_)` if this method makes the containing trait not object safe.
218fn object_safety_violation_for_method<'tcx>(tcx: &ty::ctxt<'tcx>,
e9174d1e 219 trait_def_id: DefId,
c34b1796
AL
220 method: &ty::Method<'tcx>)
221 -> Option<MethodViolationCode>
1a4d82fc 222{
c34b1796
AL
223 // Any method that has a `Self : Sized` requisite is otherwise
224 // exempt from the regulations.
225 if generics_require_sized_self(tcx, &method.generics, &method.predicates) {
226 return None;
227 }
228
229 virtual_call_violation_for_method(tcx, trait_def_id, method)
230}
1a4d82fc 231
c34b1796
AL
232/// We say a method is *vtable safe* if it can be invoked on a trait
233/// object. Note that object-safe traits can have some
234/// non-vtable-safe methods, so long as they require `Self:Sized` or
235/// otherwise ensure that they cannot be used when `Self=Trait`.
236pub fn is_vtable_safe_method<'tcx>(tcx: &ty::ctxt<'tcx>,
e9174d1e 237 trait_def_id: DefId,
c34b1796
AL
238 method: &ty::Method<'tcx>)
239 -> bool
240{
241 virtual_call_violation_for_method(tcx, trait_def_id, method).is_none()
242}
243
244/// Returns `Some(_)` if this method cannot be called on a trait
245/// object; this does not necessarily imply that the enclosing trait
246/// is not object safe, because the method might have a where clause
247/// `Self:Sized`.
248fn virtual_call_violation_for_method<'tcx>(tcx: &ty::ctxt<'tcx>,
e9174d1e 249 trait_def_id: DefId,
c34b1796
AL
250 method: &ty::Method<'tcx>)
251 -> Option<MethodViolationCode>
252{
253 // The method's first parameter must be something that derefs (or
254 // autorefs) to `&self`. For now, we only accept `self`, `&self`
255 // and `Box<Self>`.
256 match method.explicit_self {
9cc50fc6 257 ty::ExplicitSelfCategory::Static => {
1a4d82fc
JJ
258 return Some(MethodViolationCode::StaticMethod);
259 }
260
9cc50fc6
SL
261 ty::ExplicitSelfCategory::ByValue |
262 ty::ExplicitSelfCategory::ByReference(..) |
263 ty::ExplicitSelfCategory::ByBox => {
1a4d82fc
JJ
264 }
265 }
266
267 // The `Self` type is erased, so it should not appear in list of
268 // arguments or return type apart from the receiver.
269 let ref sig = method.fty.sig;
85aaf69f 270 for &input_ty in &sig.0.inputs[1..] {
1a4d82fc
JJ
271 if contains_illegal_self_type_reference(tcx, trait_def_id, input_ty) {
272 return Some(MethodViolationCode::ReferencesSelf);
273 }
274 }
275 if let ty::FnConverging(result_type) = sig.0.output {
276 if contains_illegal_self_type_reference(tcx, trait_def_id, result_type) {
277 return Some(MethodViolationCode::ReferencesSelf);
278 }
279 }
280
281 // We can't monomorphize things like `fn foo<A>(...)`.
282 if !method.generics.types.is_empty_in(subst::FnSpace) {
283 return Some(MethodViolationCode::Generic);
284 }
285
286 None
287}
288
289fn contains_illegal_self_type_reference<'tcx>(tcx: &ty::ctxt<'tcx>,
e9174d1e 290 trait_def_id: DefId,
1a4d82fc
JJ
291 ty: Ty<'tcx>)
292 -> bool
293{
294 // This is somewhat subtle. In general, we want to forbid
295 // references to `Self` in the argument and return types,
296 // since the value of `Self` is erased. However, there is one
297 // exception: it is ok to reference `Self` in order to access
298 // an associated type of the current trait, since we retain
299 // the value of those associated types in the object type
300 // itself.
301 //
302 // ```rust
303 // trait SuperTrait {
304 // type X;
305 // }
306 //
307 // trait Trait : SuperTrait {
308 // type Y;
309 // fn foo(&self, x: Self) // bad
310 // fn foo(&self) -> Self // bad
311 // fn foo(&self) -> Option<Self> // bad
312 // fn foo(&self) -> Self::Y // OK, desugars to next example
313 // fn foo(&self) -> <Self as Trait>::Y // OK
314 // fn foo(&self) -> Self::X // OK, desugars to next example
315 // fn foo(&self) -> <Self as SuperTrait>::X // OK
316 // }
317 // ```
318 //
319 // However, it is not as simple as allowing `Self` in a projected
320 // type, because there are illegal ways to use `Self` as well:
321 //
322 // ```rust
323 // trait Trait : SuperTrait {
324 // ...
325 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
326 // }
327 // ```
328 //
329 // Here we will not have the type of `X` recorded in the
330 // object type, and we cannot resolve `Self as SomeOtherTrait`
331 // without knowing what `Self` is.
332
333 let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
334 let mut error = false;
c1a9b12d 335 ty.maybe_walk(|ty| {
1a4d82fc 336 match ty.sty {
62682a34 337 ty::TyParam(ref param_ty) => {
1a4d82fc
JJ
338 if param_ty.space == SelfSpace {
339 error = true;
340 }
341
342 false // no contained types to walk
343 }
344
62682a34 345 ty::TyProjection(ref data) => {
1a4d82fc
JJ
346 // This is a projected type `<Foo as SomeTrait>::X`.
347
348 // Compute supertraits of current trait lazily.
349 if supertraits.is_none() {
c1a9b12d 350 let trait_def = tcx.lookup_trait_def(trait_def_id);
1a4d82fc
JJ
351 let trait_ref = ty::Binder(trait_def.trait_ref.clone());
352 supertraits = Some(traits::supertraits(tcx, trait_ref).collect());
353 }
354
355 // Determine whether the trait reference `Foo as
356 // SomeTrait` is in fact a supertrait of the
357 // current trait. In that case, this type is
358 // legal, because the type `X` will be specified
359 // in the object type. Note that we can just use
360 // direct equality here because all of these types
361 // are part of the formal parameter listing, and
362 // hence there should be no inference variables.
363 let projection_trait_ref = ty::Binder(data.trait_ref.clone());
364 let is_supertrait_of_current_trait =
365 supertraits.as_ref().unwrap().contains(&projection_trait_ref);
366
367 if is_supertrait_of_current_trait {
368 false // do not walk contained types, do not report error, do collect $200
369 } else {
370 true // DO walk contained types, POSSIBLY reporting an error
371 }
372 }
373
374 _ => true, // walk contained types, if any
375 }
376 });
377
378 error
379}