]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/object_safety.rs
Auto merge of #38076 - alexcrichton:another-rustbuild-bug, r=japaric
[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, Ty, TyCtxt, TypeFoldable};
25 use ty::subst::Substs;
26 use syntax::ast;
27
28 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
29 pub enum ObjectSafetyViolation {
30     /// Self : Sized declared on the trait
31     SizedSelf,
32
33     /// Supertrait reference references `Self` an in illegal location
34     /// (e.g. `trait Foo : Bar<Self>`)
35     SupertraitSelf,
36
37     /// Method has something illegal
38     Method(ast::Name, MethodViolationCode),
39 }
40
41 /// Reasons a method might not be object-safe.
42 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
43 pub enum MethodViolationCode {
44     /// e.g., `fn foo()`
45     StaticMethod,
46
47     /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self`
48     ReferencesSelf,
49
50     /// e.g., `fn foo<A>()`
51     Generic,
52 }
53
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);
58
59         let result = def.object_safety().unwrap_or_else(|| {
60             let result = self.object_safety_violations(trait_def_id).is_empty();
61
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);
66
67             result
68         });
69
70         debug!("is_object_safe({:?}) = {}", trait_def_id, result);
71
72         result
73     }
74
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
78     /// type collection.
79     pub fn astconv_object_safety_violations(self, trait_def_id: DefId)
80                                             -> Vec<ObjectSafetyViolation>
81     {
82         let mut violations = vec![];
83
84         if self.supertraits_reference_self(trait_def_id) {
85             violations.push(ObjectSafetyViolation::SupertraitSelf);
86         }
87
88         debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}",
89                trait_def_id,
90                violations);
91
92         violations
93     }
94
95     pub fn object_safety_violations(self, trait_def_id: DefId)
96                                     -> Vec<ObjectSafetyViolation>
97     {
98         traits::supertrait_def_ids(self, trait_def_id)
99             .flat_map(|def_id| self.object_safety_violations_for_trait(def_id))
100             .collect()
101     }
102
103     fn object_safety_violations_for_trait(self, trait_def_id: DefId)
104                                           -> Vec<ObjectSafetyViolation>
105     {
106         // Check methods for violations.
107         let mut violations: Vec<_> = self.associated_items(trait_def_id)
108             .filter(|item| item.kind == ty::AssociatedKind::Method)
109             .filter_map(|item| {
110                 self.object_safety_violation_for_method(trait_def_id, &item)
111                     .map(|code| ObjectSafetyViolation::Method(item.name, code))
112             }).collect();
113
114         // Check the trait itself.
115         if self.trait_has_sized_self(trait_def_id) {
116             violations.push(ObjectSafetyViolation::SizedSelf);
117         }
118         if self.supertraits_reference_self(trait_def_id) {
119             violations.push(ObjectSafetyViolation::SupertraitSelf);
120         }
121
122         debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
123                trait_def_id,
124                violations);
125
126         violations
127     }
128
129     fn supertraits_reference_self(self, trait_def_id: DefId) -> bool {
130         let trait_ref = ty::Binder(ty::TraitRef {
131             def_id: trait_def_id,
132             substs: Substs::identity_for_item(self, trait_def_id)
133         });
134         let predicates = self.item_super_predicates(trait_def_id);
135         predicates
136             .predicates
137             .into_iter()
138             .map(|predicate| predicate.subst_supertrait(self, &trait_ref))
139             .any(|predicate| {
140                 match predicate {
141                     ty::Predicate::Trait(ref data) => {
142                         // In the case of a trait predicate, we can skip the "self" type.
143                         data.skip_binder().input_types().skip(1).any(|t| t.has_self_ty())
144                     }
145                     ty::Predicate::Projection(..) |
146                     ty::Predicate::WellFormed(..) |
147                     ty::Predicate::ObjectSafe(..) |
148                     ty::Predicate::TypeOutlives(..) |
149                     ty::Predicate::RegionOutlives(..) |
150                     ty::Predicate::ClosureKind(..) |
151                     ty::Predicate::Equate(..) => {
152                         false
153                     }
154                 }
155             })
156     }
157
158     fn trait_has_sized_self(self, trait_def_id: DefId) -> bool {
159         self.generics_require_sized_self(trait_def_id)
160     }
161
162     fn generics_require_sized_self(self, def_id: DefId) -> bool {
163         let sized_def_id = match self.lang_items.sized_trait() {
164             Some(def_id) => def_id,
165             None => { return false; /* No Sized trait, can't require it! */ }
166         };
167
168         // Search for a predicate like `Self : Sized` amongst the trait bounds.
169         let free_substs = self.construct_free_substs(def_id,
170             self.region_maps.node_extent(ast::DUMMY_NODE_ID));
171         let predicates = self.item_predicates(def_id);
172         let predicates = predicates.instantiate(self, free_substs).predicates;
173         elaborate_predicates(self, predicates)
174             .any(|predicate| {
175                 match predicate {
176                     ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
177                         trait_pred.0.self_ty().is_self()
178                     }
179                     ty::Predicate::Projection(..) |
180                     ty::Predicate::Trait(..) |
181                     ty::Predicate::Equate(..) |
182                     ty::Predicate::RegionOutlives(..) |
183                     ty::Predicate::WellFormed(..) |
184                     ty::Predicate::ObjectSafe(..) |
185                     ty::Predicate::ClosureKind(..) |
186                     ty::Predicate::TypeOutlives(..) => {
187                         false
188                     }
189                 }
190             })
191     }
192
193     /// Returns `Some(_)` if this method makes the containing trait not object safe.
194     fn object_safety_violation_for_method(self,
195                                           trait_def_id: DefId,
196                                           method: &ty::AssociatedItem)
197                                           -> Option<MethodViolationCode>
198     {
199         // Any method that has a `Self : Sized` requisite is otherwise
200         // exempt from the regulations.
201         if self.generics_require_sized_self(method.def_id) {
202             return None;
203         }
204
205         self.virtual_call_violation_for_method(trait_def_id, method)
206     }
207
208     /// We say a method is *vtable safe* if it can be invoked on a trait
209     /// object.  Note that object-safe traits can have some
210     /// non-vtable-safe methods, so long as they require `Self:Sized` or
211     /// otherwise ensure that they cannot be used when `Self=Trait`.
212     pub fn is_vtable_safe_method(self,
213                                  trait_def_id: DefId,
214                                  method: &ty::AssociatedItem)
215                                  -> bool
216     {
217         // Any method that has a `Self : Sized` requisite can't be called.
218         if self.generics_require_sized_self(method.def_id) {
219             return false;
220         }
221
222         self.virtual_call_violation_for_method(trait_def_id, method).is_none()
223     }
224
225     /// Returns `Some(_)` if this method cannot be called on a trait
226     /// object; this does not necessarily imply that the enclosing trait
227     /// is not object safe, because the method might have a where clause
228     /// `Self:Sized`.
229     fn virtual_call_violation_for_method(self,
230                                          trait_def_id: DefId,
231                                          method: &ty::AssociatedItem)
232                                          -> Option<MethodViolationCode>
233     {
234         // The method's first parameter must be something that derefs (or
235         // autorefs) to `&self`. For now, we only accept `self`, `&self`
236         // and `Box<Self>`.
237         if !method.method_has_self_argument {
238             return Some(MethodViolationCode::StaticMethod);
239         }
240
241         // The `Self` type is erased, so it should not appear in list of
242         // arguments or return type apart from the receiver.
243         let ref sig = self.item_type(method.def_id).fn_sig();
244         for input_ty in &sig.skip_binder().inputs()[1..] {
245             if self.contains_illegal_self_type_reference(trait_def_id, input_ty) {
246                 return Some(MethodViolationCode::ReferencesSelf);
247             }
248         }
249         if self.contains_illegal_self_type_reference(trait_def_id, sig.output().skip_binder()) {
250             return Some(MethodViolationCode::ReferencesSelf);
251         }
252
253         // We can't monomorphize things like `fn foo<A>(...)`.
254         if !self.item_generics(method.def_id).types.is_empty() {
255             return Some(MethodViolationCode::Generic);
256         }
257
258         None
259     }
260
261     fn contains_illegal_self_type_reference(self,
262                                             trait_def_id: DefId,
263                                             ty: Ty<'tcx>)
264                                             -> bool
265     {
266         // This is somewhat subtle. In general, we want to forbid
267         // references to `Self` in the argument and return types,
268         // since the value of `Self` is erased. However, there is one
269         // exception: it is ok to reference `Self` in order to access
270         // an associated type of the current trait, since we retain
271         // the value of those associated types in the object type
272         // itself.
273         //
274         // ```rust
275         // trait SuperTrait {
276         //     type X;
277         // }
278         //
279         // trait Trait : SuperTrait {
280         //     type Y;
281         //     fn foo(&self, x: Self) // bad
282         //     fn foo(&self) -> Self // bad
283         //     fn foo(&self) -> Option<Self> // bad
284         //     fn foo(&self) -> Self::Y // OK, desugars to next example
285         //     fn foo(&self) -> <Self as Trait>::Y // OK
286         //     fn foo(&self) -> Self::X // OK, desugars to next example
287         //     fn foo(&self) -> <Self as SuperTrait>::X // OK
288         // }
289         // ```
290         //
291         // However, it is not as simple as allowing `Self` in a projected
292         // type, because there are illegal ways to use `Self` as well:
293         //
294         // ```rust
295         // trait Trait : SuperTrait {
296         //     ...
297         //     fn foo(&self) -> <Self as SomeOtherTrait>::X;
298         // }
299         // ```
300         //
301         // Here we will not have the type of `X` recorded in the
302         // object type, and we cannot resolve `Self as SomeOtherTrait`
303         // without knowing what `Self` is.
304
305         let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
306         let mut error = false;
307         ty.maybe_walk(|ty| {
308             match ty.sty {
309                 ty::TyParam(ref param_ty) => {
310                     if param_ty.is_self() {
311                         error = true;
312                     }
313
314                     false // no contained types to walk
315                 }
316
317                 ty::TyProjection(ref data) => {
318                     // This is a projected type `<Foo as SomeTrait>::X`.
319
320                     // Compute supertraits of current trait lazily.
321                     if supertraits.is_none() {
322                         let trait_ref = ty::Binder(ty::TraitRef {
323                             def_id: trait_def_id,
324                             substs: Substs::identity_for_item(self, trait_def_id)
325                         });
326                         supertraits = Some(traits::supertraits(self, trait_ref).collect());
327                     }
328
329                     // Determine whether the trait reference `Foo as
330                     // SomeTrait` is in fact a supertrait of the
331                     // current trait. In that case, this type is
332                     // legal, because the type `X` will be specified
333                     // in the object type.  Note that we can just use
334                     // direct equality here because all of these types
335                     // are part of the formal parameter listing, and
336                     // hence there should be no inference variables.
337                     let projection_trait_ref = ty::Binder(data.trait_ref.clone());
338                     let is_supertrait_of_current_trait =
339                         supertraits.as_ref().unwrap().contains(&projection_trait_ref);
340
341                     if is_supertrait_of_current_trait {
342                         false // do not walk contained types, do not report error, do collect $200
343                     } else {
344                         true // DO walk contained types, POSSIBLY reporting an error
345                     }
346                 }
347
348                 _ => true, // walk contained types, if any
349             }
350         });
351
352         error
353     }
354 }