]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
1 | // Copyright 2012-2014 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 | //! The region check is a final pass that runs over the AST after we have | |
12 | //! inferred the type constraints but before we have actually finalized | |
13 | //! the types. Its purpose is to embed a variety of region constraints. | |
14 | //! Inserting these constraints as a separate pass is good because (1) it | |
15 | //! localizes the code that has to do with region inference and (2) often | |
16 | //! we cannot know what constraints are needed until the basic types have | |
17 | //! been inferred. | |
18 | //! | |
19 | //! ### Interaction with the borrow checker | |
20 | //! | |
21 | //! In general, the job of the borrowck module (which runs later) is to | |
22 | //! check that all soundness criteria are met, given a particular set of | |
23 | //! regions. The job of *this* module is to anticipate the needs of the | |
24 | //! borrow checker and infer regions that will satisfy its requirements. | |
25 | //! It is generally true that the inference doesn't need to be sound, | |
26 | //! meaning that if there is a bug and we inferred bad regions, the borrow | |
27 | //! checker should catch it. This is not entirely true though; for | |
28 | //! example, the borrow checker doesn't check subtyping, and it doesn't | |
29 | //! check that region pointers are always live when they are used. It | |
30 | //! might be worthwhile to fix this so that borrowck serves as a kind of | |
31 | //! verification step -- that would add confidence in the overall | |
32 | //! correctness of the compiler, at the cost of duplicating some type | |
33 | //! checks and effort. | |
34 | //! | |
35 | //! ### Inferring the duration of borrows, automatic and otherwise | |
36 | //! | |
37 | //! Whenever we introduce a borrowed pointer, for example as the result of | |
38 | //! a borrow expression `let x = &data`, the lifetime of the pointer `x` | |
39 | //! is always specified as a region inference variable. `regionck` has the | |
40 | //! job of adding constraints such that this inference variable is as | |
41 | //! narrow as possible while still accommodating all uses (that is, every | |
42 | //! dereference of the resulting pointer must be within the lifetime). | |
43 | //! | |
44 | //! #### Reborrows | |
45 | //! | |
46 | //! Generally speaking, `regionck` does NOT try to ensure that the data | |
47 | //! `data` will outlive the pointer `x`. That is the job of borrowck. The | |
48 | //! one exception is when "re-borrowing" the contents of another borrowed | |
49 | //! pointer. For example, imagine you have a borrowed pointer `b` with | |
50 | //! lifetime L1 and you have an expression `&*b`. The result of this | |
51 | //! expression will be another borrowed pointer with lifetime L2 (which is | |
52 | //! an inference variable). The borrow checker is going to enforce the | |
53 | //! constraint that L2 < L1, because otherwise you are re-borrowing data | |
54 | //! for a lifetime larger than the original loan. However, without the | |
55 | //! routines in this module, the region inferencer would not know of this | |
56 | //! dependency and thus it might infer the lifetime of L2 to be greater | |
57 | //! than L1 (issue #3148). | |
58 | //! | |
59 | //! There are a number of troublesome scenarios in the tests | |
60 | //! `region-dependent-*.rs`, but here is one example: | |
61 | //! | |
92a42be0 | 62 | //! struct Foo { i: i32 } |
1a4d82fc | 63 | //! struct Bar { foo: Foo } |
9cc50fc6 | 64 | //! fn get_i<'a>(x: &'a Bar) -> &'a i32 { |
1a4d82fc JJ |
65 | //! let foo = &x.foo; // Lifetime L1 |
66 | //! &foo.i // Lifetime L2 | |
67 | //! } | |
68 | //! | |
69 | //! Note that this comes up either with `&` expressions, `ref` | |
70 | //! bindings, and `autorefs`, which are the three ways to introduce | |
71 | //! a borrow. | |
72 | //! | |
73 | //! The key point here is that when you are borrowing a value that | |
74 | //! is "guaranteed" by a borrowed pointer, you must link the | |
75 | //! lifetime of that borrowed pointer (L1, here) to the lifetime of | |
76 | //! the borrow itself (L2). What do I mean by "guaranteed" by a | |
77 | //! borrowed pointer? I mean any data that is reached by first | |
78 | //! dereferencing a borrowed pointer and then either traversing | |
62682a34 | 79 | //! interior offsets or boxes. We say that the guarantor |
b039eaaf | 80 | //! of such data is the region of the borrowed pointer that was |
1a4d82fc JJ |
81 | //! traversed. This is essentially the same as the ownership |
82 | //! relation, except that a borrowed pointer never owns its | |
83 | //! contents. | |
84 | ||
85aaf69f | 85 | use check::dropck; |
1a4d82fc | 86 | use check::FnCtxt; |
bd371182 | 87 | use middle::free_region::FreeRegionMap; |
1a4d82fc | 88 | use middle::mem_categorization as mc; |
92a42be0 | 89 | use middle::mem_categorization::Categorization; |
9cc50fc6 | 90 | use middle::region::{self, CodeExtent}; |
54a0048b SL |
91 | use rustc::ty::subst::Substs; |
92 | use rustc::traits; | |
a7813a04 | 93 | use rustc::ty::{self, Ty, MethodCall, TypeFoldable}; |
476ff2be | 94 | use rustc::infer::{self, GenericKind, SubregionOrigin, VerifyBound}; |
54a0048b SL |
95 | use rustc::ty::adjustment; |
96 | use rustc::ty::wf::ImpliedBound; | |
1a4d82fc | 97 | |
85aaf69f | 98 | use std::mem; |
a7813a04 | 99 | use std::ops::Deref; |
e9174d1e | 100 | use syntax::ast; |
3157f602 | 101 | use syntax_pos::Span; |
476ff2be | 102 | use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; |
54a0048b | 103 | use rustc::hir::{self, PatKind}; |
1a4d82fc | 104 | |
1a4d82fc JJ |
105 | use self::SubjectNode::Subject; |
106 | ||
107 | // a variation on try that just returns unit | |
108 | macro_rules! ignore_err { | |
109 | ($e:expr) => (match $e { Ok(e) => e, Err(_) => return () }) | |
110 | } | |
111 | ||
112 | /////////////////////////////////////////////////////////////////////////// | |
113 | // PUBLIC ENTRY POINTS | |
114 | ||
a7813a04 | 115 | impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { |
32a655c1 SL |
116 | pub fn regionck_expr(&self, body: &'gcx hir::Body) { |
117 | let id = body.value.id; | |
118 | let mut rcx = RegionCtxt::new(self, RepeatingScope(id), id, Subject(id)); | |
a7813a04 XL |
119 | if self.err_count_since_creation() == 0 { |
120 | // regionck assumes typeck succeeded | |
32a655c1 SL |
121 | rcx.visit_body(body); |
122 | rcx.visit_region_obligations(id); | |
a7813a04 XL |
123 | } |
124 | rcx.resolve_regions_and_report_errors(); | |
1a4d82fc | 125 | } |
1a4d82fc | 126 | |
a7813a04 XL |
127 | /// Region checking during the WF phase for items. `wf_tys` are the |
128 | /// types from which we should derive implied bounds, if any. | |
129 | pub fn regionck_item(&self, | |
130 | item_id: ast::NodeId, | |
131 | span: Span, | |
132 | wf_tys: &[Ty<'tcx>]) { | |
133 | debug!("regionck_item(item.id={:?}, wf_tys={:?}", item_id, wf_tys); | |
134 | let mut rcx = RegionCtxt::new(self, RepeatingScope(item_id), item_id, Subject(item_id)); | |
135 | rcx.free_region_map.relate_free_regions_from_predicates( | |
136 | &self.parameter_environment.caller_bounds); | |
137 | rcx.relate_free_regions(wf_tys, item_id, span); | |
138 | rcx.visit_region_obligations(item_id); | |
139 | rcx.resolve_regions_and_report_errors(); | |
1a4d82fc JJ |
140 | } |
141 | ||
a7813a04 XL |
142 | pub fn regionck_fn(&self, |
143 | fn_id: ast::NodeId, | |
32a655c1 | 144 | body: &'gcx hir::Body) { |
a7813a04 | 145 | debug!("regionck_fn(id={})", fn_id); |
32a655c1 | 146 | let node_id = body.value.id; |
476ff2be | 147 | let mut rcx = RegionCtxt::new(self, RepeatingScope(node_id), node_id, Subject(fn_id)); |
a7813a04 XL |
148 | |
149 | if self.err_count_since_creation() == 0 { | |
150 | // regionck assumes typeck succeeded | |
32a655c1 | 151 | rcx.visit_fn_body(fn_id, body, self.tcx.hir.span(fn_id)); |
a7813a04 XL |
152 | } |
153 | ||
154 | rcx.free_region_map.relate_free_regions_from_predicates( | |
155 | &self.parameter_environment.caller_bounds); | |
bd371182 | 156 | |
a7813a04 | 157 | rcx.resolve_regions_and_report_errors(); |
bd371182 | 158 | |
a7813a04 XL |
159 | // For the top-level fn, store the free-region-map. We don't store |
160 | // any map for closures; they just share the same map as the | |
161 | // function that created them. | |
162 | self.tcx.store_free_region_map(fn_id, rcx.free_region_map); | |
163 | } | |
1a4d82fc JJ |
164 | } |
165 | ||
1a4d82fc JJ |
166 | /////////////////////////////////////////////////////////////////////////// |
167 | // INTERNALS | |
168 | ||
a7813a04 XL |
169 | pub struct RegionCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { |
170 | pub fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, | |
1a4d82fc | 171 | |
9e0c209e | 172 | region_bound_pairs: Vec<(&'tcx ty::Region, GenericKind<'tcx>)>, |
1a4d82fc | 173 | |
bd371182 AL |
174 | free_region_map: FreeRegionMap, |
175 | ||
85aaf69f SL |
176 | // id of innermost fn body id |
177 | body_id: ast::NodeId, | |
178 | ||
9cc50fc6 SL |
179 | // call_site scope of innermost fn |
180 | call_site_scope: Option<CodeExtent>, | |
181 | ||
1a4d82fc JJ |
182 | // id of innermost fn or loop |
183 | repeating_scope: ast::NodeId, | |
184 | ||
185 | // id of AST node being analyzed (the subject of the analysis). | |
186 | subject: SubjectNode, | |
85aaf69f | 187 | |
1a4d82fc JJ |
188 | } |
189 | ||
a7813a04 XL |
190 | impl<'a, 'gcx, 'tcx> Deref for RegionCtxt<'a, 'gcx, 'tcx> { |
191 | type Target = FnCtxt<'a, 'gcx, 'tcx>; | |
192 | fn deref(&self) -> &Self::Target { | |
193 | &self.fcx | |
194 | } | |
195 | } | |
196 | ||
c34b1796 | 197 | pub struct RepeatingScope(ast::NodeId); |
1a4d82fc JJ |
198 | pub enum SubjectNode { Subject(ast::NodeId), None } |
199 | ||
a7813a04 XL |
200 | impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { |
201 | pub fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, | |
1a4d82fc | 202 | initial_repeating_scope: RepeatingScope, |
85aaf69f | 203 | initial_body_id: ast::NodeId, |
a7813a04 | 204 | subject: SubjectNode) -> RegionCtxt<'a, 'gcx, 'tcx> { |
85aaf69f | 205 | let RepeatingScope(initial_repeating_scope) = initial_repeating_scope; |
a7813a04 XL |
206 | RegionCtxt { |
207 | fcx: fcx, | |
208 | repeating_scope: initial_repeating_scope, | |
209 | body_id: initial_body_id, | |
210 | call_site_scope: None, | |
211 | subject: subject, | |
212 | region_bound_pairs: Vec::new(), | |
213 | free_region_map: FreeRegionMap::new(), | |
85aaf69f | 214 | } |
1a4d82fc JJ |
215 | } |
216 | ||
9cc50fc6 SL |
217 | fn set_call_site_scope(&mut self, call_site_scope: Option<CodeExtent>) -> Option<CodeExtent> { |
218 | mem::replace(&mut self.call_site_scope, call_site_scope) | |
219 | } | |
220 | ||
85aaf69f SL |
221 | fn set_body_id(&mut self, body_id: ast::NodeId) -> ast::NodeId { |
222 | mem::replace(&mut self.body_id, body_id) | |
223 | } | |
224 | ||
225 | fn set_repeating_scope(&mut self, scope: ast::NodeId) -> ast::NodeId { | |
226 | mem::replace(&mut self.repeating_scope, scope) | |
1a4d82fc JJ |
227 | } |
228 | ||
229 | /// Try to resolve the type for the given node, returning t_err if an error results. Note that | |
230 | /// we never care about the details of the error, the same error will be detected and reported | |
231 | /// in the writeback phase. | |
232 | /// | |
233 | /// Note one important point: we do not attempt to resolve *region variables* here. This is | |
234 | /// because regionck is essentially adding constraints to those region variables and so may yet | |
235 | /// influence how they are resolved. | |
236 | /// | |
237 | /// Consider this silly example: | |
238 | /// | |
239 | /// ``` | |
92a42be0 SL |
240 | /// fn borrow(x: &i32) -> &i32 {x} |
241 | /// fn foo(x: @i32) -> i32 { // block: B | |
1a4d82fc JJ |
242 | /// let b = borrow(x); // region: <R0> |
243 | /// *b | |
244 | /// } | |
245 | /// ``` | |
246 | /// | |
c34b1796 | 247 | /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the |
1a4d82fc JJ |
248 | /// block B and some superregion of the call. If we forced it now, we'd choose the smaller |
249 | /// region (the call). But that would make the *b illegal. Since we don't resolve, the type | |
92a42be0 | 250 | /// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and |
1a4d82fc JJ |
251 | /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B. |
252 | pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> { | |
a7813a04 | 253 | self.resolve_type_vars_if_possible(&unresolved_ty) |
1a4d82fc JJ |
254 | } |
255 | ||
256 | /// Try to resolve the type for the given node. | |
257 | fn resolve_node_type(&self, id: ast::NodeId) -> Ty<'tcx> { | |
a7813a04 | 258 | let t = self.node_ty(id); |
1a4d82fc JJ |
259 | self.resolve_type(t) |
260 | } | |
261 | ||
1a4d82fc | 262 | /// Try to resolve the type for the given node. |
e9174d1e | 263 | pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr) -> Ty<'tcx> { |
c30ab7b3 SL |
264 | let ty = self.tables.borrow().expr_ty_adjusted(expr); |
265 | self.resolve_type(ty) | |
1a4d82fc JJ |
266 | } |
267 | ||
268 | fn visit_fn_body(&mut self, | |
9cc50fc6 | 269 | id: ast::NodeId, // the id of the fn itself |
32a655c1 | 270 | body: &'gcx hir::Body, |
85aaf69f | 271 | span: Span) |
1a4d82fc JJ |
272 | { |
273 | // When we enter a function, we can derive | |
85aaf69f | 274 | debug!("visit_fn_body(id={})", id); |
1a4d82fc | 275 | |
32a655c1 SL |
276 | let body_id = body.id(); |
277 | ||
a7813a04 | 278 | let call_site = self.tcx.region_maps.lookup_code_extent( |
32a655c1 | 279 | region::CodeExtentData::CallSiteScope { fn_id: id, body_id: body_id.node_id }); |
9cc50fc6 SL |
280 | let old_call_site_scope = self.set_call_site_scope(Some(call_site)); |
281 | ||
92a42be0 | 282 | let fn_sig = { |
a7813a04 | 283 | let fn_sig_map = &self.tables.borrow().liberated_fn_sigs; |
92a42be0 SL |
284 | match fn_sig_map.get(&id) { |
285 | Some(f) => f.clone(), | |
286 | None => { | |
54a0048b | 287 | bug!("No fn-sig entry for id={}", id); |
92a42be0 | 288 | } |
1a4d82fc JJ |
289 | } |
290 | }; | |
291 | ||
bd371182 AL |
292 | let old_region_bounds_pairs_len = self.region_bound_pairs.len(); |
293 | ||
92a42be0 SL |
294 | // Collect the types from which we create inferred bounds. |
295 | // For the return type, if diverging, substitute `bool` just | |
296 | // because it will have no effect. | |
297 | // | |
9cc50fc6 | 298 | // FIXME(#27579) return types should not be implied bounds |
92a42be0 | 299 | let fn_sig_tys: Vec<_> = |
476ff2be SL |
300 | fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect(); |
301 | ||
32a655c1 SL |
302 | let old_body_id = self.set_body_id(body_id.node_id); |
303 | self.relate_free_regions(&fn_sig_tys[..], body_id.node_id, span); | |
304 | self.link_fn_args(self.tcx.region_maps.node_extent(body_id.node_id), &body.arguments); | |
305 | self.visit_body(body); | |
306 | self.visit_region_obligations(body_id.node_id); | |
bd371182 | 307 | |
9cc50fc6 | 308 | let call_site_scope = self.call_site_scope.unwrap(); |
32a655c1 SL |
309 | debug!("visit_fn_body body.id {:?} call_site_scope: {:?}", |
310 | body.id(), call_site_scope); | |
9e0c209e | 311 | let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope)); |
a7813a04 | 312 | self.type_of_node_must_outlive(infer::CallReturn(span), |
32a655c1 | 313 | body_id.node_id, |
9e0c209e | 314 | call_site_region); |
9cc50fc6 | 315 | |
bd371182 AL |
316 | self.region_bound_pairs.truncate(old_region_bounds_pairs_len); |
317 | ||
85aaf69f | 318 | self.set_body_id(old_body_id); |
9cc50fc6 | 319 | self.set_call_site_scope(old_call_site_scope); |
1a4d82fc JJ |
320 | } |
321 | ||
322 | fn visit_region_obligations(&mut self, node_id: ast::NodeId) | |
323 | { | |
324 | debug!("visit_region_obligations: node_id={}", node_id); | |
85aaf69f SL |
325 | |
326 | // region checking can introduce new pending obligations | |
327 | // which, when processed, might generate new region | |
328 | // obligations. So make sure we process those. | |
a7813a04 | 329 | self.select_all_obligations_or_error(); |
85aaf69f SL |
330 | |
331 | // Make a copy of the region obligations vec because we'll need | |
332 | // to be able to borrow the fulfillment-cx below when projecting. | |
333 | let region_obligations = | |
a7813a04 | 334 | self.fulfillment_cx |
c1a9b12d SL |
335 | .borrow() |
336 | .region_obligations(node_id) | |
337 | .to_vec(); | |
85aaf69f SL |
338 | |
339 | for r_o in ®ion_obligations { | |
e9174d1e SL |
340 | debug!("visit_region_obligations: r_o={:?} cause={:?}", |
341 | r_o, r_o.cause); | |
1a4d82fc | 342 | let sup_type = self.resolve_type(r_o.sup_type); |
c30ab7b3 | 343 | let origin = self.code_to_origin(&r_o.cause, sup_type); |
a7813a04 | 344 | self.type_must_outlive(origin, sup_type, r_o.sub_region); |
1a4d82fc | 345 | } |
85aaf69f SL |
346 | |
347 | // Processing the region obligations should not cause the list to grow further: | |
348 | assert_eq!(region_obligations.len(), | |
a7813a04 | 349 | self.fulfillment_cx.borrow().region_obligations(node_id).len()); |
e9174d1e SL |
350 | } |
351 | ||
352 | fn code_to_origin(&self, | |
c30ab7b3 SL |
353 | cause: &traits::ObligationCause<'tcx>, |
354 | sup_type: Ty<'tcx>) | |
e9174d1e | 355 | -> SubregionOrigin<'tcx> { |
c30ab7b3 SL |
356 | SubregionOrigin::from_obligation_cause(cause, |
357 | || infer::RelateParamBound(cause.span, sup_type)) | |
e9174d1e SL |
358 | } |
359 | ||
1a4d82fc JJ |
360 | /// This method populates the region map's `free_region_map`. It walks over the transformed |
361 | /// argument and return types for each function just before we check the body of that function, | |
362 | /// looking for types where you have a borrowed pointer to other borrowed data (e.g., `&'a &'b | |
c34b1796 | 363 | /// [usize]`. We do not allow references to outlive the things they point at, so we can assume |
1a4d82fc JJ |
364 | /// that `'a <= 'b`. This holds for both the argument and return types, basically because, on |
365 | /// the caller side, the caller is responsible for checking that the type of every expression | |
366 | /// (including the actual values for the arguments, as well as the return type of the fn call) | |
367 | /// is well-formed. | |
368 | /// | |
369 | /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs` | |
370 | fn relate_free_regions(&mut self, | |
371 | fn_sig_tys: &[Ty<'tcx>], | |
85aaf69f SL |
372 | body_id: ast::NodeId, |
373 | span: Span) { | |
1a4d82fc | 374 | debug!("relate_free_regions >>"); |
1a4d82fc | 375 | |
85aaf69f | 376 | for &ty in fn_sig_tys { |
1a4d82fc | 377 | let ty = self.resolve_type(ty); |
62682a34 | 378 | debug!("relate_free_regions(t={:?})", ty); |
a7813a04 | 379 | let implied_bounds = ty::wf::implied_bounds(self, body_id, ty, span); |
bd371182 AL |
380 | |
381 | // Record any relations between free regions that we observe into the free-region-map. | |
e9174d1e | 382 | self.free_region_map.relate_free_regions_from_implied_bounds(&implied_bounds); |
bd371182 AL |
383 | |
384 | // But also record other relationships, such as `T:'x`, | |
385 | // that don't go into the free-region-map but which we use | |
386 | // here. | |
e9174d1e | 387 | for implication in implied_bounds { |
62682a34 | 388 | debug!("implication: {:?}", implication); |
85aaf69f | 389 | match implication { |
9e0c209e SL |
390 | ImpliedBound::RegionSubRegion(&ty::ReFree(free_a), |
391 | &ty::ReVar(vid_b)) => { | |
a7813a04 | 392 | self.add_given(free_a, vid_b); |
1a4d82fc | 393 | } |
e9174d1e SL |
394 | ImpliedBound::RegionSubParam(r_a, param_b) => { |
395 | self.region_bound_pairs.push((r_a, GenericKind::Param(param_b))); | |
c34b1796 | 396 | } |
e9174d1e SL |
397 | ImpliedBound::RegionSubProjection(r_a, projection_b) => { |
398 | self.region_bound_pairs.push((r_a, GenericKind::Projection(projection_b))); | |
399 | } | |
400 | ImpliedBound::RegionSubRegion(..) => { | |
1a4d82fc JJ |
401 | // In principle, we could record (and take |
402 | // advantage of) every relationship here, but | |
403 | // we are also free not to -- it simply means | |
404 | // strictly less that we can successfully type | |
405 | // check. (It may also be that we should | |
406 | // revise our inference system to be more | |
407 | // general and to make use of *every* | |
408 | // relationship that arises here, but | |
409 | // presently we do not.) | |
410 | } | |
1a4d82fc JJ |
411 | } |
412 | } | |
413 | } | |
414 | ||
415 | debug!("<< relate_free_regions"); | |
416 | } | |
417 | ||
418 | fn resolve_regions_and_report_errors(&self) { | |
419 | let subject_node_id = match self.subject { | |
420 | Subject(s) => s, | |
421 | SubjectNode::None => { | |
54a0048b SL |
422 | bug!("cannot resolve_regions_and_report_errors \ |
423 | without subject node"); | |
1a4d82fc JJ |
424 | } |
425 | }; | |
426 | ||
a7813a04 XL |
427 | self.fcx.resolve_regions_and_report_errors(&self.free_region_map, |
428 | subject_node_id); | |
429 | } | |
430 | ||
431 | fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat) { | |
432 | let tcx = self.tcx; | |
433 | debug!("regionck::visit_pat(pat={:?})", pat); | |
476ff2be | 434 | pat.each_binding(|_, id, span, _| { |
a7813a04 XL |
435 | // If we have a variable that contains region'd data, that |
436 | // data will be accessible from anywhere that the variable is | |
437 | // accessed. We must be wary of loops like this: | |
438 | // | |
439 | // // from src/test/compile-fail/borrowck-lend-flow.rs | |
440 | // let mut v = box 3, w = box 4; | |
441 | // let mut x = &mut w; | |
442 | // loop { | |
443 | // **x += 1; // (2) | |
444 | // borrow(v); //~ ERROR cannot borrow | |
445 | // x = &mut v; // (1) | |
446 | // } | |
447 | // | |
448 | // Typically, we try to determine the region of a borrow from | |
449 | // those points where it is dereferenced. In this case, one | |
450 | // might imagine that the lifetime of `x` need only be the | |
451 | // body of the loop. But of course this is incorrect because | |
452 | // the pointer that is created at point (1) is consumed at | |
453 | // point (2), meaning that it must be live across the loop | |
454 | // iteration. The easiest way to guarantee this is to require | |
455 | // that the lifetime of any regions that appear in a | |
456 | // variable's type enclose at least the variable's scope. | |
457 | ||
458 | let var_scope = tcx.region_maps.var_scope(id); | |
9e0c209e | 459 | let var_region = self.tcx.mk_region(ty::ReScope(var_scope)); |
a7813a04 XL |
460 | |
461 | let origin = infer::BindingTypeIsNotValidAtDecl(span); | |
9e0c209e | 462 | self.type_of_node_must_outlive(origin, id, var_region); |
a7813a04 XL |
463 | |
464 | let typ = self.resolve_node_type(id); | |
465 | dropck::check_safety_of_destructor_if_necessary(self, typ, span, var_scope); | |
466 | }) | |
1a4d82fc JJ |
467 | } |
468 | } | |
469 | ||
476ff2be | 470 | impl<'a, 'gcx, 'tcx> Visitor<'gcx> for RegionCtxt<'a, 'gcx, 'tcx> { |
1a4d82fc JJ |
471 | // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local, |
472 | // However, right now we run into an issue whereby some free | |
473 | // regions are not properly related if they appear within the | |
474 | // types of arguments that must be inferred. This could be | |
475 | // addressed by deferring the construction of the region | |
476 | // hierarchy, and in particular the relationships between free | |
477 | // regions, until regionck, as described in #3238. | |
478 | ||
476ff2be | 479 | fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> { |
32a655c1 | 480 | NestedVisitorMap::None |
476ff2be SL |
481 | } |
482 | ||
32a655c1 SL |
483 | fn visit_fn(&mut self, _fk: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl, |
484 | b: hir::BodyId, span: Span, id: ast::NodeId) { | |
485 | let body = self.tcx.hir.body(b); | |
486 | self.visit_fn_body(id, body, span) | |
1a4d82fc JJ |
487 | } |
488 | ||
1a4d82fc JJ |
489 | //visit_pat: visit_pat, // (..) see above |
490 | ||
476ff2be | 491 | fn visit_arm(&mut self, arm: &'gcx hir::Arm) { |
a7813a04 XL |
492 | // see above |
493 | for p in &arm.pats { | |
494 | self.constrain_bindings_in_pat(p); | |
495 | } | |
496 | intravisit::walk_arm(self, arm); | |
1a4d82fc JJ |
497 | } |
498 | ||
476ff2be | 499 | fn visit_local(&mut self, l: &'gcx hir::Local) { |
a7813a04 XL |
500 | // see above |
501 | self.constrain_bindings_in_pat(&l.pat); | |
502 | self.link_local(l); | |
503 | intravisit::walk_local(self, l); | |
504 | } | |
1a4d82fc | 505 | |
476ff2be | 506 | fn visit_expr(&mut self, expr: &'gcx hir::Expr) { |
a7813a04 XL |
507 | debug!("regionck::visit_expr(e={:?}, repeating_scope={})", |
508 | expr, self.repeating_scope); | |
509 | ||
510 | // No matter what, the type of each expression must outlive the | |
511 | // scope of that expression. This also guarantees basic WF. | |
512 | let expr_ty = self.resolve_node_type(expr.id); | |
513 | // the region corresponding to this expression | |
9e0c209e | 514 | let expr_region = self.tcx.node_scope_region(expr.id); |
a7813a04 XL |
515 | self.type_must_outlive(infer::ExprTypeIsNotInScope(expr_ty, expr.span), |
516 | expr_ty, expr_region); | |
517 | ||
518 | let method_call = MethodCall::expr(expr.id); | |
519 | let opt_method_callee = self.tables.borrow().method_map.get(&method_call).cloned(); | |
520 | let has_method_map = opt_method_callee.is_some(); | |
521 | ||
522 | // If we are calling a method (either explicitly or via an | |
523 | // overloaded operator), check that all of the types provided as | |
524 | // arguments for its type parameters are well-formed, and all the regions | |
525 | // provided as arguments outlive the call. | |
526 | if let Some(callee) = opt_method_callee { | |
527 | let origin = match expr.node { | |
528 | hir::ExprMethodCall(..) => | |
529 | infer::ParameterOrigin::MethodCall, | |
530 | hir::ExprUnary(op, _) if op == hir::UnDeref => | |
531 | infer::ParameterOrigin::OverloadedDeref, | |
532 | _ => | |
533 | infer::ParameterOrigin::OverloadedOperator | |
534 | }; | |
1a4d82fc | 535 | |
a7813a04 XL |
536 | self.substs_wf_in_scope(origin, &callee.substs, expr.span, expr_region); |
537 | self.type_must_outlive(infer::ExprTypeIsNotInScope(callee.ty, expr.span), | |
538 | callee.ty, expr_region); | |
539 | } | |
1a4d82fc | 540 | |
a7813a04 XL |
541 | // Check any autoderefs or autorefs that appear. |
542 | let adjustment = self.tables.borrow().adjustments.get(&expr.id).map(|a| a.clone()); | |
543 | if let Some(adjustment) = adjustment { | |
544 | debug!("adjustment={:?}", adjustment); | |
c30ab7b3 SL |
545 | match adjustment.kind { |
546 | adjustment::Adjust::DerefRef { autoderefs, ref autoref, .. } => { | |
a7813a04 XL |
547 | let expr_ty = self.resolve_node_type(expr.id); |
548 | self.constrain_autoderefs(expr, autoderefs, expr_ty); | |
549 | if let Some(ref autoref) = *autoref { | |
550 | self.link_autoref(expr, autoderefs, autoref); | |
551 | ||
552 | // Require that the resulting region encompasses | |
553 | // the current node. | |
554 | // | |
555 | // FIXME(#6268) remove to support nested method calls | |
556 | self.type_of_node_must_outlive(infer::AutoBorrow(expr.span), | |
557 | expr.id, expr_region); | |
558 | } | |
559 | } | |
560 | /* | |
9e0c209e | 561 | adjustment::AutoObject(_, ref bounds, ..) => { |
a7813a04 XL |
562 | // Determine if we are casting `expr` to a trait |
563 | // instance. If so, we have to be sure that the type | |
564 | // of the source obeys the new region bound. | |
565 | let source_ty = self.resolve_node_type(expr.id); | |
566 | self.type_must_outlive(infer::RelateObjectBound(expr.span), | |
567 | source_ty, bounds.region_bound); | |
1a4d82fc | 568 | } |
a7813a04 XL |
569 | */ |
570 | _ => {} | |
1a4d82fc | 571 | } |
a7813a04 XL |
572 | |
573 | // If necessary, constrain destructors in the unadjusted form of this | |
574 | // expression. | |
575 | let cmt_result = { | |
576 | let mc = mc::MemCategorizationContext::new(self); | |
577 | mc.cat_expr_unadjusted(expr) | |
578 | }; | |
579 | match cmt_result { | |
580 | Ok(head_cmt) => { | |
581 | self.check_safety_of_rvalue_destructor_if_necessary(head_cmt, | |
582 | expr.span); | |
583 | } | |
584 | Err(..) => { | |
585 | self.tcx.sess.delay_span_bug(expr.span, "cat_expr_unadjusted Errd"); | |
586 | } | |
1a4d82fc | 587 | } |
1a4d82fc | 588 | } |
85aaf69f | 589 | |
a7813a04 XL |
590 | // If necessary, constrain destructors in this expression. This will be |
591 | // the adjusted form if there is an adjustment. | |
85aaf69f | 592 | let cmt_result = { |
a7813a04 XL |
593 | let mc = mc::MemCategorizationContext::new(self); |
594 | mc.cat_expr(expr) | |
85aaf69f SL |
595 | }; |
596 | match cmt_result { | |
597 | Ok(head_cmt) => { | |
a7813a04 | 598 | self.check_safety_of_rvalue_destructor_if_necessary(head_cmt, expr.span); |
85aaf69f SL |
599 | } |
600 | Err(..) => { | |
a7813a04 | 601 | self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd"); |
85aaf69f SL |
602 | } |
603 | } | |
85aaf69f | 604 | |
a7813a04 XL |
605 | debug!("regionck::visit_expr(e={:?}, repeating_scope={}) - visiting subexprs", |
606 | expr, self.repeating_scope); | |
607 | match expr.node { | |
476ff2be | 608 | hir::ExprPath(_) => { |
a7813a04 XL |
609 | self.fcx.opt_node_ty_substs(expr.id, |item_substs| { |
610 | let origin = infer::ParameterOrigin::Path; | |
611 | self.substs_wf_in_scope(origin, &item_substs.substs, expr.span, expr_region); | |
612 | }); | |
1a4d82fc JJ |
613 | } |
614 | ||
a7813a04 XL |
615 | hir::ExprCall(ref callee, ref args) => { |
616 | if has_method_map { | |
617 | self.constrain_call(expr, Some(&callee), | |
476ff2be | 618 | args.iter().map(|e| &*e), false); |
a7813a04 XL |
619 | } else { |
620 | self.constrain_callee(callee.id, expr, &callee); | |
621 | self.constrain_call(expr, None, | |
476ff2be | 622 | args.iter().map(|e| &*e), false); |
a7813a04 | 623 | } |
1a4d82fc | 624 | |
a7813a04 XL |
625 | intravisit::walk_expr(self, expr); |
626 | } | |
1a4d82fc | 627 | |
9e0c209e | 628 | hir::ExprMethodCall(.., ref args) => { |
a7813a04 | 629 | self.constrain_call(expr, Some(&args[0]), |
476ff2be | 630 | args[1..].iter().map(|e| &*e), false); |
1a4d82fc | 631 | |
a7813a04 | 632 | intravisit::walk_expr(self, expr); |
1a4d82fc JJ |
633 | } |
634 | ||
a7813a04 XL |
635 | hir::ExprAssignOp(_, ref lhs, ref rhs) => { |
636 | if has_method_map { | |
637 | self.constrain_call(expr, Some(&lhs), | |
638 | Some(&**rhs).into_iter(), false); | |
639 | } | |
1a4d82fc | 640 | |
a7813a04 XL |
641 | intravisit::walk_expr(self, expr); |
642 | } | |
1a4d82fc | 643 | |
a7813a04 XL |
644 | hir::ExprIndex(ref lhs, ref rhs) if has_method_map => { |
645 | self.constrain_call(expr, Some(&lhs), | |
646 | Some(&**rhs).into_iter(), true); | |
1a4d82fc | 647 | |
a7813a04 XL |
648 | intravisit::walk_expr(self, expr); |
649 | }, | |
1a4d82fc | 650 | |
a7813a04 XL |
651 | hir::ExprBinary(op, ref lhs, ref rhs) if has_method_map => { |
652 | let implicitly_ref_args = !op.node.is_by_value(); | |
1a4d82fc | 653 | |
a7813a04 XL |
654 | // As `expr_method_call`, but the call is via an |
655 | // overloaded op. Note that we (sadly) currently use an | |
656 | // implicit "by ref" sort of passing style here. This | |
657 | // should be converted to an adjustment! | |
658 | self.constrain_call(expr, Some(&lhs), | |
659 | Some(&**rhs).into_iter(), implicitly_ref_args); | |
1a4d82fc | 660 | |
a7813a04 | 661 | intravisit::walk_expr(self, expr); |
85aaf69f | 662 | } |
85aaf69f | 663 | |
a7813a04 XL |
664 | hir::ExprBinary(_, ref lhs, ref rhs) => { |
665 | // If you do `x OP y`, then the types of `x` and `y` must | |
666 | // outlive the operation you are performing. | |
667 | let lhs_ty = self.resolve_expr_type_adjusted(&lhs); | |
668 | let rhs_ty = self.resolve_expr_type_adjusted(&rhs); | |
669 | for &ty in &[lhs_ty, rhs_ty] { | |
670 | self.type_must_outlive(infer::Operand(expr.span), | |
671 | ty, expr_region); | |
672 | } | |
673 | intravisit::walk_expr(self, expr); | |
674 | } | |
1a4d82fc | 675 | |
a7813a04 XL |
676 | hir::ExprUnary(op, ref lhs) if has_method_map => { |
677 | let implicitly_ref_args = !op.is_by_value(); | |
1a4d82fc | 678 | |
a7813a04 XL |
679 | // As above. |
680 | self.constrain_call(expr, Some(&lhs), | |
681 | None::<hir::Expr>.iter(), implicitly_ref_args); | |
1a4d82fc | 682 | |
a7813a04 | 683 | intravisit::walk_expr(self, expr); |
1a4d82fc JJ |
684 | } |
685 | ||
a7813a04 XL |
686 | hir::ExprUnary(hir::UnDeref, ref base) => { |
687 | // For *a, the lifetime of a must enclose the deref | |
688 | let method_call = MethodCall::expr(expr.id); | |
689 | let base_ty = match self.tables.borrow().method_map.get(&method_call) { | |
690 | Some(method) => { | |
691 | self.constrain_call(expr, Some(&base), | |
692 | None::<hir::Expr>.iter(), true); | |
693 | // late-bound regions in overloaded method calls are instantiated | |
694 | let fn_ret = self.tcx.no_late_bound_regions(&method.ty.fn_ret()); | |
5bcae85e | 695 | fn_ret.unwrap() |
a7813a04 XL |
696 | } |
697 | None => self.resolve_node_type(base.id) | |
698 | }; | |
699 | if let ty::TyRef(r_ptr, _) = base_ty.sty { | |
9e0c209e | 700 | self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr); |
a7813a04 | 701 | } |
1a4d82fc | 702 | |
a7813a04 XL |
703 | intravisit::walk_expr(self, expr); |
704 | } | |
1a4d82fc | 705 | |
a7813a04 XL |
706 | hir::ExprIndex(ref vec_expr, _) => { |
707 | // For a[b], the lifetime of a must enclose the deref | |
708 | let vec_type = self.resolve_expr_type_adjusted(&vec_expr); | |
709 | self.constrain_index(expr, vec_type); | |
1a4d82fc | 710 | |
a7813a04 XL |
711 | intravisit::walk_expr(self, expr); |
712 | } | |
1a4d82fc | 713 | |
a7813a04 XL |
714 | hir::ExprCast(ref source, _) => { |
715 | // Determine if we are casting `source` to a trait | |
716 | // instance. If so, we have to be sure that the type of | |
717 | // the source obeys the trait's region bound. | |
718 | self.constrain_cast(expr, &source); | |
719 | intravisit::walk_expr(self, expr); | |
720 | } | |
1a4d82fc | 721 | |
a7813a04 XL |
722 | hir::ExprAddrOf(m, ref base) => { |
723 | self.link_addr_of(expr, m, &base); | |
724 | ||
725 | // Require that when you write a `&expr` expression, the | |
726 | // resulting pointer has a lifetime that encompasses the | |
727 | // `&expr` expression itself. Note that we constraining | |
728 | // the type of the node expr.id here *before applying | |
729 | // adjustments*. | |
730 | // | |
731 | // FIXME(#6268) nested method calls requires that this rule change | |
732 | let ty0 = self.resolve_node_type(expr.id); | |
733 | self.type_must_outlive(infer::AddrOf(expr.span), ty0, expr_region); | |
734 | intravisit::walk_expr(self, expr); | |
735 | } | |
1a4d82fc | 736 | |
a7813a04 XL |
737 | hir::ExprMatch(ref discr, ref arms, _) => { |
738 | self.link_match(&discr, &arms[..]); | |
1a4d82fc | 739 | |
a7813a04 XL |
740 | intravisit::walk_expr(self, expr); |
741 | } | |
1a4d82fc | 742 | |
476ff2be SL |
743 | hir::ExprClosure(.., body_id, _) => { |
744 | self.check_expr_fn_block(expr, body_id); | |
a7813a04 | 745 | } |
1a4d82fc | 746 | |
476ff2be | 747 | hir::ExprLoop(ref body, _, _) => { |
a7813a04 XL |
748 | let repeating_scope = self.set_repeating_scope(body.id); |
749 | intravisit::walk_expr(self, expr); | |
750 | self.set_repeating_scope(repeating_scope); | |
751 | } | |
1a4d82fc | 752 | |
a7813a04 XL |
753 | hir::ExprWhile(ref cond, ref body, _) => { |
754 | let repeating_scope = self.set_repeating_scope(cond.id); | |
755 | self.visit_expr(&cond); | |
1a4d82fc | 756 | |
a7813a04 XL |
757 | self.set_repeating_scope(body.id); |
758 | self.visit_block(&body); | |
1a4d82fc | 759 | |
a7813a04 XL |
760 | self.set_repeating_scope(repeating_scope); |
761 | } | |
1a4d82fc | 762 | |
a7813a04 XL |
763 | hir::ExprRet(Some(ref ret_expr)) => { |
764 | let call_site_scope = self.call_site_scope; | |
765 | debug!("visit_expr ExprRet ret_expr.id {} call_site_scope: {:?}", | |
766 | ret_expr.id, call_site_scope); | |
9e0c209e | 767 | let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope.unwrap())); |
a7813a04 XL |
768 | self.type_of_node_must_outlive(infer::CallReturn(ret_expr.span), |
769 | ret_expr.id, | |
9e0c209e | 770 | call_site_region); |
a7813a04 XL |
771 | intravisit::walk_expr(self, expr); |
772 | } | |
9cc50fc6 | 773 | |
a7813a04 XL |
774 | _ => { |
775 | intravisit::walk_expr(self, expr); | |
776 | } | |
1a4d82fc JJ |
777 | } |
778 | } | |
779 | } | |
780 | ||
a7813a04 XL |
781 | impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { |
782 | fn constrain_cast(&mut self, | |
783 | cast_expr: &hir::Expr, | |
784 | source_expr: &hir::Expr) | |
785 | { | |
786 | debug!("constrain_cast(cast_expr={:?}, source_expr={:?})", | |
787 | cast_expr, | |
788 | source_expr); | |
1a4d82fc | 789 | |
a7813a04 XL |
790 | let source_ty = self.resolve_node_type(source_expr.id); |
791 | let target_ty = self.resolve_node_type(cast_expr.id); | |
1a4d82fc | 792 | |
a7813a04 XL |
793 | self.walk_cast(cast_expr, source_ty, target_ty); |
794 | } | |
1a4d82fc | 795 | |
a7813a04 XL |
796 | fn walk_cast(&mut self, |
797 | cast_expr: &hir::Expr, | |
798 | from_ty: Ty<'tcx>, | |
799 | to_ty: Ty<'tcx>) { | |
62682a34 SL |
800 | debug!("walk_cast(from_ty={:?}, to_ty={:?})", |
801 | from_ty, | |
802 | to_ty); | |
1a4d82fc | 803 | match (&from_ty.sty, &to_ty.sty) { |
62682a34 SL |
804 | /*From:*/ (&ty::TyRef(from_r, ref from_mt), |
805 | /*To: */ &ty::TyRef(to_r, ref to_mt)) => { | |
1a4d82fc | 806 | // Target cannot outlive source, naturally. |
9e0c209e | 807 | self.sub_regions(infer::Reborrow(cast_expr.span), to_r, from_r); |
a7813a04 | 808 | self.walk_cast(cast_expr, from_mt.ty, to_mt.ty); |
1a4d82fc JJ |
809 | } |
810 | ||
811 | /*From:*/ (_, | |
476ff2be | 812 | /*To: */ &ty::TyDynamic(.., r)) => { |
1a4d82fc JJ |
813 | // When T is existentially quantified as a trait |
814 | // `Foo+'to`, it must outlive the region bound `'to`. | |
476ff2be | 815 | self.type_must_outlive(infer::RelateObjectBound(cast_expr.span), from_ty, r); |
1a4d82fc JJ |
816 | } |
817 | ||
32a655c1 SL |
818 | /*From:*/ (&ty::TyAdt(from_def, _), |
819 | /*To: */ &ty::TyAdt(to_def, _)) if from_def.is_box() && to_def.is_box() => { | |
820 | self.walk_cast(cast_expr, from_ty.boxed_ty(), to_ty.boxed_ty()); | |
1a4d82fc JJ |
821 | } |
822 | ||
823 | _ => { } | |
824 | } | |
825 | } | |
1a4d82fc | 826 | |
a7813a04 | 827 | fn check_expr_fn_block(&mut self, |
476ff2be | 828 | expr: &'gcx hir::Expr, |
32a655c1 SL |
829 | body_id: hir::BodyId) { |
830 | let repeating_scope = self.set_repeating_scope(body_id.node_id); | |
a7813a04 XL |
831 | intravisit::walk_expr(self, expr); |
832 | self.set_repeating_scope(repeating_scope); | |
833 | } | |
1a4d82fc | 834 | |
a7813a04 XL |
835 | fn constrain_callee(&mut self, |
836 | callee_id: ast::NodeId, | |
837 | _call_expr: &hir::Expr, | |
838 | _callee_expr: &hir::Expr) { | |
839 | let callee_ty = self.resolve_node_type(callee_id); | |
840 | match callee_ty.sty { | |
841 | ty::TyFnDef(..) | ty::TyFnPtr(_) => { } | |
842 | _ => { | |
843 | // this should not happen, but it does if the program is | |
844 | // erroneous | |
845 | // | |
846 | // bug!( | |
847 | // callee_expr.span, | |
848 | // "Calling non-function: {}", | |
849 | // callee_ty); | |
850 | } | |
1a4d82fc JJ |
851 | } |
852 | } | |
1a4d82fc | 853 | |
a7813a04 XL |
854 | fn constrain_call<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self, |
855 | call_expr: &hir::Expr, | |
856 | receiver: Option<&hir::Expr>, | |
857 | arg_exprs: I, | |
858 | implicitly_ref_args: bool) { | |
859 | //! Invoked on every call site (i.e., normal calls, method calls, | |
860 | //! and overloaded operators). Constrains the regions which appear | |
861 | //! in the type of the function. Also constrains the regions that | |
862 | //! appear in the arguments appropriately. | |
863 | ||
864 | debug!("constrain_call(call_expr={:?}, \ | |
865 | receiver={:?}, \ | |
866 | implicitly_ref_args={})", | |
867 | call_expr, | |
868 | receiver, | |
869 | implicitly_ref_args); | |
870 | ||
871 | // `callee_region` is the scope representing the time in which the | |
872 | // call occurs. | |
873 | // | |
874 | // FIXME(#6268) to support nested method calls, should be callee_id | |
875 | let callee_scope = self.tcx.region_maps.node_extent(call_expr.id); | |
9e0c209e | 876 | let callee_region = self.tcx.mk_region(ty::ReScope(callee_scope)); |
a7813a04 XL |
877 | |
878 | debug!("callee_region={:?}", callee_region); | |
879 | ||
880 | for arg_expr in arg_exprs { | |
881 | debug!("Argument: {:?}", arg_expr); | |
882 | ||
883 | // ensure that any regions appearing in the argument type are | |
884 | // valid for at least the lifetime of the function: | |
885 | self.type_of_node_must_outlive(infer::CallArg(arg_expr.span), | |
886 | arg_expr.id, callee_region); | |
887 | ||
888 | // unfortunately, there are two means of taking implicit | |
889 | // references, and we need to propagate constraints as a | |
890 | // result. modes are going away and the "DerefArgs" code | |
891 | // should be ported to use adjustments | |
892 | if implicitly_ref_args { | |
893 | self.link_by_ref(arg_expr, callee_scope); | |
894 | } | |
1a4d82fc | 895 | } |
1a4d82fc | 896 | |
a7813a04 XL |
897 | // as loop above, but for receiver |
898 | if let Some(r) = receiver { | |
899 | debug!("receiver: {:?}", r); | |
900 | self.type_of_node_must_outlive(infer::CallRcvr(r.span), | |
901 | r.id, callee_region); | |
902 | if implicitly_ref_args { | |
903 | self.link_by_ref(&r, callee_scope); | |
904 | } | |
1a4d82fc JJ |
905 | } |
906 | } | |
1a4d82fc | 907 | |
a7813a04 XL |
908 | /// Invoked on any auto-dereference that occurs. Checks that if this is a region pointer being |
909 | /// dereferenced, the lifetime of the pointer includes the deref expr. | |
910 | fn constrain_autoderefs(&mut self, | |
911 | deref_expr: &hir::Expr, | |
912 | derefs: usize, | |
913 | mut derefd_ty: Ty<'tcx>) | |
914 | { | |
915 | debug!("constrain_autoderefs(deref_expr={:?}, derefs={}, derefd_ty={:?})", | |
916 | deref_expr, | |
917 | derefs, | |
918 | derefd_ty); | |
1a4d82fc | 919 | |
9e0c209e | 920 | let r_deref_expr = self.tcx.node_scope_region(deref_expr.id); |
a7813a04 XL |
921 | for i in 0..derefs { |
922 | let method_call = MethodCall::autoderef(deref_expr.id, i as u32); | |
923 | debug!("constrain_autoderefs: method_call={:?} (of {:?} total)", method_call, derefs); | |
1a4d82fc | 924 | |
a7813a04 XL |
925 | let method = self.tables.borrow().method_map.get(&method_call).map(|m| m.clone()); |
926 | ||
927 | derefd_ty = match method { | |
928 | Some(method) => { | |
929 | debug!("constrain_autoderefs: #{} is overloaded, method={:?}", | |
930 | i, method); | |
931 | ||
932 | let origin = infer::ParameterOrigin::OverloadedDeref; | |
933 | self.substs_wf_in_scope(origin, method.substs, deref_expr.span, r_deref_expr); | |
934 | ||
c30ab7b3 | 935 | // Treat overloaded autoderefs as if an AutoBorrow adjustment |
a7813a04 XL |
936 | // was applied on the base type, as that is always the case. |
937 | let fn_sig = method.ty.fn_sig(); | |
938 | let fn_sig = // late-bound regions should have been instantiated | |
939 | self.tcx.no_late_bound_regions(fn_sig).unwrap(); | |
476ff2be | 940 | let self_ty = fn_sig.inputs()[0]; |
a7813a04 XL |
941 | let (m, r) = match self_ty.sty { |
942 | ty::TyRef(r, ref m) => (m.mutbl, r), | |
943 | _ => { | |
944 | span_bug!( | |
945 | deref_expr.span, | |
946 | "bad overloaded deref type {:?}", | |
947 | method.ty) | |
948 | } | |
949 | }; | |
950 | ||
951 | debug!("constrain_autoderefs: receiver r={:?} m={:?}", | |
952 | r, m); | |
953 | ||
954 | { | |
955 | let mc = mc::MemCategorizationContext::new(self); | |
956 | let self_cmt = ignore_err!(mc.cat_expr_autoderefd(deref_expr, i)); | |
957 | debug!("constrain_autoderefs: self_cmt={:?}", | |
958 | self_cmt); | |
959 | self.link_region(deref_expr.span, r, | |
960 | ty::BorrowKind::from_mutbl(m), self_cmt); | |
961 | } | |
1a4d82fc | 962 | |
a7813a04 XL |
963 | // Specialized version of constrain_call. |
964 | self.type_must_outlive(infer::CallRcvr(deref_expr.span), | |
965 | self_ty, r_deref_expr); | |
5bcae85e | 966 | self.type_must_outlive(infer::CallReturn(deref_expr.span), |
476ff2be SL |
967 | fn_sig.output(), r_deref_expr); |
968 | fn_sig.output() | |
1a4d82fc | 969 | } |
a7813a04 XL |
970 | None => derefd_ty |
971 | }; | |
1a4d82fc | 972 | |
a7813a04 XL |
973 | if let ty::TyRef(r_ptr, _) = derefd_ty.sty { |
974 | self.mk_subregion_due_to_dereference(deref_expr.span, | |
9e0c209e | 975 | r_deref_expr, r_ptr); |
a7813a04 | 976 | } |
1a4d82fc | 977 | |
a7813a04 XL |
978 | match derefd_ty.builtin_deref(true, ty::NoPreference) { |
979 | Some(mt) => derefd_ty = mt.ty, | |
980 | /* if this type can't be dereferenced, then there's already an error | |
981 | in the session saying so. Just bail out for now */ | |
982 | None => break | |
983 | } | |
1a4d82fc JJ |
984 | } |
985 | } | |
1a4d82fc | 986 | |
a7813a04 XL |
987 | pub fn mk_subregion_due_to_dereference(&mut self, |
988 | deref_span: Span, | |
9e0c209e SL |
989 | minimum_lifetime: &'tcx ty::Region, |
990 | maximum_lifetime: &'tcx ty::Region) { | |
a7813a04 XL |
991 | self.sub_regions(infer::DerefPointer(deref_span), |
992 | minimum_lifetime, maximum_lifetime) | |
993 | } | |
1a4d82fc | 994 | |
a7813a04 XL |
995 | fn check_safety_of_rvalue_destructor_if_necessary(&mut self, |
996 | cmt: mc::cmt<'tcx>, | |
997 | span: Span) { | |
998 | match cmt.cat { | |
32a655c1 | 999 | Categorization::Rvalue(region, _) => { |
9e0c209e | 1000 | match *region { |
a7813a04 XL |
1001 | ty::ReScope(rvalue_scope) => { |
1002 | let typ = self.resolve_type(cmt.ty); | |
1003 | dropck::check_safety_of_destructor_if_necessary(self, | |
1004 | typ, | |
1005 | span, | |
1006 | rvalue_scope); | |
1007 | } | |
1008 | ty::ReStatic => {} | |
9e0c209e | 1009 | _ => { |
a7813a04 XL |
1010 | span_bug!(span, |
1011 | "unexpected rvalue region in rvalue \ | |
1012 | destructor safety checking: `{:?}`", | |
1013 | region); | |
1014 | } | |
85aaf69f SL |
1015 | } |
1016 | } | |
a7813a04 | 1017 | _ => {} |
85aaf69f | 1018 | } |
85aaf69f | 1019 | } |
1a4d82fc | 1020 | |
a7813a04 XL |
1021 | /// Invoked on any index expression that occurs. Checks that if this is a slice |
1022 | /// being indexed, the lifetime of the pointer includes the deref expr. | |
1023 | fn constrain_index(&mut self, | |
1024 | index_expr: &hir::Expr, | |
1025 | indexed_ty: Ty<'tcx>) | |
1026 | { | |
1027 | debug!("constrain_index(index_expr=?, indexed_ty={}", | |
1028 | self.ty_to_string(indexed_ty)); | |
1029 | ||
1030 | let r_index_expr = ty::ReScope(self.tcx.region_maps.node_extent(index_expr.id)); | |
1031 | if let ty::TyRef(r_ptr, mt) = indexed_ty.sty { | |
1032 | match mt.ty.sty { | |
1033 | ty::TySlice(_) | ty::TyStr => { | |
1034 | self.sub_regions(infer::IndexSlice(index_expr.span), | |
9e0c209e | 1035 | self.tcx.mk_region(r_index_expr), r_ptr); |
a7813a04 XL |
1036 | } |
1037 | _ => {} | |
1a4d82fc | 1038 | } |
1a4d82fc JJ |
1039 | } |
1040 | } | |
1a4d82fc | 1041 | |
a7813a04 XL |
1042 | /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying |
1043 | /// adjustments) are valid for at least `minimum_lifetime` | |
1044 | fn type_of_node_must_outlive(&mut self, | |
1045 | origin: infer::SubregionOrigin<'tcx>, | |
1046 | id: ast::NodeId, | |
9e0c209e | 1047 | minimum_lifetime: &'tcx ty::Region) |
a7813a04 | 1048 | { |
a7813a04 XL |
1049 | // Try to resolve the type. If we encounter an error, then typeck |
1050 | // is going to fail anyway, so just stop here and let typeck | |
1051 | // report errors later on in the writeback phase. | |
1052 | let ty0 = self.resolve_node_type(id); | |
c30ab7b3 SL |
1053 | let ty = self.tables.borrow().adjustments.get(&id).map_or(ty0, |adj| adj.target); |
1054 | let ty = self.resolve_type(ty); | |
a7813a04 XL |
1055 | debug!("constrain_regions_in_type_of_node(\ |
1056 | ty={}, ty0={}, id={}, minimum_lifetime={:?})", | |
1057 | ty, ty0, | |
1058 | id, minimum_lifetime); | |
1059 | self.type_must_outlive(origin, ty, minimum_lifetime); | |
1060 | } | |
1a4d82fc | 1061 | |
a7813a04 XL |
1062 | /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the |
1063 | /// resulting pointer is linked to the lifetime of its guarantor (if any). | |
1064 | fn link_addr_of(&mut self, expr: &hir::Expr, | |
1065 | mutability: hir::Mutability, base: &hir::Expr) { | |
1066 | debug!("link_addr_of(expr={:?}, base={:?})", expr, base); | |
1a4d82fc | 1067 | |
a7813a04 XL |
1068 | let cmt = { |
1069 | let mc = mc::MemCategorizationContext::new(self); | |
1070 | ignore_err!(mc.cat_expr(base)) | |
1071 | }; | |
1a4d82fc | 1072 | |
a7813a04 | 1073 | debug!("link_addr_of: cmt={:?}", cmt); |
1a4d82fc | 1074 | |
a7813a04 XL |
1075 | self.link_region_from_node_type(expr.span, expr.id, mutability, cmt); |
1076 | } | |
1a4d82fc | 1077 | |
a7813a04 XL |
1078 | /// Computes the guarantors for any ref bindings in a `let` and |
1079 | /// then ensures that the lifetime of the resulting pointer is | |
1080 | /// linked to the lifetime of the initialization expression. | |
1081 | fn link_local(&self, local: &hir::Local) { | |
1082 | debug!("regionck::for_local()"); | |
1083 | let init_expr = match local.init { | |
1084 | None => { return; } | |
1085 | Some(ref expr) => &**expr, | |
1086 | }; | |
1087 | let mc = mc::MemCategorizationContext::new(self); | |
1088 | let discr_cmt = ignore_err!(mc.cat_expr(init_expr)); | |
1089 | self.link_pattern(mc, discr_cmt, &local.pat); | |
1090 | } | |
1a4d82fc | 1091 | |
a7813a04 XL |
1092 | /// Computes the guarantors for any ref bindings in a match and |
1093 | /// then ensures that the lifetime of the resulting pointer is | |
1094 | /// linked to the lifetime of its guarantor (if any). | |
1095 | fn link_match(&self, discr: &hir::Expr, arms: &[hir::Arm]) { | |
1096 | debug!("regionck::for_match()"); | |
1097 | let mc = mc::MemCategorizationContext::new(self); | |
1098 | let discr_cmt = ignore_err!(mc.cat_expr(discr)); | |
1099 | debug!("discr_cmt={:?}", discr_cmt); | |
1100 | for arm in arms { | |
1101 | for root_pat in &arm.pats { | |
1102 | self.link_pattern(mc, discr_cmt.clone(), &root_pat); | |
1103 | } | |
1a4d82fc JJ |
1104 | } |
1105 | } | |
1a4d82fc | 1106 | |
a7813a04 XL |
1107 | /// Computes the guarantors for any ref bindings in a match and |
1108 | /// then ensures that the lifetime of the resulting pointer is | |
1109 | /// linked to the lifetime of its guarantor (if any). | |
1110 | fn link_fn_args(&self, body_scope: CodeExtent, args: &[hir::Arg]) { | |
1111 | debug!("regionck::link_fn_args(body_scope={:?})", body_scope); | |
1112 | let mc = mc::MemCategorizationContext::new(self); | |
1113 | for arg in args { | |
1114 | let arg_ty = self.node_ty(arg.id); | |
9e0c209e | 1115 | let re_scope = self.tcx.mk_region(ty::ReScope(body_scope)); |
32a655c1 SL |
1116 | let arg_cmt = mc.cat_rvalue( |
1117 | arg.id, arg.pat.span, re_scope, re_scope, arg_ty); | |
a7813a04 XL |
1118 | debug!("arg_ty={:?} arg_cmt={:?} arg={:?}", |
1119 | arg_ty, | |
1120 | arg_cmt, | |
1121 | arg); | |
1122 | self.link_pattern(mc, arg_cmt, &arg.pat); | |
1123 | } | |
1a4d82fc | 1124 | } |
1a4d82fc | 1125 | |
a7813a04 XL |
1126 | /// Link lifetimes of any ref bindings in `root_pat` to the pointers found |
1127 | /// in the discriminant, if needed. | |
1128 | fn link_pattern<'t>(&self, | |
1129 | mc: mc::MemCategorizationContext<'a, 'gcx, 'tcx>, | |
1130 | discr_cmt: mc::cmt<'tcx>, | |
1131 | root_pat: &hir::Pat) { | |
1132 | debug!("link_pattern(discr_cmt={:?}, root_pat={:?})", | |
1133 | discr_cmt, | |
1134 | root_pat); | |
3157f602 | 1135 | let _ = mc.cat_pattern(discr_cmt, root_pat, |_, sub_cmt, sub_pat| { |
a7813a04 XL |
1136 | match sub_pat.node { |
1137 | // `ref x` pattern | |
9e0c209e | 1138 | PatKind::Binding(hir::BindByRef(mutbl), ..) => { |
a7813a04 XL |
1139 | self.link_region_from_node_type(sub_pat.span, sub_pat.id, |
1140 | mutbl, sub_cmt); | |
1141 | } | |
a7813a04 | 1142 | _ => {} |
1a4d82fc | 1143 | } |
a7813a04 XL |
1144 | }); |
1145 | } | |
1a4d82fc | 1146 | |
a7813a04 XL |
1147 | /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being |
1148 | /// autoref'd. | |
1149 | fn link_autoref(&self, | |
1150 | expr: &hir::Expr, | |
1151 | autoderefs: usize, | |
c30ab7b3 | 1152 | autoref: &adjustment::AutoBorrow<'tcx>) |
a7813a04 | 1153 | { |
476ff2be | 1154 | debug!("link_autoref(autoderefs={}, autoref={:?})", autoderefs, autoref); |
a7813a04 XL |
1155 | let mc = mc::MemCategorizationContext::new(self); |
1156 | let expr_cmt = ignore_err!(mc.cat_expr_autoderefd(expr, autoderefs)); | |
1157 | debug!("expr_cmt={:?}", expr_cmt); | |
1158 | ||
1159 | match *autoref { | |
c30ab7b3 | 1160 | adjustment::AutoBorrow::Ref(r, m) => { |
a7813a04 XL |
1161 | self.link_region(expr.span, r, |
1162 | ty::BorrowKind::from_mutbl(m), expr_cmt); | |
1163 | } | |
1a4d82fc | 1164 | |
c30ab7b3 | 1165 | adjustment::AutoBorrow::RawPtr(m) => { |
9e0c209e SL |
1166 | let r = self.tcx.node_scope_region(expr.id); |
1167 | self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m), expr_cmt); | |
a7813a04 | 1168 | } |
9346a6ac | 1169 | } |
1a4d82fc | 1170 | } |
1a4d82fc | 1171 | |
a7813a04 XL |
1172 | /// Computes the guarantor for cases where the `expr` is being passed by implicit reference and |
1173 | /// must outlive `callee_scope`. | |
1174 | fn link_by_ref(&self, | |
1175 | expr: &hir::Expr, | |
1176 | callee_scope: CodeExtent) { | |
1177 | debug!("link_by_ref(expr={:?}, callee_scope={:?})", | |
1178 | expr, callee_scope); | |
1179 | let mc = mc::MemCategorizationContext::new(self); | |
1180 | let expr_cmt = ignore_err!(mc.cat_expr(expr)); | |
9e0c209e SL |
1181 | let borrow_region = self.tcx.mk_region(ty::ReScope(callee_scope)); |
1182 | self.link_region(expr.span, borrow_region, ty::ImmBorrow, expr_cmt); | |
a7813a04 | 1183 | } |
1a4d82fc | 1184 | |
a7813a04 XL |
1185 | /// Like `link_region()`, except that the region is extracted from the type of `id`, |
1186 | /// which must be some reference (`&T`, `&str`, etc). | |
1187 | fn link_region_from_node_type(&self, | |
1188 | span: Span, | |
1189 | id: ast::NodeId, | |
1190 | mutbl: hir::Mutability, | |
1191 | cmt_borrowed: mc::cmt<'tcx>) { | |
1192 | debug!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})", | |
1193 | id, mutbl, cmt_borrowed); | |
1194 | ||
1195 | let rptr_ty = self.resolve_node_type(id); | |
9e0c209e | 1196 | if let ty::TyRef(r, _) = rptr_ty.sty { |
a7813a04 | 1197 | debug!("rptr_ty={}", rptr_ty); |
9e0c209e | 1198 | self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl), |
a7813a04 XL |
1199 | cmt_borrowed); |
1200 | } | |
1a4d82fc | 1201 | } |
1a4d82fc | 1202 | |
a7813a04 XL |
1203 | /// Informs the inference engine that `borrow_cmt` is being borrowed with |
1204 | /// kind `borrow_kind` and lifetime `borrow_region`. | |
1205 | /// In order to ensure borrowck is satisfied, this may create constraints | |
1206 | /// between regions, as explained in `link_reborrowed_region()`. | |
1207 | fn link_region(&self, | |
1208 | span: Span, | |
9e0c209e | 1209 | borrow_region: &'tcx ty::Region, |
a7813a04 XL |
1210 | borrow_kind: ty::BorrowKind, |
1211 | borrow_cmt: mc::cmt<'tcx>) { | |
1212 | let mut borrow_cmt = borrow_cmt; | |
1213 | let mut borrow_kind = borrow_kind; | |
1214 | ||
1215 | let origin = infer::DataBorrowed(borrow_cmt.ty, span); | |
9e0c209e | 1216 | self.type_must_outlive(origin, borrow_cmt.ty, borrow_region); |
a7813a04 XL |
1217 | |
1218 | loop { | |
1219 | debug!("link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})", | |
1220 | borrow_region, | |
1221 | borrow_kind, | |
1222 | borrow_cmt); | |
1223 | match borrow_cmt.cat.clone() { | |
1224 | Categorization::Deref(ref_cmt, _, | |
1225 | mc::Implicit(ref_kind, ref_region)) | | |
1226 | Categorization::Deref(ref_cmt, _, | |
1227 | mc::BorrowedPtr(ref_kind, ref_region)) => { | |
1228 | match self.link_reborrowed_region(span, | |
1229 | borrow_region, borrow_kind, | |
1230 | ref_cmt, ref_region, ref_kind, | |
1231 | borrow_cmt.note) { | |
1232 | Some((c, k)) => { | |
1233 | borrow_cmt = c; | |
1234 | borrow_kind = k; | |
1235 | } | |
1236 | None => { | |
1237 | return; | |
1238 | } | |
1239 | } | |
1240 | } | |
1a4d82fc | 1241 | |
a7813a04 XL |
1242 | Categorization::Downcast(cmt_base, _) | |
1243 | Categorization::Deref(cmt_base, _, mc::Unique) | | |
1244 | Categorization::Interior(cmt_base, _) => { | |
1245 | // Borrowing interior or owned data requires the base | |
1246 | // to be valid and borrowable in the same fashion. | |
1247 | borrow_cmt = cmt_base; | |
1248 | borrow_kind = borrow_kind; | |
1249 | } | |
e9174d1e | 1250 | |
9e0c209e | 1251 | Categorization::Deref(.., mc::UnsafePtr(..)) | |
a7813a04 XL |
1252 | Categorization::StaticItem | |
1253 | Categorization::Upvar(..) | | |
1254 | Categorization::Local(..) | | |
1255 | Categorization::Rvalue(..) => { | |
1256 | // These are all "base cases" with independent lifetimes | |
1257 | // that are not subject to inference | |
1258 | return; | |
1259 | } | |
1260 | } | |
1261 | } | |
1262 | } | |
1263 | ||
1264 | /// This is the most complicated case: the path being borrowed is | |
1265 | /// itself the referent of a borrowed pointer. Let me give an | |
1266 | /// example fragment of code to make clear(er) the situation: | |
1267 | /// | |
1268 | /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a | |
1269 | /// ... | |
1270 | /// &'z *r // the reborrow has lifetime 'z | |
1271 | /// | |
1272 | /// Now, in this case, our primary job is to add the inference | |
1273 | /// constraint that `'z <= 'a`. Given this setup, let's clarify the | |
1274 | /// parameters in (roughly) terms of the example: | |
1275 | /// | |
1276 | /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T` | |
1277 | /// borrow_region ^~ ref_region ^~ | |
1278 | /// borrow_kind ^~ ref_kind ^~ | |
1279 | /// ref_cmt ^ | |
1280 | /// | |
1281 | /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc). | |
1282 | /// | |
1283 | /// Unfortunately, there are some complications beyond the simple | |
1284 | /// scenario I just painted: | |
1285 | /// | |
1286 | /// 1. The reference `r` might in fact be a "by-ref" upvar. In that | |
1287 | /// case, we have two jobs. First, we are inferring whether this reference | |
1288 | /// should be an `&T`, `&mut T`, or `&uniq T` reference, and we must | |
1289 | /// adjust that based on this borrow (e.g., if this is an `&mut` borrow, | |
1290 | /// then `r` must be an `&mut` reference). Second, whenever we link | |
1291 | /// two regions (here, `'z <= 'a`), we supply a *cause*, and in this | |
1292 | /// case we adjust the cause to indicate that the reference being | |
1293 | /// "reborrowed" is itself an upvar. This provides a nicer error message | |
1294 | /// should something go wrong. | |
1295 | /// | |
1296 | /// 2. There may in fact be more levels of reborrowing. In the | |
1297 | /// example, I said the borrow was like `&'z *r`, but it might | |
1298 | /// in fact be a borrow like `&'z **q` where `q` has type `&'a | |
1299 | /// &'b mut T`. In that case, we want to ensure that `'z <= 'a` | |
1300 | /// and `'z <= 'b`. This is explained more below. | |
1301 | /// | |
1302 | /// The return value of this function indicates whether we need to | |
1303 | /// recurse and process `ref_cmt` (see case 2 above). | |
1304 | fn link_reborrowed_region(&self, | |
1305 | span: Span, | |
9e0c209e | 1306 | borrow_region: &'tcx ty::Region, |
a7813a04 XL |
1307 | borrow_kind: ty::BorrowKind, |
1308 | ref_cmt: mc::cmt<'tcx>, | |
9e0c209e | 1309 | ref_region: &'tcx ty::Region, |
a7813a04 XL |
1310 | mut ref_kind: ty::BorrowKind, |
1311 | note: mc::Note) | |
1312 | -> Option<(mc::cmt<'tcx>, ty::BorrowKind)> | |
1313 | { | |
1314 | // Possible upvar ID we may need later to create an entry in the | |
1315 | // maybe link map. | |
1316 | ||
1317 | // Detect by-ref upvar `x`: | |
1318 | let cause = match note { | |
1319 | mc::NoteUpvarRef(ref upvar_id) => { | |
1320 | let upvar_capture_map = &self.tables.borrow_mut().upvar_capture_map; | |
1321 | match upvar_capture_map.get(upvar_id) { | |
1322 | Some(&ty::UpvarCapture::ByRef(ref upvar_borrow)) => { | |
1323 | // The mutability of the upvar may have been modified | |
1324 | // by the above adjustment, so update our local variable. | |
1325 | ref_kind = upvar_borrow.kind; | |
1326 | ||
1327 | infer::ReborrowUpvar(span, *upvar_id) | |
1a4d82fc | 1328 | } |
a7813a04 XL |
1329 | _ => { |
1330 | span_bug!( span, "Illegal upvar id: {:?}", upvar_id); | |
1a4d82fc JJ |
1331 | } |
1332 | } | |
1333 | } | |
a7813a04 XL |
1334 | mc::NoteClosureEnv(ref upvar_id) => { |
1335 | // We don't have any mutability changes to propagate, but | |
1336 | // we do want to note that an upvar reborrow caused this | |
1337 | // link | |
1338 | infer::ReborrowUpvar(span, *upvar_id) | |
1339 | } | |
1340 | _ => { | |
1341 | infer::Reborrow(span) | |
1342 | } | |
1343 | }; | |
1a4d82fc | 1344 | |
a7813a04 XL |
1345 | debug!("link_reborrowed_region: {:?} <= {:?}", |
1346 | borrow_region, | |
1347 | ref_region); | |
9e0c209e | 1348 | self.sub_regions(cause, borrow_region, ref_region); |
a7813a04 XL |
1349 | |
1350 | // If we end up needing to recurse and establish a region link | |
1351 | // with `ref_cmt`, calculate what borrow kind we will end up | |
1352 | // needing. This will be used below. | |
1353 | // | |
1354 | // One interesting twist is that we can weaken the borrow kind | |
1355 | // when we recurse: to reborrow an `&mut` referent as mutable, | |
1356 | // borrowck requires a unique path to the `&mut` reference but not | |
1357 | // necessarily a *mutable* path. | |
1358 | let new_borrow_kind = match borrow_kind { | |
1359 | ty::ImmBorrow => | |
1360 | ty::ImmBorrow, | |
1361 | ty::MutBorrow | ty::UniqueImmBorrow => | |
1362 | ty::UniqueImmBorrow | |
1363 | }; | |
1364 | ||
1365 | // Decide whether we need to recurse and link any regions within | |
1366 | // the `ref_cmt`. This is concerned for the case where the value | |
1367 | // being reborrowed is in fact a borrowed pointer found within | |
1368 | // another borrowed pointer. For example: | |
1369 | // | |
1370 | // let p: &'b &'a mut T = ...; | |
1371 | // ... | |
1372 | // &'z **p | |
1373 | // | |
1374 | // What makes this case particularly tricky is that, if the data | |
1375 | // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires | |
1376 | // not only that `'z <= 'a`, (as before) but also `'z <= 'b` | |
1377 | // (otherwise the user might mutate through the `&mut T` reference | |
1378 | // after `'b` expires and invalidate the borrow we are looking at | |
1379 | // now). | |
1380 | // | |
1381 | // So let's re-examine our parameters in light of this more | |
1382 | // complicated (possible) scenario: | |
1383 | // | |
1384 | // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T` | |
1385 | // borrow_region ^~ ref_region ^~ | |
1386 | // borrow_kind ^~ ref_kind ^~ | |
1387 | // ref_cmt ^~~ | |
1388 | // | |
1389 | // (Note that since we have not examined `ref_cmt.cat`, we don't | |
1390 | // know whether this scenario has occurred; but I wanted to show | |
1391 | // how all the types get adjusted.) | |
1392 | match ref_kind { | |
1393 | ty::ImmBorrow => { | |
1394 | // The reference being reborrowed is a sharable ref of | |
1395 | // type `&'a T`. In this case, it doesn't matter where we | |
1396 | // *found* the `&T` pointer, the memory it references will | |
1397 | // be valid and immutable for `'a`. So we can stop here. | |
1398 | // | |
1399 | // (Note that the `borrow_kind` must also be ImmBorrow or | |
1400 | // else the user is borrowed imm memory as mut memory, | |
1401 | // which means they'll get an error downstream in borrowck | |
1402 | // anyhow.) | |
1403 | return None; | |
1a4d82fc JJ |
1404 | } |
1405 | ||
a7813a04 XL |
1406 | ty::MutBorrow | ty::UniqueImmBorrow => { |
1407 | // The reference being reborrowed is either an `&mut T` or | |
1408 | // `&uniq T`. This is the case where recursion is needed. | |
1409 | return Some((ref_cmt, new_borrow_kind)); | |
1a4d82fc JJ |
1410 | } |
1411 | } | |
1412 | } | |
1a4d82fc | 1413 | |
a7813a04 XL |
1414 | /// Checks that the values provided for type/region arguments in a given |
1415 | /// expression are well-formed and in-scope. | |
1416 | fn substs_wf_in_scope(&mut self, | |
1417 | origin: infer::ParameterOrigin, | |
1418 | substs: &Substs<'tcx>, | |
1419 | expr_span: Span, | |
9e0c209e | 1420 | expr_region: &'tcx ty::Region) { |
a7813a04 XL |
1421 | debug!("substs_wf_in_scope(substs={:?}, \ |
1422 | expr_region={:?}, \ | |
1423 | origin={:?}, \ | |
1424 | expr_span={:?})", | |
1425 | substs, expr_region, origin, expr_span); | |
1426 | ||
1427 | let origin = infer::ParameterInScope(origin, expr_span); | |
1428 | ||
9e0c209e | 1429 | for region in substs.regions() { |
a7813a04 | 1430 | self.sub_regions(origin.clone(), expr_region, region); |
1a4d82fc JJ |
1431 | } |
1432 | ||
9e0c209e | 1433 | for ty in substs.types() { |
a7813a04 XL |
1434 | let ty = self.resolve_type(ty); |
1435 | self.type_must_outlive(origin.clone(), ty, expr_region); | |
1a4d82fc JJ |
1436 | } |
1437 | } | |
1a4d82fc | 1438 | |
a7813a04 XL |
1439 | /// Ensures that type is well-formed in `region`, which implies (among |
1440 | /// other things) that all borrowed data reachable via `ty` outlives | |
1441 | /// `region`. | |
1442 | pub fn type_must_outlive(&self, | |
1443 | origin: infer::SubregionOrigin<'tcx>, | |
1444 | ty: Ty<'tcx>, | |
9e0c209e | 1445 | region: &'tcx ty::Region) |
a7813a04 XL |
1446 | { |
1447 | let ty = self.resolve_type(ty); | |
e9174d1e | 1448 | |
a7813a04 XL |
1449 | debug!("type_must_outlive(ty={:?}, region={:?}, origin={:?})", |
1450 | ty, | |
1451 | region, | |
1452 | origin); | |
e9174d1e | 1453 | |
a7813a04 | 1454 | assert!(!ty.has_escaping_regions()); |
e9174d1e | 1455 | |
c30ab7b3 | 1456 | let components = self.tcx.outlives_components(ty); |
a7813a04 XL |
1457 | self.components_must_outlive(origin, components, region); |
1458 | } | |
1459 | ||
1460 | fn components_must_outlive(&self, | |
1461 | origin: infer::SubregionOrigin<'tcx>, | |
1462 | components: Vec<ty::outlives::Component<'tcx>>, | |
9e0c209e | 1463 | region: &'tcx ty::Region) |
a7813a04 XL |
1464 | { |
1465 | for component in components { | |
1466 | let origin = origin.clone(); | |
1467 | match component { | |
1468 | ty::outlives::Component::Region(region1) => { | |
1469 | self.sub_regions(origin, region, region1); | |
1470 | } | |
1471 | ty::outlives::Component::Param(param_ty) => { | |
1472 | self.param_ty_must_outlive(origin, region, param_ty); | |
1473 | } | |
1474 | ty::outlives::Component::Projection(projection_ty) => { | |
1475 | self.projection_must_outlive(origin, region, projection_ty); | |
1476 | } | |
1477 | ty::outlives::Component::EscapingProjection(subcomponents) => { | |
1478 | self.components_must_outlive(origin, subcomponents, region); | |
1479 | } | |
1480 | ty::outlives::Component::UnresolvedInferenceVariable(v) => { | |
1481 | // ignore this, we presume it will yield an error | |
1482 | // later, since if a type variable is not resolved by | |
1483 | // this point it never will be | |
1484 | self.tcx.sess.delay_span_bug( | |
1485 | origin.span(), | |
1486 | &format!("unresolved inference variable in outlives: {:?}", v)); | |
1487 | } | |
1a4d82fc JJ |
1488 | } |
1489 | } | |
1490 | } | |
1a4d82fc | 1491 | |
a7813a04 XL |
1492 | fn param_ty_must_outlive(&self, |
1493 | origin: infer::SubregionOrigin<'tcx>, | |
9e0c209e | 1494 | region: &'tcx ty::Region, |
a7813a04 XL |
1495 | param_ty: ty::ParamTy) { |
1496 | debug!("param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})", | |
1497 | region, param_ty, origin); | |
1a4d82fc | 1498 | |
a7813a04 XL |
1499 | let verify_bound = self.param_bound(param_ty); |
1500 | let generic = GenericKind::Param(param_ty); | |
1501 | self.verify_generic_bound(origin, generic, region, verify_bound); | |
e9174d1e | 1502 | } |
85aaf69f | 1503 | |
a7813a04 XL |
1504 | fn projection_must_outlive(&self, |
1505 | origin: infer::SubregionOrigin<'tcx>, | |
9e0c209e | 1506 | region: &'tcx ty::Region, |
a7813a04 XL |
1507 | projection_ty: ty::ProjectionTy<'tcx>) |
1508 | { | |
1509 | debug!("projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})", | |
1510 | region, projection_ty, origin); | |
1511 | ||
1512 | // This case is thorny for inference. The fundamental problem is | |
1513 | // that there are many cases where we have choice, and inference | |
1514 | // doesn't like choice (the current region inference in | |
1515 | // particular). :) First off, we have to choose between using the | |
1516 | // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and | |
1517 | // OutlivesProjectionComponent rules, any one of which is | |
1518 | // sufficient. If there are no inference variables involved, it's | |
1519 | // not hard to pick the right rule, but if there are, we're in a | |
1520 | // bit of a catch 22: if we picked which rule we were going to | |
1521 | // use, we could add constraints to the region inference graph | |
1522 | // that make it apply, but if we don't add those constraints, the | |
1523 | // rule might not apply (but another rule might). For now, we err | |
1524 | // on the side of adding too few edges into the graph. | |
1525 | ||
1526 | // Compute the bounds we can derive from the environment or trait | |
1527 | // definition. We know that the projection outlives all the | |
1528 | // regions in this list. | |
1529 | let env_bounds = self.projection_declared_bounds(origin.span(), projection_ty); | |
1530 | ||
1531 | debug!("projection_must_outlive: env_bounds={:?}", | |
1532 | env_bounds); | |
1533 | ||
1534 | // If we know that the projection outlives 'static, then we're | |
1535 | // done here. | |
9e0c209e | 1536 | if env_bounds.contains(&&ty::ReStatic) { |
a7813a04 XL |
1537 | debug!("projection_must_outlive: 'static as declared bound"); |
1538 | return; | |
e9174d1e SL |
1539 | } |
1540 | ||
a7813a04 XL |
1541 | // If declared bounds list is empty, the only applicable rule is |
1542 | // OutlivesProjectionComponent. If there are inference variables, | |
1543 | // then, we can break down the outlives into more primitive | |
1544 | // components without adding unnecessary edges. | |
1545 | // | |
1546 | // If there are *no* inference variables, however, we COULD do | |
1547 | // this, but we choose not to, because the error messages are less | |
1548 | // good. For example, a requirement like `T::Item: 'r` would be | |
1549 | // translated to a requirement that `T: 'r`; when this is reported | |
1550 | // to the user, it will thus say "T: 'r must hold so that T::Item: | |
1551 | // 'r holds". But that makes it sound like the only way to fix | |
1552 | // the problem is to add `T: 'r`, which isn't true. So, if there are no | |
1553 | // inference variables, we use a verify constraint instead of adding | |
1554 | // edges, which winds up enforcing the same condition. | |
9e0c209e | 1555 | let needs_infer = projection_ty.trait_ref.needs_infer(); |
a7813a04 XL |
1556 | if env_bounds.is_empty() && needs_infer { |
1557 | debug!("projection_must_outlive: no declared bounds"); | |
e9174d1e | 1558 | |
9e0c209e | 1559 | for component_ty in projection_ty.trait_ref.substs.types() { |
a7813a04 XL |
1560 | self.type_must_outlive(origin.clone(), component_ty, region); |
1561 | } | |
1562 | ||
9e0c209e | 1563 | for r in projection_ty.trait_ref.substs.regions() { |
a7813a04 XL |
1564 | self.sub_regions(origin.clone(), region, r); |
1565 | } | |
e9174d1e | 1566 | |
e9174d1e | 1567 | return; |
85aaf69f | 1568 | } |
1a4d82fc | 1569 | |
a7813a04 XL |
1570 | // If we find that there is a unique declared bound `'b`, and this bound |
1571 | // appears in the trait reference, then the best action is to require that `'b:'r`, | |
1572 | // so do that. This is best no matter what rule we use: | |
1573 | // | |
1574 | // - OutlivesProjectionEnv or OutlivesProjectionTraitDef: these would translate to | |
1575 | // the requirement that `'b:'r` | |
1576 | // - OutlivesProjectionComponent: this would require `'b:'r` in addition to | |
1577 | // other conditions | |
1578 | if !env_bounds.is_empty() && env_bounds[1..].iter().all(|b| *b == env_bounds[0]) { | |
1579 | let unique_bound = env_bounds[0]; | |
1580 | debug!("projection_must_outlive: unique declared bound = {:?}", unique_bound); | |
9e0c209e | 1581 | if projection_ty.trait_ref.substs.regions().any(|r| env_bounds.contains(&r)) { |
a7813a04 XL |
1582 | debug!("projection_must_outlive: unique declared bound appears in trait ref"); |
1583 | self.sub_regions(origin.clone(), region, unique_bound); | |
1584 | return; | |
1585 | } | |
e9174d1e | 1586 | } |
a7813a04 XL |
1587 | |
1588 | // Fallback to verifying after the fact that there exists a | |
1589 | // declared bound, or that all the components appearing in the | |
1590 | // projection outlive; in some cases, this may add insufficient | |
1591 | // edges into the inference graph, leading to inference failures | |
1592 | // even though a satisfactory solution exists. | |
1593 | let verify_bound = self.projection_bound(origin.span(), env_bounds, projection_ty); | |
1594 | let generic = GenericKind::Projection(projection_ty); | |
1595 | self.verify_generic_bound(origin, generic.clone(), region, verify_bound); | |
1596 | } | |
1597 | ||
9e0c209e | 1598 | fn type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> { |
a7813a04 XL |
1599 | match ty.sty { |
1600 | ty::TyParam(p) => { | |
1601 | self.param_bound(p) | |
1602 | } | |
1603 | ty::TyProjection(data) => { | |
1604 | let declared_bounds = self.projection_declared_bounds(span, data); | |
1605 | self.projection_bound(span, declared_bounds, data) | |
1606 | } | |
1607 | _ => { | |
1608 | self.recursive_type_bound(span, ty) | |
1609 | } | |
e9174d1e SL |
1610 | } |
1611 | } | |
e9174d1e | 1612 | |
9e0c209e | 1613 | fn param_bound(&self, param_ty: ty::ParamTy) -> VerifyBound<'tcx> { |
a7813a04 | 1614 | let param_env = &self.parameter_environment; |
e9174d1e | 1615 | |
a7813a04 XL |
1616 | debug!("param_bound(param_ty={:?})", |
1617 | param_ty); | |
e9174d1e | 1618 | |
a7813a04 | 1619 | let mut param_bounds = self.declared_generic_bounds_from_env(GenericKind::Param(param_ty)); |
e9174d1e | 1620 | |
a7813a04 XL |
1621 | // Add in the default bound of fn body that applies to all in |
1622 | // scope type parameters: | |
1623 | param_bounds.push(param_env.implicit_region_bound); | |
1a4d82fc | 1624 | |
a7813a04 XL |
1625 | VerifyBound::AnyRegion(param_bounds) |
1626 | } | |
e9174d1e | 1627 | |
a7813a04 XL |
1628 | fn projection_declared_bounds(&self, |
1629 | span: Span, | |
1630 | projection_ty: ty::ProjectionTy<'tcx>) | |
9e0c209e | 1631 | -> Vec<&'tcx ty::Region> |
a7813a04 XL |
1632 | { |
1633 | // First assemble bounds from where clauses and traits. | |
e9174d1e | 1634 | |
a7813a04 XL |
1635 | let mut declared_bounds = |
1636 | self.declared_generic_bounds_from_env(GenericKind::Projection(projection_ty)); | |
e9174d1e | 1637 | |
a7813a04 XL |
1638 | declared_bounds.extend_from_slice( |
1639 | &self.declared_projection_bounds_from_trait(span, projection_ty)); | |
e9174d1e | 1640 | |
a7813a04 XL |
1641 | declared_bounds |
1642 | } | |
e9174d1e | 1643 | |
a7813a04 XL |
1644 | fn projection_bound(&self, |
1645 | span: Span, | |
9e0c209e | 1646 | declared_bounds: Vec<&'tcx ty::Region>, |
a7813a04 | 1647 | projection_ty: ty::ProjectionTy<'tcx>) |
9e0c209e | 1648 | -> VerifyBound<'tcx> { |
a7813a04 XL |
1649 | debug!("projection_bound(declared_bounds={:?}, projection_ty={:?})", |
1650 | declared_bounds, projection_ty); | |
e9174d1e | 1651 | |
a7813a04 | 1652 | // see the extensive comment in projection_must_outlive |
e9174d1e | 1653 | |
a7813a04 XL |
1654 | let ty = self.tcx.mk_projection(projection_ty.trait_ref, projection_ty.item_name); |
1655 | let recursive_bound = self.recursive_type_bound(span, ty); | |
e9174d1e | 1656 | |
a7813a04 XL |
1657 | VerifyBound::AnyRegion(declared_bounds).or(recursive_bound) |
1658 | } | |
e9174d1e | 1659 | |
9e0c209e | 1660 | fn recursive_type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> { |
a7813a04 | 1661 | let mut bounds = vec![]; |
e9174d1e | 1662 | |
a7813a04 XL |
1663 | for subty in ty.walk_shallow() { |
1664 | bounds.push(self.type_bound(span, subty)); | |
1665 | } | |
e9174d1e | 1666 | |
a7813a04 XL |
1667 | let mut regions = ty.regions(); |
1668 | regions.retain(|r| !r.is_bound()); // ignore late-bound regions | |
1669 | bounds.push(VerifyBound::AllRegions(regions)); | |
e9174d1e | 1670 | |
a7813a04 XL |
1671 | // remove bounds that must hold, since they are not interesting |
1672 | bounds.retain(|b| !b.must_hold()); | |
e9174d1e | 1673 | |
a7813a04 XL |
1674 | if bounds.len() == 1 { |
1675 | bounds.pop().unwrap() | |
1676 | } else { | |
1677 | VerifyBound::AllBounds(bounds) | |
1678 | } | |
e9174d1e | 1679 | } |
e9174d1e | 1680 | |
a7813a04 | 1681 | fn declared_generic_bounds_from_env(&self, generic: GenericKind<'tcx>) |
9e0c209e | 1682 | -> Vec<&'tcx ty::Region> |
a7813a04 XL |
1683 | { |
1684 | let param_env = &self.parameter_environment; | |
1685 | ||
1686 | // To start, collect bounds from user: | |
1687 | let mut param_bounds = self.tcx.required_region_bounds(generic.to_ty(self.tcx), | |
1688 | param_env.caller_bounds.clone()); | |
1689 | ||
1690 | // Next, collect regions we scraped from the well-formedness | |
1691 | // constraints in the fn signature. To do that, we walk the list | |
1692 | // of known relations from the fn ctxt. | |
1693 | // | |
1694 | // This is crucial because otherwise code like this fails: | |
1695 | // | |
1696 | // fn foo<'a, A>(x: &'a A) { x.bar() } | |
1697 | // | |
1698 | // The problem is that the type of `x` is `&'a A`. To be | |
1699 | // well-formed, then, A must be lower-generic by `'a`, but we | |
1700 | // don't know that this holds from first principles. | |
1701 | for &(r, p) in &self.region_bound_pairs { | |
1702 | debug!("generic={:?} p={:?}", | |
1703 | generic, | |
1704 | p); | |
1705 | if generic == p { | |
1706 | param_bounds.push(r); | |
1707 | } | |
1a4d82fc | 1708 | } |
1a4d82fc | 1709 | |
a7813a04 XL |
1710 | param_bounds |
1711 | } | |
85aaf69f | 1712 | |
a7813a04 XL |
1713 | fn declared_projection_bounds_from_trait(&self, |
1714 | span: Span, | |
1715 | projection_ty: ty::ProjectionTy<'tcx>) | |
9e0c209e | 1716 | -> Vec<&'tcx ty::Region> |
a7813a04 XL |
1717 | { |
1718 | debug!("projection_bounds(projection_ty={:?})", | |
1719 | projection_ty); | |
85aaf69f | 1720 | |
a7813a04 XL |
1721 | let ty = self.tcx.mk_projection(projection_ty.trait_ref.clone(), |
1722 | projection_ty.item_name); | |
85aaf69f | 1723 | |
a7813a04 XL |
1724 | // Say we have a projection `<T as SomeTrait<'a>>::SomeType`. We are interested |
1725 | // in looking for a trait definition like: | |
1726 | // | |
1727 | // ``` | |
1728 | // trait SomeTrait<'a> { | |
1729 | // type SomeType : 'a; | |
1730 | // } | |
1731 | // ``` | |
1732 | // | |
1733 | // we can thus deduce that `<T as SomeTrait<'a>>::SomeType : 'a`. | |
476ff2be | 1734 | let trait_predicates = self.tcx.item_predicates(projection_ty.trait_ref.def_id); |
9e0c209e | 1735 | assert_eq!(trait_predicates.parent, None); |
a7813a04 XL |
1736 | let predicates = trait_predicates.predicates.as_slice().to_vec(); |
1737 | traits::elaborate_predicates(self.tcx, predicates) | |
1738 | .filter_map(|predicate| { | |
1739 | // we're only interesting in `T : 'a` style predicates: | |
1740 | let outlives = match predicate { | |
1741 | ty::Predicate::TypeOutlives(data) => data, | |
1742 | _ => { return None; } | |
1743 | }; | |
85aaf69f | 1744 | |
a7813a04 XL |
1745 | debug!("projection_bounds: outlives={:?} (1)", |
1746 | outlives); | |
85aaf69f | 1747 | |
a7813a04 XL |
1748 | // apply the substitutions (and normalize any projected types) |
1749 | let outlives = self.instantiate_type_scheme(span, | |
1750 | projection_ty.trait_ref.substs, | |
1751 | &outlives); | |
85aaf69f | 1752 | |
a7813a04 | 1753 | debug!("projection_bounds: outlives={:?} (2)", |
62682a34 | 1754 | outlives); |
85aaf69f | 1755 | |
a7813a04 XL |
1756 | let region_result = self.commit_if_ok(|_| { |
1757 | let (outlives, _) = | |
1758 | self.replace_late_bound_regions_with_fresh_var( | |
1759 | span, | |
1760 | infer::AssocTypeProjection(projection_ty.item_name), | |
1761 | &outlives); | |
1762 | ||
1763 | debug!("projection_bounds: outlives={:?} (3)", | |
1764 | outlives); | |
1765 | ||
1766 | // check whether this predicate applies to our current projection | |
476ff2be SL |
1767 | let cause = self.fcx.misc(span); |
1768 | match self.eq_types(false, &cause, ty, outlives.0) { | |
1769 | Ok(ok) => { | |
1770 | self.register_infer_ok_obligations(ok); | |
a7813a04 XL |
1771 | Ok(outlives.1) |
1772 | } | |
1773 | Err(_) => { Err(()) } | |
54a0048b | 1774 | } |
a7813a04 | 1775 | }); |
85aaf69f | 1776 | |
a7813a04 XL |
1777 | debug!("projection_bounds: region_result={:?}", |
1778 | region_result); | |
85aaf69f | 1779 | |
a7813a04 XL |
1780 | region_result.ok() |
1781 | }) | |
1782 | .collect() | |
1783 | } | |
85aaf69f | 1784 | } |