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::expr_use_visitor as euv;
47 use middle::mem_categorization as mc;
48 use middle::ty::{self, Ty};
49 use middle::infer::{InferCtxt, UpvarRegion};
50 use std::collections::HashSet;
52 use syntax::codemap::Span;
54 use rustc_front::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 pub fn closure_analyze_const(fcx: &FnCtxt,
78 let mut seed = SeedBorrowKind::new(fcx);
79 seed.visit_expr(body);
80 let closures_with_inferred_kinds = seed.closures_with_inferred_kinds;
82 let mut adjust = AdjustBorrowKind::new(fcx, &closures_with_inferred_kinds);
83 adjust.visit_expr(body);
85 // it's our job to process these.
86 assert!(fcx.inh.deferred_call_resolutions.borrow().is_empty());
89 ///////////////////////////////////////////////////////////////////////////
92 struct SeedBorrowKind<'a,'tcx:'a> {
93 fcx: &'a FnCtxt<'a,'tcx>,
94 closures_with_inferred_kinds: HashSet<ast::NodeId>,
97 impl<'a, 'tcx, 'v> Visitor<'v> for SeedBorrowKind<'a, 'tcx> {
98 fn visit_expr(&mut self, expr: &hir::Expr) {
100 hir::ExprClosure(cc, _, ref body) => {
101 self.check_closure(expr, cc, &**body);
107 visit::walk_expr(self, expr);
110 // Skip all items; they aren't in the same context.
111 fn visit_item(&mut self, _: &'v hir::Item) { }
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: hir::CaptureClause,
132 let closure_def_id = self.tcx().map.local_def_id(expr.id);
133 if !self.fcx.inh.tables.borrow().closure_kinds.contains_key(&closure_def_id) {
134 self.closures_with_inferred_kinds.insert(expr.id);
135 self.fcx.inh.tables.borrow_mut().closure_kinds
136 .insert(closure_def_id, ty::FnClosureKind);
137 debug!("check_closure: adding closure_id={:?} to closures_with_inferred_kinds",
141 self.tcx().with_freevars(expr.id, |freevars| {
142 for freevar in freevars {
143 let var_node_id = freevar.def.var_id();
144 let upvar_id = ty::UpvarId { var_id: var_node_id,
145 closure_expr_id: expr.id };
146 debug!("seed upvar_id {:?}", upvar_id);
148 let capture_kind = match capture_clause {
149 hir::CaptureByValue => {
150 ty::UpvarCapture::ByValue
152 hir::CaptureByRef => {
153 let origin = UpvarRegion(upvar_id, expr.span);
154 let freevar_region = self.infcx().next_region_var(origin);
155 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow,
156 region: freevar_region };
157 ty::UpvarCapture::ByRef(upvar_borrow)
161 self.fcx.inh.tables.borrow_mut().upvar_capture_map.insert(upvar_id, capture_kind);
167 ///////////////////////////////////////////////////////////////////////////
168 // ADJUST BORROW KIND
170 struct AdjustBorrowKind<'a,'tcx:'a> {
171 fcx: &'a FnCtxt<'a,'tcx>,
172 closures_with_inferred_kinds: &'a HashSet<ast::NodeId>,
175 impl<'a,'tcx> AdjustBorrowKind<'a,'tcx> {
176 fn new(fcx: &'a FnCtxt<'a,'tcx>,
177 closures_with_inferred_kinds: &'a HashSet<ast::NodeId>)
178 -> AdjustBorrowKind<'a,'tcx> {
179 AdjustBorrowKind { fcx: fcx, closures_with_inferred_kinds: closures_with_inferred_kinds }
182 fn analyze_closure(&mut self,
188 * Analysis starting point.
191 debug!("analyze_closure(id={:?}, body.id={:?})", id, body.id);
194 let mut euv = euv::ExprUseVisitor::new(self, self.fcx.infcx());
195 euv.walk_fn(decl, body);
198 // Now that we've analyzed the closure, we know how each
199 // variable is borrowed, and we know what traits the closure
200 // implements (Fn vs FnMut etc). We now have some updates to do
201 // with that information.
203 // Note that no closure type C may have an upvar of type C
204 // (though it may reference itself via a trait object). This
205 // results from the desugaring of closures to a struct like
206 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
207 // C, then the type would have infinite size (and the
208 // inference algorithm will reject it).
210 // Extract the type variables UV0...UVn.
211 let closure_substs = match self.fcx.node_ty(id).sty {
212 ty::TyClosure(_, ref substs) => substs,
214 self.fcx.tcx().sess.span_bug(
216 &format!("type of closure expr {:?} is not a closure {:?}",
221 // Equate the type variables with the actual types.
222 let final_upvar_tys = self.final_upvar_tys(id);
223 debug!("analyze_closure: id={:?} closure_substs={:?} final_upvar_tys={:?}",
224 id, closure_substs, final_upvar_tys);
225 for (&upvar_ty, final_upvar_ty) in closure_substs.upvar_tys.iter().zip(final_upvar_tys) {
226 demand::eqtype(self.fcx, span, final_upvar_ty, upvar_ty);
229 // Now we must process and remove any deferred resolutions,
230 // since we have a concrete closure kind.
231 let closure_def_id = self.fcx.tcx().map.local_def_id(id);
232 if self.closures_with_inferred_kinds.contains(&id) {
233 let mut deferred_call_resolutions =
234 self.fcx.remove_deferred_call_resolutions(closure_def_id);
235 for deferred_call_resolution in &mut deferred_call_resolutions {
236 deferred_call_resolution.resolve(self.fcx);
241 // Returns a list of `ClosureUpvar`s for each upvar.
242 fn final_upvar_tys(&mut self, closure_id: ast::NodeId) -> Vec<Ty<'tcx>> {
243 // Presently an unboxed closure type cannot "escape" out of a
244 // function, so we will only encounter ones that originated in the
245 // local crate or were inlined into it along with some function.
246 // This may change if abstract return types of some sort are
248 let tcx = self.fcx.tcx();
249 tcx.with_freevars(closure_id, |freevars| {
252 let freevar_node_id = freevar.def.var_id();
253 let freevar_ty = self.fcx.node_ty(freevar_node_id);
254 let upvar_id = ty::UpvarId {
255 var_id: freevar_node_id,
256 closure_expr_id: closure_id
258 let capture = self.fcx.infcx().upvar_capture(upvar_id).unwrap();
260 debug!("freevar_node_id={:?} freevar_ty={:?} capture={:?}",
261 freevar_node_id, freevar_ty, capture);
264 ty::UpvarCapture::ByValue => freevar_ty,
265 ty::UpvarCapture::ByRef(borrow) =>
266 tcx.mk_ref(tcx.mk_region(borrow.region),
269 mutbl: borrow.kind.to_mutbl_lossy(),
277 fn adjust_upvar_borrow_kind_for_consume(&self,
279 mode: euv::ConsumeMode)
281 debug!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
284 // we only care about moves
286 euv::Copy => { return; }
290 // watch out for a move of the deref of a borrowed pointer;
291 // for that to be legal, the upvar would have to be borrowed
293 let guarantor = cmt.guarantor();
294 debug!("adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
296 match guarantor.cat {
297 mc::cat_deref(_, _, mc::BorrowedPtr(..)) |
298 mc::cat_deref(_, _, mc::Implicit(..)) => {
300 mc::NoteUpvarRef(upvar_id) => {
301 debug!("adjust_upvar_borrow_kind_for_consume: \
302 setting upvar_id={:?} to by value",
305 // to move out of an upvar, this must be a FnOnce closure
306 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnOnceClosureKind);
308 let upvar_capture_map =
309 &mut self.fcx.inh.tables.borrow_mut().upvar_capture_map;
310 upvar_capture_map.insert(upvar_id, ty::UpvarCapture::ByValue);
312 mc::NoteClosureEnv(upvar_id) => {
313 // we get just a closureenv ref if this is a
314 // `move` closure, or if the upvar has already
315 // been inferred to by-value. In any case, we
316 // must still adjust the kind of the closure
317 // to be a FnOnce closure to permit moves out
318 // of the environment.
319 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnOnceClosureKind);
329 /// Indicates that `cmt` is being directly mutated (e.g., assigned
330 /// to). If cmt contains any by-ref upvars, this implies that
331 /// those upvars must be borrowed using an `&mut` borrow.
332 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
333 debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})",
336 match cmt.cat.clone() {
337 mc::cat_deref(base, _, mc::Unique) |
338 mc::cat_interior(base, _) |
339 mc::cat_downcast(base, _) => {
340 // Interior or owned data is mutable if base is
341 // mutable, so iterate to the base.
342 self.adjust_upvar_borrow_kind_for_mut(base);
345 mc::cat_deref(base, _, mc::BorrowedPtr(..)) |
346 mc::cat_deref(base, _, mc::Implicit(..)) => {
347 if !self.try_adjust_upvar_deref(&cmt.note, ty::MutBorrow) {
348 // assignment to deref of an `&mut`
349 // borrowed pointer implies that the
350 // pointer itself must be unique, but not
351 // necessarily *mutable*
352 self.adjust_upvar_borrow_kind_for_unique(base);
356 mc::cat_deref(_, _, mc::UnsafePtr(..)) |
357 mc::cat_static_item |
360 mc::cat_upvar(..) => {
366 fn adjust_upvar_borrow_kind_for_unique(&self, cmt: mc::cmt<'tcx>) {
367 debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})",
370 match cmt.cat.clone() {
371 mc::cat_deref(base, _, mc::Unique) |
372 mc::cat_interior(base, _) |
373 mc::cat_downcast(base, _) => {
374 // Interior or owned data is unique if base is
376 self.adjust_upvar_borrow_kind_for_unique(base);
379 mc::cat_deref(base, _, mc::BorrowedPtr(..)) |
380 mc::cat_deref(base, _, mc::Implicit(..)) => {
381 if !self.try_adjust_upvar_deref(&cmt.note, ty::UniqueImmBorrow) {
382 // for a borrowed pointer to be unique, its
383 // base must be unique
384 self.adjust_upvar_borrow_kind_for_unique(base);
388 mc::cat_deref(_, _, mc::UnsafePtr(..)) |
389 mc::cat_static_item |
392 mc::cat_upvar(..) => {
397 fn try_adjust_upvar_deref(&self,
399 borrow_kind: ty::BorrowKind)
402 assert!(match borrow_kind {
403 ty::MutBorrow => true,
404 ty::UniqueImmBorrow => true,
406 // imm borrows never require adjusting any kinds, so we don't wind up here
407 ty::ImmBorrow => false,
411 mc::NoteUpvarRef(upvar_id) => {
412 // if this is an implicit deref of an
413 // upvar, then we need to modify the
414 // borrow_kind of the upvar to make sure it
415 // is inferred to mutable if necessary
417 let upvar_capture_map = &mut self.fcx.inh.tables.borrow_mut().upvar_capture_map;
418 let ub = upvar_capture_map.get_mut(&upvar_id).unwrap();
419 self.adjust_upvar_borrow_kind(upvar_id, ub, borrow_kind);
422 // also need to be in an FnMut closure since this is not an ImmBorrow
423 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnMutClosureKind);
427 mc::NoteClosureEnv(upvar_id) => {
428 // this kind of deref occurs in a `move` closure, or
429 // for a by-value upvar; in either case, to mutate an
430 // upvar, we need to be an FnMut closure
431 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnMutClosureKind);
441 /// We infer the borrow_kind with which to borrow upvars in a stack closure. The borrow_kind
442 /// basically follows a lattice of `imm < unique-imm < mut`, moving from left to right as needed
443 /// (but never right to left). Here the argument `mutbl` is the borrow_kind that is required by
444 /// some particular use.
445 fn adjust_upvar_borrow_kind(&self,
446 upvar_id: ty::UpvarId,
447 upvar_capture: &mut ty::UpvarCapture,
448 kind: ty::BorrowKind) {
449 debug!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
450 upvar_id, upvar_capture, kind);
452 match *upvar_capture {
453 ty::UpvarCapture::ByValue => {
454 // Upvar is already by-value, the strongest criteria.
456 ty::UpvarCapture::ByRef(ref mut upvar_borrow) => {
457 match (upvar_borrow.kind, kind) {
459 (ty::ImmBorrow, ty::UniqueImmBorrow) |
460 (ty::ImmBorrow, ty::MutBorrow) |
461 (ty::UniqueImmBorrow, ty::MutBorrow) => {
462 upvar_borrow.kind = kind;
465 (ty::ImmBorrow, ty::ImmBorrow) |
466 (ty::UniqueImmBorrow, ty::ImmBorrow) |
467 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
468 (ty::MutBorrow, _) => {
475 fn adjust_closure_kind(&self,
476 closure_id: ast::NodeId,
477 new_kind: ty::ClosureKind) {
478 debug!("adjust_closure_kind(closure_id={}, new_kind={:?})",
479 closure_id, new_kind);
481 if !self.closures_with_inferred_kinds.contains(&closure_id) {
485 let closure_def_id = self.fcx.tcx().map.local_def_id(closure_id);
486 let closure_kinds = &mut self.fcx.inh.tables.borrow_mut().closure_kinds;
487 let existing_kind = *closure_kinds.get(&closure_def_id).unwrap();
489 debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
490 closure_id, existing_kind, new_kind);
492 match (existing_kind, new_kind) {
493 (ty::FnClosureKind, ty::FnClosureKind) |
494 (ty::FnMutClosureKind, ty::FnClosureKind) |
495 (ty::FnMutClosureKind, ty::FnMutClosureKind) |
496 (ty::FnOnceClosureKind, _) => {
500 (ty::FnClosureKind, ty::FnMutClosureKind) |
501 (ty::FnClosureKind, ty::FnOnceClosureKind) |
502 (ty::FnMutClosureKind, ty::FnOnceClosureKind) => {
503 // new kind is stronger than the old kind
504 closure_kinds.insert(closure_def_id, new_kind);
510 impl<'a, 'tcx, 'v> Visitor<'v> for AdjustBorrowKind<'a, 'tcx> {
511 fn visit_fn(&mut self,
512 fn_kind: visit::FnKind<'v>,
513 decl: &'v hir::FnDecl,
514 body: &'v hir::Block,
518 visit::walk_fn(self, fn_kind, decl, body, span);
519 self.analyze_closure(id, span, decl, body);
522 // Skip all items; they aren't in the same context.
523 fn visit_item(&mut self, _: &'v hir::Item) { }
526 impl<'a,'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a,'tcx> {
527 fn consume(&mut self,
528 _consume_id: ast::NodeId,
531 mode: euv::ConsumeMode)
533 debug!("consume(cmt={:?},mode={:?})", cmt, mode);
534 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
537 fn matched_pat(&mut self,
538 _matched_pat: &hir::Pat,
540 _mode: euv::MatchMode)
543 fn consume_pat(&mut self,
544 _consume_pat: &hir::Pat,
546 mode: euv::ConsumeMode)
548 debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode);
549 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
553 borrow_id: ast::NodeId,
556 _loan_region: ty::Region,
558 _loan_cause: euv::LoanCause)
560 debug!("borrow(borrow_id={}, cmt={:?}, bk={:?})",
565 ty::UniqueImmBorrow => {
566 self.adjust_upvar_borrow_kind_for_unique(cmt);
569 self.adjust_upvar_borrow_kind_for_mut(cmt);
574 fn decl_without_init(&mut self,
580 _assignment_id: ast::NodeId,
581 _assignment_span: Span,
582 assignee_cmt: mc::cmt<'tcx>,
583 _mode: euv::MutateMode)
585 debug!("mutate(assignee_cmt={:?})",
588 self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);