]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/dropck.rs
165cfe6604e8b0ec1905fa60ace5500718a8f509
[rust.git] / src / librustc_typeck / check / dropck.rs
1 // Copyright 2014-2015 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 use check::regionck::RegionCtxt;
12
13 use hir::def_id::DefId;
14 use rustc::infer::{self, InferOk};
15 use rustc::infer::outlives::env::OutlivesEnvironment;
16 use rustc::middle::region;
17 use rustc::ty::subst::{Subst, Substs, UnpackedKind};
18 use rustc::ty::{self, Ty, TyCtxt};
19 use rustc::traits::{self, Reveal, ObligationCause};
20 use util::common::ErrorReported;
21 use util::nodemap::FxHashSet;
22
23 use syntax_pos::Span;
24
25 /// check_drop_impl confirms that the Drop implementation identified by
26 /// `drop_impl_did` is not any more specialized than the type it is
27 /// attached to (Issue #8142).
28 ///
29 /// This means:
30 ///
31 /// 1. The self type must be nominal (this is already checked during
32 ///    coherence),
33 ///
34 /// 2. The generic region/type parameters of the impl's self-type must
35 ///    all be parameters of the Drop impl itself (i.e. no
36 ///    specialization like `impl Drop for Foo<i32>`), and,
37 ///
38 /// 3. Any bounds on the generic parameters must be reflected in the
39 ///    struct/enum definition for the nominal type itself (i.e.
40 ///    cannot do `struct S<T>; impl<T:Clone> Drop for S<T> { ... }`).
41 ///
42 pub fn check_drop_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
43                                  drop_impl_did: DefId)
44                                  -> Result<(), ErrorReported> {
45     let dtor_self_type = tcx.type_of(drop_impl_did);
46     let dtor_predicates = tcx.predicates_of(drop_impl_did);
47     match dtor_self_type.sty {
48         ty::TyAdt(adt_def, self_to_impl_substs) => {
49             ensure_drop_params_and_item_params_correspond(tcx,
50                                                           drop_impl_did,
51                                                           dtor_self_type,
52                                                           adt_def.did)?;
53
54             ensure_drop_predicates_are_implied_by_item_defn(tcx,
55                                                             drop_impl_did,
56                                                             &dtor_predicates,
57                                                             adt_def.did,
58                                                             self_to_impl_substs)
59         }
60         _ => {
61             // Destructors only work on nominal types.  This was
62             // already checked by coherence, but compilation may
63             // not have been terminated.
64             let span = tcx.def_span(drop_impl_did);
65             tcx.sess.delay_span_bug(span,
66                             &format!("should have been rejected by coherence check: {}",
67                             dtor_self_type));
68             Err(ErrorReported)
69         }
70     }
71 }
72
73 fn ensure_drop_params_and_item_params_correspond<'a, 'tcx>(
74     tcx: TyCtxt<'a, 'tcx, 'tcx>,
75     drop_impl_did: DefId,
76     drop_impl_ty: Ty<'tcx>,
77     self_type_did: DefId)
78     -> Result<(), ErrorReported>
79 {
80     let drop_impl_node_id = tcx.hir.as_local_node_id(drop_impl_did).unwrap();
81
82     // check that the impl type can be made to match the trait type.
83
84     tcx.infer_ctxt().enter(|ref infcx| {
85         let impl_param_env = tcx.param_env(self_type_did);
86         let tcx = infcx.tcx;
87         let mut fulfillment_cx = traits::FulfillmentContext::new();
88
89         let named_type = tcx.type_of(self_type_did);
90
91         let drop_impl_span = tcx.def_span(drop_impl_did);
92         let fresh_impl_substs =
93             infcx.fresh_substs_for_item(ty::UniverseIndex::ROOT, drop_impl_span, drop_impl_did);
94         let fresh_impl_self_ty = drop_impl_ty.subst(tcx, fresh_impl_substs);
95
96         let cause = &ObligationCause::misc(drop_impl_span, drop_impl_node_id);
97         match infcx.at(cause, impl_param_env).eq(named_type, fresh_impl_self_ty) {
98             Ok(InferOk { obligations, .. }) => {
99                 fulfillment_cx.register_predicate_obligations(infcx, obligations);
100             }
101             Err(_) => {
102                 let item_span = tcx.def_span(self_type_did);
103                 struct_span_err!(tcx.sess, drop_impl_span, E0366,
104                                  "Implementations of Drop cannot be specialized")
105                     .span_note(item_span,
106                                "Use same sequence of generic type and region \
107                                 parameters that is on the struct/enum definition")
108                     .emit();
109                 return Err(ErrorReported);
110             }
111         }
112
113         if let Err(ref errors) = fulfillment_cx.select_all_or_error(&infcx) {
114             // this could be reached when we get lazy normalization
115             infcx.report_fulfillment_errors(errors, None);
116             return Err(ErrorReported);
117         }
118
119         let region_scope_tree = region::ScopeTree::default();
120
121         // NB. It seems a bit... suspicious to use an empty param-env
122         // here. The correct thing, I imagine, would be
123         // `OutlivesEnvironment::new(impl_param_env)`, which would
124         // allow region solving to take any `a: 'b` relations on the
125         // impl into account. But I could not create a test case where
126         // it did the wrong thing, so I chose to preserve existing
127         // behavior, since it ought to be simply more
128         // conservative. -nmatsakis
129         let outlives_env = OutlivesEnvironment::new(ty::ParamEnv::empty(Reveal::UserFacing));
130
131         infcx.resolve_regions_and_report_errors(drop_impl_did, &region_scope_tree, &outlives_env);
132         Ok(())
133     })
134 }
135
136 /// Confirms that every predicate imposed by dtor_predicates is
137 /// implied by assuming the predicates attached to self_type_did.
138 fn ensure_drop_predicates_are_implied_by_item_defn<'a, 'tcx>(
139     tcx: TyCtxt<'a, 'tcx, 'tcx>,
140     drop_impl_did: DefId,
141     dtor_predicates: &ty::GenericPredicates<'tcx>,
142     self_type_did: DefId,
143     self_to_impl_substs: &Substs<'tcx>)
144     -> Result<(), ErrorReported>
145 {
146     let mut result = Ok(());
147
148     // Here is an example, analogous to that from
149     // `compare_impl_method`.
150     //
151     // Consider a struct type:
152     //
153     //     struct Type<'c, 'b:'c, 'a> {
154     //         x: &'a Contents            // (contents are irrelevant;
155     //         y: &'c Cell<&'b Contents>, //  only the bounds matter for our purposes.)
156     //     }
157     //
158     // and a Drop impl:
159     //
160     //     impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
161     //         fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
162     //     }
163     //
164     // We start out with self_to_impl_substs, that maps the generic
165     // parameters of Type to that of the Drop impl.
166     //
167     //     self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
168     //
169     // Applying this to the predicates (i.e. assumptions) provided by the item
170     // definition yields the instantiated assumptions:
171     //
172     //     ['y : 'z]
173     //
174     // We then check all of the predicates of the Drop impl:
175     //
176     //     ['y:'z, 'x:'y]
177     //
178     // and ensure each is in the list of instantiated
179     // assumptions. Here, `'y:'z` is present, but `'x:'y` is
180     // absent. So we report an error that the Drop impl injected a
181     // predicate that is not present on the struct definition.
182
183     let self_type_node_id = tcx.hir.as_local_node_id(self_type_did).unwrap();
184
185     let drop_impl_span = tcx.def_span(drop_impl_did);
186
187     // We can assume the predicates attached to struct/enum definition
188     // hold.
189     let generic_assumptions = tcx.predicates_of(self_type_did);
190
191     let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
192     let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
193
194     // An earlier version of this code attempted to do this checking
195     // via the traits::fulfill machinery. However, it ran into trouble
196     // since the fulfill machinery merely turns outlives-predicates
197     // 'a:'b and T:'b into region inference constraints. It is simpler
198     // just to look for all the predicates directly.
199
200     assert_eq!(dtor_predicates.parent, None);
201     for predicate in &dtor_predicates.predicates {
202         // (We do not need to worry about deep analysis of type
203         // expressions etc because the Drop impls are already forced
204         // to take on a structure that is roughly an alpha-renaming of
205         // the generic parameters of the item definition.)
206
207         // This path now just checks *all* predicates via the direct
208         // lookup, rather than using fulfill machinery.
209         //
210         // However, it may be more efficient in the future to batch
211         // the analysis together via the fulfill , rather than the
212         // repeated `contains` calls.
213
214         if !assumptions_in_impl_context.contains(&predicate) {
215             let item_span = tcx.hir.span(self_type_node_id);
216             struct_span_err!(tcx.sess, drop_impl_span, E0367,
217                              "The requirement `{}` is added only by the Drop impl.", predicate)
218                 .span_note(item_span,
219                            "The same requirement must be part of \
220                             the struct/enum definition")
221                 .emit();
222             result = Err(ErrorReported);
223         }
224     }
225
226     result
227 }
228
229 /// check_safety_of_destructor_if_necessary confirms that the type
230 /// expression `typ` conforms to the "Drop Check Rule" from the Sound
231 /// Generic Drop (RFC 769).
232 ///
233 /// ----
234 ///
235 /// The simplified (*) Drop Check Rule is the following:
236 ///
237 /// Let `v` be some value (either temporary or named) and 'a be some
238 /// lifetime (scope). If the type of `v` owns data of type `D`, where
239 ///
240 /// * (1.) `D` has a lifetime- or type-parametric Drop implementation,
241 ///        (where that `Drop` implementation does not opt-out of
242 ///         this check via the `unsafe_destructor_blind_to_params`
243 ///         attribute), and
244 /// * (2.) the structure of `D` can reach a reference of type `&'a _`,
245 ///
246 /// then 'a must strictly outlive the scope of v.
247 ///
248 /// ----
249 ///
250 /// This function is meant to by applied to the type for every
251 /// expression in the program.
252 ///
253 /// ----
254 ///
255 /// (*) The qualifier "simplified" is attached to the above
256 /// definition of the Drop Check Rule, because it is a simplification
257 /// of the original Drop Check rule, which attempted to prove that
258 /// some `Drop` implementations could not possibly access data even if
259 /// it was technically reachable, due to parametricity.
260 ///
261 /// However, (1.) parametricity on its own turned out to be a
262 /// necessary but insufficient condition, and (2.)  future changes to
263 /// the language are expected to make it impossible to ensure that a
264 /// `Drop` implementation is actually parametric with respect to any
265 /// particular type parameter. (In particular, impl specialization is
266 /// expected to break the needed parametricity property beyond
267 /// repair.)
268 ///
269 /// Therefore we have scaled back Drop-Check to a more conservative
270 /// rule that does not attempt to deduce whether a `Drop`
271 /// implementation could not possible access data of a given lifetime;
272 /// instead Drop-Check now simply assumes that if a destructor has
273 /// access (direct or indirect) to a lifetime parameter, then that
274 /// lifetime must be forced to outlive that destructor's dynamic
275 /// extent. We then provide the `unsafe_destructor_blind_to_params`
276 /// attribute as a way for destructor implementations to opt-out of
277 /// this conservative assumption (and thus assume the obligation of
278 /// ensuring that they do not access data nor invoke methods of
279 /// values that have been previously dropped).
280 ///
281 pub fn check_safety_of_destructor_if_necessary<'a, 'gcx, 'tcx>(
282     rcx: &mut RegionCtxt<'a, 'gcx, 'tcx>,
283     ty: Ty<'tcx>,
284     span: Span,
285     scope: region::Scope)
286     -> Result<(), ErrorReported>
287 {
288     debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
289            ty, scope);
290
291
292     let parent_scope = match rcx.region_scope_tree.opt_encl_scope(scope) {
293         Some(parent_scope) => parent_scope,
294         // If no enclosing scope, then it must be the root scope
295         // which cannot be outlived.
296         None => return Ok(())
297     };
298     let parent_scope = rcx.tcx.mk_region(ty::ReScope(parent_scope));
299     let origin = || infer::SubregionOrigin::SafeDestructor(span);
300
301     let ty = rcx.fcx.resolve_type_vars_if_possible(&ty);
302     let for_ty = ty;
303     let mut types = vec![(ty, 0)];
304     let mut known = FxHashSet();
305     while let Some((ty, depth)) = types.pop() {
306         let ty::DtorckConstraint {
307             dtorck_types, outlives
308         } = rcx.tcx.dtorck_constraint_for_ty(span, for_ty, depth, ty)?;
309
310         for ty in dtorck_types {
311             let ty = rcx.fcx.normalize_associated_types_in(span, &ty);
312             let ty = rcx.fcx.resolve_type_vars_with_obligations(ty);
313             let ty = rcx.fcx.resolve_type_and_region_vars_if_possible(&ty);
314             match ty.sty {
315                 // All parameters live for the duration of the
316                 // function.
317                 ty::TyParam(..) => {}
318
319                 // A projection that we couldn't resolve - it
320                 // might have a destructor.
321                 ty::TyProjection(..) | ty::TyAnon(..) => {
322                     rcx.type_must_outlive(origin(), ty, parent_scope);
323                 }
324
325                 _ => {
326                     if let None = known.replace(ty) {
327                         types.push((ty, depth+1));
328                     }
329                 }
330             }
331         }
332
333         for outlive in outlives {
334             match outlive.unpack() {
335                 UnpackedKind::Lifetime(lt) => rcx.sub_regions(origin(), parent_scope, lt),
336                 UnpackedKind::Type(ty) => rcx.type_must_outlive(origin(), ty, parent_scope),
337             }
338         }
339     }
340
341     Ok(())
342 }