]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/dropck.rs
Auto merge of #28030 - tshepang:improve-example, r=alexcrichton
[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, LOCAL_CRATE};
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     assert!(drop_impl_did.is_local() && self_type_did.is_local());
81
82     // check that the impl type can be made to match the trait type.
83
84     let impl_param_env = ty::ParameterEnvironment::for_item(tcx, self_type_did.node);
85     let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(impl_param_env), true);
86
87     let named_type = tcx.lookup_item_type(self_type_did).ty;
88     let named_type = named_type.subst(tcx, &infcx.parameter_environment.free_substs);
89
90     let drop_impl_span = tcx.map.def_id_span(drop_impl_did, codemap::DUMMY_SP);
91     let fresh_impl_substs =
92         infcx.fresh_substs_for_generics(drop_impl_span, drop_impl_generics);
93     let fresh_impl_self_ty = drop_impl_ty.subst(tcx, &fresh_impl_substs);
94
95     if let Err(_) = infer::mk_eqty(&infcx, true, infer::TypeOrigin::Misc(drop_impl_span),
96                                    named_type, fresh_impl_self_ty) {
97         span_err!(tcx.sess, drop_impl_span, E0366,
98                   "Implementations of Drop cannot be specialized");
99         let item_span = tcx.map.span(self_type_did.node);
100         tcx.sess.span_note(item_span,
101                            "Use same sequence of generic type and region \
102                             parameters that is on the struct/enum definition");
103         return Err(());
104     }
105
106     if let Err(ref errors) = infcx.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
107         // this could be reached when we get lazy normalization
108         traits::report_fulfillment_errors(&infcx, errors);
109         return Err(());
110     }
111
112     let free_regions = FreeRegionMap::new();
113     infcx.resolve_regions_and_report_errors(&free_regions, drop_impl_did.node);
114     Ok(())
115 }
116
117 /// Confirms that every predicate imposed by dtor_predicates is
118 /// implied by assuming the predicates attached to self_type_did.
119 fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>(
120     tcx: &ty::ctxt<'tcx>,
121     drop_impl_did: DefId,
122     dtor_predicates: &ty::GenericPredicates<'tcx>,
123     self_type_did: DefId,
124     self_to_impl_substs: &subst::Substs<'tcx>) -> Result<(), ()> {
125
126     // Here is an example, analogous to that from
127     // `compare_impl_method`.
128     //
129     // Consider a struct type:
130     //
131     //     struct Type<'c, 'b:'c, 'a> {
132     //         x: &'a Contents            // (contents are irrelevant;
133     //         y: &'c Cell<&'b Contents>, //  only the bounds matter for our purposes.)
134     //     }
135     //
136     // and a Drop impl:
137     //
138     //     impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
139     //         fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
140     //     }
141     //
142     // We start out with self_to_impl_substs, that maps the generic
143     // parameters of Type to that of the Drop impl.
144     //
145     //     self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
146     //
147     // Applying this to the predicates (i.e. assumptions) provided by the item
148     // definition yields the instantiated assumptions:
149     //
150     //     ['y : 'z]
151     //
152     // We then check all of the predicates of the Drop impl:
153     //
154     //     ['y:'z, 'x:'y]
155     //
156     // and ensure each is in the list of instantiated
157     // assumptions. Here, `'y:'z` is present, but `'x:'y` is
158     // absent. So we report an error that the Drop impl injected a
159     // predicate that is not present on the struct definition.
160
161     assert_eq!(self_type_did.krate, LOCAL_CRATE);
162
163     let drop_impl_span = tcx.map.def_id_span(drop_impl_did, codemap::DUMMY_SP);
164
165     // We can assume the predicates attached to struct/enum definition
166     // hold.
167     let generic_assumptions = tcx.lookup_predicates(self_type_did);
168
169     let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
170     assert!(assumptions_in_impl_context.predicates.is_empty_in(subst::SelfSpace));
171     assert!(assumptions_in_impl_context.predicates.is_empty_in(subst::FnSpace));
172     let assumptions_in_impl_context =
173         assumptions_in_impl_context.predicates.get_slice(subst::TypeSpace);
174
175     // An earlier version of this code attempted to do this checking
176     // via the traits::fulfill machinery. However, it ran into trouble
177     // since the fulfill machinery merely turns outlives-predicates
178     // 'a:'b and T:'b into region inference constraints. It is simpler
179     // just to look for all the predicates directly.
180
181     assert!(dtor_predicates.predicates.is_empty_in(subst::SelfSpace));
182     assert!(dtor_predicates.predicates.is_empty_in(subst::FnSpace));
183     let predicates = dtor_predicates.predicates.get_slice(subst::TypeSpace);
184     for predicate in predicates {
185         // (We do not need to worry about deep analysis of type
186         // expressions etc because the Drop impls are already forced
187         // to take on a structure that is roughly a alpha-renaming of
188         // the generic parameters of the item definition.)
189
190         // This path now just checks *all* predicates via the direct
191         // lookup, rather than using fulfill machinery.
192         //
193         // However, it may be more efficient in the future to batch
194         // the analysis together via the fulfill , rather than the
195         // repeated `contains` calls.
196
197         if !assumptions_in_impl_context.contains(&predicate) {
198             let item_span = tcx.map.span(self_type_did.node);
199             span_err!(tcx.sess, drop_impl_span, E0367,
200                       "The requirement `{}` is added only by the Drop impl.", predicate);
201             tcx.sess.span_note(item_span,
202                                "The same requirement must be part of \
203                                 the struct/enum definition");
204         }
205     }
206
207     if tcx.sess.has_errors() {
208         return Err(());
209     }
210     Ok(())
211 }
212
213 /// check_safety_of_destructor_if_necessary confirms that the type
214 /// expression `typ` conforms to the "Drop Check Rule" from the Sound
215 /// Generic Drop (RFC 769).
216 ///
217 /// ----
218 ///
219 /// The Drop Check Rule is the following:
220 ///
221 /// Let `v` be some value (either temporary or named) and 'a be some
222 /// lifetime (scope). If the type of `v` owns data of type `D`, where
223 ///
224 /// * (1.) `D` has a lifetime- or type-parametric Drop implementation, and
225 /// * (2.) the structure of `D` can reach a reference of type `&'a _`, and
226 /// * (3.) either:
227 ///   * (A.) the Drop impl for `D` instantiates `D` at 'a directly,
228 ///          i.e. `D<'a>`, or,
229 ///   * (B.) the Drop impl for `D` has some type parameter with a
230 ///          trait bound `T` where `T` is a trait that has at least
231 ///          one method,
232 ///
233 /// then 'a must strictly outlive the scope of v.
234 ///
235 /// ----
236 ///
237 /// This function is meant to by applied to the type for every
238 /// expression in the program.
239 pub fn check_safety_of_destructor_if_necessary<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
240                                                          typ: ty::Ty<'tcx>,
241                                                          span: Span,
242                                                          scope: region::CodeExtent) {
243     debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
244            typ, scope);
245
246     let parent_scope = rcx.tcx().region_maps.opt_encl_scope(scope).unwrap_or_else(|| {
247         rcx.tcx().sess.span_bug(
248             span, &format!("no enclosing scope found for scope: {:?}", scope))
249     });
250
251     let result = iterate_over_potentially_unsafe_regions_in_type(
252         &mut DropckContext {
253             rcx: rcx,
254             span: span,
255             parent_scope: parent_scope,
256             breadcrumbs: FnvHashSet()
257         },
258         TypeContext::Root,
259         typ,
260         0);
261     match result {
262         Ok(()) => {}
263         Err(Error::Overflow(ref ctxt, ref detected_on_typ)) => {
264             let tcx = rcx.tcx();
265             span_err!(tcx.sess, span, E0320,
266                       "overflow while adding drop-check rules for {}", typ);
267             match *ctxt {
268                 TypeContext::Root => {
269                     // no need for an additional note if the overflow
270                     // was somehow on the root.
271                 }
272                 TypeContext::ADT { def_id, variant, field, field_index } => {
273                     let adt = tcx.lookup_adt_def(def_id);
274                     let variant_name = match adt.adt_kind() {
275                         ty::AdtKind::Enum => format!("enum {} variant {}",
276                                                      tcx.item_path_str(def_id),
277                                                      variant),
278                         ty::AdtKind::Struct => format!("struct {}",
279                                                        tcx.item_path_str(def_id))
280                     };
281                     let field_name = if field == special_idents::unnamed_field.name {
282                         format!("#{}", field_index)
283                     } else {
284                         format!("`{}`", field)
285                     };
286                     span_note!(
287                         rcx.tcx().sess,
288                         span,
289                         "overflowed on {} field {} type: {}",
290                         variant_name,
291                         field_name,
292                         detected_on_typ);
293                 }
294             }
295         }
296     }
297 }
298
299 enum Error<'tcx> {
300     Overflow(TypeContext, ty::Ty<'tcx>),
301 }
302
303 #[derive(Copy, Clone)]
304 enum TypeContext {
305     Root,
306     ADT {
307         def_id: DefId,
308         variant: ast::Name,
309         field: ast::Name,
310         field_index: usize
311     }
312 }
313
314 struct DropckContext<'a, 'b: 'a, 'tcx: 'b> {
315     rcx: &'a mut Rcx<'b, 'tcx>,
316     /// types that have already been traversed
317     breadcrumbs: FnvHashSet<Ty<'tcx>>,
318     /// span for error reporting
319     span: Span,
320     /// the scope reachable dtorck types must outlive
321     parent_scope: region::CodeExtent
322 }
323
324 // `context` is used for reporting overflow errors
325 fn iterate_over_potentially_unsafe_regions_in_type<'a, 'b, 'tcx>(
326     cx: &mut DropckContext<'a, 'b, 'tcx>,
327     context: TypeContext,
328     ty: Ty<'tcx>,
329     depth: usize) -> Result<(), Error<'tcx>>
330 {
331     let tcx = cx.rcx.tcx();
332     // Issue #22443: Watch out for overflow. While we are careful to
333     // handle regular types properly, non-regular ones cause problems.
334     let recursion_limit = tcx.sess.recursion_limit.get();
335     if depth / 4 >= recursion_limit {
336         // This can get into rather deep recursion, especially in the
337         // presence of things like Vec<T> -> Unique<T> -> PhantomData<T> -> T.
338         // use a higher recursion limit to avoid errors.
339         return Err(Error::Overflow(context, ty))
340     }
341
342     if !cx.breadcrumbs.insert(ty) {
343         debug!("iterate_over_potentially_unsafe_regions_in_type \
344                {}ty: {} scope: {:?} - cached",
345                (0..depth).map(|_| ' ').collect::<String>(),
346                ty, cx.parent_scope);
347         return Ok(()); // we already visited this type
348     }
349     debug!("iterate_over_potentially_unsafe_regions_in_type \
350            {}ty: {} scope: {:?}",
351            (0..depth).map(|_| ' ').collect::<String>(),
352            ty, cx.parent_scope);
353
354     // If `typ` has a destructor, then we must ensure that all
355     // borrowed data reachable via `typ` must outlive the parent
356     // of `scope`. This is handled below.
357     //
358     // However, there is an important special case: by
359     // parametricity, any generic type parameters have *no* trait
360     // bounds in the Drop impl can not be used in any way (apart
361     // from being dropped), and thus we can treat data borrowed
362     // via such type parameters remains unreachable.
363     //
364     // For example, consider `impl<T> Drop for Vec<T> { ... }`,
365     // which does have to be able to drop instances of `T`, but
366     // otherwise cannot read data from `T`.
367     //
368     // Of course, for the type expression passed in for any such
369     // unbounded type parameter `T`, we must resume the recursive
370     // analysis on `T` (since it would be ignored by
371     // type_must_outlive).
372     //
373     // FIXME (pnkfelix): Long term, we could be smart and actually
374     // feed which generic parameters can be ignored *into* `fn
375     // type_must_outlive` (or some generalization thereof). But
376     // for the short term, it probably covers most cases of
377     // interest to just special case Drop impls where: (1.) there
378     // are no generic lifetime parameters and (2.)  *all* generic
379     // type parameters are unbounded.  If both conditions hold, we
380     // simply skip the `type_must_outlive` call entirely (but
381     // resume the recursive checking of the type-substructure).
382     if has_dtor_of_interest(tcx, ty) {
383         debug!("iterate_over_potentially_unsafe_regions_in_type \
384                 {}ty: {} - is a dtorck type!",
385                (0..depth).map(|_| ' ').collect::<String>(),
386                ty);
387
388         regionck::type_must_outlive(cx.rcx,
389                                     infer::SubregionOrigin::SafeDestructor(cx.span),
390                                     ty,
391                                     ty::ReScope(cx.parent_scope));
392
393         return Ok(());
394     }
395
396     debug!("iterate_over_potentially_unsafe_regions_in_type \
397            {}ty: {} scope: {:?} - checking interior",
398            (0..depth).map(|_| ' ').collect::<String>(),
399            ty, cx.parent_scope);
400
401     // We still need to ensure all referenced data is safe.
402     match ty.sty {
403         ty::TyBool | ty::TyChar | ty::TyInt(_) | ty::TyUint(_) |
404         ty::TyFloat(_) | ty::TyStr => {
405             // primitive - definitely safe
406             Ok(())
407         }
408
409         ty::TyBox(ity) | ty::TyArray(ity, _) | ty::TySlice(ity) => {
410             // single-element containers, behave like their element
411             iterate_over_potentially_unsafe_regions_in_type(
412                 cx, context, ity, depth+1)
413         }
414
415         ty::TyStruct(def, substs) if def.is_phantom_data() => {
416             // PhantomData<T> - behaves identically to T
417             let ity = *substs.types.get(subst::TypeSpace, 0);
418             iterate_over_potentially_unsafe_regions_in_type(
419                 cx, context, ity, depth+1)
420         }
421
422         ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => {
423             let did = def.did;
424             for variant in &def.variants {
425                 for (i, field) in variant.fields.iter().enumerate() {
426                     let fty = field.ty(tcx, substs);
427                     let fty = cx.rcx.fcx.resolve_type_vars_if_possible(
428                         cx.rcx.fcx.normalize_associated_types_in(cx.span, &fty));
429                     try!(iterate_over_potentially_unsafe_regions_in_type(
430                         cx,
431                         TypeContext::ADT {
432                             def_id: did,
433                             field: field.name,
434                             variant: variant.name,
435                             field_index: i
436                         },
437                         fty,
438                         depth+1))
439                 }
440             }
441             Ok(())
442         }
443
444         ty::TyTuple(ref tys) |
445         ty::TyClosure(_, box ty::ClosureSubsts { upvar_tys: ref tys, .. }) => {
446             for ty in tys {
447                 try!(iterate_over_potentially_unsafe_regions_in_type(
448                     cx, context, ty, depth+1))
449             }
450             Ok(())
451         }
452
453         ty::TyRawPtr(..) | ty::TyRef(..) | ty::TyParam(..) => {
454             // these always come with a witness of liveness (references
455             // explicitly, pointers implicitly, parameters by the
456             // caller).
457             Ok(())
458         }
459
460         ty::TyBareFn(..) => {
461             // FIXME(#26656): this type is always destruction-safe, but
462             // it implicitly witnesses Self: Fn, which can be false.
463             Ok(())
464         }
465
466         ty::TyInfer(..) | ty::TyError => {
467             tcx.sess.delay_span_bug(cx.span, "unresolved type in regionck");
468             Ok(())
469         }
470
471         // these are always dtorck
472         ty::TyTrait(..) | ty::TyProjection(_) => unreachable!(),
473     }
474 }
475
476 fn has_dtor_of_interest<'tcx>(tcx: &ty::ctxt<'tcx>,
477                               ty: ty::Ty<'tcx>) -> bool {
478     match ty.sty {
479         ty::TyEnum(def, _) | ty::TyStruct(def, _) => {
480             def.is_dtorck(tcx)
481         }
482         ty::TyTrait(..) | ty::TyProjection(..) => {
483             debug!("ty: {:?} isn't known, and therefore is a dropck type", ty);
484             true
485         },
486         _ => false
487     }
488 }