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::HirId;
25 use rustc::hir::map::blocks::FnLikeNode;
27 use rustc::middle::borrowck::{BorrowCheckResult, SignalledError};
28 use rustc::hir::def_id::{DefId, LocalDefId};
29 use rustc::middle::expr_use_visitor as euv;
30 use rustc::middle::mem_categorization as mc;
31 use rustc::middle::mem_categorization::Categorization;
32 use rustc::middle::mem_categorization::ImmutabilityBlame;
33 use rustc::middle::region;
34 use rustc::middle::free_region::RegionRelations;
35 use rustc::ty::{self, Ty, TyCtxt};
36 use rustc::ty::query::Providers;
37 use rustc_mir::util::borrowck_errors::{BorrowckErrors, Origin};
38 use rustc_mir::util::suggest_ref_mut;
39 use rustc::util::nodemap::FxHashSet;
41 use std::cell::{Cell, RefCell};
44 use rustc_data_structures::sync::Lrc;
45 use std::hash::{Hash, Hasher};
47 use syntax_pos::{MultiSpan, Span};
48 use errors::{DiagnosticBuilder, DiagnosticId};
51 use rustc::hir::intravisit::{self, Visitor};
53 use dataflow::{DataFlowContext, BitwiseOperator, DataFlowOperator, KillFrom};
63 #[derive(Clone, Copy)]
64 pub struct LoanDataFlowOperator;
66 pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
68 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
69 tcx.par_body_owners(|body_owner_def_id| {
70 tcx.borrowck(body_owner_def_id);
74 pub fn provide(providers: &mut Providers) {
75 *providers = Providers {
81 /// Collection of conclusions determined via borrow checker analyses.
82 pub struct AnalysisData<'a, 'tcx: 'a> {
83 pub all_loans: Vec<Loan<'tcx>>,
84 pub loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>,
85 pub move_data: move_data::FlowedMoveData<'a, 'tcx>,
88 fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId)
89 -> Lrc<BorrowCheckResult>
91 assert!(tcx.use_ast_borrowck() || tcx.migrate_borrowck());
93 debug!("borrowck(body_owner_def_id={:?})", owner_def_id);
95 let owner_id = tcx.hir.as_local_node_id(owner_def_id).unwrap();
97 match tcx.hir.get(owner_id) {
100 // We get invoked with anything that has MIR, but some of
101 // those things (notably the synthesized constructors from
102 // tuple structs/variants) do not have an associated body
103 // and do not need borrowchecking.
104 return Lrc::new(BorrowCheckResult {
105 used_mut_nodes: FxHashSet(),
106 signalled_any_error: SignalledError::NoErrorsSeen,
112 let body_id = tcx.hir.body_owned_by(owner_id);
113 let tables = tcx.typeck_tables_of(owner_def_id);
114 let region_scope_tree = tcx.region_scope_tree(owner_def_id);
115 let body = tcx.hir.body(body_id);
116 let mut bccx = BorrowckCtxt {
122 used_mut_nodes: RefCell::new(FxHashSet()),
123 signalled_any_error: Cell::new(SignalledError::NoErrorsSeen),
126 // Eventually, borrowck will always read the MIR, but at the
127 // moment we do not. So, for now, we always force MIR to be
128 // constructed for a given fn, since this may result in errors
129 // being reported and we want that to happen.
131 // Note that `mir_validated` is a "stealable" result; the
132 // thief, `optimized_mir()`, forces borrowck, so we know that
133 // is not yet stolen.
134 ty::query::queries::mir_validated::ensure(tcx, owner_def_id);
136 // option dance because you can't capture an uninitialized variable
139 if let Some(AnalysisData { all_loans,
141 move_data: flowed_moves }) =
142 build_borrowck_dataflow_data(&mut bccx, false, body_id,
144 cfg = Some(cfg::CFG::new(bccx.tcx, &body));
145 cfg.as_mut().unwrap()
148 check_loans::check_loans(&mut bccx, &loan_dfcx, &flowed_moves, &all_loans, body);
151 if !tcx.use_mir_borrowck() {
152 unused::check(&mut bccx, body);
155 Lrc::new(BorrowCheckResult {
156 used_mut_nodes: bccx.used_mut_nodes.into_inner(),
157 signalled_any_error: bccx.signalled_any_error.into_inner(),
161 fn build_borrowck_dataflow_data<'a, 'c, 'tcx, F>(this: &mut BorrowckCtxt<'a, 'tcx>,
162 force_analysis: bool,
163 body_id: hir::BodyId,
165 -> Option<AnalysisData<'a, 'tcx>>
166 where F: FnOnce(&mut BorrowckCtxt<'a, 'tcx>) -> &'c cfg::CFG
168 // Check the body of fn items.
171 let mut visitor = intravisit::IdRangeComputingVisitor::new(&tcx.hir);
172 visitor.visit_body(this.body);
175 let (all_loans, move_data) =
176 gather_loans::gather_loans_in_fn(this, body_id);
178 if !force_analysis && move_data.is_empty() && all_loans.is_empty() {
179 // large arrays of data inserted as constants can take a lot of
180 // time and memory to borrow-check - see issue #36799. However,
181 // they don't have places, so no borrow-check is actually needed.
182 // Recognize that case and skip borrow-checking.
183 debug!("skipping loan propagation for {:?} because of no loans", body_id);
186 debug!("propagating loans in {:?}", body_id);
189 let cfg = get_cfg(this);
191 DataFlowContext::new(this.tcx,
195 LoanDataFlowOperator,
198 for (loan_idx, loan) in all_loans.iter().enumerate() {
199 loan_dfcx.add_gen(loan.gen_scope.item_local_id(), loan_idx);
200 loan_dfcx.add_kill(KillFrom::ScopeEnd,
201 loan.kill_scope.item_local_id(),
204 loan_dfcx.add_kills_from_flow_exits(cfg);
205 loan_dfcx.propagate(cfg, this.body);
207 let flowed_moves = move_data::FlowedMoveData::new(move_data,
213 Some(AnalysisData { all_loans,
215 move_data:flowed_moves })
218 /// Accessor for introspective clients inspecting `AnalysisData` and
219 /// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer.
220 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
221 tcx: TyCtxt<'a, 'tcx, 'tcx>,
222 body_id: hir::BodyId,
224 -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
226 let owner_id = tcx.hir.body_owner(body_id);
227 let owner_def_id = tcx.hir.local_def_id(owner_id);
228 let tables = tcx.typeck_tables_of(owner_def_id);
229 let region_scope_tree = tcx.region_scope_tree(owner_def_id);
230 let body = tcx.hir.body(body_id);
231 let mut bccx = BorrowckCtxt {
237 used_mut_nodes: RefCell::new(FxHashSet()),
238 signalled_any_error: Cell::new(SignalledError::NoErrorsSeen),
241 let dataflow_data = build_borrowck_dataflow_data(&mut bccx, true, body_id, |_| cfg);
242 (bccx, dataflow_data.unwrap())
245 // ----------------------------------------------------------------------
248 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
249 tcx: TyCtxt<'a, 'tcx, 'tcx>,
251 // tables for the current thing we are checking; set to
252 // Some in `borrowck_fn` and cleared later
253 tables: &'a ty::TypeckTables<'tcx>,
255 region_scope_tree: Lrc<region::ScopeTree>,
259 body: &'tcx hir::Body,
261 used_mut_nodes: RefCell<FxHashSet<HirId>>,
263 signalled_any_error: Cell<SignalledError>,
267 impl<'a, 'tcx: 'a> BorrowckCtxt<'a, 'tcx> {
268 fn signal_error(&self) {
269 self.signalled_any_error.set(SignalledError::SawSomeError);
273 impl<'a, 'b, 'tcx: 'b> BorrowckErrors<'a> for &'a BorrowckCtxt<'b, 'tcx> {
274 fn struct_span_err_with_code<S: Into<MultiSpan>>(self,
278 -> DiagnosticBuilder<'a>
280 self.tcx.sess.struct_span_err_with_code(sp, msg, code)
283 fn struct_span_err<S: Into<MultiSpan>>(self,
286 -> DiagnosticBuilder<'a>
288 self.tcx.sess.struct_span_err(sp, msg)
291 fn cancel_if_wrong_origin(self,
292 mut diag: DiagnosticBuilder<'a>,
294 -> DiagnosticBuilder<'a>
296 if !o.should_emit_errors(self.tcx.borrowck_mode()) {
297 self.tcx.sess.diagnostic().cancel(&mut diag);
303 ///////////////////////////////////////////////////////////////////////////
304 // Loans and loan paths
306 /// Record of a loan that was issued.
307 pub struct Loan<'tcx> {
309 loan_path: Rc<LoanPath<'tcx>>,
310 kind: ty::BorrowKind,
311 restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
313 /// gen_scope indicates where loan is introduced. Typically the
314 /// loan is introduced at the point of the borrow, but in some
315 /// cases, notably method arguments, the loan may be introduced
316 /// only later, once it comes into scope. See also
317 /// `GatherLoanCtxt::compute_gen_scope`.
318 gen_scope: region::Scope,
320 /// kill_scope indicates when the loan goes out of scope. This is
321 /// either when the lifetime expires or when the local variable
322 /// which roots the loan-path goes out of scope, whichever happens
323 /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
324 kill_scope: region::Scope,
326 cause: euv::LoanCause,
329 impl<'tcx> Loan<'tcx> {
330 pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
331 self.loan_path.clone()
336 pub struct LoanPath<'tcx> {
337 kind: LoanPathKind<'tcx>,
341 impl<'tcx> PartialEq for LoanPath<'tcx> {
342 fn eq(&self, that: &LoanPath<'tcx>) -> bool {
343 self.kind == that.kind
347 impl<'tcx> Hash for LoanPath<'tcx> {
348 fn hash<H: Hasher>(&self, state: &mut H) {
349 self.kind.hash(state);
353 #[derive(PartialEq, Eq, Hash, Debug)]
354 pub enum LoanPathKind<'tcx> {
355 LpVar(ast::NodeId), // `x` in README.md
356 LpUpvar(ty::UpvarId), // `x` captured by-value into closure
357 LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
358 LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem<'tcx>)
361 impl<'tcx> LoanPath<'tcx> {
362 fn new(kind: LoanPathKind<'tcx>, ty: Ty<'tcx>) -> LoanPath<'tcx> {
363 LoanPath { kind: kind, ty: ty }
366 fn to_type(&self) -> Ty<'tcx> { self.ty }
368 fn has_downcast(&self) -> bool {
370 LpDowncast(_, _) => true,
371 LpExtend(ref lp, _, LpInterior(_, _)) => {
379 // FIXME (pnkfelix): See discussion here
380 // https://github.com/pnkfelix/rust/commit/
381 // b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
382 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
384 // A local, "cleaned" version of `mc::InteriorKind` that drops
385 // information that is not relevant to loan-path analysis. (In
386 // particular, the distinction between how precisely an array-element
387 // is tracked is irrelevant here.)
388 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
389 pub enum InteriorKind {
390 InteriorField(mc::FieldIndex),
394 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
395 impl ToInteriorKind for mc::InteriorKind {
396 fn cleaned(self) -> InteriorKind {
398 mc::InteriorField(name) => InteriorField(name),
399 mc::InteriorElement(_) => InteriorElement,
405 // - a pointer dereference (`*P` in README.md)
406 // - a field reference, with an optional definition of the containing
407 // enum variant (`P.f` in README.md)
408 // `DefId` is present when the field is part of struct that is in
409 // a variant of an enum. For instance in:
410 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
411 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
412 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
413 pub enum LoanPathElem<'tcx> {
414 LpDeref(mc::PointerKind<'tcx>),
415 LpInterior(Option<DefId>, InteriorKind),
418 fn closure_to_block(closure_id: LocalDefId,
419 tcx: TyCtxt) -> ast::NodeId {
420 let closure_id = tcx.hir.local_def_id_to_node_id(closure_id);
421 match tcx.hir.get(closure_id) {
422 Node::Expr(expr) => match expr.node {
423 hir::ExprKind::Closure(.., body_id, _, _) => {
427 bug!("encountered non-closure id: {}", closure_id)
430 _ => bug!("encountered non-expr id: {}", closure_id)
434 impl<'a, 'tcx> LoanPath<'tcx> {
435 pub fn kill_scope(&self, bccx: &BorrowckCtxt<'a, 'tcx>) -> region::Scope {
438 let hir_id = bccx.tcx.hir.node_to_hir_id(local_id);
439 bccx.region_scope_tree.var_scope(hir_id.local_id)
441 LpUpvar(upvar_id) => {
442 let block_id = closure_to_block(upvar_id.closure_expr_id, bccx.tcx);
443 let hir_id = bccx.tcx.hir.node_to_hir_id(block_id);
444 region::Scope::Node(hir_id.local_id)
446 LpDowncast(ref base, _) |
447 LpExtend(ref base, ..) => base.kill_scope(bccx),
451 fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
452 match (&self.kind, &other.kind) {
453 (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
454 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
455 if id == id2 && opt_variant_id == opt_variant_id2 {
456 base.has_fork(&base2)
460 (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
461 (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&base),
466 fn depth(&self) -> usize {
468 LpExtend(ref base, _, LpDeref(_)) => base.depth(),
469 LpExtend(ref base, _, LpInterior(..)) => base.depth() + 1,
474 fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
475 match (&self.kind, &other.kind) {
476 (&LpExtend(ref base, a, LpInterior(opt_variant_id, id)),
477 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) => {
478 if id == id2 && opt_variant_id == opt_variant_id2 {
479 base.common(&base2).map(|x| {
481 if base.depth() == xd && base2.depth() == xd {
483 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
494 (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
495 (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&other),
496 (&LpVar(id), &LpVar(id2)) => {
498 Some(LoanPath { kind: LpVar(id), ty: self.ty })
503 (&LpUpvar(id), &LpUpvar(id2)) => {
505 Some(LoanPath { kind: LpUpvar(id), ty: self.ty })
515 // Avoid "cannot borrow immutable field `self.x` as mutable" as that implies that a field *can* be
516 // mutable independently of the struct it belongs to. (#35937)
517 pub fn opt_loan_path_is_field<'tcx>(cmt: &mc::cmt_<'tcx>) -> (Option<Rc<LoanPath<'tcx>>>, bool) {
518 let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
521 Categorization::Rvalue(..) |
522 Categorization::StaticItem => {
526 Categorization::Local(id) => {
527 (Some(new_lp(LpVar(id))), false)
530 Categorization::Upvar(mc::Upvar { id, .. }) => {
531 (Some(new_lp(LpUpvar(id))), false)
534 Categorization::Deref(ref cmt_base, pk) => {
535 let lp = opt_loan_path_is_field(cmt_base);
537 new_lp(LpExtend(lp, cmt.mutbl, LpDeref(pk)))
541 Categorization::Interior(ref cmt_base, ik) => {
542 (opt_loan_path(cmt_base).map(|lp| {
543 let opt_variant_id = match cmt_base.cat {
544 Categorization::Downcast(_, did) => Some(did),
547 new_lp(LpExtend(lp, cmt.mutbl, LpInterior(opt_variant_id, ik.cleaned())))
551 Categorization::Downcast(ref cmt_base, variant_def_id) => {
552 let lp = opt_loan_path_is_field(cmt_base);
554 new_lp(LpDowncast(lp, variant_def_id))
560 /// Computes the `LoanPath` (if any) for a `cmt`.
561 /// Note that this logic is somewhat duplicated in
562 /// the method `compute()` found in `gather_loans::restrictions`,
563 /// which allows it to share common loan path pieces as it
564 /// traverses the CMT.
565 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt_<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
566 opt_loan_path_is_field(cmt).0
569 ///////////////////////////////////////////////////////////////////////////
572 // Errors that can occur
573 #[derive(Debug, PartialEq)]
574 pub enum bckerr_code<'tcx> {
576 /// superscope, subscope, loan cause
577 err_out_of_scope(ty::Region<'tcx>, ty::Region<'tcx>, euv::LoanCause),
578 err_borrowed_pointer_too_short(ty::Region<'tcx>, ty::Region<'tcx>), // loan, ptr
581 // Combination of an error code and the categorization of the expression
583 #[derive(Debug, PartialEq)]
584 pub struct BckError<'c, 'tcx: 'c> {
586 cause: AliasableViolationKind,
587 cmt: &'c mc::cmt_<'tcx>,
588 code: bckerr_code<'tcx>
591 #[derive(Copy, Clone, Debug, PartialEq)]
592 pub enum AliasableViolationKind {
594 BorrowViolation(euv::LoanCause)
597 #[derive(Copy, Clone, Debug)]
598 pub enum MovedValueUseKind {
603 ///////////////////////////////////////////////////////////////////////////
606 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
607 pub fn is_subregion_of(&self,
608 r_sub: ty::Region<'tcx>,
609 r_sup: ty::Region<'tcx>)
612 let region_rels = RegionRelations::new(self.tcx,
614 &self.region_scope_tree,
615 &self.tables.free_region_map);
616 region_rels.is_subregion_of(r_sub, r_sup)
619 pub fn report(&self, err: BckError<'a, 'tcx>) {
620 // Catch and handle some particular cases.
621 match (&err.code, &err.cause) {
622 (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _),
623 &BorrowViolation(euv::ClosureCapture(span))) |
624 (&err_out_of_scope(&ty::ReScope(_), &ty::ReEarlyBound(..), _),
625 &BorrowViolation(euv::ClosureCapture(span))) |
626 (&err_out_of_scope(&ty::ReScope(_), &ty::ReFree(..), _),
627 &BorrowViolation(euv::ClosureCapture(span))) => {
628 return self.report_out_of_scope_escaping_closure_capture(&err, span);
633 self.report_bckerr(&err);
636 pub fn report_use_of_moved_value(&self,
638 use_kind: MovedValueUseKind,
640 the_move: &move_data::Move,
641 moved_lp: &LoanPath<'tcx>) {
642 let (verb, verb_participle) = match use_kind {
643 MovedInUse => ("use", "used"),
644 MovedInCapture => ("capture", "captured"),
647 let (_ol, _moved_lp_msg, mut err, need_note) = match the_move.kind {
648 move_data::Declared => {
649 // If this is an uninitialized variable, just emit a simple warning
651 self.cannot_act_on_uninitialized_variable(use_span,
653 &self.loan_path_to_string(lp),
655 .span_label(use_span, format!("use of possibly uninitialized `{}`",
656 self.loan_path_to_string(lp)))
662 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
663 // normally generate a rather confusing message:
665 // error: use of moved value: `x.b`
666 // note: `x.a` moved here...
668 // What we want to do instead is get the 'common ancestor' of the two moves and
669 // use that for most of the message instead, giving is something like this:
671 // error: use of moved value: `x`
672 // note: `x` moved here (through moving `x.a`)...
674 let common = moved_lp.common(lp);
675 let has_common = common.is_some();
676 let has_fork = moved_lp.has_fork(lp);
677 let (nl, ol, moved_lp_msg) =
678 if has_fork && has_common {
679 let nl = self.loan_path_to_string(&common.unwrap());
681 let moved_lp_msg = format!(" (through moving `{}`)",
682 self.loan_path_to_string(moved_lp));
683 (nl, ol, moved_lp_msg)
685 (self.loan_path_to_string(lp),
686 self.loan_path_to_string(moved_lp),
690 let partial = moved_lp.depth() > lp.depth();
691 let msg = if !has_fork && partial { "partially " }
692 else if has_fork && !has_common { "collaterally "}
694 let mut err = self.cannot_act_on_moved_value(use_span,
697 Some(nl.to_string()),
699 let need_note = match lp.ty.sty {
700 ty::Closure(id, _) => {
701 let node_id = self.tcx.hir.as_local_node_id(id).unwrap();
702 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
703 if let Some((span, name)) = self.tables.closure_kind_origins().get(hir_id) {
704 err.span_note(*span, &format!(
705 "closure cannot be invoked more than once because \
706 it moves the variable `{}` out of its environment",
716 (ol, moved_lp_msg, err, need_note)
720 // Get type of value and span where it was previously
722 let node_id = self.tcx.hir.hir_to_node_id(hir::HirId {
723 owner: self.body.value.hir_id.owner,
724 local_id: the_move.id
726 let (move_span, move_note) = match the_move.kind {
727 move_data::Declared => {
731 move_data::MoveExpr |
732 move_data::MovePat => (self.tcx.hir.span(node_id), ""),
734 move_data::Captured =>
735 (match self.tcx.hir.expect_expr(node_id).node {
736 hir::ExprKind::Closure(.., fn_decl_span, _) => fn_decl_span,
737 ref r => bug!("Captured({:?}) maps to non-closure: {:?}",
739 }, " (into closure)"),
742 // Annotate the use and the move in the span. Watch out for
743 // the case where the use and the move are the same. This
744 // means the use is in a loop.
745 err = if use_span == move_span {
748 format!("value moved{} here in previous iteration of loop",
752 err.span_label(use_span, format!("value {} here after move", verb_participle));
753 err.span_label(move_span, format!("value moved{} here", move_note));
759 "move occurs because {} has type `{}`, which does not implement the `Copy` trait",
760 if moved_lp.has_downcast() {
761 "the value".to_string()
763 format!("`{}`", self.loan_path_to_string(moved_lp))
768 // Note: we used to suggest adding a `ref binding` or calling
769 // `clone` but those suggestions have been removed because
770 // they are often not what you actually want to do, and were
771 // not considered particularly helpful.
777 pub fn report_partial_reinitialization_of_uninitialized_structure(
780 lp: &LoanPath<'tcx>) {
781 self.cannot_partially_reinit_an_uninit_struct(span,
782 &self.loan_path_to_string(lp),
788 pub fn report_reassigned_immutable_variable(&self,
792 &move_data::Assignment) {
793 let mut err = self.cannot_reassign_immutable(span,
794 &self.loan_path_to_string(lp),
797 err.span_label(span, "cannot assign twice to immutable variable");
798 if span != assign.span {
799 err.span_label(assign.span, format!("first assignment to `{}`",
800 self.loan_path_to_string(lp)));
806 fn report_bckerr(&self, err: &BckError<'a, 'tcx>) {
807 let error_span = err.span.clone();
811 let descr = match err.cmt.note {
812 mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
813 self.cmt_to_string(&err.cmt)
815 _ => match opt_loan_path_is_field(&err.cmt) {
817 format!("{} of {} binding",
818 self.cmt_to_string(&err.cmt),
819 err.cmt.mutbl.to_user_str())
824 err.cmt.mutbl.to_user_str(),
825 self.cmt_to_string(&err.cmt))
828 (Some(lp), true) => {
829 format!("{} `{}` of {} binding",
830 self.cmt_to_string(&err.cmt),
831 self.loan_path_to_string(&lp),
832 err.cmt.mutbl.to_user_str())
834 (Some(lp), false) => {
835 format!("{} {} `{}`",
836 err.cmt.mutbl.to_user_str(),
837 self.cmt_to_string(&err.cmt),
838 self.loan_path_to_string(&lp))
843 let mut db = match err.cause {
844 MutabilityViolation => {
845 let mut db = self.cannot_assign(error_span, &descr, Origin::Ast);
846 if let mc::NoteClosureEnv(upvar_id) = err.cmt.note {
847 let node_id = self.tcx.hir.hir_to_node_id(upvar_id.var_id);
848 let sp = self.tcx.hir.span(node_id);
849 let fn_closure_msg = "`Fn` closures cannot capture their enclosing \
850 environment for modifications";
851 match (self.tcx.sess.source_map().span_to_snippet(sp), &err.cmt.cat) {
852 (_, &Categorization::Upvar(mc::Upvar {
853 kind: ty::ClosureKind::Fn, ..
855 db.note(fn_closure_msg);
856 // we should point at the cause for this closure being
857 // identified as `Fn` (like in signature of method this
858 // closure was passed into)
860 (Ok(ref snippet), ref cat) => {
861 let msg = &format!("consider making `{}` mutable", snippet);
862 let suggestion = format!("mut {}", snippet);
864 if let &Categorization::Deref(ref cmt, _) = cat {
865 if let Categorization::Upvar(mc::Upvar {
866 kind: ty::ClosureKind::Fn, ..
868 db.note(fn_closure_msg);
870 db.span_suggestion(sp, msg, suggestion);
873 db.span_suggestion(sp, msg, suggestion);
877 db.span_help(sp, "consider making this binding mutable");
884 BorrowViolation(euv::ClosureCapture(_)) => {
885 self.closure_cannot_assign_to_borrowed(error_span, &descr, Origin::Ast)
887 BorrowViolation(euv::OverloadedOperator) |
888 BorrowViolation(euv::AddrOf) |
889 BorrowViolation(euv::RefBinding) |
890 BorrowViolation(euv::AutoRef) |
891 BorrowViolation(euv::AutoUnsafe) |
892 BorrowViolation(euv::ForLoop) |
893 BorrowViolation(euv::MatchDiscriminant) => {
894 self.cannot_borrow_path_as_mutable(error_span, &descr, Origin::Ast)
896 BorrowViolation(euv::ClosureInvocation) => {
898 "err_mutbl with a closure invocation");
902 // We add a special note about `IndexMut`, if the source of this error
903 // is the fact that `Index` is implemented, but `IndexMut` is not. Needing
904 // to implement two traits for "one operator" is not very intuitive for
906 if err.cmt.note == mc::NoteIndex {
907 let node_id = self.tcx.hir.hir_to_node_id(err.cmt.hir_id);
908 let node = self.tcx.hir.get(node_id);
910 // This pattern probably always matches.
912 hir::Expr { node: hir::ExprKind::Index(lhs, _), ..}
914 let ty = self.tables.expr_ty(lhs);
917 "trait `IndexMut` is required to modify indexed content, but \
918 it is not implemented for `{}`",
924 self.note_and_explain_mutbl_error(&mut db, &err, &error_span);
925 self.note_immutability_blame(
927 err.cmt.immutability_blame(),
928 self.tcx.hir.hir_to_node_id(err.cmt.hir_id)
933 err_out_of_scope(super_scope, sub_scope, cause) => {
934 let msg = match opt_loan_path(&err.cmt) {
935 None => "borrowed value".to_string(),
937 format!("`{}`", self.loan_path_to_string(&lp))
941 let mut db = self.path_does_not_live_long_enough(error_span, &msg, Origin::Ast);
942 let value_kind = match err.cmt.cat {
943 mc::Categorization::Rvalue(..) => "temporary value",
944 _ => "borrowed value",
947 let is_closure = match cause {
948 euv::ClosureCapture(s) => {
949 // The primary span starts out as the closure creation point.
950 // Change the primary span here to highlight the use of the variable
951 // in the closure, because it seems more natural. Highlight
952 // closure creation point as a secondary span.
953 match db.span.primary_span() {
955 db.span = MultiSpan::from_span(s);
956 db.span_label(primary, "capture occurs here");
957 db.span_label(s, format!("{} does not live long enough",
965 db.span_label(error_span, format!("{} does not live long enough",
971 let sub_span = self.region_end_span(sub_scope);
972 let super_span = self.region_end_span(super_scope);
974 match (sub_span, super_span) {
975 (Some(s1), Some(s2)) if s1 == s2 => {
977 let msg = match opt_loan_path(&err.cmt) {
978 None => value_kind.to_string(),
980 format!("`{}`", self.loan_path_to_string(&lp))
984 format!("{} dropped here while still borrowed", msg));
986 db.span_label(s1, format!("{} dropped before borrower", value_kind));
988 db.note("values in a scope are dropped in the opposite order \
991 (Some(s1), Some(s2)) if !is_closure => {
992 let msg = match opt_loan_path(&err.cmt) {
993 None => value_kind.to_string(),
995 format!("`{}`", self.loan_path_to_string(&lp))
998 db.span_label(s2, format!("{} dropped here while still borrowed", msg));
999 db.span_label(s1, format!("{} needs to live until here", value_kind));
1004 db.span_label(s, format!("{} needs to live until here",
1008 self.tcx.note_and_explain_region(
1009 &self.region_scope_tree,
1011 "borrowed value must be valid for ",
1018 db.span_label(s, format!("{} only lives until here", value_kind));
1021 self.tcx.note_and_explain_region(
1022 &self.region_scope_tree,
1024 "...but borrowed value is only valid for ",
1032 if let ty::ReScope(scope) = *super_scope {
1033 let node_id = scope.node_id(self.tcx, &self.region_scope_tree);
1034 match self.tcx.hir.find(node_id) {
1035 Some(Node::Stmt(_)) => {
1036 if *sub_scope != ty::ReStatic {
1037 db.note("consider using a `let` binding to increase its lifetime");
1046 self.signal_error();
1048 err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1049 let descr = self.cmt_to_path_or_string(err.cmt);
1050 let mut db = self.lifetime_too_short_for_reborrow(error_span, &descr, Origin::Ast);
1051 let descr = match opt_loan_path(&err.cmt) {
1053 format!("`{}`", self.loan_path_to_string(&lp))
1055 None => self.cmt_to_string(&err.cmt),
1057 self.tcx.note_and_explain_region(
1058 &self.region_scope_tree,
1060 &format!("{} would have to be valid for ",
1064 self.tcx.note_and_explain_region(
1065 &self.region_scope_tree,
1067 &format!("...but {} is only valid for ", descr),
1072 self.signal_error();
1077 pub fn report_aliasability_violation(&self,
1079 kind: AliasableViolationKind,
1080 cause: mc::AliasableReason,
1081 cmt: &mc::cmt_<'tcx>) {
1082 let mut is_closure = false;
1083 let prefix = match kind {
1084 MutabilityViolation => {
1085 "cannot assign to data"
1087 BorrowViolation(euv::ClosureCapture(_)) |
1088 BorrowViolation(euv::OverloadedOperator) |
1089 BorrowViolation(euv::AddrOf) |
1090 BorrowViolation(euv::AutoRef) |
1091 BorrowViolation(euv::AutoUnsafe) |
1092 BorrowViolation(euv::RefBinding) |
1093 BorrowViolation(euv::MatchDiscriminant) => {
1094 "cannot borrow data mutably"
1097 BorrowViolation(euv::ClosureInvocation) => {
1099 "closure invocation"
1102 BorrowViolation(euv::ForLoop) => {
1108 mc::AliasableStaticMut => {
1109 // This path cannot occur. `static mut X` is not checked
1110 // for aliasability violations.
1111 span_bug!(span, "aliasability violation for static mut `{}`", prefix)
1113 mc::AliasableStatic | mc::AliasableBorrowed => {}
1115 let blame = cmt.immutability_blame();
1116 let mut err = match blame {
1117 Some(ImmutabilityBlame::ClosureEnv(id)) => {
1118 // FIXME: the distinction between these 2 messages looks wrong.
1119 let help_msg = if let BorrowViolation(euv::ClosureCapture(_)) = kind {
1120 // The aliasability violation with closure captures can
1121 // happen for nested closures, so we know the enclosing
1122 // closure incorrectly accepts an `Fn` while it needs to
1124 "consider changing this to accept closures that implement `FnMut`"
1127 "consider changing this closure to take self by mutable reference"
1129 let node_id = self.tcx.hir.local_def_id_to_node_id(id);
1130 let help_span = self.tcx.hir.span(node_id);
1131 self.cannot_act_on_capture_in_sharable_fn(span,
1133 (help_span, help_msg),
1137 self.cannot_assign_into_immutable_reference(span, prefix,
1141 self.note_immutability_blame(
1144 self.tcx.hir.hir_to_node_id(cmt.hir_id)
1148 err.help("closures behind references must be called via `&mut`");
1151 self.signal_error();
1154 /// Given a type, if it is an immutable reference, return a suggestion to make it mutable
1155 fn suggest_mut_for_immutable(&self, pty: &hir::Ty, is_implicit_self: bool) -> Option<String> {
1156 // Check whether the argument is an immutable reference
1157 debug!("suggest_mut_for_immutable({:?}, {:?})", pty, is_implicit_self);
1158 if let hir::TyKind::Rptr(lifetime, hir::MutTy {
1159 mutbl: hir::Mutability::MutImmutable,
1162 // Account for existing lifetimes when generating the message
1163 let pointee_snippet = match self.tcx.sess.source_map().span_to_snippet(ty.span) {
1164 Ok(snippet) => snippet,
1168 let lifetime_snippet = if !lifetime.is_elided() {
1169 format!("{} ", match self.tcx.sess.source_map().span_to_snippet(lifetime.span) {
1170 Ok(lifetime_snippet) => lifetime_snippet,
1176 Some(format!("use `&{}mut {}` here to make mutable",
1178 if is_implicit_self { "self" } else { &*pointee_snippet }))
1184 fn local_binding_mode(&self, node_id: ast::NodeId) -> ty::BindingMode {
1185 let pat = match self.tcx.hir.get(node_id) {
1186 Node::Binding(pat) => pat,
1187 node => bug!("bad node for local: {:?}", node)
1191 hir::PatKind::Binding(..) => {
1193 .pat_binding_modes()
1195 .expect("missing binding mode")
1197 _ => bug!("local is not a binding: {:?}", pat)
1201 fn local_ty(&self, node_id: ast::NodeId) -> (Option<&hir::Ty>, bool) {
1202 let parent = self.tcx.hir.get_parent_node(node_id);
1203 let parent_node = self.tcx.hir.get(parent);
1205 // The parent node is like a fn
1206 if let Some(fn_like) = FnLikeNode::from_node(parent_node) {
1207 // `nid`'s parent's `Body`
1208 let fn_body = self.tcx.hir.body(fn_like.body());
1209 // Get the position of `node_id` in the arguments list
1210 let arg_pos = fn_body.arguments.iter().position(|arg| arg.pat.id == node_id);
1211 if let Some(i) = arg_pos {
1212 // The argument's `Ty`
1213 (Some(&fn_like.decl().inputs[i]),
1214 i == 0 && fn_like.decl().has_implicit_self)
1223 fn note_immutability_blame(&self,
1224 db: &mut DiagnosticBuilder,
1225 blame: Option<ImmutabilityBlame>,
1226 error_node_id: ast::NodeId) {
1229 Some(ImmutabilityBlame::ClosureEnv(_)) => {}
1230 Some(ImmutabilityBlame::ImmLocal(node_id)) => {
1231 self.note_immutable_local(db, error_node_id, node_id)
1233 Some(ImmutabilityBlame::LocalDeref(node_id)) => {
1234 match self.local_binding_mode(node_id) {
1235 ty::BindByReference(..) => {
1236 let let_span = self.tcx.hir.span(node_id);
1237 let suggestion = suggest_ref_mut(self.tcx, let_span);
1238 if let Some(replace_str) = suggestion {
1241 "use a mutable reference instead",
1246 ty::BindByValue(..) => {
1247 if let (Some(local_ty), is_implicit_self) = self.local_ty(node_id) {
1249 self.suggest_mut_for_immutable(local_ty, is_implicit_self) {
1250 db.span_label(local_ty.span, msg);
1256 Some(ImmutabilityBlame::AdtFieldDeref(_, field)) => {
1257 let node_id = match self.tcx.hir.as_local_node_id(field.did) {
1258 Some(node_id) => node_id,
1262 if let Node::Field(ref field) = self.tcx.hir.get(node_id) {
1263 if let Some(msg) = self.suggest_mut_for_immutable(&field.ty, false) {
1264 db.span_label(field.ty.span, msg);
1271 // Suggest a fix when trying to mutably borrow an immutable local
1272 // binding: either to make the binding mutable (if its type is
1273 // not a mutable reference) or to avoid borrowing altogether
1274 fn note_immutable_local(&self,
1275 db: &mut DiagnosticBuilder,
1276 borrowed_node_id: ast::NodeId,
1277 binding_node_id: ast::NodeId) {
1278 let let_span = self.tcx.hir.span(binding_node_id);
1279 if let ty::BindByValue(..) = self.local_binding_mode(binding_node_id) {
1280 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(let_span) {
1281 let (ty, is_implicit_self) = self.local_ty(binding_node_id);
1282 if is_implicit_self && snippet != "self" {
1283 // avoid suggesting `mut &self`.
1286 if let Some(&hir::TyKind::Rptr(
1289 mutbl: hir::MutMutable,
1292 )) = ty.map(|t| &t.node)
1294 let borrow_expr_id = self.tcx.hir.get_parent_node(borrowed_node_id);
1296 self.tcx.hir.span(borrow_expr_id),
1297 "consider removing the `&mut`, as it is an \
1298 immutable binding to a mutable reference",
1304 format!("consider changing this to `mut {}`", snippet),
1311 fn report_out_of_scope_escaping_closure_capture(&self,
1312 err: &BckError<'a, 'tcx>,
1315 let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
1318 match self.tcx.sess.source_map().span_to_snippet(err.span) {
1319 Ok(string) => format!("move {}", string),
1320 Err(_) => "move |<args>| <body>".to_string()
1323 self.cannot_capture_in_long_lived_closure(err.span,
1324 &cmt_path_or_string,
1327 .span_suggestion(err.span,
1328 &format!("to force the closure to take ownership of {} \
1329 (and any other referenced variables), \
1330 use the `move` keyword",
1331 cmt_path_or_string),
1334 self.signal_error();
1337 fn region_end_span(&self, region: ty::Region<'tcx>) -> Option<Span> {
1339 ty::ReScope(scope) => {
1340 Some(self.tcx.sess.source_map().end_point(
1341 scope.span(self.tcx, &self.region_scope_tree)))
1347 fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'a, 'tcx>,
1348 error_span: &Span) {
1349 match err.cmt.note {
1350 mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1351 // If this is an `Fn` closure, it simply can't mutate upvars.
1352 // If it's an `FnMut` closure, the original variable was declared immutable.
1353 // We need to determine which is the case here.
1354 let kind = match err.cmt.upvar_cat().unwrap() {
1355 Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1358 if *kind == ty::ClosureKind::Fn {
1359 let closure_node_id =
1360 self.tcx.hir.local_def_id_to_node_id(upvar_id.closure_expr_id);
1361 db.span_help(self.tcx.hir.span(closure_node_id),
1362 "consider changing this closure to take \
1363 self by mutable reference");
1367 if let Categorization::Deref(..) = err.cmt.cat {
1368 db.span_label(*error_span, "cannot borrow as mutable");
1369 } else if let Categorization::Local(local_id) = err.cmt.cat {
1370 let span = self.tcx.hir.span(local_id);
1371 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1372 if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
1373 db.span_label(*error_span, "cannot reborrow mutably");
1374 db.span_label(*error_span, "try removing `&mut` here");
1376 db.span_label(*error_span, "cannot borrow mutably");
1379 db.span_label(*error_span, "cannot borrow mutably");
1381 } else if let Categorization::Interior(ref cmt, _) = err.cmt.cat {
1382 if let mc::MutabilityCategory::McImmutable = cmt.mutbl {
1383 db.span_label(*error_span,
1384 "cannot mutably borrow field of immutable binding");
1390 pub fn append_loan_path_to_string(&self,
1391 loan_path: &LoanPath<'tcx>,
1393 match loan_path.kind {
1394 LpUpvar(ty::UpvarId { var_id: id, closure_expr_id: _ }) => {
1395 out.push_str(&self.tcx.hir.name(self.tcx.hir.hir_to_node_id(id)).as_str());
1398 out.push_str(&self.tcx.hir.name(id).as_str());
1401 LpDowncast(ref lp_base, variant_def_id) => {
1403 self.append_loan_path_to_string(&lp_base, out);
1404 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1405 out.push_str(&self.tcx.item_path_str(variant_def_id));
1409 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(mc::FieldIndex(_, info)))) => {
1410 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1412 out.push_str(&info.as_str());
1415 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement)) => {
1416 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1417 out.push_str("[..]");
1420 LpExtend(ref lp_base, _, LpDeref(_)) => {
1422 self.append_loan_path_to_string(&lp_base, out);
1427 pub fn append_autoderefd_loan_path_to_string(&self,
1428 loan_path: &LoanPath<'tcx>,
1430 match loan_path.kind {
1431 LpExtend(ref lp_base, _, LpDeref(_)) => {
1432 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1433 // rules would normally allow users to omit the `*x`.
1434 // So just serialize such paths to `x.f` or x[3]` respectively.
1435 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1438 LpDowncast(ref lp_base, variant_def_id) => {
1440 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1441 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1442 out.push_str(&self.tcx.item_path_str(variant_def_id));
1446 LpVar(..) | LpUpvar(..) | LpExtend(.., LpInterior(..)) => {
1447 self.append_loan_path_to_string(loan_path, out)
1452 pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1453 let mut result = String::new();
1454 self.append_loan_path_to_string(loan_path, &mut result);
1458 pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1459 cmt.descriptive_string(self.tcx)
1462 pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1463 match opt_loan_path(cmt) {
1464 Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1465 None => self.cmt_to_string(cmt),
1470 impl BitwiseOperator for LoanDataFlowOperator {
1472 fn join(&self, succ: usize, pred: usize) -> usize {
1473 succ | pred // loans from both preds are in scope
1477 impl DataFlowOperator for LoanDataFlowOperator {
1479 fn initial_value(&self) -> bool {
1480 false // no loans in scope by default
1484 impl<'tcx> fmt::Debug for InteriorKind {
1485 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1487 InteriorField(mc::FieldIndex(_, info)) => write!(f, "{}", info),
1488 InteriorElement => write!(f, "[]"),
1493 impl<'tcx> fmt::Debug for Loan<'tcx> {
1494 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1495 write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1501 self.restricted_paths)
1505 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1506 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1509 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_string(id)))
1512 LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => {
1513 let s = ty::tls::with(|tcx| {
1514 let var_node_id = tcx.hir.hir_to_node_id(var_id);
1515 tcx.hir.node_to_string(var_node_id)
1517 write!(f, "$({} captured by id={:?})", s, closure_expr_id)
1520 LpDowncast(ref lp, variant_def_id) => {
1521 let variant_str = if variant_def_id.is_local() {
1522 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1524 format!("{:?}", variant_def_id)
1526 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1529 LpExtend(ref lp, _, LpDeref(_)) => {
1530 write!(f, "{:?}.*", lp)
1533 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1534 write!(f, "{:?}.{:?}", lp, interior)
1540 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1541 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1544 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_user_string(id)))
1547 LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => {
1548 let s = ty::tls::with(|tcx| {
1549 let var_node_id = tcx.hir.hir_to_node_id(var_id);
1550 tcx.hir.node_to_string(var_node_id)
1552 write!(f, "$({} captured by closure)", s)
1555 LpDowncast(ref lp, variant_def_id) => {
1556 let variant_str = if variant_def_id.is_local() {
1557 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1559 format!("{:?}", variant_def_id)
1561 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1564 LpExtend(ref lp, _, LpDeref(_)) => {
1565 write!(f, "{}.*", lp)
1568 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1569 write!(f, "{}.{:?}", lp, interior)