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 //! See The Book chapter on the borrow checker for more details.
13 #![allow(non_camel_case_types)]
15 pub use self::LoanPathKind::*;
16 pub use self::LoanPathElem::*;
17 pub use self::bckerr_code::*;
18 pub use self::AliasableViolationKind::*;
19 pub use self::MovedValueUseKind::*;
21 use self::InteriorKind::*;
23 use rustc::hir::map as hir_map;
24 use rustc::hir::map::blocks::FnLikeNode;
26 use rustc::middle::dataflow::DataFlowContext;
27 use rustc::middle::dataflow::BitwiseOperator;
28 use rustc::middle::dataflow::DataFlowOperator;
29 use rustc::middle::dataflow::KillFrom;
30 use rustc::hir::def_id::DefId;
31 use rustc::middle::expr_use_visitor as euv;
32 use rustc::middle::mem_categorization as mc;
33 use rustc::middle::mem_categorization::Categorization;
34 use rustc::middle::mem_categorization::ImmutabilityBlame;
35 use rustc::middle::region::{self, RegionMaps};
36 use rustc::middle::free_region::RegionRelations;
37 use rustc::ty::{self, TyCtxt};
38 use rustc::ty::maps::Providers;
42 use std::hash::{Hash, Hasher};
44 use syntax_pos::{MultiSpan, Span};
45 use errors::DiagnosticBuilder;
48 use rustc::hir::intravisit::{self, Visitor};
56 #[derive(Clone, Copy)]
57 pub struct LoanDataFlowOperator;
59 pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
61 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
62 for body_owner_def_id in tcx.body_owners() {
63 tcx.borrowck(body_owner_def_id);
67 pub fn provide(providers: &mut Providers) {
68 *providers = Providers {
74 /// Collection of conclusions determined via borrow checker analyses.
75 pub struct AnalysisData<'a, 'tcx: 'a> {
76 pub all_loans: Vec<Loan<'tcx>>,
77 pub loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>,
78 pub move_data: move_data::FlowedMoveData<'a, 'tcx>,
81 fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId) {
82 debug!("borrowck(body_owner_def_id={:?})", owner_def_id);
84 let owner_id = tcx.hir.as_local_node_id(owner_def_id).unwrap();
86 match tcx.hir.get(owner_id) {
87 hir_map::NodeStructCtor(_) |
88 hir_map::NodeVariant(_) => {
89 // We get invoked with anything that has MIR, but some of
90 // those things (notably the synthesized constructors from
91 // tuple structs/variants) do not have an associated body
92 // and do not need borrowchecking.
98 let body_id = tcx.hir.body_owned_by(owner_id);
99 let tables = tcx.typeck_tables_of(owner_def_id);
100 let region_maps = tcx.region_maps(owner_def_id);
101 let body = tcx.hir.body(body_id);
102 let mut bccx = &mut BorrowckCtxt { tcx, tables, region_maps, owner_def_id, body };
104 // Eventually, borrowck will always read the MIR, but at the
105 // moment we do not. So, for now, we always force MIR to be
106 // constructed for a given fn, since this may result in errors
107 // being reported and we want that to happen.
109 // Note that `mir_validated` is a "stealable" result; the
110 // thief, `optimized_mir()`, forces borrowck, so we know that
111 // is not yet stolen.
112 tcx.mir_validated(owner_def_id).borrow();
114 let cfg = cfg::CFG::new(bccx.tcx, &body);
115 let AnalysisData { all_loans,
117 move_data: flowed_moves } =
118 build_borrowck_dataflow_data(bccx, &cfg, body_id);
120 check_loans::check_loans(bccx, &loan_dfcx, &flowed_moves, &all_loans, body);
123 fn build_borrowck_dataflow_data<'a, 'tcx>(this: &mut BorrowckCtxt<'a, 'tcx>,
125 body_id: hir::BodyId)
126 -> AnalysisData<'a, 'tcx>
128 // Check the body of fn items.
131 let mut visitor = intravisit::IdRangeComputingVisitor::new(&tcx.hir);
132 visitor.visit_body(this.body);
135 let (all_loans, move_data) =
136 gather_loans::gather_loans_in_fn(this, body_id);
139 DataFlowContext::new(this.tcx,
143 LoanDataFlowOperator,
146 for (loan_idx, loan) in all_loans.iter().enumerate() {
147 loan_dfcx.add_gen(loan.gen_scope.node_id(), loan_idx);
148 loan_dfcx.add_kill(KillFrom::ScopeEnd,
149 loan.kill_scope.node_id(), loan_idx);
151 loan_dfcx.add_kills_from_flow_exits(cfg);
152 loan_dfcx.propagate(cfg, this.body);
154 let flowed_moves = move_data::FlowedMoveData::new(move_data,
160 AnalysisData { all_loans: all_loans,
162 move_data:flowed_moves }
165 /// Accessor for introspective clients inspecting `AnalysisData` and
166 /// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer.
167 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
168 tcx: TyCtxt<'a, 'tcx, 'tcx>,
169 body_id: hir::BodyId,
171 -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
173 let owner_id = tcx.hir.body_owner(body_id);
174 let owner_def_id = tcx.hir.local_def_id(owner_id);
175 let tables = tcx.typeck_tables_of(owner_def_id);
176 let region_maps = tcx.region_maps(owner_def_id);
177 let body = tcx.hir.body(body_id);
178 let mut bccx = BorrowckCtxt { tcx, tables, region_maps, owner_def_id, body };
180 let dataflow_data = build_borrowck_dataflow_data(&mut bccx, cfg, body_id);
181 (bccx, dataflow_data)
184 // ----------------------------------------------------------------------
187 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
188 tcx: TyCtxt<'a, 'tcx, 'tcx>,
190 // tables for the current thing we are checking; set to
191 // Some in `borrowck_fn` and cleared later
192 tables: &'a ty::TypeckTables<'tcx>,
194 region_maps: Rc<RegionMaps>,
198 body: &'tcx hir::Body,
201 ///////////////////////////////////////////////////////////////////////////
202 // Loans and loan paths
204 /// Record of a loan that was issued.
205 pub struct Loan<'tcx> {
207 loan_path: Rc<LoanPath<'tcx>>,
208 kind: ty::BorrowKind,
209 restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
211 /// gen_scope indicates where loan is introduced. Typically the
212 /// loan is introduced at the point of the borrow, but in some
213 /// cases, notably method arguments, the loan may be introduced
214 /// only later, once it comes into scope. See also
215 /// `GatherLoanCtxt::compute_gen_scope`.
216 gen_scope: region::CodeExtent,
218 /// kill_scope indicates when the loan goes out of scope. This is
219 /// either when the lifetime expires or when the local variable
220 /// which roots the loan-path goes out of scope, whichever happens
221 /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
222 kill_scope: region::CodeExtent,
224 cause: euv::LoanCause,
227 impl<'tcx> Loan<'tcx> {
228 pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
229 self.loan_path.clone()
234 pub struct LoanPath<'tcx> {
235 kind: LoanPathKind<'tcx>,
239 impl<'tcx> PartialEq for LoanPath<'tcx> {
240 fn eq(&self, that: &LoanPath<'tcx>) -> bool {
241 self.kind == that.kind
245 impl<'tcx> Hash for LoanPath<'tcx> {
246 fn hash<H: Hasher>(&self, state: &mut H) {
247 self.kind.hash(state);
251 #[derive(PartialEq, Eq, Hash, Debug)]
252 pub enum LoanPathKind<'tcx> {
253 LpVar(ast::NodeId), // `x` in README.md
254 LpUpvar(ty::UpvarId), // `x` captured by-value into closure
255 LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
256 LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem<'tcx>)
259 impl<'tcx> LoanPath<'tcx> {
260 fn new(kind: LoanPathKind<'tcx>, ty: ty::Ty<'tcx>) -> LoanPath<'tcx> {
261 LoanPath { kind: kind, ty: ty }
264 fn to_type(&self) -> ty::Ty<'tcx> { self.ty }
267 // FIXME (pnkfelix): See discussion here
268 // https://github.com/pnkfelix/rust/commit/
269 // b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
270 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
272 // A local, "cleaned" version of `mc::InteriorKind` that drops
273 // information that is not relevant to loan-path analysis. (In
274 // particular, the distinction between how precisely an array-element
275 // is tracked is irrelevant here.)
276 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
277 pub enum InteriorKind {
278 InteriorField(mc::FieldName),
282 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
283 impl ToInteriorKind for mc::InteriorKind {
284 fn cleaned(self) -> InteriorKind {
286 mc::InteriorField(name) => InteriorField(name),
287 mc::InteriorElement(_) => InteriorElement,
293 // - a pointer dereference (`*LV` in README.md)
294 // - a field reference, with an optional definition of the containing
295 // enum variant (`LV.f` in README.md)
296 // `DefId` is present when the field is part of struct that is in
297 // a variant of an enum. For instance in:
298 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
299 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
300 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
301 pub enum LoanPathElem<'tcx> {
302 LpDeref(mc::PointerKind<'tcx>),
303 LpInterior(Option<DefId>, InteriorKind),
306 pub fn closure_to_block(closure_id: ast::NodeId,
307 tcx: TyCtxt) -> ast::NodeId {
308 match tcx.hir.get(closure_id) {
309 hir_map::NodeExpr(expr) => match expr.node {
310 hir::ExprClosure(.., body_id, _, _) => {
314 bug!("encountered non-closure id: {}", closure_id)
317 _ => bug!("encountered non-expr id: {}", closure_id)
321 impl<'a, 'tcx> LoanPath<'tcx> {
322 pub fn kill_scope(&self, bccx: &BorrowckCtxt<'a, 'tcx>) -> region::CodeExtent {
324 LpVar(local_id) => bccx.region_maps.var_scope(local_id),
325 LpUpvar(upvar_id) => {
326 let block_id = closure_to_block(upvar_id.closure_expr_id, bccx.tcx);
327 region::CodeExtent::Misc(block_id)
329 LpDowncast(ref base, _) |
330 LpExtend(ref base, ..) => base.kill_scope(bccx),
334 fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
335 match (&self.kind, &other.kind) {
336 (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
337 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
338 if id == id2 && opt_variant_id == opt_variant_id2 {
339 base.has_fork(&base2)
343 (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
344 (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&base),
349 fn depth(&self) -> usize {
351 LpExtend(ref base, _, LpDeref(_)) => base.depth(),
352 LpExtend(ref base, _, LpInterior(..)) => base.depth() + 1,
357 fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
358 match (&self.kind, &other.kind) {
359 (&LpExtend(ref base, a, LpInterior(opt_variant_id, id)),
360 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) => {
361 if id == id2 && opt_variant_id == opt_variant_id2 {
362 base.common(&base2).map(|x| {
364 if base.depth() == xd && base2.depth() == xd {
366 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
377 (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
378 (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&other),
379 (&LpVar(id), &LpVar(id2)) => {
381 Some(LoanPath { kind: LpVar(id), ty: self.ty })
386 (&LpUpvar(id), &LpUpvar(id2)) => {
388 Some(LoanPath { kind: LpUpvar(id), ty: self.ty })
398 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
399 //! Computes the `LoanPath` (if any) for a `cmt`.
400 //! Note that this logic is somewhat duplicated in
401 //! the method `compute()` found in `gather_loans::restrictions`,
402 //! which allows it to share common loan path pieces as it
403 //! traverses the CMT.
405 let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
408 Categorization::Rvalue(..) |
409 Categorization::StaticItem => {
413 Categorization::Local(id) => {
414 Some(new_lp(LpVar(id)))
417 Categorization::Upvar(mc::Upvar { id, .. }) => {
418 Some(new_lp(LpUpvar(id)))
421 Categorization::Deref(ref cmt_base, pk) => {
422 opt_loan_path(cmt_base).map(|lp| {
423 new_lp(LpExtend(lp, cmt.mutbl, LpDeref(pk)))
427 Categorization::Interior(ref cmt_base, ik) => {
428 opt_loan_path(cmt_base).map(|lp| {
429 let opt_variant_id = match cmt_base.cat {
430 Categorization::Downcast(_, did) => Some(did),
433 new_lp(LpExtend(lp, cmt.mutbl, LpInterior(opt_variant_id, ik.cleaned())))
437 Categorization::Downcast(ref cmt_base, variant_def_id) =>
438 opt_loan_path(cmt_base)
440 new_lp(LpDowncast(lp, variant_def_id))
446 ///////////////////////////////////////////////////////////////////////////
449 // Errors that can occur
450 #[derive(Debug, PartialEq)]
451 pub enum bckerr_code<'tcx> {
453 /// superscope, subscope, loan cause
454 err_out_of_scope(ty::Region<'tcx>, ty::Region<'tcx>, euv::LoanCause),
455 err_borrowed_pointer_too_short(ty::Region<'tcx>, ty::Region<'tcx>), // loan, ptr
458 // Combination of an error code and the categorization of the expression
460 #[derive(Debug, PartialEq)]
461 pub struct BckError<'tcx> {
463 cause: AliasableViolationKind,
465 code: bckerr_code<'tcx>
468 #[derive(Copy, Clone, Debug, PartialEq)]
469 pub enum AliasableViolationKind {
471 BorrowViolation(euv::LoanCause)
474 #[derive(Copy, Clone, Debug)]
475 pub enum MovedValueUseKind {
480 ///////////////////////////////////////////////////////////////////////////
483 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
484 pub fn is_subregion_of(&self,
485 r_sub: ty::Region<'tcx>,
486 r_sup: ty::Region<'tcx>)
489 let region_rels = RegionRelations::new(self.tcx,
492 &self.tables.free_region_map);
493 region_rels.is_subregion_of(r_sub, r_sup)
496 pub fn report(&self, err: BckError<'tcx>) {
497 // Catch and handle some particular cases.
498 match (&err.code, &err.cause) {
499 (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _),
500 &BorrowViolation(euv::ClosureCapture(span))) |
501 (&err_out_of_scope(&ty::ReScope(_), &ty::ReEarlyBound(..), _),
502 &BorrowViolation(euv::ClosureCapture(span))) |
503 (&err_out_of_scope(&ty::ReScope(_), &ty::ReFree(..), _),
504 &BorrowViolation(euv::ClosureCapture(span))) => {
505 return self.report_out_of_scope_escaping_closure_capture(&err, span);
510 self.report_bckerr(&err);
513 pub fn report_use_of_moved_value(&self,
515 use_kind: MovedValueUseKind,
517 the_move: &move_data::Move,
518 moved_lp: &LoanPath<'tcx>,
519 _param_env: ty::ParamEnv<'tcx>) {
520 let (verb, verb_participle) = match use_kind {
521 MovedInUse => ("use", "used"),
522 MovedInCapture => ("capture", "captured"),
525 let (_ol, _moved_lp_msg, mut err, need_note) = match the_move.kind {
526 move_data::Declared => {
527 // If this is an uninitialized variable, just emit a simple warning
530 self.tcx.sess, use_span, E0381,
531 "{} of possibly uninitialized variable: `{}`",
533 self.loan_path_to_string(lp))
534 .span_label(use_span, format!("use of possibly uninitialized `{}`",
535 self.loan_path_to_string(lp)))
540 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
541 // normally generate a rather confusing message:
543 // error: use of moved value: `x.b`
544 // note: `x.a` moved here...
546 // What we want to do instead is get the 'common ancestor' of the two moves and
547 // use that for most of the message instead, giving is something like this:
549 // error: use of moved value: `x`
550 // note: `x` moved here (through moving `x.a`)...
552 let common = moved_lp.common(lp);
553 let has_common = common.is_some();
554 let has_fork = moved_lp.has_fork(lp);
555 let (nl, ol, moved_lp_msg) =
556 if has_fork && has_common {
557 let nl = self.loan_path_to_string(&common.unwrap());
559 let moved_lp_msg = format!(" (through moving `{}`)",
560 self.loan_path_to_string(moved_lp));
561 (nl, ol, moved_lp_msg)
563 (self.loan_path_to_string(lp),
564 self.loan_path_to_string(moved_lp),
568 let partial = moved_lp.depth() > lp.depth();
569 let msg = if !has_fork && partial { "partially " }
570 else if has_fork && !has_common { "collaterally "}
572 let mut err = struct_span_err!(
573 self.tcx.sess, use_span, E0382,
574 "{} of {}moved value: `{}`",
576 let need_note = match lp.ty.sty {
577 ty::TypeVariants::TyClosure(id, _) => {
578 let node_id = self.tcx.hir.as_local_node_id(id).unwrap();
579 if let Some(&(ty::ClosureKind::FnOnce, Some((span, name)))) =
580 self.tables.closure_kinds.get(&node_id)
582 err.span_note(span, &format!(
583 "closure cannot be invoked more than once because \
584 it moves the variable `{}` out of its environment",
594 (ol, moved_lp_msg, err, need_note)
598 // Get type of value and span where it was previously
600 let (move_span, move_note) = match the_move.kind {
601 move_data::Declared => {
605 move_data::MoveExpr |
606 move_data::MovePat =>
607 (self.tcx.hir.span(the_move.id), ""),
609 move_data::Captured =>
610 (match self.tcx.hir.expect_expr(the_move.id).node {
611 hir::ExprClosure(.., fn_decl_span, _) => fn_decl_span,
612 ref r => bug!("Captured({}) maps to non-closure: {:?}",
614 }, " (into closure)"),
617 // Annotate the use and the move in the span. Watch out for
618 // the case where the use and the move are the same. This
619 // means the use is in a loop.
620 err = if use_span == move_span {
623 format!("value moved{} here in previous iteration of loop",
627 err.span_label(use_span, format!("value {} here after move", verb_participle))
628 .span_label(move_span, format!("value moved{} here", move_note));
633 err.note(&format!("move occurs because `{}` has type `{}`, \
634 which does not implement the `Copy` trait",
635 self.loan_path_to_string(moved_lp),
639 // Note: we used to suggest adding a `ref binding` or calling
640 // `clone` but those suggestions have been removed because
641 // they are often not what you actually want to do, and were
642 // not considered particularly helpful.
647 pub fn report_partial_reinitialization_of_uninitialized_structure(
650 lp: &LoanPath<'tcx>) {
652 self.tcx.sess, span, E0383,
653 "partial reinitialization of uninitialized structure `{}`",
654 self.loan_path_to_string(lp));
657 pub fn report_reassigned_immutable_variable(&self,
661 &move_data::Assignment) {
662 let mut err = struct_span_err!(
663 self.tcx.sess, span, E0384,
664 "re-assignment of immutable variable `{}`",
665 self.loan_path_to_string(lp));
666 err.span_label(span, "re-assignment of immutable variable");
667 if span != assign.span {
668 err.span_label(assign.span, format!("first assignment to `{}`",
669 self.loan_path_to_string(lp)));
674 pub fn span_err(&self, s: Span, m: &str) {
675 self.tcx.sess.span_err(s, m);
678 pub fn struct_span_err<S: Into<MultiSpan>>(&self, s: S, m: &str)
679 -> DiagnosticBuilder<'a> {
680 self.tcx.sess.struct_span_err(s, m)
683 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(&self,
687 -> DiagnosticBuilder<'a> {
688 self.tcx.sess.struct_span_err_with_code(s, msg, code)
691 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, s: S, msg: &str, code: &str) {
692 self.tcx.sess.span_err_with_code(s, msg, code);
695 fn report_bckerr(&self, err: &BckError<'tcx>) {
696 let error_span = err.span.clone();
700 let descr = match err.cmt.note {
701 mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
702 self.cmt_to_string(&err.cmt)
704 _ => match opt_loan_path(&err.cmt) {
707 err.cmt.mutbl.to_user_str(),
708 self.cmt_to_string(&err.cmt))
712 format!("{} {} `{}`",
713 err.cmt.mutbl.to_user_str(),
714 self.cmt_to_string(&err.cmt),
715 self.loan_path_to_string(&lp))
720 let mut db = match err.cause {
721 MutabilityViolation => {
722 struct_span_err!(self.tcx.sess, error_span, E0594, "cannot assign to {}", descr)
724 BorrowViolation(euv::ClosureCapture(_)) => {
725 struct_span_err!(self.tcx.sess, error_span, E0595,
726 "closure cannot assign to {}", descr)
728 BorrowViolation(euv::OverloadedOperator) |
729 BorrowViolation(euv::AddrOf) |
730 BorrowViolation(euv::RefBinding) |
731 BorrowViolation(euv::AutoRef) |
732 BorrowViolation(euv::AutoUnsafe) |
733 BorrowViolation(euv::ForLoop) |
734 BorrowViolation(euv::MatchDiscriminant) => {
735 struct_span_err!(self.tcx.sess, error_span, E0596,
736 "cannot borrow {} as mutable", descr)
738 BorrowViolation(euv::ClosureInvocation) => {
740 "err_mutbl with a closure invocation");
744 self.note_and_explain_mutbl_error(&mut db, &err, &error_span);
745 self.note_immutability_blame(&mut db, err.cmt.immutability_blame());
748 err_out_of_scope(super_scope, sub_scope, cause) => {
749 let msg = match opt_loan_path(&err.cmt) {
750 None => "borrowed value".to_string(),
752 format!("`{}`", self.loan_path_to_string(&lp))
756 // When you have a borrow that lives across a yield,
757 // that reference winds up captured in the generator
758 // type. Regionck then constraints it to live as long
759 // as the generator itself. If that borrow is borrowing
760 // data owned by the generator, this winds up resulting in
761 // an `err_out_of_scope` error:
766 // let a = &3; // this borrow is forced to ... -+
768 // println!("{}", a); // |
770 // } <----------------------... live until here --------+
773 // To detect this case, we look for cases where the
774 // `super_scope` (lifetime of the value) is within the
775 // body, but the `sub_scope` is not.
776 debug!("err_out_of_scope: self.body.is_generator = {:?}",
777 self.body.is_generator);
778 let maybe_borrow_across_yield = if self.body.is_generator {
779 let body_extent = region::CodeExtent::Misc(self.body.id().node_id);
780 debug!("err_out_of_scope: body_extent = {:?}", body_extent);
781 debug!("err_out_of_scope: super_scope = {:?}", super_scope);
782 debug!("err_out_of_scope: sub_scope = {:?}", sub_scope);
783 match (super_scope, sub_scope) {
784 (&ty::RegionKind::ReScope(value_extent),
785 &ty::RegionKind::ReScope(loan_extent)) => {
787 // value_extent <= body_extent &&
788 self.region_maps.is_subscope_of(value_extent, body_extent) &&
789 // body_extent <= loan_extent
790 self.region_maps.is_subscope_of(body_extent, loan_extent)
792 // We now know that this is a case
793 // that fits the bill described above:
794 // a borrow of something whose scope
795 // is within the generator, but the
796 // borrow is for a scope outside the
799 // Now look within the scope of the of
800 // the value being borrowed (in the
801 // example above, that would be the
802 // block remainder that starts with
803 // `let a`) for a yield. We can cite
804 // that for the user.
805 self.tcx.yield_in_extent(value_extent)
816 if let Some(yield_span) = maybe_borrow_across_yield {
817 debug!("err_out_of_scope: opt_yield_span = {:?}", yield_span);
818 struct_span_err!(self.tcx.sess,
821 "borrow may still be in use when generator yields")
822 .span_label(yield_span, "possible yield occurs here")
827 let mut db = struct_span_err!(self.tcx.sess,
830 "{} does not live long enough",
833 let (value_kind, value_msg) = match err.cmt.cat {
834 mc::Categorization::Rvalue(..) =>
835 ("temporary value", "temporary value created here"),
837 ("borrowed value", "borrow occurs here")
840 let is_closure = match cause {
841 euv::ClosureCapture(s) => {
842 // The primary span starts out as the closure creation point.
843 // Change the primary span here to highlight the use of the variable
844 // in the closure, because it seems more natural. Highlight
845 // closure creation point as a secondary span.
846 match db.span.primary_span() {
848 db.span = MultiSpan::from_span(s);
849 db.span_label(primary, "capture occurs here");
850 db.span_label(s, "does not live long enough");
857 db.span_label(error_span, "does not live long enough");
862 let sub_span = self.region_end_span(sub_scope);
863 let super_span = self.region_end_span(super_scope);
865 match (sub_span, super_span) {
866 (Some(s1), Some(s2)) if s1 == s2 => {
868 db.span = MultiSpan::from_span(s1);
869 db.span_label(error_span, value_msg);
870 let msg = match opt_loan_path(&err.cmt) {
871 None => value_kind.to_string(),
873 format!("`{}`", self.loan_path_to_string(&lp))
877 format!("{} dropped here while still borrowed", msg));
879 db.span_label(s1, format!("{} dropped before borrower", value_kind));
881 db.note("values in a scope are dropped in the opposite order \
884 (Some(s1), Some(s2)) if !is_closure => {
885 db.span = MultiSpan::from_span(s2);
886 db.span_label(error_span, value_msg);
887 let msg = match opt_loan_path(&err.cmt) {
888 None => value_kind.to_string(),
890 format!("`{}`", self.loan_path_to_string(&lp))
893 db.span_label(s2, format!("{} dropped here while still borrowed", msg));
894 db.span_label(s1, format!("{} needs to live until here", value_kind));
899 db.span_label(s, format!("{} needs to live until here",
903 self.tcx.note_and_explain_region(
905 "borrowed value must be valid for ",
912 db.span_label(s, format!("{} only lives until here", value_kind));
915 self.tcx.note_and_explain_region(
917 "...but borrowed value is only valid for ",
925 if let Some(_) = statement_scope_span(self.tcx, super_scope) {
926 db.note("consider using a `let` binding to increase its lifetime");
931 err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
932 let descr = self.cmt_to_path_or_string(&err.cmt);
933 let mut db = struct_span_err!(self.tcx.sess, error_span, E0598,
934 "lifetime of {} is too short to guarantee \
935 its contents can be safely reborrowed",
938 let descr = match opt_loan_path(&err.cmt) {
940 format!("`{}`", self.loan_path_to_string(&lp))
942 None => self.cmt_to_string(&err.cmt),
944 self.tcx.note_and_explain_region(
946 &format!("{} would have to be valid for ",
950 self.tcx.note_and_explain_region(
952 &format!("...but {} is only valid for ", descr),
961 pub fn report_aliasability_violation(&self,
963 kind: AliasableViolationKind,
964 cause: mc::AliasableReason,
965 cmt: mc::cmt<'tcx>) {
966 let mut is_closure = false;
967 let prefix = match kind {
968 MutabilityViolation => {
969 "cannot assign to data"
971 BorrowViolation(euv::ClosureCapture(_)) |
972 BorrowViolation(euv::OverloadedOperator) |
973 BorrowViolation(euv::AddrOf) |
974 BorrowViolation(euv::AutoRef) |
975 BorrowViolation(euv::AutoUnsafe) |
976 BorrowViolation(euv::RefBinding) |
977 BorrowViolation(euv::MatchDiscriminant) => {
978 "cannot borrow data mutably"
981 BorrowViolation(euv::ClosureInvocation) => {
986 BorrowViolation(euv::ForLoop) => {
992 mc::AliasableStatic |
993 mc::AliasableStaticMut => {
994 // This path cannot occur. It happens when we have an
995 // `&mut` or assignment to a static. But in the case
996 // of `static X`, we get a mutability violation first,
997 // and never get here. In the case of `static mut X`,
998 // that is unsafe and hence the aliasability error is
1000 span_bug!(span, "aliasability violation for static `{}`", prefix)
1002 mc::AliasableBorrowed => {}
1004 let blame = cmt.immutability_blame();
1005 let mut err = match blame {
1006 Some(ImmutabilityBlame::ClosureEnv(id)) => {
1007 let mut err = struct_span_err!(
1008 self.tcx.sess, span, E0387,
1009 "{} in a captured outer variable in an `Fn` closure", prefix);
1011 // FIXME: the distinction between these 2 messages looks wrong.
1012 let help = if let BorrowViolation(euv::ClosureCapture(_)) = kind {
1013 // The aliasability violation with closure captures can
1014 // happen for nested closures, so we know the enclosing
1015 // closure incorrectly accepts an `Fn` while it needs to
1017 "consider changing this to accept closures that implement `FnMut`"
1020 "consider changing this closure to take self by mutable reference"
1022 err.span_help(self.tcx.hir.span(id), help);
1026 let mut err = struct_span_err!(
1027 self.tcx.sess, span, E0389,
1028 "{} in a `&` reference", prefix);
1029 err.span_label(span, "assignment into an immutable reference");
1033 self.note_immutability_blame(&mut err, blame);
1036 err.help("closures behind references must be called via `&mut`");
1041 /// Given a type, if it is an immutable reference, return a suggestion to make it mutable
1042 fn suggest_mut_for_immutable(&self, pty: &hir::Ty, is_implicit_self: bool) -> Option<String> {
1043 // Check wether the argument is an immutable reference
1044 debug!("suggest_mut_for_immutable({:?}, {:?})", pty, is_implicit_self);
1045 if let hir::TyRptr(lifetime, hir::MutTy {
1046 mutbl: hir::Mutability::MutImmutable,
1049 // Account for existing lifetimes when generating the message
1050 let pointee_snippet = match self.tcx.sess.codemap().span_to_snippet(ty.span) {
1051 Ok(snippet) => snippet,
1055 let lifetime_snippet = if !lifetime.is_elided() {
1056 format!("{} ", match self.tcx.sess.codemap().span_to_snippet(lifetime.span) {
1057 Ok(lifetime_snippet) => lifetime_snippet,
1063 Some(format!("use `&{}mut {}` here to make mutable",
1065 if is_implicit_self { "self" } else { &*pointee_snippet }))
1071 fn local_binding_mode(&self, node_id: ast::NodeId) -> hir::BindingMode {
1072 let pat = match self.tcx.hir.get(node_id) {
1073 hir_map::Node::NodeLocal(pat) => pat,
1074 node => bug!("bad node for local: {:?}", node)
1078 hir::PatKind::Binding(mode, ..) => mode,
1079 _ => bug!("local is not a binding: {:?}", pat)
1083 fn local_ty(&self, node_id: ast::NodeId) -> (Option<&hir::Ty>, bool) {
1084 let parent = self.tcx.hir.get_parent_node(node_id);
1085 let parent_node = self.tcx.hir.get(parent);
1087 // The parent node is like a fn
1088 if let Some(fn_like) = FnLikeNode::from_node(parent_node) {
1089 // `nid`'s parent's `Body`
1090 let fn_body = self.tcx.hir.body(fn_like.body());
1091 // Get the position of `node_id` in the arguments list
1092 let arg_pos = fn_body.arguments.iter().position(|arg| arg.pat.id == node_id);
1093 if let Some(i) = arg_pos {
1094 // The argument's `Ty`
1095 (Some(&fn_like.decl().inputs[i]),
1096 i == 0 && fn_like.decl().has_implicit_self)
1105 fn note_immutability_blame(&self,
1106 db: &mut DiagnosticBuilder,
1107 blame: Option<ImmutabilityBlame>) {
1110 Some(ImmutabilityBlame::ClosureEnv(_)) => {}
1111 Some(ImmutabilityBlame::ImmLocal(node_id)) => {
1112 let let_span = self.tcx.hir.span(node_id);
1113 if let hir::BindingMode::BindByValue(..) = self.local_binding_mode(node_id) {
1114 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(let_span) {
1115 let (_, is_implicit_self) = self.local_ty(node_id);
1116 if is_implicit_self && snippet != "self" {
1117 // avoid suggesting `mut &self`.
1122 format!("consider changing this to `mut {}`", snippet)
1127 Some(ImmutabilityBlame::LocalDeref(node_id)) => {
1128 let let_span = self.tcx.hir.span(node_id);
1129 match self.local_binding_mode(node_id) {
1130 hir::BindingMode::BindByRef(..) => {
1131 let snippet = self.tcx.sess.codemap().span_to_snippet(let_span);
1132 if let Ok(snippet) = snippet {
1135 format!("consider changing this to `{}`",
1136 snippet.replace("ref ", "ref mut "))
1140 hir::BindingMode::BindByValue(..) => {
1141 if let (Some(local_ty), is_implicit_self) = self.local_ty(node_id) {
1143 self.suggest_mut_for_immutable(local_ty, is_implicit_self) {
1144 db.span_label(local_ty.span, msg);
1150 Some(ImmutabilityBlame::AdtFieldDeref(_, field)) => {
1151 let node_id = match self.tcx.hir.as_local_node_id(field.did) {
1152 Some(node_id) => node_id,
1156 if let hir_map::Node::NodeField(ref field) = self.tcx.hir.get(node_id) {
1157 if let Some(msg) = self.suggest_mut_for_immutable(&field.ty, false) {
1158 db.span_label(field.ty.span, msg);
1165 fn report_out_of_scope_escaping_closure_capture(&self,
1166 err: &BckError<'tcx>,
1169 let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
1172 match self.tcx.sess.codemap().span_to_snippet(err.span) {
1173 Ok(string) => format!("move {}", string),
1174 Err(_) => format!("move |<args>| <body>")
1177 struct_span_err!(self.tcx.sess, err.span, E0373,
1178 "closure may outlive the current function, \
1179 but it borrows {}, \
1180 which is owned by the current function",
1182 .span_label(capture_span,
1183 format!("{} is borrowed here",
1184 cmt_path_or_string))
1185 .span_label(err.span,
1186 format!("may outlive borrowed value {}",
1187 cmt_path_or_string))
1188 .span_suggestion(err.span,
1189 &format!("to force the closure to take ownership of {} \
1190 (and any other referenced variables), \
1191 use the `move` keyword",
1192 cmt_path_or_string),
1197 fn region_end_span(&self, region: ty::Region<'tcx>) -> Option<Span> {
1199 ty::ReScope(scope) => {
1200 match scope.span(&self.tcx.hir) {
1213 fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'tcx>,
1214 error_span: &Span) {
1215 match err.cmt.note {
1216 mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1217 // If this is an `Fn` closure, it simply can't mutate upvars.
1218 // If it's an `FnMut` closure, the original variable was declared immutable.
1219 // We need to determine which is the case here.
1220 let kind = match err.cmt.upvar().unwrap().cat {
1221 Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1224 if kind == ty::ClosureKind::Fn {
1225 db.span_help(self.tcx.hir.span(upvar_id.closure_expr_id),
1226 "consider changing this closure to take \
1227 self by mutable reference");
1231 if let Categorization::Deref(..) = err.cmt.cat {
1232 db.span_label(*error_span, "cannot borrow as mutable");
1233 } else if let Categorization::Local(local_id) = err.cmt.cat {
1234 let span = self.tcx.hir.span(local_id);
1235 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
1236 if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
1237 db.span_label(*error_span, "cannot reborrow mutably");
1238 db.span_label(*error_span, "try removing `&mut` here");
1240 db.span_label(*error_span, "cannot borrow mutably");
1243 db.span_label(*error_span, "cannot borrow mutably");
1245 } else if let Categorization::Interior(ref cmt, _) = err.cmt.cat {
1246 if let mc::MutabilityCategory::McImmutable = cmt.mutbl {
1247 db.span_label(*error_span,
1248 "cannot mutably borrow immutable field");
1254 pub fn append_loan_path_to_string(&self,
1255 loan_path: &LoanPath<'tcx>,
1257 match loan_path.kind {
1258 LpUpvar(ty::UpvarId{ var_id: id, closure_expr_id: _ }) |
1260 out.push_str(&self.tcx.local_var_name_str(id));
1263 LpDowncast(ref lp_base, variant_def_id) => {
1265 self.append_loan_path_to_string(&lp_base, out);
1266 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1267 out.push_str(&self.tcx.item_path_str(variant_def_id));
1271 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(fname))) => {
1272 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1274 mc::NamedField(fname) => {
1276 out.push_str(&fname.as_str());
1278 mc::PositionalField(idx) => {
1280 out.push_str(&idx.to_string());
1285 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement)) => {
1286 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1287 out.push_str("[..]");
1290 LpExtend(ref lp_base, _, LpDeref(_)) => {
1292 self.append_loan_path_to_string(&lp_base, out);
1297 pub fn append_autoderefd_loan_path_to_string(&self,
1298 loan_path: &LoanPath<'tcx>,
1300 match loan_path.kind {
1301 LpExtend(ref lp_base, _, LpDeref(_)) => {
1302 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1303 // rules would normally allow users to omit the `*x`.
1304 // So just serialize such paths to `x.f` or x[3]` respectively.
1305 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1308 LpDowncast(ref lp_base, variant_def_id) => {
1310 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1312 out.push_str(&self.tcx.item_path_str(variant_def_id));
1316 LpVar(..) | LpUpvar(..) | LpExtend(.., LpInterior(..)) => {
1317 self.append_loan_path_to_string(loan_path, out)
1322 pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1323 let mut result = String::new();
1324 self.append_loan_path_to_string(loan_path, &mut result);
1328 pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1329 cmt.descriptive_string(self.tcx)
1332 pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt<'tcx>) -> String {
1333 match opt_loan_path(cmt) {
1334 Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1335 None => self.cmt_to_string(cmt),
1340 fn statement_scope_span(tcx: TyCtxt, region: ty::Region) -> Option<Span> {
1342 ty::ReScope(scope) => {
1343 match tcx.hir.find(scope.node_id()) {
1344 Some(hir_map::NodeStmt(stmt)) => Some(stmt.span),
1352 impl BitwiseOperator for LoanDataFlowOperator {
1354 fn join(&self, succ: usize, pred: usize) -> usize {
1355 succ | pred // loans from both preds are in scope
1359 impl DataFlowOperator for LoanDataFlowOperator {
1361 fn initial_value(&self) -> bool {
1362 false // no loans in scope by default
1366 impl<'tcx> fmt::Debug for InteriorKind {
1367 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1369 InteriorField(mc::NamedField(fld)) => write!(f, "{}", fld),
1370 InteriorField(mc::PositionalField(i)) => write!(f, "#{}", i),
1371 InteriorElement => write!(f, "[]"),
1376 impl<'tcx> fmt::Debug for Loan<'tcx> {
1377 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1378 write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1384 self.restricted_paths)
1388 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1389 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1392 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_string(id)))
1395 LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => {
1396 let s = ty::tls::with(|tcx| tcx.hir.node_to_string(var_id));
1397 write!(f, "$({} captured by id={})", s, closure_expr_id)
1400 LpDowncast(ref lp, variant_def_id) => {
1401 let variant_str = if variant_def_id.is_local() {
1402 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1404 format!("{:?}", variant_def_id)
1406 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1409 LpExtend(ref lp, _, LpDeref(_)) => {
1410 write!(f, "{:?}.*", lp)
1413 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1414 write!(f, "{:?}.{:?}", lp, interior)
1420 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1421 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1424 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_user_string(id)))
1427 LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => {
1428 let s = ty::tls::with(|tcx| tcx.hir.node_to_user_string(var_id));
1429 write!(f, "$({} captured by closure)", s)
1432 LpDowncast(ref lp, variant_def_id) => {
1433 let variant_str = if variant_def_id.is_local() {
1434 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1436 format!("{:?}", variant_def_id)
1438 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1441 LpExtend(ref lp, _, LpDeref(_)) => {
1442 write!(f, "{}.*", lp)
1445 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1446 write!(f, "{}.{:?}", lp, interior)