]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/dropck.rs
Auto merge of #41676 - sirideain:expand-macro-recursion-limit, r=jseyfried
[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 middle::free_region::FreeRegionMap;
15 use rustc::infer::{self, InferOk};
16 use rustc::middle::region::{self, RegionMaps};
17 use rustc::ty::subst::{Subst, Substs};
18 use rustc::ty::{self, Ty, TyCtxt};
19 use rustc::traits::{self, ObligationCause, Reveal};
20 use util::common::ErrorReported;
21 use util::nodemap::FxHashSet;
22
23 use syntax_pos::Span;
24
25 /// check_drop_impl confirms that the Drop implementation identfied 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>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
43                                  drop_impl_did: DefId)
44                                  -> Result<(), ErrorReported> {
45     let dtor_self_type = tcx.type_of(drop_impl_did);
46     let dtor_predicates = tcx.predicates_of(drop_impl_did);
47     match dtor_self_type.sty {
48         ty::TyAdt(adt_def, self_to_impl_substs) => {
49             ensure_drop_params_and_item_params_correspond(tcx,
50                                                           drop_impl_did,
51                                                           dtor_self_type,
52                                                           adt_def.did)?;
53
54             ensure_drop_predicates_are_implied_by_item_defn(tcx,
55                                                             drop_impl_did,
56                                                             &dtor_predicates,
57                                                             adt_def.did,
58                                                             self_to_impl_substs)
59         }
60         _ => {
61             // Destructors only work on nominal types.  This was
62             // already checked by coherence, so we can panic here.
63             let span = tcx.def_span(drop_impl_did);
64             span_bug!(span,
65                       "should have been rejected by coherence check: {}",
66                       dtor_self_type);
67         }
68     }
69 }
70
71 fn ensure_drop_params_and_item_params_correspond<'a, 'tcx>(
72     tcx: TyCtxt<'a, 'tcx, 'tcx>,
73     drop_impl_did: DefId,
74     drop_impl_ty: Ty<'tcx>,
75     self_type_did: DefId)
76     -> Result<(), ErrorReported>
77 {
78     let drop_impl_node_id = tcx.hir.as_local_node_id(drop_impl_did).unwrap();
79     let self_type_node_id = tcx.hir.as_local_node_id(self_type_did).unwrap();
80
81     // check that the impl type can be made to match the trait type.
82
83     let impl_param_env = ty::ParameterEnvironment::for_item(tcx, self_type_node_id);
84     tcx.infer_ctxt(impl_param_env, Reveal::UserFacing).enter(|ref infcx| {
85         let tcx = infcx.tcx;
86         let mut fulfillment_cx = traits::FulfillmentContext::new();
87
88         let named_type = tcx.type_of(self_type_did);
89         let named_type = named_type.subst(tcx, &infcx.parameter_environment.free_substs);
90
91         let drop_impl_span = tcx.def_span(drop_impl_did);
92         let fresh_impl_substs =
93             infcx.fresh_substs_for_item(drop_impl_span, drop_impl_did);
94         let fresh_impl_self_ty = drop_impl_ty.subst(tcx, fresh_impl_substs);
95
96         let cause = &ObligationCause::misc(drop_impl_span, drop_impl_node_id);
97         match infcx.eq_types(true, cause, named_type, fresh_impl_self_ty) {
98             Ok(InferOk { obligations, .. }) => {
99                 fulfillment_cx.register_predicate_obligations(infcx, obligations);
100             }
101             Err(_) => {
102                 let item_span = tcx.hir.span(self_type_node_id);
103                 struct_span_err!(tcx.sess, drop_impl_span, E0366,
104                                  "Implementations of Drop cannot be specialized")
105                     .span_note(item_span,
106                                "Use same sequence of generic type and region \
107                                 parameters that is on the struct/enum definition")
108                     .emit();
109                 return Err(ErrorReported);
110             }
111         }
112
113         if let Err(ref errors) = fulfillment_cx.select_all_or_error(&infcx) {
114             // this could be reached when we get lazy normalization
115             infcx.report_fulfillment_errors(errors);
116             return Err(ErrorReported);
117         }
118
119         let region_maps = RegionMaps::new();
120         let free_regions = FreeRegionMap::new();
121         infcx.resolve_regions_and_report_errors(drop_impl_did, &region_maps, &free_regions);
122         Ok(())
123     })
124 }
125
126 /// Confirms that every predicate imposed by dtor_predicates is
127 /// implied by assuming the predicates attached to self_type_did.
128 fn ensure_drop_predicates_are_implied_by_item_defn<'a, 'tcx>(
129     tcx: TyCtxt<'a, 'tcx, 'tcx>,
130     drop_impl_did: DefId,
131     dtor_predicates: &ty::GenericPredicates<'tcx>,
132     self_type_did: DefId,
133     self_to_impl_substs: &Substs<'tcx>)
134     -> Result<(), ErrorReported>
135 {
136     let mut result = Ok(());
137
138     // Here is an example, analogous to that from
139     // `compare_impl_method`.
140     //
141     // Consider a struct type:
142     //
143     //     struct Type<'c, 'b:'c, 'a> {
144     //         x: &'a Contents            // (contents are irrelevant;
145     //         y: &'c Cell<&'b Contents>, //  only the bounds matter for our purposes.)
146     //     }
147     //
148     // and a Drop impl:
149     //
150     //     impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
151     //         fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
152     //     }
153     //
154     // We start out with self_to_impl_substs, that maps the generic
155     // parameters of Type to that of the Drop impl.
156     //
157     //     self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
158     //
159     // Applying this to the predicates (i.e. assumptions) provided by the item
160     // definition yields the instantiated assumptions:
161     //
162     //     ['y : 'z]
163     //
164     // We then check all of the predicates of the Drop impl:
165     //
166     //     ['y:'z, 'x:'y]
167     //
168     // and ensure each is in the list of instantiated
169     // assumptions. Here, `'y:'z` is present, but `'x:'y` is
170     // absent. So we report an error that the Drop impl injected a
171     // predicate that is not present on the struct definition.
172
173     let self_type_node_id = tcx.hir.as_local_node_id(self_type_did).unwrap();
174
175     let drop_impl_span = tcx.def_span(drop_impl_did);
176
177     // We can assume the predicates attached to struct/enum definition
178     // hold.
179     let generic_assumptions = tcx.predicates_of(self_type_did);
180
181     let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
182     let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
183
184     // An earlier version of this code attempted to do this checking
185     // via the traits::fulfill machinery. However, it ran into trouble
186     // since the fulfill machinery merely turns outlives-predicates
187     // 'a:'b and T:'b into region inference constraints. It is simpler
188     // just to look for all the predicates directly.
189
190     assert_eq!(dtor_predicates.parent, None);
191     for predicate in &dtor_predicates.predicates {
192         // (We do not need to worry about deep analysis of type
193         // expressions etc because the Drop impls are already forced
194         // to take on a structure that is roughly an alpha-renaming of
195         // the generic parameters of the item definition.)
196
197         // This path now just checks *all* predicates via the direct
198         // lookup, rather than using fulfill machinery.
199         //
200         // However, it may be more efficient in the future to batch
201         // the analysis together via the fulfill , rather than the
202         // repeated `contains` calls.
203
204         if !assumptions_in_impl_context.contains(&predicate) {
205             let item_span = tcx.hir.span(self_type_node_id);
206             struct_span_err!(tcx.sess, drop_impl_span, E0367,
207                              "The requirement `{}` is added only by the Drop impl.", predicate)
208                 .span_note(item_span,
209                            "The same requirement must be part of \
210                             the struct/enum definition")
211                 .emit();
212             result = Err(ErrorReported);
213         }
214     }
215
216     result
217 }
218
219 /// check_safety_of_destructor_if_necessary confirms that the type
220 /// expression `typ` conforms to the "Drop Check Rule" from the Sound
221 /// Generic Drop (RFC 769).
222 ///
223 /// ----
224 ///
225 /// The simplified (*) Drop Check Rule is the following:
226 ///
227 /// Let `v` be some value (either temporary or named) and 'a be some
228 /// lifetime (scope). If the type of `v` owns data of type `D`, where
229 ///
230 /// * (1.) `D` has a lifetime- or type-parametric Drop implementation,
231 ///        (where that `Drop` implementation does not opt-out of
232 ///         this check via the `unsafe_destructor_blind_to_params`
233 ///         attribute), and
234 /// * (2.) the structure of `D` can reach a reference of type `&'a _`,
235 ///
236 /// then 'a must strictly outlive the scope of v.
237 ///
238 /// ----
239 ///
240 /// This function is meant to by applied to the type for every
241 /// expression in the program.
242 ///
243 /// ----
244 ///
245 /// (*) The qualifier "simplified" is attached to the above
246 /// definition of the Drop Check Rule, because it is a simplification
247 /// of the original Drop Check rule, which attempted to prove that
248 /// some `Drop` implementations could not possibly access data even if
249 /// it was technically reachable, due to parametricity.
250 ///
251 /// However, (1.) parametricity on its own turned out to be a
252 /// necessary but insufficient condition, and (2.)  future changes to
253 /// the language are expected to make it impossible to ensure that a
254 /// `Drop` implementation is actually parametric with respect to any
255 /// particular type parameter. (In particular, impl specialization is
256 /// expected to break the needed parametricity property beyond
257 /// repair.)
258 ///
259 /// Therefore we have scaled back Drop-Check to a more conservative
260 /// rule that does not attempt to deduce whether a `Drop`
261 /// implementation could not possible access data of a given lifetime;
262 /// instead Drop-Check now simply assumes that if a destructor has
263 /// access (direct or indirect) to a lifetime parameter, then that
264 /// lifetime must be forced to outlive that destructor's dynamic
265 /// extent. We then provide the `unsafe_destructor_blind_to_params`
266 /// attribute as a way for destructor implementations to opt-out of
267 /// this conservative assumption (and thus assume the obligation of
268 /// ensuring that they do not access data nor invoke methods of
269 /// values that have been previously dropped).
270 ///
271 pub fn check_safety_of_destructor_if_necessary<'a, 'gcx, 'tcx>(
272     rcx: &mut RegionCtxt<'a, 'gcx, 'tcx>,
273     ty: ty::Ty<'tcx>,
274     span: Span,
275     scope: region::CodeExtent<'tcx>)
276     -> Result<(), ErrorReported>
277 {
278     debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
279            ty, scope);
280
281
282     let parent_scope = match rcx.region_maps.opt_encl_scope(scope) {
283         Some(parent_scope) => parent_scope,
284         // If no enclosing scope, then it must be the root scope
285         // which cannot be outlived.
286         None => return Ok(())
287     };
288     let parent_scope = rcx.tcx.mk_region(ty::ReScope(parent_scope));
289     let origin = || infer::SubregionOrigin::SafeDestructor(span);
290
291     let ty = rcx.fcx.resolve_type_vars_if_possible(&ty);
292     let for_ty = ty;
293     let mut types = vec![(ty, 0)];
294     let mut known = FxHashSet();
295     while let Some((ty, depth)) = types.pop() {
296         let ty::DtorckConstraint {
297             dtorck_types, outlives
298         } = rcx.tcx.dtorck_constraint_for_ty(span, for_ty, depth, ty)?;
299
300         for ty in dtorck_types {
301             let ty = rcx.fcx.normalize_associated_types_in(span, &ty);
302             let ty = rcx.fcx.resolve_type_vars_with_obligations(ty);
303             let ty = rcx.fcx.resolve_type_and_region_vars_if_possible(&ty);
304             match ty.sty {
305                 // All parameters live for the duration of the
306                 // function.
307                 ty::TyParam(..) => {}
308
309                 // A projection that we couldn't resolve - it
310                 // might have a destructor.
311                 ty::TyProjection(..) | ty::TyAnon(..) => {
312                     rcx.type_must_outlive(origin(), ty, parent_scope);
313                 }
314
315                 _ => {
316                     if let None = known.replace(ty) {
317                         types.push((ty, depth+1));
318                     }
319                 }
320             }
321         }
322
323         for outlive in outlives {
324             if let Some(r) = outlive.as_region() {
325                 rcx.sub_regions(origin(), parent_scope, r);
326             } else if let Some(ty) = outlive.as_type() {
327                 rcx.type_must_outlive(origin(), ty, parent_scope);
328             }
329         }
330     }
331
332     Ok(())
333 }