]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/object_safety.rs
Rollup merge of #40128 - cengizIO:master, r=nikomatsakis
[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 std::borrow::Cow;
27 use syntax::ast;
28
29 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
30 pub enum ObjectSafetyViolation {
31     /// Self : Sized declared on the trait
32     SizedSelf,
33
34     /// Supertrait reference references `Self` an in illegal location
35     /// (e.g. `trait Foo : Bar<Self>`)
36     SupertraitSelf,
37
38     /// Method has something illegal
39     Method(ast::Name, MethodViolationCode),
40 }
41
42 impl ObjectSafetyViolation {
43     pub fn error_msg(&self) -> Cow<'static, str> {
44         match *self {
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(),
57         }
58     }
59 }
60
61 /// Reasons a method might not be object-safe.
62 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
63 pub enum MethodViolationCode {
64     /// e.g., `fn foo()`
65     StaticMethod,
66
67     /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self`
68     ReferencesSelf,
69
70     /// e.g., `fn foo<A>()`
71     Generic,
72 }
73
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);
78
79         let result = def.object_safety().unwrap_or_else(|| {
80             let result = self.object_safety_violations(trait_def_id).is_empty();
81
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);
86
87             result
88         });
89
90         debug!("is_object_safe({:?}) = {}", trait_def_id, result);
91
92         result
93     }
94
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
98     /// type collection.
99     pub fn astconv_object_safety_violations(self, trait_def_id: DefId)
100                                             -> Vec<ObjectSafetyViolation>
101     {
102         let mut violations = vec![];
103
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);
107             }
108         }
109
110         debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}",
111                trait_def_id,
112                violations);
113
114         violations
115     }
116
117     pub fn object_safety_violations(self, trait_def_id: DefId)
118                                     -> Vec<ObjectSafetyViolation>
119     {
120         traits::supertrait_def_ids(self, trait_def_id)
121             .flat_map(|def_id| self.object_safety_violations_for_trait(def_id))
122             .collect()
123     }
124
125     fn object_safety_violations_for_trait(self, trait_def_id: DefId)
126                                           -> Vec<ObjectSafetyViolation>
127     {
128         // Check methods for violations.
129         let mut violations: Vec<_> = self.associated_items(trait_def_id)
130             .filter(|item| item.kind == ty::AssociatedKind::Method)
131             .filter_map(|item| {
132                 self.object_safety_violation_for_method(trait_def_id, &item)
133                     .map(|code| ObjectSafetyViolation::Method(item.name, code))
134             }).collect();
135
136         // Check the trait itself.
137         if self.trait_has_sized_self(trait_def_id) {
138             violations.push(ObjectSafetyViolation::SizedSelf);
139         }
140         if self.predicates_reference_self(trait_def_id, false) {
141             violations.push(ObjectSafetyViolation::SupertraitSelf);
142         }
143
144         debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
145                trait_def_id,
146                violations);
147
148         violations
149     }
150
151     fn predicates_reference_self(
152         self,
153         trait_def_id: DefId,
154         supertraits_only: bool) -> bool
155     {
156         let trait_ref = ty::Binder(ty::TraitRef {
157             def_id: trait_def_id,
158             substs: Substs::identity_for_item(self, trait_def_id)
159         });
160         let predicates = if supertraits_only {
161             self.item_super_predicates(trait_def_id)
162         } else {
163             self.item_predicates(trait_def_id)
164         };
165         predicates
166             .predicates
167             .into_iter()
168             .map(|predicate| predicate.subst_supertrait(self, &trait_ref))
169             .any(|predicate| {
170                 match predicate {
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())
174                     }
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(..) => {
182                         false
183                     }
184                 }
185             })
186     }
187
188     fn trait_has_sized_self(self, trait_def_id: DefId) -> bool {
189         self.generics_require_sized_self(trait_def_id)
190     }
191
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! */ }
196         };
197
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)
204             .any(|predicate| {
205                 match predicate {
206                     ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
207                         trait_pred.0.self_ty().is_self()
208                     }
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(..) => {
217                         false
218                     }
219                 }
220             })
221     }
222
223     /// Returns `Some(_)` if this method makes the containing trait not object safe.
224     fn object_safety_violation_for_method(self,
225                                           trait_def_id: DefId,
226                                           method: &ty::AssociatedItem)
227                                           -> Option<MethodViolationCode>
228     {
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) {
232             return None;
233         }
234
235         self.virtual_call_violation_for_method(trait_def_id, method)
236     }
237
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,
243                                  trait_def_id: DefId,
244                                  method: &ty::AssociatedItem)
245                                  -> bool
246     {
247         // Any method that has a `Self : Sized` requisite can't be called.
248         if self.generics_require_sized_self(method.def_id) {
249             return false;
250         }
251
252         self.virtual_call_violation_for_method(trait_def_id, method).is_none()
253     }
254
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
258     /// `Self:Sized`.
259     fn virtual_call_violation_for_method(self,
260                                          trait_def_id: DefId,
261                                          method: &ty::AssociatedItem)
262                                          -> Option<MethodViolationCode>
263     {
264         // The method's first parameter must be something that derefs (or
265         // autorefs) to `&self`. For now, we only accept `self`, `&self`
266         // and `Box<Self>`.
267         if !method.method_has_self_argument {
268             return Some(MethodViolationCode::StaticMethod);
269         }
270
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);
277             }
278         }
279         if self.contains_illegal_self_type_reference(trait_def_id, sig.output().skip_binder()) {
280             return Some(MethodViolationCode::ReferencesSelf);
281         }
282
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);
286         }
287
288         None
289     }
290
291     fn contains_illegal_self_type_reference(self,
292                                             trait_def_id: DefId,
293                                             ty: Ty<'tcx>)
294                                             -> bool
295     {
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
302         // itself.
303         //
304         // ```rust
305         // trait SuperTrait {
306         //     type X;
307         // }
308         //
309         // trait Trait : SuperTrait {
310         //     type Y;
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
318         // }
319         // ```
320         //
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:
323         //
324         // ```rust
325         // trait Trait : SuperTrait {
326         //     ...
327         //     fn foo(&self) -> <Self as SomeOtherTrait>::X;
328         // }
329         // ```
330         //
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.
334
335         let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
336         let mut error = false;
337         ty.maybe_walk(|ty| {
338             match ty.sty {
339                 ty::TyParam(ref param_ty) => {
340                     if param_ty.is_self() {
341                         error = true;
342                     }
343
344                     false // no contained types to walk
345                 }
346
347                 ty::TyProjection(ref data) => {
348                     // This is a projected type `<Foo as SomeTrait>::X`.
349
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)
355                         });
356                         supertraits = Some(traits::supertraits(self, trait_ref).collect());
357                     }
358
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);
370
371                     if is_supertrait_of_current_trait {
372                         false // do not walk contained types, do not report error, do collect $200
373                     } else {
374                         true // DO walk contained types, POSSIBLY reporting an error
375                     }
376                 }
377
378                 _ => true, // walk contained types, if any
379             }
380         });
381
382         error
383     }
384 }