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