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