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