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