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