]> git.proxmox.com Git - rustc.git/blame - src/librustc_typeck/check/dropck.rs
New upstream version 1.19.0+dfsg3
[rustc.git] / src / librustc_typeck / check / dropck.rs
CommitLineData
85aaf69f
SL
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
a7813a04 11use check::regionck::RegionCtxt;
85aaf69f 12
54a0048b 13use hir::def_id::DefId;
e9174d1e 14use middle::free_region::FreeRegionMap;
c30ab7b3 15use rustc::infer::{self, InferOk};
7cac9316 16use rustc::middle::region::{self, RegionMaps};
9e0c209e 17use rustc::ty::subst::{Subst, Substs};
cc61c64b 18use rustc::ty::{self, Ty, TyCtxt};
7cac9316 19use rustc::traits::{self, ObligationCause};
8bb4bdeb 20use util::common::ErrorReported;
476ff2be 21use util::nodemap::FxHashSet;
c34b1796 22
476ff2be 23use syntax_pos::Span;
c34b1796
AL
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///
8bb4bdeb
XL
42pub fn check_drop_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
43 drop_impl_did: DefId)
44 -> Result<(), ErrorReported> {
7cac9316
XL
45 let dtor_self_type = tcx.type_of(drop_impl_did);
46 let dtor_predicates = tcx.predicates_of(drop_impl_did);
c34b1796 47 match dtor_self_type.sty {
9e0c209e 48 ty::TyAdt(adt_def, self_to_impl_substs) => {
8bb4bdeb 49 ensure_drop_params_and_item_params_correspond(tcx,
54a0048b 50 drop_impl_did,
9e0c209e 51 dtor_self_type,
54a0048b 52 adt_def.did)?;
c34b1796 53
8bb4bdeb 54 ensure_drop_predicates_are_implied_by_item_defn(tcx,
c34b1796
AL
55 drop_impl_did,
56 &dtor_predicates,
e9174d1e 57 adt_def.did,
c34b1796
AL
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.
8bb4bdeb 63 let span = tcx.def_span(drop_impl_did);
54a0048b
SL
64 span_bug!(span,
65 "should have been rejected by coherence check: {}",
66 dtor_self_type);
c34b1796
AL
67 }
68 }
69}
70
a7813a04 71fn ensure_drop_params_and_item_params_correspond<'a, 'tcx>(
8bb4bdeb 72 tcx: TyCtxt<'a, 'tcx, 'tcx>,
e9174d1e 73 drop_impl_did: DefId,
9e0c209e 74 drop_impl_ty: Ty<'tcx>,
c30ab7b3 75 self_type_did: DefId)
8bb4bdeb 76 -> Result<(), ErrorReported>
c34b1796 77{
32a655c1 78 let drop_impl_node_id = tcx.hir.as_local_node_id(drop_impl_did).unwrap();
e9174d1e
SL
79
80 // check that the impl type can be made to match the trait type.
81
7cac9316
XL
82 tcx.infer_ctxt(()).enter(|ref infcx| {
83 let impl_param_env = tcx.param_env(self_type_did);
a7813a04
XL
84 let tcx = infcx.tcx;
85 let mut fulfillment_cx = traits::FulfillmentContext::new();
e9174d1e 86
7cac9316 87 let named_type = tcx.type_of(self_type_did);
e9174d1e 88
476ff2be 89 let drop_impl_span = tcx.def_span(drop_impl_did);
a7813a04 90 let fresh_impl_substs =
9e0c209e
SL
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);
e9174d1e 93
476ff2be 94 let cause = &ObligationCause::misc(drop_impl_span, drop_impl_node_id);
7cac9316 95 match infcx.at(cause, impl_param_env).eq(named_type, fresh_impl_self_ty) {
c30ab7b3 96 Ok(InferOk { obligations, .. }) => {
cc61c64b 97 fulfillment_cx.register_predicate_obligations(infcx, obligations);
c30ab7b3
SL
98 }
99 Err(_) => {
7cac9316 100 let item_span = tcx.def_span(self_type_did);
c30ab7b3
SL
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();
8bb4bdeb 107 return Err(ErrorReported);
c30ab7b3 108 }
a7813a04
XL
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);
8bb4bdeb 114 return Err(ErrorReported);
a7813a04
XL
115 }
116
7cac9316 117 let region_maps = RegionMaps::new();
a7813a04 118 let free_regions = FreeRegionMap::new();
7cac9316 119 infcx.resolve_regions_and_report_errors(drop_impl_did, &region_maps, &free_regions);
a7813a04
XL
120 Ok(())
121 })
c34b1796
AL
122}
123
124/// Confirms that every predicate imposed by dtor_predicates is
125/// implied by assuming the predicates attached to self_type_did.
a7813a04 126fn ensure_drop_predicates_are_implied_by_item_defn<'a, 'tcx>(
8bb4bdeb 127 tcx: TyCtxt<'a, 'tcx, 'tcx>,
e9174d1e 128 drop_impl_did: DefId,
c34b1796 129 dtor_predicates: &ty::GenericPredicates<'tcx>,
e9174d1e 130 self_type_did: DefId,
c30ab7b3 131 self_to_impl_substs: &Substs<'tcx>)
8bb4bdeb 132 -> Result<(), ErrorReported>
c30ab7b3 133{
8bb4bdeb 134 let mut result = Ok(());
c34b1796
AL
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
32a655c1 171 let self_type_node_id = tcx.hir.as_local_node_id(self_type_did).unwrap();
c34b1796 172
476ff2be 173 let drop_impl_span = tcx.def_span(drop_impl_did);
c34b1796
AL
174
175 // We can assume the predicates attached to struct/enum definition
176 // hold.
7cac9316 177 let generic_assumptions = tcx.predicates_of(self_type_did);
c34b1796
AL
178
179 let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
9e0c209e 180 let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
c34b1796
AL
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
9e0c209e
SL
188 assert_eq!(dtor_predicates.parent, None);
189 for predicate in &dtor_predicates.predicates {
c34b1796
AL
190 // (We do not need to worry about deep analysis of type
191 // expressions etc because the Drop impls are already forced
b039eaaf 192 // to take on a structure that is roughly an alpha-renaming of
c34b1796
AL
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) {
32a655c1 203 let item_span = tcx.hir.span(self_type_node_id);
9cc50fc6
SL
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();
8bb4bdeb 210 result = Err(ErrorReported);
c34b1796
AL
211 }
212 }
85aaf69f 213
8bb4bdeb 214 result
c34b1796 215}
85aaf69f 216
c34b1796
AL
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///
b039eaaf 223/// The simplified (*) Drop Check Rule is the following:
c34b1796
AL
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///
b039eaaf
SL
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 _`,
c34b1796
AL
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.
b039eaaf
SL
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///
a7813a04
XL
269pub fn check_safety_of_destructor_if_necessary<'a, 'gcx, 'tcx>(
270 rcx: &mut RegionCtxt<'a, 'gcx, 'tcx>,
cc61c64b 271 ty: ty::Ty<'tcx>,
a7813a04
XL
272 span: Span,
273 scope: region::CodeExtent)
cc61c64b 274 -> Result<(), ErrorReported>
a7813a04 275{
62682a34 276 debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
cc61c64b 277 ty, scope);
c34b1796 278
85aaf69f 279
7cac9316 280 let parent_scope = match rcx.region_maps.opt_encl_scope(scope) {
cc61c64b
XL
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);
85aaf69f 311 }
85aaf69f 312
cc61c64b
XL
313 _ => {
314 if let None = known.replace(ty) {
315 types.push((ty, depth+1));
316 }
317 }
c1a9b12d 318 }
c1a9b12d 319 }
bd371182 320
cc61c64b
XL
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);
c30ab7b3 326 }
c30ab7b3 327 }
bd371182 328 }
c30ab7b3 329
cc61c64b 330 Ok(())
c30ab7b3 331}