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, region_maps, self, self.param_env)
148 // Write the adjusted values back into the main tables.
150 if let Some(kind) = delegate.adjust_closure_kinds.remove(&id) {
151 self.tables.borrow_mut().closure_kinds.insert(id, kind);
154 self.tables.borrow_mut().upvar_capture_map.extend(
155 delegate.adjust_upvar_captures);
158 // Now that we've analyzed the closure, we know how each
159 // variable is borrowed, and we know what traits the closure
160 // implements (Fn vs FnMut etc). We now have some updates to do
161 // with that information.
163 // Note that no closure type C may have an upvar of type C
164 // (though it may reference itself via a trait object). This
165 // results from the desugaring of closures to a struct like
166 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
167 // C, then the type would have infinite size (and the
168 // inference algorithm will reject it).
170 // Extract the type variables UV0...UVn.
171 let (def_id, closure_substs) = match self.node_ty(id).sty {
172 ty::TyClosure(def_id, substs) => (def_id, substs),
176 "type of closure expr {:?} is not a closure {:?}",
181 // Equate the type variables with the actual types.
182 let final_upvar_tys = self.final_upvar_tys(id);
183 debug!("analyze_closure: id={:?} closure_substs={:?} final_upvar_tys={:?}",
184 id, closure_substs, final_upvar_tys);
185 for (upvar_ty, final_upvar_ty) in
186 closure_substs.upvar_tys(def_id, self.tcx).zip(final_upvar_tys)
188 self.demand_eqtype(span, final_upvar_ty, upvar_ty);
191 // If we are also inferred the closure kind here,
192 // process any deferred resolutions.
194 let closure_def_id = self.tcx.hir.local_def_id(id);
195 let deferred_call_resolutions =
196 self.remove_deferred_call_resolutions(closure_def_id);
197 for deferred_call_resolution in deferred_call_resolutions {
198 deferred_call_resolution.resolve(self);
203 // Returns a list of `ClosureUpvar`s for each upvar.
204 fn final_upvar_tys(&self, closure_id: ast::NodeId) -> Vec<Ty<'tcx>> {
205 // Presently an unboxed closure type cannot "escape" out of a
206 // function, so we will only encounter ones that originated in the
207 // local crate or were inlined into it along with some function.
208 // This may change if abstract return types of some sort are
211 tcx.with_freevars(closure_id, |freevars| {
212 freevars.iter().map(|freevar| {
213 let def_id = freevar.def.def_id();
214 let var_id = tcx.hir.as_local_node_id(def_id).unwrap();
215 let freevar_ty = self.node_ty(var_id);
216 let upvar_id = ty::UpvarId {
218 closure_expr_id: closure_id
220 let capture = self.tables.borrow().upvar_capture(upvar_id);
222 debug!("var_id={:?} freevar_ty={:?} capture={:?}",
223 var_id, freevar_ty, capture);
226 ty::UpvarCapture::ByValue => freevar_ty,
227 ty::UpvarCapture::ByRef(borrow) =>
228 tcx.mk_ref(borrow.region,
231 mutbl: borrow.kind.to_mutbl_lossy(),
239 struct InferBorrowKind<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
240 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
241 adjust_closure_kinds: NodeMap<(ty::ClosureKind, Option<(Span, ast::Name)>)>,
242 adjust_upvar_captures: ty::UpvarCaptureMap<'tcx>,
245 impl<'a, 'gcx, 'tcx> InferBorrowKind<'a, 'gcx, 'tcx> {
246 fn adjust_upvar_borrow_kind_for_consume(&mut self,
248 mode: euv::ConsumeMode)
250 debug!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
253 // we only care about moves
255 euv::Copy => { return; }
259 let tcx = self.fcx.tcx;
261 // watch out for a move of the deref of a borrowed pointer;
262 // for that to be legal, the upvar would have to be borrowed
264 let guarantor = cmt.guarantor();
265 debug!("adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
267 match guarantor.cat {
268 Categorization::Deref(_, mc::BorrowedPtr(..)) |
269 Categorization::Deref(_, mc::Implicit(..)) => {
271 mc::NoteUpvarRef(upvar_id) => {
272 debug!("adjust_upvar_borrow_kind_for_consume: \
273 setting upvar_id={:?} to by value",
276 // to move out of an upvar, this must be a FnOnce closure
277 self.adjust_closure_kind(upvar_id.closure_expr_id,
278 ty::ClosureKind::FnOnce,
280 tcx.hir.name(upvar_id.var_id));
282 self.adjust_upvar_captures.insert(upvar_id, ty::UpvarCapture::ByValue);
284 mc::NoteClosureEnv(upvar_id) => {
285 // we get just a closureenv ref if this is a
286 // `move` closure, or if the upvar has already
287 // been inferred to by-value. In any case, we
288 // must still adjust the kind of the closure
289 // to be a FnOnce closure to permit moves out
290 // of the environment.
291 self.adjust_closure_kind(upvar_id.closure_expr_id,
292 ty::ClosureKind::FnOnce,
294 tcx.hir.name(upvar_id.var_id));
304 /// Indicates that `cmt` is being directly mutated (e.g., assigned
305 /// to). If cmt contains any by-ref upvars, this implies that
306 /// those upvars must be borrowed using an `&mut` borrow.
307 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
308 debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})",
311 match cmt.cat.clone() {
312 Categorization::Deref(base, mc::Unique) |
313 Categorization::Interior(base, _) |
314 Categorization::Downcast(base, _) => {
315 // Interior or owned data is mutable if base is
316 // mutable, so iterate to the base.
317 self.adjust_upvar_borrow_kind_for_mut(base);
320 Categorization::Deref(base, mc::BorrowedPtr(..)) |
321 Categorization::Deref(base, mc::Implicit(..)) => {
322 if !self.try_adjust_upvar_deref(cmt, ty::MutBorrow) {
323 // assignment to deref of an `&mut`
324 // borrowed pointer implies that the
325 // pointer itself must be unique, but not
326 // necessarily *mutable*
327 self.adjust_upvar_borrow_kind_for_unique(base);
331 Categorization::Deref(_, mc::UnsafePtr(..)) |
332 Categorization::StaticItem |
333 Categorization::Rvalue(..) |
334 Categorization::Local(_) |
335 Categorization::Upvar(..) => {
341 fn adjust_upvar_borrow_kind_for_unique(&mut self, cmt: mc::cmt<'tcx>) {
342 debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})",
345 match cmt.cat.clone() {
346 Categorization::Deref(base, mc::Unique) |
347 Categorization::Interior(base, _) |
348 Categorization::Downcast(base, _) => {
349 // Interior or owned data is unique if base is
351 self.adjust_upvar_borrow_kind_for_unique(base);
354 Categorization::Deref(base, mc::BorrowedPtr(..)) |
355 Categorization::Deref(base, mc::Implicit(..)) => {
356 if !self.try_adjust_upvar_deref(cmt, ty::UniqueImmBorrow) {
357 // for a borrowed pointer to be unique, its
358 // base must be unique
359 self.adjust_upvar_borrow_kind_for_unique(base);
363 Categorization::Deref(_, mc::UnsafePtr(..)) |
364 Categorization::StaticItem |
365 Categorization::Rvalue(..) |
366 Categorization::Local(_) |
367 Categorization::Upvar(..) => {
372 fn try_adjust_upvar_deref(&mut self,
374 borrow_kind: ty::BorrowKind)
377 assert!(match borrow_kind {
378 ty::MutBorrow => true,
379 ty::UniqueImmBorrow => true,
381 // imm borrows never require adjusting any kinds, so we don't wind up here
382 ty::ImmBorrow => false,
385 let tcx = self.fcx.tcx;
388 mc::NoteUpvarRef(upvar_id) => {
389 // if this is an implicit deref of an
390 // upvar, then we need to modify the
391 // borrow_kind of the upvar to make sure it
392 // is inferred to mutable if necessary
393 self.adjust_upvar_borrow_kind(upvar_id, borrow_kind);
395 // also need to be in an FnMut closure since this is not an ImmBorrow
396 self.adjust_closure_kind(upvar_id.closure_expr_id,
397 ty::ClosureKind::FnMut,
399 tcx.hir.name(upvar_id.var_id));
403 mc::NoteClosureEnv(upvar_id) => {
404 // this kind of deref occurs in a `move` closure, or
405 // for a by-value upvar; in either case, to mutate an
406 // upvar, we need to be an FnMut closure
407 self.adjust_closure_kind(upvar_id.closure_expr_id,
408 ty::ClosureKind::FnMut,
410 tcx.hir.name(upvar_id.var_id));
420 /// We infer the borrow_kind with which to borrow upvars in a stack closure.
421 /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
422 /// moving from left to right as needed (but never right to left).
423 /// Here the argument `mutbl` is the borrow_kind that is required by
424 /// some particular use.
425 fn adjust_upvar_borrow_kind(&mut self,
426 upvar_id: ty::UpvarId,
427 kind: ty::BorrowKind) {
428 let upvar_capture = self.adjust_upvar_captures.get(&upvar_id).cloned()
429 .unwrap_or_else(|| self.fcx.tables.borrow().upvar_capture(upvar_id));
430 debug!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
431 upvar_id, upvar_capture, kind);
433 match upvar_capture {
434 ty::UpvarCapture::ByValue => {
435 // Upvar is already by-value, the strongest criteria.
437 ty::UpvarCapture::ByRef(mut upvar_borrow) => {
438 match (upvar_borrow.kind, kind) {
440 (ty::ImmBorrow, ty::UniqueImmBorrow) |
441 (ty::ImmBorrow, ty::MutBorrow) |
442 (ty::UniqueImmBorrow, ty::MutBorrow) => {
443 upvar_borrow.kind = kind;
444 self.adjust_upvar_captures.insert(upvar_id,
445 ty::UpvarCapture::ByRef(upvar_borrow));
448 (ty::ImmBorrow, ty::ImmBorrow) |
449 (ty::UniqueImmBorrow, ty::ImmBorrow) |
450 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
451 (ty::MutBorrow, _) => {
458 fn adjust_closure_kind(&mut self,
459 closure_id: ast::NodeId,
460 new_kind: ty::ClosureKind,
462 var_name: ast::Name) {
463 debug!("adjust_closure_kind(closure_id={}, new_kind={:?}, upvar_span={:?}, var_name={})",
464 closure_id, new_kind, upvar_span, var_name);
466 let closure_kind = self.adjust_closure_kinds.get(&closure_id).cloned()
467 .or_else(|| self.fcx.tables.borrow().closure_kinds.get(&closure_id).cloned());
468 if let Some((existing_kind, _)) = closure_kind {
469 debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
470 closure_id, existing_kind, new_kind);
472 match (existing_kind, new_kind) {
473 (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
474 (ty::ClosureKind::FnMut, ty::ClosureKind::Fn) |
475 (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
476 (ty::ClosureKind::FnOnce, _) => {
480 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) |
481 (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
482 (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
483 // new kind is stronger than the old kind
484 self.adjust_closure_kinds.insert(
486 (new_kind, Some((upvar_span, var_name)))
494 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'gcx, 'tcx> {
495 fn consume(&mut self,
496 _consume_id: ast::NodeId,
499 mode: euv::ConsumeMode)
501 debug!("consume(cmt={:?},mode={:?})", cmt, mode);
502 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
505 fn matched_pat(&mut self,
506 _matched_pat: &hir::Pat,
508 _mode: euv::MatchMode)
511 fn consume_pat(&mut self,
512 _consume_pat: &hir::Pat,
514 mode: euv::ConsumeMode)
516 debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode);
517 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
521 borrow_id: ast::NodeId,
524 _loan_region: ty::Region<'tcx>,
526 _loan_cause: euv::LoanCause)
528 debug!("borrow(borrow_id={}, cmt={:?}, bk={:?})",
533 ty::UniqueImmBorrow => {
534 self.adjust_upvar_borrow_kind_for_unique(cmt);
537 self.adjust_upvar_borrow_kind_for_mut(cmt);
542 fn decl_without_init(&mut self,
548 _assignment_id: ast::NodeId,
549 _assignment_span: Span,
550 assignee_cmt: mc::cmt<'tcx>,
551 _mode: euv::MutateMode)
553 debug!("mutate(assignee_cmt={:?})",
556 self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);