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::{self, InferOk};
15 use rustc::infer::outlives::env::OutlivesEnvironment;
16 use rustc::middle::region;
17 use rustc::ty::subst::{Subst, Substs, UnpackedKind};
18 use rustc::ty::{self, Ty, TyCtxt};
19 use rustc::traits::{self, Reveal, ObligationCause};
20 use util::common::ErrorReported;
21 use util::nodemap::FxHashSet;
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>(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, but compilation may
63 // not have been terminated.
64 let span = tcx.def_span(drop_impl_did);
65 tcx.sess.delay_span_bug(span,
66 &format!("should have been rejected by coherence check: {}",
73 fn ensure_drop_params_and_item_params_correspond<'a, 'tcx>(
74 tcx: TyCtxt<'a, 'tcx, 'tcx>,
76 drop_impl_ty: Ty<'tcx>,
78 -> Result<(), ErrorReported>
80 let drop_impl_node_id = tcx.hir.as_local_node_id(drop_impl_did).unwrap();
82 // check that the impl type can be made to match the trait type.
84 tcx.infer_ctxt().enter(|ref infcx| {
85 let impl_param_env = tcx.param_env(self_type_did);
87 let mut fulfillment_cx = traits::FulfillmentContext::new();
89 let named_type = tcx.type_of(self_type_did);
91 let drop_impl_span = tcx.def_span(drop_impl_did);
92 let fresh_impl_substs =
93 infcx.fresh_substs_for_item(ty::UniverseIndex::ROOT, 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.at(cause, impl_param_env).eq(named_type, fresh_impl_self_ty) {
98 Ok(InferOk { obligations, .. }) => {
99 fulfillment_cx.register_predicate_obligations(infcx, obligations);
102 let item_span = tcx.def_span(self_type_did);
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, None);
116 return Err(ErrorReported);
119 let region_scope_tree = region::ScopeTree::default();
121 // NB. It seems a bit... suspicious to use an empty param-env
122 // here. The correct thing, I imagine, would be
123 // `OutlivesEnvironment::new(impl_param_env)`, which would
124 // allow region solving to take any `a: 'b` relations on the
125 // impl into account. But I could not create a test case where
126 // it did the wrong thing, so I chose to preserve existing
127 // behavior, since it ought to be simply more
128 // conservative. -nmatsakis
129 let outlives_env = OutlivesEnvironment::new(ty::ParamEnv::empty(Reveal::UserFacing));
131 infcx.resolve_regions_and_report_errors(drop_impl_did, ®ion_scope_tree, &outlives_env);
136 /// Confirms that every predicate imposed by dtor_predicates is
137 /// implied by assuming the predicates attached to self_type_did.
138 fn ensure_drop_predicates_are_implied_by_item_defn<'a, 'tcx>(
139 tcx: TyCtxt<'a, 'tcx, 'tcx>,
140 drop_impl_did: DefId,
141 dtor_predicates: &ty::GenericPredicates<'tcx>,
142 self_type_did: DefId,
143 self_to_impl_substs: &Substs<'tcx>)
144 -> Result<(), ErrorReported>
146 let mut result = Ok(());
148 // Here is an example, analogous to that from
149 // `compare_impl_method`.
151 // Consider a struct type:
153 // struct Type<'c, 'b:'c, 'a> {
154 // x: &'a Contents // (contents are irrelevant;
155 // y: &'c Cell<&'b Contents>, // only the bounds matter for our purposes.)
160 // impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
161 // fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
164 // We start out with self_to_impl_substs, that maps the generic
165 // parameters of Type to that of the Drop impl.
167 // self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
169 // Applying this to the predicates (i.e. assumptions) provided by the item
170 // definition yields the instantiated assumptions:
174 // We then check all of the predicates of the Drop impl:
178 // and ensure each is in the list of instantiated
179 // assumptions. Here, `'y:'z` is present, but `'x:'y` is
180 // absent. So we report an error that the Drop impl injected a
181 // predicate that is not present on the struct definition.
183 let self_type_node_id = tcx.hir.as_local_node_id(self_type_did).unwrap();
185 let drop_impl_span = tcx.def_span(drop_impl_did);
187 // We can assume the predicates attached to struct/enum definition
189 let generic_assumptions = tcx.predicates_of(self_type_did);
191 let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
192 let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
194 // An earlier version of this code attempted to do this checking
195 // via the traits::fulfill machinery. However, it ran into trouble
196 // since the fulfill machinery merely turns outlives-predicates
197 // 'a:'b and T:'b into region inference constraints. It is simpler
198 // just to look for all the predicates directly.
200 assert_eq!(dtor_predicates.parent, None);
201 for predicate in &dtor_predicates.predicates {
202 // (We do not need to worry about deep analysis of type
203 // expressions etc because the Drop impls are already forced
204 // to take on a structure that is roughly an alpha-renaming of
205 // the generic parameters of the item definition.)
207 // This path now just checks *all* predicates via the direct
208 // lookup, rather than using fulfill machinery.
210 // However, it may be more efficient in the future to batch
211 // the analysis together via the fulfill , rather than the
212 // repeated `contains` calls.
214 if !assumptions_in_impl_context.contains(&predicate) {
215 let item_span = tcx.hir.span(self_type_node_id);
216 struct_span_err!(tcx.sess, drop_impl_span, E0367,
217 "The requirement `{}` is added only by the Drop impl.", predicate)
218 .span_note(item_span,
219 "The same requirement must be part of \
220 the struct/enum definition")
222 result = Err(ErrorReported);
229 /// check_safety_of_destructor_if_necessary confirms that the type
230 /// expression `typ` conforms to the "Drop Check Rule" from the Sound
231 /// Generic Drop (RFC 769).
235 /// The simplified (*) Drop Check Rule is the following:
237 /// Let `v` be some value (either temporary or named) and 'a be some
238 /// lifetime (scope). If the type of `v` owns data of type `D`, where
240 /// * (1.) `D` has a lifetime- or type-parametric Drop implementation,
241 /// (where that `Drop` implementation does not opt-out of
242 /// this check via the `unsafe_destructor_blind_to_params`
244 /// * (2.) the structure of `D` can reach a reference of type `&'a _`,
246 /// then 'a must strictly outlive the scope of v.
250 /// This function is meant to by applied to the type for every
251 /// expression in the program.
255 /// (*) The qualifier "simplified" is attached to the above
256 /// definition of the Drop Check Rule, because it is a simplification
257 /// of the original Drop Check rule, which attempted to prove that
258 /// some `Drop` implementations could not possibly access data even if
259 /// it was technically reachable, due to parametricity.
261 /// However, (1.) parametricity on its own turned out to be a
262 /// necessary but insufficient condition, and (2.) future changes to
263 /// the language are expected to make it impossible to ensure that a
264 /// `Drop` implementation is actually parametric with respect to any
265 /// particular type parameter. (In particular, impl specialization is
266 /// expected to break the needed parametricity property beyond
269 /// Therefore we have scaled back Drop-Check to a more conservative
270 /// rule that does not attempt to deduce whether a `Drop`
271 /// implementation could not possible access data of a given lifetime;
272 /// instead Drop-Check now simply assumes that if a destructor has
273 /// access (direct or indirect) to a lifetime parameter, then that
274 /// lifetime must be forced to outlive that destructor's dynamic
275 /// extent. We then provide the `unsafe_destructor_blind_to_params`
276 /// attribute as a way for destructor implementations to opt-out of
277 /// this conservative assumption (and thus assume the obligation of
278 /// ensuring that they do not access data nor invoke methods of
279 /// values that have been previously dropped).
281 pub fn check_safety_of_destructor_if_necessary<'a, 'gcx, 'tcx>(
282 rcx: &mut RegionCtxt<'a, 'gcx, 'tcx>,
285 scope: region::Scope)
286 -> Result<(), ErrorReported>
288 debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
292 let parent_scope = match rcx.region_scope_tree.opt_encl_scope(scope) {
293 Some(parent_scope) => parent_scope,
294 // If no enclosing scope, then it must be the root scope
295 // which cannot be outlived.
296 None => return Ok(())
298 let parent_scope = rcx.tcx.mk_region(ty::ReScope(parent_scope));
299 let origin = || infer::SubregionOrigin::SafeDestructor(span);
301 let ty = rcx.fcx.resolve_type_vars_if_possible(&ty);
303 let mut types = vec![(ty, 0)];
304 let mut known = FxHashSet();
305 while let Some((ty, depth)) = types.pop() {
306 let ty::DtorckConstraint {
307 dtorck_types, outlives
308 } = rcx.tcx.dtorck_constraint_for_ty(span, for_ty, depth, ty)?;
310 for ty in dtorck_types {
311 let ty = rcx.fcx.normalize_associated_types_in(span, &ty);
312 let ty = rcx.fcx.resolve_type_vars_with_obligations(ty);
313 let ty = rcx.fcx.resolve_type_and_region_vars_if_possible(&ty);
315 // All parameters live for the duration of the
317 ty::TyParam(..) => {}
319 // A projection that we couldn't resolve - it
320 // might have a destructor.
321 ty::TyProjection(..) | ty::TyAnon(..) => {
322 rcx.type_must_outlive(origin(), ty, parent_scope);
326 if let None = known.replace(ty) {
327 types.push((ty, depth+1));
333 for outlive in outlives {
334 match outlive.unpack() {
335 UnpackedKind::Lifetime(lt) => rcx.sub_regions(origin(), parent_scope, lt),
336 UnpackedKind::Type(ty) => rcx.type_must_outlive(origin(), ty, parent_scope),