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