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