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