]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/dropck.rs
compiletest: Do not run debuginfo tests with gdb on msvc targets
[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 /// 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 ///
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,
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,
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
67 fn ensure_drop_params_and_item_params_correspond<'tcx>(
68     tcx: TyCtxt<'tcx>,
69     drop_impl_did: DefId,
70     drop_impl_ty: Ty<'tcx>,
71     self_type_did: DefId,
72 ) -> Result<(), ErrorReported> {
73     let drop_impl_hir_id = tcx.hir().as_local_hir_id(drop_impl_did).unwrap();
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 = 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 = infcx.fresh_substs_for_item(drop_impl_span, drop_impl_did);
86         let fresh_impl_self_ty = drop_impl_ty.subst(tcx, fresh_impl_substs);
87
88         let cause = &ObligationCause::misc(drop_impl_span, drop_impl_hir_id);
89         match infcx.at(cause, impl_param_env).eq(named_type, fresh_impl_self_ty) {
90             Ok(InferOk { obligations, .. }) => {
91                 fulfillment_cx.register_predicate_obligations(infcx, obligations);
92             }
93             Err(_) => {
94                 let item_span = tcx.def_span(self_type_did);
95                 let self_descr = tcx
96                     .def_kind(self_type_did)
97                     .map(|kind| kind.descr(self_type_did))
98                     .unwrap_or("type");
99                 struct_span_err!(
100                     tcx.sess,
101                     drop_impl_span,
102                     E0366,
103                     "`Drop` impls cannot be specialized"
104                 )
105                 .span_note(
106                     item_span,
107                     &format!(
108                         "use the same sequence of generic type, lifetime and const parameters \
109                         as the {} definition",
110                         self_descr,
111                     ),
112                 )
113                 .emit();
114                 return Err(ErrorReported);
115             }
116         }
117
118         if let Err(ref errors) = fulfillment_cx.select_all_or_error(&infcx) {
119             // this could be reached when we get lazy normalization
120             infcx.report_fulfillment_errors(errors, None, false);
121             return Err(ErrorReported);
122         }
123
124         let region_scope_tree = region::ScopeTree::default();
125
126         // NB. It seems a bit... suspicious to use an empty param-env
127         // here. The correct thing, I imagine, would be
128         // `OutlivesEnvironment::new(impl_param_env)`, which would
129         // allow region solving to take any `a: 'b` relations on the
130         // impl into account. But I could not create a test case where
131         // it did the wrong thing, so I chose to preserve existing
132         // behavior, since it ought to be simply more
133         // conservative. -nmatsakis
134         let outlives_env = OutlivesEnvironment::new(ty::ParamEnv::empty());
135
136         infcx.resolve_regions_and_report_errors(
137             drop_impl_did,
138             &region_scope_tree,
139             &outlives_env,
140             SuppressRegionErrors::default(),
141         );
142         Ok(())
143     })
144 }
145
146 /// Confirms that every predicate imposed by dtor_predicates is
147 /// implied by assuming the predicates attached to self_type_did.
148 fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>(
149     tcx: TyCtxt<'tcx>,
150     dtor_predicates: ty::GenericPredicates<'tcx>,
151     self_type_did: DefId,
152     self_to_impl_substs: SubstsRef<'tcx>,
153 ) -> Result<(), ErrorReported> {
154     let mut result = Ok(());
155
156     // Here is an example, analogous to that from
157     // `compare_impl_method`.
158     //
159     // Consider a struct type:
160     //
161     //     struct Type<'c, 'b:'c, 'a> {
162     //         x: &'a Contents            // (contents are irrelevant;
163     //         y: &'c Cell<&'b Contents>, //  only the bounds matter for our purposes.)
164     //     }
165     //
166     // and a Drop impl:
167     //
168     //     impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
169     //         fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
170     //     }
171     //
172     // We start out with self_to_impl_substs, that maps the generic
173     // parameters of Type to that of the Drop impl.
174     //
175     //     self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
176     //
177     // Applying this to the predicates (i.e., assumptions) provided by the item
178     // definition yields the instantiated assumptions:
179     //
180     //     ['y : 'z]
181     //
182     // We then check all of the predicates of the Drop impl:
183     //
184     //     ['y:'z, 'x:'y]
185     //
186     // and ensure each is in the list of instantiated
187     // assumptions. Here, `'y:'z` is present, but `'x:'y` is
188     // absent. So we report an error that the Drop impl injected a
189     // predicate that is not present on the struct definition.
190
191     let self_type_hir_id = tcx.hir().as_local_hir_id(self_type_did).unwrap();
192
193     // We can assume the predicates attached to struct/enum definition
194     // hold.
195     let generic_assumptions = tcx.predicates_of(self_type_did);
196
197     let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
198     let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
199
200     let self_param_env = tcx.param_env(self_type_did);
201
202     // An earlier version of this code attempted to do this checking
203     // via the traits::fulfill machinery. However, it ran into trouble
204     // since the fulfill machinery merely turns outlives-predicates
205     // 'a:'b and T:'b into region inference constraints. It is simpler
206     // just to look for all the predicates directly.
207
208     assert_eq!(dtor_predicates.parent, None);
209     for (predicate, predicate_sp) in dtor_predicates.predicates {
210         // (We do not need to worry about deep analysis of type
211         // expressions etc because the Drop impls are already forced
212         // to take on a structure that is roughly an alpha-renaming of
213         // the generic parameters of the item definition.)
214
215         // This path now just checks *all* predicates via an instantiation of
216         // the `SimpleEqRelation`, which simply forwards to the `relate` machinery
217         // after taking care of anonymizing late bound regions.
218         //
219         // However, it may be more efficient in the future to batch
220         // the analysis together via the fulfill (see comment above regarding
221         // the usage of the fulfill machinery), rather than the
222         // repeated `.iter().any(..)` calls.
223
224         // This closure is a more robust way to check `Predicate` equality
225         // than simple `==` checks (which were the previous implementation).
226         // It relies on `ty::relate` for `TraitPredicate` and `ProjectionPredicate`
227         // (which implement the Relate trait), while delegating on simple equality
228         // for the other `Predicate`.
229         // This implementation solves (Issue #59497) and (Issue #58311).
230         // It is unclear to me at the moment whether the approach based on `relate`
231         // could be extended easily also to the other `Predicate`.
232         let predicate_matches_closure = |p: &'_ Predicate<'tcx>| {
233             let mut relator: SimpleEqRelation<'tcx> = SimpleEqRelation::new(tcx, self_param_env);
234             match (predicate, p) {
235                 (Predicate::Trait(a), Predicate::Trait(b)) => relator.relate(a, b).is_ok(),
236                 (Predicate::Projection(a), Predicate::Projection(b)) => {
237                     relator.relate(a, b).is_ok()
238                 }
239                 _ => predicate == p,
240             }
241         };
242
243         if !assumptions_in_impl_context.iter().any(predicate_matches_closure) {
244             let item_span = tcx.hir().span(self_type_hir_id);
245             let self_descr =
246                 tcx.def_kind(self_type_did).map(|kind| kind.descr(self_type_did)).unwrap_or("type");
247             struct_span_err!(
248                 tcx.sess,
249                 *predicate_sp,
250                 E0367,
251                 "`Drop` impl requires `{}` but the {} it is implemented for does not",
252                 predicate,
253                 self_descr,
254             )
255             .span_note(item_span, "the implementor must specify the same requirement")
256             .emit();
257             result = Err(ErrorReported);
258         }
259     }
260
261     result
262 }
263
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>,
269     ty: Ty<'tcx>,
270     span: Span,
271     body_id: hir::HirId,
272 ) -> Result<(), ErrorReported> {
273     debug!("check_drop_obligations typ: {:?}", ty);
274
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);
279
280     Ok(())
281 }
282
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> {
287     tcx: TyCtxt<'tcx>,
288     param_env: ty::ParamEnv<'tcx>,
289 }
290
291 impl<'tcx> SimpleEqRelation<'tcx> {
292     fn new(tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> SimpleEqRelation<'tcx> {
293         SimpleEqRelation { tcx, param_env }
294     }
295 }
296
297 impl TypeRelation<'tcx> for SimpleEqRelation<'tcx> {
298     fn tcx(&self) -> TyCtxt<'tcx> {
299         self.tcx
300     }
301
302     fn param_env(&self) -> ty::ParamEnv<'tcx> {
303         self.param_env
304     }
305
306     fn tag(&self) -> &'static str {
307         "dropck::SimpleEqRelation"
308     }
309
310     fn a_is_expected(&self) -> bool {
311         true
312     }
313
314     fn relate_with_variance<T: Relate<'tcx>>(
315         &mut self,
316         _: ty::Variance,
317         a: &T,
318         b: &T,
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.
322         self.relate(a, b)
323     }
324
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)
328     }
329
330     fn regions(
331         &mut self,
332         a: ty::Region<'tcx>,
333         b: ty::Region<'tcx>,
334     ) -> RelateResult<'tcx, ty::Region<'tcx>> {
335         debug!("SimpleEqRelation::regions(a={:?}, b={:?})", a, b);
336
337         // We can just equate the regions because LBRs have been
338         // already anonymized.
339         if a == b {
340             Ok(a)
341         } else {
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)
347         }
348     }
349
350     fn consts(
351         &mut self,
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)
357     }
358
359     fn binders<T>(
360         &mut self,
361         a: &ty::Binder<T>,
362         b: &ty::Binder<T>,
363     ) -> RelateResult<'tcx, ty::Binder<T>>
364     where
365         T: Relate<'tcx>,
366     {
367         debug!("SimpleEqRelation::binders({:?}: {:?}", a, b);
368
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())?;
374
375         Ok(a.clone())
376     }
377 }