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.
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.
11 use check::regionck::RegionCtxt;
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, Reveal};
20 use util::common::ErrorReported;
21 use util::nodemap::FxHashSet;
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).
31 /// 1. The self type must be nominal (this is already checked during
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,
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> { ... }`).
42 pub fn check_drop_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
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,
54 ensure_drop_predicates_are_implied_by_item_defn(tcx,
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);
65 "should have been rejected by coherence check: {}",
71 fn ensure_drop_params_and_item_params_correspond<'a, 'tcx>(
72 tcx: TyCtxt<'a, 'tcx, 'tcx>,
74 drop_impl_ty: Ty<'tcx>,
76 -> Result<(), ErrorReported>
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();
81 // check that the impl type can be made to match the trait type.
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| {
86 let mut fulfillment_cx = traits::FulfillmentContext::new();
88 let named_type = tcx.type_of(self_type_did);
89 let named_type = named_type.subst(tcx, &infcx.parameter_environment.free_substs);
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);
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);
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")
109 return Err(ErrorReported);
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);
119 let region_maps = RegionMaps::new();
120 let free_regions = FreeRegionMap::new();
121 infcx.resolve_regions_and_report_errors(drop_impl_did, ®ion_maps, &free_regions);
126 /// Confirms that every predicate imposed by dtor_predicates is
127 /// implied by assuming the predicates attached to self_type_did.
128 fn ensure_drop_predicates_are_implied_by_item_defn<'a, 'tcx>(
129 tcx: TyCtxt<'a, 'tcx, 'tcx>,
130 drop_impl_did: DefId,
131 dtor_predicates: &ty::GenericPredicates<'tcx>,
132 self_type_did: DefId,
133 self_to_impl_substs: &Substs<'tcx>)
134 -> Result<(), ErrorReported>
136 let mut result = Ok(());
138 // Here is an example, analogous to that from
139 // `compare_impl_method`.
141 // Consider a struct type:
143 // struct Type<'c, 'b:'c, 'a> {
144 // x: &'a Contents // (contents are irrelevant;
145 // y: &'c Cell<&'b Contents>, // only the bounds matter for our purposes.)
150 // impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
151 // fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
154 // We start out with self_to_impl_substs, that maps the generic
155 // parameters of Type to that of the Drop impl.
157 // self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
159 // Applying this to the predicates (i.e. assumptions) provided by the item
160 // definition yields the instantiated assumptions:
164 // We then check all of the predicates of the Drop impl:
168 // and ensure each is in the list of instantiated
169 // assumptions. Here, `'y:'z` is present, but `'x:'y` is
170 // absent. So we report an error that the Drop impl injected a
171 // predicate that is not present on the struct definition.
173 let self_type_node_id = tcx.hir.as_local_node_id(self_type_did).unwrap();
175 let drop_impl_span = tcx.def_span(drop_impl_did);
177 // We can assume the predicates attached to struct/enum definition
179 let generic_assumptions = tcx.predicates_of(self_type_did);
181 let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
182 let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
184 // An earlier version of this code attempted to do this checking
185 // via the traits::fulfill machinery. However, it ran into trouble
186 // since the fulfill machinery merely turns outlives-predicates
187 // 'a:'b and T:'b into region inference constraints. It is simpler
188 // just to look for all the predicates directly.
190 assert_eq!(dtor_predicates.parent, None);
191 for predicate in &dtor_predicates.predicates {
192 // (We do not need to worry about deep analysis of type
193 // expressions etc because the Drop impls are already forced
194 // to take on a structure that is roughly an alpha-renaming of
195 // the generic parameters of the item definition.)
197 // This path now just checks *all* predicates via the direct
198 // lookup, rather than using fulfill machinery.
200 // However, it may be more efficient in the future to batch
201 // the analysis together via the fulfill , rather than the
202 // repeated `contains` calls.
204 if !assumptions_in_impl_context.contains(&predicate) {
205 let item_span = tcx.hir.span(self_type_node_id);
206 struct_span_err!(tcx.sess, drop_impl_span, E0367,
207 "The requirement `{}` is added only by the Drop impl.", predicate)
208 .span_note(item_span,
209 "The same requirement must be part of \
210 the struct/enum definition")
212 result = Err(ErrorReported);
219 /// check_safety_of_destructor_if_necessary confirms that the type
220 /// expression `typ` conforms to the "Drop Check Rule" from the Sound
221 /// Generic Drop (RFC 769).
225 /// The simplified (*) Drop Check Rule is the following:
227 /// Let `v` be some value (either temporary or named) and 'a be some
228 /// lifetime (scope). If the type of `v` owns data of type `D`, where
230 /// * (1.) `D` has a lifetime- or type-parametric Drop implementation,
231 /// (where that `Drop` implementation does not opt-out of
232 /// this check via the `unsafe_destructor_blind_to_params`
234 /// * (2.) the structure of `D` can reach a reference of type `&'a _`,
236 /// then 'a must strictly outlive the scope of v.
240 /// This function is meant to by applied to the type for every
241 /// expression in the program.
245 /// (*) The qualifier "simplified" is attached to the above
246 /// definition of the Drop Check Rule, because it is a simplification
247 /// of the original Drop Check rule, which attempted to prove that
248 /// some `Drop` implementations could not possibly access data even if
249 /// it was technically reachable, due to parametricity.
251 /// However, (1.) parametricity on its own turned out to be a
252 /// necessary but insufficient condition, and (2.) future changes to
253 /// the language are expected to make it impossible to ensure that a
254 /// `Drop` implementation is actually parametric with respect to any
255 /// particular type parameter. (In particular, impl specialization is
256 /// expected to break the needed parametricity property beyond
259 /// Therefore we have scaled back Drop-Check to a more conservative
260 /// rule that does not attempt to deduce whether a `Drop`
261 /// implementation could not possible access data of a given lifetime;
262 /// instead Drop-Check now simply assumes that if a destructor has
263 /// access (direct or indirect) to a lifetime parameter, then that
264 /// lifetime must be forced to outlive that destructor's dynamic
265 /// extent. We then provide the `unsafe_destructor_blind_to_params`
266 /// attribute as a way for destructor implementations to opt-out of
267 /// this conservative assumption (and thus assume the obligation of
268 /// ensuring that they do not access data nor invoke methods of
269 /// values that have been previously dropped).
271 pub fn check_safety_of_destructor_if_necessary<'a, 'gcx, 'tcx>(
272 rcx: &mut RegionCtxt<'a, 'gcx, 'tcx>,
275 scope: region::CodeExtent<'tcx>)
276 -> Result<(), ErrorReported>
278 debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
282 let parent_scope = match rcx.region_maps.opt_encl_scope(scope) {
283 Some(parent_scope) => parent_scope,
284 // If no enclosing scope, then it must be the root scope
285 // which cannot be outlived.
286 None => return Ok(())
288 let parent_scope = rcx.tcx.mk_region(ty::ReScope(parent_scope));
289 let origin = || infer::SubregionOrigin::SafeDestructor(span);
291 let ty = rcx.fcx.resolve_type_vars_if_possible(&ty);
293 let mut types = vec![(ty, 0)];
294 let mut known = FxHashSet();
295 while let Some((ty, depth)) = types.pop() {
296 let ty::DtorckConstraint {
297 dtorck_types, outlives
298 } = rcx.tcx.dtorck_constraint_for_ty(span, for_ty, depth, ty)?;
300 for ty in dtorck_types {
301 let ty = rcx.fcx.normalize_associated_types_in(span, &ty);
302 let ty = rcx.fcx.resolve_type_vars_with_obligations(ty);
303 let ty = rcx.fcx.resolve_type_and_region_vars_if_possible(&ty);
305 // All parameters live for the duration of the
307 ty::TyParam(..) => {}
309 // A projection that we couldn't resolve - it
310 // might have a destructor.
311 ty::TyProjection(..) | ty::TyAnon(..) => {
312 rcx.type_must_outlive(origin(), ty, parent_scope);
316 if let None = known.replace(ty) {
317 types.push((ty, depth+1));
323 for outlive in outlives {
324 if let Some(r) = outlive.as_region() {
325 rcx.sub_regions(origin(), parent_scope, r);
326 } else if let Some(ty) = outlive.as_type() {
327 rcx.type_must_outlive(origin(), ty, parent_scope);