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