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