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