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>,
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);
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>,
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>)
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());
168 euv::ExprUseVisitor::with_options(self,
170 mc::MemCategorizationOptions {
171 during_closure_kind_inference: true
173 euv.consume_body(body);
176 // Now that we've analyzed the closure, we know how each
177 // variable is borrowed, and we know what traits the closure
178 // implements (Fn vs FnMut etc). We now have some updates to do
179 // with that information.
181 // Note that no closure type C may have an upvar of type C
182 // (though it may reference itself via a trait object). This
183 // results from the desugaring of closures to a struct like
184 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
185 // C, then the type would have infinite size (and the
186 // inference algorithm will reject it).
188 // Extract the type variables UV0...UVn.
189 let (def_id, closure_substs) = match self.fcx.node_ty(id).sty {
190 ty::TyClosure(def_id, substs) => (def_id, substs),
194 "type of closure expr {:?} is not a closure {:?}",
199 // Equate the type variables with the actual types.
200 let final_upvar_tys = self.final_upvar_tys(id);
201 debug!("analyze_closure: id={:?} closure_substs={:?} final_upvar_tys={:?}",
202 id, closure_substs, final_upvar_tys);
203 for (upvar_ty, final_upvar_ty) in
204 closure_substs.upvar_tys(def_id, self.fcx.tcx).zip(final_upvar_tys)
206 self.fcx.demand_eqtype(span, final_upvar_ty, upvar_ty);
209 // If we are also inferred the closure kind here, update the
210 // main table and process any deferred resolutions.
211 if let Some(&kind) = self.temp_closure_kinds.get(&id) {
212 self.fcx.tables.borrow_mut().closure_kinds.insert(id, kind);
213 let closure_def_id = self.fcx.tcx.hir.local_def_id(id);
214 debug!("closure_kind({:?}) = {:?}", closure_def_id, kind);
216 let mut deferred_call_resolutions =
217 self.fcx.remove_deferred_call_resolutions(closure_def_id);
218 for deferred_call_resolution in &mut deferred_call_resolutions {
219 deferred_call_resolution.resolve(self.fcx);
224 // Returns a list of `ClosureUpvar`s for each upvar.
225 fn final_upvar_tys(&mut self, closure_id: ast::NodeId) -> Vec<Ty<'tcx>> {
226 // Presently an unboxed closure type cannot "escape" out of a
227 // function, so we will only encounter ones that originated in the
228 // local crate or were inlined into it along with some function.
229 // This may change if abstract return types of some sort are
231 let tcx = self.fcx.tcx;
232 tcx.with_freevars(closure_id, |freevars| {
233 freevars.iter().map(|freevar| {
234 let def_id = freevar.def.def_id();
235 let var_id = tcx.hir.as_local_node_id(def_id).unwrap();
236 let freevar_ty = self.fcx.node_ty(var_id);
237 let upvar_id = ty::UpvarId {
239 closure_expr_id: closure_id
241 let capture = self.fcx.upvar_capture(upvar_id).unwrap();
243 debug!("var_id={:?} freevar_ty={:?} capture={:?}",
244 var_id, freevar_ty, capture);
247 ty::UpvarCapture::ByValue => freevar_ty,
248 ty::UpvarCapture::ByRef(borrow) =>
249 tcx.mk_ref(borrow.region,
252 mutbl: borrow.kind.to_mutbl_lossy(),
259 fn adjust_upvar_borrow_kind_for_consume(&mut self,
261 mode: euv::ConsumeMode)
263 debug!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
266 // we only care about moves
268 euv::Copy => { return; }
272 // watch out for a move of the deref of a borrowed pointer;
273 // for that to be legal, the upvar would have to be borrowed
275 let guarantor = cmt.guarantor();
276 debug!("adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
278 match guarantor.cat {
279 Categorization::Deref(.., mc::BorrowedPtr(..)) |
280 Categorization::Deref(.., mc::Implicit(..)) => {
282 mc::NoteUpvarRef(upvar_id) => {
283 debug!("adjust_upvar_borrow_kind_for_consume: \
284 setting upvar_id={:?} to by value",
287 // to move out of an upvar, this must be a FnOnce closure
288 self.adjust_closure_kind(upvar_id.closure_expr_id,
289 ty::ClosureKind::FnOnce);
291 let upvar_capture_map =
292 &mut self.fcx.tables.borrow_mut().upvar_capture_map;
293 upvar_capture_map.insert(upvar_id, ty::UpvarCapture::ByValue);
295 mc::NoteClosureEnv(upvar_id) => {
296 // we get just a closureenv ref if this is a
297 // `move` closure, or if the upvar has already
298 // been inferred to by-value. In any case, we
299 // must still adjust the kind of the closure
300 // to be a FnOnce closure to permit moves out
301 // of the environment.
302 self.adjust_closure_kind(upvar_id.closure_expr_id,
303 ty::ClosureKind::FnOnce);
313 /// Indicates that `cmt` is being directly mutated (e.g., assigned
314 /// to). If cmt contains any by-ref upvars, this implies that
315 /// those upvars must be borrowed using an `&mut` borrow.
316 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
317 debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})",
320 match cmt.cat.clone() {
321 Categorization::Deref(base, _, mc::Unique) |
322 Categorization::Interior(base, _) |
323 Categorization::Downcast(base, _) => {
324 // Interior or owned data is mutable if base is
325 // mutable, so iterate to the base.
326 self.adjust_upvar_borrow_kind_for_mut(base);
329 Categorization::Deref(base, _, mc::BorrowedPtr(..)) |
330 Categorization::Deref(base, _, mc::Implicit(..)) => {
331 if !self.try_adjust_upvar_deref(&cmt.note, ty::MutBorrow) {
332 // assignment to deref of an `&mut`
333 // borrowed pointer implies that the
334 // pointer itself must be unique, but not
335 // necessarily *mutable*
336 self.adjust_upvar_borrow_kind_for_unique(base);
340 Categorization::Deref(.., mc::UnsafePtr(..)) |
341 Categorization::StaticItem |
342 Categorization::Rvalue(..) |
343 Categorization::Local(_) |
344 Categorization::Upvar(..) => {
350 fn adjust_upvar_borrow_kind_for_unique(&mut self, cmt: mc::cmt<'tcx>) {
351 debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})",
354 match cmt.cat.clone() {
355 Categorization::Deref(base, _, mc::Unique) |
356 Categorization::Interior(base, _) |
357 Categorization::Downcast(base, _) => {
358 // Interior or owned data is unique if base is
360 self.adjust_upvar_borrow_kind_for_unique(base);
363 Categorization::Deref(base, _, mc::BorrowedPtr(..)) |
364 Categorization::Deref(base, _, mc::Implicit(..)) => {
365 if !self.try_adjust_upvar_deref(&cmt.note, ty::UniqueImmBorrow) {
366 // for a borrowed pointer to be unique, its
367 // base must be unique
368 self.adjust_upvar_borrow_kind_for_unique(base);
372 Categorization::Deref(.., mc::UnsafePtr(..)) |
373 Categorization::StaticItem |
374 Categorization::Rvalue(..) |
375 Categorization::Local(_) |
376 Categorization::Upvar(..) => {
381 fn try_adjust_upvar_deref(&mut self,
383 borrow_kind: ty::BorrowKind)
386 assert!(match borrow_kind {
387 ty::MutBorrow => true,
388 ty::UniqueImmBorrow => true,
390 // imm borrows never require adjusting any kinds, so we don't wind up here
391 ty::ImmBorrow => false,
395 mc::NoteUpvarRef(upvar_id) => {
396 // if this is an implicit deref of an
397 // upvar, then we need to modify the
398 // borrow_kind of the upvar to make sure it
399 // is inferred to mutable if necessary
401 let upvar_capture_map = &mut self.fcx.tables.borrow_mut().upvar_capture_map;
402 let ub = upvar_capture_map.get_mut(&upvar_id).unwrap();
403 self.adjust_upvar_borrow_kind(upvar_id, ub, borrow_kind);
406 // also need to be in an FnMut closure since this is not an ImmBorrow
407 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::ClosureKind::FnMut);
411 mc::NoteClosureEnv(upvar_id) => {
412 // this kind of deref occurs in a `move` closure, or
413 // for a by-value upvar; in either case, to mutate an
414 // upvar, we need to be an FnMut closure
415 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::ClosureKind::FnMut);
425 /// We infer the borrow_kind with which to borrow upvars in a stack closure.
426 /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
427 /// moving from left to right as needed (but never right to left).
428 /// Here the argument `mutbl` is the borrow_kind that is required by
429 /// some particular use.
430 fn adjust_upvar_borrow_kind(&mut self,
431 upvar_id: ty::UpvarId,
432 upvar_capture: &mut ty::UpvarCapture,
433 kind: ty::BorrowKind) {
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(ref 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;
450 (ty::ImmBorrow, ty::ImmBorrow) |
451 (ty::UniqueImmBorrow, ty::ImmBorrow) |
452 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
453 (ty::MutBorrow, _) => {
460 fn adjust_closure_kind(&mut self,
461 closure_id: ast::NodeId,
462 new_kind: ty::ClosureKind) {
463 debug!("adjust_closure_kind(closure_id={}, new_kind={:?})",
464 closure_id, new_kind);
466 if let Some(&existing_kind) = self.temp_closure_kinds.get(&closure_id) {
467 debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
468 closure_id, existing_kind, new_kind);
470 match (existing_kind, new_kind) {
471 (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
472 (ty::ClosureKind::FnMut, ty::ClosureKind::Fn) |
473 (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
474 (ty::ClosureKind::FnOnce, _) => {
478 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) |
479 (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
480 (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
481 // new kind is stronger than the old kind
482 self.temp_closure_kinds.insert(closure_id, new_kind);
489 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for AdjustBorrowKind<'a, 'gcx, 'tcx> {
490 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
491 NestedVisitorMap::None
494 fn visit_fn(&mut self,
495 fn_kind: intravisit::FnKind<'gcx>,
496 decl: &'gcx hir::FnDecl,
501 intravisit::walk_fn(self, fn_kind, decl, body, span, id);
503 let body = self.fcx.tcx.hir.body(body);
504 self.visit_body(body);
505 self.analyze_closure(id, span, body);
509 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a, 'gcx, 'tcx> {
510 fn consume(&mut self,
511 _consume_id: ast::NodeId,
514 mode: euv::ConsumeMode)
516 debug!("consume(cmt={:?},mode={:?})", cmt, mode);
517 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
520 fn matched_pat(&mut self,
521 _matched_pat: &hir::Pat,
523 _mode: euv::MatchMode)
526 fn consume_pat(&mut self,
527 _consume_pat: &hir::Pat,
529 mode: euv::ConsumeMode)
531 debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode);
532 self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
536 borrow_id: ast::NodeId,
539 _loan_region: &'tcx ty::Region,
541 _loan_cause: euv::LoanCause)
543 debug!("borrow(borrow_id={}, cmt={:?}, bk={:?})",
548 ty::UniqueImmBorrow => {
549 self.adjust_upvar_borrow_kind_for_unique(cmt);
552 self.adjust_upvar_borrow_kind_for_mut(cmt);
557 fn decl_without_init(&mut self,
563 _assignment_id: ast::NodeId,
564 _assignment_span: Span,
565 assignee_cmt: mc::cmt<'tcx>,
566 _mode: euv::MutateMode)
568 debug!("mutate(assignee_cmt={:?})",
571 self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);