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