]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/dropck.rs
rewrite `ensure_drop_params_and_item_params_correspond`
[rust.git] / compiler / rustc_typeck / src / check / dropck.rs
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, ErrorGuaranteed};
5 use rustc_middle::ty::error::TypeError;
6 use rustc_middle::ty::relate::{Relate, RelateResult, TypeRelation};
7 use rustc_middle::ty::subst::SubstsRef;
8 use rustc_middle::ty::{self, Predicate, Ty, TyCtxt};
9 use rustc_span::Span;
10 use rustc_trait_selection::traits::query::dropck_outlives::AtExt;
11 use rustc_trait_selection::traits::ObligationCause;
12
13 /// This function confirms that the `Drop` implementation identified by
14 /// `drop_impl_did` is not any more specialized than the type it is
15 /// attached to (Issue #8142).
16 ///
17 /// This means:
18 ///
19 /// 1. The self type must be nominal (this is already checked during
20 ///    coherence),
21 ///
22 /// 2. The generic region/type parameters of the impl's self type must
23 ///    all be parameters of the Drop impl itself (i.e., no
24 ///    specialization like `impl Drop for Foo<i32>`), and,
25 ///
26 /// 3. Any bounds on the generic parameters must be reflected in the
27 ///    struct/enum definition for the nominal type itself (i.e.
28 ///    cannot do `struct S<T>; impl<T:Clone> Drop for S<T> { ... }`).
29 ///
30 pub fn check_drop_impl(tcx: TyCtxt<'_>, drop_impl_did: DefId) -> Result<(), ErrorGuaranteed> {
31     let dtor_self_type = tcx.type_of(drop_impl_did);
32     let dtor_predicates = tcx.predicates_of(drop_impl_did);
33     match dtor_self_type.kind() {
34         ty::Adt(adt_def, self_to_impl_substs) => {
35             ensure_drop_params_and_item_params_correspond(
36                 tcx,
37                 drop_impl_did.expect_local(),
38                 adt_def.did(),
39                 self_to_impl_substs,
40             )?;
41
42             ensure_drop_predicates_are_implied_by_item_defn(
43                 tcx,
44                 dtor_predicates,
45                 adt_def.did().expect_local(),
46                 self_to_impl_substs,
47             )
48         }
49         _ => {
50             // Destructors only work on nominal types.  This was
51             // already checked by coherence, but compilation may
52             // not have been terminated.
53             let span = tcx.def_span(drop_impl_did);
54             let reported = tcx.sess.delay_span_bug(
55                 span,
56                 &format!("should have been rejected by coherence check: {dtor_self_type}"),
57             );
58             Err(reported)
59         }
60     }
61 }
62
63 fn ensure_drop_params_and_item_params_correspond<'tcx>(
64     tcx: TyCtxt<'tcx>,
65     drop_impl_did: LocalDefId,
66     self_type_did: DefId,
67     drop_impl_substs: SubstsRef<'tcx>,
68 ) -> Result<(), ErrorGuaranteed> {
69     let Err(arg) = tcx.uses_unique_generic_params(drop_impl_substs, false) else {
70         return Ok(())
71     };
72
73     let drop_impl_span = tcx.def_span(drop_impl_did);
74     let item_span = tcx.def_span(self_type_did);
75     let self_descr = tcx.def_kind(self_type_did).descr(self_type_did);
76     let mut err =
77         struct_span_err!(tcx.sess, drop_impl_span, E0366, "`Drop` impls cannot be specialized");
78     match arg {
79         ty::util::NotUniqueParam::DuplicateParam(arg) => {
80             err.note(&format!("`{arg}` is mentioned multiple times"))
81         }
82         ty::util::NotUniqueParam::NotParam(arg) => {
83             err.note(&format!("`{arg}` is not a generic parameter"))
84         }
85     };
86     err.span_note(
87         item_span,
88         &format!(
89             "use the same sequence of generic type, lifetime and const parameters \
90                      as the {self_descr} definition",
91         ),
92     );
93     Err(err.emit())
94 }
95
96 /// Confirms that every predicate imposed by dtor_predicates is
97 /// implied by assuming the predicates attached to self_type_did.
98 fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>(
99     tcx: TyCtxt<'tcx>,
100     dtor_predicates: ty::GenericPredicates<'tcx>,
101     self_type_did: LocalDefId,
102     self_to_impl_substs: SubstsRef<'tcx>,
103 ) -> Result<(), ErrorGuaranteed> {
104     let mut result = Ok(());
105
106     // Here is an example, analogous to that from
107     // `compare_impl_method`.
108     //
109     // Consider a struct type:
110     //
111     //     struct Type<'c, 'b:'c, 'a> {
112     //         x: &'a Contents            // (contents are irrelevant;
113     //         y: &'c Cell<&'b Contents>, //  only the bounds matter for our purposes.)
114     //     }
115     //
116     // and a Drop impl:
117     //
118     //     impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
119     //         fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
120     //     }
121     //
122     // We start out with self_to_impl_substs, that maps the generic
123     // parameters of Type to that of the Drop impl.
124     //
125     //     self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
126     //
127     // Applying this to the predicates (i.e., assumptions) provided by the item
128     // definition yields the instantiated assumptions:
129     //
130     //     ['y : 'z]
131     //
132     // We then check all of the predicates of the Drop impl:
133     //
134     //     ['y:'z, 'x:'y]
135     //
136     // and ensure each is in the list of instantiated
137     // assumptions. Here, `'y:'z` is present, but `'x:'y` is
138     // absent. So we report an error that the Drop impl injected a
139     // predicate that is not present on the struct definition.
140
141     // We can assume the predicates attached to struct/enum definition
142     // hold.
143     let generic_assumptions = tcx.predicates_of(self_type_did);
144
145     let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
146     let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
147
148     let self_param_env = tcx.param_env(self_type_did);
149
150     // An earlier version of this code attempted to do this checking
151     // via the traits::fulfill machinery. However, it ran into trouble
152     // since the fulfill machinery merely turns outlives-predicates
153     // 'a:'b and T:'b into region inference constraints. It is simpler
154     // just to look for all the predicates directly.
155
156     assert_eq!(dtor_predicates.parent, None);
157     for &(predicate, predicate_sp) in dtor_predicates.predicates {
158         // (We do not need to worry about deep analysis of type
159         // expressions etc because the Drop impls are already forced
160         // to take on a structure that is roughly an alpha-renaming of
161         // the generic parameters of the item definition.)
162
163         // This path now just checks *all* predicates via an instantiation of
164         // the `SimpleEqRelation`, which simply forwards to the `relate` machinery
165         // after taking care of anonymizing late bound regions.
166         //
167         // However, it may be more efficient in the future to batch
168         // the analysis together via the fulfill (see comment above regarding
169         // the usage of the fulfill machinery), rather than the
170         // repeated `.iter().any(..)` calls.
171
172         // This closure is a more robust way to check `Predicate` equality
173         // than simple `==` checks (which were the previous implementation).
174         // It relies on `ty::relate` for `TraitPredicate`, `ProjectionPredicate`,
175         // `ConstEvaluatable` and `TypeOutlives` (which implement the Relate trait),
176         // while delegating on simple equality for the other `Predicate`.
177         // This implementation solves (Issue #59497) and (Issue #58311).
178         // It is unclear to me at the moment whether the approach based on `relate`
179         // could be extended easily also to the other `Predicate`.
180         let predicate_matches_closure = |p: Predicate<'tcx>| {
181             let mut relator: SimpleEqRelation<'tcx> = SimpleEqRelation::new(tcx, self_param_env);
182             let predicate = predicate.kind();
183             let p = p.kind();
184             match (predicate.skip_binder(), p.skip_binder()) {
185                 (ty::PredicateKind::Trait(a), ty::PredicateKind::Trait(b)) => {
186                     // Since struct predicates cannot have ~const, project the impl predicate
187                     // onto one that ignores the constness. This is equivalent to saying that
188                     // we match a `Trait` bound on the struct with a `Trait` or `~const Trait`
189                     // in the impl.
190                     let non_const_a =
191                         ty::TraitPredicate { constness: ty::BoundConstness::NotConst, ..a };
192                     relator.relate(predicate.rebind(non_const_a), p.rebind(b)).is_ok()
193                 }
194                 (ty::PredicateKind::Projection(a), ty::PredicateKind::Projection(b)) => {
195                     relator.relate(predicate.rebind(a), p.rebind(b)).is_ok()
196                 }
197                 (
198                     ty::PredicateKind::ConstEvaluatable(a),
199                     ty::PredicateKind::ConstEvaluatable(b),
200                 ) => tcx.try_unify_abstract_consts(self_param_env.and((a, b))),
201                 (
202                     ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_a, lt_a)),
203                     ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_b, lt_b)),
204                 ) => {
205                     relator.relate(predicate.rebind(ty_a), p.rebind(ty_b)).is_ok()
206                         && relator.relate(predicate.rebind(lt_a), p.rebind(lt_b)).is_ok()
207                 }
208                 _ => predicate == p,
209             }
210         };
211
212         if !assumptions_in_impl_context.iter().copied().any(predicate_matches_closure) {
213             let item_span = tcx.def_span(self_type_did);
214             let self_descr = tcx.def_kind(self_type_did).descr(self_type_did.to_def_id());
215             let reported = struct_span_err!(
216                 tcx.sess,
217                 predicate_sp,
218                 E0367,
219                 "`Drop` impl requires `{predicate}` but the {self_descr} it is implemented for does not",
220             )
221             .span_note(item_span, "the implementor must specify the same requirement")
222             .emit();
223             result = Err(reported);
224         }
225     }
226
227     result
228 }
229
230 /// This function is not only checking that the dropck obligations are met for
231 /// the given type, but it's also currently preventing non-regular recursion in
232 /// types from causing stack overflows (dropck_no_diverge_on_nonregular_*.rs).
233 crate fn check_drop_obligations<'a, 'tcx>(
234     rcx: &mut RegionCtxt<'a, 'tcx>,
235     ty: Ty<'tcx>,
236     span: Span,
237     body_id: hir::HirId,
238 ) {
239     debug!("check_drop_obligations typ: {:?}", ty);
240
241     let cause = &ObligationCause::misc(span, body_id);
242     let infer_ok = rcx.infcx.at(cause, rcx.fcx.param_env).dropck_outlives(ty);
243     debug!("dropck_outlives = {:#?}", infer_ok);
244     rcx.fcx.register_infer_ok_obligations(infer_ok);
245 }
246
247 // This is an implementation of the TypeRelation trait with the
248 // aim of simply comparing for equality (without side-effects).
249 // It is not intended to be used anywhere else other than here.
250 crate struct SimpleEqRelation<'tcx> {
251     tcx: TyCtxt<'tcx>,
252     param_env: ty::ParamEnv<'tcx>,
253 }
254
255 impl<'tcx> SimpleEqRelation<'tcx> {
256     fn new(tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> SimpleEqRelation<'tcx> {
257         SimpleEqRelation { tcx, param_env }
258     }
259 }
260
261 impl<'tcx> TypeRelation<'tcx> for SimpleEqRelation<'tcx> {
262     fn tcx(&self) -> TyCtxt<'tcx> {
263         self.tcx
264     }
265
266     fn param_env(&self) -> ty::ParamEnv<'tcx> {
267         self.param_env
268     }
269
270     fn tag(&self) -> &'static str {
271         "dropck::SimpleEqRelation"
272     }
273
274     fn a_is_expected(&self) -> bool {
275         true
276     }
277
278     fn relate_with_variance<T: Relate<'tcx>>(
279         &mut self,
280         _: ty::Variance,
281         _info: ty::VarianceDiagInfo<'tcx>,
282         a: T,
283         b: T,
284     ) -> RelateResult<'tcx, T> {
285         // Here we ignore variance because we require drop impl's types
286         // to be *exactly* the same as to the ones in the struct definition.
287         self.relate(a, b)
288     }
289
290     fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
291         debug!("SimpleEqRelation::tys(a={:?}, b={:?})", a, b);
292         ty::relate::super_relate_tys(self, a, b)
293     }
294
295     fn regions(
296         &mut self,
297         a: ty::Region<'tcx>,
298         b: ty::Region<'tcx>,
299     ) -> RelateResult<'tcx, ty::Region<'tcx>> {
300         debug!("SimpleEqRelation::regions(a={:?}, b={:?})", a, b);
301
302         // We can just equate the regions because LBRs have been
303         // already anonymized.
304         if a == b {
305             Ok(a)
306         } else {
307             // I'm not sure is this `TypeError` is the right one, but
308             // it should not matter as it won't be checked (the dropck
309             // will emit its own, more informative and higher-level errors
310             // in case anything goes wrong).
311             Err(TypeError::RegionsPlaceholderMismatch)
312         }
313     }
314
315     fn consts(
316         &mut self,
317         a: ty::Const<'tcx>,
318         b: ty::Const<'tcx>,
319     ) -> RelateResult<'tcx, ty::Const<'tcx>> {
320         debug!("SimpleEqRelation::consts(a={:?}, b={:?})", a, b);
321         ty::relate::super_relate_consts(self, a, b)
322     }
323
324     fn binders<T>(
325         &mut self,
326         a: ty::Binder<'tcx, T>,
327         b: ty::Binder<'tcx, T>,
328     ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
329     where
330         T: Relate<'tcx>,
331     {
332         debug!("SimpleEqRelation::binders({:?}: {:?}", a, b);
333
334         // Anonymizing the LBRs is necessary to solve (Issue #59497).
335         // After we do so, it should be totally fine to skip the binders.
336         let anon_a = self.tcx.anonymize_late_bound_regions(a);
337         let anon_b = self.tcx.anonymize_late_bound_regions(b);
338         self.relate(anon_a.skip_binder(), anon_b.skip_binder())?;
339
340         Ok(a)
341     }
342 }