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 use std::collections::hash_map::Entry;
58 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
59 pub fn closure_analyze(&self, body: &'gcx hir::Body) {
60 InferBorrowKindVisitor { fcx: self }.visit_body(body);
62 // it's our job to process these.
63 assert!(self.deferred_call_resolutions.borrow().is_empty());
67 struct InferBorrowKindVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
68 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
71 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for InferBorrowKindVisitor<'a, 'gcx, 'tcx> {
72 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
73 NestedVisitorMap::None
76 fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
78 hir::ExprClosure(cc, _, body_id, _) => {
79 let body = self.fcx.tcx.hir.body(body_id);
80 self.visit_body(body);
81 self.fcx.analyze_closure(expr.id, expr.span, body, cc);
87 intravisit::walk_expr(self, expr);
91 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
92 fn analyze_closure(&self,
96 capture_clause: hir::CaptureClause) {
98 * Analysis starting point.
101 debug!("analyze_closure(id={:?}, body.id={:?})", id, body.id());
103 let infer_kind = match self.tables.borrow_mut().closure_kinds.entry(id) {
104 Entry::Occupied(_) => false,
105 Entry::Vacant(entry) => {
106 debug!("check_closure: adding closure {:?} as Fn", id);
107 entry.insert((ty::ClosureKind::Fn, None));
112 self.tcx.with_freevars(id, |freevars| {
113 for freevar in freevars {
114 let def_id = freevar.def.def_id();
115 let var_node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
116 let upvar_id = ty::UpvarId { var_id: var_node_id,
117 closure_expr_id: id };
118 debug!("seed upvar_id {:?}", upvar_id);
120 let capture_kind = match capture_clause {
121 hir::CaptureByValue => {
122 ty::UpvarCapture::ByValue
124 hir::CaptureByRef => {
125 let origin = UpvarRegion(upvar_id, span);
126 let freevar_region = self.next_region_var(origin);
127 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow,
128 region: freevar_region };
129 ty::UpvarCapture::ByRef(upvar_borrow)
133 self.tables.borrow_mut().upvar_capture_map.insert(upvar_id, capture_kind);
138 let body_owner_def_id = self.tcx.hir.body_owner_def_id(body.id());
139 let region_maps = &self.tcx.region_maps(body_owner_def_id);
140 let mut delegate = InferBorrowKind {
142 adjust_closure_kinds: NodeMap(),
143 adjust_upvar_captures: ty::UpvarCaptureMap::default(),
145 euv::ExprUseVisitor::new(&mut delegate,
149 &self.tables.borrow())
152 // Write the adjusted values back into the main tables.
154 if let Some(kind) = delegate.adjust_closure_kinds.remove(&id) {
155 self.tables.borrow_mut().closure_kinds.insert(id, kind);
158 self.tables.borrow_mut().upvar_capture_map.extend(
159 delegate.adjust_upvar_captures);
162 // Now that we've analyzed the closure, we know how each
163 // variable is borrowed, and we know what traits the closure
164 // implements (Fn vs FnMut etc). We now have some updates to do
165 // with that information.
167 // Note that no closure type C may have an upvar of type C
168 // (though it may reference itself via a trait object). This
169 // results from the desugaring of closures to a struct like
170 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
171 // C, then the type would have infinite size (and the
172 // inference algorithm will reject it).
174 // Extract the type variables UV0...UVn.
175 let (def_id, closure_substs) = match self.node_ty(id).sty {
176 ty::TyClosure(def_id, substs) => (def_id, substs),
180 "type of closure expr {:?} is not a closure {:?}",
185 // Equate the type variables with the actual types.
186 let final_upvar_tys = self.final_upvar_tys(id);
187 debug!("analyze_closure: id={:?} closure_substs={:?} final_upvar_tys={:?}",
188 id, closure_substs, final_upvar_tys);
189 for (upvar_ty, final_upvar_ty) in
190 closure_substs.upvar_tys(def_id, self.tcx).zip(final_upvar_tys)
192 self.demand_eqtype(span, final_upvar_ty, upvar_ty);
195 // If we are also inferred the closure kind here,
196 // process any deferred resolutions.
198 let closure_def_id = self.tcx.hir.local_def_id(id);
199 let deferred_call_resolutions =
200 self.remove_deferred_call_resolutions(closure_def_id);
201 for deferred_call_resolution in deferred_call_resolutions {
202 deferred_call_resolution.resolve(self);
207 // Returns a list of `ClosureUpvar`s for each upvar.
208 fn final_upvar_tys(&self, closure_id: ast::NodeId) -> Vec<Ty<'tcx>> {
209 // Presently an unboxed closure type cannot "escape" out of a
210 // function, so we will only encounter ones that originated in the
211 // local crate or were inlined into it along with some function.
212 // This may change if abstract return types of some sort are
215 tcx.with_freevars(closure_id, |freevars| {
216 freevars.iter().map(|freevar| {
217 let def_id = freevar.def.def_id();
218 let var_id = tcx.hir.as_local_node_id(def_id).unwrap();
219 let freevar_ty = self.node_ty(var_id);
220 let upvar_id = ty::UpvarId {
222 closure_expr_id: closure_id
224 let capture = self.tables.borrow().upvar_capture(upvar_id);
226 debug!("var_id={:?} freevar_ty={:?} capture={:?}",
227 var_id, freevar_ty, capture);
230 ty::UpvarCapture::ByValue => freevar_ty,
231 ty::UpvarCapture::ByRef(borrow) =>
232 tcx.mk_ref(borrow.region,
235 mutbl: borrow.kind.to_mutbl_lossy(),
243 struct InferBorrowKind<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
244 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
245 adjust_closure_kinds: NodeMap<(ty::ClosureKind, Option<(Span, ast::Name)>)>,
246 adjust_upvar_captures: ty::UpvarCaptureMap<'tcx>,
249 impl<'a, 'gcx, 'tcx> InferBorrowKind<'a, 'gcx, 'tcx> {
250 fn adjust_upvar_borrow_kind_for_consume(&mut self,
252 mode: euv::ConsumeMode)
254 debug!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
257 // we only care about moves
259 euv::Copy => { return; }
263 let tcx = self.fcx.tcx;
265 // watch out for a move of the deref of a borrowed pointer;
266 // for that to be legal, the upvar would have to be borrowed
268 let guarantor = cmt.guarantor();
269 debug!("adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
271 match guarantor.cat {
272 Categorization::Deref(_, mc::BorrowedPtr(..)) |
273 Categorization::Deref(_, mc::Implicit(..)) => {
275 mc::NoteUpvarRef(upvar_id) => {
276 debug!("adjust_upvar_borrow_kind_for_consume: \
277 setting upvar_id={:?} to by value",
280 // to move out of an upvar, this must be a FnOnce closure
281 self.adjust_closure_kind(upvar_id.closure_expr_id,
282 ty::ClosureKind::FnOnce,
284 tcx.hir.name(upvar_id.var_id));
286 self.adjust_upvar_captures.insert(upvar_id, ty::UpvarCapture::ByValue);
288 mc::NoteClosureEnv(upvar_id) => {
289 // we get just a closureenv ref if this is a
290 // `move` closure, or if the upvar has already
291 // been inferred to by-value. In any case, we
292 // must still adjust the kind of the closure
293 // to be a FnOnce closure to permit moves out
294 // of the environment.
295 self.adjust_closure_kind(upvar_id.closure_expr_id,
296 ty::ClosureKind::FnOnce,
298 tcx.hir.name(upvar_id.var_id));
308 /// Indicates that `cmt` is being directly mutated (e.g., assigned
309 /// to). If cmt contains any by-ref upvars, this implies that
310 /// those upvars must be borrowed using an `&mut` borrow.
311 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
312 debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})",
315 match cmt.cat.clone() {
316 Categorization::Deref(base, mc::Unique) |
317 Categorization::Interior(base, _) |
318 Categorization::Downcast(base, _) => {
319 // Interior or owned data is mutable if base is
320 // mutable, so iterate to the base.
321 self.adjust_upvar_borrow_kind_for_mut(base);
324 Categorization::Deref(base, mc::BorrowedPtr(..)) |
325 Categorization::Deref(base, mc::Implicit(..)) => {
326 if !self.try_adjust_upvar_deref(cmt, ty::MutBorrow) {
327 // assignment to deref of an `&mut`
328 // borrowed pointer implies that the
329 // pointer itself must be unique, but not
330 // necessarily *mutable*
331 self.adjust_upvar_borrow_kind_for_unique(base);
335 Categorization::Deref(_, mc::UnsafePtr(..)) |
336 Categorization::StaticItem |
337 Categorization::Rvalue(..) |
338 Categorization::Local(_) |
339 Categorization::Upvar(..) => {
345 fn adjust_upvar_borrow_kind_for_unique(&mut self, cmt: mc::cmt<'tcx>) {
346 debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})",
349 match cmt.cat.clone() {
350 Categorization::Deref(base, mc::Unique) |
351 Categorization::Interior(base, _) |
352 Categorization::Downcast(base, _) => {
353 // Interior or owned data is unique if base is
355 self.adjust_upvar_borrow_kind_for_unique(base);
358 Categorization::Deref(base, mc::BorrowedPtr(..)) |
359 Categorization::Deref(base, mc::Implicit(..)) => {
360 if !self.try_adjust_upvar_deref(cmt, ty::UniqueImmBorrow) {
361 // for a borrowed pointer to be unique, its
362 // base must be unique
363 self.adjust_upvar_borrow_kind_for_unique(base);
367 Categorization::Deref(_, mc::UnsafePtr(..)) |
368 Categorization::StaticItem |
369 Categorization::Rvalue(..) |
370 Categorization::Local(_) |
371 Categorization::Upvar(..) => {
376 fn try_adjust_upvar_deref(&mut self,
378 borrow_kind: ty::BorrowKind)
381 assert!(match borrow_kind {
382 ty::MutBorrow => true,
383 ty::UniqueImmBorrow => true,
385 // imm borrows never require adjusting any kinds, so we don't wind up here
386 ty::ImmBorrow => false,
389 let tcx = self.fcx.tcx;
392 mc::NoteUpvarRef(upvar_id) => {
393 // if this is an implicit deref of an
394 // upvar, then we need to modify the
395 // borrow_kind of the upvar to make sure it
396 // is inferred to mutable if necessary
397 self.adjust_upvar_borrow_kind(upvar_id, borrow_kind);
399 // also need to be in an FnMut closure since this is not an ImmBorrow
400 self.adjust_closure_kind(upvar_id.closure_expr_id,
401 ty::ClosureKind::FnMut,
403 tcx.hir.name(upvar_id.var_id));
407 mc::NoteClosureEnv(upvar_id) => {
408 // this kind of deref occurs in a `move` closure, or
409 // for a by-value upvar; in either case, to mutate an
410 // upvar, we need to be an FnMut closure
411 self.adjust_closure_kind(upvar_id.closure_expr_id,
412 ty::ClosureKind::FnMut,
414 tcx.hir.name(upvar_id.var_id));
424 /// We infer the borrow_kind with which to borrow upvars in a stack closure.
425 /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
426 /// moving from left to right as needed (but never right to left).
427 /// Here the argument `mutbl` is the borrow_kind that is required by
428 /// some particular use.
429 fn adjust_upvar_borrow_kind(&mut self,
430 upvar_id: ty::UpvarId,
431 kind: ty::BorrowKind) {
432 let upvar_capture = self.adjust_upvar_captures.get(&upvar_id).cloned()
433 .unwrap_or_else(|| self.fcx.tables.borrow().upvar_capture(upvar_id));
434 debug!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
435 upvar_id, upvar_capture, kind);
437 match upvar_capture {
438 ty::UpvarCapture::ByValue => {
439 // Upvar is already by-value, the strongest criteria.
441 ty::UpvarCapture::ByRef(mut upvar_borrow) => {
442 match (upvar_borrow.kind, kind) {
444 (ty::ImmBorrow, ty::UniqueImmBorrow) |
445 (ty::ImmBorrow, ty::MutBorrow) |
446 (ty::UniqueImmBorrow, ty::MutBorrow) => {
447 upvar_borrow.kind = kind;
448 self.adjust_upvar_captures.insert(upvar_id,
449 ty::UpvarCapture::ByRef(upvar_borrow));
452 (ty::ImmBorrow, ty::ImmBorrow) |
453 (ty::UniqueImmBorrow, ty::ImmBorrow) |
454 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
455 (ty::MutBorrow, _) => {
462 fn adjust_closure_kind(&mut self,
463 closure_id: ast::NodeId,
464 new_kind: ty::ClosureKind,
466 var_name: ast::Name) {
467 debug!("adjust_closure_kind(closure_id={}, new_kind={:?}, upvar_span={:?}, var_name={})",
468 closure_id, new_kind, upvar_span, var_name);
470 let closure_kind = self.adjust_closure_kinds.get(&closure_id).cloned()
471 .or_else(|| self.fcx.tables.borrow().closure_kinds.get(&closure_id).cloned());
472 if let Some((existing_kind, _)) = closure_kind {
473 debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
474 closure_id, existing_kind, new_kind);
476 match (existing_kind, new_kind) {
477 (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
478 (ty::ClosureKind::FnMut, ty::ClosureKind::Fn) |
479 (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
480 (ty::ClosureKind::FnOnce, _) => {
484 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) |
485 (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
486 (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
487 // new kind is stronger than the old kind
488 self.adjust_closure_kinds.insert(
490 (new_kind, Some((upvar_span, var_name)))
498 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'gcx, 'tcx> {
499 fn consume(&mut self,
500 _consume_id: ast::NodeId,
503 mode: euv::ConsumeMode)
505 debug!("consume(cmt={:?},mode={:?})", cmt, mode);
506 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
509 fn matched_pat(&mut self,
510 _matched_pat: &hir::Pat,
512 _mode: euv::MatchMode)
515 fn consume_pat(&mut self,
516 _consume_pat: &hir::Pat,
518 mode: euv::ConsumeMode)
520 debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode);
521 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
525 borrow_id: ast::NodeId,
528 _loan_region: ty::Region<'tcx>,
530 _loan_cause: euv::LoanCause)
532 debug!("borrow(borrow_id={}, cmt={:?}, bk={:?})",
537 ty::UniqueImmBorrow => {
538 self.adjust_upvar_borrow_kind_for_unique(cmt);
541 self.adjust_upvar_borrow_kind_for_mut(cmt);
546 fn decl_without_init(&mut self,
552 _assignment_id: ast::NodeId,
553 _assignment_span: Span,
554 assignee_cmt: mc::cmt<'tcx>,
555 _mode: euv::MutateMode)
557 debug!("mutate(assignee_cmt={:?})",
560 self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);