1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
3 use crate::borrow_check::nll::region_infer::RegionInferenceContext;
4 use rustc::hir::{self, HirId};
6 use rustc::hir::def_id::DefId;
7 use rustc::infer::InferCtxt;
8 use rustc::lint::builtin::UNUSED_MUT;
9 use rustc::lint::builtin::{MUTABLE_BORROW_RESERVATION_CONFLICT};
10 use rustc::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
12 ClearCrossCrate, Local, Location, Body, Mutability, Operand, Place, PlaceBase, PlaceElem,
13 PlaceRef, Static, StaticKind
15 use rustc::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
16 use rustc::mir::{Terminator, TerminatorKind};
17 use rustc::ty::query::Providers;
18 use rustc::ty::{self, TyCtxt};
20 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder};
21 use rustc_data_structures::bit_set::BitSet;
22 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
23 use rustc_data_structures::graph::dominators::Dominators;
24 use rustc_data_structures::indexed_vec::IndexVec;
25 use smallvec::SmallVec;
27 use std::collections::BTreeMap;
31 use syntax::ast::Name;
32 use syntax_pos::{Span, DUMMY_SP};
34 use crate::dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex};
35 use crate::dataflow::move_paths::{HasMoveData, InitLocation, LookupResult, MoveData, MoveError};
36 use crate::dataflow::Borrows;
37 use crate::dataflow::DataflowResultsConsumer;
38 use crate::dataflow::FlowAtLocation;
39 use crate::dataflow::MoveDataParamEnv;
40 use crate::dataflow::{do_dataflow, DebugFormatted};
41 use crate::dataflow::EverInitializedPlaces;
42 use crate::dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
44 use self::borrow_set::{BorrowData, BorrowSet};
45 use self::flows::Flows;
46 use self::location::LocationTable;
47 use self::prefixes::PrefixSet;
48 use self::MutateMode::{JustWrite, WriteAndRead};
49 use self::mutability_errors::AccessKind;
51 use self::path_utils::*;
59 mod mutability_errors;
62 crate mod places_conflict;
68 // FIXME(eddyb) perhaps move this somewhere more centrally.
75 /// If true, the capture is behind a reference.
78 mutability: Mutability,
81 pub fn provide(providers: &mut Providers<'_>) {
82 *providers = Providers {
88 fn mir_borrowck(tcx: TyCtxt<'_>, def_id: DefId) -> BorrowCheckResult<'_> {
89 let (input_body, promoted) = tcx.mir_validated(def_id);
90 debug!("run query mir_borrowck: {}", tcx.def_path_str(def_id));
92 let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
93 let input_body: &Body<'_> = &input_body.borrow();
94 let promoted: &IndexVec<_, _> = &promoted.borrow();
95 do_mir_borrowck(&infcx, input_body, promoted, def_id)
97 debug!("mir_borrowck done");
102 fn do_mir_borrowck<'a, 'tcx>(
103 infcx: &InferCtxt<'a, 'tcx>,
104 input_body: &Body<'tcx>,
105 input_promoted: &IndexVec<Promoted, Body<'tcx>>,
107 ) -> BorrowCheckResult<'tcx> {
108 debug!("do_mir_borrowck(def_id = {:?})", def_id);
111 let attributes = tcx.get_attrs(def_id);
112 let param_env = tcx.param_env(def_id);
115 .as_local_hir_id(def_id)
116 .expect("do_mir_borrowck: non-local DefId");
118 // Gather the upvars of a closure, if any.
119 let tables = tcx.typeck_tables_of(def_id);
120 let upvars: Vec<_> = tables
124 .flat_map(|v| v.values())
126 let var_hir_id = upvar_id.var_path.hir_id;
127 let capture = tables.upvar_capture(*upvar_id);
128 let by_ref = match capture {
129 ty::UpvarCapture::ByValue => false,
130 ty::UpvarCapture::ByRef(..) => true,
132 let mut upvar = Upvar {
133 name: tcx.hir().name(var_hir_id),
136 mutability: Mutability::Not,
138 let bm = *tables.pat_binding_modes().get(var_hir_id)
139 .expect("missing binding mode");
140 if bm == ty::BindByValue(hir::MutMutable) {
141 upvar.mutability = Mutability::Mut;
147 // Replace all regions with fresh inference variables. This
148 // requires first making our own copy of the MIR. This copy will
149 // be modified (in place) to contain non-lexical lifetimes. It
150 // will have a lifetime tied to the inference context.
151 let mut body: Body<'tcx> = input_body.clone();
152 let mut promoted: IndexVec<Promoted, Body<'tcx>> = input_promoted.clone();
154 nll::replace_regions_in_mir(infcx, def_id, param_env, &mut body, &mut promoted);
155 let body = &body; // no further changes
156 let location_table = &LocationTable::new(body);
158 let mut errors_buffer = Vec::new();
159 let (move_data, move_errors): (MoveData<'tcx>, Option<Vec<(Place<'tcx>, MoveError<'tcx>)>>) =
160 match MoveData::gather_moves(body, tcx) {
161 Ok(move_data) => (move_data, None),
162 Err((move_data, move_errors)) => (move_data, Some(move_errors)),
165 let mdpe = MoveDataParamEnv {
170 let dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
171 let mut flow_inits = FlowAtLocation::new(do_dataflow(
177 MaybeInitializedPlaces::new(tcx, body, &mdpe),
178 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
181 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
182 let borrow_set = Rc::new(BorrowSet::build(
183 tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
185 // If we are in non-lexical mode, compute the non-lexical lifetimes.
186 let (regioncx, polonius_output, opt_closure_req) = nll::compute_regions(
201 // The various `flow_*` structures can be large. We drop `flow_inits` here
202 // so it doesn't overlap with the others below. This reduces peak memory
203 // usage significantly on some benchmarks.
206 let regioncx = Rc::new(regioncx);
208 let flow_borrows = FlowAtLocation::new(do_dataflow(
214 Borrows::new(tcx, body, param_env, regioncx.clone(), &borrow_set),
215 |rs, i| DebugFormatted::new(&rs.location(i)),
217 let flow_uninits = FlowAtLocation::new(do_dataflow(
223 MaybeUninitializedPlaces::new(tcx, body, &mdpe),
224 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
226 let flow_ever_inits = FlowAtLocation::new(do_dataflow(
232 EverInitializedPlaces::new(tcx, body, &mdpe),
233 |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
236 let movable_generator = match tcx.hir().get(id) {
237 Node::Expr(&hir::Expr {
238 kind: hir::ExprKind::Closure(.., Some(hir::GeneratorMovability::Static)),
244 let dominators = body.dominators();
246 let mut mbcx = MirBorrowckCtxt {
251 move_data: &mdpe.move_data,
254 locals_are_invalidated_at_exit,
255 access_place_error_reported: Default::default(),
256 reservation_error_reported: Default::default(),
257 reservation_warnings: Default::default(),
258 move_error_reported: BTreeMap::new(),
259 uninitialized_error_reported: Default::default(),
261 nonlexical_regioncx: regioncx,
262 used_mut: Default::default(),
263 used_mut_upvars: SmallVec::new(),
269 let mut state = Flows::new(
276 if let Some(errors) = move_errors {
277 mbcx.report_move_errors(errors);
279 mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
281 // Convert any reservation warnings into lints.
282 let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
283 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
284 let mut initial_diag =
285 mbcx.report_conflicting_borrow(location, (&place, span), bk, &borrow);
287 let lint_root = if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
288 let scope = mbcx.body.source_info(location).scope;
294 // Span and message don't matter; we overwrite them below anyway
295 let mut diag = mbcx.infcx.tcx.struct_span_lint_hir(
296 MUTABLE_BORROW_RESERVATION_CONFLICT, lint_root, DUMMY_SP, "");
298 diag.message = initial_diag.styled_message().clone();
299 diag.span = initial_diag.span.clone();
301 initial_diag.cancel();
302 diag.buffer(&mut mbcx.errors_buffer);
305 // For each non-user used mutable variable, check if it's been assigned from
306 // a user-declared local. If so, then put that local into the used_mut set.
307 // Note that this set is expected to be small - only upvars from closures
308 // would have a chance of erroneously adding non-user-defined mutable vars
310 let temporary_used_locals: FxHashSet<Local> = mbcx.used_mut.iter()
311 .filter(|&local| mbcx.body.local_decls[*local].is_user_variable.is_none())
314 // For the remaining unused locals that are marked as mutable, we avoid linting any that
315 // were never initialized. These locals may have been removed as unreachable code; or will be
316 // linted as unused variables.
317 let unused_mut_locals = mbcx.body.mut_vars_iter()
318 .filter(|local| !mbcx.used_mut.contains(local))
320 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
322 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
323 let used_mut = mbcx.used_mut;
324 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
325 if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
326 let local_decl = &mbcx.body.local_decls[local];
328 // Skip implicit `self` argument for closures
329 if local.index() == 1 && tcx.is_closure(mbcx.mir_def_id) {
333 // Skip over locals that begin with an underscore or have no name
334 match local_decl.name {
335 Some(name) => if name.as_str().starts_with("_") {
341 let span = local_decl.source_info.span;
342 if span.desugaring_kind().is_some() {
343 // If the `mut` arises as part of a desugaring, we should ignore it.
347 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
348 tcx.struct_span_lint_hir(
350 vsi[local_decl.source_info.scope].lint_root,
352 "variable does not need to be mutable",
354 .span_suggestion_short(
358 Applicability::MachineApplicable,
364 // Buffer any move errors that we collected and de-duplicated.
365 for (_, (_, diag)) in mbcx.move_error_reported {
366 diag.buffer(&mut mbcx.errors_buffer);
369 if !mbcx.errors_buffer.is_empty() {
370 mbcx.errors_buffer.sort_by_key(|diag| diag.span.primary_span());
372 for diag in mbcx.errors_buffer.drain(..) {
373 mbcx.infcx.tcx.sess.diagnostic().emit_diagnostic(&diag);
377 let result = BorrowCheckResult {
378 closure_requirements: opt_closure_req,
379 used_mut_upvars: mbcx.used_mut_upvars,
382 debug!("do_mir_borrowck: result = {:#?}", result);
387 crate struct MirBorrowckCtxt<'cx, 'tcx> {
388 crate infcx: &'cx InferCtxt<'cx, 'tcx>,
389 body: &'cx Body<'tcx>,
391 param_env: ty::ParamEnv<'tcx>,
392 move_data: &'cx MoveData<'tcx>,
394 /// Map from MIR `Location` to `LocationIndex`; created
395 /// when MIR borrowck begins.
396 location_table: &'cx LocationTable,
398 movable_generator: bool,
399 /// This keeps track of whether local variables are free-ed when the function
400 /// exits even without a `StorageDead`, which appears to be the case for
403 /// I'm not sure this is the right approach - @eddyb could you try and
405 locals_are_invalidated_at_exit: bool,
406 /// This field keeps track of when borrow errors are reported in the access_place function
407 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
408 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
409 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
411 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
412 /// This field keeps track of when borrow conflict errors are reported
413 /// for reservations, so that we don't report seemingly duplicate
414 /// errors for corresponding activations.
416 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
417 // but it is currently inconvenient to track down the `BorrowIndex`
418 // at the time we detect and report a reservation error.
419 reservation_error_reported: FxHashSet<Place<'tcx>>,
420 /// Migration warnings to be reported for #56254. We delay reporting these
421 /// so that we can suppress the warning if there's a corresponding error
422 /// for the activation of the borrow.
423 reservation_warnings: FxHashMap<
425 (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)
427 /// This field keeps track of move errors that are to be reported for given move indicies.
429 /// There are situations where many errors can be reported for a single move out (see #53807)
430 /// and we want only the best of those errors.
432 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
433 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
434 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
435 /// all move errors have been reported, any diagnostics in this map are added to the buffer
438 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
439 /// when errors in the map are being re-added to the error buffer so that errors with the
440 /// same primary span come out in a consistent order.
441 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'cx, 'tcx>, DiagnosticBuilder<'cx>)>,
442 /// This field keeps track of errors reported in the checking of uninitialized variables,
443 /// so that we don't report seemingly duplicate errors.
444 uninitialized_error_reported: FxHashSet<PlaceRef<'cx, 'tcx>>,
445 /// Errors to be reported buffer
446 errors_buffer: Vec<Diagnostic>,
447 /// This field keeps track of all the local variables that are declared mut and are mutated.
448 /// Used for the warning issued by an unused mutable local variable.
449 used_mut: FxHashSet<Local>,
450 /// If the function we're checking is a closure, then we'll need to report back the list of
451 /// mutable upvars that have been used. This field keeps track of them.
452 used_mut_upvars: SmallVec<[Field; 8]>,
453 /// Non-lexical region inference context, if NLL is enabled. This
454 /// contains the results from region inference and lets us e.g.
455 /// find out which CFG points are contained in each borrow region.
456 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
458 /// The set of borrows extracted from the MIR
459 borrow_set: Rc<BorrowSet<'tcx>>,
461 /// Dominators for MIR
462 dominators: Dominators<BasicBlock>,
464 /// Information about upvars not necessarily preserved in types or MIR
469 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
470 // 2. loans made in overlapping scopes do not conflict
471 // 3. assignments do not affect things loaned out as immutable
472 // 4. moves do not affect things loaned out in any way
473 impl<'cx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
474 type FlowState = Flows<'cx, 'tcx>;
476 fn body(&self) -> &'cx Body<'tcx> {
480 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
481 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
484 fn visit_statement_entry(
487 stmt: &'cx Statement<'tcx>,
488 flow_state: &Self::FlowState,
491 "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
492 location, stmt, flow_state
494 let span = stmt.source_info.span;
496 self.check_activations(location, span, flow_state);
499 StatementKind::Assign(box(ref lhs, ref rhs)) => {
514 StatementKind::FakeRead(_, box ref place) => {
515 // Read for match doesn't access any memory and is used to
516 // assert that a place is safe and live. So we don't have to
517 // do any checks here.
519 // FIXME: Remove check that the place is initialized. This is
520 // needed for now because matches don't have never patterns yet.
521 // So this is the only place we prevent
525 self.check_if_path_or_subpath_is_moved(
527 InitializationRequiringAction::Use,
528 (place.as_ref(), span),
532 StatementKind::SetDiscriminant {
544 StatementKind::InlineAsm(ref asm) => {
545 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
547 // FIXME(eddyb) indirect inline asm outputs should
548 // be encoded through MIR place derefs instead.
552 (Deep, Read(ReadKind::Copy)),
553 LocalMutationIsAllowed::No,
556 self.check_if_path_or_subpath_is_moved(
558 InitializationRequiringAction::Use,
559 (output.as_ref(), o.span),
566 if o.is_rw { Deep } else { Shallow(None) },
567 if o.is_rw { WriteAndRead } else { JustWrite },
572 for (_, input) in asm.inputs.iter() {
573 self.consume_operand(location, (input, span), flow_state);
577 | StatementKind::AscribeUserType(..)
578 | StatementKind::Retag { .. }
579 | StatementKind::StorageLive(..) => {
580 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
583 StatementKind::StorageDead(local) => {
586 (&Place::from(local), span),
587 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
588 LocalMutationIsAllowed::Yes,
595 fn visit_terminator_entry(
598 term: &'cx Terminator<'tcx>,
599 flow_state: &Self::FlowState,
603 "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
604 location, term, flow_state
606 let span = term.source_info.span;
608 self.check_activations(location, span, flow_state);
611 TerminatorKind::SwitchInt {
617 self.consume_operand(loc, (discr, span), flow_state);
619 TerminatorKind::Drop {
620 location: ref drop_place,
624 let tcx = self.infcx.tcx;
626 // Compute the type with accurate region information.
627 let drop_place_ty = drop_place.ty(self.body, self.infcx.tcx);
629 // Erase the regions.
630 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
632 // "Lift" into the tcx -- once regions are erased, this type should be in the
633 // global arenas; this "lift" operation basically just asserts that is true, but
634 // that is useful later.
635 tcx.lift(&drop_place_ty).unwrap();
637 debug!("visit_terminator_drop \
638 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
639 loc, term, drop_place, drop_place_ty, span);
644 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
645 LocalMutationIsAllowed::Yes,
649 TerminatorKind::DropAndReplace {
650 location: ref drop_place,
651 value: ref new_value,
662 self.consume_operand(
668 TerminatorKind::Call {
675 self.consume_operand(loc, (func, span), flow_state);
677 self.consume_operand(
683 if let Some((ref dest, _ /*bb*/)) = *destination {
693 TerminatorKind::Assert {
700 self.consume_operand(loc, (cond, span), flow_state);
701 use rustc::mir::interpret::PanicInfo;
702 if let PanicInfo::BoundsCheck { ref len, ref index } = *msg {
703 self.consume_operand(loc, (len, span), flow_state);
704 self.consume_operand(loc, (index, span), flow_state);
708 TerminatorKind::Yield {
713 self.consume_operand(loc, (value, span), flow_state);
715 if self.movable_generator {
716 // Look for any active borrows to locals
717 let borrow_set = self.borrow_set.clone();
718 flow_state.with_outgoing_borrows(|borrows| {
720 let borrow = &borrow_set[i];
721 self.check_for_local_borrow(borrow, span);
727 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
728 // Returning from the function implicitly kills storage for all locals and statics.
729 // Often, the storage will already have been killed by an explicit
730 // StorageDead, but we don't always emit those (notably on unwind paths),
731 // so this "extra check" serves as a kind of backup.
732 let borrow_set = self.borrow_set.clone();
733 flow_state.with_outgoing_borrows(|borrows| {
735 let borrow = &borrow_set[i];
736 self.check_for_invalidation_at_exit(loc, borrow, span);
740 TerminatorKind::Goto { target: _ }
741 | TerminatorKind::Abort
742 | TerminatorKind::Unreachable
743 | TerminatorKind::FalseEdges {
747 | TerminatorKind::FalseUnwind {
751 // no data used, thus irrelevant to borrowck
757 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
763 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
764 use self::AccessDepth::{Deep, Shallow};
766 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
767 enum ArtificialField {
772 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
774 /// From the RFC: "A *shallow* access means that the immediate
775 /// fields reached at P are accessed, but references or pointers
776 /// found within are not dereferenced. Right now, the only access
777 /// that is shallow is an assignment like `x = ...;`, which would
778 /// be a *shallow write* of `x`."
779 Shallow(Option<ArtificialField>),
781 /// From the RFC: "A *deep* access means that all data reachable
782 /// through the given place may be invalidated or accesses by
786 /// Access is Deep only when there is a Drop implementation that
787 /// can reach the data behind the reference.
791 /// Kind of access to a value: read or write
792 /// (For informational purposes only)
793 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
795 /// From the RFC: "A *read* means that the existing data may be
796 /// read, but will not be changed."
799 /// From the RFC: "A *write* means that the data may be mutated to
800 /// new values or otherwise invalidated (for example, it could be
801 /// de-initialized, as in a move operation).
804 /// For two-phase borrows, we distinguish a reservation (which is treated
805 /// like a Read) from an activation (which is treated like a write), and
806 /// each of those is furthermore distinguished from Reads/Writes above.
807 Reservation(WriteKind),
808 Activation(WriteKind, BorrowIndex),
811 /// Kind of read access to a value
812 /// (For informational purposes only)
813 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
819 /// Kind of write access to a value
820 /// (For informational purposes only)
821 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
824 MutableBorrow(BorrowKind),
829 /// When checking permissions for a place access, this flag is used to indicate that an immutable
830 /// local place can be mutated.
832 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
833 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
834 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
835 // `is_declared_mutable()`.
836 // - Take flow state into consideration in `is_assignable()` for local variables.
837 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
838 enum LocalMutationIsAllowed {
840 /// We want use of immutable upvars to cause a "write to immutable upvar"
841 /// error, not an "reassignment" error.
846 #[derive(Copy, Clone, Debug)]
847 enum InitializationRequiringAction {
856 struct RootPlace<'d, 'tcx> {
857 place_base: &'d PlaceBase<'tcx>,
858 place_projection: &'d [PlaceElem<'tcx>],
859 is_local_mutation_allowed: LocalMutationIsAllowed,
862 impl InitializationRequiringAction {
863 fn as_noun(self) -> &'static str {
865 InitializationRequiringAction::Update => "update",
866 InitializationRequiringAction::Borrow => "borrow",
867 InitializationRequiringAction::MatchOn => "use", // no good noun
868 InitializationRequiringAction::Use => "use",
869 InitializationRequiringAction::Assignment => "assign",
870 InitializationRequiringAction::PartialAssignment => "assign to part",
874 fn as_verb_in_past_tense(self) -> &'static str {
876 InitializationRequiringAction::Update => "updated",
877 InitializationRequiringAction::Borrow => "borrowed",
878 InitializationRequiringAction::MatchOn => "matched on",
879 InitializationRequiringAction::Use => "used",
880 InitializationRequiringAction::Assignment => "assigned",
881 InitializationRequiringAction::PartialAssignment => "partially assigned",
886 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
887 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
888 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
889 /// place is initialized and (b) it is not borrowed in some way that would prevent this
892 /// Returns `true` if an error is reported.
896 place_span: (&Place<'tcx>, Span),
897 kind: (AccessDepth, ReadOrWrite),
898 is_local_mutation_allowed: LocalMutationIsAllowed,
899 flow_state: &Flows<'cx, 'tcx>,
903 if let Activation(_, borrow_index) = rw {
904 if self.reservation_error_reported.contains(&place_span.0) {
906 "skipping access_place for activation of invalid reservation \
907 place: {:?} borrow_index: {:?}",
908 place_span.0, borrow_index
914 // Check is_empty() first because it's the common case, and doing that
915 // way we avoid the clone() call.
916 if !self.access_place_error_reported.is_empty() &&
918 .access_place_error_reported
919 .contains(&(place_span.0.clone(), place_span.1))
922 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
928 let mutability_error =
929 self.check_access_permissions(
932 is_local_mutation_allowed,
937 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
939 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
940 // Suppress this warning when there's an error being emited for the
941 // same borrow: fixing the error is likely to fix the warning.
942 self.reservation_warnings.remove(&borrow_idx);
945 if conflict_error || mutability_error {
947 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
951 self.access_place_error_reported
952 .insert((place_span.0.clone(), place_span.1));
956 fn check_access_for_conflict(
959 place_span: (&Place<'tcx>, Span),
962 flow_state: &Flows<'cx, 'tcx>,
965 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
966 location, place_span, sd, rw,
969 let mut error_reported = false;
970 let tcx = self.infcx.tcx;
971 let body = self.body;
972 let param_env = self.param_env;
973 let location_table = self.location_table.start_index(location);
974 let borrow_set = self.borrow_set.clone();
975 each_borrow_involving_path(
983 flow_state.borrows_in_scope(location_table),
984 |this, borrow_index, borrow| match (rw, borrow.kind) {
985 // Obviously an activation is compatible with its own
986 // reservation (or even prior activating uses of same
987 // borrow); so don't check if they interfere.
989 // NOTE: *reservations* do conflict with themselves;
990 // thus aren't injecting unsoundenss w/ this check.)
991 (Activation(_, activating), _) if activating == borrow_index => {
993 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
994 skipping {:?} b/c activation of same borrow_index",
998 (borrow_index, borrow),
1003 (Read(_), BorrowKind::Shared)
1004 | (Read(_), BorrowKind::Shallow)
1005 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
1006 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
1010 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1011 // Handled by initialization checks.
1015 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
1016 // Reading from mere reservations of mutable-borrows is OK.
1017 if !is_active(&this.dominators, borrow, location) {
1018 assert!(allow_two_phase_borrow(borrow.kind));
1019 return Control::Continue;
1022 error_reported = true;
1025 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1026 .buffer(&mut this.errors_buffer);
1028 ReadKind::Borrow(bk) => {
1029 this.report_conflicting_borrow(location, place_span, bk, borrow)
1030 .buffer(&mut this.errors_buffer);
1036 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
1037 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared) if {
1038 tcx.migrate_borrowck() && this.borrow_set.location_map.contains_key(&location)
1040 let bi = this.borrow_set.location_map[&location];
1042 "recording invalid reservation of place: {:?} with \
1043 borrow index {:?} as warning",
1047 // rust-lang/rust#56254 - This was previously permitted on
1048 // the 2018 edition so we emit it as a warning. We buffer
1049 // these sepately so that we only emit a warning if borrow
1050 // checking was otherwise successful.
1051 this.reservation_warnings.insert(
1053 (place_span.0.clone(), place_span.1, location, bk, borrow.clone()),
1056 // Don't suppress actual errors.
1060 (Reservation(kind), _)
1061 | (Activation(kind, _), _)
1062 | (Write(kind), _) => {
1064 Reservation(..) => {
1066 "recording invalid reservation of \
1070 this.reservation_error_reported.insert(place_span.0.clone());
1072 Activation(_, activating) => {
1074 "observing check_place for activation of \
1075 borrow_index: {:?}",
1079 Read(..) | Write(..) => {}
1082 error_reported = true;
1084 WriteKind::MutableBorrow(bk) => {
1085 this.report_conflicting_borrow(location, place_span, bk, borrow)
1086 .buffer(&mut this.errors_buffer);
1088 WriteKind::StorageDeadOrDrop => {
1089 this.report_borrowed_value_does_not_live_long_enough(
1095 WriteKind::Mutate => {
1096 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1098 WriteKind::Move => {
1099 this.report_move_out_while_borrowed(location, place_span, borrow)
1113 place_span: (&'cx Place<'tcx>, Span),
1116 flow_state: &Flows<'cx, 'tcx>,
1118 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1120 MutateMode::WriteAndRead => {
1121 self.check_if_path_or_subpath_is_moved(
1123 InitializationRequiringAction::Update,
1124 (place_span.0.as_ref(), place_span.1),
1128 MutateMode::JustWrite => {
1129 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1133 // Special case: you can assign a immutable local variable
1134 // (e.g., `x = ...`) so long as it has never been initialized
1135 // before (at this point in the flow).
1137 base: PlaceBase::Local(local),
1140 if let Mutability::Not = self.body.local_decls[*local].mutability {
1141 // check for reassignments to immutable local variables
1142 self.check_if_reassignment_to_immutable_state(
1152 // Otherwise, use the normal access permission rules.
1156 (kind, Write(WriteKind::Mutate)),
1157 LocalMutationIsAllowed::No,
1165 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1166 flow_state: &Flows<'cx, 'tcx>,
1169 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1170 let access_kind = match bk {
1171 BorrowKind::Shallow => {
1172 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1174 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1175 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1176 let wk = WriteKind::MutableBorrow(bk);
1177 if allow_two_phase_borrow(bk) {
1178 (Deep, Reservation(wk))
1189 LocalMutationIsAllowed::No,
1193 let action = if bk == BorrowKind::Shallow {
1194 InitializationRequiringAction::MatchOn
1196 InitializationRequiringAction::Borrow
1199 self.check_if_path_or_subpath_is_moved(
1202 (place.as_ref(), span),
1207 Rvalue::Use(ref operand)
1208 | Rvalue::Repeat(ref operand, _)
1209 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1210 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1211 self.consume_operand(location, (operand, span), flow_state)
1214 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1215 let af = match *rvalue {
1216 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1217 Rvalue::Discriminant(..) => None,
1218 _ => unreachable!(),
1223 (Shallow(af), Read(ReadKind::Copy)),
1224 LocalMutationIsAllowed::No,
1227 self.check_if_path_or_subpath_is_moved(
1229 InitializationRequiringAction::Use,
1230 (place.as_ref(), span),
1235 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1236 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1237 self.consume_operand(location, (operand1, span), flow_state);
1238 self.consume_operand(location, (operand2, span), flow_state);
1241 Rvalue::NullaryOp(_op, _ty) => {
1242 // nullary ops take no dynamic input; no borrowck effect.
1244 // FIXME: is above actually true? Do we want to track
1245 // the fact that uninitialized data can be created via
1249 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1250 // We need to report back the list of mutable upvars that were
1251 // moved into the closure and subsequently used by the closure,
1252 // in order to populate our used_mut set.
1253 match **aggregate_kind {
1254 AggregateKind::Closure(def_id, _)
1255 | AggregateKind::Generator(def_id, _, _) => {
1256 let BorrowCheckResult {
1258 } = self.infcx.tcx.mir_borrowck(def_id);
1259 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1260 for field in used_mut_upvars {
1261 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1264 AggregateKind::Adt(..)
1265 | AggregateKind::Array(..)
1266 | AggregateKind::Tuple { .. } => (),
1269 for operand in operands {
1270 self.consume_operand(location, (operand, span), flow_state);
1276 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1277 let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1278 if !place.projection.is_empty() {
1279 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1280 this.used_mut_upvars.push(field);
1282 } else if let PlaceBase::Local(local) = place.base {
1283 this.used_mut.insert(local);
1287 // This relies on the current way that by-value
1288 // captures of a closure are copied/moved directly
1289 // when generating MIR.
1291 Operand::Move(Place {
1292 base: PlaceBase::Local(local),
1295 Operand::Copy(Place {
1296 base: PlaceBase::Local(local),
1298 }) if self.body.local_decls[local].is_user_variable.is_none() => {
1299 if self.body.local_decls[local].ty.is_mutable_ptr() {
1300 // The variable will be marked as mutable by the borrow.
1303 // This is an edge case where we have a `move` closure
1304 // inside a non-move closure, and the inner closure
1305 // contains a mutation:
1308 // || { move || { i += 1; }; };
1310 // In this case our usual strategy of assuming that the
1311 // variable will be captured by mutable reference is
1312 // wrong, since `i` can be copied into the inner
1313 // closure from a shared reference.
1315 // As such we have to search for the local that this
1316 // capture comes from and mark it as being used as mut.
1318 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1319 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1320 &self.move_data.inits[init_index]
1322 bug!("temporary should be initialized exactly once")
1325 let loc = match init.location {
1326 InitLocation::Statement(stmt) => stmt,
1327 _ => bug!("temporary initialized in arguments"),
1330 let bbd = &self.body[loc.block];
1331 let stmt = &bbd.statements[loc.statement_index];
1332 debug!("temporary assigned in: stmt={:?}", stmt);
1334 if let StatementKind::Assign(box(_, Rvalue::Ref(_, _, ref source))) = stmt.kind {
1335 propagate_closure_used_mut_place(self, source);
1337 bug!("closures should only capture user variables \
1338 or references to user variables");
1341 Operand::Move(ref place)
1342 | Operand::Copy(ref place) => {
1343 propagate_closure_used_mut_place(self, place);
1345 Operand::Constant(..) => {}
1352 (operand, span): (&'cx Operand<'tcx>, Span),
1353 flow_state: &Flows<'cx, 'tcx>,
1356 Operand::Copy(ref place) => {
1357 // copy of place: check if this is "copy of frozen path"
1358 // (FIXME: see check_loans.rs)
1362 (Deep, Read(ReadKind::Copy)),
1363 LocalMutationIsAllowed::No,
1367 // Finally, check if path was already moved.
1368 self.check_if_path_or_subpath_is_moved(
1370 InitializationRequiringAction::Use,
1371 (place.as_ref(), span),
1375 Operand::Move(ref place) => {
1376 // move of place: check if this is move of already borrowed path
1380 (Deep, Write(WriteKind::Move)),
1381 LocalMutationIsAllowed::Yes,
1385 // Finally, check if path was already moved.
1386 self.check_if_path_or_subpath_is_moved(
1388 InitializationRequiringAction::Use,
1389 (place.as_ref(), span),
1393 Operand::Constant(_) => {}
1397 /// Checks whether a borrow of this place is invalidated when the function
1399 fn check_for_invalidation_at_exit(
1402 borrow: &BorrowData<'tcx>,
1405 debug!("check_for_invalidation_at_exit({:?})", borrow);
1406 let place = &borrow.borrowed_place;
1407 let root_place = self.prefixes(place.as_ref(), PrefixSet::All).last().unwrap();
1409 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1410 // we just know that all locals are dropped at function exit (otherwise
1411 // we'll have a memory leak) and assume that all statics have a destructor.
1413 // FIXME: allow thread-locals to borrow other thread locals?
1415 assert!(root_place.projection.is_empty());
1416 let (might_be_alive, will_be_dropped) = match root_place.base {
1417 PlaceBase::Static(box Static {
1418 kind: StaticKind::Promoted(..),
1423 PlaceBase::Static(box Static {
1424 kind: StaticKind::Static,
1427 // Thread-locals might be dropped after the function exits, but
1428 // "true" statics will never be.
1429 (true, self.is_place_thread_local(root_place))
1431 PlaceBase::Local(_) => {
1432 // Locals are always dropped at function exit, and if they
1433 // have a destructor it would've been called already.
1434 (false, self.locals_are_invalidated_at_exit)
1438 if !will_be_dropped {
1440 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1446 let sd = if might_be_alive { Deep } else { Shallow(None) };
1448 if places_conflict::borrow_conflicts_with_place(
1456 places_conflict::PlaceConflictBias::Overlap,
1458 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1459 // FIXME: should be talking about the region lifetime instead
1460 // of just a span here.
1461 let span = self.infcx.tcx.sess.source_map().end_point(span);
1462 self.report_borrowed_value_does_not_live_long_enough(
1471 /// Reports an error if this is a borrow of local data.
1472 /// This is called for all Yield statements on movable generators
1473 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1474 debug!("check_for_local_borrow({:?})", borrow);
1476 if borrow_of_local_data(&borrow.borrowed_place) {
1477 let err = self.cannot_borrow_across_generator_yield(
1478 self.retrieve_borrow_spans(borrow).var_or_use(),
1482 err.buffer(&mut self.errors_buffer);
1486 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1487 // Two-phase borrow support: For each activation that is newly
1488 // generated at this statement, check if it interferes with
1490 let borrow_set = self.borrow_set.clone();
1491 for &borrow_index in borrow_set.activations_at_location(location) {
1492 let borrow = &borrow_set[borrow_index];
1494 // only mutable borrows should be 2-phase
1495 assert!(match borrow.kind {
1496 BorrowKind::Shared | BorrowKind::Shallow => false,
1497 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1502 (&borrow.borrowed_place, span),
1505 Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1507 LocalMutationIsAllowed::No,
1510 // We do not need to call `check_if_path_or_subpath_is_moved`
1511 // again, as we already called it when we made the
1512 // initial reservation.
1517 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
1518 fn check_if_reassignment_to_immutable_state(
1522 place_span: (&Place<'tcx>, Span),
1523 flow_state: &Flows<'cx, 'tcx>,
1525 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1527 // Check if any of the initializiations of `local` have happened yet:
1528 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1529 // And, if so, report an error.
1530 let init = &self.move_data.inits[init_index];
1531 let span = init.span(&self.body);
1532 self.report_illegal_reassignment(
1533 location, place_span, span, place_span.0
1538 fn check_if_full_path_is_moved(
1541 desired_action: InitializationRequiringAction,
1542 place_span: (PlaceRef<'cx, 'tcx>, Span),
1543 flow_state: &Flows<'cx, 'tcx>,
1545 let maybe_uninits = &flow_state.uninits;
1549 // 1. Move of `a.b.c`, use of `a.b.c`
1550 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1551 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1552 // partial initialization support, one might have `a.x`
1553 // initialized but not `a.b`.
1557 // 4. Move of `a.b.c`, use of `a.b.d`
1558 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1559 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1560 // must have been initialized for the use to be sound.
1561 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1563 // The dataflow tracks shallow prefixes distinctly (that is,
1564 // field-accesses on P distinctly from P itself), in order to
1565 // track substructure initialization separately from the whole
1568 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1569 // which we have a MovePath is `a.b`, then that means that the
1570 // initialization state of `a.b` is all we need to inspect to
1571 // know if `a.b.c` is valid (and from that we infer that the
1572 // dereference and `.d` access is also valid, since we assume
1573 // `a.b.c` is assigned a reference to a initialized and
1574 // well-formed record structure.)
1576 // Therefore, if we seek out the *closest* prefix for which we
1577 // have a MovePath, that should capture the initialization
1578 // state for the place scenario.
1580 // This code covers scenarios 1, 2, and 3.
1582 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1583 match self.move_path_closest_to(place_span.0) {
1584 Ok((prefix, mpi)) => {
1585 if maybe_uninits.contains(mpi) {
1586 self.report_use_of_moved_or_uninitialized(
1589 (prefix, place_span.0, place_span.1),
1592 return; // don't bother finding other problems.
1595 Err(NoMovePathFound::ReachedStatic) => {
1596 // Okay: we do not build MoveData for static variables
1597 } // Only query longest prefix with a MovePath, not further
1598 // ancestors; dataflow recurs on children when parents
1599 // move (to support partial (re)inits).
1601 // (I.e., querying parents breaks scenario 7; but may want
1602 // to do such a query based on partial-init feature-gate.)
1606 fn check_if_path_or_subpath_is_moved(
1609 desired_action: InitializationRequiringAction,
1610 place_span: (PlaceRef<'cx, 'tcx>, Span),
1611 flow_state: &Flows<'cx, 'tcx>,
1613 let maybe_uninits = &flow_state.uninits;
1617 // 1. Move of `a.b.c`, use of `a` or `a.b`
1618 // partial initialization support, one might have `a.x`
1619 // initialized but not `a.b`.
1620 // 2. All bad scenarios from `check_if_full_path_is_moved`
1624 // 3. Move of `a.b.c`, use of `a.b.d`
1625 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1626 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1627 // must have been initialized for the use to be sound.
1628 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1630 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1632 // A move of any shallow suffix of `place` also interferes
1633 // with an attempt to use `place`. This is scenario 3 above.
1635 // (Distinct from handling of scenarios 1+2+4 above because
1636 // `place` does not interfere with suffixes of its prefixes,
1637 // e.g., `a.b.c` does not interfere with `a.b.d`)
1639 // This code covers scenario 1.
1641 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1642 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1643 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1644 self.report_use_of_moved_or_uninitialized(
1647 (place_span.0, place_span.0, place_span.1),
1650 return; // don't bother finding other problems.
1655 /// Currently MoveData does not store entries for all places in
1656 /// the input MIR. For example it will currently filter out
1657 /// places that are Copy; thus we do not track places of shared
1658 /// reference type. This routine will walk up a place along its
1659 /// prefixes, searching for a foundational place that *is*
1660 /// tracked in the MoveData.
1662 /// An Err result includes a tag indicated why the search failed.
1663 /// Currently this can only occur if the place is built off of a
1664 /// static variable, as we do not track those in the MoveData.
1665 fn move_path_closest_to(
1667 place: PlaceRef<'cx, 'tcx>,
1668 ) -> Result<(PlaceRef<'cx, 'tcx>, MovePathIndex), NoMovePathFound> {
1669 let mut last_prefix = place.base;
1671 for prefix in self.prefixes(place, PrefixSet::All) {
1672 if let Some(mpi) = self.move_path_for_place(prefix) {
1673 return Ok((prefix, mpi));
1676 last_prefix = prefix.base;
1680 PlaceBase::Local(_) => panic!("should have move path for every Local"),
1681 PlaceBase::Static(_) => Err(NoMovePathFound::ReachedStatic),
1685 fn move_path_for_place(&mut self, place: PlaceRef<'cx, 'tcx>) -> Option<MovePathIndex> {
1686 // If returns None, then there is no move path corresponding
1687 // to a direct owner of `place` (which means there is nothing
1688 // that borrowck tracks for its analysis).
1690 match self.move_data.rev_lookup.find(place) {
1691 LookupResult::Parent(_) => None,
1692 LookupResult::Exact(mpi) => Some(mpi),
1696 fn check_if_assigned_path_is_moved(
1699 (place, span): (&'cx Place<'tcx>, Span),
1700 flow_state: &Flows<'cx, 'tcx>,
1702 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1704 // None case => assigning to `x` does not require `x` be initialized.
1705 let mut cursor = &*place.projection;
1706 while let [proj_base @ .., elem] = cursor {
1710 ProjectionElem::Index(_/*operand*/) |
1711 ProjectionElem::ConstantIndex { .. } |
1712 // assigning to P[i] requires P to be valid.
1713 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1714 // assigning to (P->variant) is okay if assigning to `P` is okay
1716 // FIXME: is this true even if P is a adt with a dtor?
1719 // assigning to (*P) requires P to be initialized
1720 ProjectionElem::Deref => {
1721 self.check_if_full_path_is_moved(
1722 location, InitializationRequiringAction::Use,
1725 projection: proj_base,
1726 }, span), flow_state);
1727 // (base initialized; no need to
1732 ProjectionElem::Subslice { .. } => {
1733 panic!("we don't allow assignments to subslices, location: {:?}",
1737 ProjectionElem::Field(..) => {
1738 // if type of `P` has a dtor, then
1739 // assigning to `P.f` requires `P` itself
1740 // be already initialized
1741 let tcx = self.infcx.tcx;
1742 let base_ty = Place::ty_from(&place.base, proj_base, self.body, tcx).ty;
1743 match base_ty.kind {
1744 ty::Adt(def, _) if def.has_dtor(tcx) => {
1745 self.check_if_path_or_subpath_is_moved(
1746 location, InitializationRequiringAction::Assignment,
1749 projection: proj_base,
1750 }, span), flow_state);
1752 // (base initialized; no need to
1757 // Once `let s; s.x = V; read(s.x);`,
1758 // is allowed, remove this match arm.
1759 ty::Adt(..) | ty::Tuple(..) => {
1760 check_parent_of_field(self, location, PlaceRef {
1762 projection: proj_base,
1763 }, span, flow_state);
1765 if let PlaceBase::Local(local) = place.base {
1766 // rust-lang/rust#21232,
1767 // #54499, #54986: during
1768 // period where we reject
1769 // partial initialization, do
1770 // not complain about
1771 // unnecessary `mut` on an
1772 // attempt to do a partial
1774 self.used_mut.insert(local);
1784 fn check_parent_of_field<'cx, 'tcx>(
1785 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1787 base: PlaceRef<'cx, 'tcx>,
1789 flow_state: &Flows<'cx, 'tcx>,
1791 // rust-lang/rust#21232: Until Rust allows reads from the
1792 // initialized parts of partially initialized structs, we
1793 // will, starting with the 2018 edition, reject attempts
1794 // to write to structs that are not fully initialized.
1796 // In other words, *until* we allow this:
1798 // 1. `let mut s; s.x = Val; read(s.x);`
1800 // we will for now disallow this:
1802 // 2. `let mut s; s.x = Val;`
1806 // 3. `let mut s = ...; drop(s); s.x=Val;`
1808 // This does not use check_if_path_or_subpath_is_moved,
1809 // because we want to *allow* reinitializations of fields:
1810 // e.g., want to allow
1812 // `let mut s = ...; drop(s.x); s.x=Val;`
1814 // This does not use check_if_full_path_is_moved on
1815 // `base`, because that would report an error about the
1816 // `base` as a whole, but in this scenario we *really*
1817 // want to report an error about the actual thing that was
1818 // moved, which may be some prefix of `base`.
1820 // Shallow so that we'll stop at any dereference; we'll
1821 // report errors about issues with such bases elsewhere.
1822 let maybe_uninits = &flow_state.uninits;
1824 // Find the shortest uninitialized prefix you can reach
1825 // without going over a Deref.
1826 let mut shortest_uninit_seen = None;
1827 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1828 let mpi = match this.move_path_for_place(prefix) {
1829 Some(mpi) => mpi, None => continue,
1832 if maybe_uninits.contains(mpi) {
1833 debug!("check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1834 shortest_uninit_seen, Some((prefix, mpi)));
1835 shortest_uninit_seen = Some((prefix, mpi));
1837 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1841 if let Some((prefix, mpi)) = shortest_uninit_seen {
1842 // Check for a reassignment into a uninitialized field of a union (for example,
1843 // after a move out). In this case, do not report a error here. There is an
1844 // exception, if this is the first assignment into the union (that is, there is
1845 // no move out from an earlier location) then this is an attempt at initialization
1846 // of the union - we should error in that case.
1847 let tcx = this.infcx.tcx;
1848 if let ty::Adt(def, _) =
1849 Place::ty_from(base.base, base.projection, this.body, tcx).ty.kind
1852 if this.move_data.path_map[mpi].iter().any(|moi| {
1853 this.move_data.moves[*moi].source.is_predecessor_of(
1854 location, this.body,
1862 this.report_use_of_moved_or_uninitialized(
1864 InitializationRequiringAction::PartialAssignment,
1865 (prefix, base, span),
1872 /// Checks the permissions for the given place and read or write kind
1874 /// Returns `true` if an error is reported.
1875 fn check_access_permissions(
1877 (place, span): (&Place<'tcx>, Span),
1879 is_local_mutation_allowed: LocalMutationIsAllowed,
1880 flow_state: &Flows<'cx, 'tcx>,
1884 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1885 place, kind, is_local_mutation_allowed
1891 // rust-lang/rust#21232, #54986: during period where we reject
1892 // partial initialization, do not complain about mutability
1893 // errors except for actual mutation (as opposed to an attempt
1894 // to do a partial initialization).
1895 let previously_initialized = if let PlaceBase::Local(local) = place.base {
1896 self.is_local_ever_initialized(local, flow_state).is_some()
1902 Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1903 | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
1904 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1905 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. })) => {
1906 let is_local_mutation_allowed = match borrow_kind {
1907 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1908 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1909 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1911 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1913 self.add_used_mut(root_place, flow_state);
1917 error_access = AccessKind::MutableBorrow;
1918 the_place_err = place_err;
1922 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1923 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1925 self.add_used_mut(root_place, flow_state);
1929 error_access = AccessKind::Mutate;
1930 the_place_err = place_err;
1935 Reservation(WriteKind::Move)
1936 | Write(WriteKind::Move)
1937 | Reservation(WriteKind::StorageDeadOrDrop)
1938 | Reservation(WriteKind::MutableBorrow(BorrowKind::Shared))
1939 | Reservation(WriteKind::MutableBorrow(BorrowKind::Shallow))
1940 | Write(WriteKind::StorageDeadOrDrop)
1941 | Write(WriteKind::MutableBorrow(BorrowKind::Shared))
1942 | Write(WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
1943 if let (Err(_), true) = (
1944 self.is_mutable(place.as_ref(), is_local_mutation_allowed),
1945 self.errors_buffer.is_empty()
1947 // rust-lang/rust#46908: In pure NLL mode this code path should
1948 // be unreachable (and thus we signal an ICE in the else branch here).
1951 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
1959 // permission checks are done at Reservation point.
1962 Read(ReadKind::Borrow(BorrowKind::Unique))
1963 | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
1964 | Read(ReadKind::Borrow(BorrowKind::Shared))
1965 | Read(ReadKind::Borrow(BorrowKind::Shallow))
1966 | Read(ReadKind::Copy) => {
1967 // Access authorized
1972 // at this point, we have set up the error reporting state.
1973 return if previously_initialized {
1974 self.report_mutability_error(
1987 fn is_local_ever_initialized(
1990 flow_state: &Flows<'cx, 'tcx>,
1991 ) -> Option<InitIndex> {
1992 let mpi = self.move_data.rev_lookup.find_local(local);
1993 let ii = &self.move_data.init_path_map[mpi];
1995 if flow_state.ever_inits.contains(index) {
2002 /// Adds the place into the used mutable variables set
2003 fn add_used_mut<'d>(&mut self, root_place: RootPlace<'d, 'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2006 place_base: PlaceBase::Local(local),
2007 place_projection: [],
2008 is_local_mutation_allowed,
2010 // If the local may have been initialized, and it is now currently being
2011 // mutated, then it is justified to be annotated with the `mut`
2012 // keyword, since the mutation may be a possible reassignment.
2013 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes &&
2014 self.is_local_ever_initialized(*local, flow_state).is_some()
2016 self.used_mut.insert(*local);
2021 place_projection: _,
2022 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2026 place_projection: place_projection @ [.., _],
2027 is_local_mutation_allowed: _,
2029 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2031 projection: &place_projection,
2033 self.used_mut_upvars.push(field);
2037 place_base: PlaceBase::Static(..),
2038 place_projection: [],
2039 is_local_mutation_allowed: _,
2044 /// Whether this value can be written or borrowed mutably.
2045 /// Returns the root place if the place passed in is a projection.
2048 place: PlaceRef<'d, 'tcx>,
2049 is_local_mutation_allowed: LocalMutationIsAllowed,
2050 ) -> Result<RootPlace<'d, 'tcx>, PlaceRef<'d, 'tcx>> {
2053 base: PlaceBase::Local(local),
2056 let local = &self.body.local_decls[*local];
2057 match local.mutability {
2058 Mutability::Not => match is_local_mutation_allowed {
2059 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2060 place_base: place.base,
2061 place_projection: place.projection,
2062 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2064 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2065 place_base: place.base,
2066 place_projection: place.projection,
2067 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2069 LocalMutationIsAllowed::No => Err(place),
2071 Mutability::Mut => Ok(RootPlace {
2072 place_base: place.base,
2073 place_projection: place.projection,
2074 is_local_mutation_allowed,
2078 // The rules for promotion are made by `qualify_consts`, there wouldn't even be a
2079 // `Place::Promoted` if the promotion weren't 100% legal. So we just forward this
2081 base: PlaceBase::Static(box Static {
2082 kind: StaticKind::Promoted(..),
2088 place_base: place.base,
2089 place_projection: place.projection,
2090 is_local_mutation_allowed,
2093 base: PlaceBase::Static(box Static {
2094 kind: StaticKind::Static,
2100 if !self.infcx.tcx.is_mutable_static(*def_id) {
2104 place_base: place.base,
2105 place_projection: place.projection,
2106 is_local_mutation_allowed,
2112 projection: [proj_base @ .., elem],
2115 ProjectionElem::Deref => {
2117 Place::ty_from(place.base, proj_base, self.body, self.infcx.tcx).ty;
2119 // Check the kind of deref to decide
2120 match base_ty.kind {
2121 ty::Ref(_, _, mutbl) => {
2123 // Shared borrowed data is never mutable
2124 hir::MutImmutable => Err(place),
2125 // Mutably borrowed data is mutable, but only if we have a
2126 // unique path to the `&mut`
2127 hir::MutMutable => {
2128 let mode = match self.is_upvar_field_projection(place) {
2130 if self.upvars[field.index()].by_ref =>
2132 is_local_mutation_allowed
2134 _ => LocalMutationIsAllowed::Yes,
2137 self.is_mutable(PlaceRef {
2139 projection: proj_base,
2144 ty::RawPtr(tnm) => {
2146 // `*const` raw pointers are not mutable
2147 hir::MutImmutable => Err(place),
2148 // `*mut` raw pointers are always mutable, regardless of
2149 // context. The users have to check by themselves.
2150 hir::MutMutable => {
2152 place_base: place.base,
2153 place_projection: place.projection,
2154 is_local_mutation_allowed,
2159 // `Box<T>` owns its content, so mutable if its location is mutable
2160 _ if base_ty.is_box() => {
2161 self.is_mutable(PlaceRef {
2163 projection: proj_base,
2164 }, is_local_mutation_allowed)
2166 // Deref should only be for reference, pointers or boxes
2167 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2170 // All other projections are owned by their base path, so mutable if
2171 // base path is mutable
2172 ProjectionElem::Field(..)
2173 | ProjectionElem::Index(..)
2174 | ProjectionElem::ConstantIndex { .. }
2175 | ProjectionElem::Subslice { .. }
2176 | ProjectionElem::Downcast(..) => {
2177 let upvar_field_projection = self.is_upvar_field_projection(place);
2178 if let Some(field) = upvar_field_projection {
2179 let upvar = &self.upvars[field.index()];
2181 "upvar.mutability={:?} local_mutation_is_allowed={:?} \
2183 upvar, is_local_mutation_allowed, place
2185 match (upvar.mutability, is_local_mutation_allowed) {
2186 (Mutability::Not, LocalMutationIsAllowed::No)
2187 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2190 (Mutability::Not, LocalMutationIsAllowed::Yes)
2191 | (Mutability::Mut, _) => {
2192 // Subtle: this is an upvar
2193 // reference, so it looks like
2194 // `self.foo` -- we want to double
2195 // check that the location `*self`
2196 // is mutable (i.e., this is not a
2197 // `Fn` closure). But if that
2198 // check succeeds, we want to
2199 // *blame* the mutability on
2200 // `place` (that is,
2201 // `self.foo`). This is used to
2202 // propagate the info about
2203 // whether mutability declarations
2204 // are used outwards, so that we register
2205 // the outer variable as mutable. Otherwise a
2206 // test like this fails to record the `mut`
2210 // fn foo<F: FnOnce()>(_f: F) { }
2212 // let var = Vec::new();
2218 let _ = self.is_mutable(PlaceRef {
2220 projection: proj_base,
2221 }, is_local_mutation_allowed)?;
2223 place_base: place.base,
2224 place_projection: place.projection,
2225 is_local_mutation_allowed,
2230 self.is_mutable(PlaceRef {
2232 projection: proj_base,
2233 }, is_local_mutation_allowed)
2241 /// If `place` is a field projection, and the field is being projected from a closure type,
2242 /// then returns the index of the field being projected. Note that this closure will always
2243 /// be `self` in the current MIR, because that is the only time we directly access the fields
2244 /// of a closure type.
2245 pub fn is_upvar_field_projection(&self, place_ref: PlaceRef<'cx, 'tcx>) -> Option<Field> {
2246 let mut place_projection = place_ref.projection;
2247 let mut by_ref = false;
2249 if let [proj_base @ .., ProjectionElem::Deref] = place_projection {
2250 place_projection = proj_base;
2254 match place_projection {
2255 [base @ .., ProjectionElem::Field(field, _ty)] => {
2256 let tcx = self.infcx.tcx;
2257 let base_ty = Place::ty_from(place_ref.base, base, self.body, tcx).ty;
2259 if (base_ty.is_closure() || base_ty.is_generator()) &&
2260 (!by_ref || self.upvars[field.index()].by_ref) {
2272 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2273 enum NoMovePathFound {
2277 /// The degree of overlap between 2 places for borrow-checking.
2279 /// The places might partially overlap - in this case, we give
2280 /// up and say that they might conflict. This occurs when
2281 /// different fields of a union are borrowed. For example,
2282 /// if `u` is a union, we have no way of telling how disjoint
2283 /// `u.a.x` and `a.b.y` are.
2285 /// The places have the same type, and are either completely disjoint
2286 /// or equal - i.e., they can't "partially" overlap as can occur with
2287 /// unions. This is the "base case" on which we recur for extensions
2290 /// The places are disjoint, so we know all extensions of them
2291 /// will also be disjoint.