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 pub use self::mir::elaborate_drops::ElaborateDrops;
23 use self::InteriorKind::*;
25 use rustc::hir::map as hir_map;
26 use rustc::hir::map::blocks::FnLikeNode;
28 use rustc::middle::dataflow::DataFlowContext;
29 use rustc::middle::dataflow::BitwiseOperator;
30 use rustc::middle::dataflow::DataFlowOperator;
31 use rustc::middle::dataflow::KillFrom;
32 use rustc::hir::def_id::DefId;
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::ty::{self, TyCtxt};
39 use rustc::ty::maps::Providers;
43 use std::hash::{Hash, Hasher};
45 use syntax_pos::{DUMMY_SP, MultiSpan, Span};
46 use errors::DiagnosticBuilder;
49 use rustc::hir::intravisit::{self, Visitor};
59 #[derive(Clone, Copy)]
60 pub struct LoanDataFlowOperator;
62 pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
64 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
65 tcx.visit_all_bodies_in_krate(|body_owner_def_id, _body_id| {
66 ty::queries::borrowck::get(tcx, DUMMY_SP, body_owner_def_id);
70 pub fn provide(providers: &mut Providers) {
71 *providers = Providers {
77 /// Collection of conclusions determined via borrow checker analyses.
78 pub struct AnalysisData<'a, 'tcx: 'a> {
79 pub all_loans: Vec<Loan<'tcx>>,
80 pub loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>,
81 pub move_data: move_data::FlowedMoveData<'a, 'tcx>,
84 fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId) {
85 debug!("borrowck(body_owner_def_id={:?})", owner_def_id);
87 let owner_id = tcx.hir.as_local_node_id(owner_def_id).unwrap();
88 let body_id = tcx.hir.body_owned_by(owner_id);
89 let attributes = tcx.get_attrs(owner_def_id);
90 let tables = tcx.item_tables(owner_def_id);
92 let mut bccx = &mut BorrowckCtxt {
97 let body = bccx.tcx.hir.body(body_id);
99 if bccx.tcx.has_attr(owner_def_id, "rustc_mir_borrowck") {
100 mir::borrowck_mir(bccx, owner_id, &attributes);
103 let cfg = cfg::CFG::new(bccx.tcx, &body);
104 let AnalysisData { all_loans,
106 move_data: flowed_moves } =
107 build_borrowck_dataflow_data(bccx, &cfg, body_id);
109 move_data::fragments::instrument_move_fragments(&flowed_moves.move_data,
112 move_data::fragments::build_unfragmented_map(bccx,
113 &flowed_moves.move_data,
116 check_loans::check_loans(bccx, &loan_dfcx, &flowed_moves, &all_loans, body);
119 fn build_borrowck_dataflow_data<'a, 'tcx>(this: &mut BorrowckCtxt<'a, 'tcx>,
121 body_id: hir::BodyId)
122 -> AnalysisData<'a, 'tcx>
124 // Check the body of fn items.
126 let body = tcx.hir.body(body_id);
128 let mut visitor = intravisit::IdRangeComputingVisitor::new(&tcx.hir);
129 visitor.visit_body(body);
132 let (all_loans, move_data) =
133 gather_loans::gather_loans_in_fn(this, body_id);
136 DataFlowContext::new(this.tcx,
140 LoanDataFlowOperator,
143 for (loan_idx, loan) in all_loans.iter().enumerate() {
144 loan_dfcx.add_gen(loan.gen_scope.node_id(&tcx.region_maps), loan_idx);
145 loan_dfcx.add_kill(KillFrom::ScopeEnd,
146 loan.kill_scope.node_id(&tcx.region_maps), loan_idx);
148 loan_dfcx.add_kills_from_flow_exits(cfg);
149 loan_dfcx.propagate(cfg, body);
151 let flowed_moves = move_data::FlowedMoveData::new(move_data,
157 AnalysisData { all_loans: all_loans,
159 move_data:flowed_moves }
162 /// Accessor for introspective clients inspecting `AnalysisData` and
163 /// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer.
164 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
165 tcx: TyCtxt<'a, 'tcx, 'tcx>,
166 body_id: hir::BodyId,
168 -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
170 let owner_id = tcx.hir.body_owner(body_id);
171 let owner_def_id = tcx.hir.local_def_id(owner_id);
172 let tables = tcx.item_tables(owner_def_id);
174 let mut bccx = BorrowckCtxt {
179 let dataflow_data = build_borrowck_dataflow_data(&mut bccx, cfg, body_id);
180 (bccx, dataflow_data)
183 // ----------------------------------------------------------------------
186 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
187 tcx: TyCtxt<'a, 'tcx, 'tcx>,
189 // tables for the current thing we are checking; set to
190 // Some in `borrowck_fn` and cleared later
191 tables: &'a ty::TypeckTables<'tcx>,
194 ///////////////////////////////////////////////////////////////////////////
195 // Loans and loan paths
197 /// Record of a loan that was issued.
198 pub struct Loan<'tcx> {
200 loan_path: Rc<LoanPath<'tcx>>,
201 kind: ty::BorrowKind,
202 restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
204 /// gen_scope indicates where loan is introduced. Typically the
205 /// loan is introduced at the point of the borrow, but in some
206 /// cases, notably method arguments, the loan may be introduced
207 /// only later, once it comes into scope. See also
208 /// `GatherLoanCtxt::compute_gen_scope`.
209 gen_scope: region::CodeExtent,
211 /// kill_scope indicates when the loan goes out of scope. This is
212 /// either when the lifetime expires or when the local variable
213 /// which roots the loan-path goes out of scope, whichever happens
214 /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
215 kill_scope: region::CodeExtent,
217 cause: euv::LoanCause,
220 impl<'tcx> Loan<'tcx> {
221 pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
222 self.loan_path.clone()
227 pub struct LoanPath<'tcx> {
228 kind: LoanPathKind<'tcx>,
232 impl<'tcx> PartialEq for LoanPath<'tcx> {
233 fn eq(&self, that: &LoanPath<'tcx>) -> bool {
234 self.kind == that.kind
238 impl<'tcx> Hash for LoanPath<'tcx> {
239 fn hash<H: Hasher>(&self, state: &mut H) {
240 self.kind.hash(state);
244 #[derive(PartialEq, Eq, Hash, Debug)]
245 pub enum LoanPathKind<'tcx> {
246 LpVar(ast::NodeId), // `x` in README.md
247 LpUpvar(ty::UpvarId), // `x` captured by-value into closure
248 LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
249 LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem<'tcx>)
252 impl<'tcx> LoanPath<'tcx> {
253 fn new(kind: LoanPathKind<'tcx>, ty: ty::Ty<'tcx>) -> LoanPath<'tcx> {
254 LoanPath { kind: kind, ty: ty }
257 fn to_type(&self) -> ty::Ty<'tcx> { self.ty }
260 // FIXME (pnkfelix): See discussion here
261 // https://github.com/pnkfelix/rust/commit/
262 // b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
263 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
265 // A local, "cleaned" version of `mc::InteriorKind` that drops
266 // information that is not relevant to loan-path analysis. (In
267 // particular, the distinction between how precisely an array-element
268 // is tracked is irrelevant here.)
269 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
270 pub enum InteriorKind {
271 InteriorField(mc::FieldName),
272 InteriorElement(mc::ElementKind),
275 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
276 impl ToInteriorKind for mc::InteriorKind {
277 fn cleaned(self) -> InteriorKind {
279 mc::InteriorField(name) => InteriorField(name),
280 mc::InteriorElement(_, elem_kind) => InteriorElement(elem_kind),
286 // - a pointer dereference (`*LV` in README.md)
287 // - a field reference, with an optional definition of the containing
288 // enum variant (`LV.f` in README.md)
289 // `DefId` is present when the field is part of struct that is in
290 // a variant of an enum. For instance in:
291 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
292 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
293 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
294 pub enum LoanPathElem<'tcx> {
295 LpDeref(mc::PointerKind<'tcx>),
296 LpInterior(Option<DefId>, InteriorKind),
299 pub fn closure_to_block(closure_id: ast::NodeId,
300 tcx: TyCtxt) -> ast::NodeId {
301 match tcx.hir.get(closure_id) {
302 hir_map::NodeExpr(expr) => match expr.node {
303 hir::ExprClosure(.., body_id, _) => {
307 bug!("encountered non-closure id: {}", closure_id)
310 _ => bug!("encountered non-expr id: {}", closure_id)
314 impl<'a, 'tcx> LoanPath<'tcx> {
315 pub fn kill_scope(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> region::CodeExtent {
317 LpVar(local_id) => tcx.region_maps.var_scope(local_id),
318 LpUpvar(upvar_id) => {
319 let block_id = closure_to_block(upvar_id.closure_expr_id, tcx);
320 tcx.region_maps.node_extent(block_id)
322 LpDowncast(ref base, _) |
323 LpExtend(ref base, ..) => base.kill_scope(tcx),
327 fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
328 match (&self.kind, &other.kind) {
329 (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
330 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
331 if id == id2 && opt_variant_id == opt_variant_id2 {
332 base.has_fork(&base2)
336 (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
337 (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&base),
342 fn depth(&self) -> usize {
344 LpExtend(ref base, _, LpDeref(_)) => base.depth(),
345 LpExtend(ref base, _, LpInterior(..)) => base.depth() + 1,
350 fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
351 match (&self.kind, &other.kind) {
352 (&LpExtend(ref base, a, LpInterior(opt_variant_id, id)),
353 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) => {
354 if id == id2 && opt_variant_id == opt_variant_id2 {
355 base.common(&base2).map(|x| {
357 if base.depth() == xd && base2.depth() == xd {
359 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
370 (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
371 (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&other),
372 (&LpVar(id), &LpVar(id2)) => {
374 Some(LoanPath { kind: LpVar(id), ty: self.ty })
379 (&LpUpvar(id), &LpUpvar(id2)) => {
381 Some(LoanPath { kind: LpUpvar(id), ty: self.ty })
391 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
392 //! Computes the `LoanPath` (if any) for a `cmt`.
393 //! Note that this logic is somewhat duplicated in
394 //! the method `compute()` found in `gather_loans::restrictions`,
395 //! which allows it to share common loan path pieces as it
396 //! traverses the CMT.
398 let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
401 Categorization::Rvalue(..) |
402 Categorization::StaticItem => {
406 Categorization::Local(id) => {
407 Some(new_lp(LpVar(id)))
410 Categorization::Upvar(mc::Upvar { id, .. }) => {
411 Some(new_lp(LpUpvar(id)))
414 Categorization::Deref(ref cmt_base, _, pk) => {
415 opt_loan_path(cmt_base).map(|lp| {
416 new_lp(LpExtend(lp, cmt.mutbl, LpDeref(pk)))
420 Categorization::Interior(ref cmt_base, ik) => {
421 opt_loan_path(cmt_base).map(|lp| {
422 let opt_variant_id = match cmt_base.cat {
423 Categorization::Downcast(_, did) => Some(did),
426 new_lp(LpExtend(lp, cmt.mutbl, LpInterior(opt_variant_id, ik.cleaned())))
430 Categorization::Downcast(ref cmt_base, variant_def_id) =>
431 opt_loan_path(cmt_base)
433 new_lp(LpDowncast(lp, variant_def_id))
439 ///////////////////////////////////////////////////////////////////////////
442 // Errors that can occur
443 #[derive(Debug, PartialEq)]
444 pub enum bckerr_code<'tcx> {
446 /// superscope, subscope, loan cause
447 err_out_of_scope(&'tcx ty::Region, &'tcx ty::Region, euv::LoanCause),
448 err_borrowed_pointer_too_short(&'tcx ty::Region, &'tcx ty::Region), // loan, ptr
451 // Combination of an error code and the categorization of the expression
453 #[derive(Debug, PartialEq)]
454 pub struct BckError<'tcx> {
456 cause: AliasableViolationKind,
458 code: bckerr_code<'tcx>
461 #[derive(Copy, Clone, Debug, PartialEq)]
462 pub enum AliasableViolationKind {
464 BorrowViolation(euv::LoanCause)
467 #[derive(Copy, Clone, Debug)]
468 pub enum MovedValueUseKind {
473 ///////////////////////////////////////////////////////////////////////////
476 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
477 pub fn is_subregion_of(&self,
478 r_sub: &'tcx ty::Region,
479 r_sup: &'tcx ty::Region)
482 self.tables.free_region_map.is_subregion_of(self.tcx, r_sub, r_sup)
485 pub fn report(&self, err: BckError<'tcx>) {
486 // Catch and handle some particular cases.
487 match (&err.code, &err.cause) {
488 (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _),
489 &BorrowViolation(euv::ClosureCapture(span))) |
490 (&err_out_of_scope(&ty::ReScope(_), &ty::ReFree(..), _),
491 &BorrowViolation(euv::ClosureCapture(span))) => {
492 return self.report_out_of_scope_escaping_closure_capture(&err, span);
497 let mut db = self.bckerr_to_diag(&err);
498 self.note_and_explain_bckerr(&mut db, err);
502 pub fn report_use_of_moved_value(&self,
504 use_kind: MovedValueUseKind,
506 the_move: &move_data::Move,
507 moved_lp: &LoanPath<'tcx>,
508 _param_env: &ty::ParameterEnvironment<'tcx>) {
509 let (verb, verb_participle) = match use_kind {
510 MovedInUse => ("use", "used"),
511 MovedInCapture => ("capture", "captured"),
514 let (_ol, _moved_lp_msg, mut err) = match the_move.kind {
515 move_data::Declared => {
516 // If this is an uninitialized variable, just emit a simple warning
519 self.tcx.sess, use_span, E0381,
520 "{} of possibly uninitialized variable: `{}`",
522 self.loan_path_to_string(lp))
523 .span_label(use_span, &format!("use of possibly uninitialized `{}`",
524 self.loan_path_to_string(lp)))
529 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
530 // normally generate a rather confusing message:
532 // error: use of moved value: `x.b`
533 // note: `x.a` moved here...
535 // What we want to do instead is get the 'common ancestor' of the two moves and
536 // use that for most of the message instead, giving is something like this:
538 // error: use of moved value: `x`
539 // note: `x` moved here (through moving `x.a`)...
541 let common = moved_lp.common(lp);
542 let has_common = common.is_some();
543 let has_fork = moved_lp.has_fork(lp);
544 let (nl, ol, moved_lp_msg) =
545 if has_fork && has_common {
546 let nl = self.loan_path_to_string(&common.unwrap());
548 let moved_lp_msg = format!(" (through moving `{}`)",
549 self.loan_path_to_string(moved_lp));
550 (nl, ol, moved_lp_msg)
552 (self.loan_path_to_string(lp),
553 self.loan_path_to_string(moved_lp),
557 let partial = moved_lp.depth() > lp.depth();
558 let msg = if !has_fork && partial { "partially " }
559 else if has_fork && !has_common { "collaterally "}
561 let err = struct_span_err!(
562 self.tcx.sess, use_span, E0382,
563 "{} of {}moved value: `{}`",
565 (ol, moved_lp_msg, err)}
568 // Get type of value and span where it was previously
570 let (move_span, move_note) = match the_move.kind {
571 move_data::Declared => {
575 move_data::MoveExpr |
576 move_data::MovePat =>
577 (self.tcx.hir.span(the_move.id), ""),
579 move_data::Captured =>
580 (match self.tcx.hir.expect_expr(the_move.id).node {
581 hir::ExprClosure(.., fn_decl_span) => fn_decl_span,
582 ref r => bug!("Captured({}) maps to non-closure: {:?}",
584 }, " (into closure)"),
587 // Annotate the use and the move in the span. Watch out for
588 // the case where the use and the move are the same. This
589 // means the use is in a loop.
590 err = if use_span == move_span {
593 &format!("value moved{} here in previous iteration of loop",
597 err.span_label(use_span, &format!("value {} here after move", verb_participle))
598 .span_label(move_span, &format!("value moved{} here", move_note));
602 err.note(&format!("move occurs because `{}` has type `{}`, \
603 which does not implement the `Copy` trait",
604 self.loan_path_to_string(moved_lp),
607 // Note: we used to suggest adding a `ref binding` or calling
608 // `clone` but those suggestions have been removed because
609 // they are often not what you actually want to do, and were
610 // not considered particularly helpful.
615 pub fn report_partial_reinitialization_of_uninitialized_structure(
618 lp: &LoanPath<'tcx>) {
620 self.tcx.sess, span, E0383,
621 "partial reinitialization of uninitialized structure `{}`",
622 self.loan_path_to_string(lp));
625 pub fn report_reassigned_immutable_variable(&self,
629 &move_data::Assignment) {
630 let mut err = struct_span_err!(
631 self.tcx.sess, span, E0384,
632 "re-assignment of immutable variable `{}`",
633 self.loan_path_to_string(lp));
634 err.span_label(span, &format!("re-assignment of immutable variable"));
635 if span != assign.span {
636 err.span_label(assign.span, &format!("first assignment to `{}`",
637 self.loan_path_to_string(lp)));
642 pub fn span_err(&self, s: Span, m: &str) {
643 self.tcx.sess.span_err(s, m);
646 pub fn struct_span_err<S: Into<MultiSpan>>(&self, s: S, m: &str)
647 -> DiagnosticBuilder<'a> {
648 self.tcx.sess.struct_span_err(s, m)
651 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(&self,
655 -> DiagnosticBuilder<'a> {
656 self.tcx.sess.struct_span_err_with_code(s, msg, code)
659 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, s: S, msg: &str, code: &str) {
660 self.tcx.sess.span_err_with_code(s, msg, code);
663 fn bckerr_to_diag(&self, err: &BckError<'tcx>) -> DiagnosticBuilder<'a> {
664 let span = err.span.clone();
666 let msg = match err.code {
668 let descr = match err.cmt.note {
669 mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
670 self.cmt_to_string(&err.cmt)
672 _ => match opt_loan_path(&err.cmt) {
675 err.cmt.mutbl.to_user_str(),
676 self.cmt_to_string(&err.cmt))
680 format!("{} {} `{}`",
681 err.cmt.mutbl.to_user_str(),
682 self.cmt_to_string(&err.cmt),
683 self.loan_path_to_string(&lp))
689 MutabilityViolation => {
690 format!("cannot assign to {}", descr)
692 BorrowViolation(euv::ClosureCapture(_)) => {
693 format!("closure cannot assign to {}", descr)
695 BorrowViolation(euv::OverloadedOperator) |
696 BorrowViolation(euv::AddrOf) |
697 BorrowViolation(euv::RefBinding) |
698 BorrowViolation(euv::AutoRef) |
699 BorrowViolation(euv::AutoUnsafe) |
700 BorrowViolation(euv::ForLoop) |
701 BorrowViolation(euv::MatchDiscriminant) => {
702 format!("cannot borrow {} as mutable", descr)
704 BorrowViolation(euv::ClosureInvocation) => {
706 "err_mutbl with a closure invocation");
710 err_out_of_scope(..) => {
711 let msg = match opt_loan_path(&err.cmt) {
712 None => "borrowed value".to_string(),
714 format!("`{}`", self.loan_path_to_string(&lp))
717 format!("{} does not live long enough", msg)
719 err_borrowed_pointer_too_short(..) => {
720 let descr = self.cmt_to_path_or_string(&err.cmt);
721 format!("lifetime of {} is too short to guarantee \
722 its contents can be safely reborrowed",
727 self.struct_span_err(span, &msg)
730 pub fn report_aliasability_violation(&self,
732 kind: AliasableViolationKind,
733 cause: mc::AliasableReason,
734 cmt: mc::cmt<'tcx>) {
735 let mut is_closure = false;
736 let prefix = match kind {
737 MutabilityViolation => {
738 "cannot assign to data"
740 BorrowViolation(euv::ClosureCapture(_)) |
741 BorrowViolation(euv::OverloadedOperator) |
742 BorrowViolation(euv::AddrOf) |
743 BorrowViolation(euv::AutoRef) |
744 BorrowViolation(euv::AutoUnsafe) |
745 BorrowViolation(euv::RefBinding) |
746 BorrowViolation(euv::MatchDiscriminant) => {
747 "cannot borrow data mutably"
750 BorrowViolation(euv::ClosureInvocation) => {
755 BorrowViolation(euv::ForLoop) => {
761 mc::AliasableStatic |
762 mc::AliasableStaticMut => {
763 // This path cannot occur. It happens when we have an
764 // `&mut` or assignment to a static. But in the case
765 // of `static X`, we get a mutability violation first,
766 // and never get here. In the case of `static mut X`,
767 // that is unsafe and hence the aliasability error is
769 span_bug!(span, "aliasability violation for static `{}`", prefix)
771 mc::AliasableBorrowed => {}
773 let blame = cmt.immutability_blame();
774 let mut err = match blame {
775 Some(ImmutabilityBlame::ClosureEnv(id)) => {
776 let mut err = struct_span_err!(
777 self.tcx.sess, span, E0387,
778 "{} in a captured outer variable in an `Fn` closure", prefix);
780 // FIXME: the distinction between these 2 messages looks wrong.
781 let help = if let BorrowViolation(euv::ClosureCapture(_)) = kind {
782 // The aliasability violation with closure captures can
783 // happen for nested closures, so we know the enclosing
784 // closure incorrectly accepts an `Fn` while it needs to
786 "consider changing this to accept closures that implement `FnMut`"
789 "consider changing this closure to take self by mutable reference"
791 err.span_help(self.tcx.hir.span(id), help);
795 let mut err = struct_span_err!(
796 self.tcx.sess, span, E0389,
797 "{} in a `&` reference", prefix);
798 err.span_label(span, &"assignment into an immutable reference");
802 self.note_immutability_blame(&mut err, blame);
805 err.help("closures behind references must be called via `&mut`");
810 /// Given a type, if it is an immutable reference, return a suggestion to make it mutable
811 fn suggest_mut_for_immutable(&self, pty: &hir::Ty, is_implicit_self: bool) -> Option<String> {
812 // Check wether the argument is an immutable reference
813 debug!("suggest_mut_for_immutable({:?}, {:?})", pty, is_implicit_self);
814 if let hir::TyRptr(lifetime, hir::MutTy {
815 mutbl: hir::Mutability::MutImmutable,
818 // Account for existing lifetimes when generating the message
819 let pointee_snippet = match self.tcx.sess.codemap().span_to_snippet(ty.span) {
820 Ok(snippet) => snippet,
824 let lifetime_snippet = if !lifetime.is_elided() {
825 format!("{} ", match self.tcx.sess.codemap().span_to_snippet(lifetime.span) {
826 Ok(lifetime_snippet) => lifetime_snippet,
832 Some(format!("use `&{}mut {}` here to make mutable",
834 if is_implicit_self { "self" } else { &*pointee_snippet }))
840 fn local_binding_mode(&self, node_id: ast::NodeId) -> hir::BindingMode {
841 let pat = match self.tcx.hir.get(node_id) {
842 hir_map::Node::NodeLocal(pat) => pat,
843 node => bug!("bad node for local: {:?}", node)
847 hir::PatKind::Binding(mode, ..) => mode,
848 _ => bug!("local is not a binding: {:?}", pat)
852 fn local_ty(&self, node_id: ast::NodeId) -> (Option<&hir::Ty>, bool) {
853 let parent = self.tcx.hir.get_parent_node(node_id);
854 let parent_node = self.tcx.hir.get(parent);
856 // The parent node is like a fn
857 if let Some(fn_like) = FnLikeNode::from_node(parent_node) {
858 // `nid`'s parent's `Body`
859 let fn_body = self.tcx.hir.body(fn_like.body());
860 // Get the position of `node_id` in the arguments list
861 let arg_pos = fn_body.arguments.iter().position(|arg| arg.pat.id == node_id);
862 if let Some(i) = arg_pos {
863 // The argument's `Ty`
864 (Some(&fn_like.decl().inputs[i]),
865 i == 0 && fn_like.decl().has_implicit_self)
874 fn note_immutability_blame(&self,
875 db: &mut DiagnosticBuilder,
876 blame: Option<ImmutabilityBlame>) {
879 Some(ImmutabilityBlame::ClosureEnv(_)) => {}
880 Some(ImmutabilityBlame::ImmLocal(node_id)) => {
881 let let_span = self.tcx.hir.span(node_id);
882 if let hir::BindingMode::BindByValue(..) = self.local_binding_mode(node_id) {
883 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(let_span) {
884 let (_, is_implicit_self) = self.local_ty(node_id);
885 if is_implicit_self && snippet != "self" {
886 // avoid suggesting `mut &self`.
891 &format!("consider changing this to `mut {}`", snippet)
896 Some(ImmutabilityBlame::LocalDeref(node_id)) => {
897 let let_span = self.tcx.hir.span(node_id);
898 match self.local_binding_mode(node_id) {
899 hir::BindingMode::BindByRef(..) => {
900 let snippet = self.tcx.sess.codemap().span_to_snippet(let_span);
901 if let Ok(snippet) = snippet {
904 &format!("consider changing this to `{}`",
905 snippet.replace("ref ", "ref mut "))
909 hir::BindingMode::BindByValue(..) => {
910 if let (Some(local_ty), is_implicit_self) = self.local_ty(node_id) {
912 self.suggest_mut_for_immutable(local_ty, is_implicit_self) {
913 db.span_label(local_ty.span, &msg);
919 Some(ImmutabilityBlame::AdtFieldDeref(_, field)) => {
920 let node_id = match self.tcx.hir.as_local_node_id(field.did) {
921 Some(node_id) => node_id,
925 if let hir_map::Node::NodeField(ref field) = self.tcx.hir.get(node_id) {
926 if let Some(msg) = self.suggest_mut_for_immutable(&field.ty, false) {
927 db.span_label(field.ty.span, &msg);
934 fn report_out_of_scope_escaping_closure_capture(&self,
935 err: &BckError<'tcx>,
938 let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
941 match self.tcx.sess.codemap().span_to_snippet(err.span) {
942 Ok(string) => format!("move {}", string),
943 Err(_) => format!("move |<args>| <body>")
946 struct_span_err!(self.tcx.sess, err.span, E0373,
947 "closure may outlive the current function, \
949 which is owned by the current function",
951 .span_label(capture_span,
952 &format!("{} is borrowed here",
954 .span_label(err.span,
955 &format!("may outlive borrowed value {}",
957 .span_suggestion(err.span,
958 &format!("to force the closure to take ownership of {} \
959 (and any other referenced variables), \
960 use the `move` keyword, as shown:",
966 fn region_end_span(&self, region: &'tcx ty::Region) -> Option<Span> {
968 ty::ReScope(scope) => {
969 match scope.span(&self.tcx.region_maps, &self.tcx.hir) {
982 fn note_and_explain_bckerr(&self, db: &mut DiagnosticBuilder, err: BckError<'tcx>) {
983 let error_span = err.span.clone();
986 self.note_and_explain_mutbl_error(db, &err, &error_span);
987 self.note_immutability_blame(db, err.cmt.immutability_blame());
989 err_out_of_scope(super_scope, sub_scope, cause) => {
990 let (value_kind, value_msg) = match err.cmt.cat {
991 mc::Categorization::Rvalue(..) =>
992 ("temporary value", "temporary value created here"),
994 ("borrowed value", "borrow occurs here")
997 let is_closure = match cause {
998 euv::ClosureCapture(s) => {
999 // The primary span starts out as the closure creation point.
1000 // Change the primary span here to highlight the use of the variable
1001 // in the closure, because it seems more natural. Highlight
1002 // closure creation point as a secondary span.
1003 match db.span.primary_span() {
1005 db.span = MultiSpan::from_span(s);
1006 db.span_label(primary, &format!("capture occurs here"));
1007 db.span_label(s, &"does not live long enough");
1014 db.span_label(error_span, &"does not live long enough");
1019 let sub_span = self.region_end_span(sub_scope);
1020 let super_span = self.region_end_span(super_scope);
1022 match (sub_span, super_span) {
1023 (Some(s1), Some(s2)) if s1 == s2 => {
1025 db.span = MultiSpan::from_span(s1);
1026 db.span_label(error_span, &value_msg);
1027 let msg = match opt_loan_path(&err.cmt) {
1028 None => value_kind.to_string(),
1030 format!("`{}`", self.loan_path_to_string(&lp))
1034 &format!("{} dropped here while still borrowed", msg));
1036 db.span_label(s1, &format!("{} dropped before borrower", value_kind));
1038 db.note("values in a scope are dropped in the opposite order \
1041 (Some(s1), Some(s2)) if !is_closure => {
1042 db.span = MultiSpan::from_span(s2);
1043 db.span_label(error_span, &value_msg);
1044 let msg = match opt_loan_path(&err.cmt) {
1045 None => value_kind.to_string(),
1047 format!("`{}`", self.loan_path_to_string(&lp))
1050 db.span_label(s2, &format!("{} dropped here while still borrowed", msg));
1051 db.span_label(s1, &format!("{} needs to live until here", value_kind));
1056 db.span_label(s, &format!("{} needs to live until here",
1060 self.tcx.note_and_explain_region(
1062 "borrowed value must be valid for ",
1069 db.span_label(s, &format!("{} only lives until here", value_kind));
1072 self.tcx.note_and_explain_region(
1074 "...but borrowed value is only valid for ",
1082 if let Some(_) = statement_scope_span(self.tcx, super_scope) {
1083 db.note("consider using a `let` binding to increase its lifetime");
1089 mc::Categorization::Rvalue(r, or) if r != or => {
1091 before rustc 1.16, this temporary lived longer - see issue #39283 \
1092 (https://github.com/rust-lang/rust/issues/39283)");
1098 err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1099 let descr = match opt_loan_path(&err.cmt) {
1101 format!("`{}`", self.loan_path_to_string(&lp))
1103 None => self.cmt_to_string(&err.cmt),
1105 self.tcx.note_and_explain_region(
1107 &format!("{} would have to be valid for ",
1111 self.tcx.note_and_explain_region(
1113 &format!("...but {} is only valid for ", descr),
1120 fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'tcx>,
1121 error_span: &Span) {
1122 match err.cmt.note {
1123 mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1124 // If this is an `Fn` closure, it simply can't mutate upvars.
1125 // If it's an `FnMut` closure, the original variable was declared immutable.
1126 // We need to determine which is the case here.
1127 let kind = match err.cmt.upvar().unwrap().cat {
1128 Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1131 if kind == ty::ClosureKind::Fn {
1132 db.span_help(self.tcx.hir.span(upvar_id.closure_expr_id),
1133 "consider changing this closure to take \
1134 self by mutable reference");
1138 if let Categorization::Deref(..) = err.cmt.cat {
1139 db.span_label(*error_span, &"cannot borrow as mutable");
1140 } else if let Categorization::Local(local_id) = err.cmt.cat {
1141 let span = self.tcx.hir.span(local_id);
1142 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
1143 if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
1144 db.span_label(*error_span, &format!("cannot reborrow mutably"));
1145 db.span_label(*error_span, &format!("try removing `&mut` here"));
1147 db.span_label(*error_span, &format!("cannot borrow mutably"));
1150 db.span_label(*error_span, &format!("cannot borrow mutably"));
1152 } else if let Categorization::Interior(ref cmt, _) = err.cmt.cat {
1153 if let mc::MutabilityCategory::McImmutable = cmt.mutbl {
1154 db.span_label(*error_span,
1155 &"cannot mutably borrow immutable field");
1161 pub fn append_loan_path_to_string(&self,
1162 loan_path: &LoanPath<'tcx>,
1164 match loan_path.kind {
1165 LpUpvar(ty::UpvarId{ var_id: id, closure_expr_id: _ }) |
1167 out.push_str(&self.tcx.local_var_name_str(id));
1170 LpDowncast(ref lp_base, variant_def_id) => {
1172 self.append_loan_path_to_string(&lp_base, out);
1173 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1174 out.push_str(&self.tcx.item_path_str(variant_def_id));
1178 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(fname))) => {
1179 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1181 mc::NamedField(fname) => {
1183 out.push_str(&fname.as_str());
1185 mc::PositionalField(idx) => {
1187 out.push_str(&idx.to_string());
1192 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement(..))) => {
1193 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1194 out.push_str("[..]");
1197 LpExtend(ref lp_base, _, LpDeref(_)) => {
1199 self.append_loan_path_to_string(&lp_base, out);
1204 pub fn append_autoderefd_loan_path_to_string(&self,
1205 loan_path: &LoanPath<'tcx>,
1207 match loan_path.kind {
1208 LpExtend(ref lp_base, _, LpDeref(_)) => {
1209 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1210 // rules would normally allow users to omit the `*x`.
1211 // So just serialize such paths to `x.f` or x[3]` respectively.
1212 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1215 LpDowncast(ref lp_base, variant_def_id) => {
1217 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1219 out.push_str(&self.tcx.item_path_str(variant_def_id));
1223 LpVar(..) | LpUpvar(..) | LpExtend(.., LpInterior(..)) => {
1224 self.append_loan_path_to_string(loan_path, out)
1229 pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1230 let mut result = String::new();
1231 self.append_loan_path_to_string(loan_path, &mut result);
1235 pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1236 cmt.descriptive_string(self.tcx)
1239 pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt<'tcx>) -> String {
1240 match opt_loan_path(cmt) {
1241 Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1242 None => self.cmt_to_string(cmt),
1247 fn statement_scope_span(tcx: TyCtxt, region: &ty::Region) -> Option<Span> {
1249 ty::ReScope(scope) => {
1250 match tcx.hir.find(scope.node_id(&tcx.region_maps)) {
1251 Some(hir_map::NodeStmt(stmt)) => Some(stmt.span),
1259 impl BitwiseOperator for LoanDataFlowOperator {
1261 fn join(&self, succ: usize, pred: usize) -> usize {
1262 succ | pred // loans from both preds are in scope
1266 impl DataFlowOperator for LoanDataFlowOperator {
1268 fn initial_value(&self) -> bool {
1269 false // no loans in scope by default
1273 impl<'tcx> fmt::Debug for InteriorKind {
1274 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1276 InteriorField(mc::NamedField(fld)) => write!(f, "{}", fld),
1277 InteriorField(mc::PositionalField(i)) => write!(f, "#{}", i),
1278 InteriorElement(..) => write!(f, "[]"),
1283 impl<'tcx> fmt::Debug for Loan<'tcx> {
1284 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1285 write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1291 self.restricted_paths)
1295 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1296 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1299 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_string(id)))
1302 LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => {
1303 let s = ty::tls::with(|tcx| tcx.hir.node_to_string(var_id));
1304 write!(f, "$({} captured by id={})", s, closure_expr_id)
1307 LpDowncast(ref lp, variant_def_id) => {
1308 let variant_str = if variant_def_id.is_local() {
1309 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1311 format!("{:?}", variant_def_id)
1313 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1316 LpExtend(ref lp, _, LpDeref(_)) => {
1317 write!(f, "{:?}.*", lp)
1320 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1321 write!(f, "{:?}.{:?}", lp, interior)
1327 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1328 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1331 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_user_string(id)))
1334 LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => {
1335 let s = ty::tls::with(|tcx| tcx.hir.node_to_user_string(var_id));
1336 write!(f, "$({} captured by closure)", s)
1339 LpDowncast(ref lp, variant_def_id) => {
1340 let variant_str = if variant_def_id.is_local() {
1341 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1343 format!("{:?}", variant_def_id)
1345 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1348 LpExtend(ref lp, _, LpDeref(_)) => {
1349 write!(f, "{}.*", lp)
1352 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1353 write!(f, "{}.{:?}", lp, interior)