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