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