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