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