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