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.)
46 use middle::def_id::DefId;
47 use middle::expr_use_visitor as euv;
48 use middle::mem_categorization as mc;
49 use middle::ty::{self, Ty};
50 use middle::infer::{InferCtxt, UpvarRegion};
51 use std::collections::HashSet;
53 use syntax::codemap::Span;
54 use syntax::visit::{self, Visitor};
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 // Skip all items; they aren't in the same context.
97 fn visit_item(&mut self, _: &'v ast::Item) { }
100 impl<'a,'tcx> SeedBorrowKind<'a,'tcx> {
101 fn new(fcx: &'a FnCtxt<'a,'tcx>) -> SeedBorrowKind<'a,'tcx> {
102 SeedBorrowKind { fcx: fcx, closures_with_inferred_kinds: HashSet::new() }
105 fn tcx(&self) -> &'a ty::ctxt<'tcx> {
109 fn infcx(&self) -> &'a InferCtxt<'a,'tcx> {
113 fn check_closure(&mut self,
115 capture_clause: ast::CaptureClause,
118 let closure_def_id = DefId::local(expr.id);
119 if !self.fcx.inh.tables.borrow().closure_kinds.contains_key(&closure_def_id) {
120 self.closures_with_inferred_kinds.insert(expr.id);
121 self.fcx.inh.tables.borrow_mut().closure_kinds
122 .insert(closure_def_id, ty::FnClosureKind);
123 debug!("check_closure: adding closure_id={:?} to closures_with_inferred_kinds",
127 self.tcx().with_freevars(expr.id, |freevars| {
128 for freevar in freevars {
129 let var_node_id = freevar.def.local_node_id();
130 let upvar_id = ty::UpvarId { var_id: var_node_id,
131 closure_expr_id: expr.id };
132 debug!("seed upvar_id {:?}", upvar_id);
134 let capture_kind = match capture_clause {
135 ast::CaptureByValue => {
136 ty::UpvarCapture::ByValue
138 ast::CaptureByRef => {
139 let origin = UpvarRegion(upvar_id, expr.span);
140 let freevar_region = self.infcx().next_region_var(origin);
141 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow,
142 region: freevar_region };
143 ty::UpvarCapture::ByRef(upvar_borrow)
147 self.fcx.inh.tables.borrow_mut().upvar_capture_map.insert(upvar_id, capture_kind);
153 ///////////////////////////////////////////////////////////////////////////
154 // ADJUST BORROW KIND
156 struct AdjustBorrowKind<'a,'tcx:'a> {
157 fcx: &'a FnCtxt<'a,'tcx>,
158 closures_with_inferred_kinds: &'a HashSet<ast::NodeId>,
161 impl<'a,'tcx> AdjustBorrowKind<'a,'tcx> {
162 fn new(fcx: &'a FnCtxt<'a,'tcx>,
163 closures_with_inferred_kinds: &'a HashSet<ast::NodeId>)
164 -> AdjustBorrowKind<'a,'tcx> {
165 AdjustBorrowKind { fcx: fcx, closures_with_inferred_kinds: closures_with_inferred_kinds }
168 fn analyze_closure(&mut self,
174 * Analysis starting point.
177 debug!("analyze_closure(id={:?}, body.id={:?})", id, body.id);
180 let mut euv = euv::ExprUseVisitor::new(self, self.fcx.infcx());
181 euv.walk_fn(decl, body);
184 // Now that we've analyzed the closure, we know how each
185 // variable is borrowed, and we know what traits the closure
186 // implements (Fn vs FnMut etc). We now have some updates to do
187 // with that information.
189 // Note that no closure type C may have an upvar of type C
190 // (though it may reference itself via a trait object). This
191 // results from the desugaring of closures to a struct like
192 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
193 // C, then the type would have infinite size (and the
194 // inference algorithm will reject it).
196 // Extract the type variables UV0...UVn.
197 let closure_substs = match self.fcx.node_ty(id).sty {
198 ty::TyClosure(_, ref substs) => substs,
200 self.fcx.tcx().sess.span_bug(
202 &format!("type of closure expr {:?} is not a closure {:?}",
207 // Equate the type variables with the actual types.
208 let final_upvar_tys = self.final_upvar_tys(id);
209 debug!("analyze_closure: id={:?} closure_substs={:?} final_upvar_tys={:?}",
210 id, closure_substs, final_upvar_tys);
211 for (&upvar_ty, final_upvar_ty) in closure_substs.upvar_tys.iter().zip(final_upvar_tys) {
212 demand::eqtype(self.fcx, span, final_upvar_ty, upvar_ty);
215 // Now we must process and remove any deferred resolutions,
216 // since we have a concrete closure kind.
217 let closure_def_id = DefId::local(id);
218 if self.closures_with_inferred_kinds.contains(&id) {
219 let mut deferred_call_resolutions =
220 self.fcx.remove_deferred_call_resolutions(closure_def_id);
221 for deferred_call_resolution in &mut deferred_call_resolutions {
222 deferred_call_resolution.resolve(self.fcx);
227 // Returns a list of `ClosureUpvar`s for each upvar.
228 fn final_upvar_tys(&mut self, closure_id: ast::NodeId) -> Vec<Ty<'tcx>> {
229 // Presently an unboxed closure type cannot "escape" out of a
230 // function, so we will only encounter ones that originated in the
231 // local crate or were inlined into it along with some function.
232 // This may change if abstract return types of some sort are
234 let tcx = self.fcx.tcx();
235 tcx.with_freevars(closure_id, |freevars| {
238 let freevar_def_id = freevar.def.def_id();
239 let freevar_ty = self.fcx.node_ty(freevar_def_id.node);
240 let upvar_id = ty::UpvarId {
241 var_id: freevar_def_id.node,
242 closure_expr_id: closure_id
244 let capture = self.fcx.infcx().upvar_capture(upvar_id).unwrap();
246 debug!("freevar_def_id={:?} freevar_ty={:?} capture={:?}",
247 freevar_def_id, freevar_ty, capture);
250 ty::UpvarCapture::ByValue => freevar_ty,
251 ty::UpvarCapture::ByRef(borrow) =>
252 tcx.mk_ref(tcx.mk_region(borrow.region),
255 mutbl: borrow.kind.to_mutbl_lossy(),
263 fn adjust_upvar_borrow_kind_for_consume(&self,
265 mode: euv::ConsumeMode)
267 debug!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
270 // we only care about moves
272 euv::Copy => { return; }
276 // watch out for a move of the deref of a borrowed pointer;
277 // for that to be legal, the upvar would have to be borrowed
279 let guarantor = cmt.guarantor();
280 debug!("adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
282 match guarantor.cat {
283 mc::cat_deref(_, _, mc::BorrowedPtr(..)) |
284 mc::cat_deref(_, _, mc::Implicit(..)) => {
286 mc::NoteUpvarRef(upvar_id) => {
287 debug!("adjust_upvar_borrow_kind_for_consume: \
288 setting upvar_id={:?} to by value",
291 // to move out of an upvar, this must be a FnOnce closure
292 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnOnceClosureKind);
294 let upvar_capture_map =
295 &mut self.fcx.inh.tables.borrow_mut().upvar_capture_map;
296 upvar_capture_map.insert(upvar_id, ty::UpvarCapture::ByValue);
298 mc::NoteClosureEnv(upvar_id) => {
299 // we get just a closureenv ref if this is a
300 // `move` closure, or if the upvar has already
301 // been inferred to by-value. In any case, we
302 // must still adjust the kind of the closure
303 // to be a FnOnce closure to permit moves out
304 // of the environment.
305 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnOnceClosureKind);
315 /// Indicates that `cmt` is being directly mutated (e.g., assigned
316 /// to). If cmt contains any by-ref upvars, this implies that
317 /// those upvars must be borrowed using an `&mut` borrow.
318 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
319 debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})",
322 match cmt.cat.clone() {
323 mc::cat_deref(base, _, mc::Unique) |
324 mc::cat_interior(base, _) |
325 mc::cat_downcast(base, _) => {
326 // Interior or owned data is mutable if base is
327 // mutable, so iterate to the base.
328 self.adjust_upvar_borrow_kind_for_mut(base);
331 mc::cat_deref(base, _, mc::BorrowedPtr(..)) |
332 mc::cat_deref(base, _, mc::Implicit(..)) => {
333 if !self.try_adjust_upvar_deref(&cmt.note, ty::MutBorrow) {
334 // assignment to deref of an `&mut`
335 // borrowed pointer implies that the
336 // pointer itself must be unique, but not
337 // necessarily *mutable*
338 self.adjust_upvar_borrow_kind_for_unique(base);
342 mc::cat_deref(_, _, mc::UnsafePtr(..)) |
343 mc::cat_static_item |
346 mc::cat_upvar(..) => {
352 fn adjust_upvar_borrow_kind_for_unique(&self, cmt: mc::cmt<'tcx>) {
353 debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})",
356 match cmt.cat.clone() {
357 mc::cat_deref(base, _, mc::Unique) |
358 mc::cat_interior(base, _) |
359 mc::cat_downcast(base, _) => {
360 // Interior or owned data is unique if base is
362 self.adjust_upvar_borrow_kind_for_unique(base);
365 mc::cat_deref(base, _, mc::BorrowedPtr(..)) |
366 mc::cat_deref(base, _, mc::Implicit(..)) => {
367 if !self.try_adjust_upvar_deref(&cmt.note, ty::UniqueImmBorrow) {
368 // for a borrowed pointer to be unique, its
369 // base must be unique
370 self.adjust_upvar_borrow_kind_for_unique(base);
374 mc::cat_deref(_, _, mc::UnsafePtr(..)) |
375 mc::cat_static_item |
378 mc::cat_upvar(..) => {
383 fn try_adjust_upvar_deref(&self,
385 borrow_kind: ty::BorrowKind)
388 assert!(match borrow_kind {
389 ty::MutBorrow => true,
390 ty::UniqueImmBorrow => true,
392 // imm borrows never require adjusting any kinds, so we don't wind up here
393 ty::ImmBorrow => false,
397 mc::NoteUpvarRef(upvar_id) => {
398 // if this is an implicit deref of an
399 // upvar, then we need to modify the
400 // borrow_kind of the upvar to make sure it
401 // is inferred to mutable if necessary
403 let upvar_capture_map = &mut self.fcx.inh.tables.borrow_mut().upvar_capture_map;
404 let ub = upvar_capture_map.get_mut(&upvar_id).unwrap();
405 self.adjust_upvar_borrow_kind(upvar_id, ub, borrow_kind);
408 // also need to be in an FnMut closure since this is not an ImmBorrow
409 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnMutClosureKind);
413 mc::NoteClosureEnv(upvar_id) => {
414 // this kind of deref occurs in a `move` closure, or
415 // for a by-value upvar; in either case, to mutate an
416 // upvar, we need to be an FnMut closure
417 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnMutClosureKind);
427 /// We infer the borrow_kind with which to borrow upvars in a stack closure. The borrow_kind
428 /// basically follows a lattice of `imm < unique-imm < mut`, moving from left to right as needed
429 /// (but never right to left). Here the argument `mutbl` is the borrow_kind that is required by
430 /// some particular use.
431 fn adjust_upvar_borrow_kind(&self,
432 upvar_id: ty::UpvarId,
433 upvar_capture: &mut ty::UpvarCapture,
434 kind: ty::BorrowKind) {
435 debug!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
436 upvar_id, upvar_capture, kind);
438 match *upvar_capture {
439 ty::UpvarCapture::ByValue => {
440 // Upvar is already by-value, the strongest criteria.
442 ty::UpvarCapture::ByRef(ref mut upvar_borrow) => {
443 match (upvar_borrow.kind, kind) {
445 (ty::ImmBorrow, ty::UniqueImmBorrow) |
446 (ty::ImmBorrow, ty::MutBorrow) |
447 (ty::UniqueImmBorrow, ty::MutBorrow) => {
448 upvar_borrow.kind = kind;
451 (ty::ImmBorrow, ty::ImmBorrow) |
452 (ty::UniqueImmBorrow, ty::ImmBorrow) |
453 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
454 (ty::MutBorrow, _) => {
461 fn adjust_closure_kind(&self,
462 closure_id: ast::NodeId,
463 new_kind: ty::ClosureKind) {
464 debug!("adjust_closure_kind(closure_id={}, new_kind={:?})",
465 closure_id, new_kind);
467 if !self.closures_with_inferred_kinds.contains(&closure_id) {
471 let closure_def_id = DefId::local(closure_id);
472 let closure_kinds = &mut self.fcx.inh.tables.borrow_mut().closure_kinds;
473 let existing_kind = *closure_kinds.get(&closure_def_id).unwrap();
475 debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
476 closure_id, existing_kind, new_kind);
478 match (existing_kind, new_kind) {
479 (ty::FnClosureKind, ty::FnClosureKind) |
480 (ty::FnMutClosureKind, ty::FnClosureKind) |
481 (ty::FnMutClosureKind, ty::FnMutClosureKind) |
482 (ty::FnOnceClosureKind, _) => {
486 (ty::FnClosureKind, ty::FnMutClosureKind) |
487 (ty::FnClosureKind, ty::FnOnceClosureKind) |
488 (ty::FnMutClosureKind, ty::FnOnceClosureKind) => {
489 // new kind is stronger than the old kind
490 closure_kinds.insert(closure_def_id, new_kind);
496 impl<'a, 'tcx, 'v> Visitor<'v> for AdjustBorrowKind<'a, 'tcx> {
497 fn visit_fn(&mut self,
498 fn_kind: visit::FnKind<'v>,
499 decl: &'v ast::FnDecl,
500 body: &'v ast::Block,
504 visit::walk_fn(self, fn_kind, decl, body, span);
505 self.analyze_closure(id, span, decl, body);
508 // Skip all items; they aren't in the same context.
509 fn visit_item(&mut self, _: &'v ast::Item) { }
512 impl<'a,'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a,'tcx> {
513 fn consume(&mut self,
514 _consume_id: ast::NodeId,
517 mode: euv::ConsumeMode)
519 debug!("consume(cmt={:?},mode={:?})", cmt, mode);
520 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
523 fn matched_pat(&mut self,
524 _matched_pat: &ast::Pat,
526 _mode: euv::MatchMode)
529 fn consume_pat(&mut self,
530 _consume_pat: &ast::Pat,
532 mode: euv::ConsumeMode)
534 debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode);
535 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
539 borrow_id: ast::NodeId,
542 _loan_region: ty::Region,
544 _loan_cause: euv::LoanCause)
546 debug!("borrow(borrow_id={}, cmt={:?}, bk={:?})",
551 ty::UniqueImmBorrow => {
552 self.adjust_upvar_borrow_kind_for_unique(cmt);
555 self.adjust_upvar_borrow_kind_for_mut(cmt);
560 fn decl_without_init(&mut self,
566 _assignment_id: ast::NodeId,
567 _assignment_span: Span,
568 assignee_cmt: mc::cmt<'tcx>,
569 _mode: euv::MutateMode)
571 debug!("mutate(assignee_cmt={:?})",
574 self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);