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