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