1 use crate::check::regionck::RegionCtxt;
4 use crate::hir::def_id::DefId;
5 use crate::util::common::ErrorReported;
6 use rustc::infer::outlives::env::OutlivesEnvironment;
7 use rustc::infer::{InferOk, SuppressRegionErrors};
8 use rustc::middle::region;
9 use rustc::traits::{ObligationCause, TraitEngine, TraitEngineExt};
10 use rustc::ty::error::TypeError;
11 use rustc::ty::relate::{Relate, RelateResult, TypeRelation};
12 use rustc::ty::subst::{Subst, SubstsRef};
13 use rustc::ty::{self, Predicate, Ty, TyCtxt};
17 use rustc_error_codes::*;
19 /// This function confirms that the `Drop` implementation identified by
20 /// `drop_impl_did` is not any more specialized than the type it is
21 /// attached to (Issue #8142).
25 /// 1. The self type must be nominal (this is already checked during
28 /// 2. The generic region/type parameters of the impl's self type must
29 /// all be parameters of the Drop impl itself (i.e., no
30 /// specialization like `impl Drop for Foo<i32>`), and,
32 /// 3. Any bounds on the generic parameters must be reflected in the
33 /// struct/enum definition for the nominal type itself (i.e.
34 /// cannot do `struct S<T>; impl<T:Clone> Drop for S<T> { ... }`).
36 pub fn check_drop_impl(tcx: TyCtxt<'_>, drop_impl_did: DefId) -> Result<(), ErrorReported> {
37 let dtor_self_type = tcx.type_of(drop_impl_did);
38 let dtor_predicates = tcx.predicates_of(drop_impl_did);
39 match dtor_self_type.kind {
40 ty::Adt(adt_def, self_to_impl_substs) => {
41 ensure_drop_params_and_item_params_correspond(
48 ensure_drop_predicates_are_implied_by_item_defn(
57 // Destructors only work on nominal types. This was
58 // already checked by coherence, but compilation may
59 // not have been terminated.
60 let span = tcx.def_span(drop_impl_did);
61 tcx.sess.delay_span_bug(
63 &format!("should have been rejected by coherence check: {}", dtor_self_type),
70 fn ensure_drop_params_and_item_params_correspond<'tcx>(
73 drop_impl_ty: Ty<'tcx>,
75 ) -> Result<(), ErrorReported> {
76 let drop_impl_hir_id = tcx.hir().as_local_hir_id(drop_impl_did).unwrap();
78 // check that the impl type can be made to match the trait type.
80 tcx.infer_ctxt().enter(|ref infcx| {
81 let impl_param_env = tcx.param_env(self_type_did);
83 let mut fulfillment_cx = TraitEngine::new(tcx);
85 let named_type = tcx.type_of(self_type_did);
87 let drop_impl_span = tcx.def_span(drop_impl_did);
88 let fresh_impl_substs = infcx.fresh_substs_for_item(drop_impl_span, drop_impl_did);
89 let fresh_impl_self_ty = drop_impl_ty.subst(tcx, fresh_impl_substs);
91 let cause = &ObligationCause::misc(drop_impl_span, drop_impl_hir_id);
92 match infcx.at(cause, impl_param_env).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"
106 "Use same sequence of generic type and region \
107 parameters that is on the struct/enum definition",
110 return Err(ErrorReported);
114 if let Err(ref errors) = fulfillment_cx.select_all_or_error(&infcx) {
115 // this could be reached when we get lazy normalization
116 infcx.report_fulfillment_errors(errors, None, false);
117 return Err(ErrorReported);
120 let region_scope_tree = region::ScopeTree::default();
122 // NB. It seems a bit... suspicious to use an empty param-env
123 // here. The correct thing, I imagine, would be
124 // `OutlivesEnvironment::new(impl_param_env)`, which would
125 // allow region solving to take any `a: 'b` relations on the
126 // impl into account. But I could not create a test case where
127 // it did the wrong thing, so I chose to preserve existing
128 // behavior, since it ought to be simply more
129 // conservative. -nmatsakis
130 let outlives_env = OutlivesEnvironment::new(ty::ParamEnv::empty());
132 infcx.resolve_regions_and_report_errors(
136 SuppressRegionErrors::default(),
142 /// Confirms that every predicate imposed by dtor_predicates is
143 /// implied by assuming the predicates attached to self_type_did.
144 fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>(
146 drop_impl_did: DefId,
147 dtor_predicates: ty::GenericPredicates<'tcx>,
148 self_type_did: DefId,
149 self_to_impl_substs: SubstsRef<'tcx>,
150 ) -> Result<(), ErrorReported> {
151 let mut result = Ok(());
153 // Here is an example, analogous to that from
154 // `compare_impl_method`.
156 // Consider a struct type:
158 // struct Type<'c, 'b:'c, 'a> {
159 // x: &'a Contents // (contents are irrelevant;
160 // y: &'c Cell<&'b Contents>, // only the bounds matter for our purposes.)
165 // impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
166 // fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
169 // We start out with self_to_impl_substs, that maps the generic
170 // parameters of Type to that of the Drop impl.
172 // self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
174 // Applying this to the predicates (i.e., assumptions) provided by the item
175 // definition yields the instantiated assumptions:
179 // We then check all of the predicates of the Drop impl:
183 // and ensure each is in the list of instantiated
184 // assumptions. Here, `'y:'z` is present, but `'x:'y` is
185 // absent. So we report an error that the Drop impl injected a
186 // predicate that is not present on the struct definition.
188 let self_type_hir_id = tcx.hir().as_local_hir_id(self_type_did).unwrap();
190 let drop_impl_span = tcx.def_span(drop_impl_did);
192 // We can assume the predicates attached to struct/enum definition
194 let generic_assumptions = tcx.predicates_of(self_type_did);
196 let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
197 let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
199 let self_param_env = tcx.param_env(self_type_did);
201 // An earlier version of this code attempted to do this checking
202 // via the traits::fulfill machinery. However, it ran into trouble
203 // since the fulfill machinery merely turns outlives-predicates
204 // 'a:'b and T:'b into region inference constraints. It is simpler
205 // just to look for all the predicates directly.
207 assert_eq!(dtor_predicates.parent, None);
208 for (predicate, _) in dtor_predicates.predicates {
209 // (We do not need to worry about deep analysis of type
210 // expressions etc because the Drop impls are already forced
211 // to take on a structure that is roughly an alpha-renaming of
212 // the generic parameters of the item definition.)
214 // This path now just checks *all* predicates via an instantiation of
215 // the `SimpleEqRelation`, which simply forwards to the `relate` machinery
216 // after taking care of anonymizing late bound regions.
218 // However, it may be more efficient in the future to batch
219 // the analysis together via the fulfill (see comment above regarding
220 // the usage of the fulfill machinery), rather than the
221 // repeated `.iter().any(..)` calls.
223 // This closure is a more robust way to check `Predicate` equality
224 // than simple `==` checks (which were the previous implementation).
225 // It relies on `ty::relate` for `TraitPredicate` and `ProjectionPredicate`
226 // (which implement the Relate trait), while delegating on simple equality
227 // for the other `Predicate`.
228 // This implementation solves (Issue #59497) and (Issue #58311).
229 // It is unclear to me at the moment whether the approach based on `relate`
230 // could be extended easily also to the other `Predicate`.
231 let predicate_matches_closure = |p: &'_ Predicate<'tcx>| {
232 let mut relator: SimpleEqRelation<'tcx> = SimpleEqRelation::new(tcx, self_param_env);
233 match (predicate, p) {
234 (Predicate::Trait(a), Predicate::Trait(b)) => relator.relate(a, b).is_ok(),
235 (Predicate::Projection(a), Predicate::Projection(b)) => {
236 relator.relate(a, b).is_ok()
242 if !assumptions_in_impl_context.iter().any(predicate_matches_closure) {
243 let item_span = tcx.hir().span(self_type_hir_id);
248 "The requirement `{}` is added only by the Drop impl.",
253 "The same requirement must be part of \
254 the struct/enum definition",
257 result = Err(ErrorReported);
264 /// This function is not only checking that the dropck obligations are met for
265 /// the given type, but it's also currently preventing non-regular recursion in
266 /// types from causing stack overflows (dropck_no_diverge_on_nonregular_*.rs).
267 crate fn check_drop_obligations<'a, 'tcx>(
268 rcx: &mut RegionCtxt<'a, 'tcx>,
272 ) -> Result<(), ErrorReported> {
273 debug!("check_drop_obligations typ: {:?}", ty);
275 let cause = &ObligationCause::misc(span, body_id);
276 let infer_ok = rcx.infcx.at(cause, rcx.fcx.param_env).dropck_outlives(ty);
277 debug!("dropck_outlives = {:#?}", infer_ok);
278 rcx.fcx.register_infer_ok_obligations(infer_ok);
283 // This is an implementation of the TypeRelation trait with the
284 // aim of simply comparing for equality (without side-effects).
285 // It is not intended to be used anywhere else other than here.
286 crate struct SimpleEqRelation<'tcx> {
288 param_env: ty::ParamEnv<'tcx>,
291 impl<'tcx> SimpleEqRelation<'tcx> {
292 fn new(tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> SimpleEqRelation<'tcx> {
293 SimpleEqRelation { tcx, param_env }
297 impl TypeRelation<'tcx> for SimpleEqRelation<'tcx> {
298 fn tcx(&self) -> TyCtxt<'tcx> {
302 fn param_env(&self) -> ty::ParamEnv<'tcx> {
306 fn tag(&self) -> &'static str {
307 "dropck::SimpleEqRelation"
310 fn a_is_expected(&self) -> bool {
314 fn relate_with_variance<T: Relate<'tcx>>(
319 ) -> RelateResult<'tcx, T> {
320 // Here we ignore variance because we require drop impl's types
321 // to be *exactly* the same as to the ones in the struct definition.
325 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
326 debug!("SimpleEqRelation::tys(a={:?}, b={:?})", a, b);
327 ty::relate::super_relate_tys(self, a, b)
334 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
335 debug!("SimpleEqRelation::regions(a={:?}, b={:?})", a, b);
337 // We can just equate the regions because LBRs have been
338 // already anonymized.
342 // I'm not sure is this `TypeError` is the right one, but
343 // it should not matter as it won't be checked (the dropck
344 // will emit its own, more informative and higher-level errors
345 // in case anything goes wrong).
346 Err(TypeError::RegionsPlaceholderMismatch)
352 a: &'tcx ty::Const<'tcx>,
353 b: &'tcx ty::Const<'tcx>,
354 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
355 debug!("SimpleEqRelation::consts(a={:?}, b={:?})", a, b);
356 ty::relate::super_relate_consts(self, a, b)
363 ) -> RelateResult<'tcx, ty::Binder<T>>
367 debug!("SimpleEqRelation::binders({:?}: {:?}", a, b);
369 // Anonymizing the LBRs is necessary to solve (Issue #59497).
370 // After we do so, it should be totally fine to skip the binders.
371 let anon_a = self.tcx.anonymize_late_bound_regions(a);
372 let anon_b = self.tcx.anonymize_late_bound_regions(b);
373 self.relate(anon_a.skip_binder(), anon_b.skip_binder())?;