]> git.lizzy.rs Git - rust.git/blob - src/librustc_borrowck/borrowck/mod.rs
Various minor/cosmetic improvements to code
[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: Default::default(),
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: Default::default(),
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: Default::default(),
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::ThreadLocal(..) |
524         Categorization::StaticItem => {
525             (None, false)
526         }
527
528         Categorization::Local(id) => {
529             (Some(new_lp(LpVar(id))), false)
530         }
531
532         Categorization::Upvar(mc::Upvar { id, .. }) => {
533             (Some(new_lp(LpUpvar(id))), false)
534         }
535
536         Categorization::Deref(ref cmt_base, pk) => {
537             let lp = opt_loan_path_is_field(cmt_base);
538             (lp.0.map(|lp| {
539                 new_lp(LpExtend(lp, cmt.mutbl, LpDeref(pk)))
540             }), lp.1)
541         }
542
543         Categorization::Interior(ref cmt_base, ik) => {
544             (opt_loan_path(cmt_base).map(|lp| {
545                 let opt_variant_id = match cmt_base.cat {
546                     Categorization::Downcast(_, did) =>  Some(did),
547                     _ => None
548                 };
549                 new_lp(LpExtend(lp, cmt.mutbl, LpInterior(opt_variant_id, ik.cleaned())))
550             }), true)
551         }
552
553         Categorization::Downcast(ref cmt_base, variant_def_id) => {
554             let lp = opt_loan_path_is_field(cmt_base);
555             (lp.0.map(|lp| {
556                 new_lp(LpDowncast(lp, variant_def_id))
557             }), lp.1)
558         }
559     }
560 }
561
562 /// Computes the `LoanPath` (if any) for a `cmt`.
563 /// Note that this logic is somewhat duplicated in
564 /// the method `compute()` found in `gather_loans::restrictions`,
565 /// which allows it to share common loan path pieces as it
566 /// traverses the CMT.
567 pub fn opt_loan_path<'tcx>(cmt: &mc::cmt_<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
568     opt_loan_path_is_field(cmt).0
569 }
570
571 ///////////////////////////////////////////////////////////////////////////
572 // Errors
573
574 // Errors that can occur
575 #[derive(Debug, PartialEq)]
576 pub enum bckerr_code<'tcx> {
577     err_mutbl,
578     /// superscope, subscope, loan cause
579     err_out_of_scope(ty::Region<'tcx>, ty::Region<'tcx>, euv::LoanCause),
580     err_borrowed_pointer_too_short(ty::Region<'tcx>, ty::Region<'tcx>), // loan, ptr
581 }
582
583 // Combination of an error code and the categorization of the expression
584 // that caused it
585 #[derive(Debug, PartialEq)]
586 pub struct BckError<'c, 'tcx: 'c> {
587     span: Span,
588     cause: AliasableViolationKind,
589     cmt: &'c mc::cmt_<'tcx>,
590     code: bckerr_code<'tcx>
591 }
592
593 #[derive(Copy, Clone, Debug, PartialEq)]
594 pub enum AliasableViolationKind {
595     MutabilityViolation,
596     BorrowViolation(euv::LoanCause)
597 }
598
599 #[derive(Copy, Clone, Debug)]
600 pub enum MovedValueUseKind {
601     MovedInUse,
602     MovedInCapture,
603 }
604
605 ///////////////////////////////////////////////////////////////////////////
606 // Misc
607
608 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
609     pub fn is_subregion_of(&self,
610                            r_sub: ty::Region<'tcx>,
611                            r_sup: ty::Region<'tcx>)
612                            -> bool
613     {
614         let region_rels = RegionRelations::new(self.tcx,
615                                                self.owner_def_id,
616                                                &self.region_scope_tree,
617                                                &self.tables.free_region_map);
618         region_rels.is_subregion_of(r_sub, r_sup)
619     }
620
621     pub fn report(&self, err: BckError<'a, 'tcx>) {
622         // Catch and handle some particular cases.
623         match (&err.code, &err.cause) {
624             (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _),
625              &BorrowViolation(euv::ClosureCapture(span))) |
626             (&err_out_of_scope(&ty::ReScope(_), &ty::ReEarlyBound(..), _),
627              &BorrowViolation(euv::ClosureCapture(span))) |
628             (&err_out_of_scope(&ty::ReScope(_), &ty::ReFree(..), _),
629              &BorrowViolation(euv::ClosureCapture(span))) => {
630                 return self.report_out_of_scope_escaping_closure_capture(&err, span);
631             }
632             _ => { }
633         }
634
635         self.report_bckerr(&err);
636     }
637
638     pub fn report_use_of_moved_value(&self,
639                                      use_span: Span,
640                                      use_kind: MovedValueUseKind,
641                                      lp: &LoanPath<'tcx>,
642                                      the_move: &move_data::Move,
643                                      moved_lp: &LoanPath<'tcx>) {
644         let (verb, verb_participle) = match use_kind {
645             MovedInUse => ("use", "used"),
646             MovedInCapture => ("capture", "captured"),
647         };
648
649         let (_ol, _moved_lp_msg, mut err, need_note) = match the_move.kind {
650             move_data::Declared => {
651                 // If this is an uninitialized variable, just emit a simple warning
652                 // and return.
653                 self.cannot_act_on_uninitialized_variable(use_span,
654                                                           verb,
655                                                           &self.loan_path_to_string(lp),
656                                                           Origin::Ast)
657                     .span_label(use_span, format!("use of possibly uninitialized `{}`",
658                                                   self.loan_path_to_string(lp)))
659                     .emit();
660                 self.signal_error();
661                 return;
662             }
663             _ => {
664                 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
665                 // normally generate a rather confusing message:
666                 //
667                 //     error: use of moved value: `x.b`
668                 //     note: `x.a` moved here...
669                 //
670                 // What we want to do instead is get the 'common ancestor' of the two moves and
671                 // use that for most of the message instead, giving is something like this:
672                 //
673                 //     error: use of moved value: `x`
674                 //     note: `x` moved here (through moving `x.a`)...
675
676                 let common = moved_lp.common(lp);
677                 let has_common = common.is_some();
678                 let has_fork = moved_lp.has_fork(lp);
679                 let (nl, ol, moved_lp_msg) =
680                     if has_fork && has_common {
681                         let nl = self.loan_path_to_string(&common.unwrap());
682                         let ol = nl.clone();
683                         let moved_lp_msg = format!(" (through moving `{}`)",
684                                                    self.loan_path_to_string(moved_lp));
685                         (nl, ol, moved_lp_msg)
686                     } else {
687                         (self.loan_path_to_string(lp),
688                          self.loan_path_to_string(moved_lp),
689                          String::new())
690                     };
691
692                 let partial = moved_lp.depth() > lp.depth();
693                 let msg = if !has_fork && partial { "partially " }
694                           else if has_fork && !has_common { "collaterally "}
695                 else { "" };
696                 let mut err = self.cannot_act_on_moved_value(use_span,
697                                                              verb,
698                                                              msg,
699                                                              Some(nl),
700                                                              Origin::Ast);
701                 let need_note = match lp.ty.sty {
702                     ty::Closure(id, _) => {
703                         let node_id = self.tcx.hir().as_local_node_id(id).unwrap();
704                         let hir_id = self.tcx.hir().node_to_hir_id(node_id);
705                         if let Some((span, name)) = self.tables.closure_kind_origins().get(hir_id) {
706                             err.span_note(*span, &format!(
707                                 "closure cannot be invoked more than once because \
708                                 it moves the variable `{}` out of its environment",
709                                 name
710                             ));
711                             false
712                         } else {
713                             true
714                         }
715                     }
716                     _ => true,
717                 };
718                 (ol, moved_lp_msg, err, need_note)
719             }
720         };
721
722         // Get type of value and span where it was previously
723         // moved.
724         let node_id = self.tcx.hir().hir_to_node_id(hir::HirId {
725             owner: self.body.value.hir_id.owner,
726             local_id: the_move.id
727         });
728         let (move_span, move_note) = match the_move.kind {
729             move_data::Declared => {
730                 unreachable!();
731             }
732
733             move_data::MoveExpr |
734             move_data::MovePat => (self.tcx.hir().span(node_id), ""),
735
736             move_data::Captured =>
737                 (match self.tcx.hir().expect_expr(node_id).node {
738                     hir::ExprKind::Closure(.., fn_decl_span, _) => fn_decl_span,
739                     ref r => bug!("Captured({:?}) maps to non-closure: {:?}",
740                                   the_move.id, r),
741                 }, " (into closure)"),
742         };
743
744         // Annotate the use and the move in the span. Watch out for
745         // the case where the use and the move are the same. This
746         // means the use is in a loop.
747         err = if use_span == move_span {
748             err.span_label(
749                 use_span,
750                 format!("value moved{} here in previous iteration of loop",
751                          move_note));
752             err
753         } else {
754             err.span_label(use_span, format!("value {} here after move", verb_participle));
755             err.span_label(move_span, format!("value moved{} here", move_note));
756             err
757         };
758
759         if need_note {
760             err.note(&format!(
761                 "move occurs because {} has type `{}`, which does not implement the `Copy` trait",
762                 if moved_lp.has_downcast() {
763                     "the value".to_string()
764                 } else {
765                     format!("`{}`", self.loan_path_to_string(moved_lp))
766                 },
767                 moved_lp.ty));
768         }
769
770         // Note: we used to suggest adding a `ref binding` or calling
771         // `clone` but those suggestions have been removed because
772         // they are often not what you actually want to do, and were
773         // not considered particularly helpful.
774
775         err.emit();
776         self.signal_error();
777     }
778
779     pub fn report_partial_reinitialization_of_uninitialized_structure(
780             &self,
781             span: Span,
782             lp: &LoanPath<'tcx>) {
783         self.cannot_partially_reinit_an_uninit_struct(span,
784                                                       &self.loan_path_to_string(lp),
785                                                       Origin::Ast)
786             .emit();
787         self.signal_error();
788     }
789
790     pub fn report_reassigned_immutable_variable(&self,
791                                                 span: Span,
792                                                 lp: &LoanPath<'tcx>,
793                                                 assign:
794                                                 &move_data::Assignment) {
795         let mut err = self.cannot_reassign_immutable(span,
796                                                      &self.loan_path_to_string(lp),
797                                                      false,
798                                                      Origin::Ast);
799         err.span_label(span, "cannot assign twice to immutable variable");
800         if span != assign.span {
801             err.span_label(assign.span, format!("first assignment to `{}`",
802                                                 self.loan_path_to_string(lp)));
803         }
804         err.emit();
805         self.signal_error();
806     }
807
808     fn report_bckerr(&self, err: &BckError<'a, 'tcx>) {
809         let error_span = err.span.clone();
810
811         match err.code {
812             err_mutbl => {
813                 let descr: Cow<'static, str> = match err.cmt.note {
814                     mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
815                         self.cmt_to_cow_str(&err.cmt)
816                     }
817                     _ => match opt_loan_path_is_field(&err.cmt) {
818                         (None, true) => {
819                             format!("{} of {} binding",
820                                     self.cmt_to_cow_str(&err.cmt),
821                                     err.cmt.mutbl.to_user_str()).into()
822
823                         }
824                         (None, false) => {
825                             format!("{} {}",
826                                     err.cmt.mutbl.to_user_str(),
827                                     self.cmt_to_cow_str(&err.cmt)).into()
828
829                         }
830                         (Some(lp), true) => {
831                             format!("{} `{}` of {} binding",
832                                     self.cmt_to_cow_str(&err.cmt),
833                                     self.loan_path_to_string(&lp),
834                                     err.cmt.mutbl.to_user_str()).into()
835                         }
836                         (Some(lp), false) => {
837                             format!("{} {} `{}`",
838                                     err.cmt.mutbl.to_user_str(),
839                                     self.cmt_to_cow_str(&err.cmt),
840                                     self.loan_path_to_string(&lp)).into()
841                         }
842                     }
843                 };
844
845                 let mut db = match err.cause {
846                     MutabilityViolation => {
847                         let mut db = self.cannot_assign(error_span, &descr, Origin::Ast);
848                         if let mc::NoteClosureEnv(upvar_id) = err.cmt.note {
849                             let node_id = self.tcx.hir().hir_to_node_id(upvar_id.var_path.hir_id);
850                             let sp = self.tcx.hir().span(node_id);
851                             let fn_closure_msg = "`Fn` closures cannot capture their enclosing \
852                                                   environment for modifications";
853                             match (self.tcx.sess.source_map().span_to_snippet(sp), &err.cmt.cat) {
854                                 (_, &Categorization::Upvar(mc::Upvar {
855                                     kind: ty::ClosureKind::Fn, ..
856                                 })) => {
857                                     db.note(fn_closure_msg);
858                                     // we should point at the cause for this closure being
859                                     // identified as `Fn` (like in signature of method this
860                                     // closure was passed into)
861                                 }
862                                 (Ok(ref snippet), ref cat) => {
863                                     let msg = &format!("consider making `{}` mutable", snippet);
864                                     let suggestion = format!("mut {}", snippet);
865
866                                     if let &Categorization::Deref(ref cmt, _) = cat {
867                                         if let Categorization::Upvar(mc::Upvar {
868                                             kind: ty::ClosureKind::Fn, ..
869                                         }) = cmt.cat {
870                                             db.note(fn_closure_msg);
871                                         } else {
872                                             db.span_suggestion_with_applicability(
873                                                 sp,
874                                                 msg,
875                                                 suggestion,
876                                                 Applicability::Unspecified,
877                                             );
878                                         }
879                                     } else {
880                                         db.span_suggestion_with_applicability(
881                                             sp,
882                                             msg,
883                                             suggestion,
884                                             Applicability::Unspecified,
885                                         );
886                                     }
887                                 }
888                                 _ => {
889                                     db.span_help(sp, "consider making this binding mutable");
890                                 }
891                             }
892                         }
893
894                         db
895                     }
896                     BorrowViolation(euv::ClosureCapture(_)) => {
897                         self.closure_cannot_assign_to_borrowed(error_span, &descr, Origin::Ast)
898                     }
899                     BorrowViolation(euv::OverloadedOperator) |
900                     BorrowViolation(euv::AddrOf) |
901                     BorrowViolation(euv::RefBinding) |
902                     BorrowViolation(euv::AutoRef) |
903                     BorrowViolation(euv::AutoUnsafe) |
904                     BorrowViolation(euv::ForLoop) |
905                     BorrowViolation(euv::MatchDiscriminant) => {
906                         self.cannot_borrow_path_as_mutable(error_span, &descr, Origin::Ast)
907                     }
908                     BorrowViolation(euv::ClosureInvocation) => {
909                         span_bug!(err.span,
910                             "err_mutbl with a closure invocation");
911                     }
912                 };
913
914                 // We add a special note about `IndexMut`, if the source of this error
915                 // is the fact that `Index` is implemented, but `IndexMut` is not. Needing
916                 // to implement two traits for "one operator" is not very intuitive for
917                 // many programmers.
918                 if err.cmt.note == mc::NoteIndex {
919                     let node_id = self.tcx.hir().hir_to_node_id(err.cmt.hir_id);
920                     let node =  self.tcx.hir().get(node_id);
921
922                     // This pattern probably always matches.
923                     if let Node::Expr(
924                         hir::Expr { node: hir::ExprKind::Index(lhs, _), ..}
925                     ) = node {
926                         let ty = self.tables.expr_ty(lhs);
927
928                         db.help(&format!(
929                             "trait `IndexMut` is required to modify indexed content, but \
930                              it is not implemented for `{}`",
931                             ty
932                         ));
933                     }
934                 }
935
936                 self.note_and_explain_mutbl_error(&mut db, &err, &error_span);
937                 self.note_immutability_blame(
938                     &mut db,
939                     err.cmt.immutability_blame(),
940                     self.tcx.hir().hir_to_node_id(err.cmt.hir_id)
941                 );
942                 db.emit();
943                 self.signal_error();
944             }
945             err_out_of_scope(super_scope, sub_scope, cause) => {
946                 let msg = match opt_loan_path(&err.cmt) {
947                     None => "borrowed value".to_string(),
948                     Some(lp) => {
949                         format!("`{}`", self.loan_path_to_string(&lp))
950                     }
951                 };
952
953                 let mut db = self.path_does_not_live_long_enough(error_span, &msg, Origin::Ast);
954                 let value_kind = match err.cmt.cat {
955                     mc::Categorization::Rvalue(..) => "temporary value",
956                     _ => "borrowed value",
957                 };
958
959                 let is_closure = match cause {
960                     euv::ClosureCapture(s) => {
961                         // The primary span starts out as the closure creation point.
962                         // Change the primary span here to highlight the use of the variable
963                         // in the closure, because it seems more natural. Highlight
964                         // closure creation point as a secondary span.
965                         match db.span.primary_span() {
966                             Some(primary) => {
967                                 db.span = MultiSpan::from_span(s);
968                                 db.span_label(primary, "capture occurs here");
969                                 db.span_label(s, format!("{} does not live long enough",
970                                                          value_kind));
971                                 true
972                             }
973                             None => false
974                         }
975                     }
976                     _ => {
977                         db.span_label(error_span, format!("{} does not live long enough",
978                                                           value_kind));
979                         false
980                     }
981                 };
982
983                 let sub_span = self.region_end_span(sub_scope);
984                 let super_span = self.region_end_span(super_scope);
985
986                 match (sub_span, super_span) {
987                     (Some(s1), Some(s2)) if s1 == s2 => {
988                         if !is_closure {
989                             let msg = match opt_loan_path(&err.cmt) {
990                                 None => value_kind.to_string(),
991                                 Some(lp) => {
992                                     format!("`{}`", self.loan_path_to_string(&lp))
993                                 }
994                             };
995                             db.span_label(s1,
996                                           format!("{} dropped here while still borrowed", msg));
997                         } else {
998                             db.span_label(s1, format!("{} dropped before borrower", value_kind));
999                         }
1000                         db.note("values in a scope are dropped in the opposite order \
1001                                 they are created");
1002                     }
1003                     (Some(s1), Some(s2)) if !is_closure => {
1004                         let msg = match opt_loan_path(&err.cmt) {
1005                             None => value_kind.to_string(),
1006                             Some(lp) => {
1007                                 format!("`{}`", self.loan_path_to_string(&lp))
1008                             }
1009                         };
1010                         db.span_label(s2, format!("{} dropped here while still borrowed", msg));
1011                         db.span_label(s1, format!("{} needs to live until here", value_kind));
1012                     }
1013                     _ => {
1014                         match sub_span {
1015                             Some(s) => {
1016                                 db.span_label(s, format!("{} needs to live until here",
1017                                                           value_kind));
1018                             }
1019                             None => {
1020                                 self.tcx.note_and_explain_region(
1021                                     &self.region_scope_tree,
1022                                     &mut db,
1023                                     "borrowed value must be valid for ",
1024                                     sub_scope,
1025                                     "...");
1026                             }
1027                         }
1028                         match super_span {
1029                             Some(s) => {
1030                                 db.span_label(s, format!("{} only lives until here", value_kind));
1031                             }
1032                             None => {
1033                                 self.tcx.note_and_explain_region(
1034                                     &self.region_scope_tree,
1035                                     &mut db,
1036                                     "...but borrowed value is only valid for ",
1037                                     super_scope,
1038                                     "");
1039                             }
1040                         }
1041                     }
1042                 }
1043
1044                 if let ty::ReScope(scope) = *super_scope {
1045                     let node_id = scope.node_id(self.tcx, &self.region_scope_tree);
1046                     match self.tcx.hir().find(node_id) {
1047                         Some(Node::Stmt(_)) => {
1048                             if *sub_scope != ty::ReStatic {
1049                                 db.note("consider using a `let` binding to increase its lifetime");
1050                             }
1051
1052                         }
1053                         _ => {}
1054                     }
1055                 }
1056
1057                 db.emit();
1058                 self.signal_error();
1059             }
1060             err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1061                 let descr = self.cmt_to_path_or_string(err.cmt);
1062                 let mut db = self.lifetime_too_short_for_reborrow(error_span, &descr, Origin::Ast);
1063                 let descr: Cow<'static, str> = match opt_loan_path(&err.cmt) {
1064                     Some(lp) => {
1065                         format!("`{}`", self.loan_path_to_string(&lp)).into()
1066                     }
1067                     None => self.cmt_to_cow_str(&err.cmt)
1068                 };
1069                 self.tcx.note_and_explain_region(
1070                     &self.region_scope_tree,
1071                     &mut db,
1072                     &format!("{} would have to be valid for ",
1073                             descr),
1074                     loan_scope,
1075                     "...");
1076                 self.tcx.note_and_explain_region(
1077                     &self.region_scope_tree,
1078                     &mut db,
1079                     &format!("...but {} is only valid for ", descr),
1080                     ptr_scope,
1081                     "");
1082
1083                 db.emit();
1084                 self.signal_error();
1085             }
1086         }
1087     }
1088
1089     pub fn report_aliasability_violation(&self,
1090                                          span: Span,
1091                                          kind: AliasableViolationKind,
1092                                          cause: mc::AliasableReason,
1093                                          cmt: &mc::cmt_<'tcx>) {
1094         let mut is_closure = false;
1095         let prefix = match kind {
1096             MutabilityViolation => {
1097                 "cannot assign to data"
1098             }
1099             BorrowViolation(euv::ClosureCapture(_)) |
1100             BorrowViolation(euv::OverloadedOperator) |
1101             BorrowViolation(euv::AddrOf) |
1102             BorrowViolation(euv::AutoRef) |
1103             BorrowViolation(euv::AutoUnsafe) |
1104             BorrowViolation(euv::RefBinding) |
1105             BorrowViolation(euv::MatchDiscriminant) => {
1106                 "cannot borrow data mutably"
1107             }
1108
1109             BorrowViolation(euv::ClosureInvocation) => {
1110                 is_closure = true;
1111                 "closure invocation"
1112             }
1113
1114             BorrowViolation(euv::ForLoop) => {
1115                 "`for` loop"
1116             }
1117         };
1118
1119         match cause {
1120             mc::AliasableStaticMut => {
1121                 // This path cannot occur. `static mut X` is not checked
1122                 // for aliasability violations.
1123                 span_bug!(span, "aliasability violation for static mut `{}`", prefix)
1124             }
1125             mc::AliasableStatic | mc::AliasableBorrowed => {}
1126         };
1127         let blame = cmt.immutability_blame();
1128         let mut err = match blame {
1129             Some(ImmutabilityBlame::ClosureEnv(id)) => {
1130                 // FIXME: the distinction between these 2 messages looks wrong.
1131                 let help_msg = if let BorrowViolation(euv::ClosureCapture(_)) = kind {
1132                     // The aliasability violation with closure captures can
1133                     // happen for nested closures, so we know the enclosing
1134                     // closure incorrectly accepts an `Fn` while it needs to
1135                     // be `FnMut`.
1136                     "consider changing this to accept closures that implement `FnMut`"
1137
1138                 } else {
1139                     "consider changing this closure to take self by mutable reference"
1140                 };
1141                 let node_id = self.tcx.hir().local_def_id_to_node_id(id);
1142                 let help_span = self.tcx.hir().span(node_id);
1143                 self.cannot_act_on_capture_in_sharable_fn(span,
1144                                                           prefix,
1145                                                           (help_span, help_msg),
1146                                                           Origin::Ast)
1147             }
1148             _ =>  {
1149                 self.cannot_assign_into_immutable_reference(span, prefix,
1150                                                             Origin::Ast)
1151             }
1152         };
1153         self.note_immutability_blame(
1154             &mut err,
1155             blame,
1156             self.tcx.hir().hir_to_node_id(cmt.hir_id)
1157         );
1158
1159         if is_closure {
1160             err.help("closures behind references must be called via `&mut`");
1161         }
1162         err.emit();
1163         self.signal_error();
1164     }
1165
1166     /// Given a type, if it is an immutable reference, return a suggestion to make it mutable
1167     fn suggest_mut_for_immutable(&self, pty: &hir::Ty, is_implicit_self: bool) -> Option<String> {
1168         // Check whether the argument is an immutable reference
1169         debug!("suggest_mut_for_immutable({:?}, {:?})", pty, is_implicit_self);
1170         if let hir::TyKind::Rptr(lifetime, hir::MutTy {
1171             mutbl: hir::Mutability::MutImmutable,
1172             ref ty
1173         }) = pty.node {
1174             // Account for existing lifetimes when generating the message
1175             let pointee_snippet = match self.tcx.sess.source_map().span_to_snippet(ty.span) {
1176                 Ok(snippet) => snippet,
1177                 _ => return None
1178             };
1179
1180             let lifetime_snippet = if !lifetime.is_elided() {
1181                 format!("{} ", match self.tcx.sess.source_map().span_to_snippet(lifetime.span) {
1182                     Ok(lifetime_snippet) => lifetime_snippet,
1183                     _ => return None
1184                 })
1185             } else {
1186                 String::new()
1187             };
1188             Some(format!("use `&{}mut {}` here to make mutable",
1189                          lifetime_snippet,
1190                          if is_implicit_self { "self" } else { &*pointee_snippet }))
1191         } else {
1192             None
1193         }
1194     }
1195
1196     fn local_binding_mode(&self, node_id: ast::NodeId) -> ty::BindingMode {
1197         let pat = match self.tcx.hir().get(node_id) {
1198             Node::Binding(pat) => pat,
1199             node => bug!("bad node for local: {:?}", node)
1200         };
1201
1202         match pat.node {
1203             hir::PatKind::Binding(..) => {
1204                 *self.tables
1205                      .pat_binding_modes()
1206                      .get(pat.hir_id)
1207                      .expect("missing binding mode")
1208             }
1209             _ => bug!("local is not a binding: {:?}", pat)
1210         }
1211     }
1212
1213     fn local_ty(&self, node_id: ast::NodeId) -> (Option<&hir::Ty>, bool) {
1214         let parent = self.tcx.hir().get_parent_node(node_id);
1215         let parent_node = self.tcx.hir().get(parent);
1216
1217         // The parent node is like a fn
1218         if let Some(fn_like) = FnLikeNode::from_node(parent_node) {
1219             // `nid`'s parent's `Body`
1220             let fn_body = self.tcx.hir().body(fn_like.body());
1221             // Get the position of `node_id` in the arguments list
1222             let arg_pos = fn_body.arguments.iter().position(|arg| arg.pat.id == node_id);
1223             if let Some(i) = arg_pos {
1224                 // The argument's `Ty`
1225                 (Some(&fn_like.decl().inputs[i]),
1226                  i == 0 && fn_like.decl().implicit_self.has_implicit_self())
1227             } else {
1228                 (None, false)
1229             }
1230         } else {
1231             (None, false)
1232         }
1233     }
1234
1235     fn note_immutability_blame(&self,
1236                                db: &mut DiagnosticBuilder,
1237                                blame: Option<ImmutabilityBlame>,
1238                                error_node_id: ast::NodeId) {
1239         match blame {
1240             None => {}
1241             Some(ImmutabilityBlame::ClosureEnv(_)) => {}
1242             Some(ImmutabilityBlame::ImmLocal(node_id)) => {
1243                 self.note_immutable_local(db, error_node_id, node_id)
1244             }
1245             Some(ImmutabilityBlame::LocalDeref(node_id)) => {
1246                 match self.local_binding_mode(node_id) {
1247                     ty::BindByReference(..) => {
1248                         let let_span = self.tcx.hir().span(node_id);
1249                         let suggestion = suggest_ref_mut(self.tcx, let_span);
1250                         if let Some(replace_str) = suggestion {
1251                             db.span_suggestion_with_applicability(
1252                                 let_span,
1253                                 "use a mutable reference instead",
1254                                 replace_str,
1255                                 // I believe this can be machine applicable,
1256                                 // but if there are multiple attempted uses of an immutable
1257                                 // reference, I don't know how rustfix handles it, it might
1258                                 // attempt fixing them multiple times.
1259                                 //                              @estebank
1260                                 Applicability::Unspecified,
1261                             );
1262                         }
1263                     }
1264                     ty::BindByValue(..) => {
1265                         if let (Some(local_ty), is_implicit_self) = self.local_ty(node_id) {
1266                             if let Some(msg) =
1267                                  self.suggest_mut_for_immutable(local_ty, is_implicit_self) {
1268                                 db.span_label(local_ty.span, msg);
1269                             }
1270                         }
1271                     }
1272                 }
1273             }
1274             Some(ImmutabilityBlame::AdtFieldDeref(_, field)) => {
1275                 let node_id = match self.tcx.hir().as_local_node_id(field.did) {
1276                     Some(node_id) => node_id,
1277                     None => return
1278                 };
1279
1280                 if let Node::Field(ref field) = self.tcx.hir().get(node_id) {
1281                     if let Some(msg) = self.suggest_mut_for_immutable(&field.ty, false) {
1282                         db.span_label(field.ty.span, msg);
1283                     }
1284                 }
1285             }
1286         }
1287     }
1288
1289      // Suggest a fix when trying to mutably borrow an immutable local
1290      // binding: either to make the binding mutable (if its type is
1291      // not a mutable reference) or to avoid borrowing altogether
1292     fn note_immutable_local(&self,
1293                             db: &mut DiagnosticBuilder,
1294                             borrowed_node_id: ast::NodeId,
1295                             binding_node_id: ast::NodeId) {
1296         let let_span = self.tcx.hir().span(binding_node_id);
1297         if let ty::BindByValue(..) = self.local_binding_mode(binding_node_id) {
1298             if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(let_span) {
1299                 let (ty, is_implicit_self) = self.local_ty(binding_node_id);
1300                 if is_implicit_self && snippet != "self" {
1301                     // avoid suggesting `mut &self`.
1302                     return
1303                 }
1304                 if let Some(&hir::TyKind::Rptr(
1305                     _,
1306                     hir::MutTy {
1307                         mutbl: hir::MutMutable,
1308                         ..
1309                     },
1310                 )) = ty.map(|t| &t.node)
1311                 {
1312                     let borrow_expr_id = self.tcx.hir().get_parent_node(borrowed_node_id);
1313                     db.span_suggestion_with_applicability(
1314                         self.tcx.hir().span(borrow_expr_id),
1315                         "consider removing the `&mut`, as it is an \
1316                         immutable binding to a mutable reference",
1317                         snippet,
1318                         Applicability::MachineApplicable,
1319                     );
1320                 } else {
1321                     db.span_suggestion_with_applicability(
1322                         let_span,
1323                         "make this binding mutable",
1324                         format!("mut {}", snippet),
1325                         Applicability::MachineApplicable,
1326                     );
1327                 }
1328             }
1329         }
1330     }
1331
1332     fn report_out_of_scope_escaping_closure_capture(&self,
1333                                                     err: &BckError<'a, 'tcx>,
1334                                                     capture_span: Span)
1335     {
1336         let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
1337
1338         let suggestion =
1339             match self.tcx.sess.source_map().span_to_snippet(err.span) {
1340                 Ok(string) => format!("move {}", string),
1341                 Err(_) => "move |<args>| <body>".to_string()
1342             };
1343
1344         self.cannot_capture_in_long_lived_closure(err.span,
1345                                                   &cmt_path_or_string,
1346                                                   capture_span,
1347                                                   Origin::Ast)
1348             .span_suggestion_with_applicability(
1349                  err.span,
1350                  &format!("to force the closure to take ownership of {} \
1351                            (and any other referenced variables), \
1352                            use the `move` keyword",
1353                            cmt_path_or_string),
1354                  suggestion,
1355                  Applicability::MachineApplicable,
1356             )
1357             .emit();
1358         self.signal_error();
1359     }
1360
1361     fn region_end_span(&self, region: ty::Region<'tcx>) -> Option<Span> {
1362         match *region {
1363             ty::ReScope(scope) => {
1364                 Some(self.tcx.sess.source_map().end_point(
1365                         scope.span(self.tcx, &self.region_scope_tree)))
1366             }
1367             _ => None
1368         }
1369     }
1370
1371     fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'a, 'tcx>,
1372                                     error_span: &Span) {
1373         match err.cmt.note {
1374             mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1375                 // If this is an `Fn` closure, it simply can't mutate upvars.
1376                 // If it's an `FnMut` closure, the original variable was declared immutable.
1377                 // We need to determine which is the case here.
1378                 let kind = match err.cmt.upvar_cat().unwrap() {
1379                     Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1380                     _ => bug!()
1381                 };
1382                 if *kind == ty::ClosureKind::Fn {
1383                     let closure_node_id =
1384                         self.tcx.hir().local_def_id_to_node_id(upvar_id.closure_expr_id);
1385                     db.span_help(self.tcx.hir().span(closure_node_id),
1386                                  "consider changing this closure to take \
1387                                   self by mutable reference");
1388                 }
1389             }
1390             _ => {
1391                 if let Categorization::Deref(..) = err.cmt.cat {
1392                     db.span_label(*error_span, "cannot borrow as mutable");
1393                 } else if let Categorization::Local(local_id) = err.cmt.cat {
1394                     let span = self.tcx.hir().span(local_id);
1395                     if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1396                         if snippet.starts_with("ref mut ") || snippet.starts_with("&mut ") {
1397                             db.span_label(*error_span, "cannot reborrow mutably");
1398                             db.span_label(*error_span, "try removing `&mut` here");
1399                         } else {
1400                             db.span_label(*error_span, "cannot borrow mutably");
1401                         }
1402                     } else {
1403                         db.span_label(*error_span, "cannot borrow mutably");
1404                     }
1405                 } else if let Categorization::Interior(ref cmt, _) = err.cmt.cat {
1406                     if let mc::MutabilityCategory::McImmutable = cmt.mutbl {
1407                         db.span_label(*error_span,
1408                                       "cannot mutably borrow field of immutable binding");
1409                     }
1410                 }
1411             }
1412         }
1413     }
1414     pub fn append_loan_path_to_string(&self,
1415                                       loan_path: &LoanPath<'tcx>,
1416                                       out: &mut String) {
1417         match loan_path.kind {
1418             LpUpvar(ty::UpvarId { var_path: ty::UpvarPath { hir_id: id}, closure_expr_id: _ }) => {
1419                 out.push_str(&self.tcx.hir().name(self.tcx.hir().hir_to_node_id(id)).as_str());
1420             }
1421             LpVar(id) => {
1422                 out.push_str(&self.tcx.hir().name(id).as_str());
1423             }
1424
1425             LpDowncast(ref lp_base, variant_def_id) => {
1426                 out.push('(');
1427                 self.append_loan_path_to_string(&lp_base, out);
1428                 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1429                 out.push_str(&self.tcx.item_path_str(variant_def_id));
1430                 out.push(')');
1431             }
1432
1433             LpExtend(ref lp_base, _, LpInterior(_, InteriorField(mc::FieldIndex(_, info)))) => {
1434                 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1435                 out.push('.');
1436                 out.push_str(&info.as_str());
1437             }
1438
1439             LpExtend(ref lp_base, _, LpInterior(_, InteriorElement)) => {
1440                 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1441                 out.push_str("[..]");
1442             }
1443
1444             LpExtend(ref lp_base, _, LpDeref(_)) => {
1445                 out.push('*');
1446                 self.append_loan_path_to_string(&lp_base, out);
1447             }
1448         }
1449     }
1450
1451     pub fn append_autoderefd_loan_path_to_string(&self,
1452                                                  loan_path: &LoanPath<'tcx>,
1453                                                  out: &mut String) {
1454         match loan_path.kind {
1455             LpExtend(ref lp_base, _, LpDeref(_)) => {
1456                 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1457                 // rules would normally allow users to omit the `*x`.
1458                 // So just serialize such paths to `x.f` or x[3]` respectively.
1459                 self.append_autoderefd_loan_path_to_string(&lp_base, out)
1460             }
1461
1462             LpDowncast(ref lp_base, variant_def_id) => {
1463                 out.push('(');
1464                 self.append_autoderefd_loan_path_to_string(&lp_base, out);
1465                 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1466                 out.push_str(&self.tcx.item_path_str(variant_def_id));
1467                 out.push(')');
1468             }
1469
1470             LpVar(..) | LpUpvar(..) | LpExtend(.., LpInterior(..)) => {
1471                 self.append_loan_path_to_string(loan_path, out)
1472             }
1473         }
1474     }
1475
1476     pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1477         let mut result = String::new();
1478         self.append_loan_path_to_string(loan_path, &mut result);
1479         result
1480     }
1481
1482     pub fn cmt_to_cow_str(&self, cmt: &mc::cmt_<'tcx>) -> Cow<'static, str> {
1483         cmt.descriptive_string(self.tcx)
1484     }
1485
1486     pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1487         match opt_loan_path(cmt) {
1488             Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1489             None => self.cmt_to_cow_str(cmt).into_owned(),
1490         }
1491     }
1492 }
1493
1494 impl BitwiseOperator for LoanDataFlowOperator {
1495     #[inline]
1496     fn join(&self, succ: usize, pred: usize) -> usize {
1497         succ | pred // loans from both preds are in scope
1498     }
1499 }
1500
1501 impl DataFlowOperator for LoanDataFlowOperator {
1502     #[inline]
1503     fn initial_value(&self) -> bool {
1504         false // no loans in scope by default
1505     }
1506 }
1507
1508 impl<'tcx> fmt::Debug for InteriorKind {
1509     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1510         match *self {
1511             InteriorField(mc::FieldIndex(_, info)) => write!(f, "{}", info),
1512             InteriorElement => write!(f, "[]"),
1513         }
1514     }
1515 }
1516
1517 impl<'tcx> fmt::Debug for Loan<'tcx> {
1518     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1519         write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1520                self.index,
1521                self.loan_path,
1522                self.kind,
1523                self.gen_scope,
1524                self.kill_scope,
1525                self.restricted_paths)
1526     }
1527 }
1528
1529 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1530     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1531         match self.kind {
1532             LpVar(id) => {
1533                 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir().node_to_string(id)))
1534             }
1535
1536             LpUpvar(ty::UpvarId{ var_path: ty::UpvarPath {hir_id: var_id}, closure_expr_id }) => {
1537                 let s = ty::tls::with(|tcx| {
1538                     let var_node_id = tcx.hir().hir_to_node_id(var_id);
1539                     tcx.hir().node_to_string(var_node_id)
1540                 });
1541                 write!(f, "$({} captured by id={:?})", s, closure_expr_id)
1542             }
1543
1544             LpDowncast(ref lp, variant_def_id) => {
1545                 let variant_str = if variant_def_id.is_local() {
1546                     ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1547                 } else {
1548                     format!("{:?}", variant_def_id)
1549                 };
1550                 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1551             }
1552
1553             LpExtend(ref lp, _, LpDeref(_)) => {
1554                 write!(f, "{:?}.*", lp)
1555             }
1556
1557             LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1558                 write!(f, "{:?}.{:?}", lp, interior)
1559             }
1560         }
1561     }
1562 }
1563
1564 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1565     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1566         match self.kind {
1567             LpVar(id) => {
1568                 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir().node_to_user_string(id)))
1569             }
1570
1571             LpUpvar(ty::UpvarId{ var_path: ty::UpvarPath { hir_id }, closure_expr_id: _ }) => {
1572                 let s = ty::tls::with(|tcx| {
1573                     let var_node_id = tcx.hir().hir_to_node_id(hir_id);
1574                     tcx.hir().node_to_string(var_node_id)
1575                 });
1576                 write!(f, "$({} captured by closure)", s)
1577             }
1578
1579             LpDowncast(ref lp, variant_def_id) => {
1580                 let variant_str = if variant_def_id.is_local() {
1581                     ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1582                 } else {
1583                     format!("{:?}", variant_def_id)
1584                 };
1585                 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1586             }
1587
1588             LpExtend(ref lp, _, LpDeref(_)) => {
1589                 write!(f, "{}.*", lp)
1590             }
1591
1592             LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1593                 write!(f, "{}.{:?}", lp, interior)
1594             }
1595         }
1596     }
1597 }