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.
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.
11 //! ### Inferring borrow kinds for upvars
13 //! Whenever there is a closure expression, we need to determine how each
14 //! upvar is used. We do this by initially assigning each upvar an
15 //! immutable "borrow kind" (see `ty::BorrowKind` for details) and then
16 //! "escalating" the kind as needed. The borrow kind proceeds according to
17 //! the following lattice:
19 //! ty::ImmBorrow -> ty::UniqueImmBorrow -> ty::MutBorrow
21 //! So, for example, if we see an assignment `x = 5` to an upvar `x`, we
22 //! will promote its borrow kind to mutable borrow. If we see an `&mut x`
23 //! we'll do the same. Naturally, this applies not just to the upvar, but
24 //! to everything owned by `x`, so the result is the same for something
25 //! like `x.f = 5` and so on (presuming `x` is not a borrowed pointer to a
26 //! struct). These adjustments are performed in
27 //! `adjust_upvar_borrow_kind()` (you can trace backwards through the code
30 //! The fact that we are inferring borrow kinds as we go results in a
31 //! semi-hacky interaction with mem-categorization. In particular,
32 //! mem-categorization will query the current borrow kind as it
33 //! categorizes, and we'll return the *current* value, but this may get
34 //! adjusted later. Therefore, in this module, we generally ignore the
35 //! borrow kind (and derived mutabilities) that are returned from
36 //! mem-categorization, since they may be inaccurate. (Another option
37 //! would be to use a unification scheme, where instead of returning a
38 //! concrete borrow kind like `ty::ImmBorrow`, we return a
39 //! `ty::InferBorrow(upvar_id)` or something like that, but this would
40 //! then mean that all later passes would have to check for these figments
41 //! and report an error, and it just seems like more mess in the end.)
45 use middle::expr_use_visitor as euv;
46 use middle::mem_categorization as mc;
47 use middle::ty::{self};
48 use middle::infer::{InferCtxt, UpvarRegion};
49 use std::collections::HashSet;
52 use syntax::codemap::Span;
53 use syntax::visit::{self, Visitor};
54 use util::ppaux::Repr;
56 ///////////////////////////////////////////////////////////////////////////
57 // PUBLIC ENTRY POINTS
59 pub fn closure_analyze_fn(fcx: &FnCtxt,
64 let mut seed = SeedBorrowKind::new(fcx);
65 seed.visit_block(body);
66 let closures_with_inferred_kinds = seed.closures_with_inferred_kinds;
68 let mut adjust = AdjustBorrowKind::new(fcx, &closures_with_inferred_kinds);
69 adjust.visit_block(body);
71 // it's our job to process these.
72 assert!(fcx.inh.deferred_call_resolutions.borrow().is_empty());
75 ///////////////////////////////////////////////////////////////////////////
78 struct SeedBorrowKind<'a,'tcx:'a> {
79 fcx: &'a FnCtxt<'a,'tcx>,
80 closures_with_inferred_kinds: HashSet<ast::NodeId>,
83 impl<'a, 'tcx, 'v> Visitor<'v> for SeedBorrowKind<'a, 'tcx> {
84 fn visit_expr(&mut self, expr: &ast::Expr) {
86 ast::ExprClosure(cc, _, _, ref body) => {
87 self.check_closure(expr, cc, &**body);
93 visit::walk_expr(self, expr);
96 fn visit_fn(&mut self,
97 fn_kind: visit::FnKind<'v>,
98 decl: &'v ast::FnDecl,
99 block: &'v ast::Block,
104 visit::FkItemFn(..) | visit::FkMethod(..) => {
105 // ignore nested fn items
107 visit::FkFnBlock => {
108 visit::walk_fn(self, fn_kind, decl, block, span);
114 impl<'a,'tcx> SeedBorrowKind<'a,'tcx> {
115 fn new(fcx: &'a FnCtxt<'a,'tcx>) -> SeedBorrowKind<'a,'tcx> {
116 SeedBorrowKind { fcx: fcx, closures_with_inferred_kinds: HashSet::new() }
119 fn tcx(&self) -> &'a ty::ctxt<'tcx> {
123 fn infcx(&self) -> &'a InferCtxt<'a,'tcx> {
127 fn check_closure(&mut self,
129 capture_clause: ast::CaptureClause,
132 let closure_def_id = ast_util::local_def(expr.id);
133 if !self.fcx.inh.closure_kinds.borrow().contains_key(&closure_def_id) {
134 self.closures_with_inferred_kinds.insert(expr.id);
135 self.fcx.inh.closure_kinds.borrow_mut().insert(closure_def_id, ty::FnClosureKind);
136 debug!("check_closure: adding closure_id={} to closures_with_inferred_kinds",
137 closure_def_id.repr(self.tcx()));
140 ty::with_freevars(self.tcx(), expr.id, |freevars| {
141 for freevar in freevars.iter() {
142 let var_node_id = freevar.def.local_node_id();
143 let upvar_id = ty::UpvarId { var_id: var_node_id,
144 closure_expr_id: expr.id };
145 debug!("seed upvar_id {:?}", upvar_id);
147 let capture_kind = match capture_clause {
148 ast::CaptureByValue => {
149 ty::UpvarCapture::ByValue
151 ast::CaptureByRef => {
152 let origin = UpvarRegion(upvar_id, expr.span);
153 let freevar_region = self.infcx().next_region_var(origin);
154 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow,
155 region: freevar_region };
156 ty::UpvarCapture::ByRef(upvar_borrow)
160 self.fcx.inh.upvar_capture_map.borrow_mut().insert(upvar_id, capture_kind);
166 ///////////////////////////////////////////////////////////////////////////
167 // ADJUST BORROW KIND
169 struct AdjustBorrowKind<'a,'tcx:'a> {
170 fcx: &'a FnCtxt<'a,'tcx>,
171 closures_with_inferred_kinds: &'a HashSet<ast::NodeId>,
174 impl<'a,'tcx> AdjustBorrowKind<'a,'tcx> {
175 fn new(fcx: &'a FnCtxt<'a,'tcx>,
176 closures_with_inferred_kinds: &'a HashSet<ast::NodeId>)
177 -> AdjustBorrowKind<'a,'tcx> {
178 AdjustBorrowKind { fcx: fcx, closures_with_inferred_kinds: closures_with_inferred_kinds }
181 fn tcx(&self) -> &'a ty::ctxt<'tcx> {
185 fn analyze_closure(&mut self, id: ast::NodeId, decl: &ast::FnDecl, body: &ast::Block) {
187 * Analysis starting point.
190 self.visit_block(body);
192 debug!("analyzing closure `{}` with fn body id `{}`", id, body.id);
194 let mut euv = euv::ExprUseVisitor::new(self, self.fcx);
195 euv.walk_fn(decl, body);
197 // If we had not yet settled on a closure kind for this closure,
198 // then we should have by now. Process and remove any deferred resolutions.
200 // Interesting fact: all calls to this closure must come
201 // *after* its definition. Initially, I thought that some
202 // kind of fixed-point iteration would be required, due to the
203 // possibility of twisted examples like this one:
206 // let mut closure0 = None;
207 // let vec = vec!(1, 2, 3);
211 // let closure1 = || {
212 // match closure0.take() {
214 // return c(); // (*) call to `closure0` before it is defined
222 // closure0 = || vec;
226 // However, this turns out to be wrong. Examples like this
227 // fail to compile because the type of the variable `c` above
228 // is an inference variable. And in fact since closure types
229 // cannot be written, there is no way to make this example
230 // work without a boxed closure. This implies that we can't
231 // have two closures that recursively call one another without
232 // some form of boxing (and hence explicit writing of a
233 // closure kind) involved. Huzzah. -nmatsakis
234 let closure_def_id = ast_util::local_def(id);
235 if self.closures_with_inferred_kinds.contains(&id) {
236 let mut deferred_call_resolutions =
237 self.fcx.remove_deferred_call_resolutions(closure_def_id);
238 for deferred_call_resolution in deferred_call_resolutions.iter_mut() {
239 deferred_call_resolution.resolve(self.fcx);
244 fn adjust_upvar_borrow_kind_for_consume(&self,
246 mode: euv::ConsumeMode)
248 debug!("adjust_upvar_borrow_kind_for_consume(cmt={}, mode={:?})",
249 cmt.repr(self.tcx()), mode);
251 // we only care about moves
253 euv::Copy => { return; }
257 // watch out for a move of the deref of a borrowed pointer;
258 // for that to be legal, the upvar would have to be borrowed
260 let guarantor = cmt.guarantor();
261 debug!("adjust_upvar_borrow_kind_for_consume: guarantor={}",
262 guarantor.repr(self.tcx()));
263 match guarantor.cat {
264 mc::cat_deref(_, _, mc::BorrowedPtr(..)) |
265 mc::cat_deref(_, _, mc::Implicit(..)) => {
266 if let mc::NoteUpvarRef(upvar_id) = cmt.note {
267 debug!("adjust_upvar_borrow_kind_for_consume: \
268 setting upvar_id={:?} to by value",
271 // to move out of an upvar, this must be a FnOnce closure
272 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnOnceClosureKind);
274 let mut upvar_capture_map = self.fcx.inh.upvar_capture_map.borrow_mut();
275 upvar_capture_map.insert(upvar_id, ty::UpvarCapture::ByValue);
282 /// Indicates that `cmt` is being directly mutated (e.g., assigned
283 /// to). If cmt contains any by-ref upvars, this implies that
284 /// those upvars must be borrowed using an `&mut` borow.
285 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
286 debug!("adjust_upvar_borrow_kind_for_mut(cmt={})",
287 cmt.repr(self.tcx()));
289 match cmt.cat.clone() {
290 mc::cat_deref(base, _, mc::Unique) |
291 mc::cat_interior(base, _) |
292 mc::cat_downcast(base, _) => {
293 // Interior or owned data is mutable if base is
294 // mutable, so iterate to the base.
295 self.adjust_upvar_borrow_kind_for_mut(base);
298 mc::cat_deref(base, _, mc::BorrowedPtr(..)) |
299 mc::cat_deref(base, _, mc::Implicit(..)) => {
300 if let mc::NoteUpvarRef(upvar_id) = cmt.note {
301 // if this is an implicit deref of an
302 // upvar, then we need to modify the
303 // borrow_kind of the upvar to make sure it
304 // is inferred to mutable if necessary
305 let mut upvar_capture_map = self.fcx.inh.upvar_capture_map.borrow_mut();
306 let ub = &mut upvar_capture_map[upvar_id];
307 self.adjust_upvar_borrow_kind(upvar_id, ub, ty::MutBorrow);
309 // assignment to deref of an `&mut`
310 // borrowed pointer implies that the
311 // pointer itself must be unique, but not
312 // necessarily *mutable*
313 self.adjust_upvar_borrow_kind_for_unique(base);
317 mc::cat_deref(_, _, mc::UnsafePtr(..)) |
318 mc::cat_static_item |
321 mc::cat_upvar(..) => {
327 fn adjust_upvar_borrow_kind_for_unique(&self, cmt: mc::cmt<'tcx>) {
328 debug!("adjust_upvar_borrow_kind_for_unique(cmt={})",
329 cmt.repr(self.tcx()));
331 match cmt.cat.clone() {
332 mc::cat_deref(base, _, mc::Unique) |
333 mc::cat_interior(base, _) |
334 mc::cat_downcast(base, _) => {
335 // Interior or owned data is unique if base is
337 self.adjust_upvar_borrow_kind_for_unique(base);
340 mc::cat_deref(base, _, mc::BorrowedPtr(..)) |
341 mc::cat_deref(base, _, mc::Implicit(..)) => {
342 if let mc::NoteUpvarRef(upvar_id) = cmt.note {
343 // if this is an implicit deref of an
344 // upvar, then we need to modify the
345 // borrow_kind of the upvar to make sure it
346 // is inferred to unique if necessary
347 let mut ub = self.fcx.inh.upvar_capture_map.borrow_mut();
348 let ub = &mut ub[upvar_id];
349 self.adjust_upvar_borrow_kind(upvar_id, ub, ty::UniqueImmBorrow);
351 // for a borrowed pointer to be unique, its
352 // base must be unique
353 self.adjust_upvar_borrow_kind_for_unique(base);
357 mc::cat_deref(_, _, mc::UnsafePtr(..)) |
358 mc::cat_static_item |
361 mc::cat_upvar(..) => {
366 /// We infer the borrow_kind with which to borrow upvars in a stack closure. The borrow_kind
367 /// basically follows a lattice of `imm < unique-imm < mut`, moving from left to right as needed
368 /// (but never right to left). Here the argument `mutbl` is the borrow_kind that is required by
369 /// some particular use.
370 fn adjust_upvar_borrow_kind(&self,
371 upvar_id: ty::UpvarId,
372 upvar_capture: &mut ty::UpvarCapture,
373 kind: ty::BorrowKind) {
374 debug!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
375 upvar_id, upvar_capture, kind);
379 ty::UniqueImmBorrow | ty::MutBorrow => {
380 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnMutClosureKind);
384 match *upvar_capture {
385 ty::UpvarCapture::ByValue => {
386 // Upvar is already by-value, the strongest criteria.
388 ty::UpvarCapture::ByRef(ref mut upvar_borrow) => {
389 match (upvar_borrow.kind, kind) {
391 (ty::ImmBorrow, ty::UniqueImmBorrow) |
392 (ty::ImmBorrow, ty::MutBorrow) |
393 (ty::UniqueImmBorrow, ty::MutBorrow) => {
394 upvar_borrow.kind = kind;
397 (ty::ImmBorrow, ty::ImmBorrow) |
398 (ty::UniqueImmBorrow, ty::ImmBorrow) |
399 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
400 (ty::MutBorrow, _) => {
407 fn adjust_closure_kind(&self,
408 closure_id: ast::NodeId,
409 new_kind: ty::ClosureKind) {
410 debug!("adjust_closure_kind(closure_id={}, new_kind={:?})",
411 closure_id, new_kind);
413 if !self.closures_with_inferred_kinds.contains(&closure_id) {
417 let closure_def_id = ast_util::local_def(closure_id);
418 let mut closure_kinds = self.fcx.inh.closure_kinds.borrow_mut();
419 let existing_kind = closure_kinds[closure_def_id];
421 debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
422 closure_id, existing_kind, new_kind);
424 match (existing_kind, new_kind) {
425 (ty::FnClosureKind, ty::FnClosureKind) |
426 (ty::FnMutClosureKind, ty::FnClosureKind) |
427 (ty::FnMutClosureKind, ty::FnMutClosureKind) |
428 (ty::FnOnceClosureKind, _) => {
432 (ty::FnClosureKind, ty::FnMutClosureKind) |
433 (ty::FnClosureKind, ty::FnOnceClosureKind) |
434 (ty::FnMutClosureKind, ty::FnOnceClosureKind) => {
435 // new kind is stronger than the old kind
436 closure_kinds.insert(closure_def_id, new_kind);
442 impl<'a, 'tcx, 'v> Visitor<'v> for AdjustBorrowKind<'a, 'tcx> {
443 fn visit_fn(&mut self,
444 fn_kind: visit::FnKind<'v>,
445 decl: &'v ast::FnDecl,
446 body: &'v ast::Block,
451 visit::FkItemFn(..) | visit::FkMethod(..) => {
452 // ignore nested fn items
454 visit::FkFnBlock => {
455 self.analyze_closure(id, decl, body);
456 visit::walk_fn(self, fn_kind, decl, body, span);
462 impl<'a,'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a,'tcx> {
463 fn consume(&mut self,
464 _consume_id: ast::NodeId,
467 mode: euv::ConsumeMode)
469 debug!("consume(cmt={},mode={:?})", cmt.repr(self.tcx()), mode);
470 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
473 fn matched_pat(&mut self,
474 _matched_pat: &ast::Pat,
476 _mode: euv::MatchMode)
479 fn consume_pat(&mut self,
480 _consume_pat: &ast::Pat,
482 mode: euv::ConsumeMode)
484 debug!("consume_pat(cmt={},mode={:?})", cmt.repr(self.tcx()), mode);
485 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
489 borrow_id: ast::NodeId,
492 _loan_region: ty::Region,
494 _loan_cause: euv::LoanCause)
496 debug!("borrow(borrow_id={}, cmt={}, bk={:?})",
497 borrow_id, cmt.repr(self.tcx()), bk);
501 ty::UniqueImmBorrow => {
502 self.adjust_upvar_borrow_kind_for_unique(cmt);
505 self.adjust_upvar_borrow_kind_for_mut(cmt);
510 fn decl_without_init(&mut self,
516 _assignment_id: ast::NodeId,
517 _assignment_span: Span,
518 assignee_cmt: mc::cmt<'tcx>,
519 _mode: euv::MutateMode)
521 debug!("mutate(assignee_cmt={})",
522 assignee_cmt.repr(self.tcx()));
524 self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);