1 use crate::check::regionck::RegionCtxt;
2 use crate::hir;
3 use crate::hir::def_id::{DefId, LocalDefId};
4 use rustc_errors::{struct_span_err, ErrorReported};
5 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
6 use rustc_infer::infer::{InferOk, RegionckMode, TyCtxtInferExt};
7 use rustc_infer::traits::TraitEngineExt as _;
8 use rustc_middle::ty::error::TypeError;
9 use rustc_middle::ty::relate::{Relate, RelateResult, TypeRelation};
10 use rustc_middle::ty::subst::{Subst, SubstsRef};
11 use rustc_middle::ty::{self, Predicate, Ty, TyCtxt};
12 use rustc_span::Span;
13 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
14 use rustc_trait_selection::traits::query::dropck_outlives::AtExt;
15 use rustc_trait_selection::traits::{ObligationCause, TraitEngine, TraitEngineExt};
16
17 /// This function confirms that the `Drop` implementation identified by
18 /// `drop_impl_did` is not any more specialized than the type it is
19 /// attached to (Issue #8142).
20 ///
21 /// This means:
22 ///
23 /// 1. The self type must be nominal (this is already checked during
24 /// coherence),
25 ///
26 /// 2. The generic region/type parameters of the impl's self type must
27 /// all be parameters of the Drop impl itself (i.e., no
28 /// specialization like `impl Drop for Foo<i32>`), and,
29 ///
30 /// 3. Any bounds on the generic parameters must be reflected in the
31 /// struct/enum definition for the nominal type itself (i.e.
32 /// cannot do `struct S<T>; impl<T:Clone> Drop for S<T> { ... }`).
33 ///
check_drop_impl(tcx: TyCtxt<'_>, drop_impl_did: DefId) -> Result<(), ErrorReported>34 pub fn check_drop_impl(tcx: TyCtxt<'_>, drop_impl_did: DefId) -> Result<(), ErrorReported> {
35 let dtor_self_type = tcx.type_of(drop_impl_did);
36 let dtor_predicates = tcx.predicates_of(drop_impl_did);
37 match dtor_self_type.kind() {
38 ty::Adt(adt_def, self_to_impl_substs) => {
39 ensure_drop_params_and_item_params_correspond(
40 tcx,
41 drop_impl_did.expect_local(),
42 dtor_self_type,
43 adt_def.did,
44 )?;
45
46 ensure_drop_predicates_are_implied_by_item_defn(
47 tcx,
48 dtor_predicates,
49 adt_def.did.expect_local(),
50 self_to_impl_substs,
51 )
52 }
53 _ => {
54 // Destructors only work on nominal types. This was
55 // already checked by coherence, but compilation may
56 // not have been terminated.
57 let span = tcx.def_span(drop_impl_did);
58 tcx.sess.delay_span_bug(
59 span,
60 &format!("should have been rejected by coherence check: {}", dtor_self_type),
61 );
62 Err(ErrorReported)
63 }
64 }
65 }
66
ensure_drop_params_and_item_params_correspond<'tcx>( tcx: TyCtxt<'tcx>, drop_impl_did: LocalDefId, drop_impl_ty: Ty<'tcx>, self_type_did: DefId, ) -> Result<(), ErrorReported>67 fn ensure_drop_params_and_item_params_correspond<'tcx>(
68 tcx: TyCtxt<'tcx>,
69 drop_impl_did: LocalDefId,
70 drop_impl_ty: Ty<'tcx>,
71 self_type_did: DefId,
72 ) -> Result<(), ErrorReported> {
73 let drop_impl_hir_id = tcx.hir().local_def_id_to_hir_id(drop_impl_did);
74
75 // check that the impl type can be made to match the trait type.
76
77 tcx.infer_ctxt().enter(|ref infcx| {
78 let impl_param_env = tcx.param_env(self_type_did);
79 let tcx = infcx.tcx;
80 let mut fulfillment_cx = <dyn TraitEngine<'_>>::new(tcx);
81
82 let named_type = tcx.type_of(self_type_did);
83
84 let drop_impl_span = tcx.def_span(drop_impl_did);
85 let fresh_impl_substs =
86 infcx.fresh_substs_for_item(drop_impl_span, drop_impl_did.to_def_id());
87 let fresh_impl_self_ty = drop_impl_ty.subst(tcx, fresh_impl_substs);
88
89 let cause = &ObligationCause::misc(drop_impl_span, drop_impl_hir_id);
90 match infcx.at(cause, impl_param_env).eq(named_type, fresh_impl_self_ty) {
91 Ok(InferOk { obligations, .. }) => {
92 fulfillment_cx.register_predicate_obligations(infcx, obligations);
93 }
94 Err(_) => {
95 let item_span = tcx.def_span(self_type_did);
96 let self_descr = tcx.def_kind(self_type_did).descr(self_type_did);
97 struct_span_err!(
98 tcx.sess,
99 drop_impl_span,
100 E0366,
101 "`Drop` impls cannot be specialized"
102 )
103 .span_note(
104 item_span,
105 &format!(
106 "use the same sequence of generic type, lifetime and const parameters \
107 as the {} definition",
108 self_descr,
109 ),
110 )
111 .emit();
112 return Err(ErrorReported);
113 }
114 }
115
116 let errors = fulfillment_cx.select_all_or_error(&infcx);
117 if !errors.is_empty() {
118 // this could be reached when we get lazy normalization
119 infcx.report_fulfillment_errors(&errors, None, false);
120 return Err(ErrorReported);
121 }
122
123 // NB. It seems a bit... suspicious to use an empty param-env
124 // here. The correct thing, I imagine, would be
125 // `OutlivesEnvironment::new(impl_param_env)`, which would
126 // allow region solving to take any `a: 'b` relations on the
127 // impl into account. But I could not create a test case where
128 // it did the wrong thing, so I chose to preserve existing
129 // behavior, since it ought to be simply more
130 // conservative. -nmatsakis
131 let outlives_env = OutlivesEnvironment::new(ty::ParamEnv::empty());
132
133 infcx.resolve_regions_and_report_errors(
134 drop_impl_did.to_def_id(),
135 &outlives_env,
136 RegionckMode::default(),
137 );
138 Ok(())
139 })
140 }
141
142 /// Confirms that every predicate imposed by dtor_predicates is
143 /// implied by assuming the predicates attached to self_type_did.
ensure_drop_predicates_are_implied_by_item_defn<'tcx>( tcx: TyCtxt<'tcx>, dtor_predicates: ty::GenericPredicates<'tcx>, self_type_did: LocalDefId, self_to_impl_substs: SubstsRef<'tcx>, ) -> Result<(), ErrorReported>144 fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>(
145 tcx: TyCtxt<'tcx>,
146 dtor_predicates: ty::GenericPredicates<'tcx>,
147 self_type_did: LocalDefId,
148 self_to_impl_substs: SubstsRef<'tcx>,
149 ) -> Result<(), ErrorReported> {
150 let mut result = Ok(());
151
152 // Here is an example, analogous to that from
153 // `compare_impl_method`.
154 //
155 // Consider a struct type:
156 //
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.)
160 // }
161 //
162 // and a Drop impl:
163 //
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)
166 // }
167 //
168 // We start out with self_to_impl_substs, that maps the generic
169 // parameters of Type to that of the Drop impl.
170 //
171 // self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
172 //
173 // Applying this to the predicates (i.e., assumptions) provided by the item
174 // definition yields the instantiated assumptions:
175 //
176 // ['y : 'z]
177 //
178 // We then check all of the predicates of the Drop impl:
179 //
180 // ['y:'z, 'x:'y]
181 //
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.
186
187 let self_type_hir_id = tcx.hir().local_def_id_to_hir_id(self_type_did);
188
189 // We can assume the predicates attached to struct/enum definition
190 // hold.
191 let generic_assumptions = tcx.predicates_of(self_type_did);
192
193 let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
194 let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
195
196 let self_param_env = tcx.param_env(self_type_did);
197
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.
203
204 assert_eq!(dtor_predicates.parent, None);
205 for &(predicate, predicate_sp) 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.)
210
211 // This path now just checks *all* predicates via an instantiation of
212 // the `SimpleEqRelation`, which simply forwards to the `relate` machinery
213 // after taking care of anonymizing late bound regions.
214 //
215 // However, it may be more efficient in the future to batch
216 // the analysis together via the fulfill (see comment above regarding
217 // the usage of the fulfill machinery), rather than the
218 // repeated `.iter().any(..)` calls.
219
220 // This closure is a more robust way to check `Predicate` equality
221 // than simple `==` checks (which were the previous implementation).
222 // It relies on `ty::relate` for `TraitPredicate`, `ProjectionPredicate`,
223 // `ConstEvaluatable` and `TypeOutlives` (which implement the Relate trait),
224 // while delegating on simple equality for the other `Predicate`.
225 // This implementation solves (Issue #59497) and (Issue #58311).
226 // It is unclear to me at the moment whether the approach based on `relate`
227 // could be extended easily also to the other `Predicate`.
228 let predicate_matches_closure = |p: Predicate<'tcx>| {
229 let mut relator: SimpleEqRelation<'tcx> = SimpleEqRelation::new(tcx, self_param_env);
230 let predicate = predicate.kind();
231 let p = p.kind();
232 match (predicate.skip_binder(), p.skip_binder()) {
233 (ty::PredicateKind::Trait(a), ty::PredicateKind::Trait(b)) => {
234 relator.relate(predicate.rebind(a), p.rebind(b)).is_ok()
235 }
236 (ty::PredicateKind::Projection(a), ty::PredicateKind::Projection(b)) => {
237 relator.relate(predicate.rebind(a), p.rebind(b)).is_ok()
238 }
239 (
240 ty::PredicateKind::ConstEvaluatable(a),
241 ty::PredicateKind::ConstEvaluatable(b),
242 ) => tcx.try_unify_abstract_consts((a, b)),
243 (
244 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_a, lt_a)),
245 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_b, lt_b)),
246 ) => {
247 relator.relate(predicate.rebind(ty_a), p.rebind(ty_b)).is_ok()
248 && relator.relate(predicate.rebind(lt_a), p.rebind(lt_b)).is_ok()
249 }
250 _ => predicate == p,
251 }
252 };
253
254 if !assumptions_in_impl_context.iter().copied().any(predicate_matches_closure) {
255 let item_span = tcx.hir().span(self_type_hir_id);
256 let self_descr = tcx.def_kind(self_type_did).descr(self_type_did.to_def_id());
257 struct_span_err!(
258 tcx.sess,
259 predicate_sp,
260 E0367,
261 "`Drop` impl requires `{}` but the {} it is implemented for does not",
262 predicate,
263 self_descr,
264 )
265 .span_note(item_span, "the implementor must specify the same requirement")
266 .emit();
267 result = Err(ErrorReported);
268 }
269 }
270
271 result
272 }
273
274 /// This function is not only checking that the dropck obligations are met for
275 /// the given type, but it's also currently preventing non-regular recursion in
276 /// types from causing stack overflows (dropck_no_diverge_on_nonregular_*.rs).
check_drop_obligations<'a, 'tcx>( rcx: &mut RegionCtxt<'a, 'tcx>, ty: Ty<'tcx>, span: Span, body_id: hir::HirId, )277 crate fn check_drop_obligations<'a, 'tcx>(
278 rcx: &mut RegionCtxt<'a, 'tcx>,
279 ty: Ty<'tcx>,
280 span: Span,
281 body_id: hir::HirId,
282 ) {
283 debug!("check_drop_obligations typ: {:?}", ty);
284
285 let cause = &ObligationCause::misc(span, body_id);
286 let infer_ok = rcx.infcx.at(cause, rcx.fcx.param_env).dropck_outlives(ty);
287 debug!("dropck_outlives = {:#?}", infer_ok);
288 rcx.fcx.register_infer_ok_obligations(infer_ok);
289 }
290
291 // This is an implementation of the TypeRelation trait with the
292 // aim of simply comparing for equality (without side-effects).
293 // It is not intended to be used anywhere else other than here.
294 crate struct SimpleEqRelation<'tcx> {
295 tcx: TyCtxt<'tcx>,
296 param_env: ty::ParamEnv<'tcx>,
297 }
298
299 impl<'tcx> SimpleEqRelation<'tcx> {
new(tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> SimpleEqRelation<'tcx>300 fn new(tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> SimpleEqRelation<'tcx> {
301 SimpleEqRelation { tcx, param_env }
302 }
303 }
304
305 impl TypeRelation<'tcx> for SimpleEqRelation<'tcx> {
tcx(&self) -> TyCtxt<'tcx>306 fn tcx(&self) -> TyCtxt<'tcx> {
307 self.tcx
308 }
309
param_env(&self) -> ty::ParamEnv<'tcx>310 fn param_env(&self) -> ty::ParamEnv<'tcx> {
311 self.param_env
312 }
313
tag(&self) -> &'static str314 fn tag(&self) -> &'static str {
315 "dropck::SimpleEqRelation"
316 }
317
a_is_expected(&self) -> bool318 fn a_is_expected(&self) -> bool {
319 true
320 }
321
relate_with_variance<T: Relate<'tcx>>( &mut self, _: ty::Variance, _info: ty::VarianceDiagInfo<'tcx>, a: T, b: T, ) -> RelateResult<'tcx, T>322 fn relate_with_variance<T: Relate<'tcx>>(
323 &mut self,
324 _: ty::Variance,
325 _info: ty::VarianceDiagInfo<'tcx>,
326 a: T,
327 b: T,
328 ) -> RelateResult<'tcx, T> {
329 // Here we ignore variance because we require drop impl's types
330 // to be *exactly* the same as to the ones in the struct definition.
331 self.relate(a, b)
332 }
333
tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>>334 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
335 debug!("SimpleEqRelation::tys(a={:?}, b={:?})", a, b);
336 ty::relate::super_relate_tys(self, a, b)
337 }
338
regions( &mut self, a: ty::Region<'tcx>, b: ty::Region<'tcx>, ) -> RelateResult<'tcx, ty::Region<'tcx>>339 fn regions(
340 &mut self,
341 a: ty::Region<'tcx>,
342 b: ty::Region<'tcx>,
343 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
344 debug!("SimpleEqRelation::regions(a={:?}, b={:?})", a, b);
345
346 // We can just equate the regions because LBRs have been
347 // already anonymized.
348 if a == b {
349 Ok(a)
350 } else {
351 // I'm not sure is this `TypeError` is the right one, but
352 // it should not matter as it won't be checked (the dropck
353 // will emit its own, more informative and higher-level errors
354 // in case anything goes wrong).
355 Err(TypeError::RegionsPlaceholderMismatch)
356 }
357 }
358
consts( &mut self, a: &'tcx ty::Const<'tcx>, b: &'tcx ty::Const<'tcx>, ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>>359 fn consts(
360 &mut self,
361 a: &'tcx ty::Const<'tcx>,
362 b: &'tcx ty::Const<'tcx>,
363 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
364 debug!("SimpleEqRelation::consts(a={:?}, b={:?})", a, b);
365 ty::relate::super_relate_consts(self, a, b)
366 }
367
binders<T>( &mut self, a: ty::Binder<'tcx, T>, b: ty::Binder<'tcx, T>, ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> where T: Relate<'tcx>,368 fn binders<T>(
369 &mut self,
370 a: ty::Binder<'tcx, T>,
371 b: ty::Binder<'tcx, T>,
372 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
373 where
374 T: Relate<'tcx>,
375 {
376 debug!("SimpleEqRelation::binders({:?}: {:?}", a, b);
377
378 // Anonymizing the LBRs is necessary to solve (Issue #59497).
379 // After we do so, it should be totally fine to skip the binders.
380 let anon_a = self.tcx.anonymize_late_bound_regions(a);
381 let anon_b = self.tcx.anonymize_late_bound_regions(b);
382 self.relate(anon_a.skip_binder(), anon_b.skip_binder())?;
383
384 Ok(a)
385 }
386 }
387