]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/mod.rs
Auto merge of #69076 - cjgillot:split_trait, r=matthewjasper
[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 indices.
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: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'cx>)>,
472     /// This field keeps track of errors reported in the checking of uninitialized variables,
473     /// so that we don't report seemingly duplicate errors.
474     uninitialized_error_reported: FxHashSet<PlaceRef<'tcx>>,
475     /// Errors to be reported buffer
476     errors_buffer: Vec<Diagnostic>,
477     /// This field keeps track of all the local variables that are declared mut and are mutated.
478     /// Used for the warning issued by an unused mutable local variable.
479     used_mut: FxHashSet<Local>,
480     /// If the function we're checking is a closure, then we'll need to report back the list of
481     /// mutable upvars that have been used. This field keeps track of them.
482     used_mut_upvars: SmallVec<[Field; 8]>,
483     /// Region inference context. This contains the results from region inference and lets us e.g.
484     /// find out which CFG points are contained in each borrow region.
485     regioncx: Rc<RegionInferenceContext<'tcx>>,
486
487     /// The set of borrows extracted from the MIR
488     borrow_set: Rc<BorrowSet<'tcx>>,
489
490     /// Dominators for MIR
491     dominators: Dominators<BasicBlock>,
492
493     /// Information about upvars not necessarily preserved in types or MIR
494     upvars: Vec<Upvar>,
495
496     /// Names of local (user) variables (extracted from `var_debug_info`).
497     local_names: IndexVec<Local, Option<Name>>,
498
499     /// Record the region names generated for each region in the given
500     /// MIR def so that we can reuse them later in help/error messages.
501     region_names: RefCell<FxHashMap<RegionVid, RegionName>>,
502
503     /// The counter for generating new region names.
504     next_region_name: RefCell<usize>,
505
506     /// Results of Polonius analysis.
507     polonius_output: Option<Rc<PoloniusOutput>>,
508 }
509
510 // Check that:
511 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
512 // 2. loans made in overlapping scopes do not conflict
513 // 3. assignments do not affect things loaned out as immutable
514 // 4. moves do not affect things loaned out in any way
515 impl<'cx, 'tcx> dataflow::generic::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
516     type FlowState = Flows<'cx, 'tcx>;
517
518     fn visit_statement(
519         &mut self,
520         flow_state: &Flows<'cx, 'tcx>,
521         stmt: &'cx Statement<'tcx>,
522         location: Location,
523     ) {
524         debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state);
525         let span = stmt.source_info.span;
526
527         self.check_activations(location, span, flow_state);
528
529         match stmt.kind {
530             StatementKind::Assign(box (ref lhs, ref rhs)) => {
531                 self.consume_rvalue(location, (rhs, span), flow_state);
532
533                 self.mutate_place(location, (lhs, span), Shallow(None), JustWrite, flow_state);
534             }
535             StatementKind::FakeRead(_, box ref place) => {
536                 // Read for match doesn't access any memory and is used to
537                 // assert that a place is safe and live. So we don't have to
538                 // do any checks here.
539                 //
540                 // FIXME: Remove check that the place is initialized. This is
541                 // needed for now because matches don't have never patterns yet.
542                 // So this is the only place we prevent
543                 //      let x: !;
544                 //      match x {};
545                 // from compiling.
546                 self.check_if_path_or_subpath_is_moved(
547                     location,
548                     InitializationRequiringAction::Use,
549                     (place.as_ref(), span),
550                     flow_state,
551                 );
552             }
553             StatementKind::SetDiscriminant { ref place, variant_index: _ } => {
554                 self.mutate_place(location, (place, span), Shallow(None), JustWrite, flow_state);
555             }
556             StatementKind::InlineAsm(ref asm) => {
557                 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
558                     if o.is_indirect {
559                         // FIXME(eddyb) indirect inline asm outputs should
560                         // be encoded through MIR place derefs instead.
561                         self.access_place(
562                             location,
563                             (output, o.span),
564                             (Deep, Read(ReadKind::Copy)),
565                             LocalMutationIsAllowed::No,
566                             flow_state,
567                         );
568                         self.check_if_path_or_subpath_is_moved(
569                             location,
570                             InitializationRequiringAction::Use,
571                             (output.as_ref(), o.span),
572                             flow_state,
573                         );
574                     } else {
575                         self.mutate_place(
576                             location,
577                             (output, o.span),
578                             if o.is_rw { Deep } else { Shallow(None) },
579                             if o.is_rw { WriteAndRead } else { JustWrite },
580                             flow_state,
581                         );
582                     }
583                 }
584                 for (_, input) in asm.inputs.iter() {
585                     self.consume_operand(location, (input, span), flow_state);
586                 }
587             }
588             StatementKind::Nop
589             | StatementKind::AscribeUserType(..)
590             | StatementKind::Retag { .. }
591             | StatementKind::StorageLive(..) => {
592                 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
593                 // to borrow check.
594             }
595             StatementKind::StorageDead(local) => {
596                 self.access_place(
597                     location,
598                     (&Place::from(local), span),
599                     (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
600                     LocalMutationIsAllowed::Yes,
601                     flow_state,
602                 );
603             }
604         }
605     }
606
607     fn visit_terminator(
608         &mut self,
609         flow_state: &Flows<'cx, 'tcx>,
610         term: &'cx Terminator<'tcx>,
611         loc: Location,
612     ) {
613         debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
614         let span = term.source_info.span;
615
616         self.check_activations(loc, span, flow_state);
617
618         match term.kind {
619             TerminatorKind::SwitchInt { ref discr, switch_ty: _, values: _, targets: _ } => {
620                 self.consume_operand(loc, (discr, span), flow_state);
621             }
622             TerminatorKind::Drop { location: ref drop_place, target: _, unwind: _ } => {
623                 let tcx = self.infcx.tcx;
624
625                 // Compute the type with accurate region information.
626                 let drop_place_ty = drop_place.ty(*self.body, self.infcx.tcx);
627
628                 // Erase the regions.
629                 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
630
631                 // "Lift" into the tcx -- once regions are erased, this type should be in the
632                 // global arenas; this "lift" operation basically just asserts that is true, but
633                 // that is useful later.
634                 tcx.lift(&drop_place_ty).unwrap();
635
636                 debug!(
637                     "visit_terminator_drop \
638                      loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
639                     loc, term, drop_place, drop_place_ty, span
640                 );
641
642                 self.access_place(
643                     loc,
644                     (drop_place, span),
645                     (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
646                     LocalMutationIsAllowed::Yes,
647                     flow_state,
648                 );
649             }
650             TerminatorKind::DropAndReplace {
651                 location: ref drop_place,
652                 value: ref new_value,
653                 target: _,
654                 unwind: _,
655             } => {
656                 self.mutate_place(loc, (drop_place, span), Deep, JustWrite, flow_state);
657                 self.consume_operand(loc, (new_value, span), flow_state);
658             }
659             TerminatorKind::Call {
660                 ref func,
661                 ref args,
662                 ref destination,
663                 cleanup: _,
664                 from_hir_call: _,
665             } => {
666                 self.consume_operand(loc, (func, span), flow_state);
667                 for arg in args {
668                     self.consume_operand(loc, (arg, span), flow_state);
669                 }
670                 if let Some((ref dest, _ /*bb*/)) = *destination {
671                     self.mutate_place(loc, (dest, span), Deep, JustWrite, flow_state);
672                 }
673             }
674             TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
675                 self.consume_operand(loc, (cond, span), flow_state);
676                 use rustc::mir::AssertKind;
677                 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
678                     self.consume_operand(loc, (len, span), flow_state);
679                     self.consume_operand(loc, (index, span), flow_state);
680                 }
681             }
682
683             TerminatorKind::Yield { ref value, resume: _, ref resume_arg, drop: _ } => {
684                 self.consume_operand(loc, (value, span), flow_state);
685                 self.mutate_place(loc, (resume_arg, span), Deep, JustWrite, flow_state);
686             }
687
688             TerminatorKind::Goto { target: _ }
689             | TerminatorKind::Abort
690             | TerminatorKind::Unreachable
691             | TerminatorKind::Resume
692             | TerminatorKind::Return
693             | TerminatorKind::GeneratorDrop
694             | TerminatorKind::FalseEdges { real_target: _, imaginary_target: _ }
695             | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
696                 // no data used, thus irrelevant to borrowck
697             }
698         }
699     }
700
701     fn visit_terminator_exit(
702         &mut self,
703         flow_state: &Flows<'cx, 'tcx>,
704         term: &'cx Terminator<'tcx>,
705         loc: Location,
706     ) {
707         let span = term.source_info.span;
708
709         match term.kind {
710             TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
711                 if self.movable_generator {
712                     // Look for any active borrows to locals
713                     let borrow_set = self.borrow_set.clone();
714                     for i in flow_state.borrows.iter() {
715                         let borrow = &borrow_set[i];
716                         self.check_for_local_borrow(borrow, span);
717                     }
718                 }
719             }
720
721             TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
722                 // Returning from the function implicitly kills storage for all locals and statics.
723                 // Often, the storage will already have been killed by an explicit
724                 // StorageDead, but we don't always emit those (notably on unwind paths),
725                 // so this "extra check" serves as a kind of backup.
726                 let borrow_set = self.borrow_set.clone();
727                 for i in flow_state.borrows.iter() {
728                     let borrow = &borrow_set[i];
729                     self.check_for_invalidation_at_exit(loc, borrow, span);
730                 }
731             }
732
733             TerminatorKind::Abort
734             | TerminatorKind::Assert { .. }
735             | TerminatorKind::Call { .. }
736             | TerminatorKind::Drop { .. }
737             | TerminatorKind::DropAndReplace { .. }
738             | TerminatorKind::FalseEdges { real_target: _, imaginary_target: _ }
739             | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
740             | TerminatorKind::Goto { .. }
741             | TerminatorKind::SwitchInt { .. }
742             | TerminatorKind::Unreachable => {}
743         }
744     }
745 }
746
747 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
748 enum MutateMode {
749     JustWrite,
750     WriteAndRead,
751 }
752
753 use self::AccessDepth::{Deep, Shallow};
754 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
755
756 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
757 enum ArtificialField {
758     ArrayLength,
759     ShallowBorrow,
760 }
761
762 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
763 enum AccessDepth {
764     /// From the RFC: "A *shallow* access means that the immediate
765     /// fields reached at P are accessed, but references or pointers
766     /// found within are not dereferenced. Right now, the only access
767     /// that is shallow is an assignment like `x = ...;`, which would
768     /// be a *shallow write* of `x`."
769     Shallow(Option<ArtificialField>),
770
771     /// From the RFC: "A *deep* access means that all data reachable
772     /// through the given place may be invalidated or accesses by
773     /// this action."
774     Deep,
775
776     /// Access is Deep only when there is a Drop implementation that
777     /// can reach the data behind the reference.
778     Drop,
779 }
780
781 /// Kind of access to a value: read or write
782 /// (For informational purposes only)
783 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
784 enum ReadOrWrite {
785     /// From the RFC: "A *read* means that the existing data may be
786     /// read, but will not be changed."
787     Read(ReadKind),
788
789     /// From the RFC: "A *write* means that the data may be mutated to
790     /// new values or otherwise invalidated (for example, it could be
791     /// de-initialized, as in a move operation).
792     Write(WriteKind),
793
794     /// For two-phase borrows, we distinguish a reservation (which is treated
795     /// like a Read) from an activation (which is treated like a write), and
796     /// each of those is furthermore distinguished from Reads/Writes above.
797     Reservation(WriteKind),
798     Activation(WriteKind, BorrowIndex),
799 }
800
801 /// Kind of read access to a value
802 /// (For informational purposes only)
803 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
804 enum ReadKind {
805     Borrow(BorrowKind),
806     Copy,
807 }
808
809 /// Kind of write access to a value
810 /// (For informational purposes only)
811 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
812 enum WriteKind {
813     StorageDeadOrDrop,
814     MutableBorrow(BorrowKind),
815     Mutate,
816     Move,
817 }
818
819 /// When checking permissions for a place access, this flag is used to indicate that an immutable
820 /// local place can be mutated.
821 //
822 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
823 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
824 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
825 //   `is_declared_mutable()`.
826 // - Take flow state into consideration in `is_assignable()` for local variables.
827 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
828 enum LocalMutationIsAllowed {
829     Yes,
830     /// We want use of immutable upvars to cause a "write to immutable upvar"
831     /// error, not an "reassignment" error.
832     ExceptUpvars,
833     No,
834 }
835
836 #[derive(Copy, Clone, Debug)]
837 enum InitializationRequiringAction {
838     Update,
839     Borrow,
840     MatchOn,
841     Use,
842     Assignment,
843     PartialAssignment,
844 }
845
846 struct RootPlace<'tcx> {
847     place_local: Local,
848     place_projection: &'tcx [PlaceElem<'tcx>],
849     is_local_mutation_allowed: LocalMutationIsAllowed,
850 }
851
852 impl InitializationRequiringAction {
853     fn as_noun(self) -> &'static str {
854         match self {
855             InitializationRequiringAction::Update => "update",
856             InitializationRequiringAction::Borrow => "borrow",
857             InitializationRequiringAction::MatchOn => "use", // no good noun
858             InitializationRequiringAction::Use => "use",
859             InitializationRequiringAction::Assignment => "assign",
860             InitializationRequiringAction::PartialAssignment => "assign to part",
861         }
862     }
863
864     fn as_verb_in_past_tense(self) -> &'static str {
865         match self {
866             InitializationRequiringAction::Update => "updated",
867             InitializationRequiringAction::Borrow => "borrowed",
868             InitializationRequiringAction::MatchOn => "matched on",
869             InitializationRequiringAction::Use => "used",
870             InitializationRequiringAction::Assignment => "assigned",
871             InitializationRequiringAction::PartialAssignment => "partially assigned",
872         }
873     }
874 }
875
876 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
877     fn body(&self) -> &'cx Body<'tcx> {
878         *self.body
879     }
880
881     /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
882     /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
883     /// place is initialized and (b) it is not borrowed in some way that would prevent this
884     /// access.
885     ///
886     /// Returns `true` if an error is reported.
887     fn access_place(
888         &mut self,
889         location: Location,
890         place_span: (&Place<'tcx>, Span),
891         kind: (AccessDepth, ReadOrWrite),
892         is_local_mutation_allowed: LocalMutationIsAllowed,
893         flow_state: &Flows<'cx, 'tcx>,
894     ) {
895         let (sd, rw) = kind;
896
897         if let Activation(_, borrow_index) = rw {
898             if self.reservation_error_reported.contains(&place_span.0) {
899                 debug!(
900                     "skipping access_place for activation of invalid reservation \
901                      place: {:?} borrow_index: {:?}",
902                     place_span.0, borrow_index
903                 );
904                 return;
905             }
906         }
907
908         // Check is_empty() first because it's the common case, and doing that
909         // way we avoid the clone() call.
910         if !self.access_place_error_reported.is_empty()
911             && self.access_place_error_reported.contains(&(*place_span.0, place_span.1))
912         {
913             debug!(
914                 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
915                 place_span, kind
916             );
917             return;
918         }
919
920         let mutability_error = self.check_access_permissions(
921             place_span,
922             rw,
923             is_local_mutation_allowed,
924             flow_state,
925             location,
926         );
927         let conflict_error =
928             self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
929
930         if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
931             // Suppress this warning when there's an error being emitted for the
932             // same borrow: fixing the error is likely to fix the warning.
933             self.reservation_warnings.remove(&borrow_idx);
934         }
935
936         if conflict_error || mutability_error {
937             debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
938
939             self.access_place_error_reported.insert((*place_span.0, place_span.1));
940         }
941     }
942
943     fn check_access_for_conflict(
944         &mut self,
945         location: Location,
946         place_span: (&Place<'tcx>, Span),
947         sd: AccessDepth,
948         rw: ReadOrWrite,
949         flow_state: &Flows<'cx, 'tcx>,
950     ) -> bool {
951         debug!(
952             "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
953             location, place_span, sd, rw,
954         );
955
956         let mut error_reported = false;
957         let tcx = self.infcx.tcx;
958         let body = self.body;
959         let body: &Body<'_> = &body;
960         let borrow_set = self.borrow_set.clone();
961
962         // Use polonius output if it has been enabled.
963         let polonius_output = self.polonius_output.clone();
964         let borrows_in_scope = if let Some(polonius) = &polonius_output {
965             let location = self.location_table.start_index(location);
966             Either::Left(polonius.errors_at(location).iter().copied())
967         } else {
968             Either::Right(flow_state.borrows.iter())
969         };
970
971         each_borrow_involving_path(
972             self,
973             tcx,
974             body,
975             location,
976             (sd, place_span.0),
977             &borrow_set,
978             borrows_in_scope,
979             |this, borrow_index, borrow| match (rw, borrow.kind) {
980                 // Obviously an activation is compatible with its own
981                 // reservation (or even prior activating uses of same
982                 // borrow); so don't check if they interfere.
983                 //
984                 // NOTE: *reservations* do conflict with themselves;
985                 // thus aren't injecting unsoundenss w/ this check.)
986                 (Activation(_, activating), _) if activating == borrow_index => {
987                     debug!(
988                         "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
989                          skipping {:?} b/c activation of same borrow_index",
990                         place_span,
991                         sd,
992                         rw,
993                         (borrow_index, borrow),
994                     );
995                     Control::Continue
996                 }
997
998                 (Read(_), BorrowKind::Shared)
999                 | (Read(_), BorrowKind::Shallow)
1000                 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
1001                 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
1002                     Control::Continue
1003                 }
1004
1005                 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1006                     // Handled by initialization checks.
1007                     Control::Continue
1008                 }
1009
1010                 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
1011                     // Reading from mere reservations of mutable-borrows is OK.
1012                     if !is_active(&this.dominators, borrow, location) {
1013                         assert!(allow_two_phase_borrow(borrow.kind));
1014                         return Control::Continue;
1015                     }
1016
1017                     error_reported = true;
1018                     match kind {
1019                         ReadKind::Copy => {
1020                             this.report_use_while_mutably_borrowed(location, place_span, borrow)
1021                                 .buffer(&mut this.errors_buffer);
1022                         }
1023                         ReadKind::Borrow(bk) => {
1024                             this.report_conflicting_borrow(location, place_span, bk, borrow)
1025                                 .buffer(&mut this.errors_buffer);
1026                         }
1027                     }
1028                     Control::Break
1029                 }
1030
1031                 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
1032                 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared)
1033                     if {
1034                         tcx.migrate_borrowck()
1035                             && this.borrow_set.location_map.contains_key(&location)
1036                     } =>
1037                 {
1038                     let bi = this.borrow_set.location_map[&location];
1039                     debug!(
1040                         "recording invalid reservation of place: {:?} with \
1041                          borrow index {:?} as warning",
1042                         place_span.0, bi,
1043                     );
1044                     // rust-lang/rust#56254 - This was previously permitted on
1045                     // the 2018 edition so we emit it as a warning. We buffer
1046                     // these sepately so that we only emit a warning if borrow
1047                     // checking was otherwise successful.
1048                     this.reservation_warnings
1049                         .insert(bi, (*place_span.0, place_span.1, location, bk, borrow.clone()));
1050
1051                     // Don't suppress actual errors.
1052                     Control::Continue
1053                 }
1054
1055                 (Reservation(kind), _) | (Activation(kind, _), _) | (Write(kind), _) => {
1056                     match rw {
1057                         Reservation(..) => {
1058                             debug!(
1059                                 "recording invalid reservation of \
1060                                  place: {:?}",
1061                                 place_span.0
1062                             );
1063                             this.reservation_error_reported.insert(place_span.0.clone());
1064                         }
1065                         Activation(_, activating) => {
1066                             debug!(
1067                                 "observing check_place for activation of \
1068                                  borrow_index: {:?}",
1069                                 activating
1070                             );
1071                         }
1072                         Read(..) | Write(..) => {}
1073                     }
1074
1075                     error_reported = true;
1076                     match kind {
1077                         WriteKind::MutableBorrow(bk) => {
1078                             this.report_conflicting_borrow(location, place_span, bk, borrow)
1079                                 .buffer(&mut this.errors_buffer);
1080                         }
1081                         WriteKind::StorageDeadOrDrop => this
1082                             .report_borrowed_value_does_not_live_long_enough(
1083                                 location,
1084                                 borrow,
1085                                 place_span,
1086                                 Some(kind),
1087                             ),
1088                         WriteKind::Mutate => {
1089                             this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1090                         }
1091                         WriteKind::Move => {
1092                             this.report_move_out_while_borrowed(location, place_span, borrow)
1093                         }
1094                     }
1095                     Control::Break
1096                 }
1097             },
1098         );
1099
1100         error_reported
1101     }
1102
1103     fn mutate_place(
1104         &mut self,
1105         location: Location,
1106         place_span: (&'cx Place<'tcx>, Span),
1107         kind: AccessDepth,
1108         mode: MutateMode,
1109         flow_state: &Flows<'cx, 'tcx>,
1110     ) {
1111         // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1112         match mode {
1113             MutateMode::WriteAndRead => {
1114                 self.check_if_path_or_subpath_is_moved(
1115                     location,
1116                     InitializationRequiringAction::Update,
1117                     (place_span.0.as_ref(), place_span.1),
1118                     flow_state,
1119                 );
1120             }
1121             MutateMode::JustWrite => {
1122                 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1123             }
1124         }
1125
1126         // Special case: you can assign a immutable local variable
1127         // (e.g., `x = ...`) so long as it has never been initialized
1128         // before (at this point in the flow).
1129         if let Some(local) = place_span.0.as_local() {
1130             if let Mutability::Not = self.body.local_decls[local].mutability {
1131                 // check for reassignments to immutable local variables
1132                 self.check_if_reassignment_to_immutable_state(
1133                     location, local, place_span, flow_state,
1134                 );
1135                 return;
1136             }
1137         }
1138
1139         // Otherwise, use the normal access permission rules.
1140         self.access_place(
1141             location,
1142             place_span,
1143             (kind, Write(WriteKind::Mutate)),
1144             LocalMutationIsAllowed::No,
1145             flow_state,
1146         );
1147     }
1148
1149     fn consume_rvalue(
1150         &mut self,
1151         location: Location,
1152         (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1153         flow_state: &Flows<'cx, 'tcx>,
1154     ) {
1155         match *rvalue {
1156             Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1157                 let access_kind = match bk {
1158                     BorrowKind::Shallow => {
1159                         (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1160                     }
1161                     BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1162                     BorrowKind::Unique | BorrowKind::Mut { .. } => {
1163                         let wk = WriteKind::MutableBorrow(bk);
1164                         if allow_two_phase_borrow(bk) {
1165                             (Deep, Reservation(wk))
1166                         } else {
1167                             (Deep, Write(wk))
1168                         }
1169                     }
1170                 };
1171
1172                 self.access_place(
1173                     location,
1174                     (place, span),
1175                     access_kind,
1176                     LocalMutationIsAllowed::No,
1177                     flow_state,
1178                 );
1179
1180                 let action = if bk == BorrowKind::Shallow {
1181                     InitializationRequiringAction::MatchOn
1182                 } else {
1183                     InitializationRequiringAction::Borrow
1184                 };
1185
1186                 self.check_if_path_or_subpath_is_moved(
1187                     location,
1188                     action,
1189                     (place.as_ref(), span),
1190                     flow_state,
1191                 );
1192             }
1193
1194             Rvalue::AddressOf(mutability, ref place) => {
1195                 let access_kind = match mutability {
1196                     Mutability::Mut => (
1197                         Deep,
1198                         Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1199                             allow_two_phase_borrow: false,
1200                         })),
1201                     ),
1202                     Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1203                 };
1204
1205                 self.access_place(
1206                     location,
1207                     (place, span),
1208                     access_kind,
1209                     LocalMutationIsAllowed::No,
1210                     flow_state,
1211                 );
1212
1213                 self.check_if_path_or_subpath_is_moved(
1214                     location,
1215                     InitializationRequiringAction::Borrow,
1216                     (place.as_ref(), span),
1217                     flow_state,
1218                 );
1219             }
1220
1221             Rvalue::Use(ref operand)
1222             | Rvalue::Repeat(ref operand, _)
1223             | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1224             | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1225                 self.consume_operand(location, (operand, span), flow_state)
1226             }
1227
1228             Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1229                 let af = match *rvalue {
1230                     Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1231                     Rvalue::Discriminant(..) => None,
1232                     _ => unreachable!(),
1233                 };
1234                 self.access_place(
1235                     location,
1236                     (place, span),
1237                     (Shallow(af), Read(ReadKind::Copy)),
1238                     LocalMutationIsAllowed::No,
1239                     flow_state,
1240                 );
1241                 self.check_if_path_or_subpath_is_moved(
1242                     location,
1243                     InitializationRequiringAction::Use,
1244                     (place.as_ref(), span),
1245                     flow_state,
1246                 );
1247             }
1248
1249             Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1250             | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1251                 self.consume_operand(location, (operand1, span), flow_state);
1252                 self.consume_operand(location, (operand2, span), flow_state);
1253             }
1254
1255             Rvalue::NullaryOp(_op, _ty) => {
1256                 // nullary ops take no dynamic input; no borrowck effect.
1257                 //
1258                 // FIXME: is above actually true? Do we want to track
1259                 // the fact that uninitialized data can be created via
1260                 // `NullOp::Box`?
1261             }
1262
1263             Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1264                 // We need to report back the list of mutable upvars that were
1265                 // moved into the closure and subsequently used by the closure,
1266                 // in order to populate our used_mut set.
1267                 match **aggregate_kind {
1268                     AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
1269                         let BorrowCheckResult { used_mut_upvars, .. } =
1270                             self.infcx.tcx.mir_borrowck(def_id);
1271                         debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1272                         for field in used_mut_upvars {
1273                             self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1274                         }
1275                     }
1276                     AggregateKind::Adt(..)
1277                     | AggregateKind::Array(..)
1278                     | AggregateKind::Tuple { .. } => (),
1279                 }
1280
1281                 for operand in operands {
1282                     self.consume_operand(location, (operand, span), flow_state);
1283                 }
1284             }
1285         }
1286     }
1287
1288     fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1289         let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1290             if !place.projection.is_empty() {
1291                 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1292                     this.used_mut_upvars.push(field);
1293                 }
1294             } else {
1295                 this.used_mut.insert(place.local);
1296             }
1297         };
1298
1299         // This relies on the current way that by-value
1300         // captures of a closure are copied/moved directly
1301         // when generating MIR.
1302         match *operand {
1303             Operand::Move(ref place) | Operand::Copy(ref place) => {
1304                 match place.as_local() {
1305                     Some(local) if !self.body.local_decls[local].is_user_variable() => {
1306                         if self.body.local_decls[local].ty.is_mutable_ptr() {
1307                             // The variable will be marked as mutable by the borrow.
1308                             return;
1309                         }
1310                         // This is an edge case where we have a `move` closure
1311                         // inside a non-move closure, and the inner closure
1312                         // contains a mutation:
1313                         //
1314                         // let mut i = 0;
1315                         // || { move || { i += 1; }; };
1316                         //
1317                         // In this case our usual strategy of assuming that the
1318                         // variable will be captured by mutable reference is
1319                         // wrong, since `i` can be copied into the inner
1320                         // closure from a shared reference.
1321                         //
1322                         // As such we have to search for the local that this
1323                         // capture comes from and mark it as being used as mut.
1324
1325                         let temp_mpi = self.move_data.rev_lookup.find_local(local);
1326                         let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1327                             &self.move_data.inits[init_index]
1328                         } else {
1329                             bug!("temporary should be initialized exactly once")
1330                         };
1331
1332                         let loc = match init.location {
1333                             InitLocation::Statement(stmt) => stmt,
1334                             _ => bug!("temporary initialized in arguments"),
1335                         };
1336
1337                         let body = self.body;
1338                         let bbd = &body[loc.block];
1339                         let stmt = &bbd.statements[loc.statement_index];
1340                         debug!("temporary assigned in: stmt={:?}", stmt);
1341
1342                         if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, ref source))) =
1343                             stmt.kind
1344                         {
1345                             propagate_closure_used_mut_place(self, source);
1346                         } else {
1347                             bug!(
1348                                 "closures should only capture user variables \
1349                                  or references to user variables"
1350                             );
1351                         }
1352                     }
1353                     _ => propagate_closure_used_mut_place(self, place),
1354                 }
1355             }
1356             Operand::Constant(..) => {}
1357         }
1358     }
1359
1360     fn consume_operand(
1361         &mut self,
1362         location: Location,
1363         (operand, span): (&'cx Operand<'tcx>, Span),
1364         flow_state: &Flows<'cx, 'tcx>,
1365     ) {
1366         match *operand {
1367             Operand::Copy(ref place) => {
1368                 // copy of place: check if this is "copy of frozen path"
1369                 // (FIXME: see check_loans.rs)
1370                 self.access_place(
1371                     location,
1372                     (place, span),
1373                     (Deep, Read(ReadKind::Copy)),
1374                     LocalMutationIsAllowed::No,
1375                     flow_state,
1376                 );
1377
1378                 // Finally, check if path was already moved.
1379                 self.check_if_path_or_subpath_is_moved(
1380                     location,
1381                     InitializationRequiringAction::Use,
1382                     (place.as_ref(), span),
1383                     flow_state,
1384                 );
1385             }
1386             Operand::Move(ref place) => {
1387                 // move of place: check if this is move of already borrowed path
1388                 self.access_place(
1389                     location,
1390                     (place, span),
1391                     (Deep, Write(WriteKind::Move)),
1392                     LocalMutationIsAllowed::Yes,
1393                     flow_state,
1394                 );
1395
1396                 // Finally, check if path was already moved.
1397                 self.check_if_path_or_subpath_is_moved(
1398                     location,
1399                     InitializationRequiringAction::Use,
1400                     (place.as_ref(), span),
1401                     flow_state,
1402                 );
1403             }
1404             Operand::Constant(_) => {}
1405         }
1406     }
1407
1408     /// Checks whether a borrow of this place is invalidated when the function
1409     /// exits
1410     fn check_for_invalidation_at_exit(
1411         &mut self,
1412         location: Location,
1413         borrow: &BorrowData<'tcx>,
1414         span: Span,
1415     ) {
1416         debug!("check_for_invalidation_at_exit({:?})", borrow);
1417         let place = &borrow.borrowed_place;
1418         let mut root_place = PlaceRef { local: place.local, projection: &[] };
1419
1420         // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1421         // we just know that all locals are dropped at function exit (otherwise
1422         // we'll have a memory leak) and assume that all statics have a destructor.
1423         //
1424         // FIXME: allow thread-locals to borrow other thread locals?
1425
1426         let (might_be_alive, will_be_dropped) =
1427             if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1428                 // Thread-locals might be dropped after the function exits
1429                 // We have to dereference the outer reference because
1430                 // borrows don't conflict behind shared references.
1431                 root_place.projection = DEREF_PROJECTION;
1432                 (true, true)
1433             } else {
1434                 (false, self.locals_are_invalidated_at_exit)
1435             };
1436
1437         if !will_be_dropped {
1438             debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
1439             return;
1440         }
1441
1442         let sd = if might_be_alive { Deep } else { Shallow(None) };
1443
1444         if places_conflict::borrow_conflicts_with_place(
1445             self.infcx.tcx,
1446             &self.body,
1447             place,
1448             borrow.kind,
1449             root_place,
1450             sd,
1451             places_conflict::PlaceConflictBias::Overlap,
1452         ) {
1453             debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1454             // FIXME: should be talking about the region lifetime instead
1455             // of just a span here.
1456             let span = self.infcx.tcx.sess.source_map().end_point(span);
1457             self.report_borrowed_value_does_not_live_long_enough(
1458                 location,
1459                 borrow,
1460                 (place, span),
1461                 None,
1462             )
1463         }
1464     }
1465
1466     /// Reports an error if this is a borrow of local data.
1467     /// This is called for all Yield expressions on movable generators
1468     fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1469         debug!("check_for_local_borrow({:?})", borrow);
1470
1471         if borrow_of_local_data(&borrow.borrowed_place) {
1472             let err = self.cannot_borrow_across_generator_yield(
1473                 self.retrieve_borrow_spans(borrow).var_or_use(),
1474                 yield_span,
1475             );
1476
1477             err.buffer(&mut self.errors_buffer);
1478         }
1479     }
1480
1481     fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1482         // Two-phase borrow support: For each activation that is newly
1483         // generated at this statement, check if it interferes with
1484         // another borrow.
1485         let borrow_set = self.borrow_set.clone();
1486         for &borrow_index in borrow_set.activations_at_location(location) {
1487             let borrow = &borrow_set[borrow_index];
1488
1489             // only mutable borrows should be 2-phase
1490             assert!(match borrow.kind {
1491                 BorrowKind::Shared | BorrowKind::Shallow => false,
1492                 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1493             });
1494
1495             self.access_place(
1496                 location,
1497                 (&borrow.borrowed_place, span),
1498                 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1499                 LocalMutationIsAllowed::No,
1500                 flow_state,
1501             );
1502             // We do not need to call `check_if_path_or_subpath_is_moved`
1503             // again, as we already called it when we made the
1504             // initial reservation.
1505         }
1506     }
1507
1508     fn check_if_reassignment_to_immutable_state(
1509         &mut self,
1510         location: Location,
1511         local: Local,
1512         place_span: (&Place<'tcx>, Span),
1513         flow_state: &Flows<'cx, 'tcx>,
1514     ) {
1515         debug!("check_if_reassignment_to_immutable_state({:?})", local);
1516
1517         // Check if any of the initializiations of `local` have happened yet:
1518         if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1519             // And, if so, report an error.
1520             let init = &self.move_data.inits[init_index];
1521             let span = init.span(&self.body);
1522             self.report_illegal_reassignment(location, place_span, span, place_span.0);
1523         }
1524     }
1525
1526     fn check_if_full_path_is_moved(
1527         &mut self,
1528         location: Location,
1529         desired_action: InitializationRequiringAction,
1530         place_span: (PlaceRef<'tcx>, Span),
1531         flow_state: &Flows<'cx, 'tcx>,
1532     ) {
1533         let maybe_uninits = &flow_state.uninits;
1534
1535         // Bad scenarios:
1536         //
1537         // 1. Move of `a.b.c`, use of `a.b.c`
1538         // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1539         // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1540         //    partial initialization support, one might have `a.x`
1541         //    initialized but not `a.b`.
1542         //
1543         // OK scenarios:
1544         //
1545         // 4. Move of `a.b.c`, use of `a.b.d`
1546         // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1547         // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1548         //    must have been initialized for the use to be sound.
1549         // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1550
1551         // The dataflow tracks shallow prefixes distinctly (that is,
1552         // field-accesses on P distinctly from P itself), in order to
1553         // track substructure initialization separately from the whole
1554         // structure.
1555         //
1556         // E.g., when looking at (*a.b.c).d, if the closest prefix for
1557         // which we have a MovePath is `a.b`, then that means that the
1558         // initialization state of `a.b` is all we need to inspect to
1559         // know if `a.b.c` is valid (and from that we infer that the
1560         // dereference and `.d` access is also valid, since we assume
1561         // `a.b.c` is assigned a reference to a initialized and
1562         // well-formed record structure.)
1563
1564         // Therefore, if we seek out the *closest* prefix for which we
1565         // have a MovePath, that should capture the initialization
1566         // state for the place scenario.
1567         //
1568         // This code covers scenarios 1, 2, and 3.
1569
1570         debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1571         let (prefix, mpi) = self.move_path_closest_to(place_span.0);
1572         if maybe_uninits.contains(mpi) {
1573             self.report_use_of_moved_or_uninitialized(
1574                 location,
1575                 desired_action,
1576                 (prefix, place_span.0, place_span.1),
1577                 mpi,
1578             );
1579         } // Only query longest prefix with a MovePath, not further
1580         // ancestors; dataflow recurs on children when parents
1581         // move (to support partial (re)inits).
1582         //
1583         // (I.e., querying parents breaks scenario 7; but may want
1584         // to do such a query based on partial-init feature-gate.)
1585     }
1586
1587     /// Subslices correspond to multiple move paths, so we iterate through the
1588     /// elements of the base array. For each element we check
1589     ///
1590     /// * Does this element overlap with our slice.
1591     /// * Is any part of it uninitialized.
1592     fn check_if_subslice_element_is_moved(
1593         &mut self,
1594         location: Location,
1595         desired_action: InitializationRequiringAction,
1596         place_span: (PlaceRef<'tcx>, Span),
1597         maybe_uninits: &BitSet<MovePathIndex>,
1598         from: u32,
1599         to: u32,
1600     ) {
1601         if let Some(mpi) = self.move_path_for_place(place_span.0) {
1602             let move_paths = &self.move_data.move_paths;
1603
1604             let root_path = &move_paths[mpi];
1605             for (child_mpi, child_move_path) in root_path.children(move_paths) {
1606                 let last_proj = child_move_path.place.projection.last().unwrap();
1607                 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
1608                     debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
1609
1610                     if (from..to).contains(offset) {
1611                         let uninit_child =
1612                             self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
1613                                 maybe_uninits.contains(mpi)
1614                             });
1615
1616                         if let Some(uninit_child) = uninit_child {
1617                             self.report_use_of_moved_or_uninitialized(
1618                                 location,
1619                                 desired_action,
1620                                 (place_span.0, place_span.0, place_span.1),
1621                                 uninit_child,
1622                             );
1623                             return; // don't bother finding other problems.
1624                         }
1625                     }
1626                 }
1627             }
1628         }
1629     }
1630
1631     fn check_if_path_or_subpath_is_moved(
1632         &mut self,
1633         location: Location,
1634         desired_action: InitializationRequiringAction,
1635         place_span: (PlaceRef<'tcx>, Span),
1636         flow_state: &Flows<'cx, 'tcx>,
1637     ) {
1638         let maybe_uninits = &flow_state.uninits;
1639
1640         // Bad scenarios:
1641         //
1642         // 1. Move of `a.b.c`, use of `a` or `a.b`
1643         //    partial initialization support, one might have `a.x`
1644         //    initialized but not `a.b`.
1645         // 2. All bad scenarios from `check_if_full_path_is_moved`
1646         //
1647         // OK scenarios:
1648         //
1649         // 3. Move of `a.b.c`, use of `a.b.d`
1650         // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1651         // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1652         //    must have been initialized for the use to be sound.
1653         // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1654
1655         self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1656
1657         if let [base_proj @ .., ProjectionElem::Subslice { from, to, from_end: false }] =
1658             place_span.0.projection
1659         {
1660             let place_ty =
1661                 Place::ty_from(place_span.0.local, base_proj, self.body(), self.infcx.tcx);
1662             if let ty::Array(..) = place_ty.ty.kind {
1663                 let array_place = PlaceRef { local: place_span.0.local, projection: base_proj };
1664                 self.check_if_subslice_element_is_moved(
1665                     location,
1666                     desired_action,
1667                     (array_place, place_span.1),
1668                     maybe_uninits,
1669                     *from,
1670                     *to,
1671                 );
1672                 return;
1673             }
1674         }
1675
1676         // A move of any shallow suffix of `place` also interferes
1677         // with an attempt to use `place`. This is scenario 3 above.
1678         //
1679         // (Distinct from handling of scenarios 1+2+4 above because
1680         // `place` does not interfere with suffixes of its prefixes,
1681         // e.g., `a.b.c` does not interfere with `a.b.d`)
1682         //
1683         // This code covers scenario 1.
1684
1685         debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1686         if let Some(mpi) = self.move_path_for_place(place_span.0) {
1687             let uninit_mpi = self
1688                 .move_data
1689                 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
1690
1691             if let Some(uninit_mpi) = uninit_mpi {
1692                 self.report_use_of_moved_or_uninitialized(
1693                     location,
1694                     desired_action,
1695                     (place_span.0, place_span.0, place_span.1),
1696                     uninit_mpi,
1697                 );
1698                 return; // don't bother finding other problems.
1699             }
1700         }
1701     }
1702
1703     /// Currently MoveData does not store entries for all places in
1704     /// the input MIR. For example it will currently filter out
1705     /// places that are Copy; thus we do not track places of shared
1706     /// reference type. This routine will walk up a place along its
1707     /// prefixes, searching for a foundational place that *is*
1708     /// tracked in the MoveData.
1709     ///
1710     /// An Err result includes a tag indicated why the search failed.
1711     /// Currently this can only occur if the place is built off of a
1712     /// static variable, as we do not track those in the MoveData.
1713     fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
1714         match self.move_data.rev_lookup.find(place) {
1715             LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
1716                 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
1717             }
1718             LookupResult::Parent(None) => panic!("should have move path for every Local"),
1719         }
1720     }
1721
1722     fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
1723         // If returns None, then there is no move path corresponding
1724         // to a direct owner of `place` (which means there is nothing
1725         // that borrowck tracks for its analysis).
1726
1727         match self.move_data.rev_lookup.find(place) {
1728             LookupResult::Parent(_) => None,
1729             LookupResult::Exact(mpi) => Some(mpi),
1730         }
1731     }
1732
1733     fn check_if_assigned_path_is_moved(
1734         &mut self,
1735         location: Location,
1736         (place, span): (&'cx Place<'tcx>, Span),
1737         flow_state: &Flows<'cx, 'tcx>,
1738     ) {
1739         debug!("check_if_assigned_path_is_moved place: {:?}", place);
1740
1741         // None case => assigning to `x` does not require `x` be initialized.
1742         let mut cursor = &*place.projection.as_ref();
1743         while let [proj_base @ .., elem] = cursor {
1744             cursor = proj_base;
1745
1746             match elem {
1747                 ProjectionElem::Index(_/*operand*/) |
1748                 ProjectionElem::ConstantIndex { .. } |
1749                 // assigning to P[i] requires P to be valid.
1750                 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1751                 // assigning to (P->variant) is okay if assigning to `P` is okay
1752                 //
1753                 // FIXME: is this true even if P is a adt with a dtor?
1754                 { }
1755
1756                 // assigning to (*P) requires P to be initialized
1757                 ProjectionElem::Deref => {
1758                     self.check_if_full_path_is_moved(
1759                         location, InitializationRequiringAction::Use,
1760                         (PlaceRef {
1761                             local: place.local,
1762                             projection: proj_base,
1763                         }, span), flow_state);
1764                     // (base initialized; no need to
1765                     // recur further)
1766                     break;
1767                 }
1768
1769                 ProjectionElem::Subslice { .. } => {
1770                     panic!("we don't allow assignments to subslices, location: {:?}",
1771                            location);
1772                 }
1773
1774                 ProjectionElem::Field(..) => {
1775                     // if type of `P` has a dtor, then
1776                     // assigning to `P.f` requires `P` itself
1777                     // be already initialized
1778                     let tcx = self.infcx.tcx;
1779                     let base_ty = Place::ty_from(place.local, proj_base, self.body(), tcx).ty;
1780                     match base_ty.kind {
1781                         ty::Adt(def, _) if def.has_dtor(tcx) => {
1782                             self.check_if_path_or_subpath_is_moved(
1783                                 location, InitializationRequiringAction::Assignment,
1784                                 (PlaceRef {
1785                                     local: place.local,
1786                                     projection: proj_base,
1787                                 }, span), flow_state);
1788
1789                             // (base initialized; no need to
1790                             // recur further)
1791                             break;
1792                         }
1793
1794                         // Once `let s; s.x = V; read(s.x);`,
1795                         // is allowed, remove this match arm.
1796                         ty::Adt(..) | ty::Tuple(..) => {
1797                             check_parent_of_field(self, location, PlaceRef {
1798                                 local: place.local,
1799                                 projection: proj_base,
1800                             }, span, flow_state);
1801
1802                             // rust-lang/rust#21232, #54499, #54986: during period where we reject
1803                             // partial initialization, do not complain about unnecessary `mut` on
1804                             // an attempt to do a partial initialization.
1805                             self.used_mut.insert(place.local);
1806                         }
1807
1808                         _ => {}
1809                     }
1810                 }
1811             }
1812         }
1813
1814         fn check_parent_of_field<'cx, 'tcx>(
1815             this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1816             location: Location,
1817             base: PlaceRef<'tcx>,
1818             span: Span,
1819             flow_state: &Flows<'cx, 'tcx>,
1820         ) {
1821             // rust-lang/rust#21232: Until Rust allows reads from the
1822             // initialized parts of partially initialized structs, we
1823             // will, starting with the 2018 edition, reject attempts
1824             // to write to structs that are not fully initialized.
1825             //
1826             // In other words, *until* we allow this:
1827             //
1828             // 1. `let mut s; s.x = Val; read(s.x);`
1829             //
1830             // we will for now disallow this:
1831             //
1832             // 2. `let mut s; s.x = Val;`
1833             //
1834             // and also this:
1835             //
1836             // 3. `let mut s = ...; drop(s); s.x=Val;`
1837             //
1838             // This does not use check_if_path_or_subpath_is_moved,
1839             // because we want to *allow* reinitializations of fields:
1840             // e.g., want to allow
1841             //
1842             // `let mut s = ...; drop(s.x); s.x=Val;`
1843             //
1844             // This does not use check_if_full_path_is_moved on
1845             // `base`, because that would report an error about the
1846             // `base` as a whole, but in this scenario we *really*
1847             // want to report an error about the actual thing that was
1848             // moved, which may be some prefix of `base`.
1849
1850             // Shallow so that we'll stop at any dereference; we'll
1851             // report errors about issues with such bases elsewhere.
1852             let maybe_uninits = &flow_state.uninits;
1853
1854             // Find the shortest uninitialized prefix you can reach
1855             // without going over a Deref.
1856             let mut shortest_uninit_seen = None;
1857             for prefix in this.prefixes(base, PrefixSet::Shallow) {
1858                 let mpi = match this.move_path_for_place(prefix) {
1859                     Some(mpi) => mpi,
1860                     None => continue,
1861                 };
1862
1863                 if maybe_uninits.contains(mpi) {
1864                     debug!(
1865                         "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1866                         shortest_uninit_seen,
1867                         Some((prefix, mpi))
1868                     );
1869                     shortest_uninit_seen = Some((prefix, mpi));
1870                 } else {
1871                     debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1872                 }
1873             }
1874
1875             if let Some((prefix, mpi)) = shortest_uninit_seen {
1876                 // Check for a reassignment into a uninitialized field of a union (for example,
1877                 // after a move out). In this case, do not report a error here. There is an
1878                 // exception, if this is the first assignment into the union (that is, there is
1879                 // no move out from an earlier location) then this is an attempt at initialization
1880                 // of the union - we should error in that case.
1881                 let tcx = this.infcx.tcx;
1882                 if let ty::Adt(def, _) =
1883                     Place::ty_from(base.local, base.projection, this.body(), tcx).ty.kind
1884                 {
1885                     if def.is_union() {
1886                         if this.move_data.path_map[mpi].iter().any(|moi| {
1887                             this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
1888                         }) {
1889                             return;
1890                         }
1891                     }
1892                 }
1893
1894                 this.report_use_of_moved_or_uninitialized(
1895                     location,
1896                     InitializationRequiringAction::PartialAssignment,
1897                     (prefix, base, span),
1898                     mpi,
1899                 );
1900             }
1901         }
1902     }
1903
1904     /// Checks the permissions for the given place and read or write kind
1905     ///
1906     /// Returns `true` if an error is reported.
1907     fn check_access_permissions(
1908         &mut self,
1909         (place, span): (&Place<'tcx>, Span),
1910         kind: ReadOrWrite,
1911         is_local_mutation_allowed: LocalMutationIsAllowed,
1912         flow_state: &Flows<'cx, 'tcx>,
1913         location: Location,
1914     ) -> bool {
1915         debug!(
1916             "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1917             place, kind, is_local_mutation_allowed
1918         );
1919
1920         let error_access;
1921         let the_place_err;
1922
1923         match kind {
1924             Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1925             | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
1926             | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1927             | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. })) => {
1928                 let is_local_mutation_allowed = match borrow_kind {
1929                     BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1930                     BorrowKind::Mut { .. } => is_local_mutation_allowed,
1931                     BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1932                 };
1933                 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1934                     Ok(root_place) => {
1935                         self.add_used_mut(root_place, flow_state);
1936                         return false;
1937                     }
1938                     Err(place_err) => {
1939                         error_access = AccessKind::MutableBorrow;
1940                         the_place_err = place_err;
1941                     }
1942                 }
1943             }
1944             Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1945                 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1946                     Ok(root_place) => {
1947                         self.add_used_mut(root_place, flow_state);
1948                         return false;
1949                     }
1950                     Err(place_err) => {
1951                         error_access = AccessKind::Mutate;
1952                         the_place_err = place_err;
1953                     }
1954                 }
1955             }
1956
1957             Reservation(WriteKind::Move)
1958             | Write(WriteKind::Move)
1959             | Reservation(WriteKind::StorageDeadOrDrop)
1960             | Reservation(WriteKind::MutableBorrow(BorrowKind::Shared))
1961             | Reservation(WriteKind::MutableBorrow(BorrowKind::Shallow))
1962             | Write(WriteKind::StorageDeadOrDrop)
1963             | Write(WriteKind::MutableBorrow(BorrowKind::Shared))
1964             | Write(WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
1965                 if let (Err(_), true) = (
1966                     self.is_mutable(place.as_ref(), is_local_mutation_allowed),
1967                     self.errors_buffer.is_empty(),
1968                 ) {
1969                     // rust-lang/rust#46908: In pure NLL mode this code path should be
1970                     // unreachable, but we use `delay_span_bug` because we can hit this when
1971                     // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
1972                     // enabled. We don't want to ICE for that case, as other errors will have
1973                     // been emitted (#52262).
1974                     self.infcx.tcx.sess.delay_span_bug(
1975                         span,
1976                         &format!(
1977                             "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
1978                             place, kind,
1979                         ),
1980                     );
1981                 }
1982                 return false;
1983             }
1984             Activation(..) => {
1985                 // permission checks are done at Reservation point.
1986                 return false;
1987             }
1988             Read(ReadKind::Borrow(BorrowKind::Unique))
1989             | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
1990             | Read(ReadKind::Borrow(BorrowKind::Shared))
1991             | Read(ReadKind::Borrow(BorrowKind::Shallow))
1992             | Read(ReadKind::Copy) => {
1993                 // Access authorized
1994                 return false;
1995             }
1996         }
1997
1998         // rust-lang/rust#21232, #54986: during period where we reject
1999         // partial initialization, do not complain about mutability
2000         // errors except for actual mutation (as opposed to an attempt
2001         // to do a partial initialization).
2002         let previously_initialized =
2003             self.is_local_ever_initialized(place.local, flow_state).is_some();
2004
2005         // at this point, we have set up the error reporting state.
2006         if previously_initialized {
2007             self.report_mutability_error(place, span, the_place_err, error_access, location);
2008             true
2009         } else {
2010             false
2011         }
2012     }
2013
2014     fn is_local_ever_initialized(
2015         &self,
2016         local: Local,
2017         flow_state: &Flows<'cx, 'tcx>,
2018     ) -> Option<InitIndex> {
2019         let mpi = self.move_data.rev_lookup.find_local(local);
2020         let ii = &self.move_data.init_path_map[mpi];
2021         for &index in ii {
2022             if flow_state.ever_inits.contains(index) {
2023                 return Some(index);
2024             }
2025         }
2026         None
2027     }
2028
2029     /// Adds the place into the used mutable variables set
2030     fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2031         match root_place {
2032             RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2033                 // If the local may have been initialized, and it is now currently being
2034                 // mutated, then it is justified to be annotated with the `mut`
2035                 // keyword, since the mutation may be a possible reassignment.
2036                 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2037                     && self.is_local_ever_initialized(local, flow_state).is_some()
2038                 {
2039                     self.used_mut.insert(local);
2040                 }
2041             }
2042             RootPlace {
2043                 place_local: _,
2044                 place_projection: _,
2045                 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2046             } => {}
2047             RootPlace {
2048                 place_local,
2049                 place_projection: place_projection @ [.., _],
2050                 is_local_mutation_allowed: _,
2051             } => {
2052                 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2053                     local: place_local,
2054                     projection: place_projection,
2055                 }) {
2056                     self.used_mut_upvars.push(field);
2057                 }
2058             }
2059         }
2060     }
2061
2062     /// Whether this value can be written or borrowed mutably.
2063     /// Returns the root place if the place passed in is a projection.
2064     fn is_mutable(
2065         &self,
2066         place: PlaceRef<'tcx>,
2067         is_local_mutation_allowed: LocalMutationIsAllowed,
2068     ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2069         match place {
2070             PlaceRef { local, projection: [] } => {
2071                 let local = &self.body.local_decls[local];
2072                 match local.mutability {
2073                     Mutability::Not => match is_local_mutation_allowed {
2074                         LocalMutationIsAllowed::Yes => Ok(RootPlace {
2075                             place_local: place.local,
2076                             place_projection: place.projection,
2077                             is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2078                         }),
2079                         LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2080                             place_local: place.local,
2081                             place_projection: place.projection,
2082                             is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2083                         }),
2084                         LocalMutationIsAllowed::No => Err(place),
2085                     },
2086                     Mutability::Mut => Ok(RootPlace {
2087                         place_local: place.local,
2088                         place_projection: place.projection,
2089                         is_local_mutation_allowed,
2090                     }),
2091                 }
2092             }
2093             PlaceRef { local: _, projection: [proj_base @ .., elem] } => {
2094                 match elem {
2095                     ProjectionElem::Deref => {
2096                         let base_ty =
2097                             Place::ty_from(place.local, proj_base, self.body(), self.infcx.tcx).ty;
2098
2099                         // Check the kind of deref to decide
2100                         match base_ty.kind {
2101                             ty::Ref(_, _, mutbl) => {
2102                                 match mutbl {
2103                                     // Shared borrowed data is never mutable
2104                                     hir::Mutability::Not => Err(place),
2105                                     // Mutably borrowed data is mutable, but only if we have a
2106                                     // unique path to the `&mut`
2107                                     hir::Mutability::Mut => {
2108                                         let mode = match self.is_upvar_field_projection(place) {
2109                                             Some(field) if self.upvars[field.index()].by_ref => {
2110                                                 is_local_mutation_allowed
2111                                             }
2112                                             _ => LocalMutationIsAllowed::Yes,
2113                                         };
2114
2115                                         self.is_mutable(
2116                                             PlaceRef { local: place.local, projection: proj_base },
2117                                             mode,
2118                                         )
2119                                     }
2120                                 }
2121                             }
2122                             ty::RawPtr(tnm) => {
2123                                 match tnm.mutbl {
2124                                     // `*const` raw pointers are not mutable
2125                                     hir::Mutability::Not => Err(place),
2126                                     // `*mut` raw pointers are always mutable, regardless of
2127                                     // context. The users have to check by themselves.
2128                                     hir::Mutability::Mut => Ok(RootPlace {
2129                                         place_local: place.local,
2130                                         place_projection: place.projection,
2131                                         is_local_mutation_allowed,
2132                                     }),
2133                                 }
2134                             }
2135                             // `Box<T>` owns its content, so mutable if its location is mutable
2136                             _ if base_ty.is_box() => self.is_mutable(
2137                                 PlaceRef { local: place.local, projection: proj_base },
2138                                 is_local_mutation_allowed,
2139                             ),
2140                             // Deref should only be for reference, pointers or boxes
2141                             _ => bug!("Deref of unexpected type: {:?}", base_ty),
2142                         }
2143                     }
2144                     // All other projections are owned by their base path, so mutable if
2145                     // base path is mutable
2146                     ProjectionElem::Field(..)
2147                     | ProjectionElem::Index(..)
2148                     | ProjectionElem::ConstantIndex { .. }
2149                     | ProjectionElem::Subslice { .. }
2150                     | ProjectionElem::Downcast(..) => {
2151                         let upvar_field_projection = self.is_upvar_field_projection(place);
2152                         if let Some(field) = upvar_field_projection {
2153                             let upvar = &self.upvars[field.index()];
2154                             debug!(
2155                                 "upvar.mutability={:?} local_mutation_is_allowed={:?} \
2156                                  place={:?}",
2157                                 upvar, is_local_mutation_allowed, place
2158                             );
2159                             match (upvar.mutability, is_local_mutation_allowed) {
2160                                 (Mutability::Not, LocalMutationIsAllowed::No)
2161                                 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2162                                     Err(place)
2163                                 }
2164                                 (Mutability::Not, LocalMutationIsAllowed::Yes)
2165                                 | (Mutability::Mut, _) => {
2166                                     // Subtle: this is an upvar
2167                                     // reference, so it looks like
2168                                     // `self.foo` -- we want to double
2169                                     // check that the location `*self`
2170                                     // is mutable (i.e., this is not a
2171                                     // `Fn` closure).  But if that
2172                                     // check succeeds, we want to
2173                                     // *blame* the mutability on
2174                                     // `place` (that is,
2175                                     // `self.foo`). This is used to
2176                                     // propagate the info about
2177                                     // whether mutability declarations
2178                                     // are used outwards, so that we register
2179                                     // the outer variable as mutable. Otherwise a
2180                                     // test like this fails to record the `mut`
2181                                     // as needed:
2182                                     //
2183                                     // ```
2184                                     // fn foo<F: FnOnce()>(_f: F) { }
2185                                     // fn main() {
2186                                     //     let var = Vec::new();
2187                                     //     foo(move || {
2188                                     //         var.push(1);
2189                                     //     });
2190                                     // }
2191                                     // ```
2192                                     let _ = self.is_mutable(
2193                                         PlaceRef { local: place.local, projection: proj_base },
2194                                         is_local_mutation_allowed,
2195                                     )?;
2196                                     Ok(RootPlace {
2197                                         place_local: place.local,
2198                                         place_projection: place.projection,
2199                                         is_local_mutation_allowed,
2200                                     })
2201                                 }
2202                             }
2203                         } else {
2204                             self.is_mutable(
2205                                 PlaceRef { local: place.local, projection: proj_base },
2206                                 is_local_mutation_allowed,
2207                             )
2208                         }
2209                     }
2210                 }
2211             }
2212         }
2213     }
2214
2215     /// If `place` is a field projection, and the field is being projected from a closure type,
2216     /// then returns the index of the field being projected. Note that this closure will always
2217     /// be `self` in the current MIR, because that is the only time we directly access the fields
2218     /// of a closure type.
2219     pub fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> {
2220         let mut place_projection = place_ref.projection;
2221         let mut by_ref = false;
2222
2223         if let [proj_base @ .., ProjectionElem::Deref] = place_projection {
2224             place_projection = proj_base;
2225             by_ref = true;
2226         }
2227
2228         match place_projection {
2229             [base @ .., ProjectionElem::Field(field, _ty)] => {
2230                 let tcx = self.infcx.tcx;
2231                 let base_ty = Place::ty_from(place_ref.local, base, self.body(), tcx).ty;
2232
2233                 if (base_ty.is_closure() || base_ty.is_generator())
2234                     && (!by_ref || self.upvars[field.index()].by_ref)
2235                 {
2236                     Some(*field)
2237                 } else {
2238                     None
2239                 }
2240             }
2241
2242             _ => None,
2243         }
2244     }
2245 }
2246
2247 /// The degree of overlap between 2 places for borrow-checking.
2248 enum Overlap {
2249     /// The places might partially overlap - in this case, we give
2250     /// up and say that they might conflict. This occurs when
2251     /// different fields of a union are borrowed. For example,
2252     /// if `u` is a union, we have no way of telling how disjoint
2253     /// `u.a.x` and `a.b.y` are.
2254     Arbitrary,
2255     /// The places have the same type, and are either completely disjoint
2256     /// or equal - i.e., they can't "partially" overlap as can occur with
2257     /// unions. This is the "base case" on which we recur for extensions
2258     /// of the place.
2259     EqualOrDisjoint,
2260     /// The places are disjoint, so we know all extensions of them
2261     /// will also be disjoint.
2262     Disjoint,
2263 }