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