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