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