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