1 use crate::check::regionck::RegionCtxt;
4 use crate::hir::def_id::DefId;
5 use rustc::infer::outlives::env::OutlivesEnvironment;
6 use rustc::infer::{self, InferOk, SuppressRegionErrors};
7 use rustc::middle::region;
8 use rustc::traits::{ObligationCause, TraitEngine, TraitEngineExt};
9 use rustc::ty::subst::{Subst, SubstsRef, UnpackedKind};
10 use rustc::ty::{self, Ty, TyCtxt};
11 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(tcx: TyCtxt<'_>, drop_impl_did: DefId) -> Result<(), ErrorReported> {
33 let dtor_self_type = tcx.type_of(drop_impl_did);
34 let dtor_predicates = tcx.predicates_of(drop_impl_did);
35 match dtor_self_type.kind {
36 ty::Adt(adt_def, self_to_impl_substs) => {
37 ensure_drop_params_and_item_params_correspond(
44 ensure_drop_predicates_are_implied_by_item_defn(
53 // Destructors only work on nominal types. This was
54 // already checked by coherence, but compilation may
55 // not have been terminated.
56 let span = tcx.def_span(drop_impl_did);
57 tcx.sess.delay_span_bug(span,
58 &format!("should have been rejected by coherence check: {}", dtor_self_type));
64 fn ensure_drop_params_and_item_params_correspond<'tcx>(
67 drop_impl_ty: Ty<'tcx>,
69 ) -> Result<(), ErrorReported> {
70 let drop_impl_hir_id = tcx.hir().as_local_hir_id(drop_impl_did).unwrap();
72 // check that the impl type can be made to match the trait type.
74 tcx.infer_ctxt().enter(|ref infcx| {
75 let impl_param_env = tcx.param_env(self_type_did);
77 let mut fulfillment_cx = TraitEngine::new(tcx);
79 let named_type = tcx.type_of(self_type_did);
81 let drop_impl_span = tcx.def_span(drop_impl_did);
82 let fresh_impl_substs = infcx.fresh_substs_for_item(drop_impl_span, drop_impl_did);
83 let fresh_impl_self_ty = drop_impl_ty.subst(tcx, fresh_impl_substs);
85 let cause = &ObligationCause::misc(drop_impl_span, drop_impl_hir_id);
87 .at(cause, impl_param_env)
88 .eq(named_type, fresh_impl_self_ty)
90 Ok(InferOk { obligations, .. }) => {
91 fulfillment_cx.register_predicate_obligations(infcx, obligations);
94 let item_span = tcx.def_span(self_type_did);
99 "Implementations of Drop cannot be specialized"
102 "Use same sequence of generic type and region \
103 parameters that is on the struct/enum definition",
106 return Err(ErrorReported);
110 if let Err(ref errors) = fulfillment_cx.select_all_or_error(&infcx) {
111 // this could be reached when we get lazy normalization
112 infcx.report_fulfillment_errors(errors, None, false);
113 return Err(ErrorReported);
116 let region_scope_tree = region::ScopeTree::default();
118 // NB. It seems a bit... suspicious to use an empty param-env
119 // here. The correct thing, I imagine, would be
120 // `OutlivesEnvironment::new(impl_param_env)`, which would
121 // allow region solving to take any `a: 'b` relations on the
122 // impl into account. But I could not create a test case where
123 // it did the wrong thing, so I chose to preserve existing
124 // behavior, since it ought to be simply more
125 // conservative. -nmatsakis
126 let outlives_env = OutlivesEnvironment::new(ty::ParamEnv::empty());
128 infcx.resolve_regions_and_report_errors(
132 SuppressRegionErrors::default(),
138 /// Confirms that every predicate imposed by dtor_predicates is
139 /// implied by assuming the predicates attached to self_type_did.
140 fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>(
142 drop_impl_did: DefId,
143 dtor_predicates: &ty::GenericPredicates<'tcx>,
144 self_type_did: DefId,
145 self_to_impl_substs: SubstsRef<'tcx>,
146 ) -> Result<(), ErrorReported> {
147 let mut result = Ok(());
149 // Here is an example, analogous to that from
150 // `compare_impl_method`.
152 // Consider a struct type:
154 // struct Type<'c, 'b:'c, 'a> {
155 // x: &'a Contents // (contents are irrelevant;
156 // y: &'c Cell<&'b Contents>, // only the bounds matter for our purposes.)
161 // impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
162 // fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
165 // We start out with self_to_impl_substs, that maps the generic
166 // parameters of Type to that of the Drop impl.
168 // self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
170 // Applying this to the predicates (i.e., assumptions) provided by the item
171 // definition yields the instantiated assumptions:
175 // We then check all of the predicates of the Drop impl:
179 // and ensure each is in the list of instantiated
180 // assumptions. Here, `'y:'z` is present, but `'x:'y` is
181 // absent. So we report an error that the Drop impl injected a
182 // predicate that is not present on the struct definition.
184 let self_type_hir_id = tcx.hir().as_local_hir_id(self_type_did).unwrap();
186 let drop_impl_span = tcx.def_span(drop_impl_did);
188 // We can assume the predicates attached to struct/enum definition
190 let generic_assumptions = tcx.predicates_of(self_type_did);
192 let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
193 let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
195 // An earlier version of this code attempted to do this checking
196 // via the traits::fulfill machinery. However, it ran into trouble
197 // since the fulfill machinery merely turns outlives-predicates
198 // 'a:'b and T:'b into region inference constraints. It is simpler
199 // just to look for all the predicates directly.
201 assert_eq!(dtor_predicates.parent, None);
202 for (predicate, _) in &dtor_predicates.predicates {
203 // (We do not need to worry about deep analysis of type
204 // expressions etc because the Drop impls are already forced
205 // to take on a structure that is roughly an alpha-renaming of
206 // the generic parameters of the item definition.)
208 // This path now just checks *all* predicates via the direct
209 // lookup, rather than using fulfill machinery.
211 // However, it may be more efficient in the future to batch
212 // the analysis together via the fulfill , rather than the
213 // repeated `contains` calls.
215 if !assumptions_in_impl_context.contains(&predicate) {
216 let item_span = tcx.hir().span(self_type_hir_id);
221 "The requirement `{}` is added only by the Drop impl.",
225 "The same requirement must be part of \
226 the struct/enum definition",
229 result = Err(ErrorReported);
236 /// This function confirms that the type
237 /// expression `typ` conforms to the "Drop Check Rule" from the Sound
238 /// Generic Drop RFC (#769).
242 /// The simplified (*) Drop Check Rule is the following:
244 /// Let `v` be some value (either temporary or named) and 'a be some
245 /// lifetime (scope). If the type of `v` owns data of type `D`, where
247 /// * (1.) `D` has a lifetime- or type-parametric Drop implementation,
248 /// (where that `Drop` implementation does not opt-out of
249 /// this check via the `may_dangle`
251 /// * (2.) the structure of `D` can reach a reference of type `&'a _`,
253 /// then 'a must strictly outlive the scope of v.
257 /// This function is meant to by applied to the type for every
258 /// expression in the program.
262 /// (*) The qualifier "simplified" is attached to the above
263 /// definition of the Drop Check Rule, because it is a simplification
264 /// of the original Drop Check rule, which attempted to prove that
265 /// some `Drop` implementations could not possibly access data even if
266 /// it was technically reachable, due to parametricity.
268 /// However, (1.) parametricity on its own turned out to be a
269 /// necessary but insufficient condition, and (2.) future changes to
270 /// the language are expected to make it impossible to ensure that a
271 /// `Drop` implementation is actually parametric with respect to any
272 /// particular type parameter. (In particular, impl specialization is
273 /// expected to break the needed parametricity property beyond
276 /// Therefore, we have scaled back Drop-Check to a more conservative
277 /// rule that does not attempt to deduce whether a `Drop`
278 /// implementation could not possible access data of a given lifetime;
279 /// instead Drop-Check now simply assumes that if a destructor has
280 /// access (direct or indirect) to a lifetime parameter, then that
281 /// lifetime must be forced to outlive that destructor's dynamic
282 /// extent. We then provide the `may_dangle`
283 /// attribute as a way for destructor implementations to opt-out of
284 /// this conservative assumption (and thus assume the obligation of
285 /// ensuring that they do not access data nor invoke methods of
286 /// values that have been previously dropped).
287 pub fn check_safety_of_destructor_if_necessary<'a, 'tcx>(
288 rcx: &mut RegionCtxt<'a, 'tcx>,
292 scope: region::Scope,
293 ) -> Result<(), ErrorReported> {
294 debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
297 let parent_scope = match rcx.region_scope_tree.opt_encl_scope(scope) {
298 Some(parent_scope) => parent_scope,
299 // If no enclosing scope, then it must be the root scope
300 // which cannot be outlived.
301 None => return Ok(()),
303 let parent_scope = rcx.tcx.mk_region(ty::ReScope(parent_scope));
304 let origin = || infer::SubregionOrigin::SafeDestructor(span);
305 let cause = &ObligationCause::misc(span, body_id);
306 let infer_ok = rcx.infcx.at(cause, rcx.fcx.param_env).dropck_outlives(ty);
307 debug!("dropck_outlives = {:#?}", infer_ok);
308 let kinds = rcx.fcx.register_infer_ok_obligations(infer_ok);
310 match kind.unpack() {
311 UnpackedKind::Lifetime(r) => rcx.sub_regions(origin(), parent_scope, r),
312 UnpackedKind::Type(ty) => rcx.type_must_outlive(origin(), ty, parent_scope),
313 UnpackedKind::Const(_) => {
314 // Generic consts don't add constraints.