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