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