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