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