]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/dropck.rs
Various minor/cosmetic improvements to code
[rust.git] / src / librustc_typeck / check / dropck.rs
1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use check::regionck::RegionCtxt;
12
13 use hir::def_id::DefId;
14 use rustc::infer::outlives::env::OutlivesEnvironment;
15 use rustc::infer::{self, InferOk, SuppressRegionErrors};
16 use rustc::middle::region;
17 use rustc::traits::{ObligationCause, TraitEngine, TraitEngineExt};
18 use rustc::ty::subst::{Subst, Substs, UnpackedKind};
19 use rustc::ty::{self, Ty, TyCtxt};
20 use util::common::ErrorReported;
21
22 use syntax::ast;
23 use syntax_pos::Span;
24
25 /// check_drop_impl confirms that the Drop implementation identified by
26 /// `drop_impl_did` is not any more specialized than the type it is
27 /// attached to (Issue #8142).
28 ///
29 /// This means:
30 ///
31 /// 1. The self type must be nominal (this is already checked during
32 ///    coherence),
33 ///
34 /// 2. The generic region/type parameters of the impl's self-type must
35 ///    all be parameters of the Drop impl itself (i.e., no
36 ///    specialization like `impl Drop for Foo<i32>`), and,
37 ///
38 /// 3. Any bounds on the generic parameters must be reflected in the
39 ///    struct/enum definition for the nominal type itself (i.e.
40 ///    cannot do `struct S<T>; impl<T:Clone> Drop for S<T> { ... }`).
41 ///
42 pub fn check_drop_impl<'a, 'tcx>(
43     tcx: TyCtxt<'a, 'tcx, 'tcx>,
44     drop_impl_did: DefId,
45 ) -> Result<(), ErrorReported> {
46     let dtor_self_type = tcx.type_of(drop_impl_did);
47     let dtor_predicates = tcx.predicates_of(drop_impl_did);
48     match dtor_self_type.sty {
49         ty::Adt(adt_def, self_to_impl_substs) => {
50             ensure_drop_params_and_item_params_correspond(
51                 tcx,
52                 drop_impl_did,
53                 dtor_self_type,
54                 adt_def.did,
55             )?;
56
57             ensure_drop_predicates_are_implied_by_item_defn(
58                 tcx,
59                 drop_impl_did,
60                 &dtor_predicates,
61                 adt_def.did,
62                 self_to_impl_substs,
63             )
64         }
65         _ => {
66             // Destructors only work on nominal types.  This was
67             // already checked by coherence, but compilation may
68             // not have been terminated.
69             let span = tcx.def_span(drop_impl_did);
70             tcx.sess.delay_span_bug(span,
71                 &format!("should have been rejected by coherence check: {}", dtor_self_type));
72             Err(ErrorReported)
73         }
74     }
75 }
76
77 fn ensure_drop_params_and_item_params_correspond<'a, 'tcx>(
78     tcx: TyCtxt<'a, 'tcx, 'tcx>,
79     drop_impl_did: DefId,
80     drop_impl_ty: Ty<'tcx>,
81     self_type_did: DefId,
82 ) -> Result<(), ErrorReported> {
83     let drop_impl_node_id = tcx.hir().as_local_node_id(drop_impl_did).unwrap();
84
85     // check that the impl type can be made to match the trait type.
86
87     tcx.infer_ctxt().enter(|ref infcx| {
88         let impl_param_env = tcx.param_env(self_type_did);
89         let tcx = infcx.tcx;
90         let mut fulfillment_cx = TraitEngine::new(tcx);
91
92         let named_type = tcx.type_of(self_type_did);
93
94         let drop_impl_span = tcx.def_span(drop_impl_did);
95         let fresh_impl_substs = infcx.fresh_substs_for_item(drop_impl_span, drop_impl_did);
96         let fresh_impl_self_ty = drop_impl_ty.subst(tcx, fresh_impl_substs);
97
98         let cause = &ObligationCause::misc(drop_impl_span, drop_impl_node_id);
99         match infcx
100             .at(cause, impl_param_env)
101             .eq(named_type, fresh_impl_self_ty)
102         {
103             Ok(InferOk { obligations, .. }) => {
104                 fulfillment_cx.register_predicate_obligations(infcx, obligations);
105             }
106             Err(_) => {
107                 let item_span = tcx.def_span(self_type_did);
108                 struct_span_err!(
109                     tcx.sess,
110                     drop_impl_span,
111                     E0366,
112                     "Implementations of Drop cannot be specialized"
113                 ).span_note(
114                     item_span,
115                     "Use same sequence of generic type and region \
116                      parameters that is on the struct/enum definition",
117                 )
118                     .emit();
119                 return Err(ErrorReported);
120             }
121         }
122
123         if let Err(ref errors) = fulfillment_cx.select_all_or_error(&infcx) {
124             // this could be reached when we get lazy normalization
125             infcx.report_fulfillment_errors(errors, None, false);
126             return Err(ErrorReported);
127         }
128
129         let region_scope_tree = region::ScopeTree::default();
130
131         // NB. It seems a bit... suspicious to use an empty param-env
132         // here. The correct thing, I imagine, would be
133         // `OutlivesEnvironment::new(impl_param_env)`, which would
134         // allow region solving to take any `a: 'b` relations on the
135         // impl into account. But I could not create a test case where
136         // it did the wrong thing, so I chose to preserve existing
137         // behavior, since it ought to be simply more
138         // conservative. -nmatsakis
139         let outlives_env = OutlivesEnvironment::new(ty::ParamEnv::empty());
140
141         infcx.resolve_regions_and_report_errors(
142             drop_impl_did,
143             &region_scope_tree,
144             &outlives_env,
145             SuppressRegionErrors::default(),
146         );
147         Ok(())
148     })
149 }
150
151 /// Confirms that every predicate imposed by dtor_predicates is
152 /// implied by assuming the predicates attached to self_type_did.
153 fn ensure_drop_predicates_are_implied_by_item_defn<'a, 'tcx>(
154     tcx: TyCtxt<'a, 'tcx, 'tcx>,
155     drop_impl_did: DefId,
156     dtor_predicates: &ty::GenericPredicates<'tcx>,
157     self_type_did: DefId,
158     self_to_impl_substs: &Substs<'tcx>,
159 ) -> Result<(), ErrorReported> {
160     let mut result = Ok(());
161
162     // Here is an example, analogous to that from
163     // `compare_impl_method`.
164     //
165     // Consider a struct type:
166     //
167     //     struct Type<'c, 'b:'c, 'a> {
168     //         x: &'a Contents            // (contents are irrelevant;
169     //         y: &'c Cell<&'b Contents>, //  only the bounds matter for our purposes.)
170     //     }
171     //
172     // and a Drop impl:
173     //
174     //     impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
175     //         fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
176     //     }
177     //
178     // We start out with self_to_impl_substs, that maps the generic
179     // parameters of Type to that of the Drop impl.
180     //
181     //     self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
182     //
183     // Applying this to the predicates (i.e., assumptions) provided by the item
184     // definition yields the instantiated assumptions:
185     //
186     //     ['y : 'z]
187     //
188     // We then check all of the predicates of the Drop impl:
189     //
190     //     ['y:'z, 'x:'y]
191     //
192     // and ensure each is in the list of instantiated
193     // assumptions. Here, `'y:'z` is present, but `'x:'y` is
194     // absent. So we report an error that the Drop impl injected a
195     // predicate that is not present on the struct definition.
196
197     let self_type_node_id = tcx.hir().as_local_node_id(self_type_did).unwrap();
198
199     let drop_impl_span = tcx.def_span(drop_impl_did);
200
201     // We can assume the predicates attached to struct/enum definition
202     // hold.
203     let generic_assumptions = tcx.predicates_of(self_type_did);
204
205     let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
206     let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
207
208     // An earlier version of this code attempted to do this checking
209     // via the traits::fulfill machinery. However, it ran into trouble
210     // since the fulfill machinery merely turns outlives-predicates
211     // 'a:'b and T:'b into region inference constraints. It is simpler
212     // just to look for all the predicates directly.
213
214     assert_eq!(dtor_predicates.parent, None);
215     for (predicate, _) in &dtor_predicates.predicates {
216         // (We do not need to worry about deep analysis of type
217         // expressions etc because the Drop impls are already forced
218         // to take on a structure that is roughly an alpha-renaming of
219         // the generic parameters of the item definition.)
220
221         // This path now just checks *all* predicates via the direct
222         // lookup, rather than using fulfill machinery.
223         //
224         // However, it may be more efficient in the future to batch
225         // the analysis together via the fulfill , rather than the
226         // repeated `contains` calls.
227
228         if !assumptions_in_impl_context.contains(&predicate) {
229             let item_span = tcx.hir().span(self_type_node_id);
230             struct_span_err!(
231                 tcx.sess,
232                 drop_impl_span,
233                 E0367,
234                 "The requirement `{}` is added only by the Drop impl.",
235                 predicate
236             ).span_note(
237                 item_span,
238                 "The same requirement must be part of \
239                  the struct/enum definition",
240             )
241                 .emit();
242             result = Err(ErrorReported);
243         }
244     }
245
246     result
247 }
248
249 /// check_safety_of_destructor_if_necessary confirms that the type
250 /// expression `typ` conforms to the "Drop Check Rule" from the Sound
251 /// Generic Drop (RFC 769).
252 ///
253 /// ----
254 ///
255 /// The simplified (*) Drop Check Rule is the following:
256 ///
257 /// Let `v` be some value (either temporary or named) and 'a be some
258 /// lifetime (scope). If the type of `v` owns data of type `D`, where
259 ///
260 /// * (1.) `D` has a lifetime- or type-parametric Drop implementation,
261 ///        (where that `Drop` implementation does not opt-out of
262 ///         this check via the `unsafe_destructor_blind_to_params`
263 ///         attribute), and
264 /// * (2.) the structure of `D` can reach a reference of type `&'a _`,
265 ///
266 /// then 'a must strictly outlive the scope of v.
267 ///
268 /// ----
269 ///
270 /// This function is meant to by applied to the type for every
271 /// expression in the program.
272 ///
273 /// ----
274 ///
275 /// (*) The qualifier "simplified" is attached to the above
276 /// definition of the Drop Check Rule, because it is a simplification
277 /// of the original Drop Check rule, which attempted to prove that
278 /// some `Drop` implementations could not possibly access data even if
279 /// it was technically reachable, due to parametricity.
280 ///
281 /// However, (1.) parametricity on its own turned out to be a
282 /// necessary but insufficient condition, and (2.)  future changes to
283 /// the language are expected to make it impossible to ensure that a
284 /// `Drop` implementation is actually parametric with respect to any
285 /// particular type parameter. (In particular, impl specialization is
286 /// expected to break the needed parametricity property beyond
287 /// repair.)
288 ///
289 /// Therefore we have scaled back Drop-Check to a more conservative
290 /// rule that does not attempt to deduce whether a `Drop`
291 /// implementation could not possible access data of a given lifetime;
292 /// instead Drop-Check now simply assumes that if a destructor has
293 /// access (direct or indirect) to a lifetime parameter, then that
294 /// lifetime must be forced to outlive that destructor's dynamic
295 /// extent. We then provide the `unsafe_destructor_blind_to_params`
296 /// attribute as a way for destructor implementations to opt-out of
297 /// this conservative assumption (and thus assume the obligation of
298 /// ensuring that they do not access data nor invoke methods of
299 /// values that have been previously dropped).
300 ///
301 pub fn check_safety_of_destructor_if_necessary<'a, 'gcx, 'tcx>(
302     rcx: &mut RegionCtxt<'a, 'gcx, 'tcx>,
303     ty: Ty<'tcx>,
304     span: Span,
305     body_id: ast::NodeId,
306     scope: region::Scope,
307 ) -> Result<(), ErrorReported> {
308     debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
309            ty, scope);
310
311     let parent_scope = match rcx.region_scope_tree.opt_encl_scope(scope) {
312         Some(parent_scope) => parent_scope,
313         // If no enclosing scope, then it must be the root scope
314         // which cannot be outlived.
315         None => return Ok(()),
316     };
317     let parent_scope = rcx.tcx.mk_region(ty::ReScope(parent_scope));
318     let origin = || infer::SubregionOrigin::SafeDestructor(span);
319     let cause = &ObligationCause::misc(span, body_id);
320     let infer_ok = rcx.infcx.at(cause, rcx.fcx.param_env).dropck_outlives(ty);
321     debug!("dropck_outlives = {:#?}", infer_ok);
322     let kinds = rcx.fcx.register_infer_ok_obligations(infer_ok);
323     for kind in kinds {
324         match kind.unpack() {
325             UnpackedKind::Lifetime(r) => rcx.sub_regions(origin(), parent_scope, r),
326             UnpackedKind::Type(ty) => rcx.type_must_outlive(origin(), ty, parent_scope),
327         }
328     }
329     Ok(())
330 }