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