]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/dropck.rs
9d39653375739531f56660c839397f1319d83fa6
[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::{self, Rcx};
12
13 use middle::def_id::DefId;
14 use middle::free_region::FreeRegionMap;
15 use middle::infer;
16 use middle::region;
17 use middle::subst::{self, Subst};
18 use middle::traits;
19 use middle::ty::{self, Ty};
20 use util::nodemap::FnvHashSet;
21
22 use syntax::ast;
23 use syntax::codemap::{self, Span};
24 use syntax::parse::token::special_idents;
25
26 /// check_drop_impl confirms that the Drop implementation identfied by
27 /// `drop_impl_did` is not any more specialized than the type it is
28 /// attached to (Issue #8142).
29 ///
30 /// This means:
31 ///
32 /// 1. The self type must be nominal (this is already checked during
33 ///    coherence),
34 ///
35 /// 2. The generic region/type parameters of the impl's self-type must
36 ///    all be parameters of the Drop impl itself (i.e. no
37 ///    specialization like `impl Drop for Foo<i32>`), and,
38 ///
39 /// 3. Any bounds on the generic parameters must be reflected in the
40 ///    struct/enum definition for the nominal type itself (i.e.
41 ///    cannot do `struct S<T>; impl<T:Clone> Drop for S<T> { ... }`).
42 ///
43 pub fn check_drop_impl(tcx: &ty::ctxt, drop_impl_did: DefId) -> Result<(), ()> {
44     let ty::TypeScheme { generics: ref dtor_generics,
45                          ty: dtor_self_type } = tcx.lookup_item_type(drop_impl_did);
46     let dtor_predicates = tcx.lookup_predicates(drop_impl_did);
47     match dtor_self_type.sty {
48         ty::TyEnum(adt_def, self_to_impl_substs) |
49         ty::TyStruct(adt_def, self_to_impl_substs) => {
50             try!(ensure_drop_params_and_item_params_correspond(tcx,
51                                                                drop_impl_did,
52                                                                dtor_generics,
53                                                                &dtor_self_type,
54                                                                adt_def.did));
55
56             ensure_drop_predicates_are_implied_by_item_defn(tcx,
57                                                             drop_impl_did,
58                                                             &dtor_predicates,
59                                                             adt_def.did,
60                                                             self_to_impl_substs)
61         }
62         _ => {
63             // Destructors only work on nominal types.  This was
64             // already checked by coherence, so we can panic here.
65             let span = tcx.map.def_id_span(drop_impl_did, codemap::DUMMY_SP);
66             tcx.sess.span_bug(
67                 span, &format!("should have been rejected by coherence check: {}",
68                                dtor_self_type));
69         }
70     }
71 }
72
73 fn ensure_drop_params_and_item_params_correspond<'tcx>(
74     tcx: &ty::ctxt<'tcx>,
75     drop_impl_did: DefId,
76     drop_impl_generics: &ty::Generics<'tcx>,
77     drop_impl_ty: &ty::Ty<'tcx>,
78     self_type_did: DefId) -> Result<(), ()>
79 {
80     let drop_impl_node_id = tcx.map.as_local_node_id(drop_impl_did).unwrap();
81     let self_type_node_id = tcx.map.as_local_node_id(self_type_did).unwrap();
82
83     // check that the impl type can be made to match the trait type.
84
85     let impl_param_env = ty::ParameterEnvironment::for_item(tcx, self_type_node_id);
86     let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(impl_param_env));
87     let mut fulfillment_cx = traits::FulfillmentContext::new();
88
89     let named_type = tcx.lookup_item_type(self_type_did).ty;
90     let named_type = named_type.subst(tcx, &infcx.parameter_environment.free_substs);
91
92     let drop_impl_span = tcx.map.def_id_span(drop_impl_did, codemap::DUMMY_SP);
93     let fresh_impl_substs =
94         infcx.fresh_substs_for_generics(drop_impl_span, drop_impl_generics);
95     let fresh_impl_self_ty = drop_impl_ty.subst(tcx, &fresh_impl_substs);
96
97     if let Err(_) = infer::mk_eqty(&infcx, true, infer::TypeOrigin::Misc(drop_impl_span),
98                                    named_type, fresh_impl_self_ty) {
99         let item_span = tcx.map.span(self_type_node_id);
100         struct_span_err!(tcx.sess, drop_impl_span, E0366,
101                          "Implementations of Drop cannot be specialized")
102             .span_note(item_span,
103                        "Use same sequence of generic type and region \
104                         parameters that is on the struct/enum definition")
105             .emit();
106         return Err(());
107     }
108
109     if let Err(ref errors) = fulfillment_cx.select_all_or_error(&infcx) {
110         // this could be reached when we get lazy normalization
111         traits::report_fulfillment_errors(&infcx, errors);
112         return Err(());
113     }
114
115     let free_regions = FreeRegionMap::new();
116     infcx.resolve_regions_and_report_errors(&free_regions, drop_impl_node_id);
117     Ok(())
118 }
119
120 /// Confirms that every predicate imposed by dtor_predicates is
121 /// implied by assuming the predicates attached to self_type_did.
122 fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>(
123     tcx: &ty::ctxt<'tcx>,
124     drop_impl_did: DefId,
125     dtor_predicates: &ty::GenericPredicates<'tcx>,
126     self_type_did: DefId,
127     self_to_impl_substs: &subst::Substs<'tcx>) -> Result<(), ()> {
128
129     // Here is an example, analogous to that from
130     // `compare_impl_method`.
131     //
132     // Consider a struct type:
133     //
134     //     struct Type<'c, 'b:'c, 'a> {
135     //         x: &'a Contents            // (contents are irrelevant;
136     //         y: &'c Cell<&'b Contents>, //  only the bounds matter for our purposes.)
137     //     }
138     //
139     // and a Drop impl:
140     //
141     //     impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
142     //         fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
143     //     }
144     //
145     // We start out with self_to_impl_substs, that maps the generic
146     // parameters of Type to that of the Drop impl.
147     //
148     //     self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
149     //
150     // Applying this to the predicates (i.e. assumptions) provided by the item
151     // definition yields the instantiated assumptions:
152     //
153     //     ['y : 'z]
154     //
155     // We then check all of the predicates of the Drop impl:
156     //
157     //     ['y:'z, 'x:'y]
158     //
159     // and ensure each is in the list of instantiated
160     // assumptions. Here, `'y:'z` is present, but `'x:'y` is
161     // absent. So we report an error that the Drop impl injected a
162     // predicate that is not present on the struct definition.
163
164     let self_type_node_id = tcx.map.as_local_node_id(self_type_did).unwrap();
165
166     let drop_impl_span = tcx.map.def_id_span(drop_impl_did, codemap::DUMMY_SP);
167
168     // We can assume the predicates attached to struct/enum definition
169     // hold.
170     let generic_assumptions = tcx.lookup_predicates(self_type_did);
171
172     let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
173     assert!(assumptions_in_impl_context.predicates.is_empty_in(subst::SelfSpace));
174     assert!(assumptions_in_impl_context.predicates.is_empty_in(subst::FnSpace));
175     let assumptions_in_impl_context =
176         assumptions_in_impl_context.predicates.get_slice(subst::TypeSpace);
177
178     // An earlier version of this code attempted to do this checking
179     // via the traits::fulfill machinery. However, it ran into trouble
180     // since the fulfill machinery merely turns outlives-predicates
181     // 'a:'b and T:'b into region inference constraints. It is simpler
182     // just to look for all the predicates directly.
183
184     assert!(dtor_predicates.predicates.is_empty_in(subst::SelfSpace));
185     assert!(dtor_predicates.predicates.is_empty_in(subst::FnSpace));
186     let predicates = dtor_predicates.predicates.get_slice(subst::TypeSpace);
187     for predicate in predicates {
188         // (We do not need to worry about deep analysis of type
189         // expressions etc because the Drop impls are already forced
190         // to take on a structure that is roughly an alpha-renaming of
191         // the generic parameters of the item definition.)
192
193         // This path now just checks *all* predicates via the direct
194         // lookup, rather than using fulfill machinery.
195         //
196         // However, it may be more efficient in the future to batch
197         // the analysis together via the fulfill , rather than the
198         // repeated `contains` calls.
199
200         if !assumptions_in_impl_context.contains(&predicate) {
201             let item_span = tcx.map.span(self_type_node_id);
202             struct_span_err!(tcx.sess, drop_impl_span, E0367,
203                              "The requirement `{}` is added only by the Drop impl.", predicate)
204                 .span_note(item_span,
205                            "The same requirement must be part of \
206                             the struct/enum definition")
207                 .emit();
208         }
209     }
210
211     if tcx.sess.has_errors() {
212         return Err(());
213     }
214     Ok(())
215 }
216
217 /// check_safety_of_destructor_if_necessary confirms that the type
218 /// expression `typ` conforms to the "Drop Check Rule" from the Sound
219 /// Generic Drop (RFC 769).
220 ///
221 /// ----
222 ///
223 /// The simplified (*) Drop Check Rule is the following:
224 ///
225 /// Let `v` be some value (either temporary or named) and 'a be some
226 /// lifetime (scope). If the type of `v` owns data of type `D`, where
227 ///
228 /// * (1.) `D` has a lifetime- or type-parametric Drop implementation,
229 ///        (where that `Drop` implementation does not opt-out of
230 ///         this check via the `unsafe_destructor_blind_to_params`
231 ///         attribute), and
232 /// * (2.) the structure of `D` can reach a reference of type `&'a _`,
233 ///
234 /// then 'a must strictly outlive the scope of v.
235 ///
236 /// ----
237 ///
238 /// This function is meant to by applied to the type for every
239 /// expression in the program.
240 ///
241 /// ----
242 ///
243 /// (*) The qualifier "simplified" is attached to the above
244 /// definition of the Drop Check Rule, because it is a simplification
245 /// of the original Drop Check rule, which attempted to prove that
246 /// some `Drop` implementations could not possibly access data even if
247 /// it was technically reachable, due to parametricity.
248 ///
249 /// However, (1.) parametricity on its own turned out to be a
250 /// necessary but insufficient condition, and (2.)  future changes to
251 /// the language are expected to make it impossible to ensure that a
252 /// `Drop` implementation is actually parametric with respect to any
253 /// particular type parameter. (In particular, impl specialization is
254 /// expected to break the needed parametricity property beyond
255 /// repair.)
256 ///
257 /// Therefore we have scaled back Drop-Check to a more conservative
258 /// rule that does not attempt to deduce whether a `Drop`
259 /// implementation could not possible access data of a given lifetime;
260 /// instead Drop-Check now simply assumes that if a destructor has
261 /// access (direct or indirect) to a lifetime parameter, then that
262 /// lifetime must be forced to outlive that destructor's dynamic
263 /// extent. We then provide the `unsafe_destructor_blind_to_params`
264 /// attribute as a way for destructor implementations to opt-out of
265 /// this conservative assumption (and thus assume the obligation of
266 /// ensuring that they do not access data nor invoke methods of
267 /// values that have been previously dropped).
268 ///
269 pub fn check_safety_of_destructor_if_necessary<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
270                                                          typ: ty::Ty<'tcx>,
271                                                          span: Span,
272                                                          scope: region::CodeExtent) {
273     debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
274            typ, scope);
275
276     let parent_scope = rcx.tcx().region_maps.opt_encl_scope(scope).unwrap_or_else(|| {
277         rcx.tcx().sess.span_bug(
278             span, &format!("no enclosing scope found for scope: {:?}", scope))
279     });
280
281     let result = iterate_over_potentially_unsafe_regions_in_type(
282         &mut DropckContext {
283             rcx: rcx,
284             span: span,
285             parent_scope: parent_scope,
286             breadcrumbs: FnvHashSet()
287         },
288         TypeContext::Root,
289         typ,
290         0);
291     match result {
292         Ok(()) => {}
293         Err(Error::Overflow(ref ctxt, ref detected_on_typ)) => {
294             let tcx = rcx.tcx();
295             let mut err = struct_span_err!(tcx.sess, span, E0320,
296                                            "overflow while adding drop-check rules for {}", typ);
297             match *ctxt {
298                 TypeContext::Root => {
299                     // no need for an additional note if the overflow
300                     // was somehow on the root.
301                 }
302                 TypeContext::ADT { def_id, variant, field, field_index } => {
303                     let adt = tcx.lookup_adt_def(def_id);
304                     let variant_name = match adt.adt_kind() {
305                         ty::AdtKind::Enum => format!("enum {} variant {}",
306                                                      tcx.item_path_str(def_id),
307                                                      variant),
308                         ty::AdtKind::Struct => format!("struct {}",
309                                                        tcx.item_path_str(def_id))
310                     };
311                     let field_name = if field == special_idents::unnamed_field.name {
312                         format!("#{}", field_index)
313                     } else {
314                         format!("`{}`", field)
315                     };
316                     span_note!(
317                         &mut err,
318                         span,
319                         "overflowed on {} field {} type: {}",
320                         variant_name,
321                         field_name,
322                         detected_on_typ);
323                 }
324             }
325             err.emit();
326         }
327     }
328 }
329
330 enum Error<'tcx> {
331     Overflow(TypeContext, ty::Ty<'tcx>),
332 }
333
334 #[derive(Copy, Clone)]
335 enum TypeContext {
336     Root,
337     ADT {
338         def_id: DefId,
339         variant: ast::Name,
340         field: ast::Name,
341         field_index: usize
342     }
343 }
344
345 struct DropckContext<'a, 'b: 'a, 'tcx: 'b> {
346     rcx: &'a mut Rcx<'b, 'tcx>,
347     /// types that have already been traversed
348     breadcrumbs: FnvHashSet<Ty<'tcx>>,
349     /// span for error reporting
350     span: Span,
351     /// the scope reachable dtorck types must outlive
352     parent_scope: region::CodeExtent
353 }
354
355 // `context` is used for reporting overflow errors
356 fn iterate_over_potentially_unsafe_regions_in_type<'a, 'b, 'tcx>(
357     cx: &mut DropckContext<'a, 'b, 'tcx>,
358     context: TypeContext,
359     ty: Ty<'tcx>,
360     depth: usize) -> Result<(), Error<'tcx>>
361 {
362     let tcx = cx.rcx.tcx();
363     // Issue #22443: Watch out for overflow. While we are careful to
364     // handle regular types properly, non-regular ones cause problems.
365     let recursion_limit = tcx.sess.recursion_limit.get();
366     if depth / 4 >= recursion_limit {
367         // This can get into rather deep recursion, especially in the
368         // presence of things like Vec<T> -> Unique<T> -> PhantomData<T> -> T.
369         // use a higher recursion limit to avoid errors.
370         return Err(Error::Overflow(context, ty))
371     }
372
373     // canoncialize the regions in `ty` before inserting - infinitely many
374     // region variables can refer to the same region.
375     let ty = cx.rcx.infcx().resolve_type_and_region_vars_if_possible(&ty);
376
377     if !cx.breadcrumbs.insert(ty) {
378         debug!("iterate_over_potentially_unsafe_regions_in_type \
379                {}ty: {} scope: {:?} - cached",
380                (0..depth).map(|_| ' ').collect::<String>(),
381                ty, cx.parent_scope);
382         return Ok(()); // we already visited this type
383     }
384     debug!("iterate_over_potentially_unsafe_regions_in_type \
385            {}ty: {} scope: {:?}",
386            (0..depth).map(|_| ' ').collect::<String>(),
387            ty, cx.parent_scope);
388
389     // If `typ` has a destructor, then we must ensure that all
390     // borrowed data reachable via `typ` must outlive the parent
391     // of `scope`. This is handled below.
392     //
393     // However, there is an important special case: for any Drop
394     // impl that is tagged as "blind" to their parameters,
395     // we assume that data borrowed via such type parameters
396     // remains unreachable via that Drop impl.
397     //
398     // For example, consider:
399     //
400     // ```rust
401     // #[unsafe_destructor_blind_to_params]
402     // impl<T> Drop for Vec<T> { ... }
403     // ```
404     //
405     // which does have to be able to drop instances of `T`, but
406     // otherwise cannot read data from `T`.
407     //
408     // Of course, for the type expression passed in for any such
409     // unbounded type parameter `T`, we must resume the recursive
410     // analysis on `T` (since it would be ignored by
411     // type_must_outlive).
412     if has_dtor_of_interest(tcx, ty) {
413         debug!("iterate_over_potentially_unsafe_regions_in_type \
414                 {}ty: {} - is a dtorck type!",
415                (0..depth).map(|_| ' ').collect::<String>(),
416                ty);
417
418         regionck::type_must_outlive(cx.rcx,
419                                     infer::SubregionOrigin::SafeDestructor(cx.span),
420                                     ty,
421                                     ty::ReScope(cx.parent_scope));
422
423         return Ok(());
424     }
425
426     debug!("iterate_over_potentially_unsafe_regions_in_type \
427            {}ty: {} scope: {:?} - checking interior",
428            (0..depth).map(|_| ' ').collect::<String>(),
429            ty, cx.parent_scope);
430
431     // We still need to ensure all referenced data is safe.
432     match ty.sty {
433         ty::TyBool | ty::TyChar | ty::TyInt(_) | ty::TyUint(_) |
434         ty::TyFloat(_) | ty::TyStr => {
435             // primitive - definitely safe
436             Ok(())
437         }
438
439         ty::TyBox(ity) | ty::TyArray(ity, _) | ty::TySlice(ity) => {
440             // single-element containers, behave like their element
441             iterate_over_potentially_unsafe_regions_in_type(
442                 cx, context, ity, depth+1)
443         }
444
445         ty::TyStruct(def, substs) if def.is_phantom_data() => {
446             // PhantomData<T> - behaves identically to T
447             let ity = *substs.types.get(subst::TypeSpace, 0);
448             iterate_over_potentially_unsafe_regions_in_type(
449                 cx, context, ity, depth+1)
450         }
451
452         ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => {
453             let did = def.did;
454             for variant in &def.variants {
455                 for (i, field) in variant.fields.iter().enumerate() {
456                     let fty = field.ty(tcx, substs);
457                     let fty = cx.rcx.fcx.resolve_type_vars_if_possible(
458                         cx.rcx.fcx.normalize_associated_types_in(cx.span, &fty));
459                     try!(iterate_over_potentially_unsafe_regions_in_type(
460                         cx,
461                         TypeContext::ADT {
462                             def_id: did,
463                             field: field.name,
464                             variant: variant.name,
465                             field_index: i
466                         },
467                         fty,
468                         depth+1))
469                 }
470             }
471             Ok(())
472         }
473
474         ty::TyTuple(ref tys) |
475         ty::TyClosure(_, box ty::ClosureSubsts { upvar_tys: ref tys, .. }) => {
476             for ty in tys {
477                 try!(iterate_over_potentially_unsafe_regions_in_type(
478                     cx, context, ty, depth+1))
479             }
480             Ok(())
481         }
482
483         ty::TyRawPtr(..) | ty::TyRef(..) | ty::TyParam(..) => {
484             // these always come with a witness of liveness (references
485             // explicitly, pointers implicitly, parameters by the
486             // caller).
487             Ok(())
488         }
489
490         ty::TyBareFn(..) => {
491             // FIXME(#26656): this type is always destruction-safe, but
492             // it implicitly witnesses Self: Fn, which can be false.
493             Ok(())
494         }
495
496         ty::TyInfer(..) | ty::TyError => {
497             tcx.sess.delay_span_bug(cx.span, "unresolved type in regionck");
498             Ok(())
499         }
500
501         // these are always dtorck
502         ty::TyTrait(..) | ty::TyProjection(_) => unreachable!(),
503     }
504 }
505
506 fn has_dtor_of_interest<'tcx>(tcx: &ty::ctxt<'tcx>,
507                               ty: ty::Ty<'tcx>) -> bool {
508     match ty.sty {
509         ty::TyEnum(def, _) | ty::TyStruct(def, _) => {
510             def.is_dtorck(tcx)
511         }
512         ty::TyTrait(..) | ty::TyProjection(..) => {
513             debug!("ty: {:?} isn't known, and therefore is a dropck type", ty);
514             true
515         },
516         _ => false
517     }
518 }