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