]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/mod.rs
Rollup merge of #61113 - SimonSapin:fnbox, r=alexcrichton
[rust.git] / src / librustc_mir / borrow_check / mod.rs
1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
2
3 use crate::borrow_check::nll::region_infer::RegionInferenceContext;
4 use rustc::hir::{self, HirId};
5 use rustc::hir::Node;
6 use rustc::hir::def_id::DefId;
7 use rustc::infer::InferCtxt;
8 use rustc::lint::builtin::UNUSED_MUT;
9 use rustc::lint::builtin::{MUTABLE_BORROW_RESERVATION_CONFLICT};
10 use rustc::middle::borrowck::SignalledError;
11 use rustc::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
12 use rustc::mir::{
13     ClearCrossCrate, Local, Location, Mir, Mutability, Operand, Place, PlaceBase, Static, StaticKind
14 };
15 use rustc::mir::{Field, Projection, ProjectionElem, Rvalue, Statement, StatementKind};
16 use rustc::mir::{Terminator, TerminatorKind};
17 use rustc::ty::query::Providers;
18 use rustc::ty::{self, TyCtxt};
19
20 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, Level};
21 use rustc_data_structures::bit_set::BitSet;
22 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
23 use rustc_data_structures::graph::dominators::Dominators;
24 use smallvec::SmallVec;
25
26 use std::collections::BTreeMap;
27 use std::mem;
28 use std::rc::Rc;
29
30 use syntax::ast::Name;
31 use syntax_pos::{Span, DUMMY_SP};
32
33 use crate::dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex};
34 use crate::dataflow::move_paths::{HasMoveData, InitLocation, LookupResult, MoveData, MoveError};
35 use crate::dataflow::Borrows;
36 use crate::dataflow::DataflowResultsConsumer;
37 use crate::dataflow::FlowAtLocation;
38 use crate::dataflow::MoveDataParamEnv;
39 use crate::dataflow::{do_dataflow, DebugFormatted};
40 use crate::dataflow::EverInitializedPlaces;
41 use crate::dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
42 use crate::util::borrowck_errors::{BorrowckErrors, Origin};
43
44 use self::borrow_set::{BorrowData, BorrowSet};
45 use self::flows::Flows;
46 use self::location::LocationTable;
47 use self::prefixes::PrefixSet;
48 use self::MutateMode::{JustWrite, WriteAndRead};
49 use self::mutability_errors::AccessKind;
50
51 use self::path_utils::*;
52
53 crate mod borrow_set;
54 mod error_reporting;
55 mod flows;
56 mod location;
57 mod conflict_errors;
58 mod move_errors;
59 mod mutability_errors;
60 mod path_utils;
61 crate mod place_ext;
62 crate mod places_conflict;
63 mod prefixes;
64 mod used_muts;
65
66 pub(crate) mod nll;
67
68 // FIXME(eddyb) perhaps move this somewhere more centrally.
69 #[derive(Debug)]
70 crate struct Upvar {
71     name: Name,
72
73     var_hir_id: HirId,
74
75     /// If true, the capture is behind a reference.
76     by_ref: bool,
77
78     mutability: Mutability,
79 }
80
81 pub fn provide(providers: &mut Providers<'_>) {
82     *providers = Providers {
83         mir_borrowck,
84         ..*providers
85     };
86 }
87
88 fn mir_borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> BorrowCheckResult<'tcx> {
89     let input_mir = tcx.mir_validated(def_id);
90     debug!("run query mir_borrowck: {}", tcx.def_path_str(def_id));
91
92     // We are not borrow checking the automatically generated struct/variant constructors
93     // because we want to accept structs such as this (taken from the `linked-hash-map`
94     // crate):
95     // ```rust
96     // struct Qey<Q: ?Sized>(Q);
97     // ```
98     // MIR of this struct constructor looks something like this:
99     // ```rust
100     // fn Qey(_1: Q) -> Qey<Q>{
101     //     let mut _0: Qey<Q>;                  // return place
102     //
103     //     bb0: {
104     //         (_0.0: Q) = move _1;             // bb0[0]: scope 0 at src/main.rs:1:1: 1:26
105     //         return;                          // bb0[1]: scope 0 at src/main.rs:1:1: 1:26
106     //     }
107     // }
108     // ```
109     // The problem here is that `(_0.0: Q) = move _1;` is valid only if `Q` is
110     // of statically known size, which is not known to be true because of the
111     // `Q: ?Sized` constraint. However, it is true because the constructor can be
112     // called only when `Q` is of statically known size.
113     if tcx.is_constructor(def_id) {
114         return BorrowCheckResult {
115             closure_requirements: None,
116             used_mut_upvars: SmallVec::new(),
117         };
118     }
119
120     let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
121         let input_mir: &Mir<'_> = &input_mir.borrow();
122         do_mir_borrowck(&infcx, input_mir, def_id)
123     });
124     debug!("mir_borrowck done");
125
126     opt_closure_req
127 }
128
129 fn do_mir_borrowck<'a, 'gcx, 'tcx>(
130     infcx: &InferCtxt<'a, 'gcx, 'tcx>,
131     input_mir: &Mir<'gcx>,
132     def_id: DefId,
133 ) -> BorrowCheckResult<'gcx> {
134     debug!("do_mir_borrowck(def_id = {:?})", def_id);
135
136     let tcx = infcx.tcx;
137     let attributes = tcx.get_attrs(def_id);
138     let param_env = tcx.param_env(def_id);
139     let id = tcx
140         .hir()
141         .as_local_hir_id(def_id)
142         .expect("do_mir_borrowck: non-local DefId");
143
144     // Gather the upvars of a closure, if any.
145     let tables = tcx.typeck_tables_of(def_id);
146     let upvars: Vec<_> = tables
147         .upvar_list
148         .get(&def_id)
149         .into_iter()
150         .flatten()
151         .map(|upvar_id| {
152             let var_hir_id = upvar_id.var_path.hir_id;
153             let var_node_id = tcx.hir().hir_to_node_id(var_hir_id);
154             let capture = tables.upvar_capture(*upvar_id);
155             let by_ref = match capture {
156                 ty::UpvarCapture::ByValue => false,
157                 ty::UpvarCapture::ByRef(..) => true,
158             };
159             let mut upvar = Upvar {
160                 name: tcx.hir().name(var_node_id),
161                 var_hir_id,
162                 by_ref,
163                 mutability: Mutability::Not,
164             };
165             let bm = *tables.pat_binding_modes().get(var_hir_id)
166                 .expect("missing binding mode");
167             if bm == ty::BindByValue(hir::MutMutable) {
168                 upvar.mutability = Mutability::Mut;
169             }
170             upvar
171         })
172         .collect();
173
174     // Replace all regions with fresh inference variables. This
175     // requires first making our own copy of the MIR. This copy will
176     // be modified (in place) to contain non-lexical lifetimes. It
177     // will have a lifetime tied to the inference context.
178     let mut mir: Mir<'tcx> = input_mir.clone();
179     let free_regions = nll::replace_regions_in_mir(infcx, def_id, param_env, &mut mir);
180     let mir = &mir; // no further changes
181     let location_table = &LocationTable::new(mir);
182
183     let mut errors_buffer = Vec::new();
184     let (move_data, move_errors): (MoveData<'tcx>, Option<Vec<(Place<'tcx>, MoveError<'tcx>)>>) =
185         match MoveData::gather_moves(mir, tcx) {
186             Ok(move_data) => (move_data, None),
187             Err((move_data, move_errors)) => (move_data, Some(move_errors)),
188         };
189
190     let mdpe = MoveDataParamEnv {
191         move_data: move_data,
192         param_env: param_env,
193     };
194
195     let dead_unwinds = BitSet::new_empty(mir.basic_blocks().len());
196     let mut flow_inits = FlowAtLocation::new(do_dataflow(
197         tcx,
198         mir,
199         def_id,
200         &attributes,
201         &dead_unwinds,
202         MaybeInitializedPlaces::new(tcx, mir, &mdpe),
203         |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
204     ));
205
206     let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind_by_hir_id(id).is_fn_or_closure();
207     let borrow_set = Rc::new(BorrowSet::build(
208             tcx, mir, locals_are_invalidated_at_exit, &mdpe.move_data));
209
210     // If we are in non-lexical mode, compute the non-lexical lifetimes.
211     let (regioncx, polonius_output, opt_closure_req) = nll::compute_regions(
212         infcx,
213         def_id,
214         free_regions,
215         mir,
216         &upvars,
217         location_table,
218         param_env,
219         &mut flow_inits,
220         &mdpe.move_data,
221         &borrow_set,
222         &mut errors_buffer,
223     );
224
225     // The various `flow_*` structures can be large. We drop `flow_inits` here
226     // so it doesn't overlap with the others below. This reduces peak memory
227     // usage significantly on some benchmarks.
228     drop(flow_inits);
229
230     let regioncx = Rc::new(regioncx);
231
232     let flow_borrows = FlowAtLocation::new(do_dataflow(
233         tcx,
234         mir,
235         def_id,
236         &attributes,
237         &dead_unwinds,
238         Borrows::new(tcx, mir, regioncx.clone(), &borrow_set),
239         |rs, i| DebugFormatted::new(&rs.location(i)),
240     ));
241     let flow_uninits = FlowAtLocation::new(do_dataflow(
242         tcx,
243         mir,
244         def_id,
245         &attributes,
246         &dead_unwinds,
247         MaybeUninitializedPlaces::new(tcx, mir, &mdpe),
248         |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
249     ));
250     let flow_ever_inits = FlowAtLocation::new(do_dataflow(
251         tcx,
252         mir,
253         def_id,
254         &attributes,
255         &dead_unwinds,
256         EverInitializedPlaces::new(tcx, mir, &mdpe),
257         |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
258     ));
259
260     let movable_generator = match tcx.hir().get_by_hir_id(id) {
261         Node::Expr(&hir::Expr {
262             node: hir::ExprKind::Closure(.., Some(hir::GeneratorMovability::Static)),
263             ..
264         }) => false,
265         _ => true,
266     };
267
268     let dominators = mir.dominators();
269
270     let mut mbcx = MirBorrowckCtxt {
271         infcx,
272         mir,
273         mir_def_id: def_id,
274         move_data: &mdpe.move_data,
275         location_table,
276         movable_generator,
277         locals_are_invalidated_at_exit,
278         access_place_error_reported: Default::default(),
279         reservation_error_reported: Default::default(),
280         reservation_warnings: Default::default(),
281         move_error_reported: BTreeMap::new(),
282         uninitialized_error_reported: Default::default(),
283         errors_buffer,
284         nonlexical_regioncx: regioncx,
285         used_mut: Default::default(),
286         used_mut_upvars: SmallVec::new(),
287         borrow_set,
288         dominators,
289         upvars,
290     };
291
292     let mut state = Flows::new(
293         flow_borrows,
294         flow_uninits,
295         flow_ever_inits,
296         polonius_output,
297     );
298
299     if let Some(errors) = move_errors {
300         mbcx.report_move_errors(errors);
301     }
302     mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
303
304     // Convert any reservation warnings into lints.
305     let reservation_warnings = mem::replace(&mut mbcx.reservation_warnings, Default::default());
306     for (_, (place, span, location, bk, borrow)) in reservation_warnings {
307         let mut initial_diag =
308             mbcx.report_conflicting_borrow(location, (&place, span), bk, &borrow);
309
310         let lint_root = if let ClearCrossCrate::Set(ref vsi) = mbcx.mir.source_scope_local_data {
311             let scope = mbcx.mir.source_info(location).scope;
312             vsi[scope].lint_root
313         } else {
314             id
315         };
316
317         // Span and message don't matter; we overwrite them below anyway
318         let mut diag = mbcx.infcx.tcx.struct_span_lint_hir(
319             MUTABLE_BORROW_RESERVATION_CONFLICT, lint_root, DUMMY_SP, "");
320
321         diag.message = initial_diag.styled_message().clone();
322         diag.span = initial_diag.span.clone();
323
324         initial_diag.cancel();
325         diag.buffer(&mut mbcx.errors_buffer);
326     }
327
328     // For each non-user used mutable variable, check if it's been assigned from
329     // a user-declared local. If so, then put that local into the used_mut set.
330     // Note that this set is expected to be small - only upvars from closures
331     // would have a chance of erroneously adding non-user-defined mutable vars
332     // to the set.
333     let temporary_used_locals: FxHashSet<Local> = mbcx.used_mut.iter()
334         .filter(|&local| mbcx.mir.local_decls[*local].is_user_variable.is_none())
335         .cloned()
336         .collect();
337     // For the remaining unused locals that are marked as mutable, we avoid linting any that
338     // were never initialized. These locals may have been removed as unreachable code; or will be
339     // linted as unused variables.
340     let unused_mut_locals = mbcx.mir.mut_vars_iter()
341         .filter(|local| !mbcx.used_mut.contains(local))
342         .collect();
343     mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
344
345     debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
346     let used_mut = mbcx.used_mut;
347     for local in mbcx.mir.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
348         if let ClearCrossCrate::Set(ref vsi) = mbcx.mir.source_scope_local_data {
349             let local_decl = &mbcx.mir.local_decls[local];
350
351             // Skip implicit `self` argument for closures
352             if local.index() == 1 && tcx.is_closure(mbcx.mir_def_id) {
353                 continue;
354             }
355
356             // Skip over locals that begin with an underscore or have no name
357             match local_decl.name {
358                 Some(name) => if name.as_str().starts_with("_") {
359                     continue;
360                 },
361                 None => continue,
362             }
363
364             let span = local_decl.source_info.span;
365             if span.compiler_desugaring_kind().is_some() {
366                 // If the `mut` arises as part of a desugaring, we should ignore it.
367                 continue;
368             }
369
370             let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
371             tcx.struct_span_lint_hir(
372                 UNUSED_MUT,
373                 vsi[local_decl.source_info.scope].lint_root,
374                 span,
375                 "variable does not need to be mutable",
376             )
377             .span_suggestion_short(
378                 mut_span,
379                 "remove this `mut`",
380                 String::new(),
381                 Applicability::MachineApplicable,
382             )
383             .emit();
384         }
385     }
386
387     // Buffer any move errors that we collected and de-duplicated.
388     for (_, (_, diag)) in mbcx.move_error_reported {
389         diag.buffer(&mut mbcx.errors_buffer);
390     }
391
392     if !mbcx.errors_buffer.is_empty() {
393         mbcx.errors_buffer.sort_by_key(|diag| diag.span.primary_span());
394
395         if tcx.migrate_borrowck() {
396             // When borrowck=migrate, check if AST-borrowck would
397             // error on the given code.
398
399             // rust-lang/rust#55492, rust-lang/rust#58776 check the base def id
400             // for errors. AST borrowck is responsible for aggregating
401             // `signalled_any_error` from all of the nested closures here.
402             let base_def_id = tcx.closure_base_def_id(def_id);
403
404             match tcx.borrowck(base_def_id).signalled_any_error {
405                 SignalledError::NoErrorsSeen => {
406                     // if AST-borrowck signalled no errors, then
407                     // downgrade all the buffered MIR-borrowck errors
408                     // to warnings.
409
410                     for err in mbcx.errors_buffer.iter_mut() {
411                         downgrade_if_error(err);
412                     }
413                 }
414                 SignalledError::SawSomeError => {
415                     // if AST-borrowck signalled a (cancelled) error,
416                     // then we will just emit the buffered
417                     // MIR-borrowck errors as normal.
418                 }
419             }
420         }
421
422         for diag in mbcx.errors_buffer.drain(..) {
423             DiagnosticBuilder::new_diagnostic(mbcx.infcx.tcx.sess.diagnostic(), diag).emit();
424         }
425     }
426
427     let result = BorrowCheckResult {
428         closure_requirements: opt_closure_req,
429         used_mut_upvars: mbcx.used_mut_upvars,
430     };
431
432     debug!("do_mir_borrowck: result = {:#?}", result);
433
434     result
435 }
436
437 fn downgrade_if_error(diag: &mut Diagnostic) {
438     if diag.is_error() {
439         diag.level = Level::Warning;
440         diag.warn(
441             "this error has been downgraded to a warning for backwards \
442             compatibility with previous releases",
443         ).warn(
444             "this represents potential undefined behavior in your code and \
445             this warning will become a hard error in the future",
446         ).note(
447             "for more information, try `rustc --explain E0729`"
448         );
449     }
450 }
451
452 pub struct MirBorrowckCtxt<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
453     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
454     mir: &'cx Mir<'tcx>,
455     mir_def_id: DefId,
456     move_data: &'cx MoveData<'tcx>,
457
458     /// Map from MIR `Location` to `LocationIndex`; created
459     /// when MIR borrowck begins.
460     location_table: &'cx LocationTable,
461
462     movable_generator: bool,
463     /// This keeps track of whether local variables are free-ed when the function
464     /// exits even without a `StorageDead`, which appears to be the case for
465     /// constants.
466     ///
467     /// I'm not sure this is the right approach - @eddyb could you try and
468     /// figure this out?
469     locals_are_invalidated_at_exit: bool,
470     /// This field keeps track of when borrow errors are reported in the access_place function
471     /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
472     /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
473     /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
474     /// errors.
475     access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
476     /// This field keeps track of when borrow conflict errors are reported
477     /// for reservations, so that we don't report seemingly duplicate
478     /// errors for corresponding activations.
479     //
480     // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
481     // but it is currently inconvenient to track down the `BorrowIndex`
482     // at the time we detect and report a reservation error.
483     reservation_error_reported: FxHashSet<Place<'tcx>>,
484     /// Migration warnings to be reported for #56254. We delay reporting these
485     /// so that we can suppress the warning if there's a corresponding error
486     /// for the activation of the borrow.
487     reservation_warnings: FxHashMap<
488         BorrowIndex,
489         (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)
490     >,
491     /// This field keeps track of move errors that are to be reported for given move indicies.
492     ///
493     /// There are situations where many errors can be reported for a single move out (see #53807)
494     /// and we want only the best of those errors.
495     ///
496     /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
497     /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
498     /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
499     /// all move errors have been reported, any diagnostics in this map are added to the buffer
500     /// to be emitted.
501     ///
502     /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
503     /// when errors in the map are being re-added to the error buffer so that errors with the
504     /// same primary span come out in a consistent order.
505     move_error_reported: BTreeMap<Vec<MoveOutIndex>, (Place<'tcx>, DiagnosticBuilder<'cx>)>,
506     /// This field keeps track of errors reported in the checking of uninitialized variables,
507     /// so that we don't report seemingly duplicate errors.
508     uninitialized_error_reported: FxHashSet<Place<'tcx>>,
509     /// Errors to be reported buffer
510     errors_buffer: Vec<Diagnostic>,
511     /// This field keeps track of all the local variables that are declared mut and are mutated.
512     /// Used for the warning issued by an unused mutable local variable.
513     used_mut: FxHashSet<Local>,
514     /// If the function we're checking is a closure, then we'll need to report back the list of
515     /// mutable upvars that have been used. This field keeps track of them.
516     used_mut_upvars: SmallVec<[Field; 8]>,
517     /// Non-lexical region inference context, if NLL is enabled. This
518     /// contains the results from region inference and lets us e.g.
519     /// find out which CFG points are contained in each borrow region.
520     nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
521
522     /// The set of borrows extracted from the MIR
523     borrow_set: Rc<BorrowSet<'tcx>>,
524
525     /// Dominators for MIR
526     dominators: Dominators<BasicBlock>,
527
528     /// Information about upvars not necessarily preserved in types or MIR
529     upvars: Vec<Upvar>,
530 }
531
532 // Check that:
533 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
534 // 2. loans made in overlapping scopes do not conflict
535 // 3. assignments do not affect things loaned out as immutable
536 // 4. moves do not affect things loaned out in any way
537 impl<'cx, 'gcx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
538     type FlowState = Flows<'cx, 'gcx, 'tcx>;
539
540     fn mir(&self) -> &'cx Mir<'tcx> {
541         self.mir
542     }
543
544     fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
545         debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
546     }
547
548     fn visit_statement_entry(
549         &mut self,
550         location: Location,
551         stmt: &Statement<'tcx>,
552         flow_state: &Self::FlowState,
553     ) {
554         debug!(
555             "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
556             location, stmt, flow_state
557         );
558         let span = stmt.source_info.span;
559
560         self.check_activations(location, span, flow_state);
561
562         match stmt.kind {
563             StatementKind::Assign(ref lhs, ref rhs) => {
564                 self.consume_rvalue(
565                     location,
566                     (rhs, span),
567                     flow_state,
568                 );
569
570                 self.mutate_place(
571                     location,
572                     (lhs, span),
573                     Shallow(None),
574                     JustWrite,
575                     flow_state,
576                 );
577             }
578             StatementKind::FakeRead(_, ref place) => {
579                 // Read for match doesn't access any memory and is used to
580                 // assert that a place is safe and live. So we don't have to
581                 // do any checks here.
582                 //
583                 // FIXME: Remove check that the place is initialized. This is
584                 // needed for now because matches don't have never patterns yet.
585                 // So this is the only place we prevent
586                 //      let x: !;
587                 //      match x {};
588                 // from compiling.
589                 self.check_if_path_or_subpath_is_moved(
590                     location,
591                     InitializationRequiringAction::Use,
592                     (place, span),
593                     flow_state,
594                 );
595             }
596             StatementKind::SetDiscriminant {
597                 ref place,
598                 variant_index: _,
599             } => {
600                 self.mutate_place(
601                     location,
602                     (place, span),
603                     Shallow(None),
604                     JustWrite,
605                     flow_state,
606                 );
607             }
608             StatementKind::InlineAsm(ref asm) => {
609                 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
610                     if o.is_indirect {
611                         // FIXME(eddyb) indirect inline asm outputs should
612                         // be encoded through MIR place derefs instead.
613                         self.access_place(
614                             location,
615                             (output, o.span),
616                             (Deep, Read(ReadKind::Copy)),
617                             LocalMutationIsAllowed::No,
618                             flow_state,
619                         );
620                         self.check_if_path_or_subpath_is_moved(
621                             location,
622                             InitializationRequiringAction::Use,
623                             (output, o.span),
624                             flow_state,
625                         );
626                     } else {
627                         self.mutate_place(
628                             location,
629                             (output, o.span),
630                             if o.is_rw { Deep } else { Shallow(None) },
631                             if o.is_rw { WriteAndRead } else { JustWrite },
632                             flow_state,
633                         );
634                     }
635                 }
636                 for (_, input) in asm.inputs.iter() {
637                     self.consume_operand(location, (input, span), flow_state);
638                 }
639             }
640             StatementKind::Nop
641             | StatementKind::AscribeUserType(..)
642             | StatementKind::Retag { .. }
643             | StatementKind::StorageLive(..) => {
644                 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
645                 // to borrow check.
646             }
647             StatementKind::StorageDead(local) => {
648                 self.access_place(
649                     location,
650                     (&Place::Base(PlaceBase::Local(local)), span),
651                     (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
652                     LocalMutationIsAllowed::Yes,
653                     flow_state,
654                 );
655             }
656         }
657     }
658
659     fn visit_terminator_entry(
660         &mut self,
661         location: Location,
662         term: &Terminator<'tcx>,
663         flow_state: &Self::FlowState,
664     ) {
665         let loc = location;
666         debug!(
667             "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
668             location, term, flow_state
669         );
670         let span = term.source_info.span;
671
672         self.check_activations(location, span, flow_state);
673
674         match term.kind {
675             TerminatorKind::SwitchInt {
676                 ref discr,
677                 switch_ty: _,
678                 values: _,
679                 targets: _,
680             } => {
681                 self.consume_operand(loc, (discr, span), flow_state);
682             }
683             TerminatorKind::Drop {
684                 location: ref drop_place,
685                 target: _,
686                 unwind: _,
687             } => {
688                 let gcx = self.infcx.tcx.global_tcx();
689
690                 // Compute the type with accurate region information.
691                 let drop_place_ty = drop_place.ty(self.mir, self.infcx.tcx);
692
693                 // Erase the regions.
694                 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
695
696                 // "Lift" into the gcx -- once regions are erased, this type should be in the
697                 // global arenas; this "lift" operation basically just asserts that is true, but
698                 // that is useful later.
699                 let drop_place_ty = gcx.lift(&drop_place_ty).unwrap();
700
701                 debug!("visit_terminator_drop \
702                         loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
703                        loc, term, drop_place, drop_place_ty, span);
704
705                 self.access_place(
706                     loc,
707                     (drop_place, span),
708                     (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
709                     LocalMutationIsAllowed::Yes,
710                     flow_state,
711                 );
712             }
713             TerminatorKind::DropAndReplace {
714                 location: ref drop_place,
715                 value: ref new_value,
716                 target: _,
717                 unwind: _,
718             } => {
719                 self.mutate_place(
720                     loc,
721                     (drop_place, span),
722                     Deep,
723                     JustWrite,
724                     flow_state,
725                 );
726                 self.consume_operand(
727                     loc,
728                     (new_value, span),
729                     flow_state,
730                 );
731             }
732             TerminatorKind::Call {
733                 ref func,
734                 ref args,
735                 ref destination,
736                 cleanup: _,
737                 from_hir_call: _,
738             } => {
739                 self.consume_operand(loc, (func, span), flow_state);
740                 for arg in args {
741                     self.consume_operand(
742                         loc,
743                         (arg, span),
744                         flow_state,
745                     );
746                 }
747                 if let Some((ref dest, _ /*bb*/)) = *destination {
748                     self.mutate_place(
749                         loc,
750                         (dest, span),
751                         Deep,
752                         JustWrite,
753                         flow_state,
754                     );
755                 }
756             }
757             TerminatorKind::Assert {
758                 ref cond,
759                 expected: _,
760                 ref msg,
761                 target: _,
762                 cleanup: _,
763             } => {
764                 self.consume_operand(loc, (cond, span), flow_state);
765                 use rustc::mir::interpret::InterpError::BoundsCheck;
766                 if let BoundsCheck { ref len, ref index } = *msg {
767                     self.consume_operand(loc, (len, span), flow_state);
768                     self.consume_operand(loc, (index, span), flow_state);
769                 }
770             }
771
772             TerminatorKind::Yield {
773                 ref value,
774                 resume: _,
775                 drop: _,
776             } => {
777                 self.consume_operand(loc, (value, span), flow_state);
778
779                 if self.movable_generator {
780                     // Look for any active borrows to locals
781                     let borrow_set = self.borrow_set.clone();
782                     flow_state.with_outgoing_borrows(|borrows| {
783                         for i in borrows {
784                             let borrow = &borrow_set[i];
785                             self.check_for_local_borrow(borrow, span);
786                         }
787                     });
788                 }
789             }
790
791             TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
792                 // Returning from the function implicitly kills storage for all locals and statics.
793                 // Often, the storage will already have been killed by an explicit
794                 // StorageDead, but we don't always emit those (notably on unwind paths),
795                 // so this "extra check" serves as a kind of backup.
796                 let borrow_set = self.borrow_set.clone();
797                 flow_state.with_outgoing_borrows(|borrows| {
798                     for i in borrows {
799                         let borrow = &borrow_set[i];
800                         self.check_for_invalidation_at_exit(loc, borrow, span);
801                     }
802                 });
803             }
804             TerminatorKind::Goto { target: _ }
805             | TerminatorKind::Abort
806             | TerminatorKind::Unreachable
807             | TerminatorKind::FalseEdges {
808                 real_target: _,
809                 imaginary_targets: _,
810             }
811             | TerminatorKind::FalseUnwind {
812                 real_target: _,
813                 unwind: _,
814             } => {
815                 // no data used, thus irrelevant to borrowck
816             }
817         }
818     }
819 }
820
821 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
822 enum MutateMode {
823     JustWrite,
824     WriteAndRead,
825 }
826
827 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
828 use self::AccessDepth::{Deep, Shallow};
829
830 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
831 enum ArtificialField {
832     ArrayLength,
833     ShallowBorrow,
834 }
835
836 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
837 enum AccessDepth {
838     /// From the RFC: "A *shallow* access means that the immediate
839     /// fields reached at P are accessed, but references or pointers
840     /// found within are not dereferenced. Right now, the only access
841     /// that is shallow is an assignment like `x = ...;`, which would
842     /// be a *shallow write* of `x`."
843     Shallow(Option<ArtificialField>),
844
845     /// From the RFC: "A *deep* access means that all data reachable
846     /// through the given place may be invalidated or accesses by
847     /// this action."
848     Deep,
849
850     /// Access is Deep only when there is a Drop implementation that
851     /// can reach the data behind the reference.
852     Drop,
853 }
854
855 /// Kind of access to a value: read or write
856 /// (For informational purposes only)
857 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
858 enum ReadOrWrite {
859     /// From the RFC: "A *read* means that the existing data may be
860     /// read, but will not be changed."
861     Read(ReadKind),
862
863     /// From the RFC: "A *write* means that the data may be mutated to
864     /// new values or otherwise invalidated (for example, it could be
865     /// de-initialized, as in a move operation).
866     Write(WriteKind),
867
868     /// For two-phase borrows, we distinguish a reservation (which is treated
869     /// like a Read) from an activation (which is treated like a write), and
870     /// each of those is furthermore distinguished from Reads/Writes above.
871     Reservation(WriteKind),
872     Activation(WriteKind, BorrowIndex),
873 }
874
875 /// Kind of read access to a value
876 /// (For informational purposes only)
877 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
878 enum ReadKind {
879     Borrow(BorrowKind),
880     Copy,
881 }
882
883 /// Kind of write access to a value
884 /// (For informational purposes only)
885 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
886 enum WriteKind {
887     StorageDeadOrDrop,
888     MutableBorrow(BorrowKind),
889     Mutate,
890     Move,
891 }
892
893 /// When checking permissions for a place access, this flag is used to indicate that an immutable
894 /// local place can be mutated.
895 //
896 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
897 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
898 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
899 //   `is_declared_mutable()`.
900 // - Take flow state into consideration in `is_assignable()` for local variables.
901 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
902 enum LocalMutationIsAllowed {
903     Yes,
904     /// We want use of immutable upvars to cause a "write to immutable upvar"
905     /// error, not an "reassignment" error.
906     ExceptUpvars,
907     No,
908 }
909
910 #[derive(Copy, Clone, Debug)]
911 enum InitializationRequiringAction {
912     Update,
913     Borrow,
914     MatchOn,
915     Use,
916     Assignment,
917     PartialAssignment,
918 }
919
920 struct RootPlace<'d, 'tcx: 'd> {
921     place: &'d Place<'tcx>,
922     is_local_mutation_allowed: LocalMutationIsAllowed,
923 }
924
925 impl InitializationRequiringAction {
926     fn as_noun(self) -> &'static str {
927         match self {
928             InitializationRequiringAction::Update => "update",
929             InitializationRequiringAction::Borrow => "borrow",
930             InitializationRequiringAction::MatchOn => "use", // no good noun
931             InitializationRequiringAction::Use => "use",
932             InitializationRequiringAction::Assignment => "assign",
933             InitializationRequiringAction::PartialAssignment => "assign to part",
934         }
935     }
936
937     fn as_verb_in_past_tense(self) -> &'static str {
938         match self {
939             InitializationRequiringAction::Update => "updated",
940             InitializationRequiringAction::Borrow => "borrowed",
941             InitializationRequiringAction::MatchOn => "matched on",
942             InitializationRequiringAction::Use => "used",
943             InitializationRequiringAction::Assignment => "assigned",
944             InitializationRequiringAction::PartialAssignment => "partially assigned",
945         }
946     }
947 }
948
949 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
950     /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
951     /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
952     /// place is initialized and (b) it is not borrowed in some way that would prevent this
953     /// access.
954     ///
955     /// Returns `true` if an error is reported.
956     fn access_place(
957         &mut self,
958         location: Location,
959         place_span: (&Place<'tcx>, Span),
960         kind: (AccessDepth, ReadOrWrite),
961         is_local_mutation_allowed: LocalMutationIsAllowed,
962         flow_state: &Flows<'cx, 'gcx, 'tcx>,
963     ) {
964         let (sd, rw) = kind;
965
966         if let Activation(_, borrow_index) = rw {
967             if self.reservation_error_reported.contains(&place_span.0) {
968                 debug!(
969                     "skipping access_place for activation of invalid reservation \
970                      place: {:?} borrow_index: {:?}",
971                     place_span.0, borrow_index
972                 );
973                 return;
974             }
975         }
976
977         // Check is_empty() first because it's the common case, and doing that
978         // way we avoid the clone() call.
979         if !self.access_place_error_reported.is_empty() &&
980            self
981             .access_place_error_reported
982             .contains(&(place_span.0.clone(), place_span.1))
983         {
984             debug!(
985                 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
986                 place_span, kind
987             );
988             return;
989         }
990
991         let mutability_error =
992             self.check_access_permissions(
993                 place_span,
994                 rw,
995                 is_local_mutation_allowed,
996                 flow_state,
997                 location,
998             );
999         let conflict_error =
1000             self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
1001
1002         if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
1003             // Suppress this warning when there's an error being emited for the
1004             // same borrow: fixing the error is likely to fix the warning.
1005             self.reservation_warnings.remove(&borrow_idx);
1006         }
1007
1008         if conflict_error || mutability_error {
1009             debug!(
1010                 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
1011                 place_span, kind
1012             );
1013
1014             self.access_place_error_reported
1015                 .insert((place_span.0.clone(), place_span.1));
1016         }
1017     }
1018
1019     fn check_access_for_conflict(
1020         &mut self,
1021         location: Location,
1022         place_span: (&Place<'tcx>, Span),
1023         sd: AccessDepth,
1024         rw: ReadOrWrite,
1025         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1026     ) -> bool {
1027         debug!(
1028             "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1029             location, place_span, sd, rw,
1030         );
1031
1032         let mut error_reported = false;
1033         let tcx = self.infcx.tcx;
1034         let mir = self.mir;
1035         let location_table = self.location_table.start_index(location);
1036         let borrow_set = self.borrow_set.clone();
1037         each_borrow_involving_path(
1038             self,
1039             tcx,
1040             mir,
1041             location,
1042             (sd, place_span.0),
1043             &borrow_set,
1044             flow_state.borrows_in_scope(location_table),
1045             |this, borrow_index, borrow| match (rw, borrow.kind) {
1046                 // Obviously an activation is compatible with its own
1047                 // reservation (or even prior activating uses of same
1048                 // borrow); so don't check if they interfere.
1049                 //
1050                 // NOTE: *reservations* do conflict with themselves;
1051                 // thus aren't injecting unsoundenss w/ this check.)
1052                 (Activation(_, activating), _) if activating == borrow_index => {
1053                     debug!(
1054                         "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1055                          skipping {:?} b/c activation of same borrow_index",
1056                         place_span,
1057                         sd,
1058                         rw,
1059                         (borrow_index, borrow),
1060                     );
1061                     Control::Continue
1062                 }
1063
1064                 (Read(_), BorrowKind::Shared)
1065                 | (Read(_), BorrowKind::Shallow)
1066                 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
1067                 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
1068                     Control::Continue
1069                 }
1070
1071                 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1072                     // Handled by initialization checks.
1073                     Control::Continue
1074                 }
1075
1076                 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
1077                     // Reading from mere reservations of mutable-borrows is OK.
1078                     if !is_active(&this.dominators, borrow, location) {
1079                         assert!(allow_two_phase_borrow(borrow.kind));
1080                         return Control::Continue;
1081                     }
1082
1083                     error_reported = true;
1084                     match kind {
1085                         ReadKind::Copy  => {
1086                             this.report_use_while_mutably_borrowed(location, place_span, borrow)
1087                                 .buffer(&mut this.errors_buffer);
1088                         }
1089                         ReadKind::Borrow(bk) => {
1090                             this.report_conflicting_borrow(location, place_span, bk, borrow)
1091                                 .buffer(&mut this.errors_buffer);
1092                         }
1093                     }
1094                     Control::Break
1095                 }
1096
1097                 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
1098                 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared) if {
1099                     tcx.migrate_borrowck()
1100                 } => {
1101                     let bi = this.borrow_set.location_map[&location];
1102                     debug!(
1103                         "recording invalid reservation of place: {:?} with \
1104                          borrow index {:?} as warning",
1105                         place_span.0,
1106                         bi,
1107                     );
1108                     // rust-lang/rust#56254 - This was previously permitted on
1109                     // the 2018 edition so we emit it as a warning. We buffer
1110                     // these sepately so that we only emit a warning if borrow
1111                     // checking was otherwise successful.
1112                     this.reservation_warnings.insert(
1113                         bi,
1114                         (place_span.0.clone(), place_span.1, location, bk, borrow.clone()),
1115                     );
1116
1117                     // Don't suppress actual errors.
1118                     Control::Continue
1119                 }
1120
1121                 (Reservation(kind), _)
1122                 | (Activation(kind, _), _)
1123                 | (Write(kind), _) => {
1124                     match rw {
1125                         Reservation(..) => {
1126                             debug!(
1127                                 "recording invalid reservation of \
1128                                  place: {:?}",
1129                                 place_span.0
1130                             );
1131                             this.reservation_error_reported.insert(place_span.0.clone());
1132                         }
1133                         Activation(_, activating) => {
1134                             debug!(
1135                                 "observing check_place for activation of \
1136                                  borrow_index: {:?}",
1137                                 activating
1138                             );
1139                         }
1140                         Read(..) | Write(..) => {}
1141                     }
1142
1143                     error_reported = true;
1144                     match kind {
1145                         WriteKind::MutableBorrow(bk) => {
1146                             this.report_conflicting_borrow(location, place_span, bk, borrow)
1147                                 .buffer(&mut this.errors_buffer);
1148                         }
1149                         WriteKind::StorageDeadOrDrop => {
1150                             this.report_borrowed_value_does_not_live_long_enough(
1151                                 location,
1152                                 borrow,
1153                                 place_span,
1154                                 Some(kind))
1155                         }
1156                         WriteKind::Mutate => {
1157                             this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1158                         }
1159                         WriteKind::Move => {
1160                             this.report_move_out_while_borrowed(location, place_span, borrow)
1161                         }
1162                     }
1163                     Control::Break
1164                 }
1165             },
1166         );
1167
1168         error_reported
1169     }
1170
1171     fn mutate_place(
1172         &mut self,
1173         location: Location,
1174         place_span: (&Place<'tcx>, Span),
1175         kind: AccessDepth,
1176         mode: MutateMode,
1177         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1178     ) {
1179         // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1180         match mode {
1181             MutateMode::WriteAndRead => {
1182                 self.check_if_path_or_subpath_is_moved(
1183                     location,
1184                     InitializationRequiringAction::Update,
1185                     place_span,
1186                     flow_state,
1187                 );
1188             }
1189             MutateMode::JustWrite => {
1190                 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1191             }
1192         }
1193
1194         // Special case: you can assign a immutable local variable
1195         // (e.g., `x = ...`) so long as it has never been initialized
1196         // before (at this point in the flow).
1197         if let &Place::Base(PlaceBase::Local(local)) = place_span.0 {
1198             if let Mutability::Not = self.mir.local_decls[local].mutability {
1199                 // check for reassignments to immutable local variables
1200                 self.check_if_reassignment_to_immutable_state(
1201                     location,
1202                     local,
1203                     place_span,
1204                     flow_state,
1205                 );
1206                 return;
1207             }
1208         }
1209
1210         // Otherwise, use the normal access permission rules.
1211         self.access_place(
1212             location,
1213             place_span,
1214             (kind, Write(WriteKind::Mutate)),
1215             LocalMutationIsAllowed::No,
1216             flow_state,
1217         );
1218     }
1219
1220     fn consume_rvalue(
1221         &mut self,
1222         location: Location,
1223         (rvalue, span): (&Rvalue<'tcx>, Span),
1224         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1225     ) {
1226         match *rvalue {
1227             Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1228                 let access_kind = match bk {
1229                     BorrowKind::Shallow => {
1230                         (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1231                     },
1232                     BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1233                     BorrowKind::Unique | BorrowKind::Mut { .. } => {
1234                         let wk = WriteKind::MutableBorrow(bk);
1235                         if allow_two_phase_borrow(bk) {
1236                             (Deep, Reservation(wk))
1237                         } else {
1238                             (Deep, Write(wk))
1239                         }
1240                     }
1241                 };
1242
1243                 self.access_place(
1244                     location,
1245                     (place, span),
1246                     access_kind,
1247                     LocalMutationIsAllowed::No,
1248                     flow_state,
1249                 );
1250
1251                 let action = if bk == BorrowKind::Shallow {
1252                     InitializationRequiringAction::MatchOn
1253                 } else {
1254                     InitializationRequiringAction::Borrow
1255                 };
1256
1257                 self.check_if_path_or_subpath_is_moved(
1258                     location,
1259                     action,
1260                     (place, span),
1261                     flow_state,
1262                 );
1263             }
1264
1265             Rvalue::Use(ref operand)
1266             | Rvalue::Repeat(ref operand, _)
1267             | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1268             | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1269                 self.consume_operand(location, (operand, span), flow_state)
1270             }
1271
1272             Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1273                 let af = match *rvalue {
1274                     Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1275                     Rvalue::Discriminant(..) => None,
1276                     _ => unreachable!(),
1277                 };
1278                 self.access_place(
1279                     location,
1280                     (place, span),
1281                     (Shallow(af), Read(ReadKind::Copy)),
1282                     LocalMutationIsAllowed::No,
1283                     flow_state,
1284                 );
1285                 self.check_if_path_or_subpath_is_moved(
1286                     location,
1287                     InitializationRequiringAction::Use,
1288                     (place, span),
1289                     flow_state,
1290                 );
1291             }
1292
1293             Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1294             | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1295                 self.consume_operand(location, (operand1, span), flow_state);
1296                 self.consume_operand(location, (operand2, span), flow_state);
1297             }
1298
1299             Rvalue::NullaryOp(_op, _ty) => {
1300                 // nullary ops take no dynamic input; no borrowck effect.
1301                 //
1302                 // FIXME: is above actually true? Do we want to track
1303                 // the fact that uninitialized data can be created via
1304                 // `NullOp::Box`?
1305             }
1306
1307             Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1308                 // We need to report back the list of mutable upvars that were
1309                 // moved into the closure and subsequently used by the closure,
1310                 // in order to populate our used_mut set.
1311                 match **aggregate_kind {
1312                     AggregateKind::Closure(def_id, _)
1313                     | AggregateKind::Generator(def_id, _, _) => {
1314                         let BorrowCheckResult {
1315                             used_mut_upvars, ..
1316                         } = self.infcx.tcx.mir_borrowck(def_id);
1317                         debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1318                         for field in used_mut_upvars {
1319                             self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1320                         }
1321                     }
1322                     AggregateKind::Adt(..)
1323                     | AggregateKind::Array(..)
1324                     | AggregateKind::Tuple { .. } => (),
1325                 }
1326
1327                 for operand in operands {
1328                     self.consume_operand(location, (operand, span), flow_state);
1329                 }
1330             }
1331         }
1332     }
1333
1334     fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1335         let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1336             match *place {
1337                 Place::Projection { .. } => {
1338                     if let Some(field) = this.is_upvar_field_projection(place) {
1339                         this.used_mut_upvars.push(field);
1340                     }
1341                 }
1342                 Place::Base(PlaceBase::Local(local)) => {
1343                     this.used_mut.insert(local);
1344                 }
1345                 Place::Base(PlaceBase::Static(_)) => {}
1346             }
1347         };
1348
1349         // This relies on the current way that by-value
1350         // captures of a closure are copied/moved directly
1351         // when generating MIR.
1352         match *operand {
1353             Operand::Move(Place::Base(PlaceBase::Local(local)))
1354             | Operand::Copy(Place::Base(PlaceBase::Local(local)))
1355                 if self.mir.local_decls[local].is_user_variable.is_none() =>
1356             {
1357                 if self.mir.local_decls[local].ty.is_mutable_pointer() {
1358                     // The variable will be marked as mutable by the borrow.
1359                     return;
1360                 }
1361                 // This is an edge case where we have a `move` closure
1362                 // inside a non-move closure, and the inner closure
1363                 // contains a mutation:
1364                 //
1365                 // let mut i = 0;
1366                 // || { move || { i += 1; }; };
1367                 //
1368                 // In this case our usual strategy of assuming that the
1369                 // variable will be captured by mutable reference is
1370                 // wrong, since `i` can be copied into the inner
1371                 // closure from a shared reference.
1372                 //
1373                 // As such we have to search for the local that this
1374                 // capture comes from and mark it as being used as mut.
1375
1376                 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1377                 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1378                     &self.move_data.inits[init_index]
1379                 } else {
1380                     bug!("temporary should be initialized exactly once")
1381                 };
1382
1383                 let loc = match init.location {
1384                     InitLocation::Statement(stmt) => stmt,
1385                     _ => bug!("temporary initialized in arguments"),
1386                 };
1387
1388                 let bbd = &self.mir[loc.block];
1389                 let stmt = &bbd.statements[loc.statement_index];
1390                 debug!("temporary assigned in: stmt={:?}", stmt);
1391
1392                 if let StatementKind::Assign(_, box Rvalue::Ref(_, _, ref source)) = stmt.kind {
1393                     propagate_closure_used_mut_place(self, source);
1394                 } else {
1395                     bug!("closures should only capture user variables \
1396                         or references to user variables");
1397                 }
1398             }
1399             Operand::Move(ref place)
1400             | Operand::Copy(ref place) => {
1401                 propagate_closure_used_mut_place(self, place);
1402             }
1403             Operand::Constant(..) => {}
1404         }
1405     }
1406
1407     fn consume_operand(
1408         &mut self,
1409         location: Location,
1410         (operand, span): (&Operand<'tcx>, Span),
1411         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1412     ) {
1413         match *operand {
1414             Operand::Copy(ref place) => {
1415                 // copy of place: check if this is "copy of frozen path"
1416                 // (FIXME: see check_loans.rs)
1417                 self.access_place(
1418                     location,
1419                     (place, span),
1420                     (Deep, Read(ReadKind::Copy)),
1421                     LocalMutationIsAllowed::No,
1422                     flow_state,
1423                 );
1424
1425                 // Finally, check if path was already moved.
1426                 self.check_if_path_or_subpath_is_moved(
1427                     location,
1428                     InitializationRequiringAction::Use,
1429                     (place, span),
1430                     flow_state,
1431                 );
1432             }
1433             Operand::Move(ref place) => {
1434                 // move of place: check if this is move of already borrowed path
1435                 self.access_place(
1436                     location,
1437                     (place, span),
1438                     (Deep, Write(WriteKind::Move)),
1439                     LocalMutationIsAllowed::Yes,
1440                     flow_state,
1441                 );
1442
1443                 // Finally, check if path was already moved.
1444                 self.check_if_path_or_subpath_is_moved(
1445                     location,
1446                     InitializationRequiringAction::Use,
1447                     (place, span),
1448                     flow_state,
1449                 );
1450             }
1451             Operand::Constant(_) => {}
1452         }
1453     }
1454
1455     /// Checks whether a borrow of this place is invalidated when the function
1456     /// exits
1457     fn check_for_invalidation_at_exit(
1458         &mut self,
1459         location: Location,
1460         borrow: &BorrowData<'tcx>,
1461         span: Span,
1462     ) {
1463         debug!("check_for_invalidation_at_exit({:?})", borrow);
1464         let place = &borrow.borrowed_place;
1465         let root_place = self.prefixes(place, PrefixSet::All).last().unwrap();
1466
1467         // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1468         // we just know that all locals are dropped at function exit (otherwise
1469         // we'll have a memory leak) and assume that all statics have a destructor.
1470         //
1471         // FIXME: allow thread-locals to borrow other thread locals?
1472         let (might_be_alive, will_be_dropped) = match root_place {
1473             Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Promoted(_), .. })) => {
1474                 (true, false)
1475             }
1476             Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(_), .. })) => {
1477                 // Thread-locals might be dropped after the function exits, but
1478                 // "true" statics will never be.
1479                 (true, self.is_place_thread_local(&root_place))
1480             }
1481             Place::Base(PlaceBase::Local(_)) => {
1482                 // Locals are always dropped at function exit, and if they
1483                 // have a destructor it would've been called already.
1484                 (false, self.locals_are_invalidated_at_exit)
1485             }
1486             Place::Projection(..) => {
1487                 bug!("root of {:?} is a projection ({:?})?", place, root_place)
1488             }
1489         };
1490
1491         if !will_be_dropped {
1492             debug!(
1493                 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1494                 place
1495             );
1496             return;
1497         }
1498
1499         let sd = if might_be_alive { Deep } else { Shallow(None) };
1500
1501         if places_conflict::borrow_conflicts_with_place(
1502             self.infcx.tcx,
1503             self.mir,
1504             place,
1505             borrow.kind,
1506             root_place,
1507             sd,
1508             places_conflict::PlaceConflictBias::Overlap,
1509         ) {
1510             debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1511             // FIXME: should be talking about the region lifetime instead
1512             // of just a span here.
1513             let span = self.infcx.tcx.sess.source_map().end_point(span);
1514             self.report_borrowed_value_does_not_live_long_enough(
1515                 location,
1516                 borrow,
1517                 (place, span),
1518                 None,
1519             )
1520         }
1521     }
1522
1523     /// Reports an error if this is a borrow of local data.
1524     /// This is called for all Yield statements on movable generators
1525     fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1526         debug!("check_for_local_borrow({:?})", borrow);
1527
1528         if borrow_of_local_data(&borrow.borrowed_place) {
1529             let err = self.infcx.tcx
1530                 .cannot_borrow_across_generator_yield(
1531                     self.retrieve_borrow_spans(borrow).var_or_use(),
1532                     yield_span,
1533                     Origin::Mir,
1534                 );
1535
1536             err.buffer(&mut self.errors_buffer);
1537         }
1538     }
1539
1540     fn check_activations(
1541         &mut self,
1542         location: Location,
1543         span: Span,
1544         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1545     ) {
1546         // Two-phase borrow support: For each activation that is newly
1547         // generated at this statement, check if it interferes with
1548         // another borrow.
1549         let borrow_set = self.borrow_set.clone();
1550         for &borrow_index in borrow_set.activations_at_location(location) {
1551             let borrow = &borrow_set[borrow_index];
1552
1553             // only mutable borrows should be 2-phase
1554             assert!(match borrow.kind {
1555                 BorrowKind::Shared | BorrowKind::Shallow => false,
1556                 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1557             });
1558
1559             self.access_place(
1560                 location,
1561                 (&borrow.borrowed_place, span),
1562                 (
1563                     Deep,
1564                     Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1565                 ),
1566                 LocalMutationIsAllowed::No,
1567                 flow_state,
1568             );
1569             // We do not need to call `check_if_path_or_subpath_is_moved`
1570             // again, as we already called it when we made the
1571             // initial reservation.
1572         }
1573     }
1574 }
1575
1576 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1577     fn check_if_reassignment_to_immutable_state(
1578         &mut self,
1579         location: Location,
1580         local: Local,
1581         place_span: (&Place<'tcx>, Span),
1582         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1583     ) {
1584         debug!("check_if_reassignment_to_immutable_state({:?})", local);
1585
1586         // Check if any of the initializiations of `local` have happened yet:
1587         if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1588             // And, if so, report an error.
1589             let init = &self.move_data.inits[init_index];
1590             let span = init.span(&self.mir);
1591             self.report_illegal_reassignment(
1592                 location, place_span, span, place_span.0
1593             );
1594         }
1595     }
1596
1597     fn check_if_full_path_is_moved(
1598         &mut self,
1599         location: Location,
1600         desired_action: InitializationRequiringAction,
1601         place_span: (&Place<'tcx>, Span),
1602         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1603     ) {
1604         let maybe_uninits = &flow_state.uninits;
1605
1606         // Bad scenarios:
1607         //
1608         // 1. Move of `a.b.c`, use of `a.b.c`
1609         // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1610         // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1611         //    partial initialization support, one might have `a.x`
1612         //    initialized but not `a.b`.
1613         //
1614         // OK scenarios:
1615         //
1616         // 4. Move of `a.b.c`, use of `a.b.d`
1617         // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1618         // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1619         //    must have been initialized for the use to be sound.
1620         // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1621
1622         // The dataflow tracks shallow prefixes distinctly (that is,
1623         // field-accesses on P distinctly from P itself), in order to
1624         // track substructure initialization separately from the whole
1625         // structure.
1626         //
1627         // E.g., when looking at (*a.b.c).d, if the closest prefix for
1628         // which we have a MovePath is `a.b`, then that means that the
1629         // initialization state of `a.b` is all we need to inspect to
1630         // know if `a.b.c` is valid (and from that we infer that the
1631         // dereference and `.d` access is also valid, since we assume
1632         // `a.b.c` is assigned a reference to a initialized and
1633         // well-formed record structure.)
1634
1635         // Therefore, if we seek out the *closest* prefix for which we
1636         // have a MovePath, that should capture the initialization
1637         // state for the place scenario.
1638         //
1639         // This code covers scenarios 1, 2, and 3.
1640
1641         debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1642         match self.move_path_closest_to(place_span.0) {
1643             Ok((prefix, mpi)) => {
1644                 if maybe_uninits.contains(mpi) {
1645                     self.report_use_of_moved_or_uninitialized(
1646                         location,
1647                         desired_action,
1648                         (prefix, place_span.0, place_span.1),
1649                         mpi,
1650                     );
1651                     return; // don't bother finding other problems.
1652                 }
1653             }
1654             Err(NoMovePathFound::ReachedStatic) => {
1655                 // Okay: we do not build MoveData for static variables
1656             } // Only query longest prefix with a MovePath, not further
1657               // ancestors; dataflow recurs on children when parents
1658               // move (to support partial (re)inits).
1659               //
1660               // (I.e., querying parents breaks scenario 7; but may want
1661               // to do such a query based on partial-init feature-gate.)
1662         }
1663     }
1664
1665     fn check_if_path_or_subpath_is_moved(
1666         &mut self,
1667         location: Location,
1668         desired_action: InitializationRequiringAction,
1669         place_span: (&Place<'tcx>, Span),
1670         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1671     ) {
1672         let maybe_uninits = &flow_state.uninits;
1673
1674         // Bad scenarios:
1675         //
1676         // 1. Move of `a.b.c`, use of `a` or `a.b`
1677         //    partial initialization support, one might have `a.x`
1678         //    initialized but not `a.b`.
1679         // 2. All bad scenarios from `check_if_full_path_is_moved`
1680         //
1681         // OK scenarios:
1682         //
1683         // 3. Move of `a.b.c`, use of `a.b.d`
1684         // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1685         // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1686         //    must have been initialized for the use to be sound.
1687         // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1688
1689         self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1690
1691         // A move of any shallow suffix of `place` also interferes
1692         // with an attempt to use `place`. This is scenario 3 above.
1693         //
1694         // (Distinct from handling of scenarios 1+2+4 above because
1695         // `place` does not interfere with suffixes of its prefixes,
1696         // e.g., `a.b.c` does not interfere with `a.b.d`)
1697         //
1698         // This code covers scenario 1.
1699
1700         debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1701         if let Some(mpi) = self.move_path_for_place(place_span.0) {
1702             if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1703                 self.report_use_of_moved_or_uninitialized(
1704                     location,
1705                     desired_action,
1706                     (place_span.0, place_span.0, place_span.1),
1707                     child_mpi,
1708                 );
1709                 return; // don't bother finding other problems.
1710             }
1711         }
1712     }
1713
1714     /// Currently MoveData does not store entries for all places in
1715     /// the input MIR. For example it will currently filter out
1716     /// places that are Copy; thus we do not track places of shared
1717     /// reference type. This routine will walk up a place along its
1718     /// prefixes, searching for a foundational place that *is*
1719     /// tracked in the MoveData.
1720     ///
1721     /// An Err result includes a tag indicated why the search failed.
1722     /// Currently this can only occur if the place is built off of a
1723     /// static variable, as we do not track those in the MoveData.
1724     fn move_path_closest_to<'a>(
1725         &mut self,
1726         place: &'a Place<'tcx>,
1727     ) -> Result<(&'a Place<'tcx>, MovePathIndex), NoMovePathFound> where 'cx: 'a {
1728         let mut last_prefix = place;
1729         for prefix in self.prefixes(place, PrefixSet::All) {
1730             if let Some(mpi) = self.move_path_for_place(prefix) {
1731                 return Ok((prefix, mpi));
1732             }
1733             last_prefix = prefix;
1734         }
1735         match *last_prefix {
1736             Place::Base(PlaceBase::Local(_)) => panic!("should have move path for every Local"),
1737             Place::Projection(_) => panic!("PrefixSet::All meant don't stop for Projection"),
1738             Place::Base(PlaceBase::Static(_)) => Err(NoMovePathFound::ReachedStatic),
1739         }
1740     }
1741
1742     fn move_path_for_place(&mut self, place: &Place<'tcx>) -> Option<MovePathIndex> {
1743         // If returns None, then there is no move path corresponding
1744         // to a direct owner of `place` (which means there is nothing
1745         // that borrowck tracks for its analysis).
1746
1747         match self.move_data.rev_lookup.find(place) {
1748             LookupResult::Parent(_) => None,
1749             LookupResult::Exact(mpi) => Some(mpi),
1750         }
1751     }
1752
1753     fn check_if_assigned_path_is_moved(
1754         &mut self,
1755         location: Location,
1756         (place, span): (&Place<'tcx>, Span),
1757         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1758     ) {
1759         debug!("check_if_assigned_path_is_moved place: {:?}", place);
1760         // recur down place; dispatch to external checks when necessary
1761         let mut place = place;
1762         loop {
1763             match *place {
1764                 Place::Base(PlaceBase::Local(_)) | Place::Base(PlaceBase::Static(_)) => {
1765                     // assigning to `x` does not require `x` be initialized.
1766                     break;
1767                 }
1768                 Place::Projection(ref proj) => {
1769                     let Projection { ref base, ref elem } = **proj;
1770                     match *elem {
1771                         ProjectionElem::Index(_/*operand*/) |
1772                         ProjectionElem::ConstantIndex { .. } |
1773                         // assigning to P[i] requires P to be valid.
1774                         ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1775                         // assigning to (P->variant) is okay if assigning to `P` is okay
1776                         //
1777                         // FIXME: is this true even if P is a adt with a dtor?
1778                         { }
1779
1780                         // assigning to (*P) requires P to be initialized
1781                         ProjectionElem::Deref => {
1782                             self.check_if_full_path_is_moved(
1783                                 location, InitializationRequiringAction::Use,
1784                                 (base, span), flow_state);
1785                             // (base initialized; no need to
1786                             // recur further)
1787                             break;
1788                         }
1789
1790                         ProjectionElem::Subslice { .. } => {
1791                             panic!("we don't allow assignments to subslices, location: {:?}",
1792                                    location);
1793                         }
1794
1795                         ProjectionElem::Field(..) => {
1796                             // if type of `P` has a dtor, then
1797                             // assigning to `P.f` requires `P` itself
1798                             // be already initialized
1799                             let tcx = self.infcx.tcx;
1800                             match base.ty(self.mir, tcx).ty.sty {
1801                                 ty::Adt(def, _) if def.has_dtor(tcx) => {
1802                                     self.check_if_path_or_subpath_is_moved(
1803                                         location, InitializationRequiringAction::Assignment,
1804                                         (base, span), flow_state);
1805
1806                                     // (base initialized; no need to
1807                                     // recur further)
1808                                     break;
1809                                 }
1810
1811
1812                                 // Once `let s; s.x = V; read(s.x);`,
1813                                 // is allowed, remove this match arm.
1814                                 ty::Adt(..) | ty::Tuple(..) => {
1815                                     check_parent_of_field(self, location, base, span, flow_state);
1816
1817                                     if let Some(local) = place.base_local() {
1818                                         // rust-lang/rust#21232,
1819                                         // #54499, #54986: during
1820                                         // period where we reject
1821                                         // partial initialization, do
1822                                         // not complain about
1823                                         // unnecessary `mut` on an
1824                                         // attempt to do a partial
1825                                         // initialization.
1826                                         self.used_mut.insert(local);
1827                                     }
1828                                 }
1829
1830                                 _ => {}
1831                             }
1832                         }
1833                     }
1834
1835                     place = base;
1836                 }
1837             }
1838         }
1839
1840         fn check_parent_of_field<'cx, 'gcx, 'tcx>(
1841             this: &mut MirBorrowckCtxt<'cx, 'gcx, 'tcx>,
1842             location: Location,
1843             base: &Place<'tcx>,
1844             span: Span,
1845             flow_state: &Flows<'cx, 'gcx, 'tcx>,
1846         ) {
1847             // rust-lang/rust#21232: Until Rust allows reads from the
1848             // initialized parts of partially initialized structs, we
1849             // will, starting with the 2018 edition, reject attempts
1850             // to write to structs that are not fully initialized.
1851             //
1852             // In other words, *until* we allow this:
1853             //
1854             // 1. `let mut s; s.x = Val; read(s.x);`
1855             //
1856             // we will for now disallow this:
1857             //
1858             // 2. `let mut s; s.x = Val;`
1859             //
1860             // and also this:
1861             //
1862             // 3. `let mut s = ...; drop(s); s.x=Val;`
1863             //
1864             // This does not use check_if_path_or_subpath_is_moved,
1865             // because we want to *allow* reinitializations of fields:
1866             // e.g., want to allow
1867             //
1868             // `let mut s = ...; drop(s.x); s.x=Val;`
1869             //
1870             // This does not use check_if_full_path_is_moved on
1871             // `base`, because that would report an error about the
1872             // `base` as a whole, but in this scenario we *really*
1873             // want to report an error about the actual thing that was
1874             // moved, which may be some prefix of `base`.
1875
1876             // Shallow so that we'll stop at any dereference; we'll
1877             // report errors about issues with such bases elsewhere.
1878             let maybe_uninits = &flow_state.uninits;
1879
1880             // Find the shortest uninitialized prefix you can reach
1881             // without going over a Deref.
1882             let mut shortest_uninit_seen = None;
1883             for prefix in this.prefixes(base, PrefixSet::Shallow) {
1884                 let mpi = match this.move_path_for_place(prefix) {
1885                     Some(mpi) => mpi, None => continue,
1886                 };
1887
1888                 if maybe_uninits.contains(mpi) {
1889                     debug!("check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1890                            shortest_uninit_seen, Some((prefix, mpi)));
1891                     shortest_uninit_seen = Some((prefix, mpi));
1892                 } else {
1893                     debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1894                 }
1895             }
1896
1897             if let Some((prefix, mpi)) = shortest_uninit_seen {
1898                 // Check for a reassignment into a uninitialized field of a union (for example,
1899                 // after a move out). In this case, do not report a error here. There is an
1900                 // exception, if this is the first assignment into the union (that is, there is
1901                 // no move out from an earlier location) then this is an attempt at initialization
1902                 // of the union - we should error in that case.
1903                 let tcx = this.infcx.tcx;
1904                 if let ty::Adt(def, _) = base.ty(this.mir, tcx).ty.sty {
1905                     if def.is_union() {
1906                         if this.move_data.path_map[mpi].iter().any(|moi| {
1907                             this.move_data.moves[*moi].source.is_predecessor_of(
1908                                 location, this.mir,
1909                             )
1910                         }) {
1911                             return;
1912                         }
1913                     }
1914                 }
1915
1916                 this.report_use_of_moved_or_uninitialized(
1917                     location,
1918                     InitializationRequiringAction::PartialAssignment,
1919                     (prefix, base, span),
1920                     mpi,
1921                 );
1922             }
1923         }
1924     }
1925
1926     /// Checks the permissions for the given place and read or write kind
1927     ///
1928     /// Returns `true` if an error is reported.
1929     fn check_access_permissions(
1930         &mut self,
1931         (place, span): (&Place<'tcx>, Span),
1932         kind: ReadOrWrite,
1933         is_local_mutation_allowed: LocalMutationIsAllowed,
1934         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1935         location: Location,
1936     ) -> bool {
1937         debug!(
1938             "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1939             place, kind, is_local_mutation_allowed
1940         );
1941
1942         let error_access;
1943         let the_place_err;
1944
1945         // rust-lang/rust#21232, #54986: during period where we reject
1946         // partial initialization, do not complain about mutability
1947         // errors except for actual mutation (as opposed to an attempt
1948         // to do a partial initialization).
1949         let previously_initialized = if let Some(local) = place.base_local() {
1950             self.is_local_ever_initialized(local, flow_state).is_some()
1951         } else {
1952             true
1953         };
1954
1955         match kind {
1956             Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1957             | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
1958             | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1959             | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. })) => {
1960                 let is_local_mutation_allowed = match borrow_kind {
1961                     BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1962                     BorrowKind::Mut { .. } => is_local_mutation_allowed,
1963                     BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1964                 };
1965                 match self.is_mutable(place, is_local_mutation_allowed) {
1966                     Ok(root_place) => {
1967                         self.add_used_mut(root_place, flow_state);
1968                         return false;
1969                     }
1970                     Err(place_err) => {
1971                         error_access = AccessKind::MutableBorrow;
1972                         the_place_err = place_err;
1973                     }
1974                 }
1975             }
1976             Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1977                 match self.is_mutable(place, is_local_mutation_allowed) {
1978                     Ok(root_place) => {
1979                         self.add_used_mut(root_place, flow_state);
1980                         return false;
1981                     }
1982                     Err(place_err) => {
1983                         error_access = AccessKind::Mutate;
1984                         the_place_err = place_err;
1985                     }
1986                 }
1987             }
1988
1989             Reservation(wk @ WriteKind::Move)
1990             | Write(wk @ WriteKind::Move)
1991             | Reservation(wk @ WriteKind::StorageDeadOrDrop)
1992             | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1993             | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow))
1994             | Write(wk @ WriteKind::StorageDeadOrDrop)
1995             | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1996             | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
1997                 if let (Err(_place_err), true) = (
1998                     self.is_mutable(place, is_local_mutation_allowed),
1999                     self.errors_buffer.is_empty()
2000                 ) {
2001                     if self.infcx.tcx.migrate_borrowck() {
2002                         // rust-lang/rust#46908: In pure NLL mode this
2003                         // code path should be unreachable (and thus
2004                         // we signal an ICE in the else branch
2005                         // here). But we can legitimately get here
2006                         // under borrowck=migrate mode, so instead of
2007                         // ICE'ing we instead report a legitimate
2008                         // error (which will then be downgraded to a
2009                         // warning by the migrate machinery).
2010                         error_access = match wk {
2011                             WriteKind::MutableBorrow(_) => AccessKind::MutableBorrow,
2012                             WriteKind::Move => AccessKind::Move,
2013                             WriteKind::StorageDeadOrDrop |
2014                             WriteKind::Mutate => AccessKind::Mutate,
2015                         };
2016                         self.report_mutability_error(
2017                             place,
2018                             span,
2019                             _place_err,
2020                             error_access,
2021                             location,
2022                         );
2023                     } else {
2024                         span_bug!(
2025                             span,
2026                             "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2027                             place,
2028                             kind,
2029                         );
2030                     }
2031                 }
2032                 return false;
2033             }
2034             Activation(..) => {
2035                 // permission checks are done at Reservation point.
2036                 return false;
2037             }
2038             Read(ReadKind::Borrow(BorrowKind::Unique))
2039             | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
2040             | Read(ReadKind::Borrow(BorrowKind::Shared))
2041             | Read(ReadKind::Borrow(BorrowKind::Shallow))
2042             | Read(ReadKind::Copy) => {
2043                 // Access authorized
2044                 return false;
2045             }
2046         }
2047
2048         // at this point, we have set up the error reporting state.
2049         return if previously_initialized {
2050             self.report_mutability_error(
2051                 place,
2052                 span,
2053                 the_place_err,
2054                 error_access,
2055                 location,
2056             );
2057             true
2058         } else {
2059             false
2060         };
2061     }
2062
2063     fn is_local_ever_initialized(&self,
2064                                  local: Local,
2065                                  flow_state: &Flows<'cx, 'gcx, 'tcx>)
2066                                  -> Option<InitIndex>
2067     {
2068         let mpi = self.move_data.rev_lookup.find_local(local);
2069         let ii = &self.move_data.init_path_map[mpi];
2070         for &index in ii {
2071             if flow_state.ever_inits.contains(index) {
2072                 return Some(index);
2073             }
2074         }
2075         None
2076     }
2077
2078     /// Adds the place into the used mutable variables set
2079     fn add_used_mut<'d>(
2080         &mut self,
2081         root_place: RootPlace<'d, 'tcx>,
2082         flow_state: &Flows<'cx, 'gcx, 'tcx>,
2083     ) {
2084         match root_place {
2085             RootPlace {
2086                 place: Place::Base(PlaceBase::Local(local)),
2087                 is_local_mutation_allowed,
2088             } => {
2089                 // If the local may have been initialized, and it is now currently being
2090                 // mutated, then it is justified to be annotated with the `mut`
2091                 // keyword, since the mutation may be a possible reassignment.
2092                 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes &&
2093                     self.is_local_ever_initialized(*local, flow_state).is_some()
2094                 {
2095                     self.used_mut.insert(*local);
2096                 }
2097             }
2098             RootPlace {
2099                 place: _,
2100                 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2101             } => {}
2102             RootPlace {
2103                 place: place @ Place::Projection(_),
2104                 is_local_mutation_allowed: _,
2105             } => {
2106                 if let Some(field) = self.is_upvar_field_projection(place) {
2107                     self.used_mut_upvars.push(field);
2108                 }
2109             }
2110             RootPlace {
2111                 place: Place::Base(PlaceBase::Static(..)),
2112                 is_local_mutation_allowed: _,
2113             } => {}
2114         }
2115     }
2116
2117     /// Whether this value can be written or borrowed mutably.
2118     /// Returns the root place if the place passed in is a projection.
2119     fn is_mutable<'d>(
2120         &self,
2121         place: &'d Place<'tcx>,
2122         is_local_mutation_allowed: LocalMutationIsAllowed,
2123     ) -> Result<RootPlace<'d, 'tcx>, &'d Place<'tcx>> {
2124         match *place {
2125             Place::Base(PlaceBase::Local(local)) => {
2126                 let local = &self.mir.local_decls[local];
2127                 match local.mutability {
2128                     Mutability::Not => match is_local_mutation_allowed {
2129                         LocalMutationIsAllowed::Yes => Ok(RootPlace {
2130                             place,
2131                             is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2132                         }),
2133                         LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2134                             place,
2135                             is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2136                         }),
2137                         LocalMutationIsAllowed::No => Err(place),
2138                     },
2139                     Mutability::Mut => Ok(RootPlace {
2140                         place,
2141                         is_local_mutation_allowed,
2142                     }),
2143                 }
2144             }
2145             // The rules for promotion are made by `qualify_consts`, there wouldn't even be a
2146             // `Place::Promoted` if the promotion weren't 100% legal. So we just forward this
2147             Place::Base(PlaceBase::Static(box Static{kind: StaticKind::Promoted(_), ..})) =>
2148                 Ok(RootPlace {
2149                     place,
2150                     is_local_mutation_allowed,
2151                 }),
2152             Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(def_id), .. })) => {
2153                 if !self.infcx.tcx.is_mutable_static(def_id) {
2154                     Err(place)
2155                 } else {
2156                     Ok(RootPlace {
2157                         place,
2158                         is_local_mutation_allowed,
2159                     })
2160                 }
2161             }
2162             Place::Projection(ref proj) => {
2163                 match proj.elem {
2164                     ProjectionElem::Deref => {
2165                         let base_ty = proj.base.ty(self.mir, self.infcx.tcx).ty;
2166
2167                         // Check the kind of deref to decide
2168                         match base_ty.sty {
2169                             ty::Ref(_, _, mutbl) => {
2170                                 match mutbl {
2171                                     // Shared borrowed data is never mutable
2172                                     hir::MutImmutable => Err(place),
2173                                     // Mutably borrowed data is mutable, but only if we have a
2174                                     // unique path to the `&mut`
2175                                     hir::MutMutable => {
2176                                         let mode = match self.is_upvar_field_projection(place) {
2177                                             Some(field)
2178                                                 if self.upvars[field.index()].by_ref =>
2179                                             {
2180                                                 is_local_mutation_allowed
2181                                             }
2182                                             _ => LocalMutationIsAllowed::Yes,
2183                                         };
2184
2185                                         self.is_mutable(&proj.base, mode)
2186                                     }
2187                                 }
2188                             }
2189                             ty::RawPtr(tnm) => {
2190                                 match tnm.mutbl {
2191                                     // `*const` raw pointers are not mutable
2192                                     hir::MutImmutable => Err(place),
2193                                     // `*mut` raw pointers are always mutable, regardless of
2194                                     // context. The users have to check by themselves.
2195                                     hir::MutMutable => {
2196                                         Ok(RootPlace {
2197                                             place,
2198                                             is_local_mutation_allowed,
2199                                         })
2200                                     }
2201                                 }
2202                             }
2203                             // `Box<T>` owns its content, so mutable if its location is mutable
2204                             _ if base_ty.is_box() => {
2205                                 self.is_mutable(&proj.base, is_local_mutation_allowed)
2206                             }
2207                             // Deref should only be for reference, pointers or boxes
2208                             _ => bug!("Deref of unexpected type: {:?}", base_ty),
2209                         }
2210                     }
2211                     // All other projections are owned by their base path, so mutable if
2212                     // base path is mutable
2213                     ProjectionElem::Field(..)
2214                     | ProjectionElem::Index(..)
2215                     | ProjectionElem::ConstantIndex { .. }
2216                     | ProjectionElem::Subslice { .. }
2217                     | ProjectionElem::Downcast(..) => {
2218                         let upvar_field_projection = self.is_upvar_field_projection(place);
2219                         if let Some(field) = upvar_field_projection {
2220                             let upvar = &self.upvars[field.index()];
2221                             debug!(
2222                                 "upvar.mutability={:?} local_mutation_is_allowed={:?} place={:?}",
2223                                 upvar, is_local_mutation_allowed, place
2224                             );
2225                             match (upvar.mutability, is_local_mutation_allowed) {
2226                                 (Mutability::Not, LocalMutationIsAllowed::No)
2227                                 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2228                                     Err(place)
2229                                 }
2230                                 (Mutability::Not, LocalMutationIsAllowed::Yes)
2231                                 | (Mutability::Mut, _) => {
2232                                     // Subtle: this is an upvar
2233                                     // reference, so it looks like
2234                                     // `self.foo` -- we want to double
2235                                     // check that the location `*self`
2236                                     // is mutable (i.e., this is not a
2237                                     // `Fn` closure).  But if that
2238                                     // check succeeds, we want to
2239                                     // *blame* the mutability on
2240                                     // `place` (that is,
2241                                     // `self.foo`). This is used to
2242                                     // propagate the info about
2243                                     // whether mutability declarations
2244                                     // are used outwards, so that we register
2245                                     // the outer variable as mutable. Otherwise a
2246                                     // test like this fails to record the `mut`
2247                                     // as needed:
2248                                     //
2249                                     // ```
2250                                     // fn foo<F: FnOnce()>(_f: F) { }
2251                                     // fn main() {
2252                                     //     let var = Vec::new();
2253                                     //     foo(move || {
2254                                     //         var.push(1);
2255                                     //     });
2256                                     // }
2257                                     // ```
2258                                     let _ = self.is_mutable(&proj.base, is_local_mutation_allowed)?;
2259                                     Ok(RootPlace {
2260                                         place,
2261                                         is_local_mutation_allowed,
2262                                     })
2263                                 }
2264                             }
2265                         } else {
2266                             self.is_mutable(&proj.base, is_local_mutation_allowed)
2267                         }
2268                     }
2269                 }
2270             }
2271         }
2272     }
2273
2274     /// If `place` is a field projection, and the field is being projected from a closure type,
2275     /// then returns the index of the field being projected. Note that this closure will always
2276     /// be `self` in the current MIR, because that is the only time we directly access the fields
2277     /// of a closure type.
2278     pub fn is_upvar_field_projection(&self, place: &Place<'tcx>) -> Option<Field> {
2279         let (place, by_ref) = if let Place::Projection(ref proj) = place {
2280             if let ProjectionElem::Deref = proj.elem {
2281                 (&proj.base, true)
2282             } else {
2283                 (place, false)
2284             }
2285         } else {
2286             (place, false)
2287         };
2288
2289         match place {
2290             Place::Projection(ref proj) => match proj.elem {
2291                 ProjectionElem::Field(field, _ty) => {
2292                     let tcx = self.infcx.tcx;
2293                     let base_ty = proj.base.ty(self.mir, tcx).ty;
2294
2295                     if (base_ty.is_closure() || base_ty.is_generator()) &&
2296                         (!by_ref || self.upvars[field.index()].by_ref)
2297                     {
2298                         Some(field)
2299                     } else {
2300                         None
2301                     }
2302                 },
2303                 _ => None,
2304             }
2305             _ => None,
2306         }
2307     }
2308 }
2309
2310 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2311 enum NoMovePathFound {
2312     ReachedStatic,
2313 }
2314
2315 /// The degree of overlap between 2 places for borrow-checking.
2316 enum Overlap {
2317     /// The places might partially overlap - in this case, we give
2318     /// up and say that they might conflict. This occurs when
2319     /// different fields of a union are borrowed. For example,
2320     /// if `u` is a union, we have no way of telling how disjoint
2321     /// `u.a.x` and `a.b.y` are.
2322     Arbitrary,
2323     /// The places have the same type, and are either completely disjoint
2324     /// or equal - i.e., they can't "partially" overlap as can occur with
2325     /// unions. This is the "base case" on which we recur for extensions
2326     /// of the place.
2327     EqualOrDisjoint,
2328     /// The places are disjoint, so we know all extensions of them
2329     /// will also be disjoint.
2330     Disjoint,
2331 }