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