1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
3 use rustc::infer::{opaque_types, InferCtxt};
4 use rustc::lint::builtin::MUTABLE_BORROW_RESERVATION_CONFLICT;
5 use rustc::lint::builtin::UNUSED_MUT;
7 read_only, Body, BodyAndCache, ClearCrossCrate, Local, Location, Mutability, Operand, Place,
8 PlaceBase, PlaceElem, PlaceRef, ReadOnlyBodyAndCache, Static,
10 use rustc::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
11 use rustc::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
12 use rustc::mir::{Terminator, TerminatorKind};
13 use rustc::ty::query::Providers;
14 use rustc::ty::{self, TyCtxt};
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
16 use rustc_data_structures::graph::dominators::Dominators;
17 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder};
19 use rustc_hir::{def_id::DefId, HirId, Node};
20 use rustc_index::bit_set::BitSet;
21 use rustc_index::vec::IndexVec;
23 use smallvec::SmallVec;
24 use std::collections::BTreeMap;
28 use rustc_span::{Span, DUMMY_SP};
29 use syntax::ast::Name;
31 use crate::dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex};
32 use crate::dataflow::move_paths::{HasMoveData, InitLocation, LookupResult, MoveData, MoveError};
33 use crate::dataflow::Borrows;
34 use crate::dataflow::DataflowResultsConsumer;
35 use crate::dataflow::EverInitializedPlaces;
36 use crate::dataflow::FlowAtLocation;
37 use crate::dataflow::MoveDataParamEnv;
38 use crate::dataflow::{do_dataflow, DebugFormatted};
39 use crate::dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
40 use crate::transform::MirSource;
42 use self::diagnostics::{
43 AccessKind, OutlivesSuggestionBuilder, RegionErrorKind, RegionErrorNamingCtx, RegionErrors,
45 use self::flows::Flows;
46 use self::location::LocationTable;
47 use self::prefixes::PrefixSet;
48 use self::MutateMode::{JustWrite, WriteAndRead};
50 use self::path_utils::*;
53 mod constraint_generation;
60 mod member_constraints;
69 mod universal_regions;
72 crate use borrow_set::{BorrowData, BorrowSet};
73 crate use nll::ToRegionVid;
74 crate use place_ext::PlaceExt;
75 crate use places_conflict::{places_conflict, PlaceConflictBias};
76 crate use region_infer::RegionInferenceContext;
78 // FIXME(eddyb) perhaps move this somewhere more centrally.
85 /// If true, the capture is behind a reference.
88 mutability: Mutability,
91 pub fn provide(providers: &mut Providers<'_>) {
92 *providers = Providers { mir_borrowck, ..*providers };
95 fn mir_borrowck(tcx: TyCtxt<'_>, def_id: DefId) -> BorrowCheckResult<'_> {
96 let (input_body, promoted) = tcx.mir_validated(def_id);
97 debug!("run query mir_borrowck: {}", tcx.def_path_str(def_id));
99 let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
100 let input_body: &Body<'_> = &input_body.borrow();
101 let promoted: &IndexVec<_, _> = &promoted.borrow();
102 do_mir_borrowck(&infcx, input_body, promoted, def_id)
104 debug!("mir_borrowck done");
109 fn do_mir_borrowck<'a, 'tcx>(
110 infcx: &InferCtxt<'a, 'tcx>,
111 input_body: &Body<'tcx>,
112 input_promoted: &IndexVec<Promoted, BodyAndCache<'tcx>>,
114 ) -> BorrowCheckResult<'tcx> {
115 debug!("do_mir_borrowck(def_id = {:?})", def_id);
118 let attributes = tcx.get_attrs(def_id);
119 let param_env = tcx.param_env(def_id);
120 let id = tcx.hir().as_local_hir_id(def_id).expect("do_mir_borrowck: non-local DefId");
122 let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
123 for var_debug_info in &input_body.var_debug_info {
124 if let Some(local) = var_debug_info.place.as_local() {
125 if let Some(prev_name) = local_names[local] {
126 if var_debug_info.name != prev_name {
128 var_debug_info.source_info.span,
129 "local {:?} has many names (`{}` vs `{}`)",
136 local_names[local] = Some(var_debug_info.name);
140 // Gather the upvars of a closure, if any.
141 let tables = tcx.typeck_tables_of(def_id);
142 let upvars: Vec<_> = tables
146 .flat_map(|v| v.values())
148 let var_hir_id = upvar_id.var_path.hir_id;
149 let capture = tables.upvar_capture(*upvar_id);
150 let by_ref = match capture {
151 ty::UpvarCapture::ByValue => false,
152 ty::UpvarCapture::ByRef(..) => true,
154 let mut upvar = Upvar {
155 name: tcx.hir().name(var_hir_id),
158 mutability: Mutability::Not,
160 let bm = *tables.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
161 if bm == ty::BindByValue(hir::Mutability::Mut) {
162 upvar.mutability = Mutability::Mut;
168 // Replace all regions with fresh inference variables. This
169 // requires first making our own copy of the MIR. This copy will
170 // be modified (in place) to contain non-lexical lifetimes. It
171 // will have a lifetime tied to the inference context.
172 let body_clone: Body<'tcx> = input_body.clone();
173 let mut promoted = input_promoted.clone();
174 let mut body = BodyAndCache::new(body_clone);
176 nll::replace_regions_in_mir(infcx, def_id, param_env, &mut body, &mut promoted);
177 let body = read_only!(body); // no further changes
178 let promoted: IndexVec<_, _> = promoted.iter_mut().map(|body| read_only!(body)).collect();
180 let location_table = &LocationTable::new(&body);
182 let mut errors_buffer = Vec::new();
183 let (move_data, move_errors): (MoveData<'tcx>, Option<Vec<(Place<'tcx>, MoveError<'tcx>)>>) =
184 match MoveData::gather_moves(&body, tcx, param_env) {
185 Ok(move_data) => (move_data, None),
186 Err((move_data, move_errors)) => (move_data, Some(move_errors)),
189 let mdpe = MoveDataParamEnv { move_data, param_env };
191 let dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
192 let mut flow_inits = FlowAtLocation::new(do_dataflow(
198 MaybeInitializedPlaces::new(tcx, &body, &mdpe),
199 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
202 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
204 Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
206 // Compute non-lexical lifetimes.
207 let nll::NllOutput { regioncx, polonius_output, opt_closure_req, nll_errors } =
208 nll::compute_regions(
221 // Dump MIR results into a file, if that is enabled. This let us
222 // write unit-tests, as well as helping with debugging.
223 nll::dump_mir_results(infcx, MirSource::item(def_id), &body, ®ioncx, &opt_closure_req);
225 // We also have a `#[rustc_nll]` annotation that causes us to dump
227 nll::dump_annotation(infcx, &body, def_id, ®ioncx, &opt_closure_req, &mut errors_buffer);
229 // The various `flow_*` structures can be large. We drop `flow_inits` here
230 // so it doesn't overlap with the others below. This reduces peak memory
231 // usage significantly on some benchmarks.
234 let regioncx = Rc::new(regioncx);
236 let flow_borrows = FlowAtLocation::new(do_dataflow(
242 Borrows::new(tcx, &body, param_env, regioncx.clone(), &borrow_set),
243 |rs, i| DebugFormatted::new(&rs.location(i)),
245 let flow_uninits = FlowAtLocation::new(do_dataflow(
251 MaybeUninitializedPlaces::new(tcx, &body, &mdpe),
252 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
254 let flow_ever_inits = FlowAtLocation::new(do_dataflow(
260 EverInitializedPlaces::new(tcx, &body, &mdpe),
261 |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
264 let movable_generator = match tcx.hir().get(id) {
265 Node::Expr(&hir::Expr {
266 kind: hir::ExprKind::Closure(.., Some(hir::Movability::Static)),
272 let dominators = body.dominators();
274 let mut mbcx = MirBorrowckCtxt {
279 move_data: &mdpe.move_data,
282 locals_are_invalidated_at_exit,
283 access_place_error_reported: Default::default(),
284 reservation_error_reported: Default::default(),
285 reservation_warnings: Default::default(),
286 move_error_reported: BTreeMap::new(),
287 uninitialized_error_reported: Default::default(),
289 nonlexical_regioncx: regioncx,
290 used_mut: Default::default(),
291 used_mut_upvars: SmallVec::new(),
298 // Compute and report region errors, if any.
299 mbcx.report_region_errors(nll_errors);
301 let mut state = Flows::new(flow_borrows, flow_uninits, flow_ever_inits, polonius_output);
303 if let Some(errors) = move_errors {
304 mbcx.report_move_errors(errors);
306 mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
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 =
312 mbcx.report_conflicting_borrow(location, (&place, span), bk, &borrow);
314 let scope = mbcx.body.source_info(location).scope;
315 let lint_root = match &mbcx.body.source_scopes[scope].local_data {
316 ClearCrossCrate::Set(data) => data.lint_root,
320 // Span and message don't matter; we overwrite them below anyway
321 let mut diag = mbcx.infcx.tcx.struct_span_lint_hir(
322 MUTABLE_BORROW_RESERVATION_CONFLICT,
328 diag.message = initial_diag.styled_message().clone();
329 diag.span = initial_diag.span.clone();
331 initial_diag.cancel();
332 diag.buffer(&mut mbcx.errors_buffer);
335 // For each non-user used mutable variable, check if it's been assigned from
336 // a user-declared local. If so, then put that local into the used_mut set.
337 // Note that this set is expected to be small - only upvars from closures
338 // would have a chance of erroneously adding non-user-defined mutable vars
340 let temporary_used_locals: FxHashSet<Local> = mbcx
343 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
346 // For the remaining unused locals that are marked as mutable, we avoid linting any that
347 // were never initialized. These locals may have been removed as unreachable code; or will be
348 // linted as unused variables.
349 let unused_mut_locals =
350 mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
351 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
353 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
354 let used_mut = mbcx.used_mut;
355 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
356 let local_decl = &mbcx.body.local_decls[local];
357 let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data {
358 ClearCrossCrate::Set(data) => data.lint_root,
362 // Skip over locals that begin with an underscore or have no name
363 match mbcx.local_names[local] {
365 if name.as_str().starts_with("_") {
372 let span = local_decl.source_info.span;
373 if span.desugaring_kind().is_some() {
374 // If the `mut` arises as part of a desugaring, we should ignore it.
378 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
379 tcx.struct_span_lint_hir(
383 "variable does not need to be mutable",
385 .span_suggestion_short(
389 Applicability::MachineApplicable,
394 // Buffer any move errors that we collected and de-duplicated.
395 for (_, (_, diag)) in mbcx.move_error_reported {
396 diag.buffer(&mut mbcx.errors_buffer);
399 if !mbcx.errors_buffer.is_empty() {
400 mbcx.errors_buffer.sort_by_key(|diag| diag.sort_span);
402 for diag in mbcx.errors_buffer.drain(..) {
403 mbcx.infcx.tcx.sess.diagnostic().emit_diagnostic(&diag);
407 let result = BorrowCheckResult {
408 closure_requirements: opt_closure_req,
409 used_mut_upvars: mbcx.used_mut_upvars,
412 debug!("do_mir_borrowck: result = {:#?}", result);
417 crate struct MirBorrowckCtxt<'cx, 'tcx> {
418 crate infcx: &'cx InferCtxt<'cx, 'tcx>,
419 body: ReadOnlyBodyAndCache<'cx, 'tcx>,
421 param_env: ty::ParamEnv<'tcx>,
422 move_data: &'cx MoveData<'tcx>,
424 /// Map from MIR `Location` to `LocationIndex`; created
425 /// when MIR borrowck begins.
426 location_table: &'cx LocationTable,
428 movable_generator: bool,
429 /// This keeps track of whether local variables are free-ed when the function
430 /// exits even without a `StorageDead`, which appears to be the case for
433 /// I'm not sure this is the right approach - @eddyb could you try and
435 locals_are_invalidated_at_exit: bool,
436 /// This field keeps track of when borrow errors are reported in the access_place function
437 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
438 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
439 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
441 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
442 /// This field keeps track of when borrow conflict errors are reported
443 /// for reservations, so that we don't report seemingly duplicate
444 /// errors for corresponding activations.
446 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
447 // but it is currently inconvenient to track down the `BorrowIndex`
448 // at the time we detect and report a reservation error.
449 reservation_error_reported: FxHashSet<Place<'tcx>>,
450 /// Migration warnings to be reported for #56254. We delay reporting these
451 /// so that we can suppress the warning if there's a corresponding error
452 /// for the activation of the borrow.
453 reservation_warnings:
454 FxHashMap<BorrowIndex, (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)>,
455 /// This field keeps track of move errors that are to be reported for given move indicies.
457 /// There are situations where many errors can be reported for a single move out (see #53807)
458 /// and we want only the best of those errors.
460 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
461 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
462 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
463 /// all move errors have been reported, any diagnostics in this map are added to the buffer
466 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
467 /// when errors in the map are being re-added to the error buffer so that errors with the
468 /// same primary span come out in a consistent order.
469 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'cx, 'tcx>, DiagnosticBuilder<'cx>)>,
470 /// This field keeps track of errors reported in the checking of uninitialized variables,
471 /// so that we don't report seemingly duplicate errors.
472 uninitialized_error_reported: FxHashSet<PlaceRef<'cx, 'tcx>>,
473 /// Errors to be reported buffer
474 errors_buffer: Vec<Diagnostic>,
475 /// This field keeps track of all the local variables that are declared mut and are mutated.
476 /// Used for the warning issued by an unused mutable local variable.
477 used_mut: FxHashSet<Local>,
478 /// If the function we're checking is a closure, then we'll need to report back the list of
479 /// mutable upvars that have been used. This field keeps track of them.
480 used_mut_upvars: SmallVec<[Field; 8]>,
481 /// Non-lexical region inference context, if NLL is enabled. This
482 /// contains the results from region inference and lets us e.g.
483 /// find out which CFG points are contained in each borrow region.
484 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
486 /// The set of borrows extracted from the MIR
487 borrow_set: Rc<BorrowSet<'tcx>>,
489 /// Dominators for MIR
490 dominators: Dominators<BasicBlock>,
492 /// Information about upvars not necessarily preserved in types or MIR
495 /// Names of local (user) variables (extracted from `var_debug_info`).
496 local_names: IndexVec<Local, Option<Name>>,
500 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
501 // 2. loans made in overlapping scopes do not conflict
502 // 3. assignments do not affect things loaned out as immutable
503 // 4. moves do not affect things loaned out in any way
504 impl<'cx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
505 type FlowState = Flows<'cx, 'tcx>;
507 fn body(&self) -> &'cx Body<'tcx> {
511 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
512 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
515 fn visit_statement_entry(
518 stmt: &'cx Statement<'tcx>,
519 flow_state: &Self::FlowState,
521 debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {}", location, stmt, flow_state);
522 let span = stmt.source_info.span;
524 self.check_activations(location, span, flow_state);
527 StatementKind::Assign(box (ref lhs, ref rhs)) => {
528 self.consume_rvalue(location, (rhs, span), flow_state);
530 self.mutate_place(location, (lhs, span), Shallow(None), JustWrite, flow_state);
532 StatementKind::FakeRead(_, box ref place) => {
533 // Read for match doesn't access any memory and is used to
534 // assert that a place is safe and live. So we don't have to
535 // do any checks here.
537 // FIXME: Remove check that the place is initialized. This is
538 // needed for now because matches don't have never patterns yet.
539 // So this is the only place we prevent
543 self.check_if_path_or_subpath_is_moved(
545 InitializationRequiringAction::Use,
546 (place.as_ref(), span),
550 StatementKind::SetDiscriminant { ref place, variant_index: _ } => {
551 self.mutate_place(location, (place, span), Shallow(None), JustWrite, flow_state);
553 StatementKind::InlineAsm(ref asm) => {
554 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
556 // FIXME(eddyb) indirect inline asm outputs should
557 // be encoded through MIR place derefs instead.
561 (Deep, Read(ReadKind::Copy)),
562 LocalMutationIsAllowed::No,
565 self.check_if_path_or_subpath_is_moved(
567 InitializationRequiringAction::Use,
568 (output.as_ref(), o.span),
575 if o.is_rw { Deep } else { Shallow(None) },
576 if o.is_rw { WriteAndRead } else { JustWrite },
581 for (_, input) in asm.inputs.iter() {
582 self.consume_operand(location, (input, span), flow_state);
586 | StatementKind::AscribeUserType(..)
587 | StatementKind::Retag { .. }
588 | StatementKind::StorageLive(..) => {
589 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
592 StatementKind::StorageDead(local) => {
595 (&Place::from(local), span),
596 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
597 LocalMutationIsAllowed::Yes,
604 fn visit_terminator_entry(
607 term: &'cx Terminator<'tcx>,
608 flow_state: &Self::FlowState,
611 debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {}", location, term, flow_state);
612 let span = term.source_info.span;
614 self.check_activations(location, span, flow_state);
617 TerminatorKind::SwitchInt { ref discr, switch_ty: _, values: _, targets: _ } => {
618 self.consume_operand(loc, (discr, span), flow_state);
620 TerminatorKind::Drop { location: ref drop_place, target: _, unwind: _ } => {
621 let tcx = self.infcx.tcx;
623 // Compute the type with accurate region information.
624 let drop_place_ty = drop_place.ty(*self.body, self.infcx.tcx);
626 // Erase the regions.
627 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
629 // "Lift" into the tcx -- once regions are erased, this type should be in the
630 // global arenas; this "lift" operation basically just asserts that is true, but
631 // that is useful later.
632 tcx.lift(&drop_place_ty).unwrap();
635 "visit_terminator_drop \
636 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
637 loc, term, drop_place, drop_place_ty, span
643 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
644 LocalMutationIsAllowed::Yes,
648 TerminatorKind::DropAndReplace {
649 location: ref drop_place,
650 value: ref new_value,
654 self.mutate_place(loc, (drop_place, span), Deep, JustWrite, flow_state);
655 self.consume_operand(loc, (new_value, span), flow_state);
657 TerminatorKind::Call {
664 self.consume_operand(loc, (func, span), flow_state);
666 self.consume_operand(loc, (arg, span), flow_state);
668 if let Some((ref dest, _ /*bb*/)) = *destination {
669 self.mutate_place(loc, (dest, span), Deep, JustWrite, flow_state);
672 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
673 self.consume_operand(loc, (cond, span), flow_state);
674 use rustc::mir::interpret::PanicInfo;
675 if let PanicInfo::BoundsCheck { ref len, ref index } = *msg {
676 self.consume_operand(loc, (len, span), flow_state);
677 self.consume_operand(loc, (index, span), flow_state);
681 TerminatorKind::Yield { ref value, resume: _, drop: _ } => {
682 self.consume_operand(loc, (value, span), flow_state);
684 if self.movable_generator {
685 // Look for any active borrows to locals
686 let borrow_set = self.borrow_set.clone();
687 flow_state.with_outgoing_borrows(|borrows| {
689 let borrow = &borrow_set[i];
690 self.check_for_local_borrow(borrow, span);
696 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
697 // Returning from the function implicitly kills storage for all locals and statics.
698 // Often, the storage will already have been killed by an explicit
699 // StorageDead, but we don't always emit those (notably on unwind paths),
700 // so this "extra check" serves as a kind of backup.
701 let borrow_set = self.borrow_set.clone();
702 flow_state.with_outgoing_borrows(|borrows| {
704 let borrow = &borrow_set[i];
705 self.check_for_invalidation_at_exit(loc, borrow, span);
709 TerminatorKind::Goto { target: _ }
710 | TerminatorKind::Abort
711 | TerminatorKind::Unreachable
712 | TerminatorKind::FalseEdges { real_target: _, imaginary_target: _ }
713 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
714 // no data used, thus irrelevant to borrowck
720 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
726 use self::AccessDepth::{Deep, Shallow};
727 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
729 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
730 enum ArtificialField {
735 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
737 /// From the RFC: "A *shallow* access means that the immediate
738 /// fields reached at P are accessed, but references or pointers
739 /// found within are not dereferenced. Right now, the only access
740 /// that is shallow is an assignment like `x = ...;`, which would
741 /// be a *shallow write* of `x`."
742 Shallow(Option<ArtificialField>),
744 /// From the RFC: "A *deep* access means that all data reachable
745 /// through the given place may be invalidated or accesses by
749 /// Access is Deep only when there is a Drop implementation that
750 /// can reach the data behind the reference.
754 /// Kind of access to a value: read or write
755 /// (For informational purposes only)
756 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
758 /// From the RFC: "A *read* means that the existing data may be
759 /// read, but will not be changed."
762 /// From the RFC: "A *write* means that the data may be mutated to
763 /// new values or otherwise invalidated (for example, it could be
764 /// de-initialized, as in a move operation).
767 /// For two-phase borrows, we distinguish a reservation (which is treated
768 /// like a Read) from an activation (which is treated like a write), and
769 /// each of those is furthermore distinguished from Reads/Writes above.
770 Reservation(WriteKind),
771 Activation(WriteKind, BorrowIndex),
774 /// Kind of read access to a value
775 /// (For informational purposes only)
776 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
782 /// Kind of write access to a value
783 /// (For informational purposes only)
784 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
787 MutableBorrow(BorrowKind),
792 /// When checking permissions for a place access, this flag is used to indicate that an immutable
793 /// local place can be mutated.
795 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
796 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
797 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
798 // `is_declared_mutable()`.
799 // - Take flow state into consideration in `is_assignable()` for local variables.
800 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
801 enum LocalMutationIsAllowed {
803 /// We want use of immutable upvars to cause a "write to immutable upvar"
804 /// error, not an "reassignment" error.
809 #[derive(Copy, Clone, Debug)]
810 enum InitializationRequiringAction {
819 struct RootPlace<'d, 'tcx> {
820 place_base: &'d PlaceBase<'tcx>,
821 place_projection: &'d [PlaceElem<'tcx>],
822 is_local_mutation_allowed: LocalMutationIsAllowed,
825 impl InitializationRequiringAction {
826 fn as_noun(self) -> &'static str {
828 InitializationRequiringAction::Update => "update",
829 InitializationRequiringAction::Borrow => "borrow",
830 InitializationRequiringAction::MatchOn => "use", // no good noun
831 InitializationRequiringAction::Use => "use",
832 InitializationRequiringAction::Assignment => "assign",
833 InitializationRequiringAction::PartialAssignment => "assign to part",
837 fn as_verb_in_past_tense(self) -> &'static str {
839 InitializationRequiringAction::Update => "updated",
840 InitializationRequiringAction::Borrow => "borrowed",
841 InitializationRequiringAction::MatchOn => "matched on",
842 InitializationRequiringAction::Use => "used",
843 InitializationRequiringAction::Assignment => "assigned",
844 InitializationRequiringAction::PartialAssignment => "partially assigned",
849 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
850 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
851 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
852 /// place is initialized and (b) it is not borrowed in some way that would prevent this
855 /// Returns `true` if an error is reported.
859 place_span: (&Place<'tcx>, Span),
860 kind: (AccessDepth, ReadOrWrite),
861 is_local_mutation_allowed: LocalMutationIsAllowed,
862 flow_state: &Flows<'cx, 'tcx>,
866 if let Activation(_, borrow_index) = rw {
867 if self.reservation_error_reported.contains(&place_span.0) {
869 "skipping access_place for activation of invalid reservation \
870 place: {:?} borrow_index: {:?}",
871 place_span.0, borrow_index
877 // Check is_empty() first because it's the common case, and doing that
878 // way we avoid the clone() call.
879 if !self.access_place_error_reported.is_empty()
880 && self.access_place_error_reported.contains(&(place_span.0.clone(), place_span.1))
883 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
889 let mutability_error = self.check_access_permissions(
892 is_local_mutation_allowed,
897 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
899 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
900 // Suppress this warning when there's an error being emitted for the
901 // same borrow: fixing the error is likely to fix the warning.
902 self.reservation_warnings.remove(&borrow_idx);
905 if conflict_error || mutability_error {
906 debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
908 self.access_place_error_reported.insert((place_span.0.clone(), place_span.1));
912 fn check_access_for_conflict(
915 place_span: (&Place<'tcx>, Span),
918 flow_state: &Flows<'cx, 'tcx>,
921 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
922 location, place_span, sd, rw,
925 let mut error_reported = false;
926 let tcx = self.infcx.tcx;
927 let body = self.body;
928 let body: &Body<'_> = &body;
929 let param_env = self.param_env;
930 let location_table = self.location_table.start_index(location);
931 let borrow_set = self.borrow_set.clone();
932 each_borrow_involving_path(
940 flow_state.borrows_in_scope(location_table),
941 |this, borrow_index, borrow| match (rw, borrow.kind) {
942 // Obviously an activation is compatible with its own
943 // reservation (or even prior activating uses of same
944 // borrow); so don't check if they interfere.
946 // NOTE: *reservations* do conflict with themselves;
947 // thus aren't injecting unsoundenss w/ this check.)
948 (Activation(_, activating), _) if activating == borrow_index => {
950 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
951 skipping {:?} b/c activation of same borrow_index",
955 (borrow_index, borrow),
960 (Read(_), BorrowKind::Shared)
961 | (Read(_), BorrowKind::Shallow)
962 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
963 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
967 (Write(WriteKind::Move), BorrowKind::Shallow) => {
968 // Handled by initialization checks.
972 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
973 // Reading from mere reservations of mutable-borrows is OK.
974 if !is_active(&this.dominators, borrow, location) {
975 assert!(allow_two_phase_borrow(borrow.kind));
976 return Control::Continue;
979 error_reported = true;
982 this.report_use_while_mutably_borrowed(location, place_span, borrow)
983 .buffer(&mut this.errors_buffer);
985 ReadKind::Borrow(bk) => {
986 this.report_conflicting_borrow(location, place_span, bk, borrow)
987 .buffer(&mut this.errors_buffer);
993 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
994 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared)
996 tcx.migrate_borrowck()
997 && this.borrow_set.location_map.contains_key(&location)
1000 let bi = this.borrow_set.location_map[&location];
1002 "recording invalid reservation of place: {:?} with \
1003 borrow index {:?} as warning",
1006 // rust-lang/rust#56254 - This was previously permitted on
1007 // the 2018 edition so we emit it as a warning. We buffer
1008 // these sepately so that we only emit a warning if borrow
1009 // checking was otherwise successful.
1010 this.reservation_warnings.insert(
1012 (place_span.0.clone(), place_span.1, location, bk, borrow.clone()),
1015 // Don't suppress actual errors.
1019 (Reservation(kind), _) | (Activation(kind, _), _) | (Write(kind), _) => {
1021 Reservation(..) => {
1023 "recording invalid reservation of \
1027 this.reservation_error_reported.insert(place_span.0.clone());
1029 Activation(_, activating) => {
1031 "observing check_place for activation of \
1032 borrow_index: {:?}",
1036 Read(..) | Write(..) => {}
1039 error_reported = true;
1041 WriteKind::MutableBorrow(bk) => {
1042 this.report_conflicting_borrow(location, place_span, bk, borrow)
1043 .buffer(&mut this.errors_buffer);
1045 WriteKind::StorageDeadOrDrop => this
1046 .report_borrowed_value_does_not_live_long_enough(
1052 WriteKind::Mutate => {
1053 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1055 WriteKind::Move => {
1056 this.report_move_out_while_borrowed(location, place_span, borrow)
1070 place_span: (&'cx Place<'tcx>, Span),
1073 flow_state: &Flows<'cx, 'tcx>,
1075 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1077 MutateMode::WriteAndRead => {
1078 self.check_if_path_or_subpath_is_moved(
1080 InitializationRequiringAction::Update,
1081 (place_span.0.as_ref(), place_span.1),
1085 MutateMode::JustWrite => {
1086 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1090 // Special case: you can assign a immutable local variable
1091 // (e.g., `x = ...`) so long as it has never been initialized
1092 // before (at this point in the flow).
1093 if let Some(local) = place_span.0.as_local() {
1094 if let Mutability::Not = self.body.local_decls[local].mutability {
1095 // check for reassignments to immutable local variables
1096 self.check_if_reassignment_to_immutable_state(
1097 location, local, place_span, flow_state,
1103 // Otherwise, use the normal access permission rules.
1107 (kind, Write(WriteKind::Mutate)),
1108 LocalMutationIsAllowed::No,
1116 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1117 flow_state: &Flows<'cx, 'tcx>,
1120 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1121 let access_kind = match bk {
1122 BorrowKind::Shallow => {
1123 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1125 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1126 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1127 let wk = WriteKind::MutableBorrow(bk);
1128 if allow_two_phase_borrow(bk) {
1129 (Deep, Reservation(wk))
1140 LocalMutationIsAllowed::No,
1144 let action = if bk == BorrowKind::Shallow {
1145 InitializationRequiringAction::MatchOn
1147 InitializationRequiringAction::Borrow
1150 self.check_if_path_or_subpath_is_moved(
1153 (place.as_ref(), span),
1158 Rvalue::AddressOf(mutability, ref place) => {
1159 let access_kind = match mutability {
1160 Mutability::Mut => (
1162 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1163 allow_two_phase_borrow: false,
1166 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1173 LocalMutationIsAllowed::No,
1177 self.check_if_path_or_subpath_is_moved(
1179 InitializationRequiringAction::Borrow,
1180 (place.as_ref(), span),
1185 Rvalue::Use(ref operand)
1186 | Rvalue::Repeat(ref operand, _)
1187 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1188 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1189 self.consume_operand(location, (operand, span), flow_state)
1192 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1193 let af = match *rvalue {
1194 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1195 Rvalue::Discriminant(..) => None,
1196 _ => unreachable!(),
1201 (Shallow(af), Read(ReadKind::Copy)),
1202 LocalMutationIsAllowed::No,
1205 self.check_if_path_or_subpath_is_moved(
1207 InitializationRequiringAction::Use,
1208 (place.as_ref(), span),
1213 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1214 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1215 self.consume_operand(location, (operand1, span), flow_state);
1216 self.consume_operand(location, (operand2, span), flow_state);
1219 Rvalue::NullaryOp(_op, _ty) => {
1220 // nullary ops take no dynamic input; no borrowck effect.
1222 // FIXME: is above actually true? Do we want to track
1223 // the fact that uninitialized data can be created via
1227 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1228 // We need to report back the list of mutable upvars that were
1229 // moved into the closure and subsequently used by the closure,
1230 // in order to populate our used_mut set.
1231 match **aggregate_kind {
1232 AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
1233 let BorrowCheckResult { used_mut_upvars, .. } =
1234 self.infcx.tcx.mir_borrowck(def_id);
1235 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1236 for field in used_mut_upvars {
1237 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1240 AggregateKind::Adt(..)
1241 | AggregateKind::Array(..)
1242 | AggregateKind::Tuple { .. } => (),
1245 for operand in operands {
1246 self.consume_operand(location, (operand, span), flow_state);
1252 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1253 let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1254 if !place.projection.is_empty() {
1255 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1256 this.used_mut_upvars.push(field);
1258 } else if let PlaceBase::Local(local) = place.base {
1259 this.used_mut.insert(local);
1263 // This relies on the current way that by-value
1264 // captures of a closure are copied/moved directly
1265 // when generating MIR.
1267 Operand::Move(ref place) | Operand::Copy(ref place) => {
1268 match place.as_local() {
1269 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1270 if self.body.local_decls[local].ty.is_mutable_ptr() {
1271 // The variable will be marked as mutable by the borrow.
1274 // This is an edge case where we have a `move` closure
1275 // inside a non-move closure, and the inner closure
1276 // contains a mutation:
1279 // || { move || { i += 1; }; };
1281 // In this case our usual strategy of assuming that the
1282 // variable will be captured by mutable reference is
1283 // wrong, since `i` can be copied into the inner
1284 // closure from a shared reference.
1286 // As such we have to search for the local that this
1287 // capture comes from and mark it as being used as mut.
1289 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1290 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1291 &self.move_data.inits[init_index]
1293 bug!("temporary should be initialized exactly once")
1296 let loc = match init.location {
1297 InitLocation::Statement(stmt) => stmt,
1298 _ => bug!("temporary initialized in arguments"),
1301 let body = self.body;
1302 let bbd = &body[loc.block];
1303 let stmt = &bbd.statements[loc.statement_index];
1304 debug!("temporary assigned in: stmt={:?}", stmt);
1306 if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, ref source))) =
1309 propagate_closure_used_mut_place(self, source);
1312 "closures should only capture user variables \
1313 or references to user variables"
1317 _ => propagate_closure_used_mut_place(self, place),
1320 Operand::Constant(..) => {}
1327 (operand, span): (&'cx Operand<'tcx>, Span),
1328 flow_state: &Flows<'cx, 'tcx>,
1331 Operand::Copy(ref place) => {
1332 // copy of place: check if this is "copy of frozen path"
1333 // (FIXME: see check_loans.rs)
1337 (Deep, Read(ReadKind::Copy)),
1338 LocalMutationIsAllowed::No,
1342 // Finally, check if path was already moved.
1343 self.check_if_path_or_subpath_is_moved(
1345 InitializationRequiringAction::Use,
1346 (place.as_ref(), span),
1350 Operand::Move(ref place) => {
1351 // move of place: check if this is move of already borrowed path
1355 (Deep, Write(WriteKind::Move)),
1356 LocalMutationIsAllowed::Yes,
1360 // Finally, check if path was already moved.
1361 self.check_if_path_or_subpath_is_moved(
1363 InitializationRequiringAction::Use,
1364 (place.as_ref(), span),
1368 Operand::Constant(_) => {}
1372 /// Checks whether a borrow of this place is invalidated when the function
1374 fn check_for_invalidation_at_exit(
1377 borrow: &BorrowData<'tcx>,
1380 debug!("check_for_invalidation_at_exit({:?})", borrow);
1381 let place = &borrow.borrowed_place;
1382 let deref = [ProjectionElem::Deref];
1383 let mut root_place = PlaceRef { base: &place.base, projection: &[] };
1385 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1386 // we just know that all locals are dropped at function exit (otherwise
1387 // we'll have a memory leak) and assume that all statics have a destructor.
1389 // FIXME: allow thread-locals to borrow other thread locals?
1391 let (might_be_alive, will_be_dropped) = match root_place.base {
1392 PlaceBase::Static(_) => (true, false),
1393 PlaceBase::Local(local) => {
1394 if self.body.local_decls[*local].is_ref_to_thread_local() {
1395 // Thread-locals might be dropped after the function exits
1396 // We have to dereference the outer reference because
1397 // borrows don't conflict behind shared references.
1398 root_place.projection = &deref;
1401 (false, self.locals_are_invalidated_at_exit)
1406 if !will_be_dropped {
1407 debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
1411 let sd = if might_be_alive { Deep } else { Shallow(None) };
1413 if places_conflict::borrow_conflicts_with_place(
1421 places_conflict::PlaceConflictBias::Overlap,
1423 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1424 // FIXME: should be talking about the region lifetime instead
1425 // of just a span here.
1426 let span = self.infcx.tcx.sess.source_map().end_point(span);
1427 self.report_borrowed_value_does_not_live_long_enough(
1436 /// Reports an error if this is a borrow of local data.
1437 /// This is called for all Yield expressions on movable generators
1438 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1439 debug!("check_for_local_borrow({:?})", borrow);
1441 if borrow_of_local_data(&borrow.borrowed_place) {
1442 let err = self.cannot_borrow_across_generator_yield(
1443 self.retrieve_borrow_spans(borrow).var_or_use(),
1447 err.buffer(&mut self.errors_buffer);
1451 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1452 // Two-phase borrow support: For each activation that is newly
1453 // generated at this statement, check if it interferes with
1455 let borrow_set = self.borrow_set.clone();
1456 for &borrow_index in borrow_set.activations_at_location(location) {
1457 let borrow = &borrow_set[borrow_index];
1459 // only mutable borrows should be 2-phase
1460 assert!(match borrow.kind {
1461 BorrowKind::Shared | BorrowKind::Shallow => false,
1462 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1467 (&borrow.borrowed_place, span),
1468 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1469 LocalMutationIsAllowed::No,
1472 // We do not need to call `check_if_path_or_subpath_is_moved`
1473 // again, as we already called it when we made the
1474 // initial reservation.
1478 /// Produces nice borrowck error diagnostics for all the errors collected in `nll_errors`.
1479 fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
1480 // Iterate through all the errors, producing a diagnostic for each one. The diagnostics are
1481 // buffered in the `MirBorrowckCtxt`.
1483 // FIXME(mark-i-m): Would be great to get rid of the naming context.
1484 let mut region_naming = RegionErrorNamingCtx::new();
1485 let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
1487 for nll_error in nll_errors.into_iter() {
1489 RegionErrorKind::TypeTestDoesNotLiveLongEnough { span, generic } => {
1490 // FIXME. We should handle this case better. It
1491 // indicates that we have e.g., some region variable
1492 // whose value is like `'a+'b` where `'a` and `'b` are
1493 // distinct unrelated univesal regions that are not
1494 // known to outlive one another. It'd be nice to have
1495 // some examples where this arises to decide how best
1496 // to report it; we could probably handle it by
1497 // iterating over the universal regions and reporting
1498 // an error that multiple bounds are required.
1502 .struct_span_err(span, &format!("`{}` does not live long enough", generic))
1503 .buffer(&mut self.errors_buffer);
1506 RegionErrorKind::TypeTestGenericBoundError {
1511 let region_scope_tree = &self.infcx.tcx.region_scope_tree(self.mir_def_id);
1513 .construct_generic_bound_failure(
1520 .buffer(&mut self.errors_buffer);
1523 RegionErrorKind::UnexpectedHiddenRegion {
1528 let region_scope_tree = &self.infcx.tcx.region_scope_tree(self.mir_def_id);
1529 opaque_types::unexpected_hidden_region_diagnostic(
1531 Some(region_scope_tree),
1536 .buffer(&mut self.errors_buffer);
1539 RegionErrorKind::BoundUniversalRegionError {
1544 // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
1545 let (_, span) = self.nonlexical_regioncx.find_outlives_blame_span(
1552 // FIXME: improve this error message
1556 .struct_span_err(span, "higher-ranked subtype error")
1557 .buffer(&mut self.errors_buffer);
1560 RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
1562 let db = self.nonlexical_regioncx.report_error(
1567 &mut outlives_suggestion,
1571 db.buffer(&mut self.errors_buffer);
1573 // We only report the first error, so as not to overwhelm the user. See
1574 // `RegRegionErrorKind` docs.
1576 // FIXME: currently we do nothing with these, but perhaps we can do better?
1577 // FIXME: try collecting these constraints on the outlives suggestion
1578 // builder. Does it make the suggestions any better?
1580 "Unreported region error: can't prove that {:?}: {:?}",
1581 longer_fr, shorter_fr
1588 // Emit one outlives suggestions for each MIR def we borrowck
1589 outlives_suggestion.add_suggestion(self, &mut region_naming);
1593 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
1594 fn check_if_reassignment_to_immutable_state(
1598 place_span: (&Place<'tcx>, Span),
1599 flow_state: &Flows<'cx, 'tcx>,
1601 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1603 // Check if any of the initializiations of `local` have happened yet:
1604 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1605 // And, if so, report an error.
1606 let init = &self.move_data.inits[init_index];
1607 let span = init.span(&self.body);
1608 self.report_illegal_reassignment(location, place_span, span, place_span.0);
1612 fn check_if_full_path_is_moved(
1615 desired_action: InitializationRequiringAction,
1616 place_span: (PlaceRef<'cx, 'tcx>, Span),
1617 flow_state: &Flows<'cx, 'tcx>,
1619 let maybe_uninits = &flow_state.uninits;
1623 // 1. Move of `a.b.c`, use of `a.b.c`
1624 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1625 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1626 // partial initialization support, one might have `a.x`
1627 // initialized but not `a.b`.
1631 // 4. Move of `a.b.c`, use of `a.b.d`
1632 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1633 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1634 // must have been initialized for the use to be sound.
1635 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1637 // The dataflow tracks shallow prefixes distinctly (that is,
1638 // field-accesses on P distinctly from P itself), in order to
1639 // track substructure initialization separately from the whole
1642 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1643 // which we have a MovePath is `a.b`, then that means that the
1644 // initialization state of `a.b` is all we need to inspect to
1645 // know if `a.b.c` is valid (and from that we infer that the
1646 // dereference and `.d` access is also valid, since we assume
1647 // `a.b.c` is assigned a reference to a initialized and
1648 // well-formed record structure.)
1650 // Therefore, if we seek out the *closest* prefix for which we
1651 // have a MovePath, that should capture the initialization
1652 // state for the place scenario.
1654 // This code covers scenarios 1, 2, and 3.
1656 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1657 match self.move_path_closest_to(place_span.0) {
1658 Ok((prefix, mpi)) => {
1659 if maybe_uninits.contains(mpi) {
1660 self.report_use_of_moved_or_uninitialized(
1663 (prefix, place_span.0, place_span.1),
1668 Err(NoMovePathFound::ReachedStatic) => {
1669 // Okay: we do not build MoveData for static variables
1670 } // Only query longest prefix with a MovePath, not further
1671 // ancestors; dataflow recurs on children when parents
1672 // move (to support partial (re)inits).
1674 // (I.e., querying parents breaks scenario 7; but may want
1675 // to do such a query based on partial-init feature-gate.)
1679 /// Subslices correspond to multiple move paths, so we iterate through the
1680 /// elements of the base array. For each element we check
1682 /// * Does this element overlap with our slice.
1683 /// * Is any part of it uninitialized.
1684 fn check_if_subslice_element_is_moved(
1687 desired_action: InitializationRequiringAction,
1688 place_span: (PlaceRef<'cx, 'tcx>, Span),
1689 maybe_uninits: &FlowAtLocation<'tcx, MaybeUninitializedPlaces<'cx, 'tcx>>,
1693 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1694 let mut child = self.move_data.move_paths[mpi].first_child;
1695 while let Some(child_mpi) = child {
1696 let child_move_place = &self.move_data.move_paths[child_mpi];
1697 let child_place = &child_move_place.place;
1698 let last_proj = child_place.projection.last().unwrap();
1699 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
1700 debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
1702 if (from..to).contains(offset) {
1703 if let Some(uninit_child) = maybe_uninits.has_any_child_of(child_mpi) {
1704 self.report_use_of_moved_or_uninitialized(
1707 (place_span.0, place_span.0, place_span.1),
1710 return; // don't bother finding other problems.
1714 child = child_move_place.next_sibling;
1719 fn check_if_path_or_subpath_is_moved(
1722 desired_action: InitializationRequiringAction,
1723 place_span: (PlaceRef<'cx, 'tcx>, Span),
1724 flow_state: &Flows<'cx, 'tcx>,
1726 let maybe_uninits = &flow_state.uninits;
1730 // 1. Move of `a.b.c`, use of `a` or `a.b`
1731 // partial initialization support, one might have `a.x`
1732 // initialized but not `a.b`.
1733 // 2. All bad scenarios from `check_if_full_path_is_moved`
1737 // 3. Move of `a.b.c`, use of `a.b.d`
1738 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1739 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1740 // must have been initialized for the use to be sound.
1741 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1743 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1745 if let [base_proj @ .., ProjectionElem::Subslice { from, to, from_end: false }] =
1746 place_span.0.projection
1749 Place::ty_from(place_span.0.base, base_proj, self.body(), self.infcx.tcx);
1750 if let ty::Array(..) = place_ty.ty.kind {
1751 let array_place = PlaceRef { base: place_span.0.base, projection: base_proj };
1752 self.check_if_subslice_element_is_moved(
1755 (array_place, place_span.1),
1764 // A move of any shallow suffix of `place` also interferes
1765 // with an attempt to use `place`. This is scenario 3 above.
1767 // (Distinct from handling of scenarios 1+2+4 above because
1768 // `place` does not interfere with suffixes of its prefixes,
1769 // e.g., `a.b.c` does not interfere with `a.b.d`)
1771 // This code covers scenario 1.
1773 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1774 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1775 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1776 self.report_use_of_moved_or_uninitialized(
1779 (place_span.0, place_span.0, place_span.1),
1782 return; // don't bother finding other problems.
1787 /// Currently MoveData does not store entries for all places in
1788 /// the input MIR. For example it will currently filter out
1789 /// places that are Copy; thus we do not track places of shared
1790 /// reference type. This routine will walk up a place along its
1791 /// prefixes, searching for a foundational place that *is*
1792 /// tracked in the MoveData.
1794 /// An Err result includes a tag indicated why the search failed.
1795 /// Currently this can only occur if the place is built off of a
1796 /// static variable, as we do not track those in the MoveData.
1797 fn move_path_closest_to(
1799 place: PlaceRef<'_, 'tcx>,
1800 ) -> Result<(PlaceRef<'cx, 'tcx>, MovePathIndex), NoMovePathFound> {
1801 match self.move_data.rev_lookup.find(place) {
1802 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
1803 Ok((self.move_data.move_paths[mpi].place.as_ref(), mpi))
1805 LookupResult::Parent(None) => Err(NoMovePathFound::ReachedStatic),
1809 fn move_path_for_place(&mut self, place: PlaceRef<'_, 'tcx>) -> Option<MovePathIndex> {
1810 // If returns None, then there is no move path corresponding
1811 // to a direct owner of `place` (which means there is nothing
1812 // that borrowck tracks for its analysis).
1814 match self.move_data.rev_lookup.find(place) {
1815 LookupResult::Parent(_) => None,
1816 LookupResult::Exact(mpi) => Some(mpi),
1820 fn check_if_assigned_path_is_moved(
1823 (place, span): (&'cx Place<'tcx>, Span),
1824 flow_state: &Flows<'cx, 'tcx>,
1826 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1828 // None case => assigning to `x` does not require `x` be initialized.
1829 let mut cursor = &*place.projection.as_ref();
1830 while let [proj_base @ .., elem] = cursor {
1834 ProjectionElem::Index(_/*operand*/) |
1835 ProjectionElem::ConstantIndex { .. } |
1836 // assigning to P[i] requires P to be valid.
1837 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1838 // assigning to (P->variant) is okay if assigning to `P` is okay
1840 // FIXME: is this true even if P is a adt with a dtor?
1843 // assigning to (*P) requires P to be initialized
1844 ProjectionElem::Deref => {
1845 self.check_if_full_path_is_moved(
1846 location, InitializationRequiringAction::Use,
1849 projection: proj_base,
1850 }, span), flow_state);
1851 // (base initialized; no need to
1856 ProjectionElem::Subslice { .. } => {
1857 panic!("we don't allow assignments to subslices, location: {:?}",
1861 ProjectionElem::Field(..) => {
1862 // if type of `P` has a dtor, then
1863 // assigning to `P.f` requires `P` itself
1864 // be already initialized
1865 let tcx = self.infcx.tcx;
1866 let base_ty = Place::ty_from(&place.base, proj_base, self.body(), tcx).ty;
1867 match base_ty.kind {
1868 ty::Adt(def, _) if def.has_dtor(tcx) => {
1869 self.check_if_path_or_subpath_is_moved(
1870 location, InitializationRequiringAction::Assignment,
1873 projection: proj_base,
1874 }, span), flow_state);
1876 // (base initialized; no need to
1881 // Once `let s; s.x = V; read(s.x);`,
1882 // is allowed, remove this match arm.
1883 ty::Adt(..) | ty::Tuple(..) => {
1884 check_parent_of_field(self, location, PlaceRef {
1886 projection: proj_base,
1887 }, span, flow_state);
1889 if let PlaceBase::Local(local) = place.base {
1890 // rust-lang/rust#21232,
1891 // #54499, #54986: during
1892 // period where we reject
1893 // partial initialization, do
1894 // not complain about
1895 // unnecessary `mut` on an
1896 // attempt to do a partial
1898 self.used_mut.insert(local);
1908 fn check_parent_of_field<'cx, 'tcx>(
1909 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1911 base: PlaceRef<'cx, 'tcx>,
1913 flow_state: &Flows<'cx, 'tcx>,
1915 // rust-lang/rust#21232: Until Rust allows reads from the
1916 // initialized parts of partially initialized structs, we
1917 // will, starting with the 2018 edition, reject attempts
1918 // to write to structs that are not fully initialized.
1920 // In other words, *until* we allow this:
1922 // 1. `let mut s; s.x = Val; read(s.x);`
1924 // we will for now disallow this:
1926 // 2. `let mut s; s.x = Val;`
1930 // 3. `let mut s = ...; drop(s); s.x=Val;`
1932 // This does not use check_if_path_or_subpath_is_moved,
1933 // because we want to *allow* reinitializations of fields:
1934 // e.g., want to allow
1936 // `let mut s = ...; drop(s.x); s.x=Val;`
1938 // This does not use check_if_full_path_is_moved on
1939 // `base`, because that would report an error about the
1940 // `base` as a whole, but in this scenario we *really*
1941 // want to report an error about the actual thing that was
1942 // moved, which may be some prefix of `base`.
1944 // Shallow so that we'll stop at any dereference; we'll
1945 // report errors about issues with such bases elsewhere.
1946 let maybe_uninits = &flow_state.uninits;
1948 // Find the shortest uninitialized prefix you can reach
1949 // without going over a Deref.
1950 let mut shortest_uninit_seen = None;
1951 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1952 let mpi = match this.move_path_for_place(prefix) {
1957 if maybe_uninits.contains(mpi) {
1959 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1960 shortest_uninit_seen,
1963 shortest_uninit_seen = Some((prefix, mpi));
1965 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1969 if let Some((prefix, mpi)) = shortest_uninit_seen {
1970 // Check for a reassignment into a uninitialized field of a union (for example,
1971 // after a move out). In this case, do not report a error here. There is an
1972 // exception, if this is the first assignment into the union (that is, there is
1973 // no move out from an earlier location) then this is an attempt at initialization
1974 // of the union - we should error in that case.
1975 let tcx = this.infcx.tcx;
1976 if let ty::Adt(def, _) =
1977 Place::ty_from(base.base, base.projection, this.body(), tcx).ty.kind
1980 if this.move_data.path_map[mpi].iter().any(|moi| {
1981 this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
1988 this.report_use_of_moved_or_uninitialized(
1990 InitializationRequiringAction::PartialAssignment,
1991 (prefix, base, span),
1998 /// Checks the permissions for the given place and read or write kind
2000 /// Returns `true` if an error is reported.
2001 fn check_access_permissions(
2003 (place, span): (&Place<'tcx>, Span),
2005 is_local_mutation_allowed: LocalMutationIsAllowed,
2006 flow_state: &Flows<'cx, 'tcx>,
2010 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
2011 place, kind, is_local_mutation_allowed
2018 Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
2019 | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
2020 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
2021 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. })) => {
2022 let is_local_mutation_allowed = match borrow_kind {
2023 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
2024 BorrowKind::Mut { .. } => is_local_mutation_allowed,
2025 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
2027 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2029 self.add_used_mut(root_place, flow_state);
2033 error_access = AccessKind::MutableBorrow;
2034 the_place_err = place_err;
2038 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
2039 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2041 self.add_used_mut(root_place, flow_state);
2045 error_access = AccessKind::Mutate;
2046 the_place_err = place_err;
2051 Reservation(WriteKind::Move)
2052 | Write(WriteKind::Move)
2053 | Reservation(WriteKind::StorageDeadOrDrop)
2054 | Reservation(WriteKind::MutableBorrow(BorrowKind::Shared))
2055 | Reservation(WriteKind::MutableBorrow(BorrowKind::Shallow))
2056 | Write(WriteKind::StorageDeadOrDrop)
2057 | Write(WriteKind::MutableBorrow(BorrowKind::Shared))
2058 | Write(WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
2059 if let (Err(_), true) = (
2060 self.is_mutable(place.as_ref(), is_local_mutation_allowed),
2061 self.errors_buffer.is_empty(),
2063 // rust-lang/rust#46908: In pure NLL mode this code path should be
2064 // unreachable, but we use `delay_span_bug` because we can hit this when
2065 // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
2066 // enabled. We don't want to ICE for that case, as other errors will have
2067 // been emitted (#52262).
2068 self.infcx.tcx.sess.delay_span_bug(
2071 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2079 // permission checks are done at Reservation point.
2082 Read(ReadKind::Borrow(BorrowKind::Unique))
2083 | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
2084 | Read(ReadKind::Borrow(BorrowKind::Shared))
2085 | Read(ReadKind::Borrow(BorrowKind::Shallow))
2086 | Read(ReadKind::Copy) => {
2087 // Access authorized
2092 // rust-lang/rust#21232, #54986: during period where we reject
2093 // partial initialization, do not complain about mutability
2094 // errors except for actual mutation (as opposed to an attempt
2095 // to do a partial initialization).
2096 let previously_initialized = if let PlaceBase::Local(local) = place.base {
2097 self.is_local_ever_initialized(local, flow_state).is_some()
2102 // at this point, we have set up the error reporting state.
2103 if previously_initialized {
2104 self.report_mutability_error(place, span, the_place_err, error_access, location);
2111 fn is_local_ever_initialized(
2114 flow_state: &Flows<'cx, 'tcx>,
2115 ) -> Option<InitIndex> {
2116 let mpi = self.move_data.rev_lookup.find_local(local);
2117 let ii = &self.move_data.init_path_map[mpi];
2119 if flow_state.ever_inits.contains(index) {
2126 /// Adds the place into the used mutable variables set
2127 fn add_used_mut<'d>(&mut self, root_place: RootPlace<'d, 'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2130 place_base: PlaceBase::Local(local),
2131 place_projection: [],
2132 is_local_mutation_allowed,
2134 // If the local may have been initialized, and it is now currently being
2135 // mutated, then it is justified to be annotated with the `mut`
2136 // keyword, since the mutation may be a possible reassignment.
2137 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2138 && self.is_local_ever_initialized(*local, flow_state).is_some()
2140 self.used_mut.insert(*local);
2145 place_projection: _,
2146 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2150 place_projection: place_projection @ [.., _],
2151 is_local_mutation_allowed: _,
2153 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2155 projection: &place_projection,
2157 self.used_mut_upvars.push(field);
2161 place_base: PlaceBase::Static(..),
2162 place_projection: [],
2163 is_local_mutation_allowed: _,
2168 /// Whether this value can be written or borrowed mutably.
2169 /// Returns the root place if the place passed in is a projection.
2172 place: PlaceRef<'d, 'tcx>,
2173 is_local_mutation_allowed: LocalMutationIsAllowed,
2174 ) -> Result<RootPlace<'d, 'tcx>, PlaceRef<'d, 'tcx>> {
2176 PlaceRef { base: PlaceBase::Local(local), projection: [] } => {
2177 let local = &self.body.local_decls[*local];
2178 match local.mutability {
2179 Mutability::Not => match is_local_mutation_allowed {
2180 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2181 place_base: place.base,
2182 place_projection: place.projection,
2183 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2185 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2186 place_base: place.base,
2187 place_projection: place.projection,
2188 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2190 LocalMutationIsAllowed::No => Err(place),
2192 Mutability::Mut => Ok(RootPlace {
2193 place_base: place.base,
2194 place_projection: place.projection,
2195 is_local_mutation_allowed,
2199 PlaceRef { base: PlaceBase::Static(box Static { def_id, .. }), projection: [] } => {
2200 if !self.infcx.tcx.is_mutable_static(*def_id) {
2204 place_base: place.base,
2205 place_projection: place.projection,
2206 is_local_mutation_allowed,
2210 PlaceRef { base: _, projection: [proj_base @ .., elem] } => {
2212 ProjectionElem::Deref => {
2214 Place::ty_from(place.base, proj_base, self.body(), self.infcx.tcx).ty;
2216 // Check the kind of deref to decide
2217 match base_ty.kind {
2218 ty::Ref(_, _, mutbl) => {
2220 // Shared borrowed data is never mutable
2221 hir::Mutability::Not => Err(place),
2222 // Mutably borrowed data is mutable, but only if we have a
2223 // unique path to the `&mut`
2224 hir::Mutability::Mut => {
2225 let mode = match self.is_upvar_field_projection(place) {
2226 Some(field) if self.upvars[field.index()].by_ref => {
2227 is_local_mutation_allowed
2229 _ => LocalMutationIsAllowed::Yes,
2233 PlaceRef { base: place.base, projection: proj_base },
2239 ty::RawPtr(tnm) => {
2241 // `*const` raw pointers are not mutable
2242 hir::Mutability::Not => Err(place),
2243 // `*mut` raw pointers are always mutable, regardless of
2244 // context. The users have to check by themselves.
2245 hir::Mutability::Mut => Ok(RootPlace {
2246 place_base: place.base,
2247 place_projection: place.projection,
2248 is_local_mutation_allowed,
2252 // `Box<T>` owns its content, so mutable if its location is mutable
2253 _ if base_ty.is_box() => self.is_mutable(
2254 PlaceRef { base: place.base, projection: proj_base },
2255 is_local_mutation_allowed,
2257 // Deref should only be for reference, pointers or boxes
2258 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2261 // All other projections are owned by their base path, so mutable if
2262 // base path is mutable
2263 ProjectionElem::Field(..)
2264 | ProjectionElem::Index(..)
2265 | ProjectionElem::ConstantIndex { .. }
2266 | ProjectionElem::Subslice { .. }
2267 | ProjectionElem::Downcast(..) => {
2268 let upvar_field_projection = self.is_upvar_field_projection(place);
2269 if let Some(field) = upvar_field_projection {
2270 let upvar = &self.upvars[field.index()];
2272 "upvar.mutability={:?} local_mutation_is_allowed={:?} \
2274 upvar, is_local_mutation_allowed, place
2276 match (upvar.mutability, is_local_mutation_allowed) {
2277 (Mutability::Not, LocalMutationIsAllowed::No)
2278 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2281 (Mutability::Not, LocalMutationIsAllowed::Yes)
2282 | (Mutability::Mut, _) => {
2283 // Subtle: this is an upvar
2284 // reference, so it looks like
2285 // `self.foo` -- we want to double
2286 // check that the location `*self`
2287 // is mutable (i.e., this is not a
2288 // `Fn` closure). But if that
2289 // check succeeds, we want to
2290 // *blame* the mutability on
2291 // `place` (that is,
2292 // `self.foo`). This is used to
2293 // propagate the info about
2294 // whether mutability declarations
2295 // are used outwards, so that we register
2296 // the outer variable as mutable. Otherwise a
2297 // test like this fails to record the `mut`
2301 // fn foo<F: FnOnce()>(_f: F) { }
2303 // let var = Vec::new();
2309 let _ = self.is_mutable(
2310 PlaceRef { base: place.base, projection: proj_base },
2311 is_local_mutation_allowed,
2314 place_base: place.base,
2315 place_projection: place.projection,
2316 is_local_mutation_allowed,
2322 PlaceRef { base: place.base, projection: proj_base },
2323 is_local_mutation_allowed,
2332 /// If `place` is a field projection, and the field is being projected from a closure type,
2333 /// then returns the index of the field being projected. Note that this closure will always
2334 /// be `self` in the current MIR, because that is the only time we directly access the fields
2335 /// of a closure type.
2336 pub fn is_upvar_field_projection(&self, place_ref: PlaceRef<'cx, 'tcx>) -> Option<Field> {
2337 let mut place_projection = place_ref.projection;
2338 let mut by_ref = false;
2340 if let [proj_base @ .., ProjectionElem::Deref] = place_projection {
2341 place_projection = proj_base;
2345 match place_projection {
2346 [base @ .., ProjectionElem::Field(field, _ty)] => {
2347 let tcx = self.infcx.tcx;
2348 let base_ty = Place::ty_from(place_ref.base, base, self.body(), tcx).ty;
2350 if (base_ty.is_closure() || base_ty.is_generator())
2351 && (!by_ref || self.upvars[field.index()].by_ref)
2364 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2365 enum NoMovePathFound {
2369 /// The degree of overlap between 2 places for borrow-checking.
2371 /// The places might partially overlap - in this case, we give
2372 /// up and say that they might conflict. This occurs when
2373 /// different fields of a union are borrowed. For example,
2374 /// if `u` is a union, we have no way of telling how disjoint
2375 /// `u.a.x` and `a.b.y` are.
2377 /// The places have the same type, and are either completely disjoint
2378 /// or equal - i.e., they can't "partially" overlap as can occur with
2379 /// unions. This is the "base case" on which we recur for extensions
2382 /// The places are disjoint, so we know all extensions of them
2383 /// will also be disjoint.