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::mem_categorization::Categorization;
48 use rustc::ty::{self, Ty};
49 use rustc::infer::UpvarRegion;
53 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
54 use rustc::util::nodemap::NodeMap;
56 ///////////////////////////////////////////////////////////////////////////
57 // PUBLIC ENTRY POINTS
59 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
60 pub fn closure_analyze(&self, body: &'gcx hir::Body) {
61 let mut seed = SeedBorrowKind::new(self);
62 seed.visit_body(body);
64 let mut adjust = AdjustBorrowKind::new(self, seed.temp_closure_kinds);
65 adjust.visit_body(body);
67 // it's our job to process these.
68 assert!(self.deferred_call_resolutions.borrow().is_empty());
72 ///////////////////////////////////////////////////////////////////////////
75 struct SeedBorrowKind<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
76 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
77 temp_closure_kinds: NodeMap<ty::ClosureKind>,
80 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for SeedBorrowKind<'a, 'gcx, 'tcx> {
81 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
82 NestedVisitorMap::None
85 fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
87 hir::ExprClosure(cc, _, body_id, _) => {
88 let body = self.fcx.tcx.hir.body(body_id);
89 self.visit_body(body);
90 self.check_closure(expr, cc);
96 intravisit::walk_expr(self, expr);
100 impl<'a, 'gcx, 'tcx> SeedBorrowKind<'a, 'gcx, 'tcx> {
101 fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>) -> SeedBorrowKind<'a, 'gcx, 'tcx> {
102 SeedBorrowKind { fcx: fcx, temp_closure_kinds: NodeMap() }
105 fn check_closure(&mut self,
107 capture_clause: hir::CaptureClause)
109 if !self.fcx.tables.borrow().closure_kinds.contains_key(&expr.id) {
110 self.temp_closure_kinds.insert(expr.id, ty::ClosureKind::Fn);
111 debug!("check_closure: adding closure {:?} as Fn", expr.id);
114 self.fcx.tcx.with_freevars(expr.id, |freevars| {
115 for freevar in freevars {
116 let def_id = freevar.def.def_id();
117 let var_node_id = self.fcx.tcx.hir.as_local_node_id(def_id).unwrap();
118 let upvar_id = ty::UpvarId { var_id: var_node_id,
119 closure_expr_id: expr.id };
120 debug!("seed upvar_id {:?}", upvar_id);
122 let capture_kind = match capture_clause {
123 hir::CaptureByValue => {
124 ty::UpvarCapture::ByValue
126 hir::CaptureByRef => {
127 let origin = UpvarRegion(upvar_id, expr.span);
128 let freevar_region = self.fcx.next_region_var(origin);
129 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow,
130 region: freevar_region };
131 ty::UpvarCapture::ByRef(upvar_borrow)
135 self.fcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, capture_kind);
141 ///////////////////////////////////////////////////////////////////////////
142 // ADJUST BORROW KIND
144 struct AdjustBorrowKind<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
145 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
146 temp_closure_kinds: NodeMap<ty::ClosureKind>,
149 impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> {
150 fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
151 temp_closure_kinds: NodeMap<ty::ClosureKind>)
152 -> AdjustBorrowKind<'a, 'gcx, 'tcx> {
153 AdjustBorrowKind { fcx: fcx, temp_closure_kinds: temp_closure_kinds }
156 fn analyze_closure(&mut self,
161 * Analysis starting point.
164 debug!("analyze_closure(id={:?}, body.id={:?})", id, body.id());
167 let body_owner_def_id = self.fcx.tcx.hir.body_owner_def_id(body.id());
168 let region_maps = &self.fcx.tcx.region_maps(body_owner_def_id);
170 euv::ExprUseVisitor::with_options(self,
173 mc::MemCategorizationOptions {
174 during_closure_kind_inference: true
176 euv.consume_body(body);
179 // Now that we've analyzed the closure, we know how each
180 // variable is borrowed, and we know what traits the closure
181 // implements (Fn vs FnMut etc). We now have some updates to do
182 // with that information.
184 // Note that no closure type C may have an upvar of type C
185 // (though it may reference itself via a trait object). This
186 // results from the desugaring of closures to a struct like
187 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
188 // C, then the type would have infinite size (and the
189 // inference algorithm will reject it).
191 // Extract the type variables UV0...UVn.
192 let (def_id, closure_substs) = match self.fcx.node_ty(id).sty {
193 ty::TyClosure(def_id, substs) => (def_id, substs),
197 "type of closure expr {:?} is not a closure {:?}",
202 // Equate the type variables with the actual types.
203 let final_upvar_tys = self.final_upvar_tys(id);
204 debug!("analyze_closure: id={:?} closure_substs={:?} final_upvar_tys={:?}",
205 id, closure_substs, final_upvar_tys);
206 for (upvar_ty, final_upvar_ty) in
207 closure_substs.upvar_tys(def_id, self.fcx.tcx).zip(final_upvar_tys)
209 self.fcx.demand_eqtype(span, final_upvar_ty, upvar_ty);
212 // If we are also inferred the closure kind here, update the
213 // main table and process any deferred resolutions.
214 if let Some(&kind) = self.temp_closure_kinds.get(&id) {
215 self.fcx.tables.borrow_mut().closure_kinds.insert(id, kind);
216 let closure_def_id = self.fcx.tcx.hir.local_def_id(id);
217 debug!("closure_kind({:?}) = {:?}", closure_def_id, kind);
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| {
236 freevars.iter().map(|freevar| {
237 let def_id = freevar.def.def_id();
238 let var_id = tcx.hir.as_local_node_id(def_id).unwrap();
239 let freevar_ty = self.fcx.node_ty(var_id);
240 let upvar_id = ty::UpvarId {
242 closure_expr_id: closure_id
244 let capture = self.fcx.upvar_capture(upvar_id).unwrap();
246 debug!("var_id={:?} freevar_ty={:?} capture={:?}",
247 var_id, freevar_ty, capture);
250 ty::UpvarCapture::ByValue => freevar_ty,
251 ty::UpvarCapture::ByRef(borrow) =>
252 tcx.mk_ref(borrow.region,
255 mutbl: borrow.kind.to_mutbl_lossy(),
262 fn adjust_upvar_borrow_kind_for_consume(&mut self,
264 mode: euv::ConsumeMode)
266 debug!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
269 // we only care about moves
271 euv::Copy => { return; }
275 // watch out for a move of the deref of a borrowed pointer;
276 // for that to be legal, the upvar would have to be borrowed
278 let guarantor = cmt.guarantor();
279 debug!("adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
281 match guarantor.cat {
282 Categorization::Deref(.., mc::BorrowedPtr(..)) |
283 Categorization::Deref(.., mc::Implicit(..)) => {
285 mc::NoteUpvarRef(upvar_id) => {
286 debug!("adjust_upvar_borrow_kind_for_consume: \
287 setting upvar_id={:?} to by value",
290 // to move out of an upvar, this must be a FnOnce closure
291 self.adjust_closure_kind(upvar_id.closure_expr_id,
292 ty::ClosureKind::FnOnce);
294 let upvar_capture_map =
295 &mut self.fcx.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,
306 ty::ClosureKind::FnOnce);
316 /// Indicates that `cmt` is being directly mutated (e.g., assigned
317 /// to). If cmt contains any by-ref upvars, this implies that
318 /// those upvars must be borrowed using an `&mut` borrow.
319 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
320 debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})",
323 match cmt.cat.clone() {
324 Categorization::Deref(base, _, mc::Unique) |
325 Categorization::Interior(base, _) |
326 Categorization::Downcast(base, _) => {
327 // Interior or owned data is mutable if base is
328 // mutable, so iterate to the base.
329 self.adjust_upvar_borrow_kind_for_mut(base);
332 Categorization::Deref(base, _, mc::BorrowedPtr(..)) |
333 Categorization::Deref(base, _, mc::Implicit(..)) => {
334 if !self.try_adjust_upvar_deref(&cmt.note, ty::MutBorrow) {
335 // assignment to deref of an `&mut`
336 // borrowed pointer implies that the
337 // pointer itself must be unique, but not
338 // necessarily *mutable*
339 self.adjust_upvar_borrow_kind_for_unique(base);
343 Categorization::Deref(.., mc::UnsafePtr(..)) |
344 Categorization::StaticItem |
345 Categorization::Rvalue(..) |
346 Categorization::Local(_) |
347 Categorization::Upvar(..) => {
353 fn adjust_upvar_borrow_kind_for_unique(&mut self, cmt: mc::cmt<'tcx>) {
354 debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})",
357 match cmt.cat.clone() {
358 Categorization::Deref(base, _, mc::Unique) |
359 Categorization::Interior(base, _) |
360 Categorization::Downcast(base, _) => {
361 // Interior or owned data is unique if base is
363 self.adjust_upvar_borrow_kind_for_unique(base);
366 Categorization::Deref(base, _, mc::BorrowedPtr(..)) |
367 Categorization::Deref(base, _, mc::Implicit(..)) => {
368 if !self.try_adjust_upvar_deref(&cmt.note, ty::UniqueImmBorrow) {
369 // for a borrowed pointer to be unique, its
370 // base must be unique
371 self.adjust_upvar_borrow_kind_for_unique(base);
375 Categorization::Deref(.., mc::UnsafePtr(..)) |
376 Categorization::StaticItem |
377 Categorization::Rvalue(..) |
378 Categorization::Local(_) |
379 Categorization::Upvar(..) => {
384 fn try_adjust_upvar_deref(&mut self,
386 borrow_kind: ty::BorrowKind)
389 assert!(match borrow_kind {
390 ty::MutBorrow => true,
391 ty::UniqueImmBorrow => true,
393 // imm borrows never require adjusting any kinds, so we don't wind up here
394 ty::ImmBorrow => false,
398 mc::NoteUpvarRef(upvar_id) => {
399 // if this is an implicit deref of an
400 // upvar, then we need to modify the
401 // borrow_kind of the upvar to make sure it
402 // is inferred to mutable if necessary
404 let upvar_capture_map = &mut self.fcx.tables.borrow_mut().upvar_capture_map;
405 let ub = upvar_capture_map.get_mut(&upvar_id).unwrap();
406 self.adjust_upvar_borrow_kind(upvar_id, ub, borrow_kind);
409 // also need to be in an FnMut closure since this is not an ImmBorrow
410 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::ClosureKind::FnMut);
414 mc::NoteClosureEnv(upvar_id) => {
415 // this kind of deref occurs in a `move` closure, or
416 // for a by-value upvar; in either case, to mutate an
417 // upvar, we need to be an FnMut closure
418 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::ClosureKind::FnMut);
428 /// We infer the borrow_kind with which to borrow upvars in a stack closure.
429 /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
430 /// moving from left to right as needed (but never right to left).
431 /// Here the argument `mutbl` is the borrow_kind that is required by
432 /// some particular use.
433 fn adjust_upvar_borrow_kind(&mut self,
434 upvar_id: ty::UpvarId,
435 upvar_capture: &mut ty::UpvarCapture,
436 kind: ty::BorrowKind) {
437 debug!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
438 upvar_id, upvar_capture, kind);
440 match *upvar_capture {
441 ty::UpvarCapture::ByValue => {
442 // Upvar is already by-value, the strongest criteria.
444 ty::UpvarCapture::ByRef(ref mut upvar_borrow) => {
445 match (upvar_borrow.kind, kind) {
447 (ty::ImmBorrow, ty::UniqueImmBorrow) |
448 (ty::ImmBorrow, ty::MutBorrow) |
449 (ty::UniqueImmBorrow, ty::MutBorrow) => {
450 upvar_borrow.kind = kind;
453 (ty::ImmBorrow, ty::ImmBorrow) |
454 (ty::UniqueImmBorrow, ty::ImmBorrow) |
455 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
456 (ty::MutBorrow, _) => {
463 fn adjust_closure_kind(&mut self,
464 closure_id: ast::NodeId,
465 new_kind: ty::ClosureKind) {
466 debug!("adjust_closure_kind(closure_id={}, new_kind={:?})",
467 closure_id, new_kind);
469 if let Some(&existing_kind) = self.temp_closure_kinds.get(&closure_id) {
470 debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
471 closure_id, existing_kind, new_kind);
473 match (existing_kind, new_kind) {
474 (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
475 (ty::ClosureKind::FnMut, ty::ClosureKind::Fn) |
476 (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
477 (ty::ClosureKind::FnOnce, _) => {
481 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) |
482 (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
483 (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
484 // new kind is stronger than the old kind
485 self.temp_closure_kinds.insert(closure_id, new_kind);
492 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for AdjustBorrowKind<'a, 'gcx, 'tcx> {
493 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
494 NestedVisitorMap::None
497 fn visit_fn(&mut self,
498 fn_kind: intravisit::FnKind<'gcx>,
499 decl: &'gcx hir::FnDecl,
504 intravisit::walk_fn(self, fn_kind, decl, body, span, id);
506 let body = self.fcx.tcx.hir.body(body);
507 self.visit_body(body);
508 self.analyze_closure(id, span, body);
512 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a, 'gcx, '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: &hir::Pat,
526 _mode: euv::MatchMode)
529 fn consume_pat(&mut self,
530 _consume_pat: &hir::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<'tcx>,
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);