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