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::intravisit::{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 intravisit::walk_expr(self, expr);
112 impl<'a,'tcx> SeedBorrowKind<'a,'tcx> {
113 fn new(fcx: &'a FnCtxt<'a,'tcx>) -> SeedBorrowKind<'a,'tcx> {
114 SeedBorrowKind { fcx: fcx, closures_with_inferred_kinds: HashSet::new() }
117 fn tcx(&self) -> &'a ty::ctxt<'tcx> {
121 fn infcx(&self) -> &'a InferCtxt<'a,'tcx> {
125 fn check_closure(&mut self,
127 capture_clause: hir::CaptureClause,
130 let closure_def_id = self.tcx().map.local_def_id(expr.id);
131 if !self.fcx.inh.tables.borrow().closure_kinds.contains_key(&closure_def_id) {
132 self.closures_with_inferred_kinds.insert(expr.id);
133 self.fcx.inh.tables.borrow_mut().closure_kinds
134 .insert(closure_def_id, ty::FnClosureKind);
135 debug!("check_closure: adding closure_id={:?} to closures_with_inferred_kinds",
139 self.tcx().with_freevars(expr.id, |freevars| {
140 for freevar in freevars {
141 let var_node_id = freevar.def.var_id();
142 let upvar_id = ty::UpvarId { var_id: var_node_id,
143 closure_expr_id: expr.id };
144 debug!("seed upvar_id {:?}", upvar_id);
146 let capture_kind = match capture_clause {
147 hir::CaptureByValue => {
148 ty::UpvarCapture::ByValue
150 hir::CaptureByRef => {
151 let origin = UpvarRegion(upvar_id, expr.span);
152 let freevar_region = self.infcx().next_region_var(origin);
153 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow,
154 region: freevar_region };
155 ty::UpvarCapture::ByRef(upvar_borrow)
159 self.fcx.inh.tables.borrow_mut().upvar_capture_map.insert(upvar_id, capture_kind);
165 ///////////////////////////////////////////////////////////////////////////
166 // ADJUST BORROW KIND
168 struct AdjustBorrowKind<'a,'tcx:'a> {
169 fcx: &'a FnCtxt<'a,'tcx>,
170 closures_with_inferred_kinds: &'a HashSet<ast::NodeId>,
173 impl<'a,'tcx> AdjustBorrowKind<'a,'tcx> {
174 fn new(fcx: &'a FnCtxt<'a,'tcx>,
175 closures_with_inferred_kinds: &'a HashSet<ast::NodeId>)
176 -> AdjustBorrowKind<'a,'tcx> {
177 AdjustBorrowKind { fcx: fcx, closures_with_inferred_kinds: closures_with_inferred_kinds }
180 fn analyze_closure(&mut self,
186 * Analysis starting point.
189 debug!("analyze_closure(id={:?}, body.id={:?})", id, body.id);
192 let mut euv = euv::ExprUseVisitor::new(self, self.fcx.infcx());
193 euv.walk_fn(decl, body);
196 // Now that we've analyzed the closure, we know how each
197 // variable is borrowed, and we know what traits the closure
198 // implements (Fn vs FnMut etc). We now have some updates to do
199 // with that information.
201 // Note that no closure type C may have an upvar of type C
202 // (though it may reference itself via a trait object). This
203 // results from the desugaring of closures to a struct like
204 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
205 // C, then the type would have infinite size (and the
206 // inference algorithm will reject it).
208 // Extract the type variables UV0...UVn.
209 let closure_substs = match self.fcx.node_ty(id).sty {
210 ty::TyClosure(_, ref substs) => substs,
212 self.fcx.tcx().sess.span_bug(
214 &format!("type of closure expr {:?} is not a closure {:?}",
219 // Equate the type variables with the actual types.
220 let final_upvar_tys = self.final_upvar_tys(id);
221 debug!("analyze_closure: id={:?} closure_substs={:?} final_upvar_tys={:?}",
222 id, closure_substs, final_upvar_tys);
223 for (&upvar_ty, final_upvar_ty) in closure_substs.upvar_tys.iter().zip(final_upvar_tys) {
224 demand::eqtype(self.fcx, span, final_upvar_ty, upvar_ty);
227 // Now we must process and remove any deferred resolutions,
228 // since we have a concrete closure kind.
229 let closure_def_id = self.fcx.tcx().map.local_def_id(id);
230 if self.closures_with_inferred_kinds.contains(&id) {
231 let mut deferred_call_resolutions =
232 self.fcx.remove_deferred_call_resolutions(closure_def_id);
233 for deferred_call_resolution in &mut deferred_call_resolutions {
234 deferred_call_resolution.resolve(self.fcx);
239 // Returns a list of `ClosureUpvar`s for each upvar.
240 fn final_upvar_tys(&mut self, closure_id: ast::NodeId) -> Vec<Ty<'tcx>> {
241 // Presently an unboxed closure type cannot "escape" out of a
242 // function, so we will only encounter ones that originated in the
243 // local crate or were inlined into it along with some function.
244 // This may change if abstract return types of some sort are
246 let tcx = self.fcx.tcx();
247 tcx.with_freevars(closure_id, |freevars| {
250 let freevar_node_id = freevar.def.var_id();
251 let freevar_ty = self.fcx.node_ty(freevar_node_id);
252 let upvar_id = ty::UpvarId {
253 var_id: freevar_node_id,
254 closure_expr_id: closure_id
256 let capture = self.fcx.infcx().upvar_capture(upvar_id).unwrap();
258 debug!("freevar_node_id={:?} freevar_ty={:?} capture={:?}",
259 freevar_node_id, freevar_ty, capture);
262 ty::UpvarCapture::ByValue => freevar_ty,
263 ty::UpvarCapture::ByRef(borrow) =>
264 tcx.mk_ref(tcx.mk_region(borrow.region),
267 mutbl: borrow.kind.to_mutbl_lossy(),
275 fn adjust_upvar_borrow_kind_for_consume(&self,
277 mode: euv::ConsumeMode)
279 debug!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
282 // we only care about moves
284 euv::Copy => { return; }
288 // watch out for a move of the deref of a borrowed pointer;
289 // for that to be legal, the upvar would have to be borrowed
291 let guarantor = cmt.guarantor();
292 debug!("adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
294 match guarantor.cat {
295 Categorization::Deref(_, _, mc::BorrowedPtr(..)) |
296 Categorization::Deref(_, _, mc::Implicit(..)) => {
298 mc::NoteUpvarRef(upvar_id) => {
299 debug!("adjust_upvar_borrow_kind_for_consume: \
300 setting upvar_id={:?} to by value",
303 // to move out of an upvar, this must be a FnOnce closure
304 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnOnceClosureKind);
306 let upvar_capture_map =
307 &mut self.fcx.inh.tables.borrow_mut().upvar_capture_map;
308 upvar_capture_map.insert(upvar_id, ty::UpvarCapture::ByValue);
310 mc::NoteClosureEnv(upvar_id) => {
311 // we get just a closureenv ref if this is a
312 // `move` closure, or if the upvar has already
313 // been inferred to by-value. In any case, we
314 // must still adjust the kind of the closure
315 // to be a FnOnce closure to permit moves out
316 // of the environment.
317 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnOnceClosureKind);
327 /// Indicates that `cmt` is being directly mutated (e.g., assigned
328 /// to). If cmt contains any by-ref upvars, this implies that
329 /// those upvars must be borrowed using an `&mut` borrow.
330 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
331 debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})",
334 match cmt.cat.clone() {
335 Categorization::Deref(base, _, mc::Unique) |
336 Categorization::Interior(base, _) |
337 Categorization::Downcast(base, _) => {
338 // Interior or owned data is mutable if base is
339 // mutable, so iterate to the base.
340 self.adjust_upvar_borrow_kind_for_mut(base);
343 Categorization::Deref(base, _, mc::BorrowedPtr(..)) |
344 Categorization::Deref(base, _, mc::Implicit(..)) => {
345 if !self.try_adjust_upvar_deref(&cmt.note, ty::MutBorrow) {
346 // assignment to deref of an `&mut`
347 // borrowed pointer implies that the
348 // pointer itself must be unique, but not
349 // necessarily *mutable*
350 self.adjust_upvar_borrow_kind_for_unique(base);
354 Categorization::Deref(_, _, mc::UnsafePtr(..)) |
355 Categorization::StaticItem |
356 Categorization::Rvalue(_) |
357 Categorization::Local(_) |
358 Categorization::Upvar(..) => {
364 fn adjust_upvar_borrow_kind_for_unique(&self, cmt: mc::cmt<'tcx>) {
365 debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})",
368 match cmt.cat.clone() {
369 Categorization::Deref(base, _, mc::Unique) |
370 Categorization::Interior(base, _) |
371 Categorization::Downcast(base, _) => {
372 // Interior or owned data is unique if base is
374 self.adjust_upvar_borrow_kind_for_unique(base);
377 Categorization::Deref(base, _, mc::BorrowedPtr(..)) |
378 Categorization::Deref(base, _, mc::Implicit(..)) => {
379 if !self.try_adjust_upvar_deref(&cmt.note, ty::UniqueImmBorrow) {
380 // for a borrowed pointer to be unique, its
381 // base must be unique
382 self.adjust_upvar_borrow_kind_for_unique(base);
386 Categorization::Deref(_, _, mc::UnsafePtr(..)) |
387 Categorization::StaticItem |
388 Categorization::Rvalue(_) |
389 Categorization::Local(_) |
390 Categorization::Upvar(..) => {
395 fn try_adjust_upvar_deref(&self,
397 borrow_kind: ty::BorrowKind)
400 assert!(match borrow_kind {
401 ty::MutBorrow => true,
402 ty::UniqueImmBorrow => true,
404 // imm borrows never require adjusting any kinds, so we don't wind up here
405 ty::ImmBorrow => false,
409 mc::NoteUpvarRef(upvar_id) => {
410 // if this is an implicit deref of an
411 // upvar, then we need to modify the
412 // borrow_kind of the upvar to make sure it
413 // is inferred to mutable if necessary
415 let upvar_capture_map = &mut self.fcx.inh.tables.borrow_mut().upvar_capture_map;
416 let ub = upvar_capture_map.get_mut(&upvar_id).unwrap();
417 self.adjust_upvar_borrow_kind(upvar_id, ub, borrow_kind);
420 // also need to be in an FnMut closure since this is not an ImmBorrow
421 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnMutClosureKind);
425 mc::NoteClosureEnv(upvar_id) => {
426 // this kind of deref occurs in a `move` closure, or
427 // for a by-value upvar; in either case, to mutate an
428 // upvar, we need to be an FnMut closure
429 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnMutClosureKind);
439 /// We infer the borrow_kind with which to borrow upvars in a stack closure. The borrow_kind
440 /// basically follows a lattice of `imm < unique-imm < mut`, moving from left to right as needed
441 /// (but never right to left). Here the argument `mutbl` is the borrow_kind that is required by
442 /// some particular use.
443 fn adjust_upvar_borrow_kind(&self,
444 upvar_id: ty::UpvarId,
445 upvar_capture: &mut ty::UpvarCapture,
446 kind: ty::BorrowKind) {
447 debug!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
448 upvar_id, upvar_capture, kind);
450 match *upvar_capture {
451 ty::UpvarCapture::ByValue => {
452 // Upvar is already by-value, the strongest criteria.
454 ty::UpvarCapture::ByRef(ref mut upvar_borrow) => {
455 match (upvar_borrow.kind, kind) {
457 (ty::ImmBorrow, ty::UniqueImmBorrow) |
458 (ty::ImmBorrow, ty::MutBorrow) |
459 (ty::UniqueImmBorrow, ty::MutBorrow) => {
460 upvar_borrow.kind = kind;
463 (ty::ImmBorrow, ty::ImmBorrow) |
464 (ty::UniqueImmBorrow, ty::ImmBorrow) |
465 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
466 (ty::MutBorrow, _) => {
473 fn adjust_closure_kind(&self,
474 closure_id: ast::NodeId,
475 new_kind: ty::ClosureKind) {
476 debug!("adjust_closure_kind(closure_id={}, new_kind={:?})",
477 closure_id, new_kind);
479 if !self.closures_with_inferred_kinds.contains(&closure_id) {
483 let closure_def_id = self.fcx.tcx().map.local_def_id(closure_id);
484 let closure_kinds = &mut self.fcx.inh.tables.borrow_mut().closure_kinds;
485 let existing_kind = *closure_kinds.get(&closure_def_id).unwrap();
487 debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
488 closure_id, existing_kind, new_kind);
490 match (existing_kind, new_kind) {
491 (ty::FnClosureKind, ty::FnClosureKind) |
492 (ty::FnMutClosureKind, ty::FnClosureKind) |
493 (ty::FnMutClosureKind, ty::FnMutClosureKind) |
494 (ty::FnOnceClosureKind, _) => {
498 (ty::FnClosureKind, ty::FnMutClosureKind) |
499 (ty::FnClosureKind, ty::FnOnceClosureKind) |
500 (ty::FnMutClosureKind, ty::FnOnceClosureKind) => {
501 // new kind is stronger than the old kind
502 closure_kinds.insert(closure_def_id, new_kind);
508 impl<'a, 'tcx, 'v> Visitor<'v> for AdjustBorrowKind<'a, 'tcx> {
509 fn visit_fn(&mut self,
510 fn_kind: intravisit::FnKind<'v>,
511 decl: &'v hir::FnDecl,
512 body: &'v hir::Block,
516 intravisit::walk_fn(self, fn_kind, decl, body, span);
517 self.analyze_closure(id, span, decl, body);
521 impl<'a,'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a,'tcx> {
522 fn consume(&mut self,
523 _consume_id: ast::NodeId,
526 mode: euv::ConsumeMode)
528 debug!("consume(cmt={:?},mode={:?})", cmt, mode);
529 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
532 fn matched_pat(&mut self,
533 _matched_pat: &hir::Pat,
535 _mode: euv::MatchMode)
538 fn consume_pat(&mut self,
539 _consume_pat: &hir::Pat,
541 mode: euv::ConsumeMode)
543 debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode);
544 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
548 borrow_id: ast::NodeId,
551 _loan_region: ty::Region,
553 _loan_cause: euv::LoanCause)
555 debug!("borrow(borrow_id={}, cmt={:?}, bk={:?})",
560 ty::UniqueImmBorrow => {
561 self.adjust_upvar_borrow_kind_for_unique(cmt);
564 self.adjust_upvar_borrow_kind_for_mut(cmt);
569 fn decl_without_init(&mut self,
575 _assignment_id: ast::NodeId,
576 _assignment_span: Span,
577 assignee_cmt: mc::cmt<'tcx>,
578 _mode: euv::MutateMode)
580 debug!("mutate(assignee_cmt={:?})",
583 self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);