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