]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/object_safety.rs
Auto merge of #37730 - eddyb:rollup, r=eddyb
[rust.git] / src / librustc / traits / object_safety.rs
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
20 use super::elaborate_predicates;
21
22 use hir::def_id::DefId;
23 use traits;
24 use ty::{self, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
25 use syntax::ast;
26
27 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
28 pub enum ObjectSafetyViolation {
29     /// Self : Sized declared on the trait
30     SizedSelf,
31
32     /// Supertrait reference references `Self` an in illegal location
33     /// (e.g. `trait Foo : Bar<Self>`)
34     SupertraitSelf,
35
36     /// Method has something illegal
37     Method(ast::Name, MethodViolationCode),
38 }
39
40 /// Reasons a method might not be object-safe.
41 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
42 pub enum MethodViolationCode {
43     /// e.g., `fn foo()`
44     StaticMethod,
45
46     /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self`
47     ReferencesSelf,
48
49     /// e.g., `fn foo<A>()`
50     Generic,
51 }
52
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);
57
58         let result = def.object_safety().unwrap_or_else(|| {
59             let result = self.object_safety_violations(trait_def_id).is_empty();
60
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);
65
66             result
67         });
68
69         debug!("is_object_safe({:?}) = {}", trait_def_id, result);
70
71         result
72     }
73
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
77     /// type collection.
78     pub fn astconv_object_safety_violations(self, trait_def_id: DefId)
79                                             -> Vec<ObjectSafetyViolation>
80     {
81         let mut violations = vec![];
82
83         if self.supertraits_reference_self(trait_def_id) {
84             violations.push(ObjectSafetyViolation::SupertraitSelf);
85         }
86
87         debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}",
88                trait_def_id,
89                violations);
90
91         violations
92     }
93
94     pub fn object_safety_violations(self, trait_def_id: DefId)
95                                     -> Vec<ObjectSafetyViolation>
96     {
97         traits::supertrait_def_ids(self, trait_def_id)
98             .flat_map(|def_id| self.object_safety_violations_for_trait(def_id))
99             .collect()
100     }
101
102     fn object_safety_violations_for_trait(self, trait_def_id: DefId)
103                                           -> Vec<ObjectSafetyViolation>
104     {
105         // Check methods for violations.
106         let mut violations: Vec<_> = self.associated_items(trait_def_id)
107             .filter(|item| item.kind == ty::AssociatedKind::Method)
108             .filter_map(|item| {
109                 self.object_safety_violation_for_method(trait_def_id, &item)
110                     .map(|code| ObjectSafetyViolation::Method(item.name, code))
111             }).collect();
112
113         // Check the trait itself.
114         if self.trait_has_sized_self(trait_def_id) {
115             violations.push(ObjectSafetyViolation::SizedSelf);
116         }
117         if self.supertraits_reference_self(trait_def_id) {
118             violations.push(ObjectSafetyViolation::SupertraitSelf);
119         }
120
121         debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
122                trait_def_id,
123                violations);
124
125         violations
126     }
127
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);
133         predicates
134             .predicates
135             .into_iter()
136             .map(|predicate| predicate.subst_supertrait(self, &trait_ref))
137             .any(|predicate| {
138                 match predicate {
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())
142                     }
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(..) => {
150                         false
151                     }
152                 }
153             })
154     }
155
156     fn trait_has_sized_self(self, trait_def_id: DefId) -> bool {
157         self.generics_require_sized_self(trait_def_id)
158     }
159
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! */ }
164         };
165
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)
172             .any(|predicate| {
173                 match predicate {
174                     ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
175                         trait_pred.0.self_ty().is_self()
176                     }
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(..) => {
185                         false
186                     }
187                 }
188             })
189     }
190
191     /// Returns `Some(_)` if this method makes the containing trait not object safe.
192     fn object_safety_violation_for_method(self,
193                                           trait_def_id: DefId,
194                                           method: &ty::AssociatedItem)
195                                           -> Option<MethodViolationCode>
196     {
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) {
200             return None;
201         }
202
203         self.virtual_call_violation_for_method(trait_def_id, method)
204     }
205
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,
211                                  trait_def_id: DefId,
212                                  method: &ty::AssociatedItem)
213                                  -> bool
214     {
215         // Any method that has a `Self : Sized` requisite can't be called.
216         if self.generics_require_sized_self(method.def_id) {
217             return false;
218         }
219
220         self.virtual_call_violation_for_method(trait_def_id, method).is_none()
221     }
222
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
226     /// `Self:Sized`.
227     fn virtual_call_violation_for_method(self,
228                                          trait_def_id: DefId,
229                                          method: &ty::AssociatedItem)
230                                          -> Option<MethodViolationCode>
231     {
232         // The method's first parameter must be something that derefs (or
233         // autorefs) to `&self`. For now, we only accept `self`, `&self`
234         // and `Box<Self>`.
235         if !method.method_has_self_argument {
236             return Some(MethodViolationCode::StaticMethod);
237         }
238
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);
245             }
246         }
247         if self.contains_illegal_self_type_reference(trait_def_id, sig.0.output) {
248             return Some(MethodViolationCode::ReferencesSelf);
249         }
250
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);
254         }
255
256         None
257     }
258
259     fn contains_illegal_self_type_reference(self,
260                                             trait_def_id: DefId,
261                                             ty: Ty<'tcx>)
262                                             -> bool
263     {
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
270         // itself.
271         //
272         // ```rust
273         // trait SuperTrait {
274         //     type X;
275         // }
276         //
277         // trait Trait : SuperTrait {
278         //     type Y;
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
286         // }
287         // ```
288         //
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:
291         //
292         // ```rust
293         // trait Trait : SuperTrait {
294         //     ...
295         //     fn foo(&self) -> <Self as SomeOtherTrait>::X;
296         // }
297         // ```
298         //
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.
302
303         let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
304         let mut error = false;
305         ty.maybe_walk(|ty| {
306             match ty.sty {
307                 ty::TyParam(ref param_ty) => {
308                     if param_ty.is_self() {
309                         error = true;
310                     }
311
312                     false // no contained types to walk
313                 }
314
315                 ty::TyProjection(ref data) => {
316                     // This is a projected type `<Foo as SomeTrait>::X`.
317
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());
323                     }
324
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);
336
337                     if is_supertrait_of_current_trait {
338                         false // do not walk contained types, do not report error, do collect $200
339                     } else {
340                         true // DO walk contained types, POSSIBLY reporting an error
341                     }
342                 }
343
344                 _ => true, // walk contained types, if any
345             }
346         });
347
348         error
349     }
350 }