]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/dropck.rs
Auto merge of #58341 - alexreg:cosmetic-2-doc-comments, r=steveklabnik
[rust.git] / src / librustc_typeck / check / dropck.rs
1 use crate::check::regionck::RegionCtxt;
2
3 use crate::hir::def_id::DefId;
4 use rustc::infer::outlives::env::OutlivesEnvironment;
5 use rustc::infer::{self, InferOk, SuppressRegionErrors};
6 use rustc::middle::region;
7 use rustc::traits::{ObligationCause, TraitEngine, TraitEngineExt};
8 use rustc::ty::subst::{Subst, Substs, UnpackedKind};
9 use rustc::ty::{self, Ty, TyCtxt};
10 use crate::util::common::ErrorReported;
11
12 use syntax::ast;
13 use syntax_pos::Span;
14
15 /// This function confirms that the `Drop` implementation identified by
16 /// `drop_impl_did` is not any more specialized than the type it is
17 /// attached to (Issue #8142).
18 ///
19 /// This means:
20 ///
21 /// 1. The self type must be nominal (this is already checked during
22 ///    coherence),
23 ///
24 /// 2. The generic region/type parameters of the impl's self type must
25 ///    all be parameters of the Drop impl itself (i.e., no
26 ///    specialization like `impl Drop for Foo<i32>`), and,
27 ///
28 /// 3. Any bounds on the generic parameters must be reflected in the
29 ///    struct/enum definition for the nominal type itself (i.e.
30 ///    cannot do `struct S<T>; impl<T:Clone> Drop for S<T> { ... }`).
31 ///
32 pub fn check_drop_impl<'a, 'tcx>(
33     tcx: TyCtxt<'a, 'tcx, 'tcx>,
34     drop_impl_did: DefId,
35 ) -> Result<(), ErrorReported> {
36     let dtor_self_type = tcx.type_of(drop_impl_did);
37     let dtor_predicates = tcx.predicates_of(drop_impl_did);
38     match dtor_self_type.sty {
39         ty::Adt(adt_def, self_to_impl_substs) => {
40             ensure_drop_params_and_item_params_correspond(
41                 tcx,
42                 drop_impl_did,
43                 dtor_self_type,
44                 adt_def.did,
45             )?;
46
47             ensure_drop_predicates_are_implied_by_item_defn(
48                 tcx,
49                 drop_impl_did,
50                 &dtor_predicates,
51                 adt_def.did,
52                 self_to_impl_substs,
53             )
54         }
55         _ => {
56             // Destructors only work on nominal types.  This was
57             // already checked by coherence, but compilation may
58             // not have been terminated.
59             let span = tcx.def_span(drop_impl_did);
60             tcx.sess.delay_span_bug(span,
61                 &format!("should have been rejected by coherence check: {}", dtor_self_type));
62             Err(ErrorReported)
63         }
64     }
65 }
66
67 fn ensure_drop_params_and_item_params_correspond<'a, 'tcx>(
68     tcx: TyCtxt<'a, 'tcx, 'tcx>,
69     drop_impl_did: DefId,
70     drop_impl_ty: Ty<'tcx>,
71     self_type_did: DefId,
72 ) -> Result<(), ErrorReported> {
73     let drop_impl_node_id = tcx.hir().as_local_node_id(drop_impl_did).unwrap();
74
75     // check that the impl type can be made to match the trait type.
76
77     tcx.infer_ctxt().enter(|ref infcx| {
78         let impl_param_env = tcx.param_env(self_type_did);
79         let tcx = infcx.tcx;
80         let mut fulfillment_cx = TraitEngine::new(tcx);
81
82         let named_type = tcx.type_of(self_type_did);
83
84         let drop_impl_span = tcx.def_span(drop_impl_did);
85         let fresh_impl_substs = infcx.fresh_substs_for_item(drop_impl_span, drop_impl_did);
86         let fresh_impl_self_ty = drop_impl_ty.subst(tcx, fresh_impl_substs);
87
88         let cause = &ObligationCause::misc(drop_impl_span, drop_impl_node_id);
89         match infcx
90             .at(cause, impl_param_env)
91             .eq(named_type, fresh_impl_self_ty)
92         {
93             Ok(InferOk { obligations, .. }) => {
94                 fulfillment_cx.register_predicate_obligations(infcx, obligations);
95             }
96             Err(_) => {
97                 let item_span = tcx.def_span(self_type_did);
98                 struct_span_err!(
99                     tcx.sess,
100                     drop_impl_span,
101                     E0366,
102                     "Implementations of Drop cannot be specialized"
103                 ).span_note(
104                     item_span,
105                     "Use same sequence of generic type and region \
106                      parameters that is on the struct/enum definition",
107                 )
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, None, false);
116             return Err(ErrorReported);
117         }
118
119         let region_scope_tree = region::ScopeTree::default();
120
121         // NB. It seems a bit... suspicious to use an empty param-env
122         // here. The correct thing, I imagine, would be
123         // `OutlivesEnvironment::new(impl_param_env)`, which would
124         // allow region solving to take any `a: 'b` relations on the
125         // impl into account. But I could not create a test case where
126         // it did the wrong thing, so I chose to preserve existing
127         // behavior, since it ought to be simply more
128         // conservative. -nmatsakis
129         let outlives_env = OutlivesEnvironment::new(ty::ParamEnv::empty());
130
131         infcx.resolve_regions_and_report_errors(
132             drop_impl_did,
133             &region_scope_tree,
134             &outlives_env,
135             SuppressRegionErrors::default(),
136         );
137         Ok(())
138     })
139 }
140
141 /// Confirms that every predicate imposed by dtor_predicates is
142 /// implied by assuming the predicates attached to self_type_did.
143 fn ensure_drop_predicates_are_implied_by_item_defn<'a, 'tcx>(
144     tcx: TyCtxt<'a, 'tcx, 'tcx>,
145     drop_impl_did: DefId,
146     dtor_predicates: &ty::GenericPredicates<'tcx>,
147     self_type_did: DefId,
148     self_to_impl_substs: &Substs<'tcx>,
149 ) -> Result<(), ErrorReported> {
150     let mut result = Ok(());
151
152     // Here is an example, analogous to that from
153     // `compare_impl_method`.
154     //
155     // Consider a struct type:
156     //
157     //     struct Type<'c, 'b:'c, 'a> {
158     //         x: &'a Contents            // (contents are irrelevant;
159     //         y: &'c Cell<&'b Contents>, //  only the bounds matter for our purposes.)
160     //     }
161     //
162     // and a Drop impl:
163     //
164     //     impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> {
165     //         fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y)
166     //     }
167     //
168     // We start out with self_to_impl_substs, that maps the generic
169     // parameters of Type to that of the Drop impl.
170     //
171     //     self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
172     //
173     // Applying this to the predicates (i.e., assumptions) provided by the item
174     // definition yields the instantiated assumptions:
175     //
176     //     ['y : 'z]
177     //
178     // We then check all of the predicates of the Drop impl:
179     //
180     //     ['y:'z, 'x:'y]
181     //
182     // and ensure each is in the list of instantiated
183     // assumptions. Here, `'y:'z` is present, but `'x:'y` is
184     // absent. So we report an error that the Drop impl injected a
185     // predicate that is not present on the struct definition.
186
187     let self_type_hir_id = tcx.hir().as_local_hir_id(self_type_did).unwrap();
188
189     let drop_impl_span = tcx.def_span(drop_impl_did);
190
191     // We can assume the predicates attached to struct/enum definition
192     // hold.
193     let generic_assumptions = tcx.predicates_of(self_type_did);
194
195     let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs);
196     let assumptions_in_impl_context = assumptions_in_impl_context.predicates;
197
198     // An earlier version of this code attempted to do this checking
199     // via the traits::fulfill machinery. However, it ran into trouble
200     // since the fulfill machinery merely turns outlives-predicates
201     // 'a:'b and T:'b into region inference constraints. It is simpler
202     // just to look for all the predicates directly.
203
204     assert_eq!(dtor_predicates.parent, None);
205     for (predicate, _) in &dtor_predicates.predicates {
206         // (We do not need to worry about deep analysis of type
207         // expressions etc because the Drop impls are already forced
208         // to take on a structure that is roughly an alpha-renaming of
209         // the generic parameters of the item definition.)
210
211         // This path now just checks *all* predicates via the direct
212         // lookup, rather than using fulfill machinery.
213         //
214         // However, it may be more efficient in the future to batch
215         // the analysis together via the fulfill , rather than the
216         // repeated `contains` calls.
217
218         if !assumptions_in_impl_context.contains(&predicate) {
219             let item_span = tcx.hir().span_by_hir_id(self_type_hir_id);
220             struct_span_err!(
221                 tcx.sess,
222                 drop_impl_span,
223                 E0367,
224                 "The requirement `{}` is added only by the Drop impl.",
225                 predicate
226             ).span_note(
227                 item_span,
228                 "The same requirement must be part of \
229                  the struct/enum definition",
230             )
231                 .emit();
232             result = Err(ErrorReported);
233         }
234     }
235
236     result
237 }
238
239 /// This function confirms that the type
240 /// expression `typ` conforms to the "Drop Check Rule" from the Sound
241 /// Generic Drop RFC (#769).
242 ///
243 /// ----
244 ///
245 /// The simplified (*) Drop Check Rule is the following:
246 ///
247 /// Let `v` be some value (either temporary or named) and 'a be some
248 /// lifetime (scope). If the type of `v` owns data of type `D`, where
249 ///
250 /// * (1.) `D` has a lifetime- or type-parametric Drop implementation,
251 ///        (where that `Drop` implementation does not opt-out of
252 ///         this check via the `unsafe_destructor_blind_to_params`
253 ///         attribute), and
254 /// * (2.) the structure of `D` can reach a reference of type `&'a _`,
255 ///
256 /// then 'a must strictly outlive the scope of v.
257 ///
258 /// ----
259 ///
260 /// This function is meant to by applied to the type for every
261 /// expression in the program.
262 ///
263 /// ----
264 ///
265 /// (*) The qualifier "simplified" is attached to the above
266 /// definition of the Drop Check Rule, because it is a simplification
267 /// of the original Drop Check rule, which attempted to prove that
268 /// some `Drop` implementations could not possibly access data even if
269 /// it was technically reachable, due to parametricity.
270 ///
271 /// However, (1.) parametricity on its own turned out to be a
272 /// necessary but insufficient condition, and (2.)  future changes to
273 /// the language are expected to make it impossible to ensure that a
274 /// `Drop` implementation is actually parametric with respect to any
275 /// particular type parameter. (In particular, impl specialization is
276 /// expected to break the needed parametricity property beyond
277 /// repair.)
278 ///
279 /// Therefore, we have scaled back Drop-Check to a more conservative
280 /// rule that does not attempt to deduce whether a `Drop`
281 /// implementation could not possible access data of a given lifetime;
282 /// instead Drop-Check now simply assumes that if a destructor has
283 /// access (direct or indirect) to a lifetime parameter, then that
284 /// lifetime must be forced to outlive that destructor's dynamic
285 /// extent. We then provide the `unsafe_destructor_blind_to_params`
286 /// attribute as a way for destructor implementations to opt-out of
287 /// this conservative assumption (and thus assume the obligation of
288 /// ensuring that they do not access data nor invoke methods of
289 /// values that have been previously dropped).
290 pub fn check_safety_of_destructor_if_necessary<'a, 'gcx, 'tcx>(
291     rcx: &mut RegionCtxt<'a, 'gcx, 'tcx>,
292     ty: Ty<'tcx>,
293     span: Span,
294     body_id: ast::NodeId,
295     scope: region::Scope,
296 ) -> Result<(), ErrorReported> {
297     debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
298            ty, scope);
299
300     let parent_scope = match rcx.region_scope_tree.opt_encl_scope(scope) {
301         Some(parent_scope) => parent_scope,
302         // If no enclosing scope, then it must be the root scope
303         // which cannot be outlived.
304         None => return Ok(()),
305     };
306     let parent_scope = rcx.tcx.mk_region(ty::ReScope(parent_scope));
307     let origin = || infer::SubregionOrigin::SafeDestructor(span);
308     let cause = &ObligationCause::misc(span, body_id);
309     let infer_ok = rcx.infcx.at(cause, rcx.fcx.param_env).dropck_outlives(ty);
310     debug!("dropck_outlives = {:#?}", infer_ok);
311     let kinds = rcx.fcx.register_infer_ok_obligations(infer_ok);
312     for kind in kinds {
313         match kind.unpack() {
314             UnpackedKind::Lifetime(r) => rcx.sub_regions(origin(), parent_scope, r),
315             UnpackedKind::Type(ty) => rcx.type_must_outlive(origin(), ty, parent_scope),
316         }
317     }
318     Ok(())
319 }