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