]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/dropck.rs
On-demandify region mapping
[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 middle::free_region::FreeRegionMap;
15 use rustc::infer::{self, InferOk};
16 use middle::region;
17 use rustc::ty::subst::{Subst, Substs};
18 use rustc::ty::{self, Ty, TyCtxt};
19 use rustc::traits::{self, ObligationCause, Reveal};
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 identfied 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, so we can panic here.
63             let span = tcx.def_span(drop_impl_did);
64             span_bug!(span,
65                       "should have been rejected by coherence check: {}",
66                       dtor_self_type);
67         }
68     }
69 }
70
71 fn ensure_drop_params_and_item_params_correspond<'a, 'tcx>(
72     tcx: TyCtxt<'a, 'tcx, 'tcx>,
73     drop_impl_did: DefId,
74     drop_impl_ty: Ty<'tcx>,
75     self_type_did: DefId)
76     -> Result<(), ErrorReported>
77 {
78     let drop_impl_node_id = tcx.hir.as_local_node_id(drop_impl_did).unwrap();
79     let self_type_node_id = tcx.hir.as_local_node_id(self_type_did).unwrap();
80
81     // check that the impl type can be made to match the trait type.
82
83     let impl_param_env = ty::ParameterEnvironment::for_item(tcx, self_type_node_id);
84     tcx.infer_ctxt(impl_param_env, Reveal::UserFacing).enter(|ref infcx| {
85         let tcx = infcx.tcx;
86         let mut fulfillment_cx = traits::FulfillmentContext::new();
87
88         let named_type = tcx.type_of(self_type_did);
89         let named_type = named_type.subst(tcx, &infcx.parameter_environment.free_substs);
90
91         let drop_impl_span = tcx.def_span(drop_impl_did);
92         let fresh_impl_substs =
93             infcx.fresh_substs_for_item(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.eq_types(true, cause, 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.hir.span(self_type_node_id);
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);
116             return Err(ErrorReported);
117         }
118
119         let free_regions = FreeRegionMap::new();
120         infcx.resolve_regions_and_report_errors(&free_regions, drop_impl_node_id);
121         Ok(())
122     })
123 }
124
125 /// Confirms that every predicate imposed by dtor_predicates is
126 /// implied by assuming the predicates attached to self_type_did.
127 fn ensure_drop_predicates_are_implied_by_item_defn<'a, 'tcx>(
128     tcx: TyCtxt<'a, 'tcx, 'tcx>,
129     drop_impl_did: DefId,
130     dtor_predicates: &ty::GenericPredicates<'tcx>,
131     self_type_did: DefId,
132     self_to_impl_substs: &Substs<'tcx>)
133     -> Result<(), ErrorReported>
134 {
135     let mut result = Ok(());
136
137     // Here is an example, analogous to that from
138     // `compare_impl_method`.
139     //
140     // Consider a struct type:
141     //
142     //     struct Type<'c, 'b:'c, 'a> {
143     //         x: &'a Contents            // (contents are irrelevant;
144     //         y: &'c Cell<&'b Contents>, //  only the bounds matter for our purposes.)
145     //     }
146     //
147     // and a Drop impl:
148     //
149     //     impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
150     //         fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
151     //     }
152     //
153     // We start out with self_to_impl_substs, that maps the generic
154     // parameters of Type to that of the Drop impl.
155     //
156     //     self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
157     //
158     // Applying this to the predicates (i.e. assumptions) provided by the item
159     // definition yields the instantiated assumptions:
160     //
161     //     ['y : 'z]
162     //
163     // We then check all of the predicates of the Drop impl:
164     //
165     //     ['y:'z, 'x:'y]
166     //
167     // and ensure each is in the list of instantiated
168     // assumptions. Here, `'y:'z` is present, but `'x:'y` is
169     // absent. So we report an error that the Drop impl injected a
170     // predicate that is not present on the struct definition.
171
172     let self_type_node_id = tcx.hir.as_local_node_id(self_type_did).unwrap();
173
174     let drop_impl_span = tcx.def_span(drop_impl_did);
175
176     // We can assume the predicates attached to struct/enum definition
177     // hold.
178     let generic_assumptions = tcx.predicates_of(self_type_did);
179
180     let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
181     let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
182
183     // An earlier version of this code attempted to do this checking
184     // via the traits::fulfill machinery. However, it ran into trouble
185     // since the fulfill machinery merely turns outlives-predicates
186     // 'a:'b and T:'b into region inference constraints. It is simpler
187     // just to look for all the predicates directly.
188
189     assert_eq!(dtor_predicates.parent, None);
190     for predicate in &dtor_predicates.predicates {
191         // (We do not need to worry about deep analysis of type
192         // expressions etc because the Drop impls are already forced
193         // to take on a structure that is roughly an alpha-renaming of
194         // the generic parameters of the item definition.)
195
196         // This path now just checks *all* predicates via the direct
197         // lookup, rather than using fulfill machinery.
198         //
199         // However, it may be more efficient in the future to batch
200         // the analysis together via the fulfill , rather than the
201         // repeated `contains` calls.
202
203         if !assumptions_in_impl_context.contains(&predicate) {
204             let item_span = tcx.hir.span(self_type_node_id);
205             struct_span_err!(tcx.sess, drop_impl_span, E0367,
206                              "The requirement `{}` is added only by the Drop impl.", predicate)
207                 .span_note(item_span,
208                            "The same requirement must be part of \
209                             the struct/enum definition")
210                 .emit();
211             result = Err(ErrorReported);
212         }
213     }
214
215     result
216 }
217
218 /// check_safety_of_destructor_if_necessary confirms that the type
219 /// expression `typ` conforms to the "Drop Check Rule" from the Sound
220 /// Generic Drop (RFC 769).
221 ///
222 /// ----
223 ///
224 /// The simplified (*) Drop Check Rule is the following:
225 ///
226 /// Let `v` be some value (either temporary or named) and 'a be some
227 /// lifetime (scope). If the type of `v` owns data of type `D`, where
228 ///
229 /// * (1.) `D` has a lifetime- or type-parametric Drop implementation,
230 ///        (where that `Drop` implementation does not opt-out of
231 ///         this check via the `unsafe_destructor_blind_to_params`
232 ///         attribute), and
233 /// * (2.) the structure of `D` can reach a reference of type `&'a _`,
234 ///
235 /// then 'a must strictly outlive the scope of v.
236 ///
237 /// ----
238 ///
239 /// This function is meant to by applied to the type for every
240 /// expression in the program.
241 ///
242 /// ----
243 ///
244 /// (*) The qualifier "simplified" is attached to the above
245 /// definition of the Drop Check Rule, because it is a simplification
246 /// of the original Drop Check rule, which attempted to prove that
247 /// some `Drop` implementations could not possibly access data even if
248 /// it was technically reachable, due to parametricity.
249 ///
250 /// However, (1.) parametricity on its own turned out to be a
251 /// necessary but insufficient condition, and (2.)  future changes to
252 /// the language are expected to make it impossible to ensure that a
253 /// `Drop` implementation is actually parametric with respect to any
254 /// particular type parameter. (In particular, impl specialization is
255 /// expected to break the needed parametricity property beyond
256 /// repair.)
257 ///
258 /// Therefore we have scaled back Drop-Check to a more conservative
259 /// rule that does not attempt to deduce whether a `Drop`
260 /// implementation could not possible access data of a given lifetime;
261 /// instead Drop-Check now simply assumes that if a destructor has
262 /// access (direct or indirect) to a lifetime parameter, then that
263 /// lifetime must be forced to outlive that destructor's dynamic
264 /// extent. We then provide the `unsafe_destructor_blind_to_params`
265 /// attribute as a way for destructor implementations to opt-out of
266 /// this conservative assumption (and thus assume the obligation of
267 /// ensuring that they do not access data nor invoke methods of
268 /// values that have been previously dropped).
269 ///
270 pub fn check_safety_of_destructor_if_necessary<'a, 'gcx, 'tcx>(
271     rcx: &mut RegionCtxt<'a, 'gcx, 'tcx>,
272     ty: ty::Ty<'tcx>,
273     span: Span,
274     scope: region::CodeExtent)
275     -> Result<(), ErrorReported>
276 {
277     debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
278            ty, scope);
279
280
281     let parent_scope = match rcx.tcx.region_maps().opt_encl_scope(scope) {
282         Some(parent_scope) => parent_scope,
283         // If no enclosing scope, then it must be the root scope
284         // which cannot be outlived.
285         None => return Ok(())
286     };
287     let parent_scope = rcx.tcx.mk_region(ty::ReScope(parent_scope));
288     let origin = || infer::SubregionOrigin::SafeDestructor(span);
289
290     let ty = rcx.fcx.resolve_type_vars_if_possible(&ty);
291     let for_ty = ty;
292     let mut types = vec![(ty, 0)];
293     let mut known = FxHashSet();
294     while let Some((ty, depth)) = types.pop() {
295         let ty::DtorckConstraint {
296             dtorck_types, outlives
297         } = rcx.tcx.dtorck_constraint_for_ty(span, for_ty, depth, ty)?;
298
299         for ty in dtorck_types {
300             let ty = rcx.fcx.normalize_associated_types_in(span, &ty);
301             let ty = rcx.fcx.resolve_type_vars_with_obligations(ty);
302             let ty = rcx.fcx.resolve_type_and_region_vars_if_possible(&ty);
303             match ty.sty {
304                 // All parameters live for the duration of the
305                 // function.
306                 ty::TyParam(..) => {}
307
308                 // A projection that we couldn't resolve - it
309                 // might have a destructor.
310                 ty::TyProjection(..) | ty::TyAnon(..) => {
311                     rcx.type_must_outlive(origin(), ty, parent_scope);
312                 }
313
314                 _ => {
315                     if let None = known.replace(ty) {
316                         types.push((ty, depth+1));
317                     }
318                 }
319             }
320         }
321
322         for outlive in outlives {
323             if let Some(r) = outlive.as_region() {
324                 rcx.sub_regions(origin(), parent_scope, r);
325             } else if let Some(ty) = outlive.as_type() {
326                 rcx.type_must_outlive(origin(), ty, parent_scope);
327             }
328         }
329     }
330
331     Ok(())
332 }