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