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