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::def_id::DefIndex;
54 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
55 use rustc::util::nodemap::FxHashMap;
57 use std::collections::hash_map::Entry;
59 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
60 pub fn closure_analyze(&self, body: &'gcx hir::Body) {
61 InferBorrowKindVisitor { fcx: self }.visit_body(body);
63 // it's our job to process these.
64 assert!(self.deferred_call_resolutions.borrow().is_empty());
68 struct InferBorrowKindVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
69 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
72 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for InferBorrowKindVisitor<'a, 'gcx, 'tcx> {
73 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
74 NestedVisitorMap::None
77 fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
79 hir::ExprClosure(cc, _, body_id, _, is_generator) => {
80 let body = self.fcx.tcx.hir.body(body_id);
81 self.visit_body(body);
82 self.fcx.analyze_closure((expr.id, expr.hir_id),
92 intravisit::walk_expr(self, expr);
96 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
97 fn analyze_closure(&self,
98 (closure_node_id, closure_hir_id): (ast::NodeId, hir::HirId),
101 capture_clause: hir::CaptureClause,
104 * Analysis starting point.
107 debug!("analyze_closure(id={:?}, body.id={:?})", closure_node_id, body.id());
109 let infer_kind = if gen {
115 .entry(closure_hir_id) {
116 Entry::Occupied(_) => false,
117 Entry::Vacant(entry) => {
118 debug!("check_closure: adding closure {:?} as Fn", closure_node_id);
119 entry.insert((ty::ClosureKind::Fn, None));
125 let closure_def_id = self.tcx.hir.local_def_id(closure_node_id);
127 self.tcx.with_freevars(closure_node_id, |freevars| {
128 for freevar in freevars {
129 let upvar_id = ty::UpvarId {
130 var_id: self.tcx.hir.node_to_hir_id(freevar.var_id()),
131 closure_expr_id: closure_def_id.index,
133 debug!("seed upvar_id {:?}", upvar_id);
135 let capture_kind = match capture_clause {
136 hir::CaptureByValue => {
137 ty::UpvarCapture::ByValue
139 hir::CaptureByRef => {
140 let origin = UpvarRegion(upvar_id, span);
141 let freevar_region = self.next_region_var(origin);
142 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow,
143 region: freevar_region };
144 ty::UpvarCapture::ByRef(upvar_borrow)
148 self.tables.borrow_mut().upvar_capture_map.insert(upvar_id, capture_kind);
153 let body_owner_def_id = self.tcx.hir.body_owner_def_id(body.id());
154 let region_scope_tree = &self.tcx.region_scope_tree(body_owner_def_id);
155 let mut delegate = InferBorrowKind {
157 adjust_closure_kinds: FxHashMap(),
158 adjust_upvar_captures: ty::UpvarCaptureMap::default(),
160 euv::ExprUseVisitor::with_infer(&mut delegate,
164 &self.tables.borrow())
167 // Write the adjusted values back into the main tables.
169 if let Some(kind) = delegate.adjust_closure_kinds
170 .remove(&closure_def_id.index) {
174 .insert(closure_hir_id, kind);
177 self.tables.borrow_mut().upvar_capture_map.extend(
178 delegate.adjust_upvar_captures);
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.node_ty(closure_hir_id).sty {
195 ty::TyClosure(def_id, substs) |
196 ty::TyGenerator(def_id, substs, _) => (def_id, substs),
200 "type of closure expr {:?} is not a closure {:?}",
205 // Equate the type variables with the actual types.
206 let final_upvar_tys = self.final_upvar_tys(closure_node_id);
207 debug!("analyze_closure: id={:?} closure_substs={:?} final_upvar_tys={:?}",
208 closure_node_id, closure_substs, final_upvar_tys);
209 for (upvar_ty, final_upvar_ty) in
210 closure_substs.upvar_tys(def_id, self.tcx).zip(final_upvar_tys)
212 self.demand_eqtype(span, final_upvar_ty, upvar_ty);
215 // If we are also inferred the closure kind here,
216 // process any deferred resolutions.
218 let deferred_call_resolutions =
219 self.remove_deferred_call_resolutions(closure_def_id);
220 for deferred_call_resolution in deferred_call_resolutions {
221 deferred_call_resolution.resolve(self);
226 // Returns a list of `ClosureUpvar`s for each upvar.
227 fn final_upvar_tys(&self, closure_id: ast::NodeId) -> Vec<Ty<'tcx>> {
228 // Presently an unboxed closure type cannot "escape" out of a
229 // function, so we will only encounter ones that originated in the
230 // local crate or were inlined into it along with some function.
231 // This may change if abstract return types of some sort are
234 let closure_def_index = tcx.hir.local_def_id(closure_id).index;
236 tcx.with_freevars(closure_id, |freevars| {
237 freevars.iter().map(|freevar| {
238 let var_node_id = freevar.var_id();
239 let var_hir_id = tcx.hir.node_to_hir_id(var_node_id);
240 let freevar_ty = self.node_ty(var_hir_id);
241 let upvar_id = ty::UpvarId {
243 closure_expr_id: closure_def_index,
245 let capture = self.tables.borrow().upvar_capture(upvar_id);
247 debug!("var_id={:?} freevar_ty={:?} capture={:?}",
248 var_node_id, freevar_ty, capture);
251 ty::UpvarCapture::ByValue => freevar_ty,
252 ty::UpvarCapture::ByRef(borrow) =>
253 tcx.mk_ref(borrow.region,
256 mutbl: borrow.kind.to_mutbl_lossy(),
264 struct InferBorrowKind<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
265 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
266 adjust_closure_kinds: FxHashMap<DefIndex, (ty::ClosureKind, Option<(Span, ast::Name)>)>,
267 adjust_upvar_captures: ty::UpvarCaptureMap<'tcx>,
270 impl<'a, 'gcx, 'tcx> InferBorrowKind<'a, 'gcx, 'tcx> {
271 fn adjust_upvar_borrow_kind_for_consume(&mut self,
273 mode: euv::ConsumeMode)
275 debug!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
278 // we only care about moves
280 euv::Copy => { return; }
284 let tcx = self.fcx.tcx;
286 // watch out for a move of the deref of a borrowed pointer;
287 // for that to be legal, the upvar would have to be borrowed
289 let guarantor = cmt.guarantor();
290 debug!("adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
292 match guarantor.cat {
293 Categorization::Deref(_, mc::BorrowedPtr(..)) |
294 Categorization::Deref(_, mc::Implicit(..)) => {
296 mc::NoteUpvarRef(upvar_id) => {
297 debug!("adjust_upvar_borrow_kind_for_consume: \
298 setting upvar_id={:?} to by value",
301 // to move out of an upvar, this must be a FnOnce closure
302 self.adjust_closure_kind(upvar_id.closure_expr_id,
303 ty::ClosureKind::FnOnce,
305 var_name(tcx, upvar_id.var_id));
307 self.adjust_upvar_captures.insert(upvar_id, ty::UpvarCapture::ByValue);
309 mc::NoteClosureEnv(upvar_id) => {
310 // we get just a closureenv ref if this is a
311 // `move` closure, or if the upvar has already
312 // been inferred to by-value. In any case, we
313 // must still adjust the kind of the closure
314 // to be a FnOnce closure to permit moves out
315 // of the environment.
316 self.adjust_closure_kind(upvar_id.closure_expr_id,
317 ty::ClosureKind::FnOnce,
319 var_name(tcx, upvar_id.var_id));
329 /// Indicates that `cmt` is being directly mutated (e.g., assigned
330 /// to). If cmt contains any by-ref upvars, this implies that
331 /// those upvars must be borrowed using an `&mut` borrow.
332 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
333 debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})",
336 match cmt.cat.clone() {
337 Categorization::Deref(base, mc::Unique) |
338 Categorization::Interior(base, _) |
339 Categorization::Downcast(base, _) => {
340 // Interior or owned data is mutable if base is
341 // mutable, so iterate to the base.
342 self.adjust_upvar_borrow_kind_for_mut(base);
345 Categorization::Deref(base, mc::BorrowedPtr(..)) |
346 Categorization::Deref(base, mc::Implicit(..)) => {
347 if !self.try_adjust_upvar_deref(cmt, ty::MutBorrow) {
348 // assignment to deref of an `&mut`
349 // borrowed pointer implies that the
350 // pointer itself must be unique, but not
351 // necessarily *mutable*
352 self.adjust_upvar_borrow_kind_for_unique(base);
356 Categorization::Deref(_, mc::UnsafePtr(..)) |
357 Categorization::StaticItem |
358 Categorization::Rvalue(..) |
359 Categorization::Local(_) |
360 Categorization::Upvar(..) => {
366 fn adjust_upvar_borrow_kind_for_unique(&mut self, cmt: mc::cmt<'tcx>) {
367 debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})",
370 match cmt.cat.clone() {
371 Categorization::Deref(base, mc::Unique) |
372 Categorization::Interior(base, _) |
373 Categorization::Downcast(base, _) => {
374 // Interior or owned data is unique if base is
376 self.adjust_upvar_borrow_kind_for_unique(base);
379 Categorization::Deref(base, mc::BorrowedPtr(..)) |
380 Categorization::Deref(base, mc::Implicit(..)) => {
381 if !self.try_adjust_upvar_deref(cmt, ty::UniqueImmBorrow) {
382 // for a borrowed pointer to be unique, its
383 // base must be unique
384 self.adjust_upvar_borrow_kind_for_unique(base);
388 Categorization::Deref(_, mc::UnsafePtr(..)) |
389 Categorization::StaticItem |
390 Categorization::Rvalue(..) |
391 Categorization::Local(_) |
392 Categorization::Upvar(..) => {
397 fn try_adjust_upvar_deref(&mut self,
399 borrow_kind: ty::BorrowKind)
402 assert!(match borrow_kind {
403 ty::MutBorrow => true,
404 ty::UniqueImmBorrow => true,
406 // imm borrows never require adjusting any kinds, so we don't wind up here
407 ty::ImmBorrow => false,
410 let tcx = self.fcx.tcx;
413 mc::NoteUpvarRef(upvar_id) => {
414 // if this is an implicit deref of an
415 // upvar, then we need to modify the
416 // borrow_kind of the upvar to make sure it
417 // is inferred to mutable if necessary
418 self.adjust_upvar_borrow_kind(upvar_id, 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,
422 ty::ClosureKind::FnMut,
424 var_name(tcx, upvar_id.var_id));
428 mc::NoteClosureEnv(upvar_id) => {
429 // this kind of deref occurs in a `move` closure, or
430 // for a by-value upvar; in either case, to mutate an
431 // upvar, we need to be an FnMut closure
432 self.adjust_closure_kind(upvar_id.closure_expr_id,
433 ty::ClosureKind::FnMut,
435 var_name(tcx, upvar_id.var_id));
445 /// We infer the borrow_kind with which to borrow upvars in a stack closure.
446 /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
447 /// moving from left to right as needed (but never right to left).
448 /// Here the argument `mutbl` is the borrow_kind that is required by
449 /// some particular use.
450 fn adjust_upvar_borrow_kind(&mut self,
451 upvar_id: ty::UpvarId,
452 kind: ty::BorrowKind) {
453 let upvar_capture = self.adjust_upvar_captures.get(&upvar_id).cloned()
454 .unwrap_or_else(|| self.fcx.tables.borrow().upvar_capture(upvar_id));
455 debug!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
456 upvar_id, upvar_capture, kind);
458 match upvar_capture {
459 ty::UpvarCapture::ByValue => {
460 // Upvar is already by-value, the strongest criteria.
462 ty::UpvarCapture::ByRef(mut upvar_borrow) => {
463 match (upvar_borrow.kind, kind) {
465 (ty::ImmBorrow, ty::UniqueImmBorrow) |
466 (ty::ImmBorrow, ty::MutBorrow) |
467 (ty::UniqueImmBorrow, ty::MutBorrow) => {
468 upvar_borrow.kind = kind;
469 self.adjust_upvar_captures.insert(upvar_id,
470 ty::UpvarCapture::ByRef(upvar_borrow));
473 (ty::ImmBorrow, ty::ImmBorrow) |
474 (ty::UniqueImmBorrow, ty::ImmBorrow) |
475 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
476 (ty::MutBorrow, _) => {
483 fn adjust_closure_kind(&mut self,
484 closure_id: DefIndex,
485 new_kind: ty::ClosureKind,
487 var_name: ast::Name) {
488 debug!("adjust_closure_kind(closure_id={:?}, new_kind={:?}, upvar_span={:?}, var_name={})",
489 closure_id, new_kind, upvar_span, var_name);
491 let closure_kind = self.adjust_closure_kinds.get(&closure_id).cloned()
493 let closure_id = self.fcx.tcx.hir.def_index_to_hir_id(closure_id);
494 self.fcx.tables.borrow().closure_kinds().get(closure_id).cloned()
497 if let Some((existing_kind, _)) = closure_kind {
498 debug!("adjust_closure_kind: closure_id={:?}, existing_kind={:?}, new_kind={:?}",
499 closure_id, existing_kind, new_kind);
501 match (existing_kind, new_kind) {
502 (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
503 (ty::ClosureKind::FnMut, ty::ClosureKind::Fn) |
504 (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
505 (ty::ClosureKind::FnOnce, _) => {
509 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) |
510 (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
511 (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
512 // new kind is stronger than the old kind
513 self.adjust_closure_kinds.insert(
515 (new_kind, Some((upvar_span, var_name)))
523 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'gcx, 'tcx> {
524 fn consume(&mut self,
525 _consume_id: ast::NodeId,
528 mode: euv::ConsumeMode)
530 debug!("consume(cmt={:?},mode={:?})", cmt, mode);
531 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
534 fn matched_pat(&mut self,
535 _matched_pat: &hir::Pat,
537 _mode: euv::MatchMode)
540 fn consume_pat(&mut self,
541 _consume_pat: &hir::Pat,
543 mode: euv::ConsumeMode)
545 debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode);
546 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
550 borrow_id: ast::NodeId,
553 _loan_region: ty::Region<'tcx>,
555 _loan_cause: euv::LoanCause)
557 debug!("borrow(borrow_id={}, cmt={:?}, bk={:?})",
562 ty::UniqueImmBorrow => {
563 self.adjust_upvar_borrow_kind_for_unique(cmt);
566 self.adjust_upvar_borrow_kind_for_mut(cmt);
571 fn decl_without_init(&mut self,
577 _assignment_id: ast::NodeId,
578 _assignment_span: Span,
579 assignee_cmt: mc::cmt<'tcx>,
580 _mode: euv::MutateMode)
582 debug!("mutate(assignee_cmt={:?})",
585 self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);
589 fn var_name(tcx: ty::TyCtxt, var_hir_id: hir::HirId) -> ast::Name {
590 let var_node_id = tcx.hir.hir_to_node_id(var_hir_id);
591 tcx.hir.name(var_node_id)