1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! See The Book chapter on the borrow checker for more details.
13 #![allow(non_camel_case_types)]
15 pub use self::LoanPathKind::*;
16 pub use self::LoanPathElem::*;
17 pub use self::bckerr_code::*;
18 pub use self::AliasableViolationKind::*;
19 pub use self::MovedValueUseKind::*;
21 use self::InteriorKind::*;
23 use rustc::hir::HirId;
25 use rustc::hir::map::blocks::FnLikeNode;
27 use rustc::middle::borrowck::{BorrowCheckResult, SignalledError};
28 use rustc::hir::def_id::{DefId, LocalDefId};
29 use rustc::middle::expr_use_visitor as euv;
30 use rustc::middle::mem_categorization as mc;
31 use rustc::middle::mem_categorization::Categorization;
32 use rustc::middle::mem_categorization::ImmutabilityBlame;
33 use rustc::middle::region;
34 use rustc::middle::free_region::RegionRelations;
35 use rustc::ty::{self, Ty, TyCtxt};
36 use rustc::ty::query::Providers;
37 use rustc_mir::util::borrowck_errors::{BorrowckErrors, Origin};
38 use rustc_mir::util::suggest_ref_mut;
39 use rustc::util::nodemap::FxHashSet;
42 use std::cell::{Cell, RefCell};
45 use rustc_data_structures::sync::Lrc;
46 use std::hash::{Hash, Hasher};
48 use syntax_pos::{MultiSpan, Span};
49 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
52 use rustc::hir::intravisit::{self, Visitor};
54 use dataflow::{DataFlowContext, BitwiseOperator, DataFlowOperator, KillFrom};
64 #[derive(Clone, Copy)]
65 pub struct LoanDataFlowOperator;
67 pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
69 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
70 tcx.par_body_owners(|body_owner_def_id| {
71 tcx.borrowck(body_owner_def_id);
75 pub fn provide(providers: &mut Providers) {
76 *providers = Providers {
82 /// Collection of conclusions determined via borrow checker analyses.
83 pub struct AnalysisData<'a, 'tcx: 'a> {
84 pub all_loans: Vec<Loan<'tcx>>,
85 pub loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>,
86 pub move_data: move_data::FlowedMoveData<'a, 'tcx>,
89 fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId)
90 -> Lrc<BorrowCheckResult>
92 assert!(tcx.use_ast_borrowck() || tcx.migrate_borrowck());
94 debug!("borrowck(body_owner_def_id={:?})", owner_def_id);
96 let owner_id = tcx.hir().as_local_node_id(owner_def_id).unwrap();
98 match tcx.hir().get(owner_id) {
100 Node::Variant(_) => {
101 // We get invoked with anything that has MIR, but some of
102 // those things (notably the synthesized constructors from
103 // tuple structs/variants) do not have an associated body
104 // and do not need borrowchecking.
105 return Lrc::new(BorrowCheckResult {
106 used_mut_nodes: Default::default(),
107 signalled_any_error: SignalledError::NoErrorsSeen,
113 let body_id = tcx.hir().body_owned_by(owner_id);
114 let tables = tcx.typeck_tables_of(owner_def_id);
115 let region_scope_tree = tcx.region_scope_tree(owner_def_id);
116 let body = tcx.hir().body(body_id);
117 let mut bccx = BorrowckCtxt {
123 used_mut_nodes: Default::default(),
124 signalled_any_error: Cell::new(SignalledError::NoErrorsSeen),
127 // Eventually, borrowck will always read the MIR, but at the
128 // moment we do not. So, for now, we always force MIR to be
129 // constructed for a given fn, since this may result in errors
130 // being reported and we want that to happen.
132 // Note that `mir_validated` is a "stealable" result; the
133 // thief, `optimized_mir()`, forces borrowck, so we know that
134 // is not yet stolen.
135 ty::query::queries::mir_validated::ensure(tcx, owner_def_id);
137 // option dance because you can't capture an uninitialized variable
140 if let Some(AnalysisData { all_loans,
142 move_data: flowed_moves }) =
143 build_borrowck_dataflow_data(&mut bccx, false, body_id,
145 cfg = Some(cfg::CFG::new(bccx.tcx, &body));
146 cfg.as_mut().unwrap()
149 check_loans::check_loans(&mut bccx, &loan_dfcx, &flowed_moves, &all_loans, body);
152 if !tcx.use_mir_borrowck() {
153 unused::check(&mut bccx, body);
156 Lrc::new(BorrowCheckResult {
157 used_mut_nodes: bccx.used_mut_nodes.into_inner(),
158 signalled_any_error: bccx.signalled_any_error.into_inner(),
162 fn build_borrowck_dataflow_data<'a, 'c, 'tcx, F>(this: &mut BorrowckCtxt<'a, 'tcx>,
163 force_analysis: bool,
164 body_id: hir::BodyId,
166 -> Option<AnalysisData<'a, 'tcx>>
167 where F: FnOnce(&mut BorrowckCtxt<'a, 'tcx>) -> &'c cfg::CFG
169 // Check the body of fn items.
172 let mut visitor = intravisit::IdRangeComputingVisitor::new(&tcx.hir());
173 visitor.visit_body(this.body);
176 let (all_loans, move_data) =
177 gather_loans::gather_loans_in_fn(this, body_id);
179 if !force_analysis && move_data.is_empty() && all_loans.is_empty() {
180 // large arrays of data inserted as constants can take a lot of
181 // time and memory to borrow-check - see issue #36799. However,
182 // they don't have places, so no borrow-check is actually needed.
183 // Recognize that case and skip borrow-checking.
184 debug!("skipping loan propagation for {:?} because of no loans", body_id);
187 debug!("propagating loans in {:?}", body_id);
190 let cfg = get_cfg(this);
192 DataFlowContext::new(this.tcx,
196 LoanDataFlowOperator,
199 for (loan_idx, loan) in all_loans.iter().enumerate() {
200 loan_dfcx.add_gen(loan.gen_scope.item_local_id(), loan_idx);
201 loan_dfcx.add_kill(KillFrom::ScopeEnd,
202 loan.kill_scope.item_local_id(),
205 loan_dfcx.add_kills_from_flow_exits(cfg);
206 loan_dfcx.propagate(cfg, this.body);
208 let flowed_moves = move_data::FlowedMoveData::new(move_data,
214 Some(AnalysisData { all_loans,
216 move_data:flowed_moves })
219 /// Accessor for introspective clients inspecting `AnalysisData` and
220 /// the `BorrowckCtxt` itself , e.g., the flowgraph visualizer.
221 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
222 tcx: TyCtxt<'a, 'tcx, 'tcx>,
223 body_id: hir::BodyId,
225 -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
227 let owner_id = tcx.hir().body_owner(body_id);
228 let owner_def_id = tcx.hir().local_def_id(owner_id);
229 let tables = tcx.typeck_tables_of(owner_def_id);
230 let region_scope_tree = tcx.region_scope_tree(owner_def_id);
231 let body = tcx.hir().body(body_id);
232 let mut bccx = BorrowckCtxt {
238 used_mut_nodes: Default::default(),
239 signalled_any_error: Cell::new(SignalledError::NoErrorsSeen),
242 let dataflow_data = build_borrowck_dataflow_data(&mut bccx, true, body_id, |_| cfg);
243 (bccx, dataflow_data.unwrap())
246 // ----------------------------------------------------------------------
249 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
250 tcx: TyCtxt<'a, 'tcx, 'tcx>,
252 // tables for the current thing we are checking; set to
253 // Some in `borrowck_fn` and cleared later
254 tables: &'a ty::TypeckTables<'tcx>,
256 region_scope_tree: Lrc<region::ScopeTree>,
260 body: &'tcx hir::Body,
262 used_mut_nodes: RefCell<FxHashSet<HirId>>,
264 signalled_any_error: Cell<SignalledError>,
268 impl<'a, 'tcx: 'a> BorrowckCtxt<'a, 'tcx> {
269 fn signal_error(&self) {
270 self.signalled_any_error.set(SignalledError::SawSomeError);
274 impl<'a, 'b, 'tcx: 'b> BorrowckErrors<'a> for &'a BorrowckCtxt<'b, 'tcx> {
275 fn struct_span_err_with_code<S: Into<MultiSpan>>(self,
279 -> DiagnosticBuilder<'a>
281 self.tcx.sess.struct_span_err_with_code(sp, msg, code)
284 fn struct_span_err<S: Into<MultiSpan>>(self,
287 -> DiagnosticBuilder<'a>
289 self.tcx.sess.struct_span_err(sp, msg)
292 fn cancel_if_wrong_origin(self,
293 mut diag: DiagnosticBuilder<'a>,
295 -> DiagnosticBuilder<'a>
297 if !o.should_emit_errors(self.tcx.borrowck_mode()) {
298 self.tcx.sess.diagnostic().cancel(&mut diag);
304 ///////////////////////////////////////////////////////////////////////////
305 // Loans and loan paths
307 /// Record of a loan that was issued.
308 pub struct Loan<'tcx> {
310 loan_path: Rc<LoanPath<'tcx>>,
311 kind: ty::BorrowKind,
312 restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
314 /// gen_scope indicates where loan is introduced. Typically the
315 /// loan is introduced at the point of the borrow, but in some
316 /// cases, notably method arguments, the loan may be introduced
317 /// only later, once it comes into scope. See also
318 /// `GatherLoanCtxt::compute_gen_scope`.
319 gen_scope: region::Scope,
321 /// kill_scope indicates when the loan goes out of scope. This is
322 /// either when the lifetime expires or when the local variable
323 /// which roots the loan-path goes out of scope, whichever happens
324 /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
325 kill_scope: region::Scope,
327 cause: euv::LoanCause,
330 impl<'tcx> Loan<'tcx> {
331 pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
332 self.loan_path.clone()
337 pub struct LoanPath<'tcx> {
338 kind: LoanPathKind<'tcx>,
342 impl<'tcx> PartialEq for LoanPath<'tcx> {
343 fn eq(&self, that: &LoanPath<'tcx>) -> bool {
344 self.kind == that.kind
348 impl<'tcx> Hash for LoanPath<'tcx> {
349 fn hash<H: Hasher>(&self, state: &mut H) {
350 self.kind.hash(state);
354 #[derive(PartialEq, Eq, Hash, Debug)]
355 pub enum LoanPathKind<'tcx> {
356 LpVar(ast::NodeId), // `x` in README.md
357 LpUpvar(ty::UpvarId), // `x` captured by-value into closure
358 LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
359 LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem<'tcx>)
362 impl<'tcx> LoanPath<'tcx> {
363 fn new(kind: LoanPathKind<'tcx>, ty: Ty<'tcx>) -> LoanPath<'tcx> {
364 LoanPath { kind: kind, ty: ty }
367 fn to_type(&self) -> Ty<'tcx> { self.ty }
369 fn has_downcast(&self) -> bool {
371 LpDowncast(_, _) => true,
372 LpExtend(ref lp, _, LpInterior(_, _)) => {
380 // FIXME (pnkfelix): See discussion here
381 // https://github.com/pnkfelix/rust/commit/
382 // b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
383 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
385 // A local, "cleaned" version of `mc::InteriorKind` that drops
386 // information that is not relevant to loan-path analysis. (In
387 // particular, the distinction between how precisely an array-element
388 // is tracked is irrelevant here.)
389 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
390 pub enum InteriorKind {
391 InteriorField(mc::FieldIndex),
395 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
396 impl ToInteriorKind for mc::InteriorKind {
397 fn cleaned(self) -> InteriorKind {
399 mc::InteriorField(name) => InteriorField(name),
400 mc::InteriorElement(_) => InteriorElement,
406 // - a pointer dereference (`*P` in README.md)
407 // - a field reference, with an optional definition of the containing
408 // enum variant (`P.f` in README.md)
409 // `DefId` is present when the field is part of struct that is in
410 // a variant of an enum. For instance in:
411 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
412 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
413 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
414 pub enum LoanPathElem<'tcx> {
415 LpDeref(mc::PointerKind<'tcx>),
416 LpInterior(Option<DefId>, InteriorKind),
419 fn closure_to_block(closure_id: LocalDefId,
420 tcx: TyCtxt) -> ast::NodeId {
421 let closure_id = tcx.hir().local_def_id_to_node_id(closure_id);
422 match tcx.hir().get(closure_id) {
423 Node::Expr(expr) => match expr.node {
424 hir::ExprKind::Closure(.., body_id, _, _) => {
428 bug!("encountered non-closure id: {}", closure_id)
431 _ => bug!("encountered non-expr id: {}", closure_id)
435 impl<'a, 'tcx> LoanPath<'tcx> {
436 pub fn kill_scope(&self, bccx: &BorrowckCtxt<'a, 'tcx>) -> region::Scope {
439 let hir_id = bccx.tcx.hir().node_to_hir_id(local_id);
440 bccx.region_scope_tree.var_scope(hir_id.local_id)
442 LpUpvar(upvar_id) => {
443 let block_id = closure_to_block(upvar_id.closure_expr_id, bccx.tcx);
444 let hir_id = bccx.tcx.hir().node_to_hir_id(block_id);
445 region::Scope { id: hir_id.local_id, data: region::ScopeData::Node }
447 LpDowncast(ref base, _) |
448 LpExtend(ref base, ..) => base.kill_scope(bccx),
452 fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
453 match (&self.kind, &other.kind) {
454 (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
455 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
456 if id == id2 && opt_variant_id == opt_variant_id2 {
457 base.has_fork(&base2)
461 (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
462 (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&base),
467 fn depth(&self) -> usize {
469 LpExtend(ref base, _, LpDeref(_)) => base.depth(),
470 LpExtend(ref base, _, LpInterior(..)) => base.depth() + 1,
475 fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
476 match (&self.kind, &other.kind) {
477 (&LpExtend(ref base, a, LpInterior(opt_variant_id, id)),
478 &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) => {
479 if id == id2 && opt_variant_id == opt_variant_id2 {
480 base.common(&base2).map(|x| {
482 if base.depth() == xd && base2.depth() == xd {
484 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
495 (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
496 (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&other),
497 (&LpVar(id), &LpVar(id2)) => {
499 Some(LoanPath { kind: LpVar(id), ty: self.ty })
504 (&LpUpvar(id), &LpUpvar(id2)) => {
506 Some(LoanPath { kind: LpUpvar(id), ty: self.ty })
516 // Avoid "cannot borrow immutable field `self.x` as mutable" as that implies that a field *can* be
517 // mutable independently of the struct it belongs to. (#35937)
518 pub fn opt_loan_path_is_field<'tcx>(cmt: &mc::cmt_<'tcx>) -> (Option<Rc<LoanPath<'tcx>>>, bool) {
519 let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
522 Categorization::Rvalue(..) |
523 Categorization::ThreadLocal(..) |
524 Categorization::StaticItem => {
528 Categorization::Local(id) => {
529 (Some(new_lp(LpVar(id))), false)
532 Categorization::Upvar(mc::Upvar { id, .. }) => {
533 (Some(new_lp(LpUpvar(id))), false)
536 Categorization::Deref(ref cmt_base, pk) => {
537 let lp = opt_loan_path_is_field(cmt_base);
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 let lp = opt_loan_path_is_field(cmt_base);
556 new_lp(LpDowncast(lp, variant_def_id))
562 /// Computes the `LoanPath` (if any) for a `cmt`.
563 /// Note that this logic is somewhat duplicated in
564 /// the method `compute()` found in `gather_loans::restrictions`,
565 /// which allows it to share common loan path pieces as it
566 /// traverses the CMT.
567 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt_<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
568 opt_loan_path_is_field(cmt).0
571 ///////////////////////////////////////////////////////////////////////////
574 // Errors that can occur
575 #[derive(Debug, PartialEq)]
576 pub enum bckerr_code<'tcx> {
578 /// superscope, subscope, loan cause
579 err_out_of_scope(ty::Region<'tcx>, ty::Region<'tcx>, euv::LoanCause),
580 err_borrowed_pointer_too_short(ty::Region<'tcx>, ty::Region<'tcx>), // loan, ptr
583 // Combination of an error code and the categorization of the expression
585 #[derive(Debug, PartialEq)]
586 pub struct BckError<'c, 'tcx: 'c> {
588 cause: AliasableViolationKind,
589 cmt: &'c mc::cmt_<'tcx>,
590 code: bckerr_code<'tcx>
593 #[derive(Copy, Clone, Debug, PartialEq)]
594 pub enum AliasableViolationKind {
596 BorrowViolation(euv::LoanCause)
599 #[derive(Copy, Clone, Debug)]
600 pub enum MovedValueUseKind {
605 ///////////////////////////////////////////////////////////////////////////
608 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
609 pub fn is_subregion_of(&self,
610 r_sub: ty::Region<'tcx>,
611 r_sup: ty::Region<'tcx>)
614 let region_rels = RegionRelations::new(self.tcx,
616 &self.region_scope_tree,
617 &self.tables.free_region_map);
618 region_rels.is_subregion_of(r_sub, r_sup)
621 pub fn report(&self, err: BckError<'a, 'tcx>) {
622 // Catch and handle some particular cases.
623 match (&err.code, &err.cause) {
624 (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _),
625 &BorrowViolation(euv::ClosureCapture(span))) |
626 (&err_out_of_scope(&ty::ReScope(_), &ty::ReEarlyBound(..), _),
627 &BorrowViolation(euv::ClosureCapture(span))) |
628 (&err_out_of_scope(&ty::ReScope(_), &ty::ReFree(..), _),
629 &BorrowViolation(euv::ClosureCapture(span))) => {
630 return self.report_out_of_scope_escaping_closure_capture(&err, span);
635 self.report_bckerr(&err);
638 pub fn report_use_of_moved_value(&self,
640 use_kind: MovedValueUseKind,
642 the_move: &move_data::Move,
643 moved_lp: &LoanPath<'tcx>) {
644 let (verb, verb_participle) = match use_kind {
645 MovedInUse => ("use", "used"),
646 MovedInCapture => ("capture", "captured"),
649 let (_ol, _moved_lp_msg, mut err, need_note) = match the_move.kind {
650 move_data::Declared => {
651 // If this is an uninitialized variable, just emit a simple warning
653 self.cannot_act_on_uninitialized_variable(use_span,
655 &self.loan_path_to_string(lp),
657 .span_label(use_span, format!("use of possibly uninitialized `{}`",
658 self.loan_path_to_string(lp)))
664 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
665 // normally generate a rather confusing message:
667 // error: use of moved value: `x.b`
668 // note: `x.a` moved here...
670 // What we want to do instead is get the 'common ancestor' of the two moves and
671 // use that for most of the message instead, giving is something like this:
673 // error: use of moved value: `x`
674 // note: `x` moved here (through moving `x.a`)...
676 let common = moved_lp.common(lp);
677 let has_common = common.is_some();
678 let has_fork = moved_lp.has_fork(lp);
679 let (nl, ol, moved_lp_msg) =
680 if has_fork && has_common {
681 let nl = self.loan_path_to_string(&common.unwrap());
683 let moved_lp_msg = format!(" (through moving `{}`)",
684 self.loan_path_to_string(moved_lp));
685 (nl, ol, moved_lp_msg)
687 (self.loan_path_to_string(lp),
688 self.loan_path_to_string(moved_lp),
692 let partial = moved_lp.depth() > lp.depth();
693 let msg = if !has_fork && partial { "partially " }
694 else if has_fork && !has_common { "collaterally "}
696 let mut err = self.cannot_act_on_moved_value(use_span,
701 let need_note = match lp.ty.sty {
702 ty::Closure(id, _) => {
703 let node_id = self.tcx.hir().as_local_node_id(id).unwrap();
704 let hir_id = self.tcx.hir().node_to_hir_id(node_id);
705 if let Some((span, name)) = self.tables.closure_kind_origins().get(hir_id) {
706 err.span_note(*span, &format!(
707 "closure cannot be invoked more than once because \
708 it moves the variable `{}` out of its environment",
718 (ol, moved_lp_msg, err, need_note)
722 // Get type of value and span where it was previously
724 let node_id = self.tcx.hir().hir_to_node_id(hir::HirId {
725 owner: self.body.value.hir_id.owner,
726 local_id: the_move.id
728 let (move_span, move_note) = match the_move.kind {
729 move_data::Declared => {
733 move_data::MoveExpr |
734 move_data::MovePat => (self.tcx.hir().span(node_id), ""),
736 move_data::Captured =>
737 (match self.tcx.hir().expect_expr(node_id).node {
738 hir::ExprKind::Closure(.., fn_decl_span, _) => fn_decl_span,
739 ref r => bug!("Captured({:?}) maps to non-closure: {:?}",
741 }, " (into closure)"),
744 // Annotate the use and the move in the span. Watch out for
745 // the case where the use and the move are the same. This
746 // means the use is in a loop.
747 err = if use_span == move_span {
750 format!("value moved{} here in previous iteration of loop",
754 err.span_label(use_span, format!("value {} here after move", verb_participle));
755 err.span_label(move_span, format!("value moved{} here", move_note));
761 "move occurs because {} has type `{}`, which does not implement the `Copy` trait",
762 if moved_lp.has_downcast() {
763 "the value".to_string()
765 format!("`{}`", self.loan_path_to_string(moved_lp))
770 // Note: we used to suggest adding a `ref binding` or calling
771 // `clone` but those suggestions have been removed because
772 // they are often not what you actually want to do, and were
773 // not considered particularly helpful.
779 pub fn report_partial_reinitialization_of_uninitialized_structure(
782 lp: &LoanPath<'tcx>) {
783 self.cannot_partially_reinit_an_uninit_struct(span,
784 &self.loan_path_to_string(lp),
790 pub fn report_reassigned_immutable_variable(&self,
794 &move_data::Assignment) {
795 let mut err = self.cannot_reassign_immutable(span,
796 &self.loan_path_to_string(lp),
799 err.span_label(span, "cannot assign twice to immutable variable");
800 if span != assign.span {
801 err.span_label(assign.span, format!("first assignment to `{}`",
802 self.loan_path_to_string(lp)));
808 fn report_bckerr(&self, err: &BckError<'a, 'tcx>) {
809 let error_span = err.span.clone();
813 let descr: Cow<'static, str> = match err.cmt.note {
814 mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
815 self.cmt_to_cow_str(&err.cmt)
817 _ => match opt_loan_path_is_field(&err.cmt) {
819 format!("{} of {} binding",
820 self.cmt_to_cow_str(&err.cmt),
821 err.cmt.mutbl.to_user_str()).into()
826 err.cmt.mutbl.to_user_str(),
827 self.cmt_to_cow_str(&err.cmt)).into()
830 (Some(lp), true) => {
831 format!("{} `{}` of {} binding",
832 self.cmt_to_cow_str(&err.cmt),
833 self.loan_path_to_string(&lp),
834 err.cmt.mutbl.to_user_str()).into()
836 (Some(lp), false) => {
837 format!("{} {} `{}`",
838 err.cmt.mutbl.to_user_str(),
839 self.cmt_to_cow_str(&err.cmt),
840 self.loan_path_to_string(&lp)).into()
845 let mut db = match err.cause {
846 MutabilityViolation => {
847 let mut db = self.cannot_assign(error_span, &descr, Origin::Ast);
848 if let mc::NoteClosureEnv(upvar_id) = err.cmt.note {
849 let node_id = self.tcx.hir().hir_to_node_id(upvar_id.var_path.hir_id);
850 let sp = self.tcx.hir().span(node_id);
851 let fn_closure_msg = "`Fn` closures cannot capture their enclosing \
852 environment for modifications";
853 match (self.tcx.sess.source_map().span_to_snippet(sp), &err.cmt.cat) {
854 (_, &Categorization::Upvar(mc::Upvar {
855 kind: ty::ClosureKind::Fn, ..
857 db.note(fn_closure_msg);
858 // we should point at the cause for this closure being
859 // identified as `Fn` (like in signature of method this
860 // closure was passed into)
862 (Ok(ref snippet), ref cat) => {
863 let msg = &format!("consider making `{}` mutable", snippet);
864 let suggestion = format!("mut {}", snippet);
866 if let &Categorization::Deref(ref cmt, _) = cat {
867 if let Categorization::Upvar(mc::Upvar {
868 kind: ty::ClosureKind::Fn, ..
870 db.note(fn_closure_msg);
872 db.span_suggestion_with_applicability(
876 Applicability::Unspecified,
880 db.span_suggestion_with_applicability(
884 Applicability::Unspecified,
889 db.span_help(sp, "consider making this binding mutable");
896 BorrowViolation(euv::ClosureCapture(_)) => {
897 self.closure_cannot_assign_to_borrowed(error_span, &descr, Origin::Ast)
899 BorrowViolation(euv::OverloadedOperator) |
900 BorrowViolation(euv::AddrOf) |
901 BorrowViolation(euv::RefBinding) |
902 BorrowViolation(euv::AutoRef) |
903 BorrowViolation(euv::AutoUnsafe) |
904 BorrowViolation(euv::ForLoop) |
905 BorrowViolation(euv::MatchDiscriminant) => {
906 self.cannot_borrow_path_as_mutable(error_span, &descr, Origin::Ast)
908 BorrowViolation(euv::ClosureInvocation) => {
910 "err_mutbl with a closure invocation");
914 // We add a special note about `IndexMut`, if the source of this error
915 // is the fact that `Index` is implemented, but `IndexMut` is not. Needing
916 // to implement two traits for "one operator" is not very intuitive for
918 if err.cmt.note == mc::NoteIndex {
919 let node_id = self.tcx.hir().hir_to_node_id(err.cmt.hir_id);
920 let node = self.tcx.hir().get(node_id);
922 // This pattern probably always matches.
924 hir::Expr { node: hir::ExprKind::Index(lhs, _), ..}
926 let ty = self.tables.expr_ty(lhs);
929 "trait `IndexMut` is required to modify indexed content, but \
930 it is not implemented for `{}`",
936 self.note_and_explain_mutbl_error(&mut db, &err, &error_span);
937 self.note_immutability_blame(
939 err.cmt.immutability_blame(),
940 self.tcx.hir().hir_to_node_id(err.cmt.hir_id)
945 err_out_of_scope(super_scope, sub_scope, cause) => {
946 let msg = match opt_loan_path(&err.cmt) {
947 None => "borrowed value".to_string(),
949 format!("`{}`", self.loan_path_to_string(&lp))
953 let mut db = self.path_does_not_live_long_enough(error_span, &msg, Origin::Ast);
954 let value_kind = match err.cmt.cat {
955 mc::Categorization::Rvalue(..) => "temporary value",
956 _ => "borrowed value",
959 let is_closure = match cause {
960 euv::ClosureCapture(s) => {
961 // The primary span starts out as the closure creation point.
962 // Change the primary span here to highlight the use of the variable
963 // in the closure, because it seems more natural. Highlight
964 // closure creation point as a secondary span.
965 match db.span.primary_span() {
967 db.span = MultiSpan::from_span(s);
968 db.span_label(primary, "capture occurs here");
969 db.span_label(s, format!("{} does not live long enough",
977 db.span_label(error_span, format!("{} does not live long enough",
983 let sub_span = self.region_end_span(sub_scope);
984 let super_span = self.region_end_span(super_scope);
986 match (sub_span, super_span) {
987 (Some(s1), Some(s2)) if s1 == s2 => {
989 let msg = match opt_loan_path(&err.cmt) {
990 None => value_kind.to_string(),
992 format!("`{}`", self.loan_path_to_string(&lp))
996 format!("{} dropped here while still borrowed", msg));
998 db.span_label(s1, format!("{} dropped before borrower", value_kind));
1000 db.note("values in a scope are dropped in the opposite order \
1003 (Some(s1), Some(s2)) if !is_closure => {
1004 let msg = match opt_loan_path(&err.cmt) {
1005 None => value_kind.to_string(),
1007 format!("`{}`", self.loan_path_to_string(&lp))
1010 db.span_label(s2, format!("{} dropped here while still borrowed", msg));
1011 db.span_label(s1, format!("{} needs to live until here", value_kind));
1016 db.span_label(s, format!("{} needs to live until here",
1020 self.tcx.note_and_explain_region(
1021 &self.region_scope_tree,
1023 "borrowed value must be valid for ",
1030 db.span_label(s, format!("{} only lives until here", value_kind));
1033 self.tcx.note_and_explain_region(
1034 &self.region_scope_tree,
1036 "...but borrowed value is only valid for ",
1044 if let ty::ReScope(scope) = *super_scope {
1045 let node_id = scope.node_id(self.tcx, &self.region_scope_tree);
1046 match self.tcx.hir().find(node_id) {
1047 Some(Node::Stmt(_)) => {
1048 if *sub_scope != ty::ReStatic {
1049 db.note("consider using a `let` binding to increase its lifetime");
1058 self.signal_error();
1060 err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1061 let descr = self.cmt_to_path_or_string(err.cmt);
1062 let mut db = self.lifetime_too_short_for_reborrow(error_span, &descr, Origin::Ast);
1063 let descr: Cow<'static, str> = match opt_loan_path(&err.cmt) {
1065 format!("`{}`", self.loan_path_to_string(&lp)).into()
1067 None => self.cmt_to_cow_str(&err.cmt)
1069 self.tcx.note_and_explain_region(
1070 &self.region_scope_tree,
1072 &format!("{} would have to be valid for ",
1076 self.tcx.note_and_explain_region(
1077 &self.region_scope_tree,
1079 &format!("...but {} is only valid for ", descr),
1084 self.signal_error();
1089 pub fn report_aliasability_violation(&self,
1091 kind: AliasableViolationKind,
1092 cause: mc::AliasableReason,
1093 cmt: &mc::cmt_<'tcx>) {
1094 let mut is_closure = false;
1095 let prefix = match kind {
1096 MutabilityViolation => {
1097 "cannot assign to data"
1099 BorrowViolation(euv::ClosureCapture(_)) |
1100 BorrowViolation(euv::OverloadedOperator) |
1101 BorrowViolation(euv::AddrOf) |
1102 BorrowViolation(euv::AutoRef) |
1103 BorrowViolation(euv::AutoUnsafe) |
1104 BorrowViolation(euv::RefBinding) |
1105 BorrowViolation(euv::MatchDiscriminant) => {
1106 "cannot borrow data mutably"
1109 BorrowViolation(euv::ClosureInvocation) => {
1111 "closure invocation"
1114 BorrowViolation(euv::ForLoop) => {
1120 mc::AliasableStaticMut => {
1121 // This path cannot occur. `static mut X` is not checked
1122 // for aliasability violations.
1123 span_bug!(span, "aliasability violation for static mut `{}`", prefix)
1125 mc::AliasableStatic | mc::AliasableBorrowed => {}
1127 let blame = cmt.immutability_blame();
1128 let mut err = match blame {
1129 Some(ImmutabilityBlame::ClosureEnv(id)) => {
1130 // FIXME: the distinction between these 2 messages looks wrong.
1131 let help_msg = if let BorrowViolation(euv::ClosureCapture(_)) = kind {
1132 // The aliasability violation with closure captures can
1133 // happen for nested closures, so we know the enclosing
1134 // closure incorrectly accepts an `Fn` while it needs to
1136 "consider changing this to accept closures that implement `FnMut`"
1139 "consider changing this closure to take self by mutable reference"
1141 let node_id = self.tcx.hir().local_def_id_to_node_id(id);
1142 let help_span = self.tcx.hir().span(node_id);
1143 self.cannot_act_on_capture_in_sharable_fn(span,
1145 (help_span, help_msg),
1149 self.cannot_assign_into_immutable_reference(span, prefix,
1153 self.note_immutability_blame(
1156 self.tcx.hir().hir_to_node_id(cmt.hir_id)
1160 err.help("closures behind references must be called via `&mut`");
1163 self.signal_error();
1166 /// Given a type, if it is an immutable reference, return a suggestion to make it mutable
1167 fn suggest_mut_for_immutable(&self, pty: &hir::Ty, is_implicit_self: bool) -> Option<String> {
1168 // Check whether the argument is an immutable reference
1169 debug!("suggest_mut_for_immutable({:?}, {:?})", pty, is_implicit_self);
1170 if let hir::TyKind::Rptr(lifetime, hir::MutTy {
1171 mutbl: hir::Mutability::MutImmutable,
1174 // Account for existing lifetimes when generating the message
1175 let pointee_snippet = match self.tcx.sess.source_map().span_to_snippet(ty.span) {
1176 Ok(snippet) => snippet,
1180 let lifetime_snippet = if !lifetime.is_elided() {
1181 format!("{} ", match self.tcx.sess.source_map().span_to_snippet(lifetime.span) {
1182 Ok(lifetime_snippet) => lifetime_snippet,
1188 Some(format!("use `&{}mut {}` here to make mutable",
1190 if is_implicit_self { "self" } else { &*pointee_snippet }))
1196 fn local_binding_mode(&self, node_id: ast::NodeId) -> ty::BindingMode {
1197 let pat = match self.tcx.hir().get(node_id) {
1198 Node::Binding(pat) => pat,
1199 node => bug!("bad node for local: {:?}", node)
1203 hir::PatKind::Binding(..) => {
1205 .pat_binding_modes()
1207 .expect("missing binding mode")
1209 _ => bug!("local is not a binding: {:?}", pat)
1213 fn local_ty(&self, node_id: ast::NodeId) -> (Option<&hir::Ty>, bool) {
1214 let parent = self.tcx.hir().get_parent_node(node_id);
1215 let parent_node = self.tcx.hir().get(parent);
1217 // The parent node is like a fn
1218 if let Some(fn_like) = FnLikeNode::from_node(parent_node) {
1219 // `nid`'s parent's `Body`
1220 let fn_body = self.tcx.hir().body(fn_like.body());
1221 // Get the position of `node_id` in the arguments list
1222 let arg_pos = fn_body.arguments.iter().position(|arg| arg.pat.id == node_id);
1223 if let Some(i) = arg_pos {
1224 // The argument's `Ty`
1225 (Some(&fn_like.decl().inputs[i]),
1226 i == 0 && fn_like.decl().implicit_self.has_implicit_self())
1235 fn note_immutability_blame(&self,
1236 db: &mut DiagnosticBuilder,
1237 blame: Option<ImmutabilityBlame>,
1238 error_node_id: ast::NodeId) {
1241 Some(ImmutabilityBlame::ClosureEnv(_)) => {}
1242 Some(ImmutabilityBlame::ImmLocal(node_id)) => {
1243 self.note_immutable_local(db, error_node_id, node_id)
1245 Some(ImmutabilityBlame::LocalDeref(node_id)) => {
1246 match self.local_binding_mode(node_id) {
1247 ty::BindByReference(..) => {
1248 let let_span = self.tcx.hir().span(node_id);
1249 let suggestion = suggest_ref_mut(self.tcx, let_span);
1250 if let Some(replace_str) = suggestion {
1251 db.span_suggestion_with_applicability(
1253 "use a mutable reference instead",
1255 // I believe this can be machine applicable,
1256 // but if there are multiple attempted uses of an immutable
1257 // reference, I don't know how rustfix handles it, it might
1258 // attempt fixing them multiple times.
1260 Applicability::Unspecified,
1264 ty::BindByValue(..) => {
1265 if let (Some(local_ty), is_implicit_self) = self.local_ty(node_id) {
1267 self.suggest_mut_for_immutable(local_ty, is_implicit_self) {
1268 db.span_label(local_ty.span, msg);
1274 Some(ImmutabilityBlame::AdtFieldDeref(_, field)) => {
1275 let node_id = match self.tcx.hir().as_local_node_id(field.did) {
1276 Some(node_id) => node_id,
1280 if let Node::Field(ref field) = self.tcx.hir().get(node_id) {
1281 if let Some(msg) = self.suggest_mut_for_immutable(&field.ty, false) {
1282 db.span_label(field.ty.span, msg);
1289 // Suggest a fix when trying to mutably borrow an immutable local
1290 // binding: either to make the binding mutable (if its type is
1291 // not a mutable reference) or to avoid borrowing altogether
1292 fn note_immutable_local(&self,
1293 db: &mut DiagnosticBuilder,
1294 borrowed_node_id: ast::NodeId,
1295 binding_node_id: ast::NodeId) {
1296 let let_span = self.tcx.hir().span(binding_node_id);
1297 if let ty::BindByValue(..) = self.local_binding_mode(binding_node_id) {
1298 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(let_span) {
1299 let (ty, is_implicit_self) = self.local_ty(binding_node_id);
1300 if is_implicit_self && snippet != "self" {
1301 // avoid suggesting `mut &self`.
1304 if let Some(&hir::TyKind::Rptr(
1307 mutbl: hir::MutMutable,
1310 )) = ty.map(|t| &t.node)
1312 let borrow_expr_id = self.tcx.hir().get_parent_node(borrowed_node_id);
1313 db.span_suggestion_with_applicability(
1314 self.tcx.hir().span(borrow_expr_id),
1315 "consider removing the `&mut`, as it is an \
1316 immutable binding to a mutable reference",
1318 Applicability::MachineApplicable,
1321 db.span_suggestion_with_applicability(
1323 "make this binding mutable",
1324 format!("mut {}", snippet),
1325 Applicability::MachineApplicable,
1332 fn report_out_of_scope_escaping_closure_capture(&self,
1333 err: &BckError<'a, 'tcx>,
1336 let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
1339 match self.tcx.sess.source_map().span_to_snippet(err.span) {
1340 Ok(string) => format!("move {}", string),
1341 Err(_) => "move |<args>| <body>".to_string()
1344 self.cannot_capture_in_long_lived_closure(err.span,
1345 &cmt_path_or_string,
1348 .span_suggestion_with_applicability(
1350 &format!("to force the closure to take ownership of {} \
1351 (and any other referenced variables), \
1352 use the `move` keyword",
1353 cmt_path_or_string),
1355 Applicability::MachineApplicable,
1358 self.signal_error();
1361 fn region_end_span(&self, region: ty::Region<'tcx>) -> Option<Span> {
1363 ty::ReScope(scope) => {
1364 Some(self.tcx.sess.source_map().end_point(
1365 scope.span(self.tcx, &self.region_scope_tree)))
1371 fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'a, 'tcx>,
1372 error_span: &Span) {
1373 match err.cmt.note {
1374 mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1375 // If this is an `Fn` closure, it simply can't mutate upvars.
1376 // If it's an `FnMut` closure, the original variable was declared immutable.
1377 // We need to determine which is the case here.
1378 let kind = match err.cmt.upvar_cat().unwrap() {
1379 Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1382 if *kind == ty::ClosureKind::Fn {
1383 let closure_node_id =
1384 self.tcx.hir().local_def_id_to_node_id(upvar_id.closure_expr_id);
1385 db.span_help(self.tcx.hir().span(closure_node_id),
1386 "consider changing this closure to take \
1387 self by mutable reference");
1391 if let Categorization::Deref(..) = err.cmt.cat {
1392 db.span_label(*error_span, "cannot borrow as mutable");
1393 } else if let Categorization::Local(local_id) = err.cmt.cat {
1394 let span = self.tcx.hir().span(local_id);
1395 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1396 if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
1397 db.span_label(*error_span, "cannot reborrow mutably");
1398 db.span_label(*error_span, "try removing `&mut` here");
1400 db.span_label(*error_span, "cannot borrow mutably");
1403 db.span_label(*error_span, "cannot borrow mutably");
1405 } else if let Categorization::Interior(ref cmt, _) = err.cmt.cat {
1406 if let mc::MutabilityCategory::McImmutable = cmt.mutbl {
1407 db.span_label(*error_span,
1408 "cannot mutably borrow field of immutable binding");
1414 pub fn append_loan_path_to_string(&self,
1415 loan_path: &LoanPath<'tcx>,
1417 match loan_path.kind {
1418 LpUpvar(ty::UpvarId { var_path: ty::UpvarPath { hir_id: id}, closure_expr_id: _ }) => {
1419 out.push_str(&self.tcx.hir().name(self.tcx.hir().hir_to_node_id(id)).as_str());
1422 out.push_str(&self.tcx.hir().name(id).as_str());
1425 LpDowncast(ref lp_base, variant_def_id) => {
1427 self.append_loan_path_to_string(&lp_base, out);
1428 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1429 out.push_str(&self.tcx.item_path_str(variant_def_id));
1433 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(mc::FieldIndex(_, info)))) => {
1434 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1436 out.push_str(&info.as_str());
1439 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement)) => {
1440 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1441 out.push_str("[..]");
1444 LpExtend(ref lp_base, _, LpDeref(_)) => {
1446 self.append_loan_path_to_string(&lp_base, out);
1451 pub fn append_autoderefd_loan_path_to_string(&self,
1452 loan_path: &LoanPath<'tcx>,
1454 match loan_path.kind {
1455 LpExtend(ref lp_base, _, LpDeref(_)) => {
1456 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1457 // rules would normally allow users to omit the `*x`.
1458 // So just serialize such paths to `x.f` or x[3]` respectively.
1459 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1462 LpDowncast(ref lp_base, variant_def_id) => {
1464 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1465 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1466 out.push_str(&self.tcx.item_path_str(variant_def_id));
1470 LpVar(..) | LpUpvar(..) | LpExtend(.., LpInterior(..)) => {
1471 self.append_loan_path_to_string(loan_path, out)
1476 pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1477 let mut result = String::new();
1478 self.append_loan_path_to_string(loan_path, &mut result);
1482 pub fn cmt_to_cow_str(&self, cmt: &mc::cmt_<'tcx>) -> Cow<'static, str> {
1483 cmt.descriptive_string(self.tcx)
1486 pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1487 match opt_loan_path(cmt) {
1488 Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1489 None => self.cmt_to_cow_str(cmt).into_owned(),
1494 impl BitwiseOperator for LoanDataFlowOperator {
1496 fn join(&self, succ: usize, pred: usize) -> usize {
1497 succ | pred // loans from both preds are in scope
1501 impl DataFlowOperator for LoanDataFlowOperator {
1503 fn initial_value(&self) -> bool {
1504 false // no loans in scope by default
1508 impl<'tcx> fmt::Debug for InteriorKind {
1509 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1511 InteriorField(mc::FieldIndex(_, info)) => write!(f, "{}", info),
1512 InteriorElement => write!(f, "[]"),
1517 impl<'tcx> fmt::Debug for Loan<'tcx> {
1518 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1519 write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1525 self.restricted_paths)
1529 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1530 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1533 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir().node_to_string(id)))
1536 LpUpvar(ty::UpvarId{ var_path: ty::UpvarPath {hir_id: var_id}, closure_expr_id }) => {
1537 let s = ty::tls::with(|tcx| {
1538 let var_node_id = tcx.hir().hir_to_node_id(var_id);
1539 tcx.hir().node_to_string(var_node_id)
1541 write!(f, "$({} captured by id={:?})", s, closure_expr_id)
1544 LpDowncast(ref lp, variant_def_id) => {
1545 let variant_str = if variant_def_id.is_local() {
1546 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1548 format!("{:?}", variant_def_id)
1550 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1553 LpExtend(ref lp, _, LpDeref(_)) => {
1554 write!(f, "{:?}.*", lp)
1557 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1558 write!(f, "{:?}.{:?}", lp, interior)
1564 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1565 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1568 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir().node_to_user_string(id)))
1571 LpUpvar(ty::UpvarId{ var_path: ty::UpvarPath { hir_id }, closure_expr_id: _ }) => {
1572 let s = ty::tls::with(|tcx| {
1573 let var_node_id = tcx.hir().hir_to_node_id(hir_id);
1574 tcx.hir().node_to_string(var_node_id)
1576 write!(f, "$({} captured by closure)", s)
1579 LpDowncast(ref lp, variant_def_id) => {
1580 let variant_str = if variant_def_id.is_local() {
1581 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1583 format!("{:?}", variant_def_id)
1585 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1588 LpExtend(ref lp, _, LpDeref(_)) => {
1589 write!(f, "{}.*", lp)
1592 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1593 write!(f, "{}.{:?}", lp, interior)