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::front::map as hir_map;
24 use rustc::front::map::blocks::FnParts;
25 use rustc::middle::cfg;
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::middle::def_id::DefId;
31 use rustc::middle::expr_use_visitor as euv;
32 use rustc::middle::free_region::FreeRegionMap;
33 use rustc::middle::mem_categorization as mc;
34 use rustc::middle::mem_categorization::Categorization;
35 use rustc::middle::region;
36 use rustc::middle::ty::{self, Ty};
42 use syntax::codemap::Span;
43 use syntax::errors::DiagnosticBuilder;
46 use rustc_front::hir::{FnDecl, Block};
47 use rustc_front::intravisit;
48 use rustc_front::intravisit::{Visitor, FnKind};
49 use rustc_front::util as hir_util;
57 #[derive(Clone, Copy)]
58 pub struct LoanDataFlowOperator;
60 pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
62 impl<'a, 'tcx, 'v> Visitor<'v> for BorrowckCtxt<'a, 'tcx> {
63 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
64 b: &'v Block, s: Span, id: ast::NodeId) {
67 FnKind::Method(..) => {
68 let new_free_region_map = self.tcx.free_region_map(id);
69 let old_free_region_map =
70 mem::replace(&mut self.free_region_map, new_free_region_map);
71 borrowck_fn(self, fk, fd, b, s, id);
72 self.free_region_map = old_free_region_map;
76 borrowck_fn(self, fk, fd, b, s, id);
81 fn visit_item(&mut self, item: &hir::Item) {
82 borrowck_item(self, item);
85 fn visit_trait_item(&mut self, ti: &hir::TraitItem) {
86 if let hir::ConstTraitItem(_, Some(ref expr)) = ti.node {
87 gather_loans::gather_loans_in_static_initializer(self, &*expr);
89 intravisit::walk_trait_item(self, ti);
92 fn visit_impl_item(&mut self, ii: &hir::ImplItem) {
93 if let hir::ImplItemKind::Const(_, ref expr) = ii.node {
94 gather_loans::gather_loans_in_static_initializer(self, &*expr);
96 intravisit::walk_impl_item(self, ii);
100 pub fn check_crate(tcx: &ty::ctxt) {
101 let mut bccx = BorrowckCtxt {
103 free_region_map: FreeRegionMap::new(),
105 loaned_paths_same: 0,
112 tcx.map.krate().visit_all_items(&mut bccx);
114 if tcx.sess.borrowck_stats() {
115 println!("--- borrowck stats ---");
116 println!("paths requiring guarantees: {}",
117 bccx.stats.guaranteed_paths);
118 println!("paths requiring loans : {}",
119 make_stat(&bccx, bccx.stats.loaned_paths_same));
120 println!("paths requiring imm loans : {}",
121 make_stat(&bccx, bccx.stats.loaned_paths_imm));
122 println!("stable paths : {}",
123 make_stat(&bccx, bccx.stats.stable_paths));
126 fn make_stat(bccx: &BorrowckCtxt, stat: usize) -> String {
127 let total = bccx.stats.guaranteed_paths as f64;
128 let perc = if total == 0.0 { 0.0 } else { stat as f64 * 100.0 / total };
129 format!("{} ({:.0}%)", stat, perc)
133 fn borrowck_item(this: &mut BorrowckCtxt, item: &hir::Item) {
134 // Gather loans for items. Note that we don't need
135 // to check loans for single expressions. The check
136 // loan step is intended for things that have a data
137 // flow dependent conditions.
139 hir::ItemStatic(_, _, ref ex) |
140 hir::ItemConst(_, ref ex) => {
141 gather_loans::gather_loans_in_static_initializer(this, &**ex);
146 intravisit::walk_item(this, item);
149 /// Collection of conclusions determined via borrow checker analyses.
150 pub struct AnalysisData<'a, 'tcx: 'a> {
151 pub all_loans: Vec<Loan<'tcx>>,
152 pub loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>,
153 pub move_data: move_data::FlowedMoveData<'a, 'tcx>,
156 fn borrowck_fn(this: &mut BorrowckCtxt,
162 debug!("borrowck_fn(id={})", id);
163 let cfg = cfg::CFG::new(this.tcx, body);
164 let AnalysisData { all_loans,
166 move_data: flowed_moves } =
167 build_borrowck_dataflow_data(this, fk, decl, &cfg, body, sp, id);
169 move_data::fragments::instrument_move_fragments(&flowed_moves.move_data,
173 move_data::fragments::build_unfragmented_map(this,
174 &flowed_moves.move_data,
177 check_loans::check_loans(this,
185 intravisit::walk_fn(this, fk, decl, body, sp);
188 fn build_borrowck_dataflow_data<'a, 'tcx>(this: &mut BorrowckCtxt<'a, 'tcx>,
195 -> AnalysisData<'a, 'tcx>
197 // Check the body of fn items.
199 let id_range = hir_util::compute_id_range_for_fn_body(fk, decl, body, sp, id);
200 let (all_loans, move_data) =
201 gather_loans::gather_loans_in_fn(this, id, decl, body);
204 DataFlowContext::new(this.tcx,
208 LoanDataFlowOperator,
211 for (loan_idx, loan) in all_loans.iter().enumerate() {
212 loan_dfcx.add_gen(loan.gen_scope.node_id(&tcx.region_maps), loan_idx);
213 loan_dfcx.add_kill(KillFrom::ScopeEnd,
214 loan.kill_scope.node_id(&tcx.region_maps), loan_idx);
216 loan_dfcx.add_kills_from_flow_exits(cfg);
217 loan_dfcx.propagate(cfg, body);
219 let flowed_moves = move_data::FlowedMoveData::new(move_data,
226 AnalysisData { all_loans: all_loans,
228 move_data:flowed_moves }
231 /// Accessor for introspective clients inspecting `AnalysisData` and
232 /// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer.
233 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
234 tcx: &'a ty::ctxt<'tcx>,
235 fn_parts: FnParts<'a>,
237 -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
240 let mut bccx = BorrowckCtxt {
242 free_region_map: FreeRegionMap::new(),
244 loaned_paths_same: 0,
251 let dataflow_data = build_borrowck_dataflow_data(&mut bccx,
259 (bccx, dataflow_data)
262 // ----------------------------------------------------------------------
265 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
266 tcx: &'a ty::ctxt<'tcx>,
268 // Hacky. As we visit various fns, we have to load up the
269 // free-region map for each one. This map is computed by during
270 // typeck for each fn item and stored -- closures just use the map
271 // from the fn item that encloses them. Since we walk the fns in
272 // order, we basically just overwrite this field as we enter a fn
273 // item and restore it afterwards in a stack-like fashion. Then
274 // the borrow checking code can assume that `free_region_map` is
275 // always the correct map for the current fn. Feels like it'd be
276 // better to just recompute this, rather than store it, but it's a
277 // bit of a pain to factor that code out at the moment.
278 free_region_map: FreeRegionMap,
285 loaned_paths_same: usize,
286 loaned_paths_imm: usize,
288 guaranteed_paths: usize
291 pub type BckResult<'tcx, T> = Result<T, BckError<'tcx>>;
293 ///////////////////////////////////////////////////////////////////////////
294 // Loans and loan paths
296 /// Record of a loan that was issued.
297 pub struct Loan<'tcx> {
299 loan_path: Rc<LoanPath<'tcx>>,
300 kind: ty::BorrowKind,
301 restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
303 /// gen_scope indicates where loan is introduced. Typically the
304 /// loan is introduced at the point of the borrow, but in some
305 /// cases, notably method arguments, the loan may be introduced
306 /// only later, once it comes into scope. See also
307 /// `GatherLoanCtxt::compute_gen_scope`.
308 gen_scope: region::CodeExtent,
310 /// kill_scope indicates when the loan goes out of scope. This is
311 /// either when the lifetime expires or when the local variable
312 /// which roots the loan-path goes out of scope, whichever happens
313 /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
314 kill_scope: region::CodeExtent,
316 cause: euv::LoanCause,
319 impl<'tcx> Loan<'tcx> {
320 pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
321 self.loan_path.clone()
326 pub struct LoanPath<'tcx> {
327 kind: LoanPathKind<'tcx>,
331 impl<'tcx> PartialEq for LoanPath<'tcx> {
332 fn eq(&self, that: &LoanPath<'tcx>) -> bool {
333 let r = self.kind == that.kind;
334 debug_assert!(self.ty == that.ty || !r,
335 "Somehow loan paths are equal though their tys are not.");
340 #[derive(PartialEq, Eq, Hash, Debug)]
341 pub enum LoanPathKind<'tcx> {
342 LpVar(ast::NodeId), // `x` in README.md
343 LpUpvar(ty::UpvarId), // `x` captured by-value into closure
344 LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
345 LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem)
348 impl<'tcx> LoanPath<'tcx> {
349 fn new(kind: LoanPathKind<'tcx>, ty: ty::Ty<'tcx>) -> LoanPath<'tcx> {
350 LoanPath { kind: kind, ty: ty }
353 fn to_type(&self) -> ty::Ty<'tcx> { self.ty }
356 // FIXME (pnkfelix): See discussion here
357 // https://github.com/pnkfelix/rust/commit/
358 // b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
359 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
361 // A local, "cleaned" version of `mc::InteriorKind` that drops
362 // information that is not relevant to loan-path analysis. (In
363 // particular, the distinction between how precisely an array-element
364 // is tracked is irrelevant here.)
365 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
366 pub enum InteriorKind {
367 InteriorField(mc::FieldName),
368 InteriorElement(mc::ElementKind),
371 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
372 impl ToInteriorKind for mc::InteriorKind {
373 fn cleaned(self) -> InteriorKind {
375 mc::InteriorField(name) => InteriorField(name),
376 mc::InteriorElement(_, elem_kind) => InteriorElement(elem_kind),
382 // - a pointer dereference (`*LV` in README.md)
383 // - a field reference, with an optional definition of the containing
384 // enum variant (`LV.f` in README.md)
385 // `DefId` is present when the field is part of struct that is in
386 // a variant of an enum. For instance in:
387 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
388 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
389 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
390 pub enum LoanPathElem {
391 LpDeref(mc::PointerKind),
392 LpInterior(Option<DefId>, InteriorKind),
395 pub fn closure_to_block(closure_id: ast::NodeId,
396 tcx: &ty::ctxt) -> ast::NodeId {
397 match tcx.map.get(closure_id) {
398 hir_map::NodeExpr(expr) => match expr.node {
399 hir::ExprClosure(_, _, ref block) => {
403 panic!("encountered non-closure id: {}", closure_id)
406 _ => panic!("encountered non-expr id: {}", closure_id)
410 impl<'tcx> LoanPath<'tcx> {
411 pub fn kill_scope(&self, tcx: &ty::ctxt<'tcx>) -> region::CodeExtent {
413 LpVar(local_id) => tcx.region_maps.var_scope(local_id),
414 LpUpvar(upvar_id) => {
415 let block_id = closure_to_block(upvar_id.closure_expr_id, tcx);
416 tcx.region_maps.node_extent(block_id)
418 LpDowncast(ref base, _) |
419 LpExtend(ref base, _, _) => base.kill_scope(tcx),
423 fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
424 match (&self.kind, &other.kind) {
425 (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
426 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
427 if id == id2 && opt_variant_id == opt_variant_id2 {
428 base.has_fork(&**base2)
432 (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
433 (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&**base),
438 fn depth(&self) -> usize {
440 LpExtend(ref base, _, LpDeref(_)) => base.depth(),
441 LpExtend(ref base, _, LpInterior(_, _)) => base.depth() + 1,
446 fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
447 match (&self.kind, &other.kind) {
448 (&LpExtend(ref base, a, 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.common(&**base2).map(|x| {
453 if base.depth() == xd && base2.depth() == xd {
454 assert_eq!(base.ty, base2.ty);
455 assert_eq!(self.ty, other.ty);
457 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
465 base.common(&**base2)
468 (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
469 (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&**other),
470 (&LpVar(id), &LpVar(id2)) => {
472 assert_eq!(self.ty, other.ty);
473 Some(LoanPath { kind: LpVar(id), ty: self.ty })
478 (&LpUpvar(id), &LpUpvar(id2)) => {
480 assert_eq!(self.ty, other.ty);
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 {
546 err_out_of_scope(ty::Region, ty::Region), // superscope, subscope
547 err_borrowed_pointer_too_short(ty::Region, ty::Region), // loan, ptr
550 // Combination of an error code and the categorization of the expression
553 pub struct BckError<'tcx> {
555 cause: AliasableViolationKind,
560 #[derive(Copy, Clone, Debug, PartialEq)]
561 pub enum AliasableViolationKind {
563 BorrowViolation(euv::LoanCause)
566 #[derive(Copy, Clone, Debug)]
567 pub enum MovedValueUseKind {
572 ///////////////////////////////////////////////////////////////////////////
575 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
576 pub fn is_subregion_of(&self, r_sub: ty::Region, r_sup: ty::Region)
579 self.free_region_map.is_subregion_of(self.tcx, r_sub, r_sup)
582 pub fn report(&self, err: BckError<'tcx>) {
583 // Catch and handle some particular cases.
584 match (&err.code, &err.cause) {
585 (&err_out_of_scope(ty::ReScope(_), ty::ReStatic),
586 &BorrowViolation(euv::ClosureCapture(span))) |
587 (&err_out_of_scope(ty::ReScope(_), ty::ReFree(..)),
588 &BorrowViolation(euv::ClosureCapture(span))) => {
589 return self.report_out_of_scope_escaping_closure_capture(&err, span);
595 let mut db = self.struct_span_err(
597 &self.bckerr_to_string(&err));
598 self.note_and_explain_bckerr(&mut db, err);
602 pub fn report_use_of_moved_value<'b>(&self,
604 use_kind: MovedValueUseKind,
606 the_move: &move_data::Move,
607 moved_lp: &LoanPath<'tcx>,
608 param_env: &ty::ParameterEnvironment<'b,'tcx>) {
609 let verb = match use_kind {
611 MovedInCapture => "capture",
614 let (ol, moved_lp_msg, mut err) = match the_move.kind {
615 move_data::Declared => {
616 let err = struct_span_err!(
617 self.tcx.sess, use_span, E0381,
618 "{} of possibly uninitialized variable: `{}`",
620 self.loan_path_to_string(lp));
622 (self.loan_path_to_string(moved_lp),
627 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
628 // normally generate a rather confusing message:
630 // error: use of moved value: `x.b`
631 // note: `x.a` moved here...
633 // What we want to do instead is get the 'common ancestor' of the two moves and
634 // use that for most of the message instead, giving is something like this:
636 // error: use of moved value: `x`
637 // note: `x` moved here (through moving `x.a`)...
639 let common = moved_lp.common(lp);
640 let has_common = common.is_some();
641 let has_fork = moved_lp.has_fork(lp);
642 let (nl, ol, moved_lp_msg) =
643 if has_fork && has_common {
644 let nl = self.loan_path_to_string(&common.unwrap());
646 let moved_lp_msg = format!(" (through moving `{}`)",
647 self.loan_path_to_string(moved_lp));
648 (nl, ol, moved_lp_msg)
650 (self.loan_path_to_string(lp),
651 self.loan_path_to_string(moved_lp),
655 let partial = moved_lp.depth() > lp.depth();
656 let msg = if !has_fork && partial { "partially " }
657 else if has_fork && !has_common { "collaterally "}
659 let err = struct_span_err!(
660 self.tcx.sess, use_span, E0382,
661 "{} of {}moved value: `{}`",
663 (ol, moved_lp_msg, err)
667 match the_move.kind {
668 move_data::Declared => {}
670 move_data::MoveExpr => {
671 let (expr_ty, expr_span) = match self.tcx
674 Some(hir_map::NodeExpr(expr)) => {
675 (self.tcx.expr_ty_adjusted(&*expr), expr.span)
678 self.tcx.sess.bug(&format!("MoveExpr({}) maps to \
684 let (suggestion, _) =
685 move_suggestion(param_env, expr_span, expr_ty, ("moved by default", ""));
686 // If the two spans are the same, it's because the expression will be evaluated
687 // multiple times. Avoid printing the same span and adjust the wording so it makes
688 // more sense that it's from multiple evalutations.
689 if expr_span == use_span {
691 &format!("`{}` was previously moved here{} because it has type `{}`, \
700 &format!("`{}` moved here{} because it has type `{}`, which is {}",
708 move_data::MovePat => {
709 let pat_ty = self.tcx.node_id_to_type(the_move.id);
710 let span = self.tcx.map.span(the_move.id);
712 &format!("`{}` moved here{} because it has type `{}`, \
713 which is moved by default",
717 match self.tcx.sess.codemap().span_to_snippet(span) {
721 &format!("if you would like to borrow the value instead, \
722 use a `ref` binding as shown:"),
723 format!("ref {}", string));
726 err.fileline_help(span,
727 "use `ref` to override");
732 move_data::Captured => {
733 let (expr_ty, expr_span) = match self.tcx
736 Some(hir_map::NodeExpr(expr)) => {
737 (self.tcx.expr_ty_adjusted(&*expr), expr.span)
740 self.tcx.sess.bug(&format!("Captured({}) maps to \
746 let (suggestion, help) =
747 move_suggestion(param_env,
751 "make a copy and capture that instead to override"));
754 &format!("`{}` moved into closure environment here{} because it \
755 has type `{}`, which is {}",
760 err.fileline_help(expr_span, help);
765 fn move_suggestion<'a,'tcx>(param_env: &ty::ParameterEnvironment<'a,'tcx>,
768 default_msgs: (&'static str, &'static str))
769 -> (&'static str, &'static str) {
772 if ty.moves_by_default(param_env, span) {
774 "perhaps you meant to use `clone()`?")
783 pub fn report_partial_reinitialization_of_uninitialized_structure(
786 lp: &LoanPath<'tcx>) {
788 self.tcx.sess, span, E0383,
789 "partial reinitialization of uninitialized structure `{}`",
790 self.loan_path_to_string(lp));
793 pub fn report_reassigned_immutable_variable(&self,
797 &move_data::Assignment) {
799 self.tcx.sess, span, E0384,
800 "re-assignment of immutable variable `{}`",
801 self.loan_path_to_string(lp))
802 .span_note(assign.span, "prior assignment occurs here")
806 pub fn span_err(&self, s: Span, m: &str) {
807 self.tcx.sess.span_err(s, m);
810 pub fn struct_span_err(&self, s: Span, m: &str) -> DiagnosticBuilder<'a> {
811 self.tcx.sess.struct_span_err(s, m)
814 pub fn struct_span_err_with_code(&self,
818 -> DiagnosticBuilder<'a> {
819 self.tcx.sess.struct_span_err_with_code(s, msg, code)
822 pub fn span_err_with_code(&self, s: Span, msg: &str, code: &str) {
823 self.tcx.sess.span_err_with_code(s, msg, code);
826 pub fn span_bug(&self, s: Span, m: &str) {
827 self.tcx.sess.span_bug(s, m);
830 pub fn bckerr_to_string(&self, err: &BckError<'tcx>) -> String {
833 let descr = match err.cmt.note {
834 mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
835 self.cmt_to_string(&*err.cmt)
837 _ => match opt_loan_path(&err.cmt) {
840 err.cmt.mutbl.to_user_str(),
841 self.cmt_to_string(&*err.cmt))
844 format!("{} {} `{}`",
845 err.cmt.mutbl.to_user_str(),
846 self.cmt_to_string(&*err.cmt),
847 self.loan_path_to_string(&*lp))
853 MutabilityViolation => {
854 format!("cannot assign to {}", descr)
856 BorrowViolation(euv::ClosureCapture(_)) => {
857 format!("closure cannot assign to {}", descr)
859 BorrowViolation(euv::OverloadedOperator) |
860 BorrowViolation(euv::AddrOf) |
861 BorrowViolation(euv::RefBinding) |
862 BorrowViolation(euv::AutoRef) |
863 BorrowViolation(euv::AutoUnsafe) |
864 BorrowViolation(euv::ForLoop) |
865 BorrowViolation(euv::MatchDiscriminant) => {
866 format!("cannot borrow {} as mutable", descr)
868 BorrowViolation(euv::ClosureInvocation) => {
869 self.tcx.sess.span_bug(err.span,
870 "err_mutbl with a closure invocation");
874 err_out_of_scope(..) => {
875 let msg = match opt_loan_path(&err.cmt) {
876 None => "borrowed value".to_string(),
878 format!("`{}`", self.loan_path_to_string(&*lp))
881 format!("{} does not live long enough", msg)
883 err_borrowed_pointer_too_short(..) => {
884 let descr = self.cmt_to_path_or_string(&err.cmt);
885 format!("lifetime of {} is too short to guarantee \
886 its contents can be safely reborrowed",
892 pub fn report_aliasability_violation(&self,
894 kind: AliasableViolationKind,
895 cause: mc::AliasableReason) {
896 let mut is_closure = false;
897 let prefix = match kind {
898 MutabilityViolation => {
899 "cannot assign to data"
901 BorrowViolation(euv::ClosureCapture(_)) |
902 BorrowViolation(euv::OverloadedOperator) |
903 BorrowViolation(euv::AddrOf) |
904 BorrowViolation(euv::AutoRef) |
905 BorrowViolation(euv::AutoUnsafe) |
906 BorrowViolation(euv::RefBinding) |
907 BorrowViolation(euv::MatchDiscriminant) => {
908 "cannot borrow data mutably"
911 BorrowViolation(euv::ClosureInvocation) => {
916 BorrowViolation(euv::ForLoop) => {
921 let mut err = match cause {
922 mc::AliasableOther => {
924 self.tcx.sess, span, E0385,
925 "{} in an aliasable location", prefix)
927 mc::AliasableReason::UnaliasableImmutable => {
929 self.tcx.sess, span, E0386,
930 "{} in an immutable container", prefix)
932 mc::AliasableClosure(id) => {
933 let mut err = struct_span_err!(
934 self.tcx.sess, span, E0387,
935 "{} in a captured outer variable in an `Fn` closure", prefix);
936 if let BorrowViolation(euv::ClosureCapture(_)) = kind {
937 // The aliasability violation with closure captures can
938 // happen for nested closures, so we know the enclosing
939 // closure incorrectly accepts an `Fn` while it needs to
941 span_help!(&mut err, self.tcx.map.span(id),
942 "consider changing this to accept closures that implement `FnMut`");
944 span_help!(&mut err, self.tcx.map.span(id),
945 "consider changing this closure to take self by mutable reference");
949 mc::AliasableStatic |
950 mc::AliasableStaticMut => {
952 self.tcx.sess, span, E0388,
953 "{} in a static location", prefix)
955 mc::AliasableBorrowed => {
957 self.tcx.sess, span, E0389,
958 "{} in a `&` reference", prefix)
963 err.fileline_help(span,
964 "closures behind references must be called via `&mut`");
969 fn report_out_of_scope_escaping_closure_capture(&self,
970 err: &BckError<'tcx>,
973 let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
976 match self.tcx.sess.codemap().span_to_snippet(err.span) {
977 Ok(string) => format!("move {}", string),
978 Err(_) => format!("move |<args>| <body>")
981 struct_span_err!(self.tcx.sess, err.span, E0373,
982 "closure may outlive the current function, \
984 which is owned by the current function",
986 .span_note(capture_span,
987 &format!("{} is borrowed here",
989 .span_suggestion(err.span,
990 &format!("to force the closure to take ownership of {} \
991 (and any other referenced variables), \
992 use the `move` keyword, as shown:",
998 pub fn note_and_explain_bckerr(&self, db: &mut DiagnosticBuilder, err: BckError<'tcx>) {
1002 match err.cmt.note {
1003 mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1004 // If this is an `Fn` closure, it simply can't mutate upvars.
1005 // If it's an `FnMut` closure, the original variable was declared immutable.
1006 // We need to determine which is the case here.
1007 let kind = match err.cmt.upvar().unwrap().cat {
1008 Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1011 if kind == ty::FnClosureKind {
1013 self.tcx.map.span(upvar_id.closure_expr_id),
1014 "consider changing this closure to take \
1015 self by mutable reference");
1019 if let Categorization::Local(local_id) = err.cmt.cat {
1020 let span = self.tcx.map.span(local_id);
1021 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
1024 &format!("to make the {} mutable, use `mut` as shown:",
1025 self.cmt_to_string(&err.cmt)),
1026 format!("mut {}", snippet));
1033 err_out_of_scope(super_scope, sub_scope) => {
1034 self.tcx.note_and_explain_region(
1036 "reference must be valid for ",
1039 self.tcx.note_and_explain_region(
1041 "...but borrowed value is only valid for ",
1044 if let Some(span) = statement_scope_span(self.tcx, super_scope) {
1046 "consider using a `let` binding to increase its lifetime");
1050 err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1051 let descr = match opt_loan_path(&err.cmt) {
1053 format!("`{}`", self.loan_path_to_string(&*lp))
1055 None => self.cmt_to_string(&*err.cmt),
1057 self.tcx.note_and_explain_region(
1059 &format!("{} would have to be valid for ",
1063 self.tcx.note_and_explain_region(
1065 &format!("...but {} is only valid for ", descr),
1072 pub fn append_loan_path_to_string(&self,
1073 loan_path: &LoanPath<'tcx>,
1075 match loan_path.kind {
1076 LpUpvar(ty::UpvarId{ var_id: id, closure_expr_id: _ }) |
1078 out.push_str(&self.tcx.local_var_name_str(id));
1081 LpDowncast(ref lp_base, variant_def_id) => {
1083 self.append_loan_path_to_string(&**lp_base, out);
1084 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1085 out.push_str(&self.tcx.item_path_str(variant_def_id));
1090 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(fname))) => {
1091 self.append_autoderefd_loan_path_to_string(&**lp_base, out);
1093 mc::NamedField(fname) => {
1095 out.push_str(&fname.as_str());
1097 mc::PositionalField(idx) => {
1099 out.push_str(&idx.to_string());
1104 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement(..))) => {
1105 self.append_autoderefd_loan_path_to_string(&**lp_base, out);
1106 out.push_str("[..]");
1109 LpExtend(ref lp_base, _, LpDeref(_)) => {
1111 self.append_loan_path_to_string(&**lp_base, out);
1116 pub fn append_autoderefd_loan_path_to_string(&self,
1117 loan_path: &LoanPath<'tcx>,
1119 match loan_path.kind {
1120 LpExtend(ref lp_base, _, LpDeref(_)) => {
1121 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1122 // rules would normally allow users to omit the `*x`.
1123 // So just serialize such paths to `x.f` or x[3]` respectively.
1124 self.append_autoderefd_loan_path_to_string(&**lp_base, out)
1127 LpDowncast(ref lp_base, variant_def_id) => {
1129 self.append_autoderefd_loan_path_to_string(&**lp_base, out);
1131 out.push_str(&self.tcx.item_path_str(variant_def_id));
1135 LpVar(..) | LpUpvar(..) | LpExtend(_, _, LpInterior(..)) => {
1136 self.append_loan_path_to_string(loan_path, out)
1141 pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1142 let mut result = String::new();
1143 self.append_loan_path_to_string(loan_path, &mut result);
1147 pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1148 cmt.descriptive_string(self.tcx)
1151 pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt<'tcx>) -> String {
1152 match opt_loan_path(cmt) {
1153 Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1154 None => self.cmt_to_string(cmt),
1159 fn statement_scope_span(tcx: &ty::ctxt, region: ty::Region) -> Option<Span> {
1161 ty::ReScope(scope) => {
1162 match tcx.map.find(scope.node_id(&tcx.region_maps)) {
1163 Some(hir_map::NodeStmt(stmt)) => Some(stmt.span),
1171 impl BitwiseOperator for LoanDataFlowOperator {
1173 fn join(&self, succ: usize, pred: usize) -> usize {
1174 succ | pred // loans from both preds are in scope
1178 impl DataFlowOperator for LoanDataFlowOperator {
1180 fn initial_value(&self) -> bool {
1181 false // no loans in scope by default
1185 impl<'tcx> fmt::Debug for InteriorKind {
1186 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1188 InteriorField(mc::NamedField(fld)) => write!(f, "{}", fld),
1189 InteriorField(mc::PositionalField(i)) => write!(f, "#{}", i),
1190 InteriorElement(..) => write!(f, "[]"),
1195 impl<'tcx> fmt::Debug for Loan<'tcx> {
1196 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1197 write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1203 self.restricted_paths)
1207 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1208 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1211 write!(f, "$({})", ty::tls::with(|tcx| tcx.map.node_to_string(id)))
1214 LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => {
1215 let s = ty::tls::with(|tcx| tcx.map.node_to_string(var_id));
1216 write!(f, "$({} captured by id={})", s, closure_expr_id)
1219 LpDowncast(ref lp, variant_def_id) => {
1220 let variant_str = if variant_def_id.is_local() {
1221 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1223 format!("{:?}", variant_def_id)
1225 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1228 LpExtend(ref lp, _, LpDeref(_)) => {
1229 write!(f, "{:?}.*", lp)
1232 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1233 write!(f, "{:?}.{:?}", lp, interior)
1239 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1240 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1243 write!(f, "$({})", ty::tls::with(|tcx| tcx.map.node_to_user_string(id)))
1246 LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => {
1247 let s = ty::tls::with(|tcx| tcx.map.node_to_user_string(var_id));
1248 write!(f, "$({} captured by closure)", s)
1251 LpDowncast(ref lp, variant_def_id) => {
1252 let variant_str = if variant_def_id.is_local() {
1253 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1255 format!("{:?}", variant_def_id)
1257 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1260 LpExtend(ref lp, _, LpDeref(_)) => {
1261 write!(f, "{}.*", lp)
1264 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1265 write!(f, "{}.{:?}", lp, interior)