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