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_index::bit_set::BitSet;
22 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
23 use rustc_data_structures::graph::dominators::Dominators;
24 use rustc_index::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 let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
119 for var_debug_info in &input_body.var_debug_info {
120 if let Some(local) = var_debug_info.place.as_local() {
121 if let Some(prev_name) = local_names[local] {
122 if var_debug_info.name != prev_name {
123 span_bug!(var_debug_info.source_info.span,
124 "local {:?} has many names (`{}` vs `{}`)",
125 local, prev_name, var_debug_info.name);
128 local_names[local] = Some(var_debug_info.name);
132 // Gather the upvars of a closure, if any.
133 let tables = tcx.typeck_tables_of(def_id);
134 let upvars: Vec<_> = tables
138 .flat_map(|v| v.values())
140 let var_hir_id = upvar_id.var_path.hir_id;
141 let capture = tables.upvar_capture(*upvar_id);
142 let by_ref = match capture {
143 ty::UpvarCapture::ByValue => false,
144 ty::UpvarCapture::ByRef(..) => true,
146 let mut upvar = Upvar {
147 name: tcx.hir().name(var_hir_id),
150 mutability: Mutability::Not,
152 let bm = *tables.pat_binding_modes().get(var_hir_id)
153 .expect("missing binding mode");
154 if bm == ty::BindByValue(hir::Mutability::Mutable) {
155 upvar.mutability = Mutability::Mut;
161 // Replace all regions with fresh inference variables. This
162 // requires first making our own copy of the MIR. This copy will
163 // be modified (in place) to contain non-lexical lifetimes. It
164 // will have a lifetime tied to the inference context.
165 let mut body: Body<'tcx> = input_body.clone();
166 let mut promoted: IndexVec<Promoted, Body<'tcx>> = input_promoted.clone();
168 nll::replace_regions_in_mir(infcx, def_id, param_env, &mut body, &mut promoted);
169 let body = &body; // no further changes
170 let location_table = &LocationTable::new(body);
172 let mut errors_buffer = Vec::new();
173 let (move_data, move_errors): (MoveData<'tcx>, Option<Vec<(Place<'tcx>, MoveError<'tcx>)>>) =
174 match MoveData::gather_moves(body, tcx) {
175 Ok(move_data) => (move_data, None),
176 Err((move_data, move_errors)) => (move_data, Some(move_errors)),
179 let mdpe = MoveDataParamEnv {
184 let dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
185 let mut flow_inits = FlowAtLocation::new(do_dataflow(
191 MaybeInitializedPlaces::new(tcx, body, &mdpe),
192 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
195 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
196 let borrow_set = Rc::new(BorrowSet::build(
197 tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
199 // If we are in non-lexical mode, compute the non-lexical lifetimes.
200 let (regioncx, polonius_output, opt_closure_req) = nll::compute_regions(
216 // The various `flow_*` structures can be large. We drop `flow_inits` here
217 // so it doesn't overlap with the others below. This reduces peak memory
218 // usage significantly on some benchmarks.
221 let regioncx = Rc::new(regioncx);
223 let flow_borrows = FlowAtLocation::new(do_dataflow(
229 Borrows::new(tcx, body, param_env, regioncx.clone(), &borrow_set),
230 |rs, i| DebugFormatted::new(&rs.location(i)),
232 let flow_uninits = FlowAtLocation::new(do_dataflow(
238 MaybeUninitializedPlaces::new(tcx, body, &mdpe),
239 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
241 let flow_ever_inits = FlowAtLocation::new(do_dataflow(
247 EverInitializedPlaces::new(tcx, body, &mdpe),
248 |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
251 let movable_generator = match tcx.hir().get(id) {
252 Node::Expr(&hir::Expr {
253 kind: hir::ExprKind::Closure(.., Some(hir::Movability::Static)),
259 let dominators = body.dominators();
261 let mut mbcx = MirBorrowckCtxt {
266 move_data: &mdpe.move_data,
269 locals_are_invalidated_at_exit,
270 access_place_error_reported: Default::default(),
271 reservation_error_reported: Default::default(),
272 reservation_warnings: Default::default(),
273 move_error_reported: BTreeMap::new(),
274 uninitialized_error_reported: Default::default(),
276 nonlexical_regioncx: regioncx,
277 used_mut: Default::default(),
278 used_mut_upvars: SmallVec::new(),
285 let mut state = Flows::new(
292 if let Some(errors) = move_errors {
293 mbcx.report_move_errors(errors);
295 mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
297 // Convert any reservation warnings into lints.
298 let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
299 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
300 let mut initial_diag =
301 mbcx.report_conflicting_borrow(location, (&place, span), bk, &borrow);
303 let lint_root = if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
304 let scope = mbcx.body.source_info(location).scope;
310 // Span and message don't matter; we overwrite them below anyway
311 let mut diag = mbcx.infcx.tcx.struct_span_lint_hir(
312 MUTABLE_BORROW_RESERVATION_CONFLICT, lint_root, DUMMY_SP, "");
314 diag.message = initial_diag.styled_message().clone();
315 diag.span = initial_diag.span.clone();
317 initial_diag.cancel();
318 diag.buffer(&mut mbcx.errors_buffer);
321 // For each non-user used mutable variable, check if it's been assigned from
322 // a user-declared local. If so, then put that local into the used_mut set.
323 // Note that this set is expected to be small - only upvars from closures
324 // would have a chance of erroneously adding non-user-defined mutable vars
326 let temporary_used_locals: FxHashSet<Local> = mbcx.used_mut.iter()
327 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
330 // For the remaining unused locals that are marked as mutable, we avoid linting any that
331 // were never initialized. These locals may have been removed as unreachable code; or will be
332 // linted as unused variables.
333 let unused_mut_locals = mbcx.body.mut_vars_iter()
334 .filter(|local| !mbcx.used_mut.contains(local))
336 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
338 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
339 let used_mut = mbcx.used_mut;
340 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
341 if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
342 let local_decl = &mbcx.body.local_decls[local];
344 // Skip over locals that begin with an underscore or have no name
345 match mbcx.local_names[local] {
346 Some(name) => if name.as_str().starts_with("_") {
352 let span = local_decl.source_info.span;
353 if span.desugaring_kind().is_some() {
354 // If the `mut` arises as part of a desugaring, we should ignore it.
358 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
359 tcx.struct_span_lint_hir(
361 vsi[local_decl.source_info.scope].lint_root,
363 "variable does not need to be mutable",
365 .span_suggestion_short(
369 Applicability::MachineApplicable,
375 // Buffer any move errors that we collected and de-duplicated.
376 for (_, (_, diag)) in mbcx.move_error_reported {
377 diag.buffer(&mut mbcx.errors_buffer);
380 if !mbcx.errors_buffer.is_empty() {
381 mbcx.errors_buffer.sort_by_key(|diag| diag.sort_span);
383 for diag in mbcx.errors_buffer.drain(..) {
384 mbcx.infcx.tcx.sess.diagnostic().emit_diagnostic(&diag);
388 let result = BorrowCheckResult {
389 closure_requirements: opt_closure_req,
390 used_mut_upvars: mbcx.used_mut_upvars,
393 debug!("do_mir_borrowck: result = {:#?}", result);
398 crate struct MirBorrowckCtxt<'cx, 'tcx> {
399 crate infcx: &'cx InferCtxt<'cx, 'tcx>,
400 body: &'cx Body<'tcx>,
402 param_env: ty::ParamEnv<'tcx>,
403 move_data: &'cx MoveData<'tcx>,
405 /// Map from MIR `Location` to `LocationIndex`; created
406 /// when MIR borrowck begins.
407 location_table: &'cx LocationTable,
409 movable_generator: bool,
410 /// This keeps track of whether local variables are free-ed when the function
411 /// exits even without a `StorageDead`, which appears to be the case for
414 /// I'm not sure this is the right approach - @eddyb could you try and
416 locals_are_invalidated_at_exit: bool,
417 /// This field keeps track of when borrow errors are reported in the access_place function
418 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
419 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
420 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
422 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
423 /// This field keeps track of when borrow conflict errors are reported
424 /// for reservations, so that we don't report seemingly duplicate
425 /// errors for corresponding activations.
427 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
428 // but it is currently inconvenient to track down the `BorrowIndex`
429 // at the time we detect and report a reservation error.
430 reservation_error_reported: FxHashSet<Place<'tcx>>,
431 /// Migration warnings to be reported for #56254. We delay reporting these
432 /// so that we can suppress the warning if there's a corresponding error
433 /// for the activation of the borrow.
434 reservation_warnings: FxHashMap<
436 (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)
438 /// This field keeps track of move errors that are to be reported for given move indicies.
440 /// There are situations where many errors can be reported for a single move out (see #53807)
441 /// and we want only the best of those errors.
443 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
444 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
445 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
446 /// all move errors have been reported, any diagnostics in this map are added to the buffer
449 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
450 /// when errors in the map are being re-added to the error buffer so that errors with the
451 /// same primary span come out in a consistent order.
452 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'cx, 'tcx>, DiagnosticBuilder<'cx>)>,
453 /// This field keeps track of errors reported in the checking of uninitialized variables,
454 /// so that we don't report seemingly duplicate errors.
455 uninitialized_error_reported: FxHashSet<PlaceRef<'cx, 'tcx>>,
456 /// Errors to be reported buffer
457 errors_buffer: Vec<Diagnostic>,
458 /// This field keeps track of all the local variables that are declared mut and are mutated.
459 /// Used for the warning issued by an unused mutable local variable.
460 used_mut: FxHashSet<Local>,
461 /// If the function we're checking is a closure, then we'll need to report back the list of
462 /// mutable upvars that have been used. This field keeps track of them.
463 used_mut_upvars: SmallVec<[Field; 8]>,
464 /// Non-lexical region inference context, if NLL is enabled. This
465 /// contains the results from region inference and lets us e.g.
466 /// find out which CFG points are contained in each borrow region.
467 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
469 /// The set of borrows extracted from the MIR
470 borrow_set: Rc<BorrowSet<'tcx>>,
472 /// Dominators for MIR
473 dominators: Dominators<BasicBlock>,
475 /// Information about upvars not necessarily preserved in types or MIR
478 /// Names of local (user) variables (extracted from `var_debug_info`).
479 local_names: IndexVec<Local, Option<Name>>,
483 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
484 // 2. loans made in overlapping scopes do not conflict
485 // 3. assignments do not affect things loaned out as immutable
486 // 4. moves do not affect things loaned out in any way
487 impl<'cx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
488 type FlowState = Flows<'cx, 'tcx>;
490 fn body(&self) -> &'cx Body<'tcx> {
494 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
495 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
498 fn visit_statement_entry(
501 stmt: &'cx Statement<'tcx>,
502 flow_state: &Self::FlowState,
505 "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
506 location, stmt, flow_state
508 let span = stmt.source_info.span;
510 self.check_activations(location, span, flow_state);
513 StatementKind::Assign(box(ref lhs, ref rhs)) => {
528 StatementKind::FakeRead(_, box ref place) => {
529 // Read for match doesn't access any memory and is used to
530 // assert that a place is safe and live. So we don't have to
531 // do any checks here.
533 // FIXME: Remove check that the place is initialized. This is
534 // needed for now because matches don't have never patterns yet.
535 // So this is the only place we prevent
539 self.check_if_path_or_subpath_is_moved(
541 InitializationRequiringAction::Use,
542 (place.as_ref(), span),
546 StatementKind::SetDiscriminant {
558 StatementKind::InlineAsm(ref asm) => {
559 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
561 // FIXME(eddyb) indirect inline asm outputs should
562 // be encoded through MIR place derefs instead.
566 (Deep, Read(ReadKind::Copy)),
567 LocalMutationIsAllowed::No,
570 self.check_if_path_or_subpath_is_moved(
572 InitializationRequiringAction::Use,
573 (output.as_ref(), o.span),
580 if o.is_rw { Deep } else { Shallow(None) },
581 if o.is_rw { WriteAndRead } else { JustWrite },
586 for (_, input) in asm.inputs.iter() {
587 self.consume_operand(location, (input, span), flow_state);
591 | StatementKind::AscribeUserType(..)
592 | StatementKind::Retag { .. }
593 | StatementKind::StorageLive(..) => {
594 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
597 StatementKind::StorageDead(local) => {
600 (&Place::from(local), span),
601 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
602 LocalMutationIsAllowed::Yes,
609 fn visit_terminator_entry(
612 term: &'cx Terminator<'tcx>,
613 flow_state: &Self::FlowState,
617 "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
618 location, term, flow_state
620 let span = term.source_info.span;
622 self.check_activations(location, span, flow_state);
625 TerminatorKind::SwitchInt {
631 self.consume_operand(loc, (discr, span), flow_state);
633 TerminatorKind::Drop {
634 location: ref drop_place,
638 let tcx = self.infcx.tcx;
640 // Compute the type with accurate region information.
641 let drop_place_ty = drop_place.ty(self.body, self.infcx.tcx);
643 // Erase the regions.
644 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
646 // "Lift" into the tcx -- once regions are erased, this type should be in the
647 // global arenas; this "lift" operation basically just asserts that is true, but
648 // that is useful later.
649 tcx.lift(&drop_place_ty).unwrap();
651 debug!("visit_terminator_drop \
652 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
653 loc, term, drop_place, drop_place_ty, span);
658 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
659 LocalMutationIsAllowed::Yes,
663 TerminatorKind::DropAndReplace {
664 location: ref drop_place,
665 value: ref new_value,
676 self.consume_operand(
682 TerminatorKind::Call {
689 self.consume_operand(loc, (func, span), flow_state);
691 self.consume_operand(
697 if let Some((ref dest, _ /*bb*/)) = *destination {
707 TerminatorKind::Assert {
714 self.consume_operand(loc, (cond, span), flow_state);
715 use rustc::mir::interpret::PanicInfo;
716 if let PanicInfo::BoundsCheck { ref len, ref index } = *msg {
717 self.consume_operand(loc, (len, span), flow_state);
718 self.consume_operand(loc, (index, span), flow_state);
722 TerminatorKind::Yield {
727 self.consume_operand(loc, (value, span), flow_state);
729 if self.movable_generator {
730 // Look for any active borrows to locals
731 let borrow_set = self.borrow_set.clone();
732 flow_state.with_outgoing_borrows(|borrows| {
734 let borrow = &borrow_set[i];
735 self.check_for_local_borrow(borrow, span);
741 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
742 // Returning from the function implicitly kills storage for all locals and statics.
743 // Often, the storage will already have been killed by an explicit
744 // StorageDead, but we don't always emit those (notably on unwind paths),
745 // so this "extra check" serves as a kind of backup.
746 let borrow_set = self.borrow_set.clone();
747 flow_state.with_outgoing_borrows(|borrows| {
749 let borrow = &borrow_set[i];
750 self.check_for_invalidation_at_exit(loc, borrow, span);
754 TerminatorKind::Goto { target: _ }
755 | TerminatorKind::Abort
756 | TerminatorKind::Unreachable
757 | TerminatorKind::FalseEdges {
761 | TerminatorKind::FalseUnwind {
765 // no data used, thus irrelevant to borrowck
771 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
777 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
778 use self::AccessDepth::{Deep, Shallow};
780 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
781 enum ArtificialField {
786 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
788 /// From the RFC: "A *shallow* access means that the immediate
789 /// fields reached at P are accessed, but references or pointers
790 /// found within are not dereferenced. Right now, the only access
791 /// that is shallow is an assignment like `x = ...;`, which would
792 /// be a *shallow write* of `x`."
793 Shallow(Option<ArtificialField>),
795 /// From the RFC: "A *deep* access means that all data reachable
796 /// through the given place may be invalidated or accesses by
800 /// Access is Deep only when there is a Drop implementation that
801 /// can reach the data behind the reference.
805 /// Kind of access to a value: read or write
806 /// (For informational purposes only)
807 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
809 /// From the RFC: "A *read* means that the existing data may be
810 /// read, but will not be changed."
813 /// From the RFC: "A *write* means that the data may be mutated to
814 /// new values or otherwise invalidated (for example, it could be
815 /// de-initialized, as in a move operation).
818 /// For two-phase borrows, we distinguish a reservation (which is treated
819 /// like a Read) from an activation (which is treated like a write), and
820 /// each of those is furthermore distinguished from Reads/Writes above.
821 Reservation(WriteKind),
822 Activation(WriteKind, BorrowIndex),
825 /// Kind of read access to a value
826 /// (For informational purposes only)
827 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
833 /// Kind of write access to a value
834 /// (For informational purposes only)
835 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
838 MutableBorrow(BorrowKind),
843 /// When checking permissions for a place access, this flag is used to indicate that an immutable
844 /// local place can be mutated.
846 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
847 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
848 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
849 // `is_declared_mutable()`.
850 // - Take flow state into consideration in `is_assignable()` for local variables.
851 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
852 enum LocalMutationIsAllowed {
854 /// We want use of immutable upvars to cause a "write to immutable upvar"
855 /// error, not an "reassignment" error.
860 #[derive(Copy, Clone, Debug)]
861 enum InitializationRequiringAction {
870 struct RootPlace<'d, 'tcx> {
871 place_base: &'d PlaceBase<'tcx>,
872 place_projection: &'d [PlaceElem<'tcx>],
873 is_local_mutation_allowed: LocalMutationIsAllowed,
876 impl InitializationRequiringAction {
877 fn as_noun(self) -> &'static str {
879 InitializationRequiringAction::Update => "update",
880 InitializationRequiringAction::Borrow => "borrow",
881 InitializationRequiringAction::MatchOn => "use", // no good noun
882 InitializationRequiringAction::Use => "use",
883 InitializationRequiringAction::Assignment => "assign",
884 InitializationRequiringAction::PartialAssignment => "assign to part",
888 fn as_verb_in_past_tense(self) -> &'static str {
890 InitializationRequiringAction::Update => "updated",
891 InitializationRequiringAction::Borrow => "borrowed",
892 InitializationRequiringAction::MatchOn => "matched on",
893 InitializationRequiringAction::Use => "used",
894 InitializationRequiringAction::Assignment => "assigned",
895 InitializationRequiringAction::PartialAssignment => "partially assigned",
900 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
901 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
902 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
903 /// place is initialized and (b) it is not borrowed in some way that would prevent this
906 /// Returns `true` if an error is reported.
910 place_span: (&Place<'tcx>, Span),
911 kind: (AccessDepth, ReadOrWrite),
912 is_local_mutation_allowed: LocalMutationIsAllowed,
913 flow_state: &Flows<'cx, 'tcx>,
917 if let Activation(_, borrow_index) = rw {
918 if self.reservation_error_reported.contains(&place_span.0) {
920 "skipping access_place for activation of invalid reservation \
921 place: {:?} borrow_index: {:?}",
922 place_span.0, borrow_index
928 // Check is_empty() first because it's the common case, and doing that
929 // way we avoid the clone() call.
930 if !self.access_place_error_reported.is_empty() &&
932 .access_place_error_reported
933 .contains(&(place_span.0.clone(), place_span.1))
936 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
942 let mutability_error =
943 self.check_access_permissions(
946 is_local_mutation_allowed,
951 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
953 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
954 // Suppress this warning when there's an error being emitted for the
955 // same borrow: fixing the error is likely to fix the warning.
956 self.reservation_warnings.remove(&borrow_idx);
959 if conflict_error || mutability_error {
961 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
965 self.access_place_error_reported
966 .insert((place_span.0.clone(), place_span.1));
970 fn check_access_for_conflict(
973 place_span: (&Place<'tcx>, Span),
976 flow_state: &Flows<'cx, 'tcx>,
979 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
980 location, place_span, sd, rw,
983 let mut error_reported = false;
984 let tcx = self.infcx.tcx;
985 let body = self.body;
986 let param_env = self.param_env;
987 let location_table = self.location_table.start_index(location);
988 let borrow_set = self.borrow_set.clone();
989 each_borrow_involving_path(
997 flow_state.borrows_in_scope(location_table),
998 |this, borrow_index, borrow| match (rw, borrow.kind) {
999 // Obviously an activation is compatible with its own
1000 // reservation (or even prior activating uses of same
1001 // borrow); so don't check if they interfere.
1003 // NOTE: *reservations* do conflict with themselves;
1004 // thus aren't injecting unsoundenss w/ this check.)
1005 (Activation(_, activating), _) if activating == borrow_index => {
1007 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1008 skipping {:?} b/c activation of same borrow_index",
1012 (borrow_index, borrow),
1017 (Read(_), BorrowKind::Shared)
1018 | (Read(_), BorrowKind::Shallow)
1019 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
1020 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
1024 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1025 // Handled by initialization checks.
1029 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
1030 // Reading from mere reservations of mutable-borrows is OK.
1031 if !is_active(&this.dominators, borrow, location) {
1032 assert!(allow_two_phase_borrow(borrow.kind));
1033 return Control::Continue;
1036 error_reported = true;
1039 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1040 .buffer(&mut this.errors_buffer);
1042 ReadKind::Borrow(bk) => {
1043 this.report_conflicting_borrow(location, place_span, bk, borrow)
1044 .buffer(&mut this.errors_buffer);
1050 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
1051 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared) if {
1052 tcx.migrate_borrowck() && this.borrow_set.location_map.contains_key(&location)
1054 let bi = this.borrow_set.location_map[&location];
1056 "recording invalid reservation of place: {:?} with \
1057 borrow index {:?} as warning",
1061 // rust-lang/rust#56254 - This was previously permitted on
1062 // the 2018 edition so we emit it as a warning. We buffer
1063 // these sepately so that we only emit a warning if borrow
1064 // checking was otherwise successful.
1065 this.reservation_warnings.insert(
1067 (place_span.0.clone(), place_span.1, location, bk, borrow.clone()),
1070 // Don't suppress actual errors.
1074 (Reservation(kind), _)
1075 | (Activation(kind, _), _)
1076 | (Write(kind), _) => {
1078 Reservation(..) => {
1080 "recording invalid reservation of \
1084 this.reservation_error_reported.insert(place_span.0.clone());
1086 Activation(_, activating) => {
1088 "observing check_place for activation of \
1089 borrow_index: {:?}",
1093 Read(..) | Write(..) => {}
1096 error_reported = true;
1098 WriteKind::MutableBorrow(bk) => {
1099 this.report_conflicting_borrow(location, place_span, bk, borrow)
1100 .buffer(&mut this.errors_buffer);
1102 WriteKind::StorageDeadOrDrop => {
1103 this.report_borrowed_value_does_not_live_long_enough(
1109 WriteKind::Mutate => {
1110 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1112 WriteKind::Move => {
1113 this.report_move_out_while_borrowed(location, place_span, borrow)
1127 place_span: (&'cx Place<'tcx>, Span),
1130 flow_state: &Flows<'cx, 'tcx>,
1132 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1134 MutateMode::WriteAndRead => {
1135 self.check_if_path_or_subpath_is_moved(
1137 InitializationRequiringAction::Update,
1138 (place_span.0.as_ref(), place_span.1),
1142 MutateMode::JustWrite => {
1143 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1147 // Special case: you can assign a immutable local variable
1148 // (e.g., `x = ...`) so long as it has never been initialized
1149 // before (at this point in the flow).
1150 if let Some(local) = place_span.0.as_local() {
1151 if let Mutability::Not = self.body.local_decls[local].mutability {
1152 // check for reassignments to immutable local variables
1153 self.check_if_reassignment_to_immutable_state(
1163 // Otherwise, use the normal access permission rules.
1167 (kind, Write(WriteKind::Mutate)),
1168 LocalMutationIsAllowed::No,
1176 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1177 flow_state: &Flows<'cx, 'tcx>,
1180 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1181 let access_kind = match bk {
1182 BorrowKind::Shallow => {
1183 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1185 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1186 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1187 let wk = WriteKind::MutableBorrow(bk);
1188 if allow_two_phase_borrow(bk) {
1189 (Deep, Reservation(wk))
1200 LocalMutationIsAllowed::No,
1204 let action = if bk == BorrowKind::Shallow {
1205 InitializationRequiringAction::MatchOn
1207 InitializationRequiringAction::Borrow
1210 self.check_if_path_or_subpath_is_moved(
1213 (place.as_ref(), span),
1218 Rvalue::Use(ref operand)
1219 | Rvalue::Repeat(ref operand, _)
1220 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1221 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1222 self.consume_operand(location, (operand, span), flow_state)
1225 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1226 let af = match *rvalue {
1227 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1228 Rvalue::Discriminant(..) => None,
1229 _ => unreachable!(),
1234 (Shallow(af), Read(ReadKind::Copy)),
1235 LocalMutationIsAllowed::No,
1238 self.check_if_path_or_subpath_is_moved(
1240 InitializationRequiringAction::Use,
1241 (place.as_ref(), span),
1246 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1247 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1248 self.consume_operand(location, (operand1, span), flow_state);
1249 self.consume_operand(location, (operand2, span), flow_state);
1252 Rvalue::NullaryOp(_op, _ty) => {
1253 // nullary ops take no dynamic input; no borrowck effect.
1255 // FIXME: is above actually true? Do we want to track
1256 // the fact that uninitialized data can be created via
1260 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1261 // We need to report back the list of mutable upvars that were
1262 // moved into the closure and subsequently used by the closure,
1263 // in order to populate our used_mut set.
1264 match **aggregate_kind {
1265 AggregateKind::Closure(def_id, _)
1266 | AggregateKind::Generator(def_id, _, _) => {
1267 let BorrowCheckResult {
1269 } = self.infcx.tcx.mir_borrowck(def_id);
1270 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1271 for field in used_mut_upvars {
1272 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1275 AggregateKind::Adt(..)
1276 | AggregateKind::Array(..)
1277 | AggregateKind::Tuple { .. } => (),
1280 for operand in operands {
1281 self.consume_operand(location, (operand, span), flow_state);
1287 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1288 let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1289 if !place.projection.is_empty() {
1290 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1291 this.used_mut_upvars.push(field);
1293 } else if let PlaceBase::Local(local) = place.base {
1294 this.used_mut.insert(local);
1298 // This relies on the current way that by-value
1299 // captures of a closure are copied/moved directly
1300 // when generating MIR.
1302 Operand::Move(ref place) | Operand::Copy(ref place) => {
1303 match place.as_local() {
1304 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1305 if self.body.local_decls[local].ty.is_mutable_ptr() {
1306 // The variable will be marked as mutable by the borrow.
1309 // This is an edge case where we have a `move` closure
1310 // inside a non-move closure, and the inner closure
1311 // contains a mutation:
1314 // || { move || { i += 1; }; };
1316 // In this case our usual strategy of assuming that the
1317 // variable will be captured by mutable reference is
1318 // wrong, since `i` can be copied into the inner
1319 // closure from a shared reference.
1321 // As such we have to search for the local that this
1322 // capture comes from and mark it as being used as mut.
1324 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1325 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1326 &self.move_data.inits[init_index]
1328 bug!("temporary should be initialized exactly once")
1331 let loc = match init.location {
1332 InitLocation::Statement(stmt) => stmt,
1333 _ => bug!("temporary initialized in arguments"),
1336 let bbd = &self.body[loc.block];
1337 let stmt = &bbd.statements[loc.statement_index];
1338 debug!("temporary assigned in: stmt={:?}", stmt);
1340 if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, ref source))) =
1343 propagate_closure_used_mut_place(self, source);
1346 "closures should only capture user variables \
1347 or references to user variables"
1351 _ => propagate_closure_used_mut_place(self, place),
1354 Operand::Constant(..) => {}
1361 (operand, span): (&'cx Operand<'tcx>, Span),
1362 flow_state: &Flows<'cx, 'tcx>,
1365 Operand::Copy(ref place) => {
1366 // copy of place: check if this is "copy of frozen path"
1367 // (FIXME: see check_loans.rs)
1371 (Deep, Read(ReadKind::Copy)),
1372 LocalMutationIsAllowed::No,
1376 // Finally, check if path was already moved.
1377 self.check_if_path_or_subpath_is_moved(
1379 InitializationRequiringAction::Use,
1380 (place.as_ref(), span),
1384 Operand::Move(ref place) => {
1385 // move of place: check if this is move of already borrowed path
1389 (Deep, Write(WriteKind::Move)),
1390 LocalMutationIsAllowed::Yes,
1394 // Finally, check if path was already moved.
1395 self.check_if_path_or_subpath_is_moved(
1397 InitializationRequiringAction::Use,
1398 (place.as_ref(), span),
1402 Operand::Constant(_) => {}
1406 /// Checks whether a borrow of this place is invalidated when the function
1408 fn check_for_invalidation_at_exit(
1411 borrow: &BorrowData<'tcx>,
1414 debug!("check_for_invalidation_at_exit({:?})", borrow);
1415 let place = &borrow.borrowed_place;
1416 let deref = [ProjectionElem::Deref];
1417 let mut root_place = PlaceRef { base: &place.base, projection: &[] };
1419 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1420 // we just know that all locals are dropped at function exit (otherwise
1421 // we'll have a memory leak) and assume that all statics have a destructor.
1423 // FIXME: allow thread-locals to borrow other thread locals?
1425 let (might_be_alive, will_be_dropped) = match root_place.base {
1426 PlaceBase::Static(_) => {
1429 PlaceBase::Local(local) => {
1430 if self.body.local_decls[*local].is_ref_to_thread_local() {
1431 // Thread-locals might be dropped after the function exits
1432 // We have to dereference the outer reference because
1433 // borrows don't conflict behind shared references.
1434 root_place.projection = &deref;
1437 (false, self.locals_are_invalidated_at_exit)
1442 if !will_be_dropped {
1444 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1450 let sd = if might_be_alive { Deep } else { Shallow(None) };
1452 if places_conflict::borrow_conflicts_with_place(
1460 places_conflict::PlaceConflictBias::Overlap,
1462 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1463 // FIXME: should be talking about the region lifetime instead
1464 // of just a span here.
1465 let span = self.infcx.tcx.sess.source_map().end_point(span);
1466 self.report_borrowed_value_does_not_live_long_enough(
1475 /// Reports an error if this is a borrow of local data.
1476 /// This is called for all Yield statements on movable generators
1477 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1478 debug!("check_for_local_borrow({:?})", borrow);
1480 if borrow_of_local_data(&borrow.borrowed_place) {
1481 let err = self.cannot_borrow_across_generator_yield(
1482 self.retrieve_borrow_spans(borrow).var_or_use(),
1486 err.buffer(&mut self.errors_buffer);
1490 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1491 // Two-phase borrow support: For each activation that is newly
1492 // generated at this statement, check if it interferes with
1494 let borrow_set = self.borrow_set.clone();
1495 for &borrow_index in borrow_set.activations_at_location(location) {
1496 let borrow = &borrow_set[borrow_index];
1498 // only mutable borrows should be 2-phase
1499 assert!(match borrow.kind {
1500 BorrowKind::Shared | BorrowKind::Shallow => false,
1501 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1506 (&borrow.borrowed_place, span),
1509 Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1511 LocalMutationIsAllowed::No,
1514 // We do not need to call `check_if_path_or_subpath_is_moved`
1515 // again, as we already called it when we made the
1516 // initial reservation.
1521 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
1522 fn check_if_reassignment_to_immutable_state(
1526 place_span: (&Place<'tcx>, Span),
1527 flow_state: &Flows<'cx, 'tcx>,
1529 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1531 // Check if any of the initializiations of `local` have happened yet:
1532 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1533 // And, if so, report an error.
1534 let init = &self.move_data.inits[init_index];
1535 let span = init.span(&self.body);
1536 self.report_illegal_reassignment(
1537 location, place_span, span, place_span.0
1542 fn check_if_full_path_is_moved(
1545 desired_action: InitializationRequiringAction,
1546 place_span: (PlaceRef<'cx, 'tcx>, Span),
1547 flow_state: &Flows<'cx, 'tcx>,
1549 let maybe_uninits = &flow_state.uninits;
1553 // 1. Move of `a.b.c`, use of `a.b.c`
1554 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1555 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1556 // partial initialization support, one might have `a.x`
1557 // initialized but not `a.b`.
1561 // 4. Move of `a.b.c`, use of `a.b.d`
1562 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1563 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1564 // must have been initialized for the use to be sound.
1565 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1567 // The dataflow tracks shallow prefixes distinctly (that is,
1568 // field-accesses on P distinctly from P itself), in order to
1569 // track substructure initialization separately from the whole
1572 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1573 // which we have a MovePath is `a.b`, then that means that the
1574 // initialization state of `a.b` is all we need to inspect to
1575 // know if `a.b.c` is valid (and from that we infer that the
1576 // dereference and `.d` access is also valid, since we assume
1577 // `a.b.c` is assigned a reference to a initialized and
1578 // well-formed record structure.)
1580 // Therefore, if we seek out the *closest* prefix for which we
1581 // have a MovePath, that should capture the initialization
1582 // state for the place scenario.
1584 // This code covers scenarios 1, 2, and 3.
1586 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1587 match self.move_path_closest_to(place_span.0) {
1588 Ok((prefix, mpi)) => {
1589 if maybe_uninits.contains(mpi) {
1590 self.report_use_of_moved_or_uninitialized(
1593 (prefix, place_span.0, place_span.1),
1596 return; // don't bother finding other problems.
1599 Err(NoMovePathFound::ReachedStatic) => {
1600 // Okay: we do not build MoveData for static variables
1601 } // Only query longest prefix with a MovePath, not further
1602 // ancestors; dataflow recurs on children when parents
1603 // move (to support partial (re)inits).
1605 // (I.e., querying parents breaks scenario 7; but may want
1606 // to do such a query based on partial-init feature-gate.)
1610 fn check_if_path_or_subpath_is_moved(
1613 desired_action: InitializationRequiringAction,
1614 place_span: (PlaceRef<'cx, 'tcx>, Span),
1615 flow_state: &Flows<'cx, 'tcx>,
1617 let maybe_uninits = &flow_state.uninits;
1621 // 1. Move of `a.b.c`, use of `a` or `a.b`
1622 // partial initialization support, one might have `a.x`
1623 // initialized but not `a.b`.
1624 // 2. All bad scenarios from `check_if_full_path_is_moved`
1628 // 3. Move of `a.b.c`, use of `a.b.d`
1629 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1630 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1631 // must have been initialized for the use to be sound.
1632 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1634 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1636 // A move of any shallow suffix of `place` also interferes
1637 // with an attempt to use `place`. This is scenario 3 above.
1639 // (Distinct from handling of scenarios 1+2+4 above because
1640 // `place` does not interfere with suffixes of its prefixes,
1641 // e.g., `a.b.c` does not interfere with `a.b.d`)
1643 // This code covers scenario 1.
1645 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1646 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1647 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1648 self.report_use_of_moved_or_uninitialized(
1651 (place_span.0, place_span.0, place_span.1),
1654 return; // don't bother finding other problems.
1659 /// Currently MoveData does not store entries for all places in
1660 /// the input MIR. For example it will currently filter out
1661 /// places that are Copy; thus we do not track places of shared
1662 /// reference type. This routine will walk up a place along its
1663 /// prefixes, searching for a foundational place that *is*
1664 /// tracked in the MoveData.
1666 /// An Err result includes a tag indicated why the search failed.
1667 /// Currently this can only occur if the place is built off of a
1668 /// static variable, as we do not track those in the MoveData.
1669 fn move_path_closest_to(
1671 place: PlaceRef<'cx, 'tcx>,
1672 ) -> Result<(PlaceRef<'cx, 'tcx>, MovePathIndex), NoMovePathFound> {
1673 let mut last_prefix = place.base;
1675 for prefix in self.prefixes(place, PrefixSet::All) {
1676 if let Some(mpi) = self.move_path_for_place(prefix) {
1677 return Ok((prefix, mpi));
1680 last_prefix = prefix.base;
1684 PlaceBase::Local(_) => panic!("should have move path for every Local"),
1685 PlaceBase::Static(_) => Err(NoMovePathFound::ReachedStatic),
1689 fn move_path_for_place(&mut self, place: PlaceRef<'cx, 'tcx>) -> Option<MovePathIndex> {
1690 // If returns None, then there is no move path corresponding
1691 // to a direct owner of `place` (which means there is nothing
1692 // that borrowck tracks for its analysis).
1694 match self.move_data.rev_lookup.find(place) {
1695 LookupResult::Parent(_) => None,
1696 LookupResult::Exact(mpi) => Some(mpi),
1700 fn check_if_assigned_path_is_moved(
1703 (place, span): (&'cx Place<'tcx>, Span),
1704 flow_state: &Flows<'cx, 'tcx>,
1706 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1708 // None case => assigning to `x` does not require `x` be initialized.
1709 let mut cursor = &*place.projection.as_ref();
1710 while let [proj_base @ .., elem] = cursor {
1714 ProjectionElem::Index(_/*operand*/) |
1715 ProjectionElem::ConstantIndex { .. } |
1716 // assigning to P[i] requires P to be valid.
1717 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1718 // assigning to (P->variant) is okay if assigning to `P` is okay
1720 // FIXME: is this true even if P is a adt with a dtor?
1723 // assigning to (*P) requires P to be initialized
1724 ProjectionElem::Deref => {
1725 self.check_if_full_path_is_moved(
1726 location, InitializationRequiringAction::Use,
1729 projection: proj_base,
1730 }, span), flow_state);
1731 // (base initialized; no need to
1736 ProjectionElem::Subslice { .. } => {
1737 panic!("we don't allow assignments to subslices, location: {:?}",
1741 ProjectionElem::Field(..) => {
1742 // if type of `P` has a dtor, then
1743 // assigning to `P.f` requires `P` itself
1744 // be already initialized
1745 let tcx = self.infcx.tcx;
1746 let base_ty = Place::ty_from(&place.base, proj_base, self.body, tcx).ty;
1747 match base_ty.kind {
1748 ty::Adt(def, _) if def.has_dtor(tcx) => {
1749 self.check_if_path_or_subpath_is_moved(
1750 location, InitializationRequiringAction::Assignment,
1753 projection: proj_base,
1754 }, span), flow_state);
1756 // (base initialized; no need to
1761 // Once `let s; s.x = V; read(s.x);`,
1762 // is allowed, remove this match arm.
1763 ty::Adt(..) | ty::Tuple(..) => {
1764 check_parent_of_field(self, location, PlaceRef {
1766 projection: proj_base,
1767 }, span, flow_state);
1769 if let PlaceBase::Local(local) = place.base {
1770 // rust-lang/rust#21232,
1771 // #54499, #54986: during
1772 // period where we reject
1773 // partial initialization, do
1774 // not complain about
1775 // unnecessary `mut` on an
1776 // attempt to do a partial
1778 self.used_mut.insert(local);
1788 fn check_parent_of_field<'cx, 'tcx>(
1789 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1791 base: PlaceRef<'cx, 'tcx>,
1793 flow_state: &Flows<'cx, 'tcx>,
1795 // rust-lang/rust#21232: Until Rust allows reads from the
1796 // initialized parts of partially initialized structs, we
1797 // will, starting with the 2018 edition, reject attempts
1798 // to write to structs that are not fully initialized.
1800 // In other words, *until* we allow this:
1802 // 1. `let mut s; s.x = Val; read(s.x);`
1804 // we will for now disallow this:
1806 // 2. `let mut s; s.x = Val;`
1810 // 3. `let mut s = ...; drop(s); s.x=Val;`
1812 // This does not use check_if_path_or_subpath_is_moved,
1813 // because we want to *allow* reinitializations of fields:
1814 // e.g., want to allow
1816 // `let mut s = ...; drop(s.x); s.x=Val;`
1818 // This does not use check_if_full_path_is_moved on
1819 // `base`, because that would report an error about the
1820 // `base` as a whole, but in this scenario we *really*
1821 // want to report an error about the actual thing that was
1822 // moved, which may be some prefix of `base`.
1824 // Shallow so that we'll stop at any dereference; we'll
1825 // report errors about issues with such bases elsewhere.
1826 let maybe_uninits = &flow_state.uninits;
1828 // Find the shortest uninitialized prefix you can reach
1829 // without going over a Deref.
1830 let mut shortest_uninit_seen = None;
1831 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1832 let mpi = match this.move_path_for_place(prefix) {
1833 Some(mpi) => mpi, None => continue,
1836 if maybe_uninits.contains(mpi) {
1837 debug!("check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1838 shortest_uninit_seen, Some((prefix, mpi)));
1839 shortest_uninit_seen = Some((prefix, mpi));
1841 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1845 if let Some((prefix, mpi)) = shortest_uninit_seen {
1846 // Check for a reassignment into a uninitialized field of a union (for example,
1847 // after a move out). In this case, do not report a error here. There is an
1848 // exception, if this is the first assignment into the union (that is, there is
1849 // no move out from an earlier location) then this is an attempt at initialization
1850 // of the union - we should error in that case.
1851 let tcx = this.infcx.tcx;
1852 if let ty::Adt(def, _) =
1853 Place::ty_from(base.base, base.projection, this.body, tcx).ty.kind
1856 if this.move_data.path_map[mpi].iter().any(|moi| {
1857 this.move_data.moves[*moi].source.is_predecessor_of(
1858 location, this.body,
1866 this.report_use_of_moved_or_uninitialized(
1868 InitializationRequiringAction::PartialAssignment,
1869 (prefix, base, span),
1876 /// Checks the permissions for the given place and read or write kind
1878 /// Returns `true` if an error is reported.
1879 fn check_access_permissions(
1881 (place, span): (&Place<'tcx>, Span),
1883 is_local_mutation_allowed: LocalMutationIsAllowed,
1884 flow_state: &Flows<'cx, 'tcx>,
1888 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1889 place, kind, is_local_mutation_allowed
1896 Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1897 | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
1898 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1899 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. })) => {
1900 let is_local_mutation_allowed = match borrow_kind {
1901 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1902 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1903 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1905 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1907 self.add_used_mut(root_place, flow_state);
1911 error_access = AccessKind::MutableBorrow;
1912 the_place_err = place_err;
1916 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1917 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1919 self.add_used_mut(root_place, flow_state);
1923 error_access = AccessKind::Mutate;
1924 the_place_err = place_err;
1929 Reservation(WriteKind::Move)
1930 | Write(WriteKind::Move)
1931 | Reservation(WriteKind::StorageDeadOrDrop)
1932 | Reservation(WriteKind::MutableBorrow(BorrowKind::Shared))
1933 | Reservation(WriteKind::MutableBorrow(BorrowKind::Shallow))
1934 | Write(WriteKind::StorageDeadOrDrop)
1935 | Write(WriteKind::MutableBorrow(BorrowKind::Shared))
1936 | Write(WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
1937 if let (Err(_), true) = (
1938 self.is_mutable(place.as_ref(), is_local_mutation_allowed),
1939 self.errors_buffer.is_empty()
1941 // rust-lang/rust#46908: In pure NLL mode this code path should be
1942 // unreachable, but we use `delay_span_bug` because we can hit this when
1943 // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
1944 // enabled. We don't want to ICE for that case, as other errors will have
1945 // been emitted (#52262).
1946 self.infcx.tcx.sess.delay_span_bug(span, &format!(
1947 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
1955 // permission checks are done at Reservation point.
1958 Read(ReadKind::Borrow(BorrowKind::Unique))
1959 | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
1960 | Read(ReadKind::Borrow(BorrowKind::Shared))
1961 | Read(ReadKind::Borrow(BorrowKind::Shallow))
1962 | Read(ReadKind::Copy) => {
1963 // Access authorized
1968 // rust-lang/rust#21232, #54986: during period where we reject
1969 // partial initialization, do not complain about mutability
1970 // errors except for actual mutation (as opposed to an attempt
1971 // to do a partial initialization).
1972 let previously_initialized = if let PlaceBase::Local(local) = place.base {
1973 self.is_local_ever_initialized(local, flow_state).is_some()
1978 // at this point, we have set up the error reporting state.
1979 if previously_initialized {
1980 self.report_mutability_error(
1993 fn is_local_ever_initialized(
1996 flow_state: &Flows<'cx, 'tcx>,
1997 ) -> Option<InitIndex> {
1998 let mpi = self.move_data.rev_lookup.find_local(local);
1999 let ii = &self.move_data.init_path_map[mpi];
2001 if flow_state.ever_inits.contains(index) {
2008 /// Adds the place into the used mutable variables set
2009 fn add_used_mut<'d>(&mut self, root_place: RootPlace<'d, 'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2012 place_base: PlaceBase::Local(local),
2013 place_projection: [],
2014 is_local_mutation_allowed,
2016 // If the local may have been initialized, and it is now currently being
2017 // mutated, then it is justified to be annotated with the `mut`
2018 // keyword, since the mutation may be a possible reassignment.
2019 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes &&
2020 self.is_local_ever_initialized(*local, flow_state).is_some()
2022 self.used_mut.insert(*local);
2027 place_projection: _,
2028 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2032 place_projection: place_projection @ [.., _],
2033 is_local_mutation_allowed: _,
2035 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2037 projection: &place_projection,
2039 self.used_mut_upvars.push(field);
2043 place_base: PlaceBase::Static(..),
2044 place_projection: [],
2045 is_local_mutation_allowed: _,
2050 /// Whether this value can be written or borrowed mutably.
2051 /// Returns the root place if the place passed in is a projection.
2054 place: PlaceRef<'d, 'tcx>,
2055 is_local_mutation_allowed: LocalMutationIsAllowed,
2056 ) -> Result<RootPlace<'d, 'tcx>, PlaceRef<'d, 'tcx>> {
2059 base: PlaceBase::Local(local),
2062 let local = &self.body.local_decls[*local];
2063 match local.mutability {
2064 Mutability::Not => match is_local_mutation_allowed {
2065 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2066 place_base: place.base,
2067 place_projection: place.projection,
2068 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2070 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2071 place_base: place.base,
2072 place_projection: place.projection,
2073 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2075 LocalMutationIsAllowed::No => Err(place),
2077 Mutability::Mut => Ok(RootPlace {
2078 place_base: place.base,
2079 place_projection: place.projection,
2080 is_local_mutation_allowed,
2084 // The rules for promotion are made by `qualify_consts`, there wouldn't even be a
2085 // `Place::Promoted` if the promotion weren't 100% legal. So we just forward this
2087 base: PlaceBase::Static(box Static {
2088 kind: StaticKind::Promoted(..),
2094 place_base: place.base,
2095 place_projection: place.projection,
2096 is_local_mutation_allowed,
2099 base: PlaceBase::Static(box Static {
2100 kind: StaticKind::Static,
2106 if !self.infcx.tcx.is_mutable_static(*def_id) {
2110 place_base: place.base,
2111 place_projection: place.projection,
2112 is_local_mutation_allowed,
2118 projection: [proj_base @ .., elem],
2121 ProjectionElem::Deref => {
2123 Place::ty_from(place.base, proj_base, self.body, self.infcx.tcx).ty;
2125 // Check the kind of deref to decide
2126 match base_ty.kind {
2127 ty::Ref(_, _, mutbl) => {
2129 // Shared borrowed data is never mutable
2130 hir::Mutability::Immutable => Err(place),
2131 // Mutably borrowed data is mutable, but only if we have a
2132 // unique path to the `&mut`
2133 hir::Mutability::Mutable => {
2134 let mode = match self.is_upvar_field_projection(place) {
2136 if self.upvars[field.index()].by_ref =>
2138 is_local_mutation_allowed
2140 _ => LocalMutationIsAllowed::Yes,
2143 self.is_mutable(PlaceRef {
2145 projection: proj_base,
2150 ty::RawPtr(tnm) => {
2152 // `*const` raw pointers are not mutable
2153 hir::Mutability::Immutable => Err(place),
2154 // `*mut` raw pointers are always mutable, regardless of
2155 // context. The users have to check by themselves.
2156 hir::Mutability::Mutable => {
2158 place_base: place.base,
2159 place_projection: place.projection,
2160 is_local_mutation_allowed,
2165 // `Box<T>` owns its content, so mutable if its location is mutable
2166 _ if base_ty.is_box() => {
2167 self.is_mutable(PlaceRef {
2169 projection: proj_base,
2170 }, is_local_mutation_allowed)
2172 // Deref should only be for reference, pointers or boxes
2173 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2176 // All other projections are owned by their base path, so mutable if
2177 // base path is mutable
2178 ProjectionElem::Field(..)
2179 | ProjectionElem::Index(..)
2180 | ProjectionElem::ConstantIndex { .. }
2181 | ProjectionElem::Subslice { .. }
2182 | ProjectionElem::Downcast(..) => {
2183 let upvar_field_projection = self.is_upvar_field_projection(place);
2184 if let Some(field) = upvar_field_projection {
2185 let upvar = &self.upvars[field.index()];
2187 "upvar.mutability={:?} local_mutation_is_allowed={:?} \
2189 upvar, is_local_mutation_allowed, place
2191 match (upvar.mutability, is_local_mutation_allowed) {
2192 (Mutability::Not, LocalMutationIsAllowed::No)
2193 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2196 (Mutability::Not, LocalMutationIsAllowed::Yes)
2197 | (Mutability::Mut, _) => {
2198 // Subtle: this is an upvar
2199 // reference, so it looks like
2200 // `self.foo` -- we want to double
2201 // check that the location `*self`
2202 // is mutable (i.e., this is not a
2203 // `Fn` closure). But if that
2204 // check succeeds, we want to
2205 // *blame* the mutability on
2206 // `place` (that is,
2207 // `self.foo`). This is used to
2208 // propagate the info about
2209 // whether mutability declarations
2210 // are used outwards, so that we register
2211 // the outer variable as mutable. Otherwise a
2212 // test like this fails to record the `mut`
2216 // fn foo<F: FnOnce()>(_f: F) { }
2218 // let var = Vec::new();
2224 let _ = self.is_mutable(PlaceRef {
2226 projection: proj_base,
2227 }, is_local_mutation_allowed)?;
2229 place_base: place.base,
2230 place_projection: place.projection,
2231 is_local_mutation_allowed,
2236 self.is_mutable(PlaceRef {
2238 projection: proj_base,
2239 }, is_local_mutation_allowed)
2247 /// If `place` is a field projection, and the field is being projected from a closure type,
2248 /// then returns the index of the field being projected. Note that this closure will always
2249 /// be `self` in the current MIR, because that is the only time we directly access the fields
2250 /// of a closure type.
2251 pub fn is_upvar_field_projection(&self, place_ref: PlaceRef<'cx, 'tcx>) -> Option<Field> {
2252 let mut place_projection = place_ref.projection;
2253 let mut by_ref = false;
2255 if let [proj_base @ .., ProjectionElem::Deref] = place_projection {
2256 place_projection = proj_base;
2260 match place_projection {
2261 [base @ .., ProjectionElem::Field(field, _ty)] => {
2262 let tcx = self.infcx.tcx;
2263 let base_ty = Place::ty_from(place_ref.base, base, self.body, tcx).ty;
2265 if (base_ty.is_closure() || base_ty.is_generator()) &&
2266 (!by_ref || self.upvars[field.index()].by_ref) {
2278 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2279 enum NoMovePathFound {
2283 /// The degree of overlap between 2 places for borrow-checking.
2285 /// The places might partially overlap - in this case, we give
2286 /// up and say that they might conflict. This occurs when
2287 /// different fields of a union are borrowed. For example,
2288 /// if `u` is a union, we have no way of telling how disjoint
2289 /// `u.a.x` and `a.b.y` are.
2291 /// The places have the same type, and are either completely disjoint
2292 /// or equal - i.e., they can't "partially" overlap as can occur with
2293 /// unions. This is the "base case" on which we recur for extensions
2296 /// The places are disjoint, so we know all extensions of them
2297 /// will also be disjoint.