]> git.lizzy.rs Git - rust.git/blob - src/librustc_borrowck/borrowck/mod.rs
Fix invalid associated type rendering in rustdoc
[rust.git] / src / librustc_borrowck / borrowck / mod.rs
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.
4 //
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.
10
11 //! See The Book chapter on the borrow checker for more details.
12
13 #![allow(non_camel_case_types)]
14
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::*;
20
21 pub use self::mir::elaborate_drops::ElaborateDrops;
22
23 use self::InteriorKind::*;
24
25 use rustc::dep_graph::DepNode;
26 use rustc::hir::map as hir_map;
27 use rustc::hir::map::blocks::FnLikeNode;
28 use rustc::cfg;
29 use rustc::middle::dataflow::DataFlowContext;
30 use rustc::middle::dataflow::BitwiseOperator;
31 use rustc::middle::dataflow::DataFlowOperator;
32 use rustc::middle::dataflow::KillFrom;
33 use rustc::hir::def_id::DefId;
34 use rustc::middle::expr_use_visitor as euv;
35 use rustc::middle::mem_categorization as mc;
36 use rustc::middle::mem_categorization::Categorization;
37 use rustc::middle::mem_categorization::ImmutabilityBlame;
38 use rustc::middle::region;
39 use rustc::ty::{self, TyCtxt};
40
41 use std::fmt;
42 use std::rc::Rc;
43 use std::hash::{Hash, Hasher};
44 use syntax::ast;
45 use syntax_pos::{MultiSpan, Span};
46 use errors::DiagnosticBuilder;
47
48 use rustc::hir;
49 use rustc::hir::intravisit::{self, Visitor};
50
51 pub mod check_loans;
52
53 pub mod gather_loans;
54
55 pub mod move_data;
56
57 mod mir;
58
59 #[derive(Clone, Copy)]
60 pub struct LoanDataFlowOperator;
61
62 pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
63
64 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
65     tcx.dep_graph.with_task(DepNode::BorrowCheckKrate, tcx, (), check_crate_task);
66
67     fn check_crate_task<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, (): ()) {
68         tcx.visit_all_bodies_in_krate(|body_owner_def_id, body_id| {
69             tcx.dep_graph.with_task(DepNode::BorrowCheck(body_owner_def_id),
70                                     tcx,
71                                     body_id,
72                                     borrowck_fn);
73         });
74     }
75 }
76
77 /// Collection of conclusions determined via borrow checker analyses.
78 pub struct AnalysisData<'a, 'tcx: 'a> {
79     pub all_loans: Vec<Loan<'tcx>>,
80     pub loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>,
81     pub move_data: move_data::FlowedMoveData<'a, 'tcx>,
82 }
83
84 fn borrowck_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, body_id: hir::BodyId) {
85     debug!("borrowck_fn(body_id={:?})", body_id);
86
87     let owner_id = tcx.hir.body_owner(body_id);
88     let owner_def_id = tcx.hir.local_def_id(owner_id);
89     let attributes = tcx.get_attrs(owner_def_id);
90     let tables = tcx.item_tables(owner_def_id);
91
92     let mut bccx = &mut BorrowckCtxt {
93         tcx: tcx,
94         tables: tables,
95     };
96
97     let body = bccx.tcx.hir.body(body_id);
98
99     if bccx.tcx.has_attr(owner_def_id, "rustc_mir_borrowck") {
100         mir::borrowck_mir(bccx, owner_id, &attributes);
101     }
102
103     let cfg = cfg::CFG::new(bccx.tcx, &body);
104     let AnalysisData { all_loans,
105                        loans: loan_dfcx,
106                        move_data: flowed_moves } =
107         build_borrowck_dataflow_data(bccx, &cfg, body_id);
108
109     move_data::fragments::instrument_move_fragments(&flowed_moves.move_data,
110                                                     bccx.tcx,
111                                                     owner_id);
112     move_data::fragments::build_unfragmented_map(bccx,
113                                                  &flowed_moves.move_data,
114                                                  owner_id);
115
116     check_loans::check_loans(bccx, &loan_dfcx, &flowed_moves, &all_loans, body);
117 }
118
119 fn build_borrowck_dataflow_data<'a, 'tcx>(this: &mut BorrowckCtxt<'a, 'tcx>,
120                                           cfg: &cfg::CFG,
121                                           body_id: hir::BodyId)
122                                           -> AnalysisData<'a, 'tcx>
123 {
124     // Check the body of fn items.
125     let tcx = this.tcx;
126     let body = tcx.hir.body(body_id);
127     let id_range = {
128         let mut visitor = intravisit::IdRangeComputingVisitor::new(&tcx.hir);
129         visitor.visit_body(body);
130         visitor.result()
131     };
132     let (all_loans, move_data) =
133         gather_loans::gather_loans_in_fn(this, body_id);
134
135     let mut loan_dfcx =
136         DataFlowContext::new(this.tcx,
137                              "borrowck",
138                              Some(body),
139                              cfg,
140                              LoanDataFlowOperator,
141                              id_range,
142                              all_loans.len());
143     for (loan_idx, loan) in all_loans.iter().enumerate() {
144         loan_dfcx.add_gen(loan.gen_scope.node_id(&tcx.region_maps), loan_idx);
145         loan_dfcx.add_kill(KillFrom::ScopeEnd,
146                            loan.kill_scope.node_id(&tcx.region_maps), loan_idx);
147     }
148     loan_dfcx.add_kills_from_flow_exits(cfg);
149     loan_dfcx.propagate(cfg, body);
150
151     let flowed_moves = move_data::FlowedMoveData::new(move_data,
152                                                       this.tcx,
153                                                       cfg,
154                                                       id_range,
155                                                       body);
156
157     AnalysisData { all_loans: all_loans,
158                    loans: loan_dfcx,
159                    move_data:flowed_moves }
160 }
161
162 /// Accessor for introspective clients inspecting `AnalysisData` and
163 /// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer.
164 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
165     tcx: TyCtxt<'a, 'tcx, 'tcx>,
166     body_id: hir::BodyId,
167     cfg: &cfg::CFG)
168     -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
169 {
170     let owner_id = tcx.hir.body_owner(body_id);
171     let owner_def_id = tcx.hir.local_def_id(owner_id);
172     let tables = tcx.item_tables(owner_def_id);
173
174     let mut bccx = BorrowckCtxt {
175         tcx: tcx,
176         tables: tables,
177     };
178
179     let dataflow_data = build_borrowck_dataflow_data(&mut bccx, cfg, body_id);
180     (bccx, dataflow_data)
181 }
182
183 // ----------------------------------------------------------------------
184 // Type definitions
185
186 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
187     tcx: TyCtxt<'a, 'tcx, 'tcx>,
188
189     // tables for the current thing we are checking; set to
190     // Some in `borrowck_fn` and cleared later
191     tables: &'a ty::TypeckTables<'tcx>,
192 }
193
194 ///////////////////////////////////////////////////////////////////////////
195 // Loans and loan paths
196
197 /// Record of a loan that was issued.
198 pub struct Loan<'tcx> {
199     index: usize,
200     loan_path: Rc<LoanPath<'tcx>>,
201     kind: ty::BorrowKind,
202     restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
203
204     /// gen_scope indicates where loan is introduced. Typically the
205     /// loan is introduced at the point of the borrow, but in some
206     /// cases, notably method arguments, the loan may be introduced
207     /// only later, once it comes into scope.  See also
208     /// `GatherLoanCtxt::compute_gen_scope`.
209     gen_scope: region::CodeExtent,
210
211     /// kill_scope indicates when the loan goes out of scope.  This is
212     /// either when the lifetime expires or when the local variable
213     /// which roots the loan-path goes out of scope, whichever happens
214     /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
215     kill_scope: region::CodeExtent,
216     span: Span,
217     cause: euv::LoanCause,
218 }
219
220 impl<'tcx> Loan<'tcx> {
221     pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
222         self.loan_path.clone()
223     }
224 }
225
226 #[derive(Eq)]
227 pub struct LoanPath<'tcx> {
228     kind: LoanPathKind<'tcx>,
229     ty: ty::Ty<'tcx>,
230 }
231
232 impl<'tcx> PartialEq for LoanPath<'tcx> {
233     fn eq(&self, that: &LoanPath<'tcx>) -> bool {
234         self.kind == that.kind
235     }
236 }
237
238 impl<'tcx> Hash for LoanPath<'tcx> {
239     fn hash<H: Hasher>(&self, state: &mut H) {
240         self.kind.hash(state);
241     }
242 }
243
244 #[derive(PartialEq, Eq, Hash, Debug)]
245 pub enum LoanPathKind<'tcx> {
246     LpVar(ast::NodeId),                         // `x` in README.md
247     LpUpvar(ty::UpvarId),                       // `x` captured by-value into closure
248     LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
249     LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem<'tcx>)
250 }
251
252 impl<'tcx> LoanPath<'tcx> {
253     fn new(kind: LoanPathKind<'tcx>, ty: ty::Ty<'tcx>) -> LoanPath<'tcx> {
254         LoanPath { kind: kind, ty: ty }
255     }
256
257     fn to_type(&self) -> ty::Ty<'tcx> { self.ty }
258 }
259
260 // FIXME (pnkfelix): See discussion here
261 // https://github.com/pnkfelix/rust/commit/
262 //     b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
263 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
264
265 // A local, "cleaned" version of `mc::InteriorKind` that drops
266 // information that is not relevant to loan-path analysis. (In
267 // particular, the distinction between how precisely an array-element
268 // is tracked is irrelevant here.)
269 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
270 pub enum InteriorKind {
271     InteriorField(mc::FieldName),
272     InteriorElement(mc::ElementKind),
273 }
274
275 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
276 impl ToInteriorKind for mc::InteriorKind {
277     fn cleaned(self) -> InteriorKind {
278         match self {
279             mc::InteriorField(name) => InteriorField(name),
280             mc::InteriorElement(_, elem_kind) => InteriorElement(elem_kind),
281         }
282     }
283 }
284
285 // This can be:
286 // - a pointer dereference (`*LV` in README.md)
287 // - a field reference, with an optional definition of the containing
288 //   enum variant (`LV.f` in README.md)
289 // `DefId` is present when the field is part of struct that is in
290 // a variant of an enum. For instance in:
291 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
292 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
293 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
294 pub enum LoanPathElem<'tcx> {
295     LpDeref(mc::PointerKind<'tcx>),
296     LpInterior(Option<DefId>, InteriorKind),
297 }
298
299 pub fn closure_to_block(closure_id: ast::NodeId,
300                         tcx: TyCtxt) -> ast::NodeId {
301     match tcx.hir.get(closure_id) {
302         hir_map::NodeExpr(expr) => match expr.node {
303             hir::ExprClosure(.., body_id, _) => {
304                 body_id.node_id
305             }
306             _ => {
307                 bug!("encountered non-closure id: {}", closure_id)
308             }
309         },
310         _ => bug!("encountered non-expr id: {}", closure_id)
311     }
312 }
313
314 impl<'a, 'tcx> LoanPath<'tcx> {
315     pub fn kill_scope(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> region::CodeExtent {
316         match self.kind {
317             LpVar(local_id) => tcx.region_maps.var_scope(local_id),
318             LpUpvar(upvar_id) => {
319                 let block_id = closure_to_block(upvar_id.closure_expr_id, tcx);
320                 tcx.region_maps.node_extent(block_id)
321             }
322             LpDowncast(ref base, _) |
323             LpExtend(ref base, ..) => base.kill_scope(tcx),
324         }
325     }
326
327     fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
328         match (&self.kind, &other.kind) {
329             (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
330              &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
331                 if id == id2 && opt_variant_id == opt_variant_id2 {
332                     base.has_fork(&base2)
333                 } else {
334                     true
335                 },
336             (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
337             (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&base),
338             _ => false,
339         }
340     }
341
342     fn depth(&self) -> usize {
343         match self.kind {
344             LpExtend(ref base, _, LpDeref(_)) => base.depth(),
345             LpExtend(ref base, _, LpInterior(..)) => base.depth() + 1,
346             _ => 0,
347         }
348     }
349
350     fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
351         match (&self.kind, &other.kind) {
352             (&LpExtend(ref base, a, LpInterior(opt_variant_id, id)),
353              &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) => {
354                 if id == id2 && opt_variant_id == opt_variant_id2 {
355                     base.common(&base2).map(|x| {
356                         let xd = x.depth();
357                         if base.depth() == xd && base2.depth() == xd {
358                             LoanPath {
359                                 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
360                                 ty: self.ty,
361                             }
362                         } else {
363                             x
364                         }
365                     })
366                 } else {
367                     base.common(&base2)
368                 }
369             }
370             (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
371             (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&other),
372             (&LpVar(id), &LpVar(id2)) => {
373                 if id == id2 {
374                     Some(LoanPath { kind: LpVar(id), ty: self.ty })
375                 } else {
376                     None
377                 }
378             }
379             (&LpUpvar(id), &LpUpvar(id2)) => {
380                 if id == id2 {
381                     Some(LoanPath { kind: LpUpvar(id), ty: self.ty })
382                 } else {
383                     None
384                 }
385             }
386             _ => None,
387         }
388     }
389 }
390
391 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
392     //! Computes the `LoanPath` (if any) for a `cmt`.
393     //! Note that this logic is somewhat duplicated in
394     //! the method `compute()` found in `gather_loans::restrictions`,
395     //! which allows it to share common loan path pieces as it
396     //! traverses the CMT.
397
398     let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
399
400     match cmt.cat {
401         Categorization::Rvalue(..) |
402         Categorization::StaticItem => {
403             None
404         }
405
406         Categorization::Local(id) => {
407             Some(new_lp(LpVar(id)))
408         }
409
410         Categorization::Upvar(mc::Upvar { id, .. }) => {
411             Some(new_lp(LpUpvar(id)))
412         }
413
414         Categorization::Deref(ref cmt_base, _, pk) => {
415             opt_loan_path(cmt_base).map(|lp| {
416                 new_lp(LpExtend(lp, cmt.mutbl, LpDeref(pk)))
417             })
418         }
419
420         Categorization::Interior(ref cmt_base, ik) => {
421             opt_loan_path(cmt_base).map(|lp| {
422                 let opt_variant_id = match cmt_base.cat {
423                     Categorization::Downcast(_, did) =>  Some(did),
424                     _ => None
425                 };
426                 new_lp(LpExtend(lp, cmt.mutbl, LpInterior(opt_variant_id, ik.cleaned())))
427             })
428         }
429
430         Categorization::Downcast(ref cmt_base, variant_def_id) =>
431             opt_loan_path(cmt_base)
432             .map(|lp| {
433                 new_lp(LpDowncast(lp, variant_def_id))
434             }),
435
436     }
437 }
438
439 ///////////////////////////////////////////////////////////////////////////
440 // Errors
441
442 // Errors that can occur
443 #[derive(Debug, PartialEq)]
444 pub enum bckerr_code<'tcx> {
445     err_mutbl,
446     /// superscope, subscope, loan cause
447     err_out_of_scope(&'tcx ty::Region, &'tcx ty::Region, euv::LoanCause),
448     err_borrowed_pointer_too_short(&'tcx ty::Region, &'tcx ty::Region), // loan, ptr
449 }
450
451 // Combination of an error code and the categorization of the expression
452 // that caused it
453 #[derive(Debug, PartialEq)]
454 pub struct BckError<'tcx> {
455     span: Span,
456     cause: AliasableViolationKind,
457     cmt: mc::cmt<'tcx>,
458     code: bckerr_code<'tcx>
459 }
460
461 #[derive(Copy, Clone, Debug, PartialEq)]
462 pub enum AliasableViolationKind {
463     MutabilityViolation,
464     BorrowViolation(euv::LoanCause)
465 }
466
467 #[derive(Copy, Clone, Debug)]
468 pub enum MovedValueUseKind {
469     MovedInUse,
470     MovedInCapture,
471 }
472
473 ///////////////////////////////////////////////////////////////////////////
474 // Misc
475
476 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
477     pub fn is_subregion_of(&self,
478                            r_sub: &'tcx ty::Region,
479                            r_sup: &'tcx ty::Region)
480                            -> bool
481     {
482         self.tables.free_region_map.is_subregion_of(self.tcx, r_sub, r_sup)
483     }
484
485     pub fn report(&self, err: BckError<'tcx>) {
486         // Catch and handle some particular cases.
487         match (&err.code, &err.cause) {
488             (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _),
489              &BorrowViolation(euv::ClosureCapture(span))) |
490             (&err_out_of_scope(&ty::ReScope(_), &ty::ReFree(..), _),
491              &BorrowViolation(euv::ClosureCapture(span))) => {
492                 return self.report_out_of_scope_escaping_closure_capture(&err, span);
493             }
494             _ => { }
495         }
496
497         let mut db = self.bckerr_to_diag(&err);
498         self.note_and_explain_bckerr(&mut db, err);
499         db.emit();
500     }
501
502     pub fn report_use_of_moved_value(&self,
503                                      use_span: Span,
504                                      use_kind: MovedValueUseKind,
505                                      lp: &LoanPath<'tcx>,
506                                      the_move: &move_data::Move,
507                                      moved_lp: &LoanPath<'tcx>,
508                                      _param_env: &ty::ParameterEnvironment<'tcx>) {
509         let (verb, verb_participle) = match use_kind {
510             MovedInUse => ("use", "used"),
511             MovedInCapture => ("capture", "captured"),
512         };
513
514         let (_ol, _moved_lp_msg, mut err) = match the_move.kind {
515             move_data::Declared => {
516                 // If this is an uninitialized variable, just emit a simple warning
517                 // and return.
518                 struct_span_err!(
519                     self.tcx.sess, use_span, E0381,
520                     "{} of possibly uninitialized variable: `{}`",
521                     verb,
522                     self.loan_path_to_string(lp))
523                 .span_label(use_span, &format!("use of possibly uninitialized `{}`",
524                     self.loan_path_to_string(lp)))
525                 .emit();
526                 return;
527             }
528             _ => {
529                 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
530                 // normally generate a rather confusing message:
531                 //
532                 //     error: use of moved value: `x.b`
533                 //     note: `x.a` moved here...
534                 //
535                 // What we want to do instead is get the 'common ancestor' of the two moves and
536                 // use that for most of the message instead, giving is something like this:
537                 //
538                 //     error: use of moved value: `x`
539                 //     note: `x` moved here (through moving `x.a`)...
540
541                 let common = moved_lp.common(lp);
542                 let has_common = common.is_some();
543                 let has_fork = moved_lp.has_fork(lp);
544                 let (nl, ol, moved_lp_msg) =
545                     if has_fork && has_common {
546                         let nl = self.loan_path_to_string(&common.unwrap());
547                         let ol = nl.clone();
548                         let moved_lp_msg = format!(" (through moving `{}`)",
549                                                    self.loan_path_to_string(moved_lp));
550                         (nl, ol, moved_lp_msg)
551                     } else {
552                         (self.loan_path_to_string(lp),
553                          self.loan_path_to_string(moved_lp),
554                          String::new())
555                     };
556
557                 let partial = moved_lp.depth() > lp.depth();
558                 let msg = if !has_fork && partial { "partially " }
559                           else if has_fork && !has_common { "collaterally "}
560                           else { "" };
561                 let err = struct_span_err!(
562                     self.tcx.sess, use_span, E0382,
563                     "{} of {}moved value: `{}`",
564                     verb, msg, nl);
565                 (ol, moved_lp_msg, err)}
566         };
567
568         // Get type of value and span where it was previously
569         // moved.
570         let (move_span, move_note) = match the_move.kind {
571             move_data::Declared => {
572                 unreachable!();
573             }
574
575             move_data::MoveExpr |
576             move_data::MovePat =>
577                 (self.tcx.hir.span(the_move.id), ""),
578
579             move_data::Captured =>
580                 (match self.tcx.hir.expect_expr(the_move.id).node {
581                     hir::ExprClosure(.., fn_decl_span) => fn_decl_span,
582                     ref r => bug!("Captured({}) maps to non-closure: {:?}",
583                                   the_move.id, r),
584                 }, " (into closure)"),
585         };
586
587         // Annotate the use and the move in the span. Watch out for
588         // the case where the use and the move are the same. This
589         // means the use is in a loop.
590         err = if use_span == move_span {
591             err.span_label(
592                 use_span,
593                 &format!("value moved{} here in previous iteration of loop",
594                          move_note));
595             err
596         } else {
597             err.span_label(use_span, &format!("value {} here after move", verb_participle))
598                .span_label(move_span, &format!("value moved{} here", move_note));
599             err
600         };
601
602         err.note(&format!("move occurs because `{}` has type `{}`, \
603                            which does not implement the `Copy` trait",
604                           self.loan_path_to_string(moved_lp),
605                           moved_lp.ty));
606
607         // Note: we used to suggest adding a `ref binding` or calling
608         // `clone` but those suggestions have been removed because
609         // they are often not what you actually want to do, and were
610         // not considered particularly helpful.
611
612         err.emit();
613     }
614
615     pub fn report_partial_reinitialization_of_uninitialized_structure(
616             &self,
617             span: Span,
618             lp: &LoanPath<'tcx>) {
619         span_err!(
620             self.tcx.sess, span, E0383,
621             "partial reinitialization of uninitialized structure `{}`",
622             self.loan_path_to_string(lp));
623     }
624
625     pub fn report_reassigned_immutable_variable(&self,
626                                                 span: Span,
627                                                 lp: &LoanPath<'tcx>,
628                                                 assign:
629                                                 &move_data::Assignment) {
630         let mut err = struct_span_err!(
631             self.tcx.sess, span, E0384,
632             "re-assignment of immutable variable `{}`",
633             self.loan_path_to_string(lp));
634         err.span_label(span, &format!("re-assignment of immutable variable"));
635         if span != assign.span {
636             err.span_label(assign.span, &format!("first assignment to `{}`",
637                                               self.loan_path_to_string(lp)));
638         }
639         err.emit();
640     }
641
642     pub fn span_err(&self, s: Span, m: &str) {
643         self.tcx.sess.span_err(s, m);
644     }
645
646     pub fn struct_span_err<S: Into<MultiSpan>>(&self, s: S, m: &str)
647                                               -> DiagnosticBuilder<'a> {
648         self.tcx.sess.struct_span_err(s, m)
649     }
650
651     pub fn struct_span_err_with_code<S: Into<MultiSpan>>(&self,
652                                                          s: S,
653                                                          msg: &str,
654                                                          code: &str)
655                                                          -> DiagnosticBuilder<'a> {
656         self.tcx.sess.struct_span_err_with_code(s, msg, code)
657     }
658
659     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, s: S, msg: &str, code: &str) {
660         self.tcx.sess.span_err_with_code(s, msg, code);
661     }
662
663     fn bckerr_to_diag(&self, err: &BckError<'tcx>) -> DiagnosticBuilder<'a> {
664         let span = err.span.clone();
665
666         let msg = match err.code {
667             err_mutbl => {
668                 let descr = match err.cmt.note {
669                     mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
670                         self.cmt_to_string(&err.cmt)
671                     }
672                     _ => match opt_loan_path(&err.cmt) {
673                         None => {
674                             format!("{} {}",
675                                     err.cmt.mutbl.to_user_str(),
676                                     self.cmt_to_string(&err.cmt))
677
678                         }
679                         Some(lp) => {
680                             format!("{} {} `{}`",
681                                     err.cmt.mutbl.to_user_str(),
682                                     self.cmt_to_string(&err.cmt),
683                                     self.loan_path_to_string(&lp))
684                         }
685                     }
686                 };
687
688                 match err.cause {
689                     MutabilityViolation => {
690                         format!("cannot assign to {}", descr)
691                     }
692                     BorrowViolation(euv::ClosureCapture(_)) => {
693                         format!("closure cannot assign to {}", descr)
694                     }
695                     BorrowViolation(euv::OverloadedOperator) |
696                     BorrowViolation(euv::AddrOf) |
697                     BorrowViolation(euv::RefBinding) |
698                     BorrowViolation(euv::AutoRef) |
699                     BorrowViolation(euv::AutoUnsafe) |
700                     BorrowViolation(euv::ForLoop) |
701                     BorrowViolation(euv::MatchDiscriminant) => {
702                         format!("cannot borrow {} as mutable", descr)
703                     }
704                     BorrowViolation(euv::ClosureInvocation) => {
705                         span_bug!(err.span,
706                             "err_mutbl with a closure invocation");
707                     }
708                 }
709             }
710             err_out_of_scope(..) => {
711                 let msg = match opt_loan_path(&err.cmt) {
712                     None => "borrowed value".to_string(),
713                     Some(lp) => {
714                         format!("`{}`", self.loan_path_to_string(&lp))
715                     }
716                 };
717                 format!("{} does not live long enough", msg)
718             }
719             err_borrowed_pointer_too_short(..) => {
720                 let descr = self.cmt_to_path_or_string(&err.cmt);
721                 format!("lifetime of {} is too short to guarantee \
722                          its contents can be safely reborrowed",
723                         descr)
724             }
725         };
726
727         self.struct_span_err(span, &msg)
728     }
729
730     pub fn report_aliasability_violation(&self,
731                                          span: Span,
732                                          kind: AliasableViolationKind,
733                                          cause: mc::AliasableReason,
734                                          cmt: mc::cmt<'tcx>) {
735         let mut is_closure = false;
736         let prefix = match kind {
737             MutabilityViolation => {
738                 "cannot assign to data"
739             }
740             BorrowViolation(euv::ClosureCapture(_)) |
741             BorrowViolation(euv::OverloadedOperator) |
742             BorrowViolation(euv::AddrOf) |
743             BorrowViolation(euv::AutoRef) |
744             BorrowViolation(euv::AutoUnsafe) |
745             BorrowViolation(euv::RefBinding) |
746             BorrowViolation(euv::MatchDiscriminant) => {
747                 "cannot borrow data mutably"
748             }
749
750             BorrowViolation(euv::ClosureInvocation) => {
751                 is_closure = true;
752                 "closure invocation"
753             }
754
755             BorrowViolation(euv::ForLoop) => {
756                 "`for` loop"
757             }
758         };
759
760         match cause {
761             mc::AliasableStatic |
762             mc::AliasableStaticMut => {
763                 // This path cannot occur. It happens when we have an
764                 // `&mut` or assignment to a static. But in the case
765                 // of `static X`, we get a mutability violation first,
766                 // and never get here. In the case of `static mut X`,
767                 // that is unsafe and hence the aliasability error is
768                 // ignored.
769                 span_bug!(span, "aliasability violation for static `{}`", prefix)
770             }
771             mc::AliasableBorrowed => {}
772         };
773         let blame = cmt.immutability_blame();
774         let mut err = match blame {
775             Some(ImmutabilityBlame::ClosureEnv(id)) => {
776                 let mut err = struct_span_err!(
777                     self.tcx.sess, span, E0387,
778                     "{} in a captured outer variable in an `Fn` closure", prefix);
779
780                 // FIXME: the distinction between these 2 messages looks wrong.
781                 let help = if let BorrowViolation(euv::ClosureCapture(_)) = kind {
782                     // The aliasability violation with closure captures can
783                     // happen for nested closures, so we know the enclosing
784                     // closure incorrectly accepts an `Fn` while it needs to
785                     // be `FnMut`.
786                     "consider changing this to accept closures that implement `FnMut`"
787
788                 } else {
789                     "consider changing this closure to take self by mutable reference"
790                 };
791                 err.span_help(self.tcx.hir.span(id), help);
792                 err
793             }
794             _ =>  {
795                 let mut err = struct_span_err!(
796                     self.tcx.sess, span, E0389,
797                     "{} in a `&` reference", prefix);
798                 err.span_label(span, &"assignment into an immutable reference");
799                 err
800             }
801         };
802         self.note_immutability_blame(&mut err, blame);
803
804         if is_closure {
805             err.help("closures behind references must be called via `&mut`");
806         }
807         err.emit();
808     }
809
810     /// Given a type, if it is an immutable reference, return a suggestion to make it mutable
811     fn suggest_mut_for_immutable(&self, pty: &hir::Ty, is_implicit_self: bool) -> Option<String> {
812         // Check wether the argument is an immutable reference
813         debug!("suggest_mut_for_immutable({:?}, {:?})", pty, is_implicit_self);
814         if let hir::TyRptr(lifetime, hir::MutTy {
815             mutbl: hir::Mutability::MutImmutable,
816             ref ty
817         }) = pty.node {
818             // Account for existing lifetimes when generating the message
819             let pointee_snippet = match self.tcx.sess.codemap().span_to_snippet(ty.span) {
820                 Ok(snippet) => snippet,
821                 _ => return None
822             };
823
824             let lifetime_snippet = if !lifetime.is_elided() {
825                 format!("{} ", match self.tcx.sess.codemap().span_to_snippet(lifetime.span) {
826                     Ok(lifetime_snippet) => lifetime_snippet,
827                     _ => return None
828                 })
829             } else {
830                 String::new()
831             };
832             Some(format!("use `&{}mut {}` here to make mutable",
833                          lifetime_snippet,
834                          if is_implicit_self { "self" } else { &*pointee_snippet }))
835         } else {
836             None
837         }
838     }
839
840     fn local_binding_mode(&self, node_id: ast::NodeId) -> hir::BindingMode {
841         let pat = match self.tcx.hir.get(node_id) {
842             hir_map::Node::NodeLocal(pat) => pat,
843             node => bug!("bad node for local: {:?}", node)
844         };
845
846         match pat.node {
847             hir::PatKind::Binding(mode, ..) => mode,
848             _ => bug!("local is not a binding: {:?}", pat)
849         }
850     }
851
852     fn local_ty(&self, node_id: ast::NodeId) -> (Option<&hir::Ty>, bool) {
853         let parent = self.tcx.hir.get_parent_node(node_id);
854         let parent_node = self.tcx.hir.get(parent);
855
856         // The parent node is like a fn
857         if let Some(fn_like) = FnLikeNode::from_node(parent_node) {
858             // `nid`'s parent's `Body`
859             let fn_body = self.tcx.hir.body(fn_like.body());
860             // Get the position of `node_id` in the arguments list
861             let arg_pos = fn_body.arguments.iter().position(|arg| arg.pat.id == node_id);
862             if let Some(i) = arg_pos {
863                 // The argument's `Ty`
864                 (Some(&fn_like.decl().inputs[i]),
865                  i == 0 && fn_like.decl().has_implicit_self)
866             } else {
867                 (None, false)
868             }
869         } else {
870             (None, false)
871         }
872     }
873
874     fn note_immutability_blame(&self,
875                                db: &mut DiagnosticBuilder,
876                                blame: Option<ImmutabilityBlame>) {
877         match blame {
878             None => {}
879             Some(ImmutabilityBlame::ClosureEnv(_)) => {}
880             Some(ImmutabilityBlame::ImmLocal(node_id)) => {
881                 let let_span = self.tcx.hir.span(node_id);
882                 if let hir::BindingMode::BindByValue(..) = self.local_binding_mode(node_id) {
883                     if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(let_span) {
884                         let (_, is_implicit_self) = self.local_ty(node_id);
885                         if is_implicit_self && snippet != "self" {
886                             // avoid suggesting `mut &self`.
887                             return
888                         }
889                         db.span_label(
890                             let_span,
891                             &format!("consider changing this to `mut {}`", snippet)
892                         );
893                     }
894                 }
895             }
896             Some(ImmutabilityBlame::LocalDeref(node_id)) => {
897                 let let_span = self.tcx.hir.span(node_id);
898                 match self.local_binding_mode(node_id) {
899                     hir::BindingMode::BindByRef(..) => {
900                         let snippet = self.tcx.sess.codemap().span_to_snippet(let_span);
901                         if let Ok(snippet) = snippet {
902                             db.span_label(
903                                 let_span,
904                                 &format!("consider changing this to `{}`",
905                                          snippet.replace("ref ", "ref mut "))
906                             );
907                         }
908                     }
909                     hir::BindingMode::BindByValue(..) => {
910                         if let (Some(local_ty), is_implicit_self) = self.local_ty(node_id) {
911                             if let Some(msg) =
912                                  self.suggest_mut_for_immutable(local_ty, is_implicit_self) {
913                                 db.span_label(local_ty.span, &msg);
914                             }
915                         }
916                     }
917                 }
918             }
919             Some(ImmutabilityBlame::AdtFieldDeref(_, field)) => {
920                 let node_id = match self.tcx.hir.as_local_node_id(field.did) {
921                     Some(node_id) => node_id,
922                     None => return
923                 };
924
925                 if let hir_map::Node::NodeField(ref field) = self.tcx.hir.get(node_id) {
926                     if let Some(msg) = self.suggest_mut_for_immutable(&field.ty, false) {
927                         db.span_label(field.ty.span, &msg);
928                     }
929                 }
930             }
931         }
932     }
933
934     fn report_out_of_scope_escaping_closure_capture(&self,
935                                                     err: &BckError<'tcx>,
936                                                     capture_span: Span)
937     {
938         let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
939
940         let suggestion =
941             match self.tcx.sess.codemap().span_to_snippet(err.span) {
942                 Ok(string) => format!("move {}", string),
943                 Err(_) => format!("move |<args>| <body>")
944             };
945
946         struct_span_err!(self.tcx.sess, err.span, E0373,
947                          "closure may outlive the current function, \
948                           but it borrows {}, \
949                           which is owned by the current function",
950                          cmt_path_or_string)
951             .span_label(capture_span,
952                        &format!("{} is borrowed here",
953                                 cmt_path_or_string))
954             .span_label(err.span,
955                        &format!("may outlive borrowed value {}",
956                                 cmt_path_or_string))
957             .span_suggestion(err.span,
958                              &format!("to force the closure to take ownership of {} \
959                                        (and any other referenced variables), \
960                                        use the `move` keyword, as shown:",
961                                        cmt_path_or_string),
962                              suggestion)
963             .emit();
964     }
965
966     fn region_end_span(&self, region: &'tcx ty::Region) -> Option<Span> {
967         match *region {
968             ty::ReScope(scope) => {
969                 match scope.span(&self.tcx.region_maps, &self.tcx.hir) {
970                     Some(s) => {
971                         Some(s.end_point())
972                     }
973                     None => {
974                         None
975                     }
976                 }
977             }
978             _ => None
979         }
980     }
981
982     fn note_and_explain_bckerr(&self, db: &mut DiagnosticBuilder, err: BckError<'tcx>) {
983         let error_span = err.span.clone();
984         match err.code {
985             err_mutbl => {
986                 self.note_and_explain_mutbl_error(db, &err, &error_span);
987                 self.note_immutability_blame(db, err.cmt.immutability_blame());
988             }
989             err_out_of_scope(super_scope, sub_scope, cause) => {
990                 let (value_kind, value_msg) = match err.cmt.cat {
991                     mc::Categorization::Rvalue(..) =>
992                         ("temporary value", "temporary value created here"),
993                     _ =>
994                         ("borrowed value", "borrow occurs here")
995                 };
996
997                 let is_closure = match cause {
998                     euv::ClosureCapture(s) => {
999                         // The primary span starts out as the closure creation point.
1000                         // Change the primary span here to highlight the use of the variable
1001                         // in the closure, because it seems more natural. Highlight
1002                         // closure creation point as a secondary span.
1003                         match db.span.primary_span() {
1004                             Some(primary) => {
1005                                 db.span = MultiSpan::from_span(s);
1006                                 db.span_label(primary, &format!("capture occurs here"));
1007                                 db.span_label(s, &"does not live long enough");
1008                                 true
1009                             }
1010                             None => false
1011                         }
1012                     }
1013                     _ => {
1014                         db.span_label(error_span, &"does not live long enough");
1015                         false
1016                     }
1017                 };
1018
1019                 let sub_span = self.region_end_span(sub_scope);
1020                 let super_span = self.region_end_span(super_scope);
1021
1022                 match (sub_span, super_span) {
1023                     (Some(s1), Some(s2)) if s1 == s2 => {
1024                         if !is_closure {
1025                             db.span = MultiSpan::from_span(s1);
1026                             db.span_label(error_span, &value_msg);
1027                             let msg = match opt_loan_path(&err.cmt) {
1028                                 None => value_kind.to_string(),
1029                                 Some(lp) => {
1030                                     format!("`{}`", self.loan_path_to_string(&lp))
1031                                 }
1032                             };
1033                             db.span_label(s1,
1034                                           &format!("{} dropped here while still borrowed", msg));
1035                         } else {
1036                             db.span_label(s1, &format!("{} dropped before borrower", value_kind));
1037                         }
1038                         db.note("values in a scope are dropped in the opposite order \
1039                                 they are created");
1040                     }
1041                     (Some(s1), Some(s2)) if !is_closure => {
1042                         db.span = MultiSpan::from_span(s2);
1043                         db.span_label(error_span, &value_msg);
1044                         let msg = match opt_loan_path(&err.cmt) {
1045                             None => value_kind.to_string(),
1046                             Some(lp) => {
1047                                 format!("`{}`", self.loan_path_to_string(&lp))
1048                             }
1049                         };
1050                         db.span_label(s2, &format!("{} dropped here while still borrowed", msg));
1051                         db.span_label(s1, &format!("{} needs to live until here", value_kind));
1052                     }
1053                     _ => {
1054                         match sub_span {
1055                             Some(s) => {
1056                                 db.span_label(s, &format!("{} needs to live until here",
1057                                                           value_kind));
1058                             }
1059                             None => {
1060                                 self.tcx.note_and_explain_region(
1061                                     db,
1062                                     "borrowed value must be valid for ",
1063                                     sub_scope,
1064                                     "...");
1065                             }
1066                         }
1067                         match super_span {
1068                             Some(s) => {
1069                                 db.span_label(s, &format!("{} only lives until here", value_kind));
1070                             }
1071                             None => {
1072                                 self.tcx.note_and_explain_region(
1073                                     db,
1074                                     "...but borrowed value is only valid for ",
1075                                     super_scope,
1076                                     "");
1077                             }
1078                         }
1079                     }
1080                 }
1081
1082                 if let Some(_) = statement_scope_span(self.tcx, super_scope) {
1083                     db.note("consider using a `let` binding to increase its lifetime");
1084                 }
1085
1086
1087
1088                 match err.cmt.cat {
1089                     mc::Categorization::Rvalue(r, or) if r != or => {
1090                         db.note("\
1091 before rustc 1.16, this temporary lived longer - see issue #39283 \
1092 (https://github.com/rust-lang/rust/issues/39283)");
1093                     }
1094                     _ => {}
1095                 }
1096             }
1097
1098             err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1099                 let descr = match opt_loan_path(&err.cmt) {
1100                     Some(lp) => {
1101                         format!("`{}`", self.loan_path_to_string(&lp))
1102                     }
1103                     None => self.cmt_to_string(&err.cmt),
1104                 };
1105                 self.tcx.note_and_explain_region(
1106                     db,
1107                     &format!("{} would have to be valid for ",
1108                             descr),
1109                     loan_scope,
1110                     "...");
1111                 self.tcx.note_and_explain_region(
1112                     db,
1113                     &format!("...but {} is only valid for ", descr),
1114                     ptr_scope,
1115                     "");
1116             }
1117         }
1118     }
1119
1120     fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'tcx>,
1121                                     error_span: &Span) {
1122         match err.cmt.note {
1123             mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1124                 // If this is an `Fn` closure, it simply can't mutate upvars.
1125                 // If it's an `FnMut` closure, the original variable was declared immutable.
1126                 // We need to determine which is the case here.
1127                 let kind = match err.cmt.upvar().unwrap().cat {
1128                     Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1129                     _ => bug!()
1130                 };
1131                 if kind == ty::ClosureKind::Fn {
1132                     db.span_help(self.tcx.hir.span(upvar_id.closure_expr_id),
1133                                  "consider changing this closure to take \
1134                                  self by mutable reference");
1135                 }
1136             }
1137             _ => {
1138                 if let Categorization::Deref(..) = err.cmt.cat {
1139                     db.span_label(*error_span, &"cannot borrow as mutable");
1140                 } else if let Categorization::Local(local_id) = err.cmt.cat {
1141                     let span = self.tcx.hir.span(local_id);
1142                     if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
1143                         if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
1144                             db.span_label(*error_span, &format!("cannot reborrow mutably"));
1145                             db.span_label(*error_span, &format!("try removing `&mut` here"));
1146                         } else {
1147                             db.span_label(*error_span, &format!("cannot borrow mutably"));
1148                         }
1149                     } else {
1150                         db.span_label(*error_span, &format!("cannot borrow mutably"));
1151                     }
1152                 } else if let Categorization::Interior(ref cmt, _) = err.cmt.cat {
1153                     if let mc::MutabilityCategory::McImmutable = cmt.mutbl {
1154                         db.span_label(*error_span,
1155                                       &"cannot mutably borrow immutable field");
1156                     }
1157                 }
1158             }
1159         }
1160     }
1161     pub fn append_loan_path_to_string(&self,
1162                                       loan_path: &LoanPath<'tcx>,
1163                                       out: &mut String) {
1164         match loan_path.kind {
1165             LpUpvar(ty::UpvarId{ var_id: id, closure_expr_id: _ }) |
1166             LpVar(id) => {
1167                 out.push_str(&self.tcx.local_var_name_str(id));
1168             }
1169
1170             LpDowncast(ref lp_base, variant_def_id) => {
1171                 out.push('(');
1172                 self.append_loan_path_to_string(&lp_base, out);
1173                 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1174                 out.push_str(&self.tcx.item_path_str(variant_def_id));
1175                 out.push(')');
1176             }
1177
1178             LpExtend(ref lp_base, _, LpInterior(_, InteriorField(fname))) => {
1179                 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1180                 match fname {
1181                     mc::NamedField(fname) => {
1182                         out.push('.');
1183                         out.push_str(&fname.as_str());
1184                     }
1185                     mc::PositionalField(idx) => {
1186                         out.push('.');
1187                         out.push_str(&idx.to_string());
1188                     }
1189                 }
1190             }
1191
1192             LpExtend(ref lp_base, _, LpInterior(_, InteriorElement(..))) => {
1193                 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1194                 out.push_str("[..]");
1195             }
1196
1197             LpExtend(ref lp_base, _, LpDeref(_)) => {
1198                 out.push('*');
1199                 self.append_loan_path_to_string(&lp_base, out);
1200             }
1201         }
1202     }
1203
1204     pub fn append_autoderefd_loan_path_to_string(&self,
1205                                                  loan_path: &LoanPath<'tcx>,
1206                                                  out: &mut String) {
1207         match loan_path.kind {
1208             LpExtend(ref lp_base, _, LpDeref(_)) => {
1209                 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1210                 // rules would normally allow users to omit the `*x`.
1211                 // So just serialize such paths to `x.f` or x[3]` respectively.
1212                 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1213             }
1214
1215             LpDowncast(ref lp_base, variant_def_id) => {
1216                 out.push('(');
1217                 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1218                 out.push(':');
1219                 out.push_str(&self.tcx.item_path_str(variant_def_id));
1220                 out.push(')');
1221             }
1222
1223             LpVar(..) | LpUpvar(..) | LpExtend(.., LpInterior(..)) => {
1224                 self.append_loan_path_to_string(loan_path, out)
1225             }
1226         }
1227     }
1228
1229     pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1230         let mut result = String::new();
1231         self.append_loan_path_to_string(loan_path, &mut result);
1232         result
1233     }
1234
1235     pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1236         cmt.descriptive_string(self.tcx)
1237     }
1238
1239     pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt<'tcx>) -> String {
1240         match opt_loan_path(cmt) {
1241             Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1242             None => self.cmt_to_string(cmt),
1243         }
1244     }
1245 }
1246
1247 fn statement_scope_span(tcx: TyCtxt, region: &ty::Region) -> Option<Span> {
1248     match *region {
1249         ty::ReScope(scope) => {
1250             match tcx.hir.find(scope.node_id(&tcx.region_maps)) {
1251                 Some(hir_map::NodeStmt(stmt)) => Some(stmt.span),
1252                 _ => None
1253             }
1254         }
1255         _ => None
1256     }
1257 }
1258
1259 impl BitwiseOperator for LoanDataFlowOperator {
1260     #[inline]
1261     fn join(&self, succ: usize, pred: usize) -> usize {
1262         succ | pred // loans from both preds are in scope
1263     }
1264 }
1265
1266 impl DataFlowOperator for LoanDataFlowOperator {
1267     #[inline]
1268     fn initial_value(&self) -> bool {
1269         false // no loans in scope by default
1270     }
1271 }
1272
1273 impl<'tcx> fmt::Debug for InteriorKind {
1274     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1275         match *self {
1276             InteriorField(mc::NamedField(fld)) => write!(f, "{}", fld),
1277             InteriorField(mc::PositionalField(i)) => write!(f, "#{}", i),
1278             InteriorElement(..) => write!(f, "[]"),
1279         }
1280     }
1281 }
1282
1283 impl<'tcx> fmt::Debug for Loan<'tcx> {
1284     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1285         write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1286                self.index,
1287                self.loan_path,
1288                self.kind,
1289                self.gen_scope,
1290                self.kill_scope,
1291                self.restricted_paths)
1292     }
1293 }
1294
1295 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1296     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1297         match self.kind {
1298             LpVar(id) => {
1299                 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_string(id)))
1300             }
1301
1302             LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => {
1303                 let s = ty::tls::with(|tcx| tcx.hir.node_to_string(var_id));
1304                 write!(f, "$({} captured by id={})", s, closure_expr_id)
1305             }
1306
1307             LpDowncast(ref lp, variant_def_id) => {
1308                 let variant_str = if variant_def_id.is_local() {
1309                     ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1310                 } else {
1311                     format!("{:?}", variant_def_id)
1312                 };
1313                 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1314             }
1315
1316             LpExtend(ref lp, _, LpDeref(_)) => {
1317                 write!(f, "{:?}.*", lp)
1318             }
1319
1320             LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1321                 write!(f, "{:?}.{:?}", lp, interior)
1322             }
1323         }
1324     }
1325 }
1326
1327 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1328     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1329         match self.kind {
1330             LpVar(id) => {
1331                 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir.node_to_user_string(id)))
1332             }
1333
1334             LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => {
1335                 let s = ty::tls::with(|tcx| tcx.hir.node_to_user_string(var_id));
1336                 write!(f, "$({} captured by closure)", s)
1337             }
1338
1339             LpDowncast(ref lp, variant_def_id) => {
1340                 let variant_str = if variant_def_id.is_local() {
1341                     ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1342                 } else {
1343                     format!("{:?}", variant_def_id)
1344                 };
1345                 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1346             }
1347
1348             LpExtend(ref lp, _, LpDeref(_)) => {
1349                 write!(f, "{}.*", lp)
1350             }
1351
1352             LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1353                 write!(f, "{}.{:?}", lp, interior)
1354             }
1355         }
1356     }
1357 }