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;
24 use rustc::hir::map as hir_map;
25 use rustc::hir::map::blocks::FnLikeNode;
27 use rustc::middle::dataflow::DataFlowContext;
28 use rustc::middle::dataflow::BitwiseOperator;
29 use rustc::middle::dataflow::DataFlowOperator;
30 use rustc::middle::dataflow::KillFrom;
31 use rustc::middle::borrowck::BorrowCheckResult;
32 use rustc::hir::def_id::{DefId, LocalDefId};
33 use rustc::middle::expr_use_visitor as euv;
34 use rustc::middle::mem_categorization as mc;
35 use rustc::middle::mem_categorization::Categorization;
36 use rustc::middle::mem_categorization::ImmutabilityBlame;
37 use rustc::middle::region;
38 use rustc::middle::free_region::RegionRelations;
39 use rustc::ty::{self, Ty, TyCtxt};
40 use rustc::ty::maps::Providers;
41 use rustc_mir::util::borrowck_errors::{BorrowckErrors, Origin};
42 use rustc::util::nodemap::FxHashSet;
44 use std::cell::RefCell;
47 use std::hash::{Hash, Hasher};
49 use syntax_pos::{MultiSpan, Span};
50 use errors::{DiagnosticBuilder, DiagnosticId};
53 use rustc::hir::intravisit::{self, Visitor};
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 for body_owner_def_id in tcx.body_owners() {
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 -> Rc<BorrowCheckResult>
91 debug!("borrowck(body_owner_def_id={:?})", owner_def_id);
93 let owner_id = tcx.hir.as_local_node_id(owner_def_id).unwrap();
95 match tcx.hir.get(owner_id) {
96 hir_map::NodeStructCtor(_) |
97 hir_map::NodeVariant(_) => {
98 // We get invoked with anything that has MIR, but some of
99 // those things (notably the synthesized constructors from
100 // tuple structs/variants) do not have an associated body
101 // and do not need borrowchecking.
102 return Rc::new(BorrowCheckResult {
103 used_mut_nodes: FxHashSet(),
109 let body_id = tcx.hir.body_owned_by(owner_id);
110 let tables = tcx.typeck_tables_of(owner_def_id);
111 let region_scope_tree = tcx.region_scope_tree(owner_def_id);
112 let body = tcx.hir.body(body_id);
113 let mut bccx = BorrowckCtxt {
119 used_mut_nodes: RefCell::new(FxHashSet()),
122 // Eventually, borrowck will always read the MIR, but at the
123 // moment we do not. So, for now, we always force MIR to be
124 // constructed for a given fn, since this may result in errors
125 // being reported and we want that to happen.
127 // Note that `mir_validated` is a "stealable" result; the
128 // thief, `optimized_mir()`, forces borrowck, so we know that
129 // is not yet stolen.
130 tcx.mir_validated(owner_def_id).borrow();
132 // option dance because you can't capture an uninitialized variable
135 if let Some(AnalysisData { all_loans,
137 move_data: flowed_moves }) =
138 build_borrowck_dataflow_data(&mut bccx, false, body_id,
140 cfg = Some(cfg::CFG::new(bccx.tcx, &body));
141 cfg.as_mut().unwrap()
144 check_loans::check_loans(&mut bccx, &loan_dfcx, &flowed_moves, &all_loans, body);
146 unused::check(&mut bccx, body);
148 Rc::new(BorrowCheckResult {
149 used_mut_nodes: bccx.used_mut_nodes.into_inner(),
153 fn build_borrowck_dataflow_data<'a, 'c, 'tcx, F>(this: &mut BorrowckCtxt<'a, 'tcx>,
154 force_analysis: bool,
155 body_id: hir::BodyId,
157 -> Option<AnalysisData<'a, 'tcx>>
158 where F: FnOnce(&mut BorrowckCtxt<'a, 'tcx>) -> &'c cfg::CFG
160 // Check the body of fn items.
163 let mut visitor = intravisit::IdRangeComputingVisitor::new(&tcx.hir);
164 visitor.visit_body(this.body);
167 let (all_loans, move_data) =
168 gather_loans::gather_loans_in_fn(this, body_id);
170 if !force_analysis && move_data.is_empty() && all_loans.is_empty() {
171 // large arrays of data inserted as constants can take a lot of
172 // time and memory to borrow-check - see issue #36799. However,
173 // they don't have places, so no borrow-check is actually needed.
174 // Recognize that case and skip borrow-checking.
175 debug!("skipping loan propagation for {:?} because of no loans", body_id);
178 debug!("propagating loans in {:?}", body_id);
181 let cfg = get_cfg(this);
183 DataFlowContext::new(this.tcx,
187 LoanDataFlowOperator,
190 for (loan_idx, loan) in all_loans.iter().enumerate() {
191 loan_dfcx.add_gen(loan.gen_scope.item_local_id(), loan_idx);
192 loan_dfcx.add_kill(KillFrom::ScopeEnd,
193 loan.kill_scope.item_local_id(),
196 loan_dfcx.add_kills_from_flow_exits(cfg);
197 loan_dfcx.propagate(cfg, this.body);
199 let flowed_moves = move_data::FlowedMoveData::new(move_data,
205 Some(AnalysisData { all_loans,
207 move_data:flowed_moves })
210 /// Accessor for introspective clients inspecting `AnalysisData` and
211 /// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer.
212 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
213 tcx: TyCtxt<'a, 'tcx, 'tcx>,
214 body_id: hir::BodyId,
216 -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
218 let owner_id = tcx.hir.body_owner(body_id);
219 let owner_def_id = tcx.hir.local_def_id(owner_id);
220 let tables = tcx.typeck_tables_of(owner_def_id);
221 let region_scope_tree = tcx.region_scope_tree(owner_def_id);
222 let body = tcx.hir.body(body_id);
223 let mut bccx = BorrowckCtxt {
229 used_mut_nodes: RefCell::new(FxHashSet()),
232 let dataflow_data = build_borrowck_dataflow_data(&mut bccx, true, body_id, |_| cfg);
233 (bccx, dataflow_data.unwrap())
236 // ----------------------------------------------------------------------
239 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
240 tcx: TyCtxt<'a, 'tcx, 'tcx>,
242 // tables for the current thing we are checking; set to
243 // Some in `borrowck_fn` and cleared later
244 tables: &'a ty::TypeckTables<'tcx>,
246 region_scope_tree: Rc<region::ScopeTree>,
250 body: &'tcx hir::Body,
252 used_mut_nodes: RefCell<FxHashSet<HirId>>,
255 impl<'b, 'tcx: 'b> BorrowckErrors for BorrowckCtxt<'b, 'tcx> {
256 fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
260 -> DiagnosticBuilder<'a>
262 self.tcx.sess.struct_span_err_with_code(sp, msg, code)
265 fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
268 -> DiagnosticBuilder<'a>
270 self.tcx.sess.struct_span_err(sp, msg)
273 fn cancel_if_wrong_origin<'a>(&'a self,
274 mut diag: DiagnosticBuilder<'a>,
276 -> DiagnosticBuilder<'a>
278 if !o.should_emit_errors(self.tcx.sess.borrowck_mode()) {
279 self.tcx.sess.diagnostic().cancel(&mut diag);
285 ///////////////////////////////////////////////////////////////////////////
286 // Loans and loan paths
288 /// Record of a loan that was issued.
289 pub struct Loan<'tcx> {
291 loan_path: Rc<LoanPath<'tcx>>,
292 kind: ty::BorrowKind,
293 restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
295 /// gen_scope indicates where loan is introduced. Typically the
296 /// loan is introduced at the point of the borrow, but in some
297 /// cases, notably method arguments, the loan may be introduced
298 /// only later, once it comes into scope. See also
299 /// `GatherLoanCtxt::compute_gen_scope`.
300 gen_scope: region::Scope,
302 /// kill_scope indicates when the loan goes out of scope. This is
303 /// either when the lifetime expires or when the local variable
304 /// which roots the loan-path goes out of scope, whichever happens
305 /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
306 kill_scope: region::Scope,
308 cause: euv::LoanCause,
311 impl<'tcx> Loan<'tcx> {
312 pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
313 self.loan_path.clone()
318 pub struct LoanPath<'tcx> {
319 kind: LoanPathKind<'tcx>,
323 impl<'tcx> PartialEq for LoanPath<'tcx> {
324 fn eq(&self, that: &LoanPath<'tcx>) -> bool {
325 self.kind == that.kind
329 impl<'tcx> Hash for LoanPath<'tcx> {
330 fn hash<H: Hasher>(&self, state: &mut H) {
331 self.kind.hash(state);
335 #[derive(PartialEq, Eq, Hash, Debug)]
336 pub enum LoanPathKind<'tcx> {
337 LpVar(ast::NodeId), // `x` in README.md
338 LpUpvar(ty::UpvarId), // `x` captured by-value into closure
339 LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
340 LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem<'tcx>)
343 impl<'tcx> LoanPath<'tcx> {
344 fn new(kind: LoanPathKind<'tcx>, ty: Ty<'tcx>) -> LoanPath<'tcx> {
345 LoanPath { kind: kind, ty: ty }
348 fn to_type(&self) -> Ty<'tcx> { self.ty }
350 fn has_downcast(&self) -> bool {
352 LpDowncast(_, _) => true,
353 LpExtend(ref lp, _, LpInterior(_, _)) => {
361 // FIXME (pnkfelix): See discussion here
362 // https://github.com/pnkfelix/rust/commit/
363 // b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
364 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
366 // A local, "cleaned" version of `mc::InteriorKind` that drops
367 // information that is not relevant to loan-path analysis. (In
368 // particular, the distinction between how precisely an array-element
369 // is tracked is irrelevant here.)
370 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
371 pub enum InteriorKind {
372 InteriorField(mc::FieldName),
376 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
377 impl ToInteriorKind for mc::InteriorKind {
378 fn cleaned(self) -> InteriorKind {
380 mc::InteriorField(name) => InteriorField(name),
381 mc::InteriorElement(_) => InteriorElement,
387 // - a pointer dereference (`*P` in README.md)
388 // - a field reference, with an optional definition of the containing
389 // enum variant (`P.f` in README.md)
390 // `DefId` is present when the field is part of struct that is in
391 // a variant of an enum. For instance in:
392 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
393 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
394 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
395 pub enum LoanPathElem<'tcx> {
396 LpDeref(mc::PointerKind<'tcx>),
397 LpInterior(Option<DefId>, InteriorKind),
400 fn closure_to_block(closure_id: LocalDefId,
401 tcx: TyCtxt) -> ast::NodeId {
402 let closure_id = tcx.hir.local_def_id_to_node_id(closure_id);
403 match tcx.hir.get(closure_id) {
404 hir_map::NodeExpr(expr) => match expr.node {
405 hir::ExprClosure(.., body_id, _, _) => {
409 bug!("encountered non-closure id: {}", closure_id)
412 _ => bug!("encountered non-expr id: {}", closure_id)
416 impl<'a, 'tcx> LoanPath<'tcx> {
417 pub fn kill_scope(&self, bccx: &BorrowckCtxt<'a, 'tcx>) -> region::Scope {
420 let hir_id = bccx.tcx.hir.node_to_hir_id(local_id);
421 bccx.region_scope_tree.var_scope(hir_id.local_id)
423 LpUpvar(upvar_id) => {
424 let block_id = closure_to_block(upvar_id.closure_expr_id, bccx.tcx);
425 let hir_id = bccx.tcx.hir.node_to_hir_id(block_id);
426 region::Scope::Node(hir_id.local_id)
428 LpDowncast(ref base, _) |
429 LpExtend(ref base, ..) => base.kill_scope(bccx),
433 fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
434 match (&self.kind, &other.kind) {
435 (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
436 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
437 if id == id2 && opt_variant_id == opt_variant_id2 {
438 base.has_fork(&base2)
442 (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
443 (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&base),
448 fn depth(&self) -> usize {
450 LpExtend(ref base, _, LpDeref(_)) => base.depth(),
451 LpExtend(ref base, _, LpInterior(..)) => base.depth() + 1,
456 fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
457 match (&self.kind, &other.kind) {
458 (&LpExtend(ref base, a, LpInterior(opt_variant_id, id)),
459 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) => {
460 if id == id2 && opt_variant_id == opt_variant_id2 {
461 base.common(&base2).map(|x| {
463 if base.depth() == xd && base2.depth() == xd {
465 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
476 (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
477 (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&other),
478 (&LpVar(id), &LpVar(id2)) => {
480 Some(LoanPath { kind: LpVar(id), ty: self.ty })
485 (&LpUpvar(id), &LpUpvar(id2)) => {
487 Some(LoanPath { kind: LpUpvar(id), ty: self.ty })
497 // Avoid "cannot borrow immutable field `self.x` as mutable" as that implies that a field *can* be
498 // mutable independently of the struct it belongs to. (#35937)
499 pub fn opt_loan_path_is_field<'tcx>(cmt: &mc::cmt<'tcx>) -> (Option<Rc<LoanPath<'tcx>>>, bool) {
500 let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
503 Categorization::Rvalue(..) |
504 Categorization::StaticItem => {
508 Categorization::Local(id) => {
509 (Some(new_lp(LpVar(id))), false)
512 Categorization::Upvar(mc::Upvar { id, .. }) => {
513 (Some(new_lp(LpUpvar(id))), false)
516 Categorization::Deref(ref cmt_base, pk) => {
517 let lp = opt_loan_path_is_field(cmt_base);
519 new_lp(LpExtend(lp, cmt.mutbl, LpDeref(pk)))
523 Categorization::Interior(ref cmt_base, ik) => {
524 (opt_loan_path(cmt_base).map(|lp| {
525 let opt_variant_id = match cmt_base.cat {
526 Categorization::Downcast(_, did) => Some(did),
529 new_lp(LpExtend(lp, cmt.mutbl, LpInterior(opt_variant_id, ik.cleaned())))
533 Categorization::Downcast(ref cmt_base, variant_def_id) => {
534 let lp = opt_loan_path_is_field(cmt_base);
536 new_lp(LpDowncast(lp, variant_def_id))
542 /// Computes the `LoanPath` (if any) for a `cmt`.
543 /// Note that this logic is somewhat duplicated in
544 /// the method `compute()` found in `gather_loans::restrictions`,
545 /// which allows it to share common loan path pieces as it
546 /// traverses the CMT.
547 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
548 opt_loan_path_is_field(cmt).0
551 ///////////////////////////////////////////////////////////////////////////
554 // Errors that can occur
555 #[derive(Debug, PartialEq)]
556 pub enum bckerr_code<'tcx> {
558 /// superscope, subscope, loan cause
559 err_out_of_scope(ty::Region<'tcx>, ty::Region<'tcx>, euv::LoanCause),
560 err_borrowed_pointer_too_short(ty::Region<'tcx>, ty::Region<'tcx>), // loan, ptr
563 // Combination of an error code and the categorization of the expression
565 #[derive(Debug, PartialEq)]
566 pub struct BckError<'tcx> {
568 cause: AliasableViolationKind,
570 code: bckerr_code<'tcx>
573 #[derive(Copy, Clone, Debug, PartialEq)]
574 pub enum AliasableViolationKind {
576 BorrowViolation(euv::LoanCause)
579 #[derive(Copy, Clone, Debug)]
580 pub enum MovedValueUseKind {
585 ///////////////////////////////////////////////////////////////////////////
588 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
589 pub fn is_subregion_of(&self,
590 r_sub: ty::Region<'tcx>,
591 r_sup: ty::Region<'tcx>)
594 let region_rels = RegionRelations::new(self.tcx,
596 &self.region_scope_tree,
597 &self.tables.free_region_map);
598 region_rels.is_subregion_of(r_sub, r_sup)
601 pub fn report(&self, err: BckError<'tcx>) {
602 // Catch and handle some particular cases.
603 match (&err.code, &err.cause) {
604 (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _),
605 &BorrowViolation(euv::ClosureCapture(span))) |
606 (&err_out_of_scope(&ty::ReScope(_), &ty::ReEarlyBound(..), _),
607 &BorrowViolation(euv::ClosureCapture(span))) |
608 (&err_out_of_scope(&ty::ReScope(_), &ty::ReFree(..), _),
609 &BorrowViolation(euv::ClosureCapture(span))) => {
610 return self.report_out_of_scope_escaping_closure_capture(&err, span);
615 self.report_bckerr(&err);
618 pub fn report_use_of_moved_value(&self,
620 use_kind: MovedValueUseKind,
622 the_move: &move_data::Move,
623 moved_lp: &LoanPath<'tcx>,
624 _param_env: ty::ParamEnv<'tcx>) {
625 let (verb, verb_participle) = match use_kind {
626 MovedInUse => ("use", "used"),
627 MovedInCapture => ("capture", "captured"),
630 let (_ol, _moved_lp_msg, mut err, need_note) = match the_move.kind {
631 move_data::Declared => {
632 // If this is an uninitialized variable, just emit a simple warning
634 self.cannot_act_on_uninitialized_variable(use_span,
636 &self.loan_path_to_string(lp),
638 .span_label(use_span, format!("use of possibly uninitialized `{}`",
639 self.loan_path_to_string(lp)))
644 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
645 // normally generate a rather confusing message:
647 // error: use of moved value: `x.b`
648 // note: `x.a` moved here...
650 // What we want to do instead is get the 'common ancestor' of the two moves and
651 // use that for most of the message instead, giving is something like this:
653 // error: use of moved value: `x`
654 // note: `x` moved here (through moving `x.a`)...
656 let common = moved_lp.common(lp);
657 let has_common = common.is_some();
658 let has_fork = moved_lp.has_fork(lp);
659 let (nl, ol, moved_lp_msg) =
660 if has_fork && has_common {
661 let nl = self.loan_path_to_string(&common.unwrap());
663 let moved_lp_msg = format!(" (through moving `{}`)",
664 self.loan_path_to_string(moved_lp));
665 (nl, ol, moved_lp_msg)
667 (self.loan_path_to_string(lp),
668 self.loan_path_to_string(moved_lp),
672 let partial = moved_lp.depth() > lp.depth();
673 let msg = if !has_fork && partial { "partially " }
674 else if has_fork && !has_common { "collaterally "}
676 let mut err = self.cannot_act_on_moved_value(use_span,
681 let need_note = match lp.ty.sty {
682 ty::TypeVariants::TyClosure(id, _) => {
683 let node_id = self.tcx.hir.as_local_node_id(id).unwrap();
684 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
685 if let Some((span, name)) = self.tables.closure_kind_origins().get(hir_id) {
686 err.span_note(*span, &format!(
687 "closure cannot be invoked more than once because \
688 it moves the variable `{}` out of its environment",
698 (ol, moved_lp_msg, err, need_note)
702 // Get type of value and span where it was previously
704 let node_id = self.tcx.hir.hir_to_node_id(hir::HirId {
705 owner: self.body.value.hir_id.owner,
706 local_id: the_move.id
708 let (move_span, move_note) = match the_move.kind {
709 move_data::Declared => {
713 move_data::MoveExpr |
714 move_data::MovePat => (self.tcx.hir.span(node_id), ""),
716 move_data::Captured =>
717 (match self.tcx.hir.expect_expr(node_id).node {
718 hir::ExprClosure(.., fn_decl_span, _) => fn_decl_span,
719 ref r => bug!("Captured({:?}) maps to non-closure: {:?}",
721 }, " (into closure)"),
724 // Annotate the use and the move in the span. Watch out for
725 // the case where the use and the move are the same. This
726 // means the use is in a loop.
727 err = if use_span == move_span {
730 format!("value moved{} here in previous iteration of loop",
734 err.span_label(use_span, format!("value {} here after move", verb_participle));
735 err.span_label(move_span, format!("value moved{} here", move_note));
741 "move occurs because {} has type `{}`, which does not implement the `Copy` trait",
742 if moved_lp.has_downcast() {
743 "the value".to_string()
745 format!("`{}`", self.loan_path_to_string(moved_lp))
750 // Note: we used to suggest adding a `ref binding` or calling
751 // `clone` but those suggestions have been removed because
752 // they are often not what you actually want to do, and were
753 // not considered particularly helpful.
758 pub fn report_partial_reinitialization_of_uninitialized_structure(
761 lp: &LoanPath<'tcx>) {
762 self.cannot_partially_reinit_an_uninit_struct(span,
763 &self.loan_path_to_string(lp),
768 pub fn report_reassigned_immutable_variable(&self,
772 &move_data::Assignment) {
773 let mut err = self.cannot_reassign_immutable(span,
774 &self.loan_path_to_string(lp),
777 err.span_label(span, "cannot assign twice to immutable variable");
778 if span != assign.span {
779 err.span_label(assign.span, format!("first assignment to `{}`",
780 self.loan_path_to_string(lp)));
785 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(&self,
789 -> DiagnosticBuilder<'a> {
790 self.tcx.sess.struct_span_err_with_code(s, msg, code)
793 pub fn span_err_with_code<S: Into<MultiSpan>>(
799 self.tcx.sess.span_err_with_code(s, msg, code);
802 fn report_bckerr(&self, err: &BckError<'tcx>) {
803 let error_span = err.span.clone();
807 let descr = match err.cmt.note {
808 mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
809 self.cmt_to_string(&err.cmt)
811 _ => match opt_loan_path_is_field(&err.cmt) {
813 format!("{} of {} binding",
814 self.cmt_to_string(&err.cmt),
815 err.cmt.mutbl.to_user_str())
820 err.cmt.mutbl.to_user_str(),
821 self.cmt_to_string(&err.cmt))
824 (Some(lp), true) => {
825 format!("{} `{}` of {} binding",
826 self.cmt_to_string(&err.cmt),
827 self.loan_path_to_string(&lp),
828 err.cmt.mutbl.to_user_str())
830 (Some(lp), false) => {
831 format!("{} {} `{}`",
832 err.cmt.mutbl.to_user_str(),
833 self.cmt_to_string(&err.cmt),
834 self.loan_path_to_string(&lp))
839 let mut db = match err.cause {
840 MutabilityViolation => {
841 let mut db = self.cannot_assign(error_span, &descr, Origin::Ast);
842 if let mc::NoteClosureEnv(upvar_id) = err.cmt.note {
843 let node_id = self.tcx.hir.hir_to_node_id(upvar_id.var_id);
844 let sp = self.tcx.hir.span(node_id);
845 let fn_closure_msg = "`Fn` closures cannot capture their enclosing \
846 environment for modifications";
847 match (self.tcx.sess.codemap().span_to_snippet(sp), &err.cmt.cat) {
848 (_, &Categorization::Upvar(mc::Upvar {
849 kind: ty::ClosureKind::Fn, ..
851 db.note(fn_closure_msg);
852 // we should point at the cause for this closure being
853 // identified as `Fn` (like in signature of method this
854 // closure was passed into)
856 (Ok(ref snippet), ref cat) => {
857 let msg = &format!("consider making `{}` mutable", snippet);
858 let suggestion = format!("mut {}", snippet);
860 if let &Categorization::Deref(ref cmt, _) = cat {
861 if let Categorization::Upvar(mc::Upvar {
862 kind: ty::ClosureKind::Fn, ..
864 db.note(fn_closure_msg);
866 db.span_suggestion(sp, msg, suggestion);
869 db.span_suggestion(sp, msg, suggestion);
873 db.span_help(sp, "consider making this binding mutable");
879 BorrowViolation(euv::ClosureCapture(_)) => {
880 self.closure_cannot_assign_to_borrowed(error_span, &descr, Origin::Ast)
882 BorrowViolation(euv::OverloadedOperator) |
883 BorrowViolation(euv::AddrOf) |
884 BorrowViolation(euv::RefBinding) |
885 BorrowViolation(euv::AutoRef) |
886 BorrowViolation(euv::AutoUnsafe) |
887 BorrowViolation(euv::ForLoop) |
888 BorrowViolation(euv::MatchDiscriminant) => {
889 self.cannot_borrow_path_as_mutable(error_span, &descr, Origin::Ast)
891 BorrowViolation(euv::ClosureInvocation) => {
893 "err_mutbl with a closure invocation");
897 self.note_and_explain_mutbl_error(&mut db, &err, &error_span);
898 self.note_immutability_blame(&mut db, err.cmt.immutability_blame());
901 err_out_of_scope(super_scope, sub_scope, cause) => {
902 let msg = match opt_loan_path(&err.cmt) {
903 None => "borrowed value".to_string(),
905 format!("`{}`", self.loan_path_to_string(&lp))
909 let mut db = self.path_does_not_live_long_enough(error_span, &msg, Origin::Ast);
910 let value_kind = match err.cmt.cat {
911 mc::Categorization::Rvalue(..) => "temporary value",
912 _ => "borrowed value",
915 let is_closure = match cause {
916 euv::ClosureCapture(s) => {
917 // The primary span starts out as the closure creation point.
918 // Change the primary span here to highlight the use of the variable
919 // in the closure, because it seems more natural. Highlight
920 // closure creation point as a secondary span.
921 match db.span.primary_span() {
923 db.span = MultiSpan::from_span(s);
924 db.span_label(primary, "capture occurs here");
925 db.span_label(s, format!("{} does not live long enough",
933 db.span_label(error_span, format!("{} does not live long enough",
939 let sub_span = self.region_end_span(sub_scope);
940 let super_span = self.region_end_span(super_scope);
942 match (sub_span, super_span) {
943 (Some(s1), Some(s2)) if s1 == s2 => {
945 let msg = match opt_loan_path(&err.cmt) {
946 None => value_kind.to_string(),
948 format!("`{}`", self.loan_path_to_string(&lp))
952 format!("{} dropped here while still borrowed", msg));
954 db.span_label(s1, format!("{} dropped before borrower", value_kind));
956 db.note("values in a scope are dropped in the opposite order \
959 (Some(s1), Some(s2)) if !is_closure => {
960 let msg = match opt_loan_path(&err.cmt) {
961 None => value_kind.to_string(),
963 format!("`{}`", self.loan_path_to_string(&lp))
966 db.span_label(s2, format!("{} dropped here while still borrowed", msg));
967 db.span_label(s1, format!("{} needs to live until here", value_kind));
972 db.span_label(s, format!("{} needs to live until here",
976 self.tcx.note_and_explain_region(
977 &self.region_scope_tree,
979 "borrowed value must be valid for ",
986 db.span_label(s, format!("{} only lives until here", value_kind));
989 self.tcx.note_and_explain_region(
990 &self.region_scope_tree,
992 "...but borrowed value is only valid for ",
1000 if let ty::ReScope(scope) = *super_scope {
1001 let node_id = scope.node_id(self.tcx, &self.region_scope_tree);
1002 match self.tcx.hir.find(node_id) {
1003 Some(hir_map::NodeStmt(_)) => {
1004 db.note("consider using a `let` binding to increase its lifetime");
1012 err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1013 let descr = self.cmt_to_path_or_string(&err.cmt);
1014 let mut db = self.lifetime_too_short_for_reborrow(error_span, &descr, Origin::Ast);
1015 let descr = match opt_loan_path(&err.cmt) {
1017 format!("`{}`", self.loan_path_to_string(&lp))
1019 None => self.cmt_to_string(&err.cmt),
1021 self.tcx.note_and_explain_region(
1022 &self.region_scope_tree,
1024 &format!("{} would have to be valid for ",
1028 self.tcx.note_and_explain_region(
1029 &self.region_scope_tree,
1031 &format!("...but {} is only valid for ", descr),
1040 pub fn report_aliasability_violation(&self,
1042 kind: AliasableViolationKind,
1043 cause: mc::AliasableReason,
1044 cmt: mc::cmt<'tcx>) {
1045 let mut is_closure = false;
1046 let prefix = match kind {
1047 MutabilityViolation => {
1048 "cannot assign to data"
1050 BorrowViolation(euv::ClosureCapture(_)) |
1051 BorrowViolation(euv::OverloadedOperator) |
1052 BorrowViolation(euv::AddrOf) |
1053 BorrowViolation(euv::AutoRef) |
1054 BorrowViolation(euv::AutoUnsafe) |
1055 BorrowViolation(euv::RefBinding) |
1056 BorrowViolation(euv::MatchDiscriminant) => {
1057 "cannot borrow data mutably"
1060 BorrowViolation(euv::ClosureInvocation) => {
1062 "closure invocation"
1065 BorrowViolation(euv::ForLoop) => {
1071 mc::AliasableStaticMut => {
1072 // This path cannot occur. `static mut X` is not checked
1073 // for aliasability violations.
1074 span_bug!(span, "aliasability violation for static mut `{}`", prefix)
1076 mc::AliasableStatic | mc::AliasableBorrowed => {}
1078 let blame = cmt.immutability_blame();
1079 let mut err = match blame {
1080 Some(ImmutabilityBlame::ClosureEnv(id)) => {
1081 // FIXME: the distinction between these 2 messages looks wrong.
1082 let help_msg = if let BorrowViolation(euv::ClosureCapture(_)) = kind {
1083 // The aliasability violation with closure captures can
1084 // happen for nested closures, so we know the enclosing
1085 // closure incorrectly accepts an `Fn` while it needs to
1087 "consider changing this to accept closures that implement `FnMut`"
1090 "consider changing this closure to take self by mutable reference"
1092 let node_id = self.tcx.hir.local_def_id_to_node_id(id);
1093 let help_span = self.tcx.hir.span(node_id);
1094 self.cannot_act_on_capture_in_sharable_fn(span,
1096 (help_span, help_msg),
1100 self.cannot_assign_into_immutable_reference(span, prefix,
1104 self.note_immutability_blame(&mut err, blame);
1107 err.help("closures behind references must be called via `&mut`");
1112 /// Given a type, if it is an immutable reference, return a suggestion to make it mutable
1113 fn suggest_mut_for_immutable(&self, pty: &hir::Ty, is_implicit_self: bool) -> Option<String> {
1114 // Check wether the argument is an immutable reference
1115 debug!("suggest_mut_for_immutable({:?}, {:?})", pty, is_implicit_self);
1116 if let hir::TyRptr(lifetime, hir::MutTy {
1117 mutbl: hir::Mutability::MutImmutable,
1120 // Account for existing lifetimes when generating the message
1121 let pointee_snippet = match self.tcx.sess.codemap().span_to_snippet(ty.span) {
1122 Ok(snippet) => snippet,
1126 let lifetime_snippet = if !lifetime.is_elided() {
1127 format!("{} ", match self.tcx.sess.codemap().span_to_snippet(lifetime.span) {
1128 Ok(lifetime_snippet) => lifetime_snippet,
1134 Some(format!("use `&{}mut {}` here to make mutable",
1136 if is_implicit_self { "self" } else { &*pointee_snippet }))
1142 fn local_binding_mode(&self, node_id: ast::NodeId) -> ty::BindingMode {
1143 let pat = match self.tcx.hir.get(node_id) {
1144 hir_map::Node::NodeBinding(pat) => pat,
1145 node => bug!("bad node for local: {:?}", node)
1149 hir::PatKind::Binding(..) => {
1151 .pat_binding_modes()
1153 .expect("missing binding mode")
1155 _ => bug!("local is not a binding: {:?}", pat)
1159 fn local_ty(&self, node_id: ast::NodeId) -> (Option<&hir::Ty>, bool) {
1160 let parent = self.tcx.hir.get_parent_node(node_id);
1161 let parent_node = self.tcx.hir.get(parent);
1163 // The parent node is like a fn
1164 if let Some(fn_like) = FnLikeNode::from_node(parent_node) {
1165 // `nid`'s parent's `Body`
1166 let fn_body = self.tcx.hir.body(fn_like.body());
1167 // Get the position of `node_id` in the arguments list
1168 let arg_pos = fn_body.arguments.iter().position(|arg| arg.pat.id == node_id);
1169 if let Some(i) = arg_pos {
1170 // The argument's `Ty`
1171 (Some(&fn_like.decl().inputs[i]),
1172 i == 0 && fn_like.decl().has_implicit_self)
1181 fn note_immutability_blame(&self,
1182 db: &mut DiagnosticBuilder,
1183 blame: Option<ImmutabilityBlame>) {
1186 Some(ImmutabilityBlame::ClosureEnv(_)) => {}
1187 Some(ImmutabilityBlame::ImmLocal(node_id)) => {
1188 let let_span = self.tcx.hir.span(node_id);
1189 if let ty::BindByValue(..) = self.local_binding_mode(node_id) {
1190 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(let_span) {
1191 let (_, is_implicit_self) = self.local_ty(node_id);
1192 if is_implicit_self && snippet != "self" {
1193 // avoid suggesting `mut &self`.
1198 format!("consider changing this to `mut {}`", snippet)
1203 Some(ImmutabilityBlame::LocalDeref(node_id)) => {
1204 let let_span = self.tcx.hir.span(node_id);
1205 match self.local_binding_mode(node_id) {
1206 ty::BindByReference(..) => {
1207 let snippet = self.tcx.sess.codemap().span_to_snippet(let_span);
1208 if let Ok(snippet) = snippet {
1211 format!("consider changing this to `{}`",
1212 snippet.replace("ref ", "ref mut "))
1216 ty::BindByValue(..) => {
1217 if let (Some(local_ty), is_implicit_self) = self.local_ty(node_id) {
1219 self.suggest_mut_for_immutable(local_ty, is_implicit_self) {
1220 db.span_label(local_ty.span, msg);
1226 Some(ImmutabilityBlame::AdtFieldDeref(_, field)) => {
1227 let node_id = match self.tcx.hir.as_local_node_id(field.did) {
1228 Some(node_id) => node_id,
1232 if let hir_map::Node::NodeField(ref field) = self.tcx.hir.get(node_id) {
1233 if let Some(msg) = self.suggest_mut_for_immutable(&field.ty, false) {
1234 db.span_label(field.ty.span, msg);
1241 fn report_out_of_scope_escaping_closure_capture(&self,
1242 err: &BckError<'tcx>,
1245 let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
1248 match self.tcx.sess.codemap().span_to_snippet(err.span) {
1249 Ok(string) => format!("move {}", string),
1250 Err(_) => format!("move |<args>| <body>")
1253 self.cannot_capture_in_long_lived_closure(err.span,
1254 &cmt_path_or_string,
1257 .span_suggestion(err.span,
1258 &format!("to force the closure to take ownership of {} \
1259 (and any other referenced variables), \
1260 use the `move` keyword",
1261 cmt_path_or_string),
1266 fn region_end_span(&self, region: ty::Region<'tcx>) -> Option<Span> {
1268 ty::ReScope(scope) => {
1269 Some(self.tcx.sess.codemap().end_point(
1270 scope.span(self.tcx, &self.region_scope_tree)))
1276 fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'tcx>,
1277 error_span: &Span) {
1278 match err.cmt.note {
1279 mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1280 // If this is an `Fn` closure, it simply can't mutate upvars.
1281 // If it's an `FnMut` closure, the original variable was declared immutable.
1282 // We need to determine which is the case here.
1283 let kind = match err.cmt.upvar().unwrap().cat {
1284 Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1287 if kind == ty::ClosureKind::Fn {
1288 let closure_node_id =
1289 self.tcx.hir.local_def_id_to_node_id(upvar_id.closure_expr_id);
1290 db.span_help(self.tcx.hir.span(closure_node_id),
1291 "consider changing this closure to take \
1292 self by mutable reference");
1296 if let Categorization::Deref(..) = err.cmt.cat {
1297 db.span_label(*error_span, "cannot borrow as mutable");
1298 } else if let Categorization::Local(local_id) = err.cmt.cat {
1299 let span = self.tcx.hir.span(local_id);
1300 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
1301 if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
1302 db.span_label(*error_span, "cannot reborrow mutably");
1303 db.span_label(*error_span, "try removing `&mut` here");
1305 db.span_label(*error_span, "cannot borrow mutably");
1308 db.span_label(*error_span, "cannot borrow mutably");
1310 } else if let Categorization::Interior(ref cmt, _) = err.cmt.cat {
1311 if let mc::MutabilityCategory::McImmutable = cmt.mutbl {
1312 db.span_label(*error_span,
1313 "cannot mutably borrow field of immutable binding");
1319 pub fn append_loan_path_to_string(&self,
1320 loan_path: &LoanPath<'tcx>,
1322 match loan_path.kind {
1323 LpUpvar(ty::UpvarId { var_id: id, closure_expr_id: _ }) => {
1324 out.push_str(&self.tcx.hir.name(self.tcx.hir.hir_to_node_id(id)).as_str());
1327 out.push_str(&self.tcx.hir.name(id).as_str());
1330 LpDowncast(ref lp_base, variant_def_id) => {
1332 self.append_loan_path_to_string(&lp_base, out);
1333 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1334 out.push_str(&self.tcx.item_path_str(variant_def_id));
1338 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(fname))) => {
1339 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1341 mc::NamedField(fname) => {
1343 out.push_str(&fname.as_str());
1345 mc::PositionalField(idx) => {
1347 out.push_str(&idx.to_string());
1352 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement)) => {
1353 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1354 out.push_str("[..]");
1357 LpExtend(ref lp_base, _, LpDeref(_)) => {
1359 self.append_loan_path_to_string(&lp_base, out);
1364 pub fn append_autoderefd_loan_path_to_string(&self,
1365 loan_path: &LoanPath<'tcx>,
1367 match loan_path.kind {
1368 LpExtend(ref lp_base, _, LpDeref(_)) => {
1369 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1370 // rules would normally allow users to omit the `*x`.
1371 // So just serialize such paths to `x.f` or x[3]` respectively.
1372 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1375 LpDowncast(ref lp_base, variant_def_id) => {
1377 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1378 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1379 out.push_str(&self.tcx.item_path_str(variant_def_id));
1383 LpVar(..) | LpUpvar(..) | LpExtend(.., LpInterior(..)) => {
1384 self.append_loan_path_to_string(loan_path, out)
1389 pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1390 let mut result = String::new();
1391 self.append_loan_path_to_string(loan_path, &mut result);
1395 pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1396 cmt.descriptive_string(self.tcx)
1399 pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt<'tcx>) -> String {
1400 match opt_loan_path(cmt) {
1401 Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1402 None => self.cmt_to_string(cmt),
1407 impl BitwiseOperator for LoanDataFlowOperator {
1409 fn join(&self, succ: usize, pred: usize) -> usize {
1410 succ | pred // loans from both preds are in scope
1414 impl DataFlowOperator for LoanDataFlowOperator {
1416 fn initial_value(&self) -> bool {
1417 false // no loans in scope by default
1421 impl<'tcx> fmt::Debug for InteriorKind {
1422 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1424 InteriorField(mc::NamedField(fld)) => write!(f, "{}", fld),
1425 InteriorField(mc::PositionalField(i)) => write!(f, "#{}", i),
1426 InteriorElement => write!(f, "[]"),
1431 impl<'tcx> fmt::Debug for Loan<'tcx> {
1432 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1433 write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1439 self.restricted_paths)
1443 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1444 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1447 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_string(id)))
1450 LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => {
1451 let s = ty::tls::with(|tcx| {
1452 let var_node_id = tcx.hir.hir_to_node_id(var_id);
1453 tcx.hir.node_to_string(var_node_id)
1455 write!(f, "$({} captured by id={:?})", s, closure_expr_id)
1458 LpDowncast(ref lp, variant_def_id) => {
1459 let variant_str = if variant_def_id.is_local() {
1460 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1462 format!("{:?}", variant_def_id)
1464 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1467 LpExtend(ref lp, _, LpDeref(_)) => {
1468 write!(f, "{:?}.*", lp)
1471 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1472 write!(f, "{:?}.{:?}", lp, interior)
1478 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1479 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1482 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_user_string(id)))
1485 LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => {
1486 let s = ty::tls::with(|tcx| {
1487 let var_node_id = tcx.hir.hir_to_node_id(var_id);
1488 tcx.hir.node_to_string(var_node_id)
1490 write!(f, "$({} captured by closure)", s)
1493 LpDowncast(ref lp, variant_def_id) => {
1494 let variant_str = if variant_def_id.is_local() {
1495 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1497 format!("{:?}", variant_def_id)
1499 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1502 LpExtend(ref lp, _, LpDeref(_)) => {
1503 write!(f, "{}.*", lp)
1506 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1507 write!(f, "{}.{:?}", lp, interior)