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