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::middle::borrowck::SignalledError;
11 use rustc::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
13 ClearCrossCrate, Local, Location, Mir, Mutability, Operand, Place, PlaceBase, Static, StaticKind
15 use rustc::mir::{Field, Projection, ProjectionElem, 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, Level};
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 smallvec::SmallVec;
26 use std::collections::BTreeMap;
30 use syntax::ast::Name;
31 use syntax_pos::{Span, DUMMY_SP};
33 use crate::dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex};
34 use crate::dataflow::move_paths::{HasMoveData, InitLocation, LookupResult, MoveData, MoveError};
35 use crate::dataflow::Borrows;
36 use crate::dataflow::DataflowResultsConsumer;
37 use crate::dataflow::FlowAtLocation;
38 use crate::dataflow::MoveDataParamEnv;
39 use crate::dataflow::{do_dataflow, DebugFormatted};
40 use crate::dataflow::EverInitializedPlaces;
41 use crate::dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
42 use crate::util::borrowck_errors::{BorrowckErrors, Origin};
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::*;
58 mod mutability_errors;
61 crate mod places_conflict;
67 // FIXME(eddyb) perhaps move this somewhere more centrally.
74 /// If true, the capture is behind a reference.
77 mutability: Mutability,
80 pub fn provide(providers: &mut Providers<'_>) {
81 *providers = Providers {
87 fn mir_borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> BorrowCheckResult<'tcx> {
88 let input_mir = tcx.mir_validated(def_id);
89 debug!("run query mir_borrowck: {}", tcx.def_path_str(def_id));
91 // We are not borrow checking the automatically generated struct/variant constructors
92 // because we want to accept structs such as this (taken from the `linked-hash-map`
95 // struct Qey<Q: ?Sized>(Q);
97 // MIR of this struct constructor looks something like this:
99 // fn Qey(_1: Q) -> Qey<Q>{
100 // let mut _0: Qey<Q>; // return place
103 // (_0.0: Q) = move _1; // bb0[0]: scope 0 at src/main.rs:1:1: 1:26
104 // return; // bb0[1]: scope 0 at src/main.rs:1:1: 1:26
108 // The problem here is that `(_0.0: Q) = move _1;` is valid only if `Q` is
109 // of statically known size, which is not known to be true because of the
110 // `Q: ?Sized` constraint. However, it is true because the constructor can be
111 // called only when `Q` is of statically known size.
112 if tcx.is_constructor(def_id) {
113 return BorrowCheckResult {
114 closure_requirements: None,
115 used_mut_upvars: SmallVec::new(),
119 let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
120 let input_mir: &Mir<'_> = &input_mir.borrow();
121 do_mir_borrowck(&infcx, input_mir, def_id)
123 debug!("mir_borrowck done");
128 fn do_mir_borrowck<'a, 'gcx, 'tcx>(
129 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
130 input_mir: &Mir<'gcx>,
132 ) -> BorrowCheckResult<'gcx> {
133 debug!("do_mir_borrowck(def_id = {:?})", def_id);
136 let attributes = tcx.get_attrs(def_id);
137 let param_env = tcx.param_env(def_id);
140 .as_local_hir_id(def_id)
141 .expect("do_mir_borrowck: non-local DefId");
143 // Gather the upvars of a closure, if any.
144 let tables = tcx.typeck_tables_of(def_id);
145 let upvars: Vec<_> = tables
151 let var_hir_id = upvar_id.var_path.hir_id;
152 let var_node_id = tcx.hir().hir_to_node_id(var_hir_id);
153 let capture = tables.upvar_capture(*upvar_id);
154 let by_ref = match capture {
155 ty::UpvarCapture::ByValue => false,
156 ty::UpvarCapture::ByRef(..) => true,
158 let mut upvar = Upvar {
159 name: tcx.hir().name(var_node_id),
162 mutability: Mutability::Not,
164 let bm = *tables.pat_binding_modes().get(var_hir_id)
165 .expect("missing binding mode");
166 if bm == ty::BindByValue(hir::MutMutable) {
167 upvar.mutability = Mutability::Mut;
173 // Replace all regions with fresh inference variables. This
174 // requires first making our own copy of the MIR. This copy will
175 // be modified (in place) to contain non-lexical lifetimes. It
176 // will have a lifetime tied to the inference context.
177 let mut mir: Mir<'tcx> = input_mir.clone();
178 let free_regions = nll::replace_regions_in_mir(infcx, def_id, param_env, &mut mir);
179 let mir = &mir; // no further changes
180 let location_table = &LocationTable::new(mir);
182 let mut errors_buffer = Vec::new();
183 let (move_data, move_errors): (MoveData<'tcx>, Option<Vec<(Place<'tcx>, MoveError<'tcx>)>>) =
184 match MoveData::gather_moves(mir, tcx) {
185 Ok(move_data) => (move_data, None),
186 Err((move_data, move_errors)) => (move_data, Some(move_errors)),
189 let mdpe = MoveDataParamEnv {
190 move_data: move_data,
191 param_env: param_env,
194 let dead_unwinds = BitSet::new_empty(mir.basic_blocks().len());
195 let mut flow_inits = FlowAtLocation::new(do_dataflow(
201 MaybeInitializedPlaces::new(tcx, mir, &mdpe),
202 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
205 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind_by_hir_id(id).is_fn_or_closure();
206 let borrow_set = Rc::new(BorrowSet::build(
207 tcx, mir, locals_are_invalidated_at_exit, &mdpe.move_data));
209 // If we are in non-lexical mode, compute the non-lexical lifetimes.
210 let (regioncx, polonius_output, opt_closure_req) = nll::compute_regions(
224 // The various `flow_*` structures can be large. We drop `flow_inits` here
225 // so it doesn't overlap with the others below. This reduces peak memory
226 // usage significantly on some benchmarks.
229 let regioncx = Rc::new(regioncx);
231 let flow_borrows = FlowAtLocation::new(do_dataflow(
237 Borrows::new(tcx, mir, regioncx.clone(), &borrow_set),
238 |rs, i| DebugFormatted::new(&rs.location(i)),
240 let flow_uninits = FlowAtLocation::new(do_dataflow(
246 MaybeUninitializedPlaces::new(tcx, mir, &mdpe),
247 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
249 let flow_ever_inits = FlowAtLocation::new(do_dataflow(
255 EverInitializedPlaces::new(tcx, mir, &mdpe),
256 |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
259 let movable_generator = match tcx.hir().get_by_hir_id(id) {
260 Node::Expr(&hir::Expr {
261 node: hir::ExprKind::Closure(.., Some(hir::GeneratorMovability::Static)),
267 let dominators = mir.dominators();
269 let mut mbcx = MirBorrowckCtxt {
273 move_data: &mdpe.move_data,
276 locals_are_invalidated_at_exit,
277 access_place_error_reported: Default::default(),
278 reservation_error_reported: Default::default(),
279 reservation_warnings: Default::default(),
280 move_error_reported: BTreeMap::new(),
281 uninitialized_error_reported: Default::default(),
283 nonlexical_regioncx: regioncx,
284 used_mut: Default::default(),
285 used_mut_upvars: SmallVec::new(),
291 let mut state = Flows::new(
298 if let Some(errors) = move_errors {
299 mbcx.report_move_errors(errors);
301 mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
303 // Convert any reservation warnings into lints.
304 let reservation_warnings = mem::replace(&mut mbcx.reservation_warnings, Default::default());
305 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
306 let mut initial_diag =
307 mbcx.report_conflicting_borrow(location, (&place, span), bk, &borrow);
309 let lint_root = if let ClearCrossCrate::Set(ref vsi) = mbcx.mir.source_scope_local_data {
310 let scope = mbcx.mir.source_info(location).scope;
316 // Span and message don't matter; we overwrite them below anyway
317 let mut diag = mbcx.infcx.tcx.struct_span_lint_hir(
318 MUTABLE_BORROW_RESERVATION_CONFLICT, lint_root, DUMMY_SP, "");
320 diag.message = initial_diag.styled_message().clone();
321 diag.span = initial_diag.span.clone();
323 initial_diag.cancel();
324 diag.buffer(&mut mbcx.errors_buffer);
327 // For each non-user used mutable variable, check if it's been assigned from
328 // a user-declared local. If so, then put that local into the used_mut set.
329 // Note that this set is expected to be small - only upvars from closures
330 // would have a chance of erroneously adding non-user-defined mutable vars
332 let temporary_used_locals: FxHashSet<Local> = mbcx.used_mut.iter()
333 .filter(|&local| mbcx.mir.local_decls[*local].is_user_variable.is_none())
336 // For the remaining unused locals that are marked as mutable, we avoid linting any that
337 // were never initialized. These locals may have been removed as unreachable code; or will be
338 // linted as unused variables.
339 let unused_mut_locals = mbcx.mir.mut_vars_iter()
340 .filter(|local| !mbcx.used_mut.contains(local))
342 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
344 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
345 let used_mut = mbcx.used_mut;
346 for local in mbcx.mir.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
347 if let ClearCrossCrate::Set(ref vsi) = mbcx.mir.source_scope_local_data {
348 let local_decl = &mbcx.mir.local_decls[local];
350 // Skip implicit `self` argument for closures
351 if local.index() == 1 && tcx.is_closure(mbcx.mir_def_id) {
355 // Skip over locals that begin with an underscore or have no name
356 match local_decl.name {
357 Some(name) => if name.as_str().starts_with("_") {
363 let span = local_decl.source_info.span;
364 if span.compiler_desugaring_kind().is_some() {
365 // If the `mut` arises as part of a desugaring, we should ignore it.
369 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
370 tcx.struct_span_lint_hir(
372 vsi[local_decl.source_info.scope].lint_root,
374 "variable does not need to be mutable",
376 .span_suggestion_short(
380 Applicability::MachineApplicable,
386 // Buffer any move errors that we collected and de-duplicated.
387 for (_, (_, diag)) in mbcx.move_error_reported {
388 diag.buffer(&mut mbcx.errors_buffer);
391 if !mbcx.errors_buffer.is_empty() {
392 mbcx.errors_buffer.sort_by_key(|diag| diag.span.primary_span());
394 if tcx.migrate_borrowck() {
395 // When borrowck=migrate, check if AST-borrowck would
396 // error on the given code.
398 // rust-lang/rust#55492, rust-lang/rust#58776 check the base def id
399 // for errors. AST borrowck is responsible for aggregating
400 // `signalled_any_error` from all of the nested closures here.
401 let base_def_id = tcx.closure_base_def_id(def_id);
403 match tcx.borrowck(base_def_id).signalled_any_error {
404 SignalledError::NoErrorsSeen => {
405 // if AST-borrowck signalled no errors, then
406 // downgrade all the buffered MIR-borrowck errors
409 for err in mbcx.errors_buffer.iter_mut() {
410 downgrade_if_error(err);
413 SignalledError::SawSomeError => {
414 // if AST-borrowck signalled a (cancelled) error,
415 // then we will just emit the buffered
416 // MIR-borrowck errors as normal.
421 for diag in mbcx.errors_buffer.drain(..) {
422 DiagnosticBuilder::new_diagnostic(mbcx.infcx.tcx.sess.diagnostic(), diag).emit();
426 let result = BorrowCheckResult {
427 closure_requirements: opt_closure_req,
428 used_mut_upvars: mbcx.used_mut_upvars,
431 debug!("do_mir_borrowck: result = {:#?}", result);
436 fn downgrade_if_error(diag: &mut Diagnostic) {
438 diag.level = Level::Warning;
440 "this error has been downgraded to a warning for backwards \
441 compatibility with previous releases",
443 "this represents potential undefined behavior in your code and \
444 this warning will become a hard error in the future",
446 "for more information, try `rustc --explain E0729`"
451 pub struct MirBorrowckCtxt<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
452 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
455 move_data: &'cx MoveData<'tcx>,
457 /// Map from MIR `Location` to `LocationIndex`; created
458 /// when MIR borrowck begins.
459 location_table: &'cx LocationTable,
461 movable_generator: bool,
462 /// This keeps track of whether local variables are free-ed when the function
463 /// exits even without a `StorageDead`, which appears to be the case for
466 /// I'm not sure this is the right approach - @eddyb could you try and
468 locals_are_invalidated_at_exit: bool,
469 /// This field keeps track of when borrow errors are reported in the access_place function
470 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
471 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
472 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
474 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
475 /// This field keeps track of when borrow conflict errors are reported
476 /// for reservations, so that we don't report seemingly duplicate
477 /// errors for corresponding activations.
479 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
480 // but it is currently inconvenient to track down the `BorrowIndex`
481 // at the time we detect and report a reservation error.
482 reservation_error_reported: FxHashSet<Place<'tcx>>,
483 /// Migration warnings to be reported for #56254. We delay reporting these
484 /// so that we can suppress the warning if there's a corresponding error
485 /// for the activation of the borrow.
486 reservation_warnings: FxHashMap<
488 (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)
490 /// This field keeps track of move errors that are to be reported for given move indicies.
492 /// There are situations where many errors can be reported for a single move out (see #53807)
493 /// and we want only the best of those errors.
495 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
496 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
497 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
498 /// all move errors have been reported, any diagnostics in this map are added to the buffer
501 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
502 /// when errors in the map are being re-added to the error buffer so that errors with the
503 /// same primary span come out in a consistent order.
504 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (Place<'tcx>, DiagnosticBuilder<'cx>)>,
505 /// This field keeps track of errors reported in the checking of uninitialized variables,
506 /// so that we don't report seemingly duplicate errors.
507 uninitialized_error_reported: FxHashSet<Place<'tcx>>,
508 /// Errors to be reported buffer
509 errors_buffer: Vec<Diagnostic>,
510 /// This field keeps track of all the local variables that are declared mut and are mutated.
511 /// Used for the warning issued by an unused mutable local variable.
512 used_mut: FxHashSet<Local>,
513 /// If the function we're checking is a closure, then we'll need to report back the list of
514 /// mutable upvars that have been used. This field keeps track of them.
515 used_mut_upvars: SmallVec<[Field; 8]>,
516 /// Non-lexical region inference context, if NLL is enabled. This
517 /// contains the results from region inference and lets us e.g.
518 /// find out which CFG points are contained in each borrow region.
519 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
521 /// The set of borrows extracted from the MIR
522 borrow_set: Rc<BorrowSet<'tcx>>,
524 /// Dominators for MIR
525 dominators: Dominators<BasicBlock>,
527 /// Information about upvars not necessarily preserved in types or MIR
532 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
533 // 2. loans made in overlapping scopes do not conflict
534 // 3. assignments do not affect things loaned out as immutable
535 // 4. moves do not affect things loaned out in any way
536 impl<'cx, 'gcx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
537 type FlowState = Flows<'cx, 'gcx, 'tcx>;
539 fn mir(&self) -> &'cx Mir<'tcx> {
543 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
544 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
547 fn visit_statement_entry(
550 stmt: &Statement<'tcx>,
551 flow_state: &Self::FlowState,
554 "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
555 location, stmt, flow_state
557 let span = stmt.source_info.span;
559 self.check_activations(location, span, flow_state);
562 StatementKind::Assign(ref lhs, ref rhs) => {
577 StatementKind::FakeRead(_, ref place) => {
578 // Read for match doesn't access any memory and is used to
579 // assert that a place is safe and live. So we don't have to
580 // do any checks here.
582 // FIXME: Remove check that the place is initialized. This is
583 // needed for now because matches don't have never patterns yet.
584 // So this is the only place we prevent
588 self.check_if_path_or_subpath_is_moved(
590 InitializationRequiringAction::Use,
595 StatementKind::SetDiscriminant {
607 StatementKind::InlineAsm(ref asm) => {
608 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
610 // FIXME(eddyb) indirect inline asm outputs should
611 // be encoded through MIR place derefs instead.
615 (Deep, Read(ReadKind::Copy)),
616 LocalMutationIsAllowed::No,
619 self.check_if_path_or_subpath_is_moved(
621 InitializationRequiringAction::Use,
629 if o.is_rw { Deep } else { Shallow(None) },
630 if o.is_rw { WriteAndRead } else { JustWrite },
635 for (_, input) in asm.inputs.iter() {
636 self.consume_operand(location, (input, span), flow_state);
640 | StatementKind::AscribeUserType(..)
641 | StatementKind::Retag { .. }
642 | StatementKind::StorageLive(..) => {
643 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
646 StatementKind::StorageDead(local) => {
649 (&Place::Base(PlaceBase::Local(local)), span),
650 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
651 LocalMutationIsAllowed::Yes,
658 fn visit_terminator_entry(
661 term: &Terminator<'tcx>,
662 flow_state: &Self::FlowState,
666 "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
667 location, term, flow_state
669 let span = term.source_info.span;
671 self.check_activations(location, span, flow_state);
674 TerminatorKind::SwitchInt {
680 self.consume_operand(loc, (discr, span), flow_state);
682 TerminatorKind::Drop {
683 location: ref drop_place,
687 let gcx = self.infcx.tcx.global_tcx();
689 // Compute the type with accurate region information.
690 let drop_place_ty = drop_place.ty(self.mir, self.infcx.tcx);
692 // Erase the regions.
693 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
695 // "Lift" into the gcx -- once regions are erased, this type should be in the
696 // global arenas; this "lift" operation basically just asserts that is true, but
697 // that is useful later.
698 let drop_place_ty = gcx.lift(&drop_place_ty).unwrap();
700 debug!("visit_terminator_drop \
701 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
702 loc, term, drop_place, drop_place_ty, span);
707 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
708 LocalMutationIsAllowed::Yes,
712 TerminatorKind::DropAndReplace {
713 location: ref drop_place,
714 value: ref new_value,
725 self.consume_operand(
731 TerminatorKind::Call {
738 self.consume_operand(loc, (func, span), flow_state);
740 self.consume_operand(
746 if let Some((ref dest, _ /*bb*/)) = *destination {
756 TerminatorKind::Assert {
763 self.consume_operand(loc, (cond, span), flow_state);
764 use rustc::mir::interpret::InterpError::BoundsCheck;
765 if let BoundsCheck { ref len, ref index } = *msg {
766 self.consume_operand(loc, (len, span), flow_state);
767 self.consume_operand(loc, (index, span), flow_state);
771 TerminatorKind::Yield {
776 self.consume_operand(loc, (value, span), flow_state);
778 if self.movable_generator {
779 // Look for any active borrows to locals
780 let borrow_set = self.borrow_set.clone();
781 flow_state.with_outgoing_borrows(|borrows| {
783 let borrow = &borrow_set[i];
784 self.check_for_local_borrow(borrow, span);
790 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
791 // Returning from the function implicitly kills storage for all locals and statics.
792 // Often, the storage will already have been killed by an explicit
793 // StorageDead, but we don't always emit those (notably on unwind paths),
794 // so this "extra check" serves as a kind of backup.
795 let borrow_set = self.borrow_set.clone();
796 flow_state.with_outgoing_borrows(|borrows| {
798 let borrow = &borrow_set[i];
799 self.check_for_invalidation_at_exit(loc, borrow, span);
803 TerminatorKind::Goto { target: _ }
804 | TerminatorKind::Abort
805 | TerminatorKind::Unreachable
806 | TerminatorKind::FalseEdges {
808 imaginary_targets: _,
810 | TerminatorKind::FalseUnwind {
814 // no data used, thus irrelevant to borrowck
820 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
826 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
827 use self::AccessDepth::{Deep, Shallow};
829 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
830 enum ArtificialField {
835 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
837 /// From the RFC: "A *shallow* access means that the immediate
838 /// fields reached at P are accessed, but references or pointers
839 /// found within are not dereferenced. Right now, the only access
840 /// that is shallow is an assignment like `x = ...;`, which would
841 /// be a *shallow write* of `x`."
842 Shallow(Option<ArtificialField>),
844 /// From the RFC: "A *deep* access means that all data reachable
845 /// through the given place may be invalidated or accesses by
849 /// Access is Deep only when there is a Drop implementation that
850 /// can reach the data behind the reference.
854 /// Kind of access to a value: read or write
855 /// (For informational purposes only)
856 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
858 /// From the RFC: "A *read* means that the existing data may be
859 /// read, but will not be changed."
862 /// From the RFC: "A *write* means that the data may be mutated to
863 /// new values or otherwise invalidated (for example, it could be
864 /// de-initialized, as in a move operation).
867 /// For two-phase borrows, we distinguish a reservation (which is treated
868 /// like a Read) from an activation (which is treated like a write), and
869 /// each of those is furthermore distinguished from Reads/Writes above.
870 Reservation(WriteKind),
871 Activation(WriteKind, BorrowIndex),
874 /// Kind of read access to a value
875 /// (For informational purposes only)
876 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
882 /// Kind of write access to a value
883 /// (For informational purposes only)
884 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
887 MutableBorrow(BorrowKind),
892 /// When checking permissions for a place access, this flag is used to indicate that an immutable
893 /// local place can be mutated.
895 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
896 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
897 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
898 // `is_declared_mutable()`.
899 // - Take flow state into consideration in `is_assignable()` for local variables.
900 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
901 enum LocalMutationIsAllowed {
903 /// We want use of immutable upvars to cause a "write to immutable upvar"
904 /// error, not an "reassignment" error.
909 #[derive(Copy, Clone, Debug)]
910 enum InitializationRequiringAction {
919 struct RootPlace<'d, 'tcx: 'd> {
920 place: &'d Place<'tcx>,
921 is_local_mutation_allowed: LocalMutationIsAllowed,
924 impl InitializationRequiringAction {
925 fn as_noun(self) -> &'static str {
927 InitializationRequiringAction::Update => "update",
928 InitializationRequiringAction::Borrow => "borrow",
929 InitializationRequiringAction::MatchOn => "use", // no good noun
930 InitializationRequiringAction::Use => "use",
931 InitializationRequiringAction::Assignment => "assign",
932 InitializationRequiringAction::PartialAssignment => "assign to part",
936 fn as_verb_in_past_tense(self) -> &'static str {
938 InitializationRequiringAction::Update => "updated",
939 InitializationRequiringAction::Borrow => "borrowed",
940 InitializationRequiringAction::MatchOn => "matched on",
941 InitializationRequiringAction::Use => "used",
942 InitializationRequiringAction::Assignment => "assigned",
943 InitializationRequiringAction::PartialAssignment => "partially assigned",
948 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
949 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
950 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
951 /// place is initialized and (b) it is not borrowed in some way that would prevent this
954 /// Returns `true` if an error is reported.
958 place_span: (&Place<'tcx>, Span),
959 kind: (AccessDepth, ReadOrWrite),
960 is_local_mutation_allowed: LocalMutationIsAllowed,
961 flow_state: &Flows<'cx, 'gcx, 'tcx>,
965 if let Activation(_, borrow_index) = rw {
966 if self.reservation_error_reported.contains(&place_span.0) {
968 "skipping access_place for activation of invalid reservation \
969 place: {:?} borrow_index: {:?}",
970 place_span.0, borrow_index
976 // Check is_empty() first because it's the common case, and doing that
977 // way we avoid the clone() call.
978 if !self.access_place_error_reported.is_empty() &&
980 .access_place_error_reported
981 .contains(&(place_span.0.clone(), place_span.1))
984 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
990 let mutability_error =
991 self.check_access_permissions(
994 is_local_mutation_allowed,
999 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
1001 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
1002 // Suppress this warning when there's an error being emited for the
1003 // same borrow: fixing the error is likely to fix the warning.
1004 self.reservation_warnings.remove(&borrow_idx);
1007 if conflict_error || mutability_error {
1009 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
1013 self.access_place_error_reported
1014 .insert((place_span.0.clone(), place_span.1));
1018 fn check_access_for_conflict(
1021 place_span: (&Place<'tcx>, Span),
1024 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1027 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1028 location, place_span, sd, rw,
1031 let mut error_reported = false;
1032 let tcx = self.infcx.tcx;
1034 let location_table = self.location_table.start_index(location);
1035 let borrow_set = self.borrow_set.clone();
1036 each_borrow_involving_path(
1043 flow_state.borrows_in_scope(location_table),
1044 |this, borrow_index, borrow| match (rw, borrow.kind) {
1045 // Obviously an activation is compatible with its own
1046 // reservation (or even prior activating uses of same
1047 // borrow); so don't check if they interfere.
1049 // NOTE: *reservations* do conflict with themselves;
1050 // thus aren't injecting unsoundenss w/ this check.)
1051 (Activation(_, activating), _) if activating == borrow_index => {
1053 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1054 skipping {:?} b/c activation of same borrow_index",
1058 (borrow_index, borrow),
1063 (Read(_), BorrowKind::Shared)
1064 | (Read(_), BorrowKind::Shallow)
1065 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
1066 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
1070 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1071 // Handled by initialization checks.
1075 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
1076 // Reading from mere reservations of mutable-borrows is OK.
1077 if !is_active(&this.dominators, borrow, location) {
1078 assert!(allow_two_phase_borrow(borrow.kind));
1079 return Control::Continue;
1082 error_reported = true;
1085 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1086 .buffer(&mut this.errors_buffer);
1088 ReadKind::Borrow(bk) => {
1089 this.report_conflicting_borrow(location, place_span, bk, borrow)
1090 .buffer(&mut this.errors_buffer);
1096 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
1097 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared) if {
1098 tcx.migrate_borrowck()
1100 let bi = this.borrow_set.location_map[&location];
1102 "recording invalid reservation of place: {:?} with \
1103 borrow index {:?} as warning",
1107 // rust-lang/rust#56254 - This was previously permitted on
1108 // the 2018 edition so we emit it as a warning. We buffer
1109 // these sepately so that we only emit a warning if borrow
1110 // checking was otherwise successful.
1111 this.reservation_warnings.insert(
1113 (place_span.0.clone(), place_span.1, location, bk, borrow.clone()),
1116 // Don't suppress actual errors.
1120 (Reservation(kind), _)
1121 | (Activation(kind, _), _)
1122 | (Write(kind), _) => {
1124 Reservation(..) => {
1126 "recording invalid reservation of \
1130 this.reservation_error_reported.insert(place_span.0.clone());
1132 Activation(_, activating) => {
1134 "observing check_place for activation of \
1135 borrow_index: {:?}",
1139 Read(..) | Write(..) => {}
1142 error_reported = true;
1144 WriteKind::MutableBorrow(bk) => {
1145 this.report_conflicting_borrow(location, place_span, bk, borrow)
1146 .buffer(&mut this.errors_buffer);
1148 WriteKind::StorageDeadOrDrop => {
1149 this.report_borrowed_value_does_not_live_long_enough(
1155 WriteKind::Mutate => {
1156 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1158 WriteKind::Move => {
1159 this.report_move_out_while_borrowed(location, place_span, borrow)
1173 place_span: (&Place<'tcx>, Span),
1176 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1178 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1180 MutateMode::WriteAndRead => {
1181 self.check_if_path_or_subpath_is_moved(
1183 InitializationRequiringAction::Update,
1188 MutateMode::JustWrite => {
1189 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1193 // Special case: you can assign a immutable local variable
1194 // (e.g., `x = ...`) so long as it has never been initialized
1195 // before (at this point in the flow).
1196 if let &Place::Base(PlaceBase::Local(local)) = place_span.0 {
1197 if let Mutability::Not = self.mir.local_decls[local].mutability {
1198 // check for reassignments to immutable local variables
1199 self.check_if_reassignment_to_immutable_state(
1209 // Otherwise, use the normal access permission rules.
1213 (kind, Write(WriteKind::Mutate)),
1214 LocalMutationIsAllowed::No,
1222 (rvalue, span): (&Rvalue<'tcx>, Span),
1223 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1226 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1227 let access_kind = match bk {
1228 BorrowKind::Shallow => {
1229 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1231 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1232 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1233 let wk = WriteKind::MutableBorrow(bk);
1234 if allow_two_phase_borrow(bk) {
1235 (Deep, Reservation(wk))
1246 LocalMutationIsAllowed::No,
1250 let action = if bk == BorrowKind::Shallow {
1251 InitializationRequiringAction::MatchOn
1253 InitializationRequiringAction::Borrow
1256 self.check_if_path_or_subpath_is_moved(
1264 Rvalue::Use(ref operand)
1265 | Rvalue::Repeat(ref operand, _)
1266 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1267 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1268 self.consume_operand(location, (operand, span), flow_state)
1271 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1272 let af = match *rvalue {
1273 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1274 Rvalue::Discriminant(..) => None,
1275 _ => unreachable!(),
1280 (Shallow(af), Read(ReadKind::Copy)),
1281 LocalMutationIsAllowed::No,
1284 self.check_if_path_or_subpath_is_moved(
1286 InitializationRequiringAction::Use,
1292 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1293 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1294 self.consume_operand(location, (operand1, span), flow_state);
1295 self.consume_operand(location, (operand2, span), flow_state);
1298 Rvalue::NullaryOp(_op, _ty) => {
1299 // nullary ops take no dynamic input; no borrowck effect.
1301 // FIXME: is above actually true? Do we want to track
1302 // the fact that uninitialized data can be created via
1306 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1307 // We need to report back the list of mutable upvars that were
1308 // moved into the closure and subsequently used by the closure,
1309 // in order to populate our used_mut set.
1310 match **aggregate_kind {
1311 AggregateKind::Closure(def_id, _)
1312 | AggregateKind::Generator(def_id, _, _) => {
1313 let BorrowCheckResult {
1315 } = self.infcx.tcx.mir_borrowck(def_id);
1316 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1317 for field in used_mut_upvars {
1318 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1321 AggregateKind::Adt(..)
1322 | AggregateKind::Array(..)
1323 | AggregateKind::Tuple { .. } => (),
1326 for operand in operands {
1327 self.consume_operand(location, (operand, span), flow_state);
1333 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1334 let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1336 Place::Projection { .. } => {
1337 if let Some(field) = this.is_upvar_field_projection(place) {
1338 this.used_mut_upvars.push(field);
1341 Place::Base(PlaceBase::Local(local)) => {
1342 this.used_mut.insert(local);
1344 Place::Base(PlaceBase::Static(_)) => {}
1348 // This relies on the current way that by-value
1349 // captures of a closure are copied/moved directly
1350 // when generating MIR.
1352 Operand::Move(Place::Base(PlaceBase::Local(local)))
1353 | Operand::Copy(Place::Base(PlaceBase::Local(local)))
1354 if self.mir.local_decls[local].is_user_variable.is_none() =>
1356 if self.mir.local_decls[local].ty.is_mutable_pointer() {
1357 // The variable will be marked as mutable by the borrow.
1360 // This is an edge case where we have a `move` closure
1361 // inside a non-move closure, and the inner closure
1362 // contains a mutation:
1365 // || { move || { i += 1; }; };
1367 // In this case our usual strategy of assuming that the
1368 // variable will be captured by mutable reference is
1369 // wrong, since `i` can be copied into the inner
1370 // closure from a shared reference.
1372 // As such we have to search for the local that this
1373 // capture comes from and mark it as being used as mut.
1375 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1376 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1377 &self.move_data.inits[init_index]
1379 bug!("temporary should be initialized exactly once")
1382 let loc = match init.location {
1383 InitLocation::Statement(stmt) => stmt,
1384 _ => bug!("temporary initialized in arguments"),
1387 let bbd = &self.mir[loc.block];
1388 let stmt = &bbd.statements[loc.statement_index];
1389 debug!("temporary assigned in: stmt={:?}", stmt);
1391 if let StatementKind::Assign(_, box Rvalue::Ref(_, _, ref source)) = stmt.kind {
1392 propagate_closure_used_mut_place(self, source);
1394 bug!("closures should only capture user variables \
1395 or references to user variables");
1398 Operand::Move(ref place)
1399 | Operand::Copy(ref place) => {
1400 propagate_closure_used_mut_place(self, place);
1402 Operand::Constant(..) => {}
1409 (operand, span): (&Operand<'tcx>, Span),
1410 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1413 Operand::Copy(ref place) => {
1414 // copy of place: check if this is "copy of frozen path"
1415 // (FIXME: see check_loans.rs)
1419 (Deep, Read(ReadKind::Copy)),
1420 LocalMutationIsAllowed::No,
1424 // Finally, check if path was already moved.
1425 self.check_if_path_or_subpath_is_moved(
1427 InitializationRequiringAction::Use,
1432 Operand::Move(ref place) => {
1433 // move of place: check if this is move of already borrowed path
1437 (Deep, Write(WriteKind::Move)),
1438 LocalMutationIsAllowed::Yes,
1442 // Finally, check if path was already moved.
1443 self.check_if_path_or_subpath_is_moved(
1445 InitializationRequiringAction::Use,
1450 Operand::Constant(_) => {}
1454 /// Checks whether a borrow of this place is invalidated when the function
1456 fn check_for_invalidation_at_exit(
1459 borrow: &BorrowData<'tcx>,
1462 debug!("check_for_invalidation_at_exit({:?})", borrow);
1463 let place = &borrow.borrowed_place;
1464 let root_place = self.prefixes(place, PrefixSet::All).last().unwrap();
1466 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1467 // we just know that all locals are dropped at function exit (otherwise
1468 // we'll have a memory leak) and assume that all statics have a destructor.
1470 // FIXME: allow thread-locals to borrow other thread locals?
1471 let (might_be_alive, will_be_dropped) = match root_place {
1472 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Promoted(_), .. })) => {
1475 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(_), .. })) => {
1476 // Thread-locals might be dropped after the function exits, but
1477 // "true" statics will never be.
1478 (true, self.is_place_thread_local(&root_place))
1480 Place::Base(PlaceBase::Local(_)) => {
1481 // Locals are always dropped at function exit, and if they
1482 // have a destructor it would've been called already.
1483 (false, self.locals_are_invalidated_at_exit)
1485 Place::Projection(..) => {
1486 bug!("root of {:?} is a projection ({:?})?", place, root_place)
1490 if !will_be_dropped {
1492 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1498 let sd = if might_be_alive { Deep } else { Shallow(None) };
1500 if places_conflict::borrow_conflicts_with_place(
1507 places_conflict::PlaceConflictBias::Overlap,
1509 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1510 // FIXME: should be talking about the region lifetime instead
1511 // of just a span here.
1512 let span = self.infcx.tcx.sess.source_map().end_point(span);
1513 self.report_borrowed_value_does_not_live_long_enough(
1522 /// Reports an error if this is a borrow of local data.
1523 /// This is called for all Yield statements on movable generators
1524 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1525 debug!("check_for_local_borrow({:?})", borrow);
1527 if borrow_of_local_data(&borrow.borrowed_place) {
1528 let err = self.infcx.tcx
1529 .cannot_borrow_across_generator_yield(
1530 self.retrieve_borrow_spans(borrow).var_or_use(),
1535 err.buffer(&mut self.errors_buffer);
1539 fn check_activations(
1543 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1545 // Two-phase borrow support: For each activation that is newly
1546 // generated at this statement, check if it interferes with
1548 let borrow_set = self.borrow_set.clone();
1549 for &borrow_index in borrow_set.activations_at_location(location) {
1550 let borrow = &borrow_set[borrow_index];
1552 // only mutable borrows should be 2-phase
1553 assert!(match borrow.kind {
1554 BorrowKind::Shared | BorrowKind::Shallow => false,
1555 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1560 (&borrow.borrowed_place, span),
1563 Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1565 LocalMutationIsAllowed::No,
1568 // We do not need to call `check_if_path_or_subpath_is_moved`
1569 // again, as we already called it when we made the
1570 // initial reservation.
1575 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1576 fn check_if_reassignment_to_immutable_state(
1580 place_span: (&Place<'tcx>, Span),
1581 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1583 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1585 // Check if any of the initializiations of `local` have happened yet:
1586 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1587 // And, if so, report an error.
1588 let init = &self.move_data.inits[init_index];
1589 let span = init.span(&self.mir);
1590 self.report_illegal_reassignment(
1591 location, place_span, span, place_span.0
1596 fn check_if_full_path_is_moved(
1599 desired_action: InitializationRequiringAction,
1600 place_span: (&Place<'tcx>, Span),
1601 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1603 let maybe_uninits = &flow_state.uninits;
1607 // 1. Move of `a.b.c`, use of `a.b.c`
1608 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1609 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1610 // partial initialization support, one might have `a.x`
1611 // initialized but not `a.b`.
1615 // 4. Move of `a.b.c`, use of `a.b.d`
1616 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1617 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1618 // must have been initialized for the use to be sound.
1619 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1621 // The dataflow tracks shallow prefixes distinctly (that is,
1622 // field-accesses on P distinctly from P itself), in order to
1623 // track substructure initialization separately from the whole
1626 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1627 // which we have a MovePath is `a.b`, then that means that the
1628 // initialization state of `a.b` is all we need to inspect to
1629 // know if `a.b.c` is valid (and from that we infer that the
1630 // dereference and `.d` access is also valid, since we assume
1631 // `a.b.c` is assigned a reference to a initialized and
1632 // well-formed record structure.)
1634 // Therefore, if we seek out the *closest* prefix for which we
1635 // have a MovePath, that should capture the initialization
1636 // state for the place scenario.
1638 // This code covers scenarios 1, 2, and 3.
1640 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1641 match self.move_path_closest_to(place_span.0) {
1642 Ok((prefix, mpi)) => {
1643 if maybe_uninits.contains(mpi) {
1644 self.report_use_of_moved_or_uninitialized(
1647 (prefix, place_span.0, place_span.1),
1650 return; // don't bother finding other problems.
1653 Err(NoMovePathFound::ReachedStatic) => {
1654 // Okay: we do not build MoveData for static variables
1655 } // Only query longest prefix with a MovePath, not further
1656 // ancestors; dataflow recurs on children when parents
1657 // move (to support partial (re)inits).
1659 // (I.e., querying parents breaks scenario 7; but may want
1660 // to do such a query based on partial-init feature-gate.)
1664 fn check_if_path_or_subpath_is_moved(
1667 desired_action: InitializationRequiringAction,
1668 place_span: (&Place<'tcx>, Span),
1669 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1671 let maybe_uninits = &flow_state.uninits;
1675 // 1. Move of `a.b.c`, use of `a` or `a.b`
1676 // partial initialization support, one might have `a.x`
1677 // initialized but not `a.b`.
1678 // 2. All bad scenarios from `check_if_full_path_is_moved`
1682 // 3. Move of `a.b.c`, use of `a.b.d`
1683 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1684 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1685 // must have been initialized for the use to be sound.
1686 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1688 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1690 // A move of any shallow suffix of `place` also interferes
1691 // with an attempt to use `place`. This is scenario 3 above.
1693 // (Distinct from handling of scenarios 1+2+4 above because
1694 // `place` does not interfere with suffixes of its prefixes,
1695 // e.g., `a.b.c` does not interfere with `a.b.d`)
1697 // This code covers scenario 1.
1699 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1700 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1701 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1702 self.report_use_of_moved_or_uninitialized(
1705 (place_span.0, place_span.0, place_span.1),
1708 return; // don't bother finding other problems.
1713 /// Currently MoveData does not store entries for all places in
1714 /// the input MIR. For example it will currently filter out
1715 /// places that are Copy; thus we do not track places of shared
1716 /// reference type. This routine will walk up a place along its
1717 /// prefixes, searching for a foundational place that *is*
1718 /// tracked in the MoveData.
1720 /// An Err result includes a tag indicated why the search failed.
1721 /// Currently this can only occur if the place is built off of a
1722 /// static variable, as we do not track those in the MoveData.
1723 fn move_path_closest_to<'a>(
1725 place: &'a Place<'tcx>,
1726 ) -> Result<(&'a Place<'tcx>, MovePathIndex), NoMovePathFound> where 'cx: 'a {
1727 let mut last_prefix = place;
1728 for prefix in self.prefixes(place, PrefixSet::All) {
1729 if let Some(mpi) = self.move_path_for_place(prefix) {
1730 return Ok((prefix, mpi));
1732 last_prefix = prefix;
1734 match *last_prefix {
1735 Place::Base(PlaceBase::Local(_)) => panic!("should have move path for every Local"),
1736 Place::Projection(_) => panic!("PrefixSet::All meant don't stop for Projection"),
1737 Place::Base(PlaceBase::Static(_)) => Err(NoMovePathFound::ReachedStatic),
1741 fn move_path_for_place(&mut self, place: &Place<'tcx>) -> Option<MovePathIndex> {
1742 // If returns None, then there is no move path corresponding
1743 // to a direct owner of `place` (which means there is nothing
1744 // that borrowck tracks for its analysis).
1746 match self.move_data.rev_lookup.find(place) {
1747 LookupResult::Parent(_) => None,
1748 LookupResult::Exact(mpi) => Some(mpi),
1752 fn check_if_assigned_path_is_moved(
1755 (place, span): (&Place<'tcx>, Span),
1756 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1758 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1759 // recur down place; dispatch to external checks when necessary
1760 let mut place = place;
1763 Place::Base(PlaceBase::Local(_)) | Place::Base(PlaceBase::Static(_)) => {
1764 // assigning to `x` does not require `x` be initialized.
1767 Place::Projection(ref proj) => {
1768 let Projection { ref base, ref elem } = **proj;
1770 ProjectionElem::Index(_/*operand*/) |
1771 ProjectionElem::ConstantIndex { .. } |
1772 // assigning to P[i] requires P to be valid.
1773 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1774 // assigning to (P->variant) is okay if assigning to `P` is okay
1776 // FIXME: is this true even if P is a adt with a dtor?
1779 // assigning to (*P) requires P to be initialized
1780 ProjectionElem::Deref => {
1781 self.check_if_full_path_is_moved(
1782 location, InitializationRequiringAction::Use,
1783 (base, span), flow_state);
1784 // (base initialized; no need to
1789 ProjectionElem::Subslice { .. } => {
1790 panic!("we don't allow assignments to subslices, location: {:?}",
1794 ProjectionElem::Field(..) => {
1795 // if type of `P` has a dtor, then
1796 // assigning to `P.f` requires `P` itself
1797 // be already initialized
1798 let tcx = self.infcx.tcx;
1799 match base.ty(self.mir, tcx).ty.sty {
1800 ty::Adt(def, _) if def.has_dtor(tcx) => {
1801 self.check_if_path_or_subpath_is_moved(
1802 location, InitializationRequiringAction::Assignment,
1803 (base, span), flow_state);
1805 // (base initialized; no need to
1811 // Once `let s; s.x = V; read(s.x);`,
1812 // is allowed, remove this match arm.
1813 ty::Adt(..) | ty::Tuple(..) => {
1814 check_parent_of_field(self, location, base, span, flow_state);
1816 if let Some(local) = place.base_local() {
1817 // rust-lang/rust#21232,
1818 // #54499, #54986: during
1819 // period where we reject
1820 // partial initialization, do
1821 // not complain about
1822 // unnecessary `mut` on an
1823 // attempt to do a partial
1825 self.used_mut.insert(local);
1839 fn check_parent_of_field<'cx, 'gcx, 'tcx>(
1840 this: &mut MirBorrowckCtxt<'cx, 'gcx, 'tcx>,
1844 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1846 // rust-lang/rust#21232: Until Rust allows reads from the
1847 // initialized parts of partially initialized structs, we
1848 // will, starting with the 2018 edition, reject attempts
1849 // to write to structs that are not fully initialized.
1851 // In other words, *until* we allow this:
1853 // 1. `let mut s; s.x = Val; read(s.x);`
1855 // we will for now disallow this:
1857 // 2. `let mut s; s.x = Val;`
1861 // 3. `let mut s = ...; drop(s); s.x=Val;`
1863 // This does not use check_if_path_or_subpath_is_moved,
1864 // because we want to *allow* reinitializations of fields:
1865 // e.g., want to allow
1867 // `let mut s = ...; drop(s.x); s.x=Val;`
1869 // This does not use check_if_full_path_is_moved on
1870 // `base`, because that would report an error about the
1871 // `base` as a whole, but in this scenario we *really*
1872 // want to report an error about the actual thing that was
1873 // moved, which may be some prefix of `base`.
1875 // Shallow so that we'll stop at any dereference; we'll
1876 // report errors about issues with such bases elsewhere.
1877 let maybe_uninits = &flow_state.uninits;
1879 // Find the shortest uninitialized prefix you can reach
1880 // without going over a Deref.
1881 let mut shortest_uninit_seen = None;
1882 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1883 let mpi = match this.move_path_for_place(prefix) {
1884 Some(mpi) => mpi, None => continue,
1887 if maybe_uninits.contains(mpi) {
1888 debug!("check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1889 shortest_uninit_seen, Some((prefix, mpi)));
1890 shortest_uninit_seen = Some((prefix, mpi));
1892 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1896 if let Some((prefix, mpi)) = shortest_uninit_seen {
1897 // Check for a reassignment into a uninitialized field of a union (for example,
1898 // after a move out). In this case, do not report a error here. There is an
1899 // exception, if this is the first assignment into the union (that is, there is
1900 // no move out from an earlier location) then this is an attempt at initialization
1901 // of the union - we should error in that case.
1902 let tcx = this.infcx.tcx;
1903 if let ty::Adt(def, _) = base.ty(this.mir, tcx).ty.sty {
1905 if this.move_data.path_map[mpi].iter().any(|moi| {
1906 this.move_data.moves[*moi].source.is_predecessor_of(
1915 this.report_use_of_moved_or_uninitialized(
1917 InitializationRequiringAction::PartialAssignment,
1918 (prefix, base, span),
1925 /// Checks the permissions for the given place and read or write kind
1927 /// Returns `true` if an error is reported.
1928 fn check_access_permissions(
1930 (place, span): (&Place<'tcx>, Span),
1932 is_local_mutation_allowed: LocalMutationIsAllowed,
1933 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1937 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1938 place, kind, is_local_mutation_allowed
1944 // rust-lang/rust#21232, #54986: during period where we reject
1945 // partial initialization, do not complain about mutability
1946 // errors except for actual mutation (as opposed to an attempt
1947 // to do a partial initialization).
1948 let previously_initialized = if let Some(local) = place.base_local() {
1949 self.is_local_ever_initialized(local, flow_state).is_some()
1955 Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1956 | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
1957 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1958 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. })) => {
1959 let is_local_mutation_allowed = match borrow_kind {
1960 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1961 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1962 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1964 match self.is_mutable(place, is_local_mutation_allowed) {
1966 self.add_used_mut(root_place, flow_state);
1970 error_access = AccessKind::MutableBorrow;
1971 the_place_err = place_err;
1975 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1976 match self.is_mutable(place, is_local_mutation_allowed) {
1978 self.add_used_mut(root_place, flow_state);
1982 error_access = AccessKind::Mutate;
1983 the_place_err = place_err;
1988 Reservation(wk @ WriteKind::Move)
1989 | Write(wk @ WriteKind::Move)
1990 | Reservation(wk @ WriteKind::StorageDeadOrDrop)
1991 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1992 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow))
1993 | Write(wk @ WriteKind::StorageDeadOrDrop)
1994 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1995 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
1996 if let (Err(_place_err), true) = (
1997 self.is_mutable(place, is_local_mutation_allowed),
1998 self.errors_buffer.is_empty()
2000 if self.infcx.tcx.migrate_borrowck() {
2001 // rust-lang/rust#46908: In pure NLL mode this
2002 // code path should be unreachable (and thus
2003 // we signal an ICE in the else branch
2004 // here). But we can legitimately get here
2005 // under borrowck=migrate mode, so instead of
2006 // ICE'ing we instead report a legitimate
2007 // error (which will then be downgraded to a
2008 // warning by the migrate machinery).
2009 error_access = match wk {
2010 WriteKind::MutableBorrow(_) => AccessKind::MutableBorrow,
2011 WriteKind::Move => AccessKind::Move,
2012 WriteKind::StorageDeadOrDrop |
2013 WriteKind::Mutate => AccessKind::Mutate,
2015 self.report_mutability_error(
2025 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2034 // permission checks are done at Reservation point.
2037 Read(ReadKind::Borrow(BorrowKind::Unique))
2038 | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
2039 | Read(ReadKind::Borrow(BorrowKind::Shared))
2040 | Read(ReadKind::Borrow(BorrowKind::Shallow))
2041 | Read(ReadKind::Copy) => {
2042 // Access authorized
2047 // at this point, we have set up the error reporting state.
2048 return if previously_initialized {
2049 self.report_mutability_error(
2062 fn is_local_ever_initialized(&self,
2064 flow_state: &Flows<'cx, 'gcx, 'tcx>)
2065 -> Option<InitIndex>
2067 let mpi = self.move_data.rev_lookup.find_local(local);
2068 let ii = &self.move_data.init_path_map[mpi];
2070 if flow_state.ever_inits.contains(index) {
2077 /// Adds the place into the used mutable variables set
2078 fn add_used_mut<'d>(
2080 root_place: RootPlace<'d, 'tcx>,
2081 flow_state: &Flows<'cx, 'gcx, 'tcx>,
2085 place: Place::Base(PlaceBase::Local(local)),
2086 is_local_mutation_allowed,
2088 // If the local may have been initialized, and it is now currently being
2089 // mutated, then it is justified to be annotated with the `mut`
2090 // keyword, since the mutation may be a possible reassignment.
2091 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes &&
2092 self.is_local_ever_initialized(*local, flow_state).is_some()
2094 self.used_mut.insert(*local);
2099 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2102 place: place @ Place::Projection(_),
2103 is_local_mutation_allowed: _,
2105 if let Some(field) = self.is_upvar_field_projection(place) {
2106 self.used_mut_upvars.push(field);
2110 place: Place::Base(PlaceBase::Static(..)),
2111 is_local_mutation_allowed: _,
2116 /// Whether this value can be written or borrowed mutably.
2117 /// Returns the root place if the place passed in is a projection.
2120 place: &'d Place<'tcx>,
2121 is_local_mutation_allowed: LocalMutationIsAllowed,
2122 ) -> Result<RootPlace<'d, 'tcx>, &'d Place<'tcx>> {
2124 Place::Base(PlaceBase::Local(local)) => {
2125 let local = &self.mir.local_decls[local];
2126 match local.mutability {
2127 Mutability::Not => match is_local_mutation_allowed {
2128 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2130 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2132 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2134 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2136 LocalMutationIsAllowed::No => Err(place),
2138 Mutability::Mut => Ok(RootPlace {
2140 is_local_mutation_allowed,
2144 // The rules for promotion are made by `qualify_consts`, there wouldn't even be a
2145 // `Place::Promoted` if the promotion weren't 100% legal. So we just forward this
2146 Place::Base(PlaceBase::Static(box Static{kind: StaticKind::Promoted(_), ..})) =>
2149 is_local_mutation_allowed,
2151 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(def_id), .. })) => {
2152 if !self.infcx.tcx.is_mutable_static(def_id) {
2157 is_local_mutation_allowed,
2161 Place::Projection(ref proj) => {
2163 ProjectionElem::Deref => {
2164 let base_ty = proj.base.ty(self.mir, self.infcx.tcx).ty;
2166 // Check the kind of deref to decide
2168 ty::Ref(_, _, mutbl) => {
2170 // Shared borrowed data is never mutable
2171 hir::MutImmutable => Err(place),
2172 // Mutably borrowed data is mutable, but only if we have a
2173 // unique path to the `&mut`
2174 hir::MutMutable => {
2175 let mode = match self.is_upvar_field_projection(place) {
2177 if self.upvars[field.index()].by_ref =>
2179 is_local_mutation_allowed
2181 _ => LocalMutationIsAllowed::Yes,
2184 self.is_mutable(&proj.base, mode)
2188 ty::RawPtr(tnm) => {
2190 // `*const` raw pointers are not mutable
2191 hir::MutImmutable => Err(place),
2192 // `*mut` raw pointers are always mutable, regardless of
2193 // context. The users have to check by themselves.
2194 hir::MutMutable => {
2197 is_local_mutation_allowed,
2202 // `Box<T>` owns its content, so mutable if its location is mutable
2203 _ if base_ty.is_box() => {
2204 self.is_mutable(&proj.base, is_local_mutation_allowed)
2206 // Deref should only be for reference, pointers or boxes
2207 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2210 // All other projections are owned by their base path, so mutable if
2211 // base path is mutable
2212 ProjectionElem::Field(..)
2213 | ProjectionElem::Index(..)
2214 | ProjectionElem::ConstantIndex { .. }
2215 | ProjectionElem::Subslice { .. }
2216 | ProjectionElem::Downcast(..) => {
2217 let upvar_field_projection = self.is_upvar_field_projection(place);
2218 if let Some(field) = upvar_field_projection {
2219 let upvar = &self.upvars[field.index()];
2221 "upvar.mutability={:?} local_mutation_is_allowed={:?} place={:?}",
2222 upvar, is_local_mutation_allowed, place
2224 match (upvar.mutability, is_local_mutation_allowed) {
2225 (Mutability::Not, LocalMutationIsAllowed::No)
2226 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2229 (Mutability::Not, LocalMutationIsAllowed::Yes)
2230 | (Mutability::Mut, _) => {
2231 // Subtle: this is an upvar
2232 // reference, so it looks like
2233 // `self.foo` -- we want to double
2234 // check that the location `*self`
2235 // is mutable (i.e., this is not a
2236 // `Fn` closure). But if that
2237 // check succeeds, we want to
2238 // *blame* the mutability on
2239 // `place` (that is,
2240 // `self.foo`). This is used to
2241 // propagate the info about
2242 // whether mutability declarations
2243 // are used outwards, so that we register
2244 // the outer variable as mutable. Otherwise a
2245 // test like this fails to record the `mut`
2249 // fn foo<F: FnOnce()>(_f: F) { }
2251 // let var = Vec::new();
2257 let _ = self.is_mutable(&proj.base, is_local_mutation_allowed)?;
2260 is_local_mutation_allowed,
2265 self.is_mutable(&proj.base, is_local_mutation_allowed)
2273 /// If `place` is a field projection, and the field is being projected from a closure type,
2274 /// then returns the index of the field being projected. Note that this closure will always
2275 /// be `self` in the current MIR, because that is the only time we directly access the fields
2276 /// of a closure type.
2277 pub fn is_upvar_field_projection(&self, place: &Place<'tcx>) -> Option<Field> {
2278 let (place, by_ref) = if let Place::Projection(ref proj) = place {
2279 if let ProjectionElem::Deref = proj.elem {
2289 Place::Projection(ref proj) => match proj.elem {
2290 ProjectionElem::Field(field, _ty) => {
2291 let tcx = self.infcx.tcx;
2292 let base_ty = proj.base.ty(self.mir, tcx).ty;
2294 if (base_ty.is_closure() || base_ty.is_generator()) &&
2295 (!by_ref || self.upvars[field.index()].by_ref)
2309 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2310 enum NoMovePathFound {
2314 /// The degree of overlap between 2 places for borrow-checking.
2316 /// The places might partially overlap - in this case, we give
2317 /// up and say that they might conflict. This occurs when
2318 /// different fields of a union are borrowed. For example,
2319 /// if `u` is a union, we have no way of telling how disjoint
2320 /// `u.a.x` and `a.b.y` are.
2322 /// The places have the same type, and are either completely disjoint
2323 /// or equal - i.e., they can't "partially" overlap as can occur with
2324 /// unions. This is the "base case" on which we recur for extensions
2327 /// The places are disjoint, so we know all extensions of them
2328 /// will also be disjoint.