1 use crate::check::regionck::RegionCtxt;
3 use crate::hir::def_id::DefId;
4 use rustc::infer::outlives::env::OutlivesEnvironment;
5 use rustc::infer::{self, InferOk, SuppressRegionErrors};
6 use rustc::middle::region;
7 use rustc::traits::{ObligationCause, TraitEngine, TraitEngineExt};
8 use rustc::ty::subst::{Subst, Substs, UnpackedKind};
9 use rustc::ty::{self, Ty, TyCtxt};
10 use crate::util::common::ErrorReported;
15 /// This function confirms that the `Drop` implementation identified by
16 /// `drop_impl_did` is not any more specialized than the type it is
17 /// attached to (Issue #8142).
21 /// 1. The self type must be nominal (this is already checked during
24 /// 2. The generic region/type parameters of the impl's self type must
25 /// all be parameters of the Drop impl itself (i.e., no
26 /// specialization like `impl Drop for Foo<i32>`), and,
28 /// 3. Any bounds on the generic parameters must be reflected in the
29 /// struct/enum definition for the nominal type itself (i.e.
30 /// cannot do `struct S<T>; impl<T:Clone> Drop for S<T> { ... }`).
32 pub fn check_drop_impl<'a, 'tcx>(
33 tcx: TyCtxt<'a, 'tcx, 'tcx>,
35 ) -> Result<(), ErrorReported> {
36 let dtor_self_type = tcx.type_of(drop_impl_did);
37 let dtor_predicates = tcx.predicates_of(drop_impl_did);
38 match dtor_self_type.sty {
39 ty::Adt(adt_def, self_to_impl_substs) => {
40 ensure_drop_params_and_item_params_correspond(
47 ensure_drop_predicates_are_implied_by_item_defn(
56 // Destructors only work on nominal types. This was
57 // already checked by coherence, but compilation may
58 // not have been terminated.
59 let span = tcx.def_span(drop_impl_did);
60 tcx.sess.delay_span_bug(span,
61 &format!("should have been rejected by coherence check: {}", dtor_self_type));
67 fn ensure_drop_params_and_item_params_correspond<'a, 'tcx>(
68 tcx: TyCtxt<'a, 'tcx, 'tcx>,
70 drop_impl_ty: Ty<'tcx>,
72 ) -> Result<(), ErrorReported> {
73 let drop_impl_node_id = tcx.hir().as_local_node_id(drop_impl_did).unwrap();
75 // check that the impl type can be made to match the trait type.
77 tcx.infer_ctxt().enter(|ref infcx| {
78 let impl_param_env = tcx.param_env(self_type_did);
80 let mut fulfillment_cx = TraitEngine::new(tcx);
82 let named_type = tcx.type_of(self_type_did);
84 let drop_impl_span = tcx.def_span(drop_impl_did);
85 let fresh_impl_substs = infcx.fresh_substs_for_item(drop_impl_span, drop_impl_did);
86 let fresh_impl_self_ty = drop_impl_ty.subst(tcx, fresh_impl_substs);
88 let cause = &ObligationCause::misc(drop_impl_span, drop_impl_node_id);
90 .at(cause, impl_param_env)
91 .eq(named_type, fresh_impl_self_ty)
93 Ok(InferOk { obligations, .. }) => {
94 fulfillment_cx.register_predicate_obligations(infcx, obligations);
97 let item_span = tcx.def_span(self_type_did);
102 "Implementations of Drop cannot be specialized"
105 "Use same sequence of generic type and region \
106 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, false);
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());
131 infcx.resolve_regions_and_report_errors(
135 SuppressRegionErrors::default(),
141 /// Confirms that every predicate imposed by dtor_predicates is
142 /// implied by assuming the predicates attached to self_type_did.
143 fn ensure_drop_predicates_are_implied_by_item_defn<'a, 'tcx>(
144 tcx: TyCtxt<'a, 'tcx, 'tcx>,
145 drop_impl_did: DefId,
146 dtor_predicates: &ty::GenericPredicates<'tcx>,
147 self_type_did: DefId,
148 self_to_impl_substs: &Substs<'tcx>,
149 ) -> Result<(), ErrorReported> {
150 let mut result = Ok(());
152 // Here is an example, analogous to that from
153 // `compare_impl_method`.
155 // Consider a struct type:
157 // struct Type<'c, 'b:'c, 'a> {
158 // x: &'a Contents // (contents are irrelevant;
159 // y: &'c Cell<&'b Contents>, // only the bounds matter for our purposes.)
164 // impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
165 // fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
168 // We start out with self_to_impl_substs, that maps the generic
169 // parameters of Type to that of the Drop impl.
171 // self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
173 // Applying this to the predicates (i.e., assumptions) provided by the item
174 // definition yields the instantiated assumptions:
178 // We then check all of the predicates of the Drop impl:
182 // and ensure each is in the list of instantiated
183 // assumptions. Here, `'y:'z` is present, but `'x:'y` is
184 // absent. So we report an error that the Drop impl injected a
185 // predicate that is not present on the struct definition.
187 let self_type_hir_id = tcx.hir().as_local_hir_id(self_type_did).unwrap();
189 let drop_impl_span = tcx.def_span(drop_impl_did);
191 // We can assume the predicates attached to struct/enum definition
193 let generic_assumptions = tcx.predicates_of(self_type_did);
195 let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
196 let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
198 // An earlier version of this code attempted to do this checking
199 // via the traits::fulfill machinery. However, it ran into trouble
200 // since the fulfill machinery merely turns outlives-predicates
201 // 'a:'b and T:'b into region inference constraints. It is simpler
202 // just to look for all the predicates directly.
204 assert_eq!(dtor_predicates.parent, None);
205 for (predicate, _) in &dtor_predicates.predicates {
206 // (We do not need to worry about deep analysis of type
207 // expressions etc because the Drop impls are already forced
208 // to take on a structure that is roughly an alpha-renaming of
209 // the generic parameters of the item definition.)
211 // This path now just checks *all* predicates via the direct
212 // lookup, rather than using fulfill machinery.
214 // However, it may be more efficient in the future to batch
215 // the analysis together via the fulfill , rather than the
216 // repeated `contains` calls.
218 if !assumptions_in_impl_context.contains(&predicate) {
219 let item_span = tcx.hir().span_by_hir_id(self_type_hir_id);
224 "The requirement `{}` is added only by the Drop impl.",
228 "The same requirement must be part of \
229 the struct/enum definition",
232 result = Err(ErrorReported);
239 /// This function confirms that the type
240 /// expression `typ` conforms to the "Drop Check Rule" from the Sound
241 /// Generic Drop RFC (#769).
245 /// The simplified (*) Drop Check Rule is the following:
247 /// Let `v` be some value (either temporary or named) and 'a be some
248 /// lifetime (scope). If the type of `v` owns data of type `D`, where
250 /// * (1.) `D` has a lifetime- or type-parametric Drop implementation,
251 /// (where that `Drop` implementation does not opt-out of
252 /// this check via the `unsafe_destructor_blind_to_params`
254 /// * (2.) the structure of `D` can reach a reference of type `&'a _`,
256 /// then 'a must strictly outlive the scope of v.
260 /// This function is meant to by applied to the type for every
261 /// expression in the program.
265 /// (*) The qualifier "simplified" is attached to the above
266 /// definition of the Drop Check Rule, because it is a simplification
267 /// of the original Drop Check rule, which attempted to prove that
268 /// some `Drop` implementations could not possibly access data even if
269 /// it was technically reachable, due to parametricity.
271 /// However, (1.) parametricity on its own turned out to be a
272 /// necessary but insufficient condition, and (2.) future changes to
273 /// the language are expected to make it impossible to ensure that a
274 /// `Drop` implementation is actually parametric with respect to any
275 /// particular type parameter. (In particular, impl specialization is
276 /// expected to break the needed parametricity property beyond
279 /// Therefore, we have scaled back Drop-Check to a more conservative
280 /// rule that does not attempt to deduce whether a `Drop`
281 /// implementation could not possible access data of a given lifetime;
282 /// instead Drop-Check now simply assumes that if a destructor has
283 /// access (direct or indirect) to a lifetime parameter, then that
284 /// lifetime must be forced to outlive that destructor's dynamic
285 /// extent. We then provide the `unsafe_destructor_blind_to_params`
286 /// attribute as a way for destructor implementations to opt-out of
287 /// this conservative assumption (and thus assume the obligation of
288 /// ensuring that they do not access data nor invoke methods of
289 /// values that have been previously dropped).
290 pub fn check_safety_of_destructor_if_necessary<'a, 'gcx, 'tcx>(
291 rcx: &mut RegionCtxt<'a, 'gcx, 'tcx>,
294 body_id: ast::NodeId,
295 scope: region::Scope,
296 ) -> Result<(), ErrorReported> {
297 debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
300 let parent_scope = match rcx.region_scope_tree.opt_encl_scope(scope) {
301 Some(parent_scope) => parent_scope,
302 // If no enclosing scope, then it must be the root scope
303 // which cannot be outlived.
304 None => return Ok(()),
306 let parent_scope = rcx.tcx.mk_region(ty::ReScope(parent_scope));
307 let origin = || infer::SubregionOrigin::SafeDestructor(span);
308 let cause = &ObligationCause::misc(span, body_id);
309 let infer_ok = rcx.infcx.at(cause, rcx.fcx.param_env).dropck_outlives(ty);
310 debug!("dropck_outlives = {:#?}", infer_ok);
311 let kinds = rcx.fcx.register_infer_ok_obligations(infer_ok);
313 match kind.unpack() {
314 UnpackedKind::Lifetime(r) => rcx.sub_regions(origin(), parent_scope, r),
315 UnpackedKind::Type(ty) => rcx.type_must_outlive(origin(), ty, parent_scope),