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::dep_graph::DepNode;
26 use rustc::hir::map as hir_map;
27 use rustc::hir::map::blocks::FnLikeNode;
29 use rustc::middle::dataflow::DataFlowContext;
30 use rustc::middle::dataflow::BitwiseOperator;
31 use rustc::middle::dataflow::DataFlowOperator;
32 use rustc::middle::dataflow::KillFrom;
33 use rustc::hir::def_id::DefId;
34 use rustc::middle::expr_use_visitor as euv;
35 use rustc::middle::free_region::FreeRegionMap;
36 use rustc::middle::mem_categorization as mc;
37 use rustc::middle::mem_categorization::Categorization;
38 use rustc::middle::region;
39 use rustc::ty::{self, TyCtxt};
44 use std::hash::{Hash, Hasher};
46 use syntax_pos::{MultiSpan, Span};
47 use errors::DiagnosticBuilder;
50 use rustc::hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap};
60 #[derive(Clone, Copy)]
61 pub struct LoanDataFlowOperator;
63 pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
65 impl<'a, 'tcx> Visitor<'tcx> for BorrowckCtxt<'a, 'tcx> {
66 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
67 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
70 fn visit_fn(&mut self, fk: FnKind<'tcx>, fd: &'tcx hir::FnDecl,
71 b: hir::BodyId, s: Span, id: ast::NodeId) {
74 FnKind::Method(..) => {
75 self.with_temp_region_map(id, |this| {
76 borrowck_fn(this, fk, fd, b, s, id, fk.attrs())
80 FnKind::Closure(..) => {
81 borrowck_fn(self, fk, fd, b, s, id, fk.attrs());
86 fn visit_item(&mut self, item: &'tcx hir::Item) {
87 borrowck_item(self, item);
90 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
91 if let hir::TraitItemKind::Const(_, Some(expr)) = ti.node {
92 gather_loans::gather_loans_in_static_initializer(self, expr);
94 intravisit::walk_trait_item(self, ti);
97 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
98 if let hir::ImplItemKind::Const(_, expr) = ii.node {
99 gather_loans::gather_loans_in_static_initializer(self, expr);
101 intravisit::walk_impl_item(self, ii);
105 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
106 let mut bccx = BorrowckCtxt {
108 free_region_map: FreeRegionMap::new(),
110 loaned_paths_same: 0,
117 tcx.visit_all_item_likes_in_krate(DepNode::BorrowCheck, &mut bccx.as_deep_visitor());
119 if tcx.sess.borrowck_stats() {
120 println!("--- borrowck stats ---");
121 println!("paths requiring guarantees: {}",
122 bccx.stats.guaranteed_paths);
123 println!("paths requiring loans : {}",
124 make_stat(&bccx, bccx.stats.loaned_paths_same));
125 println!("paths requiring imm loans : {}",
126 make_stat(&bccx, bccx.stats.loaned_paths_imm));
127 println!("stable paths : {}",
128 make_stat(&bccx, bccx.stats.stable_paths));
131 fn make_stat(bccx: &BorrowckCtxt, stat: usize) -> String {
132 let total = bccx.stats.guaranteed_paths as f64;
133 let perc = if total == 0.0 { 0.0 } else { stat as f64 * 100.0 / total };
134 format!("{} ({:.0}%)", stat, perc)
138 fn borrowck_item<'a, 'tcx>(this: &mut BorrowckCtxt<'a, 'tcx>, item: &'tcx hir::Item) {
139 // Gather loans for items. Note that we don't need
140 // to check loans for single expressions. The check
141 // loan step is intended for things that have a data
142 // flow dependent conditions.
144 hir::ItemStatic(.., ex) |
145 hir::ItemConst(_, ex) => {
146 gather_loans::gather_loans_in_static_initializer(this, ex);
151 intravisit::walk_item(this, item);
154 /// Collection of conclusions determined via borrow checker analyses.
155 pub struct AnalysisData<'a, 'tcx: 'a> {
156 pub all_loans: Vec<Loan<'tcx>>,
157 pub loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>,
158 pub move_data: move_data::FlowedMoveData<'a, 'tcx>,
161 fn borrowck_fn<'a, 'tcx>(this: &mut BorrowckCtxt<'a, 'tcx>,
163 decl: &'tcx hir::FnDecl,
164 body_id: hir::BodyId,
167 attributes: &[ast::Attribute]) {
168 debug!("borrowck_fn(id={})", id);
170 let body = this.tcx.hir.body(body_id);
172 if attributes.iter().any(|item| item.check_name("rustc_mir_borrowck")) {
173 this.with_temp_region_map(id, |this| {
174 mir::borrowck_mir(this, id, attributes)
178 let cfg = cfg::CFG::new(this.tcx, &body.value);
179 let AnalysisData { all_loans,
181 move_data: flowed_moves } =
182 build_borrowck_dataflow_data(this, &cfg, body_id);
184 move_data::fragments::instrument_move_fragments(&flowed_moves.move_data,
188 move_data::fragments::build_unfragmented_map(this,
189 &flowed_moves.move_data,
192 check_loans::check_loans(this, &loan_dfcx, &flowed_moves, &all_loans[..], body);
194 intravisit::walk_fn(this, fk, decl, body_id, sp, id);
197 fn build_borrowck_dataflow_data<'a, 'tcx>(this: &mut BorrowckCtxt<'a, 'tcx>,
199 body_id: hir::BodyId)
200 -> AnalysisData<'a, 'tcx>
202 // Check the body of fn items.
204 let body = tcx.hir.body(body_id);
206 let mut visitor = intravisit::IdRangeComputingVisitor::new(&tcx.hir);
207 visitor.visit_body(body);
210 let (all_loans, move_data) =
211 gather_loans::gather_loans_in_fn(this, body_id);
214 DataFlowContext::new(this.tcx,
218 LoanDataFlowOperator,
221 for (loan_idx, loan) in all_loans.iter().enumerate() {
222 loan_dfcx.add_gen(loan.gen_scope.node_id(&tcx.region_maps), loan_idx);
223 loan_dfcx.add_kill(KillFrom::ScopeEnd,
224 loan.kill_scope.node_id(&tcx.region_maps), loan_idx);
226 loan_dfcx.add_kills_from_flow_exits(cfg);
227 loan_dfcx.propagate(cfg, body);
229 let flowed_moves = move_data::FlowedMoveData::new(move_data,
235 AnalysisData { all_loans: all_loans,
237 move_data:flowed_moves }
240 /// Accessor for introspective clients inspecting `AnalysisData` and
241 /// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer.
242 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
243 tcx: TyCtxt<'a, 'tcx, 'tcx>,
246 -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
249 let mut bccx = BorrowckCtxt {
251 free_region_map: FreeRegionMap::new(),
253 loaned_paths_same: 0,
260 let dataflow_data = build_borrowck_dataflow_data(&mut bccx, cfg, body);
261 (bccx, dataflow_data)
264 // ----------------------------------------------------------------------
267 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
268 tcx: TyCtxt<'a, 'tcx, 'tcx>,
270 // Hacky. As we visit various fns, we have to load up the
271 // free-region map for each one. This map is computed by during
272 // typeck for each fn item and stored -- closures just use the map
273 // from the fn item that encloses them. Since we walk the fns in
274 // order, we basically just overwrite this field as we enter a fn
275 // item and restore it afterwards in a stack-like fashion. Then
276 // the borrow checking code can assume that `free_region_map` is
277 // always the correct map for the current fn. Feels like it'd be
278 // better to just recompute this, rather than store it, but it's a
279 // bit of a pain to factor that code out at the moment.
280 free_region_map: FreeRegionMap,
288 loaned_paths_same: usize,
289 loaned_paths_imm: usize,
291 guaranteed_paths: usize
294 ///////////////////////////////////////////////////////////////////////////
295 // Loans and loan paths
297 /// Record of a loan that was issued.
298 pub struct Loan<'tcx> {
300 loan_path: Rc<LoanPath<'tcx>>,
301 kind: ty::BorrowKind,
302 restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
304 /// gen_scope indicates where loan is introduced. Typically the
305 /// loan is introduced at the point of the borrow, but in some
306 /// cases, notably method arguments, the loan may be introduced
307 /// only later, once it comes into scope. See also
308 /// `GatherLoanCtxt::compute_gen_scope`.
309 gen_scope: region::CodeExtent,
311 /// kill_scope indicates when the loan goes out of scope. This is
312 /// either when the lifetime expires or when the local variable
313 /// which roots the loan-path goes out of scope, whichever happens
314 /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
315 kill_scope: region::CodeExtent,
317 cause: euv::LoanCause,
320 impl<'tcx> Loan<'tcx> {
321 pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
322 self.loan_path.clone()
327 pub struct LoanPath<'tcx> {
328 kind: LoanPathKind<'tcx>,
332 impl<'tcx> PartialEq for LoanPath<'tcx> {
333 fn eq(&self, that: &LoanPath<'tcx>) -> bool {
334 self.kind == that.kind
338 impl<'tcx> Hash for LoanPath<'tcx> {
339 fn hash<H: Hasher>(&self, state: &mut H) {
340 self.kind.hash(state);
344 #[derive(PartialEq, Eq, Hash, Debug)]
345 pub enum LoanPathKind<'tcx> {
346 LpVar(ast::NodeId), // `x` in README.md
347 LpUpvar(ty::UpvarId), // `x` captured by-value into closure
348 LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
349 LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem<'tcx>)
352 impl<'tcx> LoanPath<'tcx> {
353 fn new(kind: LoanPathKind<'tcx>, ty: ty::Ty<'tcx>) -> LoanPath<'tcx> {
354 LoanPath { kind: kind, ty: ty }
357 fn to_type(&self) -> ty::Ty<'tcx> { self.ty }
360 // FIXME (pnkfelix): See discussion here
361 // https://github.com/pnkfelix/rust/commit/
362 // b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
363 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
365 // A local, "cleaned" version of `mc::InteriorKind` that drops
366 // information that is not relevant to loan-path analysis. (In
367 // particular, the distinction between how precisely an array-element
368 // is tracked is irrelevant here.)
369 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
370 pub enum InteriorKind {
371 InteriorField(mc::FieldName),
372 InteriorElement(mc::ElementKind),
375 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
376 impl ToInteriorKind for mc::InteriorKind {
377 fn cleaned(self) -> InteriorKind {
379 mc::InteriorField(name) => InteriorField(name),
380 mc::InteriorElement(_, elem_kind) => InteriorElement(elem_kind),
386 // - a pointer dereference (`*LV` in README.md)
387 // - a field reference, with an optional definition of the containing
388 // enum variant (`LV.f` in README.md)
389 // `DefId` is present when the field is part of struct that is in
390 // a variant of an enum. For instance in:
391 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
392 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
393 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
394 pub enum LoanPathElem<'tcx> {
395 LpDeref(mc::PointerKind<'tcx>),
396 LpInterior(Option<DefId>, InteriorKind),
399 pub fn closure_to_block(closure_id: ast::NodeId,
400 tcx: TyCtxt) -> ast::NodeId {
401 match tcx.hir.get(closure_id) {
402 hir_map::NodeExpr(expr) => match expr.node {
403 hir::ExprClosure(.., body_id, _) => {
407 bug!("encountered non-closure id: {}", closure_id)
410 _ => bug!("encountered non-expr id: {}", closure_id)
414 impl<'a, 'tcx> LoanPath<'tcx> {
415 pub fn kill_scope(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> region::CodeExtent {
417 LpVar(local_id) => tcx.region_maps.var_scope(local_id),
418 LpUpvar(upvar_id) => {
419 let block_id = closure_to_block(upvar_id.closure_expr_id, tcx);
420 tcx.region_maps.node_extent(block_id)
422 LpDowncast(ref base, _) |
423 LpExtend(ref base, ..) => base.kill_scope(tcx),
427 fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
428 match (&self.kind, &other.kind) {
429 (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
430 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
431 if id == id2 && opt_variant_id == opt_variant_id2 {
432 base.has_fork(&base2)
436 (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
437 (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&base),
442 fn depth(&self) -> usize {
444 LpExtend(ref base, _, LpDeref(_)) => base.depth(),
445 LpExtend(ref base, _, LpInterior(..)) => base.depth() + 1,
450 fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
451 match (&self.kind, &other.kind) {
452 (&LpExtend(ref base, a, LpInterior(opt_variant_id, id)),
453 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) => {
454 if id == id2 && opt_variant_id == opt_variant_id2 {
455 base.common(&base2).map(|x| {
457 if base.depth() == xd && base2.depth() == xd {
459 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
470 (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
471 (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&other),
472 (&LpVar(id), &LpVar(id2)) => {
474 Some(LoanPath { kind: LpVar(id), ty: self.ty })
479 (&LpUpvar(id), &LpUpvar(id2)) => {
481 Some(LoanPath { kind: LpUpvar(id), ty: self.ty })
491 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
492 //! Computes the `LoanPath` (if any) for a `cmt`.
493 //! Note that this logic is somewhat duplicated in
494 //! the method `compute()` found in `gather_loans::restrictions`,
495 //! which allows it to share common loan path pieces as it
496 //! traverses the CMT.
498 let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
501 Categorization::Rvalue(..) |
502 Categorization::StaticItem => {
506 Categorization::Local(id) => {
507 Some(new_lp(LpVar(id)))
510 Categorization::Upvar(mc::Upvar { id, .. }) => {
511 Some(new_lp(LpUpvar(id)))
514 Categorization::Deref(ref cmt_base, _, pk) => {
515 opt_loan_path(cmt_base).map(|lp| {
516 new_lp(LpExtend(lp, cmt.mutbl, LpDeref(pk)))
520 Categorization::Interior(ref cmt_base, ik) => {
521 opt_loan_path(cmt_base).map(|lp| {
522 let opt_variant_id = match cmt_base.cat {
523 Categorization::Downcast(_, did) => Some(did),
526 new_lp(LpExtend(lp, cmt.mutbl, LpInterior(opt_variant_id, ik.cleaned())))
530 Categorization::Downcast(ref cmt_base, variant_def_id) =>
531 opt_loan_path(cmt_base)
533 new_lp(LpDowncast(lp, variant_def_id))
539 ///////////////////////////////////////////////////////////////////////////
542 // Errors that can occur
544 pub enum bckerr_code<'tcx> {
546 /// superscope, subscope, loan cause
547 err_out_of_scope(&'tcx ty::Region, &'tcx ty::Region, euv::LoanCause),
548 err_borrowed_pointer_too_short(&'tcx ty::Region, &'tcx ty::Region), // loan, ptr
551 // Combination of an error code and the categorization of the expression
554 pub struct BckError<'tcx> {
556 cause: AliasableViolationKind,
558 code: bckerr_code<'tcx>
561 #[derive(Copy, Clone, Debug, PartialEq)]
562 pub enum AliasableViolationKind {
564 BorrowViolation(euv::LoanCause)
567 #[derive(Copy, Clone, Debug)]
568 pub enum MovedValueUseKind {
573 ///////////////////////////////////////////////////////////////////////////
576 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
577 fn with_temp_region_map<F>(&mut self, id: ast::NodeId, f: F)
578 where F: for <'b> FnOnce(&'b mut BorrowckCtxt<'a, 'tcx>)
580 let new_free_region_map = self.tcx.free_region_map(id);
581 let old_free_region_map = mem::replace(&mut self.free_region_map, new_free_region_map);
583 self.free_region_map = old_free_region_map;
586 pub fn is_subregion_of(&self, r_sub: &'tcx ty::Region, r_sup: &'tcx ty::Region)
589 self.free_region_map.is_subregion_of(self.tcx, r_sub, r_sup)
592 pub fn report(&self, err: BckError<'tcx>) {
593 // Catch and handle some particular cases.
594 match (&err.code, &err.cause) {
595 (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _),
596 &BorrowViolation(euv::ClosureCapture(span))) |
597 (&err_out_of_scope(&ty::ReScope(_), &ty::ReFree(..), _),
598 &BorrowViolation(euv::ClosureCapture(span))) => {
599 return self.report_out_of_scope_escaping_closure_capture(&err, span);
605 let span = err.span.clone();
606 let mut db = self.struct_span_err(
608 &self.bckerr_to_string(&err));
609 self.note_and_explain_bckerr(&mut db, err, span);
613 pub fn report_use_of_moved_value(&self,
615 use_kind: MovedValueUseKind,
617 the_move: &move_data::Move,
618 moved_lp: &LoanPath<'tcx>,
619 _param_env: &ty::ParameterEnvironment<'tcx>) {
620 let (verb, verb_participle) = match use_kind {
621 MovedInUse => ("use", "used"),
622 MovedInCapture => ("capture", "captured"),
625 let (_ol, _moved_lp_msg, mut err) = match the_move.kind {
626 move_data::Declared => {
627 // If this is an uninitialized variable, just emit a simple warning
630 self.tcx.sess, use_span, E0381,
631 "{} of possibly uninitialized variable: `{}`",
633 self.loan_path_to_string(lp))
634 .span_label(use_span, &format!("use of possibly uninitialized `{}`",
635 self.loan_path_to_string(lp)))
640 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
641 // normally generate a rather confusing message:
643 // error: use of moved value: `x.b`
644 // note: `x.a` moved here...
646 // What we want to do instead is get the 'common ancestor' of the two moves and
647 // use that for most of the message instead, giving is something like this:
649 // error: use of moved value: `x`
650 // note: `x` moved here (through moving `x.a`)...
652 let common = moved_lp.common(lp);
653 let has_common = common.is_some();
654 let has_fork = moved_lp.has_fork(lp);
655 let (nl, ol, moved_lp_msg) =
656 if has_fork && has_common {
657 let nl = self.loan_path_to_string(&common.unwrap());
659 let moved_lp_msg = format!(" (through moving `{}`)",
660 self.loan_path_to_string(moved_lp));
661 (nl, ol, moved_lp_msg)
663 (self.loan_path_to_string(lp),
664 self.loan_path_to_string(moved_lp),
668 let partial = moved_lp.depth() > lp.depth();
669 let msg = if !has_fork && partial { "partially " }
670 else if has_fork && !has_common { "collaterally "}
672 let err = struct_span_err!(
673 self.tcx.sess, use_span, E0382,
674 "{} of {}moved value: `{}`",
676 (ol, moved_lp_msg, err)}
679 // Get type of value and span where it was previously
681 let (move_span, move_note) = match the_move.kind {
682 move_data::Declared => {
686 move_data::MoveExpr |
687 move_data::MovePat =>
688 (self.tcx.hir.span(the_move.id), ""),
690 move_data::Captured =>
691 (match self.tcx.hir.expect_expr(the_move.id).node {
692 hir::ExprClosure(.., fn_decl_span) => fn_decl_span,
693 ref r => bug!("Captured({}) maps to non-closure: {:?}",
695 }, " (into closure)"),
698 // Annotate the use and the move in the span. Watch out for
699 // the case where the use and the move are the same. This
700 // means the use is in a loop.
701 err = if use_span == move_span {
704 &format!("value moved{} here in previous iteration of loop",
708 err.span_label(use_span, &format!("value {} here after move", verb_participle))
709 .span_label(move_span, &format!("value moved{} here", move_note));
713 err.note(&format!("move occurs because `{}` has type `{}`, \
714 which does not implement the `Copy` trait",
715 self.loan_path_to_string(moved_lp),
718 // Note: we used to suggest adding a `ref binding` or calling
719 // `clone` but those suggestions have been removed because
720 // they are often not what you actually want to do, and were
721 // not considered particularly helpful.
726 pub fn report_partial_reinitialization_of_uninitialized_structure(
729 lp: &LoanPath<'tcx>) {
731 self.tcx.sess, span, E0383,
732 "partial reinitialization of uninitialized structure `{}`",
733 self.loan_path_to_string(lp));
736 pub fn report_reassigned_immutable_variable(&self,
740 &move_data::Assignment) {
741 let mut err = struct_span_err!(
742 self.tcx.sess, span, E0384,
743 "re-assignment of immutable variable `{}`",
744 self.loan_path_to_string(lp));
745 err.span_label(span, &format!("re-assignment of immutable variable"));
746 if span != assign.span {
747 err.span_label(assign.span, &format!("first assignment to `{}`",
748 self.loan_path_to_string(lp)));
753 pub fn span_err(&self, s: Span, m: &str) {
754 self.tcx.sess.span_err(s, m);
757 pub fn struct_span_err<S: Into<MultiSpan>>(&self, s: S, m: &str)
758 -> DiagnosticBuilder<'a> {
759 self.tcx.sess.struct_span_err(s, m)
762 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(&self,
766 -> DiagnosticBuilder<'a> {
767 self.tcx.sess.struct_span_err_with_code(s, msg, code)
770 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, s: S, msg: &str, code: &str) {
771 self.tcx.sess.span_err_with_code(s, msg, code);
774 pub fn bckerr_to_string(&self, err: &BckError<'tcx>) -> String {
777 let descr = match err.cmt.note {
778 mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
779 self.cmt_to_string(&err.cmt)
781 _ => match opt_loan_path(&err.cmt) {
784 err.cmt.mutbl.to_user_str(),
785 self.cmt_to_string(&err.cmt))
788 format!("{} {} `{}`",
789 err.cmt.mutbl.to_user_str(),
790 self.cmt_to_string(&err.cmt),
791 self.loan_path_to_string(&lp))
797 MutabilityViolation => {
798 format!("cannot assign to {}", descr)
800 BorrowViolation(euv::ClosureCapture(_)) => {
801 format!("closure cannot assign to {}", descr)
803 BorrowViolation(euv::OverloadedOperator) |
804 BorrowViolation(euv::AddrOf) |
805 BorrowViolation(euv::RefBinding) |
806 BorrowViolation(euv::AutoRef) |
807 BorrowViolation(euv::AutoUnsafe) |
808 BorrowViolation(euv::ForLoop) |
809 BorrowViolation(euv::MatchDiscriminant) => {
810 format!("cannot borrow {} as mutable", descr)
812 BorrowViolation(euv::ClosureInvocation) => {
814 "err_mutbl with a closure invocation");
818 err_out_of_scope(..) => {
819 let msg = match opt_loan_path(&err.cmt) {
820 None => "borrowed value".to_string(),
822 format!("`{}`", self.loan_path_to_string(&lp))
825 format!("{} does not live long enough", msg)
827 err_borrowed_pointer_too_short(..) => {
828 let descr = self.cmt_to_path_or_string(&err.cmt);
829 format!("lifetime of {} is too short to guarantee \
830 its contents can be safely reborrowed",
836 pub fn report_aliasability_violation(&self,
838 kind: AliasableViolationKind,
839 cause: mc::AliasableReason) {
840 let mut is_closure = false;
841 let prefix = match kind {
842 MutabilityViolation => {
843 "cannot assign to data"
845 BorrowViolation(euv::ClosureCapture(_)) |
846 BorrowViolation(euv::OverloadedOperator) |
847 BorrowViolation(euv::AddrOf) |
848 BorrowViolation(euv::AutoRef) |
849 BorrowViolation(euv::AutoUnsafe) |
850 BorrowViolation(euv::RefBinding) |
851 BorrowViolation(euv::MatchDiscriminant) => {
852 "cannot borrow data mutably"
855 BorrowViolation(euv::ClosureInvocation) => {
860 BorrowViolation(euv::ForLoop) => {
865 let mut err = match cause {
866 mc::AliasableOther => {
868 self.tcx.sess, span, E0385,
869 "{} in an aliasable location", prefix)
871 mc::AliasableReason::UnaliasableImmutable => {
873 self.tcx.sess, span, E0386,
874 "{} in an immutable container", prefix)
876 mc::AliasableClosure(id) => {
877 let mut err = struct_span_err!(
878 self.tcx.sess, span, E0387,
879 "{} in a captured outer variable in an `Fn` closure", prefix);
880 if let BorrowViolation(euv::ClosureCapture(_)) = kind {
881 // The aliasability violation with closure captures can
882 // happen for nested closures, so we know the enclosing
883 // closure incorrectly accepts an `Fn` while it needs to
885 span_help!(&mut err, self.tcx.hir.span(id),
886 "consider changing this to accept closures that implement `FnMut`");
888 span_help!(&mut err, self.tcx.hir.span(id),
889 "consider changing this closure to take self by mutable reference");
893 mc::AliasableStatic |
894 mc::AliasableStaticMut => {
895 let mut err = struct_span_err!(
896 self.tcx.sess, span, E0388,
897 "{} in a static location", prefix);
898 err.span_label(span, &format!("cannot write data in a static definition"));
901 mc::AliasableBorrowed => {
902 let mut e = struct_span_err!(
903 self.tcx.sess, span, E0389,
904 "{} in a `&` reference", prefix);
905 e.span_label(span, &"assignment into an immutable reference");
911 err.help("closures behind references must be called via `&mut`");
916 fn report_out_of_scope_escaping_closure_capture(&self,
917 err: &BckError<'tcx>,
920 let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
923 match self.tcx.sess.codemap().span_to_snippet(err.span) {
924 Ok(string) => format!("move {}", string),
925 Err(_) => format!("move |<args>| <body>")
928 struct_span_err!(self.tcx.sess, err.span, E0373,
929 "closure may outlive the current function, \
931 which is owned by the current function",
933 .span_label(capture_span,
934 &format!("{} is borrowed here",
936 .span_label(err.span,
937 &format!("may outlive borrowed value {}",
939 .span_suggestion(err.span,
940 &format!("to force the closure to take ownership of {} \
941 (and any other referenced variables), \
942 use the `move` keyword, as shown:",
948 fn region_end_span(&self, region: &'tcx ty::Region) -> Option<Span> {
950 ty::ReScope(scope) => {
951 match scope.span(&self.tcx.region_maps, &self.tcx.hir) {
964 pub fn note_and_explain_bckerr(&self, db: &mut DiagnosticBuilder, err: BckError<'tcx>,
967 err_mutbl => self.note_and_explain_mutbl_error(db, &err, &error_span),
968 err_out_of_scope(super_scope, sub_scope, cause) => {
969 let (value_kind, value_msg) = match err.cmt.cat {
970 mc::Categorization::Rvalue(..) =>
971 ("temporary value", "temporary value created here"),
973 ("borrowed value", "borrow occurs here")
976 let is_closure = match cause {
977 euv::ClosureCapture(s) => {
978 // The primary span starts out as the closure creation point.
979 // Change the primary span here to highlight the use of the variable
980 // in the closure, because it seems more natural. Highlight
981 // closure creation point as a secondary span.
982 match db.span.primary_span() {
984 db.span = MultiSpan::from_span(s);
985 db.span_label(primary, &format!("capture occurs here"));
986 db.span_label(s, &"does not live long enough");
993 db.span_label(error_span, &"does not live long enough");
998 let sub_span = self.region_end_span(sub_scope);
999 let super_span = self.region_end_span(super_scope);
1001 match (sub_span, super_span) {
1002 (Some(s1), Some(s2)) if s1 == s2 => {
1004 db.span = MultiSpan::from_span(s1);
1005 db.span_label(error_span, &value_msg);
1006 let msg = match opt_loan_path(&err.cmt) {
1007 None => value_kind.to_string(),
1009 format!("`{}`", self.loan_path_to_string(&lp))
1013 &format!("{} dropped here while still borrowed", msg));
1015 db.span_label(s1, &format!("{} dropped before borrower", value_kind));
1017 db.note("values in a scope are dropped in the opposite order \
1020 (Some(s1), Some(s2)) if !is_closure => {
1021 db.span = MultiSpan::from_span(s2);
1022 db.span_label(error_span, &value_msg);
1023 let msg = match opt_loan_path(&err.cmt) {
1024 None => value_kind.to_string(),
1026 format!("`{}`", self.loan_path_to_string(&lp))
1029 db.span_label(s2, &format!("{} dropped here while still borrowed", msg));
1030 db.span_label(s1, &format!("{} needs to live until here", value_kind));
1035 db.span_label(s, &format!("{} needs to live until here",
1039 self.tcx.note_and_explain_region(
1041 "borrowed value must be valid for ",
1048 db.span_label(s, &format!("{} only lives until here", value_kind));
1051 self.tcx.note_and_explain_region(
1053 "...but borrowed value is only valid for ",
1061 if let Some(_) = statement_scope_span(self.tcx, super_scope) {
1062 db.note("consider using a `let` binding to increase its lifetime");
1068 mc::Categorization::Rvalue(r, or) if r != or => {
1070 before rustc 1.16, this temporary lived longer - see issue #39283 \
1071 (https://github.com/rust-lang/rust/issues/39283)");
1077 err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1078 let descr = match opt_loan_path(&err.cmt) {
1080 format!("`{}`", self.loan_path_to_string(&lp))
1082 None => self.cmt_to_string(&err.cmt),
1084 self.tcx.note_and_explain_region(
1086 &format!("{} would have to be valid for ",
1090 self.tcx.note_and_explain_region(
1092 &format!("...but {} is only valid for ", descr),
1099 fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'tcx>,
1100 error_span: &Span) {
1101 match err.cmt.note {
1102 mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1103 // If this is an `Fn` closure, it simply can't mutate upvars.
1104 // If it's an `FnMut` closure, the original variable was declared immutable.
1105 // We need to determine which is the case here.
1106 let kind = match err.cmt.upvar().unwrap().cat {
1107 Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1110 if kind == ty::ClosureKind::Fn {
1111 db.span_help(self.tcx.hir.span(upvar_id.closure_expr_id),
1112 "consider changing this closure to take \
1113 self by mutable reference");
1117 if let Categorization::Deref(ref inner_cmt, ..) = err.cmt.cat {
1118 if let Categorization::Local(local_id) = inner_cmt.cat {
1119 let parent = self.tcx.hir.get_parent_node(local_id);
1121 if let Some(fn_like) = FnLikeNode::from_node(self.tcx.hir.get(parent)) {
1122 if let Some(i) = self.tcx.hir.body(fn_like.body()).arguments.iter()
1123 .position(|arg| arg.pat.id == local_id) {
1124 let arg_ty = &fn_like.decl().inputs[i];
1127 hir::MutTy{mutbl: hir::Mutability::MutImmutable, ref ty}) =
1129 if let Some(lifetime) = opt_lifetime {
1130 if let Ok(snippet) = self.tcx.sess.codemap()
1131 .span_to_snippet(ty.span) {
1132 if let Ok(lifetime_snippet) = self.tcx.sess.codemap()
1133 .span_to_snippet(lifetime.span) {
1134 db.span_label(arg_ty.span,
1135 &format!("use `&{} mut {}` \
1136 here to make mutable",
1142 else if let Ok(snippet) = self.tcx.sess.codemap()
1143 .span_to_snippet(arg_ty.span) {
1144 if snippet.starts_with("&") {
1145 db.span_label(arg_ty.span,
1146 &format!("use `{}` here to make mutable",
1147 snippet.replace("&", "&mut ")));
1154 } else if let Categorization::Local(local_id) = err.cmt.cat {
1155 let span = self.tcx.hir.span(local_id);
1156 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
1157 if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
1158 db.span_label(*error_span, &format!("cannot reborrow mutably"));
1159 db.span_label(*error_span, &format!("try removing `&mut` here"));
1161 if snippet.starts_with("ref ") {
1162 db.span_label(span, &format!("use `{}` here to make mutable",
1163 snippet.replace("ref ", "ref mut ")));
1164 } else if snippet != "self" {
1166 &format!("use `mut {}` here to make mutable",
1169 db.span_label(*error_span, &format!("cannot borrow mutably"));
1172 db.span_label(*error_span, &format!("cannot borrow mutably"));
1178 pub fn append_loan_path_to_string(&self,
1179 loan_path: &LoanPath<'tcx>,
1181 match loan_path.kind {
1182 LpUpvar(ty::UpvarId{ var_id: id, closure_expr_id: _ }) |
1184 out.push_str(&self.tcx.local_var_name_str(id));
1187 LpDowncast(ref lp_base, variant_def_id) => {
1189 self.append_loan_path_to_string(&lp_base, out);
1190 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1191 out.push_str(&self.tcx.item_path_str(variant_def_id));
1195 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(fname))) => {
1196 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1198 mc::NamedField(fname) => {
1200 out.push_str(&fname.as_str());
1202 mc::PositionalField(idx) => {
1204 out.push_str(&idx.to_string());
1209 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement(..))) => {
1210 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1211 out.push_str("[..]");
1214 LpExtend(ref lp_base, _, LpDeref(_)) => {
1216 self.append_loan_path_to_string(&lp_base, out);
1221 pub fn append_autoderefd_loan_path_to_string(&self,
1222 loan_path: &LoanPath<'tcx>,
1224 match loan_path.kind {
1225 LpExtend(ref lp_base, _, LpDeref(_)) => {
1226 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1227 // rules would normally allow users to omit the `*x`.
1228 // So just serialize such paths to `x.f` or x[3]` respectively.
1229 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1232 LpDowncast(ref lp_base, variant_def_id) => {
1234 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1236 out.push_str(&self.tcx.item_path_str(variant_def_id));
1240 LpVar(..) | LpUpvar(..) | LpExtend(.., LpInterior(..)) => {
1241 self.append_loan_path_to_string(loan_path, out)
1246 pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1247 let mut result = String::new();
1248 self.append_loan_path_to_string(loan_path, &mut result);
1252 pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1253 cmt.descriptive_string(self.tcx)
1256 pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt<'tcx>) -> String {
1257 match opt_loan_path(cmt) {
1258 Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1259 None => self.cmt_to_string(cmt),
1264 fn statement_scope_span(tcx: TyCtxt, region: &ty::Region) -> Option<Span> {
1266 ty::ReScope(scope) => {
1267 match tcx.hir.find(scope.node_id(&tcx.region_maps)) {
1268 Some(hir_map::NodeStmt(stmt)) => Some(stmt.span),
1276 impl BitwiseOperator for LoanDataFlowOperator {
1278 fn join(&self, succ: usize, pred: usize) -> usize {
1279 succ | pred // loans from both preds are in scope
1283 impl DataFlowOperator for LoanDataFlowOperator {
1285 fn initial_value(&self) -> bool {
1286 false // no loans in scope by default
1290 impl<'tcx> fmt::Debug for InteriorKind {
1291 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1293 InteriorField(mc::NamedField(fld)) => write!(f, "{}", fld),
1294 InteriorField(mc::PositionalField(i)) => write!(f, "#{}", i),
1295 InteriorElement(..) => write!(f, "[]"),
1300 impl<'tcx> fmt::Debug for Loan<'tcx> {
1301 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1302 write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1308 self.restricted_paths)
1312 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1313 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1316 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_string(id)))
1319 LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => {
1320 let s = ty::tls::with(|tcx| tcx.hir.node_to_string(var_id));
1321 write!(f, "$({} captured by id={})", s, closure_expr_id)
1324 LpDowncast(ref lp, variant_def_id) => {
1325 let variant_str = if variant_def_id.is_local() {
1326 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1328 format!("{:?}", variant_def_id)
1330 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1333 LpExtend(ref lp, _, LpDeref(_)) => {
1334 write!(f, "{:?}.*", lp)
1337 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1338 write!(f, "{:?}.{:?}", lp, interior)
1344 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1345 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1348 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_user_string(id)))
1351 LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => {
1352 let s = ty::tls::with(|tcx| tcx.hir.node_to_user_string(var_id));
1353 write!(f, "$({} captured by closure)", s)
1356 LpDowncast(ref lp, variant_def_id) => {
1357 let variant_str = if variant_def_id.is_local() {
1358 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1360 format!("{:?}", variant_def_id)
1362 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1365 LpExtend(ref lp, _, LpDeref(_)) => {
1366 write!(f, "{}.*", lp)
1369 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1370 write!(f, "{}.{:?}", lp, interior)