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