]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/lib.rs
During MirBorrowck, ignore ConstEvalCounter
[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(once_cell)]
9 #![feature(rustc_attrs)]
10 #![feature(stmt_expr_attributes)]
11 #![feature(trusted_step)]
12 #![feature(try_blocks)]
13 #![recursion_limit = "256"]
14
15 #[macro_use]
16 extern crate rustc_middle;
17 #[macro_use]
18 extern crate tracing;
19
20 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
21 use rustc_data_structures::graph::dominators::Dominators;
22 use rustc_data_structures::vec_map::VecMap;
23 use rustc_errors::{Diagnostic, DiagnosticBuilder};
24 use rustc_hir as hir;
25 use rustc_hir::def_id::LocalDefId;
26 use rustc_index::bit_set::ChunkedBitSet;
27 use rustc_index::vec::IndexVec;
28 use rustc_infer::infer::{DefiningAnchor, InferCtxt, TyCtxtInferExt};
29 use rustc_middle::mir::{
30     traversal, Body, ClearCrossCrate, Local, Location, Mutability, NonDivergingIntrinsic, Operand,
31     Place, PlaceElem, PlaceRef, VarDebugInfoContents,
32 };
33 use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
34 use rustc_middle::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
35 use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind};
36 use rustc_middle::ty::query::Providers;
37 use rustc_middle::ty::{self, CapturedPlace, ParamEnv, RegionVid, TyCtxt};
38 use rustc_session::lint::builtin::UNUSED_MUT;
39 use rustc_span::{Span, Symbol};
40
41 use either::Either;
42 use smallvec::SmallVec;
43 use std::cell::OnceCell;
44 use std::cell::RefCell;
45 use std::collections::BTreeMap;
46 use std::rc::Rc;
47
48 use rustc_mir_dataflow::impls::{
49     EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces,
50 };
51 use rustc_mir_dataflow::move_paths::{InitIndex, MoveOutIndex, MovePathIndex};
52 use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveData, MoveError};
53 use rustc_mir_dataflow::Analysis;
54 use rustc_mir_dataflow::MoveDataParamEnv;
55
56 use crate::session_diagnostics::VarNeedNotMut;
57
58 use self::diagnostics::{AccessKind, RegionName};
59 use self::location::LocationTable;
60 use self::prefixes::PrefixSet;
61 use facts::AllFacts;
62
63 use self::path_utils::*;
64
65 pub mod borrow_set;
66 mod borrowck_errors;
67 mod constraint_generation;
68 mod constraints;
69 mod dataflow;
70 mod def_use;
71 mod diagnostics;
72 mod facts;
73 mod invalidation;
74 mod location;
75 mod member_constraints;
76 mod nll;
77 mod path_utils;
78 mod place_ext;
79 mod places_conflict;
80 mod prefixes;
81 mod region_infer;
82 mod renumber;
83 mod session_diagnostics;
84 mod type_check;
85 mod universal_regions;
86 mod used_muts;
87
88 /// A public API provided for the Rust compiler consumers.
89 pub mod consumers;
90
91 use borrow_set::{BorrowData, BorrowSet};
92 use dataflow::{BorrowIndex, BorrowckFlowState as Flows, BorrowckResults, Borrows};
93 use nll::{PoloniusOutput, ToRegionVid};
94 use place_ext::PlaceExt;
95 use places_conflict::{places_conflict, PlaceConflictBias};
96 use region_infer::RegionInferenceContext;
97
98 // FIXME(eddyb) perhaps move this somewhere more centrally.
99 #[derive(Debug)]
100 struct Upvar<'tcx> {
101     place: CapturedPlace<'tcx>,
102
103     /// If true, the capture is behind a reference.
104     by_ref: bool,
105 }
106
107 /// Associate some local constants with the `'tcx` lifetime
108 struct TyCtxtConsts<'tcx>(TyCtxt<'tcx>);
109 impl<'tcx> TyCtxtConsts<'tcx> {
110     const DEREF_PROJECTION: &'tcx [PlaceElem<'tcx>; 1] = &[ProjectionElem::Deref];
111 }
112
113 pub fn provide(providers: &mut Providers) {
114     *providers = Providers {
115         mir_borrowck: |tcx, did| {
116             if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
117                 tcx.mir_borrowck_const_arg(def)
118             } else {
119                 mir_borrowck(tcx, ty::WithOptConstParam::unknown(did))
120             }
121         },
122         mir_borrowck_const_arg: |tcx, (did, param_did)| {
123             mir_borrowck(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
124         },
125         ..*providers
126     };
127 }
128
129 fn mir_borrowck(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> &BorrowCheckResult<'_> {
130     let (input_body, promoted) = tcx.mir_promoted(def);
131     debug!("run query mir_borrowck: {}", tcx.def_path_str(def.did.to_def_id()));
132
133     if input_body.borrow().should_skip() {
134         debug!("Skipping borrowck because of injected body");
135         // Let's make up a borrowck result! Fun times!
136         let result = BorrowCheckResult {
137             concrete_opaque_types: VecMap::new(),
138             closure_requirements: None,
139             used_mut_upvars: SmallVec::new(),
140             tainted_by_errors: None,
141         };
142         return tcx.arena.alloc(result);
143     }
144
145     let hir_owner = tcx.hir().local_def_id_to_hir_id(def.did).owner;
146
147     let infcx =
148         tcx.infer_ctxt().with_opaque_type_inference(DefiningAnchor::Bind(hir_owner.def_id)).build();
149     let input_body: &Body<'_> = &input_body.borrow();
150     let promoted: &IndexVec<_, _> = &promoted.borrow();
151     let opt_closure_req = do_mir_borrowck(&infcx, input_body, promoted, false).0;
152     debug!("mir_borrowck done");
153
154     tcx.arena.alloc(opt_closure_req)
155 }
156
157 /// Perform the actual borrow checking.
158 ///
159 /// If `return_body_with_facts` is true, then return the body with non-erased
160 /// region ids on which the borrow checking was performed together with Polonius
161 /// facts.
162 #[instrument(skip(infcx, input_body, input_promoted), fields(id=?input_body.source.with_opt_param().as_local().unwrap()), level = "debug")]
163 fn do_mir_borrowck<'tcx>(
164     infcx: &InferCtxt<'tcx>,
165     input_body: &Body<'tcx>,
166     input_promoted: &IndexVec<Promoted, Body<'tcx>>,
167     return_body_with_facts: bool,
168 ) -> (BorrowCheckResult<'tcx>, Option<Box<BodyWithBorrowckFacts<'tcx>>>) {
169     let def = input_body.source.with_opt_param().as_local().unwrap();
170
171     debug!(?def);
172
173     let tcx = infcx.tcx;
174     let param_env = tcx.param_env(def.did);
175
176     let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
177     for var_debug_info in &input_body.var_debug_info {
178         if let VarDebugInfoContents::Place(place) = var_debug_info.value {
179             if let Some(local) = place.as_local() {
180                 if let Some(prev_name) = local_names[local] && var_debug_info.name != prev_name {
181                     span_bug!(
182                         var_debug_info.source_info.span,
183                         "local {:?} has many names (`{}` vs `{}`)",
184                         local,
185                         prev_name,
186                         var_debug_info.name
187                     );
188                 }
189                 local_names[local] = Some(var_debug_info.name);
190             }
191         }
192     }
193
194     let mut errors = error::BorrowckErrors::new(infcx.tcx);
195
196     // Gather the upvars of a closure, if any.
197     let tables = tcx.typeck_opt_const_arg(def);
198     if let Some(e) = tables.tainted_by_errors {
199         infcx.set_tainted_by_errors(e);
200         errors.set_tainted_by_errors(e);
201     }
202     let upvars: Vec<_> = tables
203         .closure_min_captures_flattened(def.did)
204         .map(|captured_place| {
205             let capture = captured_place.info.capture_kind;
206             let by_ref = match capture {
207                 ty::UpvarCapture::ByValue => false,
208                 ty::UpvarCapture::ByRef(..) => true,
209             };
210             Upvar { place: captured_place.clone(), by_ref }
211         })
212         .collect();
213
214     // Replace all regions with fresh inference variables. This
215     // requires first making our own copy of the MIR. This copy will
216     // be modified (in place) to contain non-lexical lifetimes. It
217     // will have a lifetime tied to the inference context.
218     let mut body_owned = input_body.clone();
219     let mut promoted = input_promoted.clone();
220     let free_regions =
221         nll::replace_regions_in_mir(infcx, param_env, &mut body_owned, &mut promoted);
222     let body = &body_owned; // no further changes
223
224     let location_table_owned = LocationTable::new(body);
225     let location_table = &location_table_owned;
226
227     let (move_data, move_errors): (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>) =
228         match MoveData::gather_moves(&body, tcx, param_env) {
229             Ok((_, move_data)) => (move_data, Vec::new()),
230             Err((move_data, move_errors)) => (move_data, move_errors),
231         };
232     let promoted_errors = promoted
233         .iter_enumerated()
234         .map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env)));
235
236     let mdpe = MoveDataParamEnv { move_data, param_env };
237
238     let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe)
239         .into_engine(tcx, &body)
240         .pass_name("borrowck")
241         .iterate_to_fixpoint()
242         .into_results_cursor(&body);
243
244     let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(def.did).is_fn_or_closure();
245     let borrow_set =
246         Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
247
248     let use_polonius = return_body_with_facts || infcx.tcx.sess.opts.unstable_opts.polonius;
249
250     // Compute non-lexical lifetimes.
251     let nll::NllOutput {
252         regioncx,
253         opaque_type_values,
254         polonius_input,
255         polonius_output,
256         opt_closure_req,
257         nll_errors,
258     } = nll::compute_regions(
259         infcx,
260         free_regions,
261         body,
262         &promoted,
263         location_table,
264         param_env,
265         &mut flow_inits,
266         &mdpe.move_data,
267         &borrow_set,
268         &upvars,
269         use_polonius,
270     );
271
272     // Dump MIR results into a file, if that is enabled. This let us
273     // write unit-tests, as well as helping with debugging.
274     nll::dump_mir_results(infcx, &body, &regioncx, &opt_closure_req);
275
276     // We also have a `#[rustc_regions]` annotation that causes us to dump
277     // information.
278     nll::dump_annotation(
279         infcx,
280         &body,
281         &regioncx,
282         &opt_closure_req,
283         &opaque_type_values,
284         &mut errors,
285     );
286
287     // The various `flow_*` structures can be large. We drop `flow_inits` here
288     // so it doesn't overlap with the others below. This reduces peak memory
289     // usage significantly on some benchmarks.
290     drop(flow_inits);
291
292     let regioncx = Rc::new(regioncx);
293
294     let flow_borrows = Borrows::new(tcx, body, &regioncx, &borrow_set)
295         .into_engine(tcx, body)
296         .pass_name("borrowck")
297         .iterate_to_fixpoint();
298     let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &mdpe)
299         .into_engine(tcx, body)
300         .pass_name("borrowck")
301         .iterate_to_fixpoint();
302     let flow_ever_inits = EverInitializedPlaces::new(tcx, body, &mdpe)
303         .into_engine(tcx, body)
304         .pass_name("borrowck")
305         .iterate_to_fixpoint();
306
307     let movable_generator =
308         // The first argument is the generator type passed by value
309         if let Some(local) = body.local_decls.raw.get(1)
310         // Get the interior types and substs which typeck computed
311         && let ty::Generator(_, _, hir::Movability::Static) = local.ty.kind()
312     {
313         false
314     } else {
315         true
316     };
317
318     for (idx, move_data_results) in promoted_errors {
319         let promoted_body = &promoted[idx];
320
321         if let Err((move_data, move_errors)) = move_data_results {
322             let mut promoted_mbcx = MirBorrowckCtxt {
323                 infcx,
324                 param_env,
325                 body: promoted_body,
326                 move_data: &move_data,
327                 location_table, // no need to create a real one for the promoted, it is not used
328                 movable_generator,
329                 fn_self_span_reported: Default::default(),
330                 locals_are_invalidated_at_exit,
331                 access_place_error_reported: Default::default(),
332                 reservation_error_reported: Default::default(),
333                 uninitialized_error_reported: Default::default(),
334                 regioncx: regioncx.clone(),
335                 used_mut: Default::default(),
336                 used_mut_upvars: SmallVec::new(),
337                 borrow_set: Rc::clone(&borrow_set),
338                 dominators: Default::default(),
339                 upvars: Vec::new(),
340                 local_names: IndexVec::from_elem(None, &promoted_body.local_decls),
341                 region_names: RefCell::default(),
342                 next_region_name: RefCell::new(1),
343                 polonius_output: None,
344                 errors,
345             };
346             promoted_mbcx.report_move_errors(move_errors);
347             errors = promoted_mbcx.errors;
348         };
349     }
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: Default::default(),
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: OnceCell<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             // These do not actually affect borrowck
613             | StatementKind::ConstEvalCounter
614             | StatementKind::StorageLive(..) => {}
615             StatementKind::StorageDead(local) => {
616                 self.access_place(
617                     location,
618                     (Place::from(*local), span),
619                     (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
620                     LocalMutationIsAllowed::Yes,
621                     flow_state,
622                 );
623             }
624             StatementKind::Nop
625             | StatementKind::Retag { .. }
626             | StatementKind::Deinit(..)
627             | StatementKind::SetDiscriminant { .. } => {
628                 bug!("Statement not allowed in this MIR phase")
629             }
630         }
631     }
632
633     fn visit_terminator_before_primary_effect(
634         &mut self,
635         flow_state: &Flows<'cx, 'tcx>,
636         term: &'cx Terminator<'tcx>,
637         loc: Location,
638     ) {
639         debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
640         let span = term.source_info.span;
641
642         self.check_activations(loc, span, flow_state);
643
644         match &term.kind {
645             TerminatorKind::SwitchInt { discr, targets: _ } => {
646                 self.consume_operand(loc, (discr, span), flow_state);
647             }
648             TerminatorKind::Drop { place, target: _, unwind: _ } => {
649                 debug!(
650                     "visit_terminator_drop \
651                      loc: {:?} term: {:?} place: {:?} span: {:?}",
652                     loc, term, place, span
653                 );
654
655                 self.access_place(
656                     loc,
657                     (*place, span),
658                     (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
659                     LocalMutationIsAllowed::Yes,
660                     flow_state,
661                 );
662             }
663             TerminatorKind::DropAndReplace {
664                 place: drop_place,
665                 value: new_value,
666                 target: _,
667                 unwind: _,
668             } => {
669                 self.mutate_place(loc, (*drop_place, span), Deep, flow_state);
670                 self.consume_operand(loc, (new_value, span), flow_state);
671             }
672             TerminatorKind::Call {
673                 func,
674                 args,
675                 destination,
676                 target: _,
677                 cleanup: _,
678                 from_hir_call: _,
679                 fn_span: _,
680             } => {
681                 self.consume_operand(loc, (func, span), flow_state);
682                 for arg in args {
683                     self.consume_operand(loc, (arg, span), flow_state);
684                 }
685                 self.mutate_place(loc, (*destination, span), Deep, flow_state);
686             }
687             TerminatorKind::Assert { cond, expected: _, msg, target: _, cleanup: _ } => {
688                 self.consume_operand(loc, (cond, span), flow_state);
689                 use rustc_middle::mir::AssertKind;
690                 if let AssertKind::BoundsCheck { len, index } = msg {
691                     self.consume_operand(loc, (len, span), flow_state);
692                     self.consume_operand(loc, (index, span), flow_state);
693                 }
694             }
695
696             TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
697                 self.consume_operand(loc, (value, span), flow_state);
698                 self.mutate_place(loc, (*resume_arg, span), Deep, flow_state);
699             }
700
701             TerminatorKind::InlineAsm {
702                 template: _,
703                 operands,
704                 options: _,
705                 line_spans: _,
706                 destination: _,
707                 cleanup: _,
708             } => {
709                 for op in operands {
710                     match op {
711                         InlineAsmOperand::In { reg: _, value } => {
712                             self.consume_operand(loc, (value, span), flow_state);
713                         }
714                         InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
715                             if let Some(place) = place {
716                                 self.mutate_place(loc, (*place, span), Shallow(None), flow_state);
717                             }
718                         }
719                         InlineAsmOperand::InOut { reg: _, late: _, in_value, out_place } => {
720                             self.consume_operand(loc, (in_value, span), flow_state);
721                             if let &Some(out_place) = out_place {
722                                 self.mutate_place(
723                                     loc,
724                                     (out_place, span),
725                                     Shallow(None),
726                                     flow_state,
727                                 );
728                             }
729                         }
730                         InlineAsmOperand::Const { value: _ }
731                         | InlineAsmOperand::SymFn { value: _ }
732                         | InlineAsmOperand::SymStatic { def_id: _ } => {}
733                     }
734                 }
735             }
736
737             TerminatorKind::Goto { target: _ }
738             | TerminatorKind::Abort
739             | TerminatorKind::Unreachable
740             | TerminatorKind::Resume
741             | TerminatorKind::Return
742             | TerminatorKind::GeneratorDrop
743             | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
744             | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
745                 // no data used, thus irrelevant to borrowck
746             }
747         }
748     }
749
750     fn visit_terminator_after_primary_effect(
751         &mut self,
752         flow_state: &Flows<'cx, 'tcx>,
753         term: &'cx Terminator<'tcx>,
754         loc: Location,
755     ) {
756         let span = term.source_info.span;
757
758         match term.kind {
759             TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
760                 if self.movable_generator {
761                     // Look for any active borrows to locals
762                     let borrow_set = self.borrow_set.clone();
763                     for i in flow_state.borrows.iter() {
764                         let borrow = &borrow_set[i];
765                         self.check_for_local_borrow(borrow, span);
766                     }
767                 }
768             }
769
770             TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
771                 // Returning from the function implicitly kills storage for all locals and statics.
772                 // Often, the storage will already have been killed by an explicit
773                 // StorageDead, but we don't always emit those (notably on unwind paths),
774                 // so this "extra check" serves as a kind of backup.
775                 let borrow_set = self.borrow_set.clone();
776                 for i in flow_state.borrows.iter() {
777                     let borrow = &borrow_set[i];
778                     self.check_for_invalidation_at_exit(loc, borrow, span);
779                 }
780             }
781
782             TerminatorKind::Abort
783             | TerminatorKind::Assert { .. }
784             | TerminatorKind::Call { .. }
785             | TerminatorKind::Drop { .. }
786             | TerminatorKind::DropAndReplace { .. }
787             | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
788             | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
789             | TerminatorKind::Goto { .. }
790             | TerminatorKind::SwitchInt { .. }
791             | TerminatorKind::Unreachable
792             | TerminatorKind::InlineAsm { .. } => {}
793         }
794     }
795 }
796
797 use self::AccessDepth::{Deep, Shallow};
798 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
799
800 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
801 enum ArtificialField {
802     ArrayLength,
803     ShallowBorrow,
804 }
805
806 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
807 enum AccessDepth {
808     /// From the RFC: "A *shallow* access means that the immediate
809     /// fields reached at P are accessed, but references or pointers
810     /// found within are not dereferenced. Right now, the only access
811     /// that is shallow is an assignment like `x = ...;`, which would
812     /// be a *shallow write* of `x`."
813     Shallow(Option<ArtificialField>),
814
815     /// From the RFC: "A *deep* access means that all data reachable
816     /// through the given place may be invalidated or accesses by
817     /// this action."
818     Deep,
819
820     /// Access is Deep only when there is a Drop implementation that
821     /// can reach the data behind the reference.
822     Drop,
823 }
824
825 /// Kind of access to a value: read or write
826 /// (For informational purposes only)
827 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
828 enum ReadOrWrite {
829     /// From the RFC: "A *read* means that the existing data may be
830     /// read, but will not be changed."
831     Read(ReadKind),
832
833     /// From the RFC: "A *write* means that the data may be mutated to
834     /// new values or otherwise invalidated (for example, it could be
835     /// de-initialized, as in a move operation).
836     Write(WriteKind),
837
838     /// For two-phase borrows, we distinguish a reservation (which is treated
839     /// like a Read) from an activation (which is treated like a write), and
840     /// each of those is furthermore distinguished from Reads/Writes above.
841     Reservation(WriteKind),
842     Activation(WriteKind, BorrowIndex),
843 }
844
845 /// Kind of read access to a value
846 /// (For informational purposes only)
847 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
848 enum ReadKind {
849     Borrow(BorrowKind),
850     Copy,
851 }
852
853 /// Kind of write access to a value
854 /// (For informational purposes only)
855 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
856 enum WriteKind {
857     StorageDeadOrDrop,
858     MutableBorrow(BorrowKind),
859     Mutate,
860     Move,
861 }
862
863 /// When checking permissions for a place access, this flag is used to indicate that an immutable
864 /// local place can be mutated.
865 //
866 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
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         self.access_place(
1136             location,
1137             place_span,
1138             (kind, Write(WriteKind::Mutate)),
1139             LocalMutationIsAllowed::No,
1140             flow_state,
1141         );
1142     }
1143
1144     fn consume_rvalue(
1145         &mut self,
1146         location: Location,
1147         (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1148         flow_state: &Flows<'cx, 'tcx>,
1149     ) {
1150         match rvalue {
1151             &Rvalue::Ref(_ /*rgn*/, bk, place) => {
1152                 let access_kind = match bk {
1153                     BorrowKind::Shallow => {
1154                         (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1155                     }
1156                     BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1157                     BorrowKind::Unique | BorrowKind::Mut { .. } => {
1158                         let wk = WriteKind::MutableBorrow(bk);
1159                         if allow_two_phase_borrow(bk) {
1160                             (Deep, Reservation(wk))
1161                         } else {
1162                             (Deep, Write(wk))
1163                         }
1164                     }
1165                 };
1166
1167                 self.access_place(
1168                     location,
1169                     (place, span),
1170                     access_kind,
1171                     LocalMutationIsAllowed::No,
1172                     flow_state,
1173                 );
1174
1175                 let action = if bk == BorrowKind::Shallow {
1176                     InitializationRequiringAction::MatchOn
1177                 } else {
1178                     InitializationRequiringAction::Borrow
1179                 };
1180
1181                 self.check_if_path_or_subpath_is_moved(
1182                     location,
1183                     action,
1184                     (place.as_ref(), span),
1185                     flow_state,
1186                 );
1187             }
1188
1189             &Rvalue::AddressOf(mutability, place) => {
1190                 let access_kind = match mutability {
1191                     Mutability::Mut => (
1192                         Deep,
1193                         Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1194                             allow_two_phase_borrow: false,
1195                         })),
1196                     ),
1197                     Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1198                 };
1199
1200                 self.access_place(
1201                     location,
1202                     (place, span),
1203                     access_kind,
1204                     LocalMutationIsAllowed::No,
1205                     flow_state,
1206                 );
1207
1208                 self.check_if_path_or_subpath_is_moved(
1209                     location,
1210                     InitializationRequiringAction::Borrow,
1211                     (place.as_ref(), span),
1212                     flow_state,
1213                 );
1214             }
1215
1216             Rvalue::ThreadLocalRef(_) => {}
1217
1218             Rvalue::Use(operand)
1219             | Rvalue::Repeat(operand, _)
1220             | Rvalue::UnaryOp(_ /*un_op*/, operand)
1221             | Rvalue::Cast(_ /*cast_kind*/, operand, _ /*ty*/)
1222             | Rvalue::ShallowInitBox(operand, _ /*ty*/) => {
1223                 self.consume_operand(location, (operand, span), flow_state)
1224             }
1225
1226             &Rvalue::CopyForDeref(place) => {
1227                 self.access_place(
1228                     location,
1229                     (place, span),
1230                     (Deep, Read(ReadKind::Copy)),
1231                     LocalMutationIsAllowed::No,
1232                     flow_state,
1233                 );
1234
1235                 // Finally, check if path was already moved.
1236                 self.check_if_path_or_subpath_is_moved(
1237                     location,
1238                     InitializationRequiringAction::Use,
1239                     (place.as_ref(), span),
1240                     flow_state,
1241                 );
1242             }
1243
1244             &(Rvalue::Len(place) | Rvalue::Discriminant(place)) => {
1245                 let af = match *rvalue {
1246                     Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1247                     Rvalue::Discriminant(..) => None,
1248                     _ => unreachable!(),
1249                 };
1250                 self.access_place(
1251                     location,
1252                     (place, span),
1253                     (Shallow(af), Read(ReadKind::Copy)),
1254                     LocalMutationIsAllowed::No,
1255                     flow_state,
1256                 );
1257                 self.check_if_path_or_subpath_is_moved(
1258                     location,
1259                     InitializationRequiringAction::Use,
1260                     (place.as_ref(), span),
1261                     flow_state,
1262                 );
1263             }
1264
1265             Rvalue::BinaryOp(_bin_op, box (operand1, operand2))
1266             | Rvalue::CheckedBinaryOp(_bin_op, box (operand1, operand2)) => {
1267                 self.consume_operand(location, (operand1, span), flow_state);
1268                 self.consume_operand(location, (operand2, span), flow_state);
1269             }
1270
1271             Rvalue::NullaryOp(_op, _ty) => {
1272                 // nullary ops take no dynamic input; no borrowck effect.
1273             }
1274
1275             Rvalue::Aggregate(aggregate_kind, operands) => {
1276                 // We need to report back the list of mutable upvars that were
1277                 // moved into the closure and subsequently used by the closure,
1278                 // in order to populate our used_mut set.
1279                 match **aggregate_kind {
1280                     AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
1281                         let BorrowCheckResult { used_mut_upvars, .. } =
1282                             self.infcx.tcx.mir_borrowck(def_id);
1283                         debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1284                         for field in used_mut_upvars {
1285                             self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1286                         }
1287                     }
1288                     AggregateKind::Adt(..)
1289                     | AggregateKind::Array(..)
1290                     | AggregateKind::Tuple { .. } => (),
1291                 }
1292
1293                 for operand in operands {
1294                     self.consume_operand(location, (operand, span), flow_state);
1295                 }
1296             }
1297         }
1298     }
1299
1300     fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1301         let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1302             // We have three possibilities here:
1303             // a. We are modifying something through a mut-ref
1304             // b. We are modifying something that is local to our parent
1305             // c. Current body is a nested closure, and we are modifying path starting from
1306             //    a Place captured by our parent closure.
1307
1308             // Handle (c), the path being modified is exactly the path captured by our parent
1309             if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1310                 this.used_mut_upvars.push(field);
1311                 return;
1312             }
1313
1314             for (place_ref, proj) in place.iter_projections().rev() {
1315                 // Handle (a)
1316                 if proj == ProjectionElem::Deref {
1317                     match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1318                         // We aren't modifying a variable directly
1319                         ty::Ref(_, _, hir::Mutability::Mut) => return,
1320
1321                         _ => {}
1322                     }
1323                 }
1324
1325                 // Handle (c)
1326                 if let Some(field) = this.is_upvar_field_projection(place_ref) {
1327                     this.used_mut_upvars.push(field);
1328                     return;
1329                 }
1330             }
1331
1332             // Handle(b)
1333             this.used_mut.insert(place.local);
1334         };
1335
1336         // This relies on the current way that by-value
1337         // captures of a closure are copied/moved directly
1338         // when generating MIR.
1339         match *operand {
1340             Operand::Move(place) | Operand::Copy(place) => {
1341                 match place.as_local() {
1342                     Some(local) if !self.body.local_decls[local].is_user_variable() => {
1343                         if self.body.local_decls[local].ty.is_mutable_ptr() {
1344                             // The variable will be marked as mutable by the borrow.
1345                             return;
1346                         }
1347                         // This is an edge case where we have a `move` closure
1348                         // inside a non-move closure, and the inner closure
1349                         // contains a mutation:
1350                         //
1351                         // let mut i = 0;
1352                         // || { move || { i += 1; }; };
1353                         //
1354                         // In this case our usual strategy of assuming that the
1355                         // variable will be captured by mutable reference is
1356                         // wrong, since `i` can be copied into the inner
1357                         // closure from a shared reference.
1358                         //
1359                         // As such we have to search for the local that this
1360                         // capture comes from and mark it as being used as mut.
1361
1362                         let temp_mpi = self.move_data.rev_lookup.find_local(local);
1363                         let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1364                             &self.move_data.inits[init_index]
1365                         } else {
1366                             bug!("temporary should be initialized exactly once")
1367                         };
1368
1369                         let InitLocation::Statement(loc) = init.location else {
1370                             bug!("temporary initialized in arguments")
1371                         };
1372
1373                         let body = self.body;
1374                         let bbd = &body[loc.block];
1375                         let stmt = &bbd.statements[loc.statement_index];
1376                         debug!("temporary assigned in: stmt={:?}", stmt);
1377
1378                         if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, source))) = stmt.kind
1379                         {
1380                             propagate_closure_used_mut_place(self, source);
1381                         } else {
1382                             bug!(
1383                                 "closures should only capture user variables \
1384                                  or references to user variables"
1385                             );
1386                         }
1387                     }
1388                     _ => propagate_closure_used_mut_place(self, place),
1389                 }
1390             }
1391             Operand::Constant(..) => {}
1392         }
1393     }
1394
1395     fn consume_operand(
1396         &mut self,
1397         location: Location,
1398         (operand, span): (&'cx Operand<'tcx>, Span),
1399         flow_state: &Flows<'cx, 'tcx>,
1400     ) {
1401         match *operand {
1402             Operand::Copy(place) => {
1403                 // copy of place: check if this is "copy of frozen path"
1404                 // (FIXME: see check_loans.rs)
1405                 self.access_place(
1406                     location,
1407                     (place, span),
1408                     (Deep, Read(ReadKind::Copy)),
1409                     LocalMutationIsAllowed::No,
1410                     flow_state,
1411                 );
1412
1413                 // Finally, check if path was already moved.
1414                 self.check_if_path_or_subpath_is_moved(
1415                     location,
1416                     InitializationRequiringAction::Use,
1417                     (place.as_ref(), span),
1418                     flow_state,
1419                 );
1420             }
1421             Operand::Move(place) => {
1422                 // move of place: check if this is move of already borrowed path
1423                 self.access_place(
1424                     location,
1425                     (place, span),
1426                     (Deep, Write(WriteKind::Move)),
1427                     LocalMutationIsAllowed::Yes,
1428                     flow_state,
1429                 );
1430
1431                 // Finally, check if path was already moved.
1432                 self.check_if_path_or_subpath_is_moved(
1433                     location,
1434                     InitializationRequiringAction::Use,
1435                     (place.as_ref(), span),
1436                     flow_state,
1437                 );
1438             }
1439             Operand::Constant(_) => {}
1440         }
1441     }
1442
1443     /// Checks whether a borrow of this place is invalidated when the function
1444     /// exits
1445     #[instrument(level = "debug", skip(self))]
1446     fn check_for_invalidation_at_exit(
1447         &mut self,
1448         location: Location,
1449         borrow: &BorrowData<'tcx>,
1450         span: Span,
1451     ) {
1452         let place = borrow.borrowed_place;
1453         let mut root_place = PlaceRef { local: place.local, projection: &[] };
1454
1455         // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1456         // we just know that all locals are dropped at function exit (otherwise
1457         // we'll have a memory leak) and assume that all statics have a destructor.
1458         //
1459         // FIXME: allow thread-locals to borrow other thread locals?
1460
1461         let (might_be_alive, will_be_dropped) =
1462             if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1463                 // Thread-locals might be dropped after the function exits
1464                 // We have to dereference the outer reference because
1465                 // borrows don't conflict behind shared references.
1466                 root_place.projection = TyCtxtConsts::DEREF_PROJECTION;
1467                 (true, true)
1468             } else {
1469                 (false, self.locals_are_invalidated_at_exit)
1470             };
1471
1472         if !will_be_dropped {
1473             debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
1474             return;
1475         }
1476
1477         let sd = if might_be_alive { Deep } else { Shallow(None) };
1478
1479         if places_conflict::borrow_conflicts_with_place(
1480             self.infcx.tcx,
1481             &self.body,
1482             place,
1483             borrow.kind,
1484             root_place,
1485             sd,
1486             places_conflict::PlaceConflictBias::Overlap,
1487         ) {
1488             debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1489             // FIXME: should be talking about the region lifetime instead
1490             // of just a span here.
1491             let span = self.infcx.tcx.sess.source_map().end_point(span);
1492             self.report_borrowed_value_does_not_live_long_enough(
1493                 location,
1494                 borrow,
1495                 (place, span),
1496                 None,
1497             )
1498         }
1499     }
1500
1501     /// Reports an error if this is a borrow of local data.
1502     /// This is called for all Yield expressions on movable generators
1503     fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1504         debug!("check_for_local_borrow({:?})", borrow);
1505
1506         if borrow_of_local_data(borrow.borrowed_place) {
1507             let err = self.cannot_borrow_across_generator_yield(
1508                 self.retrieve_borrow_spans(borrow).var_or_use(),
1509                 yield_span,
1510             );
1511
1512             self.buffer_error(err);
1513         }
1514     }
1515
1516     fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1517         // Two-phase borrow support: For each activation that is newly
1518         // generated at this statement, check if it interferes with
1519         // another borrow.
1520         let borrow_set = self.borrow_set.clone();
1521         for &borrow_index in borrow_set.activations_at_location(location) {
1522             let borrow = &borrow_set[borrow_index];
1523
1524             // only mutable borrows should be 2-phase
1525             assert!(match borrow.kind {
1526                 BorrowKind::Shared | BorrowKind::Shallow => false,
1527                 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1528             });
1529
1530             self.access_place(
1531                 location,
1532                 (borrow.borrowed_place, span),
1533                 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1534                 LocalMutationIsAllowed::No,
1535                 flow_state,
1536             );
1537             // We do not need to call `check_if_path_or_subpath_is_moved`
1538             // again, as we already called it when we made the
1539             // initial reservation.
1540         }
1541     }
1542
1543     fn check_if_full_path_is_moved(
1544         &mut self,
1545         location: Location,
1546         desired_action: InitializationRequiringAction,
1547         place_span: (PlaceRef<'tcx>, Span),
1548         flow_state: &Flows<'cx, 'tcx>,
1549     ) {
1550         let maybe_uninits = &flow_state.uninits;
1551
1552         // Bad scenarios:
1553         //
1554         // 1. Move of `a.b.c`, use of `a.b.c`
1555         // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1556         // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1557         //    partial initialization support, one might have `a.x`
1558         //    initialized but not `a.b`.
1559         //
1560         // OK scenarios:
1561         //
1562         // 4. Move of `a.b.c`, use of `a.b.d`
1563         // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1564         // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1565         //    must have been initialized for the use to be sound.
1566         // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1567
1568         // The dataflow tracks shallow prefixes distinctly (that is,
1569         // field-accesses on P distinctly from P itself), in order to
1570         // track substructure initialization separately from the whole
1571         // structure.
1572         //
1573         // E.g., when looking at (*a.b.c).d, if the closest prefix for
1574         // which we have a MovePath is `a.b`, then that means that the
1575         // initialization state of `a.b` is all we need to inspect to
1576         // know if `a.b.c` is valid (and from that we infer that the
1577         // dereference and `.d` access is also valid, since we assume
1578         // `a.b.c` is assigned a reference to an initialized and
1579         // well-formed record structure.)
1580
1581         // Therefore, if we seek out the *closest* prefix for which we
1582         // have a MovePath, that should capture the initialization
1583         // state for the place scenario.
1584         //
1585         // This code covers scenarios 1, 2, and 3.
1586
1587         debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1588         let (prefix, mpi) = self.move_path_closest_to(place_span.0);
1589         if maybe_uninits.contains(mpi) {
1590             self.report_use_of_moved_or_uninitialized(
1591                 location,
1592                 desired_action,
1593                 (prefix, place_span.0, place_span.1),
1594                 mpi,
1595             );
1596         } // Only query longest prefix with a MovePath, not further
1597         // ancestors; dataflow recurs on children when parents
1598         // move (to support partial (re)inits).
1599         //
1600         // (I.e., querying parents breaks scenario 7; but may want
1601         // to do such a query based on partial-init feature-gate.)
1602     }
1603
1604     /// Subslices correspond to multiple move paths, so we iterate through the
1605     /// elements of the base array. For each element we check
1606     ///
1607     /// * Does this element overlap with our slice.
1608     /// * Is any part of it uninitialized.
1609     fn check_if_subslice_element_is_moved(
1610         &mut self,
1611         location: Location,
1612         desired_action: InitializationRequiringAction,
1613         place_span: (PlaceRef<'tcx>, Span),
1614         maybe_uninits: &ChunkedBitSet<MovePathIndex>,
1615         from: u64,
1616         to: u64,
1617     ) {
1618         if let Some(mpi) = self.move_path_for_place(place_span.0) {
1619             let move_paths = &self.move_data.move_paths;
1620
1621             let root_path = &move_paths[mpi];
1622             for (child_mpi, child_move_path) in root_path.children(move_paths) {
1623                 let last_proj = child_move_path.place.projection.last().unwrap();
1624                 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
1625                     debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
1626
1627                     if (from..to).contains(offset) {
1628                         let uninit_child =
1629                             self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
1630                                 maybe_uninits.contains(mpi)
1631                             });
1632
1633                         if let Some(uninit_child) = uninit_child {
1634                             self.report_use_of_moved_or_uninitialized(
1635                                 location,
1636                                 desired_action,
1637                                 (place_span.0, place_span.0, place_span.1),
1638                                 uninit_child,
1639                             );
1640                             return; // don't bother finding other problems.
1641                         }
1642                     }
1643                 }
1644             }
1645         }
1646     }
1647
1648     fn check_if_path_or_subpath_is_moved(
1649         &mut self,
1650         location: Location,
1651         desired_action: InitializationRequiringAction,
1652         place_span: (PlaceRef<'tcx>, Span),
1653         flow_state: &Flows<'cx, 'tcx>,
1654     ) {
1655         let maybe_uninits = &flow_state.uninits;
1656
1657         // Bad scenarios:
1658         //
1659         // 1. Move of `a.b.c`, use of `a` or `a.b`
1660         //    partial initialization support, one might have `a.x`
1661         //    initialized but not `a.b`.
1662         // 2. All bad scenarios from `check_if_full_path_is_moved`
1663         //
1664         // OK scenarios:
1665         //
1666         // 3. Move of `a.b.c`, use of `a.b.d`
1667         // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1668         // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1669         //    must have been initialized for the use to be sound.
1670         // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1671
1672         self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1673
1674         if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
1675             place_span.0.last_projection()
1676         {
1677             let place_ty = place_base.ty(self.body(), self.infcx.tcx);
1678             if let ty::Array(..) = place_ty.ty.kind() {
1679                 self.check_if_subslice_element_is_moved(
1680                     location,
1681                     desired_action,
1682                     (place_base, place_span.1),
1683                     maybe_uninits,
1684                     from,
1685                     to,
1686                 );
1687                 return;
1688             }
1689         }
1690
1691         // A move of any shallow suffix of `place` also interferes
1692         // with an attempt to use `place`. This is scenario 3 above.
1693         //
1694         // (Distinct from handling of scenarios 1+2+4 above because
1695         // `place` does not interfere with suffixes of its prefixes,
1696         // e.g., `a.b.c` does not interfere with `a.b.d`)
1697         //
1698         // This code covers scenario 1.
1699
1700         debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1701         if let Some(mpi) = self.move_path_for_place(place_span.0) {
1702             let uninit_mpi = self
1703                 .move_data
1704                 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
1705
1706             if let Some(uninit_mpi) = uninit_mpi {
1707                 self.report_use_of_moved_or_uninitialized(
1708                     location,
1709                     desired_action,
1710                     (place_span.0, place_span.0, place_span.1),
1711                     uninit_mpi,
1712                 );
1713                 return; // don't bother finding other problems.
1714             }
1715         }
1716     }
1717
1718     /// Currently MoveData does not store entries for all places in
1719     /// the input MIR. For example it will currently filter out
1720     /// places that are Copy; thus we do not track places of shared
1721     /// reference type. This routine will walk up a place along its
1722     /// prefixes, searching for a foundational place that *is*
1723     /// tracked in the MoveData.
1724     ///
1725     /// An Err result includes a tag indicated why the search failed.
1726     /// Currently this can only occur if the place is built off of a
1727     /// static variable, as we do not track those in the MoveData.
1728     fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
1729         match self.move_data.rev_lookup.find(place) {
1730             LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
1731                 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
1732             }
1733             LookupResult::Parent(None) => panic!("should have move path for every Local"),
1734         }
1735     }
1736
1737     fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
1738         // If returns None, then there is no move path corresponding
1739         // to a direct owner of `place` (which means there is nothing
1740         // that borrowck tracks for its analysis).
1741
1742         match self.move_data.rev_lookup.find(place) {
1743             LookupResult::Parent(_) => None,
1744             LookupResult::Exact(mpi) => Some(mpi),
1745         }
1746     }
1747
1748     fn check_if_assigned_path_is_moved(
1749         &mut self,
1750         location: Location,
1751         (place, span): (Place<'tcx>, Span),
1752         flow_state: &Flows<'cx, 'tcx>,
1753     ) {
1754         debug!("check_if_assigned_path_is_moved place: {:?}", place);
1755
1756         // None case => assigning to `x` does not require `x` be initialized.
1757         for (place_base, elem) in place.iter_projections().rev() {
1758             match elem {
1759                 ProjectionElem::Index(_/*operand*/) |
1760                 ProjectionElem::OpaqueCast(_) |
1761                 ProjectionElem::ConstantIndex { .. } |
1762                 // assigning to P[i] requires P to be valid.
1763                 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1764                 // assigning to (P->variant) is okay if assigning to `P` is okay
1765                 //
1766                 // FIXME: is this true even if P is an adt with a dtor?
1767                 { }
1768
1769                 // assigning to (*P) requires P to be initialized
1770                 ProjectionElem::Deref => {
1771                     self.check_if_full_path_is_moved(
1772                         location, InitializationRequiringAction::Use,
1773                         (place_base, span), flow_state);
1774                     // (base initialized; no need to
1775                     // recur further)
1776                     break;
1777                 }
1778
1779                 ProjectionElem::Subslice { .. } => {
1780                     panic!("we don't allow assignments to subslices, location: {:?}",
1781                            location);
1782                 }
1783
1784                 ProjectionElem::Field(..) => {
1785                     // if type of `P` has a dtor, then
1786                     // assigning to `P.f` requires `P` itself
1787                     // be already initialized
1788                     let tcx = self.infcx.tcx;
1789                     let base_ty = place_base.ty(self.body(), tcx).ty;
1790                     match base_ty.kind() {
1791                         ty::Adt(def, _) if def.has_dtor(tcx) => {
1792                             self.check_if_path_or_subpath_is_moved(
1793                                 location, InitializationRequiringAction::Assignment,
1794                                 (place_base, span), flow_state);
1795
1796                             // (base initialized; no need to
1797                             // recur further)
1798                             break;
1799                         }
1800
1801                         // Once `let s; s.x = V; read(s.x);`,
1802                         // is allowed, remove this match arm.
1803                         ty::Adt(..) | ty::Tuple(..) => {
1804                             check_parent_of_field(self, location, place_base, span, flow_state);
1805
1806                             // rust-lang/rust#21232, #54499, #54986: during period where we reject
1807                             // partial initialization, do not complain about unnecessary `mut` on
1808                             // an attempt to do a partial initialization.
1809                             self.used_mut.insert(place.local);
1810                         }
1811
1812                         _ => {}
1813                     }
1814                 }
1815             }
1816         }
1817
1818         fn check_parent_of_field<'cx, 'tcx>(
1819             this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1820             location: Location,
1821             base: PlaceRef<'tcx>,
1822             span: Span,
1823             flow_state: &Flows<'cx, 'tcx>,
1824         ) {
1825             // rust-lang/rust#21232: Until Rust allows reads from the
1826             // initialized parts of partially initialized structs, we
1827             // will, starting with the 2018 edition, reject attempts
1828             // to write to structs that are not fully initialized.
1829             //
1830             // In other words, *until* we allow this:
1831             //
1832             // 1. `let mut s; s.x = Val; read(s.x);`
1833             //
1834             // we will for now disallow this:
1835             //
1836             // 2. `let mut s; s.x = Val;`
1837             //
1838             // and also this:
1839             //
1840             // 3. `let mut s = ...; drop(s); s.x=Val;`
1841             //
1842             // This does not use check_if_path_or_subpath_is_moved,
1843             // because we want to *allow* reinitializations of fields:
1844             // e.g., want to allow
1845             //
1846             // `let mut s = ...; drop(s.x); s.x=Val;`
1847             //
1848             // This does not use check_if_full_path_is_moved on
1849             // `base`, because that would report an error about the
1850             // `base` as a whole, but in this scenario we *really*
1851             // want to report an error about the actual thing that was
1852             // moved, which may be some prefix of `base`.
1853
1854             // Shallow so that we'll stop at any dereference; we'll
1855             // report errors about issues with such bases elsewhere.
1856             let maybe_uninits = &flow_state.uninits;
1857
1858             // Find the shortest uninitialized prefix you can reach
1859             // without going over a Deref.
1860             let mut shortest_uninit_seen = None;
1861             for prefix in this.prefixes(base, PrefixSet::Shallow) {
1862                 let Some(mpi) = this.move_path_for_place(prefix) else { continue };
1863
1864                 if maybe_uninits.contains(mpi) {
1865                     debug!(
1866                         "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1867                         shortest_uninit_seen,
1868                         Some((prefix, mpi))
1869                     );
1870                     shortest_uninit_seen = Some((prefix, mpi));
1871                 } else {
1872                     debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1873                 }
1874             }
1875
1876             if let Some((prefix, mpi)) = shortest_uninit_seen {
1877                 // Check for a reassignment into an uninitialized field of a union (for example,
1878                 // after a move out). In this case, do not report an error here. There is an
1879                 // exception, if this is the first assignment into the union (that is, there is
1880                 // no move out from an earlier location) then this is an attempt at initialization
1881                 // of the union - we should error in that case.
1882                 let tcx = this.infcx.tcx;
1883                 if base.ty(this.body(), tcx).ty.is_union() {
1884                     if this.move_data.path_map[mpi].iter().any(|moi| {
1885                         this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
1886                     }) {
1887                         return;
1888                     }
1889                 }
1890
1891                 this.report_use_of_moved_or_uninitialized(
1892                     location,
1893                     InitializationRequiringAction::PartialAssignment,
1894                     (prefix, base, span),
1895                     mpi,
1896                 );
1897             }
1898         }
1899     }
1900
1901     /// Checks the permissions for the given place and read or write kind
1902     ///
1903     /// Returns `true` if an error is reported.
1904     fn check_access_permissions(
1905         &mut self,
1906         (place, span): (Place<'tcx>, Span),
1907         kind: ReadOrWrite,
1908         is_local_mutation_allowed: LocalMutationIsAllowed,
1909         flow_state: &Flows<'cx, 'tcx>,
1910         location: Location,
1911     ) -> bool {
1912         debug!(
1913             "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1914             place, kind, is_local_mutation_allowed
1915         );
1916
1917         let error_access;
1918         let the_place_err;
1919
1920         match kind {
1921             Reservation(WriteKind::MutableBorrow(
1922                 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
1923             ))
1924             | Write(WriteKind::MutableBorrow(
1925                 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
1926             )) => {
1927                 let is_local_mutation_allowed = match borrow_kind {
1928                     BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1929                     BorrowKind::Mut { .. } => is_local_mutation_allowed,
1930                     BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1931                 };
1932                 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1933                     Ok(root_place) => {
1934                         self.add_used_mut(root_place, flow_state);
1935                         return false;
1936                     }
1937                     Err(place_err) => {
1938                         error_access = AccessKind::MutableBorrow;
1939                         the_place_err = place_err;
1940                     }
1941                 }
1942             }
1943             Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1944                 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1945                     Ok(root_place) => {
1946                         self.add_used_mut(root_place, flow_state);
1947                         return false;
1948                     }
1949                     Err(place_err) => {
1950                         error_access = AccessKind::Mutate;
1951                         the_place_err = place_err;
1952                     }
1953                 }
1954             }
1955
1956             Reservation(
1957                 WriteKind::Move
1958                 | WriteKind::StorageDeadOrDrop
1959                 | WriteKind::MutableBorrow(BorrowKind::Shared)
1960                 | WriteKind::MutableBorrow(BorrowKind::Shallow),
1961             )
1962             | Write(
1963                 WriteKind::Move
1964                 | WriteKind::StorageDeadOrDrop
1965                 | WriteKind::MutableBorrow(BorrowKind::Shared)
1966                 | WriteKind::MutableBorrow(BorrowKind::Shallow),
1967             ) => {
1968                 if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err()
1969                     && !self.has_buffered_errors()
1970                 {
1971                     // rust-lang/rust#46908: In pure NLL mode this code path should be
1972                     // unreachable, but we use `delay_span_bug` because we can hit this when
1973                     // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
1974                     // enabled. We don't want to ICE for that case, as other errors will have
1975                     // been emitted (#52262).
1976                     self.infcx.tcx.sess.delay_span_bug(
1977                         span,
1978                         &format!(
1979                             "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
1980                             place, kind,
1981                         ),
1982                     );
1983                 }
1984                 return false;
1985             }
1986             Activation(..) => {
1987                 // permission checks are done at Reservation point.
1988                 return false;
1989             }
1990             Read(
1991                 ReadKind::Borrow(
1992                     BorrowKind::Unique
1993                     | BorrowKind::Mut { .. }
1994                     | BorrowKind::Shared
1995                     | BorrowKind::Shallow,
1996                 )
1997                 | ReadKind::Copy,
1998             ) => {
1999                 // Access authorized
2000                 return false;
2001             }
2002         }
2003
2004         // rust-lang/rust#21232, #54986: during period where we reject
2005         // partial initialization, do not complain about mutability
2006         // errors except for actual mutation (as opposed to an attempt
2007         // to do a partial initialization).
2008         let previously_initialized = self.is_local_ever_initialized(place.local, flow_state);
2009
2010         // at this point, we have set up the error reporting state.
2011         if let Some(init_index) = previously_initialized {
2012             if let (AccessKind::Mutate, Some(_)) = (error_access, place.as_local()) {
2013                 // If this is a mutate access to an immutable local variable with no projections
2014                 // report the error as an illegal reassignment
2015                 let init = &self.move_data.inits[init_index];
2016                 let assigned_span = init.span(&self.body);
2017                 self.report_illegal_reassignment(location, (place, span), assigned_span, place);
2018             } else {
2019                 self.report_mutability_error(place, span, the_place_err, error_access, location)
2020             }
2021             true
2022         } else {
2023             false
2024         }
2025     }
2026
2027     fn is_local_ever_initialized(
2028         &self,
2029         local: Local,
2030         flow_state: &Flows<'cx, 'tcx>,
2031     ) -> Option<InitIndex> {
2032         let mpi = self.move_data.rev_lookup.find_local(local);
2033         let ii = &self.move_data.init_path_map[mpi];
2034         ii.into_iter().find(|&&index| flow_state.ever_inits.contains(index)).copied()
2035     }
2036
2037     /// Adds the place into the used mutable variables set
2038     fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2039         match root_place {
2040             RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2041                 // If the local may have been initialized, and it is now currently being
2042                 // mutated, then it is justified to be annotated with the `mut`
2043                 // keyword, since the mutation may be a possible reassignment.
2044                 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2045                     && self.is_local_ever_initialized(local, flow_state).is_some()
2046                 {
2047                     self.used_mut.insert(local);
2048                 }
2049             }
2050             RootPlace {
2051                 place_local: _,
2052                 place_projection: _,
2053                 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2054             } => {}
2055             RootPlace {
2056                 place_local,
2057                 place_projection: place_projection @ [.., _],
2058                 is_local_mutation_allowed: _,
2059             } => {
2060                 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2061                     local: place_local,
2062                     projection: place_projection,
2063                 }) {
2064                     self.used_mut_upvars.push(field);
2065                 }
2066             }
2067         }
2068     }
2069
2070     /// Whether this value can be written or borrowed mutably.
2071     /// Returns the root place if the place passed in is a projection.
2072     fn is_mutable(
2073         &self,
2074         place: PlaceRef<'tcx>,
2075         is_local_mutation_allowed: LocalMutationIsAllowed,
2076     ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2077         debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2078         match place.last_projection() {
2079             None => {
2080                 let local = &self.body.local_decls[place.local];
2081                 match local.mutability {
2082                     Mutability::Not => match is_local_mutation_allowed {
2083                         LocalMutationIsAllowed::Yes => Ok(RootPlace {
2084                             place_local: place.local,
2085                             place_projection: place.projection,
2086                             is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2087                         }),
2088                         LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2089                             place_local: place.local,
2090                             place_projection: place.projection,
2091                             is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2092                         }),
2093                         LocalMutationIsAllowed::No => Err(place),
2094                     },
2095                     Mutability::Mut => Ok(RootPlace {
2096                         place_local: place.local,
2097                         place_projection: place.projection,
2098                         is_local_mutation_allowed,
2099                     }),
2100                 }
2101             }
2102             Some((place_base, elem)) => {
2103                 match elem {
2104                     ProjectionElem::Deref => {
2105                         let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2106
2107                         // Check the kind of deref to decide
2108                         match base_ty.kind() {
2109                             ty::Ref(_, _, mutbl) => {
2110                                 match mutbl {
2111                                     // Shared borrowed data is never mutable
2112                                     hir::Mutability::Not => Err(place),
2113                                     // Mutably borrowed data is mutable, but only if we have a
2114                                     // unique path to the `&mut`
2115                                     hir::Mutability::Mut => {
2116                                         let mode = match self.is_upvar_field_projection(place) {
2117                                             Some(field) if self.upvars[field.index()].by_ref => {
2118                                                 is_local_mutation_allowed
2119                                             }
2120                                             _ => LocalMutationIsAllowed::Yes,
2121                                         };
2122
2123                                         self.is_mutable(place_base, mode)
2124                                     }
2125                                 }
2126                             }
2127                             ty::RawPtr(tnm) => {
2128                                 match tnm.mutbl {
2129                                     // `*const` raw pointers are not mutable
2130                                     hir::Mutability::Not => Err(place),
2131                                     // `*mut` raw pointers are always mutable, regardless of
2132                                     // context. The users have to check by themselves.
2133                                     hir::Mutability::Mut => Ok(RootPlace {
2134                                         place_local: place.local,
2135                                         place_projection: place.projection,
2136                                         is_local_mutation_allowed,
2137                                     }),
2138                                 }
2139                             }
2140                             // `Box<T>` owns its content, so mutable if its location is mutable
2141                             _ if base_ty.is_box() => {
2142                                 self.is_mutable(place_base, is_local_mutation_allowed)
2143                             }
2144                             // Deref should only be for reference, pointers or boxes
2145                             _ => bug!("Deref of unexpected type: {:?}", base_ty),
2146                         }
2147                     }
2148                     // All other projections are owned by their base path, so mutable if
2149                     // base path is mutable
2150                     ProjectionElem::Field(..)
2151                     | ProjectionElem::Index(..)
2152                     | ProjectionElem::ConstantIndex { .. }
2153                     | ProjectionElem::Subslice { .. }
2154                     | ProjectionElem::OpaqueCast { .. }
2155                     | ProjectionElem::Downcast(..) => {
2156                         let upvar_field_projection = self.is_upvar_field_projection(place);
2157                         if let Some(field) = upvar_field_projection {
2158                             let upvar = &self.upvars[field.index()];
2159                             debug!(
2160                                 "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2161                                  place={:?}, place_base={:?}",
2162                                 upvar, is_local_mutation_allowed, place, place_base
2163                             );
2164                             match (upvar.place.mutability, is_local_mutation_allowed) {
2165                                 (
2166                                     Mutability::Not,
2167                                     LocalMutationIsAllowed::No
2168                                     | LocalMutationIsAllowed::ExceptUpvars,
2169                                 ) => Err(place),
2170                                 (Mutability::Not, LocalMutationIsAllowed::Yes)
2171                                 | (Mutability::Mut, _) => {
2172                                     // Subtle: this is an upvar
2173                                     // reference, so it looks like
2174                                     // `self.foo` -- we want to double
2175                                     // check that the location `*self`
2176                                     // is mutable (i.e., this is not a
2177                                     // `Fn` closure). But if that
2178                                     // check succeeds, we want to
2179                                     // *blame* the mutability on
2180                                     // `place` (that is,
2181                                     // `self.foo`). This is used to
2182                                     // propagate the info about
2183                                     // whether mutability declarations
2184                                     // are used outwards, so that we register
2185                                     // the outer variable as mutable. Otherwise a
2186                                     // test like this fails to record the `mut`
2187                                     // as needed:
2188                                     //
2189                                     // ```
2190                                     // fn foo<F: FnOnce()>(_f: F) { }
2191                                     // fn main() {
2192                                     //     let var = Vec::new();
2193                                     //     foo(move || {
2194                                     //         var.push(1);
2195                                     //     });
2196                                     // }
2197                                     // ```
2198                                     let _ =
2199                                         self.is_mutable(place_base, is_local_mutation_allowed)?;
2200                                     Ok(RootPlace {
2201                                         place_local: place.local,
2202                                         place_projection: place.projection,
2203                                         is_local_mutation_allowed,
2204                                     })
2205                                 }
2206                             }
2207                         } else {
2208                             self.is_mutable(place_base, is_local_mutation_allowed)
2209                         }
2210                     }
2211                 }
2212             }
2213         }
2214     }
2215
2216     /// If `place` is a field projection, and the field is being projected from a closure type,
2217     /// then returns the index of the field being projected. Note that this closure will always
2218     /// be `self` in the current MIR, because that is the only time we directly access the fields
2219     /// of a closure type.
2220     fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> {
2221         path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2222     }
2223
2224     fn dominators(&self) -> &Dominators<BasicBlock> {
2225         self.dominators.get_or_init(|| self.body.basic_blocks.dominators())
2226     }
2227 }
2228
2229 mod error {
2230     use rustc_errors::ErrorGuaranteed;
2231
2232     use super::*;
2233
2234     pub struct BorrowckErrors<'tcx> {
2235         tcx: TyCtxt<'tcx>,
2236         /// This field keeps track of move errors that are to be reported for given move indices.
2237         ///
2238         /// There are situations where many errors can be reported for a single move out (see #53807)
2239         /// and we want only the best of those errors.
2240         ///
2241         /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
2242         /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
2243         /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
2244         /// all move errors have been reported, any diagnostics in this map are added to the buffer
2245         /// to be emitted.
2246         ///
2247         /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
2248         /// when errors in the map are being re-added to the error buffer so that errors with the
2249         /// same primary span come out in a consistent order.
2250         buffered_move_errors:
2251             BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorGuaranteed>)>,
2252         buffered_mut_errors: FxHashMap<Span, (DiagnosticBuilder<'tcx, ErrorGuaranteed>, usize)>,
2253         /// Diagnostics to be reported buffer.
2254         buffered: Vec<Diagnostic>,
2255         /// Set to Some if we emit an error during borrowck
2256         tainted_by_errors: Option<ErrorGuaranteed>,
2257     }
2258
2259     impl<'tcx> BorrowckErrors<'tcx> {
2260         pub fn new(tcx: TyCtxt<'tcx>) -> Self {
2261             BorrowckErrors {
2262                 tcx,
2263                 buffered_move_errors: BTreeMap::new(),
2264                 buffered_mut_errors: Default::default(),
2265                 buffered: Default::default(),
2266                 tainted_by_errors: None,
2267             }
2268         }
2269
2270         pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorGuaranteed>) {
2271             if let None = self.tainted_by_errors {
2272                 self.tainted_by_errors = Some(
2273                     self.tcx
2274                         .sess
2275                         .delay_span_bug(t.span.clone(), "diagnostic buffered but not emitted"),
2276                 )
2277             }
2278             t.buffer(&mut self.buffered);
2279         }
2280
2281         pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) {
2282             t.buffer(&mut self.buffered);
2283         }
2284
2285         pub fn set_tainted_by_errors(&mut self, e: ErrorGuaranteed) {
2286             self.tainted_by_errors = Some(e);
2287         }
2288     }
2289
2290     impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
2291         pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorGuaranteed>) {
2292             self.errors.buffer_error(t);
2293         }
2294
2295         pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) {
2296             self.errors.buffer_non_error_diag(t);
2297         }
2298
2299         pub fn buffer_move_error(
2300             &mut self,
2301             move_out_indices: Vec<MoveOutIndex>,
2302             place_and_err: (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorGuaranteed>),
2303         ) -> bool {
2304             if let Some((_, diag)) =
2305                 self.errors.buffered_move_errors.insert(move_out_indices, place_and_err)
2306             {
2307                 // Cancel the old diagnostic so we don't ICE
2308                 diag.cancel();
2309                 false
2310             } else {
2311                 true
2312             }
2313         }
2314
2315         pub fn get_buffered_mut_error(
2316             &mut self,
2317             span: Span,
2318         ) -> Option<(DiagnosticBuilder<'tcx, ErrorGuaranteed>, usize)> {
2319             self.errors.buffered_mut_errors.remove(&span)
2320         }
2321
2322         pub fn buffer_mut_error(
2323             &mut self,
2324             span: Span,
2325             t: DiagnosticBuilder<'tcx, ErrorGuaranteed>,
2326             count: usize,
2327         ) {
2328             self.errors.buffered_mut_errors.insert(span, (t, count));
2329         }
2330
2331         pub fn emit_errors(&mut self) -> Option<ErrorGuaranteed> {
2332             // Buffer any move errors that we collected and de-duplicated.
2333             for (_, (_, diag)) in std::mem::take(&mut self.errors.buffered_move_errors) {
2334                 // We have already set tainted for this error, so just buffer it.
2335                 diag.buffer(&mut self.errors.buffered);
2336             }
2337             for (_, (mut diag, count)) in std::mem::take(&mut self.errors.buffered_mut_errors) {
2338                 if count > 10 {
2339                     diag.note(&format!("...and {} other attempted mutable borrows", count - 10));
2340                 }
2341                 diag.buffer(&mut self.errors.buffered);
2342             }
2343
2344             if !self.errors.buffered.is_empty() {
2345                 self.errors.buffered.sort_by_key(|diag| diag.sort_span);
2346
2347                 for mut diag in self.errors.buffered.drain(..) {
2348                     self.infcx.tcx.sess.diagnostic().emit_diagnostic(&mut diag);
2349                 }
2350             }
2351
2352             self.errors.tainted_by_errors
2353         }
2354
2355         pub fn has_buffered_errors(&self) -> bool {
2356             self.errors.buffered.is_empty()
2357         }
2358
2359         pub fn has_move_error(
2360             &self,
2361             move_out_indices: &[MoveOutIndex],
2362         ) -> Option<&(PlaceRef<'tcx>, DiagnosticBuilder<'cx, ErrorGuaranteed>)> {
2363             self.errors.buffered_move_errors.get(move_out_indices)
2364         }
2365     }
2366 }
2367
2368 /// The degree of overlap between 2 places for borrow-checking.
2369 enum Overlap {
2370     /// The places might partially overlap - in this case, we give
2371     /// up and say that they might conflict. This occurs when
2372     /// different fields of a union are borrowed. For example,
2373     /// if `u` is a union, we have no way of telling how disjoint
2374     /// `u.a.x` and `a.b.y` are.
2375     Arbitrary,
2376     /// The places have the same type, and are either completely disjoint
2377     /// or equal - i.e., they can't "partially" overlap as can occur with
2378     /// unions. This is the "base case" on which we recur for extensions
2379     /// of the place.
2380     EqualOrDisjoint,
2381     /// The places are disjoint, so we know all extensions of them
2382     /// will also be disjoint.
2383     Disjoint,
2384 }