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.
12 use check::regionck::RegionCtxt;
14 use hir::def_id::DefId;
15 use middle::free_region::FreeRegionMap;
18 use rustc::ty::subst::{Subst, Substs};
19 use rustc::ty::{self, Ty, TyCtxt};
20 use rustc::traits::{self, Reveal};
21 use util::nodemap::FnvHashSet;
24 use syntax_pos::{self, Span};
26 /// check_drop_impl confirms that the Drop implementation identfied by
27 /// `drop_impl_did` is not any more specialized than the type it is
28 /// attached to (Issue #8142).
32 /// 1. The self type must be nominal (this is already checked during
35 /// 2. The generic region/type parameters of the impl's self-type must
36 /// all be parameters of the Drop impl itself (i.e. no
37 /// specialization like `impl Drop for Foo<i32>`), and,
39 /// 3. Any bounds on the generic parameters must be reflected in the
40 /// struct/enum definition for the nominal type itself (i.e.
41 /// cannot do `struct S<T>; impl<T:Clone> Drop for S<T> { ... }`).
43 pub fn check_drop_impl(ccx: &CrateCtxt, drop_impl_did: DefId) -> Result<(), ()> {
44 let dtor_self_type = ccx.tcx.lookup_item_type(drop_impl_did).ty;
45 let dtor_predicates = ccx.tcx.lookup_predicates(drop_impl_did);
46 match dtor_self_type.sty {
47 ty::TyEnum(adt_def, self_to_impl_substs) |
48 ty::TyStruct(adt_def, self_to_impl_substs) => {
49 ensure_drop_params_and_item_params_correspond(ccx,
54 ensure_drop_predicates_are_implied_by_item_defn(ccx,
61 // Destructors only work on nominal types. This was
62 // already checked by coherence, so we can panic here.
63 let span = ccx.tcx.map.def_id_span(drop_impl_did, syntax_pos::DUMMY_SP);
65 "should have been rejected by coherence check: {}",
71 fn ensure_drop_params_and_item_params_correspond<'a, 'tcx>(
72 ccx: &CrateCtxt<'a, 'tcx>,
74 drop_impl_ty: Ty<'tcx>,
75 self_type_did: DefId) -> Result<(), ()>
78 let drop_impl_node_id = tcx.map.as_local_node_id(drop_impl_did).unwrap();
79 let self_type_node_id = tcx.map.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(None, Some(impl_param_env), Reveal::NotSpecializable).enter(|infcx| {
86 let mut fulfillment_cx = traits::FulfillmentContext::new();
88 let named_type = tcx.lookup_item_type(self_type_did).ty;
89 let named_type = named_type.subst(tcx, &infcx.parameter_environment.free_substs);
91 let drop_impl_span = tcx.map.def_id_span(drop_impl_did, syntax_pos::DUMMY_SP);
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 if let Err(_) = infcx.eq_types(true, infer::TypeOrigin::Misc(drop_impl_span),
97 named_type, fresh_impl_self_ty) {
98 let item_span = tcx.map.span(self_type_node_id);
99 struct_span_err!(tcx.sess, drop_impl_span, E0366,
100 "Implementations of Drop cannot be specialized")
101 .span_note(item_span,
102 "Use same sequence of generic type and region \
103 parameters that is on the struct/enum definition")
108 if let Err(ref errors) = fulfillment_cx.select_all_or_error(&infcx) {
109 // this could be reached when we get lazy normalization
110 infcx.report_fulfillment_errors(errors);
114 let free_regions = FreeRegionMap::new();
115 infcx.resolve_regions_and_report_errors(&free_regions, drop_impl_node_id);
120 /// Confirms that every predicate imposed by dtor_predicates is
121 /// implied by assuming the predicates attached to self_type_did.
122 fn ensure_drop_predicates_are_implied_by_item_defn<'a, 'tcx>(
123 ccx: &CrateCtxt<'a, 'tcx>,
124 drop_impl_did: DefId,
125 dtor_predicates: &ty::GenericPredicates<'tcx>,
126 self_type_did: DefId,
127 self_to_impl_substs: &Substs<'tcx>) -> Result<(), ()> {
129 // Here is an example, analogous to that from
130 // `compare_impl_method`.
132 // Consider a struct type:
134 // struct Type<'c, 'b:'c, 'a> {
135 // x: &'a Contents // (contents are irrelevant;
136 // y: &'c Cell<&'b Contents>, // only the bounds matter for our purposes.)
141 // impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
142 // fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
145 // We start out with self_to_impl_substs, that maps the generic
146 // parameters of Type to that of the Drop impl.
148 // self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
150 // Applying this to the predicates (i.e. assumptions) provided by the item
151 // definition yields the instantiated assumptions:
155 // We then check all of the predicates of the Drop impl:
159 // and ensure each is in the list of instantiated
160 // assumptions. Here, `'y:'z` is present, but `'x:'y` is
161 // absent. So we report an error that the Drop impl injected a
162 // predicate that is not present on the struct definition.
166 let self_type_node_id = tcx.map.as_local_node_id(self_type_did).unwrap();
168 let drop_impl_span = tcx.map.def_id_span(drop_impl_did, syntax_pos::DUMMY_SP);
170 // We can assume the predicates attached to struct/enum definition
172 let generic_assumptions = tcx.lookup_predicates(self_type_did);
174 let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
175 let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
177 // An earlier version of this code attempted to do this checking
178 // via the traits::fulfill machinery. However, it ran into trouble
179 // since the fulfill machinery merely turns outlives-predicates
180 // 'a:'b and T:'b into region inference constraints. It is simpler
181 // just to look for all the predicates directly.
183 assert_eq!(dtor_predicates.parent, None);
184 for predicate in &dtor_predicates.predicates {
185 // (We do not need to worry about deep analysis of type
186 // expressions etc because the Drop impls are already forced
187 // to take on a structure that is roughly an alpha-renaming of
188 // the generic parameters of the item definition.)
190 // This path now just checks *all* predicates via the direct
191 // lookup, rather than using fulfill machinery.
193 // However, it may be more efficient in the future to batch
194 // the analysis together via the fulfill , rather than the
195 // repeated `contains` calls.
197 if !assumptions_in_impl_context.contains(&predicate) {
198 let item_span = tcx.map.span(self_type_node_id);
199 struct_span_err!(tcx.sess, drop_impl_span, E0367,
200 "The requirement `{}` is added only by the Drop impl.", predicate)
201 .span_note(item_span,
202 "The same requirement must be part of \
203 the struct/enum definition")
208 if tcx.sess.has_errors() {
214 /// check_safety_of_destructor_if_necessary confirms that the type
215 /// expression `typ` conforms to the "Drop Check Rule" from the Sound
216 /// Generic Drop (RFC 769).
220 /// The simplified (*) Drop Check Rule is the following:
222 /// Let `v` be some value (either temporary or named) and 'a be some
223 /// lifetime (scope). If the type of `v` owns data of type `D`, where
225 /// * (1.) `D` has a lifetime- or type-parametric Drop implementation,
226 /// (where that `Drop` implementation does not opt-out of
227 /// this check via the `unsafe_destructor_blind_to_params`
229 /// * (2.) the structure of `D` can reach a reference of type `&'a _`,
231 /// then 'a must strictly outlive the scope of v.
235 /// This function is meant to by applied to the type for every
236 /// expression in the program.
240 /// (*) The qualifier "simplified" is attached to the above
241 /// definition of the Drop Check Rule, because it is a simplification
242 /// of the original Drop Check rule, which attempted to prove that
243 /// some `Drop` implementations could not possibly access data even if
244 /// it was technically reachable, due to parametricity.
246 /// However, (1.) parametricity on its own turned out to be a
247 /// necessary but insufficient condition, and (2.) future changes to
248 /// the language are expected to make it impossible to ensure that a
249 /// `Drop` implementation is actually parametric with respect to any
250 /// particular type parameter. (In particular, impl specialization is
251 /// expected to break the needed parametricity property beyond
254 /// Therefore we have scaled back Drop-Check to a more conservative
255 /// rule that does not attempt to deduce whether a `Drop`
256 /// implementation could not possible access data of a given lifetime;
257 /// instead Drop-Check now simply assumes that if a destructor has
258 /// access (direct or indirect) to a lifetime parameter, then that
259 /// lifetime must be forced to outlive that destructor's dynamic
260 /// extent. We then provide the `unsafe_destructor_blind_to_params`
261 /// attribute as a way for destructor implementations to opt-out of
262 /// this conservative assumption (and thus assume the obligation of
263 /// ensuring that they do not access data nor invoke methods of
264 /// values that have been previously dropped).
266 pub fn check_safety_of_destructor_if_necessary<'a, 'gcx, 'tcx>(
267 rcx: &mut RegionCtxt<'a, 'gcx, 'tcx>,
270 scope: region::CodeExtent)
272 debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
275 let parent_scope = rcx.tcx.region_maps.opt_encl_scope(scope).unwrap_or_else(|| {
276 span_bug!(span, "no enclosing scope found for scope: {:?}", scope)
279 let result = iterate_over_potentially_unsafe_regions_in_type(
283 parent_scope: parent_scope,
284 breadcrumbs: FnvHashSet()
291 Err(Error::Overflow(ref ctxt, ref detected_on_typ)) => {
293 let mut err = struct_span_err!(tcx.sess, span, E0320,
294 "overflow while adding drop-check rules for {}", typ);
296 TypeContext::Root => {
297 // no need for an additional note if the overflow
298 // was somehow on the root.
300 TypeContext::ADT { def_id, variant, field } => {
301 let adt = tcx.lookup_adt_def(def_id);
302 let variant_name = match adt.adt_kind() {
303 ty::AdtKind::Enum => format!("enum {} variant {}",
304 tcx.item_path_str(def_id),
306 ty::AdtKind::Struct => format!("struct {}",
307 tcx.item_path_str(def_id))
312 "overflowed on {} field {} type: {}",
324 Overflow(TypeContext, ty::Ty<'tcx>),
327 #[derive(Copy, Clone)]
337 struct DropckContext<'a, 'b: 'a, 'gcx: 'b+'tcx, 'tcx: 'b> {
338 rcx: &'a mut RegionCtxt<'b, 'gcx, 'tcx>,
339 /// types that have already been traversed
340 breadcrumbs: FnvHashSet<Ty<'tcx>>,
341 /// span for error reporting
343 /// the scope reachable dtorck types must outlive
344 parent_scope: region::CodeExtent
347 // `context` is used for reporting overflow errors
348 fn iterate_over_potentially_unsafe_regions_in_type<'a, 'b, 'gcx, 'tcx>(
349 cx: &mut DropckContext<'a, 'b, 'gcx, 'tcx>,
350 context: TypeContext,
352 depth: usize) -> Result<(), Error<'tcx>>
354 let tcx = cx.rcx.tcx;
355 // Issue #22443: Watch out for overflow. While we are careful to
356 // handle regular types properly, non-regular ones cause problems.
357 let recursion_limit = tcx.sess.recursion_limit.get();
358 if depth / 4 >= recursion_limit {
359 // This can get into rather deep recursion, especially in the
360 // presence of things like Vec<T> -> Unique<T> -> PhantomData<T> -> T.
361 // use a higher recursion limit to avoid errors.
362 return Err(Error::Overflow(context, ty))
365 // canoncialize the regions in `ty` before inserting - infinitely many
366 // region variables can refer to the same region.
367 let ty = cx.rcx.resolve_type_and_region_vars_if_possible(&ty);
369 if !cx.breadcrumbs.insert(ty) {
370 debug!("iterate_over_potentially_unsafe_regions_in_type \
371 {}ty: {} scope: {:?} - cached",
372 (0..depth).map(|_| ' ').collect::<String>(),
373 ty, cx.parent_scope);
374 return Ok(()); // we already visited this type
376 debug!("iterate_over_potentially_unsafe_regions_in_type \
377 {}ty: {} scope: {:?}",
378 (0..depth).map(|_| ' ').collect::<String>(),
379 ty, cx.parent_scope);
381 // If `typ` has a destructor, then we must ensure that all
382 // borrowed data reachable via `typ` must outlive the parent
383 // of `scope`. This is handled below.
385 // However, there is an important special case: for any Drop
386 // impl that is tagged as "blind" to their parameters,
387 // we assume that data borrowed via such type parameters
388 // remains unreachable via that Drop impl.
390 // For example, consider:
393 // #[unsafe_destructor_blind_to_params]
394 // impl<T> Drop for Vec<T> { ... }
397 // which does have to be able to drop instances of `T`, but
398 // otherwise cannot read data from `T`.
400 // Of course, for the type expression passed in for any such
401 // unbounded type parameter `T`, we must resume the recursive
402 // analysis on `T` (since it would be ignored by
403 // type_must_outlive).
404 if has_dtor_of_interest(tcx, ty) {
405 debug!("iterate_over_potentially_unsafe_regions_in_type \
406 {}ty: {} - is a dtorck type!",
407 (0..depth).map(|_| ' ').collect::<String>(),
410 cx.rcx.type_must_outlive(infer::SubregionOrigin::SafeDestructor(cx.span),
411 ty, tcx.mk_region(ty::ReScope(cx.parent_scope)));
416 debug!("iterate_over_potentially_unsafe_regions_in_type \
417 {}ty: {} scope: {:?} - checking interior",
418 (0..depth).map(|_| ' ').collect::<String>(),
419 ty, cx.parent_scope);
421 // We still need to ensure all referenced data is safe.
423 ty::TyBool | ty::TyChar | ty::TyInt(_) | ty::TyUint(_) |
424 ty::TyFloat(_) | ty::TyStr | ty::TyNever => {
425 // primitive - definitely safe
429 ty::TyBox(ity) | ty::TyArray(ity, _) | ty::TySlice(ity) => {
430 // single-element containers, behave like their element
431 iterate_over_potentially_unsafe_regions_in_type(
432 cx, context, ity, depth+1)
435 ty::TyStruct(def, substs) if def.is_phantom_data() => {
436 // PhantomData<T> - behaves identically to T
437 let ity = substs.type_at(0);
438 iterate_over_potentially_unsafe_regions_in_type(
439 cx, context, ity, depth+1)
442 ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => {
444 for variant in &def.variants {
445 for field in variant.fields.iter() {
446 let fty = field.ty(tcx, substs);
447 let fty = cx.rcx.fcx.resolve_type_vars_with_obligations(
448 cx.rcx.fcx.normalize_associated_types_in(cx.span, &fty));
449 iterate_over_potentially_unsafe_regions_in_type(
454 variant: variant.name,
464 ty::TyClosure(_, ty::ClosureSubsts { upvar_tys: tys, .. }) => {
466 iterate_over_potentially_unsafe_regions_in_type(cx, context, ty, depth+1)?
471 ty::TyRawPtr(..) | ty::TyRef(..) | ty::TyParam(..) => {
472 // these always come with a witness of liveness (references
473 // explicitly, pointers implicitly, parameters by the
478 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
479 // FIXME(#26656): this type is always destruction-safe, but
480 // it implicitly witnesses Self: Fn, which can be false.
484 ty::TyInfer(..) | ty::TyError => {
485 tcx.sess.delay_span_bug(cx.span, "unresolved type in regionck");
489 // these are always dtorck
490 ty::TyTrait(..) | ty::TyProjection(_) | ty::TyAnon(..) => bug!(),
494 fn has_dtor_of_interest<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
495 ty: Ty<'tcx>) -> bool {
497 ty::TyEnum(def, _) | ty::TyStruct(def, _) => {
500 ty::TyTrait(..) | ty::TyProjection(..) | ty::TyAnon(..) => {
501 debug!("ty: {:?} isn't known, and therefore is a dropck type", ty);