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}
;
55 ///////////////////////////////////////////////////////////////////////////
56 // PUBLIC ENTRY POINTS
58 pub fn closure_analyze_fn(fcx
: &FnCtxt
,
63 let mut seed
= SeedBorrowKind
::new(fcx
);
64 seed
.visit_block(body
);
65 let closures_with_inferred_kinds
= seed
.closures_with_inferred_kinds
;
67 let mut adjust
= AdjustBorrowKind
::new(fcx
, &closures_with_inferred_kinds
);
68 adjust
.visit_block(body
);
70 // it's our job to process these.
71 assert
!(fcx
.inh
.deferred_call_resolutions
.borrow().is_empty());
74 ///////////////////////////////////////////////////////////////////////////
77 struct SeedBorrowKind
<'a
,'tcx
:'a
> {
78 fcx
: &'a FnCtxt
<'a
,'tcx
>,
79 closures_with_inferred_kinds
: HashSet
<ast
::NodeId
>,
82 impl<'a
, 'tcx
, 'v
> Visitor
<'v
> for SeedBorrowKind
<'a
, 'tcx
> {
83 fn visit_expr(&mut self, expr
: &ast
::Expr
) {
85 ast
::ExprClosure(cc
, _
, ref body
) => {
86 self.check_closure(expr
, cc
, &**body
);
92 visit
::walk_expr(self, expr
);
95 fn visit_fn(&mut self,
96 fn_kind
: visit
::FnKind
<'v
>,
97 decl
: &'v ast
::FnDecl
,
98 block
: &'v ast
::Block
,
103 visit
::FkItemFn(..) | visit
::FkMethod(..) => {
104 // ignore nested fn items
106 visit
::FkFnBlock
=> {
107 visit
::walk_fn(self, fn_kind
, decl
, block
, span
);
113 impl<'a
,'tcx
> SeedBorrowKind
<'a
,'tcx
> {
114 fn new(fcx
: &'a FnCtxt
<'a
,'tcx
>) -> SeedBorrowKind
<'a
,'tcx
> {
115 SeedBorrowKind { fcx: fcx, closures_with_inferred_kinds: HashSet::new() }
118 fn tcx(&self) -> &'a ty
::ctxt
<'tcx
> {
122 fn infcx(&self) -> &'a InferCtxt
<'a
,'tcx
> {
126 fn check_closure(&mut self,
128 capture_clause
: ast
::CaptureClause
,
131 let closure_def_id
= ast_util
::local_def(expr
.id
);
132 if !self.fcx
.inh
.closure_kinds
.borrow().contains_key(&closure_def_id
) {
133 self.closures_with_inferred_kinds
.insert(expr
.id
);
134 self.fcx
.inh
.closure_kinds
.borrow_mut().insert(closure_def_id
, ty
::FnClosureKind
);
135 debug
!("check_closure: adding closure_id={:?} to closures_with_inferred_kinds",
139 ty
::with_freevars(self.tcx(), expr
.id
, |freevars
| {
140 for freevar
in freevars
{
141 let var_node_id
= freevar
.def
.local_node_id();
142 let upvar_id
= ty
::UpvarId
{ var_id
: var_node_id
,
143 closure_expr_id
: expr
.id
};
144 debug
!("seed upvar_id {:?}", upvar_id
);
146 let capture_kind
= match capture_clause
{
147 ast
::CaptureByValue
=> {
148 ty
::UpvarCapture
::ByValue
150 ast
::CaptureByRef
=> {
151 let origin
= UpvarRegion(upvar_id
, expr
.span
);
152 let freevar_region
= self.infcx().next_region_var(origin
);
153 let upvar_borrow
= ty
::UpvarBorrow
{ kind
: ty
::ImmBorrow
,
154 region
: freevar_region
};
155 ty
::UpvarCapture
::ByRef(upvar_borrow
)
159 self.fcx
.inh
.upvar_capture_map
.borrow_mut().insert(upvar_id
, capture_kind
);
165 ///////////////////////////////////////////////////////////////////////////
166 // ADJUST BORROW KIND
168 struct AdjustBorrowKind
<'a
,'tcx
:'a
> {
169 fcx
: &'a FnCtxt
<'a
,'tcx
>,
170 closures_with_inferred_kinds
: &'a HashSet
<ast
::NodeId
>,
173 impl<'a
,'tcx
> AdjustBorrowKind
<'a
,'tcx
> {
174 fn new(fcx
: &'a FnCtxt
<'a
,'tcx
>,
175 closures_with_inferred_kinds
: &'a HashSet
<ast
::NodeId
>)
176 -> AdjustBorrowKind
<'a
,'tcx
> {
177 AdjustBorrowKind { fcx: fcx, closures_with_inferred_kinds: closures_with_inferred_kinds }
180 fn analyze_closure(&mut self, id
: ast
::NodeId
, decl
: &ast
::FnDecl
, body
: &ast
::Block
) {
182 * Analysis starting point.
185 self.visit_block(body
);
187 debug
!("analyzing closure `{}` with fn body id `{}`", id
, body
.id
);
189 let mut euv
= euv
::ExprUseVisitor
::new(self, self.fcx
);
190 euv
.walk_fn(decl
, body
);
192 // If we had not yet settled on a closure kind for this closure,
193 // then we should have by now. Process and remove any deferred resolutions.
195 // Interesting fact: all calls to this closure must come
196 // *after* its definition. Initially, I thought that some
197 // kind of fixed-point iteration would be required, due to the
198 // possibility of twisted examples like this one:
201 // let mut closure0 = None;
202 // let vec = vec!(1, 2, 3);
206 // let closure1 = || {
207 // match closure0.take() {
209 // return c(); // (*) call to `closure0` before it is defined
217 // closure0 = || vec;
221 // However, this turns out to be wrong. Examples like this
222 // fail to compile because the type of the variable `c` above
223 // is an inference variable. And in fact since closure types
224 // cannot be written, there is no way to make this example
225 // work without a boxed closure. This implies that we can't
226 // have two closures that recursively call one another without
227 // some form of boxing (and hence explicit writing of a
228 // closure kind) involved. Huzzah. -nmatsakis
229 let closure_def_id
= ast_util
::local_def(id
);
230 if self.closures_with_inferred_kinds
.contains(&id
) {
231 let mut deferred_call_resolutions
=
232 self.fcx
.remove_deferred_call_resolutions(closure_def_id
);
233 for deferred_call_resolution
in &mut deferred_call_resolutions
{
234 deferred_call_resolution
.resolve(self.fcx
);
239 fn adjust_upvar_borrow_kind_for_consume(&self,
241 mode
: euv
::ConsumeMode
)
243 debug
!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
246 // we only care about moves
248 euv
::Copy
=> { return; }
252 // watch out for a move of the deref of a borrowed pointer;
253 // for that to be legal, the upvar would have to be borrowed
255 let guarantor
= cmt
.guarantor();
256 debug
!("adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
258 match guarantor
.cat
{
259 mc
::cat_deref(_
, _
, mc
::BorrowedPtr(..)) |
260 mc
::cat_deref(_
, _
, mc
::Implicit(..)) => {
262 mc
::NoteUpvarRef(upvar_id
) => {
263 debug
!("adjust_upvar_borrow_kind_for_consume: \
264 setting upvar_id={:?} to by value",
267 // to move out of an upvar, this must be a FnOnce closure
268 self.adjust_closure_kind(upvar_id
.closure_expr_id
, ty
::FnOnceClosureKind
);
270 let mut upvar_capture_map
= self.fcx
.inh
.upvar_capture_map
.borrow_mut();
271 upvar_capture_map
.insert(upvar_id
, ty
::UpvarCapture
::ByValue
);
273 mc
::NoteClosureEnv(upvar_id
) => {
274 // we get just a closureenv ref if this is a
275 // `move` closure, or if the upvar has already
276 // been inferred to by-value. In any case, we
277 // must still adjust the kind of the closure
278 // to be a FnOnce closure to permit moves out
279 // of the environment.
280 self.adjust_closure_kind(upvar_id
.closure_expr_id
, ty
::FnOnceClosureKind
);
290 /// Indicates that `cmt` is being directly mutated (e.g., assigned
291 /// to). If cmt contains any by-ref upvars, this implies that
292 /// those upvars must be borrowed using an `&mut` borrow.
293 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt
: mc
::cmt
<'tcx
>) {
294 debug
!("adjust_upvar_borrow_kind_for_mut(cmt={:?})",
297 match cmt
.cat
.clone() {
298 mc
::cat_deref(base
, _
, mc
::Unique
) |
299 mc
::cat_interior(base
, _
) |
300 mc
::cat_downcast(base
, _
) => {
301 // Interior or owned data is mutable if base is
302 // mutable, so iterate to the base.
303 self.adjust_upvar_borrow_kind_for_mut(base
);
306 mc
::cat_deref(base
, _
, mc
::BorrowedPtr(..)) |
307 mc
::cat_deref(base
, _
, mc
::Implicit(..)) => {
308 if !self.try_adjust_upvar_deref(&cmt
.note
, 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={:?})",
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 !self.try_adjust_upvar_deref(&cmt
.note
, ty
::UniqueImmBorrow
) {
343 // for a borrowed pointer to be unique, its
344 // base must be unique
345 self.adjust_upvar_borrow_kind_for_unique(base
);
349 mc
::cat_deref(_
, _
, mc
::UnsafePtr(..)) |
350 mc
::cat_static_item
|
353 mc
::cat_upvar(..) => {
358 fn try_adjust_upvar_deref(&self,
360 borrow_kind
: ty
::BorrowKind
)
363 assert
!(match borrow_kind
{
364 ty
::MutBorrow
=> true,
365 ty
::UniqueImmBorrow
=> true,
367 // imm borrows never require adjusting any kinds, so we don't wind up here
368 ty
::ImmBorrow
=> false,
372 mc
::NoteUpvarRef(upvar_id
) => {
373 // if this is an implicit deref of an
374 // upvar, then we need to modify the
375 // borrow_kind of the upvar to make sure it
376 // is inferred to mutable if necessary
377 let mut upvar_capture_map
= self.fcx
.inh
.upvar_capture_map
.borrow_mut();
378 let ub
= upvar_capture_map
.get_mut(&upvar_id
).unwrap();
379 self.adjust_upvar_borrow_kind(upvar_id
, ub
, borrow_kind
);
381 // also need to be in an FnMut closure since this is not an ImmBorrow
382 self.adjust_closure_kind(upvar_id
.closure_expr_id
, ty
::FnMutClosureKind
);
386 mc
::NoteClosureEnv(upvar_id
) => {
387 // this kind of deref occurs in a `move` closure, or
388 // for a by-value upvar; in either case, to mutate an
389 // upvar, we need to be an FnMut closure
390 self.adjust_closure_kind(upvar_id
.closure_expr_id
, ty
::FnMutClosureKind
);
400 /// We infer the borrow_kind with which to borrow upvars in a stack closure. The borrow_kind
401 /// basically follows a lattice of `imm < unique-imm < mut`, moving from left to right as needed
402 /// (but never right to left). Here the argument `mutbl` is the borrow_kind that is required by
403 /// some particular use.
404 fn adjust_upvar_borrow_kind(&self,
405 upvar_id
: ty
::UpvarId
,
406 upvar_capture
: &mut ty
::UpvarCapture
,
407 kind
: ty
::BorrowKind
) {
408 debug
!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
409 upvar_id
, upvar_capture
, kind
);
411 match *upvar_capture
{
412 ty
::UpvarCapture
::ByValue
=> {
413 // Upvar is already by-value, the strongest criteria.
415 ty
::UpvarCapture
::ByRef(ref mut upvar_borrow
) => {
416 match (upvar_borrow
.kind
, kind
) {
418 (ty
::ImmBorrow
, ty
::UniqueImmBorrow
) |
419 (ty
::ImmBorrow
, ty
::MutBorrow
) |
420 (ty
::UniqueImmBorrow
, ty
::MutBorrow
) => {
421 upvar_borrow
.kind
= kind
;
424 (ty
::ImmBorrow
, ty
::ImmBorrow
) |
425 (ty
::UniqueImmBorrow
, ty
::ImmBorrow
) |
426 (ty
::UniqueImmBorrow
, ty
::UniqueImmBorrow
) |
427 (ty
::MutBorrow
, _
) => {
434 fn adjust_closure_kind(&self,
435 closure_id
: ast
::NodeId
,
436 new_kind
: ty
::ClosureKind
) {
437 debug
!("adjust_closure_kind(closure_id={}, new_kind={:?})",
438 closure_id
, new_kind
);
440 if !self.closures_with_inferred_kinds
.contains(&closure_id
) {
444 let closure_def_id
= ast_util
::local_def(closure_id
);
445 let mut closure_kinds
= self.fcx
.inh
.closure_kinds
.borrow_mut();
446 let existing_kind
= *closure_kinds
.get(&closure_def_id
).unwrap();
448 debug
!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
449 closure_id
, existing_kind
, new_kind
);
451 match (existing_kind
, new_kind
) {
452 (ty
::FnClosureKind
, ty
::FnClosureKind
) |
453 (ty
::FnMutClosureKind
, ty
::FnClosureKind
) |
454 (ty
::FnMutClosureKind
, ty
::FnMutClosureKind
) |
455 (ty
::FnOnceClosureKind
, _
) => {
459 (ty
::FnClosureKind
, ty
::FnMutClosureKind
) |
460 (ty
::FnClosureKind
, ty
::FnOnceClosureKind
) |
461 (ty
::FnMutClosureKind
, ty
::FnOnceClosureKind
) => {
462 // new kind is stronger than the old kind
463 closure_kinds
.insert(closure_def_id
, new_kind
);
469 impl<'a
, 'tcx
, 'v
> Visitor
<'v
> for AdjustBorrowKind
<'a
, 'tcx
> {
470 fn visit_fn(&mut self,
471 fn_kind
: visit
::FnKind
<'v
>,
472 decl
: &'v ast
::FnDecl
,
473 body
: &'v ast
::Block
,
478 visit
::FkItemFn(..) | visit
::FkMethod(..) => {
479 // ignore nested fn items
481 visit
::FkFnBlock
=> {
482 self.analyze_closure(id
, decl
, body
);
483 visit
::walk_fn(self, fn_kind
, decl
, body
, span
);
489 impl<'a
,'tcx
> euv
::Delegate
<'tcx
> for AdjustBorrowKind
<'a
,'tcx
> {
490 fn consume(&mut self,
491 _consume_id
: ast
::NodeId
,
494 mode
: euv
::ConsumeMode
)
496 debug
!("consume(cmt={:?},mode={:?})", cmt
, mode
);
497 self.adjust_upvar_borrow_kind_for_consume(cmt
, mode
);
500 fn matched_pat(&mut self,
501 _matched_pat
: &ast
::Pat
,
503 _mode
: euv
::MatchMode
)
506 fn consume_pat(&mut self,
507 _consume_pat
: &ast
::Pat
,
509 mode
: euv
::ConsumeMode
)
511 debug
!("consume_pat(cmt={:?},mode={:?})", cmt
, mode
);
512 self.adjust_upvar_borrow_kind_for_consume(cmt
, mode
);
516 borrow_id
: ast
::NodeId
,
519 _loan_region
: ty
::Region
,
521 _loan_cause
: euv
::LoanCause
)
523 debug
!("borrow(borrow_id={}, cmt={:?}, bk={:?})",
528 ty
::UniqueImmBorrow
=> {
529 self.adjust_upvar_borrow_kind_for_unique(cmt
);
532 self.adjust_upvar_borrow_kind_for_mut(cmt
);
537 fn decl_without_init(&mut self,
543 _assignment_id
: ast
::NodeId
,
544 _assignment_span
: Span
,
545 assignee_cmt
: mc
::cmt
<'tcx
>,
546 _mode
: euv
::MutateMode
)
548 debug
!("mutate(assignee_cmt={:?})",
551 self.adjust_upvar_borrow_kind_for_mut(assignee_cmt
);