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};
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_fn(&self, body: &hir::Block) {
61 let mut seed = SeedBorrowKind::new(self);
62 seed.visit_block(body);
64 let mut adjust = AdjustBorrowKind::new(self, seed.temp_closure_kinds);
65 adjust.visit_block(body);
67 // it's our job to process these.
68 assert!(self.deferred_call_resolutions.borrow().is_empty());
71 pub fn closure_analyze_const(&self, body: &hir::Expr) {
72 let mut seed = SeedBorrowKind::new(self);
73 seed.visit_expr(body);
75 let mut adjust = AdjustBorrowKind::new(self, seed.temp_closure_kinds);
76 adjust.visit_expr(body);
78 // it's our job to process these.
79 assert!(self.deferred_call_resolutions.borrow().is_empty());
83 ///////////////////////////////////////////////////////////////////////////
86 struct SeedBorrowKind<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
87 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
88 temp_closure_kinds: NodeMap<ty::ClosureKind>,
91 impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for SeedBorrowKind<'a, 'gcx, 'tcx> {
92 fn visit_expr(&mut self, expr: &hir::Expr) {
94 hir::ExprClosure(cc, _, ref body, _) => {
95 self.check_closure(expr, cc, &body);
101 intravisit::walk_expr(self, expr);
105 impl<'a, 'gcx, 'tcx> SeedBorrowKind<'a, 'gcx, 'tcx> {
106 fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>) -> SeedBorrowKind<'a, 'gcx, 'tcx> {
107 SeedBorrowKind { fcx: fcx, temp_closure_kinds: NodeMap() }
110 fn check_closure(&mut self,
112 capture_clause: hir::CaptureClause,
115 let closure_def_id = self.fcx.tcx.map.local_def_id(expr.id);
116 if !self.fcx.tables.borrow().closure_kinds.contains_key(&closure_def_id) {
117 self.temp_closure_kinds.insert(expr.id, ty::ClosureKind::Fn);
118 debug!("check_closure: adding closure {:?} as Fn", expr.id);
121 self.fcx.tcx.with_freevars(expr.id, |freevars| {
122 for freevar in freevars {
123 let var_node_id = freevar.def.var_id();
124 let upvar_id = ty::UpvarId { var_id: var_node_id,
125 closure_expr_id: expr.id };
126 debug!("seed upvar_id {:?}", upvar_id);
128 let capture_kind = match capture_clause {
129 hir::CaptureByValue => {
130 ty::UpvarCapture::ByValue
132 hir::CaptureByRef => {
133 let origin = UpvarRegion(upvar_id, expr.span);
134 let freevar_region = self.fcx.next_region_var(origin);
135 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow,
136 region: freevar_region };
137 ty::UpvarCapture::ByRef(upvar_borrow)
141 self.fcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, capture_kind);
147 ///////////////////////////////////////////////////////////////////////////
148 // ADJUST BORROW KIND
150 struct AdjustBorrowKind<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
151 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
152 temp_closure_kinds: NodeMap<ty::ClosureKind>,
155 impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> {
156 fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
157 temp_closure_kinds: NodeMap<ty::ClosureKind>)
158 -> AdjustBorrowKind<'a, 'gcx, 'tcx> {
159 AdjustBorrowKind { fcx: fcx, temp_closure_kinds: temp_closure_kinds }
162 fn analyze_closure(&mut self,
168 * Analysis starting point.
171 debug!("analyze_closure(id={:?}, body.id={:?})", id, body.id);
175 euv::ExprUseVisitor::with_options(self,
177 mc::MemCategorizationOptions {
178 during_closure_kind_inference: true
180 euv.walk_fn(decl, body);
183 // Now that we've analyzed the closure, we know how each
184 // variable is borrowed, and we know what traits the closure
185 // implements (Fn vs FnMut etc). We now have some updates to do
186 // with that information.
188 // Note that no closure type C may have an upvar of type C
189 // (though it may reference itself via a trait object). This
190 // results from the desugaring of closures to a struct like
191 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
192 // C, then the type would have infinite size (and the
193 // inference algorithm will reject it).
195 // Extract the type variables UV0...UVn.
196 let closure_substs = match self.fcx.node_ty(id).sty {
197 ty::TyClosure(_, ref substs) => substs,
201 "type of closure expr {:?} is not a closure {:?}",
206 // Equate the type variables with the actual types.
207 let final_upvar_tys = self.final_upvar_tys(id);
208 debug!("analyze_closure: id={:?} closure_substs={:?} final_upvar_tys={:?}",
209 id, closure_substs, final_upvar_tys);
210 for (&upvar_ty, final_upvar_ty) in closure_substs.upvar_tys.iter().zip(final_upvar_tys) {
211 self.fcx.demand_eqtype(span, final_upvar_ty, upvar_ty);
214 // If we are also inferred the closure kind here, update the
215 // main table and process any deferred resolutions.
216 let closure_def_id = self.fcx.tcx.map.local_def_id(id);
217 if let Some(&kind) = self.temp_closure_kinds.get(&id) {
218 self.fcx.tables.borrow_mut().closure_kinds
219 .insert(closure_def_id, kind);
220 debug!("closure_kind({:?}) = {:?}", closure_def_id, kind);
222 let mut deferred_call_resolutions =
223 self.fcx.remove_deferred_call_resolutions(closure_def_id);
224 for deferred_call_resolution in &mut deferred_call_resolutions {
225 deferred_call_resolution.resolve(self.fcx);
230 // Returns a list of `ClosureUpvar`s for each upvar.
231 fn final_upvar_tys(&mut self, closure_id: ast::NodeId) -> Vec<Ty<'tcx>> {
232 // Presently an unboxed closure type cannot "escape" out of a
233 // function, so we will only encounter ones that originated in the
234 // local crate or were inlined into it along with some function.
235 // This may change if abstract return types of some sort are
237 let tcx = self.fcx.tcx;
238 tcx.with_freevars(closure_id, |freevars| {
241 let freevar_node_id = freevar.def.var_id();
242 let freevar_ty = self.fcx.node_ty(freevar_node_id);
243 let upvar_id = ty::UpvarId {
244 var_id: freevar_node_id,
245 closure_expr_id: closure_id
247 let capture = self.fcx.upvar_capture(upvar_id).unwrap();
249 debug!("freevar_node_id={:?} freevar_ty={:?} capture={:?}",
250 freevar_node_id, freevar_ty, capture);
253 ty::UpvarCapture::ByValue => freevar_ty,
254 ty::UpvarCapture::ByRef(borrow) =>
255 tcx.mk_ref(tcx.mk_region(borrow.region),
258 mutbl: borrow.kind.to_mutbl_lossy(),
266 fn adjust_upvar_borrow_kind_for_consume(&mut self,
268 mode: euv::ConsumeMode)
270 debug!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
273 // we only care about moves
275 euv::Copy => { return; }
279 // watch out for a move of the deref of a borrowed pointer;
280 // for that to be legal, the upvar would have to be borrowed
282 let guarantor = cmt.guarantor();
283 debug!("adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
285 match guarantor.cat {
286 Categorization::Deref(_, _, mc::BorrowedPtr(..)) |
287 Categorization::Deref(_, _, mc::Implicit(..)) => {
289 mc::NoteUpvarRef(upvar_id) => {
290 debug!("adjust_upvar_borrow_kind_for_consume: \
291 setting upvar_id={:?} to by value",
294 // to move out of an upvar, this must be a FnOnce closure
295 self.adjust_closure_kind(upvar_id.closure_expr_id,
296 ty::ClosureKind::FnOnce);
298 let upvar_capture_map =
299 &mut self.fcx.tables.borrow_mut().upvar_capture_map;
300 upvar_capture_map.insert(upvar_id, ty::UpvarCapture::ByValue);
302 mc::NoteClosureEnv(upvar_id) => {
303 // we get just a closureenv ref if this is a
304 // `move` closure, or if the upvar has already
305 // been inferred to by-value. In any case, we
306 // must still adjust the kind of the closure
307 // to be a FnOnce closure to permit moves out
308 // of the environment.
309 self.adjust_closure_kind(upvar_id.closure_expr_id,
310 ty::ClosureKind::FnOnce);
320 /// Indicates that `cmt` is being directly mutated (e.g., assigned
321 /// to). If cmt contains any by-ref upvars, this implies that
322 /// those upvars must be borrowed using an `&mut` borrow.
323 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
324 debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})",
327 match cmt.cat.clone() {
328 Categorization::Deref(base, _, mc::Unique) |
329 Categorization::Interior(base, _) |
330 Categorization::Downcast(base, _) => {
331 // Interior or owned data is mutable if base is
332 // mutable, so iterate to the base.
333 self.adjust_upvar_borrow_kind_for_mut(base);
336 Categorization::Deref(base, _, mc::BorrowedPtr(..)) |
337 Categorization::Deref(base, _, mc::Implicit(..)) => {
338 if !self.try_adjust_upvar_deref(&cmt.note, ty::MutBorrow) {
339 // assignment to deref of an `&mut`
340 // borrowed pointer implies that the
341 // pointer itself must be unique, but not
342 // necessarily *mutable*
343 self.adjust_upvar_borrow_kind_for_unique(base);
347 Categorization::Deref(_, _, mc::UnsafePtr(..)) |
348 Categorization::StaticItem |
349 Categorization::Rvalue(_) |
350 Categorization::Local(_) |
351 Categorization::Upvar(..) => {
357 fn adjust_upvar_borrow_kind_for_unique(&mut self, cmt: mc::cmt<'tcx>) {
358 debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})",
361 match cmt.cat.clone() {
362 Categorization::Deref(base, _, mc::Unique) |
363 Categorization::Interior(base, _) |
364 Categorization::Downcast(base, _) => {
365 // Interior or owned data is unique if base is
367 self.adjust_upvar_borrow_kind_for_unique(base);
370 Categorization::Deref(base, _, mc::BorrowedPtr(..)) |
371 Categorization::Deref(base, _, mc::Implicit(..)) => {
372 if !self.try_adjust_upvar_deref(&cmt.note, ty::UniqueImmBorrow) {
373 // for a borrowed pointer to be unique, its
374 // base must be unique
375 self.adjust_upvar_borrow_kind_for_unique(base);
379 Categorization::Deref(_, _, mc::UnsafePtr(..)) |
380 Categorization::StaticItem |
381 Categorization::Rvalue(_) |
382 Categorization::Local(_) |
383 Categorization::Upvar(..) => {
388 fn try_adjust_upvar_deref(&mut self,
390 borrow_kind: ty::BorrowKind)
393 assert!(match borrow_kind {
394 ty::MutBorrow => true,
395 ty::UniqueImmBorrow => true,
397 // imm borrows never require adjusting any kinds, so we don't wind up here
398 ty::ImmBorrow => false,
402 mc::NoteUpvarRef(upvar_id) => {
403 // if this is an implicit deref of an
404 // upvar, then we need to modify the
405 // borrow_kind of the upvar to make sure it
406 // is inferred to mutable if necessary
408 let upvar_capture_map = &mut self.fcx.tables.borrow_mut().upvar_capture_map;
409 let ub = upvar_capture_map.get_mut(&upvar_id).unwrap();
410 self.adjust_upvar_borrow_kind(upvar_id, ub, borrow_kind);
413 // also need to be in an FnMut closure since this is not an ImmBorrow
414 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::ClosureKind::FnMut);
418 mc::NoteClosureEnv(upvar_id) => {
419 // this kind of deref occurs in a `move` closure, or
420 // for a by-value upvar; in either case, to mutate an
421 // upvar, we need to be an FnMut closure
422 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::ClosureKind::FnMut);
432 /// We infer the borrow_kind with which to borrow upvars in a stack closure.
433 /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
434 /// moving from left to right as needed (but never right to left).
435 /// Here the argument `mutbl` is the borrow_kind that is required by
436 /// some particular use.
437 fn adjust_upvar_borrow_kind(&mut self,
438 upvar_id: ty::UpvarId,
439 upvar_capture: &mut ty::UpvarCapture,
440 kind: ty::BorrowKind) {
441 debug!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
442 upvar_id, upvar_capture, kind);
444 match *upvar_capture {
445 ty::UpvarCapture::ByValue => {
446 // Upvar is already by-value, the strongest criteria.
448 ty::UpvarCapture::ByRef(ref mut upvar_borrow) => {
449 match (upvar_borrow.kind, kind) {
451 (ty::ImmBorrow, ty::UniqueImmBorrow) |
452 (ty::ImmBorrow, ty::MutBorrow) |
453 (ty::UniqueImmBorrow, ty::MutBorrow) => {
454 upvar_borrow.kind = kind;
457 (ty::ImmBorrow, ty::ImmBorrow) |
458 (ty::UniqueImmBorrow, ty::ImmBorrow) |
459 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
460 (ty::MutBorrow, _) => {
467 fn adjust_closure_kind(&mut self,
468 closure_id: ast::NodeId,
469 new_kind: ty::ClosureKind) {
470 debug!("adjust_closure_kind(closure_id={}, new_kind={:?})",
471 closure_id, new_kind);
473 if let Some(&existing_kind) = self.temp_closure_kinds.get(&closure_id) {
474 debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
475 closure_id, existing_kind, new_kind);
477 match (existing_kind, new_kind) {
478 (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
479 (ty::ClosureKind::FnMut, ty::ClosureKind::Fn) |
480 (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
481 (ty::ClosureKind::FnOnce, _) => {
485 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) |
486 (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
487 (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
488 // new kind is stronger than the old kind
489 self.temp_closure_kinds.insert(closure_id, new_kind);
496 impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for AdjustBorrowKind<'a, 'gcx, 'tcx> {
497 fn visit_fn(&mut self,
498 fn_kind: intravisit::FnKind<'v>,
499 decl: &'v hir::FnDecl,
500 body: &'v hir::Block,
504 intravisit::walk_fn(self, fn_kind, decl, body, span, id);
505 self.analyze_closure(id, span, decl, body);
509 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a, 'gcx, 'tcx> {
510 fn consume(&mut self,
511 _consume_id: ast::NodeId,
514 mode: euv::ConsumeMode)
516 debug!("consume(cmt={:?},mode={:?})", cmt, mode);
517 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
520 fn matched_pat(&mut self,
521 _matched_pat: &hir::Pat,
523 _mode: euv::MatchMode)
526 fn consume_pat(&mut self,
527 _consume_pat: &hir::Pat,
529 mode: euv::ConsumeMode)
531 debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode);
532 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
536 borrow_id: ast::NodeId,
539 _loan_region: ty::Region,
541 _loan_cause: euv::LoanCause)
543 debug!("borrow(borrow_id={}, cmt={:?}, bk={:?})",
548 ty::UniqueImmBorrow => {
549 self.adjust_upvar_borrow_kind_for_unique(cmt);
552 self.adjust_upvar_borrow_kind_for_mut(cmt);
557 fn decl_without_init(&mut self,
563 _assignment_id: ast::NodeId,
564 _assignment_span: Span,
565 assignee_cmt: mc::cmt<'tcx>,
566 _mode: euv::MutateMode)
568 debug!("mutate(assignee_cmt={:?})",
571 self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);