1 //! See The Book chapter on the borrow checker for more details.
3 #![allow(non_camel_case_types)]
5 pub use LoanPathKind::*;
6 pub use LoanPathElem::*;
7 pub use bckerr_code::*;
8 pub use AliasableViolationKind::*;
9 pub use MovedValueUseKind::*;
13 use rustc::hir::HirId;
15 use rustc::hir::map::blocks::FnLikeNode;
17 use rustc::middle::borrowck::{BorrowCheckResult, SignalledError};
18 use rustc::hir::def_id::{DefId, LocalDefId};
19 use rustc::middle::expr_use_visitor as euv;
20 use rustc::middle::mem_categorization as mc;
21 use rustc::middle::mem_categorization::Categorization;
22 use rustc::middle::mem_categorization::ImmutabilityBlame;
23 use rustc::middle::region;
24 use rustc::middle::free_region::RegionRelations;
25 use rustc::ty::{self, Ty, TyCtxt};
26 use rustc::ty::query::Providers;
27 use rustc_mir::util::borrowck_errors::{BorrowckErrors, Origin};
28 use rustc_mir::util::suggest_ref_mut;
29 use rustc::util::nodemap::FxHashSet;
32 use std::cell::{Cell, RefCell};
35 use rustc_data_structures::sync::Lrc;
36 use std::hash::{Hash, Hasher};
38 use syntax_pos::{MultiSpan, Span};
39 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
44 use crate::dataflow::{DataFlowContext, BitwiseOperator, DataFlowOperator, KillFrom};
54 #[derive(Clone, Copy)]
55 pub struct LoanDataFlowOperator;
57 pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
59 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
60 tcx.par_body_owners(|body_owner_def_id| {
61 tcx.ensure().borrowck(body_owner_def_id);
65 pub fn provide(providers: &mut Providers<'_>) {
66 *providers = Providers {
72 /// Collection of conclusions determined via borrow checker analyses.
73 pub struct AnalysisData<'a, 'tcx: 'a> {
74 pub all_loans: Vec<Loan<'tcx>>,
75 pub loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>,
76 pub move_data: move_data::FlowedMoveData<'a, 'tcx>,
79 fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId)
80 -> Lrc<BorrowCheckResult>
82 assert!(tcx.use_ast_borrowck() || tcx.migrate_borrowck());
84 debug!("borrowck(body_owner_def_id={:?})", owner_def_id);
86 let owner_id = tcx.hir().as_local_node_id(owner_def_id).unwrap();
88 match tcx.hir().get(owner_id) {
91 // We get invoked with anything that has MIR, but some of
92 // those things (notably the synthesized constructors from
93 // tuple structs/variants) do not have an associated body
94 // and do not need borrowchecking.
95 return Lrc::new(BorrowCheckResult {
96 used_mut_nodes: Default::default(),
97 signalled_any_error: SignalledError::NoErrorsSeen,
103 let body_id = tcx.hir().body_owned_by(owner_id);
104 let tables = tcx.typeck_tables_of(owner_def_id);
105 let region_scope_tree = tcx.region_scope_tree(owner_def_id);
106 let body = tcx.hir().body(body_id);
107 let mut bccx = BorrowckCtxt {
113 used_mut_nodes: Default::default(),
114 signalled_any_error: Cell::new(SignalledError::NoErrorsSeen),
117 // Eventually, borrowck will always read the MIR, but at the
118 // moment we do not. So, for now, we always force MIR to be
119 // constructed for a given fn, since this may result in errors
120 // being reported and we want that to happen.
122 // Note that `mir_validated` is a "stealable" result; the
123 // thief, `optimized_mir()`, forces borrowck, so we know that
124 // is not yet stolen.
125 tcx.ensure().mir_validated(owner_def_id);
127 // option dance because you can't capture an uninitialized variable
130 if let Some(AnalysisData { all_loans,
132 move_data: flowed_moves }) =
133 build_borrowck_dataflow_data(&mut bccx, false, body_id,
135 cfg = Some(cfg::CFG::new(bccx.tcx, &body));
136 cfg.as_mut().unwrap()
139 check_loans::check_loans(&mut bccx, &loan_dfcx, &flowed_moves, &all_loans, body);
142 if !tcx.use_mir_borrowck() {
143 unused::check(&mut bccx, body);
146 Lrc::new(BorrowCheckResult {
147 used_mut_nodes: bccx.used_mut_nodes.into_inner(),
148 signalled_any_error: bccx.signalled_any_error.into_inner(),
152 fn build_borrowck_dataflow_data<'a, 'c, 'tcx, F>(this: &mut BorrowckCtxt<'a, 'tcx>,
153 force_analysis: bool,
154 body_id: hir::BodyId,
156 -> Option<AnalysisData<'a, 'tcx>>
157 where F: FnOnce(&mut BorrowckCtxt<'a, 'tcx>) -> &'c cfg::CFG
159 // Check the body of fn items.
160 let (all_loans, move_data) =
161 gather_loans::gather_loans_in_fn(this, body_id);
163 if !force_analysis && move_data.is_empty() && all_loans.is_empty() {
164 // large arrays of data inserted as constants can take a lot of
165 // time and memory to borrow-check - see issue #36799. However,
166 // they don't have places, so no borrow-check is actually needed.
167 // Recognize that case and skip borrow-checking.
168 debug!("skipping loan propagation for {:?} because of no loans", body_id);
171 debug!("propagating loans in {:?}", body_id);
174 let cfg = get_cfg(this);
176 DataFlowContext::new(this.tcx,
180 LoanDataFlowOperator,
182 for (loan_idx, loan) in all_loans.iter().enumerate() {
183 loan_dfcx.add_gen(loan.gen_scope.item_local_id(), loan_idx);
184 loan_dfcx.add_kill(KillFrom::ScopeEnd,
185 loan.kill_scope.item_local_id(),
188 loan_dfcx.add_kills_from_flow_exits(cfg);
189 loan_dfcx.propagate(cfg, this.body);
191 let flowed_moves = move_data::FlowedMoveData::new(move_data,
196 Some(AnalysisData { all_loans,
198 move_data:flowed_moves })
201 /// Accessor for introspective clients inspecting `AnalysisData` and
202 /// the `BorrowckCtxt` itself , e.g., the flowgraph visualizer.
203 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
204 tcx: TyCtxt<'a, 'tcx, 'tcx>,
205 body_id: hir::BodyId,
207 -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
209 let owner_id = tcx.hir().body_owner(body_id);
210 let owner_def_id = tcx.hir().local_def_id(owner_id);
211 let tables = tcx.typeck_tables_of(owner_def_id);
212 let region_scope_tree = tcx.region_scope_tree(owner_def_id);
213 let body = tcx.hir().body(body_id);
214 let mut bccx = BorrowckCtxt {
220 used_mut_nodes: Default::default(),
221 signalled_any_error: Cell::new(SignalledError::NoErrorsSeen),
224 let dataflow_data = build_borrowck_dataflow_data(&mut bccx, true, body_id, |_| cfg);
225 (bccx, dataflow_data.unwrap())
228 // ----------------------------------------------------------------------
231 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
232 tcx: TyCtxt<'a, 'tcx, 'tcx>,
234 // tables for the current thing we are checking; set to
235 // Some in `borrowck_fn` and cleared later
236 tables: &'a ty::TypeckTables<'tcx>,
238 region_scope_tree: Lrc<region::ScopeTree>,
242 body: &'tcx hir::Body,
244 used_mut_nodes: RefCell<FxHashSet<HirId>>,
246 signalled_any_error: Cell<SignalledError>,
250 impl<'a, 'tcx: 'a> BorrowckCtxt<'a, 'tcx> {
251 fn signal_error(&self) {
252 self.signalled_any_error.set(SignalledError::SawSomeError);
256 impl<'a, 'b, 'tcx: 'b> BorrowckErrors<'a> for &'a BorrowckCtxt<'b, 'tcx> {
257 fn struct_span_err_with_code<S: Into<MultiSpan>>(self,
261 -> DiagnosticBuilder<'a>
263 self.tcx.sess.struct_span_err_with_code(sp, msg, code)
266 fn struct_span_err<S: Into<MultiSpan>>(self,
269 -> DiagnosticBuilder<'a>
271 self.tcx.sess.struct_span_err(sp, msg)
274 fn cancel_if_wrong_origin(self,
275 mut diag: DiagnosticBuilder<'a>,
277 -> DiagnosticBuilder<'a>
279 if !o.should_emit_errors(self.tcx.borrowck_mode()) {
280 self.tcx.sess.diagnostic().cancel(&mut diag);
286 ///////////////////////////////////////////////////////////////////////////
287 // Loans and loan paths
289 /// Record of a loan that was issued.
290 pub struct Loan<'tcx> {
292 loan_path: Rc<LoanPath<'tcx>>,
293 kind: ty::BorrowKind,
294 restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
296 /// gen_scope indicates where loan is introduced. Typically the
297 /// loan is introduced at the point of the borrow, but in some
298 /// cases, notably method arguments, the loan may be introduced
299 /// only later, once it comes into scope. See also
300 /// `GatherLoanCtxt::compute_gen_scope`.
301 gen_scope: region::Scope,
303 /// kill_scope indicates when the loan goes out of scope. This is
304 /// either when the lifetime expires or when the local variable
305 /// which roots the loan-path goes out of scope, whichever happens
306 /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
307 kill_scope: region::Scope,
309 cause: euv::LoanCause,
312 impl<'tcx> Loan<'tcx> {
313 pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
314 self.loan_path.clone()
319 pub struct LoanPath<'tcx> {
320 kind: LoanPathKind<'tcx>,
324 impl<'tcx> PartialEq for LoanPath<'tcx> {
325 fn eq(&self, that: &LoanPath<'tcx>) -> bool {
326 self.kind == that.kind
330 impl<'tcx> Hash for LoanPath<'tcx> {
331 fn hash<H: Hasher>(&self, state: &mut H) {
332 self.kind.hash(state);
336 #[derive(PartialEq, Eq, Hash, Debug)]
337 pub enum LoanPathKind<'tcx> {
338 LpVar(ast::NodeId), // `x` in README.md
339 LpUpvar(ty::UpvarId), // `x` captured by-value into closure
340 LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
341 LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem<'tcx>)
344 impl<'tcx> LoanPath<'tcx> {
345 fn new(kind: LoanPathKind<'tcx>, ty: Ty<'tcx>) -> LoanPath<'tcx> {
346 LoanPath { kind: kind, ty: ty }
349 fn to_type(&self) -> Ty<'tcx> { self.ty }
351 fn has_downcast(&self) -> bool {
353 LpDowncast(_, _) => true,
354 LpExtend(ref lp, _, LpInterior(_, _)) => {
362 // FIXME (pnkfelix): See discussion here
363 // https://github.com/pnkfelix/rust/commit/
364 // b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
365 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
367 // A local, "cleaned" version of `mc::InteriorKind` that drops
368 // information that is not relevant to loan-path analysis. (In
369 // particular, the distinction between how precisely an array-element
370 // is tracked is irrelevant here.)
371 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
372 pub enum InteriorKind {
373 InteriorField(mc::FieldIndex),
377 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
378 impl ToInteriorKind for mc::InteriorKind {
379 fn cleaned(self) -> InteriorKind {
381 mc::InteriorField(name) => InteriorField(name),
382 mc::InteriorElement(_) => InteriorElement,
388 // - a pointer dereference (`*P` in README.md)
389 // - a field reference, with an optional definition of the containing
390 // enum variant (`P.f` in README.md)
391 // `DefId` is present when the field is part of struct that is in
392 // a variant of an enum. For instance in:
393 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
394 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
395 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
396 pub enum LoanPathElem<'tcx> {
397 LpDeref(mc::PointerKind<'tcx>),
398 LpInterior(Option<DefId>, InteriorKind),
401 fn closure_to_block(closure_id: LocalDefId,
402 tcx: TyCtxt<'_, '_, '_>) -> ast::NodeId {
403 let closure_id = tcx.hir().local_def_id_to_node_id(closure_id);
404 match tcx.hir().get(closure_id) {
405 Node::Expr(expr) => match expr.node {
406 hir::ExprKind::Closure(.., body_id, _, _) => {
407 tcx.hir().hir_to_node_id(body_id.hir_id)
410 bug!("encountered non-closure id: {}", closure_id)
413 _ => bug!("encountered non-expr id: {}", closure_id)
417 impl<'a, 'tcx> LoanPath<'tcx> {
418 pub fn kill_scope(&self, bccx: &BorrowckCtxt<'a, 'tcx>) -> region::Scope {
421 let hir_id = bccx.tcx.hir().node_to_hir_id(local_id);
422 bccx.region_scope_tree.var_scope(hir_id.local_id)
424 LpUpvar(upvar_id) => {
425 let block_id = closure_to_block(upvar_id.closure_expr_id, bccx.tcx);
426 let hir_id = bccx.tcx.hir().node_to_hir_id(block_id);
427 region::Scope { id: hir_id.local_id, data: region::ScopeData::Node }
429 LpDowncast(ref base, _) |
430 LpExtend(ref base, ..) => base.kill_scope(bccx),
434 fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
435 match (&self.kind, &other.kind) {
436 (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
437 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
438 if id == id2 && opt_variant_id == opt_variant_id2 {
439 base.has_fork(&base2)
443 (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
444 (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&base),
449 fn depth(&self) -> usize {
451 LpExtend(ref base, _, LpDeref(_)) => base.depth(),
452 LpExtend(ref base, _, LpInterior(..)) => base.depth() + 1,
457 fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
458 match (&self.kind, &other.kind) {
459 (&LpExtend(ref base, a, LpInterior(opt_variant_id, id)),
460 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) => {
461 if id == id2 && opt_variant_id == opt_variant_id2 {
462 base.common(&base2).map(|x| {
464 if base.depth() == xd && base2.depth() == xd {
466 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
477 (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
478 (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&other),
479 (&LpVar(id), &LpVar(id2)) => {
481 Some(LoanPath { kind: LpVar(id), ty: self.ty })
486 (&LpUpvar(id), &LpUpvar(id2)) => {
488 Some(LoanPath { kind: LpUpvar(id), ty: self.ty })
498 // Avoid "cannot borrow immutable field `self.x` as mutable" as that implies that a field *can* be
499 // mutable independently of the struct it belongs to. (#35937)
500 pub fn opt_loan_path_is_field<'tcx>(cmt: &mc::cmt_<'tcx>) -> (Option<Rc<LoanPath<'tcx>>>, bool) {
501 let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
504 Categorization::Rvalue(..) |
505 Categorization::ThreadLocal(..) |
506 Categorization::StaticItem => {
510 Categorization::Local(id) => {
511 (Some(new_lp(LpVar(id))), false)
514 Categorization::Upvar(mc::Upvar { id, .. }) => {
515 (Some(new_lp(LpUpvar(id))), false)
518 Categorization::Deref(ref cmt_base, pk) => {
519 let lp = opt_loan_path_is_field(cmt_base);
521 new_lp(LpExtend(lp, cmt.mutbl, LpDeref(pk)))
525 Categorization::Interior(ref cmt_base, ik) => {
526 (opt_loan_path(cmt_base).map(|lp| {
527 let opt_variant_id = match cmt_base.cat {
528 Categorization::Downcast(_, did) => Some(did),
531 new_lp(LpExtend(lp, cmt.mutbl, LpInterior(opt_variant_id, ik.cleaned())))
535 Categorization::Downcast(ref cmt_base, variant_def_id) => {
536 let lp = opt_loan_path_is_field(cmt_base);
538 new_lp(LpDowncast(lp, variant_def_id))
544 /// Computes the `LoanPath` (if any) for a `cmt`.
545 /// Note that this logic is somewhat duplicated in
546 /// the method `compute()` found in `gather_loans::restrictions`,
547 /// which allows it to share common loan path pieces as it
548 /// traverses the CMT.
549 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt_<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
550 opt_loan_path_is_field(cmt).0
553 ///////////////////////////////////////////////////////////////////////////
556 // Errors that can occur
557 #[derive(Debug, PartialEq)]
558 pub enum bckerr_code<'tcx> {
560 /// superscope, subscope, loan cause
561 err_out_of_scope(ty::Region<'tcx>, ty::Region<'tcx>, euv::LoanCause),
562 err_borrowed_pointer_too_short(ty::Region<'tcx>, ty::Region<'tcx>), // loan, ptr
565 // Combination of an error code and the categorization of the expression
567 #[derive(Debug, PartialEq)]
568 pub struct BckError<'c, 'tcx: 'c> {
570 cause: AliasableViolationKind,
571 cmt: &'c mc::cmt_<'tcx>,
572 code: bckerr_code<'tcx>
575 #[derive(Copy, Clone, Debug, PartialEq)]
576 pub enum AliasableViolationKind {
578 BorrowViolation(euv::LoanCause)
581 #[derive(Copy, Clone, Debug)]
582 pub enum MovedValueUseKind {
587 ///////////////////////////////////////////////////////////////////////////
590 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
591 pub fn is_subregion_of(&self,
592 r_sub: ty::Region<'tcx>,
593 r_sup: ty::Region<'tcx>)
596 let region_rels = RegionRelations::new(self.tcx,
598 &self.region_scope_tree,
599 &self.tables.free_region_map);
600 region_rels.is_subregion_of(r_sub, r_sup)
603 pub fn report(&self, err: BckError<'a, 'tcx>) {
604 // Catch and handle some particular cases.
605 match (&err.code, &err.cause) {
606 (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _),
607 &BorrowViolation(euv::ClosureCapture(span))) |
608 (&err_out_of_scope(&ty::ReScope(_), &ty::ReEarlyBound(..), _),
609 &BorrowViolation(euv::ClosureCapture(span))) |
610 (&err_out_of_scope(&ty::ReScope(_), &ty::ReFree(..), _),
611 &BorrowViolation(euv::ClosureCapture(span))) => {
612 return self.report_out_of_scope_escaping_closure_capture(&err, span);
617 self.report_bckerr(&err);
620 pub fn report_use_of_moved_value(&self,
622 use_kind: MovedValueUseKind,
624 the_move: &move_data::Move,
625 moved_lp: &LoanPath<'tcx>) {
626 let (verb, verb_participle) = match use_kind {
627 MovedInUse => ("use", "used"),
628 MovedInCapture => ("capture", "captured"),
631 let (_ol, _moved_lp_msg, mut err, need_note) = match the_move.kind {
632 move_data::Declared => {
633 // If this is an uninitialized variable, just emit a simple warning
635 self.cannot_act_on_uninitialized_variable(use_span,
637 &self.loan_path_to_string(lp),
639 .span_label(use_span, format!("use of possibly uninitialized `{}`",
640 self.loan_path_to_string(lp)))
646 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
647 // normally generate a rather confusing message:
649 // error: use of moved value: `x.b`
650 // note: `x.a` moved here...
652 // What we want to do instead is get the 'common ancestor' of the two moves and
653 // use that for most of the message instead, giving is something like this:
655 // error: use of moved value: `x`
656 // note: `x` moved here (through moving `x.a`)...
658 let common = moved_lp.common(lp);
659 let has_common = common.is_some();
660 let has_fork = moved_lp.has_fork(lp);
661 let (nl, ol, moved_lp_msg) =
662 if has_fork && has_common {
663 let nl = self.loan_path_to_string(&common.unwrap());
665 let moved_lp_msg = format!(" (through moving `{}`)",
666 self.loan_path_to_string(moved_lp));
667 (nl, ol, moved_lp_msg)
669 (self.loan_path_to_string(lp),
670 self.loan_path_to_string(moved_lp),
674 let partial = moved_lp.depth() > lp.depth();
675 let msg = if !has_fork && partial { "partially " }
676 else if has_fork && !has_common { "collaterally "}
678 let mut err = self.cannot_act_on_moved_value(use_span,
683 let need_note = match lp.ty.sty {
684 ty::Closure(id, _) => {
685 let node_id = self.tcx.hir().as_local_node_id(id).unwrap();
686 let hir_id = self.tcx.hir().node_to_hir_id(node_id);
687 if let Some((span, name)) = self.tables.closure_kind_origins().get(hir_id) {
688 err.span_note(*span, &format!(
689 "closure cannot be invoked more than once because \
690 it moves the variable `{}` out of its environment",
700 (ol, moved_lp_msg, err, need_note)
704 // Get type of value and span where it was previously
706 let node_id = self.tcx.hir().hir_to_node_id(hir::HirId {
707 owner: self.body.value.hir_id.owner,
708 local_id: the_move.id
710 let (move_span, move_note) = match the_move.kind {
711 move_data::Declared => {
715 move_data::MoveExpr |
716 move_data::MovePat => (self.tcx.hir().span(node_id), ""),
718 move_data::Captured =>
719 (match self.tcx.hir().expect_expr(node_id).node {
720 hir::ExprKind::Closure(.., fn_decl_span, _) => fn_decl_span,
721 ref r => bug!("Captured({:?}) maps to non-closure: {:?}",
723 }, " (into closure)"),
726 // Annotate the use and the move in the span. Watch out for
727 // the case where the use and the move are the same. This
728 // means the use is in a loop.
729 err = if use_span == move_span {
732 format!("value moved{} here in previous iteration of loop",
736 err.span_label(use_span, format!("value {} here after move", verb_participle));
737 err.span_label(move_span, format!("value moved{} here", move_note));
743 "move occurs because {} has type `{}`, which does not implement the `Copy` trait",
744 if moved_lp.has_downcast() {
745 "the value".to_string()
747 format!("`{}`", self.loan_path_to_string(moved_lp))
752 // Note: we used to suggest adding a `ref binding` or calling
753 // `clone` but those suggestions have been removed because
754 // they are often not what you actually want to do, and were
755 // not considered particularly helpful.
761 pub fn report_partial_reinitialization_of_uninitialized_structure(
764 lp: &LoanPath<'tcx>) {
765 self.cannot_partially_reinit_an_uninit_struct(span,
766 &self.loan_path_to_string(lp),
772 pub fn report_reassigned_immutable_variable(&self,
776 &move_data::Assignment) {
777 let mut err = self.cannot_reassign_immutable(span,
778 &self.loan_path_to_string(lp),
781 err.span_label(span, "cannot assign twice to immutable variable");
782 if span != assign.span {
783 err.span_label(assign.span, format!("first assignment to `{}`",
784 self.loan_path_to_string(lp)));
790 fn report_bckerr(&self, err: &BckError<'a, 'tcx>) {
791 let error_span = err.span.clone();
795 let descr: Cow<'static, str> = match err.cmt.note {
796 mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
797 self.cmt_to_cow_str(&err.cmt)
799 _ => match opt_loan_path_is_field(&err.cmt) {
801 format!("{} of {} binding",
802 self.cmt_to_cow_str(&err.cmt),
803 err.cmt.mutbl.to_user_str()).into()
808 err.cmt.mutbl.to_user_str(),
809 self.cmt_to_cow_str(&err.cmt)).into()
812 (Some(lp), true) => {
813 format!("{} `{}` of {} binding",
814 self.cmt_to_cow_str(&err.cmt),
815 self.loan_path_to_string(&lp),
816 err.cmt.mutbl.to_user_str()).into()
818 (Some(lp), false) => {
819 format!("{} {} `{}`",
820 err.cmt.mutbl.to_user_str(),
821 self.cmt_to_cow_str(&err.cmt),
822 self.loan_path_to_string(&lp)).into()
827 let mut db = match err.cause {
828 MutabilityViolation => {
829 let mut db = self.cannot_assign(error_span, &descr, Origin::Ast);
830 if let mc::NoteClosureEnv(upvar_id) = err.cmt.note {
831 let node_id = self.tcx.hir().hir_to_node_id(upvar_id.var_path.hir_id);
832 let sp = self.tcx.hir().span(node_id);
833 let fn_closure_msg = "`Fn` closures cannot capture their enclosing \
834 environment for modifications";
835 match (self.tcx.sess.source_map().span_to_snippet(sp), &err.cmt.cat) {
836 (_, &Categorization::Upvar(mc::Upvar {
837 kind: ty::ClosureKind::Fn, ..
839 db.note(fn_closure_msg);
840 // we should point at the cause for this closure being
841 // identified as `Fn` (like in signature of method this
842 // closure was passed into)
844 (Ok(ref snippet), ref cat) => {
845 let msg = &format!("consider making `{}` mutable", snippet);
846 let suggestion = format!("mut {}", snippet);
848 if let &Categorization::Deref(ref cmt, _) = cat {
849 if let Categorization::Upvar(mc::Upvar {
850 kind: ty::ClosureKind::Fn, ..
852 db.note(fn_closure_msg);
858 Applicability::Unspecified,
866 Applicability::Unspecified,
871 db.span_help(sp, "consider making this binding mutable");
878 BorrowViolation(euv::ClosureCapture(_)) => {
879 self.closure_cannot_assign_to_borrowed(error_span, &descr, Origin::Ast)
881 BorrowViolation(euv::OverloadedOperator) |
882 BorrowViolation(euv::AddrOf) |
883 BorrowViolation(euv::RefBinding) |
884 BorrowViolation(euv::AutoRef) |
885 BorrowViolation(euv::AutoUnsafe) |
886 BorrowViolation(euv::ForLoop) |
887 BorrowViolation(euv::MatchDiscriminant) => {
888 self.cannot_borrow_path_as_mutable(error_span, &descr, Origin::Ast)
890 BorrowViolation(euv::ClosureInvocation) => {
892 "err_mutbl with a closure invocation");
896 // We add a special note about `IndexMut`, if the source of this error
897 // is the fact that `Index` is implemented, but `IndexMut` is not. Needing
898 // to implement two traits for "one operator" is not very intuitive for
900 if err.cmt.note == mc::NoteIndex {
901 let node_id = self.tcx.hir().hir_to_node_id(err.cmt.hir_id);
902 let node = self.tcx.hir().get(node_id);
904 // This pattern probably always matches.
906 hir::Expr { node: hir::ExprKind::Index(lhs, _), ..}
908 let ty = self.tables.expr_ty(lhs);
911 "trait `IndexMut` is required to modify indexed content, but \
912 it is not implemented for `{}`",
918 self.note_and_explain_mutbl_error(&mut db, &err, &error_span);
919 self.note_immutability_blame(
921 err.cmt.immutability_blame(),
922 self.tcx.hir().hir_to_node_id(err.cmt.hir_id)
927 err_out_of_scope(super_scope, sub_scope, cause) => {
928 let msg = match opt_loan_path(&err.cmt) {
929 None => "borrowed value".to_string(),
931 format!("`{}`", self.loan_path_to_string(&lp))
935 let mut db = self.path_does_not_live_long_enough(error_span, &msg, Origin::Ast);
936 let value_kind = match err.cmt.cat {
937 mc::Categorization::Rvalue(..) => "temporary value",
938 _ => "borrowed value",
941 let is_closure = match cause {
942 euv::ClosureCapture(s) => {
943 // The primary span starts out as the closure creation point.
944 // Change the primary span here to highlight the use of the variable
945 // in the closure, because it seems more natural. Highlight
946 // closure creation point as a secondary span.
947 match db.span.primary_span() {
949 db.span = MultiSpan::from_span(s);
950 db.span_label(primary, "capture occurs here");
951 db.span_label(s, format!("{} does not live long enough",
959 db.span_label(error_span, format!("{} does not live long enough",
965 let sub_span = self.region_end_span(sub_scope);
966 let super_span = self.region_end_span(super_scope);
968 match (sub_span, super_span) {
969 (Some(s1), Some(s2)) if s1 == s2 => {
971 let msg = match opt_loan_path(&err.cmt) {
972 None => value_kind.to_string(),
974 format!("`{}`", self.loan_path_to_string(&lp))
978 format!("{} dropped here while still borrowed", msg));
980 db.span_label(s1, format!("{} dropped before borrower", value_kind));
982 db.note("values in a scope are dropped in the opposite order \
985 (Some(s1), Some(s2)) if !is_closure => {
986 let msg = match opt_loan_path(&err.cmt) {
987 None => value_kind.to_string(),
989 format!("`{}`", self.loan_path_to_string(&lp))
992 db.span_label(s2, format!("{} dropped here while still borrowed", msg));
993 db.span_label(s1, format!("{} needs to live until here", value_kind));
998 db.span_label(s, format!("{} needs to live until here",
1002 self.tcx.note_and_explain_region(
1003 &self.region_scope_tree,
1005 "borrowed value must be valid for ",
1012 db.span_label(s, format!("{} only lives until here", value_kind));
1015 self.tcx.note_and_explain_region(
1016 &self.region_scope_tree,
1018 "...but borrowed value is only valid for ",
1026 if let ty::ReScope(scope) = *super_scope {
1027 let node_id = scope.node_id(self.tcx, &self.region_scope_tree);
1028 match self.tcx.hir().find(node_id) {
1029 Some(Node::Stmt(_)) => {
1030 if *sub_scope != ty::ReStatic {
1031 db.note("consider using a `let` binding to increase its lifetime");
1040 self.signal_error();
1042 err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1043 let descr = self.cmt_to_path_or_string(err.cmt);
1044 let mut db = self.lifetime_too_short_for_reborrow(error_span, &descr, Origin::Ast);
1045 let descr: Cow<'static, str> = match opt_loan_path(&err.cmt) {
1047 format!("`{}`", self.loan_path_to_string(&lp)).into()
1049 None => self.cmt_to_cow_str(&err.cmt)
1051 self.tcx.note_and_explain_region(
1052 &self.region_scope_tree,
1054 &format!("{} would have to be valid for ",
1058 self.tcx.note_and_explain_region(
1059 &self.region_scope_tree,
1061 &format!("...but {} is only valid for ", descr),
1066 self.signal_error();
1071 pub fn report_aliasability_violation(&self,
1073 kind: AliasableViolationKind,
1074 cause: mc::AliasableReason,
1075 cmt: &mc::cmt_<'tcx>) {
1076 let mut is_closure = false;
1077 let prefix = match kind {
1078 MutabilityViolation => {
1079 "cannot assign to data"
1081 BorrowViolation(euv::ClosureCapture(_)) |
1082 BorrowViolation(euv::OverloadedOperator) |
1083 BorrowViolation(euv::AddrOf) |
1084 BorrowViolation(euv::AutoRef) |
1085 BorrowViolation(euv::AutoUnsafe) |
1086 BorrowViolation(euv::RefBinding) |
1087 BorrowViolation(euv::MatchDiscriminant) => {
1088 "cannot borrow data mutably"
1091 BorrowViolation(euv::ClosureInvocation) => {
1093 "closure invocation"
1096 BorrowViolation(euv::ForLoop) => {
1102 mc::AliasableStaticMut => {
1103 // This path cannot occur. `static mut X` is not checked
1104 // for aliasability violations.
1105 span_bug!(span, "aliasability violation for static mut `{}`", prefix)
1107 mc::AliasableStatic | mc::AliasableBorrowed => {}
1109 let blame = cmt.immutability_blame();
1110 let mut err = match blame {
1111 Some(ImmutabilityBlame::ClosureEnv(id)) => {
1112 // FIXME: the distinction between these 2 messages looks wrong.
1113 let help_msg = if let BorrowViolation(euv::ClosureCapture(_)) = kind {
1114 // The aliasability violation with closure captures can
1115 // happen for nested closures, so we know the enclosing
1116 // closure incorrectly accepts an `Fn` while it needs to
1118 "consider changing this to accept closures that implement `FnMut`"
1121 "consider changing this closure to take self by mutable reference"
1123 let node_id = self.tcx.hir().local_def_id_to_node_id(id);
1124 let help_span = self.tcx.hir().span(node_id);
1125 self.cannot_act_on_capture_in_sharable_fn(span,
1127 (help_span, help_msg),
1131 self.cannot_assign_into_immutable_reference(span, prefix,
1135 self.note_immutability_blame(
1138 self.tcx.hir().hir_to_node_id(cmt.hir_id)
1142 err.help("closures behind references must be called via `&mut`");
1145 self.signal_error();
1148 /// Given a type, if it is an immutable reference, return a suggestion to make it mutable
1149 fn suggest_mut_for_immutable(&self, pty: &hir::Ty, is_implicit_self: bool) -> Option<String> {
1150 // Check whether the argument is an immutable reference
1151 debug!("suggest_mut_for_immutable({:?}, {:?})", pty, is_implicit_self);
1152 if let hir::TyKind::Rptr(lifetime, hir::MutTy {
1153 mutbl: hir::Mutability::MutImmutable,
1156 // Account for existing lifetimes when generating the message
1157 let pointee_snippet = match self.tcx.sess.source_map().span_to_snippet(ty.span) {
1158 Ok(snippet) => snippet,
1162 let lifetime_snippet = if !lifetime.is_elided() {
1163 format!("{} ", match self.tcx.sess.source_map().span_to_snippet(lifetime.span) {
1164 Ok(lifetime_snippet) => lifetime_snippet,
1170 Some(format!("use `&{}mut {}` here to make mutable",
1172 if is_implicit_self { "self" } else { &*pointee_snippet }))
1178 fn local_binding_mode(&self, node_id: ast::NodeId) -> ty::BindingMode {
1179 let pat = match self.tcx.hir().get(node_id) {
1180 Node::Binding(pat) => pat,
1181 node => bug!("bad node for local: {:?}", node)
1185 hir::PatKind::Binding(..) => {
1187 .pat_binding_modes()
1189 .expect("missing binding mode")
1191 _ => bug!("local is not a binding: {:?}", pat)
1195 fn local_ty(&self, node_id: ast::NodeId) -> (Option<&hir::Ty>, bool) {
1196 let parent = self.tcx.hir().get_parent_node(node_id);
1197 let parent_node = self.tcx.hir().get(parent);
1199 // The parent node is like a fn
1200 if let Some(fn_like) = FnLikeNode::from_node(parent_node) {
1201 // `nid`'s parent's `Body`
1202 let fn_body = self.tcx.hir().body(fn_like.body());
1203 // Get the position of `node_id` in the arguments list
1204 let arg_pos = fn_body.arguments.iter().position(|arg| arg.pat.id == node_id);
1205 if let Some(i) = arg_pos {
1206 // The argument's `Ty`
1207 (Some(&fn_like.decl().inputs[i]),
1208 i == 0 && fn_like.decl().implicit_self.has_implicit_self())
1217 fn note_immutability_blame(&self,
1218 db: &mut DiagnosticBuilder<'_>,
1219 blame: Option<ImmutabilityBlame<'_>>,
1220 error_node_id: ast::NodeId) {
1223 Some(ImmutabilityBlame::ClosureEnv(_)) => {}
1224 Some(ImmutabilityBlame::ImmLocal(node_id)) => {
1225 self.note_immutable_local(db, error_node_id, node_id)
1227 Some(ImmutabilityBlame::LocalDeref(node_id)) => {
1228 match self.local_binding_mode(node_id) {
1229 ty::BindByReference(..) => {
1230 let let_span = self.tcx.hir().span(node_id);
1231 let suggestion = suggest_ref_mut(self.tcx, let_span);
1232 if let Some(replace_str) = suggestion {
1235 "use a mutable reference instead",
1237 // I believe this can be machine applicable,
1238 // but if there are multiple attempted uses of an immutable
1239 // reference, I don't know how rustfix handles it, it might
1240 // attempt fixing them multiple times.
1242 Applicability::Unspecified,
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",
1300 Applicability::MachineApplicable,
1305 "make this binding mutable",
1306 format!("mut {}", snippet),
1307 Applicability::MachineApplicable,
1314 fn report_out_of_scope_escaping_closure_capture(&self,
1315 err: &BckError<'a, 'tcx>,
1318 let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
1321 match self.tcx.sess.source_map().span_to_snippet(err.span) {
1322 Ok(string) => format!("move {}", string),
1323 Err(_) => "move |<args>| <body>".to_string()
1326 self.cannot_capture_in_long_lived_closure(err.span,
1327 &cmt_path_or_string,
1332 &format!("to force the closure to take ownership of {} \
1333 (and any other referenced variables), \
1334 use the `move` keyword",
1335 cmt_path_or_string),
1337 Applicability::MachineApplicable,
1340 self.signal_error();
1343 fn region_end_span(&self, region: ty::Region<'tcx>) -> Option<Span> {
1345 ty::ReScope(scope) => {
1346 Some(self.tcx.sess.source_map().end_point(
1347 scope.span(self.tcx, &self.region_scope_tree)))
1353 fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder<'_>, err: &BckError<'a, 'tcx>,
1354 error_span: &Span) {
1355 match err.cmt.note {
1356 mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1357 // If this is an `Fn` closure, it simply can't mutate upvars.
1358 // If it's an `FnMut` closure, the original variable was declared immutable.
1359 // We need to determine which is the case here.
1360 let kind = match err.cmt.upvar_cat().unwrap() {
1361 Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1364 if *kind == ty::ClosureKind::Fn {
1365 let closure_node_id =
1366 self.tcx.hir().local_def_id_to_node_id(upvar_id.closure_expr_id);
1367 db.span_help(self.tcx.hir().span(closure_node_id),
1368 "consider changing this closure to take \
1369 self by mutable reference");
1373 if let Categorization::Deref(..) = err.cmt.cat {
1374 db.span_label(*error_span, "cannot borrow as mutable");
1375 } else if let Categorization::Local(local_id) = err.cmt.cat {
1376 let span = self.tcx.hir().span(local_id);
1377 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1378 if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
1379 db.span_label(*error_span, "cannot reborrow mutably");
1380 db.span_label(*error_span, "try removing `&mut` here");
1382 db.span_label(*error_span, "cannot borrow mutably");
1385 db.span_label(*error_span, "cannot borrow mutably");
1387 } else if let Categorization::Interior(ref cmt, _) = err.cmt.cat {
1388 if let mc::MutabilityCategory::McImmutable = cmt.mutbl {
1389 db.span_label(*error_span,
1390 "cannot mutably borrow field of immutable binding");
1396 pub fn append_loan_path_to_string(&self,
1397 loan_path: &LoanPath<'tcx>,
1399 match loan_path.kind {
1400 LpUpvar(ty::UpvarId { var_path: ty::UpvarPath { hir_id: id}, closure_expr_id: _ }) => {
1401 out.push_str(&self.tcx.hir().name(self.tcx.hir().hir_to_node_id(id)).as_str());
1404 out.push_str(&self.tcx.hir().name(id).as_str());
1407 LpDowncast(ref lp_base, variant_def_id) => {
1409 self.append_loan_path_to_string(&lp_base, out);
1410 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1411 out.push_str(&self.tcx.item_path_str(variant_def_id));
1415 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(mc::FieldIndex(_, info)))) => {
1416 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1418 out.push_str(&info.as_str());
1421 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement)) => {
1422 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1423 out.push_str("[..]");
1426 LpExtend(ref lp_base, _, LpDeref(_)) => {
1428 self.append_loan_path_to_string(&lp_base, out);
1433 pub fn append_autoderefd_loan_path_to_string(&self,
1434 loan_path: &LoanPath<'tcx>,
1436 match loan_path.kind {
1437 LpExtend(ref lp_base, _, LpDeref(_)) => {
1438 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1439 // rules would normally allow users to omit the `*x`.
1440 // So just serialize such paths to `x.f` or x[3]` respectively.
1441 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1444 LpDowncast(ref lp_base, variant_def_id) => {
1446 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1447 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1448 out.push_str(&self.tcx.item_path_str(variant_def_id));
1452 LpVar(..) | LpUpvar(..) | LpExtend(.., LpInterior(..)) => {
1453 self.append_loan_path_to_string(loan_path, out)
1458 pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1459 let mut result = String::new();
1460 self.append_loan_path_to_string(loan_path, &mut result);
1464 pub fn cmt_to_cow_str(&self, cmt: &mc::cmt_<'tcx>) -> Cow<'static, str> {
1465 cmt.descriptive_string(self.tcx)
1468 pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1469 match opt_loan_path(cmt) {
1470 Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1471 None => self.cmt_to_cow_str(cmt).into_owned(),
1476 impl BitwiseOperator for LoanDataFlowOperator {
1478 fn join(&self, succ: usize, pred: usize) -> usize {
1479 succ | pred // loans from both preds are in scope
1483 impl DataFlowOperator for LoanDataFlowOperator {
1485 fn initial_value(&self) -> bool {
1486 false // no loans in scope by default
1490 impl<'tcx> fmt::Debug for InteriorKind {
1491 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1493 InteriorField(mc::FieldIndex(_, info)) => write!(f, "{}", info),
1494 InteriorElement => write!(f, "[]"),
1499 impl<'tcx> fmt::Debug for Loan<'tcx> {
1500 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1501 write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1507 self.restricted_paths)
1511 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1512 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1515 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir().node_to_string(id)))
1518 LpUpvar(ty::UpvarId{ var_path: ty::UpvarPath {hir_id: var_id}, closure_expr_id }) => {
1519 let s = ty::tls::with(|tcx| {
1520 let var_node_id = tcx.hir().hir_to_node_id(var_id);
1521 tcx.hir().node_to_string(var_node_id)
1523 write!(f, "$({} captured by id={:?})", s, closure_expr_id)
1526 LpDowncast(ref lp, variant_def_id) => {
1527 let variant_str = if variant_def_id.is_local() {
1528 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1530 format!("{:?}", variant_def_id)
1532 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1535 LpExtend(ref lp, _, LpDeref(_)) => {
1536 write!(f, "{:?}.*", lp)
1539 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1540 write!(f, "{:?}.{:?}", lp, interior)
1546 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1547 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1550 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir().node_to_user_string(id)))
1553 LpUpvar(ty::UpvarId{ var_path: ty::UpvarPath { hir_id }, closure_expr_id: _ }) => {
1554 let s = ty::tls::with(|tcx| {
1555 let var_node_id = tcx.hir().hir_to_node_id(hir_id);
1556 tcx.hir().node_to_string(var_node_id)
1558 write!(f, "$({} captured by closure)", s)
1561 LpDowncast(ref lp, variant_def_id) => {
1562 let variant_str = if variant_def_id.is_local() {
1563 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1565 format!("{:?}", variant_def_id)
1567 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1570 LpExtend(ref lp, _, LpDeref(_)) => {
1571 write!(f, "{}.*", lp)
1574 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1575 write!(f, "{}.{:?}", lp, interior)