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