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