1 // Copyright 2012-2014 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 // The borrow check proceeds in two phases. In phase one, we gather the full
15 // set of loans that are required at any point. These are sorted according to
16 // their associated scopes. In phase two, checking loans, we will then make
17 // sure that all of these loans are honored.
20 use borrowck::move_data::MoveData;
21 use rustc::middle::expr_use_visitor as euv;
22 use rustc::middle::mem_categorization as mc;
23 use rustc::middle::mem_categorization::Categorization;
24 use rustc::middle::region;
25 use rustc::ty::{self, TyCtxt};
31 use self::restrictions::RestrictionResult;
38 pub fn gather_loans_in_fn<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
40 -> (Vec<Loan<'tcx>>, move_data::MoveData<'tcx>) {
41 let def_id = bccx.tcx.hir.body_owner_def_id(body);
42 let param_env = bccx.tcx.param_env(def_id);
43 let mut glcx = GatherLoanCtxt {
45 all_loans: Vec::new(),
46 item_ub: region::CodeExtent::Misc(body.node_id),
47 move_data: MoveData::new(),
48 move_error_collector: move_error::MoveErrorCollector::new(),
51 let body = glcx.bccx.tcx.hir.body(body);
52 let infcx = bccx.tcx.borrowck_fake_infer_ctxt();
53 euv::ExprUseVisitor::new(&mut glcx, &infcx, param_env, &bccx.region_maps, bccx.tables)
56 glcx.report_potential_errors();
57 let GatherLoanCtxt { all_loans, move_data, .. } = glcx;
58 (all_loans, move_data)
61 struct GatherLoanCtxt<'a, 'tcx: 'a> {
62 bccx: &'a BorrowckCtxt<'a, 'tcx>,
63 move_data: move_data::MoveData<'tcx>,
64 move_error_collector: move_error::MoveErrorCollector<'tcx>,
65 all_loans: Vec<Loan<'tcx>>,
66 /// `item_ub` is used as an upper-bound on the lifetime whenever we
67 /// ask for the scope of an expression categorized as an upvar.
68 item_ub: region::CodeExtent,
71 impl<'a, 'tcx> euv::Delegate<'tcx> for GatherLoanCtxt<'a, 'tcx> {
73 consume_id: ast::NodeId,
76 mode: euv::ConsumeMode) {
77 debug!("consume(consume_id={}, cmt={:?}, mode={:?})",
78 consume_id, cmt, mode);
81 euv::Move(move_reason) => {
82 gather_moves::gather_move_from_expr(
83 self.bccx, &self.move_data, &mut self.move_error_collector,
84 consume_id, cmt, move_reason);
90 fn matched_pat(&mut self,
91 matched_pat: &hir::Pat,
93 mode: euv::MatchMode) {
94 debug!("matched_pat(matched_pat={:?}, cmt={:?}, mode={:?})",
99 if let Categorization::Downcast(..) = cmt.cat {
100 gather_moves::gather_match_variant(
101 self.bccx, &self.move_data, &mut self.move_error_collector,
102 matched_pat, cmt, mode);
106 fn consume_pat(&mut self,
107 consume_pat: &hir::Pat,
109 mode: euv::ConsumeMode) {
110 debug!("consume_pat(consume_pat={:?}, cmt={:?}, mode={:?})",
116 euv::Copy => { return; }
120 gather_moves::gather_move_from_pat(
121 self.bccx, &self.move_data, &mut self.move_error_collector,
126 borrow_id: ast::NodeId,
129 loan_region: ty::Region<'tcx>,
131 loan_cause: euv::LoanCause)
133 debug!("borrow(borrow_id={}, cmt={:?}, loan_region={:?}, \
134 bk={:?}, loan_cause={:?})",
135 borrow_id, cmt, loan_region,
138 self.guarantee_valid(borrow_id,
147 assignment_id: ast::NodeId,
148 assignment_span: Span,
149 assignee_cmt: mc::cmt<'tcx>,
150 mode: euv::MutateMode)
152 self.guarantee_assignment_valid(assignment_id,
158 fn decl_without_init(&mut self, id: ast::NodeId, _span: Span) {
159 let ty = self.bccx.tables.node_id_to_type(id);
160 gather_moves::gather_decl(self.bccx, &self.move_data, id, ty);
164 /// Implements the A-* rules in README.md.
165 fn check_aliasability<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
167 loan_cause: AliasableViolationKind,
169 req_kind: ty::BorrowKind)
172 let aliasability = cmt.freely_aliasable();
173 debug!("check_aliasability aliasability={:?} req_kind={:?}",
174 aliasability, req_kind);
176 match (aliasability, req_kind) {
177 (mc::Aliasability::NonAliasable, _) => {
178 /* Uniquely accessible path -- OK for `&` and `&mut` */
181 (mc::Aliasability::FreelyAliasable(mc::AliasableStatic), ty::ImmBorrow) => {
182 // Borrow of an immutable static item.
185 (mc::Aliasability::FreelyAliasable(mc::AliasableStaticMut), _) => {
186 // Even touching a static mut is considered unsafe. We assume the
187 // user knows what they're doing in these cases.
190 (mc::Aliasability::FreelyAliasable(alias_cause), ty::UniqueImmBorrow) |
191 (mc::Aliasability::FreelyAliasable(alias_cause), ty::MutBorrow) => {
192 bccx.report_aliasability_violation(
205 /// Implements the M-* rules in README.md.
206 fn check_mutability<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
208 cause: AliasableViolationKind,
210 req_kind: ty::BorrowKind)
212 debug!("check_mutability(cause={:?} cmt={:?} req_kind={:?}",
213 cause, cmt, req_kind);
215 ty::UniqueImmBorrow | ty::ImmBorrow => {
217 // I am intentionally leaving this here to help
218 // refactoring if, in the future, we should add new
219 // kinds of mutability.
220 mc::McImmutable | mc::McDeclared | mc::McInherited => {
221 // both imm and mut data can be lent as imm;
222 // for mutable data, this is a freeze
229 // Only mutable data can be lent as mutable.
230 if !cmt.mutbl.is_mutable() {
231 Err(bccx.report(BckError { span: borrow_span,
242 impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> {
243 pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.bccx.tcx }
245 /// Guarantees that `cmt` is assignable, or reports an error.
246 fn guarantee_assignment_valid(&mut self,
247 assignment_id: ast::NodeId,
248 assignment_span: Span,
250 mode: euv::MutateMode) {
252 let opt_lp = opt_loan_path(&cmt);
253 debug!("guarantee_assignment_valid(assignment_id={}, cmt={:?}) opt_lp={:?}",
254 assignment_id, cmt, opt_lp);
256 if let Categorization::Local(..) = cmt.cat {
257 // Only re-assignments to locals require it to be
258 // mutable - this is checked in check_loans.
260 // Check that we don't allow assignments to non-mutable data.
261 if check_mutability(self.bccx, assignment_span, MutabilityViolation,
262 cmt.clone(), ty::MutBorrow).is_err() {
263 return; // reported an error, no sense in reporting more.
267 // Check that we don't allow assignments to aliasable data
268 if check_aliasability(self.bccx, assignment_span, MutabilityViolation,
269 cmt.clone(), ty::MutBorrow).is_err() {
270 return; // reported an error, no sense in reporting more.
275 if let Categorization::Local(..) = cmt.cat {
276 // Only re-assignments to locals require it to be
277 // mutable - this is checked in check_loans.
279 self.mark_loan_path_as_mutated(&lp);
281 gather_moves::gather_assignment(self.bccx, &self.move_data,
282 assignment_id, assignment_span,
286 // This can occur with e.g. `*foo() = 5`. In such
287 // cases, there is no need to check for conflicts
288 // with moves etc, just ignore.
293 /// Guarantees that `addr_of(cmt)` will be valid for the duration of `static_scope_r`, or
294 /// reports an error. This may entail taking out loans, which will be added to the
296 fn guarantee_valid(&mut self,
297 borrow_id: ast::NodeId,
300 req_kind: ty::BorrowKind,
301 loan_region: ty::Region<'tcx>,
302 cause: euv::LoanCause) {
303 debug!("guarantee_valid(borrow_id={}, cmt={:?}, \
304 req_mutbl={:?}, loan_region={:?})",
310 // a loan for the empty region can never be dereferenced, so
312 if *loan_region == ty::ReEmpty {
316 // Check that the lifetime of the borrow does not exceed
317 // the lifetime of the data being borrowed.
318 if lifetime::guarantee_lifetime(self.bccx, self.item_ub,
319 borrow_span, cause, cmt.clone(), loan_region,
321 return; // reported an error, no sense in reporting more.
324 // Check that we don't allow mutable borrows of non-mutable data.
325 if check_mutability(self.bccx, borrow_span, BorrowViolation(cause),
326 cmt.clone(), req_kind).is_err() {
327 return; // reported an error, no sense in reporting more.
330 // Check that we don't allow mutable borrows of aliasable data.
331 if check_aliasability(self.bccx, borrow_span, BorrowViolation(cause),
332 cmt.clone(), req_kind).is_err() {
333 return; // reported an error, no sense in reporting more.
336 // Compute the restrictions that are required to enforce the
338 let restr = restrictions::compute_restrictions(
339 self.bccx, borrow_span, cause,
340 cmt.clone(), loan_region);
342 debug!("guarantee_valid(): restrictions={:?}", restr);
344 // Create the loan record (if needed).
345 let loan = match restr {
346 RestrictionResult::Safe => {
347 // No restrictions---no loan record necessary
351 RestrictionResult::SafeIf(loan_path, restricted_paths) => {
352 let loan_scope = match *loan_region {
353 ty::ReScope(scope) => scope,
355 ty::ReEarlyBound(ref br) => {
356 self.bccx.region_maps.early_free_extent(self.tcx(), br)
359 ty::ReFree(ref fr) => {
360 self.bccx.region_maps.free_extent(self.tcx(), fr)
363 ty::ReStatic => self.item_ub,
366 ty::ReLateBound(..) |
368 ty::ReSkolemized(..) |
372 "invalid borrow lifetime: {:?}",
376 debug!("loan_scope = {:?}", loan_scope);
378 let borrow_scope = region::CodeExtent::Misc(borrow_id);
379 let gen_scope = self.compute_gen_scope(borrow_scope, loan_scope);
380 debug!("gen_scope = {:?}", gen_scope);
382 let kill_scope = self.compute_kill_scope(loan_scope, &loan_path);
383 debug!("kill_scope = {:?}", kill_scope);
385 if req_kind == ty::MutBorrow {
386 self.mark_loan_path_as_mutated(&loan_path);
390 index: self.all_loans.len(),
391 loan_path: loan_path,
393 gen_scope: gen_scope,
394 kill_scope: kill_scope,
396 restricted_paths: restricted_paths,
402 debug!("guarantee_valid(borrow_id={}), loan={:?}",
405 // let loan_path = loan.loan_path;
406 // let loan_gen_scope = loan.gen_scope;
407 // let loan_kill_scope = loan.kill_scope;
408 self.all_loans.push(loan);
410 // if loan_gen_scope != borrow_id {
411 // FIXME(#6268) Nested method calls
413 // Typically, the scope of the loan includes the point at
414 // which the loan is originated. This
415 // This is a subtle case. See the test case
416 // <compile-fail/borrowck-bad-nested-calls-free.rs>
417 // to see what we are guarding against.
419 //let restr = restrictions::compute_restrictions(
420 // self.bccx, borrow_span, cmt, RESTR_EMPTY);
422 // let all_loans = &mut *self.all_loans; // FIXME(#5074)
424 // index: all_loans.len(),
425 // loan_path: loan_path,
427 // mutbl: ConstMutability,
428 // gen_scope: borrow_id,
429 // kill_scope: kill_scope,
430 // span: borrow_span,
431 // restrictions: restrictions
436 pub fn mark_loan_path_as_mutated(&self, loan_path: &LoanPath) {
437 //! For mutable loans of content whose mutability derives
438 //! from a local variable, mark the mutability decl as necessary.
440 match loan_path.kind {
442 LpUpvar(ty::UpvarId{ var_id: local_id, closure_expr_id: _ }) => {
443 self.tcx().used_mut_nodes.borrow_mut().insert(local_id);
445 LpDowncast(ref base, _) |
446 LpExtend(ref base, mc::McInherited, _) |
447 LpExtend(ref base, mc::McDeclared, _) => {
448 self.mark_loan_path_as_mutated(&base);
450 LpExtend(_, mc::McImmutable, _) => {
456 pub fn compute_gen_scope(&self,
457 borrow_scope: region::CodeExtent,
458 loan_scope: region::CodeExtent)
459 -> region::CodeExtent {
460 //! Determine when to introduce the loan. Typically the loan
461 //! is introduced at the point of the borrow, but in some cases,
462 //! notably method arguments, the loan may be introduced only
463 //! later, once it comes into scope.
465 if self.bccx.region_maps.is_subscope_of(borrow_scope, loan_scope) {
472 pub fn compute_kill_scope(&self, loan_scope: region::CodeExtent, lp: &LoanPath<'tcx>)
473 -> region::CodeExtent {
474 //! Determine when the loan restrictions go out of scope.
475 //! This is either when the lifetime expires or when the
476 //! local variable which roots the loan-path goes out of scope,
477 //! whichever happens faster.
479 //! It may seem surprising that we might have a loan region
480 //! larger than the variable which roots the loan-path; this can
481 //! come about when variables of `&mut` type are re-borrowed,
482 //! as in this example:
484 //! struct Foo { counter: u32 }
486 //! fn counter<'a>(v: &'a mut Foo) -> &'a mut u32 {
490 //! In this case, the reference (`'a`) outlives the
491 //! variable `v` that hosts it. Note that this doesn't come up
492 //! with immutable `&` pointers, because borrows of such pointers
493 //! do not require restrictions and hence do not cause a loan.
495 let lexical_scope = lp.kill_scope(self.bccx);
496 if self.bccx.region_maps.is_subscope_of(lexical_scope, loan_scope) {
499 assert!(self.bccx.region_maps.is_subscope_of(loan_scope, lexical_scope));
504 pub fn report_potential_errors(&self) {
505 self.move_error_collector.report_potential_errors(self.bccx);