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::*;
27 use syntax::codemap::Span;
28 use syntax::visit::Visitor;
30 use util::ppaux::Repr;
32 struct CheckLoanCtxt<'a> {
33 bccx: &'a BorrowckCtxt,
34 dfcx_loans: &'a LoanDataFlow,
35 move_data: move_data::FlowedMoveData,
36 all_loans: &'a [Loan],
39 impl<'a> Visitor<()> for CheckLoanCtxt<'a> {
41 fn visit_expr(&mut self, ex: &ast::Expr, _: ()) {
42 check_loans_in_expr(self, ex);
44 fn visit_local(&mut self, l: &ast::Local, _: ()) {
45 check_loans_in_local(self, l);
47 fn visit_block(&mut self, b: &ast::Block, _: ()) {
48 check_loans_in_block(self, b);
50 fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
51 check_loans_in_pat(self, p);
53 fn visit_fn(&mut self, _fk: &visit::FnKind, _fd: &ast::FnDecl,
54 _b: &ast::Block, _s: Span, _n: ast::NodeId, _: ()) {
55 // Don't process nested items or closures here,
56 // the outer loop will take care of it.
60 // FIXME(#10894) should continue recursing
61 fn visit_ty(&mut self, _t: &ast::Ty, _: ()) {}
64 pub fn check_loans(bccx: &BorrowckCtxt,
65 dfcx_loans: &LoanDataFlow,
66 move_data: move_data::FlowedMoveData,
69 debug!("check_loans(body id={:?})", body.id);
71 let mut clcx = CheckLoanCtxt {
73 dfcx_loans: dfcx_loans,
78 clcx.visit_block(body, ());
84 MoveWhileBorrowed(/*loan*/@LoanPath, /*loan*/Span)
87 impl<'a> CheckLoanCtxt<'a> {
88 pub fn tcx(&self) -> ty::ctxt { self.bccx.tcx }
90 pub fn each_issued_loan(&self, scope_id: ast::NodeId, op: |&Loan| -> bool)
92 //! Iterates over each loan that has been issued
93 //! on entrance to `scope_id`, regardless of whether it is
94 //! actually *in scope* at that point. Sometimes loans
95 //! are issued for future scopes and thus they may have been
96 //! *issued* but not yet be in effect.
98 self.dfcx_loans.each_bit_on_entry_frozen(scope_id, |loan_index| {
99 let loan = &self.all_loans[loan_index];
104 pub fn each_in_scope_loan(&self,
105 scope_id: ast::NodeId,
108 //! Like `each_issued_loan()`, but only considers loans that are
109 //! currently in scope.
111 let tcx = self.tcx();
112 self.each_issued_loan(scope_id, |loan| {
113 if tcx.region_maps.is_subscope_of(scope_id, loan.kill_scope) {
121 pub fn each_in_scope_restriction(&self,
122 scope_id: ast::NodeId,
123 loan_path: @LoanPath,
124 op: |&Loan, &Restriction| -> bool)
126 //! Iterates through all the in-scope restrictions for the
127 //! given `loan_path`
129 self.each_in_scope_loan(scope_id, |loan| {
130 debug!("each_in_scope_restriction found loan: {:?}",
131 loan.repr(self.tcx()));
134 for restr in loan.restrictions.iter() {
135 if restr.loan_path == loan_path {
136 if !op(loan, restr) {
146 pub fn loans_generated_by(&self, scope_id: ast::NodeId) -> ~[uint] {
147 //! Returns a vector of the loans that are generated as
148 //! we encounter `scope_id`.
150 let mut result = ~[];
151 self.dfcx_loans.each_gen_bit_frozen(scope_id, |loan_index| {
152 result.push(loan_index);
158 pub fn check_for_conflicting_loans(&self, scope_id: ast::NodeId) {
159 //! Checks to see whether any of the loans that are issued
160 //! by `scope_id` conflict with loans that have already been
161 //! issued when we enter `scope_id` (for example, we do not
162 //! permit two `&mut` borrows of the same variable).
164 debug!("check_for_conflicting_loans(scope_id={:?})", scope_id);
166 let new_loan_indices = self.loans_generated_by(scope_id);
167 debug!("new_loan_indices = {:?}", new_loan_indices);
169 self.each_issued_loan(scope_id, |issued_loan| {
170 for &new_loan_index in new_loan_indices.iter() {
171 let new_loan = &self.all_loans[new_loan_index];
172 self.report_error_if_loans_conflict(issued_loan, new_loan);
177 for (i, &x) in new_loan_indices.iter().enumerate() {
178 let old_loan = &self.all_loans[x];
179 for &y in new_loan_indices.slice_from(i+1).iter() {
180 let new_loan = &self.all_loans[y];
181 self.report_error_if_loans_conflict(old_loan, new_loan);
186 pub fn report_error_if_loans_conflict(&self,
189 //! Checks whether `old_loan` and `new_loan` can safely be issued
192 debug!("report_error_if_loans_conflict(old_loan={}, new_loan={})",
193 old_loan.repr(self.tcx()),
194 new_loan.repr(self.tcx()));
196 // Should only be called for loans that are in scope at the same time.
197 assert!(self.tcx().region_maps.scopes_intersect(old_loan.kill_scope,
198 new_loan.kill_scope));
200 self.report_error_if_loan_conflicts_with_restriction(
201 old_loan, new_loan, old_loan, new_loan) &&
202 self.report_error_if_loan_conflicts_with_restriction(
203 new_loan, old_loan, old_loan, new_loan);
206 pub fn report_error_if_loan_conflicts_with_restriction(&self,
212 //! Checks whether the restrictions introduced by `loan1` would
213 //! prohibit `loan2`. Returns false if an error is reported.
215 debug!("report_error_if_loan_conflicts_with_restriction(\
216 loan1={}, loan2={})",
217 loan1.repr(self.tcx()),
218 loan2.repr(self.tcx()));
220 // Restrictions that would cause the new loan to be illegal:
221 let illegal_if = match loan2.kind {
222 // Look for restrictions against mutation. These are
223 // generated by all other borrows.
224 ty::MutBorrow => RESTR_MUTATE,
226 // Look for restrictions against freezing (immutable borrows).
227 // These are generated by `&mut` borrows.
228 ty::ImmBorrow => RESTR_FREEZE,
230 // No matter how the data is borrowed (as `&`, as `&mut`,
231 // or as `&unique imm`) it will always generate a
232 // restriction against mutating the data. So look for those.
233 ty::UniqueImmBorrow => RESTR_MUTATE,
235 debug!("illegal_if={:?}", illegal_if);
237 for restr in loan1.restrictions.iter() {
238 if !restr.set.intersects(illegal_if) { continue; }
239 if restr.loan_path != loan2.loan_path { continue; }
241 let old_pronoun = if new_loan.loan_path == old_loan.loan_path {
245 self.bccx.loan_path_to_str(old_loan.loan_path))
248 match (new_loan.kind, old_loan.kind) {
249 (ty::MutBorrow, ty::MutBorrow) => {
252 format!("cannot borrow `{}` as mutable \
253 more than once at a time",
254 self.bccx.loan_path_to_str(new_loan.loan_path)));
257 (ty::UniqueImmBorrow, _) => {
260 format!("closure requires unique access to `{}` \
261 but {} is already borrowed",
262 self.bccx.loan_path_to_str(new_loan.loan_path),
266 (_, ty::UniqueImmBorrow) => {
269 format!("cannot borrow `{}` as {} because \
270 previous closure requires unique access",
271 self.bccx.loan_path_to_str(new_loan.loan_path),
272 new_loan.kind.to_user_str()));
278 format!("cannot borrow `{}` as {} because \
279 {} is also borrowed as {}",
280 self.bccx.loan_path_to_str(new_loan.loan_path),
281 new_loan.kind.to_user_str(),
283 old_loan.kind.to_user_str()));
287 match new_loan.cause {
288 ClosureCapture(span) => {
291 format!("borrow occurs due to use of `{}` in closure",
292 self.bccx.loan_path_to_str(new_loan.loan_path)));
297 let rule_summary = match old_loan.kind {
299 format!("the mutable borrow prevents subsequent \
300 moves, borrows, or modification of `{0}` \
301 until the borrow ends",
302 self.bccx.loan_path_to_str(old_loan.loan_path))
306 format!("the immutable borrow prevents subsequent \
307 moves or mutable borrows of `{0}` \
308 until the borrow ends",
309 self.bccx.loan_path_to_str(old_loan.loan_path))
312 ty::UniqueImmBorrow => {
313 format!("the unique capture prevents subsequent \
314 moves or borrows of `{0}` \
315 until the borrow ends",
316 self.bccx.loan_path_to_str(old_loan.loan_path))
320 let borrow_summary = match old_loan.cause {
321 ClosureCapture(_) => {
322 format!("previous borrow of `{}` occurs here due to \
324 self.bccx.loan_path_to_str(old_loan.loan_path))
327 AddrOf | AutoRef | RefBinding => {
328 format!("previous borrow of `{}` occurs here",
329 self.bccx.loan_path_to_str(old_loan.loan_path))
335 format!("{}; {}", borrow_summary, rule_summary));
337 let old_loan_span = self.tcx().map.span(old_loan.kill_scope);
338 self.bccx.span_end_note(old_loan_span,
339 "previous borrow ends here");
347 pub fn is_local_variable(&self, cmt: mc::cmt) -> bool {
349 mc::cat_local(_) => true,
354 pub fn check_if_path_is_moved(&self,
357 use_kind: MovedValueUseKind,
360 * Reports an error if `expr` (which should be a path)
361 * is using a moved/uninitialized value
364 debug!("check_if_path_is_moved(id={:?}, use_kind={:?}, lp={})",
365 id, use_kind, lp.repr(self.bccx.tcx));
366 self.move_data.each_move_of(id, lp, |move, moved_lp| {
367 self.bccx.report_use_of_moved_value(
377 pub fn check_assignment(&self, expr: &ast::Expr) {
378 // We don't use cat_expr() here because we don't want to treat
379 // auto-ref'd parameters in overloaded operators as rvalues.
381 let adjustments = self.bccx.tcx.adjustments.borrow();
382 adjustments.get().find_copy(&expr.id)
384 let cmt = match adj {
385 None => self.bccx.cat_expr_unadjusted(expr),
386 Some(adj) => self.bccx.cat_expr_autoderefd(expr, adj)
389 debug!("check_assignment(cmt={})", cmt.repr(self.tcx()));
391 // Mutable values can be assigned, as long as they obey loans
392 // and aliasing restrictions:
393 if cmt.mutbl.is_mutable() {
394 if check_for_aliasable_mutable_writes(self, expr, cmt) {
395 if check_for_assignment_to_restricted_or_frozen_location(
398 // Safe, but record for lint pass later:
399 mark_variable_as_used_mut(self, cmt);
405 // For immutable local variables, assignments are legal
406 // if they cannot already have been assigned
407 if self.is_local_variable(cmt) {
408 assert!(cmt.mutbl.is_immutable()); // no "const" locals
409 let lp = opt_loan_path(cmt).unwrap();
410 self.move_data.each_assignment_of(expr.id, lp, |assign| {
411 self.bccx.report_reassigned_immutable_variable(
420 // Otherwise, just a plain error.
421 match opt_loan_path(cmt) {
425 format!("cannot assign to {} {} `{}`",
426 cmt.mutbl.to_user_str(),
427 self.bccx.cmt_to_str(cmt),
428 self.bccx.loan_path_to_str(lp)));
433 format!("cannot assign to {} {}",
434 cmt.mutbl.to_user_str(),
435 self.bccx.cmt_to_str(cmt)));
440 fn mark_variable_as_used_mut(this: &CheckLoanCtxt,
442 //! If the mutability of the `cmt` being written is inherited
443 //! from a local variable, liveness will
444 //! not have been able to detect that this variable's mutability
445 //! is important, so we must add the variable to the
446 //! `used_mut_nodes` table here.
450 debug!("mark_writes_through_upvars_as_used_mut(cmt={})",
451 cmt.repr(this.tcx()));
453 mc::cat_local(id) | mc::cat_arg(id) => {
454 let mut used_mut_nodes = this.tcx()
457 used_mut_nodes.get().insert(id);
461 mc::cat_upvar(..) => {
465 mc::cat_deref(_, _, mc::GcPtr) => {
466 assert_eq!(cmt.mutbl, mc::McImmutable);
471 mc::cat_static_item |
472 mc::cat_copied_upvar(..) |
473 mc::cat_deref(_, _, mc::UnsafePtr(..)) |
474 mc::cat_deref(_, _, mc::BorrowedPtr(..)) => {
475 assert_eq!(cmt.mutbl, mc::McDeclared);
479 mc::cat_discr(b, _) |
480 mc::cat_deref(b, _, mc::OwnedPtr) => {
481 assert_eq!(cmt.mutbl, mc::McInherited);
485 mc::cat_downcast(b) |
486 mc::cat_interior(b, _) => {
487 assert_eq!(cmt.mutbl, mc::McInherited);
494 fn check_for_aliasable_mutable_writes(this: &CheckLoanCtxt,
496 cmt: mc::cmt) -> bool {
497 //! Safety checks related to writes to aliasable, mutable locations
499 let guarantor = cmt.guarantor();
500 debug!("check_for_aliasable_mutable_writes(cmt={}, guarantor={})",
501 cmt.repr(this.tcx()), guarantor.repr(this.tcx()));
502 match guarantor.cat {
503 mc::cat_deref(b, _, mc::BorrowedPtr(ty::MutBorrow, _)) => {
504 // Statically prohibit writes to `&mut` when aliasable
506 check_for_aliasability_violation(this, expr, b);
512 return true; // no errors reported
515 fn check_for_aliasability_violation(this: &CheckLoanCtxt,
519 match cmt.freely_aliasable() {
524 this.bccx.report_aliasability_violation(
533 fn check_for_assignment_to_restricted_or_frozen_location(
534 this: &CheckLoanCtxt,
536 cmt: mc::cmt) -> bool
538 //! Check for assignments that violate the terms of an
539 //! outstanding loan.
541 let loan_path = match opt_loan_path(cmt) {
543 None => { return true; /* no loan path, can't be any loans */ }
546 // Start by searching for an assignment to a *restricted*
547 // location. Here is one example of the kind of error caught
550 // let mut v = ~[1, 2, 3];
554 // In this case, creating `p` triggers a RESTR_MUTATE
555 // restriction on the path `v`.
557 // Here is a second, more subtle example:
559 // let mut v = ~[1, 2, 3];
560 // let p = &const v[0];
563 // v = ~[4, 5, 3]; // Error
565 // In this case, `p` is pointing to `v[0]`, and it is a
566 // `const` pointer in any case. So the first two
567 // assignments are legal (and would be permitted by this
568 // check). However, the final assignment (which is
569 // logically equivalent) is forbidden, because it would
570 // cause the existing `v` array to be freed, thus
571 // invalidating `p`. In the code, this error results
572 // because `gather_loans::restrictions` adds a
573 // `RESTR_MUTATE` restriction whenever the contents of an
574 // owned pointer are borrowed, and hence while `v[*]` is not
575 // restricted from being written, `v` is.
576 let cont = this.each_in_scope_restriction(expr.id,
579 if restr.set.intersects(RESTR_MUTATE) {
580 this.report_illegal_mutation(expr, loan_path, loan);
587 if !cont { return false }
589 // The previous code handled assignments to paths that
590 // have been restricted. This covers paths that have been
591 // directly lent out and their base paths, but does not
592 // cover random extensions of those paths. For example,
593 // the following program is not declared illegal by the
596 // let mut v = ~[1, 2, 3];
598 // v[0] = 4; // declared error by loop below, not code above
600 // The reason that this passes the previous check whereas
601 // an assignment like `v = ~[4]` fails is because the assignment
602 // here is to `v[*]`, and the existing restrictions were issued
603 // for `v`, not `v[*]`.
605 // So in this loop, we walk back up the loan path so long
606 // as the mutability of the path is dependent on a super
607 // path, and check that the super path was not lent out as
608 // mutable or immutable (a const loan is ok).
610 // Mutability of a path can be dependent on the super path
611 // in two ways. First, it might be inherited mutability.
612 // Second, the pointee of an `&mut` pointer can only be
613 // mutated if it is found in an unaliased location, so we
614 // have to check that the owner location is not borrowed.
616 // Note that we are *not* checking for any and all
617 // restrictions. We are only interested in the pointers
618 // that the user created, whereas we add restrictions for
619 // all kinds of paths that are not directly aliased. If we checked
620 // for all restrictions, and not just loans, then the following
621 // valid program would be considered illegal:
623 // let mut v = ~[1, 2, 3];
624 // let p = &const v[0];
627 // Here the restriction that `v` not be mutated would be misapplied
628 // to block the subpath `v[1]`.
629 let full_loan_path = loan_path;
630 let mut loan_path = loan_path;
633 // Peel back one layer if, for `loan_path` to be
634 // mutable, `lp_base` must be mutable. This occurs
635 // with inherited mutability and with `&mut`
637 LpExtend(lp_base, mc::McInherited, _) |
638 LpExtend(lp_base, _, LpDeref(mc::BorrowedPtr(ty::MutBorrow, _))) => {
642 // Otherwise stop iterating
643 LpExtend(_, mc::McDeclared, _) |
644 LpExtend(_, mc::McImmutable, _) |
650 // Check for a non-const loan of `loan_path`
651 let cont = this.each_in_scope_loan(expr.id, |loan| {
652 if loan.loan_path == loan_path {
653 this.report_illegal_mutation(expr, full_loan_path, loan);
660 if !cont { return false }
665 pub fn report_illegal_mutation(&self,
667 loan_path: &LoanPath,
671 format!("cannot assign to `{}` because it is borrowed",
672 self.bccx.loan_path_to_str(loan_path)));
675 format!("borrow of `{}` occurs here",
676 self.bccx.loan_path_to_str(loan_path)));
679 fn check_move_out_from_expr(&self, expr: &ast::Expr) {
681 ast::ExprFnBlock(..) | ast::ExprProc(..) => {
682 // Moves due to captures are checked in
683 // check_captured_variables() because it allows
684 // us to give a more precise error message with
685 // a more precise span.
688 self.check_move_out_from_id(expr.id, expr.span)
693 fn check_move_out_from_id(&self, id: ast::NodeId, span: Span) {
694 self.move_data.each_path_moved_by(id, |_, move_path| {
695 match self.analyze_move_out_from(id, move_path) {
697 MoveWhileBorrowed(loan_path, loan_span) => {
700 format!("cannot move out of `{}` \
701 because it is borrowed",
702 self.bccx.loan_path_to_str(move_path)));
705 format!("borrow of `{}` occurs here",
706 self.bccx.loan_path_to_str(loan_path)));
713 fn check_captured_variables(&self,
714 closure_id: ast::NodeId,
716 let capture_map = self.bccx.capture_map.borrow();
717 let cap_vars = capture_map.get().get(&closure_id);
718 for cap_var in cap_vars.borrow().iter() {
719 let var_id = ast_util::def_id_of_def(cap_var.def).node;
720 let var_path = @LpVar(var_id);
721 self.check_if_path_is_moved(closure_id, span,
722 MovedInCapture, var_path);
724 moves::CapRef | moves::CapCopy => {}
726 check_by_move_capture(self, closure_id, cap_var, var_path);
732 fn check_by_move_capture(this: &CheckLoanCtxt,
733 closure_id: ast::NodeId,
734 cap_var: &moves::CaptureVar,
735 move_path: @LoanPath) {
736 let move_err = this.analyze_move_out_from(closure_id, move_path);
739 MoveWhileBorrowed(loan_path, loan_span) => {
742 format!("cannot move `{}` into closure \
743 because it is borrowed",
744 this.bccx.loan_path_to_str(move_path)));
747 format!("borrow of `{}` occurs here",
748 this.bccx.loan_path_to_str(loan_path)));
754 pub fn analyze_move_out_from(&self,
755 expr_id: ast::NodeId,
756 mut move_path: @LoanPath)
758 debug!("analyze_move_out_from(expr_id={:?}, move_path={})",
759 self.tcx().map.node_to_str(expr_id),
760 move_path.repr(self.tcx()));
762 // We must check every element of a move path. See
763 // `borrowck-move-subcomponent.rs` for a test case.
765 // check for a conflicting loan:
766 let mut ret = MoveOk;
767 self.each_in_scope_restriction(expr_id, move_path, |loan, _| {
768 // Any restriction prevents moves.
769 ret = MoveWhileBorrowed(loan.loan_path, loan.span);
778 LpVar(_) => return MoveOk,
779 LpExtend(subpath, _, _) => move_path = subpath,
784 pub fn check_call(&self,
786 _callee: Option<@ast::Expr>,
787 _callee_id: ast::NodeId,
789 _args: &[@ast::Expr]) {
790 // NB: This call to check for conflicting loans is not truly
791 // necessary, because the callee_id never issues new loans.
792 // However, I added it for consistency and lest the system
793 // should change in the future.
795 // FIXME(#6268) nested method calls
796 // self.check_for_conflicting_loans(callee_id);
800 fn check_loans_in_local<'a>(this: &mut CheckLoanCtxt<'a>,
801 local: &ast::Local) {
802 visit::walk_local(this, local, ());
805 fn check_loans_in_expr<'a>(this: &mut CheckLoanCtxt<'a>,
807 visit::walk_expr(this, expr, ());
809 debug!("check_loans_in_expr(expr={})",
810 expr.repr(this.tcx()));
812 this.check_for_conflicting_loans(expr.id);
813 this.check_move_out_from_expr(expr);
815 let method_map = this.bccx.method_map.borrow();
817 ast::ExprPath(..) => {
818 if !this.move_data.is_assignee(expr.id) {
819 let cmt = this.bccx.cat_expr_unadjusted(expr);
820 debug!("path cmt={}", cmt.repr(this.tcx()));
821 let r = opt_loan_path(cmt);
822 for &lp in r.iter() {
823 this.check_if_path_is_moved(expr.id, expr.span, MovedInUse, lp);
827 ast::ExprFnBlock(..) | ast::ExprProc(..) => {
828 this.check_captured_variables(expr.id, expr.span)
830 ast::ExprAssign(dest, _) |
831 ast::ExprAssignOp(_, _, dest, _) => {
832 this.check_assignment(dest);
834 ast::ExprCall(f, ref args) => {
835 this.check_call(expr, Some(f), f.id, f.span, *args);
837 ast::ExprMethodCall(callee_id, _, _, ref args) => {
838 this.check_call(expr, None, callee_id, expr.span, *args);
840 ast::ExprIndex(callee_id, _, rval) |
841 ast::ExprBinary(callee_id, _, _, rval)
842 if method_map.get().contains_key(&expr.id) => {
843 this.check_call(expr, None, callee_id, expr.span, [rval]);
845 ast::ExprUnary(callee_id, _, _) | ast::ExprIndex(callee_id, _, _)
846 if method_map.get().contains_key(&expr.id) => {
847 this.check_call(expr, None, callee_id, expr.span, []);
849 ast::ExprInlineAsm(ref ia) => {
850 for &(_, out) in ia.outputs.iter() {
851 this.check_assignment(out);
858 fn check_loans_in_pat<'a>(this: &mut CheckLoanCtxt<'a>,
861 this.check_for_conflicting_loans(pat.id);
862 this.check_move_out_from_id(pat.id, pat.span);
863 visit::walk_pat(this, pat, ());
866 fn check_loans_in_block<'a>(this: &mut CheckLoanCtxt<'a>,
869 visit::walk_block(this, blk, ());
870 this.check_for_conflicting_loans(blk.id);