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;
42 use syntax_pos::DUMMY_SP;
46 use std::hash::{Hash, Hasher};
48 use syntax_pos::{MultiSpan, Span};
49 use errors::DiagnosticBuilder;
52 use rustc::hir::intravisit::{self, Visitor};
62 #[derive(Clone, Copy)]
63 pub struct LoanDataFlowOperator;
65 pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
67 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
68 for body_owner_def_id in tcx.body_owners() {
69 tcx.borrowck(body_owner_def_id);
73 pub fn provide(providers: &mut Providers) {
74 *providers = Providers {
80 /// Collection of conclusions determined via borrow checker analyses.
81 pub struct AnalysisData<'a, 'tcx: 'a> {
82 pub all_loans: Vec<Loan<'tcx>>,
83 pub loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>,
84 pub move_data: move_data::FlowedMoveData<'a, 'tcx>,
87 fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId) {
88 debug!("borrowck(body_owner_def_id={:?})", owner_def_id);
90 let owner_id = tcx.hir.as_local_node_id(owner_def_id).unwrap();
92 match tcx.hir.get(owner_id) {
93 hir_map::NodeStructCtor(_) |
94 hir_map::NodeVariant(_) => {
95 // We get invoked with anything that has MIR, but some of
96 // those things (notably the synthesized constructors from
97 // tuple structs/variants) do not have an associated body
98 // and do not need borrowchecking.
104 let body_id = tcx.hir.body_owned_by(owner_id);
105 let attributes = tcx.get_attrs(owner_def_id);
106 let tables = tcx.typeck_tables_of(owner_def_id);
107 let region_maps = tcx.region_maps(owner_def_id);
108 let mut bccx = &mut BorrowckCtxt { tcx, tables, region_maps, owner_def_id };
110 let body = bccx.tcx.hir.body(body_id);
112 if bccx.tcx.has_attr(owner_def_id, "rustc_mir_borrowck") {
113 mir::borrowck_mir(bccx, owner_id, &attributes);
115 // Eventually, borrowck will always read the MIR, but at the
116 // moment we do not. So, for now, we always force MIR to be
117 // constructed for a given fn, since this may result in errors
118 // being reported and we want that to happen.
120 // Note that `mir_validated` is a "stealable" result; the
121 // thief, `optimized_mir()`, forces borrowck, so we know that
122 // is not yet stolen.
123 tcx.mir_validated(owner_def_id).borrow();
126 let cfg = cfg::CFG::new(bccx.tcx, &body);
127 let AnalysisData { all_loans,
129 move_data: flowed_moves } =
130 build_borrowck_dataflow_data(bccx, &cfg, body_id);
132 check_loans::check_loans(bccx, &loan_dfcx, &flowed_moves, &all_loans, body);
135 fn build_borrowck_dataflow_data<'a, 'tcx>(this: &mut BorrowckCtxt<'a, 'tcx>,
137 body_id: hir::BodyId)
138 -> AnalysisData<'a, 'tcx>
140 // Check the body of fn items.
142 let body = tcx.hir.body(body_id);
144 let mut visitor = intravisit::IdRangeComputingVisitor::new(&tcx.hir);
145 visitor.visit_body(body);
148 let (all_loans, move_data) =
149 gather_loans::gather_loans_in_fn(this, body_id);
152 DataFlowContext::new(this.tcx,
156 LoanDataFlowOperator,
159 for (loan_idx, loan) in all_loans.iter().enumerate() {
160 loan_dfcx.add_gen(loan.gen_scope.node_id(), loan_idx);
161 loan_dfcx.add_kill(KillFrom::ScopeEnd,
162 loan.kill_scope.node_id(), loan_idx);
164 loan_dfcx.add_kills_from_flow_exits(cfg);
165 loan_dfcx.propagate(cfg, body);
167 let flowed_moves = move_data::FlowedMoveData::new(move_data,
173 AnalysisData { all_loans: all_loans,
175 move_data:flowed_moves }
178 /// Accessor for introspective clients inspecting `AnalysisData` and
179 /// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer.
180 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
181 tcx: TyCtxt<'a, 'tcx, 'tcx>,
182 body_id: hir::BodyId,
184 -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
186 let owner_id = tcx.hir.body_owner(body_id);
187 let owner_def_id = tcx.hir.local_def_id(owner_id);
188 let tables = tcx.typeck_tables_of(owner_def_id);
189 let region_maps = tcx.region_maps(owner_def_id);
190 let mut bccx = BorrowckCtxt { tcx, tables, region_maps, owner_def_id };
192 let dataflow_data = build_borrowck_dataflow_data(&mut bccx, cfg, body_id);
193 (bccx, dataflow_data)
196 // ----------------------------------------------------------------------
199 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
200 tcx: TyCtxt<'a, 'tcx, 'tcx>,
202 // tables for the current thing we are checking; set to
203 // Some in `borrowck_fn` and cleared later
204 tables: &'a ty::TypeckTables<'tcx>,
206 region_maps: Rc<RegionMaps>,
211 ///////////////////////////////////////////////////////////////////////////
212 // Loans and loan paths
214 /// Record of a loan that was issued.
215 pub struct Loan<'tcx> {
217 loan_path: Rc<LoanPath<'tcx>>,
218 kind: ty::BorrowKind,
219 restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
221 /// gen_scope indicates where loan is introduced. Typically the
222 /// loan is introduced at the point of the borrow, but in some
223 /// cases, notably method arguments, the loan may be introduced
224 /// only later, once it comes into scope. See also
225 /// `GatherLoanCtxt::compute_gen_scope`.
226 gen_scope: region::CodeExtent,
228 /// kill_scope indicates when the loan goes out of scope. This is
229 /// either when the lifetime expires or when the local variable
230 /// which roots the loan-path goes out of scope, whichever happens
231 /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
232 kill_scope: region::CodeExtent,
234 cause: euv::LoanCause,
237 impl<'tcx> Loan<'tcx> {
238 pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
239 self.loan_path.clone()
244 pub struct LoanPath<'tcx> {
245 kind: LoanPathKind<'tcx>,
249 impl<'tcx> PartialEq for LoanPath<'tcx> {
250 fn eq(&self, that: &LoanPath<'tcx>) -> bool {
251 self.kind == that.kind
255 impl<'tcx> Hash for LoanPath<'tcx> {
256 fn hash<H: Hasher>(&self, state: &mut H) {
257 self.kind.hash(state);
261 #[derive(PartialEq, Eq, Hash, Debug)]
262 pub enum LoanPathKind<'tcx> {
263 LpVar(ast::NodeId), // `x` in README.md
264 LpUpvar(ty::UpvarId), // `x` captured by-value into closure
265 LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
266 LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem<'tcx>)
269 impl<'tcx> LoanPath<'tcx> {
270 fn new(kind: LoanPathKind<'tcx>, ty: ty::Ty<'tcx>) -> LoanPath<'tcx> {
271 LoanPath { kind: kind, ty: ty }
274 fn to_type(&self) -> ty::Ty<'tcx> { self.ty }
277 // FIXME (pnkfelix): See discussion here
278 // https://github.com/pnkfelix/rust/commit/
279 // b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
280 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
282 // A local, "cleaned" version of `mc::InteriorKind` that drops
283 // information that is not relevant to loan-path analysis. (In
284 // particular, the distinction between how precisely an array-element
285 // is tracked is irrelevant here.)
286 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
287 pub enum InteriorKind {
288 InteriorField(mc::FieldName),
289 InteriorElement(mc::ElementKind),
292 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
293 impl ToInteriorKind for mc::InteriorKind {
294 fn cleaned(self) -> InteriorKind {
296 mc::InteriorField(name) => InteriorField(name),
297 mc::InteriorElement(_, elem_kind) => InteriorElement(elem_kind),
303 // - a pointer dereference (`*LV` in README.md)
304 // - a field reference, with an optional definition of the containing
305 // enum variant (`LV.f` in README.md)
306 // `DefId` is present when the field is part of struct that is in
307 // a variant of an enum. For instance in:
308 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
309 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
310 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
311 pub enum LoanPathElem<'tcx> {
312 LpDeref(mc::PointerKind<'tcx>),
313 LpInterior(Option<DefId>, InteriorKind),
316 pub fn closure_to_block(closure_id: ast::NodeId,
317 tcx: TyCtxt) -> ast::NodeId {
318 match tcx.hir.get(closure_id) {
319 hir_map::NodeExpr(expr) => match expr.node {
320 hir::ExprClosure(.., body_id, _) => {
324 bug!("encountered non-closure id: {}", closure_id)
327 _ => bug!("encountered non-expr id: {}", closure_id)
331 impl<'a, 'tcx> LoanPath<'tcx> {
332 pub fn kill_scope(&self, bccx: &BorrowckCtxt<'a, 'tcx>) -> region::CodeExtent {
334 LpVar(local_id) => bccx.region_maps.var_scope(local_id),
335 LpUpvar(upvar_id) => {
336 let block_id = closure_to_block(upvar_id.closure_expr_id, bccx.tcx);
337 region::CodeExtent::Misc(block_id)
339 LpDowncast(ref base, _) |
340 LpExtend(ref base, ..) => base.kill_scope(bccx),
344 fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
345 match (&self.kind, &other.kind) {
346 (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
347 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
348 if id == id2 && opt_variant_id == opt_variant_id2 {
349 base.has_fork(&base2)
353 (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
354 (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&base),
359 fn depth(&self) -> usize {
361 LpExtend(ref base, _, LpDeref(_)) => base.depth(),
362 LpExtend(ref base, _, LpInterior(..)) => base.depth() + 1,
367 fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
368 match (&self.kind, &other.kind) {
369 (&LpExtend(ref base, a, LpInterior(opt_variant_id, id)),
370 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) => {
371 if id == id2 && opt_variant_id == opt_variant_id2 {
372 base.common(&base2).map(|x| {
374 if base.depth() == xd && base2.depth() == xd {
376 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
387 (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
388 (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&other),
389 (&LpVar(id), &LpVar(id2)) => {
391 Some(LoanPath { kind: LpVar(id), ty: self.ty })
396 (&LpUpvar(id), &LpUpvar(id2)) => {
398 Some(LoanPath { kind: LpUpvar(id), ty: self.ty })
408 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
409 //! Computes the `LoanPath` (if any) for a `cmt`.
410 //! Note that this logic is somewhat duplicated in
411 //! the method `compute()` found in `gather_loans::restrictions`,
412 //! which allows it to share common loan path pieces as it
413 //! traverses the CMT.
415 let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
418 Categorization::Rvalue(..) |
419 Categorization::StaticItem => {
423 Categorization::Local(id) => {
424 Some(new_lp(LpVar(id)))
427 Categorization::Upvar(mc::Upvar { id, .. }) => {
428 Some(new_lp(LpUpvar(id)))
431 Categorization::Deref(ref cmt_base, _, pk) => {
432 opt_loan_path(cmt_base).map(|lp| {
433 new_lp(LpExtend(lp, cmt.mutbl, LpDeref(pk)))
437 Categorization::Interior(ref cmt_base, ik) => {
438 opt_loan_path(cmt_base).map(|lp| {
439 let opt_variant_id = match cmt_base.cat {
440 Categorization::Downcast(_, did) => Some(did),
443 new_lp(LpExtend(lp, cmt.mutbl, LpInterior(opt_variant_id, ik.cleaned())))
447 Categorization::Downcast(ref cmt_base, variant_def_id) =>
448 opt_loan_path(cmt_base)
450 new_lp(LpDowncast(lp, variant_def_id))
456 ///////////////////////////////////////////////////////////////////////////
459 // Errors that can occur
460 #[derive(Debug, PartialEq)]
461 pub enum bckerr_code<'tcx> {
463 /// superscope, subscope, loan cause
464 err_out_of_scope(ty::Region<'tcx>, ty::Region<'tcx>, euv::LoanCause),
465 err_borrowed_pointer_too_short(ty::Region<'tcx>, ty::Region<'tcx>), // loan, ptr
468 // Combination of an error code and the categorization of the expression
470 #[derive(Debug, PartialEq)]
471 pub struct BckError<'tcx> {
473 cause: AliasableViolationKind,
475 code: bckerr_code<'tcx>
478 #[derive(Copy, Clone, Debug, PartialEq)]
479 pub enum AliasableViolationKind {
481 BorrowViolation(euv::LoanCause)
484 #[derive(Copy, Clone, Debug)]
485 pub enum MovedValueUseKind {
490 ///////////////////////////////////////////////////////////////////////////
493 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
494 pub fn is_subregion_of(&self,
495 r_sub: ty::Region<'tcx>,
496 r_sup: ty::Region<'tcx>)
499 let region_rels = RegionRelations::new(self.tcx,
502 &self.tables.free_region_map);
503 region_rels.is_subregion_of(r_sub, r_sup)
506 pub fn report(&self, err: BckError<'tcx>) {
507 // Catch and handle some particular cases.
508 match (&err.code, &err.cause) {
509 (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _),
510 &BorrowViolation(euv::ClosureCapture(span))) |
511 (&err_out_of_scope(&ty::ReScope(_), &ty::ReEarlyBound(..), _),
512 &BorrowViolation(euv::ClosureCapture(span))) |
513 (&err_out_of_scope(&ty::ReScope(_), &ty::ReFree(..), _),
514 &BorrowViolation(euv::ClosureCapture(span))) => {
515 return self.report_out_of_scope_escaping_closure_capture(&err, span);
520 let mut db = self.bckerr_to_diag(&err);
521 self.note_and_explain_bckerr(&mut db, err);
525 pub fn report_use_of_moved_value(&self,
527 use_kind: MovedValueUseKind,
529 the_move: &move_data::Move,
530 moved_lp: &LoanPath<'tcx>,
531 _param_env: &ty::ParamEnv<'tcx>) {
532 let (verb, verb_participle) = match use_kind {
533 MovedInUse => ("use", "used"),
534 MovedInCapture => ("capture", "captured"),
537 let (_ol, _moved_lp_msg, mut err, need_note) = match the_move.kind {
538 move_data::Declared => {
539 // If this is an uninitialized variable, just emit a simple warning
542 self.tcx.sess, use_span, E0381,
543 "{} of possibly uninitialized variable: `{}`",
545 self.loan_path_to_string(lp))
546 .span_label(use_span, format!("use of possibly uninitialized `{}`",
547 self.loan_path_to_string(lp)))
552 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
553 // normally generate a rather confusing message:
555 // error: use of moved value: `x.b`
556 // note: `x.a` moved here...
558 // What we want to do instead is get the 'common ancestor' of the two moves and
559 // use that for most of the message instead, giving is something like this:
561 // error: use of moved value: `x`
562 // note: `x` moved here (through moving `x.a`)...
564 let common = moved_lp.common(lp);
565 let has_common = common.is_some();
566 let has_fork = moved_lp.has_fork(lp);
567 let (nl, ol, moved_lp_msg) =
568 if has_fork && has_common {
569 let nl = self.loan_path_to_string(&common.unwrap());
571 let moved_lp_msg = format!(" (through moving `{}`)",
572 self.loan_path_to_string(moved_lp));
573 (nl, ol, moved_lp_msg)
575 (self.loan_path_to_string(lp),
576 self.loan_path_to_string(moved_lp),
580 let partial = moved_lp.depth() > lp.depth();
581 let msg = if !has_fork && partial { "partially " }
582 else if has_fork && !has_common { "collaterally "}
584 let mut err = struct_span_err!(
585 self.tcx.sess, use_span, E0382,
586 "{} of {}moved value: `{}`",
588 let need_note = match lp.ty.sty {
589 ty::TypeVariants::TyClosure(id, _) => {
590 if let Ok(ty::ClosureKind::FnOnce) =
591 ty::queries::closure_kind::try_get(self.tcx, DUMMY_SP, id) {
592 err.help("closure was moved because it only implements `FnOnce`");
600 (ol, moved_lp_msg, err, need_note)
604 // Get type of value and span where it was previously
606 let (move_span, move_note) = match the_move.kind {
607 move_data::Declared => {
611 move_data::MoveExpr |
612 move_data::MovePat =>
613 (self.tcx.hir.span(the_move.id), ""),
615 move_data::Captured =>
616 (match self.tcx.hir.expect_expr(the_move.id).node {
617 hir::ExprClosure(.., fn_decl_span) => fn_decl_span,
618 ref r => bug!("Captured({}) maps to non-closure: {:?}",
620 }, " (into closure)"),
623 // Annotate the use and the move in the span. Watch out for
624 // the case where the use and the move are the same. This
625 // means the use is in a loop.
626 err = if use_span == move_span {
629 format!("value moved{} here in previous iteration of loop",
633 err.span_label(use_span, format!("value {} here after move", verb_participle))
634 .span_label(move_span, format!("value moved{} here", move_note));
639 err.note(&format!("move occurs because `{}` has type `{}`, \
640 which does not implement the `Copy` trait",
641 self.loan_path_to_string(moved_lp),
645 // Note: we used to suggest adding a `ref binding` or calling
646 // `clone` but those suggestions have been removed because
647 // they are often not what you actually want to do, and were
648 // not considered particularly helpful.
653 pub fn report_partial_reinitialization_of_uninitialized_structure(
656 lp: &LoanPath<'tcx>) {
658 self.tcx.sess, span, E0383,
659 "partial reinitialization of uninitialized structure `{}`",
660 self.loan_path_to_string(lp));
663 pub fn report_reassigned_immutable_variable(&self,
667 &move_data::Assignment) {
668 let mut err = struct_span_err!(
669 self.tcx.sess, span, E0384,
670 "re-assignment of immutable variable `{}`",
671 self.loan_path_to_string(lp));
672 err.span_label(span, "re-assignment of immutable variable");
673 if span != assign.span {
674 err.span_label(assign.span, format!("first assignment to `{}`",
675 self.loan_path_to_string(lp)));
680 pub fn span_err(&self, s: Span, m: &str) {
681 self.tcx.sess.span_err(s, m);
684 pub fn struct_span_err<S: Into<MultiSpan>>(&self, s: S, m: &str)
685 -> DiagnosticBuilder<'a> {
686 self.tcx.sess.struct_span_err(s, m)
689 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(&self,
693 -> DiagnosticBuilder<'a> {
694 self.tcx.sess.struct_span_err_with_code(s, msg, code)
697 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, s: S, msg: &str, code: &str) {
698 self.tcx.sess.span_err_with_code(s, msg, code);
701 fn bckerr_to_diag(&self, err: &BckError<'tcx>) -> DiagnosticBuilder<'a> {
702 let span = err.span.clone();
706 let descr = match err.cmt.note {
707 mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
708 self.cmt_to_string(&err.cmt)
710 _ => match opt_loan_path(&err.cmt) {
713 err.cmt.mutbl.to_user_str(),
714 self.cmt_to_string(&err.cmt))
718 format!("{} {} `{}`",
719 err.cmt.mutbl.to_user_str(),
720 self.cmt_to_string(&err.cmt),
721 self.loan_path_to_string(&lp))
727 MutabilityViolation => {
728 struct_span_err!(self.tcx.sess, span, E0594, "cannot assign to {}", descr)
730 BorrowViolation(euv::ClosureCapture(_)) => {
731 struct_span_err!(self.tcx.sess, span, E0595,
732 "closure cannot assign to {}", descr)
734 BorrowViolation(euv::OverloadedOperator) |
735 BorrowViolation(euv::AddrOf) |
736 BorrowViolation(euv::RefBinding) |
737 BorrowViolation(euv::AutoRef) |
738 BorrowViolation(euv::AutoUnsafe) |
739 BorrowViolation(euv::ForLoop) |
740 BorrowViolation(euv::MatchDiscriminant) => {
741 struct_span_err!(self.tcx.sess, span, E0596,
742 "cannot borrow {} as mutable", descr)
744 BorrowViolation(euv::ClosureInvocation) => {
746 "err_mutbl with a closure invocation");
750 err_out_of_scope(..) => {
751 let msg = match opt_loan_path(&err.cmt) {
752 None => "borrowed value".to_string(),
754 format!("`{}`", self.loan_path_to_string(&lp))
757 struct_span_err!(self.tcx.sess, span, E0597, "{} does not live long enough", msg)
759 err_borrowed_pointer_too_short(..) => {
760 let descr = self.cmt_to_path_or_string(&err.cmt);
761 struct_span_err!(self.tcx.sess, span, E0598,
762 "lifetime of {} is too short to guarantee \
763 its contents can be safely reborrowed",
769 pub fn report_aliasability_violation(&self,
771 kind: AliasableViolationKind,
772 cause: mc::AliasableReason,
773 cmt: mc::cmt<'tcx>) {
774 let mut is_closure = false;
775 let prefix = match kind {
776 MutabilityViolation => {
777 "cannot assign to data"
779 BorrowViolation(euv::ClosureCapture(_)) |
780 BorrowViolation(euv::OverloadedOperator) |
781 BorrowViolation(euv::AddrOf) |
782 BorrowViolation(euv::AutoRef) |
783 BorrowViolation(euv::AutoUnsafe) |
784 BorrowViolation(euv::RefBinding) |
785 BorrowViolation(euv::MatchDiscriminant) => {
786 "cannot borrow data mutably"
789 BorrowViolation(euv::ClosureInvocation) => {
794 BorrowViolation(euv::ForLoop) => {
800 mc::AliasableStatic |
801 mc::AliasableStaticMut => {
802 // This path cannot occur. It happens when we have an
803 // `&mut` or assignment to a static. But in the case
804 // of `static X`, we get a mutability violation first,
805 // and never get here. In the case of `static mut X`,
806 // that is unsafe and hence the aliasability error is
808 span_bug!(span, "aliasability violation for static `{}`", prefix)
810 mc::AliasableBorrowed => {}
812 let blame = cmt.immutability_blame();
813 let mut err = match blame {
814 Some(ImmutabilityBlame::ClosureEnv(id)) => {
815 let mut err = struct_span_err!(
816 self.tcx.sess, span, E0387,
817 "{} in a captured outer variable in an `Fn` closure", prefix);
819 // FIXME: the distinction between these 2 messages looks wrong.
820 let help = if let BorrowViolation(euv::ClosureCapture(_)) = kind {
821 // The aliasability violation with closure captures can
822 // happen for nested closures, so we know the enclosing
823 // closure incorrectly accepts an `Fn` while it needs to
825 "consider changing this to accept closures that implement `FnMut`"
828 "consider changing this closure to take self by mutable reference"
830 err.span_help(self.tcx.hir.span(id), help);
834 let mut err = struct_span_err!(
835 self.tcx.sess, span, E0389,
836 "{} in a `&` reference", prefix);
837 err.span_label(span, "assignment into an immutable reference");
841 self.note_immutability_blame(&mut err, blame);
844 err.help("closures behind references must be called via `&mut`");
849 /// Given a type, if it is an immutable reference, return a suggestion to make it mutable
850 fn suggest_mut_for_immutable(&self, pty: &hir::Ty, is_implicit_self: bool) -> Option<String> {
851 // Check wether the argument is an immutable reference
852 debug!("suggest_mut_for_immutable({:?}, {:?})", pty, is_implicit_self);
853 if let hir::TyRptr(lifetime, hir::MutTy {
854 mutbl: hir::Mutability::MutImmutable,
857 // Account for existing lifetimes when generating the message
858 let pointee_snippet = match self.tcx.sess.codemap().span_to_snippet(ty.span) {
859 Ok(snippet) => snippet,
863 let lifetime_snippet = if !lifetime.is_elided() {
864 format!("{} ", match self.tcx.sess.codemap().span_to_snippet(lifetime.span) {
865 Ok(lifetime_snippet) => lifetime_snippet,
871 Some(format!("use `&{}mut {}` here to make mutable",
873 if is_implicit_self { "self" } else { &*pointee_snippet }))
879 fn local_binding_mode(&self, node_id: ast::NodeId) -> hir::BindingMode {
880 let pat = match self.tcx.hir.get(node_id) {
881 hir_map::Node::NodeLocal(pat) => pat,
882 node => bug!("bad node for local: {:?}", node)
886 hir::PatKind::Binding(mode, ..) => mode,
887 _ => bug!("local is not a binding: {:?}", pat)
891 fn local_ty(&self, node_id: ast::NodeId) -> (Option<&hir::Ty>, bool) {
892 let parent = self.tcx.hir.get_parent_node(node_id);
893 let parent_node = self.tcx.hir.get(parent);
895 // The parent node is like a fn
896 if let Some(fn_like) = FnLikeNode::from_node(parent_node) {
897 // `nid`'s parent's `Body`
898 let fn_body = self.tcx.hir.body(fn_like.body());
899 // Get the position of `node_id` in the arguments list
900 let arg_pos = fn_body.arguments.iter().position(|arg| arg.pat.id == node_id);
901 if let Some(i) = arg_pos {
902 // The argument's `Ty`
903 (Some(&fn_like.decl().inputs[i]),
904 i == 0 && fn_like.decl().has_implicit_self)
913 fn note_immutability_blame(&self,
914 db: &mut DiagnosticBuilder,
915 blame: Option<ImmutabilityBlame>) {
918 Some(ImmutabilityBlame::ClosureEnv(_)) => {}
919 Some(ImmutabilityBlame::ImmLocal(node_id)) => {
920 let let_span = self.tcx.hir.span(node_id);
921 if let hir::BindingMode::BindByValue(..) = self.local_binding_mode(node_id) {
922 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(let_span) {
923 let (_, is_implicit_self) = self.local_ty(node_id);
924 if is_implicit_self && snippet != "self" {
925 // avoid suggesting `mut &self`.
930 format!("consider changing this to `mut {}`", snippet)
935 Some(ImmutabilityBlame::LocalDeref(node_id)) => {
936 let let_span = self.tcx.hir.span(node_id);
937 match self.local_binding_mode(node_id) {
938 hir::BindingMode::BindByRef(..) => {
939 let snippet = self.tcx.sess.codemap().span_to_snippet(let_span);
940 if let Ok(snippet) = snippet {
943 format!("consider changing this to `{}`",
944 snippet.replace("ref ", "ref mut "))
948 hir::BindingMode::BindByValue(..) => {
949 if let (Some(local_ty), is_implicit_self) = self.local_ty(node_id) {
951 self.suggest_mut_for_immutable(local_ty, is_implicit_self) {
952 db.span_label(local_ty.span, msg);
958 Some(ImmutabilityBlame::AdtFieldDeref(_, field)) => {
959 let node_id = match self.tcx.hir.as_local_node_id(field.did) {
960 Some(node_id) => node_id,
964 if let hir_map::Node::NodeField(ref field) = self.tcx.hir.get(node_id) {
965 if let Some(msg) = self.suggest_mut_for_immutable(&field.ty, false) {
966 db.span_label(field.ty.span, msg);
973 fn report_out_of_scope_escaping_closure_capture(&self,
974 err: &BckError<'tcx>,
977 let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
980 match self.tcx.sess.codemap().span_to_snippet(err.span) {
981 Ok(string) => format!("move {}", string),
982 Err(_) => format!("move |<args>| <body>")
985 struct_span_err!(self.tcx.sess, err.span, E0373,
986 "closure may outlive the current function, \
988 which is owned by the current function",
990 .span_label(capture_span,
991 format!("{} is borrowed here",
993 .span_label(err.span,
994 format!("may outlive borrowed value {}",
996 .span_suggestion(err.span,
997 &format!("to force the closure to take ownership of {} \
998 (and any other referenced variables), \
999 use the `move` keyword, as shown:",
1000 cmt_path_or_string),
1005 fn region_end_span(&self, region: ty::Region<'tcx>) -> Option<Span> {
1007 ty::ReScope(scope) => {
1008 match scope.span(&self.tcx.hir) {
1021 fn note_and_explain_bckerr(&self, db: &mut DiagnosticBuilder, err: BckError<'tcx>) {
1022 let error_span = err.span.clone();
1025 self.note_and_explain_mutbl_error(db, &err, &error_span);
1026 self.note_immutability_blame(db, err.cmt.immutability_blame());
1028 err_out_of_scope(super_scope, sub_scope, cause) => {
1029 let (value_kind, value_msg) = match err.cmt.cat {
1030 mc::Categorization::Rvalue(..) =>
1031 ("temporary value", "temporary value created here"),
1033 ("borrowed value", "borrow occurs here")
1036 let is_closure = match cause {
1037 euv::ClosureCapture(s) => {
1038 // The primary span starts out as the closure creation point.
1039 // Change the primary span here to highlight the use of the variable
1040 // in the closure, because it seems more natural. Highlight
1041 // closure creation point as a secondary span.
1042 match db.span.primary_span() {
1044 db.span = MultiSpan::from_span(s);
1045 db.span_label(primary, "capture occurs here");
1046 db.span_label(s, "does not live long enough");
1053 db.span_label(error_span, "does not live long enough");
1058 let sub_span = self.region_end_span(sub_scope);
1059 let super_span = self.region_end_span(super_scope);
1061 match (sub_span, super_span) {
1062 (Some(s1), Some(s2)) if s1 == s2 => {
1064 db.span = MultiSpan::from_span(s1);
1065 db.span_label(error_span, value_msg);
1066 let msg = match opt_loan_path(&err.cmt) {
1067 None => value_kind.to_string(),
1069 format!("`{}`", self.loan_path_to_string(&lp))
1073 format!("{} dropped here while still borrowed", msg));
1075 db.span_label(s1, format!("{} dropped before borrower", value_kind));
1077 db.note("values in a scope are dropped in the opposite order \
1080 (Some(s1), Some(s2)) if !is_closure => {
1081 db.span = MultiSpan::from_span(s2);
1082 db.span_label(error_span, value_msg);
1083 let msg = match opt_loan_path(&err.cmt) {
1084 None => value_kind.to_string(),
1086 format!("`{}`", self.loan_path_to_string(&lp))
1089 db.span_label(s2, format!("{} dropped here while still borrowed", msg));
1090 db.span_label(s1, format!("{} needs to live until here", value_kind));
1095 db.span_label(s, format!("{} needs to live until here",
1099 self.tcx.note_and_explain_region(
1101 "borrowed value must be valid for ",
1108 db.span_label(s, format!("{} only lives until here", value_kind));
1111 self.tcx.note_and_explain_region(
1113 "...but borrowed value is only valid for ",
1121 if let Some(_) = statement_scope_span(self.tcx, super_scope) {
1122 db.note("consider using a `let` binding to increase its lifetime");
1128 mc::Categorization::Rvalue(r, or) if r != or => {
1130 before rustc 1.16, this temporary lived longer - see issue #39283 \
1131 (https://github.com/rust-lang/rust/issues/39283)");
1137 err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1138 let descr = match opt_loan_path(&err.cmt) {
1140 format!("`{}`", self.loan_path_to_string(&lp))
1142 None => self.cmt_to_string(&err.cmt),
1144 self.tcx.note_and_explain_region(
1146 &format!("{} would have to be valid for ",
1150 self.tcx.note_and_explain_region(
1152 &format!("...but {} is only valid for ", descr),
1159 fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'tcx>,
1160 error_span: &Span) {
1161 match err.cmt.note {
1162 mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1163 // If this is an `Fn` closure, it simply can't mutate upvars.
1164 // If it's an `FnMut` closure, the original variable was declared immutable.
1165 // We need to determine which is the case here.
1166 let kind = match err.cmt.upvar().unwrap().cat {
1167 Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1170 if kind == ty::ClosureKind::Fn {
1171 db.span_help(self.tcx.hir.span(upvar_id.closure_expr_id),
1172 "consider changing this closure to take \
1173 self by mutable reference");
1177 if let Categorization::Deref(..) = err.cmt.cat {
1178 db.span_label(*error_span, "cannot borrow as mutable");
1179 } else if let Categorization::Local(local_id) = err.cmt.cat {
1180 let span = self.tcx.hir.span(local_id);
1181 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
1182 if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
1183 db.span_label(*error_span, "cannot reborrow mutably");
1184 db.span_label(*error_span, "try removing `&mut` here");
1186 db.span_label(*error_span, "cannot borrow mutably");
1189 db.span_label(*error_span, "cannot borrow mutably");
1191 } else if let Categorization::Interior(ref cmt, _) = err.cmt.cat {
1192 if let mc::MutabilityCategory::McImmutable = cmt.mutbl {
1193 db.span_label(*error_span,
1194 "cannot mutably borrow immutable field");
1200 pub fn append_loan_path_to_string(&self,
1201 loan_path: &LoanPath<'tcx>,
1203 match loan_path.kind {
1204 LpUpvar(ty::UpvarId{ var_id: id, closure_expr_id: _ }) |
1206 out.push_str(&self.tcx.local_var_name_str(id));
1209 LpDowncast(ref lp_base, variant_def_id) => {
1211 self.append_loan_path_to_string(&lp_base, out);
1212 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1213 out.push_str(&self.tcx.item_path_str(variant_def_id));
1217 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(fname))) => {
1218 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1220 mc::NamedField(fname) => {
1222 out.push_str(&fname.as_str());
1224 mc::PositionalField(idx) => {
1226 out.push_str(&idx.to_string());
1231 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement(..))) => {
1232 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1233 out.push_str("[..]");
1236 LpExtend(ref lp_base, _, LpDeref(_)) => {
1238 self.append_loan_path_to_string(&lp_base, out);
1243 pub fn append_autoderefd_loan_path_to_string(&self,
1244 loan_path: &LoanPath<'tcx>,
1246 match loan_path.kind {
1247 LpExtend(ref lp_base, _, LpDeref(_)) => {
1248 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1249 // rules would normally allow users to omit the `*x`.
1250 // So just serialize such paths to `x.f` or x[3]` respectively.
1251 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1254 LpDowncast(ref lp_base, variant_def_id) => {
1256 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1258 out.push_str(&self.tcx.item_path_str(variant_def_id));
1262 LpVar(..) | LpUpvar(..) | LpExtend(.., LpInterior(..)) => {
1263 self.append_loan_path_to_string(loan_path, out)
1268 pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1269 let mut result = String::new();
1270 self.append_loan_path_to_string(loan_path, &mut result);
1274 pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1275 cmt.descriptive_string(self.tcx)
1278 pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt<'tcx>) -> String {
1279 match opt_loan_path(cmt) {
1280 Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1281 None => self.cmt_to_string(cmt),
1286 fn statement_scope_span(tcx: TyCtxt, region: ty::Region) -> Option<Span> {
1288 ty::ReScope(scope) => {
1289 match tcx.hir.find(scope.node_id()) {
1290 Some(hir_map::NodeStmt(stmt)) => Some(stmt.span),
1298 impl BitwiseOperator for LoanDataFlowOperator {
1300 fn join(&self, succ: usize, pred: usize) -> usize {
1301 succ | pred // loans from both preds are in scope
1305 impl DataFlowOperator for LoanDataFlowOperator {
1307 fn initial_value(&self) -> bool {
1308 false // no loans in scope by default
1312 impl<'tcx> fmt::Debug for InteriorKind {
1313 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1315 InteriorField(mc::NamedField(fld)) => write!(f, "{}", fld),
1316 InteriorField(mc::PositionalField(i)) => write!(f, "#{}", i),
1317 InteriorElement(..) => write!(f, "[]"),
1322 impl<'tcx> fmt::Debug for Loan<'tcx> {
1323 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1324 write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1330 self.restricted_paths)
1334 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1335 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1338 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_string(id)))
1341 LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => {
1342 let s = ty::tls::with(|tcx| tcx.hir.node_to_string(var_id));
1343 write!(f, "$({} captured by id={})", s, closure_expr_id)
1346 LpDowncast(ref lp, variant_def_id) => {
1347 let variant_str = if variant_def_id.is_local() {
1348 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1350 format!("{:?}", variant_def_id)
1352 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1355 LpExtend(ref lp, _, LpDeref(_)) => {
1356 write!(f, "{:?}.*", lp)
1359 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1360 write!(f, "{:?}.{:?}", lp, interior)
1366 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1367 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1370 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_user_string(id)))
1373 LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => {
1374 let s = ty::tls::with(|tcx| tcx.hir.node_to_user_string(var_id));
1375 write!(f, "$({} captured by closure)", s)
1378 LpDowncast(ref lp, variant_def_id) => {
1379 let variant_str = if variant_def_id.is_local() {
1380 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1382 format!("{:?}", variant_def_id)
1384 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1387 LpExtend(ref lp, _, LpDeref(_)) => {
1388 write!(f, "{}.*", lp)
1391 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1392 write!(f, "{}.{:?}", lp, interior)