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