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