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