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::{self, RegionMaps};
38 use rustc::middle::free_region::RegionRelations;
39 use rustc::ty::{self, TyCtxt};
40 use rustc::ty::maps::Providers;
44 use std::hash::{Hash, Hasher};
46 use syntax_pos::{MultiSpan, Span};
47 use errors::DiagnosticBuilder;
50 use rustc::hir::intravisit::{self, Visitor};
60 #[derive(Clone, Copy)]
61 pub struct LoanDataFlowOperator;
63 pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
65 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
66 for body_owner_def_id in tcx.body_owners() {
67 tcx.borrowck(body_owner_def_id);
71 pub fn provide(providers: &mut Providers) {
72 *providers = Providers {
78 /// Collection of conclusions determined via borrow checker analyses.
79 pub struct AnalysisData<'a, 'tcx: 'a> {
80 pub all_loans: Vec<Loan<'tcx>>,
81 pub loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>,
82 pub move_data: move_data::FlowedMoveData<'a, 'tcx>,
85 fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId) {
86 debug!("borrowck(body_owner_def_id={:?})", owner_def_id);
88 let owner_id = tcx.hir.as_local_node_id(owner_def_id).unwrap();
90 match tcx.hir.get(owner_id) {
91 hir_map::NodeStructCtor(_) |
92 hir_map::NodeVariant(_) => {
93 // We get invoked with anything that has MIR, but some of
94 // those things (notably the synthesized constructors from
95 // tuple structs/variants) do not have an associated body
96 // and do not need borrowchecking.
102 let body_id = tcx.hir.body_owned_by(owner_id);
103 let attributes = tcx.get_attrs(owner_def_id);
104 let tables = tcx.typeck_tables_of(owner_def_id);
105 let region_maps = tcx.region_maps(owner_def_id);
106 let mut bccx = &mut BorrowckCtxt { tcx, tables, region_maps, owner_def_id };
108 let body = bccx.tcx.hir.body(body_id);
110 if bccx.tcx.has_attr(owner_def_id, "rustc_mir_borrowck") {
111 mir::borrowck_mir(bccx, owner_id, &attributes);
113 // Eventually, borrowck will always read the MIR, but at the
114 // moment we do not. So, for now, we always force MIR to be
115 // constructed for a given fn, since this may result in errors
116 // being reported and we want that to happen.
118 // Note that `mir_validated` is a "stealable" result; the
119 // thief, `optimized_mir()`, forces borrowck, so we know that
120 // is not yet stolen.
121 tcx.mir_validated(owner_def_id).borrow();
124 let cfg = cfg::CFG::new(bccx.tcx, &body);
125 let AnalysisData { all_loans,
127 move_data: flowed_moves } =
128 build_borrowck_dataflow_data(bccx, &cfg, body_id);
130 move_data::fragments::instrument_move_fragments(&flowed_moves.move_data,
133 move_data::fragments::build_unfragmented_map(bccx,
134 &flowed_moves.move_data,
137 check_loans::check_loans(bccx, &loan_dfcx, &flowed_moves, &all_loans, body);
140 fn build_borrowck_dataflow_data<'a, 'tcx>(this: &mut BorrowckCtxt<'a, 'tcx>,
142 body_id: hir::BodyId)
143 -> AnalysisData<'a, 'tcx>
145 // Check the body of fn items.
147 let body = tcx.hir.body(body_id);
149 let mut visitor = intravisit::IdRangeComputingVisitor::new(&tcx.hir);
150 visitor.visit_body(body);
153 let (all_loans, move_data) =
154 gather_loans::gather_loans_in_fn(this, body_id);
157 DataFlowContext::new(this.tcx,
161 LoanDataFlowOperator,
164 for (loan_idx, loan) in all_loans.iter().enumerate() {
165 loan_dfcx.add_gen(loan.gen_scope.node_id(), loan_idx);
166 loan_dfcx.add_kill(KillFrom::ScopeEnd,
167 loan.kill_scope.node_id(), loan_idx);
169 loan_dfcx.add_kills_from_flow_exits(cfg);
170 loan_dfcx.propagate(cfg, body);
172 let flowed_moves = move_data::FlowedMoveData::new(move_data,
178 AnalysisData { all_loans: all_loans,
180 move_data:flowed_moves }
183 /// Accessor for introspective clients inspecting `AnalysisData` and
184 /// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer.
185 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
186 tcx: TyCtxt<'a, 'tcx, 'tcx>,
187 body_id: hir::BodyId,
189 -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
191 let owner_id = tcx.hir.body_owner(body_id);
192 let owner_def_id = tcx.hir.local_def_id(owner_id);
193 let tables = tcx.typeck_tables_of(owner_def_id);
194 let region_maps = tcx.region_maps(owner_def_id);
195 let mut bccx = BorrowckCtxt { tcx, tables, region_maps, owner_def_id };
197 let dataflow_data = build_borrowck_dataflow_data(&mut bccx, cfg, body_id);
198 (bccx, dataflow_data)
201 // ----------------------------------------------------------------------
204 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
205 tcx: TyCtxt<'a, 'tcx, 'tcx>,
207 // tables for the current thing we are checking; set to
208 // Some in `borrowck_fn` and cleared later
209 tables: &'a ty::TypeckTables<'tcx>,
211 region_maps: Rc<RegionMaps<'tcx>>,
216 ///////////////////////////////////////////////////////////////////////////
217 // Loans and loan paths
219 /// Record of a loan that was issued.
220 pub struct Loan<'tcx> {
222 loan_path: Rc<LoanPath<'tcx>>,
223 kind: ty::BorrowKind,
224 restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
226 /// gen_scope indicates where loan is introduced. Typically the
227 /// loan is introduced at the point of the borrow, but in some
228 /// cases, notably method arguments, the loan may be introduced
229 /// only later, once it comes into scope. See also
230 /// `GatherLoanCtxt::compute_gen_scope`.
231 gen_scope: region::CodeExtent<'tcx>,
233 /// kill_scope indicates when the loan goes out of scope. This is
234 /// either when the lifetime expires or when the local variable
235 /// which roots the loan-path goes out of scope, whichever happens
236 /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
237 kill_scope: region::CodeExtent<'tcx>,
239 cause: euv::LoanCause,
242 impl<'tcx> Loan<'tcx> {
243 pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
244 self.loan_path.clone()
249 pub struct LoanPath<'tcx> {
250 kind: LoanPathKind<'tcx>,
254 impl<'tcx> PartialEq for LoanPath<'tcx> {
255 fn eq(&self, that: &LoanPath<'tcx>) -> bool {
256 self.kind == that.kind
260 impl<'tcx> Hash for LoanPath<'tcx> {
261 fn hash<H: Hasher>(&self, state: &mut H) {
262 self.kind.hash(state);
266 #[derive(PartialEq, Eq, Hash, Debug)]
267 pub enum LoanPathKind<'tcx> {
268 LpVar(ast::NodeId), // `x` in README.md
269 LpUpvar(ty::UpvarId), // `x` captured by-value into closure
270 LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
271 LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem<'tcx>)
274 impl<'tcx> LoanPath<'tcx> {
275 fn new(kind: LoanPathKind<'tcx>, ty: ty::Ty<'tcx>) -> LoanPath<'tcx> {
276 LoanPath { kind: kind, ty: ty }
279 fn to_type(&self) -> ty::Ty<'tcx> { self.ty }
282 // FIXME (pnkfelix): See discussion here
283 // https://github.com/pnkfelix/rust/commit/
284 // b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
285 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
287 // A local, "cleaned" version of `mc::InteriorKind` that drops
288 // information that is not relevant to loan-path analysis. (In
289 // particular, the distinction between how precisely an array-element
290 // is tracked is irrelevant here.)
291 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
292 pub enum InteriorKind {
293 InteriorField(mc::FieldName),
294 InteriorElement(mc::ElementKind),
297 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
298 impl ToInteriorKind for mc::InteriorKind {
299 fn cleaned(self) -> InteriorKind {
301 mc::InteriorField(name) => InteriorField(name),
302 mc::InteriorElement(_, elem_kind) => InteriorElement(elem_kind),
308 // - a pointer dereference (`*LV` in README.md)
309 // - a field reference, with an optional definition of the containing
310 // enum variant (`LV.f` in README.md)
311 // `DefId` is present when the field is part of struct that is in
312 // a variant of an enum. For instance in:
313 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
314 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
315 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
316 pub enum LoanPathElem<'tcx> {
317 LpDeref(mc::PointerKind<'tcx>),
318 LpInterior(Option<DefId>, InteriorKind),
321 pub fn closure_to_block(closure_id: ast::NodeId,
322 tcx: TyCtxt) -> ast::NodeId {
323 match tcx.hir.get(closure_id) {
324 hir_map::NodeExpr(expr) => match expr.node {
325 hir::ExprClosure(.., body_id, _) => {
329 bug!("encountered non-closure id: {}", closure_id)
332 _ => bug!("encountered non-expr id: {}", closure_id)
336 impl<'a, 'tcx> LoanPath<'tcx> {
337 pub fn kill_scope(&self, bccx: &BorrowckCtxt<'a, 'tcx>) -> region::CodeExtent<'tcx> {
339 LpVar(local_id) => bccx.region_maps.var_scope(local_id),
340 LpUpvar(upvar_id) => {
341 let block_id = closure_to_block(upvar_id.closure_expr_id, bccx.tcx);
342 bccx.tcx.node_extent(block_id)
344 LpDowncast(ref base, _) |
345 LpExtend(ref base, ..) => base.kill_scope(bccx),
349 fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
350 match (&self.kind, &other.kind) {
351 (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
352 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
353 if id == id2 && opt_variant_id == opt_variant_id2 {
354 base.has_fork(&base2)
358 (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
359 (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&base),
364 fn depth(&self) -> usize {
366 LpExtend(ref base, _, LpDeref(_)) => base.depth(),
367 LpExtend(ref base, _, LpInterior(..)) => base.depth() + 1,
372 fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
373 match (&self.kind, &other.kind) {
374 (&LpExtend(ref base, a, LpInterior(opt_variant_id, id)),
375 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) => {
376 if id == id2 && opt_variant_id == opt_variant_id2 {
377 base.common(&base2).map(|x| {
379 if base.depth() == xd && base2.depth() == xd {
381 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
392 (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
393 (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&other),
394 (&LpVar(id), &LpVar(id2)) => {
396 Some(LoanPath { kind: LpVar(id), ty: self.ty })
401 (&LpUpvar(id), &LpUpvar(id2)) => {
403 Some(LoanPath { kind: LpUpvar(id), ty: self.ty })
413 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
414 //! Computes the `LoanPath` (if any) for a `cmt`.
415 //! Note that this logic is somewhat duplicated in
416 //! the method `compute()` found in `gather_loans::restrictions`,
417 //! which allows it to share common loan path pieces as it
418 //! traverses the CMT.
420 let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
423 Categorization::Rvalue(..) |
424 Categorization::StaticItem => {
428 Categorization::Local(id) => {
429 Some(new_lp(LpVar(id)))
432 Categorization::Upvar(mc::Upvar { id, .. }) => {
433 Some(new_lp(LpUpvar(id)))
436 Categorization::Deref(ref cmt_base, _, pk) => {
437 opt_loan_path(cmt_base).map(|lp| {
438 new_lp(LpExtend(lp, cmt.mutbl, LpDeref(pk)))
442 Categorization::Interior(ref cmt_base, ik) => {
443 opt_loan_path(cmt_base).map(|lp| {
444 let opt_variant_id = match cmt_base.cat {
445 Categorization::Downcast(_, did) => Some(did),
448 new_lp(LpExtend(lp, cmt.mutbl, LpInterior(opt_variant_id, ik.cleaned())))
452 Categorization::Downcast(ref cmt_base, variant_def_id) =>
453 opt_loan_path(cmt_base)
455 new_lp(LpDowncast(lp, variant_def_id))
461 ///////////////////////////////////////////////////////////////////////////
464 // Errors that can occur
465 #[derive(Debug, PartialEq)]
466 pub enum bckerr_code<'tcx> {
468 /// superscope, subscope, loan cause
469 err_out_of_scope(ty::Region<'tcx>, ty::Region<'tcx>, euv::LoanCause),
470 err_borrowed_pointer_too_short(ty::Region<'tcx>, ty::Region<'tcx>), // loan, ptr
473 // Combination of an error code and the categorization of the expression
475 #[derive(Debug, PartialEq)]
476 pub struct BckError<'tcx> {
478 cause: AliasableViolationKind,
480 code: bckerr_code<'tcx>
483 #[derive(Copy, Clone, Debug, PartialEq)]
484 pub enum AliasableViolationKind {
486 BorrowViolation(euv::LoanCause)
489 #[derive(Copy, Clone, Debug)]
490 pub enum MovedValueUseKind {
495 ///////////////////////////////////////////////////////////////////////////
498 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
499 pub fn is_subregion_of(&self,
500 r_sub: ty::Region<'tcx>,
501 r_sup: ty::Region<'tcx>)
504 let region_rels = RegionRelations::new(self.tcx,
507 &self.tables.free_region_map);
508 region_rels.is_subregion_of(r_sub, r_sup)
511 pub fn report(&self, err: BckError<'tcx>) {
512 // Catch and handle some particular cases.
513 match (&err.code, &err.cause) {
514 (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _),
515 &BorrowViolation(euv::ClosureCapture(span))) |
516 (&err_out_of_scope(&ty::ReScope(_), &ty::ReFree(..), _),
517 &BorrowViolation(euv::ClosureCapture(span))) => {
518 return self.report_out_of_scope_escaping_closure_capture(&err, span);
523 let mut db = self.bckerr_to_diag(&err);
524 self.note_and_explain_bckerr(&mut db, err);
528 pub fn report_use_of_moved_value(&self,
530 use_kind: MovedValueUseKind,
532 the_move: &move_data::Move,
533 moved_lp: &LoanPath<'tcx>,
534 _param_env: &ty::ParameterEnvironment<'tcx>) {
535 let (verb, verb_participle) = match use_kind {
536 MovedInUse => ("use", "used"),
537 MovedInCapture => ("capture", "captured"),
540 let (_ol, _moved_lp_msg, mut err) = match the_move.kind {
541 move_data::Declared => {
542 // If this is an uninitialized variable, just emit a simple warning
545 self.tcx.sess, use_span, E0381,
546 "{} of possibly uninitialized variable: `{}`",
548 self.loan_path_to_string(lp))
549 .span_label(use_span, format!("use of possibly uninitialized `{}`",
550 self.loan_path_to_string(lp)))
555 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
556 // normally generate a rather confusing message:
558 // error: use of moved value: `x.b`
559 // note: `x.a` moved here...
561 // What we want to do instead is get the 'common ancestor' of the two moves and
562 // use that for most of the message instead, giving is something like this:
564 // error: use of moved value: `x`
565 // note: `x` moved here (through moving `x.a`)...
567 let common = moved_lp.common(lp);
568 let has_common = common.is_some();
569 let has_fork = moved_lp.has_fork(lp);
570 let (nl, ol, moved_lp_msg) =
571 if has_fork && has_common {
572 let nl = self.loan_path_to_string(&common.unwrap());
574 let moved_lp_msg = format!(" (through moving `{}`)",
575 self.loan_path_to_string(moved_lp));
576 (nl, ol, moved_lp_msg)
578 (self.loan_path_to_string(lp),
579 self.loan_path_to_string(moved_lp),
583 let partial = moved_lp.depth() > lp.depth();
584 let msg = if !has_fork && partial { "partially " }
585 else if has_fork && !has_common { "collaterally "}
587 let err = struct_span_err!(
588 self.tcx.sess, use_span, E0382,
589 "{} of {}moved value: `{}`",
591 (ol, moved_lp_msg, err)}
594 // Get type of value and span where it was previously
596 let (move_span, move_note) = match the_move.kind {
597 move_data::Declared => {
601 move_data::MoveExpr |
602 move_data::MovePat =>
603 (self.tcx.hir.span(the_move.id), ""),
605 move_data::Captured =>
606 (match self.tcx.hir.expect_expr(the_move.id).node {
607 hir::ExprClosure(.., fn_decl_span) => fn_decl_span,
608 ref r => bug!("Captured({}) maps to non-closure: {:?}",
610 }, " (into closure)"),
613 // Annotate the use and the move in the span. Watch out for
614 // the case where the use and the move are the same. This
615 // means the use is in a loop.
616 err = if use_span == move_span {
619 format!("value moved{} here in previous iteration of loop",
623 err.span_label(use_span, format!("value {} here after move", verb_participle))
624 .span_label(move_span, format!("value moved{} here", move_note));
628 err.note(&format!("move occurs because `{}` has type `{}`, \
629 which does not implement the `Copy` trait",
630 self.loan_path_to_string(moved_lp),
633 // Note: we used to suggest adding a `ref binding` or calling
634 // `clone` but those suggestions have been removed because
635 // they are often not what you actually want to do, and were
636 // not considered particularly helpful.
641 pub fn report_partial_reinitialization_of_uninitialized_structure(
644 lp: &LoanPath<'tcx>) {
646 self.tcx.sess, span, E0383,
647 "partial reinitialization of uninitialized structure `{}`",
648 self.loan_path_to_string(lp));
651 pub fn report_reassigned_immutable_variable(&self,
655 &move_data::Assignment) {
656 let mut err = struct_span_err!(
657 self.tcx.sess, span, E0384,
658 "re-assignment of immutable variable `{}`",
659 self.loan_path_to_string(lp));
660 err.span_label(span, "re-assignment of immutable variable");
661 if span != assign.span {
662 err.span_label(assign.span, format!("first assignment to `{}`",
663 self.loan_path_to_string(lp)));
668 pub fn span_err(&self, s: Span, m: &str) {
669 self.tcx.sess.span_err(s, m);
672 pub fn struct_span_err<S: Into<MultiSpan>>(&self, s: S, m: &str)
673 -> DiagnosticBuilder<'a> {
674 self.tcx.sess.struct_span_err(s, m)
677 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(&self,
681 -> DiagnosticBuilder<'a> {
682 self.tcx.sess.struct_span_err_with_code(s, msg, code)
685 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, s: S, msg: &str, code: &str) {
686 self.tcx.sess.span_err_with_code(s, msg, code);
689 fn bckerr_to_diag(&self, err: &BckError<'tcx>) -> DiagnosticBuilder<'a> {
690 let span = err.span.clone();
692 let msg = match err.code {
694 let descr = match err.cmt.note {
695 mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
696 self.cmt_to_string(&err.cmt)
698 _ => match opt_loan_path(&err.cmt) {
701 err.cmt.mutbl.to_user_str(),
702 self.cmt_to_string(&err.cmt))
706 format!("{} {} `{}`",
707 err.cmt.mutbl.to_user_str(),
708 self.cmt_to_string(&err.cmt),
709 self.loan_path_to_string(&lp))
715 MutabilityViolation => {
716 format!("cannot assign to {}", descr)
718 BorrowViolation(euv::ClosureCapture(_)) => {
719 format!("closure cannot assign to {}", descr)
721 BorrowViolation(euv::OverloadedOperator) |
722 BorrowViolation(euv::AddrOf) |
723 BorrowViolation(euv::RefBinding) |
724 BorrowViolation(euv::AutoRef) |
725 BorrowViolation(euv::AutoUnsafe) |
726 BorrowViolation(euv::ForLoop) |
727 BorrowViolation(euv::MatchDiscriminant) => {
728 format!("cannot borrow {} as mutable", descr)
730 BorrowViolation(euv::ClosureInvocation) => {
732 "err_mutbl with a closure invocation");
736 err_out_of_scope(..) => {
737 let msg = match opt_loan_path(&err.cmt) {
738 None => "borrowed value".to_string(),
740 format!("`{}`", self.loan_path_to_string(&lp))
743 format!("{} does not live long enough", msg)
745 err_borrowed_pointer_too_short(..) => {
746 let descr = self.cmt_to_path_or_string(&err.cmt);
747 format!("lifetime of {} is too short to guarantee \
748 its contents can be safely reborrowed",
753 self.struct_span_err(span, &msg)
756 pub fn report_aliasability_violation(&self,
758 kind: AliasableViolationKind,
759 cause: mc::AliasableReason,
760 cmt: mc::cmt<'tcx>) {
761 let mut is_closure = false;
762 let prefix = match kind {
763 MutabilityViolation => {
764 "cannot assign to data"
766 BorrowViolation(euv::ClosureCapture(_)) |
767 BorrowViolation(euv::OverloadedOperator) |
768 BorrowViolation(euv::AddrOf) |
769 BorrowViolation(euv::AutoRef) |
770 BorrowViolation(euv::AutoUnsafe) |
771 BorrowViolation(euv::RefBinding) |
772 BorrowViolation(euv::MatchDiscriminant) => {
773 "cannot borrow data mutably"
776 BorrowViolation(euv::ClosureInvocation) => {
781 BorrowViolation(euv::ForLoop) => {
787 mc::AliasableStatic |
788 mc::AliasableStaticMut => {
789 // This path cannot occur. It happens when we have an
790 // `&mut` or assignment to a static. But in the case
791 // of `static X`, we get a mutability violation first,
792 // and never get here. In the case of `static mut X`,
793 // that is unsafe and hence the aliasability error is
795 span_bug!(span, "aliasability violation for static `{}`", prefix)
797 mc::AliasableBorrowed => {}
799 let blame = cmt.immutability_blame();
800 let mut err = match blame {
801 Some(ImmutabilityBlame::ClosureEnv(id)) => {
802 let mut err = struct_span_err!(
803 self.tcx.sess, span, E0387,
804 "{} in a captured outer variable in an `Fn` closure", prefix);
806 // FIXME: the distinction between these 2 messages looks wrong.
807 let help = if let BorrowViolation(euv::ClosureCapture(_)) = kind {
808 // The aliasability violation with closure captures can
809 // happen for nested closures, so we know the enclosing
810 // closure incorrectly accepts an `Fn` while it needs to
812 "consider changing this to accept closures that implement `FnMut`"
815 "consider changing this closure to take self by mutable reference"
817 err.span_help(self.tcx.hir.span(id), help);
821 let mut err = struct_span_err!(
822 self.tcx.sess, span, E0389,
823 "{} in a `&` reference", prefix);
824 err.span_label(span, "assignment into an immutable reference");
828 self.note_immutability_blame(&mut err, blame);
831 err.help("closures behind references must be called via `&mut`");
836 /// Given a type, if it is an immutable reference, return a suggestion to make it mutable
837 fn suggest_mut_for_immutable(&self, pty: &hir::Ty, is_implicit_self: bool) -> Option<String> {
838 // Check wether the argument is an immutable reference
839 debug!("suggest_mut_for_immutable({:?}, {:?})", pty, is_implicit_self);
840 if let hir::TyRptr(lifetime, hir::MutTy {
841 mutbl: hir::Mutability::MutImmutable,
844 // Account for existing lifetimes when generating the message
845 let pointee_snippet = match self.tcx.sess.codemap().span_to_snippet(ty.span) {
846 Ok(snippet) => snippet,
850 let lifetime_snippet = if !lifetime.is_elided() {
851 format!("{} ", match self.tcx.sess.codemap().span_to_snippet(lifetime.span) {
852 Ok(lifetime_snippet) => lifetime_snippet,
858 Some(format!("use `&{}mut {}` here to make mutable",
860 if is_implicit_self { "self" } else { &*pointee_snippet }))
866 fn local_binding_mode(&self, node_id: ast::NodeId) -> hir::BindingMode {
867 let pat = match self.tcx.hir.get(node_id) {
868 hir_map::Node::NodeLocal(pat) => pat,
869 node => bug!("bad node for local: {:?}", node)
873 hir::PatKind::Binding(mode, ..) => mode,
874 _ => bug!("local is not a binding: {:?}", pat)
878 fn local_ty(&self, node_id: ast::NodeId) -> (Option<&hir::Ty>, bool) {
879 let parent = self.tcx.hir.get_parent_node(node_id);
880 let parent_node = self.tcx.hir.get(parent);
882 // The parent node is like a fn
883 if let Some(fn_like) = FnLikeNode::from_node(parent_node) {
884 // `nid`'s parent's `Body`
885 let fn_body = self.tcx.hir.body(fn_like.body());
886 // Get the position of `node_id` in the arguments list
887 let arg_pos = fn_body.arguments.iter().position(|arg| arg.pat.id == node_id);
888 if let Some(i) = arg_pos {
889 // The argument's `Ty`
890 (Some(&fn_like.decl().inputs[i]),
891 i == 0 && fn_like.decl().has_implicit_self)
900 fn note_immutability_blame(&self,
901 db: &mut DiagnosticBuilder,
902 blame: Option<ImmutabilityBlame>) {
905 Some(ImmutabilityBlame::ClosureEnv(_)) => {}
906 Some(ImmutabilityBlame::ImmLocal(node_id)) => {
907 let let_span = self.tcx.hir.span(node_id);
908 if let hir::BindingMode::BindByValue(..) = self.local_binding_mode(node_id) {
909 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(let_span) {
910 let (_, is_implicit_self) = self.local_ty(node_id);
911 if is_implicit_self && snippet != "self" {
912 // avoid suggesting `mut &self`.
917 format!("consider changing this to `mut {}`", snippet)
922 Some(ImmutabilityBlame::LocalDeref(node_id)) => {
923 let let_span = self.tcx.hir.span(node_id);
924 match self.local_binding_mode(node_id) {
925 hir::BindingMode::BindByRef(..) => {
926 let snippet = self.tcx.sess.codemap().span_to_snippet(let_span);
927 if let Ok(snippet) = snippet {
930 format!("consider changing this to `{}`",
931 snippet.replace("ref ", "ref mut "))
935 hir::BindingMode::BindByValue(..) => {
936 if let (Some(local_ty), is_implicit_self) = self.local_ty(node_id) {
938 self.suggest_mut_for_immutable(local_ty, is_implicit_self) {
939 db.span_label(local_ty.span, msg);
945 Some(ImmutabilityBlame::AdtFieldDeref(_, field)) => {
946 let node_id = match self.tcx.hir.as_local_node_id(field.did) {
947 Some(node_id) => node_id,
951 if let hir_map::Node::NodeField(ref field) = self.tcx.hir.get(node_id) {
952 if let Some(msg) = self.suggest_mut_for_immutable(&field.ty, false) {
953 db.span_label(field.ty.span, msg);
960 fn report_out_of_scope_escaping_closure_capture(&self,
961 err: &BckError<'tcx>,
964 let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
967 match self.tcx.sess.codemap().span_to_snippet(err.span) {
968 Ok(string) => format!("move {}", string),
969 Err(_) => format!("move |<args>| <body>")
972 struct_span_err!(self.tcx.sess, err.span, E0373,
973 "closure may outlive the current function, \
975 which is owned by the current function",
977 .span_label(capture_span,
978 format!("{} is borrowed here",
980 .span_label(err.span,
981 format!("may outlive borrowed value {}",
983 .span_suggestion(err.span,
984 &format!("to force the closure to take ownership of {} \
985 (and any other referenced variables), \
986 use the `move` keyword, as shown:",
992 fn region_end_span(&self, region: ty::Region<'tcx>) -> Option<Span> {
994 ty::ReScope(scope) => {
995 match scope.span(&self.tcx.hir) {
1008 fn note_and_explain_bckerr(&self, db: &mut DiagnosticBuilder, err: BckError<'tcx>) {
1009 let error_span = err.span.clone();
1012 self.note_and_explain_mutbl_error(db, &err, &error_span);
1013 self.note_immutability_blame(db, err.cmt.immutability_blame());
1015 err_out_of_scope(super_scope, sub_scope, cause) => {
1016 let (value_kind, value_msg) = match err.cmt.cat {
1017 mc::Categorization::Rvalue(..) =>
1018 ("temporary value", "temporary value created here"),
1020 ("borrowed value", "borrow occurs here")
1023 let is_closure = match cause {
1024 euv::ClosureCapture(s) => {
1025 // The primary span starts out as the closure creation point.
1026 // Change the primary span here to highlight the use of the variable
1027 // in the closure, because it seems more natural. Highlight
1028 // closure creation point as a secondary span.
1029 match db.span.primary_span() {
1031 db.span = MultiSpan::from_span(s);
1032 db.span_label(primary, "capture occurs here");
1033 db.span_label(s, "does not live long enough");
1040 db.span_label(error_span, "does not live long enough");
1045 let sub_span = self.region_end_span(sub_scope);
1046 let super_span = self.region_end_span(super_scope);
1048 match (sub_span, super_span) {
1049 (Some(s1), Some(s2)) if s1 == s2 => {
1051 db.span = MultiSpan::from_span(s1);
1052 db.span_label(error_span, value_msg);
1053 let msg = match opt_loan_path(&err.cmt) {
1054 None => value_kind.to_string(),
1056 format!("`{}`", self.loan_path_to_string(&lp))
1060 format!("{} dropped here while still borrowed", msg));
1062 db.span_label(s1, format!("{} dropped before borrower", value_kind));
1064 db.note("values in a scope are dropped in the opposite order \
1067 (Some(s1), Some(s2)) if !is_closure => {
1068 db.span = MultiSpan::from_span(s2);
1069 db.span_label(error_span, value_msg);
1070 let msg = match opt_loan_path(&err.cmt) {
1071 None => value_kind.to_string(),
1073 format!("`{}`", self.loan_path_to_string(&lp))
1076 db.span_label(s2, format!("{} dropped here while still borrowed", msg));
1077 db.span_label(s1, format!("{} needs to live until here", value_kind));
1082 db.span_label(s, format!("{} needs to live until here",
1086 self.tcx.note_and_explain_region(
1088 "borrowed value must be valid for ",
1095 db.span_label(s, format!("{} only lives until here", value_kind));
1098 self.tcx.note_and_explain_region(
1100 "...but borrowed value is only valid for ",
1108 if let Some(_) = statement_scope_span(self.tcx, super_scope) {
1109 db.note("consider using a `let` binding to increase its lifetime");
1115 mc::Categorization::Rvalue(r, or) if r != or => {
1117 before rustc 1.16, this temporary lived longer - see issue #39283 \
1118 (https://github.com/rust-lang/rust/issues/39283)");
1124 err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1125 let descr = match opt_loan_path(&err.cmt) {
1127 format!("`{}`", self.loan_path_to_string(&lp))
1129 None => self.cmt_to_string(&err.cmt),
1131 self.tcx.note_and_explain_region(
1133 &format!("{} would have to be valid for ",
1137 self.tcx.note_and_explain_region(
1139 &format!("...but {} is only valid for ", descr),
1146 fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'tcx>,
1147 error_span: &Span) {
1148 match err.cmt.note {
1149 mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1150 // If this is an `Fn` closure, it simply can't mutate upvars.
1151 // If it's an `FnMut` closure, the original variable was declared immutable.
1152 // We need to determine which is the case here.
1153 let kind = match err.cmt.upvar().unwrap().cat {
1154 Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1157 if kind == ty::ClosureKind::Fn {
1158 db.span_help(self.tcx.hir.span(upvar_id.closure_expr_id),
1159 "consider changing this closure to take \
1160 self by mutable reference");
1164 if let Categorization::Deref(..) = err.cmt.cat {
1165 db.span_label(*error_span, "cannot borrow as mutable");
1166 } else if let Categorization::Local(local_id) = err.cmt.cat {
1167 let span = self.tcx.hir.span(local_id);
1168 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
1169 if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
1170 db.span_label(*error_span, "cannot reborrow mutably");
1171 db.span_label(*error_span, "try removing `&mut` here");
1173 db.span_label(*error_span, "cannot borrow mutably");
1176 db.span_label(*error_span, "cannot borrow mutably");
1178 } else if let Categorization::Interior(ref cmt, _) = err.cmt.cat {
1179 if let mc::MutabilityCategory::McImmutable = cmt.mutbl {
1180 db.span_label(*error_span,
1181 "cannot mutably borrow immutable field");
1187 pub fn append_loan_path_to_string(&self,
1188 loan_path: &LoanPath<'tcx>,
1190 match loan_path.kind {
1191 LpUpvar(ty::UpvarId{ var_id: id, closure_expr_id: _ }) |
1193 out.push_str(&self.tcx.local_var_name_str(id));
1196 LpDowncast(ref lp_base, variant_def_id) => {
1198 self.append_loan_path_to_string(&lp_base, out);
1199 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1200 out.push_str(&self.tcx.item_path_str(variant_def_id));
1204 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(fname))) => {
1205 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1207 mc::NamedField(fname) => {
1209 out.push_str(&fname.as_str());
1211 mc::PositionalField(idx) => {
1213 out.push_str(&idx.to_string());
1218 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement(..))) => {
1219 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1220 out.push_str("[..]");
1223 LpExtend(ref lp_base, _, LpDeref(_)) => {
1225 self.append_loan_path_to_string(&lp_base, out);
1230 pub fn append_autoderefd_loan_path_to_string(&self,
1231 loan_path: &LoanPath<'tcx>,
1233 match loan_path.kind {
1234 LpExtend(ref lp_base, _, LpDeref(_)) => {
1235 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1236 // rules would normally allow users to omit the `*x`.
1237 // So just serialize such paths to `x.f` or x[3]` respectively.
1238 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1241 LpDowncast(ref lp_base, variant_def_id) => {
1243 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1245 out.push_str(&self.tcx.item_path_str(variant_def_id));
1249 LpVar(..) | LpUpvar(..) | LpExtend(.., LpInterior(..)) => {
1250 self.append_loan_path_to_string(loan_path, out)
1255 pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1256 let mut result = String::new();
1257 self.append_loan_path_to_string(loan_path, &mut result);
1261 pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1262 cmt.descriptive_string(self.tcx)
1265 pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt<'tcx>) -> String {
1266 match opt_loan_path(cmt) {
1267 Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1268 None => self.cmt_to_string(cmt),
1273 fn statement_scope_span(tcx: TyCtxt, region: ty::Region) -> Option<Span> {
1275 ty::ReScope(scope) => {
1276 match tcx.hir.find(scope.node_id()) {
1277 Some(hir_map::NodeStmt(stmt)) => Some(stmt.span),
1285 impl BitwiseOperator for LoanDataFlowOperator {
1287 fn join(&self, succ: usize, pred: usize) -> usize {
1288 succ | pred // loans from both preds are in scope
1292 impl DataFlowOperator for LoanDataFlowOperator {
1294 fn initial_value(&self) -> bool {
1295 false // no loans in scope by default
1299 impl<'tcx> fmt::Debug for InteriorKind {
1300 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1302 InteriorField(mc::NamedField(fld)) => write!(f, "{}", fld),
1303 InteriorField(mc::PositionalField(i)) => write!(f, "#{}", i),
1304 InteriorElement(..) => write!(f, "[]"),
1309 impl<'tcx> fmt::Debug for Loan<'tcx> {
1310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1311 write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1317 self.restricted_paths)
1321 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1322 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1325 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_string(id)))
1328 LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => {
1329 let s = ty::tls::with(|tcx| tcx.hir.node_to_string(var_id));
1330 write!(f, "$({} captured by id={})", s, closure_expr_id)
1333 LpDowncast(ref lp, variant_def_id) => {
1334 let variant_str = if variant_def_id.is_local() {
1335 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1337 format!("{:?}", variant_def_id)
1339 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1342 LpExtend(ref lp, _, LpDeref(_)) => {
1343 write!(f, "{:?}.*", lp)
1346 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1347 write!(f, "{:?}.{:?}", lp, interior)
1353 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1354 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1357 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_user_string(id)))
1360 LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => {
1361 let s = ty::tls::with(|tcx| tcx.hir.node_to_user_string(var_id));
1362 write!(f, "$({} captured by closure)", s)
1365 LpDowncast(ref lp, variant_def_id) => {
1366 let variant_str = if variant_def_id.is_local() {
1367 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1369 format!("{:?}", variant_def_id)
1371 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1374 LpExtend(ref lp, _, LpDeref(_)) => {
1375 write!(f, "{}.*", lp)
1378 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1379 write!(f, "{}.{:?}", lp, interior)