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