]> git.lizzy.rs Git - rust.git/blob - src/librustc_borrowck/borrowck/check_loans.rs
Rollup merge of #52019 - michaelwoerister:cross-lto-auto-plugin, r=alexcrichton
[rust.git] / src / librustc_borrowck / borrowck / check_loans.rs
1 // Copyright 2012-2013 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.
4 //
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.
10
11 // ----------------------------------------------------------------------
12 // Checking loans
13 //
14 // Phase 2 of check: we walk down the tree and check that:
15 // 1. assignments are always made to mutable locations;
16 // 2. loans made in overlapping scopes do not conflict
17 // 3. assignments do not affect things loaned out as immutable
18 // 4. moves do not affect things loaned out in any way
19 use self::UseError::*;
20
21 use borrowck::*;
22 use borrowck::InteriorKind::{InteriorElement, InteriorField};
23 use rustc::middle::expr_use_visitor as euv;
24 use rustc::middle::expr_use_visitor::MutateMode;
25 use rustc::middle::mem_categorization as mc;
26 use rustc::middle::mem_categorization::Categorization;
27 use rustc::middle::region;
28 use rustc::ty::{self, TyCtxt, RegionKind};
29 use syntax::ast;
30 use syntax_pos::Span;
31 use rustc::hir;
32 use rustc_mir::util::borrowck_errors::{BorrowckErrors, Origin};
33
34 use std::rc::Rc;
35
36 // FIXME (#16118): These functions are intended to allow the borrow checker to
37 // be less precise in its handling of Box while still allowing moves out of a
38 // Box. They should be removed when Unique is removed from LoanPath.
39
40 fn owned_ptr_base_path<'a, 'tcx>(loan_path: &'a LoanPath<'tcx>) -> &'a LoanPath<'tcx> {
41     //! Returns the base of the leftmost dereference of an Unique in
42     //! `loan_path`. If there is no dereference of an Unique in `loan_path`,
43     //! then it just returns `loan_path` itself.
44
45     return match helper(loan_path) {
46         Some(new_loan_path) => new_loan_path,
47         None => loan_path.clone()
48     };
49
50     fn helper<'a, 'tcx>(loan_path: &'a LoanPath<'tcx>) -> Option<&'a LoanPath<'tcx>> {
51         match loan_path.kind {
52             LpVar(_) | LpUpvar(_) => None,
53             LpExtend(ref lp_base, _, LpDeref(mc::Unique)) => {
54                 match helper(&lp_base) {
55                     v @ Some(_) => v,
56                     None => Some(&lp_base)
57                 }
58             }
59             LpDowncast(ref lp_base, _) |
60             LpExtend(ref lp_base, ..) => helper(&lp_base)
61         }
62     }
63 }
64
65 fn owned_ptr_base_path_rc<'tcx>(loan_path: &Rc<LoanPath<'tcx>>) -> Rc<LoanPath<'tcx>> {
66     //! The equivalent of `owned_ptr_base_path` for an &Rc<LoanPath> rather than
67     //! a &LoanPath.
68
69     return match helper(loan_path) {
70         Some(new_loan_path) => new_loan_path,
71         None => loan_path.clone()
72     };
73
74     fn helper<'tcx>(loan_path: &Rc<LoanPath<'tcx>>) -> Option<Rc<LoanPath<'tcx>>> {
75         match loan_path.kind {
76             LpVar(_) | LpUpvar(_) => None,
77             LpExtend(ref lp_base, _, LpDeref(mc::Unique)) => {
78                 match helper(lp_base) {
79                     v @ Some(_) => v,
80                     None => Some(lp_base.clone())
81                 }
82             }
83             LpDowncast(ref lp_base, _) |
84             LpExtend(ref lp_base, ..) => helper(lp_base)
85         }
86     }
87 }
88
89 struct CheckLoanCtxt<'a, 'tcx: 'a> {
90     bccx: &'a BorrowckCtxt<'a, 'tcx>,
91     dfcx_loans: &'a LoanDataFlow<'a, 'tcx>,
92     move_data: &'a move_data::FlowedMoveData<'a, 'tcx>,
93     all_loans: &'a [Loan<'tcx>],
94     param_env: ty::ParamEnv<'tcx>,
95     movable_generator: bool,
96 }
97
98 impl<'a, 'tcx> euv::Delegate<'tcx> for CheckLoanCtxt<'a, 'tcx> {
99     fn consume(&mut self,
100                consume_id: ast::NodeId,
101                consume_span: Span,
102                cmt: &mc::cmt_<'tcx>,
103                mode: euv::ConsumeMode) {
104         debug!("consume(consume_id={}, cmt={:?}, mode={:?})",
105                consume_id, cmt, mode);
106
107         let hir_id = self.tcx().hir.node_to_hir_id(consume_id);
108         self.consume_common(hir_id.local_id, consume_span, cmt, mode);
109     }
110
111     fn matched_pat(&mut self,
112                    _matched_pat: &hir::Pat,
113                    _cmt: &mc::cmt_,
114                    _mode: euv::MatchMode) { }
115
116     fn consume_pat(&mut self,
117                    consume_pat: &hir::Pat,
118                    cmt: &mc::cmt_<'tcx>,
119                    mode: euv::ConsumeMode) {
120         debug!("consume_pat(consume_pat={:?}, cmt={:?}, mode={:?})",
121                consume_pat,
122                cmt,
123                mode);
124
125         self.consume_common(consume_pat.hir_id.local_id, consume_pat.span, cmt, mode);
126     }
127
128     fn borrow(&mut self,
129               borrow_id: ast::NodeId,
130               borrow_span: Span,
131               cmt: &mc::cmt_<'tcx>,
132               loan_region: ty::Region<'tcx>,
133               bk: ty::BorrowKind,
134               loan_cause: euv::LoanCause)
135     {
136         debug!("borrow(borrow_id={}, cmt={:?}, loan_region={:?}, \
137                bk={:?}, loan_cause={:?})",
138                borrow_id, cmt, loan_region,
139                bk, loan_cause);
140
141         let hir_id = self.tcx().hir.node_to_hir_id(borrow_id);
142         if let Some(lp) = opt_loan_path(cmt) {
143             let moved_value_use_kind = match loan_cause {
144                 euv::ClosureCapture(_) => MovedInCapture,
145                 _ => MovedInUse,
146             };
147             self.check_if_path_is_moved(hir_id.local_id, borrow_span, moved_value_use_kind, &lp);
148         }
149
150         self.check_for_conflicting_loans(hir_id.local_id);
151
152         self.check_for_loans_across_yields(cmt, loan_region, borrow_span);
153     }
154
155     fn mutate(&mut self,
156               assignment_id: ast::NodeId,
157               assignment_span: Span,
158               assignee_cmt: &mc::cmt_<'tcx>,
159               mode: euv::MutateMode)
160     {
161         debug!("mutate(assignment_id={}, assignee_cmt={:?})",
162                assignment_id, assignee_cmt);
163
164         if let Some(lp) = opt_loan_path(assignee_cmt) {
165             match mode {
166                 MutateMode::Init | MutateMode::JustWrite => {
167                     // In a case like `path = 1`, then path does not
168                     // have to be *FULLY* initialized, but we still
169                     // must be careful lest it contains derefs of
170                     // pointers.
171                     self.check_if_assigned_path_is_moved(assignee_cmt.hir_id.local_id,
172                                                          assignment_span,
173                                                          MovedInUse,
174                                                          &lp);
175                 }
176                 MutateMode::WriteAndRead => {
177                     // In a case like `path += 1`, then path must be
178                     // fully initialized, since we will read it before
179                     // we write it.
180                     self.check_if_path_is_moved(assignee_cmt.hir_id.local_id,
181                                                 assignment_span,
182                                                 MovedInUse,
183                                                 &lp);
184                 }
185             }
186         }
187         self.check_assignment(self.tcx().hir.node_to_hir_id(assignment_id).local_id,
188                               assignment_span, assignee_cmt);
189     }
190
191     fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) { }
192 }
193
194 pub fn check_loans<'a, 'b, 'c, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
195                                      dfcx_loans: &LoanDataFlow<'b, 'tcx>,
196                                      move_data: &move_data::FlowedMoveData<'c, 'tcx>,
197                                      all_loans: &[Loan<'tcx>],
198                                      body: &hir::Body) {
199     debug!("check_loans(body id={})", body.value.id);
200
201     let def_id = bccx.tcx.hir.body_owner_def_id(body.id());
202
203     let node_id = bccx.tcx.hir.as_local_node_id(def_id).unwrap();
204     let movable_generator = !match bccx.tcx.hir.get(node_id) {
205         hir::map::Node::NodeExpr(&hir::Expr {
206             node: hir::ExprClosure(.., Some(hir::GeneratorMovability::Static)),
207             ..
208         }) => true,
209         _ => false,
210     };
211
212     let param_env = bccx.tcx.param_env(def_id);
213     let mut clcx = CheckLoanCtxt {
214         bccx,
215         dfcx_loans,
216         move_data,
217         all_loans,
218         param_env,
219         movable_generator,
220     };
221     let rvalue_promotable_map = bccx.tcx.rvalue_promotable_map(def_id);
222     euv::ExprUseVisitor::new(&mut clcx,
223                              bccx.tcx,
224                              param_env,
225                              &bccx.region_scope_tree,
226                              bccx.tables,
227                              Some(rvalue_promotable_map))
228         .consume_body(body);
229 }
230
231 #[derive(PartialEq)]
232 enum UseError<'tcx> {
233     UseOk,
234     UseWhileBorrowed(/*loan*/Rc<LoanPath<'tcx>>, /*loan*/Span)
235 }
236
237 fn compatible_borrow_kinds(borrow_kind1: ty::BorrowKind,
238                            borrow_kind2: ty::BorrowKind)
239                            -> bool {
240     borrow_kind1 == ty::ImmBorrow && borrow_kind2 == ty::ImmBorrow
241 }
242
243 impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> {
244     pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.bccx.tcx }
245
246     pub fn each_issued_loan<F>(&self, node: hir::ItemLocalId, mut op: F) -> bool where
247         F: FnMut(&Loan<'tcx>) -> bool,
248     {
249         //! Iterates over each loan that has been issued
250         //! on entrance to `node`, regardless of whether it is
251         //! actually *in scope* at that point.  Sometimes loans
252         //! are issued for future scopes and thus they may have been
253         //! *issued* but not yet be in effect.
254
255         self.dfcx_loans.each_bit_on_entry(node, |loan_index| {
256             let loan = &self.all_loans[loan_index];
257             op(loan)
258         })
259     }
260
261     pub fn each_in_scope_loan<F>(&self, scope: region::Scope, mut op: F) -> bool where
262         F: FnMut(&Loan<'tcx>) -> bool,
263     {
264         //! Like `each_issued_loan()`, but only considers loans that are
265         //! currently in scope.
266
267         self.each_issued_loan(scope.item_local_id(), |loan| {
268             if self.bccx.region_scope_tree.is_subscope_of(scope, loan.kill_scope) {
269                 op(loan)
270             } else {
271                 true
272             }
273         })
274     }
275
276     fn each_in_scope_loan_affecting_path<F>(&self,
277                                             scope: region::Scope,
278                                             loan_path: &LoanPath<'tcx>,
279                                             mut op: F)
280                                             -> bool where
281         F: FnMut(&Loan<'tcx>) -> bool,
282     {
283         //! Iterates through all of the in-scope loans affecting `loan_path`,
284         //! calling `op`, and ceasing iteration if `false` is returned.
285
286         // First, we check for a loan restricting the path P being used. This
287         // accounts for borrows of P but also borrows of subpaths, like P.a.b.
288         // Consider the following example:
289         //
290         //     let x = &mut a.b.c; // Restricts a, a.b, and a.b.c
291         //     let y = a;          // Conflicts with restriction
292
293         let loan_path = owned_ptr_base_path(loan_path);
294         let cont = self.each_in_scope_loan(scope, |loan| {
295             let mut ret = true;
296             for restr_path in &loan.restricted_paths {
297                 if **restr_path == *loan_path {
298                     if !op(loan) {
299                         ret = false;
300                         break;
301                     }
302                 }
303             }
304             ret
305         });
306
307         if !cont {
308             return false;
309         }
310
311         // Next, we must check for *loans* (not restrictions) on the path P or
312         // any base path. This rejects examples like the following:
313         //
314         //     let x = &mut a.b;
315         //     let y = a.b.c;
316         //
317         // Limiting this search to *loans* and not *restrictions* means that
318         // examples like the following continue to work:
319         //
320         //     let x = &mut a.b;
321         //     let y = a.c;
322
323         let mut loan_path = loan_path;
324         loop {
325             match loan_path.kind {
326                 LpVar(_) | LpUpvar(_) => {
327                     break;
328                 }
329                 LpDowncast(ref lp_base, _) |
330                 LpExtend(ref lp_base, ..) => {
331                     loan_path = &lp_base;
332                 }
333             }
334
335             let cont = self.each_in_scope_loan(scope, |loan| {
336                 if *loan.loan_path == *loan_path {
337                     op(loan)
338                 } else {
339                     true
340                 }
341             });
342
343             if !cont {
344                 return false;
345             }
346         }
347
348         return true;
349     }
350
351     pub fn loans_generated_by(&self, node: hir::ItemLocalId) -> Vec<usize> {
352         //! Returns a vector of the loans that are generated as
353         //! we enter `node`.
354
355         let mut result = Vec::new();
356         self.dfcx_loans.each_gen_bit(node, |loan_index| {
357             result.push(loan_index);
358             true
359         });
360         return result;
361     }
362
363     pub fn check_for_loans_across_yields(&self,
364                                          cmt: &mc::cmt_<'tcx>,
365                                          loan_region: ty::Region<'tcx>,
366                                          borrow_span: Span) {
367         pub fn borrow_of_local_data<'tcx>(cmt: &mc::cmt_<'tcx>) -> bool {
368             match cmt.cat {
369                 // Borrows of static items is allowed
370                 Categorization::StaticItem => false,
371                 // Reborrow of already borrowed data is ignored
372                 // Any errors will be caught on the initial borrow
373                 Categorization::Deref(..) => false,
374
375                 // By-ref upvars has Derefs so they will get ignored.
376                 // Generators counts as FnOnce so this leaves only
377                 // by-move upvars, which is local data for generators
378                 Categorization::Upvar(..) => true,
379
380                 Categorization::Rvalue(region) => {
381                     // Rvalues promoted to 'static are no longer local
382                     if let RegionKind::ReStatic = *region {
383                         false
384                     } else {
385                         true
386                     }
387                 }
388
389                 // Borrow of local data must be checked
390                 Categorization::Local(..) => true,
391
392                 // For interior references and downcasts, find out if the base is local
393                 Categorization::Downcast(ref cmt_base, _) |
394                 Categorization::Interior(ref cmt_base, _) => borrow_of_local_data(&cmt_base),
395             }
396         }
397
398         if !self.movable_generator {
399             return;
400         }
401
402         if !borrow_of_local_data(cmt) {
403             return;
404         }
405
406         let scope = match *loan_region {
407             // A concrete region in which we will look for a yield expression
408             RegionKind::ReScope(scope) => scope,
409
410             // There cannot be yields inside an empty region
411             RegionKind::ReEmpty => return,
412
413             // Local data cannot have these lifetimes
414             RegionKind::ReEarlyBound(..) |
415             RegionKind::ReLateBound(..) |
416             RegionKind::ReFree(..) |
417             RegionKind::ReStatic => {
418                 self.bccx
419                     .tcx
420                     .sess.delay_span_bug(borrow_span,
421                                          &format!("unexpected region for local data {:?}",
422                                                   loan_region));
423                 return
424             }
425
426             // These cannot exist in borrowck
427             RegionKind::ReVar(..) |
428             RegionKind::ReCanonical(..) |
429             RegionKind::ReSkolemized(..) |
430             RegionKind::ReClosureBound(..) |
431             RegionKind::ReErased => span_bug!(borrow_span,
432                                               "unexpected region in borrowck {:?}",
433                                               loan_region),
434         };
435
436         let body_id = self.bccx.body.value.hir_id.local_id;
437
438         if self.bccx.region_scope_tree.containing_body(scope) != Some(body_id) {
439             // We are borrowing local data longer than its storage.
440             // This should result in other borrowck errors.
441             self.bccx.tcx.sess.delay_span_bug(borrow_span,
442                                               "borrowing local data longer than its storage");
443             return;
444         }
445
446         if let Some(yield_span) = self.bccx
447                                       .region_scope_tree
448                                       .yield_in_scope_for_expr(scope,
449                                                                cmt.hir_id,
450                                                                self.bccx.body) {
451             self.bccx.cannot_borrow_across_generator_yield(borrow_span,
452                                                            yield_span,
453                                                            Origin::Ast).emit();
454         }
455     }
456
457     pub fn check_for_conflicting_loans(&self, node: hir::ItemLocalId) {
458         //! Checks to see whether any of the loans that are issued
459         //! on entrance to `node` conflict with loans that have already been
460         //! issued when we enter `node` (for example, we do not
461         //! permit two `&mut` borrows of the same variable).
462         //!
463         //! (Note that some loans can be *issued* without necessarily
464         //! taking effect yet.)
465
466         debug!("check_for_conflicting_loans(node={:?})", node);
467
468         let new_loan_indices = self.loans_generated_by(node);
469         debug!("new_loan_indices = {:?}", new_loan_indices);
470
471         for &new_loan_index in &new_loan_indices {
472             self.each_issued_loan(node, |issued_loan| {
473                 let new_loan = &self.all_loans[new_loan_index];
474                 // Only report an error for the first issued loan that conflicts
475                 // to avoid O(n^2) errors.
476                 self.report_error_if_loans_conflict(issued_loan, new_loan)
477             });
478         }
479
480         for (i, &x) in new_loan_indices.iter().enumerate() {
481             let old_loan = &self.all_loans[x];
482             for &y in &new_loan_indices[(i+1) ..] {
483                 let new_loan = &self.all_loans[y];
484                 self.report_error_if_loans_conflict(old_loan, new_loan);
485             }
486         }
487     }
488
489     pub fn report_error_if_loans_conflict(&self,
490                                           old_loan: &Loan<'tcx>,
491                                           new_loan: &Loan<'tcx>)
492                                           -> bool {
493         //! Checks whether `old_loan` and `new_loan` can safely be issued
494         //! simultaneously.
495
496         debug!("report_error_if_loans_conflict(old_loan={:?}, new_loan={:?})",
497                old_loan,
498                new_loan);
499
500         // Should only be called for loans that are in scope at the same time.
501         assert!(self.bccx.region_scope_tree.scopes_intersect(old_loan.kill_scope,
502                                                        new_loan.kill_scope));
503
504         let err_old_new = self.report_error_if_loan_conflicts_with_restriction(
505             old_loan, new_loan, old_loan, new_loan).err();
506         let err_new_old = self.report_error_if_loan_conflicts_with_restriction(
507             new_loan, old_loan, old_loan, new_loan).err();
508
509         match (err_old_new, err_new_old) {
510             (Some(mut err), None) | (None, Some(mut err)) => err.emit(),
511             (Some(mut err_old), Some(mut err_new)) => {
512                 err_old.emit();
513                 err_new.cancel();
514             }
515             (None, None) => return true,
516         }
517
518         false
519     }
520
521     pub fn report_error_if_loan_conflicts_with_restriction(&self,
522                                                            loan1: &Loan<'tcx>,
523                                                            loan2: &Loan<'tcx>,
524                                                            old_loan: &Loan<'tcx>,
525                                                            new_loan: &Loan<'tcx>)
526                                                            -> Result<(), DiagnosticBuilder<'a>> {
527         //! Checks whether the restrictions introduced by `loan1` would
528         //! prohibit `loan2`. Returns false if an error is reported.
529
530         debug!("report_error_if_loan_conflicts_with_restriction(\
531                 loan1={:?}, loan2={:?})",
532                loan1,
533                loan2);
534
535         if compatible_borrow_kinds(loan1.kind, loan2.kind) {
536             return Ok(());
537         }
538
539         let loan2_base_path = owned_ptr_base_path_rc(&loan2.loan_path);
540         for restr_path in &loan1.restricted_paths {
541             if *restr_path != loan2_base_path { continue; }
542
543             // If new_loan is something like `x.a`, and old_loan is something like `x.b`, we would
544             // normally generate a rather confusing message (in this case, for multiple mutable
545             // borrows):
546             //
547             //     error: cannot borrow `x.b` as mutable more than once at a time
548             //     note: previous borrow of `x.a` occurs here; the mutable borrow prevents
549             //     subsequent moves, borrows, or modification of `x.a` until the borrow ends
550             //
551             // What we want to do instead is get the 'common ancestor' of the two borrow paths and
552             // use that for most of the message instead, giving is something like this:
553             //
554             //     error: cannot borrow `x` as mutable more than once at a time
555             //     note: previous borrow of `x` occurs here (through borrowing `x.a`); the mutable
556             //     borrow prevents subsequent moves, borrows, or modification of `x` until the
557             //     borrow ends
558
559             let common = new_loan.loan_path.common(&old_loan.loan_path);
560             let (nl, ol, new_loan_msg, old_loan_msg) = {
561                 if new_loan.loan_path.has_fork(&old_loan.loan_path) && common.is_some() {
562                     let nl = self.bccx.loan_path_to_string(&common.unwrap());
563                     let ol = nl.clone();
564                     let new_loan_msg = format!(" (via `{}`)",
565                                                self.bccx.loan_path_to_string(
566                                                    &new_loan.loan_path));
567                     let old_loan_msg = format!(" (via `{}`)",
568                                                self.bccx.loan_path_to_string(
569                                                    &old_loan.loan_path));
570                     (nl, ol, new_loan_msg, old_loan_msg)
571                 } else {
572                     (self.bccx.loan_path_to_string(&new_loan.loan_path),
573                      self.bccx.loan_path_to_string(&old_loan.loan_path),
574                      String::new(),
575                      String::new())
576                 }
577             };
578
579             let ol_pronoun = if new_loan.loan_path == old_loan.loan_path {
580                 "it".to_string()
581             } else {
582                 format!("`{}`", ol)
583             };
584
585             // We want to assemble all the relevant locations for the error.
586             //
587             // 1. Where did the new loan occur.
588             //    - if due to closure creation, where was the variable used in closure?
589             // 2. Where did old loan occur.
590             // 3. Where does old loan expire.
591
592             let previous_end_span =
593                 Some(self.tcx().sess.codemap().end_point(
594                         old_loan.kill_scope.span(self.tcx(), &self.bccx.region_scope_tree)));
595
596             let mut err = match (new_loan.kind, old_loan.kind) {
597                 (ty::MutBorrow, ty::MutBorrow) =>
598                     self.bccx.cannot_mutably_borrow_multiply(
599                         new_loan.span, &nl, &new_loan_msg, old_loan.span, &old_loan_msg,
600                         previous_end_span, Origin::Ast),
601                 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) =>
602                     self.bccx.cannot_uniquely_borrow_by_two_closures(
603                         new_loan.span, &nl, old_loan.span, previous_end_span, Origin::Ast),
604                 (ty::UniqueImmBorrow, _) =>
605                     self.bccx.cannot_uniquely_borrow_by_one_closure(
606                         new_loan.span, &nl, &new_loan_msg,
607                         old_loan.span, &ol_pronoun, &old_loan_msg, previous_end_span, Origin::Ast),
608                 (_, ty::UniqueImmBorrow) => {
609                     let new_loan_str = &new_loan.kind.to_user_str();
610                     self.bccx.cannot_reborrow_already_uniquely_borrowed(
611                         new_loan.span, &nl, &new_loan_msg, new_loan_str,
612                         old_loan.span, &old_loan_msg, previous_end_span, Origin::Ast)
613                 }
614                 (..) =>
615                     self.bccx.cannot_reborrow_already_borrowed(
616                         new_loan.span,
617                         &nl, &new_loan_msg, &new_loan.kind.to_user_str(),
618                         old_loan.span, &ol_pronoun, &old_loan.kind.to_user_str(), &old_loan_msg,
619                         previous_end_span, Origin::Ast)
620             };
621
622             match new_loan.cause {
623                 euv::ClosureCapture(span) => {
624                     err.span_label(
625                         span,
626                         format!("borrow occurs due to use of `{}` in closure", nl));
627                 }
628                 _ => { }
629             }
630
631             match old_loan.cause {
632                 euv::ClosureCapture(span) => {
633                     err.span_label(
634                         span,
635                         format!("previous borrow occurs due to use of `{}` in closure",
636                                  ol));
637                 }
638                 _ => { }
639             }
640
641             return Err(err);
642         }
643
644         Ok(())
645     }
646
647     fn consume_common(&self,
648                       id: hir::ItemLocalId,
649                       span: Span,
650                       cmt: &mc::cmt_<'tcx>,
651                       mode: euv::ConsumeMode) {
652         if let Some(lp) = opt_loan_path(cmt) {
653             let moved_value_use_kind = match mode {
654                 euv::Copy => {
655                     self.check_for_copy_of_frozen_path(id, span, &lp);
656                     MovedInUse
657                 }
658                 euv::Move(_) => {
659                     match self.move_data.kind_of_move_of_path(id, &lp) {
660                         None => {
661                             // Sometimes moves don't have a move kind;
662                             // this either means that the original move
663                             // was from something illegal to move,
664                             // or was moved from referent of an unsafe
665                             // pointer or something like that.
666                             MovedInUse
667                         }
668                         Some(move_kind) => {
669                             self.check_for_move_of_borrowed_path(id, span,
670                                                                  &lp, move_kind);
671                             if move_kind == move_data::Captured {
672                                 MovedInCapture
673                             } else {
674                                 MovedInUse
675                             }
676                         }
677                     }
678                 }
679             };
680
681             self.check_if_path_is_moved(id, span, moved_value_use_kind, &lp);
682         }
683     }
684
685     fn check_for_copy_of_frozen_path(&self,
686                                      id: hir::ItemLocalId,
687                                      span: Span,
688                                      copy_path: &LoanPath<'tcx>) {
689         match self.analyze_restrictions_on_use(id, copy_path, ty::ImmBorrow) {
690             UseOk => { }
691             UseWhileBorrowed(loan_path, loan_span) => {
692                 let desc = self.bccx.loan_path_to_string(copy_path);
693                 self.bccx.cannot_use_when_mutably_borrowed(
694                         span, &desc,
695                         loan_span, &self.bccx.loan_path_to_string(&loan_path),
696                         Origin::Ast)
697                     .emit();
698             }
699         }
700     }
701
702     fn check_for_move_of_borrowed_path(&self,
703                                        id: hir::ItemLocalId,
704                                        span: Span,
705                                        move_path: &LoanPath<'tcx>,
706                                        move_kind: move_data::MoveKind) {
707         // We want to detect if there are any loans at all, so we search for
708         // any loans incompatible with MutBorrrow, since all other kinds of
709         // loans are incompatible with that.
710         match self.analyze_restrictions_on_use(id, move_path, ty::MutBorrow) {
711             UseOk => { }
712             UseWhileBorrowed(loan_path, loan_span) => {
713                 let mut err = match move_kind {
714                     move_data::Captured => {
715                         let mut err = self.bccx.cannot_move_into_closure(
716                             span, &self.bccx.loan_path_to_string(move_path), Origin::Ast);
717                         err.span_label(
718                             loan_span,
719                             format!("borrow of `{}` occurs here",
720                                     &self.bccx.loan_path_to_string(&loan_path))
721                             );
722                         err.span_label(
723                             span,
724                             "move into closure occurs here"
725                             );
726                         err
727                     }
728                     move_data::Declared |
729                     move_data::MoveExpr |
730                     move_data::MovePat => {
731                         let desc = self.bccx.loan_path_to_string(move_path);
732                         let mut err = self.bccx.cannot_move_when_borrowed(span, &desc, Origin::Ast);
733                         err.span_label(
734                             loan_span,
735                             format!("borrow of `{}` occurs here",
736                                     &self.bccx.loan_path_to_string(&loan_path))
737                             );
738                         err.span_label(
739                             span,
740                             format!("move out of `{}` occurs here",
741                                 &self.bccx.loan_path_to_string(move_path))
742                             );
743                         err
744                     }
745                 };
746
747                 err.emit();
748             }
749         }
750     }
751
752     pub fn analyze_restrictions_on_use(&self,
753                                        expr_id: hir::ItemLocalId,
754                                        use_path: &LoanPath<'tcx>,
755                                        borrow_kind: ty::BorrowKind)
756                                        -> UseError<'tcx> {
757         debug!("analyze_restrictions_on_use(expr_id={:?}, use_path={:?})",
758                expr_id, use_path);
759
760         let mut ret = UseOk;
761
762         self.each_in_scope_loan_affecting_path(
763             region::Scope::Node(expr_id), use_path, |loan| {
764             if !compatible_borrow_kinds(loan.kind, borrow_kind) {
765                 ret = UseWhileBorrowed(loan.loan_path.clone(), loan.span);
766                 false
767             } else {
768                 true
769             }
770         });
771
772         return ret;
773     }
774
775     /// Reports an error if `expr` (which should be a path)
776     /// is using a moved/uninitialized value
777     fn check_if_path_is_moved(&self,
778                               id: hir::ItemLocalId,
779                               span: Span,
780                               use_kind: MovedValueUseKind,
781                               lp: &Rc<LoanPath<'tcx>>) {
782         debug!("check_if_path_is_moved(id={:?}, use_kind={:?}, lp={:?})",
783                id, use_kind, lp);
784
785         // FIXME: if you find yourself tempted to cut and paste
786         // the body below and then specializing the error reporting,
787         // consider refactoring this instead!
788
789         let base_lp = owned_ptr_base_path_rc(lp);
790         self.move_data.each_move_of(id, &base_lp, |the_move, moved_lp| {
791             self.bccx.report_use_of_moved_value(
792                 span,
793                 use_kind,
794                 &lp,
795                 the_move,
796                 moved_lp,
797                 self.param_env);
798             false
799         });
800     }
801
802     /// Reports an error if assigning to `lp` will use a
803     /// moved/uninitialized value. Mainly this is concerned with
804     /// detecting derefs of uninitialized pointers.
805     ///
806     /// For example:
807     ///
808     /// ```
809     /// let a: i32;
810     /// a = 10; // ok, even though a is uninitialized
811     /// ```
812     ///
813     /// ```
814     /// struct Point { x: u32, y: u32 }
815     /// let mut p: Point;
816     /// p.x = 22; // ok, even though `p` is uninitialized
817     /// ```
818     ///
819     /// ```compile_fail,E0381
820     /// # struct Point { x: u32, y: u32 }
821     /// let mut p: Box<Point>;
822     /// (*p).x = 22; // not ok, p is uninitialized, can't deref
823     /// ```
824     fn check_if_assigned_path_is_moved(&self,
825                                        id: hir::ItemLocalId,
826                                        span: Span,
827                                        use_kind: MovedValueUseKind,
828                                        lp: &Rc<LoanPath<'tcx>>)
829     {
830         match lp.kind {
831             LpVar(_) | LpUpvar(_) => {
832                 // assigning to `x` does not require that `x` is initialized
833             }
834             LpDowncast(ref lp_base, _) => {
835                 // assigning to `(P->Variant).f` is ok if assigning to `P` is ok
836                 self.check_if_assigned_path_is_moved(id, span,
837                                                      use_kind, lp_base);
838             }
839             LpExtend(ref lp_base, _, LpInterior(_, InteriorField(_))) => {
840                 match lp_base.to_type().sty {
841                     ty::TyAdt(def, _) if def.has_dtor(self.tcx()) => {
842                         // In the case where the owner implements drop, then
843                         // the path must be initialized to prevent a case of
844                         // partial reinitialization
845                         //
846                         // FIXME: could refactor via hypothetical
847                         // generalized check_if_path_is_moved
848                         let loan_path = owned_ptr_base_path_rc(lp_base);
849                         self.move_data.each_move_of(id, &loan_path, |_, _| {
850                             self.bccx
851                                 .report_partial_reinitialization_of_uninitialized_structure(
852                                     span,
853                                     &loan_path);
854                             false
855                         });
856                         return;
857                     },
858                     _ => {},
859                 }
860
861                 // assigning to `P.f` is ok if assigning to `P` is ok
862                 self.check_if_assigned_path_is_moved(id, span,
863                                                      use_kind, lp_base);
864             }
865             LpExtend(ref lp_base, _, LpInterior(_, InteriorElement)) |
866             LpExtend(ref lp_base, _, LpDeref(_)) => {
867                 // assigning to `P[i]` requires `P` is initialized
868                 // assigning to `(*P)` requires `P` is initialized
869                 self.check_if_path_is_moved(id, span, use_kind, lp_base);
870             }
871         }
872     }
873
874     fn check_assignment(&self,
875                         assignment_id: hir::ItemLocalId,
876                         assignment_span: Span,
877                         assignee_cmt: &mc::cmt_<'tcx>) {
878         debug!("check_assignment(assignee_cmt={:?})", assignee_cmt);
879
880         // Check that we don't invalidate any outstanding loans
881         if let Some(loan_path) = opt_loan_path(assignee_cmt) {
882             let scope = region::Scope::Node(assignment_id);
883             self.each_in_scope_loan_affecting_path(scope, &loan_path, |loan| {
884                 self.report_illegal_mutation(assignment_span, &loan_path, loan);
885                 false
886             });
887         }
888
889         // Check for reassignments to (immutable) local variables. This
890         // needs to be done here instead of in check_loans because we
891         // depend on move data.
892         if let Categorization::Local(local_id) = assignee_cmt.cat {
893             let lp = opt_loan_path(assignee_cmt).unwrap();
894             self.move_data.each_assignment_of(assignment_id, &lp, |assign| {
895                 if assignee_cmt.mutbl.is_mutable() {
896                     let hir_id = self.bccx.tcx.hir.node_to_hir_id(local_id);
897                     self.bccx.used_mut_nodes.borrow_mut().insert(hir_id);
898                 } else {
899                     self.bccx.report_reassigned_immutable_variable(
900                         assignment_span,
901                         &lp,
902                         assign);
903                 }
904                 false
905             });
906             return
907         }
908     }
909
910     pub fn report_illegal_mutation(&self,
911                                    span: Span,
912                                    loan_path: &LoanPath<'tcx>,
913                                    loan: &Loan) {
914         self.bccx.cannot_assign_to_borrowed(
915             span, loan.span, &self.bccx.loan_path_to_string(loan_path), Origin::Ast)
916             .emit();
917     }
918 }