]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/object_safety.rs
Auto merge of #41267 - alexcrichton:fix-analysis-dist, r=alexcrichton
[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 supertraits or where-clauses".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::Subtype(..) |
182                     ty::Predicate::Equate(..) => {
183                         false
184                     }
185                 }
186             })
187     }
188
189     fn trait_has_sized_self(self, trait_def_id: DefId) -> bool {
190         self.generics_require_sized_self(trait_def_id)
191     }
192
193     fn generics_require_sized_self(self, def_id: DefId) -> bool {
194         let sized_def_id = match self.lang_items.sized_trait() {
195             Some(def_id) => def_id,
196             None => { return false; /* No Sized trait, can't require it! */ }
197         };
198
199         // Search for a predicate like `Self : Sized` amongst the trait bounds.
200         let free_substs = self.construct_free_substs(def_id,
201             self.region_maps.node_extent(ast::DUMMY_NODE_ID));
202         let predicates = self.item_predicates(def_id);
203         let predicates = predicates.instantiate(self, free_substs).predicates;
204         elaborate_predicates(self, predicates)
205             .any(|predicate| {
206                 match predicate {
207                     ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
208                         trait_pred.0.self_ty().is_self()
209                     }
210                     ty::Predicate::Projection(..) |
211                     ty::Predicate::Trait(..) |
212                     ty::Predicate::Equate(..) |
213                     ty::Predicate::Subtype(..) |
214                     ty::Predicate::RegionOutlives(..) |
215                     ty::Predicate::WellFormed(..) |
216                     ty::Predicate::ObjectSafe(..) |
217                     ty::Predicate::ClosureKind(..) |
218                     ty::Predicate::TypeOutlives(..) => {
219                         false
220                     }
221                 }
222             })
223     }
224
225     /// Returns `Some(_)` if this method makes the containing trait not object safe.
226     fn object_safety_violation_for_method(self,
227                                           trait_def_id: DefId,
228                                           method: &ty::AssociatedItem)
229                                           -> Option<MethodViolationCode>
230     {
231         // Any method that has a `Self : Sized` requisite is otherwise
232         // exempt from the regulations.
233         if self.generics_require_sized_self(method.def_id) {
234             return None;
235         }
236
237         self.virtual_call_violation_for_method(trait_def_id, method)
238     }
239
240     /// We say a method is *vtable safe* if it can be invoked on a trait
241     /// object.  Note that object-safe traits can have some
242     /// non-vtable-safe methods, so long as they require `Self:Sized` or
243     /// otherwise ensure that they cannot be used when `Self=Trait`.
244     pub fn is_vtable_safe_method(self,
245                                  trait_def_id: DefId,
246                                  method: &ty::AssociatedItem)
247                                  -> bool
248     {
249         // Any method that has a `Self : Sized` requisite can't be called.
250         if self.generics_require_sized_self(method.def_id) {
251             return false;
252         }
253
254         self.virtual_call_violation_for_method(trait_def_id, method).is_none()
255     }
256
257     /// Returns `Some(_)` if this method cannot be called on a trait
258     /// object; this does not necessarily imply that the enclosing trait
259     /// is not object safe, because the method might have a where clause
260     /// `Self:Sized`.
261     fn virtual_call_violation_for_method(self,
262                                          trait_def_id: DefId,
263                                          method: &ty::AssociatedItem)
264                                          -> Option<MethodViolationCode>
265     {
266         // The method's first parameter must be something that derefs (or
267         // autorefs) to `&self`. For now, we only accept `self`, `&self`
268         // and `Box<Self>`.
269         if !method.method_has_self_argument {
270             return Some(MethodViolationCode::StaticMethod);
271         }
272
273         // The `Self` type is erased, so it should not appear in list of
274         // arguments or return type apart from the receiver.
275         let ref sig = self.item_type(method.def_id).fn_sig();
276         for input_ty in &sig.skip_binder().inputs()[1..] {
277             if self.contains_illegal_self_type_reference(trait_def_id, input_ty) {
278                 return Some(MethodViolationCode::ReferencesSelf);
279             }
280         }
281         if self.contains_illegal_self_type_reference(trait_def_id, sig.output().skip_binder()) {
282             return Some(MethodViolationCode::ReferencesSelf);
283         }
284
285         // We can't monomorphize things like `fn foo<A>(...)`.
286         if !self.item_generics(method.def_id).types.is_empty() {
287             return Some(MethodViolationCode::Generic);
288         }
289
290         None
291     }
292
293     fn contains_illegal_self_type_reference(self,
294                                             trait_def_id: DefId,
295                                             ty: Ty<'tcx>)
296                                             -> bool
297     {
298         // This is somewhat subtle. In general, we want to forbid
299         // references to `Self` in the argument and return types,
300         // since the value of `Self` is erased. However, there is one
301         // exception: it is ok to reference `Self` in order to access
302         // an associated type of the current trait, since we retain
303         // the value of those associated types in the object type
304         // itself.
305         //
306         // ```rust
307         // trait SuperTrait {
308         //     type X;
309         // }
310         //
311         // trait Trait : SuperTrait {
312         //     type Y;
313         //     fn foo(&self, x: Self) // bad
314         //     fn foo(&self) -> Self // bad
315         //     fn foo(&self) -> Option<Self> // bad
316         //     fn foo(&self) -> Self::Y // OK, desugars to next example
317         //     fn foo(&self) -> <Self as Trait>::Y // OK
318         //     fn foo(&self) -> Self::X // OK, desugars to next example
319         //     fn foo(&self) -> <Self as SuperTrait>::X // OK
320         // }
321         // ```
322         //
323         // However, it is not as simple as allowing `Self` in a projected
324         // type, because there are illegal ways to use `Self` as well:
325         //
326         // ```rust
327         // trait Trait : SuperTrait {
328         //     ...
329         //     fn foo(&self) -> <Self as SomeOtherTrait>::X;
330         // }
331         // ```
332         //
333         // Here we will not have the type of `X` recorded in the
334         // object type, and we cannot resolve `Self as SomeOtherTrait`
335         // without knowing what `Self` is.
336
337         let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
338         let mut error = false;
339         ty.maybe_walk(|ty| {
340             match ty.sty {
341                 ty::TyParam(ref param_ty) => {
342                     if param_ty.is_self() {
343                         error = true;
344                     }
345
346                     false // no contained types to walk
347                 }
348
349                 ty::TyProjection(ref data) => {
350                     // This is a projected type `<Foo as SomeTrait>::X`.
351
352                     // Compute supertraits of current trait lazily.
353                     if supertraits.is_none() {
354                         let trait_ref = ty::Binder(ty::TraitRef {
355                             def_id: trait_def_id,
356                             substs: Substs::identity_for_item(self, trait_def_id)
357                         });
358                         supertraits = Some(traits::supertraits(self, trait_ref).collect());
359                     }
360
361                     // Determine whether the trait reference `Foo as
362                     // SomeTrait` is in fact a supertrait of the
363                     // current trait. In that case, this type is
364                     // legal, because the type `X` will be specified
365                     // in the object type.  Note that we can just use
366                     // direct equality here because all of these types
367                     // are part of the formal parameter listing, and
368                     // hence there should be no inference variables.
369                     let projection_trait_ref = ty::Binder(data.trait_ref.clone());
370                     let is_supertrait_of_current_trait =
371                         supertraits.as_ref().unwrap().contains(&projection_trait_ref);
372
373                     if is_supertrait_of_current_trait {
374                         false // do not walk contained types, do not report error, do collect $200
375                     } else {
376                         true // DO walk contained types, POSSIBLY reporting an error
377                     }
378                 }
379
380                 _ => true, // walk contained types, if any
381             }
382         });
383
384         error
385     }
386 }