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