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.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // ----------------------------------------------------------------------
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::*;
22 use borrowck::InteriorKind::{InteriorElement, InteriorField};
23 use rustc::middle::expr_use_visitor as euv;
24 use rustc::middle::expr_use_visitor::MutateMode;
25 use rustc::middle::mem_categorization as mc;
26 use rustc::middle::mem_categorization::Categorization;
27 use rustc::middle::region;
28 use rustc::ty::{self, TyCtxt, RegionKind};
32 use rustc_mir::util::borrowck_errors::{BorrowckErrors, Origin};
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.
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.
45 return match helper(loan_path) {
46 Some(new_loan_path) => new_loan_path,
47 None => loan_path.clone()
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) {
56 None => Some(&lp_base)
59 LpDowncast(ref lp_base, _) |
60 LpExtend(ref lp_base, ..) => helper(&lp_base)
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
69 return match helper(loan_path) {
70 Some(new_loan_path) => new_loan_path,
71 None => loan_path.clone()
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) {
80 None => Some(lp_base.clone())
83 LpDowncast(ref lp_base, _) |
84 LpExtend(ref lp_base, ..) => helper(lp_base)
89 struct CheckLoanCtxt<'a, 'tcx: 'a> {
90 bccx: &'a BorrowckCtxt<'a, 'tcx>,
91 dfcx_loans: &'a LoanDataFlow<'a, 'tcx>,
92 move_data: &'a move_data::FlowedMoveData<'a, 'tcx>,
93 all_loans: &'a [Loan<'tcx>],
94 param_env: ty::ParamEnv<'tcx>,
95 movable_generator: bool,
98 impl<'a, 'tcx> euv::Delegate<'tcx> for CheckLoanCtxt<'a, 'tcx> {
100 consume_id: ast::NodeId,
102 cmt: &mc::cmt_<'tcx>,
103 mode: euv::ConsumeMode) {
104 debug!("consume(consume_id={}, cmt={:?}, mode={:?})",
105 consume_id, cmt, mode);
107 let hir_id = self.tcx().hir.node_to_hir_id(consume_id);
108 self.consume_common(hir_id.local_id, consume_span, cmt, mode);
111 fn matched_pat(&mut self,
112 _matched_pat: &hir::Pat,
114 _mode: euv::MatchMode) { }
116 fn consume_pat(&mut self,
117 consume_pat: &hir::Pat,
118 cmt: &mc::cmt_<'tcx>,
119 mode: euv::ConsumeMode) {
120 debug!("consume_pat(consume_pat={:?}, cmt={:?}, mode={:?})",
125 self.consume_common(consume_pat.hir_id.local_id, consume_pat.span, cmt, mode);
129 borrow_id: ast::NodeId,
131 cmt: &mc::cmt_<'tcx>,
132 loan_region: ty::Region<'tcx>,
134 loan_cause: euv::LoanCause)
136 debug!("borrow(borrow_id={}, cmt={:?}, loan_region={:?}, \
137 bk={:?}, loan_cause={:?})",
138 borrow_id, cmt, loan_region,
141 let hir_id = self.tcx().hir.node_to_hir_id(borrow_id);
142 if let Some(lp) = opt_loan_path(cmt) {
143 let moved_value_use_kind = match loan_cause {
144 euv::ClosureCapture(_) => MovedInCapture,
147 self.check_if_path_is_moved(hir_id.local_id, borrow_span, moved_value_use_kind, &lp);
150 self.check_for_conflicting_loans(hir_id.local_id);
152 self.check_for_loans_across_yields(cmt, loan_region, borrow_span);
156 assignment_id: ast::NodeId,
157 assignment_span: Span,
158 assignee_cmt: &mc::cmt_<'tcx>,
159 mode: euv::MutateMode)
161 debug!("mutate(assignment_id={}, assignee_cmt={:?})",
162 assignment_id, assignee_cmt);
164 if let Some(lp) = opt_loan_path(assignee_cmt) {
166 MutateMode::Init | MutateMode::JustWrite => {
167 // In a case like `path = 1`, then path does not
168 // have to be *FULLY* initialized, but we still
169 // must be careful lest it contains derefs of
171 self.check_if_assigned_path_is_moved(assignee_cmt.hir_id.local_id,
176 MutateMode::WriteAndRead => {
177 // In a case like `path += 1`, then path must be
178 // fully initialized, since we will read it before
180 self.check_if_path_is_moved(assignee_cmt.hir_id.local_id,
187 self.check_assignment(self.tcx().hir.node_to_hir_id(assignment_id).local_id,
188 assignment_span, assignee_cmt);
191 fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) { }
194 pub fn check_loans<'a, 'b, 'c, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
195 dfcx_loans: &LoanDataFlow<'b, 'tcx>,
196 move_data: &move_data::FlowedMoveData<'c, 'tcx>,
197 all_loans: &[Loan<'tcx>],
199 debug!("check_loans(body id={})", body.value.id);
201 let def_id = bccx.tcx.hir.body_owner_def_id(body.id());
203 let node_id = bccx.tcx.hir.as_local_node_id(def_id).unwrap();
204 let movable_generator = !match bccx.tcx.hir.get(node_id) {
205 hir::map::Node::NodeExpr(&hir::Expr {
206 node: hir::ExprClosure(.., Some(hir::GeneratorMovability::Static)),
212 let param_env = bccx.tcx.param_env(def_id);
213 let mut clcx = CheckLoanCtxt {
221 let rvalue_promotable_map = bccx.tcx.rvalue_promotable_map(def_id);
222 euv::ExprUseVisitor::new(&mut clcx,
225 &bccx.region_scope_tree,
227 Some(rvalue_promotable_map))
232 enum UseError<'tcx> {
234 UseWhileBorrowed(/*loan*/Rc<LoanPath<'tcx>>, /*loan*/Span)
237 fn compatible_borrow_kinds(borrow_kind1: ty::BorrowKind,
238 borrow_kind2: ty::BorrowKind)
240 borrow_kind1 == ty::ImmBorrow && borrow_kind2 == ty::ImmBorrow
243 impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> {
244 pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.bccx.tcx }
246 pub fn each_issued_loan<F>(&self, node: hir::ItemLocalId, mut op: F) -> bool where
247 F: FnMut(&Loan<'tcx>) -> bool,
249 //! Iterates over each loan that has been issued
250 //! on entrance to `node`, regardless of whether it is
251 //! actually *in scope* at that point. Sometimes loans
252 //! are issued for future scopes and thus they may have been
253 //! *issued* but not yet be in effect.
255 self.dfcx_loans.each_bit_on_entry(node, |loan_index| {
256 let loan = &self.all_loans[loan_index];
261 pub fn each_in_scope_loan<F>(&self, scope: region::Scope, mut op: F) -> bool where
262 F: FnMut(&Loan<'tcx>) -> bool,
264 //! Like `each_issued_loan()`, but only considers loans that are
265 //! currently in scope.
267 self.each_issued_loan(scope.item_local_id(), |loan| {
268 if self.bccx.region_scope_tree.is_subscope_of(scope, loan.kill_scope) {
276 fn each_in_scope_loan_affecting_path<F>(&self,
277 scope: region::Scope,
278 loan_path: &LoanPath<'tcx>,
281 F: FnMut(&Loan<'tcx>) -> bool,
283 //! Iterates through all of the in-scope loans affecting `loan_path`,
284 //! calling `op`, and ceasing iteration if `false` is returned.
286 // First, we check for a loan restricting the path P being used. This
287 // accounts for borrows of P but also borrows of subpaths, like P.a.b.
288 // Consider the following example:
290 // let x = &mut a.b.c; // Restricts a, a.b, and a.b.c
291 // let y = a; // Conflicts with restriction
293 let loan_path = owned_ptr_base_path(loan_path);
294 let cont = self.each_in_scope_loan(scope, |loan| {
296 for restr_path in &loan.restricted_paths {
297 if **restr_path == *loan_path {
311 // Next, we must check for *loans* (not restrictions) on the path P or
312 // any base path. This rejects examples like the following:
317 // Limiting this search to *loans* and not *restrictions* means that
318 // examples like the following continue to work:
323 let mut loan_path = loan_path;
325 match loan_path.kind {
326 LpVar(_) | LpUpvar(_) => {
329 LpDowncast(ref lp_base, _) |
330 LpExtend(ref lp_base, ..) => {
331 loan_path = &lp_base;
335 let cont = self.each_in_scope_loan(scope, |loan| {
336 if *loan.loan_path == *loan_path {
351 pub fn loans_generated_by(&self, node: hir::ItemLocalId) -> Vec<usize> {
352 //! Returns a vector of the loans that are generated as
355 let mut result = Vec::new();
356 self.dfcx_loans.each_gen_bit(node, |loan_index| {
357 result.push(loan_index);
363 pub fn check_for_loans_across_yields(&self,
364 cmt: &mc::cmt_<'tcx>,
365 loan_region: ty::Region<'tcx>,
367 pub fn borrow_of_local_data<'tcx>(cmt: &mc::cmt_<'tcx>) -> bool {
369 // Borrows of static items is allowed
370 Categorization::StaticItem => false,
371 // Reborrow of already borrowed data is ignored
372 // Any errors will be caught on the initial borrow
373 Categorization::Deref(..) => false,
375 // By-ref upvars has Derefs so they will get ignored.
376 // Generators counts as FnOnce so this leaves only
377 // by-move upvars, which is local data for generators
378 Categorization::Upvar(..) => true,
380 Categorization::Rvalue(region) => {
381 // Rvalues promoted to 'static are no longer local
382 if let RegionKind::ReStatic = *region {
389 // Borrow of local data must be checked
390 Categorization::Local(..) => true,
392 // For interior references and downcasts, find out if the base is local
393 Categorization::Downcast(ref cmt_base, _) |
394 Categorization::Interior(ref cmt_base, _) => borrow_of_local_data(&cmt_base),
398 if !self.movable_generator {
402 if !borrow_of_local_data(cmt) {
406 let scope = match *loan_region {
407 // A concrete region in which we will look for a yield expression
408 RegionKind::ReScope(scope) => scope,
410 // There cannot be yields inside an empty region
411 RegionKind::ReEmpty => return,
413 // Local data cannot have these lifetimes
414 RegionKind::ReEarlyBound(..) |
415 RegionKind::ReLateBound(..) |
416 RegionKind::ReFree(..) |
417 RegionKind::ReStatic => {
420 .sess.delay_span_bug(borrow_span,
421 &format!("unexpected region for local data {:?}",
426 // These cannot exist in borrowck
427 RegionKind::ReVar(..) |
428 RegionKind::ReCanonical(..) |
429 RegionKind::ReSkolemized(..) |
430 RegionKind::ReClosureBound(..) |
431 RegionKind::ReErased => span_bug!(borrow_span,
432 "unexpected region in borrowck {:?}",
436 let body_id = self.bccx.body.value.hir_id.local_id;
438 if self.bccx.region_scope_tree.containing_body(scope) != Some(body_id) {
439 // We are borrowing local data longer than its storage.
440 // This should result in other borrowck errors.
441 self.bccx.tcx.sess.delay_span_bug(borrow_span,
442 "borrowing local data longer than its storage");
446 if let Some(yield_span) = self.bccx
448 .yield_in_scope_for_expr(scope,
451 self.bccx.cannot_borrow_across_generator_yield(borrow_span,
457 pub fn check_for_conflicting_loans(&self, node: hir::ItemLocalId) {
458 //! Checks to see whether any of the loans that are issued
459 //! on entrance to `node` conflict with loans that have already been
460 //! issued when we enter `node` (for example, we do not
461 //! permit two `&mut` borrows of the same variable).
463 //! (Note that some loans can be *issued* without necessarily
464 //! taking effect yet.)
466 debug!("check_for_conflicting_loans(node={:?})", node);
468 let new_loan_indices = self.loans_generated_by(node);
469 debug!("new_loan_indices = {:?}", new_loan_indices);
471 for &new_loan_index in &new_loan_indices {
472 self.each_issued_loan(node, |issued_loan| {
473 let new_loan = &self.all_loans[new_loan_index];
474 // Only report an error for the first issued loan that conflicts
475 // to avoid O(n^2) errors.
476 self.report_error_if_loans_conflict(issued_loan, new_loan)
480 for (i, &x) in new_loan_indices.iter().enumerate() {
481 let old_loan = &self.all_loans[x];
482 for &y in &new_loan_indices[(i+1) ..] {
483 let new_loan = &self.all_loans[y];
484 self.report_error_if_loans_conflict(old_loan, new_loan);
489 pub fn report_error_if_loans_conflict(&self,
490 old_loan: &Loan<'tcx>,
491 new_loan: &Loan<'tcx>)
493 //! Checks whether `old_loan` and `new_loan` can safely be issued
496 debug!("report_error_if_loans_conflict(old_loan={:?}, new_loan={:?})",
500 // Should only be called for loans that are in scope at the same time.
501 assert!(self.bccx.region_scope_tree.scopes_intersect(old_loan.kill_scope,
502 new_loan.kill_scope));
504 let err_old_new = self.report_error_if_loan_conflicts_with_restriction(
505 old_loan, new_loan, old_loan, new_loan).err();
506 let err_new_old = self.report_error_if_loan_conflicts_with_restriction(
507 new_loan, old_loan, old_loan, new_loan).err();
509 match (err_old_new, err_new_old) {
510 (Some(mut err), None) | (None, Some(mut err)) => err.emit(),
511 (Some(mut err_old), Some(mut err_new)) => {
515 (None, None) => return true,
521 pub fn report_error_if_loan_conflicts_with_restriction(&self,
524 old_loan: &Loan<'tcx>,
525 new_loan: &Loan<'tcx>)
526 -> Result<(), DiagnosticBuilder<'a>> {
527 //! Checks whether the restrictions introduced by `loan1` would
528 //! prohibit `loan2`. Returns false if an error is reported.
530 debug!("report_error_if_loan_conflicts_with_restriction(\
531 loan1={:?}, loan2={:?})",
535 if compatible_borrow_kinds(loan1.kind, loan2.kind) {
539 let loan2_base_path = owned_ptr_base_path_rc(&loan2.loan_path);
540 for restr_path in &loan1.restricted_paths {
541 if *restr_path != loan2_base_path { continue; }
543 // If new_loan is something like `x.a`, and old_loan is something like `x.b`, we would
544 // normally generate a rather confusing message (in this case, for multiple mutable
547 // error: cannot borrow `x.b` as mutable more than once at a time
548 // note: previous borrow of `x.a` occurs here; the mutable borrow prevents
549 // subsequent moves, borrows, or modification of `x.a` until the borrow ends
551 // What we want to do instead is get the 'common ancestor' of the two borrow paths and
552 // use that for most of the message instead, giving is something like this:
554 // error: cannot borrow `x` as mutable more than once at a time
555 // note: previous borrow of `x` occurs here (through borrowing `x.a`); the mutable
556 // borrow prevents subsequent moves, borrows, or modification of `x` until the
559 let common = new_loan.loan_path.common(&old_loan.loan_path);
560 let (nl, ol, new_loan_msg, old_loan_msg) = {
561 if new_loan.loan_path.has_fork(&old_loan.loan_path) && common.is_some() {
562 let nl = self.bccx.loan_path_to_string(&common.unwrap());
564 let new_loan_msg = format!(" (via `{}`)",
565 self.bccx.loan_path_to_string(
566 &new_loan.loan_path));
567 let old_loan_msg = format!(" (via `{}`)",
568 self.bccx.loan_path_to_string(
569 &old_loan.loan_path));
570 (nl, ol, new_loan_msg, old_loan_msg)
572 (self.bccx.loan_path_to_string(&new_loan.loan_path),
573 self.bccx.loan_path_to_string(&old_loan.loan_path),
579 let ol_pronoun = if new_loan.loan_path == old_loan.loan_path {
585 // We want to assemble all the relevant locations for the error.
587 // 1. Where did the new loan occur.
588 // - if due to closure creation, where was the variable used in closure?
589 // 2. Where did old loan occur.
590 // 3. Where does old loan expire.
592 let previous_end_span =
593 Some(self.tcx().sess.codemap().end_point(
594 old_loan.kill_scope.span(self.tcx(), &self.bccx.region_scope_tree)));
596 let mut err = match (new_loan.kind, old_loan.kind) {
597 (ty::MutBorrow, ty::MutBorrow) =>
598 self.bccx.cannot_mutably_borrow_multiply(
599 new_loan.span, &nl, &new_loan_msg, old_loan.span, &old_loan_msg,
600 previous_end_span, Origin::Ast),
601 (ty::UniqueImmBorrow, ty::UniqueImmBorrow) =>
602 self.bccx.cannot_uniquely_borrow_by_two_closures(
603 new_loan.span, &nl, old_loan.span, previous_end_span, Origin::Ast),
604 (ty::UniqueImmBorrow, _) =>
605 self.bccx.cannot_uniquely_borrow_by_one_closure(
606 new_loan.span, &nl, &new_loan_msg,
607 old_loan.span, &ol_pronoun, &old_loan_msg, previous_end_span, Origin::Ast),
608 (_, ty::UniqueImmBorrow) => {
609 let new_loan_str = &new_loan.kind.to_user_str();
610 self.bccx.cannot_reborrow_already_uniquely_borrowed(
611 new_loan.span, &nl, &new_loan_msg, new_loan_str,
612 old_loan.span, &old_loan_msg, previous_end_span, Origin::Ast)
615 self.bccx.cannot_reborrow_already_borrowed(
617 &nl, &new_loan_msg, &new_loan.kind.to_user_str(),
618 old_loan.span, &ol_pronoun, &old_loan.kind.to_user_str(), &old_loan_msg,
619 previous_end_span, Origin::Ast)
622 match new_loan.cause {
623 euv::ClosureCapture(span) => {
626 format!("borrow occurs due to use of `{}` in closure", nl));
631 match old_loan.cause {
632 euv::ClosureCapture(span) => {
635 format!("previous borrow occurs due to use of `{}` in closure",
647 fn consume_common(&self,
648 id: hir::ItemLocalId,
650 cmt: &mc::cmt_<'tcx>,
651 mode: euv::ConsumeMode) {
652 if let Some(lp) = opt_loan_path(cmt) {
653 let moved_value_use_kind = match mode {
655 self.check_for_copy_of_frozen_path(id, span, &lp);
659 match self.move_data.kind_of_move_of_path(id, &lp) {
661 // Sometimes moves don't have a move kind;
662 // this either means that the original move
663 // was from something illegal to move,
664 // or was moved from referent of an unsafe
665 // pointer or something like that.
669 self.check_for_move_of_borrowed_path(id, span,
671 if move_kind == move_data::Captured {
681 self.check_if_path_is_moved(id, span, moved_value_use_kind, &lp);
685 fn check_for_copy_of_frozen_path(&self,
686 id: hir::ItemLocalId,
688 copy_path: &LoanPath<'tcx>) {
689 match self.analyze_restrictions_on_use(id, copy_path, ty::ImmBorrow) {
691 UseWhileBorrowed(loan_path, loan_span) => {
692 let desc = self.bccx.loan_path_to_string(copy_path);
693 self.bccx.cannot_use_when_mutably_borrowed(
695 loan_span, &self.bccx.loan_path_to_string(&loan_path),
702 fn check_for_move_of_borrowed_path(&self,
703 id: hir::ItemLocalId,
705 move_path: &LoanPath<'tcx>,
706 move_kind: move_data::MoveKind) {
707 // We want to detect if there are any loans at all, so we search for
708 // any loans incompatible with MutBorrrow, since all other kinds of
709 // loans are incompatible with that.
710 match self.analyze_restrictions_on_use(id, move_path, ty::MutBorrow) {
712 UseWhileBorrowed(loan_path, loan_span) => {
713 let mut err = match move_kind {
714 move_data::Captured => {
715 let mut err = self.bccx.cannot_move_into_closure(
716 span, &self.bccx.loan_path_to_string(move_path), Origin::Ast);
719 format!("borrow of `{}` occurs here",
720 &self.bccx.loan_path_to_string(&loan_path))
724 "move into closure occurs here"
728 move_data::Declared |
729 move_data::MoveExpr |
730 move_data::MovePat => {
731 let desc = self.bccx.loan_path_to_string(move_path);
732 let mut err = self.bccx.cannot_move_when_borrowed(span, &desc, Origin::Ast);
735 format!("borrow of `{}` occurs here",
736 &self.bccx.loan_path_to_string(&loan_path))
740 format!("move out of `{}` occurs here",
741 &self.bccx.loan_path_to_string(move_path))
752 pub fn analyze_restrictions_on_use(&self,
753 expr_id: hir::ItemLocalId,
754 use_path: &LoanPath<'tcx>,
755 borrow_kind: ty::BorrowKind)
757 debug!("analyze_restrictions_on_use(expr_id={:?}, use_path={:?})",
762 self.each_in_scope_loan_affecting_path(
763 region::Scope::Node(expr_id), use_path, |loan| {
764 if !compatible_borrow_kinds(loan.kind, borrow_kind) {
765 ret = UseWhileBorrowed(loan.loan_path.clone(), loan.span);
775 /// Reports an error if `expr` (which should be a path)
776 /// is using a moved/uninitialized value
777 fn check_if_path_is_moved(&self,
778 id: hir::ItemLocalId,
780 use_kind: MovedValueUseKind,
781 lp: &Rc<LoanPath<'tcx>>) {
782 debug!("check_if_path_is_moved(id={:?}, use_kind={:?}, lp={:?})",
785 // FIXME: if you find yourself tempted to cut and paste
786 // the body below and then specializing the error reporting,
787 // consider refactoring this instead!
789 let base_lp = owned_ptr_base_path_rc(lp);
790 self.move_data.each_move_of(id, &base_lp, |the_move, moved_lp| {
791 self.bccx.report_use_of_moved_value(
802 /// Reports an error if assigning to `lp` will use a
803 /// moved/uninitialized value. Mainly this is concerned with
804 /// detecting derefs of uninitialized pointers.
810 /// a = 10; // ok, even though a is uninitialized
814 /// struct Point { x: u32, y: u32 }
815 /// let mut p: Point;
816 /// p.x = 22; // ok, even though `p` is uninitialized
819 /// ```compile_fail,E0381
820 /// # struct Point { x: u32, y: u32 }
821 /// let mut p: Box<Point>;
822 /// (*p).x = 22; // not ok, p is uninitialized, can't deref
824 fn check_if_assigned_path_is_moved(&self,
825 id: hir::ItemLocalId,
827 use_kind: MovedValueUseKind,
828 lp: &Rc<LoanPath<'tcx>>)
831 LpVar(_) | LpUpvar(_) => {
832 // assigning to `x` does not require that `x` is initialized
834 LpDowncast(ref lp_base, _) => {
835 // assigning to `(P->Variant).f` is ok if assigning to `P` is ok
836 self.check_if_assigned_path_is_moved(id, span,
839 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(_))) => {
840 match lp_base.to_type().sty {
841 ty::TyAdt(def, _) if def.has_dtor(self.tcx()) => {
842 // In the case where the owner implements drop, then
843 // the path must be initialized to prevent a case of
844 // partial reinitialization
846 // FIXME: could refactor via hypothetical
847 // generalized check_if_path_is_moved
848 let loan_path = owned_ptr_base_path_rc(lp_base);
849 self.move_data.each_move_of(id, &loan_path, |_, _| {
851 .report_partial_reinitialization_of_uninitialized_structure(
861 // assigning to `P.f` is ok if assigning to `P` is ok
862 self.check_if_assigned_path_is_moved(id, span,
865 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement)) |
866 LpExtend(ref lp_base, _, LpDeref(_)) => {
867 // assigning to `P[i]` requires `P` is initialized
868 // assigning to `(*P)` requires `P` is initialized
869 self.check_if_path_is_moved(id, span, use_kind, lp_base);
874 fn check_assignment(&self,
875 assignment_id: hir::ItemLocalId,
876 assignment_span: Span,
877 assignee_cmt: &mc::cmt_<'tcx>) {
878 debug!("check_assignment(assignee_cmt={:?})", assignee_cmt);
880 // Check that we don't invalidate any outstanding loans
881 if let Some(loan_path) = opt_loan_path(assignee_cmt) {
882 let scope = region::Scope::Node(assignment_id);
883 self.each_in_scope_loan_affecting_path(scope, &loan_path, |loan| {
884 self.report_illegal_mutation(assignment_span, &loan_path, loan);
889 // Check for reassignments to (immutable) local variables. This
890 // needs to be done here instead of in check_loans because we
891 // depend on move data.
892 if let Categorization::Local(local_id) = assignee_cmt.cat {
893 let lp = opt_loan_path(assignee_cmt).unwrap();
894 self.move_data.each_assignment_of(assignment_id, &lp, |assign| {
895 if assignee_cmt.mutbl.is_mutable() {
896 let hir_id = self.bccx.tcx.hir.node_to_hir_id(local_id);
897 self.bccx.used_mut_nodes.borrow_mut().insert(hir_id);
899 self.bccx.report_reassigned_immutable_variable(
910 pub fn report_illegal_mutation(&self,
912 loan_path: &LoanPath<'tcx>,
914 self.bccx.cannot_assign_to_borrowed(
915 span, loan.span, &self.bccx.loan_path_to_string(loan_path), Origin::Ast)