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