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::ty::{self};
48 use middle::infer::{InferCtxt, UpvarRegion};
50 use syntax::codemap::Span;
51 use syntax::visit::{self, Visitor};
52 use util::ppaux::Repr;
54 ///////////////////////////////////////////////////////////////////////////
55 // PUBLIC ENTRY POINTS
57 pub fn closure_analyze_fn(fcx: &FnCtxt,
61 let mut seed = SeedBorrowKind::new(fcx);
62 seed.visit_block(body);
64 let mut adjust = AdjustBorrowKind::new(fcx);
65 adjust.analyze_fn(decl, body);
68 ///////////////////////////////////////////////////////////////////////////
71 struct SeedBorrowKind<'a,'tcx:'a> {
72 fcx: &'a FnCtxt<'a,'tcx>,
75 impl<'a, 'tcx, 'v> Visitor<'v> for SeedBorrowKind<'a, 'tcx> {
76 fn visit_expr(&mut self, expr: &ast::Expr) {
78 ast::ExprClosure(cc, _, _, ref body) => {
79 self.check_closure(expr, cc, &**body);
85 visit::walk_expr(self, expr);
88 fn visit_fn(&mut self,
89 fn_kind: visit::FnKind<'v>,
90 decl: &'v ast::FnDecl,
91 block: &'v ast::Block,
96 visit::FkItemFn(..) | visit::FkMethod(..) => {
97 // ignore nested fn items
100 visit::walk_fn(self, fn_kind, decl, block, span);
106 impl<'a,'tcx> SeedBorrowKind<'a,'tcx> {
107 fn new(fcx: &'a FnCtxt<'a,'tcx>) -> SeedBorrowKind<'a,'tcx> {
108 SeedBorrowKind { fcx: fcx }
111 fn tcx(&self) -> &'a ty::ctxt<'tcx> {
115 fn infcx(&self) -> &'a InferCtxt<'a,'tcx> {
119 fn check_closure(&mut self,
121 capture_clause: ast::CaptureClause,
124 let is_old_skool_closure = match self.fcx.expr_ty(expr).sty {
128 match capture_clause {
129 ast::CaptureByValue if !is_old_skool_closure => {
132 ty::with_freevars(self.tcx(), expr.id, |freevars| {
133 for freevar in freevars.iter() {
134 let var_node_id = freevar.def.local_node_id();
135 let upvar_id = ty::UpvarId { var_id: var_node_id,
136 closure_expr_id: expr.id };
137 debug!("seed upvar_id {}", upvar_id);
138 let origin = UpvarRegion(upvar_id, expr.span);
139 let freevar_region = self.infcx().next_region_var(origin);
140 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow,
141 region: freevar_region };
142 self.fcx.inh.upvar_borrow_map.borrow_mut().insert(upvar_id,
151 ///////////////////////////////////////////////////////////////////////////
152 // ADJUST BORROW KIND
154 struct AdjustBorrowKind<'a,'tcx:'a> {
155 fcx: &'a FnCtxt<'a,'tcx>
158 impl<'a,'tcx> AdjustBorrowKind<'a,'tcx>{
159 fn new(fcx: &'a FnCtxt<'a,'tcx>) -> AdjustBorrowKind<'a,'tcx> {
160 AdjustBorrowKind { fcx: fcx }
163 fn tcx(&self) -> &'a ty::ctxt<'tcx> {
167 fn analyze_fn(&mut self, decl: &ast::FnDecl, body: &ast::Block) {
169 * Analysis starting point.
172 self.visit_block(body);
174 debug!("analyzing fn body with id {}", body.id);
176 let mut euv = euv::ExprUseVisitor::new(self, self.fcx);
177 euv.walk_fn(decl, body);
180 /// Indicates that `cmt` is being directly mutated (e.g., assigned
181 /// to). If cmt contains any by-ref upvars, this implies that
182 /// those upvars must be borrowed using an `&mut` borow.
183 fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
184 debug!("adjust_upvar_borrow_kind_for_mut(cmt={})",
185 cmt.repr(self.tcx()));
187 match cmt.cat.clone() {
188 mc::cat_deref(base, _, mc::Unique) |
189 mc::cat_interior(base, _) |
190 mc::cat_downcast(base, _) => {
191 // Interior or owned data is mutable if base is
192 // mutable, so iterate to the base.
193 self.adjust_upvar_borrow_kind_for_mut(base);
196 mc::cat_deref(base, _, mc::BorrowedPtr(..)) |
197 mc::cat_deref(base, _, mc::Implicit(..)) => {
198 if let mc::NoteUpvarRef(upvar_id) = cmt.note {
199 // if this is an implicit deref of an
200 // upvar, then we need to modify the
201 // borrow_kind of the upvar to make sure it
202 // is inferred to mutable if necessary
203 let mut upvar_borrow_map = self.fcx.inh.upvar_borrow_map.borrow_mut();
204 let ub = &mut upvar_borrow_map[upvar_id];
205 self.adjust_upvar_borrow_kind(upvar_id, ub, ty::MutBorrow);
207 // assignment to deref of an `&mut`
208 // borrowed pointer implies that the
209 // pointer itself must be unique, but not
210 // necessarily *mutable*
211 self.adjust_upvar_borrow_kind_for_unique(base);
215 mc::cat_deref(_, _, mc::UnsafePtr(..)) |
216 mc::cat_static_item |
219 mc::cat_upvar(..) => {
225 fn adjust_upvar_borrow_kind_for_unique(&self, cmt: mc::cmt<'tcx>) {
226 debug!("adjust_upvar_borrow_kind_for_unique(cmt={})",
227 cmt.repr(self.tcx()));
229 match cmt.cat.clone() {
230 mc::cat_deref(base, _, mc::Unique) |
231 mc::cat_interior(base, _) |
232 mc::cat_downcast(base, _) => {
233 // Interior or owned data is unique if base is
235 self.adjust_upvar_borrow_kind_for_unique(base);
238 mc::cat_deref(base, _, mc::BorrowedPtr(..)) |
239 mc::cat_deref(base, _, mc::Implicit(..)) => {
240 if let mc::NoteUpvarRef(upvar_id) = cmt.note {
241 // if this is an implicit deref of an
242 // upvar, then we need to modify the
243 // borrow_kind of the upvar to make sure it
244 // is inferred to unique if necessary
245 let mut ub = self.fcx.inh.upvar_borrow_map.borrow_mut();
246 let ub = &mut ub[upvar_id];
247 self.adjust_upvar_borrow_kind(upvar_id, ub, ty::UniqueImmBorrow);
249 // for a borrowed pointer to be unique, its
250 // base must be unique
251 self.adjust_upvar_borrow_kind_for_unique(base);
255 mc::cat_deref(_, _, mc::UnsafePtr(..)) |
256 mc::cat_static_item |
259 mc::cat_upvar(..) => {
264 /// We infer the borrow_kind with which to borrow upvars in a stack closure. The borrow_kind
265 /// basically follows a lattice of `imm < unique-imm < mut`, moving from left to right as needed
266 /// (but never right to left). Here the argument `mutbl` is the borrow_kind that is required by
267 /// some particular use.
268 fn adjust_upvar_borrow_kind(&self,
269 upvar_id: ty::UpvarId,
270 upvar_borrow: &mut ty::UpvarBorrow,
271 kind: ty::BorrowKind) {
272 debug!("adjust_upvar_borrow_kind: id={} kind=({} -> {})",
273 upvar_id, upvar_borrow.kind, kind);
275 match (upvar_borrow.kind, kind) {
277 (ty::ImmBorrow, ty::UniqueImmBorrow) |
278 (ty::ImmBorrow, ty::MutBorrow) |
279 (ty::UniqueImmBorrow, ty::MutBorrow) => {
280 upvar_borrow.kind = kind;
283 (ty::ImmBorrow, ty::ImmBorrow) |
284 (ty::UniqueImmBorrow, ty::ImmBorrow) |
285 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
286 (ty::MutBorrow, _) => {
292 impl<'a, 'tcx, 'v> Visitor<'v> for AdjustBorrowKind<'a, 'tcx> {
293 fn visit_fn(&mut self,
294 fn_kind: visit::FnKind<'v>,
295 decl: &'v ast::FnDecl,
296 body: &'v ast::Block,
301 visit::FkItemFn(..) | visit::FkMethod(..) => {
302 // ignore nested fn items
304 visit::FkFnBlock => {
305 self.analyze_fn(decl, body);
306 visit::walk_fn(self, fn_kind, decl, body, span);
312 impl<'a,'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a,'tcx> {
313 fn consume(&mut self,
314 _consume_id: ast::NodeId,
317 _mode: euv::ConsumeMode)
320 fn matched_pat(&mut self,
321 _matched_pat: &ast::Pat,
323 _mode: euv::MatchMode)
326 fn consume_pat(&mut self,
327 _consume_pat: &ast::Pat,
329 _mode: euv::ConsumeMode)
333 borrow_id: ast::NodeId,
336 _loan_region: ty::Region,
338 _loan_cause: euv::LoanCause)
340 debug!("borrow(borrow_id={}, cmt={}, bk={})",
341 borrow_id, cmt.repr(self.tcx()), bk);
345 ty::UniqueImmBorrow => {
346 self.adjust_upvar_borrow_kind_for_unique(cmt);
349 self.adjust_upvar_borrow_kind_for_mut(cmt);
354 fn decl_without_init(&mut self,
360 _assignment_id: ast::NodeId,
361 _assignment_span: Span,
362 assignee_cmt: mc::cmt<'tcx>,
363 _mode: euv::MutateMode)
365 debug!("mutate(assignee_cmt={})",
366 assignee_cmt.repr(self.tcx()));
368 self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);