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::mem_categorization::Categorization;
49 use middle::ty::{self, Ty};
50 use middle::infer::{InferCtxt, UpvarRegion};
51 use std::collections::HashSet;
53 use syntax::codemap::Span;
55 use rustc_front::visit::{self, Visitor};
57 ///////////////////////////////////////////////////////////////////////////
58 // PUBLIC ENTRY POINTS
60 pub fn closure_analyze_fn(fcx: &FnCtxt,
65 let mut seed = SeedBorrowKind::new(fcx);
66 seed.visit_block(body);
67 let closures_with_inferred_kinds = seed.closures_with_inferred_kinds;
69 let mut adjust = AdjustBorrowKind::new(fcx, &closures_with_inferred_kinds);
70 adjust.visit_block(body);
72 // it's our job to process these.
73 assert!(fcx.inh.deferred_call_resolutions.borrow().is_empty());
76 pub fn closure_analyze_const(fcx: &FnCtxt,
79 let mut seed = SeedBorrowKind::new(fcx);
80 seed.visit_expr(body);
81 let closures_with_inferred_kinds = seed.closures_with_inferred_kinds;
83 let mut adjust = AdjustBorrowKind::new(fcx, &closures_with_inferred_kinds);
84 adjust.visit_expr(body);
86 // it's our job to process these.
87 assert!(fcx.inh.deferred_call_resolutions.borrow().is_empty());
90 ///////////////////////////////////////////////////////////////////////////
93 struct SeedBorrowKind<'a,'tcx:'a> {
94 fcx: &'a FnCtxt<'a,'tcx>,
95 closures_with_inferred_kinds: HashSet<ast::NodeId>,
98 impl<'a, 'tcx, 'v> Visitor<'v> for SeedBorrowKind<'a, 'tcx> {
99 fn visit_expr(&mut self, expr: &hir::Expr) {
101 hir::ExprClosure(cc, _, ref body) => {
102 self.check_closure(expr, cc, &**body);
108 visit::walk_expr(self, expr);
111 // Skip all items; they aren't in the same context.
112 fn visit_item(&mut self, _: &'v hir::Item) { }
115 impl<'a,'tcx> SeedBorrowKind<'a,'tcx> {
116 fn new(fcx: &'a FnCtxt<'a,'tcx>) -> SeedBorrowKind<'a,'tcx> {
117 SeedBorrowKind { fcx: fcx, closures_with_inferred_kinds: HashSet::new() }
120 fn tcx(&self) -> &'a ty::ctxt<'tcx> {
124 fn infcx(&self) -> &'a InferCtxt<'a,'tcx> {
128 fn check_closure(&mut self,
130 capture_clause: hir::CaptureClause,
133 let closure_def_id = self.tcx().map.local_def_id(expr.id);
134 if !self.fcx.inh.tables.borrow().closure_kinds.contains_key(&closure_def_id) {
135 self.closures_with_inferred_kinds.insert(expr.id);
136 self.fcx.inh.tables.borrow_mut().closure_kinds
137 .insert(closure_def_id, ty::FnClosureKind);
138 debug!("check_closure: adding closure_id={:?} to closures_with_inferred_kinds",
142 self.tcx().with_freevars(expr.id, |freevars| {
143 for freevar in freevars {
144 let var_node_id = freevar.def.var_id();
145 let upvar_id = ty::UpvarId { var_id: var_node_id,
146 closure_expr_id: expr.id };
147 debug!("seed upvar_id {:?}", upvar_id);
149 let capture_kind = match capture_clause {
150 hir::CaptureByValue => {
151 ty::UpvarCapture::ByValue
153 hir::CaptureByRef => {
154 let origin = UpvarRegion(upvar_id, expr.span);
155 let freevar_region = self.infcx().next_region_var(origin);
156 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow,
157 region: freevar_region };
158 ty::UpvarCapture::ByRef(upvar_borrow)
162 self.fcx.inh.tables.borrow_mut().upvar_capture_map.insert(upvar_id, capture_kind);
168 ///////////////////////////////////////////////////////////////////////////
169 // ADJUST BORROW KIND
171 struct AdjustBorrowKind<'a,'tcx:'a> {
172 fcx: &'a FnCtxt<'a,'tcx>,
173 closures_with_inferred_kinds: &'a HashSet<ast::NodeId>,
176 impl<'a,'tcx> AdjustBorrowKind<'a,'tcx> {
177 fn new(fcx: &'a FnCtxt<'a,'tcx>,
178 closures_with_inferred_kinds: &'a HashSet<ast::NodeId>)
179 -> AdjustBorrowKind<'a,'tcx> {
180 AdjustBorrowKind { fcx: fcx, closures_with_inferred_kinds: closures_with_inferred_kinds }
183 fn analyze_closure(&mut self,
189 * Analysis starting point.
192 debug!("analyze_closure(id={:?}, body.id={:?})", id, body.id);
195 let mut euv = euv::ExprUseVisitor::new(self, self.fcx.infcx());
196 euv.walk_fn(decl, body);
199 // Now that we've analyzed the closure, we know how each
200 // variable is borrowed, and we know what traits the closure
201 // implements (Fn vs FnMut etc). We now have some updates to do
202 // with that information.
204 // Note that no closure type C may have an upvar of type C
205 // (though it may reference itself via a trait object). This
206 // results from the desugaring of closures to a struct like
207 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
208 // C, then the type would have infinite size (and the
209 // inference algorithm will reject it).
211 // Extract the type variables UV0...UVn.
212 let closure_substs = match self.fcx.node_ty(id).sty {
213 ty::TyClosure(_, ref substs) => substs,
215 self.fcx.tcx().sess.span_bug(
217 &format!("type of closure expr {:?} is not a closure {:?}",
222 // Equate the type variables with the actual types.
223 let final_upvar_tys = self.final_upvar_tys(id);
224 debug!("analyze_closure: id={:?} closure_substs={:?} final_upvar_tys={:?}",
225 id, closure_substs, final_upvar_tys);
226 for (&upvar_ty, final_upvar_ty) in closure_substs.upvar_tys.iter().zip(final_upvar_tys) {
227 demand::eqtype(self.fcx, span, final_upvar_ty, upvar_ty);
230 // Now we must process and remove any deferred resolutions,
231 // since we have a concrete closure kind.
232 let closure_def_id = self.fcx.tcx().map.local_def_id(id);
233 if self.closures_with_inferred_kinds.contains(&id) {
234 let mut deferred_call_resolutions =
235 self.fcx.remove_deferred_call_resolutions(closure_def_id);
236 for deferred_call_resolution in &mut deferred_call_resolutions {
237 deferred_call_resolution.resolve(self.fcx);
242 // Returns a list of `ClosureUpvar`s for each upvar.
243 fn final_upvar_tys(&mut self, closure_id: ast::NodeId) -> Vec<Ty<'tcx>> {
244 // Presently an unboxed closure type cannot "escape" out of a
245 // function, so we will only encounter ones that originated in the
246 // local crate or were inlined into it along with some function.
247 // This may change if abstract return types of some sort are
249 let tcx = self.fcx.tcx();
250 tcx.with_freevars(closure_id, |freevars| {
253 let freevar_node_id = freevar.def.var_id();
254 let freevar_ty = self.fcx.node_ty(freevar_node_id);
255 let upvar_id = ty::UpvarId {
256 var_id: freevar_node_id,
257 closure_expr_id: closure_id
259 let capture = self.fcx.infcx().upvar_capture(upvar_id).unwrap();
261 debug!("freevar_node_id={:?} freevar_ty={:?} capture={:?}",
262 freevar_node_id, freevar_ty, capture);
265 ty::UpvarCapture::ByValue => freevar_ty,
266 ty::UpvarCapture::ByRef(borrow) =>
267 tcx.mk_ref(tcx.mk_region(borrow.region),
270 mutbl: borrow.kind.to_mutbl_lossy(),
278 fn adjust_upvar_borrow_kind_for_consume(&self,
280 mode: euv::ConsumeMode)
282 debug!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
285 // we only care about moves
287 euv::Copy => { return; }
291 // watch out for a move of the deref of a borrowed pointer;
292 // for that to be legal, the upvar would have to be borrowed
294 let guarantor = cmt.guarantor();
295 debug!("adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
297 match guarantor.cat {
298 Categorization::Deref(_, _, mc::BorrowedPtr(..)) |
299 Categorization::Deref(_, _, mc::Implicit(..)) => {
301 mc::NoteUpvarRef(upvar_id) => {
302 debug!("adjust_upvar_borrow_kind_for_consume: \
303 setting upvar_id={:?} to by value",
306 // to move out of an upvar, this must be a FnOnce closure
307 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnOnceClosureKind);
309 let upvar_capture_map =
310 &mut self.fcx.inh.tables.borrow_mut().upvar_capture_map;
311 upvar_capture_map.insert(upvar_id, ty::UpvarCapture::ByValue);
313 mc::NoteClosureEnv(upvar_id) => {
314 // we get just a closureenv ref if this is a
315 // `move` closure, or if the upvar has already
316 // been inferred to by-value. In any case, we
317 // must still adjust the kind of the closure
318 // to be a FnOnce closure to permit moves out
319 // of the environment.
320 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnOnceClosureKind);
330 /// Indicates that `cmt` is being directly mutated (e.g., assigned
331 /// to). If cmt contains any by-ref upvars, this implies that
332 /// those upvars must be borrowed using an `&mut` borrow.
333 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
334 debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})",
337 match cmt.cat.clone() {
338 Categorization::Deref(base, _, mc::Unique) |
339 Categorization::Interior(base, _) |
340 Categorization::Downcast(base, _) => {
341 // Interior or owned data is mutable if base is
342 // mutable, so iterate to the base.
343 self.adjust_upvar_borrow_kind_for_mut(base);
346 Categorization::Deref(base, _, mc::BorrowedPtr(..)) |
347 Categorization::Deref(base, _, mc::Implicit(..)) => {
348 if !self.try_adjust_upvar_deref(&cmt.note, ty::MutBorrow) {
349 // assignment to deref of an `&mut`
350 // borrowed pointer implies that the
351 // pointer itself must be unique, but not
352 // necessarily *mutable*
353 self.adjust_upvar_borrow_kind_for_unique(base);
357 Categorization::Deref(_, _, mc::UnsafePtr(..)) |
358 Categorization::StaticItem |
359 Categorization::Rvalue(_) |
360 Categorization::Local(_) |
361 Categorization::Upvar(..) => {
367 fn adjust_upvar_borrow_kind_for_unique(&self, cmt: mc::cmt<'tcx>) {
368 debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})",
371 match cmt.cat.clone() {
372 Categorization::Deref(base, _, mc::Unique) |
373 Categorization::Interior(base, _) |
374 Categorization::Downcast(base, _) => {
375 // Interior or owned data is unique if base is
377 self.adjust_upvar_borrow_kind_for_unique(base);
380 Categorization::Deref(base, _, mc::BorrowedPtr(..)) |
381 Categorization::Deref(base, _, mc::Implicit(..)) => {
382 if !self.try_adjust_upvar_deref(&cmt.note, ty::UniqueImmBorrow) {
383 // for a borrowed pointer to be unique, its
384 // base must be unique
385 self.adjust_upvar_borrow_kind_for_unique(base);
389 Categorization::Deref(_, _, mc::UnsafePtr(..)) |
390 Categorization::StaticItem |
391 Categorization::Rvalue(_) |
392 Categorization::Local(_) |
393 Categorization::Upvar(..) => {
398 fn try_adjust_upvar_deref(&self,
400 borrow_kind: ty::BorrowKind)
403 assert!(match borrow_kind {
404 ty::MutBorrow => true,
405 ty::UniqueImmBorrow => true,
407 // imm borrows never require adjusting any kinds, so we don't wind up here
408 ty::ImmBorrow => false,
412 mc::NoteUpvarRef(upvar_id) => {
413 // if this is an implicit deref of an
414 // upvar, then we need to modify the
415 // borrow_kind of the upvar to make sure it
416 // is inferred to mutable if necessary
418 let upvar_capture_map = &mut self.fcx.inh.tables.borrow_mut().upvar_capture_map;
419 let ub = upvar_capture_map.get_mut(&upvar_id).unwrap();
420 self.adjust_upvar_borrow_kind(upvar_id, ub, borrow_kind);
423 // also need to be in an FnMut closure since this is not an ImmBorrow
424 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnMutClosureKind);
428 mc::NoteClosureEnv(upvar_id) => {
429 // this kind of deref occurs in a `move` closure, or
430 // for a by-value upvar; in either case, to mutate an
431 // upvar, we need to be an FnMut closure
432 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnMutClosureKind);
442 /// We infer the borrow_kind with which to borrow upvars in a stack closure. The borrow_kind
443 /// basically follows a lattice of `imm < unique-imm < mut`, moving from left to right as needed
444 /// (but never right to left). Here the argument `mutbl` is the borrow_kind that is required by
445 /// some particular use.
446 fn adjust_upvar_borrow_kind(&self,
447 upvar_id: ty::UpvarId,
448 upvar_capture: &mut ty::UpvarCapture,
449 kind: ty::BorrowKind) {
450 debug!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
451 upvar_id, upvar_capture, kind);
453 match *upvar_capture {
454 ty::UpvarCapture::ByValue => {
455 // Upvar is already by-value, the strongest criteria.
457 ty::UpvarCapture::ByRef(ref mut upvar_borrow) => {
458 match (upvar_borrow.kind, kind) {
460 (ty::ImmBorrow, ty::UniqueImmBorrow) |
461 (ty::ImmBorrow, ty::MutBorrow) |
462 (ty::UniqueImmBorrow, ty::MutBorrow) => {
463 upvar_borrow.kind = kind;
466 (ty::ImmBorrow, ty::ImmBorrow) |
467 (ty::UniqueImmBorrow, ty::ImmBorrow) |
468 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
469 (ty::MutBorrow, _) => {
476 fn adjust_closure_kind(&self,
477 closure_id: ast::NodeId,
478 new_kind: ty::ClosureKind) {
479 debug!("adjust_closure_kind(closure_id={}, new_kind={:?})",
480 closure_id, new_kind);
482 if !self.closures_with_inferred_kinds.contains(&closure_id) {
486 let closure_def_id = self.fcx.tcx().map.local_def_id(closure_id);
487 let closure_kinds = &mut self.fcx.inh.tables.borrow_mut().closure_kinds;
488 let existing_kind = *closure_kinds.get(&closure_def_id).unwrap();
490 debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
491 closure_id, existing_kind, new_kind);
493 match (existing_kind, new_kind) {
494 (ty::FnClosureKind, ty::FnClosureKind) |
495 (ty::FnMutClosureKind, ty::FnClosureKind) |
496 (ty::FnMutClosureKind, ty::FnMutClosureKind) |
497 (ty::FnOnceClosureKind, _) => {
501 (ty::FnClosureKind, ty::FnMutClosureKind) |
502 (ty::FnClosureKind, ty::FnOnceClosureKind) |
503 (ty::FnMutClosureKind, ty::FnOnceClosureKind) => {
504 // new kind is stronger than the old kind
505 closure_kinds.insert(closure_def_id, new_kind);
511 impl<'a, 'tcx, 'v> Visitor<'v> for AdjustBorrowKind<'a, 'tcx> {
512 fn visit_fn(&mut self,
513 fn_kind: visit::FnKind<'v>,
514 decl: &'v hir::FnDecl,
515 body: &'v hir::Block,
519 visit::walk_fn(self, fn_kind, decl, body, span);
520 self.analyze_closure(id, span, decl, body);
523 // Skip all items; they aren't in the same context.
524 fn visit_item(&mut self, _: &'v hir::Item) { }
527 impl<'a,'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a,'tcx> {
528 fn consume(&mut self,
529 _consume_id: ast::NodeId,
532 mode: euv::ConsumeMode)
534 debug!("consume(cmt={:?},mode={:?})", cmt, mode);
535 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
538 fn matched_pat(&mut self,
539 _matched_pat: &hir::Pat,
541 _mode: euv::MatchMode)
544 fn consume_pat(&mut self,
545 _consume_pat: &hir::Pat,
547 mode: euv::ConsumeMode)
549 debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode);
550 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
554 borrow_id: ast::NodeId,
557 _loan_region: ty::Region,
559 _loan_cause: euv::LoanCause)
561 debug!("borrow(borrow_id={}, cmt={:?}, bk={:?})",
566 ty::UniqueImmBorrow => {
567 self.adjust_upvar_borrow_kind_for_unique(cmt);
570 self.adjust_upvar_borrow_kind_for_mut(cmt);
575 fn decl_without_init(&mut self,
581 _assignment_id: ast::NodeId,
582 _assignment_span: Span,
583 assignee_cmt: mc::cmt<'tcx>,
584 _mode: euv::MutateMode)
586 debug!("mutate(assignee_cmt={:?})",
589 self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);