1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
3 use rustc_ast::ast::Name;
4 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5 use rustc_data_structures::graph::dominators::Dominators;
6 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorReported};
8 use rustc_hir::{def_id::DefId, HirId, Node};
9 use rustc_index::bit_set::BitSet;
10 use rustc_index::vec::IndexVec;
11 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
12 use rustc_middle::mir::{
13 read_only, traversal, Body, BodyAndCache, ClearCrossCrate, Local, Location, Mutability,
14 Operand, Place, PlaceElem, PlaceRef, ReadOnlyBodyAndCache,
16 use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
17 use rustc_middle::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
18 use rustc_middle::mir::{Terminator, TerminatorKind};
19 use rustc_middle::ty::query::Providers;
20 use rustc_middle::ty::{self, RegionVid, TyCtxt};
21 use rustc_session::lint::builtin::{MUTABLE_BORROW_RESERVATION_CONFLICT, UNUSED_MUT};
22 use rustc_span::{Span, DUMMY_SP};
25 use smallvec::SmallVec;
26 use std::cell::RefCell;
27 use std::collections::BTreeMap;
32 use crate::dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex};
33 use crate::dataflow::move_paths::{InitLocation, LookupResult, MoveData, MoveError};
34 use crate::dataflow::Borrows;
35 use crate::dataflow::EverInitializedPlaces;
36 use crate::dataflow::MoveDataParamEnv;
37 use crate::dataflow::{Analysis, BorrowckFlowState as Flows, BorrowckResults};
38 use crate::dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
39 use crate::transform::MirSource;
41 use self::diagnostics::{AccessKind, RegionName};
42 use self::location::LocationTable;
43 use self::prefixes::PrefixSet;
44 use self::MutateMode::{JustWrite, WriteAndRead};
46 use self::path_utils::*;
49 mod constraint_generation;
55 mod member_constraints;
64 mod universal_regions;
67 crate use borrow_set::{BorrowData, BorrowSet};
68 crate use nll::{PoloniusOutput, ToRegionVid};
69 crate use place_ext::PlaceExt;
70 crate use places_conflict::{places_conflict, PlaceConflictBias};
71 crate use region_infer::RegionInferenceContext;
73 // FIXME(eddyb) perhaps move this somewhere more centrally.
80 /// If true, the capture is behind a reference.
83 mutability: Mutability,
86 const DEREF_PROJECTION: &[PlaceElem<'_>; 1] = &[ProjectionElem::Deref];
88 pub fn provide(providers: &mut Providers<'_>) {
89 *providers = Providers { mir_borrowck, ..*providers };
92 fn mir_borrowck(tcx: TyCtxt<'_>, def_id: DefId) -> &BorrowCheckResult<'_> {
93 let (input_body, promoted) = tcx.mir_validated(def_id);
94 debug!("run query mir_borrowck: {}", tcx.def_path_str(def_id));
96 let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
97 let input_body: &Body<'_> = &input_body.borrow();
98 let promoted: &IndexVec<_, _> = &promoted.borrow();
99 do_mir_borrowck(&infcx, input_body, promoted, def_id)
101 debug!("mir_borrowck done");
103 tcx.arena.alloc(opt_closure_req)
106 fn do_mir_borrowck<'a, 'tcx>(
107 infcx: &InferCtxt<'a, 'tcx>,
108 input_body: &Body<'tcx>,
109 input_promoted: &IndexVec<Promoted, BodyAndCache<'tcx>>,
111 ) -> BorrowCheckResult<'tcx> {
112 debug!("do_mir_borrowck(def_id = {:?})", def_id);
115 let param_env = tcx.param_env(def_id);
116 let id = tcx.hir().as_local_hir_id(def_id).expect("do_mir_borrowck: non-local DefId");
118 let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
119 for var_debug_info in &input_body.var_debug_info {
120 if let Some(local) = var_debug_info.place.as_local() {
121 if let Some(prev_name) = local_names[local] {
122 if var_debug_info.name != prev_name {
124 var_debug_info.source_info.span,
125 "local {:?} has many names (`{}` vs `{}`)",
132 local_names[local] = Some(var_debug_info.name);
136 // Gather the upvars of a closure, if any.
137 let tables = tcx.typeck_tables_of(def_id);
138 if let Some(ErrorReported) = tables.tainted_by_errors {
139 infcx.set_tainted_by_errors();
141 let upvars: Vec<_> = tables
145 .flat_map(|v| v.values())
147 let var_hir_id = upvar_id.var_path.hir_id;
148 let capture = tables.upvar_capture(*upvar_id);
149 let by_ref = match capture {
150 ty::UpvarCapture::ByValue => false,
151 ty::UpvarCapture::ByRef(..) => true,
153 let mut upvar = Upvar {
154 name: tcx.hir().name(var_hir_id),
157 mutability: Mutability::Not,
159 let bm = *tables.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
160 if bm == ty::BindByValue(hir::Mutability::Mut) {
161 upvar.mutability = Mutability::Mut;
167 // Replace all regions with fresh inference variables. This
168 // requires first making our own copy of the MIR. This copy will
169 // be modified (in place) to contain non-lexical lifetimes. It
170 // will have a lifetime tied to the inference context.
171 let body_clone: Body<'tcx> = input_body.clone();
172 let mut promoted = input_promoted.clone();
173 let mut body = BodyAndCache::new(body_clone);
175 nll::replace_regions_in_mir(infcx, def_id, param_env, &mut body, &mut promoted);
176 let body = read_only!(body); // no further changes
177 let promoted: IndexVec<_, _> = promoted.iter_mut().map(|body| read_only!(body)).collect();
179 let location_table = &LocationTable::new(&body);
181 let mut errors_buffer = Vec::new();
182 let (move_data, move_errors): (MoveData<'tcx>, Option<Vec<(Place<'tcx>, MoveError<'tcx>)>>) =
183 match MoveData::gather_moves(&body, tcx, param_env) {
184 Ok(move_data) => (move_data, None),
185 Err((move_data, move_errors)) => (move_data, Some(move_errors)),
188 let mdpe = MoveDataParamEnv { move_data, param_env };
190 let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe)
191 .into_engine(tcx, &body, def_id)
192 .iterate_to_fixpoint()
193 .into_results_cursor(&body);
195 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
197 Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
199 // Compute non-lexical lifetimes.
206 } = nll::compute_regions(
219 // Dump MIR results into a file, if that is enabled. This let us
220 // write unit-tests, as well as helping with debugging.
221 nll::dump_mir_results(infcx, MirSource::item(def_id), &body, ®ioncx, &opt_closure_req);
223 // We also have a `#[rustc_regions]` annotation that causes us to dump
225 nll::dump_annotation(
235 // The various `flow_*` structures can be large. We drop `flow_inits` here
236 // so it doesn't overlap with the others below. This reduces peak memory
237 // usage significantly on some benchmarks.
240 let regioncx = Rc::new(regioncx);
242 let flow_borrows = Borrows::new(tcx, &body, regioncx.clone(), &borrow_set)
243 .into_engine(tcx, &body, def_id)
244 .iterate_to_fixpoint();
245 let flow_uninits = MaybeUninitializedPlaces::new(tcx, &body, &mdpe)
246 .into_engine(tcx, &body, def_id)
247 .iterate_to_fixpoint();
248 let flow_ever_inits = EverInitializedPlaces::new(tcx, &body, &mdpe)
249 .into_engine(tcx, &body, def_id)
250 .iterate_to_fixpoint();
252 let movable_generator = match tcx.hir().get(id) {
253 Node::Expr(&hir::Expr {
254 kind: hir::ExprKind::Closure(.., Some(hir::Movability::Static)),
260 let dominators = body.dominators();
262 let mut mbcx = MirBorrowckCtxt {
266 move_data: &mdpe.move_data,
269 locals_are_invalidated_at_exit,
270 access_place_error_reported: Default::default(),
271 reservation_error_reported: Default::default(),
272 reservation_warnings: Default::default(),
273 move_error_reported: BTreeMap::new(),
274 uninitialized_error_reported: Default::default(),
277 used_mut: Default::default(),
278 used_mut_upvars: SmallVec::new(),
283 region_names: RefCell::default(),
284 next_region_name: RefCell::new(1),
288 // Compute and report region errors, if any.
289 mbcx.report_region_errors(nll_errors);
291 let results = BorrowckResults {
292 ever_inits: flow_ever_inits,
293 uninits: flow_uninits,
294 borrows: flow_borrows,
297 if let Some(errors) = move_errors {
298 mbcx.report_move_errors(errors);
301 dataflow::visit_results(
303 traversal::reverse_postorder(&body).map(|(bb, _)| bb),
308 // Convert any reservation warnings into lints.
309 let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
310 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
311 let mut initial_diag = mbcx.report_conflicting_borrow(location, (place, span), bk, &borrow);
313 let scope = mbcx.body.source_info(location).scope;
314 let lint_root = match &mbcx.body.source_scopes[scope].local_data {
315 ClearCrossCrate::Set(data) => data.lint_root,
319 // Span and message don't matter; we overwrite them below anyway
320 mbcx.infcx.tcx.struct_span_lint_hir(
321 MUTABLE_BORROW_RESERVATION_CONFLICT,
325 let mut diag = lint.build("");
327 diag.message = initial_diag.styled_message().clone();
328 diag.span = initial_diag.span.clone();
330 diag.buffer(&mut mbcx.errors_buffer);
333 initial_diag.cancel();
336 // For each non-user used mutable variable, check if it's been assigned from
337 // a user-declared local. If so, then put that local into the used_mut set.
338 // Note that this set is expected to be small - only upvars from closures
339 // would have a chance of erroneously adding non-user-defined mutable vars
341 let temporary_used_locals: FxHashSet<Local> = mbcx
344 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
347 // For the remaining unused locals that are marked as mutable, we avoid linting any that
348 // were never initialized. These locals may have been removed as unreachable code; or will be
349 // linted as unused variables.
350 let unused_mut_locals =
351 mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
352 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
354 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
355 let used_mut = mbcx.used_mut;
356 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
357 let local_decl = &mbcx.body.local_decls[local];
358 let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data {
359 ClearCrossCrate::Set(data) => data.lint_root,
363 // Skip over locals that begin with an underscore or have no name
364 match mbcx.local_names[local] {
366 if name.as_str().starts_with('_') {
373 let span = local_decl.source_info.span;
374 if span.desugaring_kind().is_some() {
375 // If the `mut` arises as part of a desugaring, we should ignore it.
379 tcx.struct_span_lint_hir(UNUSED_MUT, lint_root, span, |lint| {
380 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
381 lint.build("variable does not need to be mutable")
382 .span_suggestion_short(
386 Applicability::MachineApplicable,
392 // Buffer any move errors that we collected and de-duplicated.
393 for (_, (_, diag)) in mbcx.move_error_reported {
394 diag.buffer(&mut mbcx.errors_buffer);
397 if !mbcx.errors_buffer.is_empty() {
398 mbcx.errors_buffer.sort_by_key(|diag| diag.sort_span);
400 for diag in mbcx.errors_buffer.drain(..) {
401 mbcx.infcx.tcx.sess.diagnostic().emit_diagnostic(&diag);
405 let result = BorrowCheckResult {
406 concrete_opaque_types: opaque_type_values,
407 closure_requirements: opt_closure_req,
408 used_mut_upvars: mbcx.used_mut_upvars,
411 debug!("do_mir_borrowck: result = {:#?}", result);
416 crate struct MirBorrowckCtxt<'cx, 'tcx> {
417 crate infcx: &'cx InferCtxt<'cx, 'tcx>,
418 body: ReadOnlyBodyAndCache<'cx, 'tcx>,
420 move_data: &'cx MoveData<'tcx>,
422 /// Map from MIR `Location` to `LocationIndex`; created
423 /// when MIR borrowck begins.
424 location_table: &'cx LocationTable,
426 movable_generator: bool,
427 /// This keeps track of whether local variables are free-ed when the function
428 /// exits even without a `StorageDead`, which appears to be the case for
431 /// I'm not sure this is the right approach - @eddyb could you try and
433 locals_are_invalidated_at_exit: bool,
434 /// This field keeps track of when borrow errors are reported in the access_place function
435 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
436 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
437 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
439 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
440 /// This field keeps track of when borrow conflict errors are reported
441 /// for reservations, so that we don't report seemingly duplicate
442 /// errors for corresponding activations.
444 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
445 // but it is currently inconvenient to track down the `BorrowIndex`
446 // at the time we detect and report a reservation error.
447 reservation_error_reported: FxHashSet<Place<'tcx>>,
448 /// Migration warnings to be reported for #56254. We delay reporting these
449 /// so that we can suppress the warning if there's a corresponding error
450 /// for the activation of the borrow.
451 reservation_warnings:
452 FxHashMap<BorrowIndex, (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)>,
453 /// This field keeps track of move errors that are to be reported for given move indices.
455 /// There are situations where many errors can be reported for a single move out (see #53807)
456 /// and we want only the best of those errors.
458 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
459 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
460 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
461 /// all move errors have been reported, any diagnostics in this map are added to the buffer
464 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
465 /// when errors in the map are being re-added to the error buffer so that errors with the
466 /// same primary span come out in a consistent order.
467 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'cx>)>,
468 /// This field keeps track of errors reported in the checking of uninitialized variables,
469 /// so that we don't report seemingly duplicate errors.
470 uninitialized_error_reported: FxHashSet<PlaceRef<'tcx>>,
471 /// Errors to be reported buffer
472 errors_buffer: Vec<Diagnostic>,
473 /// This field keeps track of all the local variables that are declared mut and are mutated.
474 /// Used for the warning issued by an unused mutable local variable.
475 used_mut: FxHashSet<Local>,
476 /// If the function we're checking is a closure, then we'll need to report back the list of
477 /// mutable upvars that have been used. This field keeps track of them.
478 used_mut_upvars: SmallVec<[Field; 8]>,
479 /// Region inference context. This contains the results from region inference and lets us e.g.
480 /// find out which CFG points are contained in each borrow region.
481 regioncx: Rc<RegionInferenceContext<'tcx>>,
483 /// The set of borrows extracted from the MIR
484 borrow_set: Rc<BorrowSet<'tcx>>,
486 /// Dominators for MIR
487 dominators: Dominators<BasicBlock>,
489 /// Information about upvars not necessarily preserved in types or MIR
492 /// Names of local (user) variables (extracted from `var_debug_info`).
493 local_names: IndexVec<Local, Option<Name>>,
495 /// Record the region names generated for each region in the given
496 /// MIR def so that we can reuse them later in help/error messages.
497 region_names: RefCell<FxHashMap<RegionVid, RegionName>>,
499 /// The counter for generating new region names.
500 next_region_name: RefCell<usize>,
502 /// Results of Polonius analysis.
503 polonius_output: Option<Rc<PoloniusOutput>>,
507 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
508 // 2. loans made in overlapping scopes do not conflict
509 // 3. assignments do not affect things loaned out as immutable
510 // 4. moves do not affect things loaned out in any way
511 impl<'cx, 'tcx> dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
512 type FlowState = Flows<'cx, 'tcx>;
516 flow_state: &Flows<'cx, 'tcx>,
517 stmt: &'cx Statement<'tcx>,
520 debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state);
521 let span = stmt.source_info.span;
523 self.check_activations(location, span, flow_state);
526 StatementKind::Assign(box (lhs, ref rhs)) => {
527 self.consume_rvalue(location, (rhs, span), flow_state);
529 self.mutate_place(location, (*lhs, span), Shallow(None), JustWrite, flow_state);
531 StatementKind::FakeRead(_, box ref place) => {
532 // Read for match doesn't access any memory and is used to
533 // assert that a place is safe and live. So we don't have to
534 // do any checks here.
536 // FIXME: Remove check that the place is initialized. This is
537 // needed for now because matches don't have never patterns yet.
538 // So this is the only place we prevent
542 self.check_if_path_or_subpath_is_moved(
544 InitializationRequiringAction::Use,
545 (place.as_ref(), span),
549 StatementKind::SetDiscriminant { place, variant_index: _ } => {
550 self.mutate_place(location, (**place, span), Shallow(None), JustWrite, flow_state);
552 StatementKind::LlvmInlineAsm(ref asm) => {
553 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
555 // FIXME(eddyb) indirect inline asm outputs should
556 // be encoded through MIR place derefs instead.
560 (Deep, Read(ReadKind::Copy)),
561 LocalMutationIsAllowed::No,
564 self.check_if_path_or_subpath_is_moved(
566 InitializationRequiringAction::Use,
567 (output.as_ref(), o.span),
574 if o.is_rw { Deep } else { Shallow(None) },
575 if o.is_rw { WriteAndRead } else { JustWrite },
580 for (_, input) in asm.inputs.iter() {
581 self.consume_operand(location, (input, span), flow_state);
585 | StatementKind::AscribeUserType(..)
586 | StatementKind::Retag { .. }
587 | StatementKind::StorageLive(..) => {
588 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
591 StatementKind::StorageDead(local) => {
594 (Place::from(*local), span),
595 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
596 LocalMutationIsAllowed::Yes,
605 flow_state: &Flows<'cx, 'tcx>,
606 term: &'cx Terminator<'tcx>,
609 debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
610 let span = term.source_info.span;
612 self.check_activations(loc, span, flow_state);
615 TerminatorKind::SwitchInt { ref discr, switch_ty: _, values: _, targets: _ } => {
616 self.consume_operand(loc, (discr, span), flow_state);
618 TerminatorKind::Drop { location: ref drop_place, target: _, unwind: _ } => {
619 let tcx = self.infcx.tcx;
621 // Compute the type with accurate region information.
622 let drop_place_ty = drop_place.ty(self.body, self.infcx.tcx);
624 // Erase the regions.
625 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
627 // "Lift" into the tcx -- once regions are erased, this type should be in the
628 // global arenas; this "lift" operation basically just asserts that is true, but
629 // that is useful later.
630 tcx.lift(&drop_place_ty).unwrap();
633 "visit_terminator_drop \
634 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
635 loc, term, drop_place, drop_place_ty, span
641 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
642 LocalMutationIsAllowed::Yes,
646 TerminatorKind::DropAndReplace {
647 location: drop_place,
648 value: ref new_value,
652 self.mutate_place(loc, (drop_place, span), Deep, JustWrite, flow_state);
653 self.consume_operand(loc, (new_value, span), flow_state);
655 TerminatorKind::Call {
662 self.consume_operand(loc, (func, span), flow_state);
664 self.consume_operand(loc, (arg, span), flow_state);
666 if let Some((dest, _ /*bb*/)) = *destination {
667 self.mutate_place(loc, (dest, span), Deep, JustWrite, flow_state);
670 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
671 self.consume_operand(loc, (cond, span), flow_state);
672 use rustc_middle::mir::AssertKind;
673 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
674 self.consume_operand(loc, (len, span), flow_state);
675 self.consume_operand(loc, (index, span), flow_state);
679 TerminatorKind::Yield { ref value, resume: _, resume_arg, drop: _ } => {
680 self.consume_operand(loc, (value, span), flow_state);
681 self.mutate_place(loc, (resume_arg, span), Deep, JustWrite, flow_state);
684 TerminatorKind::Goto { target: _ }
685 | TerminatorKind::Abort
686 | TerminatorKind::Unreachable
687 | TerminatorKind::Resume
688 | TerminatorKind::Return
689 | TerminatorKind::GeneratorDrop
690 | TerminatorKind::FalseEdges { real_target: _, imaginary_target: _ }
691 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
692 // no data used, thus irrelevant to borrowck
697 fn visit_terminator_exit(
699 flow_state: &Flows<'cx, 'tcx>,
700 term: &'cx Terminator<'tcx>,
703 let span = term.source_info.span;
706 TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
707 if self.movable_generator {
708 // Look for any active borrows to locals
709 let borrow_set = self.borrow_set.clone();
710 for i in flow_state.borrows.iter() {
711 let borrow = &borrow_set[i];
712 self.check_for_local_borrow(borrow, span);
717 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
718 // Returning from the function implicitly kills storage for all locals and statics.
719 // Often, the storage will already have been killed by an explicit
720 // StorageDead, but we don't always emit those (notably on unwind paths),
721 // so this "extra check" serves as a kind of backup.
722 let borrow_set = self.borrow_set.clone();
723 for i in flow_state.borrows.iter() {
724 let borrow = &borrow_set[i];
725 self.check_for_invalidation_at_exit(loc, borrow, span);
729 TerminatorKind::Abort
730 | TerminatorKind::Assert { .. }
731 | TerminatorKind::Call { .. }
732 | TerminatorKind::Drop { .. }
733 | TerminatorKind::DropAndReplace { .. }
734 | TerminatorKind::FalseEdges { real_target: _, imaginary_target: _ }
735 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
736 | TerminatorKind::Goto { .. }
737 | TerminatorKind::SwitchInt { .. }
738 | TerminatorKind::Unreachable => {}
743 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
749 use self::AccessDepth::{Deep, Shallow};
750 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
752 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
753 enum ArtificialField {
758 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
760 /// From the RFC: "A *shallow* access means that the immediate
761 /// fields reached at P are accessed, but references or pointers
762 /// found within are not dereferenced. Right now, the only access
763 /// that is shallow is an assignment like `x = ...;`, which would
764 /// be a *shallow write* of `x`."
765 Shallow(Option<ArtificialField>),
767 /// From the RFC: "A *deep* access means that all data reachable
768 /// through the given place may be invalidated or accesses by
772 /// Access is Deep only when there is a Drop implementation that
773 /// can reach the data behind the reference.
777 /// Kind of access to a value: read or write
778 /// (For informational purposes only)
779 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
781 /// From the RFC: "A *read* means that the existing data may be
782 /// read, but will not be changed."
785 /// From the RFC: "A *write* means that the data may be mutated to
786 /// new values or otherwise invalidated (for example, it could be
787 /// de-initialized, as in a move operation).
790 /// For two-phase borrows, we distinguish a reservation (which is treated
791 /// like a Read) from an activation (which is treated like a write), and
792 /// each of those is furthermore distinguished from Reads/Writes above.
793 Reservation(WriteKind),
794 Activation(WriteKind, BorrowIndex),
797 /// Kind of read access to a value
798 /// (For informational purposes only)
799 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
805 /// Kind of write access to a value
806 /// (For informational purposes only)
807 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
810 MutableBorrow(BorrowKind),
815 /// When checking permissions for a place access, this flag is used to indicate that an immutable
816 /// local place can be mutated.
818 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
819 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
820 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
821 // `is_declared_mutable()`.
822 // - Take flow state into consideration in `is_assignable()` for local variables.
823 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
824 enum LocalMutationIsAllowed {
826 /// We want use of immutable upvars to cause a "write to immutable upvar"
827 /// error, not an "reassignment" error.
832 #[derive(Copy, Clone, Debug)]
833 enum InitializationRequiringAction {
842 struct RootPlace<'tcx> {
844 place_projection: &'tcx [PlaceElem<'tcx>],
845 is_local_mutation_allowed: LocalMutationIsAllowed,
848 impl InitializationRequiringAction {
849 fn as_noun(self) -> &'static str {
851 InitializationRequiringAction::Update => "update",
852 InitializationRequiringAction::Borrow => "borrow",
853 InitializationRequiringAction::MatchOn => "use", // no good noun
854 InitializationRequiringAction::Use => "use",
855 InitializationRequiringAction::Assignment => "assign",
856 InitializationRequiringAction::PartialAssignment => "assign to part",
860 fn as_verb_in_past_tense(self) -> &'static str {
862 InitializationRequiringAction::Update => "updated",
863 InitializationRequiringAction::Borrow => "borrowed",
864 InitializationRequiringAction::MatchOn => "matched on",
865 InitializationRequiringAction::Use => "used",
866 InitializationRequiringAction::Assignment => "assigned",
867 InitializationRequiringAction::PartialAssignment => "partially assigned",
872 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
873 fn body(&self) -> &'cx Body<'tcx> {
877 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
878 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
879 /// place is initialized and (b) it is not borrowed in some way that would prevent this
882 /// Returns `true` if an error is reported.
886 place_span: (Place<'tcx>, Span),
887 kind: (AccessDepth, ReadOrWrite),
888 is_local_mutation_allowed: LocalMutationIsAllowed,
889 flow_state: &Flows<'cx, 'tcx>,
893 if let Activation(_, borrow_index) = rw {
894 if self.reservation_error_reported.contains(&place_span.0) {
896 "skipping access_place for activation of invalid reservation \
897 place: {:?} borrow_index: {:?}",
898 place_span.0, borrow_index
904 // Check is_empty() first because it's the common case, and doing that
905 // way we avoid the clone() call.
906 if !self.access_place_error_reported.is_empty()
907 && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
910 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
916 let mutability_error = self.check_access_permissions(
919 is_local_mutation_allowed,
924 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
926 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
927 // Suppress this warning when there's an error being emitted for the
928 // same borrow: fixing the error is likely to fix the warning.
929 self.reservation_warnings.remove(&borrow_idx);
932 if conflict_error || mutability_error {
933 debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
935 self.access_place_error_reported.insert((place_span.0, place_span.1));
939 fn check_access_for_conflict(
942 place_span: (Place<'tcx>, Span),
945 flow_state: &Flows<'cx, 'tcx>,
948 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
949 location, place_span, sd, rw,
952 let mut error_reported = false;
953 let tcx = self.infcx.tcx;
954 let body = self.body;
955 let body: &Body<'_> = &body;
956 let borrow_set = self.borrow_set.clone();
958 // Use polonius output if it has been enabled.
959 let polonius_output = self.polonius_output.clone();
960 let borrows_in_scope = if let Some(polonius) = &polonius_output {
961 let location = self.location_table.start_index(location);
962 Either::Left(polonius.errors_at(location).iter().copied())
964 Either::Right(flow_state.borrows.iter())
967 each_borrow_involving_path(
975 |this, borrow_index, borrow| match (rw, borrow.kind) {
976 // Obviously an activation is compatible with its own
977 // reservation (or even prior activating uses of same
978 // borrow); so don't check if they interfere.
980 // NOTE: *reservations* do conflict with themselves;
981 // thus aren't injecting unsoundenss w/ this check.)
982 (Activation(_, activating), _) if activating == borrow_index => {
984 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
985 skipping {:?} b/c activation of same borrow_index",
989 (borrow_index, borrow),
994 (Read(_), BorrowKind::Shared | BorrowKind::Shallow)
996 Read(ReadKind::Borrow(BorrowKind::Shallow)),
997 BorrowKind::Unique | BorrowKind::Mut { .. },
998 ) => Control::Continue,
1000 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1001 // Handled by initialization checks.
1005 (Read(kind), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
1006 // Reading from mere reservations of mutable-borrows is OK.
1007 if !is_active(&this.dominators, borrow, location) {
1008 assert!(allow_two_phase_borrow(borrow.kind));
1009 return Control::Continue;
1012 error_reported = true;
1015 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1016 .buffer(&mut this.errors_buffer);
1018 ReadKind::Borrow(bk) => {
1019 this.report_conflicting_borrow(location, place_span, bk, borrow)
1020 .buffer(&mut this.errors_buffer);
1027 Reservation(WriteKind::MutableBorrow(bk)),
1028 BorrowKind::Shallow | BorrowKind::Shared,
1030 tcx.migrate_borrowck() && this.borrow_set.location_map.contains_key(&location)
1033 let bi = this.borrow_set.location_map[&location];
1035 "recording invalid reservation of place: {:?} with \
1036 borrow index {:?} as warning",
1039 // rust-lang/rust#56254 - This was previously permitted on
1040 // the 2018 edition so we emit it as a warning. We buffer
1041 // these sepately so that we only emit a warning if borrow
1042 // checking was otherwise successful.
1043 this.reservation_warnings
1044 .insert(bi, (place_span.0, place_span.1, location, bk, borrow.clone()));
1046 // Don't suppress actual errors.
1050 (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1052 Reservation(..) => {
1054 "recording invalid reservation of \
1058 this.reservation_error_reported.insert(place_span.0);
1060 Activation(_, activating) => {
1062 "observing check_place for activation of \
1063 borrow_index: {:?}",
1067 Read(..) | Write(..) => {}
1070 error_reported = true;
1072 WriteKind::MutableBorrow(bk) => {
1073 this.report_conflicting_borrow(location, place_span, bk, borrow)
1074 .buffer(&mut this.errors_buffer);
1076 WriteKind::StorageDeadOrDrop => this
1077 .report_borrowed_value_does_not_live_long_enough(
1083 WriteKind::Mutate => {
1084 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1086 WriteKind::Move => {
1087 this.report_move_out_while_borrowed(location, place_span, borrow)
1101 place_span: (Place<'tcx>, Span),
1104 flow_state: &Flows<'cx, 'tcx>,
1106 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1108 MutateMode::WriteAndRead => {
1109 self.check_if_path_or_subpath_is_moved(
1111 InitializationRequiringAction::Update,
1112 (place_span.0.as_ref(), place_span.1),
1116 MutateMode::JustWrite => {
1117 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1121 // Special case: you can assign a immutable local variable
1122 // (e.g., `x = ...`) so long as it has never been initialized
1123 // before (at this point in the flow).
1124 if let Some(local) = place_span.0.as_local() {
1125 if let Mutability::Not = self.body.local_decls[local].mutability {
1126 // check for reassignments to immutable local variables
1127 self.check_if_reassignment_to_immutable_state(
1128 location, local, place_span, flow_state,
1134 // Otherwise, use the normal access permission rules.
1138 (kind, Write(WriteKind::Mutate)),
1139 LocalMutationIsAllowed::No,
1147 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1148 flow_state: &Flows<'cx, 'tcx>,
1151 Rvalue::Ref(_ /*rgn*/, bk, place) => {
1152 let access_kind = match bk {
1153 BorrowKind::Shallow => {
1154 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1156 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1157 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1158 let wk = WriteKind::MutableBorrow(bk);
1159 if allow_two_phase_borrow(bk) {
1160 (Deep, Reservation(wk))
1171 LocalMutationIsAllowed::No,
1175 let action = if bk == BorrowKind::Shallow {
1176 InitializationRequiringAction::MatchOn
1178 InitializationRequiringAction::Borrow
1181 self.check_if_path_or_subpath_is_moved(
1184 (place.as_ref(), span),
1189 Rvalue::AddressOf(mutability, place) => {
1190 let access_kind = match mutability {
1191 Mutability::Mut => (
1193 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1194 allow_two_phase_borrow: false,
1197 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1204 LocalMutationIsAllowed::No,
1208 self.check_if_path_or_subpath_is_moved(
1210 InitializationRequiringAction::Borrow,
1211 (place.as_ref(), span),
1216 Rvalue::Use(ref operand)
1217 | Rvalue::Repeat(ref operand, _)
1218 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1219 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1220 self.consume_operand(location, (operand, span), flow_state)
1223 Rvalue::Len(place) | Rvalue::Discriminant(place) => {
1224 let af = match *rvalue {
1225 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1226 Rvalue::Discriminant(..) => None,
1227 _ => unreachable!(),
1232 (Shallow(af), Read(ReadKind::Copy)),
1233 LocalMutationIsAllowed::No,
1236 self.check_if_path_or_subpath_is_moved(
1238 InitializationRequiringAction::Use,
1239 (place.as_ref(), span),
1244 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1245 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1246 self.consume_operand(location, (operand1, span), flow_state);
1247 self.consume_operand(location, (operand2, span), flow_state);
1250 Rvalue::NullaryOp(_op, _ty) => {
1251 // nullary ops take no dynamic input; no borrowck effect.
1253 // FIXME: is above actually true? Do we want to track
1254 // the fact that uninitialized data can be created via
1258 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1259 // We need to report back the list of mutable upvars that were
1260 // moved into the closure and subsequently used by the closure,
1261 // in order to populate our used_mut set.
1262 match **aggregate_kind {
1263 AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
1264 let BorrowCheckResult { used_mut_upvars, .. } =
1265 self.infcx.tcx.mir_borrowck(def_id);
1266 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1267 for field in used_mut_upvars {
1268 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1271 AggregateKind::Adt(..)
1272 | AggregateKind::Array(..)
1273 | AggregateKind::Tuple { .. } => (),
1276 for operand in operands {
1277 self.consume_operand(location, (operand, span), flow_state);
1283 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1284 let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1285 if !place.projection.is_empty() {
1286 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1287 this.used_mut_upvars.push(field);
1290 this.used_mut.insert(place.local);
1294 // This relies on the current way that by-value
1295 // captures of a closure are copied/moved directly
1296 // when generating MIR.
1298 Operand::Move(place) | Operand::Copy(place) => {
1299 match place.as_local() {
1300 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1301 if self.body.local_decls[local].ty.is_mutable_ptr() {
1302 // The variable will be marked as mutable by the borrow.
1305 // This is an edge case where we have a `move` closure
1306 // inside a non-move closure, and the inner closure
1307 // contains a mutation:
1310 // || { move || { i += 1; }; };
1312 // In this case our usual strategy of assuming that the
1313 // variable will be captured by mutable reference is
1314 // wrong, since `i` can be copied into the inner
1315 // closure from a shared reference.
1317 // As such we have to search for the local that this
1318 // capture comes from and mark it as being used as mut.
1320 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1321 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1322 &self.move_data.inits[init_index]
1324 bug!("temporary should be initialized exactly once")
1327 let loc = match init.location {
1328 InitLocation::Statement(stmt) => stmt,
1329 _ => bug!("temporary initialized in arguments"),
1332 let body = self.body;
1333 let bbd = &body[loc.block];
1334 let stmt = &bbd.statements[loc.statement_index];
1335 debug!("temporary assigned in: stmt={:?}", stmt);
1337 if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, source))) = stmt.kind
1339 propagate_closure_used_mut_place(self, source);
1342 "closures should only capture user variables \
1343 or references to user variables"
1347 _ => propagate_closure_used_mut_place(self, place),
1350 Operand::Constant(..) => {}
1357 (operand, span): (&'cx Operand<'tcx>, Span),
1358 flow_state: &Flows<'cx, 'tcx>,
1361 Operand::Copy(place) => {
1362 // copy of place: check if this is "copy of frozen path"
1363 // (FIXME: see check_loans.rs)
1367 (Deep, Read(ReadKind::Copy)),
1368 LocalMutationIsAllowed::No,
1372 // Finally, check if path was already moved.
1373 self.check_if_path_or_subpath_is_moved(
1375 InitializationRequiringAction::Use,
1376 (place.as_ref(), span),
1380 Operand::Move(place) => {
1381 // move of place: check if this is move of already borrowed path
1385 (Deep, Write(WriteKind::Move)),
1386 LocalMutationIsAllowed::Yes,
1390 // Finally, check if path was already moved.
1391 self.check_if_path_or_subpath_is_moved(
1393 InitializationRequiringAction::Use,
1394 (place.as_ref(), span),
1398 Operand::Constant(_) => {}
1402 /// Checks whether a borrow of this place is invalidated when the function
1404 fn check_for_invalidation_at_exit(
1407 borrow: &BorrowData<'tcx>,
1410 debug!("check_for_invalidation_at_exit({:?})", borrow);
1411 let place = borrow.borrowed_place;
1412 let mut root_place = PlaceRef { local: place.local, projection: &[] };
1414 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1415 // we just know that all locals are dropped at function exit (otherwise
1416 // we'll have a memory leak) and assume that all statics have a destructor.
1418 // FIXME: allow thread-locals to borrow other thread locals?
1420 let (might_be_alive, will_be_dropped) =
1421 if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1422 // Thread-locals might be dropped after the function exits
1423 // We have to dereference the outer reference because
1424 // borrows don't conflict behind shared references.
1425 root_place.projection = DEREF_PROJECTION;
1428 (false, self.locals_are_invalidated_at_exit)
1431 if !will_be_dropped {
1432 debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
1436 let sd = if might_be_alive { Deep } else { Shallow(None) };
1438 if places_conflict::borrow_conflicts_with_place(
1445 places_conflict::PlaceConflictBias::Overlap,
1447 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1448 // FIXME: should be talking about the region lifetime instead
1449 // of just a span here.
1450 let span = self.infcx.tcx.sess.source_map().end_point(span);
1451 self.report_borrowed_value_does_not_live_long_enough(
1460 /// Reports an error if this is a borrow of local data.
1461 /// This is called for all Yield expressions on movable generators
1462 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1463 debug!("check_for_local_borrow({:?})", borrow);
1465 if borrow_of_local_data(borrow.borrowed_place) {
1466 let err = self.cannot_borrow_across_generator_yield(
1467 self.retrieve_borrow_spans(borrow).var_or_use(),
1471 err.buffer(&mut self.errors_buffer);
1475 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1476 // Two-phase borrow support: For each activation that is newly
1477 // generated at this statement, check if it interferes with
1479 let borrow_set = self.borrow_set.clone();
1480 for &borrow_index in borrow_set.activations_at_location(location) {
1481 let borrow = &borrow_set[borrow_index];
1483 // only mutable borrows should be 2-phase
1484 assert!(match borrow.kind {
1485 BorrowKind::Shared | BorrowKind::Shallow => false,
1486 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1491 (borrow.borrowed_place, span),
1492 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1493 LocalMutationIsAllowed::No,
1496 // We do not need to call `check_if_path_or_subpath_is_moved`
1497 // again, as we already called it when we made the
1498 // initial reservation.
1502 fn check_if_reassignment_to_immutable_state(
1506 place_span: (Place<'tcx>, Span),
1507 flow_state: &Flows<'cx, 'tcx>,
1509 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1511 // Check if any of the initializiations of `local` have happened yet:
1512 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1513 // And, if so, report an error.
1514 let init = &self.move_data.inits[init_index];
1515 let span = init.span(&self.body);
1516 self.report_illegal_reassignment(location, place_span, span, place_span.0);
1520 fn check_if_full_path_is_moved(
1523 desired_action: InitializationRequiringAction,
1524 place_span: (PlaceRef<'tcx>, Span),
1525 flow_state: &Flows<'cx, 'tcx>,
1527 let maybe_uninits = &flow_state.uninits;
1531 // 1. Move of `a.b.c`, use of `a.b.c`
1532 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1533 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1534 // partial initialization support, one might have `a.x`
1535 // initialized but not `a.b`.
1539 // 4. Move of `a.b.c`, use of `a.b.d`
1540 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1541 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1542 // must have been initialized for the use to be sound.
1543 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1545 // The dataflow tracks shallow prefixes distinctly (that is,
1546 // field-accesses on P distinctly from P itself), in order to
1547 // track substructure initialization separately from the whole
1550 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1551 // which we have a MovePath is `a.b`, then that means that the
1552 // initialization state of `a.b` is all we need to inspect to
1553 // know if `a.b.c` is valid (and from that we infer that the
1554 // dereference and `.d` access is also valid, since we assume
1555 // `a.b.c` is assigned a reference to a initialized and
1556 // well-formed record structure.)
1558 // Therefore, if we seek out the *closest* prefix for which we
1559 // have a MovePath, that should capture the initialization
1560 // state for the place scenario.
1562 // This code covers scenarios 1, 2, and 3.
1564 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1565 let (prefix, mpi) = self.move_path_closest_to(place_span.0);
1566 if maybe_uninits.contains(mpi) {
1567 self.report_use_of_moved_or_uninitialized(
1570 (prefix, place_span.0, place_span.1),
1573 } // Only query longest prefix with a MovePath, not further
1574 // ancestors; dataflow recurs on children when parents
1575 // move (to support partial (re)inits).
1577 // (I.e., querying parents breaks scenario 7; but may want
1578 // to do such a query based on partial-init feature-gate.)
1581 /// Subslices correspond to multiple move paths, so we iterate through the
1582 /// elements of the base array. For each element we check
1584 /// * Does this element overlap with our slice.
1585 /// * Is any part of it uninitialized.
1586 fn check_if_subslice_element_is_moved(
1589 desired_action: InitializationRequiringAction,
1590 place_span: (PlaceRef<'tcx>, Span),
1591 maybe_uninits: &BitSet<MovePathIndex>,
1595 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1596 let move_paths = &self.move_data.move_paths;
1598 let root_path = &move_paths[mpi];
1599 for (child_mpi, child_move_path) in root_path.children(move_paths) {
1600 let last_proj = child_move_path.place.projection.last().unwrap();
1601 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
1602 debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
1604 if (from..to).contains(offset) {
1606 self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
1607 maybe_uninits.contains(mpi)
1610 if let Some(uninit_child) = uninit_child {
1611 self.report_use_of_moved_or_uninitialized(
1614 (place_span.0, place_span.0, place_span.1),
1617 return; // don't bother finding other problems.
1625 fn check_if_path_or_subpath_is_moved(
1628 desired_action: InitializationRequiringAction,
1629 place_span: (PlaceRef<'tcx>, Span),
1630 flow_state: &Flows<'cx, 'tcx>,
1632 let maybe_uninits = &flow_state.uninits;
1636 // 1. Move of `a.b.c`, use of `a` or `a.b`
1637 // partial initialization support, one might have `a.x`
1638 // initialized but not `a.b`.
1639 // 2. All bad scenarios from `check_if_full_path_is_moved`
1643 // 3. Move of `a.b.c`, use of `a.b.d`
1644 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1645 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1646 // must have been initialized for the use to be sound.
1647 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1649 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1651 if let [base_proj @ .., ProjectionElem::Subslice { from, to, from_end: false }] =
1652 place_span.0.projection
1655 Place::ty_from(place_span.0.local, base_proj, self.body(), self.infcx.tcx);
1656 if let ty::Array(..) = place_ty.ty.kind {
1657 let array_place = PlaceRef { local: place_span.0.local, projection: base_proj };
1658 self.check_if_subslice_element_is_moved(
1661 (array_place, place_span.1),
1670 // A move of any shallow suffix of `place` also interferes
1671 // with an attempt to use `place`. This is scenario 3 above.
1673 // (Distinct from handling of scenarios 1+2+4 above because
1674 // `place` does not interfere with suffixes of its prefixes,
1675 // e.g., `a.b.c` does not interfere with `a.b.d`)
1677 // This code covers scenario 1.
1679 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1680 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1681 let uninit_mpi = self
1683 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
1685 if let Some(uninit_mpi) = uninit_mpi {
1686 self.report_use_of_moved_or_uninitialized(
1689 (place_span.0, place_span.0, place_span.1),
1692 return; // don't bother finding other problems.
1697 /// Currently MoveData does not store entries for all places in
1698 /// the input MIR. For example it will currently filter out
1699 /// places that are Copy; thus we do not track places of shared
1700 /// reference type. This routine will walk up a place along its
1701 /// prefixes, searching for a foundational place that *is*
1702 /// tracked in the MoveData.
1704 /// An Err result includes a tag indicated why the search failed.
1705 /// Currently this can only occur if the place is built off of a
1706 /// static variable, as we do not track those in the MoveData.
1707 fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
1708 match self.move_data.rev_lookup.find(place) {
1709 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
1710 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
1712 LookupResult::Parent(None) => panic!("should have move path for every Local"),
1716 fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
1717 // If returns None, then there is no move path corresponding
1718 // to a direct owner of `place` (which means there is nothing
1719 // that borrowck tracks for its analysis).
1721 match self.move_data.rev_lookup.find(place) {
1722 LookupResult::Parent(_) => None,
1723 LookupResult::Exact(mpi) => Some(mpi),
1727 fn check_if_assigned_path_is_moved(
1730 (place, span): (Place<'tcx>, Span),
1731 flow_state: &Flows<'cx, 'tcx>,
1733 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1735 // None case => assigning to `x` does not require `x` be initialized.
1736 let mut cursor = &*place.projection.as_ref();
1737 while let [proj_base @ .., elem] = cursor {
1741 ProjectionElem::Index(_/*operand*/) |
1742 ProjectionElem::ConstantIndex { .. } |
1743 // assigning to P[i] requires P to be valid.
1744 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1745 // assigning to (P->variant) is okay if assigning to `P` is okay
1747 // FIXME: is this true even if P is a adt with a dtor?
1750 // assigning to (*P) requires P to be initialized
1751 ProjectionElem::Deref => {
1752 self.check_if_full_path_is_moved(
1753 location, InitializationRequiringAction::Use,
1756 projection: proj_base,
1757 }, span), flow_state);
1758 // (base initialized; no need to
1763 ProjectionElem::Subslice { .. } => {
1764 panic!("we don't allow assignments to subslices, location: {:?}",
1768 ProjectionElem::Field(..) => {
1769 // if type of `P` has a dtor, then
1770 // assigning to `P.f` requires `P` itself
1771 // be already initialized
1772 let tcx = self.infcx.tcx;
1773 let base_ty = Place::ty_from(place.local, proj_base, self.body(), tcx).ty;
1774 match base_ty.kind {
1775 ty::Adt(def, _) if def.has_dtor(tcx) => {
1776 self.check_if_path_or_subpath_is_moved(
1777 location, InitializationRequiringAction::Assignment,
1780 projection: proj_base,
1781 }, span), flow_state);
1783 // (base initialized; no need to
1788 // Once `let s; s.x = V; read(s.x);`,
1789 // is allowed, remove this match arm.
1790 ty::Adt(..) | ty::Tuple(..) => {
1791 check_parent_of_field(self, location, PlaceRef {
1793 projection: proj_base,
1794 }, span, flow_state);
1796 // rust-lang/rust#21232, #54499, #54986: during period where we reject
1797 // partial initialization, do not complain about unnecessary `mut` on
1798 // an attempt to do a partial initialization.
1799 self.used_mut.insert(place.local);
1808 fn check_parent_of_field<'cx, 'tcx>(
1809 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1811 base: PlaceRef<'tcx>,
1813 flow_state: &Flows<'cx, 'tcx>,
1815 // rust-lang/rust#21232: Until Rust allows reads from the
1816 // initialized parts of partially initialized structs, we
1817 // will, starting with the 2018 edition, reject attempts
1818 // to write to structs that are not fully initialized.
1820 // In other words, *until* we allow this:
1822 // 1. `let mut s; s.x = Val; read(s.x);`
1824 // we will for now disallow this:
1826 // 2. `let mut s; s.x = Val;`
1830 // 3. `let mut s = ...; drop(s); s.x=Val;`
1832 // This does not use check_if_path_or_subpath_is_moved,
1833 // because we want to *allow* reinitializations of fields:
1834 // e.g., want to allow
1836 // `let mut s = ...; drop(s.x); s.x=Val;`
1838 // This does not use check_if_full_path_is_moved on
1839 // `base`, because that would report an error about the
1840 // `base` as a whole, but in this scenario we *really*
1841 // want to report an error about the actual thing that was
1842 // moved, which may be some prefix of `base`.
1844 // Shallow so that we'll stop at any dereference; we'll
1845 // report errors about issues with such bases elsewhere.
1846 let maybe_uninits = &flow_state.uninits;
1848 // Find the shortest uninitialized prefix you can reach
1849 // without going over a Deref.
1850 let mut shortest_uninit_seen = None;
1851 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1852 let mpi = match this.move_path_for_place(prefix) {
1857 if maybe_uninits.contains(mpi) {
1859 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1860 shortest_uninit_seen,
1863 shortest_uninit_seen = Some((prefix, mpi));
1865 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1869 if let Some((prefix, mpi)) = shortest_uninit_seen {
1870 // Check for a reassignment into a uninitialized field of a union (for example,
1871 // after a move out). In this case, do not report a error here. There is an
1872 // exception, if this is the first assignment into the union (that is, there is
1873 // no move out from an earlier location) then this is an attempt at initialization
1874 // of the union - we should error in that case.
1875 let tcx = this.infcx.tcx;
1876 if let ty::Adt(def, _) =
1877 Place::ty_from(base.local, base.projection, this.body(), tcx).ty.kind
1880 if this.move_data.path_map[mpi].iter().any(|moi| {
1881 this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
1888 this.report_use_of_moved_or_uninitialized(
1890 InitializationRequiringAction::PartialAssignment,
1891 (prefix, base, span),
1898 /// Checks the permissions for the given place and read or write kind
1900 /// Returns `true` if an error is reported.
1901 fn check_access_permissions(
1903 (place, span): (Place<'tcx>, Span),
1905 is_local_mutation_allowed: LocalMutationIsAllowed,
1906 flow_state: &Flows<'cx, 'tcx>,
1910 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1911 place, kind, is_local_mutation_allowed
1918 Reservation(WriteKind::MutableBorrow(
1919 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
1921 | Write(WriteKind::MutableBorrow(
1922 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
1924 let is_local_mutation_allowed = match borrow_kind {
1925 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1926 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1927 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1929 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1931 self.add_used_mut(root_place, flow_state);
1935 error_access = AccessKind::MutableBorrow;
1936 the_place_err = place_err;
1940 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1941 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1943 self.add_used_mut(root_place, flow_state);
1947 error_access = AccessKind::Mutate;
1948 the_place_err = place_err;
1955 | WriteKind::StorageDeadOrDrop
1956 | WriteKind::MutableBorrow(BorrowKind::Shared)
1957 | WriteKind::MutableBorrow(BorrowKind::Shallow),
1961 | WriteKind::StorageDeadOrDrop
1962 | WriteKind::MutableBorrow(BorrowKind::Shared)
1963 | WriteKind::MutableBorrow(BorrowKind::Shallow),
1965 if let (Err(_), true) = (
1966 self.is_mutable(place.as_ref(), is_local_mutation_allowed),
1967 self.errors_buffer.is_empty(),
1969 // rust-lang/rust#46908: In pure NLL mode this code path should be
1970 // unreachable, but we use `delay_span_bug` because we can hit this when
1971 // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
1972 // enabled. We don't want to ICE for that case, as other errors will have
1973 // been emitted (#52262).
1974 self.infcx.tcx.sess.delay_span_bug(
1977 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
1985 // permission checks are done at Reservation point.
1991 | BorrowKind::Mut { .. }
1992 | BorrowKind::Shared
1993 | BorrowKind::Shallow,
1997 // Access authorized
2002 // rust-lang/rust#21232, #54986: during period where we reject
2003 // partial initialization, do not complain about mutability
2004 // errors except for actual mutation (as opposed to an attempt
2005 // to do a partial initialization).
2006 let previously_initialized =
2007 self.is_local_ever_initialized(place.local, flow_state).is_some();
2009 // at this point, we have set up the error reporting state.
2010 if previously_initialized {
2011 self.report_mutability_error(place, span, the_place_err, error_access, location);
2018 fn is_local_ever_initialized(
2021 flow_state: &Flows<'cx, 'tcx>,
2022 ) -> Option<InitIndex> {
2023 let mpi = self.move_data.rev_lookup.find_local(local);
2024 let ii = &self.move_data.init_path_map[mpi];
2026 if flow_state.ever_inits.contains(index) {
2033 /// Adds the place into the used mutable variables set
2034 fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2036 RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2037 // If the local may have been initialized, and it is now currently being
2038 // mutated, then it is justified to be annotated with the `mut`
2039 // keyword, since the mutation may be a possible reassignment.
2040 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2041 && self.is_local_ever_initialized(local, flow_state).is_some()
2043 self.used_mut.insert(local);
2048 place_projection: _,
2049 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2053 place_projection: place_projection @ [.., _],
2054 is_local_mutation_allowed: _,
2056 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2058 projection: place_projection,
2060 self.used_mut_upvars.push(field);
2066 /// Whether this value can be written or borrowed mutably.
2067 /// Returns the root place if the place passed in is a projection.
2070 place: PlaceRef<'tcx>,
2071 is_local_mutation_allowed: LocalMutationIsAllowed,
2072 ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2074 PlaceRef { local, projection: [] } => {
2075 let local = &self.body.local_decls[local];
2076 match local.mutability {
2077 Mutability::Not => match is_local_mutation_allowed {
2078 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2079 place_local: place.local,
2080 place_projection: place.projection,
2081 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2083 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2084 place_local: place.local,
2085 place_projection: place.projection,
2086 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2088 LocalMutationIsAllowed::No => Err(place),
2090 Mutability::Mut => Ok(RootPlace {
2091 place_local: place.local,
2092 place_projection: place.projection,
2093 is_local_mutation_allowed,
2097 PlaceRef { local: _, projection: [proj_base @ .., elem] } => {
2099 ProjectionElem::Deref => {
2101 Place::ty_from(place.local, proj_base, self.body(), self.infcx.tcx).ty;
2103 // Check the kind of deref to decide
2104 match base_ty.kind {
2105 ty::Ref(_, _, mutbl) => {
2107 // Shared borrowed data is never mutable
2108 hir::Mutability::Not => Err(place),
2109 // Mutably borrowed data is mutable, but only if we have a
2110 // unique path to the `&mut`
2111 hir::Mutability::Mut => {
2112 let mode = match self.is_upvar_field_projection(place) {
2113 Some(field) if self.upvars[field.index()].by_ref => {
2114 is_local_mutation_allowed
2116 _ => LocalMutationIsAllowed::Yes,
2120 PlaceRef { local: place.local, projection: proj_base },
2126 ty::RawPtr(tnm) => {
2128 // `*const` raw pointers are not mutable
2129 hir::Mutability::Not => Err(place),
2130 // `*mut` raw pointers are always mutable, regardless of
2131 // context. The users have to check by themselves.
2132 hir::Mutability::Mut => Ok(RootPlace {
2133 place_local: place.local,
2134 place_projection: place.projection,
2135 is_local_mutation_allowed,
2139 // `Box<T>` owns its content, so mutable if its location is mutable
2140 _ if base_ty.is_box() => self.is_mutable(
2141 PlaceRef { local: place.local, projection: proj_base },
2142 is_local_mutation_allowed,
2144 // Deref should only be for reference, pointers or boxes
2145 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2148 // All other projections are owned by their base path, so mutable if
2149 // base path is mutable
2150 ProjectionElem::Field(..)
2151 | ProjectionElem::Index(..)
2152 | ProjectionElem::ConstantIndex { .. }
2153 | ProjectionElem::Subslice { .. }
2154 | ProjectionElem::Downcast(..) => {
2155 let upvar_field_projection = self.is_upvar_field_projection(place);
2156 if let Some(field) = upvar_field_projection {
2157 let upvar = &self.upvars[field.index()];
2159 "upvar.mutability={:?} local_mutation_is_allowed={:?} \
2161 upvar, is_local_mutation_allowed, place
2163 match (upvar.mutability, is_local_mutation_allowed) {
2166 LocalMutationIsAllowed::No
2167 | LocalMutationIsAllowed::ExceptUpvars,
2169 (Mutability::Not, LocalMutationIsAllowed::Yes)
2170 | (Mutability::Mut, _) => {
2171 // Subtle: this is an upvar
2172 // reference, so it looks like
2173 // `self.foo` -- we want to double
2174 // check that the location `*self`
2175 // is mutable (i.e., this is not a
2176 // `Fn` closure). But if that
2177 // check succeeds, we want to
2178 // *blame* the mutability on
2179 // `place` (that is,
2180 // `self.foo`). This is used to
2181 // propagate the info about
2182 // whether mutability declarations
2183 // are used outwards, so that we register
2184 // the outer variable as mutable. Otherwise a
2185 // test like this fails to record the `mut`
2189 // fn foo<F: FnOnce()>(_f: F) { }
2191 // let var = Vec::new();
2197 let _ = self.is_mutable(
2198 PlaceRef { local: place.local, projection: proj_base },
2199 is_local_mutation_allowed,
2202 place_local: place.local,
2203 place_projection: place.projection,
2204 is_local_mutation_allowed,
2210 PlaceRef { local: place.local, projection: proj_base },
2211 is_local_mutation_allowed,
2220 /// If `place` is a field projection, and the field is being projected from a closure type,
2221 /// then returns the index of the field being projected. Note that this closure will always
2222 /// be `self` in the current MIR, because that is the only time we directly access the fields
2223 /// of a closure type.
2224 pub fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> {
2225 let mut place_projection = place_ref.projection;
2226 let mut by_ref = false;
2228 if let [proj_base @ .., ProjectionElem::Deref] = place_projection {
2229 place_projection = proj_base;
2233 match place_projection {
2234 [base @ .., ProjectionElem::Field(field, _ty)] => {
2235 let tcx = self.infcx.tcx;
2236 let base_ty = Place::ty_from(place_ref.local, base, self.body(), tcx).ty;
2238 if (base_ty.is_closure() || base_ty.is_generator())
2239 && (!by_ref || self.upvars[field.index()].by_ref)
2252 /// The degree of overlap between 2 places for borrow-checking.
2254 /// The places might partially overlap - in this case, we give
2255 /// up and say that they might conflict. This occurs when
2256 /// different fields of a union are borrowed. For example,
2257 /// if `u` is a union, we have no way of telling how disjoint
2258 /// `u.a.x` and `a.b.y` are.
2260 /// The places have the same type, and are either completely disjoint
2261 /// or equal - i.e., they can't "partially" overlap as can occur with
2262 /// unions. This is the "base case" on which we recur for extensions
2265 /// The places are disjoint, so we know all extensions of them
2266 /// will also be disjoint.