]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/borrowck/check_loans.rs
auto merge of #13095 : alexcrichton/rust/serialize-tuple, r=huonw
[rust.git] / src / librustc / middle / 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
20
21 use mc = middle::mem_categorization;
22 use middle::borrowck::*;
23 use middle::moves;
24 use middle::ty;
25 use middle::typeck::MethodCall;
26 use syntax::ast;
27 use syntax::ast_util;
28 use syntax::codemap::Span;
29 use syntax::visit::Visitor;
30 use syntax::visit;
31 use util::ppaux::Repr;
32
33 struct CheckLoanCtxt<'a> {
34     bccx: &'a BorrowckCtxt<'a>,
35     dfcx_loans: &'a LoanDataFlow<'a>,
36     move_data: move_data::FlowedMoveData<'a>,
37     all_loans: &'a [Loan],
38 }
39
40 impl<'a> Visitor<()> for CheckLoanCtxt<'a> {
41
42     fn visit_expr(&mut self, ex: &ast::Expr, _: ()) {
43         check_loans_in_expr(self, ex);
44     }
45     fn visit_local(&mut self, l: &ast::Local, _: ()) {
46         check_loans_in_local(self, l);
47     }
48     fn visit_block(&mut self, b: &ast::Block, _: ()) {
49         check_loans_in_block(self, b);
50     }
51     fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
52         check_loans_in_pat(self, p);
53     }
54     fn visit_fn(&mut self, _fk: &visit::FnKind, _fd: &ast::FnDecl,
55                 _b: &ast::Block, _s: Span, _n: ast::NodeId, _: ()) {
56         // Don't process nested items or closures here,
57         // the outer loop will take care of it.
58         return;
59     }
60
61     // FIXME(#10894) should continue recursing
62     fn visit_ty(&mut self, _t: &ast::Ty, _: ()) {}
63 }
64
65 pub fn check_loans(bccx: &BorrowckCtxt,
66                    dfcx_loans: &LoanDataFlow,
67                    move_data: move_data::FlowedMoveData,
68                    all_loans: &[Loan],
69                    body: &ast::Block) {
70     debug!("check_loans(body id={:?})", body.id);
71
72     let mut clcx = CheckLoanCtxt {
73         bccx: bccx,
74         dfcx_loans: dfcx_loans,
75         move_data: move_data,
76         all_loans: all_loans,
77     };
78
79     clcx.visit_block(body, ());
80 }
81
82 #[deriving(Eq)]
83 enum MoveError {
84     MoveOk,
85     MoveWhileBorrowed(/*loan*/@LoanPath, /*loan*/Span)
86 }
87
88 impl<'a> CheckLoanCtxt<'a> {
89     pub fn tcx(&self) -> &'a ty::ctxt { self.bccx.tcx }
90
91     pub fn each_issued_loan(&self, scope_id: ast::NodeId, op: |&Loan| -> bool)
92                             -> bool {
93         //! Iterates over each loan that has been issued
94         //! on entrance to `scope_id`, regardless of whether it is
95         //! actually *in scope* at that point.  Sometimes loans
96         //! are issued for future scopes and thus they may have been
97         //! *issued* but not yet be in effect.
98
99         self.dfcx_loans.each_bit_on_entry_frozen(scope_id, |loan_index| {
100             let loan = &self.all_loans[loan_index];
101             op(loan)
102         })
103     }
104
105     pub fn each_in_scope_loan(&self,
106                               scope_id: ast::NodeId,
107                               op: |&Loan| -> bool)
108                               -> bool {
109         //! Like `each_issued_loan()`, but only considers loans that are
110         //! currently in scope.
111
112         let tcx = self.tcx();
113         self.each_issued_loan(scope_id, |loan| {
114             if tcx.region_maps.is_subscope_of(scope_id, loan.kill_scope) {
115                 op(loan)
116             } else {
117                 true
118             }
119         })
120     }
121
122     pub fn each_in_scope_restriction(&self,
123                                      scope_id: ast::NodeId,
124                                      loan_path: @LoanPath,
125                                      op: |&Loan, &Restriction| -> bool)
126                                      -> bool {
127         //! Iterates through all the in-scope restrictions for the
128         //! given `loan_path`
129
130         self.each_in_scope_loan(scope_id, |loan| {
131             debug!("each_in_scope_restriction found loan: {:?}",
132                    loan.repr(self.tcx()));
133
134             let mut ret = true;
135             for restr in loan.restrictions.iter() {
136                 if restr.loan_path == loan_path {
137                     if !op(loan, restr) {
138                         ret = false;
139                         break;
140                     }
141                 }
142             }
143             ret
144         })
145     }
146
147     pub fn loans_generated_by(&self, scope_id: ast::NodeId) -> Vec<uint> {
148         //! Returns a vector of the loans that are generated as
149         //! we encounter `scope_id`.
150
151         let mut result = Vec::new();
152         self.dfcx_loans.each_gen_bit_frozen(scope_id, |loan_index| {
153             result.push(loan_index);
154             true
155         });
156         return result;
157     }
158
159     pub fn check_for_conflicting_loans(&self, scope_id: ast::NodeId) {
160         //! Checks to see whether any of the loans that are issued
161         //! by `scope_id` conflict with loans that have already been
162         //! issued when we enter `scope_id` (for example, we do not
163         //! permit two `&mut` borrows of the same variable).
164
165         debug!("check_for_conflicting_loans(scope_id={:?})", scope_id);
166
167         let new_loan_indices = self.loans_generated_by(scope_id);
168         debug!("new_loan_indices = {:?}", new_loan_indices);
169
170         self.each_issued_loan(scope_id, |issued_loan| {
171             for &new_loan_index in new_loan_indices.iter() {
172                 let new_loan = &self.all_loans[new_loan_index];
173                 self.report_error_if_loans_conflict(issued_loan, new_loan);
174             }
175             true
176         });
177
178         for (i, &x) in new_loan_indices.iter().enumerate() {
179             let old_loan = &self.all_loans[x];
180             for &y in new_loan_indices.slice_from(i+1).iter() {
181                 let new_loan = &self.all_loans[y];
182                 self.report_error_if_loans_conflict(old_loan, new_loan);
183             }
184         }
185     }
186
187     pub fn report_error_if_loans_conflict(&self,
188                                           old_loan: &Loan,
189                                           new_loan: &Loan) {
190         //! Checks whether `old_loan` and `new_loan` can safely be issued
191         //! simultaneously.
192
193         debug!("report_error_if_loans_conflict(old_loan={}, new_loan={})",
194                old_loan.repr(self.tcx()),
195                new_loan.repr(self.tcx()));
196
197         // Should only be called for loans that are in scope at the same time.
198         assert!(self.tcx().region_maps.scopes_intersect(old_loan.kill_scope,
199                                                         new_loan.kill_scope));
200
201         self.report_error_if_loan_conflicts_with_restriction(
202             old_loan, new_loan, old_loan, new_loan) &&
203         self.report_error_if_loan_conflicts_with_restriction(
204             new_loan, old_loan, old_loan, new_loan);
205     }
206
207     pub fn report_error_if_loan_conflicts_with_restriction(&self,
208                                                            loan1: &Loan,
209                                                            loan2: &Loan,
210                                                            old_loan: &Loan,
211                                                            new_loan: &Loan)
212                                                            -> bool {
213         //! Checks whether the restrictions introduced by `loan1` would
214         //! prohibit `loan2`. Returns false if an error is reported.
215
216         debug!("report_error_if_loan_conflicts_with_restriction(\
217                 loan1={}, loan2={})",
218                loan1.repr(self.tcx()),
219                loan2.repr(self.tcx()));
220
221         // Restrictions that would cause the new loan to be illegal:
222         let illegal_if = match loan2.kind {
223             // Look for restrictions against mutation. These are
224             // generated by all other borrows.
225             ty::MutBorrow => RESTR_MUTATE,
226
227             // Look for restrictions against freezing (immutable borrows).
228             // These are generated by `&mut` borrows.
229             ty::ImmBorrow => RESTR_FREEZE,
230
231             // No matter how the data is borrowed (as `&`, as `&mut`,
232             // or as `&unique imm`) it will always generate a
233             // restriction against mutating the data. So look for those.
234             ty::UniqueImmBorrow => RESTR_MUTATE,
235         };
236         debug!("illegal_if={:?}", illegal_if);
237
238         for restr in loan1.restrictions.iter() {
239             if !restr.set.intersects(illegal_if) { continue; }
240             if restr.loan_path != loan2.loan_path { continue; }
241
242             let old_pronoun = if new_loan.loan_path == old_loan.loan_path {
243                 ~"it"
244             } else {
245                 format!("`{}`",
246                         self.bccx.loan_path_to_str(old_loan.loan_path))
247             };
248
249             match (new_loan.kind, old_loan.kind) {
250                 (ty::MutBorrow, ty::MutBorrow) => {
251                     self.bccx.span_err(
252                         new_loan.span,
253                         format!("cannot borrow `{}` as mutable \
254                                 more than once at a time",
255                                 self.bccx.loan_path_to_str(new_loan.loan_path)));
256                 }
257
258                 (ty::UniqueImmBorrow, _) => {
259                     self.bccx.span_err(
260                         new_loan.span,
261                         format!("closure requires unique access to `{}` \
262                                 but {} is already borrowed",
263                                 self.bccx.loan_path_to_str(new_loan.loan_path),
264                                 old_pronoun));
265                 }
266
267                 (_, ty::UniqueImmBorrow) => {
268                     self.bccx.span_err(
269                         new_loan.span,
270                         format!("cannot borrow `{}` as {} because \
271                                 previous closure requires unique access",
272                                 self.bccx.loan_path_to_str(new_loan.loan_path),
273                                 new_loan.kind.to_user_str()));
274                 }
275
276                 (_, _) => {
277                     self.bccx.span_err(
278                         new_loan.span,
279                         format!("cannot borrow `{}` as {} because \
280                                 {} is also borrowed as {}",
281                                 self.bccx.loan_path_to_str(new_loan.loan_path),
282                                 new_loan.kind.to_user_str(),
283                                 old_pronoun,
284                                 old_loan.kind.to_user_str()));
285                 }
286             }
287
288             match new_loan.cause {
289                 ClosureCapture(span) => {
290                     self.bccx.span_note(
291                         span,
292                         format!("borrow occurs due to use of `{}` in closure",
293                                 self.bccx.loan_path_to_str(new_loan.loan_path)));
294                 }
295                 _ => { }
296             }
297
298             let rule_summary = match old_loan.kind {
299                 ty::MutBorrow => {
300                     format!("the mutable borrow prevents subsequent \
301                             moves, borrows, or modification of `{0}` \
302                             until the borrow ends",
303                             self.bccx.loan_path_to_str(old_loan.loan_path))
304                 }
305
306                 ty::ImmBorrow => {
307                     format!("the immutable borrow prevents subsequent \
308                             moves or mutable borrows of `{0}` \
309                             until the borrow ends",
310                             self.bccx.loan_path_to_str(old_loan.loan_path))
311                 }
312
313                 ty::UniqueImmBorrow => {
314                     format!("the unique capture prevents subsequent \
315                             moves or borrows of `{0}` \
316                             until the borrow ends",
317                             self.bccx.loan_path_to_str(old_loan.loan_path))
318                 }
319             };
320
321             let borrow_summary = match old_loan.cause {
322                 ClosureCapture(_) => {
323                     format!("previous borrow of `{}` occurs here due to \
324                             use in closure",
325                             self.bccx.loan_path_to_str(old_loan.loan_path))
326                 }
327
328                 AddrOf | AutoRef | RefBinding => {
329                     format!("previous borrow of `{}` occurs here",
330                             self.bccx.loan_path_to_str(old_loan.loan_path))
331                 }
332             };
333
334             self.bccx.span_note(
335                 old_loan.span,
336                 format!("{}; {}", borrow_summary, rule_summary));
337
338             let old_loan_span = self.tcx().map.span(old_loan.kill_scope);
339             self.bccx.span_end_note(old_loan_span,
340                                     "previous borrow ends here");
341
342             return false;
343         }
344
345         true
346     }
347
348     pub fn is_local_variable(&self, cmt: mc::cmt) -> bool {
349         match cmt.cat {
350           mc::cat_local(_) => true,
351           _ => false
352         }
353     }
354
355     pub fn check_if_path_is_moved(&self,
356                                   id: ast::NodeId,
357                                   span: Span,
358                                   use_kind: MovedValueUseKind,
359                                   lp: @LoanPath) {
360         /*!
361          * Reports an error if `expr` (which should be a path)
362          * is using a moved/uninitialized value
363          */
364
365         debug!("check_if_path_is_moved(id={:?}, use_kind={:?}, lp={})",
366                id, use_kind, lp.repr(self.bccx.tcx));
367         self.move_data.each_move_of(id, lp, |move, moved_lp| {
368             self.bccx.report_use_of_moved_value(
369                 span,
370                 use_kind,
371                 lp,
372                 move,
373                 moved_lp);
374             false
375         });
376     }
377
378     pub fn check_assignment(&self, expr: &ast::Expr) {
379         // We don't use cat_expr() here because we don't want to treat
380         // auto-ref'd parameters in overloaded operators as rvalues.
381         let cmt = match self.bccx.tcx.adjustments.borrow().find_copy(&expr.id) {
382             None => self.bccx.cat_expr_unadjusted(expr),
383             Some(adj) => self.bccx.cat_expr_autoderefd(expr, adj)
384         };
385
386         debug!("check_assignment(cmt={})", cmt.repr(self.tcx()));
387
388         // Mutable values can be assigned, as long as they obey loans
389         // and aliasing restrictions:
390         if cmt.mutbl.is_mutable() {
391             if check_for_aliasable_mutable_writes(self, expr, cmt) {
392                 if check_for_assignment_to_restricted_or_frozen_location(
393                     self, expr, cmt)
394                 {
395                     // Safe, but record for lint pass later:
396                     mark_variable_as_used_mut(self, cmt);
397                 }
398             }
399             return;
400         }
401
402         // For immutable local variables, assignments are legal
403         // if they cannot already have been assigned
404         if self.is_local_variable(cmt) {
405             assert!(cmt.mutbl.is_immutable()); // no "const" locals
406             let lp = opt_loan_path(cmt).unwrap();
407             self.move_data.each_assignment_of(expr.id, lp, |assign| {
408                 self.bccx.report_reassigned_immutable_variable(
409                     expr.span,
410                     lp,
411                     assign);
412                 false
413             });
414             return;
415         }
416
417         // Otherwise, just a plain error.
418         match opt_loan_path(cmt) {
419             Some(lp) => {
420                 self.bccx.span_err(
421                     expr.span,
422                     format!("cannot assign to {} {} `{}`",
423                             cmt.mutbl.to_user_str(),
424                             self.bccx.cmt_to_str(cmt),
425                             self.bccx.loan_path_to_str(lp)));
426             }
427             None => {
428                 self.bccx.span_err(
429                     expr.span,
430                     format!("cannot assign to {} {}",
431                             cmt.mutbl.to_user_str(),
432                             self.bccx.cmt_to_str(cmt)));
433             }
434         }
435         return;
436
437         fn mark_variable_as_used_mut(this: &CheckLoanCtxt,
438                                      cmt: mc::cmt) {
439             //! If the mutability of the `cmt` being written is inherited
440             //! from a local variable, liveness will
441             //! not have been able to detect that this variable's mutability
442             //! is important, so we must add the variable to the
443             //! `used_mut_nodes` table here.
444
445             let mut cmt = cmt;
446             loop {
447                 debug!("mark_writes_through_upvars_as_used_mut(cmt={})",
448                        cmt.repr(this.tcx()));
449                 match cmt.cat {
450                     mc::cat_local(id) | mc::cat_arg(id) => {
451                         this.tcx().used_mut_nodes.borrow_mut().insert(id);
452                         return;
453                     }
454
455                     mc::cat_upvar(..) => {
456                         return;
457                     }
458
459                     mc::cat_deref(_, _, mc::GcPtr) => {
460                         assert_eq!(cmt.mutbl, mc::McImmutable);
461                         return;
462                     }
463
464                     mc::cat_rvalue(..) |
465                     mc::cat_static_item |
466                     mc::cat_copied_upvar(..) |
467                     mc::cat_deref(_, _, mc::UnsafePtr(..)) |
468                     mc::cat_deref(_, _, mc::BorrowedPtr(..)) => {
469                         assert_eq!(cmt.mutbl, mc::McDeclared);
470                         return;
471                     }
472
473                     mc::cat_discr(b, _) |
474                     mc::cat_deref(b, _, mc::OwnedPtr) => {
475                         assert_eq!(cmt.mutbl, mc::McInherited);
476                         cmt = b;
477                     }
478
479                     mc::cat_downcast(b) |
480                     mc::cat_interior(b, _) => {
481                         assert_eq!(cmt.mutbl, mc::McInherited);
482                         cmt = b;
483                     }
484                 }
485             }
486         }
487
488         fn check_for_aliasable_mutable_writes(this: &CheckLoanCtxt,
489                                               expr: &ast::Expr,
490                                               cmt: mc::cmt) -> bool {
491             //! Safety checks related to writes to aliasable, mutable locations
492
493             let guarantor = cmt.guarantor();
494             debug!("check_for_aliasable_mutable_writes(cmt={}, guarantor={})",
495                    cmt.repr(this.tcx()), guarantor.repr(this.tcx()));
496             match guarantor.cat {
497                 mc::cat_deref(b, _, mc::BorrowedPtr(ty::MutBorrow, _)) => {
498                     // Statically prohibit writes to `&mut` when aliasable
499
500                     check_for_aliasability_violation(this, expr, b);
501                 }
502
503                 _ => {}
504             }
505
506             return true; // no errors reported
507         }
508
509         fn check_for_aliasability_violation(this: &CheckLoanCtxt,
510                                             expr: &ast::Expr,
511                                             cmt: mc::cmt)
512                                             -> bool {
513             match cmt.freely_aliasable(this.tcx()) {
514                 None => {
515                     return true;
516                 }
517                 Some(mc::AliasableStaticMut(..)) => {
518                     return true;
519                 }
520                 Some(cause) => {
521                     this.bccx.report_aliasability_violation(
522                         expr.span,
523                         MutabilityViolation,
524                         cause);
525                     return false;
526                 }
527             }
528         }
529
530         fn check_for_assignment_to_restricted_or_frozen_location(
531             this: &CheckLoanCtxt,
532             expr: &ast::Expr,
533             cmt: mc::cmt) -> bool
534         {
535             //! Check for assignments that violate the terms of an
536             //! outstanding loan.
537
538             let loan_path = match opt_loan_path(cmt) {
539                 Some(lp) => lp,
540                 None => { return true; /* no loan path, can't be any loans */ }
541             };
542
543             // Start by searching for an assignment to a *restricted*
544             // location. Here is one example of the kind of error caught
545             // by this check:
546             //
547             //    let mut v = ~[1, 2, 3];
548             //    let p = &v;
549             //    v = ~[4];
550             //
551             // In this case, creating `p` triggers a RESTR_MUTATE
552             // restriction on the path `v`.
553             //
554             // Here is a second, more subtle example:
555             //
556             //    let mut v = ~[1, 2, 3];
557             //    let p = &const v[0];
558             //    v[0] = 4;                   // OK
559             //    v[1] = 5;                   // OK
560             //    v = ~[4, 5, 3];             // Error
561             //
562             // In this case, `p` is pointing to `v[0]`, and it is a
563             // `const` pointer in any case. So the first two
564             // assignments are legal (and would be permitted by this
565             // check). However, the final assignment (which is
566             // logically equivalent) is forbidden, because it would
567             // cause the existing `v` array to be freed, thus
568             // invalidating `p`. In the code, this error results
569             // because `gather_loans::restrictions` adds a
570             // `RESTR_MUTATE` restriction whenever the contents of an
571             // owned pointer are borrowed, and hence while `v[*]` is not
572             // restricted from being written, `v` is.
573             let cont = this.each_in_scope_restriction(expr.id,
574                                                       loan_path,
575                                                       |loan, restr| {
576                 if restr.set.intersects(RESTR_MUTATE) {
577                     this.report_illegal_mutation(expr, loan_path, loan);
578                     false
579                 } else {
580                     true
581                 }
582             });
583
584             if !cont { return false }
585
586             // The previous code handled assignments to paths that
587             // have been restricted. This covers paths that have been
588             // directly lent out and their base paths, but does not
589             // cover random extensions of those paths. For example,
590             // the following program is not declared illegal by the
591             // previous check:
592             //
593             //    let mut v = ~[1, 2, 3];
594             //    let p = &v;
595             //    v[0] = 4; // declared error by loop below, not code above
596             //
597             // The reason that this passes the previous check whereas
598             // an assignment like `v = ~[4]` fails is because the assignment
599             // here is to `v[*]`, and the existing restrictions were issued
600             // for `v`, not `v[*]`.
601             //
602             // So in this loop, we walk back up the loan path so long
603             // as the mutability of the path is dependent on a super
604             // path, and check that the super path was not lent out as
605             // mutable or immutable (a const loan is ok).
606             //
607             // Mutability of a path can be dependent on the super path
608             // in two ways. First, it might be inherited mutability.
609             // Second, the pointee of an `&mut` pointer can only be
610             // mutated if it is found in an unaliased location, so we
611             // have to check that the owner location is not borrowed.
612             //
613             // Note that we are *not* checking for any and all
614             // restrictions.  We are only interested in the pointers
615             // that the user created, whereas we add restrictions for
616             // all kinds of paths that are not directly aliased. If we checked
617             // for all restrictions, and not just loans, then the following
618             // valid program would be considered illegal:
619             //
620             //    let mut v = ~[1, 2, 3];
621             //    let p = &const v[0];
622             //    v[1] = 5; // ok
623             //
624             // Here the restriction that `v` not be mutated would be misapplied
625             // to block the subpath `v[1]`.
626             let full_loan_path = loan_path;
627             let mut loan_path = loan_path;
628             loop {
629                 match *loan_path {
630                     // Peel back one layer if, for `loan_path` to be
631                     // mutable, `lp_base` must be mutable. This occurs
632                     // with inherited mutability and with `&mut`
633                     // pointers.
634                     LpExtend(lp_base, mc::McInherited, _) |
635                     LpExtend(lp_base, _, LpDeref(mc::BorrowedPtr(ty::MutBorrow, _))) => {
636                         loan_path = lp_base;
637                     }
638
639                     // Otherwise stop iterating
640                     LpExtend(_, mc::McDeclared, _) |
641                     LpExtend(_, mc::McImmutable, _) |
642                     LpVar(_) => {
643                         return true;
644                     }
645                 }
646
647                 // Check for a non-const loan of `loan_path`
648                 let cont = this.each_in_scope_loan(expr.id, |loan| {
649                     if loan.loan_path == loan_path {
650                         this.report_illegal_mutation(expr, full_loan_path, loan);
651                         false
652                     } else {
653                         true
654                     }
655                 });
656
657                 if !cont { return false }
658             }
659         }
660     }
661
662     pub fn report_illegal_mutation(&self,
663                                    expr: &ast::Expr,
664                                    loan_path: &LoanPath,
665                                    loan: &Loan) {
666         self.bccx.span_err(
667             expr.span,
668             format!("cannot assign to `{}` because it is borrowed",
669                  self.bccx.loan_path_to_str(loan_path)));
670         self.bccx.span_note(
671             loan.span,
672             format!("borrow of `{}` occurs here",
673                  self.bccx.loan_path_to_str(loan_path)));
674     }
675
676     fn check_move_out_from_expr(&self, expr: &ast::Expr) {
677         match expr.node {
678             ast::ExprFnBlock(..) | ast::ExprProc(..) => {
679                 // Moves due to captures are checked in
680                 // check_captured_variables() because it allows
681                 // us to give a more precise error message with
682                 // a more precise span.
683             }
684             _ => {
685                 self.check_move_out_from_id(expr.id, expr.span)
686             }
687         }
688     }
689
690     fn check_move_out_from_id(&self, id: ast::NodeId, span: Span) {
691         self.move_data.each_path_moved_by(id, |_, move_path| {
692             match self.analyze_move_out_from(id, move_path) {
693                 MoveOk => {}
694                 MoveWhileBorrowed(loan_path, loan_span) => {
695                     self.bccx.span_err(
696                         span,
697                         format!("cannot move out of `{}` \
698                                 because it is borrowed",
699                              self.bccx.loan_path_to_str(move_path)));
700                     self.bccx.span_note(
701                         loan_span,
702                         format!("borrow of `{}` occurs here",
703                                 self.bccx.loan_path_to_str(loan_path)));
704                 }
705             }
706             true
707         });
708     }
709
710     fn check_captured_variables(&self,
711                                 closure_id: ast::NodeId,
712                                 span: Span) {
713         for cap_var in self.bccx.capture_map.get(&closure_id).iter() {
714             let var_id = ast_util::def_id_of_def(cap_var.def).node;
715             let var_path = @LpVar(var_id);
716             self.check_if_path_is_moved(closure_id, span,
717                                         MovedInCapture, var_path);
718             match cap_var.mode {
719                 moves::CapRef | moves::CapCopy => {}
720                 moves::CapMove => {
721                     check_by_move_capture(self, closure_id, cap_var, var_path);
722                 }
723             }
724         }
725         return;
726
727         fn check_by_move_capture(this: &CheckLoanCtxt,
728                                  closure_id: ast::NodeId,
729                                  cap_var: &moves::CaptureVar,
730                                  move_path: @LoanPath) {
731             let move_err = this.analyze_move_out_from(closure_id, move_path);
732             match move_err {
733                 MoveOk => {}
734                 MoveWhileBorrowed(loan_path, loan_span) => {
735                     this.bccx.span_err(
736                         cap_var.span,
737                         format!("cannot move `{}` into closure \
738                                 because it is borrowed",
739                                 this.bccx.loan_path_to_str(move_path)));
740                     this.bccx.span_note(
741                         loan_span,
742                         format!("borrow of `{}` occurs here",
743                                 this.bccx.loan_path_to_str(loan_path)));
744                 }
745             }
746         }
747     }
748
749     pub fn analyze_move_out_from(&self,
750                                  expr_id: ast::NodeId,
751                                  mut move_path: @LoanPath)
752                                  -> MoveError {
753         debug!("analyze_move_out_from(expr_id={:?}, move_path={})",
754                self.tcx().map.node_to_str(expr_id),
755                move_path.repr(self.tcx()));
756
757         // We must check every element of a move path. See
758         // `borrowck-move-subcomponent.rs` for a test case.
759         loop {
760             // check for a conflicting loan:
761             let mut ret = MoveOk;
762             self.each_in_scope_restriction(expr_id, move_path, |loan, _| {
763                 // Any restriction prevents moves.
764                 ret = MoveWhileBorrowed(loan.loan_path, loan.span);
765                 false
766             });
767
768             if ret != MoveOk {
769                 return ret
770             }
771
772             match *move_path {
773                 LpVar(_) => return MoveOk,
774                 LpExtend(subpath, _, _) => move_path = subpath,
775             }
776         }
777     }
778
779     pub fn check_call(&self,
780                       _expr: &ast::Expr,
781                       _callee: Option<@ast::Expr>,
782                       _callee_span: Span,
783                       _args: &[@ast::Expr]) {
784         // NB: This call to check for conflicting loans is not truly
785         // necessary, because the callee_id never issues new loans.
786         // However, I added it for consistency and lest the system
787         // should change in the future.
788         //
789         // FIXME(#6268) nested method calls
790         // self.check_for_conflicting_loans(callee_id);
791     }
792 }
793
794 fn check_loans_in_local<'a>(this: &mut CheckLoanCtxt<'a>,
795                             local: &ast::Local) {
796     visit::walk_local(this, local, ());
797 }
798
799 fn check_loans_in_expr<'a>(this: &mut CheckLoanCtxt<'a>,
800                            expr: &ast::Expr) {
801     visit::walk_expr(this, expr, ());
802
803     debug!("check_loans_in_expr(expr={})",
804            expr.repr(this.tcx()));
805
806     this.check_for_conflicting_loans(expr.id);
807     this.check_move_out_from_expr(expr);
808
809     let method_map = this.bccx.method_map.borrow();
810     match expr.node {
811       ast::ExprPath(..) => {
812           if !this.move_data.is_assignee(expr.id) {
813               let cmt = this.bccx.cat_expr_unadjusted(expr);
814               debug!("path cmt={}", cmt.repr(this.tcx()));
815               let r = opt_loan_path(cmt);
816               for &lp in r.iter() {
817                   this.check_if_path_is_moved(expr.id, expr.span, MovedInUse, lp);
818               }
819           }
820       }
821       ast::ExprFnBlock(..) | ast::ExprProc(..) => {
822           this.check_captured_variables(expr.id, expr.span)
823       }
824       ast::ExprAssign(dest, _) |
825       ast::ExprAssignOp(_, dest, _) => {
826         this.check_assignment(dest);
827       }
828       ast::ExprCall(f, ref args) => {
829         this.check_call(expr, Some(f), f.span, args.as_slice());
830       }
831       ast::ExprMethodCall(_, _, ref args) => {
832         this.check_call(expr, None, expr.span, args.as_slice());
833       }
834       ast::ExprIndex(_, rval) | ast::ExprBinary(_, _, rval)
835       if method_map.contains_key(&MethodCall::expr(expr.id)) => {
836         this.check_call(expr, None, expr.span, [rval]);
837       }
838       ast::ExprUnary(_, _) | ast::ExprIndex(_, _)
839       if method_map.contains_key(&MethodCall::expr(expr.id)) => {
840         this.check_call(expr, None, expr.span, []);
841       }
842       ast::ExprInlineAsm(ref ia) => {
843           for &(_, out) in ia.outputs.iter() {
844               this.check_assignment(out);
845           }
846       }
847       _ => {}
848     }
849 }
850
851 fn check_loans_in_pat<'a>(this: &mut CheckLoanCtxt<'a>,
852                           pat: &ast::Pat)
853 {
854     this.check_for_conflicting_loans(pat.id);
855     this.check_move_out_from_id(pat.id, pat.span);
856     visit::walk_pat(this, pat, ());
857 }
858
859 fn check_loans_in_block<'a>(this: &mut CheckLoanCtxt<'a>,
860                             blk: &ast::Block)
861 {
862     visit::walk_block(this, blk, ());
863     this.check_for_conflicting_loans(blk.id);
864 }