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