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
21 use mc = middle::mem_categorization;
22 use middle::borrowck::*;
25 use middle::typeck::MethodCall;
28 use syntax::codemap::Span;
29 use syntax::visit::Visitor;
31 use util::ppaux::Repr;
33 struct CheckLoanCtxt<'a> {
34 bccx: &'a BorrowckCtxt<'a>,
35 dfcx_loans: &'a LoanDataFlow<'a>,
36 move_data: move_data::FlowedMoveData<'a>,
37 all_loans: &'a [Loan],
40 impl<'a> Visitor<()> for CheckLoanCtxt<'a> {
42 fn visit_expr(&mut self, ex: &ast::Expr, _: ()) {
43 check_loans_in_expr(self, ex);
45 fn visit_local(&mut self, l: &ast::Local, _: ()) {
46 check_loans_in_local(self, l);
48 fn visit_block(&mut self, b: &ast::Block, _: ()) {
49 check_loans_in_block(self, b);
51 fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
52 check_loans_in_pat(self, p);
54 fn visit_fn(&mut self, _fk: &visit::FnKind, _fd: &ast::FnDecl,
55 _b: &ast::Block, _s: Span, _n: ast::NodeId, _: ()) {
56 // Don't process nested items or closures here,
57 // the outer loop will take care of it.
61 // FIXME(#10894) should continue recursing
62 fn visit_ty(&mut self, _t: &ast::Ty, _: ()) {}
65 pub fn check_loans(bccx: &BorrowckCtxt,
66 dfcx_loans: &LoanDataFlow,
67 move_data: move_data::FlowedMoveData,
70 debug!("check_loans(body id={:?})", body.id);
72 let mut clcx = CheckLoanCtxt {
74 dfcx_loans: dfcx_loans,
79 clcx.visit_block(body, ());
85 MoveWhileBorrowed(/*loan*/@LoanPath, /*loan*/Span)
88 impl<'a> CheckLoanCtxt<'a> {
89 pub fn tcx(&self) -> &'a ty::ctxt { self.bccx.tcx }
91 pub fn each_issued_loan(&self, scope_id: ast::NodeId, op: |&Loan| -> bool)
93 //! Iterates over each loan that has been issued
94 //! on entrance to `scope_id`, regardless of whether it is
95 //! actually *in scope* at that point. Sometimes loans
96 //! are issued for future scopes and thus they may have been
97 //! *issued* but not yet be in effect.
99 self.dfcx_loans.each_bit_on_entry_frozen(scope_id, |loan_index| {
100 let loan = &self.all_loans[loan_index];
105 pub fn each_in_scope_loan(&self,
106 scope_id: ast::NodeId,
109 //! Like `each_issued_loan()`, but only considers loans that are
110 //! currently in scope.
112 let tcx = self.tcx();
113 self.each_issued_loan(scope_id, |loan| {
114 if tcx.region_maps.is_subscope_of(scope_id, loan.kill_scope) {
122 pub fn each_in_scope_restriction(&self,
123 scope_id: ast::NodeId,
124 loan_path: @LoanPath,
125 op: |&Loan, &Restriction| -> bool)
127 //! Iterates through all the in-scope restrictions for the
128 //! given `loan_path`
130 self.each_in_scope_loan(scope_id, |loan| {
131 debug!("each_in_scope_restriction found loan: {:?}",
132 loan.repr(self.tcx()));
135 for restr in loan.restrictions.iter() {
136 if restr.loan_path == loan_path {
137 if !op(loan, restr) {
147 pub fn loans_generated_by(&self, scope_id: ast::NodeId) -> Vec<uint> {
148 //! Returns a vector of the loans that are generated as
149 //! we encounter `scope_id`.
151 let mut result = Vec::new();
152 self.dfcx_loans.each_gen_bit_frozen(scope_id, |loan_index| {
153 result.push(loan_index);
159 pub fn check_for_conflicting_loans(&self, scope_id: ast::NodeId) {
160 //! Checks to see whether any of the loans that are issued
161 //! by `scope_id` conflict with loans that have already been
162 //! issued when we enter `scope_id` (for example, we do not
163 //! permit two `&mut` borrows of the same variable).
165 debug!("check_for_conflicting_loans(scope_id={:?})", scope_id);
167 let new_loan_indices = self.loans_generated_by(scope_id);
168 debug!("new_loan_indices = {:?}", new_loan_indices);
170 self.each_issued_loan(scope_id, |issued_loan| {
171 for &new_loan_index in new_loan_indices.iter() {
172 let new_loan = &self.all_loans[new_loan_index];
173 self.report_error_if_loans_conflict(issued_loan, new_loan);
178 for (i, &x) in new_loan_indices.iter().enumerate() {
179 let old_loan = &self.all_loans[x];
180 for &y in new_loan_indices.slice_from(i+1).iter() {
181 let new_loan = &self.all_loans[y];
182 self.report_error_if_loans_conflict(old_loan, new_loan);
187 pub fn report_error_if_loans_conflict(&self,
190 //! Checks whether `old_loan` and `new_loan` can safely be issued
193 debug!("report_error_if_loans_conflict(old_loan={}, new_loan={})",
194 old_loan.repr(self.tcx()),
195 new_loan.repr(self.tcx()));
197 // Should only be called for loans that are in scope at the same time.
198 assert!(self.tcx().region_maps.scopes_intersect(old_loan.kill_scope,
199 new_loan.kill_scope));
201 self.report_error_if_loan_conflicts_with_restriction(
202 old_loan, new_loan, old_loan, new_loan) &&
203 self.report_error_if_loan_conflicts_with_restriction(
204 new_loan, old_loan, old_loan, new_loan);
207 pub fn report_error_if_loan_conflicts_with_restriction(&self,
213 //! Checks whether the restrictions introduced by `loan1` would
214 //! prohibit `loan2`. Returns false if an error is reported.
216 debug!("report_error_if_loan_conflicts_with_restriction(\
217 loan1={}, loan2={})",
218 loan1.repr(self.tcx()),
219 loan2.repr(self.tcx()));
221 // Restrictions that would cause the new loan to be illegal:
222 let illegal_if = match loan2.kind {
223 // Look for restrictions against mutation. These are
224 // generated by all other borrows.
225 ty::MutBorrow => RESTR_MUTATE,
227 // Look for restrictions against freezing (immutable borrows).
228 // These are generated by `&mut` borrows.
229 ty::ImmBorrow => RESTR_FREEZE,
231 // No matter how the data is borrowed (as `&`, as `&mut`,
232 // or as `&unique imm`) it will always generate a
233 // restriction against mutating the data. So look for those.
234 ty::UniqueImmBorrow => RESTR_MUTATE,
236 debug!("illegal_if={:?}", illegal_if);
238 for restr in loan1.restrictions.iter() {
239 if !restr.set.intersects(illegal_if) { continue; }
240 if restr.loan_path != loan2.loan_path { continue; }
242 let old_pronoun = if new_loan.loan_path == old_loan.loan_path {
246 self.bccx.loan_path_to_str(old_loan.loan_path))
249 match (new_loan.kind, old_loan.kind) {
250 (ty::MutBorrow, ty::MutBorrow) => {
253 format!("cannot borrow `{}` as mutable \
254 more than once at a time",
255 self.bccx.loan_path_to_str(new_loan.loan_path)));
258 (ty::UniqueImmBorrow, _) => {
261 format!("closure requires unique access to `{}` \
262 but {} is already borrowed",
263 self.bccx.loan_path_to_str(new_loan.loan_path),
267 (_, ty::UniqueImmBorrow) => {
270 format!("cannot borrow `{}` as {} because \
271 previous closure requires unique access",
272 self.bccx.loan_path_to_str(new_loan.loan_path),
273 new_loan.kind.to_user_str()));
279 format!("cannot borrow `{}` as {} because \
280 {} is also borrowed as {}",
281 self.bccx.loan_path_to_str(new_loan.loan_path),
282 new_loan.kind.to_user_str(),
284 old_loan.kind.to_user_str()));
288 match new_loan.cause {
289 ClosureCapture(span) => {
292 format!("borrow occurs due to use of `{}` in closure",
293 self.bccx.loan_path_to_str(new_loan.loan_path)));
298 let rule_summary = match old_loan.kind {
300 format!("the mutable borrow prevents subsequent \
301 moves, borrows, or modification of `{0}` \
302 until the borrow ends",
303 self.bccx.loan_path_to_str(old_loan.loan_path))
307 format!("the immutable borrow prevents subsequent \
308 moves or mutable borrows of `{0}` \
309 until the borrow ends",
310 self.bccx.loan_path_to_str(old_loan.loan_path))
313 ty::UniqueImmBorrow => {
314 format!("the unique capture prevents subsequent \
315 moves or borrows of `{0}` \
316 until the borrow ends",
317 self.bccx.loan_path_to_str(old_loan.loan_path))
321 let borrow_summary = match old_loan.cause {
322 ClosureCapture(_) => {
323 format!("previous borrow of `{}` occurs here due to \
325 self.bccx.loan_path_to_str(old_loan.loan_path))
328 AddrOf | AutoRef | RefBinding => {
329 format!("previous borrow of `{}` occurs here",
330 self.bccx.loan_path_to_str(old_loan.loan_path))
336 format!("{}; {}", borrow_summary, rule_summary));
338 let old_loan_span = self.tcx().map.span(old_loan.kill_scope);
339 self.bccx.span_end_note(old_loan_span,
340 "previous borrow ends here");
348 pub fn is_local_variable(&self, cmt: mc::cmt) -> bool {
350 mc::cat_local(_) => true,
355 pub fn check_if_path_is_moved(&self,
358 use_kind: MovedValueUseKind,
361 * Reports an error if `expr` (which should be a path)
362 * is using a moved/uninitialized value
365 debug!("check_if_path_is_moved(id={:?}, use_kind={:?}, lp={})",
366 id, use_kind, lp.repr(self.bccx.tcx));
367 self.move_data.each_move_of(id, lp, |move, moved_lp| {
368 self.bccx.report_use_of_moved_value(
378 pub fn check_assignment(&self, expr: &ast::Expr) {
379 // We don't use cat_expr() here because we don't want to treat
380 // auto-ref'd parameters in overloaded operators as rvalues.
381 let cmt = match self.bccx.tcx.adjustments.borrow().find_copy(&expr.id) {
382 None => self.bccx.cat_expr_unadjusted(expr),
383 Some(adj) => self.bccx.cat_expr_autoderefd(expr, adj)
386 debug!("check_assignment(cmt={})", cmt.repr(self.tcx()));
388 // Mutable values can be assigned, as long as they obey loans
389 // and aliasing restrictions:
390 if cmt.mutbl.is_mutable() {
391 if check_for_aliasable_mutable_writes(self, expr, cmt) {
392 if check_for_assignment_to_restricted_or_frozen_location(
395 // Safe, but record for lint pass later:
396 mark_variable_as_used_mut(self, cmt);
402 // For immutable local variables, assignments are legal
403 // if they cannot already have been assigned
404 if self.is_local_variable(cmt) {
405 assert!(cmt.mutbl.is_immutable()); // no "const" locals
406 let lp = opt_loan_path(cmt).unwrap();
407 self.move_data.each_assignment_of(expr.id, lp, |assign| {
408 self.bccx.report_reassigned_immutable_variable(
417 // Otherwise, just a plain error.
418 match opt_loan_path(cmt) {
422 format!("cannot assign to {} {} `{}`",
423 cmt.mutbl.to_user_str(),
424 self.bccx.cmt_to_str(cmt),
425 self.bccx.loan_path_to_str(lp)));
430 format!("cannot assign to {} {}",
431 cmt.mutbl.to_user_str(),
432 self.bccx.cmt_to_str(cmt)));
437 fn mark_variable_as_used_mut(this: &CheckLoanCtxt,
439 //! If the mutability of the `cmt` being written is inherited
440 //! from a local variable, liveness will
441 //! not have been able to detect that this variable's mutability
442 //! is important, so we must add the variable to the
443 //! `used_mut_nodes` table here.
447 debug!("mark_writes_through_upvars_as_used_mut(cmt={})",
448 cmt.repr(this.tcx()));
450 mc::cat_local(id) | mc::cat_arg(id) => {
451 this.tcx().used_mut_nodes.borrow_mut().insert(id);
455 mc::cat_upvar(..) => {
459 mc::cat_deref(_, _, mc::GcPtr) => {
460 assert_eq!(cmt.mutbl, mc::McImmutable);
465 mc::cat_static_item |
466 mc::cat_copied_upvar(..) |
467 mc::cat_deref(_, _, mc::UnsafePtr(..)) |
468 mc::cat_deref(_, _, mc::BorrowedPtr(..)) => {
469 assert_eq!(cmt.mutbl, mc::McDeclared);
473 mc::cat_discr(b, _) |
474 mc::cat_deref(b, _, mc::OwnedPtr) => {
475 assert_eq!(cmt.mutbl, mc::McInherited);
479 mc::cat_downcast(b) |
480 mc::cat_interior(b, _) => {
481 assert_eq!(cmt.mutbl, mc::McInherited);
488 fn check_for_aliasable_mutable_writes(this: &CheckLoanCtxt,
490 cmt: mc::cmt) -> bool {
491 //! Safety checks related to writes to aliasable, mutable locations
493 let guarantor = cmt.guarantor();
494 debug!("check_for_aliasable_mutable_writes(cmt={}, guarantor={})",
495 cmt.repr(this.tcx()), guarantor.repr(this.tcx()));
496 match guarantor.cat {
497 mc::cat_deref(b, _, mc::BorrowedPtr(ty::MutBorrow, _)) => {
498 // Statically prohibit writes to `&mut` when aliasable
500 check_for_aliasability_violation(this, expr, b);
506 return true; // no errors reported
509 fn check_for_aliasability_violation(this: &CheckLoanCtxt,
513 match cmt.freely_aliasable(this.tcx()) {
517 Some(mc::AliasableStaticMut(..)) => {
521 this.bccx.report_aliasability_violation(
530 fn check_for_assignment_to_restricted_or_frozen_location(
531 this: &CheckLoanCtxt,
533 cmt: mc::cmt) -> bool
535 //! Check for assignments that violate the terms of an
536 //! outstanding loan.
538 let loan_path = match opt_loan_path(cmt) {
540 None => { return true; /* no loan path, can't be any loans */ }
543 // Start by searching for an assignment to a *restricted*
544 // location. Here is one example of the kind of error caught
547 // let mut v = ~[1, 2, 3];
551 // In this case, creating `p` triggers a RESTR_MUTATE
552 // restriction on the path `v`.
554 // Here is a second, more subtle example:
556 // let mut v = ~[1, 2, 3];
557 // let p = &const v[0];
560 // v = ~[4, 5, 3]; // Error
562 // In this case, `p` is pointing to `v[0]`, and it is a
563 // `const` pointer in any case. So the first two
564 // assignments are legal (and would be permitted by this
565 // check). However, the final assignment (which is
566 // logically equivalent) is forbidden, because it would
567 // cause the existing `v` array to be freed, thus
568 // invalidating `p`. In the code, this error results
569 // because `gather_loans::restrictions` adds a
570 // `RESTR_MUTATE` restriction whenever the contents of an
571 // owned pointer are borrowed, and hence while `v[*]` is not
572 // restricted from being written, `v` is.
573 let cont = this.each_in_scope_restriction(expr.id,
576 if restr.set.intersects(RESTR_MUTATE) {
577 this.report_illegal_mutation(expr, loan_path, loan);
584 if !cont { return false }
586 // The previous code handled assignments to paths that
587 // have been restricted. This covers paths that have been
588 // directly lent out and their base paths, but does not
589 // cover random extensions of those paths. For example,
590 // the following program is not declared illegal by the
593 // let mut v = ~[1, 2, 3];
595 // v[0] = 4; // declared error by loop below, not code above
597 // The reason that this passes the previous check whereas
598 // an assignment like `v = ~[4]` fails is because the assignment
599 // here is to `v[*]`, and the existing restrictions were issued
600 // for `v`, not `v[*]`.
602 // So in this loop, we walk back up the loan path so long
603 // as the mutability of the path is dependent on a super
604 // path, and check that the super path was not lent out as
605 // mutable or immutable (a const loan is ok).
607 // Mutability of a path can be dependent on the super path
608 // in two ways. First, it might be inherited mutability.
609 // Second, the pointee of an `&mut` pointer can only be
610 // mutated if it is found in an unaliased location, so we
611 // have to check that the owner location is not borrowed.
613 // Note that we are *not* checking for any and all
614 // restrictions. We are only interested in the pointers
615 // that the user created, whereas we add restrictions for
616 // all kinds of paths that are not directly aliased. If we checked
617 // for all restrictions, and not just loans, then the following
618 // valid program would be considered illegal:
620 // let mut v = ~[1, 2, 3];
621 // let p = &const v[0];
624 // Here the restriction that `v` not be mutated would be misapplied
625 // to block the subpath `v[1]`.
626 let full_loan_path = loan_path;
627 let mut loan_path = loan_path;
630 // Peel back one layer if, for `loan_path` to be
631 // mutable, `lp_base` must be mutable. This occurs
632 // with inherited mutability and with `&mut`
634 LpExtend(lp_base, mc::McInherited, _) |
635 LpExtend(lp_base, _, LpDeref(mc::BorrowedPtr(ty::MutBorrow, _))) => {
639 // Otherwise stop iterating
640 LpExtend(_, mc::McDeclared, _) |
641 LpExtend(_, mc::McImmutable, _) |
647 // Check for a non-const loan of `loan_path`
648 let cont = this.each_in_scope_loan(expr.id, |loan| {
649 if loan.loan_path == loan_path {
650 this.report_illegal_mutation(expr, full_loan_path, loan);
657 if !cont { return false }
662 pub fn report_illegal_mutation(&self,
664 loan_path: &LoanPath,
668 format!("cannot assign to `{}` because it is borrowed",
669 self.bccx.loan_path_to_str(loan_path)));
672 format!("borrow of `{}` occurs here",
673 self.bccx.loan_path_to_str(loan_path)));
676 fn check_move_out_from_expr(&self, expr: &ast::Expr) {
678 ast::ExprFnBlock(..) | ast::ExprProc(..) => {
679 // Moves due to captures are checked in
680 // check_captured_variables() because it allows
681 // us to give a more precise error message with
682 // a more precise span.
685 self.check_move_out_from_id(expr.id, expr.span)
690 fn check_move_out_from_id(&self, id: ast::NodeId, span: Span) {
691 self.move_data.each_path_moved_by(id, |_, move_path| {
692 match self.analyze_move_out_from(id, move_path) {
694 MoveWhileBorrowed(loan_path, loan_span) => {
697 format!("cannot move out of `{}` \
698 because it is borrowed",
699 self.bccx.loan_path_to_str(move_path)));
702 format!("borrow of `{}` occurs here",
703 self.bccx.loan_path_to_str(loan_path)));
710 fn check_captured_variables(&self,
711 closure_id: ast::NodeId,
713 for cap_var in self.bccx.capture_map.get(&closure_id).iter() {
714 let var_id = ast_util::def_id_of_def(cap_var.def).node;
715 let var_path = @LpVar(var_id);
716 self.check_if_path_is_moved(closure_id, span,
717 MovedInCapture, var_path);
719 moves::CapRef | moves::CapCopy => {}
721 check_by_move_capture(self, closure_id, cap_var, var_path);
727 fn check_by_move_capture(this: &CheckLoanCtxt,
728 closure_id: ast::NodeId,
729 cap_var: &moves::CaptureVar,
730 move_path: @LoanPath) {
731 let move_err = this.analyze_move_out_from(closure_id, move_path);
734 MoveWhileBorrowed(loan_path, loan_span) => {
737 format!("cannot move `{}` into closure \
738 because it is borrowed",
739 this.bccx.loan_path_to_str(move_path)));
742 format!("borrow of `{}` occurs here",
743 this.bccx.loan_path_to_str(loan_path)));
749 pub fn analyze_move_out_from(&self,
750 expr_id: ast::NodeId,
751 mut move_path: @LoanPath)
753 debug!("analyze_move_out_from(expr_id={:?}, move_path={})",
754 self.tcx().map.node_to_str(expr_id),
755 move_path.repr(self.tcx()));
757 // We must check every element of a move path. See
758 // `borrowck-move-subcomponent.rs` for a test case.
760 // check for a conflicting loan:
761 let mut ret = MoveOk;
762 self.each_in_scope_restriction(expr_id, move_path, |loan, _| {
763 // Any restriction prevents moves.
764 ret = MoveWhileBorrowed(loan.loan_path, loan.span);
773 LpVar(_) => return MoveOk,
774 LpExtend(subpath, _, _) => move_path = subpath,
779 pub fn check_call(&self,
781 _callee: Option<@ast::Expr>,
783 _args: &[@ast::Expr]) {
784 // NB: This call to check for conflicting loans is not truly
785 // necessary, because the callee_id never issues new loans.
786 // However, I added it for consistency and lest the system
787 // should change in the future.
789 // FIXME(#6268) nested method calls
790 // self.check_for_conflicting_loans(callee_id);
794 fn check_loans_in_local<'a>(this: &mut CheckLoanCtxt<'a>,
795 local: &ast::Local) {
796 visit::walk_local(this, local, ());
799 fn check_loans_in_expr<'a>(this: &mut CheckLoanCtxt<'a>,
801 visit::walk_expr(this, expr, ());
803 debug!("check_loans_in_expr(expr={})",
804 expr.repr(this.tcx()));
806 this.check_for_conflicting_loans(expr.id);
807 this.check_move_out_from_expr(expr);
809 let method_map = this.bccx.method_map.borrow();
811 ast::ExprPath(..) => {
812 if !this.move_data.is_assignee(expr.id) {
813 let cmt = this.bccx.cat_expr_unadjusted(expr);
814 debug!("path cmt={}", cmt.repr(this.tcx()));
815 let r = opt_loan_path(cmt);
816 for &lp in r.iter() {
817 this.check_if_path_is_moved(expr.id, expr.span, MovedInUse, lp);
821 ast::ExprFnBlock(..) | ast::ExprProc(..) => {
822 this.check_captured_variables(expr.id, expr.span)
824 ast::ExprAssign(dest, _) |
825 ast::ExprAssignOp(_, dest, _) => {
826 this.check_assignment(dest);
828 ast::ExprCall(f, ref args) => {
829 this.check_call(expr, Some(f), f.span, args.as_slice());
831 ast::ExprMethodCall(_, _, ref args) => {
832 this.check_call(expr, None, expr.span, args.as_slice());
834 ast::ExprIndex(_, rval) | ast::ExprBinary(_, _, rval)
835 if method_map.contains_key(&MethodCall::expr(expr.id)) => {
836 this.check_call(expr, None, expr.span, [rval]);
838 ast::ExprUnary(_, _) | ast::ExprIndex(_, _)
839 if method_map.contains_key(&MethodCall::expr(expr.id)) => {
840 this.check_call(expr, None, expr.span, []);
842 ast::ExprInlineAsm(ref ia) => {
843 for &(_, out) in ia.outputs.iter() {
844 this.check_assignment(out);
851 fn check_loans_in_pat<'a>(this: &mut CheckLoanCtxt<'a>,
854 this.check_for_conflicting_loans(pat.id);
855 this.check_move_out_from_id(pat.id, pat.span);
856 visit::walk_pat(this, pat, ());
859 fn check_loans_in_block<'a>(this: &mut CheckLoanCtxt<'a>,
862 visit::walk_block(this, blk, ());
863 this.check_for_conflicting_loans(blk.id);