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