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 rustc::infer::outlives::env::OutlivesEnvironment;
15 use rustc::infer::{self, InferOk, SuppressRegionErrors};
16 use rustc::middle::region;
17 use rustc::traits::{ObligationCause, TraitEngine, TraitEngineExt};
18 use rustc::ty::subst::{Subst, Substs, UnpackedKind};
19 use rustc::ty::{self, Ty, TyCtxt};
20 use util::common::ErrorReported;
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).
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>(
43 tcx: TyCtxt<'a, 'tcx, 'tcx>,
45 ) -> Result<(), ErrorReported> {
46 let dtor_self_type = tcx.type_of(drop_impl_did);
47 let dtor_predicates = tcx.predicates_of(drop_impl_did);
48 match dtor_self_type.sty {
49 ty::Adt(adt_def, self_to_impl_substs) => {
50 ensure_drop_params_and_item_params_correspond(
57 ensure_drop_predicates_are_implied_by_item_defn(
66 // Destructors only work on nominal types. This was
67 // already checked by coherence, but compilation may
68 // not have been terminated.
69 let span = tcx.def_span(drop_impl_did);
70 tcx.sess.delay_span_bug(span,
71 &format!("should have been rejected by coherence check: {}", dtor_self_type));
77 fn ensure_drop_params_and_item_params_correspond<'a, 'tcx>(
78 tcx: TyCtxt<'a, 'tcx, 'tcx>,
80 drop_impl_ty: Ty<'tcx>,
82 ) -> Result<(), ErrorReported> {
83 let drop_impl_node_id = tcx.hir().as_local_node_id(drop_impl_did).unwrap();
85 // check that the impl type can be made to match the trait type.
87 tcx.infer_ctxt().enter(|ref infcx| {
88 let impl_param_env = tcx.param_env(self_type_did);
90 let mut fulfillment_cx = TraitEngine::new(tcx);
92 let named_type = tcx.type_of(self_type_did);
94 let drop_impl_span = tcx.def_span(drop_impl_did);
95 let fresh_impl_substs = infcx.fresh_substs_for_item(drop_impl_span, drop_impl_did);
96 let fresh_impl_self_ty = drop_impl_ty.subst(tcx, fresh_impl_substs);
98 let cause = &ObligationCause::misc(drop_impl_span, drop_impl_node_id);
100 .at(cause, impl_param_env)
101 .eq(named_type, fresh_impl_self_ty)
103 Ok(InferOk { obligations, .. }) => {
104 fulfillment_cx.register_predicate_obligations(infcx, obligations);
107 let item_span = tcx.def_span(self_type_did);
112 "Implementations of Drop cannot be specialized"
115 "Use same sequence of generic type and region \
116 parameters that is on the struct/enum definition",
119 return Err(ErrorReported);
123 if let Err(ref errors) = fulfillment_cx.select_all_or_error(&infcx) {
124 // this could be reached when we get lazy normalization
125 infcx.report_fulfillment_errors(errors, None, false);
126 return Err(ErrorReported);
129 let region_scope_tree = region::ScopeTree::default();
131 // NB. It seems a bit... suspicious to use an empty param-env
132 // here. The correct thing, I imagine, would be
133 // `OutlivesEnvironment::new(impl_param_env)`, which would
134 // allow region solving to take any `a: 'b` relations on the
135 // impl into account. But I could not create a test case where
136 // it did the wrong thing, so I chose to preserve existing
137 // behavior, since it ought to be simply more
138 // conservative. -nmatsakis
139 let outlives_env = OutlivesEnvironment::new(ty::ParamEnv::empty());
141 infcx.resolve_regions_and_report_errors(
145 SuppressRegionErrors::default(),
151 /// Confirms that every predicate imposed by dtor_predicates is
152 /// implied by assuming the predicates attached to self_type_did.
153 fn ensure_drop_predicates_are_implied_by_item_defn<'a, 'tcx>(
154 tcx: TyCtxt<'a, 'tcx, 'tcx>,
155 drop_impl_did: DefId,
156 dtor_predicates: &ty::GenericPredicates<'tcx>,
157 self_type_did: DefId,
158 self_to_impl_substs: &Substs<'tcx>,
159 ) -> Result<(), ErrorReported> {
160 let mut result = Ok(());
162 // Here is an example, analogous to that from
163 // `compare_impl_method`.
165 // Consider a struct type:
167 // struct Type<'c, 'b:'c, 'a> {
168 // x: &'a Contents // (contents are irrelevant;
169 // y: &'c Cell<&'b Contents>, // only the bounds matter for our purposes.)
174 // impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
175 // fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
178 // We start out with self_to_impl_substs, that maps the generic
179 // parameters of Type to that of the Drop impl.
181 // self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
183 // Applying this to the predicates (i.e., assumptions) provided by the item
184 // definition yields the instantiated assumptions:
188 // We then check all of the predicates of the Drop impl:
192 // and ensure each is in the list of instantiated
193 // assumptions. Here, `'y:'z` is present, but `'x:'y` is
194 // absent. So we report an error that the Drop impl injected a
195 // predicate that is not present on the struct definition.
197 let self_type_node_id = tcx.hir().as_local_node_id(self_type_did).unwrap();
199 let drop_impl_span = tcx.def_span(drop_impl_did);
201 // We can assume the predicates attached to struct/enum definition
203 let generic_assumptions = tcx.predicates_of(self_type_did);
205 let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
206 let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
208 // An earlier version of this code attempted to do this checking
209 // via the traits::fulfill machinery. However, it ran into trouble
210 // since the fulfill machinery merely turns outlives-predicates
211 // 'a:'b and T:'b into region inference constraints. It is simpler
212 // just to look for all the predicates directly.
214 assert_eq!(dtor_predicates.parent, None);
215 for (predicate, _) in &dtor_predicates.predicates {
216 // (We do not need to worry about deep analysis of type
217 // expressions etc because the Drop impls are already forced
218 // to take on a structure that is roughly an alpha-renaming of
219 // the generic parameters of the item definition.)
221 // This path now just checks *all* predicates via the direct
222 // lookup, rather than using fulfill machinery.
224 // However, it may be more efficient in the future to batch
225 // the analysis together via the fulfill , rather than the
226 // repeated `contains` calls.
228 if !assumptions_in_impl_context.contains(&predicate) {
229 let item_span = tcx.hir().span(self_type_node_id);
234 "The requirement `{}` is added only by the Drop impl.",
238 "The same requirement must be part of \
239 the struct/enum definition",
242 result = Err(ErrorReported);
249 /// check_safety_of_destructor_if_necessary confirms that the type
250 /// expression `typ` conforms to the "Drop Check Rule" from the Sound
251 /// Generic Drop (RFC 769).
255 /// The simplified (*) Drop Check Rule is the following:
257 /// Let `v` be some value (either temporary or named) and 'a be some
258 /// lifetime (scope). If the type of `v` owns data of type `D`, where
260 /// * (1.) `D` has a lifetime- or type-parametric Drop implementation,
261 /// (where that `Drop` implementation does not opt-out of
262 /// this check via the `unsafe_destructor_blind_to_params`
264 /// * (2.) the structure of `D` can reach a reference of type `&'a _`,
266 /// then 'a must strictly outlive the scope of v.
270 /// This function is meant to by applied to the type for every
271 /// expression in the program.
275 /// (*) The qualifier "simplified" is attached to the above
276 /// definition of the Drop Check Rule, because it is a simplification
277 /// of the original Drop Check rule, which attempted to prove that
278 /// some `Drop` implementations could not possibly access data even if
279 /// it was technically reachable, due to parametricity.
281 /// However, (1.) parametricity on its own turned out to be a
282 /// necessary but insufficient condition, and (2.) future changes to
283 /// the language are expected to make it impossible to ensure that a
284 /// `Drop` implementation is actually parametric with respect to any
285 /// particular type parameter. (In particular, impl specialization is
286 /// expected to break the needed parametricity property beyond
289 /// Therefore we have scaled back Drop-Check to a more conservative
290 /// rule that does not attempt to deduce whether a `Drop`
291 /// implementation could not possible access data of a given lifetime;
292 /// instead Drop-Check now simply assumes that if a destructor has
293 /// access (direct or indirect) to a lifetime parameter, then that
294 /// lifetime must be forced to outlive that destructor's dynamic
295 /// extent. We then provide the `unsafe_destructor_blind_to_params`
296 /// attribute as a way for destructor implementations to opt-out of
297 /// this conservative assumption (and thus assume the obligation of
298 /// ensuring that they do not access data nor invoke methods of
299 /// values that have been previously dropped).
301 pub fn check_safety_of_destructor_if_necessary<'a, 'gcx, 'tcx>(
302 rcx: &mut RegionCtxt<'a, 'gcx, 'tcx>,
305 body_id: ast::NodeId,
306 scope: region::Scope,
307 ) -> Result<(), ErrorReported> {
308 debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
311 let parent_scope = match rcx.region_scope_tree.opt_encl_scope(scope) {
312 Some(parent_scope) => parent_scope,
313 // If no enclosing scope, then it must be the root scope
314 // which cannot be outlived.
315 None => return Ok(()),
317 let parent_scope = rcx.tcx.mk_region(ty::ReScope(parent_scope));
318 let origin = || infer::SubregionOrigin::SafeDestructor(span);
319 let cause = &ObligationCause::misc(span, body_id);
320 let infer_ok = rcx.infcx.at(cause, rcx.fcx.param_env).dropck_outlives(ty);
321 debug!("dropck_outlives = {:#?}", infer_ok);
322 let kinds = rcx.fcx.register_infer_ok_obligations(infer_ok);
324 match kind.unpack() {
325 UnpackedKind::Lifetime(r) => rcx.sub_regions(origin(), parent_scope, r),
326 UnpackedKind::Type(ty) => rcx.type_must_outlive(origin(), ty, parent_scope),