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::FnParts;
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};
45 use syntax::attr::AttrMetaMethods;
46 use syntax_pos::{MultiSpan, Span};
47 use errors::DiagnosticBuilder;
50 use rustc::hir::{FnDecl, Block};
51 use rustc::hir::intravisit;
52 use rustc::hir::intravisit::{Visitor, FnKind};
54 use rustc::mir::mir_map::MirMap;
64 #[derive(Clone, Copy)]
65 pub struct LoanDataFlowOperator;
67 pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
69 impl<'a, 'tcx, 'v> Visitor<'v> for BorrowckCtxt<'a, 'tcx> {
70 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
71 b: &'v Block, 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: &hir::Item) {
87 borrowck_item(self, item);
90 fn visit_trait_item(&mut self, ti: &hir::TraitItem) {
91 if let hir::ConstTraitItem(_, Some(ref expr)) = ti.node {
92 gather_loans::gather_loans_in_static_initializer(self, ti.id, &expr);
94 intravisit::walk_trait_item(self, ti);
97 fn visit_impl_item(&mut self, ii: &hir::ImplItem) {
98 if let hir::ImplItemKind::Const(_, ref expr) = ii.node {
99 gather_loans::gather_loans_in_static_initializer(self, ii.id, &expr);
101 intravisit::walk_impl_item(self, ii);
105 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, mir_map: &MirMap<'tcx>) {
106 let mut bccx = BorrowckCtxt {
108 mir_map: Some(mir_map),
109 free_region_map: FreeRegionMap::new(),
111 loaned_paths_same: 0,
118 tcx.visit_all_items_in_krate(DepNode::BorrowCheck, &mut bccx);
120 if tcx.sess.borrowck_stats() {
121 println!("--- borrowck stats ---");
122 println!("paths requiring guarantees: {}",
123 bccx.stats.guaranteed_paths);
124 println!("paths requiring loans : {}",
125 make_stat(&bccx, bccx.stats.loaned_paths_same));
126 println!("paths requiring imm loans : {}",
127 make_stat(&bccx, bccx.stats.loaned_paths_imm));
128 println!("stable paths : {}",
129 make_stat(&bccx, bccx.stats.stable_paths));
132 fn make_stat(bccx: &BorrowckCtxt, stat: usize) -> String {
133 let total = bccx.stats.guaranteed_paths as f64;
134 let perc = if total == 0.0 { 0.0 } else { stat as f64 * 100.0 / total };
135 format!("{} ({:.0}%)", stat, perc)
139 fn borrowck_item(this: &mut BorrowckCtxt, item: &hir::Item) {
140 // Gather loans for items. Note that we don't need
141 // to check loans for single expressions. The check
142 // loan step is intended for things that have a data
143 // flow dependent conditions.
145 hir::ItemStatic(_, _, ref ex) |
146 hir::ItemConst(_, ref ex) => {
147 gather_loans::gather_loans_in_static_initializer(this, item.id, &ex);
152 intravisit::walk_item(this, item);
155 /// Collection of conclusions determined via borrow checker analyses.
156 pub struct AnalysisData<'a, 'tcx: 'a> {
157 pub all_loans: Vec<Loan<'tcx>>,
158 pub loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>,
159 pub move_data: move_data::FlowedMoveData<'a, 'tcx>,
162 fn borrowck_fn(this: &mut BorrowckCtxt,
168 attributes: &[ast::Attribute]) {
169 debug!("borrowck_fn(id={})", id);
171 let def_id = this.tcx.map.local_def_id(id);
173 if attributes.iter().any(|item| item.check_name("rustc_mir_borrowck")) {
174 let mir = this.mir_map.unwrap().map.get(&def_id).unwrap();
175 this.with_temp_region_map(id, |this| {
176 mir::borrowck_mir(this, fk, decl, mir, body, sp, id, attributes)
180 let cfg = cfg::CFG::new(this.tcx, body);
181 let AnalysisData { all_loans,
183 move_data: flowed_moves } =
184 build_borrowck_dataflow_data(this, fk, decl, &cfg, body, sp, id);
186 move_data::fragments::instrument_move_fragments(&flowed_moves.move_data,
190 move_data::fragments::build_unfragmented_map(this,
191 &flowed_moves.move_data,
194 check_loans::check_loans(this,
202 intravisit::walk_fn(this, fk, decl, body, sp, id);
205 fn build_borrowck_dataflow_data<'a, 'tcx>(this: &mut BorrowckCtxt<'a, 'tcx>,
212 -> AnalysisData<'a, 'tcx>
214 // Check the body of fn items.
216 let id_range = intravisit::compute_id_range_for_fn_body(fk, decl, body, sp, id);
217 let (all_loans, move_data) =
218 gather_loans::gather_loans_in_fn(this, id, decl, body);
221 DataFlowContext::new(this.tcx,
225 LoanDataFlowOperator,
228 for (loan_idx, loan) in all_loans.iter().enumerate() {
229 loan_dfcx.add_gen(loan.gen_scope.node_id(&tcx.region_maps), loan_idx);
230 loan_dfcx.add_kill(KillFrom::ScopeEnd,
231 loan.kill_scope.node_id(&tcx.region_maps), loan_idx);
233 loan_dfcx.add_kills_from_flow_exits(cfg);
234 loan_dfcx.propagate(cfg, body);
236 let flowed_moves = move_data::FlowedMoveData::new(move_data,
243 AnalysisData { all_loans: all_loans,
245 move_data:flowed_moves }
248 /// Accessor for introspective clients inspecting `AnalysisData` and
249 /// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer.
250 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
251 tcx: TyCtxt<'a, 'tcx, 'tcx>,
252 mir_map: Option<&'a MirMap<'tcx>>,
253 fn_parts: FnParts<'a>,
255 -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
258 let mut bccx = BorrowckCtxt {
261 free_region_map: FreeRegionMap::new(),
263 loaned_paths_same: 0,
270 let dataflow_data = build_borrowck_dataflow_data(&mut bccx,
278 (bccx, dataflow_data)
281 // ----------------------------------------------------------------------
284 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
285 tcx: TyCtxt<'a, 'tcx, 'tcx>,
287 // Hacky. As we visit various fns, we have to load up the
288 // free-region map for each one. This map is computed by during
289 // typeck for each fn item and stored -- closures just use the map
290 // from the fn item that encloses them. Since we walk the fns in
291 // order, we basically just overwrite this field as we enter a fn
292 // item and restore it afterwards in a stack-like fashion. Then
293 // the borrow checking code can assume that `free_region_map` is
294 // always the correct map for the current fn. Feels like it'd be
295 // better to just recompute this, rather than store it, but it's a
296 // bit of a pain to factor that code out at the moment.
297 free_region_map: FreeRegionMap,
302 // NodeId to MIR mapping (for methods that carry the #[rustc_mir] attribute).
303 mir_map: Option<&'a MirMap<'tcx>>,
308 loaned_paths_same: usize,
309 loaned_paths_imm: usize,
311 guaranteed_paths: usize
314 pub type BckResult<'tcx, T> = Result<T, BckError<'tcx>>;
316 ///////////////////////////////////////////////////////////////////////////
317 // Loans and loan paths
319 /// Record of a loan that was issued.
320 pub struct Loan<'tcx> {
322 loan_path: Rc<LoanPath<'tcx>>,
323 kind: ty::BorrowKind,
324 restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
326 /// gen_scope indicates where loan is introduced. Typically the
327 /// loan is introduced at the point of the borrow, but in some
328 /// cases, notably method arguments, the loan may be introduced
329 /// only later, once it comes into scope. See also
330 /// `GatherLoanCtxt::compute_gen_scope`.
331 gen_scope: region::CodeExtent,
333 /// kill_scope indicates when the loan goes out of scope. This is
334 /// either when the lifetime expires or when the local variable
335 /// which roots the loan-path goes out of scope, whichever happens
336 /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
337 kill_scope: region::CodeExtent,
339 cause: euv::LoanCause,
342 impl<'tcx> Loan<'tcx> {
343 pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
344 self.loan_path.clone()
349 pub struct LoanPath<'tcx> {
350 kind: LoanPathKind<'tcx>,
354 impl<'tcx> PartialEq for LoanPath<'tcx> {
355 fn eq(&self, that: &LoanPath<'tcx>) -> bool {
356 let r = self.kind == that.kind;
357 debug_assert!(self.ty == that.ty || !r,
358 "Somehow loan paths are equal though their tys are not.");
363 #[derive(PartialEq, Eq, Hash, Debug)]
364 pub enum LoanPathKind<'tcx> {
365 LpVar(ast::NodeId), // `x` in README.md
366 LpUpvar(ty::UpvarId), // `x` captured by-value into closure
367 LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
368 LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem)
371 impl<'tcx> LoanPath<'tcx> {
372 fn new(kind: LoanPathKind<'tcx>, ty: ty::Ty<'tcx>) -> LoanPath<'tcx> {
373 LoanPath { kind: kind, ty: ty }
376 fn to_type(&self) -> ty::Ty<'tcx> { self.ty }
379 // FIXME (pnkfelix): See discussion here
380 // https://github.com/pnkfelix/rust/commit/
381 // b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
382 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
384 // A local, "cleaned" version of `mc::InteriorKind` that drops
385 // information that is not relevant to loan-path analysis. (In
386 // particular, the distinction between how precisely an array-element
387 // is tracked is irrelevant here.)
388 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
389 pub enum InteriorKind {
390 InteriorField(mc::FieldName),
391 InteriorElement(mc::ElementKind),
394 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
395 impl ToInteriorKind for mc::InteriorKind {
396 fn cleaned(self) -> InteriorKind {
398 mc::InteriorField(name) => InteriorField(name),
399 mc::InteriorElement(_, elem_kind) => InteriorElement(elem_kind),
405 // - a pointer dereference (`*LV` in README.md)
406 // - a field reference, with an optional definition of the containing
407 // enum variant (`LV.f` in README.md)
408 // `DefId` is present when the field is part of struct that is in
409 // a variant of an enum. For instance in:
410 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
411 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
412 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
413 pub enum LoanPathElem {
414 LpDeref(mc::PointerKind),
415 LpInterior(Option<DefId>, InteriorKind),
418 pub fn closure_to_block(closure_id: ast::NodeId,
419 tcx: TyCtxt) -> ast::NodeId {
420 match tcx.map.get(closure_id) {
421 hir_map::NodeExpr(expr) => match expr.node {
422 hir::ExprClosure(_, _, ref block, _) => {
426 bug!("encountered non-closure id: {}", closure_id)
429 _ => bug!("encountered non-expr id: {}", closure_id)
433 impl<'a, 'tcx> LoanPath<'tcx> {
434 pub fn kill_scope(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> region::CodeExtent {
436 LpVar(local_id) => tcx.region_maps.var_scope(local_id),
437 LpUpvar(upvar_id) => {
438 let block_id = closure_to_block(upvar_id.closure_expr_id, tcx);
439 tcx.region_maps.node_extent(block_id)
441 LpDowncast(ref base, _) |
442 LpExtend(ref base, _, _) => base.kill_scope(tcx),
446 fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
447 match (&self.kind, &other.kind) {
448 (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
449 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
450 if id == id2 && opt_variant_id == opt_variant_id2 {
451 base.has_fork(&base2)
455 (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
456 (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&base),
461 fn depth(&self) -> usize {
463 LpExtend(ref base, _, LpDeref(_)) => base.depth(),
464 LpExtend(ref base, _, LpInterior(_, _)) => base.depth() + 1,
469 fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
470 match (&self.kind, &other.kind) {
471 (&LpExtend(ref base, a, LpInterior(opt_variant_id, id)),
472 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) => {
473 if id == id2 && opt_variant_id == opt_variant_id2 {
474 base.common(&base2).map(|x| {
476 if base.depth() == xd && base2.depth() == xd {
477 assert_eq!(base.ty, base2.ty);
478 assert_eq!(self.ty, other.ty);
480 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
491 (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
492 (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&other),
493 (&LpVar(id), &LpVar(id2)) => {
495 assert_eq!(self.ty, other.ty);
496 Some(LoanPath { kind: LpVar(id), ty: self.ty })
501 (&LpUpvar(id), &LpUpvar(id2)) => {
503 assert_eq!(self.ty, other.ty);
504 Some(LoanPath { kind: LpUpvar(id), ty: self.ty })
514 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
515 //! Computes the `LoanPath` (if any) for a `cmt`.
516 //! Note that this logic is somewhat duplicated in
517 //! the method `compute()` found in `gather_loans::restrictions`,
518 //! which allows it to share common loan path pieces as it
519 //! traverses the CMT.
521 let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
524 Categorization::Rvalue(..) |
525 Categorization::StaticItem => {
529 Categorization::Local(id) => {
530 Some(new_lp(LpVar(id)))
533 Categorization::Upvar(mc::Upvar { id, .. }) => {
534 Some(new_lp(LpUpvar(id)))
537 Categorization::Deref(ref cmt_base, _, pk) => {
538 opt_loan_path(cmt_base).map(|lp| {
539 new_lp(LpExtend(lp, cmt.mutbl, LpDeref(pk)))
543 Categorization::Interior(ref cmt_base, ik) => {
544 opt_loan_path(cmt_base).map(|lp| {
545 let opt_variant_id = match cmt_base.cat {
546 Categorization::Downcast(_, did) => Some(did),
549 new_lp(LpExtend(lp, cmt.mutbl, LpInterior(opt_variant_id, ik.cleaned())))
553 Categorization::Downcast(ref cmt_base, variant_def_id) =>
554 opt_loan_path(cmt_base)
556 new_lp(LpDowncast(lp, variant_def_id))
562 ///////////////////////////////////////////////////////////////////////////
565 // Errors that can occur
567 pub enum bckerr_code {
569 err_out_of_scope(ty::Region, ty::Region), // superscope, subscope
570 err_borrowed_pointer_too_short(ty::Region, ty::Region), // loan, ptr
573 // Combination of an error code and the categorization of the expression
576 pub struct BckError<'tcx> {
578 cause: AliasableViolationKind,
583 #[derive(Copy, Clone, Debug, PartialEq)]
584 pub enum AliasableViolationKind {
586 BorrowViolation(euv::LoanCause)
589 #[derive(Copy, Clone, Debug)]
590 pub enum MovedValueUseKind {
595 ///////////////////////////////////////////////////////////////////////////
598 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
599 fn with_temp_region_map<F>(&mut self, id: ast::NodeId, f: F)
600 where F: for <'b> FnOnce(&'b mut BorrowckCtxt<'a, 'tcx>)
602 let new_free_region_map = self.tcx.free_region_map(id);
603 let old_free_region_map = mem::replace(&mut self.free_region_map, new_free_region_map);
605 self.free_region_map = old_free_region_map;
608 pub fn is_subregion_of(&self, r_sub: ty::Region, r_sup: ty::Region)
611 self.free_region_map.is_subregion_of(self.tcx, r_sub, r_sup)
614 pub fn report(&self, err: BckError<'tcx>) {
615 // Catch and handle some particular cases.
616 match (&err.code, &err.cause) {
617 (&err_out_of_scope(ty::ReScope(_), ty::ReStatic),
618 &BorrowViolation(euv::ClosureCapture(span))) |
619 (&err_out_of_scope(ty::ReScope(_), ty::ReFree(..)),
620 &BorrowViolation(euv::ClosureCapture(span))) => {
621 return self.report_out_of_scope_escaping_closure_capture(&err, span);
627 let span = err.span.clone();
628 let mut db = self.struct_span_err(
630 &self.bckerr_to_string(&err));
631 self.note_and_explain_bckerr(&mut db, err, span);
635 pub fn report_use_of_moved_value(&self,
637 use_kind: MovedValueUseKind,
639 the_move: &move_data::Move,
640 moved_lp: &LoanPath<'tcx>,
641 _param_env: &ty::ParameterEnvironment<'tcx>) {
642 let (verb, verb_participle) = match use_kind {
643 MovedInUse => ("use", "used"),
644 MovedInCapture => ("capture", "captured"),
647 let (_ol, _moved_lp_msg, mut err) = match the_move.kind {
648 move_data::Declared => {
649 // If this is an uninitialized variable, just emit a simple warning
652 self.tcx.sess, use_span, E0381,
653 "{} of possibly uninitialized variable: `{}`",
655 self.loan_path_to_string(lp))
656 .span_label(use_span, &format!("use of possibly uninitialized `{}`",
657 self.loan_path_to_string(lp)))
662 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
663 // normally generate a rather confusing message:
665 // error: use of moved value: `x.b`
666 // note: `x.a` moved here...
668 // What we want to do instead is get the 'common ancestor' of the two moves and
669 // use that for most of the message instead, giving is something like this:
671 // error: use of moved value: `x`
672 // note: `x` moved here (through moving `x.a`)...
674 let common = moved_lp.common(lp);
675 let has_common = common.is_some();
676 let has_fork = moved_lp.has_fork(lp);
677 let (nl, ol, moved_lp_msg) =
678 if has_fork && has_common {
679 let nl = self.loan_path_to_string(&common.unwrap());
681 let moved_lp_msg = format!(" (through moving `{}`)",
682 self.loan_path_to_string(moved_lp));
683 (nl, ol, moved_lp_msg)
685 (self.loan_path_to_string(lp),
686 self.loan_path_to_string(moved_lp),
690 let partial = moved_lp.depth() > lp.depth();
691 let msg = if !has_fork && partial { "partially " }
692 else if has_fork && !has_common { "collaterally "}
694 let err = struct_span_err!(
695 self.tcx.sess, use_span, E0382,
696 "{} of {}moved value: `{}`",
698 (ol, moved_lp_msg, err)}
701 // Get type of value and span where it was previously
703 let (move_span, move_note) = match the_move.kind {
704 move_data::Declared => {
708 move_data::MoveExpr |
709 move_data::MovePat =>
710 (self.tcx.map.span(the_move.id), ""),
712 move_data::Captured =>
713 (match self.tcx.map.expect_expr(the_move.id).node {
714 hir::ExprClosure(_, _, _, fn_decl_span) => fn_decl_span,
715 ref r => bug!("Captured({}) maps to non-closure: {:?}",
717 }, " (into closure)"),
720 // Annotate the use and the move in the span. Watch out for
721 // the case where the use and the move are the same. This
722 // means the use is in a loop.
723 err = if use_span == move_span {
726 &format!("value moved{} here in previous iteration of loop",
730 err.span_label(use_span, &format!("value {} here after move", verb_participle))
731 .span_label(move_span, &format!("value moved{} here", move_note));
735 err.note(&format!("move occurs because `{}` has type `{}`, \
736 which does not implement the `Copy` trait",
737 self.loan_path_to_string(moved_lp),
740 // Note: we used to suggest adding a `ref binding` or calling
741 // `clone` but those suggestions have been removed because
742 // they are often not what you actually want to do, and were
743 // not considered particularly helpful.
748 pub fn report_partial_reinitialization_of_uninitialized_structure(
751 lp: &LoanPath<'tcx>) {
753 self.tcx.sess, span, E0383,
754 "partial reinitialization of uninitialized structure `{}`",
755 self.loan_path_to_string(lp));
758 pub fn report_reassigned_immutable_variable(&self,
762 &move_data::Assignment) {
763 let mut err = struct_span_err!(
764 self.tcx.sess, span, E0384,
765 "re-assignment of immutable variable `{}`",
766 self.loan_path_to_string(lp));
767 err.span_label(span, &format!("re-assignment of immutable variable"));
768 if span != assign.span {
769 err.span_label(assign.span, &format!("first assignment to `{}`",
770 self.loan_path_to_string(lp)));
775 pub fn span_err(&self, s: Span, m: &str) {
776 self.tcx.sess.span_err(s, m);
779 pub fn struct_span_err<S: Into<MultiSpan>>(&self, s: S, m: &str)
780 -> DiagnosticBuilder<'a> {
781 self.tcx.sess.struct_span_err(s, m)
784 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(&self,
788 -> DiagnosticBuilder<'a> {
789 self.tcx.sess.struct_span_err_with_code(s, msg, code)
792 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, s: S, msg: &str, code: &str) {
793 self.tcx.sess.span_err_with_code(s, msg, code);
796 pub fn bckerr_to_string(&self, err: &BckError<'tcx>) -> String {
799 let descr = match err.cmt.note {
800 mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
801 self.cmt_to_string(&err.cmt)
803 _ => match opt_loan_path(&err.cmt) {
806 err.cmt.mutbl.to_user_str(),
807 self.cmt_to_string(&err.cmt))
810 format!("{} {} `{}`",
811 err.cmt.mutbl.to_user_str(),
812 self.cmt_to_string(&err.cmt),
813 self.loan_path_to_string(&lp))
819 MutabilityViolation => {
820 format!("cannot assign to {}", descr)
822 BorrowViolation(euv::ClosureCapture(_)) => {
823 format!("closure cannot assign to {}", descr)
825 BorrowViolation(euv::OverloadedOperator) |
826 BorrowViolation(euv::AddrOf) |
827 BorrowViolation(euv::RefBinding) |
828 BorrowViolation(euv::AutoRef) |
829 BorrowViolation(euv::AutoUnsafe) |
830 BorrowViolation(euv::ForLoop) |
831 BorrowViolation(euv::MatchDiscriminant) => {
832 format!("cannot borrow {} as mutable", descr)
834 BorrowViolation(euv::ClosureInvocation) => {
836 "err_mutbl with a closure invocation");
840 err_out_of_scope(..) => {
841 let msg = match opt_loan_path(&err.cmt) {
842 None => "borrowed value".to_string(),
844 format!("`{}`", self.loan_path_to_string(&lp))
847 format!("{} does not live long enough", msg)
849 err_borrowed_pointer_too_short(..) => {
850 let descr = self.cmt_to_path_or_string(&err.cmt);
851 format!("lifetime of {} is too short to guarantee \
852 its contents can be safely reborrowed",
858 pub fn report_aliasability_violation(&self,
860 kind: AliasableViolationKind,
861 cause: mc::AliasableReason) {
862 let mut is_closure = false;
863 let prefix = match kind {
864 MutabilityViolation => {
865 "cannot assign to data"
867 BorrowViolation(euv::ClosureCapture(_)) |
868 BorrowViolation(euv::OverloadedOperator) |
869 BorrowViolation(euv::AddrOf) |
870 BorrowViolation(euv::AutoRef) |
871 BorrowViolation(euv::AutoUnsafe) |
872 BorrowViolation(euv::RefBinding) |
873 BorrowViolation(euv::MatchDiscriminant) => {
874 "cannot borrow data mutably"
877 BorrowViolation(euv::ClosureInvocation) => {
882 BorrowViolation(euv::ForLoop) => {
887 let mut err = match cause {
888 mc::AliasableOther => {
890 self.tcx.sess, span, E0385,
891 "{} in an aliasable location", prefix)
893 mc::AliasableReason::UnaliasableImmutable => {
895 self.tcx.sess, span, E0386,
896 "{} in an immutable container", prefix)
898 mc::AliasableClosure(id) => {
899 let mut err = struct_span_err!(
900 self.tcx.sess, span, E0387,
901 "{} in a captured outer variable in an `Fn` closure", prefix);
902 if let BorrowViolation(euv::ClosureCapture(_)) = kind {
903 // The aliasability violation with closure captures can
904 // happen for nested closures, so we know the enclosing
905 // closure incorrectly accepts an `Fn` while it needs to
907 span_help!(&mut err, self.tcx.map.span(id),
908 "consider changing this to accept closures that implement `FnMut`");
910 span_help!(&mut err, self.tcx.map.span(id),
911 "consider changing this closure to take self by mutable reference");
915 mc::AliasableStatic |
916 mc::AliasableStaticMut => {
918 self.tcx.sess, span, E0388,
919 "{} in a static location", prefix)
921 mc::AliasableBorrowed => {
923 self.tcx.sess, span, E0389,
924 "{} in a `&` reference", prefix)
929 err.help("closures behind references must be called via `&mut`");
934 fn report_out_of_scope_escaping_closure_capture(&self,
935 err: &BckError<'tcx>,
938 let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
941 match self.tcx.sess.codemap().span_to_snippet(err.span) {
942 Ok(string) => format!("move {}", string),
943 Err(_) => format!("move |<args>| <body>")
946 struct_span_err!(self.tcx.sess, err.span, E0373,
947 "closure may outlive the current function, \
949 which is owned by the current function",
951 .span_label(capture_span,
952 &format!("{} is borrowed here",
954 .span_label(err.span,
955 &format!("may outlive borrowed value {}",
957 .span_suggestion(err.span,
958 &format!("to force the closure to take ownership of {} \
959 (and any other referenced variables), \
960 use the `move` keyword, as shown:",
966 pub fn note_and_explain_bckerr(&self, db: &mut DiagnosticBuilder, err: BckError<'tcx>,
972 mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
973 // If this is an `Fn` closure, it simply can't mutate upvars.
974 // If it's an `FnMut` closure, the original variable was declared immutable.
975 // We need to determine which is the case here.
976 let kind = match err.cmt.upvar().unwrap().cat {
977 Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
980 if kind == ty::ClosureKind::Fn {
982 self.tcx.map.span(upvar_id.closure_expr_id),
983 "consider changing this closure to take \
984 self by mutable reference");
988 if let Categorization::Local(local_id) = err.cmt.cat {
989 let span = self.tcx.map.span(local_id);
990 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
991 if snippet.starts_with("ref ") {
993 &format!("use `{}` here to make mutable",
994 snippet.replace("ref ", "ref mut ")));
995 } else if snippet != "self" {
997 &format!("use `mut {}` here to make mutable", snippet));
1000 db.span_label(error_span, &format!("cannot borrow mutably"));
1006 err_out_of_scope(super_scope, sub_scope) => {
1007 self.tcx.note_and_explain_region(
1009 "reference must be valid for ",
1012 self.tcx.note_and_explain_region(
1014 "...but borrowed value is only valid for ",
1017 if let Some(span) = statement_scope_span(self.tcx, super_scope) {
1018 db.span_label(error_span, &format!("does not live long enough"));
1020 "consider using a `let` binding to increase its lifetime");
1024 err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1025 let descr = match opt_loan_path(&err.cmt) {
1027 format!("`{}`", self.loan_path_to_string(&lp))
1029 None => self.cmt_to_string(&err.cmt),
1031 self.tcx.note_and_explain_region(
1033 &format!("{} would have to be valid for ",
1037 self.tcx.note_and_explain_region(
1039 &format!("...but {} is only valid for ", descr),
1046 pub fn append_loan_path_to_string(&self,
1047 loan_path: &LoanPath<'tcx>,
1049 match loan_path.kind {
1050 LpUpvar(ty::UpvarId{ var_id: id, closure_expr_id: _ }) |
1052 out.push_str(&self.tcx.local_var_name_str(id));
1055 LpDowncast(ref lp_base, variant_def_id) => {
1057 self.append_loan_path_to_string(&lp_base, out);
1058 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1059 out.push_str(&self.tcx.item_path_str(variant_def_id));
1064 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(fname))) => {
1065 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1067 mc::NamedField(fname) => {
1069 out.push_str(&fname.as_str());
1071 mc::PositionalField(idx) => {
1073 out.push_str(&idx.to_string());
1078 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement(..))) => {
1079 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1080 out.push_str("[..]");
1083 LpExtend(ref lp_base, _, LpDeref(_)) => {
1085 self.append_loan_path_to_string(&lp_base, out);
1090 pub fn append_autoderefd_loan_path_to_string(&self,
1091 loan_path: &LoanPath<'tcx>,
1093 match loan_path.kind {
1094 LpExtend(ref lp_base, _, LpDeref(_)) => {
1095 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1096 // rules would normally allow users to omit the `*x`.
1097 // So just serialize such paths to `x.f` or x[3]` respectively.
1098 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1101 LpDowncast(ref lp_base, variant_def_id) => {
1103 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1105 out.push_str(&self.tcx.item_path_str(variant_def_id));
1109 LpVar(..) | LpUpvar(..) | LpExtend(_, _, LpInterior(..)) => {
1110 self.append_loan_path_to_string(loan_path, out)
1115 pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1116 let mut result = String::new();
1117 self.append_loan_path_to_string(loan_path, &mut result);
1121 pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1122 cmt.descriptive_string(self.tcx)
1125 pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt<'tcx>) -> String {
1126 match opt_loan_path(cmt) {
1127 Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1128 None => self.cmt_to_string(cmt),
1133 fn statement_scope_span(tcx: TyCtxt, region: ty::Region) -> Option<Span> {
1135 ty::ReScope(scope) => {
1136 match tcx.map.find(scope.node_id(&tcx.region_maps)) {
1137 Some(hir_map::NodeStmt(stmt)) => Some(stmt.span),
1145 impl BitwiseOperator for LoanDataFlowOperator {
1147 fn join(&self, succ: usize, pred: usize) -> usize {
1148 succ | pred // loans from both preds are in scope
1152 impl DataFlowOperator for LoanDataFlowOperator {
1154 fn initial_value(&self) -> bool {
1155 false // no loans in scope by default
1159 impl<'tcx> fmt::Debug for InteriorKind {
1160 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1162 InteriorField(mc::NamedField(fld)) => write!(f, "{}", fld),
1163 InteriorField(mc::PositionalField(i)) => write!(f, "#{}", i),
1164 InteriorElement(..) => write!(f, "[]"),
1169 impl<'tcx> fmt::Debug for Loan<'tcx> {
1170 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1171 write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1177 self.restricted_paths)
1181 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1182 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1185 write!(f, "$({})", ty::tls::with(|tcx| tcx.map.node_to_string(id)))
1188 LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => {
1189 let s = ty::tls::with(|tcx| tcx.map.node_to_string(var_id));
1190 write!(f, "$({} captured by id={})", s, closure_expr_id)
1193 LpDowncast(ref lp, variant_def_id) => {
1194 let variant_str = if variant_def_id.is_local() {
1195 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1197 format!("{:?}", variant_def_id)
1199 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1202 LpExtend(ref lp, _, LpDeref(_)) => {
1203 write!(f, "{:?}.*", lp)
1206 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1207 write!(f, "{:?}.{:?}", lp, interior)
1213 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1214 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1217 write!(f, "$({})", ty::tls::with(|tcx| tcx.map.node_to_user_string(id)))
1220 LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => {
1221 let s = ty::tls::with(|tcx| tcx.map.node_to_user_string(var_id));
1222 write!(f, "$({} captured by closure)", s)
1225 LpDowncast(ref lp, variant_def_id) => {
1226 let variant_str = if variant_def_id.is_local() {
1227 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1229 format!("{:?}", variant_def_id)
1231 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1234 LpExtend(ref lp, _, LpDeref(_)) => {
1235 write!(f, "{}.*", lp)
1238 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1239 write!(f, "{}.{:?}", lp, interior)