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