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