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, Option<(Span, ast::Name)>)>,
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, None));
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, Option<(Span, ast::Name)>)>,
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, Option<(Span, ast::Name)>)>)
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);
169 let param_env = self.fcx.param_env;
171 euv::ExprUseVisitor::with_options(self,
175 mc::MemCategorizationOptions {
176 during_closure_kind_inference: true
178 euv.consume_body(body);
181 // Now that we've analyzed the closure, we know how each
182 // variable is borrowed, and we know what traits the closure
183 // implements (Fn vs FnMut etc). We now have some updates to do
184 // with that information.
186 // Note that no closure type C may have an upvar of type C
187 // (though it may reference itself via a trait object). This
188 // results from the desugaring of closures to a struct like
189 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
190 // C, then the type would have infinite size (and the
191 // inference algorithm will reject it).
193 // Extract the type variables UV0...UVn.
194 let (def_id, closure_substs) = match self.fcx.node_ty(id).sty {
195 ty::TyClosure(def_id, substs) => (def_id, substs),
199 "type of closure expr {:?} is not a closure {:?}",
204 // Equate the type variables with the actual types.
205 let final_upvar_tys = self.final_upvar_tys(id);
206 debug!("analyze_closure: id={:?} closure_substs={:?} final_upvar_tys={:?}",
207 id, closure_substs, final_upvar_tys);
208 for (upvar_ty, final_upvar_ty) in
209 closure_substs.upvar_tys(def_id, self.fcx.tcx).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 if let Some(&(kind, context)) = self.temp_closure_kinds.get(&id) {
217 self.fcx.tables.borrow_mut().closure_kinds.insert(id, (kind, context));
218 let closure_def_id = self.fcx.tcx.hir.local_def_id(id);
219 debug!("closure_kind({:?}) = {:?}", closure_def_id, kind);
221 let deferred_call_resolutions =
222 self.fcx.remove_deferred_call_resolutions(closure_def_id);
223 for deferred_call_resolution in deferred_call_resolutions {
224 deferred_call_resolution.resolve(self.fcx);
229 // Returns a list of `ClosureUpvar`s for each upvar.
230 fn final_upvar_tys(&mut self, closure_id: ast::NodeId) -> Vec<Ty<'tcx>> {
231 // Presently an unboxed closure type cannot "escape" out of a
232 // function, so we will only encounter ones that originated in the
233 // local crate or were inlined into it along with some function.
234 // This may change if abstract return types of some sort are
236 let tcx = self.fcx.tcx;
237 tcx.with_freevars(closure_id, |freevars| {
238 freevars.iter().map(|freevar| {
239 let def_id = freevar.def.def_id();
240 let var_id = tcx.hir.as_local_node_id(def_id).unwrap();
241 let freevar_ty = self.fcx.node_ty(var_id);
242 let upvar_id = ty::UpvarId {
244 closure_expr_id: closure_id
246 let capture = self.fcx.upvar_capture(upvar_id).unwrap();
248 debug!("var_id={:?} freevar_ty={:?} capture={:?}",
249 var_id, freevar_ty, capture);
252 ty::UpvarCapture::ByValue => freevar_ty,
253 ty::UpvarCapture::ByRef(borrow) =>
254 tcx.mk_ref(borrow.region,
257 mutbl: borrow.kind.to_mutbl_lossy(),
264 fn adjust_upvar_borrow_kind_for_consume(&mut self,
266 mode: euv::ConsumeMode)
268 debug!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
271 // we only care about moves
273 euv::Copy => { return; }
277 let tcx = self.fcx.tcx;
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 tcx.hir.name(upvar_id.var_id));
300 let upvar_capture_map =
301 &mut self.fcx.tables.borrow_mut().upvar_capture_map;
302 upvar_capture_map.insert(upvar_id, ty::UpvarCapture::ByValue);
304 mc::NoteClosureEnv(upvar_id) => {
305 // we get just a closureenv ref if this is a
306 // `move` closure, or if the upvar has already
307 // been inferred to by-value. In any case, we
308 // must still adjust the kind of the closure
309 // to be a FnOnce closure to permit moves out
310 // of the environment.
311 self.adjust_closure_kind(upvar_id.closure_expr_id,
312 ty::ClosureKind::FnOnce,
314 tcx.hir.name(upvar_id.var_id));
324 /// Indicates that `cmt` is being directly mutated (e.g., assigned
325 /// to). If cmt contains any by-ref upvars, this implies that
326 /// those upvars must be borrowed using an `&mut` borrow.
327 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
328 debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})",
331 match cmt.cat.clone() {
332 Categorization::Deref(base, mc::Unique) |
333 Categorization::Interior(base, _) |
334 Categorization::Downcast(base, _) => {
335 // Interior or owned data is mutable if base is
336 // mutable, so iterate to the base.
337 self.adjust_upvar_borrow_kind_for_mut(base);
340 Categorization::Deref(base, mc::BorrowedPtr(..)) |
341 Categorization::Deref(base, mc::Implicit(..)) => {
342 if !self.try_adjust_upvar_deref(cmt, ty::MutBorrow) {
343 // assignment to deref of an `&mut`
344 // borrowed pointer implies that the
345 // pointer itself must be unique, but not
346 // necessarily *mutable*
347 self.adjust_upvar_borrow_kind_for_unique(base);
351 Categorization::Deref(_, mc::UnsafePtr(..)) |
352 Categorization::StaticItem |
353 Categorization::Rvalue(..) |
354 Categorization::Local(_) |
355 Categorization::Upvar(..) => {
361 fn adjust_upvar_borrow_kind_for_unique(&mut self, cmt: mc::cmt<'tcx>) {
362 debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})",
365 match cmt.cat.clone() {
366 Categorization::Deref(base, mc::Unique) |
367 Categorization::Interior(base, _) |
368 Categorization::Downcast(base, _) => {
369 // Interior or owned data is unique if base is
371 self.adjust_upvar_borrow_kind_for_unique(base);
374 Categorization::Deref(base, mc::BorrowedPtr(..)) |
375 Categorization::Deref(base, mc::Implicit(..)) => {
376 if !self.try_adjust_upvar_deref(cmt, ty::UniqueImmBorrow) {
377 // for a borrowed pointer to be unique, its
378 // base must be unique
379 self.adjust_upvar_borrow_kind_for_unique(base);
383 Categorization::Deref(_, mc::UnsafePtr(..)) |
384 Categorization::StaticItem |
385 Categorization::Rvalue(..) |
386 Categorization::Local(_) |
387 Categorization::Upvar(..) => {
392 fn try_adjust_upvar_deref(&mut self,
394 borrow_kind: ty::BorrowKind)
397 assert!(match borrow_kind {
398 ty::MutBorrow => true,
399 ty::UniqueImmBorrow => true,
401 // imm borrows never require adjusting any kinds, so we don't wind up here
402 ty::ImmBorrow => false,
405 let tcx = self.fcx.tcx;
408 mc::NoteUpvarRef(upvar_id) => {
409 // if this is an implicit deref of an
410 // upvar, then we need to modify the
411 // borrow_kind of the upvar to make sure it
412 // is inferred to mutable if necessary
414 let upvar_capture_map = &mut self.fcx.tables.borrow_mut().upvar_capture_map;
415 let ub = upvar_capture_map.get_mut(&upvar_id).unwrap();
416 self.adjust_upvar_borrow_kind(upvar_id, ub, borrow_kind);
419 // also need to be in an FnMut closure since this is not an ImmBorrow
420 self.adjust_closure_kind(upvar_id.closure_expr_id,
421 ty::ClosureKind::FnMut,
423 tcx.hir.name(upvar_id.var_id));
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,
432 ty::ClosureKind::FnMut,
434 tcx.hir.name(upvar_id.var_id));
444 /// We infer the borrow_kind with which to borrow upvars in a stack closure.
445 /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
446 /// moving from left to right as needed (but never right to left).
447 /// Here the argument `mutbl` is the borrow_kind that is required by
448 /// some particular use.
449 fn adjust_upvar_borrow_kind(&mut self,
450 upvar_id: ty::UpvarId,
451 upvar_capture: &mut ty::UpvarCapture,
452 kind: ty::BorrowKind) {
453 debug!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
454 upvar_id, upvar_capture, kind);
456 match *upvar_capture {
457 ty::UpvarCapture::ByValue => {
458 // Upvar is already by-value, the strongest criteria.
460 ty::UpvarCapture::ByRef(ref mut upvar_borrow) => {
461 match (upvar_borrow.kind, kind) {
463 (ty::ImmBorrow, ty::UniqueImmBorrow) |
464 (ty::ImmBorrow, ty::MutBorrow) |
465 (ty::UniqueImmBorrow, ty::MutBorrow) => {
466 upvar_borrow.kind = kind;
469 (ty::ImmBorrow, ty::ImmBorrow) |
470 (ty::UniqueImmBorrow, ty::ImmBorrow) |
471 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
472 (ty::MutBorrow, _) => {
479 fn adjust_closure_kind(&mut self,
480 closure_id: ast::NodeId,
481 new_kind: ty::ClosureKind,
483 var_name: ast::Name) {
484 debug!("adjust_closure_kind(closure_id={}, new_kind={:?}, upvar_span={:?}, var_name={})",
485 closure_id, new_kind, upvar_span, var_name);
487 if let Some(&(existing_kind, _)) = self.temp_closure_kinds.get(&closure_id) {
488 debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
489 closure_id, existing_kind, new_kind);
491 match (existing_kind, new_kind) {
492 (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
493 (ty::ClosureKind::FnMut, ty::ClosureKind::Fn) |
494 (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
495 (ty::ClosureKind::FnOnce, _) => {
499 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) |
500 (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
501 (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
502 // new kind is stronger than the old kind
503 self.temp_closure_kinds.insert(
505 (new_kind, Some((upvar_span, var_name)))
513 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for AdjustBorrowKind<'a, 'gcx, 'tcx> {
514 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
515 NestedVisitorMap::None
518 fn visit_fn(&mut self,
519 fn_kind: intravisit::FnKind<'gcx>,
520 decl: &'gcx hir::FnDecl,
525 intravisit::walk_fn(self, fn_kind, decl, body, span, id);
527 let body = self.fcx.tcx.hir.body(body);
528 self.visit_body(body);
529 self.analyze_closure(id, span, body);
533 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a, 'gcx, 'tcx> {
534 fn consume(&mut self,
535 _consume_id: ast::NodeId,
538 mode: euv::ConsumeMode)
540 debug!("consume(cmt={:?},mode={:?})", cmt, mode);
541 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
544 fn matched_pat(&mut self,
545 _matched_pat: &hir::Pat,
547 _mode: euv::MatchMode)
550 fn consume_pat(&mut self,
551 _consume_pat: &hir::Pat,
553 mode: euv::ConsumeMode)
555 debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode);
556 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
560 borrow_id: ast::NodeId,
563 _loan_region: ty::Region<'tcx>,
565 _loan_cause: euv::LoanCause)
567 debug!("borrow(borrow_id={}, cmt={:?}, bk={:?})",
572 ty::UniqueImmBorrow => {
573 self.adjust_upvar_borrow_kind_for_unique(cmt);
576 self.adjust_upvar_borrow_kind_for_mut(cmt);
581 fn decl_without_init(&mut self,
587 _assignment_id: ast::NodeId,
588 _assignment_span: Span,
589 assignee_cmt: mc::cmt<'tcx>,
590 _mode: euv::MutateMode)
592 debug!("mutate(assignee_cmt={:?})",
595 self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);