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 use self::InteriorKind::*;
23 use rustc::hir::map as hir_map;
24 use rustc::hir::map::blocks::FnLikeNode;
26 use rustc::middle::dataflow::DataFlowContext;
27 use rustc::middle::dataflow::BitwiseOperator;
28 use rustc::middle::dataflow::DataFlowOperator;
29 use rustc::middle::dataflow::KillFrom;
30 use rustc::hir::def_id::{DefId, DefIndex};
31 use rustc::middle::expr_use_visitor as euv;
32 use rustc::middle::mem_categorization as mc;
33 use rustc::middle::mem_categorization::Categorization;
34 use rustc::middle::mem_categorization::ImmutabilityBlame;
35 use rustc::middle::region::{self, RegionMaps};
36 use rustc::middle::free_region::RegionRelations;
37 use rustc::ty::{self, TyCtxt};
38 use rustc::ty::maps::Providers;
39 use rustc::util::nodemap::FxHashMap;
42 use std::hash::{Hash, Hasher};
44 use syntax_pos::{MultiSpan, Span};
45 use errors::DiagnosticBuilder;
48 use rustc::hir::intravisit::{self, Visitor};
56 #[derive(Clone, Copy)]
57 pub struct LoanDataFlowOperator;
59 pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
61 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
62 for body_owner_def_id in tcx.body_owners() {
63 tcx.borrowck(body_owner_def_id);
67 pub fn provide(providers: &mut Providers) {
68 *providers = Providers {
74 /// Collection of conclusions determined via borrow checker analyses.
75 pub struct AnalysisData<'a, 'tcx: 'a> {
76 pub all_loans: Vec<Loan<'tcx>>,
77 pub loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>,
78 pub move_data: move_data::FlowedMoveData<'a, 'tcx>,
81 fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId) {
82 debug!("borrowck(body_owner_def_id={:?})", owner_def_id);
84 let owner_id = tcx.hir.as_local_node_id(owner_def_id).unwrap();
86 match tcx.hir.get(owner_id) {
87 hir_map::NodeStructCtor(_) |
88 hir_map::NodeVariant(_) => {
89 // We get invoked with anything that has MIR, but some of
90 // those things (notably the synthesized constructors from
91 // tuple structs/variants) do not have an associated body
92 // and do not need borrowchecking.
98 let body_id = tcx.hir.body_owned_by(owner_id);
99 let tables = tcx.typeck_tables_of(owner_def_id);
100 let region_maps = tcx.region_maps(owner_def_id);
101 let body = tcx.hir.body(body_id);
102 let bccx = &mut BorrowckCtxt { tcx, tables, region_maps, owner_def_id, body };
104 // Eventually, borrowck will always read the MIR, but at the
105 // moment we do not. So, for now, we always force MIR to be
106 // constructed for a given fn, since this may result in errors
107 // being reported and we want that to happen.
109 // Note that `mir_validated` is a "stealable" result; the
110 // thief, `optimized_mir()`, forces borrowck, so we know that
111 // is not yet stolen.
112 tcx.mir_validated(owner_def_id).borrow();
114 // option dance because you can't capture an uninitialized variable
117 if let Some(AnalysisData { all_loans,
119 move_data: flowed_moves }) =
120 build_borrowck_dataflow_data(bccx, false, body_id,
122 cfg = Some(cfg::CFG::new(bccx.tcx, &body));
123 cfg.as_mut().unwrap()
126 check_loans::check_loans(bccx, &loan_dfcx, &flowed_moves, &all_loans, body);
130 fn build_borrowck_dataflow_data<'a, 'c, 'tcx, F>(this: &mut BorrowckCtxt<'a, 'tcx>,
131 force_analysis: bool,
132 body_id: hir::BodyId,
134 -> Option<AnalysisData<'a, 'tcx>>
135 where F: FnOnce(&mut BorrowckCtxt<'a, 'tcx>) -> &'c cfg::CFG
137 // Check the body of fn items.
140 let mut visitor = intravisit::IdRangeComputingVisitor::new(&tcx.hir);
141 visitor.visit_body(this.body);
144 let (all_loans, move_data) =
145 gather_loans::gather_loans_in_fn(this, body_id);
147 if !force_analysis && move_data.is_empty() && all_loans.is_empty() {
148 // large arrays of data inserted as constants can take a lot of
149 // time and memory to borrow-check - see issue #36799. However,
150 // they don't have lvalues, so no borrow-check is actually needed.
151 // Recognize that case and skip borrow-checking.
152 debug!("skipping loan propagation for {:?} because of no loans", body_id);
155 debug!("propagating loans in {:?}", body_id);
158 let cfg = get_cfg(this);
160 DataFlowContext::new(this.tcx,
164 LoanDataFlowOperator,
167 for (loan_idx, loan) in all_loans.iter().enumerate() {
168 loan_dfcx.add_gen(loan.gen_scope.node_id(), loan_idx);
169 loan_dfcx.add_kill(KillFrom::ScopeEnd,
170 loan.kill_scope.node_id(), loan_idx);
172 loan_dfcx.add_kills_from_flow_exits(cfg);
173 loan_dfcx.propagate(cfg, this.body);
175 let flowed_moves = move_data::FlowedMoveData::new(move_data,
181 Some(AnalysisData { all_loans,
183 move_data:flowed_moves })
186 /// Accessor for introspective clients inspecting `AnalysisData` and
187 /// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer.
188 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
189 tcx: TyCtxt<'a, 'tcx, 'tcx>,
190 body_id: hir::BodyId,
192 -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
194 let owner_id = tcx.hir.body_owner(body_id);
195 let owner_def_id = tcx.hir.local_def_id(owner_id);
196 let tables = tcx.typeck_tables_of(owner_def_id);
197 let region_maps = tcx.region_maps(owner_def_id);
198 let body = tcx.hir.body(body_id);
199 let mut bccx = BorrowckCtxt { tcx, tables, region_maps, owner_def_id, body };
201 let dataflow_data = build_borrowck_dataflow_data(&mut bccx, true, body_id, |_| cfg);
202 (bccx, dataflow_data.unwrap())
205 // ----------------------------------------------------------------------
208 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
209 tcx: TyCtxt<'a, 'tcx, 'tcx>,
211 // tables for the current thing we are checking; set to
212 // Some in `borrowck_fn` and cleared later
213 tables: &'a ty::TypeckTables<'tcx>,
215 region_maps: Rc<RegionMaps>,
219 body: &'tcx hir::Body,
222 ///////////////////////////////////////////////////////////////////////////
223 // Loans and loan paths
225 /// Record of a loan that was issued.
226 pub struct Loan<'tcx> {
228 loan_path: Rc<LoanPath<'tcx>>,
229 kind: ty::BorrowKind,
230 restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
232 /// gen_scope indicates where loan is introduced. Typically the
233 /// loan is introduced at the point of the borrow, but in some
234 /// cases, notably method arguments, the loan may be introduced
235 /// only later, once it comes into scope. See also
236 /// `GatherLoanCtxt::compute_gen_scope`.
237 gen_scope: region::CodeExtent,
239 /// kill_scope indicates when the loan goes out of scope. This is
240 /// either when the lifetime expires or when the local variable
241 /// which roots the loan-path goes out of scope, whichever happens
242 /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
243 kill_scope: region::CodeExtent,
245 cause: euv::LoanCause,
248 impl<'tcx> Loan<'tcx> {
249 pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
250 self.loan_path.clone()
255 pub struct LoanPath<'tcx> {
256 kind: LoanPathKind<'tcx>,
260 impl<'tcx> PartialEq for LoanPath<'tcx> {
261 fn eq(&self, that: &LoanPath<'tcx>) -> bool {
262 self.kind == that.kind
266 impl<'tcx> Hash for LoanPath<'tcx> {
267 fn hash<H: Hasher>(&self, state: &mut H) {
268 self.kind.hash(state);
272 #[derive(PartialEq, Eq, Hash, Debug)]
273 pub enum LoanPathKind<'tcx> {
274 LpVar(ast::NodeId), // `x` in README.md
275 LpUpvar(ty::UpvarId), // `x` captured by-value into closure
276 LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
277 LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem<'tcx>)
280 impl<'tcx> LoanPath<'tcx> {
281 fn new(kind: LoanPathKind<'tcx>, ty: ty::Ty<'tcx>) -> LoanPath<'tcx> {
282 LoanPath { kind: kind, ty: ty }
285 fn to_type(&self) -> ty::Ty<'tcx> { self.ty }
288 // FIXME (pnkfelix): See discussion here
289 // https://github.com/pnkfelix/rust/commit/
290 // b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
291 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
293 // A local, "cleaned" version of `mc::InteriorKind` that drops
294 // information that is not relevant to loan-path analysis. (In
295 // particular, the distinction between how precisely an array-element
296 // is tracked is irrelevant here.)
297 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
298 pub enum InteriorKind {
299 InteriorField(mc::FieldName),
303 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
304 impl ToInteriorKind for mc::InteriorKind {
305 fn cleaned(self) -> InteriorKind {
307 mc::InteriorField(name) => InteriorField(name),
308 mc::InteriorElement(_) => InteriorElement,
314 // - a pointer dereference (`*LV` in README.md)
315 // - a field reference, with an optional definition of the containing
316 // enum variant (`LV.f` in README.md)
317 // `DefId` is present when the field is part of struct that is in
318 // a variant of an enum. For instance in:
319 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
320 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
321 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
322 pub enum LoanPathElem<'tcx> {
323 LpDeref(mc::PointerKind<'tcx>),
324 LpInterior(Option<DefId>, InteriorKind),
327 fn closure_to_block(closure_id: DefIndex,
328 tcx: TyCtxt) -> ast::NodeId {
329 let closure_id = tcx.hir.def_index_to_node_id(closure_id);
330 match tcx.hir.get(closure_id) {
331 hir_map::NodeExpr(expr) => match expr.node {
332 hir::ExprClosure(.., body_id, _, _) => {
336 bug!("encountered non-closure id: {}", closure_id)
339 _ => bug!("encountered non-expr id: {}", closure_id)
343 impl<'a, 'tcx> LoanPath<'tcx> {
344 pub fn kill_scope(&self, bccx: &BorrowckCtxt<'a, 'tcx>) -> region::CodeExtent {
346 LpVar(local_id) => bccx.region_maps.var_scope(local_id),
347 LpUpvar(upvar_id) => {
348 let block_id = closure_to_block(upvar_id.closure_expr_id, bccx.tcx);
349 region::CodeExtent::Misc(block_id)
351 LpDowncast(ref base, _) |
352 LpExtend(ref base, ..) => base.kill_scope(bccx),
356 fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
357 match (&self.kind, &other.kind) {
358 (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
359 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
360 if id == id2 && opt_variant_id == opt_variant_id2 {
361 base.has_fork(&base2)
365 (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
366 (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&base),
371 fn depth(&self) -> usize {
373 LpExtend(ref base, _, LpDeref(_)) => base.depth(),
374 LpExtend(ref base, _, LpInterior(..)) => base.depth() + 1,
379 fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
380 match (&self.kind, &other.kind) {
381 (&LpExtend(ref base, a, LpInterior(opt_variant_id, id)),
382 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) => {
383 if id == id2 && opt_variant_id == opt_variant_id2 {
384 base.common(&base2).map(|x| {
386 if base.depth() == xd && base2.depth() == xd {
388 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
399 (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
400 (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&other),
401 (&LpVar(id), &LpVar(id2)) => {
403 Some(LoanPath { kind: LpVar(id), ty: self.ty })
408 (&LpUpvar(id), &LpUpvar(id2)) => {
410 Some(LoanPath { kind: LpUpvar(id), ty: self.ty })
420 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
421 //! Computes the `LoanPath` (if any) for a `cmt`.
422 //! Note that this logic is somewhat duplicated in
423 //! the method `compute()` found in `gather_loans::restrictions`,
424 //! which allows it to share common loan path pieces as it
425 //! traverses the CMT.
427 let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
430 Categorization::Rvalue(..) |
431 Categorization::StaticItem => {
435 Categorization::Local(id) => {
436 Some(new_lp(LpVar(id)))
439 Categorization::Upvar(mc::Upvar { id, .. }) => {
440 Some(new_lp(LpUpvar(id)))
443 Categorization::Deref(ref cmt_base, pk) => {
444 opt_loan_path(cmt_base).map(|lp| {
445 new_lp(LpExtend(lp, cmt.mutbl, LpDeref(pk)))
449 Categorization::Interior(ref cmt_base, ik) => {
450 opt_loan_path(cmt_base).map(|lp| {
451 let opt_variant_id = match cmt_base.cat {
452 Categorization::Downcast(_, did) => Some(did),
455 new_lp(LpExtend(lp, cmt.mutbl, LpInterior(opt_variant_id, ik.cleaned())))
459 Categorization::Downcast(ref cmt_base, variant_def_id) =>
460 opt_loan_path(cmt_base)
462 new_lp(LpDowncast(lp, variant_def_id))
468 ///////////////////////////////////////////////////////////////////////////
471 // Errors that can occur
472 #[derive(Debug, PartialEq)]
473 pub enum bckerr_code<'tcx> {
475 /// superscope, subscope, loan cause
476 err_out_of_scope(ty::Region<'tcx>, ty::Region<'tcx>, euv::LoanCause),
477 err_borrowed_pointer_too_short(ty::Region<'tcx>, ty::Region<'tcx>), // loan, ptr
480 // Combination of an error code and the categorization of the expression
482 #[derive(Debug, PartialEq)]
483 pub struct BckError<'tcx> {
485 cause: AliasableViolationKind,
487 code: bckerr_code<'tcx>
490 #[derive(Copy, Clone, Debug, PartialEq)]
491 pub enum AliasableViolationKind {
493 BorrowViolation(euv::LoanCause)
496 #[derive(Copy, Clone, Debug)]
497 pub enum MovedValueUseKind {
502 ///////////////////////////////////////////////////////////////////////////
505 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
506 pub fn is_subregion_of(&self,
507 r_sub: ty::Region<'tcx>,
508 r_sup: ty::Region<'tcx>)
511 let region_rels = RegionRelations::new(self.tcx,
514 &self.tables.free_region_map);
515 region_rels.is_subregion_of(r_sub, r_sup)
518 pub fn report(&self, err: BckError<'tcx>) {
519 // Catch and handle some particular cases.
520 match (&err.code, &err.cause) {
521 (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _),
522 &BorrowViolation(euv::ClosureCapture(span))) |
523 (&err_out_of_scope(&ty::ReScope(_), &ty::ReEarlyBound(..), _),
524 &BorrowViolation(euv::ClosureCapture(span))) |
525 (&err_out_of_scope(&ty::ReScope(_), &ty::ReFree(..), _),
526 &BorrowViolation(euv::ClosureCapture(span))) => {
527 return self.report_out_of_scope_escaping_closure_capture(&err, span);
532 self.report_bckerr(&err);
535 pub fn report_use_of_moved_value(&self,
537 use_kind: MovedValueUseKind,
539 the_move: &move_data::Move,
540 moved_lp: &LoanPath<'tcx>,
541 _param_env: ty::ParamEnv<'tcx>) {
542 let (verb, verb_participle) = match use_kind {
543 MovedInUse => ("use", "used"),
544 MovedInCapture => ("capture", "captured"),
547 let (_ol, _moved_lp_msg, mut err, need_note) = match the_move.kind {
548 move_data::Declared => {
549 // If this is an uninitialized variable, just emit a simple warning
552 self.tcx.sess, use_span, E0381,
553 "{} of possibly uninitialized variable: `{}`",
555 self.loan_path_to_string(lp))
556 .span_label(use_span, format!("use of possibly uninitialized `{}`",
557 self.loan_path_to_string(lp)))
562 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
563 // normally generate a rather confusing message:
565 // error: use of moved value: `x.b`
566 // note: `x.a` moved here...
568 // What we want to do instead is get the 'common ancestor' of the two moves and
569 // use that for most of the message instead, giving is something like this:
571 // error: use of moved value: `x`
572 // note: `x` moved here (through moving `x.a`)...
574 let common = moved_lp.common(lp);
575 let has_common = common.is_some();
576 let has_fork = moved_lp.has_fork(lp);
577 let (nl, ol, moved_lp_msg) =
578 if has_fork && has_common {
579 let nl = self.loan_path_to_string(&common.unwrap());
581 let moved_lp_msg = format!(" (through moving `{}`)",
582 self.loan_path_to_string(moved_lp));
583 (nl, ol, moved_lp_msg)
585 (self.loan_path_to_string(lp),
586 self.loan_path_to_string(moved_lp),
590 let partial = moved_lp.depth() > lp.depth();
591 let msg = if !has_fork && partial { "partially " }
592 else if has_fork && !has_common { "collaterally "}
594 let mut err = struct_span_err!(
595 self.tcx.sess, use_span, E0382,
596 "{} of {}moved value: `{}`",
598 let need_note = match lp.ty.sty {
599 ty::TypeVariants::TyClosure(id, _) => {
600 let node_id = self.tcx.hir.as_local_node_id(id).unwrap();
601 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
602 if let Some(&(ty::ClosureKind::FnOnce, Some((span, name)))) =
603 self.tables.closure_kinds().get(hir_id)
605 err.span_note(span, &format!(
606 "closure cannot be invoked more than once because \
607 it moves the variable `{}` out of its environment",
617 (ol, moved_lp_msg, err, need_note)
621 // Get type of value and span where it was previously
623 let (move_span, move_note) = match the_move.kind {
624 move_data::Declared => {
628 move_data::MoveExpr |
629 move_data::MovePat =>
630 (self.tcx.hir.span(the_move.id), ""),
632 move_data::Captured =>
633 (match self.tcx.hir.expect_expr(the_move.id).node {
634 hir::ExprClosure(.., fn_decl_span, _) => fn_decl_span,
635 ref r => bug!("Captured({}) maps to non-closure: {:?}",
637 }, " (into closure)"),
640 // Annotate the use and the move in the span. Watch out for
641 // the case where the use and the move are the same. This
642 // means the use is in a loop.
643 err = if use_span == move_span {
646 format!("value moved{} here in previous iteration of loop",
650 err.span_label(use_span, format!("value {} here after move", verb_participle))
651 .span_label(move_span, format!("value moved{} here", move_note));
656 err.note(&format!("move occurs because `{}` has type `{}`, \
657 which does not implement the `Copy` trait",
658 self.loan_path_to_string(moved_lp),
662 // Note: we used to suggest adding a `ref binding` or calling
663 // `clone` but those suggestions have been removed because
664 // they are often not what you actually want to do, and were
665 // not considered particularly helpful.
670 pub fn report_partial_reinitialization_of_uninitialized_structure(
673 lp: &LoanPath<'tcx>) {
675 self.tcx.sess, span, E0383,
676 "partial reinitialization of uninitialized structure `{}`",
677 self.loan_path_to_string(lp));
680 pub fn report_reassigned_immutable_variable(&self,
684 &move_data::Assignment) {
685 let mut err = struct_span_err!(
686 self.tcx.sess, span, E0384,
687 "re-assignment of immutable variable `{}`",
688 self.loan_path_to_string(lp));
689 err.span_label(span, "re-assignment of immutable variable");
690 if span != assign.span {
691 err.span_label(assign.span, format!("first assignment to `{}`",
692 self.loan_path_to_string(lp)));
697 pub fn span_err(&self, s: Span, m: &str) {
698 self.tcx.sess.span_err(s, m);
701 pub fn struct_span_err<S: Into<MultiSpan>>(&self, s: S, m: &str)
702 -> DiagnosticBuilder<'a> {
703 self.tcx.sess.struct_span_err(s, m)
706 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(&self,
710 -> DiagnosticBuilder<'a> {
711 self.tcx.sess.struct_span_err_with_code(s, msg, code)
714 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, s: S, msg: &str, code: &str) {
715 self.tcx.sess.span_err_with_code(s, msg, code);
718 fn report_bckerr(&self, err: &BckError<'tcx>) {
719 let error_span = err.span.clone();
723 let descr = match err.cmt.note {
724 mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
725 self.cmt_to_string(&err.cmt)
727 _ => match opt_loan_path(&err.cmt) {
730 err.cmt.mutbl.to_user_str(),
731 self.cmt_to_string(&err.cmt))
735 format!("{} {} `{}`",
736 err.cmt.mutbl.to_user_str(),
737 self.cmt_to_string(&err.cmt),
738 self.loan_path_to_string(&lp))
743 let mut db = match err.cause {
744 MutabilityViolation => {
745 struct_span_err!(self.tcx.sess,
748 "cannot assign to {}",
751 BorrowViolation(euv::ClosureCapture(_)) => {
752 struct_span_err!(self.tcx.sess, error_span, E0595,
753 "closure cannot assign to {}", descr)
755 BorrowViolation(euv::OverloadedOperator) |
756 BorrowViolation(euv::AddrOf) |
757 BorrowViolation(euv::RefBinding) |
758 BorrowViolation(euv::AutoRef) |
759 BorrowViolation(euv::AutoUnsafe) |
760 BorrowViolation(euv::ForLoop) |
761 BorrowViolation(euv::MatchDiscriminant) => {
762 struct_span_err!(self.tcx.sess, error_span, E0596,
763 "cannot borrow {} as mutable", descr)
765 BorrowViolation(euv::ClosureInvocation) => {
767 "err_mutbl with a closure invocation");
771 self.note_and_explain_mutbl_error(&mut db, &err, &error_span);
772 self.note_immutability_blame(&mut db, err.cmt.immutability_blame());
775 err_out_of_scope(super_scope, sub_scope, cause) => {
776 let msg = match opt_loan_path(&err.cmt) {
777 None => "borrowed value".to_string(),
779 format!("`{}`", self.loan_path_to_string(&lp))
783 // When you have a borrow that lives across a yield,
784 // that reference winds up captured in the generator
785 // type. Regionck then constraints it to live as long
786 // as the generator itself. If that borrow is borrowing
787 // data owned by the generator, this winds up resulting in
788 // an `err_out_of_scope` error:
793 // let a = &3; // this borrow is forced to ... -+
795 // println!("{}", a); // |
797 // } <----------------------... live until here --------+
800 // To detect this case, we look for cases where the
801 // `super_scope` (lifetime of the value) is within the
802 // body, but the `sub_scope` is not.
803 debug!("err_out_of_scope: self.body.is_generator = {:?}",
804 self.body.is_generator);
805 let maybe_borrow_across_yield = if self.body.is_generator {
806 let body_extent = region::CodeExtent::Misc(self.body.id().node_id);
807 debug!("err_out_of_scope: body_extent = {:?}", body_extent);
808 debug!("err_out_of_scope: super_scope = {:?}", super_scope);
809 debug!("err_out_of_scope: sub_scope = {:?}", sub_scope);
810 match (super_scope, sub_scope) {
811 (&ty::RegionKind::ReScope(value_extent),
812 &ty::RegionKind::ReScope(loan_extent)) => {
814 // value_extent <= body_extent &&
815 self.region_maps.is_subscope_of(value_extent, body_extent) &&
816 // body_extent <= loan_extent
817 self.region_maps.is_subscope_of(body_extent, loan_extent)
819 // We now know that this is a case
820 // that fits the bill described above:
821 // a borrow of something whose scope
822 // is within the generator, but the
823 // borrow is for a scope outside the
826 // Now look within the scope of the of
827 // the value being borrowed (in the
828 // example above, that would be the
829 // block remainder that starts with
830 // `let a`) for a yield. We can cite
831 // that for the user.
832 self.tcx.yield_in_extent(value_extent, &mut FxHashMap())
843 if let Some(yield_span) = maybe_borrow_across_yield {
844 debug!("err_out_of_scope: opt_yield_span = {:?}", yield_span);
845 struct_span_err!(self.tcx.sess,
848 "borrow may still be in use when generator yields")
849 .span_label(yield_span, "possible yield occurs here")
854 let mut db = struct_span_err!(self.tcx.sess,
857 "{} does not live long enough",
860 let (value_kind, value_msg) = match err.cmt.cat {
861 mc::Categorization::Rvalue(..) =>
862 ("temporary value", "temporary value created here"),
864 ("borrowed value", "borrow occurs here")
867 let is_closure = match cause {
868 euv::ClosureCapture(s) => {
869 // The primary span starts out as the closure creation point.
870 // Change the primary span here to highlight the use of the variable
871 // in the closure, because it seems more natural. Highlight
872 // closure creation point as a secondary span.
873 match db.span.primary_span() {
875 db.span = MultiSpan::from_span(s);
876 db.span_label(primary, "capture occurs here");
877 db.span_label(s, "does not live long enough");
884 db.span_label(error_span, "does not live long enough");
889 let sub_span = self.region_end_span(sub_scope);
890 let super_span = self.region_end_span(super_scope);
892 match (sub_span, super_span) {
893 (Some(s1), Some(s2)) if s1 == s2 => {
895 db.span = MultiSpan::from_span(s1);
896 db.span_label(error_span, value_msg);
897 let msg = match opt_loan_path(&err.cmt) {
898 None => value_kind.to_string(),
900 format!("`{}`", self.loan_path_to_string(&lp))
904 format!("{} dropped here while still borrowed", msg));
906 db.span_label(s1, format!("{} dropped before borrower", value_kind));
908 db.note("values in a scope are dropped in the opposite order \
911 (Some(s1), Some(s2)) if !is_closure => {
912 db.span = MultiSpan::from_span(s2);
913 db.span_label(error_span, value_msg);
914 let msg = match opt_loan_path(&err.cmt) {
915 None => value_kind.to_string(),
917 format!("`{}`", self.loan_path_to_string(&lp))
920 db.span_label(s2, format!("{} dropped here while still borrowed", msg));
921 db.span_label(s1, format!("{} needs to live until here", value_kind));
926 db.span_label(s, format!("{} needs to live until here",
930 self.tcx.note_and_explain_region(
932 "borrowed value must be valid for ",
939 db.span_label(s, format!("{} only lives until here", value_kind));
942 self.tcx.note_and_explain_region(
944 "...but borrowed value is only valid for ",
952 if let Some(_) = statement_scope_span(self.tcx, super_scope) {
953 db.note("consider using a `let` binding to increase its lifetime");
958 err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
959 let descr = self.cmt_to_path_or_string(&err.cmt);
960 let mut db = struct_span_err!(self.tcx.sess, error_span, E0598,
961 "lifetime of {} is too short to guarantee \
962 its contents can be safely reborrowed",
965 let descr = match opt_loan_path(&err.cmt) {
967 format!("`{}`", self.loan_path_to_string(&lp))
969 None => self.cmt_to_string(&err.cmt),
971 self.tcx.note_and_explain_region(
973 &format!("{} would have to be valid for ",
977 self.tcx.note_and_explain_region(
979 &format!("...but {} is only valid for ", descr),
988 pub fn report_aliasability_violation(&self,
990 kind: AliasableViolationKind,
991 cause: mc::AliasableReason,
992 cmt: mc::cmt<'tcx>) {
993 let mut is_closure = false;
994 let prefix = match kind {
995 MutabilityViolation => {
996 "cannot assign to data"
998 BorrowViolation(euv::ClosureCapture(_)) |
999 BorrowViolation(euv::OverloadedOperator) |
1000 BorrowViolation(euv::AddrOf) |
1001 BorrowViolation(euv::AutoRef) |
1002 BorrowViolation(euv::AutoUnsafe) |
1003 BorrowViolation(euv::RefBinding) |
1004 BorrowViolation(euv::MatchDiscriminant) => {
1005 "cannot borrow data mutably"
1008 BorrowViolation(euv::ClosureInvocation) => {
1010 "closure invocation"
1013 BorrowViolation(euv::ForLoop) => {
1019 mc::AliasableStatic |
1020 mc::AliasableStaticMut => {
1021 // This path cannot occur. It happens when we have an
1022 // `&mut` or assignment to a static. But in the case
1023 // of `static X`, we get a mutability violation first,
1024 // and never get here. In the case of `static mut X`,
1025 // that is unsafe and hence the aliasability error is
1027 span_bug!(span, "aliasability violation for static `{}`", prefix)
1029 mc::AliasableBorrowed => {}
1031 let blame = cmt.immutability_blame();
1032 let mut err = match blame {
1033 Some(ImmutabilityBlame::ClosureEnv(id)) => {
1034 let mut err = struct_span_err!(
1035 self.tcx.sess, span, E0387,
1036 "{} in a captured outer variable in an `Fn` closure", prefix);
1038 // FIXME: the distinction between these 2 messages looks wrong.
1039 let help = if let BorrowViolation(euv::ClosureCapture(_)) = kind {
1040 // The aliasability violation with closure captures can
1041 // happen for nested closures, so we know the enclosing
1042 // closure incorrectly accepts an `Fn` while it needs to
1044 "consider changing this to accept closures that implement `FnMut`"
1047 "consider changing this closure to take self by mutable reference"
1049 let node_id = self.tcx.hir.def_index_to_node_id(id);
1050 err.span_help(self.tcx.hir.span(node_id), help);
1054 let mut err = struct_span_err!(
1055 self.tcx.sess, span, E0389,
1056 "{} in a `&` reference", prefix);
1057 err.span_label(span, "assignment into an immutable reference");
1061 self.note_immutability_blame(&mut err, blame);
1064 err.help("closures behind references must be called via `&mut`");
1069 /// Given a type, if it is an immutable reference, return a suggestion to make it mutable
1070 fn suggest_mut_for_immutable(&self, pty: &hir::Ty, is_implicit_self: bool) -> Option<String> {
1071 // Check wether the argument is an immutable reference
1072 debug!("suggest_mut_for_immutable({:?}, {:?})", pty, is_implicit_self);
1073 if let hir::TyRptr(lifetime, hir::MutTy {
1074 mutbl: hir::Mutability::MutImmutable,
1077 // Account for existing lifetimes when generating the message
1078 let pointee_snippet = match self.tcx.sess.codemap().span_to_snippet(ty.span) {
1079 Ok(snippet) => snippet,
1083 let lifetime_snippet = if !lifetime.is_elided() {
1084 format!("{} ", match self.tcx.sess.codemap().span_to_snippet(lifetime.span) {
1085 Ok(lifetime_snippet) => lifetime_snippet,
1091 Some(format!("use `&{}mut {}` here to make mutable",
1093 if is_implicit_self { "self" } else { &*pointee_snippet }))
1099 fn local_binding_mode(&self, node_id: ast::NodeId) -> ty::BindingMode {
1100 let pat = match self.tcx.hir.get(node_id) {
1101 hir_map::Node::NodeLocal(pat) => pat,
1102 node => bug!("bad node for local: {:?}", node)
1106 hir::PatKind::Binding(..) => {
1108 .pat_binding_modes()
1110 .expect("missing binding mode")
1112 _ => bug!("local is not a binding: {:?}", pat)
1116 fn local_ty(&self, node_id: ast::NodeId) -> (Option<&hir::Ty>, bool) {
1117 let parent = self.tcx.hir.get_parent_node(node_id);
1118 let parent_node = self.tcx.hir.get(parent);
1120 // The parent node is like a fn
1121 if let Some(fn_like) = FnLikeNode::from_node(parent_node) {
1122 // `nid`'s parent's `Body`
1123 let fn_body = self.tcx.hir.body(fn_like.body());
1124 // Get the position of `node_id` in the arguments list
1125 let arg_pos = fn_body.arguments.iter().position(|arg| arg.pat.id == node_id);
1126 if let Some(i) = arg_pos {
1127 // The argument's `Ty`
1128 (Some(&fn_like.decl().inputs[i]),
1129 i == 0 && fn_like.decl().has_implicit_self)
1138 fn note_immutability_blame(&self,
1139 db: &mut DiagnosticBuilder,
1140 blame: Option<ImmutabilityBlame>) {
1143 Some(ImmutabilityBlame::ClosureEnv(_)) => {}
1144 Some(ImmutabilityBlame::ImmLocal(node_id)) => {
1145 let let_span = self.tcx.hir.span(node_id);
1146 if let ty::BindByValue(..) = self.local_binding_mode(node_id) {
1147 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(let_span) {
1148 let (_, is_implicit_self) = self.local_ty(node_id);
1149 if is_implicit_self && snippet != "self" {
1150 // avoid suggesting `mut &self`.
1155 format!("consider changing this to `mut {}`", snippet)
1160 Some(ImmutabilityBlame::LocalDeref(node_id)) => {
1161 let let_span = self.tcx.hir.span(node_id);
1162 match self.local_binding_mode(node_id) {
1163 ty::BindByReference(..) => {
1164 let snippet = self.tcx.sess.codemap().span_to_snippet(let_span);
1165 if let Ok(snippet) = snippet {
1168 format!("consider changing this to `{}`",
1169 snippet.replace("ref ", "ref mut "))
1173 ty::BindByValue(..) => {
1174 if let (Some(local_ty), is_implicit_self) = self.local_ty(node_id) {
1176 self.suggest_mut_for_immutable(local_ty, is_implicit_self) {
1177 db.span_label(local_ty.span, msg);
1183 Some(ImmutabilityBlame::AdtFieldDeref(_, field)) => {
1184 let node_id = match self.tcx.hir.as_local_node_id(field.did) {
1185 Some(node_id) => node_id,
1189 if let hir_map::Node::NodeField(ref field) = self.tcx.hir.get(node_id) {
1190 if let Some(msg) = self.suggest_mut_for_immutable(&field.ty, false) {
1191 db.span_label(field.ty.span, msg);
1198 fn report_out_of_scope_escaping_closure_capture(&self,
1199 err: &BckError<'tcx>,
1202 let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
1205 match self.tcx.sess.codemap().span_to_snippet(err.span) {
1206 Ok(string) => format!("move {}", string),
1207 Err(_) => format!("move |<args>| <body>")
1210 struct_span_err!(self.tcx.sess, err.span, E0373,
1211 "closure may outlive the current function, \
1212 but it borrows {}, \
1213 which is owned by the current function",
1215 .span_label(capture_span,
1216 format!("{} is borrowed here",
1217 cmt_path_or_string))
1218 .span_label(err.span,
1219 format!("may outlive borrowed value {}",
1220 cmt_path_or_string))
1221 .span_suggestion(err.span,
1222 &format!("to force the closure to take ownership of {} \
1223 (and any other referenced variables), \
1224 use the `move` keyword",
1225 cmt_path_or_string),
1230 fn region_end_span(&self, region: ty::Region<'tcx>) -> Option<Span> {
1232 ty::ReScope(scope) => {
1233 match scope.span(&self.tcx.hir) {
1246 fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'tcx>,
1247 error_span: &Span) {
1248 match err.cmt.note {
1249 mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1250 // If this is an `Fn` closure, it simply can't mutate upvars.
1251 // If it's an `FnMut` closure, the original variable was declared immutable.
1252 // We need to determine which is the case here.
1253 let kind = match err.cmt.upvar().unwrap().cat {
1254 Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1257 if kind == ty::ClosureKind::Fn {
1258 let closure_node_id =
1259 self.tcx.hir.def_index_to_node_id(upvar_id.closure_expr_id);
1260 db.span_help(self.tcx.hir.span(closure_node_id),
1261 "consider changing this closure to take \
1262 self by mutable reference");
1266 if let Categorization::Deref(..) = err.cmt.cat {
1267 db.span_label(*error_span, "cannot borrow as mutable");
1268 } else if let Categorization::Local(local_id) = err.cmt.cat {
1269 let span = self.tcx.hir.span(local_id);
1270 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
1271 if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
1272 db.span_label(*error_span, "cannot reborrow mutably");
1273 db.span_label(*error_span, "try removing `&mut` here");
1275 db.span_label(*error_span, "cannot borrow mutably");
1278 db.span_label(*error_span, "cannot borrow mutably");
1280 } else if let Categorization::Interior(ref cmt, _) = err.cmt.cat {
1281 if let mc::MutabilityCategory::McImmutable = cmt.mutbl {
1282 db.span_label(*error_span,
1283 "cannot mutably borrow immutable field");
1289 pub fn append_loan_path_to_string(&self,
1290 loan_path: &LoanPath<'tcx>,
1292 match loan_path.kind {
1293 LpUpvar(ty::UpvarId { var_id: id, closure_expr_id: _ }) => {
1294 out.push_str(&self.tcx.local_var_name_str_def_index(id));
1297 out.push_str(&self.tcx.local_var_name_str(id));
1300 LpDowncast(ref lp_base, variant_def_id) => {
1302 self.append_loan_path_to_string(&lp_base, out);
1303 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1304 out.push_str(&self.tcx.item_path_str(variant_def_id));
1308 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(fname))) => {
1309 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1311 mc::NamedField(fname) => {
1313 out.push_str(&fname.as_str());
1315 mc::PositionalField(idx) => {
1317 out.push_str(&idx.to_string());
1322 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement)) => {
1323 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1324 out.push_str("[..]");
1327 LpExtend(ref lp_base, _, LpDeref(_)) => {
1329 self.append_loan_path_to_string(&lp_base, out);
1334 pub fn append_autoderefd_loan_path_to_string(&self,
1335 loan_path: &LoanPath<'tcx>,
1337 match loan_path.kind {
1338 LpExtend(ref lp_base, _, LpDeref(_)) => {
1339 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1340 // rules would normally allow users to omit the `*x`.
1341 // So just serialize such paths to `x.f` or x[3]` respectively.
1342 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1345 LpDowncast(ref lp_base, variant_def_id) => {
1347 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1349 out.push_str(&self.tcx.item_path_str(variant_def_id));
1353 LpVar(..) | LpUpvar(..) | LpExtend(.., LpInterior(..)) => {
1354 self.append_loan_path_to_string(loan_path, out)
1359 pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1360 let mut result = String::new();
1361 self.append_loan_path_to_string(loan_path, &mut result);
1365 pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1366 cmt.descriptive_string(self.tcx)
1369 pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt<'tcx>) -> String {
1370 match opt_loan_path(cmt) {
1371 Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1372 None => self.cmt_to_string(cmt),
1377 fn statement_scope_span(tcx: TyCtxt, region: ty::Region) -> Option<Span> {
1379 ty::ReScope(scope) => {
1380 match tcx.hir.find(scope.node_id()) {
1381 Some(hir_map::NodeStmt(stmt)) => Some(stmt.span),
1389 impl BitwiseOperator for LoanDataFlowOperator {
1391 fn join(&self, succ: usize, pred: usize) -> usize {
1392 succ | pred // loans from both preds are in scope
1396 impl DataFlowOperator for LoanDataFlowOperator {
1398 fn initial_value(&self) -> bool {
1399 false // no loans in scope by default
1403 impl<'tcx> fmt::Debug for InteriorKind {
1404 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1406 InteriorField(mc::NamedField(fld)) => write!(f, "{}", fld),
1407 InteriorField(mc::PositionalField(i)) => write!(f, "#{}", i),
1408 InteriorElement => write!(f, "[]"),
1413 impl<'tcx> fmt::Debug for Loan<'tcx> {
1414 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1415 write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1421 self.restricted_paths)
1425 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1426 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1429 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_string(id)))
1432 LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => {
1433 let s = ty::tls::with(|tcx| {
1434 let var_node_id = tcx.hir.def_index_to_node_id(var_id);
1435 tcx.hir.node_to_string(var_node_id)
1437 write!(f, "$({} captured by id={:?})", s, closure_expr_id)
1440 LpDowncast(ref lp, variant_def_id) => {
1441 let variant_str = if variant_def_id.is_local() {
1442 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1444 format!("{:?}", variant_def_id)
1446 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1449 LpExtend(ref lp, _, LpDeref(_)) => {
1450 write!(f, "{:?}.*", lp)
1453 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1454 write!(f, "{:?}.{:?}", lp, interior)
1460 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1461 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1464 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_user_string(id)))
1467 LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => {
1468 let s = ty::tls::with(|tcx| {
1469 let var_node_id = tcx.hir.def_index_to_node_id(var_id);
1470 tcx.hir.node_to_string(var_node_id)
1472 write!(f, "$({} captured by closure)", s)
1475 LpDowncast(ref lp, variant_def_id) => {
1476 let variant_str = if variant_def_id.is_local() {
1477 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1479 format!("{:?}", variant_def_id)
1481 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1484 LpExtend(ref lp, _, LpDeref(_)) => {
1485 write!(f, "{}.*", lp)
1488 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1489 write!(f, "{}.{:?}", lp, interior)