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