]> git.lizzy.rs Git - rust.git/blob - src/librustc_borrowck/borrowck/mod.rs
Auto merge of #30641 - tsion:match-range, r=eddyb
[rust.git] / src / librustc_borrowck / borrowck / mod.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! See The Book chapter on the borrow checker for more details.
12
13 #![allow(non_camel_case_types)]
14
15 pub use self::LoanPathKind::*;
16 pub use self::LoanPathElem::*;
17 pub use self::bckerr_code::*;
18 pub use self::AliasableViolationKind::*;
19 pub use self::MovedValueUseKind::*;
20
21 use self::InteriorKind::*;
22
23 use rustc::front::map as hir_map;
24 use rustc::front::map::blocks::FnParts;
25 use rustc::middle::cfg;
26 use rustc::middle::dataflow::DataFlowContext;
27 use rustc::middle::dataflow::BitwiseOperator;
28 use rustc::middle::dataflow::DataFlowOperator;
29 use rustc::middle::dataflow::KillFrom;
30 use rustc::middle::def_id::DefId;
31 use rustc::middle::expr_use_visitor as euv;
32 use rustc::middle::free_region::FreeRegionMap;
33 use rustc::middle::mem_categorization as mc;
34 use rustc::middle::mem_categorization::Categorization;
35 use rustc::middle::region;
36 use rustc::middle::ty::{self, Ty};
37
38 use std::fmt;
39 use std::mem;
40 use std::rc::Rc;
41 use syntax::ast;
42 use syntax::codemap::Span;
43 use syntax::errors::DiagnosticBuilder;
44
45 use rustc_front::hir;
46 use rustc_front::hir::{FnDecl, Block};
47 use rustc_front::intravisit;
48 use rustc_front::intravisit::{Visitor, FnKind};
49 use rustc_front::util as hir_util;
50
51 pub mod check_loans;
52
53 pub mod gather_loans;
54
55 pub mod move_data;
56
57 #[derive(Clone, Copy)]
58 pub struct LoanDataFlowOperator;
59
60 pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
61
62 impl<'a, 'tcx, 'v> Visitor<'v> for BorrowckCtxt<'a, 'tcx> {
63     fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
64                 b: &'v Block, s: Span, id: ast::NodeId) {
65         match fk {
66             FnKind::ItemFn(..) |
67             FnKind::Method(..) => {
68                 let new_free_region_map = self.tcx.free_region_map(id);
69                 let old_free_region_map =
70                     mem::replace(&mut self.free_region_map, new_free_region_map);
71                 borrowck_fn(self, fk, fd, b, s, id);
72                 self.free_region_map = old_free_region_map;
73             }
74
75             FnKind::Closure => {
76                 borrowck_fn(self, fk, fd, b, s, id);
77             }
78         }
79     }
80
81     fn visit_item(&mut self, item: &hir::Item) {
82         borrowck_item(self, item);
83     }
84
85     fn visit_trait_item(&mut self, ti: &hir::TraitItem) {
86         if let hir::ConstTraitItem(_, Some(ref expr)) = ti.node {
87             gather_loans::gather_loans_in_static_initializer(self, &*expr);
88         }
89         intravisit::walk_trait_item(self, ti);
90     }
91
92     fn visit_impl_item(&mut self, ii: &hir::ImplItem) {
93         if let hir::ImplItemKind::Const(_, ref expr) = ii.node {
94             gather_loans::gather_loans_in_static_initializer(self, &*expr);
95         }
96         intravisit::walk_impl_item(self, ii);
97     }
98 }
99
100 pub fn check_crate(tcx: &ty::ctxt) {
101     let mut bccx = BorrowckCtxt {
102         tcx: tcx,
103         free_region_map: FreeRegionMap::new(),
104         stats: BorrowStats {
105             loaned_paths_same: 0,
106             loaned_paths_imm: 0,
107             stable_paths: 0,
108             guaranteed_paths: 0
109         }
110     };
111
112     tcx.map.krate().visit_all_items(&mut bccx);
113
114     if tcx.sess.borrowck_stats() {
115         println!("--- borrowck stats ---");
116         println!("paths requiring guarantees: {}",
117                  bccx.stats.guaranteed_paths);
118         println!("paths requiring loans     : {}",
119                  make_stat(&bccx, bccx.stats.loaned_paths_same));
120         println!("paths requiring imm loans : {}",
121                  make_stat(&bccx, bccx.stats.loaned_paths_imm));
122         println!("stable paths              : {}",
123                  make_stat(&bccx, bccx.stats.stable_paths));
124     }
125
126     fn make_stat(bccx: &BorrowckCtxt, stat: usize) -> String {
127         let total = bccx.stats.guaranteed_paths as f64;
128         let perc = if total == 0.0 { 0.0 } else { stat as f64 * 100.0 / total };
129         format!("{} ({:.0}%)", stat, perc)
130     }
131 }
132
133 fn borrowck_item(this: &mut BorrowckCtxt, item: &hir::Item) {
134     // Gather loans for items. Note that we don't need
135     // to check loans for single expressions. The check
136     // loan step is intended for things that have a data
137     // flow dependent conditions.
138     match item.node {
139         hir::ItemStatic(_, _, ref ex) |
140         hir::ItemConst(_, ref ex) => {
141             gather_loans::gather_loans_in_static_initializer(this, &**ex);
142         }
143         _ => { }
144     }
145
146     intravisit::walk_item(this, item);
147 }
148
149 /// Collection of conclusions determined via borrow checker analyses.
150 pub struct AnalysisData<'a, 'tcx: 'a> {
151     pub all_loans: Vec<Loan<'tcx>>,
152     pub loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>,
153     pub move_data: move_data::FlowedMoveData<'a, 'tcx>,
154 }
155
156 fn borrowck_fn(this: &mut BorrowckCtxt,
157                fk: FnKind,
158                decl: &hir::FnDecl,
159                body: &hir::Block,
160                sp: Span,
161                id: ast::NodeId) {
162     debug!("borrowck_fn(id={})", id);
163     let cfg = cfg::CFG::new(this.tcx, body);
164     let AnalysisData { all_loans,
165                        loans: loan_dfcx,
166                        move_data: flowed_moves } =
167         build_borrowck_dataflow_data(this, fk, decl, &cfg, body, sp, id);
168
169     move_data::fragments::instrument_move_fragments(&flowed_moves.move_data,
170                                                     this.tcx,
171                                                     sp,
172                                                     id);
173     move_data::fragments::build_unfragmented_map(this,
174                                                  &flowed_moves.move_data,
175                                                  id);
176
177     check_loans::check_loans(this,
178                              &loan_dfcx,
179                              &flowed_moves,
180                              &all_loans[..],
181                              id,
182                              decl,
183                              body);
184
185     intravisit::walk_fn(this, fk, decl, body, sp);
186 }
187
188 fn build_borrowck_dataflow_data<'a, 'tcx>(this: &mut BorrowckCtxt<'a, 'tcx>,
189                                           fk: FnKind,
190                                           decl: &hir::FnDecl,
191                                           cfg: &cfg::CFG,
192                                           body: &hir::Block,
193                                           sp: Span,
194                                           id: ast::NodeId)
195                                           -> AnalysisData<'a, 'tcx>
196 {
197     // Check the body of fn items.
198     let tcx = this.tcx;
199     let id_range = hir_util::compute_id_range_for_fn_body(fk, decl, body, sp, id);
200     let (all_loans, move_data) =
201         gather_loans::gather_loans_in_fn(this, id, decl, body);
202
203     let mut loan_dfcx =
204         DataFlowContext::new(this.tcx,
205                              "borrowck",
206                              Some(decl),
207                              cfg,
208                              LoanDataFlowOperator,
209                              id_range,
210                              all_loans.len());
211     for (loan_idx, loan) in all_loans.iter().enumerate() {
212         loan_dfcx.add_gen(loan.gen_scope.node_id(&tcx.region_maps), loan_idx);
213         loan_dfcx.add_kill(KillFrom::ScopeEnd,
214                            loan.kill_scope.node_id(&tcx.region_maps), loan_idx);
215     }
216     loan_dfcx.add_kills_from_flow_exits(cfg);
217     loan_dfcx.propagate(cfg, body);
218
219     let flowed_moves = move_data::FlowedMoveData::new(move_data,
220                                                       this.tcx,
221                                                       cfg,
222                                                       id_range,
223                                                       decl,
224                                                       body);
225
226     AnalysisData { all_loans: all_loans,
227                    loans: loan_dfcx,
228                    move_data:flowed_moves }
229 }
230
231 /// Accessor for introspective clients inspecting `AnalysisData` and
232 /// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer.
233 pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
234     tcx: &'a ty::ctxt<'tcx>,
235     fn_parts: FnParts<'a>,
236     cfg: &cfg::CFG)
237     -> (BorrowckCtxt<'a, 'tcx>, AnalysisData<'a, 'tcx>)
238 {
239
240     let mut bccx = BorrowckCtxt {
241         tcx: tcx,
242         free_region_map: FreeRegionMap::new(),
243         stats: BorrowStats {
244             loaned_paths_same: 0,
245             loaned_paths_imm: 0,
246             stable_paths: 0,
247             guaranteed_paths: 0
248         }
249     };
250
251     let dataflow_data = build_borrowck_dataflow_data(&mut bccx,
252                                                      fn_parts.kind,
253                                                      &*fn_parts.decl,
254                                                      cfg,
255                                                      &*fn_parts.body,
256                                                      fn_parts.span,
257                                                      fn_parts.id);
258
259     (bccx, dataflow_data)
260 }
261
262 // ----------------------------------------------------------------------
263 // Type definitions
264
265 pub struct BorrowckCtxt<'a, 'tcx: 'a> {
266     tcx: &'a ty::ctxt<'tcx>,
267
268     // Hacky. As we visit various fns, we have to load up the
269     // free-region map for each one. This map is computed by during
270     // typeck for each fn item and stored -- closures just use the map
271     // from the fn item that encloses them. Since we walk the fns in
272     // order, we basically just overwrite this field as we enter a fn
273     // item and restore it afterwards in a stack-like fashion. Then
274     // the borrow checking code can assume that `free_region_map` is
275     // always the correct map for the current fn. Feels like it'd be
276     // better to just recompute this, rather than store it, but it's a
277     // bit of a pain to factor that code out at the moment.
278     free_region_map: FreeRegionMap,
279
280     // Statistics:
281     stats: BorrowStats
282 }
283
284 struct BorrowStats {
285     loaned_paths_same: usize,
286     loaned_paths_imm: usize,
287     stable_paths: usize,
288     guaranteed_paths: usize
289 }
290
291 pub type BckResult<'tcx, T> = Result<T, BckError<'tcx>>;
292
293 ///////////////////////////////////////////////////////////////////////////
294 // Loans and loan paths
295
296 /// Record of a loan that was issued.
297 pub struct Loan<'tcx> {
298     index: usize,
299     loan_path: Rc<LoanPath<'tcx>>,
300     kind: ty::BorrowKind,
301     restricted_paths: Vec<Rc<LoanPath<'tcx>>>,
302
303     /// gen_scope indicates where loan is introduced. Typically the
304     /// loan is introduced at the point of the borrow, but in some
305     /// cases, notably method arguments, the loan may be introduced
306     /// only later, once it comes into scope.  See also
307     /// `GatherLoanCtxt::compute_gen_scope`.
308     gen_scope: region::CodeExtent,
309
310     /// kill_scope indicates when the loan goes out of scope.  This is
311     /// either when the lifetime expires or when the local variable
312     /// which roots the loan-path goes out of scope, whichever happens
313     /// faster. See also `GatherLoanCtxt::compute_kill_scope`.
314     kill_scope: region::CodeExtent,
315     span: Span,
316     cause: euv::LoanCause,
317 }
318
319 impl<'tcx> Loan<'tcx> {
320     pub fn loan_path(&self) -> Rc<LoanPath<'tcx>> {
321         self.loan_path.clone()
322     }
323 }
324
325 #[derive(Eq, Hash)]
326 pub struct LoanPath<'tcx> {
327     kind: LoanPathKind<'tcx>,
328     ty: ty::Ty<'tcx>,
329 }
330
331 impl<'tcx> PartialEq for LoanPath<'tcx> {
332     fn eq(&self, that: &LoanPath<'tcx>) -> bool {
333         let r = self.kind == that.kind;
334         debug_assert!(self.ty == that.ty || !r,
335                       "Somehow loan paths are equal though their tys are not.");
336         r
337     }
338 }
339
340 #[derive(PartialEq, Eq, Hash, Debug)]
341 pub enum LoanPathKind<'tcx> {
342     LpVar(ast::NodeId),                         // `x` in README.md
343     LpUpvar(ty::UpvarId),                       // `x` captured by-value into closure
344     LpDowncast(Rc<LoanPath<'tcx>>, DefId), // `x` downcast to particular enum variant
345     LpExtend(Rc<LoanPath<'tcx>>, mc::MutabilityCategory, LoanPathElem)
346 }
347
348 impl<'tcx> LoanPath<'tcx> {
349     fn new(kind: LoanPathKind<'tcx>, ty: ty::Ty<'tcx>) -> LoanPath<'tcx> {
350         LoanPath { kind: kind, ty: ty }
351     }
352
353     fn to_type(&self) -> ty::Ty<'tcx> { self.ty }
354 }
355
356 // FIXME (pnkfelix): See discussion here
357 // https://github.com/pnkfelix/rust/commit/
358 //     b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
359 const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
360
361 // A local, "cleaned" version of `mc::InteriorKind` that drops
362 // information that is not relevant to loan-path analysis. (In
363 // particular, the distinction between how precisely an array-element
364 // is tracked is irrelevant here.)
365 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
366 pub enum InteriorKind {
367     InteriorField(mc::FieldName),
368     InteriorElement(mc::ElementKind),
369 }
370
371 trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
372 impl ToInteriorKind for mc::InteriorKind {
373     fn cleaned(self) -> InteriorKind {
374         match self {
375             mc::InteriorField(name) => InteriorField(name),
376             mc::InteriorElement(_, elem_kind) => InteriorElement(elem_kind),
377         }
378     }
379 }
380
381 // This can be:
382 // - a pointer dereference (`*LV` in README.md)
383 // - a field reference, with an optional definition of the containing
384 //   enum variant (`LV.f` in README.md)
385 // `DefId` is present when the field is part of struct that is in
386 // a variant of an enum. For instance in:
387 // `enum E { X { foo: u32 }, Y { foo: u32 }}`
388 // each `foo` is qualified by the definitition id of the variant (`X` or `Y`).
389 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
390 pub enum LoanPathElem {
391     LpDeref(mc::PointerKind),
392     LpInterior(Option<DefId>, InteriorKind),
393 }
394
395 pub fn closure_to_block(closure_id: ast::NodeId,
396                         tcx: &ty::ctxt) -> ast::NodeId {
397     match tcx.map.get(closure_id) {
398         hir_map::NodeExpr(expr) => match expr.node {
399             hir::ExprClosure(_, _, ref block) => {
400                 block.id
401             }
402             _ => {
403                 panic!("encountered non-closure id: {}", closure_id)
404             }
405         },
406         _ => panic!("encountered non-expr id: {}", closure_id)
407     }
408 }
409
410 impl<'tcx> LoanPath<'tcx> {
411     pub fn kill_scope(&self, tcx: &ty::ctxt<'tcx>) -> region::CodeExtent {
412         match self.kind {
413             LpVar(local_id) => tcx.region_maps.var_scope(local_id),
414             LpUpvar(upvar_id) => {
415                 let block_id = closure_to_block(upvar_id.closure_expr_id, tcx);
416                 tcx.region_maps.node_extent(block_id)
417             }
418             LpDowncast(ref base, _) |
419             LpExtend(ref base, _, _) => base.kill_scope(tcx),
420         }
421     }
422
423     fn has_fork(&self, other: &LoanPath<'tcx>) -> bool {
424         match (&self.kind, &other.kind) {
425             (&LpExtend(ref base, _, LpInterior(opt_variant_id, id)),
426              &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) =>
427                 if id == id2 && opt_variant_id == opt_variant_id2 {
428                     base.has_fork(&**base2)
429                 } else {
430                     true
431                 },
432             (&LpExtend(ref base, _, LpDeref(_)), _) => base.has_fork(other),
433             (_, &LpExtend(ref base, _, LpDeref(_))) => self.has_fork(&**base),
434             _ => false,
435         }
436     }
437
438     fn depth(&self) -> usize {
439         match self.kind {
440             LpExtend(ref base, _, LpDeref(_)) => base.depth(),
441             LpExtend(ref base, _, LpInterior(_, _)) => base.depth() + 1,
442             _ => 0,
443         }
444     }
445
446     fn common(&self, other: &LoanPath<'tcx>) -> Option<LoanPath<'tcx>> {
447         match (&self.kind, &other.kind) {
448             (&LpExtend(ref base, a, LpInterior(opt_variant_id, id)),
449              &LpExtend(ref base2, _, LpInterior(opt_variant_id2, id2))) => {
450                 if id == id2 && opt_variant_id == opt_variant_id2 {
451                     base.common(&**base2).map(|x| {
452                         let xd = x.depth();
453                         if base.depth() == xd && base2.depth() == xd {
454                             assert_eq!(base.ty, base2.ty);
455                             assert_eq!(self.ty, other.ty);
456                             LoanPath {
457                                 kind: LpExtend(Rc::new(x), a, LpInterior(opt_variant_id, id)),
458                                 ty: self.ty,
459                             }
460                         } else {
461                             x
462                         }
463                     })
464                 } else {
465                     base.common(&**base2)
466                 }
467             }
468             (&LpExtend(ref base, _, LpDeref(_)), _) => base.common(other),
469             (_, &LpExtend(ref other, _, LpDeref(_))) => self.common(&**other),
470             (&LpVar(id), &LpVar(id2)) => {
471                 if id == id2 {
472                     assert_eq!(self.ty, other.ty);
473                     Some(LoanPath { kind: LpVar(id), ty: self.ty })
474                 } else {
475                     None
476                 }
477             }
478             (&LpUpvar(id), &LpUpvar(id2)) => {
479                 if id == id2 {
480                     assert_eq!(self.ty, other.ty);
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(PartialEq)]
544 pub enum bckerr_code {
545     err_mutbl,
546     err_out_of_scope(ty::Region, ty::Region), // superscope, subscope
547     err_borrowed_pointer_too_short(ty::Region, ty::Region), // loan, ptr
548 }
549
550 // Combination of an error code and the categorization of the expression
551 // that caused it
552 #[derive(PartialEq)]
553 pub struct BckError<'tcx> {
554     span: Span,
555     cause: AliasableViolationKind,
556     cmt: mc::cmt<'tcx>,
557     code: bckerr_code
558 }
559
560 #[derive(Copy, Clone, Debug, PartialEq)]
561 pub enum AliasableViolationKind {
562     MutabilityViolation,
563     BorrowViolation(euv::LoanCause)
564 }
565
566 #[derive(Copy, Clone, Debug)]
567 pub enum MovedValueUseKind {
568     MovedInUse,
569     MovedInCapture,
570 }
571
572 ///////////////////////////////////////////////////////////////////////////
573 // Misc
574
575 impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
576     pub fn is_subregion_of(&self, r_sub: ty::Region, r_sup: ty::Region)
577                            -> bool
578     {
579         self.free_region_map.is_subregion_of(self.tcx, r_sub, r_sup)
580     }
581
582     pub fn report(&self, err: BckError<'tcx>) {
583         // Catch and handle some particular cases.
584         match (&err.code, &err.cause) {
585             (&err_out_of_scope(ty::ReScope(_), ty::ReStatic),
586              &BorrowViolation(euv::ClosureCapture(span))) |
587             (&err_out_of_scope(ty::ReScope(_), ty::ReFree(..)),
588              &BorrowViolation(euv::ClosureCapture(span))) => {
589                 return self.report_out_of_scope_escaping_closure_capture(&err, span);
590             }
591             _ => { }
592         }
593
594         // General fallback.
595         let mut db = self.struct_span_err(
596             err.span,
597             &self.bckerr_to_string(&err));
598         self.note_and_explain_bckerr(&mut db, err);
599         db.emit();
600     }
601
602     pub fn report_use_of_moved_value<'b>(&self,
603                                          use_span: Span,
604                                          use_kind: MovedValueUseKind,
605                                          lp: &LoanPath<'tcx>,
606                                          the_move: &move_data::Move,
607                                          moved_lp: &LoanPath<'tcx>,
608                                          param_env: &ty::ParameterEnvironment<'b,'tcx>) {
609         let verb = match use_kind {
610             MovedInUse => "use",
611             MovedInCapture => "capture",
612         };
613
614         let (ol, moved_lp_msg, mut err) = match the_move.kind {
615             move_data::Declared => {
616                 let err = struct_span_err!(
617                     self.tcx.sess, use_span, E0381,
618                     "{} of possibly uninitialized variable: `{}`",
619                     verb,
620                     self.loan_path_to_string(lp));
621
622                 (self.loan_path_to_string(moved_lp),
623                  String::new(),
624                  err)
625             }
626             _ => {
627                 // If moved_lp is something like `x.a`, and lp is something like `x.b`, we would
628                 // normally generate a rather confusing message:
629                 //
630                 //     error: use of moved value: `x.b`
631                 //     note: `x.a` moved here...
632                 //
633                 // What we want to do instead is get the 'common ancestor' of the two moves and
634                 // use that for most of the message instead, giving is something like this:
635                 //
636                 //     error: use of moved value: `x`
637                 //     note: `x` moved here (through moving `x.a`)...
638
639                 let common = moved_lp.common(lp);
640                 let has_common = common.is_some();
641                 let has_fork = moved_lp.has_fork(lp);
642                 let (nl, ol, moved_lp_msg) =
643                     if has_fork && has_common {
644                         let nl = self.loan_path_to_string(&common.unwrap());
645                         let ol = nl.clone();
646                         let moved_lp_msg = format!(" (through moving `{}`)",
647                                                    self.loan_path_to_string(moved_lp));
648                         (nl, ol, moved_lp_msg)
649                     } else {
650                         (self.loan_path_to_string(lp),
651                          self.loan_path_to_string(moved_lp),
652                          String::new())
653                     };
654
655                 let partial = moved_lp.depth() > lp.depth();
656                 let msg = if !has_fork && partial { "partially " }
657                           else if has_fork && !has_common { "collaterally "}
658                           else { "" };
659                 let err = struct_span_err!(
660                     self.tcx.sess, use_span, E0382,
661                     "{} of {}moved value: `{}`",
662                     verb, msg, nl);
663                 (ol, moved_lp_msg, err)
664             }
665         };
666
667         match the_move.kind {
668             move_data::Declared => {}
669
670             move_data::MoveExpr => {
671                 let (expr_ty, expr_span) = match self.tcx
672                                                      .map
673                                                      .find(the_move.id) {
674                     Some(hir_map::NodeExpr(expr)) => {
675                         (self.tcx.expr_ty_adjusted(&*expr), expr.span)
676                     }
677                     r => {
678                         self.tcx.sess.bug(&format!("MoveExpr({}) maps to \
679                                                    {:?}, not Expr",
680                                                   the_move.id,
681                                                   r))
682                     }
683                 };
684                 let (suggestion, _) =
685                     move_suggestion(param_env, expr_span, expr_ty, ("moved by default", ""));
686                 // If the two spans are the same, it's because the expression will be evaluated
687                 // multiple times. Avoid printing the same span and adjust the wording so it makes
688                 // more sense that it's from multiple evalutations.
689                 if expr_span == use_span {
690                     err.note(
691                         &format!("`{}` was previously moved here{} because it has type `{}`, \
692                                   which is {}",
693                                  ol,
694                                  moved_lp_msg,
695                                  expr_ty,
696                                  suggestion));
697                 } else {
698                     err.span_note(
699                         expr_span,
700                         &format!("`{}` moved here{} because it has type `{}`, which is {}",
701                                  ol,
702                                  moved_lp_msg,
703                                  expr_ty,
704                                  suggestion));
705                 }
706             }
707
708             move_data::MovePat => {
709                 let pat_ty = self.tcx.node_id_to_type(the_move.id);
710                 let span = self.tcx.map.span(the_move.id);
711                 err.span_note(span,
712                     &format!("`{}` moved here{} because it has type `{}`, \
713                              which is moved by default",
714                             ol,
715                             moved_lp_msg,
716                             pat_ty));
717                 match self.tcx.sess.codemap().span_to_snippet(span) {
718                     Ok(string) => {
719                         err.span_suggestion(
720                             span,
721                             &format!("if you would like to borrow the value instead, \
722                                       use a `ref` binding as shown:"),
723                             format!("ref {}", string));
724                     },
725                     Err(_) => {
726                         err.fileline_help(span,
727                             "use `ref` to override");
728                     },
729                 }
730             }
731
732             move_data::Captured => {
733                 let (expr_ty, expr_span) = match self.tcx
734                                                      .map
735                                                      .find(the_move.id) {
736                     Some(hir_map::NodeExpr(expr)) => {
737                         (self.tcx.expr_ty_adjusted(&*expr), expr.span)
738                     }
739                     r => {
740                         self.tcx.sess.bug(&format!("Captured({}) maps to \
741                                                    {:?}, not Expr",
742                                                   the_move.id,
743                                                   r))
744                     }
745                 };
746                 let (suggestion, help) =
747                     move_suggestion(param_env,
748                                     expr_span,
749                                     expr_ty,
750                                     ("moved by default",
751                                      "make a copy and capture that instead to override"));
752                 err.span_note(
753                     expr_span,
754                     &format!("`{}` moved into closure environment here{} because it \
755                             has type `{}`, which is {}",
756                             ol,
757                             moved_lp_msg,
758                             moved_lp.ty,
759                             suggestion));
760                 err.fileline_help(expr_span, help);
761             }
762         }
763         err.emit();
764
765         fn move_suggestion<'a,'tcx>(param_env: &ty::ParameterEnvironment<'a,'tcx>,
766                                     span: Span,
767                                     ty: Ty<'tcx>,
768                                     default_msgs: (&'static str, &'static str))
769                                     -> (&'static str, &'static str) {
770             match ty.sty {
771                 _ => {
772                     if ty.moves_by_default(param_env, span) {
773                         ("non-copyable",
774                          "perhaps you meant to use `clone()`?")
775                     } else {
776                         default_msgs
777                     }
778                 }
779             }
780         }
781     }
782
783     pub fn report_partial_reinitialization_of_uninitialized_structure(
784             &self,
785             span: Span,
786             lp: &LoanPath<'tcx>) {
787         span_err!(
788             self.tcx.sess, span, E0383,
789             "partial reinitialization of uninitialized structure `{}`",
790             self.loan_path_to_string(lp));
791     }
792
793     pub fn report_reassigned_immutable_variable(&self,
794                                                 span: Span,
795                                                 lp: &LoanPath<'tcx>,
796                                                 assign:
797                                                 &move_data::Assignment) {
798         struct_span_err!(
799             self.tcx.sess, span, E0384,
800             "re-assignment of immutable variable `{}`",
801             self.loan_path_to_string(lp))
802             .span_note(assign.span, "prior assignment occurs here")
803             .emit();
804     }
805
806     pub fn span_err(&self, s: Span, m: &str) {
807         self.tcx.sess.span_err(s, m);
808     }
809
810     pub fn struct_span_err(&self, s: Span, m: &str) -> DiagnosticBuilder<'a> {
811         self.tcx.sess.struct_span_err(s, m)
812     }
813
814     pub fn struct_span_err_with_code(&self,
815                                      s: Span,
816                                      msg: &str,
817                                      code: &str)
818                                      -> DiagnosticBuilder<'a> {
819         self.tcx.sess.struct_span_err_with_code(s, msg, code)
820     }
821
822     pub fn span_err_with_code(&self, s: Span, msg: &str, code: &str) {
823         self.tcx.sess.span_err_with_code(s, msg, code);
824     }
825
826     pub fn span_bug(&self, s: Span, m: &str) {
827         self.tcx.sess.span_bug(s, m);
828     }
829
830     pub fn bckerr_to_string(&self, err: &BckError<'tcx>) -> String {
831         match err.code {
832             err_mutbl => {
833                 let descr = match err.cmt.note {
834                     mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
835                         self.cmt_to_string(&*err.cmt)
836                     }
837                     _ => match opt_loan_path(&err.cmt) {
838                         None => {
839                             format!("{} {}",
840                                     err.cmt.mutbl.to_user_str(),
841                                     self.cmt_to_string(&*err.cmt))
842                         }
843                         Some(lp) => {
844                             format!("{} {} `{}`",
845                                     err.cmt.mutbl.to_user_str(),
846                                     self.cmt_to_string(&*err.cmt),
847                                     self.loan_path_to_string(&*lp))
848                         }
849                     }
850                 };
851
852                 match err.cause {
853                     MutabilityViolation => {
854                         format!("cannot assign to {}", descr)
855                     }
856                     BorrowViolation(euv::ClosureCapture(_)) => {
857                         format!("closure cannot assign to {}", descr)
858                     }
859                     BorrowViolation(euv::OverloadedOperator) |
860                     BorrowViolation(euv::AddrOf) |
861                     BorrowViolation(euv::RefBinding) |
862                     BorrowViolation(euv::AutoRef) |
863                     BorrowViolation(euv::AutoUnsafe) |
864                     BorrowViolation(euv::ForLoop) |
865                     BorrowViolation(euv::MatchDiscriminant) => {
866                         format!("cannot borrow {} as mutable", descr)
867                     }
868                     BorrowViolation(euv::ClosureInvocation) => {
869                         self.tcx.sess.span_bug(err.span,
870                             "err_mutbl with a closure invocation");
871                     }
872                 }
873             }
874             err_out_of_scope(..) => {
875                 let msg = match opt_loan_path(&err.cmt) {
876                     None => "borrowed value".to_string(),
877                     Some(lp) => {
878                         format!("`{}`", self.loan_path_to_string(&*lp))
879                     }
880                 };
881                 format!("{} does not live long enough", msg)
882             }
883             err_borrowed_pointer_too_short(..) => {
884                 let descr = self.cmt_to_path_or_string(&err.cmt);
885                 format!("lifetime of {} is too short to guarantee \
886                          its contents can be safely reborrowed",
887                         descr)
888             }
889         }
890     }
891
892     pub fn report_aliasability_violation(&self,
893                                          span: Span,
894                                          kind: AliasableViolationKind,
895                                          cause: mc::AliasableReason) {
896         let mut is_closure = false;
897         let prefix = match kind {
898             MutabilityViolation => {
899                 "cannot assign to data"
900             }
901             BorrowViolation(euv::ClosureCapture(_)) |
902             BorrowViolation(euv::OverloadedOperator) |
903             BorrowViolation(euv::AddrOf) |
904             BorrowViolation(euv::AutoRef) |
905             BorrowViolation(euv::AutoUnsafe) |
906             BorrowViolation(euv::RefBinding) |
907             BorrowViolation(euv::MatchDiscriminant) => {
908                 "cannot borrow data mutably"
909             }
910
911             BorrowViolation(euv::ClosureInvocation) => {
912                 is_closure = true;
913                 "closure invocation"
914             }
915
916             BorrowViolation(euv::ForLoop) => {
917                 "`for` loop"
918             }
919         };
920
921         let mut err = match cause {
922             mc::AliasableOther => {
923                 struct_span_err!(
924                     self.tcx.sess, span, E0385,
925                     "{} in an aliasable location", prefix)
926             }
927             mc::AliasableReason::UnaliasableImmutable => {
928                 struct_span_err!(
929                     self.tcx.sess, span, E0386,
930                     "{} in an immutable container", prefix)
931             }
932             mc::AliasableClosure(id) => {
933                 let mut err = struct_span_err!(
934                     self.tcx.sess, span, E0387,
935                     "{} in a captured outer variable in an `Fn` closure", prefix);
936                 if let BorrowViolation(euv::ClosureCapture(_)) = kind {
937                     // The aliasability violation with closure captures can
938                     // happen for nested closures, so we know the enclosing
939                     // closure incorrectly accepts an `Fn` while it needs to
940                     // be `FnMut`.
941                     span_help!(&mut err, self.tcx.map.span(id),
942                            "consider changing this to accept closures that implement `FnMut`");
943                 } else {
944                     span_help!(&mut err, self.tcx.map.span(id),
945                            "consider changing this closure to take self by mutable reference");
946                 }
947                 err
948             }
949             mc::AliasableStatic |
950             mc::AliasableStaticMut => {
951                 struct_span_err!(
952                     self.tcx.sess, span, E0388,
953                     "{} in a static location", prefix)
954             }
955             mc::AliasableBorrowed => {
956                 struct_span_err!(
957                     self.tcx.sess, span, E0389,
958                     "{} in a `&` reference", prefix)
959             }
960         };
961
962         if is_closure {
963             err.fileline_help(span,
964                               "closures behind references must be called via `&mut`");
965         }
966         err.emit();
967     }
968
969     fn report_out_of_scope_escaping_closure_capture(&self,
970                                                     err: &BckError<'tcx>,
971                                                     capture_span: Span)
972     {
973         let cmt_path_or_string = self.cmt_to_path_or_string(&err.cmt);
974
975         let suggestion =
976             match self.tcx.sess.codemap().span_to_snippet(err.span) {
977                 Ok(string) => format!("move {}", string),
978                 Err(_) => format!("move |<args>| <body>")
979             };
980
981         struct_span_err!(self.tcx.sess, err.span, E0373,
982                          "closure may outlive the current function, \
983                           but it borrows {}, \
984                           which is owned by the current function",
985                          cmt_path_or_string)
986             .span_note(capture_span,
987                        &format!("{} is borrowed here",
988                                 cmt_path_or_string))
989             .span_suggestion(err.span,
990                              &format!("to force the closure to take ownership of {} \
991                                        (and any other referenced variables), \
992                                        use the `move` keyword, as shown:",
993                                       cmt_path_or_string),
994                              suggestion)
995             .emit();
996     }
997
998     pub fn note_and_explain_bckerr(&self, db: &mut DiagnosticBuilder, err: BckError<'tcx>) {
999         let code = err.code;
1000         match code {
1001             err_mutbl => {
1002                 match err.cmt.note {
1003                     mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
1004                         // If this is an `Fn` closure, it simply can't mutate upvars.
1005                         // If it's an `FnMut` closure, the original variable was declared immutable.
1006                         // We need to determine which is the case here.
1007                         let kind = match err.cmt.upvar().unwrap().cat {
1008                             Categorization::Upvar(mc::Upvar { kind, .. }) => kind,
1009                             _ => unreachable!()
1010                         };
1011                         if kind == ty::FnClosureKind {
1012                             db.span_help(
1013                                 self.tcx.map.span(upvar_id.closure_expr_id),
1014                                 "consider changing this closure to take \
1015                                  self by mutable reference");
1016                         }
1017                     }
1018                     _ => {
1019                         if let Categorization::Local(local_id) = err.cmt.cat {
1020                             let span = self.tcx.map.span(local_id);
1021                             if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
1022                                 db.span_suggestion(
1023                                     span,
1024                                     &format!("to make the {} mutable, use `mut` as shown:",
1025                                              self.cmt_to_string(&err.cmt)),
1026                                     format!("mut {}", snippet));
1027                             }
1028                         }
1029                     }
1030                 }
1031             }
1032
1033             err_out_of_scope(super_scope, sub_scope) => {
1034                 self.tcx.note_and_explain_region(
1035                     db,
1036                     "reference must be valid for ",
1037                     sub_scope,
1038                     "...");
1039                 self.tcx.note_and_explain_region(
1040                     db,
1041                     "...but borrowed value is only valid for ",
1042                     super_scope,
1043                     "");
1044                 if let Some(span) = statement_scope_span(self.tcx, super_scope) {
1045                     db.span_help(span,
1046                                  "consider using a `let` binding to increase its lifetime");
1047                 }
1048             }
1049
1050             err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
1051                 let descr = match opt_loan_path(&err.cmt) {
1052                     Some(lp) => {
1053                         format!("`{}`", self.loan_path_to_string(&*lp))
1054                     }
1055                     None => self.cmt_to_string(&*err.cmt),
1056                 };
1057                 self.tcx.note_and_explain_region(
1058                     db,
1059                     &format!("{} would have to be valid for ",
1060                             descr),
1061                     loan_scope,
1062                     "...");
1063                 self.tcx.note_and_explain_region(
1064                     db,
1065                     &format!("...but {} is only valid for ", descr),
1066                     ptr_scope,
1067                     "");
1068             }
1069         }
1070     }
1071
1072     pub fn append_loan_path_to_string(&self,
1073                                       loan_path: &LoanPath<'tcx>,
1074                                       out: &mut String) {
1075         match loan_path.kind {
1076             LpUpvar(ty::UpvarId{ var_id: id, closure_expr_id: _ }) |
1077             LpVar(id) => {
1078                 out.push_str(&self.tcx.local_var_name_str(id));
1079             }
1080
1081             LpDowncast(ref lp_base, variant_def_id) => {
1082                 out.push('(');
1083                 self.append_loan_path_to_string(&**lp_base, out);
1084                 out.push_str(DOWNCAST_PRINTED_OPERATOR);
1085                 out.push_str(&self.tcx.item_path_str(variant_def_id));
1086                 out.push(')');
1087             }
1088
1089
1090             LpExtend(ref lp_base, _, LpInterior(_, InteriorField(fname))) => {
1091                 self.append_autoderefd_loan_path_to_string(&**lp_base, out);
1092                 match fname {
1093                     mc::NamedField(fname) => {
1094                         out.push('.');
1095                         out.push_str(&fname.as_str());
1096                     }
1097                     mc::PositionalField(idx) => {
1098                         out.push('.');
1099                         out.push_str(&idx.to_string());
1100                     }
1101                 }
1102             }
1103
1104             LpExtend(ref lp_base, _, LpInterior(_, InteriorElement(..))) => {
1105                 self.append_autoderefd_loan_path_to_string(&**lp_base, out);
1106                 out.push_str("[..]");
1107             }
1108
1109             LpExtend(ref lp_base, _, LpDeref(_)) => {
1110                 out.push('*');
1111                 self.append_loan_path_to_string(&**lp_base, out);
1112             }
1113         }
1114     }
1115
1116     pub fn append_autoderefd_loan_path_to_string(&self,
1117                                                  loan_path: &LoanPath<'tcx>,
1118                                                  out: &mut String) {
1119         match loan_path.kind {
1120             LpExtend(ref lp_base, _, LpDeref(_)) => {
1121                 // For a path like `(*x).f` or `(*x)[3]`, autoderef
1122                 // rules would normally allow users to omit the `*x`.
1123                 // So just serialize such paths to `x.f` or x[3]` respectively.
1124                 self.append_autoderefd_loan_path_to_string(&**lp_base, out)
1125             }
1126
1127             LpDowncast(ref lp_base, variant_def_id) => {
1128                 out.push('(');
1129                 self.append_autoderefd_loan_path_to_string(&**lp_base, out);
1130                 out.push(':');
1131                 out.push_str(&self.tcx.item_path_str(variant_def_id));
1132                 out.push(')');
1133             }
1134
1135             LpVar(..) | LpUpvar(..) | LpExtend(_, _, LpInterior(..)) => {
1136                 self.append_loan_path_to_string(loan_path, out)
1137             }
1138         }
1139     }
1140
1141     pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
1142         let mut result = String::new();
1143         self.append_loan_path_to_string(loan_path, &mut result);
1144         result
1145     }
1146
1147     pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
1148         cmt.descriptive_string(self.tcx)
1149     }
1150
1151     pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt<'tcx>) -> String {
1152         match opt_loan_path(cmt) {
1153             Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
1154             None => self.cmt_to_string(cmt),
1155         }
1156     }
1157 }
1158
1159 fn statement_scope_span(tcx: &ty::ctxt, region: ty::Region) -> Option<Span> {
1160     match region {
1161         ty::ReScope(scope) => {
1162             match tcx.map.find(scope.node_id(&tcx.region_maps)) {
1163                 Some(hir_map::NodeStmt(stmt)) => Some(stmt.span),
1164                 _ => None
1165             }
1166         }
1167         _ => None
1168     }
1169 }
1170
1171 impl BitwiseOperator for LoanDataFlowOperator {
1172     #[inline]
1173     fn join(&self, succ: usize, pred: usize) -> usize {
1174         succ | pred // loans from both preds are in scope
1175     }
1176 }
1177
1178 impl DataFlowOperator for LoanDataFlowOperator {
1179     #[inline]
1180     fn initial_value(&self) -> bool {
1181         false // no loans in scope by default
1182     }
1183 }
1184
1185 impl<'tcx> fmt::Debug for InteriorKind {
1186     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1187         match *self {
1188             InteriorField(mc::NamedField(fld)) => write!(f, "{}", fld),
1189             InteriorField(mc::PositionalField(i)) => write!(f, "#{}", i),
1190             InteriorElement(..) => write!(f, "[]"),
1191         }
1192     }
1193 }
1194
1195 impl<'tcx> fmt::Debug for Loan<'tcx> {
1196     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1197         write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
1198                self.index,
1199                self.loan_path,
1200                self.kind,
1201                self.gen_scope,
1202                self.kill_scope,
1203                self.restricted_paths)
1204     }
1205 }
1206
1207 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
1208     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1209         match self.kind {
1210             LpVar(id) => {
1211                 write!(f, "$({})", ty::tls::with(|tcx| tcx.map.node_to_string(id)))
1212             }
1213
1214             LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => {
1215                 let s = ty::tls::with(|tcx| tcx.map.node_to_string(var_id));
1216                 write!(f, "$({} captured by id={})", s, closure_expr_id)
1217             }
1218
1219             LpDowncast(ref lp, variant_def_id) => {
1220                 let variant_str = if variant_def_id.is_local() {
1221                     ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1222                 } else {
1223                     format!("{:?}", variant_def_id)
1224                 };
1225                 write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1226             }
1227
1228             LpExtend(ref lp, _, LpDeref(_)) => {
1229                 write!(f, "{:?}.*", lp)
1230             }
1231
1232             LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1233                 write!(f, "{:?}.{:?}", lp, interior)
1234             }
1235         }
1236     }
1237 }
1238
1239 impl<'tcx> fmt::Display for LoanPath<'tcx> {
1240     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1241         match self.kind {
1242             LpVar(id) => {
1243                 write!(f, "$({})", ty::tls::with(|tcx| tcx.map.node_to_user_string(id)))
1244             }
1245
1246             LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => {
1247                 let s = ty::tls::with(|tcx| tcx.map.node_to_user_string(var_id));
1248                 write!(f, "$({} captured by closure)", s)
1249             }
1250
1251             LpDowncast(ref lp, variant_def_id) => {
1252                 let variant_str = if variant_def_id.is_local() {
1253                     ty::tls::with(|tcx| tcx.item_path_str(variant_def_id))
1254                 } else {
1255                     format!("{:?}", variant_def_id)
1256                 };
1257                 write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str)
1258             }
1259
1260             LpExtend(ref lp, _, LpDeref(_)) => {
1261                 write!(f, "{}.*", lp)
1262             }
1263
1264             LpExtend(ref lp, _, LpInterior(_, ref interior)) => {
1265                 write!(f, "{}.{:?}", lp, interior)
1266             }
1267         }
1268     }
1269 }