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