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: FxHashSet(),
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: RefCell::new(FxHashSet()),
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: RefCell::new(FxHashSet()),
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::StaticItem => {
527 Categorization::Local(id) => {
528 (Some(new_lp(LpVar(id))), false)
531 Categorization::Upvar(mc::Upvar { id, .. }) => {
532 (Some(new_lp(LpUpvar(id))), false)
535 Categorization::Deref(ref cmt_base, pk) => {
536 let lp = opt_loan_path_is_field(cmt_base);
538 new_lp(LpExtend(lp, cmt.mutbl, LpDeref(pk)))
542 Categorization::Interior(ref cmt_base, ik) => {
543 (opt_loan_path(cmt_base).map(|lp| {
544 let opt_variant_id = match cmt_base.cat {
545 Categorization::Downcast(_, did) => Some(did),
548 new_lp(LpExtend(lp, cmt.mutbl, LpInterior(opt_variant_id, ik.cleaned())))
552 Categorization::Downcast(ref cmt_base, variant_def_id) => {
553 let lp = opt_loan_path_is_field(cmt_base);
555 new_lp(LpDowncast(lp, variant_def_id))
561 /// Computes the `LoanPath` (if any) for a `cmt`.
562 /// Note that this logic is somewhat duplicated in
563 /// the method `compute()` found in `gather_loans::restrictions`,
564 /// which allows it to share common loan path pieces as it
565 /// traverses the CMT.
566 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt_<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
567 opt_loan_path_is_field(cmt).0
570 ///////////////////////////////////////////////////////////////////////////
573 // Errors that can occur
574 #[derive(Debug, PartialEq)]
575 pub enum bckerr_code<'tcx> {
577 /// superscope, subscope, loan cause
578 err_out_of_scope(ty::Region<'tcx>, ty::Region<'tcx>, euv::LoanCause),
579 err_borrowed_pointer_too_short(ty::Region<'tcx>, ty::Region<'tcx>), // loan, ptr
582 // Combination of an error code and the categorization of the expression
584 #[derive(Debug, PartialEq)]
585 pub struct BckError<'c, 'tcx: 'c> {
587 cause: AliasableViolationKind,
588 cmt: &'c mc::cmt_<'tcx>,
589 code: bckerr_code<'tcx>
592 #[derive(Copy, Clone, Debug, PartialEq)]
593 pub enum AliasableViolationKind {
595 BorrowViolation(euv::LoanCause)
598 #[derive(Copy, Clone, Debug)]
599 pub enum MovedValueUseKind {
604 ///////////////////////////////////////////////////////////////////////////
607 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
608 pub fn is_subregion_of(&self,
609 r_sub: ty::Region<'tcx>,
610 r_sup: ty::Region<'tcx>)
613 let region_rels = RegionRelations::new(self.tcx,
615 &self.region_scope_tree,
616 &self.tables.free_region_map);
617 region_rels.is_subregion_of(r_sub, r_sup)
620 pub fn report(&self, err: BckError<'a, 'tcx>) {
621 // Catch and handle some particular cases.
622 match (&err.code, &err.cause) {
623 (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _),
624 &BorrowViolation(euv::ClosureCapture(span))) |
625 (&err_out_of_scope(&ty::ReScope(_), &ty::ReEarlyBound(..), _),
626 &BorrowViolation(euv::ClosureCapture(span))) |
627 (&err_out_of_scope(&ty::ReScope(_), &ty::ReFree(..), _),
628 &BorrowViolation(euv::ClosureCapture(span))) => {
629 return self.report_out_of_scope_escaping_closure_capture(&err, span);
634 self.report_bckerr(&err);
637 pub fn report_use_of_moved_value(&self,
639 use_kind: MovedValueUseKind,
641 the_move: &move_data::Move,
642 moved_lp: &LoanPath<'tcx>) {
643 let (verb, verb_participle) = match use_kind {
644 MovedInUse => ("use", "used"),
645 MovedInCapture => ("capture", "captured"),
648 let (_ol, _moved_lp_msg, mut err, need_note) = match the_move.kind {
649 move_data::Declared => {
650 // If this is an uninitialized variable, just emit a simple warning
652 self.cannot_act_on_uninitialized_variable(use_span,
654 &self.loan_path_to_string(lp),
656 .span_label(use_span, format!("use of possibly uninitialized `{}`",
657 self.loan_path_to_string(lp)))
663 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
664 // normally generate a rather confusing message:
666 // error: use of moved value: `x.b`
667 // note: `x.a` moved here...
669 // What we want to do instead is get the 'common ancestor' of the two moves and
670 // use that for most of the message instead, giving is something like this:
672 // error: use of moved value: `x`
673 // note: `x` moved here (through moving `x.a`)...
675 let common = moved_lp.common(lp);
676 let has_common = common.is_some();
677 let has_fork = moved_lp.has_fork(lp);
678 let (nl, ol, moved_lp_msg) =
679 if has_fork && has_common {
680 let nl = self.loan_path_to_string(&common.unwrap());
682 let moved_lp_msg = format!(" (through moving `{}`)",
683 self.loan_path_to_string(moved_lp));
684 (nl, ol, moved_lp_msg)
686 (self.loan_path_to_string(lp),
687 self.loan_path_to_string(moved_lp),
691 let partial = moved_lp.depth() > lp.depth();
692 let msg = if !has_fork && partial { "partially " }
693 else if has_fork && !has_common { "collaterally "}
695 let mut err = self.cannot_act_on_moved_value(use_span,
698 Some(nl.to_string()),
700 let need_note = match lp.ty.sty {
701 ty::Closure(id, _) => {
702 let node_id = self.tcx.hir.as_local_node_id(id).unwrap();
703 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
704 if let Some((span, name)) = self.tables.closure_kind_origins().get(hir_id) {
705 err.span_note(*span, &format!(
706 "closure cannot be invoked more than once because \
707 it moves the variable `{}` out of its environment",
717 (ol, moved_lp_msg, err, need_note)
721 // Get type of value and span where it was previously
723 let node_id = self.tcx.hir.hir_to_node_id(hir::HirId {
724 owner: self.body.value.hir_id.owner,
725 local_id: the_move.id
727 let (move_span, move_note) = match the_move.kind {
728 move_data::Declared => {
732 move_data::MoveExpr |
733 move_data::MovePat => (self.tcx.hir.span(node_id), ""),
735 move_data::Captured =>
736 (match self.tcx.hir.expect_expr(node_id).node {
737 hir::ExprKind::Closure(.., fn_decl_span, _) => fn_decl_span,
738 ref r => bug!("Captured({:?}) maps to non-closure: {:?}",
740 }, " (into closure)"),
743 // Annotate the use and the move in the span. Watch out for
744 // the case where the use and the move are the same. This
745 // means the use is in a loop.
746 err = if use_span == move_span {
749 format!("value moved{} here in previous iteration of loop",
753 err.span_label(use_span, format!("value {} here after move", verb_participle));
754 err.span_label(move_span, format!("value moved{} here", move_note));
760 "move occurs because {} has type `{}`, which does not implement the `Copy` trait",
761 if moved_lp.has_downcast() {
762 "the value".to_string()
764 format!("`{}`", self.loan_path_to_string(moved_lp))
769 // Note: we used to suggest adding a `ref binding` or calling
770 // `clone` but those suggestions have been removed because
771 // they are often not what you actually want to do, and were
772 // not considered particularly helpful.
778 pub fn report_partial_reinitialization_of_uninitialized_structure(
781 lp: &LoanPath<'tcx>) {
782 self.cannot_partially_reinit_an_uninit_struct(span,
783 &self.loan_path_to_string(lp),
789 pub fn report_reassigned_immutable_variable(&self,
793 &move_data::Assignment) {
794 let mut err = self.cannot_reassign_immutable(span,
795 &self.loan_path_to_string(lp),
798 err.span_label(span, "cannot assign twice to immutable variable");
799 if span != assign.span {
800 err.span_label(assign.span, format!("first assignment to `{}`",
801 self.loan_path_to_string(lp)));
807 fn report_bckerr(&self, err: &BckError<'a, 'tcx>) {
808 let error_span = err.span.clone();
812 let descr: Cow<'static, str> = match err.cmt.note {
813 mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
814 self.cmt_to_cow_str(&err.cmt)
816 _ => match opt_loan_path_is_field(&err.cmt) {
818 format!("{} of {} binding",
819 self.cmt_to_cow_str(&err.cmt),
820 err.cmt.mutbl.to_user_str()).into()
825 err.cmt.mutbl.to_user_str(),
826 self.cmt_to_cow_str(&err.cmt)).into()
829 (Some(lp), true) => {
830 format!("{} `{}` of {} binding",
831 self.cmt_to_cow_str(&err.cmt),
832 self.loan_path_to_string(&lp),
833 err.cmt.mutbl.to_user_str()).into()
835 (Some(lp), false) => {
836 format!("{} {} `{}`",
837 err.cmt.mutbl.to_user_str(),
838 self.cmt_to_cow_str(&err.cmt),
839 self.loan_path_to_string(&lp)).into()
844 let mut db = match err.cause {
845 MutabilityViolation => {
846 let mut db = self.cannot_assign(error_span, &descr, Origin::Ast);
847 if let mc::NoteClosureEnv(upvar_id) = err.cmt.note {
848 let node_id = self.tcx.hir.hir_to_node_id(upvar_id.var_id);
849 let sp = self.tcx.hir.span(node_id);
850 let fn_closure_msg = "`Fn` closures cannot capture their enclosing \
851 environment for modifications";
852 match (self.tcx.sess.source_map().span_to_snippet(sp), &err.cmt.cat) {
853 (_, &Categorization::Upvar(mc::Upvar {
854 kind: ty::ClosureKind::Fn, ..
856 db.note(fn_closure_msg);
857 // we should point at the cause for this closure being
858 // identified as `Fn` (like in signature of method this
859 // closure was passed into)
861 (Ok(ref snippet), ref cat) => {
862 let msg = &format!("consider making `{}` mutable", snippet);
863 let suggestion = format!("mut {}", snippet);
865 if let &Categorization::Deref(ref cmt, _) = cat {
866 if let Categorization::Upvar(mc::Upvar {
867 kind: ty::ClosureKind::Fn, ..
869 db.note(fn_closure_msg);
871 db.span_suggestion_with_applicability(
875 Applicability::Unspecified,
879 db.span_suggestion_with_applicability(
883 Applicability::Unspecified,
888 db.span_help(sp, "consider making this binding mutable");
895 BorrowViolation(euv::ClosureCapture(_)) => {
896 self.closure_cannot_assign_to_borrowed(error_span, &descr, Origin::Ast)
898 BorrowViolation(euv::OverloadedOperator) |
899 BorrowViolation(euv::AddrOf) |
900 BorrowViolation(euv::RefBinding) |
901 BorrowViolation(euv::AutoRef) |
902 BorrowViolation(euv::AutoUnsafe) |
903 BorrowViolation(euv::ForLoop) |
904 BorrowViolation(euv::MatchDiscriminant) => {
905 self.cannot_borrow_path_as_mutable(error_span, &descr, Origin::Ast)
907 BorrowViolation(euv::ClosureInvocation) => {
909 "err_mutbl with a closure invocation");
913 // We add a special note about `IndexMut`, if the source of this error
914 // is the fact that `Index` is implemented, but `IndexMut` is not. Needing
915 // to implement two traits for "one operator" is not very intuitive for
917 if err.cmt.note == mc::NoteIndex {
918 let node_id = self.tcx.hir.hir_to_node_id(err.cmt.hir_id);
919 let node = self.tcx.hir.get(node_id);
921 // This pattern probably always matches.
923 hir::Expr { node: hir::ExprKind::Index(lhs, _), ..}
925 let ty = self.tables.expr_ty(lhs);
928 "trait `IndexMut` is required to modify indexed content, but \
929 it is not implemented for `{}`",
935 self.note_and_explain_mutbl_error(&mut db, &err, &error_span);
936 self.note_immutability_blame(
938 err.cmt.immutability_blame(),
939 self.tcx.hir.hir_to_node_id(err.cmt.hir_id)
944 err_out_of_scope(super_scope, sub_scope, cause) => {
945 let msg = match opt_loan_path(&err.cmt) {
946 None => "borrowed value".to_string(),
948 format!("`{}`", self.loan_path_to_string(&lp))
952 let mut db = self.path_does_not_live_long_enough(error_span, &msg, Origin::Ast);
953 let value_kind = match err.cmt.cat {
954 mc::Categorization::Rvalue(..) => "temporary value",
955 _ => "borrowed value",
958 let is_closure = match cause {
959 euv::ClosureCapture(s) => {
960 // The primary span starts out as the closure creation point.
961 // Change the primary span here to highlight the use of the variable
962 // in the closure, because it seems more natural. Highlight
963 // closure creation point as a secondary span.
964 match db.span.primary_span() {
966 db.span = MultiSpan::from_span(s);
967 db.span_label(primary, "capture occurs here");
968 db.span_label(s, format!("{} does not live long enough",
976 db.span_label(error_span, format!("{} does not live long enough",
982 let sub_span = self.region_end_span(sub_scope);
983 let super_span = self.region_end_span(super_scope);
985 match (sub_span, super_span) {
986 (Some(s1), Some(s2)) if s1 == s2 => {
988 let msg = match opt_loan_path(&err.cmt) {
989 None => value_kind.to_string(),
991 format!("`{}`", self.loan_path_to_string(&lp))
995 format!("{} dropped here while still borrowed", msg));
997 db.span_label(s1, format!("{} dropped before borrower", value_kind));
999 db.note("values in a scope are dropped in the opposite order \
1002 (Some(s1), Some(s2)) if !is_closure => {
1003 let msg = match opt_loan_path(&err.cmt) {
1004 None => value_kind.to_string(),
1006 format!("`{}`", self.loan_path_to_string(&lp))
1009 db.span_label(s2, format!("{} dropped here while still borrowed", msg));
1010 db.span_label(s1, format!("{} needs to live until here", value_kind));
1015 db.span_label(s, format!("{} needs to live until here",
1019 self.tcx.note_and_explain_region(
1020 &self.region_scope_tree,
1022 "borrowed value must be valid for ",
1029 db.span_label(s, format!("{} only lives until here", value_kind));
1032 self.tcx.note_and_explain_region(
1033 &self.region_scope_tree,
1035 "...but borrowed value is only valid for ",
1043 if let ty::ReScope(scope) = *super_scope {
1044 let node_id = scope.node_id(self.tcx, &self.region_scope_tree);
1045 match self.tcx.hir.find(node_id) {
1046 Some(Node::Stmt(_)) => {
1047 if *sub_scope != ty::ReStatic {
1048 db.note("consider using a `let` binding to increase its lifetime");
1057 self.signal_error();
1059 err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1060 let descr = self.cmt_to_path_or_string(err.cmt);
1061 let mut db = self.lifetime_too_short_for_reborrow(error_span, &descr, Origin::Ast);
1062 let descr: Cow<'static, str> = match opt_loan_path(&err.cmt) {
1064 format!("`{}`", self.loan_path_to_string(&lp)).into()
1066 None => self.cmt_to_cow_str(&err.cmt)
1068 self.tcx.note_and_explain_region(
1069 &self.region_scope_tree,
1071 &format!("{} would have to be valid for ",
1075 self.tcx.note_and_explain_region(
1076 &self.region_scope_tree,
1078 &format!("...but {} is only valid for ", descr),
1083 self.signal_error();
1088 pub fn report_aliasability_violation(&self,
1090 kind: AliasableViolationKind,
1091 cause: mc::AliasableReason,
1092 cmt: &mc::cmt_<'tcx>) {
1093 let mut is_closure = false;
1094 let prefix = match kind {
1095 MutabilityViolation => {
1096 "cannot assign to data"
1098 BorrowViolation(euv::ClosureCapture(_)) |
1099 BorrowViolation(euv::OverloadedOperator) |
1100 BorrowViolation(euv::AddrOf) |
1101 BorrowViolation(euv::AutoRef) |
1102 BorrowViolation(euv::AutoUnsafe) |
1103 BorrowViolation(euv::RefBinding) |
1104 BorrowViolation(euv::MatchDiscriminant) => {
1105 "cannot borrow data mutably"
1108 BorrowViolation(euv::ClosureInvocation) => {
1110 "closure invocation"
1113 BorrowViolation(euv::ForLoop) => {
1119 mc::AliasableStaticMut => {
1120 // This path cannot occur. `static mut X` is not checked
1121 // for aliasability violations.
1122 span_bug!(span, "aliasability violation for static mut `{}`", prefix)
1124 mc::AliasableStatic | mc::AliasableBorrowed => {}
1126 let blame = cmt.immutability_blame();
1127 let mut err = match blame {
1128 Some(ImmutabilityBlame::ClosureEnv(id)) => {
1129 // FIXME: the distinction between these 2 messages looks wrong.
1130 let help_msg = if let BorrowViolation(euv::ClosureCapture(_)) = kind {
1131 // The aliasability violation with closure captures can
1132 // happen for nested closures, so we know the enclosing
1133 // closure incorrectly accepts an `Fn` while it needs to
1135 "consider changing this to accept closures that implement `FnMut`"
1138 "consider changing this closure to take self by mutable reference"
1140 let node_id = self.tcx.hir.local_def_id_to_node_id(id);
1141 let help_span = self.tcx.hir.span(node_id);
1142 self.cannot_act_on_capture_in_sharable_fn(span,
1144 (help_span, help_msg),
1148 self.cannot_assign_into_immutable_reference(span, prefix,
1152 self.note_immutability_blame(
1155 self.tcx.hir.hir_to_node_id(cmt.hir_id)
1159 err.help("closures behind references must be called via `&mut`");
1162 self.signal_error();
1165 /// Given a type, if it is an immutable reference, return a suggestion to make it mutable
1166 fn suggest_mut_for_immutable(&self, pty: &hir::Ty, is_implicit_self: bool) -> Option<String> {
1167 // Check whether the argument is an immutable reference
1168 debug!("suggest_mut_for_immutable({:?}, {:?})", pty, is_implicit_self);
1169 if let hir::TyKind::Rptr(lifetime, hir::MutTy {
1170 mutbl: hir::Mutability::MutImmutable,
1173 // Account for existing lifetimes when generating the message
1174 let pointee_snippet = match self.tcx.sess.source_map().span_to_snippet(ty.span) {
1175 Ok(snippet) => snippet,
1179 let lifetime_snippet = if !lifetime.is_elided() {
1180 format!("{} ", match self.tcx.sess.source_map().span_to_snippet(lifetime.span) {
1181 Ok(lifetime_snippet) => lifetime_snippet,
1187 Some(format!("use `&{}mut {}` here to make mutable",
1189 if is_implicit_self { "self" } else { &*pointee_snippet }))
1195 fn local_binding_mode(&self, node_id: ast::NodeId) -> ty::BindingMode {
1196 let pat = match self.tcx.hir.get(node_id) {
1197 Node::Binding(pat) => pat,
1198 node => bug!("bad node for local: {:?}", node)
1202 hir::PatKind::Binding(..) => {
1204 .pat_binding_modes()
1206 .expect("missing binding mode")
1208 _ => bug!("local is not a binding: {:?}", pat)
1212 fn local_ty(&self, node_id: ast::NodeId) -> (Option<&hir::Ty>, bool) {
1213 let parent = self.tcx.hir.get_parent_node(node_id);
1214 let parent_node = self.tcx.hir.get(parent);
1216 // The parent node is like a fn
1217 if let Some(fn_like) = FnLikeNode::from_node(parent_node) {
1218 // `nid`'s parent's `Body`
1219 let fn_body = self.tcx.hir.body(fn_like.body());
1220 // Get the position of `node_id` in the arguments list
1221 let arg_pos = fn_body.arguments.iter().position(|arg| arg.pat.id == node_id);
1222 if let Some(i) = arg_pos {
1223 // The argument's `Ty`
1224 (Some(&fn_like.decl().inputs[i]),
1225 i == 0 && fn_like.decl().implicit_self.has_implicit_self())
1234 fn note_immutability_blame(&self,
1235 db: &mut DiagnosticBuilder,
1236 blame: Option<ImmutabilityBlame>,
1237 error_node_id: ast::NodeId) {
1240 Some(ImmutabilityBlame::ClosureEnv(_)) => {}
1241 Some(ImmutabilityBlame::ImmLocal(node_id)) => {
1242 self.note_immutable_local(db, error_node_id, node_id)
1244 Some(ImmutabilityBlame::LocalDeref(node_id)) => {
1245 match self.local_binding_mode(node_id) {
1246 ty::BindByReference(..) => {
1247 let let_span = self.tcx.hir.span(node_id);
1248 let suggestion = suggest_ref_mut(self.tcx, let_span);
1249 if let Some(replace_str) = suggestion {
1250 db.span_suggestion_with_applicability(
1252 "use a mutable reference instead",
1254 // I believe this can be machine applicable,
1255 // but if there are multiple attempted uses of an immutable
1256 // reference, I don't know how rustfix handles it, it might
1257 // attempt fixing them multiple times.
1259 Applicability::Unspecified,
1263 ty::BindByValue(..) => {
1264 if let (Some(local_ty), is_implicit_self) = self.local_ty(node_id) {
1266 self.suggest_mut_for_immutable(local_ty, is_implicit_self) {
1267 db.span_label(local_ty.span, msg);
1273 Some(ImmutabilityBlame::AdtFieldDeref(_, field)) => {
1274 let node_id = match self.tcx.hir.as_local_node_id(field.did) {
1275 Some(node_id) => node_id,
1279 if let Node::Field(ref field) = self.tcx.hir.get(node_id) {
1280 if let Some(msg) = self.suggest_mut_for_immutable(&field.ty, false) {
1281 db.span_label(field.ty.span, msg);
1288 // Suggest a fix when trying to mutably borrow an immutable local
1289 // binding: either to make the binding mutable (if its type is
1290 // not a mutable reference) or to avoid borrowing altogether
1291 fn note_immutable_local(&self,
1292 db: &mut DiagnosticBuilder,
1293 borrowed_node_id: ast::NodeId,
1294 binding_node_id: ast::NodeId) {
1295 let let_span = self.tcx.hir.span(binding_node_id);
1296 if let ty::BindByValue(..) = self.local_binding_mode(binding_node_id) {
1297 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(let_span) {
1298 let (ty, is_implicit_self) = self.local_ty(binding_node_id);
1299 if is_implicit_self && snippet != "self" {
1300 // avoid suggesting `mut &self`.
1303 if let Some(&hir::TyKind::Rptr(
1306 mutbl: hir::MutMutable,
1309 )) = ty.map(|t| &t.node)
1311 let borrow_expr_id = self.tcx.hir.get_parent_node(borrowed_node_id);
1312 db.span_suggestion_with_applicability(
1313 self.tcx.hir.span(borrow_expr_id),
1314 "consider removing the `&mut`, as it is an \
1315 immutable binding to a mutable reference",
1317 Applicability::MachineApplicable,
1320 db.span_suggestion_with_applicability(
1322 "make this binding mutable",
1323 format!("mut {}", snippet),
1324 Applicability::MachineApplicable,
1331 fn report_out_of_scope_escaping_closure_capture(&self,
1332 err: &BckError<'a, 'tcx>,
1335 let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
1338 match self.tcx.sess.source_map().span_to_snippet(err.span) {
1339 Ok(string) => format!("move {}", string),
1340 Err(_) => "move |<args>| <body>".to_string()
1343 self.cannot_capture_in_long_lived_closure(err.span,
1344 &cmt_path_or_string,
1347 .span_suggestion_with_applicability(
1349 &format!("to force the closure to take ownership of {} \
1350 (and any other referenced variables), \
1351 use the `move` keyword",
1352 cmt_path_or_string),
1354 Applicability::MachineApplicable,
1357 self.signal_error();
1360 fn region_end_span(&self, region: ty::Region<'tcx>) -> Option<Span> {
1362 ty::ReScope(scope) => {
1363 Some(self.tcx.sess.source_map().end_point(
1364 scope.span(self.tcx, &self.region_scope_tree)))
1370 fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'a, 'tcx>,
1371 error_span: &Span) {
1372 match err.cmt.note {
1373 mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1374 // If this is an `Fn` closure, it simply can't mutate upvars.
1375 // If it's an `FnMut` closure, the original variable was declared immutable.
1376 // We need to determine which is the case here.
1377 let kind = match err.cmt.upvar_cat().unwrap() {
1378 Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1381 if *kind == ty::ClosureKind::Fn {
1382 let closure_node_id =
1383 self.tcx.hir.local_def_id_to_node_id(upvar_id.closure_expr_id);
1384 db.span_help(self.tcx.hir.span(closure_node_id),
1385 "consider changing this closure to take \
1386 self by mutable reference");
1390 if let Categorization::Deref(..) = err.cmt.cat {
1391 db.span_label(*error_span, "cannot borrow as mutable");
1392 } else if let Categorization::Local(local_id) = err.cmt.cat {
1393 let span = self.tcx.hir.span(local_id);
1394 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1395 if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
1396 db.span_label(*error_span, "cannot reborrow mutably");
1397 db.span_label(*error_span, "try removing `&mut` here");
1399 db.span_label(*error_span, "cannot borrow mutably");
1402 db.span_label(*error_span, "cannot borrow mutably");
1404 } else if let Categorization::Interior(ref cmt, _) = err.cmt.cat {
1405 if let mc::MutabilityCategory::McImmutable = cmt.mutbl {
1406 db.span_label(*error_span,
1407 "cannot mutably borrow field of immutable binding");
1413 pub fn append_loan_path_to_string(&self,
1414 loan_path: &LoanPath<'tcx>,
1416 match loan_path.kind {
1417 LpUpvar(ty::UpvarId { var_id: id, closure_expr_id: _ }) => {
1418 out.push_str(&self.tcx.hir.name(self.tcx.hir.hir_to_node_id(id)).as_str());
1421 out.push_str(&self.tcx.hir.name(id).as_str());
1424 LpDowncast(ref lp_base, variant_def_id) => {
1426 self.append_loan_path_to_string(&lp_base, out);
1427 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1428 out.push_str(&self.tcx.item_path_str(variant_def_id));
1432 LpExtend(ref lp_base, _, LpInterior(_, InteriorField(mc::FieldIndex(_, info)))) => {
1433 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1435 out.push_str(&info.as_str());
1438 LpExtend(ref lp_base, _, LpInterior(_, InteriorElement)) => {
1439 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1440 out.push_str("[..]");
1443 LpExtend(ref lp_base, _, LpDeref(_)) => {
1445 self.append_loan_path_to_string(&lp_base, out);
1450 pub fn append_autoderefd_loan_path_to_string(&self,
1451 loan_path: &LoanPath<'tcx>,
1453 match loan_path.kind {
1454 LpExtend(ref lp_base, _, LpDeref(_)) => {
1455 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1456 // rules would normally allow users to omit the `*x`.
1457 // So just serialize such paths to `x.f` or x[3]` respectively.
1458 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1461 LpDowncast(ref lp_base, variant_def_id) => {
1463 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1464 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1465 out.push_str(&self.tcx.item_path_str(variant_def_id));
1469 LpVar(..) | LpUpvar(..) | LpExtend(.., LpInterior(..)) => {
1470 self.append_loan_path_to_string(loan_path, out)
1475 pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1476 let mut result = String::new();
1477 self.append_loan_path_to_string(loan_path, &mut result);
1481 pub fn cmt_to_cow_str(&self, cmt: &mc::cmt_<'tcx>) -> Cow<'static, str> {
1482 cmt.descriptive_string(self.tcx)
1485 pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1486 match opt_loan_path(cmt) {
1487 Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1488 None => self.cmt_to_cow_str(cmt).into_owned(),
1493 impl BitwiseOperator for LoanDataFlowOperator {
1495 fn join(&self, succ: usize, pred: usize) -> usize {
1496 succ | pred // loans from both preds are in scope
1500 impl DataFlowOperator for LoanDataFlowOperator {
1502 fn initial_value(&self) -> bool {
1503 false // no loans in scope by default
1507 impl<'tcx> fmt::Debug for InteriorKind {
1508 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1510 InteriorField(mc::FieldIndex(_, info)) => write!(f, "{}", info),
1511 InteriorElement => write!(f, "[]"),
1516 impl<'tcx> fmt::Debug for Loan<'tcx> {
1517 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1518 write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1524 self.restricted_paths)
1528 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1529 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1532 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_string(id)))
1535 LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => {
1536 let s = ty::tls::with(|tcx| {
1537 let var_node_id = tcx.hir.hir_to_node_id(var_id);
1538 tcx.hir.node_to_string(var_node_id)
1540 write!(f, "$({} captured by id={:?})", s, closure_expr_id)
1543 LpDowncast(ref lp, variant_def_id) => {
1544 let variant_str = if variant_def_id.is_local() {
1545 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1547 format!("{:?}", variant_def_id)
1549 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1552 LpExtend(ref lp, _, LpDeref(_)) => {
1553 write!(f, "{:?}.*", lp)
1556 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1557 write!(f, "{:?}.{:?}", lp, interior)
1563 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1564 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1567 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_user_string(id)))
1570 LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => {
1571 let s = ty::tls::with(|tcx| {
1572 let var_node_id = tcx.hir.hir_to_node_id(var_id);
1573 tcx.hir.node_to_string(var_node_id)
1575 write!(f, "$({} captured by closure)", s)
1578 LpDowncast(ref lp, variant_def_id) => {
1579 let variant_str = if variant_def_id.is_local() {
1580 ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1582 format!("{:?}", variant_def_id)
1584 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1587 LpExtend(ref lp, _, LpDeref(_)) => {
1588 write!(f, "{}.*", lp)
1591 LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1592 write!(f, "{}.{:?}", lp, interior)