]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/mod.rs
Track unused mutable variables across closures
[rust.git] / src / librustc_mir / borrow_check / mod.rs
1 // Copyright 2017 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 //! This query borrow-checks the MIR to (further) ensure it is not broken.
12
13 use borrow_check::nll::region_infer::{RegionCausalInfo, RegionInferenceContext};
14 use rustc::hir;
15 use rustc::hir::def_id::DefId;
16 use rustc::hir::map::definitions::DefPathData;
17 use rustc::infer::InferCtxt;
18 use rustc::ty::{self, ParamEnv, TyCtxt};
19 use rustc::ty::maps::Providers;
20 use rustc::lint::builtin::UNUSED_MUT;
21 use rustc::mir::{AssertMessage, AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
22 use rustc::mir::{ClearCrossCrate, Local, Location, Place, Mir, Mutability, Operand};
23 use rustc::mir::{Projection, ProjectionElem, Rvalue, Field, Statement, StatementKind};
24 use rustc::mir::{Terminator, TerminatorKind};
25
26 use rustc_data_structures::control_flow_graph::dominators::Dominators;
27 use rustc_data_structures::fx::FxHashSet;
28 use rustc_data_structures::indexed_set::IdxSetBuf;
29 use rustc_data_structures::indexed_vec::Idx;
30 use rustc_data_structures::small_vec::SmallVec;
31
32 use std::rc::Rc;
33
34 use syntax_pos::Span;
35
36 use dataflow::{do_dataflow, DebugFormatted};
37 use dataflow::FlowAtLocation;
38 use dataflow::MoveDataParamEnv;
39 use dataflow::{DataflowResultsConsumer};
40 use dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
41 use dataflow::{EverInitializedPlaces, MovingOutStatements};
42 use dataflow::Borrows;
43 use dataflow::indexes::BorrowIndex;
44 use dataflow::move_paths::{IllegalMoveOriginKind, MoveError};
45 use dataflow::move_paths::{HasMoveData, LookupResult, MoveData, MovePathIndex};
46 use util::borrowck_errors::{BorrowckErrors, Origin};
47 use util::collect_writes::FindAssignments;
48
49 use std::iter;
50
51 use self::borrow_set::{BorrowSet, BorrowData};
52 use self::flows::Flows;
53 use self::prefixes::PrefixSet;
54 use self::MutateMode::{JustWrite, WriteAndRead};
55
56 crate mod borrow_set;
57 mod error_reporting;
58 mod flows;
59 crate mod place_ext;
60 mod prefixes;
61
62 pub(crate) mod nll;
63
64 pub fn provide(providers: &mut Providers) {
65     *providers = Providers {
66         mir_borrowck,
67         ..*providers
68     };
69 }
70
71 fn mir_borrowck<'a, 'tcx>(
72     tcx: TyCtxt<'a, 'tcx, 'tcx>,
73     def_id: DefId,
74 ) -> BorrowCheckResult<'tcx> {
75     let input_mir = tcx.mir_validated(def_id);
76     debug!("run query mir_borrowck: {}", tcx.item_path_str(def_id));
77
78     if !tcx.has_attr(def_id, "rustc_mir_borrowck") && !tcx.use_mir_borrowck() {
79         return BorrowCheckResult {
80             closure_requirements: None,
81             used_mut_upvars: SmallVec::new(),
82         };
83     }
84
85     let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
86         let input_mir: &Mir = &input_mir.borrow();
87         do_mir_borrowck(&infcx, input_mir, def_id)
88     });
89     debug!("mir_borrowck done");
90
91     opt_closure_req
92 }
93
94 fn do_mir_borrowck<'a, 'gcx, 'tcx>(
95     infcx: &InferCtxt<'a, 'gcx, 'tcx>,
96     input_mir: &Mir<'gcx>,
97     def_id: DefId,
98 ) -> BorrowCheckResult<'gcx> {
99     let tcx = infcx.tcx;
100     let attributes = tcx.get_attrs(def_id);
101     let param_env = tcx.param_env(def_id);
102     let id = tcx.hir
103         .as_local_node_id(def_id)
104         .expect("do_mir_borrowck: non-local DefId");
105
106     // Replace all regions with fresh inference variables. This
107     // requires first making our own copy of the MIR. This copy will
108     // be modified (in place) to contain non-lexical lifetimes. It
109     // will have a lifetime tied to the inference context.
110     let mut mir: Mir<'tcx> = input_mir.clone();
111     let free_regions = nll::replace_regions_in_mir(infcx, def_id, param_env, &mut mir);
112     let mir = &mir; // no further changes
113
114     let move_data: MoveData<'tcx> = match MoveData::gather_moves(mir, tcx) {
115         Ok(move_data) => move_data,
116         Err((move_data, move_errors)) => {
117             for move_error in move_errors {
118                 let (span, kind): (Span, IllegalMoveOriginKind) = match move_error {
119                     MoveError::UnionMove { .. } => {
120                         unimplemented!("don't know how to report union move errors yet.")
121                     }
122                     MoveError::IllegalMove {
123                         cannot_move_out_of: o,
124                     } => (o.span, o.kind),
125                 };
126                 let origin = Origin::Mir;
127                 let mut err = match kind {
128                     IllegalMoveOriginKind::Static => {
129                         tcx.cannot_move_out_of(span, "static item", origin)
130                     }
131                     IllegalMoveOriginKind::BorrowedContent => {
132                         tcx.cannot_move_out_of(span, "borrowed content", origin)
133                     }
134                     IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
135                         tcx.cannot_move_out_of_interior_of_drop(span, ty, origin)
136                     }
137                     IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => {
138                         tcx.cannot_move_out_of_interior_noncopy(span, ty, is_index, origin)
139                     }
140                 };
141                 err.emit();
142             }
143             move_data
144         }
145     };
146
147     let mdpe = MoveDataParamEnv {
148         move_data: move_data,
149         param_env: param_env,
150     };
151     let body_id = match tcx.def_key(def_id).disambiguated_data.data {
152         DefPathData::StructCtor | DefPathData::EnumVariant(_) => None,
153         _ => Some(tcx.hir.body_owned_by(id)),
154     };
155
156     let dead_unwinds = IdxSetBuf::new_empty(mir.basic_blocks().len());
157     let mut flow_inits = FlowAtLocation::new(do_dataflow(
158         tcx,
159         mir,
160         id,
161         &attributes,
162         &dead_unwinds,
163         MaybeInitializedPlaces::new(tcx, mir, &mdpe),
164         |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
165     ));
166     let flow_uninits = FlowAtLocation::new(do_dataflow(
167         tcx,
168         mir,
169         id,
170         &attributes,
171         &dead_unwinds,
172         MaybeUninitializedPlaces::new(tcx, mir, &mdpe),
173         |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
174     ));
175     let flow_move_outs = FlowAtLocation::new(do_dataflow(
176         tcx,
177         mir,
178         id,
179         &attributes,
180         &dead_unwinds,
181         MovingOutStatements::new(tcx, mir, &mdpe),
182         |bd, i| DebugFormatted::new(&bd.move_data().moves[i]),
183     ));
184     let flow_ever_inits = FlowAtLocation::new(do_dataflow(
185         tcx,
186         mir,
187         id,
188         &attributes,
189         &dead_unwinds,
190         EverInitializedPlaces::new(tcx, mir, &mdpe),
191         |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
192     ));
193
194     let borrow_set = Rc::new(BorrowSet::build(tcx, mir));
195
196     // If we are in non-lexical mode, compute the non-lexical lifetimes.
197     let (regioncx, opt_closure_req) = nll::compute_regions(
198         infcx,
199         def_id,
200         free_regions,
201         mir,
202         param_env,
203         &mut flow_inits,
204         &mdpe.move_data,
205         &borrow_set,
206     );
207     let regioncx = Rc::new(regioncx);
208     let flow_inits = flow_inits; // remove mut
209
210     let flow_borrows = FlowAtLocation::new(do_dataflow(
211         tcx,
212         mir,
213         id,
214         &attributes,
215         &dead_unwinds,
216         Borrows::new(tcx, mir, regioncx.clone(), def_id, body_id, &borrow_set),
217         |rs, i| DebugFormatted::new(&rs.location(i)),
218     ));
219
220     let movable_generator = match tcx.hir.get(id) {
221         hir::map::Node::NodeExpr(&hir::Expr {
222             node: hir::ExprClosure(.., Some(hir::GeneratorMovability::Static)),
223             ..
224         }) => false,
225         _ => true,
226     };
227
228     let dominators = mir.dominators();
229
230     let mut mbcx = MirBorrowckCtxt {
231         tcx: tcx,
232         mir: mir,
233         mir_def_id: def_id,
234         move_data: &mdpe.move_data,
235         param_env: param_env,
236         movable_generator,
237         locals_are_invalidated_at_exit: match tcx.hir.body_owner_kind(id) {
238             hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => false,
239             hir::BodyOwnerKind::Fn => true,
240         },
241         access_place_error_reported: FxHashSet(),
242         reservation_error_reported: FxHashSet(),
243         moved_error_reported: FxHashSet(),
244         nonlexical_regioncx: opt_regioncx,
245         used_mut: FxHashSet(),
246         used_mut_upvars: SmallVec::new(),
247         nonlexical_cause_info: None,
248         borrow_set,
249         dominators,
250     };
251
252     let mut state = Flows::new(
253         flow_borrows,
254         flow_inits,
255         flow_uninits,
256         flow_move_outs,
257         flow_ever_inits,
258     );
259
260     mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
261
262     debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
263
264     for local in mbcx.mir.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)) {
265         if let ClearCrossCrate::Set(ref vsi) = mbcx.mir.visibility_scope_info {
266             let source_info = mbcx.mir.local_decls[local].source_info;
267             let mut_span = tcx.sess.codemap().span_until_non_whitespace(source_info.span);
268
269             tcx.struct_span_lint_node(
270                 UNUSED_MUT,
271                 vsi[source_info.scope].lint_root,
272                 source_info.span,
273                 "variable does not need to be mutable"
274             )
275             .span_suggestion_short(mut_span, "remove this `mut`", "".to_owned())
276             .emit();
277         }
278     }
279
280     BorrowCheckResult {
281         closure_requirements: opt_closure_req,
282         used_mut_upvars: mbcx.used_mut_upvars,
283     }
284 }
285
286 #[allow(dead_code)]
287 pub struct MirBorrowckCtxt<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
288     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
289     mir: &'cx Mir<'tcx>,
290     mir_def_id: DefId,
291     move_data: &'cx MoveData<'tcx>,
292     param_env: ParamEnv<'gcx>,
293     movable_generator: bool,
294     /// This keeps track of whether local variables are free-ed when the function
295     /// exits even without a `StorageDead`, which appears to be the case for
296     /// constants.
297     ///
298     /// I'm not sure this is the right approach - @eddyb could you try and
299     /// figure this out?
300     locals_are_invalidated_at_exit: bool,
301     /// This field keeps track of when borrow errors are reported in the access_place function
302     /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
303     /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
304     /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
305     /// errors.
306     access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
307     /// This field keeps track of when borrow conflict errors are reported
308     /// for reservations, so that we don't report seemingly duplicate
309     /// errors for corresponding activations
310     ///
311     /// FIXME: Ideally this would be a set of BorrowIndex, not Places,
312     /// but it is currently inconvenient to track down the BorrowIndex
313     /// at the time we detect and report a reservation error.
314     reservation_error_reported: FxHashSet<Place<'tcx>>,
315     /// This field keeps track of errors reported in the checking of moved variables,
316     /// so that we don't report report seemingly duplicate errors.
317     moved_error_reported: FxHashSet<Place<'tcx>>,
318     /// This field keeps track of all the local variables that are declared mut and are mutated.
319     /// Used for the warning issued by an unused mutable local variable.
320     used_mut: FxHashSet<Local>,
321     /// If the function we're checking is a closure, then we'll need to report back the list of
322     /// mutable upvars that have been used. This field keeps track of them.
323     used_mut_upvars: SmallVec<[Field; 8]>,
324     /// Non-lexical region inference context, if NLL is enabled.  This
325     /// contains the results from region inference and lets us e.g.
326     /// find out which CFG points are contained in each borrow region.
327     nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
328     nonlexical_cause_info: Option<RegionCausalInfo>,
329
330     /// The set of borrows extracted from the MIR
331     borrow_set: Rc<BorrowSet<'tcx>>,
332
333     /// Dominators for MIR
334     dominators: Dominators<BasicBlock>,
335 }
336
337 // Check that:
338 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
339 // 2. loans made in overlapping scopes do not conflict
340 // 3. assignments do not affect things loaned out as immutable
341 // 4. moves do not affect things loaned out in any way
342 impl<'cx, 'gcx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
343     type FlowState = Flows<'cx, 'gcx, 'tcx>;
344
345     fn mir(&self) -> &'cx Mir<'tcx> {
346         self.mir
347     }
348
349     fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
350         debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
351     }
352
353     fn visit_statement_entry(
354         &mut self,
355         location: Location,
356         stmt: &Statement<'tcx>,
357         flow_state: &Self::FlowState,
358     ) {
359         debug!(
360             "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
361             location, stmt, flow_state
362         );
363         let span = stmt.source_info.span;
364
365         self.check_activations(location, span, flow_state);
366
367         match stmt.kind {
368             StatementKind::Assign(ref lhs, ref rhs) => {
369                 self.consume_rvalue(
370                     ContextKind::AssignRhs.new(location),
371                     (rhs, span),
372                     location,
373                     flow_state,
374                 );
375
376                 self.mutate_place(
377                     ContextKind::AssignLhs.new(location),
378                     (lhs, span),
379                     Shallow(None),
380                     JustWrite,
381                     flow_state,
382                 );
383             }
384             StatementKind::SetDiscriminant {
385                 ref place,
386                 variant_index: _,
387             } => {
388                 self.mutate_place(
389                     ContextKind::SetDiscrim.new(location),
390                     (place, span),
391                     Shallow(Some(ArtificialField::Discriminant)),
392                     JustWrite,
393                     flow_state,
394                 );
395             }
396             StatementKind::InlineAsm {
397                 ref asm,
398                 ref outputs,
399                 ref inputs,
400             } => {
401                 let context = ContextKind::InlineAsm.new(location);
402                 for (o, output) in asm.outputs.iter().zip(outputs) {
403                     if o.is_indirect {
404                         // FIXME(eddyb) indirect inline asm outputs should
405                         // be encoeded through MIR place derefs instead.
406                         self.access_place(
407                             context,
408                             (output, span),
409                             (Deep, Read(ReadKind::Copy)),
410                             LocalMutationIsAllowed::No,
411                             flow_state,
412                         );
413                         self.check_if_path_or_subpath_is_moved(
414                             context,
415                             InitializationRequiringAction::Use,
416                             (output, span),
417                             flow_state,
418                         );
419                     } else {
420                         self.mutate_place(
421                             context,
422                             (output, span),
423                             if o.is_rw { Deep } else { Shallow(None) },
424                             if o.is_rw { WriteAndRead } else { JustWrite },
425                             flow_state,
426                         );
427                     }
428                 }
429                 for input in inputs {
430                     self.consume_operand(context, (input, span), flow_state);
431                 }
432             }
433             StatementKind::EndRegion(ref _rgn) => {
434                 // ignored when consuming results (update to
435                 // flow_state already handled).
436             }
437             StatementKind::Nop |
438             StatementKind::UserAssertTy(..) |
439             StatementKind::Validate(..) |
440             StatementKind::StorageLive(..) => {
441                 // `Nop`, `UserAssertTy`, `Validate`, and `StorageLive` are irrelevant
442                 // to borrow check.
443             }
444             StatementKind::StorageDead(local) => {
445                 self.access_place(
446                     ContextKind::StorageDead.new(location),
447                     (&Place::Local(local), span),
448                     (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
449                     LocalMutationIsAllowed::Yes,
450                     flow_state,
451                 );
452             }
453         }
454     }
455
456     fn visit_terminator_entry(
457         &mut self,
458         location: Location,
459         term: &Terminator<'tcx>,
460         flow_state: &Self::FlowState,
461     ) {
462         let loc = location;
463         debug!(
464             "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
465             location, term, flow_state
466         );
467         let span = term.source_info.span;
468
469         self.check_activations(location, span, flow_state);
470
471         match term.kind {
472             TerminatorKind::SwitchInt {
473                 ref discr,
474                 switch_ty: _,
475                 values: _,
476                 targets: _,
477             } => {
478                 self.consume_operand(ContextKind::SwitchInt.new(loc), (discr, span), flow_state);
479             }
480             TerminatorKind::Drop {
481                 location: ref drop_place,
482                 target: _,
483                 unwind: _,
484             } => {
485                 let gcx = self.tcx.global_tcx();
486
487                 // Compute the type with accurate region information.
488                 let drop_place_ty = drop_place.ty(self.mir, self.tcx);
489
490                 // Erase the regions.
491                 let drop_place_ty = self.tcx.erase_regions(&drop_place_ty).to_ty(self.tcx);
492
493                 // "Lift" into the gcx -- once regions are erased, this type should be in the
494                 // global arenas; this "lift" operation basically just asserts that is true, but
495                 // that is useful later.
496                 let drop_place_ty = gcx.lift(&drop_place_ty).unwrap();
497
498                 self.visit_terminator_drop(loc, term, flow_state, drop_place, drop_place_ty, span);
499             }
500             TerminatorKind::DropAndReplace {
501                 location: ref drop_place,
502                 value: ref new_value,
503                 target: _,
504                 unwind: _,
505             } => {
506                 self.mutate_place(
507                     ContextKind::DropAndReplace.new(loc),
508                     (drop_place, span),
509                     Deep,
510                     JustWrite,
511                     flow_state,
512                 );
513                 self.consume_operand(
514                     ContextKind::DropAndReplace.new(loc),
515                     (new_value, span),
516                     flow_state,
517                 );
518             }
519             TerminatorKind::Call {
520                 ref func,
521                 ref args,
522                 ref destination,
523                 cleanup: _,
524             } => {
525                 self.consume_operand(ContextKind::CallOperator.new(loc), (func, span), flow_state);
526                 for arg in args {
527                     self.consume_operand(
528                         ContextKind::CallOperand.new(loc),
529                         (arg, span),
530                         flow_state,
531                     );
532                 }
533                 if let Some((ref dest, _ /*bb*/)) = *destination {
534                     self.mutate_place(
535                         ContextKind::CallDest.new(loc),
536                         (dest, span),
537                         Deep,
538                         JustWrite,
539                         flow_state,
540                     );
541                 }
542             }
543             TerminatorKind::Assert {
544                 ref cond,
545                 expected: _,
546                 ref msg,
547                 target: _,
548                 cleanup: _,
549             } => {
550                 self.consume_operand(ContextKind::Assert.new(loc), (cond, span), flow_state);
551                 match *msg {
552                     AssertMessage::BoundsCheck { ref len, ref index } => {
553                         self.consume_operand(ContextKind::Assert.new(loc), (len, span), flow_state);
554                         self.consume_operand(
555                             ContextKind::Assert.new(loc),
556                             (index, span),
557                             flow_state,
558                         );
559                     }
560                     AssertMessage::Math(_ /*const_math_err*/) => {}
561                     AssertMessage::GeneratorResumedAfterReturn => {}
562                     AssertMessage::GeneratorResumedAfterPanic => {}
563                 }
564             }
565
566             TerminatorKind::Yield {
567                 ref value,
568                 resume: _,
569                 drop: _,
570             } => {
571                 self.consume_operand(ContextKind::Yield.new(loc), (value, span), flow_state);
572
573                 if self.movable_generator {
574                     // Look for any active borrows to locals
575                     let borrow_set = self.borrow_set.clone();
576                     flow_state.with_outgoing_borrows(|borrows| {
577                         for i in borrows {
578                             let borrow = &borrow_set[i];
579                             self.check_for_local_borrow(borrow, span);
580                         }
581                     });
582                 }
583             }
584
585             TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
586                 // Returning from the function implicitly kills storage for all locals and statics.
587                 // Often, the storage will already have been killed by an explicit
588                 // StorageDead, but we don't always emit those (notably on unwind paths),
589                 // so this "extra check" serves as a kind of backup.
590                 let borrow_set = self.borrow_set.clone();
591                 flow_state.with_outgoing_borrows(|borrows| {
592                     for i in borrows {
593                         let borrow = &borrow_set[i];
594                         let context = ContextKind::StorageDead.new(loc);
595                         self.check_for_invalidation_at_exit(context, borrow, span);
596                     }
597                 });
598             }
599             TerminatorKind::Goto { target: _ }
600             | TerminatorKind::Abort
601             | TerminatorKind::Unreachable
602             | TerminatorKind::FalseEdges {
603                 real_target: _,
604                 imaginary_targets: _,
605             }
606             | TerminatorKind::FalseUnwind {
607                 real_target: _,
608                 unwind: _,
609             } => {
610                 // no data used, thus irrelevant to borrowck
611             }
612         }
613     }
614 }
615
616 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
617 enum MutateMode {
618     JustWrite,
619     WriteAndRead,
620 }
621
622 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
623 enum Control {
624     Continue,
625     Break,
626 }
627
628 use self::ShallowOrDeep::{Deep, Shallow};
629 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
630
631 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
632 enum ArtificialField {
633     Discriminant,
634     ArrayLength,
635 }
636
637 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
638 enum ShallowOrDeep {
639     /// From the RFC: "A *shallow* access means that the immediate
640     /// fields reached at P are accessed, but references or pointers
641     /// found within are not dereferenced. Right now, the only access
642     /// that is shallow is an assignment like `x = ...;`, which would
643     /// be a *shallow write* of `x`."
644     Shallow(Option<ArtificialField>),
645
646     /// From the RFC: "A *deep* access means that all data reachable
647     /// through the given place may be invalidated or accesses by
648     /// this action."
649     Deep,
650 }
651
652 /// Kind of access to a value: read or write
653 /// (For informational purposes only)
654 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
655 enum ReadOrWrite {
656     /// From the RFC: "A *read* means that the existing data may be
657     /// read, but will not be changed."
658     Read(ReadKind),
659
660     /// From the RFC: "A *write* means that the data may be mutated to
661     /// new values or otherwise invalidated (for example, it could be
662     /// de-initialized, as in a move operation).
663     Write(WriteKind),
664
665     /// For two-phase borrows, we distinguish a reservation (which is treated
666     /// like a Read) from an activation (which is treated like a write), and
667     /// each of those is furthermore distinguished from Reads/Writes above.
668     Reservation(WriteKind),
669     Activation(WriteKind, BorrowIndex),
670 }
671
672 /// Kind of read access to a value
673 /// (For informational purposes only)
674 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
675 enum ReadKind {
676     Borrow(BorrowKind),
677     Copy,
678 }
679
680 /// Kind of write access to a value
681 /// (For informational purposes only)
682 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
683 enum WriteKind {
684     StorageDeadOrDrop,
685     MutableBorrow(BorrowKind),
686     Mutate,
687     Move,
688 }
689
690 /// When checking permissions for a place access, this flag is used to indicate that an immutable
691 /// local place can be mutated.
692 ///
693 /// FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
694 /// - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`
695 /// - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
696 ///   `is_declared_mutable()`
697 /// - Take flow state into consideration in `is_assignable()` for local variables
698 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
699 enum LocalMutationIsAllowed {
700     Yes,
701     /// We want use of immutable upvars to cause a "write to immutable upvar"
702     /// error, not an "reassignment" error.
703     ExceptUpvars,
704     No,
705 }
706
707 struct AccessErrorsReported {
708     mutability_error: bool,
709     #[allow(dead_code)]
710     conflict_error: bool,
711 }
712
713 #[derive(Copy, Clone)]
714 enum InitializationRequiringAction {
715     Update,
716     Borrow,
717     Use,
718     Assignment,
719 }
720
721 impl InitializationRequiringAction {
722     fn as_noun(self) -> &'static str {
723         match self {
724             InitializationRequiringAction::Update => "update",
725             InitializationRequiringAction::Borrow => "borrow",
726             InitializationRequiringAction::Use => "use",
727             InitializationRequiringAction::Assignment => "assign",
728         }
729     }
730
731     fn as_verb_in_past_tense(self) -> &'static str {
732         match self {
733             InitializationRequiringAction::Update => "updated",
734             InitializationRequiringAction::Borrow => "borrowed",
735             InitializationRequiringAction::Use => "used",
736             InitializationRequiringAction::Assignment => "assigned",
737         }
738     }
739 }
740
741 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
742     /// Returns true if the borrow represented by `kind` is
743     /// allowed to be split into separate Reservation and
744     /// Activation phases.
745     fn allow_two_phase_borrow(&self, kind: BorrowKind) -> bool {
746         self.tcx.two_phase_borrows()
747             && (kind.allows_two_phase_borrow()
748                 || self.tcx.sess.opts.debugging_opts.two_phase_beyond_autoref)
749     }
750
751     /// Invokes `access_place` as appropriate for dropping the value
752     /// at `drop_place`. Note that the *actual* `Drop` in the MIR is
753     /// always for a variable (e.g., `Drop(x)`) -- but we recursively
754     /// break this variable down into subpaths (e.g., `Drop(x.foo)`)
755     /// to indicate more precisely which fields might actually be
756     /// accessed by a destructor.
757     fn visit_terminator_drop(
758         &mut self,
759         loc: Location,
760         term: &Terminator<'tcx>,
761         flow_state: &Flows<'cx, 'gcx, 'tcx>,
762         drop_place: &Place<'tcx>,
763         erased_drop_place_ty: ty::Ty<'gcx>,
764         span: Span,
765     ) {
766         let gcx = self.tcx.global_tcx();
767         let drop_field = |
768             mir: &mut MirBorrowckCtxt<'cx, 'gcx, 'tcx>,
769             (index, field): (usize, ty::Ty<'gcx>),
770         | {
771             let field_ty = gcx.normalize_erasing_regions(mir.param_env, field);
772             let place = drop_place.clone().field(Field::new(index), field_ty);
773
774             mir.visit_terminator_drop(loc, term, flow_state, &place, field_ty, span);
775         };
776
777         match erased_drop_place_ty.sty {
778             // When a struct is being dropped, we need to check
779             // whether it has a destructor, if it does, then we can
780             // call it, if it does not then we need to check the
781             // individual fields instead. This way if `foo` has a
782             // destructor but `bar` does not, we will only check for
783             // borrows of `x.foo` and not `x.bar`. See #47703.
784             ty::TyAdt(def, substs) if def.is_struct() && !def.has_dtor(self.tcx) => {
785                 def.all_fields()
786                     .map(|field| field.ty(gcx, substs))
787                     .enumerate()
788                     .for_each(|field| drop_field(self, field));
789             }
790             // Same as above, but for tuples.
791             ty::TyTuple(tys) => {
792                 tys.iter().cloned().enumerate()
793                     .for_each(|field| drop_field(self, field));
794             }
795             // Closures and generators also have disjoint fields, but they are only
796             // directly accessed in the body of the closure/generator.
797             ty::TyClosure(def, substs)
798             | ty::TyGenerator(def, substs, ..)
799                 if *drop_place == Place::Local(Local::new(1)) && !self.mir.upvar_decls.is_empty()
800             => {
801                 substs.upvar_tys(def, self.tcx).enumerate()
802                     .for_each(|field| drop_field(self, field));
803             }
804             _ => {
805                 // We have now refined the type of the value being
806                 // dropped (potentially) to just the type of a
807                 // subfield; so check whether that field's type still
808                 // "needs drop". If so, we assume that the destructor
809                 // may access any data it likes (i.e., a Deep Write).
810                 if erased_drop_place_ty.needs_drop(gcx, self.param_env) {
811                     self.access_place(
812                         ContextKind::Drop.new(loc),
813                         (drop_place, span),
814                         (Deep, Write(WriteKind::StorageDeadOrDrop)),
815                         LocalMutationIsAllowed::Yes,
816                         flow_state,
817                     );
818                 }
819             }
820         }
821     }
822
823     /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
824     /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
825     /// place is initialized and (b) it is not borrowed in some way that would prevent this
826     /// access.
827     ///
828     /// Returns true if an error is reported, false otherwise.
829     fn access_place(
830         &mut self,
831         context: Context,
832         place_span: (&Place<'tcx>, Span),
833         kind: (ShallowOrDeep, ReadOrWrite),
834         is_local_mutation_allowed: LocalMutationIsAllowed,
835         flow_state: &Flows<'cx, 'gcx, 'tcx>,
836     ) -> AccessErrorsReported {
837         let (sd, rw) = kind;
838
839         if let Activation(_, borrow_index) = rw {
840             if self.reservation_error_reported.contains(&place_span.0) {
841                 debug!(
842                     "skipping access_place for activation of invalid reservation \
843                      place: {:?} borrow_index: {:?}",
844                     place_span.0, borrow_index
845                 );
846                 return AccessErrorsReported {
847                     mutability_error: false,
848                     conflict_error: true,
849                 };
850             }
851         }
852
853         if self.access_place_error_reported
854             .contains(&(place_span.0.clone(), place_span.1))
855         {
856             debug!(
857                 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
858                 place_span, kind
859             );
860             return AccessErrorsReported {
861                 mutability_error: false,
862                 conflict_error: true,
863             };
864         }
865
866         let mutability_error =
867             self.check_access_permissions(place_span, rw, is_local_mutation_allowed);
868         let conflict_error =
869             self.check_access_for_conflict(context, place_span, sd, rw, flow_state);
870
871         if conflict_error || mutability_error {
872             debug!(
873                 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
874                 place_span, kind
875             );
876             self.access_place_error_reported
877                 .insert((place_span.0.clone(), place_span.1));
878         }
879
880         AccessErrorsReported {
881             mutability_error,
882             conflict_error,
883         }
884     }
885
886     fn check_access_for_conflict(
887         &mut self,
888         context: Context,
889         place_span: (&Place<'tcx>, Span),
890         sd: ShallowOrDeep,
891         rw: ReadOrWrite,
892         flow_state: &Flows<'cx, 'gcx, 'tcx>,
893     ) -> bool {
894         debug!(
895             "check_access_for_conflict(context={:?}, place_span={:?}, sd={:?}, rw={:?})",
896             context,
897             place_span,
898             sd,
899             rw,
900         );
901
902         let mut error_reported = false;
903         self.each_borrow_involving_path(
904             context,
905             (sd, place_span.0),
906             flow_state,
907             |this, borrow_index, borrow| match (rw, borrow.kind) {
908                 // Obviously an activation is compatible with its own
909                 // reservation (or even prior activating uses of same
910                 // borrow); so don't check if they interfere.
911                 //
912                 // NOTE: *reservations* do conflict with themselves;
913                 // thus aren't injecting unsoundenss w/ this check.)
914                 (Activation(_, activating), _) if activating == borrow_index => {
915                     debug!(
916                         "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
917                          skipping {:?} b/c activation of same borrow_index",
918                         place_span,
919                         sd,
920                         rw,
921                         (borrow_index, borrow),
922                     );
923                     Control::Continue
924                 }
925
926                 (Read(_), BorrowKind::Shared) | (Reservation(..), BorrowKind::Shared) => {
927                     Control::Continue
928                 }
929
930                 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
931                     // Reading from mere reservations of mutable-borrows is OK.
932                     if !this.is_active(borrow, context.loc) {
933                         assert!(this.allow_two_phase_borrow(borrow.kind));
934                         return Control::Continue;
935                     }
936
937                     match kind {
938                         ReadKind::Copy => {
939                             error_reported = true;
940                             this.report_use_while_mutably_borrowed(context, place_span, borrow)
941                         }
942                         ReadKind::Borrow(bk) => {
943                             error_reported = true;
944                             this.report_conflicting_borrow(
945                                 context,
946                                 place_span,
947                                 bk,
948                                 &borrow,
949                             )
950                         }
951                     }
952                     Control::Break
953                 }
954
955                 (Reservation(kind), BorrowKind::Unique)
956                 | (Reservation(kind), BorrowKind::Mut { .. })
957                 | (Activation(kind, _), _)
958                 | (Write(kind), _) => {
959                     match rw {
960                         Reservation(_) => {
961                             debug!(
962                                 "recording invalid reservation of \
963                                  place: {:?}",
964                                 place_span.0
965                             );
966                             this.reservation_error_reported.insert(place_span.0.clone());
967                         }
968                         Activation(_, activating) => {
969                             debug!(
970                                 "observing check_place for activation of \
971                                  borrow_index: {:?}",
972                                 activating
973                             );
974                         }
975                         Read(..) | Write(..) => {}
976                     }
977
978                     match kind {
979                         WriteKind::MutableBorrow(bk) => {
980                             error_reported = true;
981                             this.report_conflicting_borrow(
982                                 context,
983                                 place_span,
984                                 bk,
985                                 &borrow,
986                             )
987                         }
988                         WriteKind::StorageDeadOrDrop => {
989                             error_reported = true;
990                             this.report_borrowed_value_does_not_live_long_enough(
991                                 context,
992                                 borrow,
993                                 place_span.1,
994                             );
995                         }
996                         WriteKind::Mutate => {
997                             error_reported = true;
998                             this.report_illegal_mutation_of_borrowed(context, place_span, borrow)
999                         }
1000                         WriteKind::Move => {
1001                             error_reported = true;
1002                             this.report_move_out_while_borrowed(context, place_span, &borrow)
1003                         }
1004                     }
1005                     Control::Break
1006                 }
1007             },
1008         );
1009
1010         error_reported
1011     }
1012
1013     fn mutate_place(
1014         &mut self,
1015         context: Context,
1016         place_span: (&Place<'tcx>, Span),
1017         kind: ShallowOrDeep,
1018         mode: MutateMode,
1019         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1020     ) {
1021         // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1022         match mode {
1023             MutateMode::WriteAndRead => {
1024                 self.check_if_path_or_subpath_is_moved(
1025                     context,
1026                     InitializationRequiringAction::Update,
1027                     place_span,
1028                     flow_state,
1029                 );
1030             }
1031             MutateMode::JustWrite => {
1032                 self.check_if_assigned_path_is_moved(context, place_span, flow_state);
1033             }
1034         }
1035
1036         let errors_reported = self.access_place(
1037             context,
1038             place_span,
1039             (kind, Write(WriteKind::Mutate)),
1040             // We want immutable upvars to cause an "assignment to immutable var"
1041             // error, not an "reassignment of immutable var" error, because the
1042             // latter can't find a good previous assignment span.
1043             //
1044             // There's probably a better way to do this.
1045             LocalMutationIsAllowed::ExceptUpvars,
1046             flow_state,
1047         );
1048
1049         if !errors_reported.mutability_error {
1050             // check for reassignments to immutable local variables
1051             self.check_if_reassignment_to_immutable_state(context, place_span, flow_state);
1052         }
1053     }
1054
1055     fn consume_rvalue(
1056         &mut self,
1057         context: Context,
1058         (rvalue, span): (&Rvalue<'tcx>, Span),
1059         _location: Location,
1060         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1061     ) {
1062         match *rvalue {
1063             Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1064                 let access_kind = match bk {
1065                     BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1066                     BorrowKind::Unique | BorrowKind::Mut { .. } => {
1067                         let wk = WriteKind::MutableBorrow(bk);
1068                         if self.allow_two_phase_borrow(bk) {
1069                             (Deep, Reservation(wk))
1070                         } else {
1071                             (Deep, Write(wk))
1072                         }
1073                     }
1074                 };
1075
1076                 self.access_place(
1077                     context,
1078                     (place, span),
1079                     access_kind,
1080                     LocalMutationIsAllowed::No,
1081                     flow_state,
1082                 );
1083
1084                 self.check_if_path_or_subpath_is_moved(
1085                     context,
1086                     InitializationRequiringAction::Borrow,
1087                     (place, span),
1088                     flow_state,
1089                 );
1090             }
1091
1092             Rvalue::Use(ref operand)
1093             | Rvalue::Repeat(ref operand, _)
1094             | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1095             | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1096                 self.consume_operand(context, (operand, span), flow_state)
1097             }
1098
1099             Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1100                 let af = match *rvalue {
1101                     Rvalue::Len(..) => ArtificialField::ArrayLength,
1102                     Rvalue::Discriminant(..) => ArtificialField::Discriminant,
1103                     _ => unreachable!(),
1104                 };
1105                 self.access_place(
1106                     context,
1107                     (place, span),
1108                     (Shallow(Some(af)), Read(ReadKind::Copy)),
1109                     LocalMutationIsAllowed::No,
1110                     flow_state,
1111                 );
1112                 self.check_if_path_or_subpath_is_moved(
1113                     context,
1114                     InitializationRequiringAction::Use,
1115                     (place, span),
1116                     flow_state,
1117                 );
1118             }
1119
1120             Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1121             | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1122                 self.consume_operand(context, (operand1, span), flow_state);
1123                 self.consume_operand(context, (operand2, span), flow_state);
1124             }
1125
1126             Rvalue::NullaryOp(_op, _ty) => {
1127                 // nullary ops take no dynamic input; no borrowck effect.
1128                 //
1129                 // FIXME: is above actually true? Do we want to track
1130                 // the fact that uninitialized data can be created via
1131                 // `NullOp::Box`?
1132             }
1133
1134             Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1135                 // We need to report back the list of mutable upvars that were
1136                 // moved into the closure and subsequently used by the closure,
1137                 // in order to populate our used_mut set.
1138                 if let AggregateKind::Closure(def_id, _) = &**aggregate_kind {
1139                     let BorrowCheckResult { used_mut_upvars, .. } = self.tcx.mir_borrowck(*def_id);
1140                     for field in used_mut_upvars {
1141                         match operands[field.index()] {
1142                             Operand::Move(Place::Local(local)) => {
1143                                 self.used_mut.insert(local);
1144                             }
1145                             Operand::Move(Place::Projection(ref proj)) => {
1146                                 if let Some(field) = self.is_upvar_field_projection(&proj.base) {
1147                                     self.used_mut_upvars.push(field);
1148                                 }
1149                             }
1150                             Operand::Move(Place::Static(..)) |
1151                             Operand::Copy(..) |
1152                             Operand::Constant(..) => {}
1153                         }
1154                     }
1155                 }
1156
1157                 for operand in operands {
1158                     self.consume_operand(context, (operand, span), flow_state);
1159                 }
1160             }
1161         }
1162     }
1163
1164     fn consume_operand(
1165         &mut self,
1166         context: Context,
1167         (operand, span): (&Operand<'tcx>, Span),
1168         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1169     ) {
1170         match *operand {
1171             Operand::Copy(ref place) => {
1172                 // copy of place: check if this is "copy of frozen path"
1173                 // (FIXME: see check_loans.rs)
1174                 self.access_place(
1175                     context,
1176                     (place, span),
1177                     (Deep, Read(ReadKind::Copy)),
1178                     LocalMutationIsAllowed::No,
1179                     flow_state,
1180                 );
1181
1182                 // Finally, check if path was already moved.
1183                 self.check_if_path_or_subpath_is_moved(
1184                     context,
1185                     InitializationRequiringAction::Use,
1186                     (place, span),
1187                     flow_state,
1188                 );
1189             }
1190             Operand::Move(ref place) => {
1191                 // move of place: check if this is move of already borrowed path
1192                 self.access_place(
1193                     context,
1194                     (place, span),
1195                     (Deep, Write(WriteKind::Move)),
1196                     LocalMutationIsAllowed::Yes,
1197                     flow_state,
1198                 );
1199
1200                 // Finally, check if path was already moved.
1201                 self.check_if_path_or_subpath_is_moved(
1202                     context,
1203                     InitializationRequiringAction::Use,
1204                     (place, span),
1205                     flow_state,
1206                 );
1207             }
1208             Operand::Constant(_) => {}
1209         }
1210     }
1211
1212     /// Returns whether a borrow of this place is invalidated when the function
1213     /// exits
1214     fn check_for_invalidation_at_exit(
1215         &mut self,
1216         context: Context,
1217         borrow: &BorrowData<'tcx>,
1218         span: Span,
1219     ) {
1220         debug!("check_for_invalidation_at_exit({:?})", borrow);
1221         let place = &borrow.borrowed_place;
1222         let root_place = self.prefixes(place, PrefixSet::All).last().unwrap();
1223
1224         // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1225         // we just know that all locals are dropped at function exit (otherwise
1226         // we'll have a memory leak) and assume that all statics have a destructor.
1227         //
1228         // FIXME: allow thread-locals to borrow other thread locals?
1229         let (might_be_alive, will_be_dropped) = match root_place {
1230             Place::Static(statik) => {
1231                 // Thread-locals might be dropped after the function exits, but
1232                 // "true" statics will never be.
1233                 let is_thread_local = self.tcx
1234                     .get_attrs(statik.def_id)
1235                     .iter()
1236                     .any(|attr| attr.check_name("thread_local"));
1237
1238                 (true, is_thread_local)
1239             }
1240             Place::Local(_) => {
1241                 // Locals are always dropped at function exit, and if they
1242                 // have a destructor it would've been called already.
1243                 (false, self.locals_are_invalidated_at_exit)
1244             }
1245             Place::Projection(..) => {
1246                 bug!("root of {:?} is a projection ({:?})?", place, root_place)
1247             }
1248         };
1249
1250         if !will_be_dropped {
1251             debug!(
1252                 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1253                 place
1254             );
1255             return;
1256         }
1257
1258         // FIXME: replace this with a proper borrow_conflicts_with_place when
1259         // that is merged.
1260         let sd = if might_be_alive { Deep } else { Shallow(None) };
1261
1262         if self.places_conflict(place, root_place, sd) {
1263             debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1264             // FIXME: should be talking about the region lifetime instead
1265             // of just a span here.
1266             let span = self.tcx.sess.codemap().end_point(span);
1267             self.report_borrowed_value_does_not_live_long_enough(
1268                 context,
1269                 borrow,
1270                 span,
1271             )
1272         }
1273     }
1274
1275     /// Reports an error if this is a borrow of local data.
1276     /// This is called for all Yield statements on movable generators
1277     fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1278         fn borrow_of_local_data<'tcx>(place: &Place<'tcx>) -> bool {
1279             match place {
1280                 Place::Static(..) => false,
1281                 Place::Local(..) => true,
1282                 Place::Projection(box proj) => {
1283                     match proj.elem {
1284                         // Reborrow of already borrowed data is ignored
1285                         // Any errors will be caught on the initial borrow
1286                         ProjectionElem::Deref => false,
1287
1288                         // For interior references and downcasts, find out if the base is local
1289                         ProjectionElem::Field(..)
1290                         | ProjectionElem::Index(..)
1291                         | ProjectionElem::ConstantIndex { .. }
1292                         | ProjectionElem::Subslice { .. }
1293                         | ProjectionElem::Downcast(..) => borrow_of_local_data(&proj.base),
1294                     }
1295                 }
1296             }
1297         }
1298
1299         debug!("check_for_local_borrow({:?})", borrow);
1300
1301         if borrow_of_local_data(&borrow.borrowed_place) {
1302             self.tcx
1303                 .cannot_borrow_across_generator_yield(
1304                     self.retrieve_borrow_span(borrow),
1305                     yield_span,
1306                     Origin::Mir,
1307                 )
1308                 .emit();
1309         }
1310     }
1311
1312     fn check_activations(
1313         &mut self,
1314         location: Location,
1315         span: Span,
1316         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1317     ) {
1318         if !self.tcx.two_phase_borrows() {
1319             return;
1320         }
1321
1322         // Two-phase borrow support: For each activation that is newly
1323         // generated at this statement, check if it interferes with
1324         // another borrow.
1325         let borrow_set = self.borrow_set.clone();
1326         for &borrow_index in borrow_set.activations_at_location(location) {
1327             let borrow = &borrow_set[borrow_index];
1328
1329             // only mutable borrows should be 2-phase
1330             assert!(match borrow.kind {
1331                 BorrowKind::Shared => false,
1332                 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1333             });
1334
1335             self.access_place(
1336                 ContextKind::Activation.new(location),
1337                 (&borrow.borrowed_place, span),
1338                 (
1339                     Deep,
1340                     Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1341                 ),
1342                 LocalMutationIsAllowed::No,
1343                 flow_state,
1344             );
1345             // We do not need to call `check_if_path_or_subpath_is_moved`
1346             // again, as we already called it when we made the
1347             // initial reservation.
1348         }
1349     }
1350 }
1351
1352 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1353     fn check_if_reassignment_to_immutable_state(
1354         &mut self,
1355         context: Context,
1356         (place, span): (&Place<'tcx>, Span),
1357         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1358     ) {
1359         debug!("check_if_reassignment_to_immutable_state({:?})", place);
1360         // determine if this path has a non-mut owner (and thus needs checking).
1361         if let Ok(()) = self.is_mutable(place, LocalMutationIsAllowed::No) {
1362             return;
1363         }
1364         debug!(
1365             "check_if_reassignment_to_immutable_state({:?}) - is an imm local",
1366             place
1367         );
1368
1369         for i in flow_state.ever_inits.iter_incoming() {
1370             let init = self.move_data.inits[i];
1371             let init_place = &self.move_data.move_paths[init.path].place;
1372             if self.places_conflict(&init_place, place, Deep) {
1373                 self.report_illegal_reassignment(context, (place, span), init.span);
1374                 break;
1375             }
1376         }
1377     }
1378
1379     fn check_if_full_path_is_moved(
1380         &mut self,
1381         context: Context,
1382         desired_action: InitializationRequiringAction,
1383         place_span: (&Place<'tcx>, Span),
1384         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1385     ) {
1386         // FIXME: analogous code in check_loans first maps `place` to
1387         // its base_path ... but is that what we want here?
1388         let place = self.base_path(place_span.0);
1389
1390         let maybe_uninits = &flow_state.uninits;
1391         let curr_move_outs = &flow_state.move_outs;
1392
1393         // Bad scenarios:
1394         //
1395         // 1. Move of `a.b.c`, use of `a.b.c`
1396         // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1397         // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1398         //    partial initialization support, one might have `a.x`
1399         //    initialized but not `a.b`.
1400         //
1401         // OK scenarios:
1402         //
1403         // 4. Move of `a.b.c`, use of `a.b.d`
1404         // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1405         // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1406         //    must have been initialized for the use to be sound.
1407         // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1408
1409         // The dataflow tracks shallow prefixes distinctly (that is,
1410         // field-accesses on P distinctly from P itself), in order to
1411         // track substructure initialization separately from the whole
1412         // structure.
1413         //
1414         // E.g., when looking at (*a.b.c).d, if the closest prefix for
1415         // which we have a MovePath is `a.b`, then that means that the
1416         // initialization state of `a.b` is all we need to inspect to
1417         // know if `a.b.c` is valid (and from that we infer that the
1418         // dereference and `.d` access is also valid, since we assume
1419         // `a.b.c` is assigned a reference to a initialized and
1420         // well-formed record structure.)
1421
1422         // Therefore, if we seek out the *closest* prefix for which we
1423         // have a MovePath, that should capture the initialization
1424         // state for the place scenario.
1425         //
1426         // This code covers scenarios 1, 2, and 3.
1427
1428         debug!("check_if_full_path_is_moved place: {:?}", place);
1429         match self.move_path_closest_to(place) {
1430             Ok(mpi) => {
1431                 if maybe_uninits.contains(&mpi) {
1432                     self.report_use_of_moved_or_uninitialized(
1433                         context,
1434                         desired_action,
1435                         place_span,
1436                         mpi,
1437                         curr_move_outs,
1438                     );
1439                     return; // don't bother finding other problems.
1440                 }
1441             }
1442             Err(NoMovePathFound::ReachedStatic) => {
1443                 // Okay: we do not build MoveData for static variables
1444             } // Only query longest prefix with a MovePath, not further
1445               // ancestors; dataflow recurs on children when parents
1446               // move (to support partial (re)inits).
1447               //
1448               // (I.e. querying parents breaks scenario 7; but may want
1449               // to do such a query based on partial-init feature-gate.)
1450         }
1451     }
1452
1453     fn check_if_path_or_subpath_is_moved(
1454         &mut self,
1455         context: Context,
1456         desired_action: InitializationRequiringAction,
1457         place_span: (&Place<'tcx>, Span),
1458         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1459     ) {
1460         // FIXME: analogous code in check_loans first maps `place` to
1461         // its base_path ... but is that what we want here?
1462         let place = self.base_path(place_span.0);
1463
1464         let maybe_uninits = &flow_state.uninits;
1465         let curr_move_outs = &flow_state.move_outs;
1466
1467         // Bad scenarios:
1468         //
1469         // 1. Move of `a.b.c`, use of `a` or `a.b`
1470         //    partial initialization support, one might have `a.x`
1471         //    initialized but not `a.b`.
1472         // 2. All bad scenarios from `check_if_full_path_is_moved`
1473         //
1474         // OK scenarios:
1475         //
1476         // 3. Move of `a.b.c`, use of `a.b.d`
1477         // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1478         // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1479         //    must have been initialized for the use to be sound.
1480         // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1481
1482         self.check_if_full_path_is_moved(context, desired_action, place_span, flow_state);
1483
1484         // A move of any shallow suffix of `place` also interferes
1485         // with an attempt to use `place`. This is scenario 3 above.
1486         //
1487         // (Distinct from handling of scenarios 1+2+4 above because
1488         // `place` does not interfere with suffixes of its prefixes,
1489         // e.g. `a.b.c` does not interfere with `a.b.d`)
1490         //
1491         // This code covers scenario 1.
1492
1493         debug!("check_if_path_or_subpath_is_moved place: {:?}", place);
1494         if let Some(mpi) = self.move_path_for_place(place) {
1495             if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1496                 self.report_use_of_moved_or_uninitialized(
1497                     context,
1498                     desired_action,
1499                     place_span,
1500                     child_mpi,
1501                     curr_move_outs,
1502                 );
1503                 return; // don't bother finding other problems.
1504             }
1505         }
1506     }
1507
1508     /// Currently MoveData does not store entries for all places in
1509     /// the input MIR. For example it will currently filter out
1510     /// places that are Copy; thus we do not track places of shared
1511     /// reference type. This routine will walk up a place along its
1512     /// prefixes, searching for a foundational place that *is*
1513     /// tracked in the MoveData.
1514     ///
1515     /// An Err result includes a tag indicated why the search failed.
1516     /// Currently this can only occur if the place is built off of a
1517     /// static variable, as we do not track those in the MoveData.
1518     fn move_path_closest_to(
1519         &mut self,
1520         place: &Place<'tcx>,
1521     ) -> Result<MovePathIndex, NoMovePathFound> {
1522         let mut last_prefix = place;
1523         for prefix in self.prefixes(place, PrefixSet::All) {
1524             if let Some(mpi) = self.move_path_for_place(prefix) {
1525                 return Ok(mpi);
1526             }
1527             last_prefix = prefix;
1528         }
1529         match *last_prefix {
1530             Place::Local(_) => panic!("should have move path for every Local"),
1531             Place::Projection(_) => panic!("PrefixSet::All meant don't stop for Projection"),
1532             Place::Static(_) => return Err(NoMovePathFound::ReachedStatic),
1533         }
1534     }
1535
1536     fn move_path_for_place(&mut self, place: &Place<'tcx>) -> Option<MovePathIndex> {
1537         // If returns None, then there is no move path corresponding
1538         // to a direct owner of `place` (which means there is nothing
1539         // that borrowck tracks for its analysis).
1540
1541         match self.move_data.rev_lookup.find(place) {
1542             LookupResult::Parent(_) => None,
1543             LookupResult::Exact(mpi) => Some(mpi),
1544         }
1545     }
1546
1547     fn check_if_assigned_path_is_moved(
1548         &mut self,
1549         context: Context,
1550         (place, span): (&Place<'tcx>, Span),
1551         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1552     ) {
1553         debug!("check_if_assigned_path_is_moved place: {:?}", place);
1554         // recur down place; dispatch to external checks when necessary
1555         let mut place = place;
1556         loop {
1557             match *place {
1558                 Place::Local(_) | Place::Static(_) => {
1559                     // assigning to `x` does not require `x` be initialized.
1560                     break;
1561                 }
1562                 Place::Projection(ref proj) => {
1563                     let Projection { ref base, ref elem } = **proj;
1564                     match *elem {
1565                         ProjectionElem::Index(_/*operand*/) |
1566                         ProjectionElem::ConstantIndex { .. } |
1567                         // assigning to P[i] requires P to be valid.
1568                         ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1569                         // assigning to (P->variant) is okay if assigning to `P` is okay
1570                         //
1571                         // FIXME: is this true even if P is a adt with a dtor?
1572                         { }
1573
1574                         // assigning to (*P) requires P to be initialized
1575                         ProjectionElem::Deref => {
1576                             self.check_if_full_path_is_moved(
1577                                 context, InitializationRequiringAction::Use,
1578                                 (base, span), flow_state);
1579                             // (base initialized; no need to
1580                             // recur further)
1581                             break;
1582                         }
1583
1584                         ProjectionElem::Subslice { .. } => {
1585                             panic!("we don't allow assignments to subslices, context: {:?}",
1586                                    context);
1587                         }
1588
1589                         ProjectionElem::Field(..) => {
1590                             // if type of `P` has a dtor, then
1591                             // assigning to `P.f` requires `P` itself
1592                             // be already initialized
1593                             let tcx = self.tcx;
1594                             match base.ty(self.mir, tcx).to_ty(tcx).sty {
1595                                 ty::TyAdt(def, _) if def.has_dtor(tcx) => {
1596
1597                                     // FIXME: analogous code in
1598                                     // check_loans.rs first maps
1599                                     // `base` to its base_path.
1600
1601                                     self.check_if_path_or_subpath_is_moved(
1602                                         context, InitializationRequiringAction::Assignment,
1603                                         (base, span), flow_state);
1604
1605                                     // (base initialized; no need to
1606                                     // recur further)
1607                                     break;
1608                                 }
1609                                 _ => {}
1610                             }
1611                         }
1612                     }
1613
1614                     place = base;
1615                     continue;
1616                 }
1617             }
1618         }
1619     }
1620
1621     fn specialized_description(&self, place:&Place<'tcx>) -> Option<String>{
1622         if let Some(_name) = self.describe_place(place) {
1623             Some(format!("data in a `&` reference"))
1624         } else {
1625             None
1626         }
1627     }
1628
1629     fn get_default_err_msg(&self, place:&Place<'tcx>) -> String{
1630         match self.describe_place(place) {
1631             Some(name) => format!("immutable item `{}`", name),
1632             None => "immutable item".to_owned(),
1633         }
1634     }
1635
1636     fn get_secondary_err_msg(&self, place:&Place<'tcx>) -> String{
1637         match self.specialized_description(place) {
1638             Some(_) => format!("data in a `&` reference"),
1639             None => self.get_default_err_msg(place)
1640         }
1641     }
1642
1643     fn get_primary_err_msg(&self, place:&Place<'tcx>) -> String{
1644         if let Some(name) = self.describe_place(place) {
1645             format!("`{}` is a `&` reference, so the data it refers to cannot be written", name)
1646         } else {
1647             format!("cannot assign through `&`-reference")
1648         }
1649     }
1650
1651     /// Check the permissions for the given place and read or write kind
1652     ///
1653     /// Returns true if an error is reported, false otherwise.
1654     fn check_access_permissions(
1655         &mut self,
1656         (place, span): (&Place<'tcx>, Span),
1657         kind: ReadOrWrite,
1658         is_local_mutation_allowed: LocalMutationIsAllowed,
1659     ) -> bool {
1660         debug!(
1661             "check_access_permissions({:?}, {:?}, {:?})",
1662             place, kind, is_local_mutation_allowed
1663         );
1664         let mut error_reported = false;
1665         match kind {
1666             Reservation(WriteKind::MutableBorrow(BorrowKind::Unique))
1667             | Write(WriteKind::MutableBorrow(BorrowKind::Unique)) => {
1668                 if let Err(_place_err) = self.is_mutable(place, LocalMutationIsAllowed::Yes) {
1669                     span_bug!(span, "&unique borrow for {:?} should not fail", place);
1670                 }
1671             }
1672             Reservation(WriteKind::MutableBorrow(BorrowKind::Mut { .. }))
1673             | Write(WriteKind::MutableBorrow(BorrowKind::Mut { .. })) => if let Err(place_err) =
1674                 self.is_mutable(place, is_local_mutation_allowed)
1675             {
1676                 error_reported = true;
1677                 let item_msg = self.get_default_err_msg(place);
1678                 let mut err = self.tcx
1679                     .cannot_borrow_path_as_mutable(span, &item_msg, Origin::Mir);
1680                 err.span_label(span, "cannot borrow as mutable");
1681
1682                 if place != place_err {
1683                     if let Some(name) = self.describe_place(place_err) {
1684                         err.note(&format!("the value which is causing this path not to be mutable \
1685                                            is...: `{}`", name));
1686                     }
1687                 }
1688
1689                 err.emit();
1690             },
1691             Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1692                 match place {
1693                     Place::Local(local) => {
1694                         self.used_mut.insert(*local);
1695                     }
1696                     Place::Projection(ref proj) => {
1697                         if let Some(field) = self.is_upvar_field_projection(&proj.base) {
1698                             self.used_mut_upvars.push(field);
1699                         }
1700                     }
1701                     Place::Static(..) => {}
1702                 }
1703                 if let Err(place_err) = self.is_mutable(place, is_local_mutation_allowed) {
1704                     error_reported = true;
1705                     let mut err_info = None;
1706                     match *place_err {
1707
1708                         Place::Projection(box Projection {
1709                         ref base, elem:ProjectionElem::Deref}) => {
1710                             match *base {
1711                                 Place::Local(local) => {
1712                                     let locations = self.mir.find_assignments(local);
1713                                         if locations.len() > 0 {
1714                                             let item_msg = if error_reported {
1715                                                 self.get_secondary_err_msg(base)
1716                                             } else {
1717                                                 self.get_default_err_msg(place)
1718                                             };
1719                                             let sp = self.mir.source_info(locations[0]).span;
1720                                             let mut to_suggest_span = String::new();
1721                                             if let Ok(src) =
1722                                                 self.tcx.sess.codemap().span_to_snippet(sp) {
1723                                                     to_suggest_span = src[1..].to_string();
1724                                             };
1725                                             err_info = Some((
1726                                                     sp,
1727                                                     "consider changing this to be a \
1728                                                     mutable reference",
1729                                                     to_suggest_span,
1730                                                     item_msg,
1731                                                     self.get_primary_err_msg(base)));
1732                                         }
1733                                 },
1734                             _ => {},
1735                             }
1736                         },
1737                         _ => {},
1738                     }
1739
1740                     if let Some((err_help_span,
1741                                  err_help_stmt,
1742                                  to_suggest_span,
1743                                  item_msg,
1744                                  sec_span)) = err_info {
1745                         let mut err = self.tcx.cannot_assign(span, &item_msg, Origin::Mir);
1746                         err.span_suggestion(err_help_span,
1747                                             err_help_stmt,
1748                                             format!("&mut {}", to_suggest_span));
1749                         if place != place_err {
1750                             err.span_label(span, sec_span);
1751                         }
1752                         err.emit()
1753                     } else {
1754                         let item_msg_ = self.get_default_err_msg(place);
1755                         let mut err = self.tcx.cannot_assign(span, &item_msg_, Origin::Mir);
1756                         err.span_label(span, "cannot mutate");
1757                         if place != place_err {
1758                             if let Some(name) = self.describe_place(place_err) {
1759                                 err.note(&format!("the value which is causing this path not to be \
1760                                                    mutable is...: `{}`", name));
1761                             }
1762                         }
1763                         err.emit();
1764                     }
1765                 }
1766             }
1767             Reservation(WriteKind::Move)
1768             | Reservation(WriteKind::StorageDeadOrDrop)
1769             | Reservation(WriteKind::MutableBorrow(BorrowKind::Shared))
1770             | Write(WriteKind::Move)
1771             | Write(WriteKind::StorageDeadOrDrop)
1772             | Write(WriteKind::MutableBorrow(BorrowKind::Shared)) => {
1773                 if let Err(_place_err) = self.is_mutable(place, is_local_mutation_allowed) {
1774                     self.tcx.sess.delay_span_bug(
1775                         span,
1776                         &format!(
1777                             "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
1778                             place, kind
1779                         ),
1780                     );
1781                 }
1782             }
1783             Activation(..) => {} // permission checks are done at Reservation point.
1784             Read(ReadKind::Borrow(BorrowKind::Unique))
1785             | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
1786             | Read(ReadKind::Borrow(BorrowKind::Shared))
1787             | Read(ReadKind::Copy) => {} // Access authorized
1788         }
1789
1790         error_reported
1791     }
1792
1793     /// Can this value be written or borrowed mutably
1794     fn is_mutable<'d>(
1795         &self,
1796         place: &'d Place<'tcx>,
1797         is_local_mutation_allowed: LocalMutationIsAllowed,
1798     ) -> Result<(), &'d Place<'tcx>> {
1799         match *place {
1800             Place::Local(local) => {
1801                 let local = &self.mir.local_decls[local];
1802                 match local.mutability {
1803                     Mutability::Not => match is_local_mutation_allowed {
1804                         LocalMutationIsAllowed::Yes | LocalMutationIsAllowed::ExceptUpvars => {
1805                             Ok(())
1806                         }
1807                         LocalMutationIsAllowed::No => Err(place),
1808                     },
1809                     Mutability::Mut => Ok(()),
1810                 }
1811             }
1812             Place::Static(ref static_) =>
1813                 if self.tcx.is_static(static_.def_id) != Some(hir::Mutability::MutMutable) {
1814                     Err(place)
1815                 } else {
1816                     Ok(())
1817                 },
1818             Place::Projection(ref proj) => {
1819                 match proj.elem {
1820                     ProjectionElem::Deref => {
1821                         let base_ty = proj.base.ty(self.mir, self.tcx).to_ty(self.tcx);
1822
1823                         // Check the kind of deref to decide
1824                         match base_ty.sty {
1825                             ty::TyRef(_, tnm) => {
1826                                 match tnm.mutbl {
1827                                     // Shared borrowed data is never mutable
1828                                     hir::MutImmutable => Err(place),
1829                                     // Mutably borrowed data is mutable, but only if we have a
1830                                     // unique path to the `&mut`
1831                                     hir::MutMutable => {
1832                                         let mode = match self.is_upvar_field_projection(&proj.base)
1833                                         {
1834                                             Some(field)
1835                                                 if {
1836                                                     self.mir.upvar_decls[field.index()].by_ref
1837                                                 } =>
1838                                             {
1839                                                 is_local_mutation_allowed
1840                                             }
1841                                             _ => LocalMutationIsAllowed::Yes,
1842                                         };
1843
1844                                         self.is_mutable(&proj.base, mode)
1845                                     }
1846                                 }
1847                             }
1848                             ty::TyRawPtr(tnm) => {
1849                                 match tnm.mutbl {
1850                                     // `*const` raw pointers are not mutable
1851                                     hir::MutImmutable => return Err(place),
1852                                     // `*mut` raw pointers are always mutable, regardless of context
1853                                     // The users have to check by themselve.
1854                                     hir::MutMutable => return Ok(()),
1855                                 }
1856                             }
1857                             // `Box<T>` owns its content, so mutable if its location is mutable
1858                             _ if base_ty.is_box() => {
1859                                 self.is_mutable(&proj.base, is_local_mutation_allowed)
1860                             }
1861                             // Deref should only be for reference, pointers or boxes
1862                             _ => bug!("Deref of unexpected type: {:?}", base_ty),
1863                         }
1864                     }
1865                     // All other projections are owned by their base path, so mutable if
1866                     // base path is mutable
1867                     ProjectionElem::Field(..)
1868                     | ProjectionElem::Index(..)
1869                     | ProjectionElem::ConstantIndex { .. }
1870                     | ProjectionElem::Subslice { .. }
1871                     | ProjectionElem::Downcast(..) => {
1872                         if let Some(field) = self.is_upvar_field_projection(place) {
1873                             let decl = &self.mir.upvar_decls[field.index()];
1874                             debug!(
1875                                 "decl.mutability={:?} local_mutation_is_allowed={:?} place={:?}",
1876                                 decl, is_local_mutation_allowed, place
1877                             );
1878                             match (decl.mutability, is_local_mutation_allowed) {
1879                                 (Mutability::Not, LocalMutationIsAllowed::No)
1880                                 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
1881                                     Err(place)
1882                                 }
1883                                 (Mutability::Not, LocalMutationIsAllowed::Yes)
1884                                 | (Mutability::Mut, _) => {
1885                                     self.is_mutable(&proj.base, is_local_mutation_allowed)
1886                                 }
1887                             }
1888                         } else {
1889                             self.is_mutable(&proj.base, is_local_mutation_allowed)
1890                         }
1891                     }
1892                 }
1893             }
1894         }
1895     }
1896
1897     /// If this is a field projection, and the field is being projected from a closure type,
1898     /// then returns the index of the field being projected. Note that this closure will always
1899     /// be `self` in the current MIR, because that is the only time we directly access the fields
1900     /// of a closure type.
1901     fn is_upvar_field_projection(&self, place: &Place<'tcx>) -> Option<Field> {
1902         match *place {
1903             Place::Projection(ref proj) => match proj.elem {
1904                 ProjectionElem::Field(field, _ty) => {
1905                     let is_projection_from_ty_closure = proj.base
1906                         .ty(self.mir, self.tcx)
1907                         .to_ty(self.tcx)
1908                         .is_closure();
1909
1910                     if is_projection_from_ty_closure {
1911                         Some(field)
1912                     } else {
1913                         None
1914                     }
1915                 }
1916                 _ => None,
1917             },
1918             _ => None,
1919         }
1920     }
1921 }
1922
1923 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1924 enum NoMovePathFound {
1925     ReachedStatic,
1926 }
1927
1928 /// The degree of overlap between 2 places for borrow-checking.
1929 enum Overlap {
1930     /// The places might partially overlap - in this case, we give
1931     /// up and say that they might conflict. This occurs when
1932     /// different fields of a union are borrowed. For example,
1933     /// if `u` is a union, we have no way of telling how disjoint
1934     /// `u.a.x` and `a.b.y` are.
1935     Arbitrary,
1936     /// The places have the same type, and are either completely disjoint
1937     /// or equal - i.e. they can't "partially" overlap as can occur with
1938     /// unions. This is the "base case" on which we recur for extensions
1939     /// of the place.
1940     EqualOrDisjoint,
1941     /// The places are disjoint, so we know all extensions of them
1942     /// will also be disjoint.
1943     Disjoint,
1944 }
1945
1946 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1947     // Given that the bases of `elem1` and `elem2` are always either equal
1948     // or disjoint (and have the same type!), return the overlap situation
1949     // between `elem1` and `elem2`.
1950     fn place_element_conflict(&self, elem1: &Place<'tcx>, elem2: &Place<'tcx>) -> Overlap {
1951         match (elem1, elem2) {
1952             (Place::Local(l1), Place::Local(l2)) => {
1953                 if l1 == l2 {
1954                     // the same local - base case, equal
1955                     debug!("place_element_conflict: DISJOINT-OR-EQ-LOCAL");
1956                     Overlap::EqualOrDisjoint
1957                 } else {
1958                     // different locals - base case, disjoint
1959                     debug!("place_element_conflict: DISJOINT-LOCAL");
1960                     Overlap::Disjoint
1961                 }
1962             }
1963             (Place::Static(static1), Place::Static(static2)) => {
1964                 if static1.def_id != static2.def_id {
1965                     debug!("place_element_conflict: DISJOINT-STATIC");
1966                     Overlap::Disjoint
1967                 } else if self.tcx.is_static(static1.def_id) == Some(hir::Mutability::MutMutable) {
1968                     // We ignore mutable statics - they can only be unsafe code.
1969                     debug!("place_element_conflict: IGNORE-STATIC-MUT");
1970                     Overlap::Disjoint
1971                 } else {
1972                     debug!("place_element_conflict: DISJOINT-OR-EQ-STATIC");
1973                     Overlap::EqualOrDisjoint
1974                 }
1975             }
1976             (Place::Local(_), Place::Static(_)) | (Place::Static(_), Place::Local(_)) => {
1977                 debug!("place_element_conflict: DISJOINT-STATIC-LOCAL");
1978                 Overlap::Disjoint
1979             }
1980             (Place::Projection(pi1), Place::Projection(pi2)) => {
1981                 match (&pi1.elem, &pi2.elem) {
1982                     (ProjectionElem::Deref, ProjectionElem::Deref) => {
1983                         // derefs (e.g. `*x` vs. `*x`) - recur.
1984                         debug!("place_element_conflict: DISJOINT-OR-EQ-DEREF");
1985                         Overlap::EqualOrDisjoint
1986                     }
1987                     (ProjectionElem::Field(f1, _), ProjectionElem::Field(f2, _)) => {
1988                         if f1 == f2 {
1989                             // same field (e.g. `a.y` vs. `a.y`) - recur.
1990                             debug!("place_element_conflict: DISJOINT-OR-EQ-FIELD");
1991                             Overlap::EqualOrDisjoint
1992                         } else {
1993                             let ty = pi1.base.ty(self.mir, self.tcx).to_ty(self.tcx);
1994                             match ty.sty {
1995                                 ty::TyAdt(def, _) if def.is_union() => {
1996                                     // Different fields of a union, we are basically stuck.
1997                                     debug!("place_element_conflict: STUCK-UNION");
1998                                     Overlap::Arbitrary
1999                                 }
2000                                 _ => {
2001                                     // Different fields of a struct (`a.x` vs. `a.y`). Disjoint!
2002                                     debug!("place_element_conflict: DISJOINT-FIELD");
2003                                     Overlap::Disjoint
2004                                 }
2005                             }
2006                         }
2007                     }
2008                     (ProjectionElem::Downcast(_, v1), ProjectionElem::Downcast(_, v2)) => {
2009                         // different variants are treated as having disjoint fields,
2010                         // even if they occupy the same "space", because it's
2011                         // impossible for 2 variants of the same enum to exist
2012                         // (and therefore, to be borrowed) at the same time.
2013                         //
2014                         // Note that this is different from unions - we *do* allow
2015                         // this code to compile:
2016                         //
2017                         // ```
2018                         // fn foo(x: &mut Result<i32, i32>) {
2019                         //     let mut v = None;
2020                         //     if let Ok(ref mut a) = *x {
2021                         //         v = Some(a);
2022                         //     }
2023                         //     // here, you would *think* that the
2024                         //     // *entirety* of `x` would be borrowed,
2025                         //     // but in fact only the `Ok` variant is,
2026                         //     // so the `Err` variant is *entirely free*:
2027                         //     if let Err(ref mut a) = *x {
2028                         //         v = Some(a);
2029                         //     }
2030                         //     drop(v);
2031                         // }
2032                         // ```
2033                         if v1 == v2 {
2034                             debug!("place_element_conflict: DISJOINT-OR-EQ-FIELD");
2035                             Overlap::EqualOrDisjoint
2036                         } else {
2037                             debug!("place_element_conflict: DISJOINT-FIELD");
2038                             Overlap::Disjoint
2039                         }
2040                     }
2041                     (ProjectionElem::Index(..), ProjectionElem::Index(..))
2042                     | (ProjectionElem::Index(..), ProjectionElem::ConstantIndex { .. })
2043                     | (ProjectionElem::Index(..), ProjectionElem::Subslice { .. })
2044                     | (ProjectionElem::ConstantIndex { .. }, ProjectionElem::Index(..))
2045                     | (
2046                         ProjectionElem::ConstantIndex { .. },
2047                         ProjectionElem::ConstantIndex { .. },
2048                     )
2049                     | (ProjectionElem::ConstantIndex { .. }, ProjectionElem::Subslice { .. })
2050                     | (ProjectionElem::Subslice { .. }, ProjectionElem::Index(..))
2051                     | (ProjectionElem::Subslice { .. }, ProjectionElem::ConstantIndex { .. })
2052                     | (ProjectionElem::Subslice { .. }, ProjectionElem::Subslice { .. }) => {
2053                         // Array indexes (`a[0]` vs. `a[i]`). These can either be disjoint
2054                         // (if the indexes differ) or equal (if they are the same), so this
2055                         // is the recursive case that gives "equal *or* disjoint" its meaning.
2056                         //
2057                         // Note that by construction, MIR at borrowck can't subdivide
2058                         // `Subslice` accesses (e.g. `a[2..3][i]` will never be present) - they
2059                         // are only present in slice patterns, and we "merge together" nested
2060                         // slice patterns. That means we don't have to think about these. It's
2061                         // probably a good idea to assert this somewhere, but I'm too lazy.
2062                         //
2063                         // FIXME(#8636) we might want to return Disjoint if
2064                         // both projections are constant and disjoint.
2065                         debug!("place_element_conflict: DISJOINT-OR-EQ-ARRAY");
2066                         Overlap::EqualOrDisjoint
2067                     }
2068
2069                     (ProjectionElem::Deref, _)
2070                     | (ProjectionElem::Field(..), _)
2071                     | (ProjectionElem::Index(..), _)
2072                     | (ProjectionElem::ConstantIndex { .. }, _)
2073                     | (ProjectionElem::Subslice { .. }, _)
2074                     | (ProjectionElem::Downcast(..), _) => bug!(
2075                         "mismatched projections in place_element_conflict: {:?} and {:?}",
2076                         elem1,
2077                         elem2
2078                     ),
2079                 }
2080             }
2081             (Place::Projection(_), _) | (_, Place::Projection(_)) => bug!(
2082                 "unexpected elements in place_element_conflict: {:?} and {:?}",
2083                 elem1,
2084                 elem2
2085             ),
2086         }
2087     }
2088
2089     /// Returns whether an access of kind `access` to `access_place` conflicts with
2090     /// a borrow/full access to `borrow_place` (for deep accesses to mutable
2091     /// locations, this function is symmetric between `borrow_place` & `access_place`).
2092     fn places_conflict(
2093         &mut self,
2094         borrow_place: &Place<'tcx>,
2095         access_place: &Place<'tcx>,
2096         access: ShallowOrDeep,
2097     ) -> bool {
2098         debug!(
2099             "places_conflict({:?},{:?},{:?})",
2100             borrow_place, access_place, access
2101         );
2102
2103         // Return all the prefixes of `place` in reverse order, including
2104         // downcasts.
2105         fn place_elements<'a, 'tcx>(place: &'a Place<'tcx>) -> Vec<&'a Place<'tcx>> {
2106             let mut result = vec![];
2107             let mut place = place;
2108             loop {
2109                 result.push(place);
2110                 match place {
2111                     Place::Projection(interior) => {
2112                         place = &interior.base;
2113                     }
2114                     Place::Local(_) | Place::Static(_) => {
2115                         result.reverse();
2116                         return result;
2117                     }
2118                 }
2119             }
2120         }
2121
2122         let borrow_components = place_elements(borrow_place);
2123         let access_components = place_elements(access_place);
2124         debug!(
2125             "places_conflict: components {:?} / {:?}",
2126             borrow_components, access_components
2127         );
2128
2129         let borrow_components = borrow_components
2130             .into_iter()
2131             .map(Some)
2132             .chain(iter::repeat(None));
2133         let access_components = access_components
2134             .into_iter()
2135             .map(Some)
2136             .chain(iter::repeat(None));
2137         // The borrowck rules for proving disjointness are applied from the "root" of the
2138         // borrow forwards, iterating over "similar" projections in lockstep until
2139         // we can prove overlap one way or another. Essentially, we treat `Overlap` as
2140         // a monoid and report a conflict if the product ends up not being `Disjoint`.
2141         //
2142         // At each step, if we didn't run out of borrow or place, we know that our elements
2143         // have the same type, and that they only overlap if they are the identical.
2144         //
2145         // For example, if we are comparing these:
2146         // BORROW:  (*x1[2].y).z.a
2147         // ACCESS:  (*x1[i].y).w.b
2148         //
2149         // Then our steps are:
2150         //       x1         |   x1          -- places are the same
2151         //       x1[2]      |   x1[i]       -- equal or disjoint (disjoint if indexes differ)
2152         //       x1[2].y    |   x1[i].y     -- equal or disjoint
2153         //      *x1[2].y    |  *x1[i].y     -- equal or disjoint
2154         //     (*x1[2].y).z | (*x1[i].y).w  -- we are disjoint and don't need to check more!
2155         //
2156         // Because `zip` does potentially bad things to the iterator inside, this loop
2157         // also handles the case where the access might be a *prefix* of the borrow, e.g.
2158         //
2159         // BORROW:  (*x1[2].y).z.a
2160         // ACCESS:  x1[i].y
2161         //
2162         // Then our steps are:
2163         //       x1         |   x1          -- places are the same
2164         //       x1[2]      |   x1[i]       -- equal or disjoint (disjoint if indexes differ)
2165         //       x1[2].y    |   x1[i].y     -- equal or disjoint
2166         //
2167         // -- here we run out of access - the borrow can access a part of it. If this
2168         // is a full deep access, then we *know* the borrow conflicts with it. However,
2169         // if the access is shallow, then we can proceed:
2170         //
2171         //       x1[2].y    | (*x1[i].y)    -- a deref! the access can't get past this, so we
2172         //                                     are disjoint
2173         //
2174         // Our invariant is, that at each step of the iteration:
2175         //  - If we didn't run out of access to match, our borrow and access are comparable
2176         //    and either equal or disjoint.
2177         //  - If we did run out of accesss, the borrow can access a part of it.
2178         for (borrow_c, access_c) in borrow_components.zip(access_components) {
2179             // loop invariant: borrow_c is always either equal to access_c or disjoint from it.
2180             debug!("places_conflict: {:?} vs. {:?}", borrow_c, access_c);
2181             match (borrow_c, access_c) {
2182                 (None, _) => {
2183                     // If we didn't run out of access, the borrow can access all of our
2184                     // place (e.g. a borrow of `a.b` with an access to `a.b.c`),
2185                     // so we have a conflict.
2186                     //
2187                     // If we did, then we still know that the borrow can access a *part*
2188                     // of our place that our access cares about (a borrow of `a.b.c`
2189                     // with an access to `a.b`), so we still have a conflict.
2190                     //
2191                     // FIXME: Differs from AST-borrowck; includes drive-by fix
2192                     // to #38899. Will probably need back-compat mode flag.
2193                     debug!("places_conflict: full borrow, CONFLICT");
2194                     return true;
2195                 }
2196                 (Some(borrow_c), None) => {
2197                     // We know that the borrow can access a part of our place. This
2198                     // is a conflict if that is a part our access cares about.
2199
2200                     let (base, elem) = match borrow_c {
2201                         Place::Projection(box Projection { base, elem }) => (base, elem),
2202                         _ => bug!("place has no base?"),
2203                     };
2204                     let base_ty = base.ty(self.mir, self.tcx).to_ty(self.tcx);
2205
2206                     match (elem, &base_ty.sty, access) {
2207                         (_, _, Shallow(Some(ArtificialField::Discriminant)))
2208                         | (_, _, Shallow(Some(ArtificialField::ArrayLength))) => {
2209                             // The discriminant and array length are like
2210                             // additional fields on the type; they do not
2211                             // overlap any existing data there. Furthermore,
2212                             // they cannot actually be a prefix of any
2213                             // borrowed place (at least in MIR as it is
2214                             // currently.)
2215                             //
2216                             // e.g. a (mutable) borrow of `a[5]` while we read the
2217                             // array length of `a`.
2218                             debug!("places_conflict: implicit field");
2219                             return false;
2220                         }
2221
2222                         (ProjectionElem::Deref, _, Shallow(None)) => {
2223                             // e.g. a borrow of `*x.y` while we shallowly access `x.y` or some
2224                             // prefix thereof - the shallow access can't touch anything behind
2225                             // the pointer.
2226                             debug!("places_conflict: shallow access behind ptr");
2227                             return false;
2228                         }
2229                         (
2230                             ProjectionElem::Deref,
2231                             ty::TyRef(
2232                                 _,
2233                                 ty::TypeAndMut {
2234                                     ty: _,
2235                                     mutbl: hir::MutImmutable,
2236                                 },
2237                             ),
2238                             _,
2239                         ) => {
2240                             // the borrow goes through a dereference of a shared reference.
2241                             //
2242                             // I'm not sure why we are tracking these borrows - shared
2243                             // references can *always* be aliased, which means the
2244                             // permission check already account for this borrow.
2245                             debug!("places_conflict: behind a shared ref");
2246                             return false;
2247                         }
2248
2249                         (ProjectionElem::Deref, _, Deep)
2250                         | (ProjectionElem::Field { .. }, _, _)
2251                         | (ProjectionElem::Index { .. }, _, _)
2252                         | (ProjectionElem::ConstantIndex { .. }, _, _)
2253                         | (ProjectionElem::Subslice { .. }, _, _)
2254                         | (ProjectionElem::Downcast { .. }, _, _) => {
2255                             // Recursive case. This can still be disjoint on a
2256                             // further iteration if this a shallow access and
2257                             // there's a deref later on, e.g. a borrow
2258                             // of `*x.y` while accessing `x`.
2259                         }
2260                     }
2261                 }
2262                 (Some(borrow_c), Some(access_c)) => {
2263                     match self.place_element_conflict(&borrow_c, access_c) {
2264                         Overlap::Arbitrary => {
2265                             // We have encountered different fields of potentially
2266                             // the same union - the borrow now partially overlaps.
2267                             //
2268                             // There is no *easy* way of comparing the fields
2269                             // further on, because they might have different types
2270                             // (e.g. borrows of `u.a.0` and `u.b.y` where `.0` and
2271                             // `.y` come from different structs).
2272                             //
2273                             // We could try to do some things here - e.g. count
2274                             // dereferences - but that's probably not a good
2275                             // idea, at least for now, so just give up and
2276                             // report a conflict. This is unsafe code anyway so
2277                             // the user could always use raw pointers.
2278                             debug!("places_conflict: arbitrary -> conflict");
2279                             return true;
2280                         }
2281                         Overlap::EqualOrDisjoint => {
2282                             // This is the recursive case - proceed to the next element.
2283                         }
2284                         Overlap::Disjoint => {
2285                             // We have proven the borrow disjoint - further
2286                             // projections will remain disjoint.
2287                             debug!("places_conflict: disjoint");
2288                             return false;
2289                         }
2290                     }
2291                 }
2292             }
2293         }
2294         unreachable!("iter::repeat returned None")
2295     }
2296
2297     /// This function iterates over all of the in-scope borrows that
2298     /// conflict with an access to a place, invoking the `op` callback
2299     /// for each one.
2300     ///
2301     /// "Current borrow" here means a borrow that reaches the point in
2302     /// the control-flow where the access occurs.
2303     ///
2304     /// The borrow's phase is represented by the IsActive parameter
2305     /// passed to the callback.
2306     fn each_borrow_involving_path<F>(
2307         &mut self,
2308         _context: Context,
2309         access_place: (ShallowOrDeep, &Place<'tcx>),
2310         flow_state: &Flows<'cx, 'gcx, 'tcx>,
2311         mut op: F,
2312     ) where
2313         F: FnMut(&mut Self, BorrowIndex, &BorrowData<'tcx>) -> Control,
2314     {
2315         let (access, place) = access_place;
2316
2317         // FIXME: analogous code in check_loans first maps `place` to
2318         // its base_path.
2319
2320         // check for loan restricting path P being used. Accounts for
2321         // borrows of P, P.a.b, etc.
2322         let borrow_set = self.borrow_set.clone();
2323         for i in flow_state.borrows_in_scope() {
2324             let borrowed = &borrow_set[i];
2325
2326             if self.places_conflict(&borrowed.borrowed_place, place, access) {
2327                 debug!(
2328                     "each_borrow_involving_path: {:?} @ {:?} vs. {:?}/{:?}",
2329                     i, borrowed, place, access
2330                 );
2331                 let ctrl = op(self, i, borrowed);
2332                 if ctrl == Control::Break {
2333                     return;
2334                 }
2335             }
2336         }
2337     }
2338
2339     fn is_active(
2340         &self,
2341         borrow_data: &BorrowData<'tcx>,
2342         location: Location
2343     ) -> bool {
2344         debug!("is_active(borrow_data={:?}, location={:?})", borrow_data, location);
2345
2346         // If this is not a 2-phase borrow, it is always active.
2347         let activation_location = match borrow_data.activation_location {
2348             Some(v) => v,
2349             None => return true,
2350         };
2351
2352         // Otherwise, it is active for every location *except* in between
2353         // the reservation and the activation:
2354         //
2355         //       X
2356         //      /
2357         //     R      <--+ Except for this
2358         //    / \        | diamond
2359         //    \ /        |
2360         //     A  <------+
2361         //     |
2362         //     Z
2363         //
2364         // Note that we assume that:
2365         // - the reservation R dominates the activation A
2366         // - the activation A post-dominates the reservation R (ignoring unwinding edges).
2367         //
2368         // This means that there can't be an edge that leaves A and
2369         // comes back into that diamond unless it passes through R.
2370         //
2371         // Suboptimal: In some cases, this code walks the dominator
2372         // tree twice when it only has to be walked once. I am
2373         // lazy. -nmatsakis
2374
2375         // If dominated by the activation A, then it is active. The
2376         // activation occurs upon entering the point A, so this is
2377         // also true if location == activation_location.
2378         if activation_location.dominates(location, &self.dominators) {
2379             return true;
2380         }
2381
2382         // The reservation starts *on exiting* the reservation block,
2383         // so check if the location is dominated by R.successor. If so,
2384         // this point falls in between the reservation and location.
2385         let reserve_location = borrow_data.reserve_location.successor_within_block();
2386         if reserve_location.dominates(location, &self.dominators) {
2387             false
2388         } else {
2389             // Otherwise, this point is outside the diamond, so
2390             // consider the borrow active. This could happen for
2391             // example if the borrow remains active around a loop (in
2392             // which case it would be active also for the point R,
2393             // which would generate an error).
2394             true
2395         }
2396     }
2397 }
2398
2399 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
2400     // FIXME (#16118): function intended to allow the borrow checker
2401     // to be less precise in its handling of Box while still allowing
2402     // moves out of a Box. They should be removed when/if we stop
2403     // treating Box specially (e.g. when/if DerefMove is added...)
2404
2405     fn base_path<'d>(&self, place: &'d Place<'tcx>) -> &'d Place<'tcx> {
2406         //! Returns the base of the leftmost (deepest) dereference of an
2407         //! Box in `place`. If there is no dereference of an Box
2408         //! in `place`, then it just returns `place` itself.
2409
2410         let mut cursor = place;
2411         let mut deepest = place;
2412         loop {
2413             let proj = match *cursor {
2414                 Place::Local(..) | Place::Static(..) => return deepest,
2415                 Place::Projection(ref proj) => proj,
2416             };
2417             if proj.elem == ProjectionElem::Deref
2418                 && place.ty(self.mir, self.tcx).to_ty(self.tcx).is_box()
2419             {
2420                 deepest = &proj.base;
2421             }
2422             cursor = &proj.base;
2423         }
2424     }
2425 }
2426
2427 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2428 struct Context {
2429     kind: ContextKind,
2430     loc: Location,
2431 }
2432
2433 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2434 enum ContextKind {
2435     Activation,
2436     AssignLhs,
2437     AssignRhs,
2438     SetDiscrim,
2439     InlineAsm,
2440     SwitchInt,
2441     Drop,
2442     DropAndReplace,
2443     CallOperator,
2444     CallOperand,
2445     CallDest,
2446     Assert,
2447     Yield,
2448     StorageDead,
2449 }
2450
2451 impl ContextKind {
2452     fn new(self, loc: Location) -> Context {
2453         Context {
2454             kind: self,
2455             loc: loc,
2456         }
2457     }
2458 }
2459