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