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