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);
114 let cfg = cfg::CFG::new(bccx.tcx, &body);
115 let AnalysisData { all_loans,
117 move_data: flowed_moves } =
118 build_borrowck_dataflow_data(bccx, &cfg, body_id);
120 move_data::fragments::instrument_move_fragments(&flowed_moves.move_data,
123 move_data::fragments::build_unfragmented_map(bccx,
124 &flowed_moves.move_data,
127 check_loans::check_loans(bccx, &loan_dfcx, &flowed_moves, &all_loans, body);
130 fn build_borrowck_dataflow_data<'a, 'tcx>(this: &mut BorrowckCtxt<'a, 'tcx>,
132 body_id: hir::BodyId)
133 -> AnalysisData<'a, 'tcx>
135 // Check the body of fn items.
137 let body = tcx.hir.body(body_id);
139 let mut visitor = intravisit::IdRangeComputingVisitor::new(&tcx.hir);
140 visitor.visit_body(body);
143 let (all_loans, move_data) =
144 gather_loans::gather_loans_in_fn(this, body_id);
147 DataFlowContext::new(this.tcx,
151 LoanDataFlowOperator,
154 for (loan_idx, loan) in all_loans.iter().enumerate() {
155 loan_dfcx.add_gen(loan.gen_scope.node_id(), loan_idx);
156 loan_dfcx.add_kill(KillFrom::ScopeEnd,
157 loan.kill_scope.node_id(), loan_idx);
159 loan_dfcx.add_kills_from_flow_exits(cfg);
160 loan_dfcx.propagate(cfg, body);
162 let flowed_moves = move_data::FlowedMoveData::new(move_data,
168 AnalysisData { all_loans: all_loans,
170 move_data:flowed_moves }
173 /// Accessor for introspective clients inspecting `AnalysisData` and
174 /// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer.
175 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
176 tcx: TyCtxt<'a, 'tcx, 'tcx>,
177 body_id: hir::BodyId,
179 -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
181 let owner_id = tcx.hir.body_owner(body_id);
182 let owner_def_id = tcx.hir.local_def_id(owner_id);
183 let tables = tcx.typeck_tables_of(owner_def_id);
184 let region_maps = tcx.region_maps(owner_def_id);
185 let mut bccx = BorrowckCtxt { tcx, tables, region_maps, owner_def_id };
187 let dataflow_data = build_borrowck_dataflow_data(&mut bccx, cfg, body_id);
188 (bccx, dataflow_data)
191 // ----------------------------------------------------------------------
194 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
195 tcx: TyCtxt<'a, 'tcx, 'tcx>,
197 // tables for the current thing we are checking; set to
198 // Some in `borrowck_fn` and cleared later
199 tables: &'a ty::TypeckTables<'tcx>,
201 region_maps: Rc<RegionMaps<'tcx>>,
206 ///////////////////////////////////////////////////////////////////////////
207 // Loans and loan paths
209 /// Record of a loan that was issued.
210 pub struct Loan<'tcx> {
212 loan_path: Rc<LoanPath<'tcx>>,
213 kind: ty::BorrowKind,
214 restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
216 /// gen_scope indicates where loan is introduced. Typically the
217 /// loan is introduced at the point of the borrow, but in some
218 /// cases, notably method arguments, the loan may be introduced
219 /// only later, once it comes into scope. See also
220 /// `GatherLoanCtxt::compute_gen_scope`.
221 gen_scope: region::CodeExtent<'tcx>,
223 /// kill_scope indicates when the loan goes out of scope. This is
224 /// either when the lifetime expires or when the local variable
225 /// which roots the loan-path goes out of scope, whichever happens
226 /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
227 kill_scope: region::CodeExtent<'tcx>,
229 cause: euv::LoanCause,
232 impl<'tcx> Loan<'tcx> {
233 pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
234 self.loan_path.clone()
239 pub struct LoanPath<'tcx> {
240 kind: LoanPathKind<'tcx>,
244 impl<'tcx> PartialEq for LoanPath<'tcx> {
245 fn eq(&self, that: &LoanPath<'tcx>) -> bool {
246 self.kind == that.kind
250 impl<'tcx> Hash for LoanPath<'tcx> {
251 fn hash<H: Hasher>(&self, state: &mut H) {
252 self.kind.hash(state);
256 #[derive(PartialEq, Eq, Hash, Debug)]
257 pub enum LoanPathKind<'tcx> {
258 LpVar(ast::NodeId), // `x` in README.md
259 LpUpvar(ty::UpvarId), // `x` captured by-value into closure
260 LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
261 LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem<'tcx>)
264 impl<'tcx> LoanPath<'tcx> {
265 fn new(kind: LoanPathKind<'tcx>, ty: ty::Ty<'tcx>) -> LoanPath<'tcx> {
266 LoanPath { kind: kind, ty: ty }
269 fn to_type(&self) -> ty::Ty<'tcx> { self.ty }
272 // FIXME (pnkfelix): See discussion here
273 // https://github.com/pnkfelix/rust/commit/
274 // b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
275 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
277 // A local, "cleaned" version of `mc::InteriorKind` that drops
278 // information that is not relevant to loan-path analysis. (In
279 // particular, the distinction between how precisely an array-element
280 // is tracked is irrelevant here.)
281 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
282 pub enum InteriorKind {
283 InteriorField(mc::FieldName),
284 InteriorElement(mc::ElementKind),
287 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
288 impl ToInteriorKind for mc::InteriorKind {
289 fn cleaned(self) -> InteriorKind {
291 mc::InteriorField(name) => InteriorField(name),
292 mc::InteriorElement(_, elem_kind) => InteriorElement(elem_kind),
298 // - a pointer dereference (`*LV` in README.md)
299 // - a field reference, with an optional definition of the containing
300 // enum variant (`LV.f` in README.md)
301 // `DefId` is present when the field is part of struct that is in
302 // a variant of an enum. For instance in:
303 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
304 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
305 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
306 pub enum LoanPathElem<'tcx> {
307 LpDeref(mc::PointerKind<'tcx>),
308 LpInterior(Option<DefId>, InteriorKind),
311 pub fn closure_to_block(closure_id: ast::NodeId,
312 tcx: TyCtxt) -> ast::NodeId {
313 match tcx.hir.get(closure_id) {
314 hir_map::NodeExpr(expr) => match expr.node {
315 hir::ExprClosure(.., body_id, _) => {
319 bug!("encountered non-closure id: {}", closure_id)
322 _ => bug!("encountered non-expr id: {}", closure_id)
326 impl<'a, 'tcx> LoanPath<'tcx> {
327 pub fn kill_scope(&self, bccx: &BorrowckCtxt<'a, 'tcx>) -> region::CodeExtent<'tcx> {
329 LpVar(local_id) => bccx.region_maps.var_scope(local_id),
330 LpUpvar(upvar_id) => {
331 let block_id = closure_to_block(upvar_id.closure_expr_id, bccx.tcx);
332 bccx.tcx.node_extent(block_id)
334 LpDowncast(ref base, _) |
335 LpExtend(ref base, ..) => base.kill_scope(bccx),
339 fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
340 match (&self.kind, &other.kind) {
341 (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
342 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
343 if id == id2 && opt_variant_id == opt_variant_id2 {
344 base.has_fork(&base2)
348 (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
349 (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&base),
354 fn depth(&self) -> usize {
356 LpExtend(ref base, _, LpDeref(_)) => base.depth(),
357 LpExtend(ref base, _, LpInterior(..)) => base.depth() + 1,
362 fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
363 match (&self.kind, &other.kind) {
364 (&LpExtend(ref base, a, LpInterior(opt_variant_id, id)),
365 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) => {
366 if id == id2 && opt_variant_id == opt_variant_id2 {
367 base.common(&base2).map(|x| {
369 if base.depth() == xd && base2.depth() == xd {
371 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
382 (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
383 (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&other),
384 (&LpVar(id), &LpVar(id2)) => {
386 Some(LoanPath { kind: LpVar(id), ty: self.ty })
391 (&LpUpvar(id), &LpUpvar(id2)) => {
393 Some(LoanPath { kind: LpUpvar(id), ty: self.ty })
403 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
404 //! Computes the `LoanPath` (if any) for a `cmt`.
405 //! Note that this logic is somewhat duplicated in
406 //! the method `compute()` found in `gather_loans::restrictions`,
407 //! which allows it to share common loan path pieces as it
408 //! traverses the CMT.
410 let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
413 Categorization::Rvalue(..) |
414 Categorization::StaticItem => {
418 Categorization::Local(id) => {
419 Some(new_lp(LpVar(id)))
422 Categorization::Upvar(mc::Upvar { id, .. }) => {
423 Some(new_lp(LpUpvar(id)))
426 Categorization::Deref(ref cmt_base, _, pk) => {
427 opt_loan_path(cmt_base).map(|lp| {
428 new_lp(LpExtend(lp, cmt.mutbl, LpDeref(pk)))
432 Categorization::Interior(ref cmt_base, ik) => {
433 opt_loan_path(cmt_base).map(|lp| {
434 let opt_variant_id = match cmt_base.cat {
435 Categorization::Downcast(_, did) => Some(did),
438 new_lp(LpExtend(lp, cmt.mutbl, LpInterior(opt_variant_id, ik.cleaned())))
442 Categorization::Downcast(ref cmt_base, variant_def_id) =>
443 opt_loan_path(cmt_base)
445 new_lp(LpDowncast(lp, variant_def_id))
451 ///////////////////////////////////////////////////////////////////////////
454 // Errors that can occur
455 #[derive(Debug, PartialEq)]
456 pub enum bckerr_code<'tcx> {
458 /// superscope, subscope, loan cause
459 err_out_of_scope(ty::Region<'tcx>, ty::Region<'tcx>, euv::LoanCause),
460 err_borrowed_pointer_too_short(ty::Region<'tcx>, ty::Region<'tcx>), // loan, ptr
463 // Combination of an error code and the categorization of the expression
465 #[derive(Debug, PartialEq)]
466 pub struct BckError<'tcx> {
468 cause: AliasableViolationKind,
470 code: bckerr_code<'tcx>
473 #[derive(Copy, Clone, Debug, PartialEq)]
474 pub enum AliasableViolationKind {
476 BorrowViolation(euv::LoanCause)
479 #[derive(Copy, Clone, Debug)]
480 pub enum MovedValueUseKind {
485 ///////////////////////////////////////////////////////////////////////////
488 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
489 pub fn is_subregion_of(&self,
490 r_sub: ty::Region<'tcx>,
491 r_sup: ty::Region<'tcx>)
494 let region_rels = RegionRelations::new(self.tcx,
497 &self.tables.free_region_map);
498 region_rels.is_subregion_of(r_sub, r_sup)
501 pub fn report(&self, err: BckError<'tcx>) {
502 // Catch and handle some particular cases.
503 match (&err.code, &err.cause) {
504 (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _),
505 &BorrowViolation(euv::ClosureCapture(span))) |
506 (&err_out_of_scope(&ty::ReScope(_), &ty::ReFree(..), _),
507 &BorrowViolation(euv::ClosureCapture(span))) => {
508 return self.report_out_of_scope_escaping_closure_capture(&err, span);
513 let mut db = self.bckerr_to_diag(&err);
514 self.note_and_explain_bckerr(&mut db, err);
518 pub fn report_use_of_moved_value(&self,
520 use_kind: MovedValueUseKind,
522 the_move: &move_data::Move,
523 moved_lp: &LoanPath<'tcx>,
524 _param_env: &ty::ParameterEnvironment<'tcx>) {
525 let (verb, verb_participle) = match use_kind {
526 MovedInUse => ("use", "used"),
527 MovedInCapture => ("capture", "captured"),
530 let (_ol, _moved_lp_msg, mut err) = match the_move.kind {
531 move_data::Declared => {
532 // If this is an uninitialized variable, just emit a simple warning
535 self.tcx.sess, use_span, E0381,
536 "{} of possibly uninitialized variable: `{}`",
538 self.loan_path_to_string(lp))
539 .span_label(use_span, &format!("use of possibly uninitialized `{}`",
540 self.loan_path_to_string(lp)))
545 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
546 // normally generate a rather confusing message:
548 // error: use of moved value: `x.b`
549 // note: `x.a` moved here...
551 // What we want to do instead is get the 'common ancestor' of the two moves and
552 // use that for most of the message instead, giving is something like this:
554 // error: use of moved value: `x`
555 // note: `x` moved here (through moving `x.a`)...
557 let common = moved_lp.common(lp);
558 let has_common = common.is_some();
559 let has_fork = moved_lp.has_fork(lp);
560 let (nl, ol, moved_lp_msg) =
561 if has_fork && has_common {
562 let nl = self.loan_path_to_string(&common.unwrap());
564 let moved_lp_msg = format!(" (through moving `{}`)",
565 self.loan_path_to_string(moved_lp));
566 (nl, ol, moved_lp_msg)
568 (self.loan_path_to_string(lp),
569 self.loan_path_to_string(moved_lp),
573 let partial = moved_lp.depth() > lp.depth();
574 let msg = if !has_fork && partial { "partially " }
575 else if has_fork && !has_common { "collaterally "}
577 let err = struct_span_err!(
578 self.tcx.sess, use_span, E0382,
579 "{} of {}moved value: `{}`",
581 (ol, moved_lp_msg, err)}
584 // Get type of value and span where it was previously
586 let (move_span, move_note) = match the_move.kind {
587 move_data::Declared => {
591 move_data::MoveExpr |
592 move_data::MovePat =>
593 (self.tcx.hir.span(the_move.id), ""),
595 move_data::Captured =>
596 (match self.tcx.hir.expect_expr(the_move.id).node {
597 hir::ExprClosure(.., fn_decl_span) => fn_decl_span,
598 ref r => bug!("Captured({}) maps to non-closure: {:?}",
600 }, " (into closure)"),
603 // Annotate the use and the move in the span. Watch out for
604 // the case where the use and the move are the same. This
605 // means the use is in a loop.
606 err = if use_span == move_span {
609 &format!("value moved{} here in previous iteration of loop",
613 err.span_label(use_span, &format!("value {} here after move", verb_participle))
614 .span_label(move_span, &format!("value moved{} here", move_note));
618 err.note(&format!("move occurs because `{}` has type `{}`, \
619 which does not implement the `Copy` trait",
620 self.loan_path_to_string(moved_lp),
623 // Note: we used to suggest adding a `ref binding` or calling
624 // `clone` but those suggestions have been removed because
625 // they are often not what you actually want to do, and were
626 // not considered particularly helpful.
631 pub fn report_partial_reinitialization_of_uninitialized_structure(
634 lp: &LoanPath<'tcx>) {
636 self.tcx.sess, span, E0383,
637 "partial reinitialization of uninitialized structure `{}`",
638 self.loan_path_to_string(lp));
641 pub fn report_reassigned_immutable_variable(&self,
645 &move_data::Assignment) {
646 let mut err = struct_span_err!(
647 self.tcx.sess, span, E0384,
648 "re-assignment of immutable variable `{}`",
649 self.loan_path_to_string(lp));
650 err.span_label(span, &format!("re-assignment of immutable variable"));
651 if span != assign.span {
652 err.span_label(assign.span, &format!("first assignment to `{}`",
653 self.loan_path_to_string(lp)));
658 pub fn span_err(&self, s: Span, m: &str) {
659 self.tcx.sess.span_err(s, m);
662 pub fn struct_span_err<S: Into<MultiSpan>>(&self, s: S, m: &str)
663 -> DiagnosticBuilder<'a> {
664 self.tcx.sess.struct_span_err(s, m)
667 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(&self,
671 -> DiagnosticBuilder<'a> {
672 self.tcx.sess.struct_span_err_with_code(s, msg, code)
675 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, s: S, msg: &str, code: &str) {
676 self.tcx.sess.span_err_with_code(s, msg, code);
679 fn bckerr_to_diag(&self, err: &BckError<'tcx>) -> DiagnosticBuilder<'a> {
680 let span = err.span.clone();
682 let msg = match err.code {
684 let descr = match err.cmt.note {
685 mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
686 self.cmt_to_string(&err.cmt)
688 _ => match opt_loan_path(&err.cmt) {
691 err.cmt.mutbl.to_user_str(),
692 self.cmt_to_string(&err.cmt))
696 format!("{} {} `{}`",
697 err.cmt.mutbl.to_user_str(),
698 self.cmt_to_string(&err.cmt),
699 self.loan_path_to_string(&lp))
705 MutabilityViolation => {
706 format!("cannot assign to {}", descr)
708 BorrowViolation(euv::ClosureCapture(_)) => {
709 format!("closure cannot assign to {}", descr)
711 BorrowViolation(euv::OverloadedOperator) |
712 BorrowViolation(euv::AddrOf) |
713 BorrowViolation(euv::RefBinding) |
714 BorrowViolation(euv::AutoRef) |
715 BorrowViolation(euv::AutoUnsafe) |
716 BorrowViolation(euv::ForLoop) |
717 BorrowViolation(euv::MatchDiscriminant) => {
718 format!("cannot borrow {} as mutable", descr)
720 BorrowViolation(euv::ClosureInvocation) => {
722 "err_mutbl with a closure invocation");
726 err_out_of_scope(..) => {
727 let msg = match opt_loan_path(&err.cmt) {
728 None => "borrowed value".to_string(),
730 format!("`{}`", self.loan_path_to_string(&lp))
733 format!("{} does not live long enough", msg)
735 err_borrowed_pointer_too_short(..) => {
736 let descr = self.cmt_to_path_or_string(&err.cmt);
737 format!("lifetime of {} is too short to guarantee \
738 its contents can be safely reborrowed",
743 self.struct_span_err(span, &msg)
746 pub fn report_aliasability_violation(&self,
748 kind: AliasableViolationKind,
749 cause: mc::AliasableReason,
750 cmt: mc::cmt<'tcx>) {
751 let mut is_closure = false;
752 let prefix = match kind {
753 MutabilityViolation => {
754 "cannot assign to data"
756 BorrowViolation(euv::ClosureCapture(_)) |
757 BorrowViolation(euv::OverloadedOperator) |
758 BorrowViolation(euv::AddrOf) |
759 BorrowViolation(euv::AutoRef) |
760 BorrowViolation(euv::AutoUnsafe) |
761 BorrowViolation(euv::RefBinding) |
762 BorrowViolation(euv::MatchDiscriminant) => {
763 "cannot borrow data mutably"
766 BorrowViolation(euv::ClosureInvocation) => {
771 BorrowViolation(euv::ForLoop) => {
777 mc::AliasableStatic |
778 mc::AliasableStaticMut => {
779 // This path cannot occur. It happens when we have an
780 // `&mut` or assignment to a static. But in the case
781 // of `static X`, we get a mutability violation first,
782 // and never get here. In the case of `static mut X`,
783 // that is unsafe and hence the aliasability error is
785 span_bug!(span, "aliasability violation for static `{}`", prefix)
787 mc::AliasableBorrowed => {}
789 let blame = cmt.immutability_blame();
790 let mut err = match blame {
791 Some(ImmutabilityBlame::ClosureEnv(id)) => {
792 let mut err = struct_span_err!(
793 self.tcx.sess, span, E0387,
794 "{} in a captured outer variable in an `Fn` closure", prefix);
796 // FIXME: the distinction between these 2 messages looks wrong.
797 let help = if let BorrowViolation(euv::ClosureCapture(_)) = kind {
798 // The aliasability violation with closure captures can
799 // happen for nested closures, so we know the enclosing
800 // closure incorrectly accepts an `Fn` while it needs to
802 "consider changing this to accept closures that implement `FnMut`"
805 "consider changing this closure to take self by mutable reference"
807 err.span_help(self.tcx.hir.span(id), help);
811 let mut err = struct_span_err!(
812 self.tcx.sess, span, E0389,
813 "{} in a `&` reference", prefix);
814 err.span_label(span, &"assignment into an immutable reference");
818 self.note_immutability_blame(&mut err, blame);
821 err.help("closures behind references must be called via `&mut`");
826 /// Given a type, if it is an immutable reference, return a suggestion to make it mutable
827 fn suggest_mut_for_immutable(&self, pty: &hir::Ty, is_implicit_self: bool) -> Option<String> {
828 // Check wether the argument is an immutable reference
829 debug!("suggest_mut_for_immutable({:?}, {:?})", pty, is_implicit_self);
830 if let hir::TyRptr(lifetime, hir::MutTy {
831 mutbl: hir::Mutability::MutImmutable,
834 // Account for existing lifetimes when generating the message
835 let pointee_snippet = match self.tcx.sess.codemap().span_to_snippet(ty.span) {
836 Ok(snippet) => snippet,
840 let lifetime_snippet = if !lifetime.is_elided() {
841 format!("{} ", match self.tcx.sess.codemap().span_to_snippet(lifetime.span) {
842 Ok(lifetime_snippet) => lifetime_snippet,
848 Some(format!("use `&{}mut {}` here to make mutable",
850 if is_implicit_self { "self" } else { &*pointee_snippet }))
856 fn local_binding_mode(&self, node_id: ast::NodeId) -> hir::BindingMode {
857 let pat = match self.tcx.hir.get(node_id) {
858 hir_map::Node::NodeLocal(pat) => pat,
859 node => bug!("bad node for local: {:?}", node)
863 hir::PatKind::Binding(mode, ..) => mode,
864 _ => bug!("local is not a binding: {:?}", pat)
868 fn local_ty(&self, node_id: ast::NodeId) -> (Option<&hir::Ty>, bool) {
869 let parent = self.tcx.hir.get_parent_node(node_id);
870 let parent_node = self.tcx.hir.get(parent);
872 // The parent node is like a fn
873 if let Some(fn_like) = FnLikeNode::from_node(parent_node) {
874 // `nid`'s parent's `Body`
875 let fn_body = self.tcx.hir.body(fn_like.body());
876 // Get the position of `node_id` in the arguments list
877 let arg_pos = fn_body.arguments.iter().position(|arg| arg.pat.id == node_id);
878 if let Some(i) = arg_pos {
879 // The argument's `Ty`
880 (Some(&fn_like.decl().inputs[i]),
881 i == 0 && fn_like.decl().has_implicit_self)
890 fn note_immutability_blame(&self,
891 db: &mut DiagnosticBuilder,
892 blame: Option<ImmutabilityBlame>) {
895 Some(ImmutabilityBlame::ClosureEnv(_)) => {}
896 Some(ImmutabilityBlame::ImmLocal(node_id)) => {
897 let let_span = self.tcx.hir.span(node_id);
898 if let hir::BindingMode::BindByValue(..) = self.local_binding_mode(node_id) {
899 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(let_span) {
900 let (_, is_implicit_self) = self.local_ty(node_id);
901 if is_implicit_self && snippet != "self" {
902 // avoid suggesting `mut &self`.
907 &format!("consider changing this to `mut {}`", snippet)
912 Some(ImmutabilityBlame::LocalDeref(node_id)) => {
913 let let_span = self.tcx.hir.span(node_id);
914 match self.local_binding_mode(node_id) {
915 hir::BindingMode::BindByRef(..) => {
916 let snippet = self.tcx.sess.codemap().span_to_snippet(let_span);
917 if let Ok(snippet) = snippet {
920 &format!("consider changing this to `{}`",
921 snippet.replace("ref ", "ref mut "))
925 hir::BindingMode::BindByValue(..) => {
926 if let (Some(local_ty), is_implicit_self) = self.local_ty(node_id) {
928 self.suggest_mut_for_immutable(local_ty, is_implicit_self) {
929 db.span_label(local_ty.span, &msg);
935 Some(ImmutabilityBlame::AdtFieldDeref(_, field)) => {
936 let node_id = match self.tcx.hir.as_local_node_id(field.did) {
937 Some(node_id) => node_id,
941 if let hir_map::Node::NodeField(ref field) = self.tcx.hir.get(node_id) {
942 if let Some(msg) = self.suggest_mut_for_immutable(&field.ty, false) {
943 db.span_label(field.ty.span, &msg);
950 fn report_out_of_scope_escaping_closure_capture(&self,
951 err: &BckError<'tcx>,
954 let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
957 match self.tcx.sess.codemap().span_to_snippet(err.span) {
958 Ok(string) => format!("move {}", string),
959 Err(_) => format!("move |<args>| <body>")
962 struct_span_err!(self.tcx.sess, err.span, E0373,
963 "closure may outlive the current function, \
965 which is owned by the current function",
967 .span_label(capture_span,
968 &format!("{} is borrowed here",
970 .span_label(err.span,
971 &format!("may outlive borrowed value {}",
973 .span_suggestion(err.span,
974 &format!("to force the closure to take ownership of {} \
975 (and any other referenced variables), \
976 use the `move` keyword, as shown:",
982 fn region_end_span(&self, region: ty::Region<'tcx>) -> Option<Span> {
984 ty::ReScope(scope) => {
985 match scope.span(&self.tcx.hir) {
998 fn note_and_explain_bckerr(&self, db: &mut DiagnosticBuilder, err: BckError<'tcx>) {
999 let error_span = err.span.clone();
1002 self.note_and_explain_mutbl_error(db, &err, &error_span);
1003 self.note_immutability_blame(db, err.cmt.immutability_blame());
1005 err_out_of_scope(super_scope, sub_scope, cause) => {
1006 let (value_kind, value_msg) = match err.cmt.cat {
1007 mc::Categorization::Rvalue(..) =>
1008 ("temporary value", "temporary value created here"),
1010 ("borrowed value", "borrow occurs here")
1013 let is_closure = match cause {
1014 euv::ClosureCapture(s) => {
1015 // The primary span starts out as the closure creation point.
1016 // Change the primary span here to highlight the use of the variable
1017 // in the closure, because it seems more natural. Highlight
1018 // closure creation point as a secondary span.
1019 match db.span.primary_span() {
1021 db.span = MultiSpan::from_span(s);
1022 db.span_label(primary, &format!("capture occurs here"));
1023 db.span_label(s, &"does not live long enough");
1030 db.span_label(error_span, &"does not live long enough");
1035 let sub_span = self.region_end_span(sub_scope);
1036 let super_span = self.region_end_span(super_scope);
1038 match (sub_span, super_span) {
1039 (Some(s1), Some(s2)) if s1 == s2 => {
1041 db.span = MultiSpan::from_span(s1);
1042 db.span_label(error_span, &value_msg);
1043 let msg = match opt_loan_path(&err.cmt) {
1044 None => value_kind.to_string(),
1046 format!("`{}`", self.loan_path_to_string(&lp))
1050 &format!("{} dropped here while still borrowed", msg));
1052 db.span_label(s1, &format!("{} dropped before borrower", value_kind));
1054 db.note("values in a scope are dropped in the opposite order \
1057 (Some(s1), Some(s2)) if !is_closure => {
1058 db.span = MultiSpan::from_span(s2);
1059 db.span_label(error_span, &value_msg);
1060 let msg = match opt_loan_path(&err.cmt) {
1061 None => value_kind.to_string(),
1063 format!("`{}`", self.loan_path_to_string(&lp))
1066 db.span_label(s2, &format!("{} dropped here while still borrowed", msg));
1067 db.span_label(s1, &format!("{} needs to live until here", value_kind));
1072 db.span_label(s, &format!("{} needs to live until here",
1076 self.tcx.note_and_explain_region(
1078 "borrowed value must be valid for ",
1085 db.span_label(s, &format!("{} only lives until here", value_kind));
1088 self.tcx.note_and_explain_region(
1090 "...but borrowed value is only valid for ",
1098 if let Some(_) = statement_scope_span(self.tcx, super_scope) {
1099 db.note("consider using a `let` binding to increase its lifetime");
1105 mc::Categorization::Rvalue(r, or) if r != or => {
1107 before rustc 1.16, this temporary lived longer - see issue #39283 \
1108 (https://github.com/rust-lang/rust/issues/39283)");
1114 err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1115 let descr = match opt_loan_path(&err.cmt) {
1117 format!("`{}`", self.loan_path_to_string(&lp))
1119 None => self.cmt_to_string(&err.cmt),
1121 self.tcx.note_and_explain_region(
1123 &format!("{} would have to be valid for ",
1127 self.tcx.note_and_explain_region(
1129 &format!("...but {} is only valid for ", descr),
1136 fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'tcx>,
1137 error_span: &Span) {
1138 match err.cmt.note {
1139 mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1140 // If this is an `Fn` closure, it simply can't mutate upvars.
1141 // If it's an `FnMut` closure, the original variable was declared immutable.
1142 // We need to determine which is the case here.
1143 let kind = match err.cmt.upvar().unwrap().cat {
1144 Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1147 if kind == ty::ClosureKind::Fn {
1148 db.span_help(self.tcx.hir.span(upvar_id.closure_expr_id),
1149 "consider changing this closure to take \
1150 self by mutable reference");
1154 if let Categorization::Deref(..) = err.cmt.cat {
1155 db.span_label(*error_span, &"cannot borrow as mutable");
1156 } else if let Categorization::Local(local_id) = err.cmt.cat {
1157 let span = self.tcx.hir.span(local_id);
1158 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
1159 if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
1160 db.span_label(*error_span, &format!("cannot reborrow mutably"));
1161 db.span_label(*error_span, &format!("try removing `&mut` here"));
1163 db.span_label(*error_span, &format!("cannot borrow mutably"));
1166 db.span_label(*error_span, &format!("cannot borrow mutably"));
1168 } else if let Categorization::Interior(ref cmt, _) = err.cmt.cat {
1169 if let mc::MutabilityCategory::McImmutable = cmt.mutbl {
1170 db.span_label(*error_span,
1171 &"cannot mutably borrow immutable field");
1177 pub fn append_loan_path_to_string(&self,
1178 loan_path: &LoanPath<'tcx>,
1180 match loan_path.kind {
1181 LpUpvar(ty::UpvarId{ var_id: id, closure_expr_id: _ }) |
1183 out.push_str(&self.tcx.local_var_name_str(id));
1186 LpDowncast(ref lp_base, variant_def_id) => {
1188 self.append_loan_path_to_string(&lp_base, out);
1189 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1190 out.push_str(&self.tcx.item_path_str(variant_def_id));
1194 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(fname))) => {
1195 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1197 mc::NamedField(fname) => {
1199 out.push_str(&fname.as_str());
1201 mc::PositionalField(idx) => {
1203 out.push_str(&idx.to_string());
1208 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement(..))) => {
1209 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1210 out.push_str("[..]");
1213 LpExtend(ref lp_base, _, LpDeref(_)) => {
1215 self.append_loan_path_to_string(&lp_base, out);
1220 pub fn append_autoderefd_loan_path_to_string(&self,
1221 loan_path: &LoanPath<'tcx>,
1223 match loan_path.kind {
1224 LpExtend(ref lp_base, _, LpDeref(_)) => {
1225 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1226 // rules would normally allow users to omit the `*x`.
1227 // So just serialize such paths to `x.f` or x[3]` respectively.
1228 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1231 LpDowncast(ref lp_base, variant_def_id) => {
1233 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1235 out.push_str(&self.tcx.item_path_str(variant_def_id));
1239 LpVar(..) | LpUpvar(..) | LpExtend(.., LpInterior(..)) => {
1240 self.append_loan_path_to_string(loan_path, out)
1245 pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1246 let mut result = String::new();
1247 self.append_loan_path_to_string(loan_path, &mut result);
1251 pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1252 cmt.descriptive_string(self.tcx)
1255 pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt<'tcx>) -> String {
1256 match opt_loan_path(cmt) {
1257 Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1258 None => self.cmt_to_string(cmt),
1263 fn statement_scope_span(tcx: TyCtxt, region: ty::Region) -> Option<Span> {
1265 ty::ReScope(scope) => {
1266 match tcx.hir.find(scope.node_id()) {
1267 Some(hir_map::NodeStmt(stmt)) => Some(stmt.span),
1275 impl BitwiseOperator for LoanDataFlowOperator {
1277 fn join(&self, succ: usize, pred: usize) -> usize {
1278 succ | pred // loans from both preds are in scope
1282 impl DataFlowOperator for LoanDataFlowOperator {
1284 fn initial_value(&self) -> bool {
1285 false // no loans in scope by default
1289 impl<'tcx> fmt::Debug for InteriorKind {
1290 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1292 InteriorField(mc::NamedField(fld)) => write!(f, "{}", fld),
1293 InteriorField(mc::PositionalField(i)) => write!(f, "#{}", i),
1294 InteriorElement(..) => write!(f, "[]"),
1299 impl<'tcx> fmt::Debug for Loan<'tcx> {
1300 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1301 write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1307 self.restricted_paths)
1311 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1312 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1315 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_string(id)))
1318 LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => {
1319 let s = ty::tls::with(|tcx| tcx.hir.node_to_string(var_id));
1320 write!(f, "$({} captured by id={})", s, closure_expr_id)
1323 LpDowncast(ref lp, variant_def_id) => {
1324 let variant_str = if variant_def_id.is_local() {
1325 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1327 format!("{:?}", variant_def_id)
1329 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1332 LpExtend(ref lp, _, LpDeref(_)) => {
1333 write!(f, "{:?}.*", lp)
1336 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1337 write!(f, "{:?}.{:?}", lp, interior)
1343 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1344 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1347 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_user_string(id)))
1350 LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => {
1351 let s = ty::tls::with(|tcx| tcx.hir.node_to_user_string(var_id));
1352 write!(f, "$({} captured by closure)", s)
1355 LpDowncast(ref lp, variant_def_id) => {
1356 let variant_str = if variant_def_id.is_local() {
1357 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1359 format!("{:?}", variant_def_id)
1361 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1364 LpExtend(ref lp, _, LpDeref(_)) => {
1365 write!(f, "{}.*", lp)
1368 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1369 write!(f, "{}.{:?}", lp, interior)