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",
444 "this represents potential undefined behavior in your code and \
445 this warning will become a hard error in the future",
450 pub struct MirBorrowckCtxt<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
451 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
454 move_data: &'cx MoveData<'tcx>,
456 /// Map from MIR `Location` to `LocationIndex`; created
457 /// when MIR borrowck begins.
458 location_table: &'cx LocationTable,
460 movable_generator: bool,
461 /// This keeps track of whether local variables are free-ed when the function
462 /// exits even without a `StorageDead`, which appears to be the case for
465 /// I'm not sure this is the right approach - @eddyb could you try and
467 locals_are_invalidated_at_exit: bool,
468 /// This field keeps track of when borrow errors are reported in the access_place function
469 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
470 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
471 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
473 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
474 /// This field keeps track of when borrow conflict errors are reported
475 /// for reservations, so that we don't report seemingly duplicate
476 /// errors for corresponding activations.
478 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
479 // but it is currently inconvenient to track down the `BorrowIndex`
480 // at the time we detect and report a reservation error.
481 reservation_error_reported: FxHashSet<Place<'tcx>>,
482 /// Migration warnings to be reported for #56254. We delay reporting these
483 /// so that we can suppress the warning if there's a corresponding error
484 /// for the activation of the borrow.
485 reservation_warnings: FxHashMap<
487 (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)
489 /// This field keeps track of move errors that are to be reported for given move indicies.
491 /// There are situations where many errors can be reported for a single move out (see #53807)
492 /// and we want only the best of those errors.
494 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
495 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
496 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
497 /// all move errors have been reported, any diagnostics in this map are added to the buffer
500 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
501 /// when errors in the map are being re-added to the error buffer so that errors with the
502 /// same primary span come out in a consistent order.
503 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (Place<'tcx>, DiagnosticBuilder<'cx>)>,
504 /// This field keeps track of errors reported in the checking of uninitialized variables,
505 /// so that we don't report seemingly duplicate errors.
506 uninitialized_error_reported: FxHashSet<Place<'tcx>>,
507 /// Errors to be reported buffer
508 errors_buffer: Vec<Diagnostic>,
509 /// This field keeps track of all the local variables that are declared mut and are mutated.
510 /// Used for the warning issued by an unused mutable local variable.
511 used_mut: FxHashSet<Local>,
512 /// If the function we're checking is a closure, then we'll need to report back the list of
513 /// mutable upvars that have been used. This field keeps track of them.
514 used_mut_upvars: SmallVec<[Field; 8]>,
515 /// Non-lexical region inference context, if NLL is enabled. This
516 /// contains the results from region inference and lets us e.g.
517 /// find out which CFG points are contained in each borrow region.
518 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
520 /// The set of borrows extracted from the MIR
521 borrow_set: Rc<BorrowSet<'tcx>>,
523 /// Dominators for MIR
524 dominators: Dominators<BasicBlock>,
526 /// Information about upvars not necessarily preserved in types or MIR
531 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
532 // 2. loans made in overlapping scopes do not conflict
533 // 3. assignments do not affect things loaned out as immutable
534 // 4. moves do not affect things loaned out in any way
535 impl<'cx, 'gcx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
536 type FlowState = Flows<'cx, 'gcx, 'tcx>;
538 fn mir(&self) -> &'cx Mir<'tcx> {
542 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
543 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
546 fn visit_statement_entry(
549 stmt: &Statement<'tcx>,
550 flow_state: &Self::FlowState,
553 "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
554 location, stmt, flow_state
556 let span = stmt.source_info.span;
558 self.check_activations(location, span, flow_state);
561 StatementKind::Assign(ref lhs, ref rhs) => {
576 StatementKind::FakeRead(_, ref place) => {
577 // Read for match doesn't access any memory and is used to
578 // assert that a place is safe and live. So we don't have to
579 // do any checks here.
581 // FIXME: Remove check that the place is initialized. This is
582 // needed for now because matches don't have never patterns yet.
583 // So this is the only place we prevent
587 self.check_if_path_or_subpath_is_moved(
589 InitializationRequiringAction::Use,
594 StatementKind::SetDiscriminant {
606 StatementKind::InlineAsm(ref asm) => {
607 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
609 // FIXME(eddyb) indirect inline asm outputs should
610 // be encoded through MIR place derefs instead.
614 (Deep, Read(ReadKind::Copy)),
615 LocalMutationIsAllowed::No,
618 self.check_if_path_or_subpath_is_moved(
620 InitializationRequiringAction::Use,
628 if o.is_rw { Deep } else { Shallow(None) },
629 if o.is_rw { WriteAndRead } else { JustWrite },
634 for (_, input) in asm.inputs.iter() {
635 self.consume_operand(location, (input, span), flow_state);
639 | StatementKind::AscribeUserType(..)
640 | StatementKind::Retag { .. }
641 | StatementKind::StorageLive(..) => {
642 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
645 StatementKind::StorageDead(local) => {
648 (&Place::Base(PlaceBase::Local(local)), span),
649 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
650 LocalMutationIsAllowed::Yes,
657 fn visit_terminator_entry(
660 term: &Terminator<'tcx>,
661 flow_state: &Self::FlowState,
665 "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
666 location, term, flow_state
668 let span = term.source_info.span;
670 self.check_activations(location, span, flow_state);
673 TerminatorKind::SwitchInt {
679 self.consume_operand(loc, (discr, span), flow_state);
681 TerminatorKind::Drop {
682 location: ref drop_place,
686 let gcx = self.infcx.tcx.global_tcx();
688 // Compute the type with accurate region information.
689 let drop_place_ty = drop_place.ty(self.mir, self.infcx.tcx);
691 // Erase the regions.
692 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
694 // "Lift" into the gcx -- once regions are erased, this type should be in the
695 // global arenas; this "lift" operation basically just asserts that is true, but
696 // that is useful later.
697 let drop_place_ty = gcx.lift(&drop_place_ty).unwrap();
699 debug!("visit_terminator_drop \
700 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
701 loc, term, drop_place, drop_place_ty, span);
706 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
707 LocalMutationIsAllowed::Yes,
711 TerminatorKind::DropAndReplace {
712 location: ref drop_place,
713 value: ref new_value,
724 self.consume_operand(
730 TerminatorKind::Call {
737 self.consume_operand(loc, (func, span), flow_state);
739 self.consume_operand(
745 if let Some((ref dest, _ /*bb*/)) = *destination {
755 TerminatorKind::Assert {
762 self.consume_operand(loc, (cond, span), flow_state);
763 use rustc::mir::interpret::InterpError::BoundsCheck;
764 if let BoundsCheck { ref len, ref index } = *msg {
765 self.consume_operand(loc, (len, span), flow_state);
766 self.consume_operand(loc, (index, span), flow_state);
770 TerminatorKind::Yield {
775 self.consume_operand(loc, (value, span), flow_state);
777 if self.movable_generator {
778 // Look for any active borrows to locals
779 let borrow_set = self.borrow_set.clone();
780 flow_state.with_outgoing_borrows(|borrows| {
782 let borrow = &borrow_set[i];
783 self.check_for_local_borrow(borrow, span);
789 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
790 // Returning from the function implicitly kills storage for all locals and statics.
791 // Often, the storage will already have been killed by an explicit
792 // StorageDead, but we don't always emit those (notably on unwind paths),
793 // so this "extra check" serves as a kind of backup.
794 let borrow_set = self.borrow_set.clone();
795 flow_state.with_outgoing_borrows(|borrows| {
797 let borrow = &borrow_set[i];
798 self.check_for_invalidation_at_exit(loc, borrow, span);
802 TerminatorKind::Goto { target: _ }
803 | TerminatorKind::Abort
804 | TerminatorKind::Unreachable
805 | TerminatorKind::FalseEdges {
807 imaginary_targets: _,
809 | TerminatorKind::FalseUnwind {
813 // no data used, thus irrelevant to borrowck
819 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
825 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
826 use self::AccessDepth::{Deep, Shallow};
828 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
829 enum ArtificialField {
834 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
836 /// From the RFC: "A *shallow* access means that the immediate
837 /// fields reached at P are accessed, but references or pointers
838 /// found within are not dereferenced. Right now, the only access
839 /// that is shallow is an assignment like `x = ...;`, which would
840 /// be a *shallow write* of `x`."
841 Shallow(Option<ArtificialField>),
843 /// From the RFC: "A *deep* access means that all data reachable
844 /// through the given place may be invalidated or accesses by
848 /// Access is Deep only when there is a Drop implementation that
849 /// can reach the data behind the reference.
853 /// Kind of access to a value: read or write
854 /// (For informational purposes only)
855 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
857 /// From the RFC: "A *read* means that the existing data may be
858 /// read, but will not be changed."
861 /// From the RFC: "A *write* means that the data may be mutated to
862 /// new values or otherwise invalidated (for example, it could be
863 /// de-initialized, as in a move operation).
866 /// For two-phase borrows, we distinguish a reservation (which is treated
867 /// like a Read) from an activation (which is treated like a write), and
868 /// each of those is furthermore distinguished from Reads/Writes above.
869 Reservation(WriteKind),
870 Activation(WriteKind, BorrowIndex),
873 /// Kind of read access to a value
874 /// (For informational purposes only)
875 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
881 /// Kind of write access to a value
882 /// (For informational purposes only)
883 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
886 MutableBorrow(BorrowKind),
891 /// When checking permissions for a place access, this flag is used to indicate that an immutable
892 /// local place can be mutated.
894 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
895 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
896 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
897 // `is_declared_mutable()`.
898 // - Take flow state into consideration in `is_assignable()` for local variables.
899 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
900 enum LocalMutationIsAllowed {
902 /// We want use of immutable upvars to cause a "write to immutable upvar"
903 /// error, not an "reassignment" error.
908 #[derive(Copy, Clone, Debug)]
909 enum InitializationRequiringAction {
918 struct RootPlace<'d, 'tcx: 'd> {
919 place: &'d Place<'tcx>,
920 is_local_mutation_allowed: LocalMutationIsAllowed,
923 impl InitializationRequiringAction {
924 fn as_noun(self) -> &'static str {
926 InitializationRequiringAction::Update => "update",
927 InitializationRequiringAction::Borrow => "borrow",
928 InitializationRequiringAction::MatchOn => "use", // no good noun
929 InitializationRequiringAction::Use => "use",
930 InitializationRequiringAction::Assignment => "assign",
931 InitializationRequiringAction::PartialAssignment => "assign to part",
935 fn as_verb_in_past_tense(self) -> &'static str {
937 InitializationRequiringAction::Update => "updated",
938 InitializationRequiringAction::Borrow => "borrowed",
939 InitializationRequiringAction::MatchOn => "matched on",
940 InitializationRequiringAction::Use => "used",
941 InitializationRequiringAction::Assignment => "assigned",
942 InitializationRequiringAction::PartialAssignment => "partially assigned",
947 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
948 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
949 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
950 /// place is initialized and (b) it is not borrowed in some way that would prevent this
953 /// Returns `true` if an error is reported.
957 place_span: (&Place<'tcx>, Span),
958 kind: (AccessDepth, ReadOrWrite),
959 is_local_mutation_allowed: LocalMutationIsAllowed,
960 flow_state: &Flows<'cx, 'gcx, 'tcx>,
964 if let Activation(_, borrow_index) = rw {
965 if self.reservation_error_reported.contains(&place_span.0) {
967 "skipping access_place for activation of invalid reservation \
968 place: {:?} borrow_index: {:?}",
969 place_span.0, borrow_index
975 // Check is_empty() first because it's the common case, and doing that
976 // way we avoid the clone() call.
977 if !self.access_place_error_reported.is_empty() &&
979 .access_place_error_reported
980 .contains(&(place_span.0.clone(), place_span.1))
983 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
989 let mutability_error =
990 self.check_access_permissions(
993 is_local_mutation_allowed,
998 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
1000 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
1001 // Suppress this warning when there's an error being emited for the
1002 // same borrow: fixing the error is likely to fix the warning.
1003 self.reservation_warnings.remove(&borrow_idx);
1006 if conflict_error || mutability_error {
1008 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
1012 self.access_place_error_reported
1013 .insert((place_span.0.clone(), place_span.1));
1017 fn check_access_for_conflict(
1020 place_span: (&Place<'tcx>, Span),
1023 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1026 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1027 location, place_span, sd, rw,
1030 let mut error_reported = false;
1031 let tcx = self.infcx.tcx;
1033 let location_table = self.location_table.start_index(location);
1034 let borrow_set = self.borrow_set.clone();
1035 each_borrow_involving_path(
1042 flow_state.borrows_in_scope(location_table),
1043 |this, borrow_index, borrow| match (rw, borrow.kind) {
1044 // Obviously an activation is compatible with its own
1045 // reservation (or even prior activating uses of same
1046 // borrow); so don't check if they interfere.
1048 // NOTE: *reservations* do conflict with themselves;
1049 // thus aren't injecting unsoundenss w/ this check.)
1050 (Activation(_, activating), _) if activating == borrow_index => {
1052 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1053 skipping {:?} b/c activation of same borrow_index",
1057 (borrow_index, borrow),
1062 (Read(_), BorrowKind::Shared)
1063 | (Read(_), BorrowKind::Shallow)
1064 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
1065 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
1069 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1070 // Handled by initialization checks.
1074 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
1075 // Reading from mere reservations of mutable-borrows is OK.
1076 if !is_active(&this.dominators, borrow, location) {
1077 assert!(allow_two_phase_borrow(borrow.kind));
1078 return Control::Continue;
1081 error_reported = true;
1084 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1085 .buffer(&mut this.errors_buffer);
1087 ReadKind::Borrow(bk) => {
1088 this.report_conflicting_borrow(location, place_span, bk, borrow)
1089 .buffer(&mut this.errors_buffer);
1095 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
1096 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared) if {
1097 tcx.migrate_borrowck()
1099 let bi = this.borrow_set.location_map[&location];
1101 "recording invalid reservation of place: {:?} with \
1102 borrow index {:?} as warning",
1106 // rust-lang/rust#56254 - This was previously permitted on
1107 // the 2018 edition so we emit it as a warning. We buffer
1108 // these sepately so that we only emit a warning if borrow
1109 // checking was otherwise successful.
1110 this.reservation_warnings.insert(
1112 (place_span.0.clone(), place_span.1, location, bk, borrow.clone()),
1115 // Don't suppress actual errors.
1119 (Reservation(kind), _)
1120 | (Activation(kind, _), _)
1121 | (Write(kind), _) => {
1123 Reservation(..) => {
1125 "recording invalid reservation of \
1129 this.reservation_error_reported.insert(place_span.0.clone());
1131 Activation(_, activating) => {
1133 "observing check_place for activation of \
1134 borrow_index: {:?}",
1138 Read(..) | Write(..) => {}
1141 error_reported = true;
1143 WriteKind::MutableBorrow(bk) => {
1144 this.report_conflicting_borrow(location, place_span, bk, borrow)
1145 .buffer(&mut this.errors_buffer);
1147 WriteKind::StorageDeadOrDrop => {
1148 this.report_borrowed_value_does_not_live_long_enough(
1154 WriteKind::Mutate => {
1155 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1157 WriteKind::Move => {
1158 this.report_move_out_while_borrowed(location, place_span, borrow)
1172 place_span: (&Place<'tcx>, Span),
1175 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1177 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1179 MutateMode::WriteAndRead => {
1180 self.check_if_path_or_subpath_is_moved(
1182 InitializationRequiringAction::Update,
1187 MutateMode::JustWrite => {
1188 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1192 // Special case: you can assign a immutable local variable
1193 // (e.g., `x = ...`) so long as it has never been initialized
1194 // before (at this point in the flow).
1195 if let &Place::Base(PlaceBase::Local(local)) = place_span.0 {
1196 if let Mutability::Not = self.mir.local_decls[local].mutability {
1197 // check for reassignments to immutable local variables
1198 self.check_if_reassignment_to_immutable_state(
1208 // Otherwise, use the normal access permission rules.
1212 (kind, Write(WriteKind::Mutate)),
1213 LocalMutationIsAllowed::No,
1221 (rvalue, span): (&Rvalue<'tcx>, Span),
1222 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1225 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1226 let access_kind = match bk {
1227 BorrowKind::Shallow => {
1228 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1230 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1231 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1232 let wk = WriteKind::MutableBorrow(bk);
1233 if allow_two_phase_borrow(bk) {
1234 (Deep, Reservation(wk))
1245 LocalMutationIsAllowed::No,
1249 let action = if bk == BorrowKind::Shallow {
1250 InitializationRequiringAction::MatchOn
1252 InitializationRequiringAction::Borrow
1255 self.check_if_path_or_subpath_is_moved(
1263 Rvalue::Use(ref operand)
1264 | Rvalue::Repeat(ref operand, _)
1265 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1266 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1267 self.consume_operand(location, (operand, span), flow_state)
1270 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1271 let af = match *rvalue {
1272 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1273 Rvalue::Discriminant(..) => None,
1274 _ => unreachable!(),
1279 (Shallow(af), Read(ReadKind::Copy)),
1280 LocalMutationIsAllowed::No,
1283 self.check_if_path_or_subpath_is_moved(
1285 InitializationRequiringAction::Use,
1291 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1292 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1293 self.consume_operand(location, (operand1, span), flow_state);
1294 self.consume_operand(location, (operand2, span), flow_state);
1297 Rvalue::NullaryOp(_op, _ty) => {
1298 // nullary ops take no dynamic input; no borrowck effect.
1300 // FIXME: is above actually true? Do we want to track
1301 // the fact that uninitialized data can be created via
1305 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1306 // We need to report back the list of mutable upvars that were
1307 // moved into the closure and subsequently used by the closure,
1308 // in order to populate our used_mut set.
1309 match **aggregate_kind {
1310 AggregateKind::Closure(def_id, _)
1311 | AggregateKind::Generator(def_id, _, _) => {
1312 let BorrowCheckResult {
1314 } = self.infcx.tcx.mir_borrowck(def_id);
1315 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1316 for field in used_mut_upvars {
1317 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1320 AggregateKind::Adt(..)
1321 | AggregateKind::Array(..)
1322 | AggregateKind::Tuple { .. } => (),
1325 for operand in operands {
1326 self.consume_operand(location, (operand, span), flow_state);
1332 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1333 let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1335 Place::Projection { .. } => {
1336 if let Some(field) = this.is_upvar_field_projection(place) {
1337 this.used_mut_upvars.push(field);
1340 Place::Base(PlaceBase::Local(local)) => {
1341 this.used_mut.insert(local);
1343 Place::Base(PlaceBase::Static(_)) => {}
1347 // This relies on the current way that by-value
1348 // captures of a closure are copied/moved directly
1349 // when generating MIR.
1351 Operand::Move(Place::Base(PlaceBase::Local(local)))
1352 | Operand::Copy(Place::Base(PlaceBase::Local(local)))
1353 if self.mir.local_decls[local].is_user_variable.is_none() =>
1355 if self.mir.local_decls[local].ty.is_mutable_pointer() {
1356 // The variable will be marked as mutable by the borrow.
1359 // This is an edge case where we have a `move` closure
1360 // inside a non-move closure, and the inner closure
1361 // contains a mutation:
1364 // || { move || { i += 1; }; };
1366 // In this case our usual strategy of assuming that the
1367 // variable will be captured by mutable reference is
1368 // wrong, since `i` can be copied into the inner
1369 // closure from a shared reference.
1371 // As such we have to search for the local that this
1372 // capture comes from and mark it as being used as mut.
1374 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1375 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1376 &self.move_data.inits[init_index]
1378 bug!("temporary should be initialized exactly once")
1381 let loc = match init.location {
1382 InitLocation::Statement(stmt) => stmt,
1383 _ => bug!("temporary initialized in arguments"),
1386 let bbd = &self.mir[loc.block];
1387 let stmt = &bbd.statements[loc.statement_index];
1388 debug!("temporary assigned in: stmt={:?}", stmt);
1390 if let StatementKind::Assign(_, box Rvalue::Ref(_, _, ref source)) = stmt.kind {
1391 propagate_closure_used_mut_place(self, source);
1393 bug!("closures should only capture user variables \
1394 or references to user variables");
1397 Operand::Move(ref place)
1398 | Operand::Copy(ref place) => {
1399 propagate_closure_used_mut_place(self, place);
1401 Operand::Constant(..) => {}
1408 (operand, span): (&Operand<'tcx>, Span),
1409 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1412 Operand::Copy(ref place) => {
1413 // copy of place: check if this is "copy of frozen path"
1414 // (FIXME: see check_loans.rs)
1418 (Deep, Read(ReadKind::Copy)),
1419 LocalMutationIsAllowed::No,
1423 // Finally, check if path was already moved.
1424 self.check_if_path_or_subpath_is_moved(
1426 InitializationRequiringAction::Use,
1431 Operand::Move(ref place) => {
1432 // move of place: check if this is move of already borrowed path
1436 (Deep, Write(WriteKind::Move)),
1437 LocalMutationIsAllowed::Yes,
1441 // Finally, check if path was already moved.
1442 self.check_if_path_or_subpath_is_moved(
1444 InitializationRequiringAction::Use,
1449 Operand::Constant(_) => {}
1453 /// Checks whether a borrow of this place is invalidated when the function
1455 fn check_for_invalidation_at_exit(
1458 borrow: &BorrowData<'tcx>,
1461 debug!("check_for_invalidation_at_exit({:?})", borrow);
1462 let place = &borrow.borrowed_place;
1463 let root_place = self.prefixes(place, PrefixSet::All).last().unwrap();
1465 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1466 // we just know that all locals are dropped at function exit (otherwise
1467 // we'll have a memory leak) and assume that all statics have a destructor.
1469 // FIXME: allow thread-locals to borrow other thread locals?
1470 let (might_be_alive, will_be_dropped) = match root_place {
1471 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Promoted(_), .. })) => {
1474 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(_), .. })) => {
1475 // Thread-locals might be dropped after the function exits, but
1476 // "true" statics will never be.
1477 (true, self.is_place_thread_local(&root_place))
1479 Place::Base(PlaceBase::Local(_)) => {
1480 // Locals are always dropped at function exit, and if they
1481 // have a destructor it would've been called already.
1482 (false, self.locals_are_invalidated_at_exit)
1484 Place::Projection(..) => {
1485 bug!("root of {:?} is a projection ({:?})?", place, root_place)
1489 if !will_be_dropped {
1491 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1497 let sd = if might_be_alive { Deep } else { Shallow(None) };
1499 if places_conflict::borrow_conflicts_with_place(
1506 places_conflict::PlaceConflictBias::Overlap,
1508 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1509 // FIXME: should be talking about the region lifetime instead
1510 // of just a span here.
1511 let span = self.infcx.tcx.sess.source_map().end_point(span);
1512 self.report_borrowed_value_does_not_live_long_enough(
1521 /// Reports an error if this is a borrow of local data.
1522 /// This is called for all Yield statements on movable generators
1523 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1524 debug!("check_for_local_borrow({:?})", borrow);
1526 if borrow_of_local_data(&borrow.borrowed_place) {
1527 let err = self.infcx.tcx
1528 .cannot_borrow_across_generator_yield(
1529 self.retrieve_borrow_spans(borrow).var_or_use(),
1534 err.buffer(&mut self.errors_buffer);
1538 fn check_activations(
1542 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1544 // Two-phase borrow support: For each activation that is newly
1545 // generated at this statement, check if it interferes with
1547 let borrow_set = self.borrow_set.clone();
1548 for &borrow_index in borrow_set.activations_at_location(location) {
1549 let borrow = &borrow_set[borrow_index];
1551 // only mutable borrows should be 2-phase
1552 assert!(match borrow.kind {
1553 BorrowKind::Shared | BorrowKind::Shallow => false,
1554 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1559 (&borrow.borrowed_place, span),
1562 Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1564 LocalMutationIsAllowed::No,
1567 // We do not need to call `check_if_path_or_subpath_is_moved`
1568 // again, as we already called it when we made the
1569 // initial reservation.
1574 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1575 fn check_if_reassignment_to_immutable_state(
1579 place_span: (&Place<'tcx>, Span),
1580 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1582 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1584 // Check if any of the initializiations of `local` have happened yet:
1585 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1586 // And, if so, report an error.
1587 let init = &self.move_data.inits[init_index];
1588 let span = init.span(&self.mir);
1589 self.report_illegal_reassignment(
1590 location, place_span, span, place_span.0
1595 fn check_if_full_path_is_moved(
1598 desired_action: InitializationRequiringAction,
1599 place_span: (&Place<'tcx>, Span),
1600 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1602 let maybe_uninits = &flow_state.uninits;
1606 // 1. Move of `a.b.c`, use of `a.b.c`
1607 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1608 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1609 // partial initialization support, one might have `a.x`
1610 // initialized but not `a.b`.
1614 // 4. Move of `a.b.c`, use of `a.b.d`
1615 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1616 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1617 // must have been initialized for the use to be sound.
1618 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1620 // The dataflow tracks shallow prefixes distinctly (that is,
1621 // field-accesses on P distinctly from P itself), in order to
1622 // track substructure initialization separately from the whole
1625 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1626 // which we have a MovePath is `a.b`, then that means that the
1627 // initialization state of `a.b` is all we need to inspect to
1628 // know if `a.b.c` is valid (and from that we infer that the
1629 // dereference and `.d` access is also valid, since we assume
1630 // `a.b.c` is assigned a reference to a initialized and
1631 // well-formed record structure.)
1633 // Therefore, if we seek out the *closest* prefix for which we
1634 // have a MovePath, that should capture the initialization
1635 // state for the place scenario.
1637 // This code covers scenarios 1, 2, and 3.
1639 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1640 match self.move_path_closest_to(place_span.0) {
1641 Ok((prefix, mpi)) => {
1642 if maybe_uninits.contains(mpi) {
1643 self.report_use_of_moved_or_uninitialized(
1646 (prefix, place_span.0, place_span.1),
1649 return; // don't bother finding other problems.
1652 Err(NoMovePathFound::ReachedStatic) => {
1653 // Okay: we do not build MoveData for static variables
1654 } // Only query longest prefix with a MovePath, not further
1655 // ancestors; dataflow recurs on children when parents
1656 // move (to support partial (re)inits).
1658 // (I.e., querying parents breaks scenario 7; but may want
1659 // to do such a query based on partial-init feature-gate.)
1663 fn check_if_path_or_subpath_is_moved(
1666 desired_action: InitializationRequiringAction,
1667 place_span: (&Place<'tcx>, Span),
1668 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1670 let maybe_uninits = &flow_state.uninits;
1674 // 1. Move of `a.b.c`, use of `a` or `a.b`
1675 // partial initialization support, one might have `a.x`
1676 // initialized but not `a.b`.
1677 // 2. All bad scenarios from `check_if_full_path_is_moved`
1681 // 3. Move of `a.b.c`, use of `a.b.d`
1682 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1683 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1684 // must have been initialized for the use to be sound.
1685 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1687 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1689 // A move of any shallow suffix of `place` also interferes
1690 // with an attempt to use `place`. This is scenario 3 above.
1692 // (Distinct from handling of scenarios 1+2+4 above because
1693 // `place` does not interfere with suffixes of its prefixes,
1694 // e.g., `a.b.c` does not interfere with `a.b.d`)
1696 // This code covers scenario 1.
1698 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1699 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1700 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1701 self.report_use_of_moved_or_uninitialized(
1704 (place_span.0, place_span.0, place_span.1),
1707 return; // don't bother finding other problems.
1712 /// Currently MoveData does not store entries for all places in
1713 /// the input MIR. For example it will currently filter out
1714 /// places that are Copy; thus we do not track places of shared
1715 /// reference type. This routine will walk up a place along its
1716 /// prefixes, searching for a foundational place that *is*
1717 /// tracked in the MoveData.
1719 /// An Err result includes a tag indicated why the search failed.
1720 /// Currently this can only occur if the place is built off of a
1721 /// static variable, as we do not track those in the MoveData.
1722 fn move_path_closest_to<'a>(
1724 place: &'a Place<'tcx>,
1725 ) -> Result<(&'a Place<'tcx>, MovePathIndex), NoMovePathFound> where 'cx: 'a {
1726 let mut last_prefix = place;
1727 for prefix in self.prefixes(place, PrefixSet::All) {
1728 if let Some(mpi) = self.move_path_for_place(prefix) {
1729 return Ok((prefix, mpi));
1731 last_prefix = prefix;
1733 match *last_prefix {
1734 Place::Base(PlaceBase::Local(_)) => panic!("should have move path for every Local"),
1735 Place::Projection(_) => panic!("PrefixSet::All meant don't stop for Projection"),
1736 Place::Base(PlaceBase::Static(_)) => Err(NoMovePathFound::ReachedStatic),
1740 fn move_path_for_place(&mut self, place: &Place<'tcx>) -> Option<MovePathIndex> {
1741 // If returns None, then there is no move path corresponding
1742 // to a direct owner of `place` (which means there is nothing
1743 // that borrowck tracks for its analysis).
1745 match self.move_data.rev_lookup.find(place) {
1746 LookupResult::Parent(_) => None,
1747 LookupResult::Exact(mpi) => Some(mpi),
1751 fn check_if_assigned_path_is_moved(
1754 (place, span): (&Place<'tcx>, Span),
1755 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1757 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1758 // recur down place; dispatch to external checks when necessary
1759 let mut place = place;
1762 Place::Base(PlaceBase::Local(_)) | Place::Base(PlaceBase::Static(_)) => {
1763 // assigning to `x` does not require `x` be initialized.
1766 Place::Projection(ref proj) => {
1767 let Projection { ref base, ref elem } = **proj;
1769 ProjectionElem::Index(_/*operand*/) |
1770 ProjectionElem::ConstantIndex { .. } |
1771 // assigning to P[i] requires P to be valid.
1772 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1773 // assigning to (P->variant) is okay if assigning to `P` is okay
1775 // FIXME: is this true even if P is a adt with a dtor?
1778 // assigning to (*P) requires P to be initialized
1779 ProjectionElem::Deref => {
1780 self.check_if_full_path_is_moved(
1781 location, InitializationRequiringAction::Use,
1782 (base, span), flow_state);
1783 // (base initialized; no need to
1788 ProjectionElem::Subslice { .. } => {
1789 panic!("we don't allow assignments to subslices, location: {:?}",
1793 ProjectionElem::Field(..) => {
1794 // if type of `P` has a dtor, then
1795 // assigning to `P.f` requires `P` itself
1796 // be already initialized
1797 let tcx = self.infcx.tcx;
1798 match base.ty(self.mir, tcx).ty.sty {
1799 ty::Adt(def, _) if def.has_dtor(tcx) => {
1800 self.check_if_path_or_subpath_is_moved(
1801 location, InitializationRequiringAction::Assignment,
1802 (base, span), flow_state);
1804 // (base initialized; no need to
1810 // Once `let s; s.x = V; read(s.x);`,
1811 // is allowed, remove this match arm.
1812 ty::Adt(..) | ty::Tuple(..) => {
1813 check_parent_of_field(self, location, base, span, flow_state);
1815 if let Some(local) = place.base_local() {
1816 // rust-lang/rust#21232,
1817 // #54499, #54986: during
1818 // period where we reject
1819 // partial initialization, do
1820 // not complain about
1821 // unnecessary `mut` on an
1822 // attempt to do a partial
1824 self.used_mut.insert(local);
1838 fn check_parent_of_field<'cx, 'gcx, 'tcx>(
1839 this: &mut MirBorrowckCtxt<'cx, 'gcx, 'tcx>,
1843 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1845 // rust-lang/rust#21232: Until Rust allows reads from the
1846 // initialized parts of partially initialized structs, we
1847 // will, starting with the 2018 edition, reject attempts
1848 // to write to structs that are not fully initialized.
1850 // In other words, *until* we allow this:
1852 // 1. `let mut s; s.x = Val; read(s.x);`
1854 // we will for now disallow this:
1856 // 2. `let mut s; s.x = Val;`
1860 // 3. `let mut s = ...; drop(s); s.x=Val;`
1862 // This does not use check_if_path_or_subpath_is_moved,
1863 // because we want to *allow* reinitializations of fields:
1864 // e.g., want to allow
1866 // `let mut s = ...; drop(s.x); s.x=Val;`
1868 // This does not use check_if_full_path_is_moved on
1869 // `base`, because that would report an error about the
1870 // `base` as a whole, but in this scenario we *really*
1871 // want to report an error about the actual thing that was
1872 // moved, which may be some prefix of `base`.
1874 // Shallow so that we'll stop at any dereference; we'll
1875 // report errors about issues with such bases elsewhere.
1876 let maybe_uninits = &flow_state.uninits;
1878 // Find the shortest uninitialized prefix you can reach
1879 // without going over a Deref.
1880 let mut shortest_uninit_seen = None;
1881 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1882 let mpi = match this.move_path_for_place(prefix) {
1883 Some(mpi) => mpi, None => continue,
1886 if maybe_uninits.contains(mpi) {
1887 debug!("check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1888 shortest_uninit_seen, Some((prefix, mpi)));
1889 shortest_uninit_seen = Some((prefix, mpi));
1891 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1895 if let Some((prefix, mpi)) = shortest_uninit_seen {
1896 // Check for a reassignment into a uninitialized field of a union (for example,
1897 // after a move out). In this case, do not report a error here. There is an
1898 // exception, if this is the first assignment into the union (that is, there is
1899 // no move out from an earlier location) then this is an attempt at initialization
1900 // of the union - we should error in that case.
1901 let tcx = this.infcx.tcx;
1902 if let ty::Adt(def, _) = base.ty(this.mir, tcx).ty.sty {
1904 if this.move_data.path_map[mpi].iter().any(|moi| {
1905 this.move_data.moves[*moi].source.is_predecessor_of(
1914 this.report_use_of_moved_or_uninitialized(
1916 InitializationRequiringAction::PartialAssignment,
1917 (prefix, base, span),
1924 /// Checks the permissions for the given place and read or write kind
1926 /// Returns `true` if an error is reported.
1927 fn check_access_permissions(
1929 (place, span): (&Place<'tcx>, Span),
1931 is_local_mutation_allowed: LocalMutationIsAllowed,
1932 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1936 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1937 place, kind, is_local_mutation_allowed
1943 // rust-lang/rust#21232, #54986: during period where we reject
1944 // partial initialization, do not complain about mutability
1945 // errors except for actual mutation (as opposed to an attempt
1946 // to do a partial initialization).
1947 let previously_initialized = if let Some(local) = place.base_local() {
1948 self.is_local_ever_initialized(local, flow_state).is_some()
1954 Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1955 | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
1956 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1957 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. })) => {
1958 let is_local_mutation_allowed = match borrow_kind {
1959 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1960 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1961 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1963 match self.is_mutable(place, is_local_mutation_allowed) {
1965 self.add_used_mut(root_place, flow_state);
1969 error_access = AccessKind::MutableBorrow;
1970 the_place_err = place_err;
1974 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1975 match self.is_mutable(place, is_local_mutation_allowed) {
1977 self.add_used_mut(root_place, flow_state);
1981 error_access = AccessKind::Mutate;
1982 the_place_err = place_err;
1987 Reservation(wk @ WriteKind::Move)
1988 | Write(wk @ WriteKind::Move)
1989 | Reservation(wk @ WriteKind::StorageDeadOrDrop)
1990 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1991 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow))
1992 | Write(wk @ WriteKind::StorageDeadOrDrop)
1993 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1994 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
1995 if let (Err(_place_err), true) = (
1996 self.is_mutable(place, is_local_mutation_allowed),
1997 self.errors_buffer.is_empty()
1999 if self.infcx.tcx.migrate_borrowck() {
2000 // rust-lang/rust#46908: In pure NLL mode this
2001 // code path should be unreachable (and thus
2002 // we signal an ICE in the else branch
2003 // here). But we can legitimately get here
2004 // under borrowck=migrate mode, so instead of
2005 // ICE'ing we instead report a legitimate
2006 // error (which will then be downgraded to a
2007 // warning by the migrate machinery).
2008 error_access = match wk {
2009 WriteKind::MutableBorrow(_) => AccessKind::MutableBorrow,
2010 WriteKind::Move => AccessKind::Move,
2011 WriteKind::StorageDeadOrDrop |
2012 WriteKind::Mutate => AccessKind::Mutate,
2014 self.report_mutability_error(
2024 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2033 // permission checks are done at Reservation point.
2036 Read(ReadKind::Borrow(BorrowKind::Unique))
2037 | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
2038 | Read(ReadKind::Borrow(BorrowKind::Shared))
2039 | Read(ReadKind::Borrow(BorrowKind::Shallow))
2040 | Read(ReadKind::Copy) => {
2041 // Access authorized
2046 // at this point, we have set up the error reporting state.
2047 return if previously_initialized {
2048 self.report_mutability_error(
2061 fn is_local_ever_initialized(&self,
2063 flow_state: &Flows<'cx, 'gcx, 'tcx>)
2064 -> Option<InitIndex>
2066 let mpi = self.move_data.rev_lookup.find_local(local);
2067 let ii = &self.move_data.init_path_map[mpi];
2069 if flow_state.ever_inits.contains(index) {
2076 /// Adds the place into the used mutable variables set
2077 fn add_used_mut<'d>(
2079 root_place: RootPlace<'d, 'tcx>,
2080 flow_state: &Flows<'cx, 'gcx, 'tcx>,
2084 place: Place::Base(PlaceBase::Local(local)),
2085 is_local_mutation_allowed,
2087 // If the local may have been initialized, and it is now currently being
2088 // mutated, then it is justified to be annotated with the `mut`
2089 // keyword, since the mutation may be a possible reassignment.
2090 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes &&
2091 self.is_local_ever_initialized(*local, flow_state).is_some()
2093 self.used_mut.insert(*local);
2098 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2101 place: place @ Place::Projection(_),
2102 is_local_mutation_allowed: _,
2104 if let Some(field) = self.is_upvar_field_projection(place) {
2105 self.used_mut_upvars.push(field);
2109 place: Place::Base(PlaceBase::Static(..)),
2110 is_local_mutation_allowed: _,
2115 /// Whether this value can be written or borrowed mutably.
2116 /// Returns the root place if the place passed in is a projection.
2119 place: &'d Place<'tcx>,
2120 is_local_mutation_allowed: LocalMutationIsAllowed,
2121 ) -> Result<RootPlace<'d, 'tcx>, &'d Place<'tcx>> {
2123 Place::Base(PlaceBase::Local(local)) => {
2124 let local = &self.mir.local_decls[local];
2125 match local.mutability {
2126 Mutability::Not => match is_local_mutation_allowed {
2127 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2129 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2131 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2133 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2135 LocalMutationIsAllowed::No => Err(place),
2137 Mutability::Mut => Ok(RootPlace {
2139 is_local_mutation_allowed,
2143 // The rules for promotion are made by `qualify_consts`, there wouldn't even be a
2144 // `Place::Promoted` if the promotion weren't 100% legal. So we just forward this
2145 Place::Base(PlaceBase::Static(box Static{kind: StaticKind::Promoted(_), ..})) =>
2148 is_local_mutation_allowed,
2150 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(def_id), .. })) => {
2151 if !self.infcx.tcx.is_mutable_static(def_id) {
2156 is_local_mutation_allowed,
2160 Place::Projection(ref proj) => {
2162 ProjectionElem::Deref => {
2163 let base_ty = proj.base.ty(self.mir, self.infcx.tcx).ty;
2165 // Check the kind of deref to decide
2167 ty::Ref(_, _, mutbl) => {
2169 // Shared borrowed data is never mutable
2170 hir::MutImmutable => Err(place),
2171 // Mutably borrowed data is mutable, but only if we have a
2172 // unique path to the `&mut`
2173 hir::MutMutable => {
2174 let mode = match self.is_upvar_field_projection(place) {
2176 if self.upvars[field.index()].by_ref =>
2178 is_local_mutation_allowed
2180 _ => LocalMutationIsAllowed::Yes,
2183 self.is_mutable(&proj.base, mode)
2187 ty::RawPtr(tnm) => {
2189 // `*const` raw pointers are not mutable
2190 hir::MutImmutable => Err(place),
2191 // `*mut` raw pointers are always mutable, regardless of
2192 // context. The users have to check by themselves.
2193 hir::MutMutable => {
2196 is_local_mutation_allowed,
2201 // `Box<T>` owns its content, so mutable if its location is mutable
2202 _ if base_ty.is_box() => {
2203 self.is_mutable(&proj.base, is_local_mutation_allowed)
2205 // Deref should only be for reference, pointers or boxes
2206 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2209 // All other projections are owned by their base path, so mutable if
2210 // base path is mutable
2211 ProjectionElem::Field(..)
2212 | ProjectionElem::Index(..)
2213 | ProjectionElem::ConstantIndex { .. }
2214 | ProjectionElem::Subslice { .. }
2215 | ProjectionElem::Downcast(..) => {
2216 let upvar_field_projection = self.is_upvar_field_projection(place);
2217 if let Some(field) = upvar_field_projection {
2218 let upvar = &self.upvars[field.index()];
2220 "upvar.mutability={:?} local_mutation_is_allowed={:?} place={:?}",
2221 upvar, is_local_mutation_allowed, place
2223 match (upvar.mutability, is_local_mutation_allowed) {
2224 (Mutability::Not, LocalMutationIsAllowed::No)
2225 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2228 (Mutability::Not, LocalMutationIsAllowed::Yes)
2229 | (Mutability::Mut, _) => {
2230 // Subtle: this is an upvar
2231 // reference, so it looks like
2232 // `self.foo` -- we want to double
2233 // check that the location `*self`
2234 // is mutable (i.e., this is not a
2235 // `Fn` closure). But if that
2236 // check succeeds, we want to
2237 // *blame* the mutability on
2238 // `place` (that is,
2239 // `self.foo`). This is used to
2240 // propagate the info about
2241 // whether mutability declarations
2242 // are used outwards, so that we register
2243 // the outer variable as mutable. Otherwise a
2244 // test like this fails to record the `mut`
2248 // fn foo<F: FnOnce()>(_f: F) { }
2250 // let var = Vec::new();
2256 let _ = self.is_mutable(&proj.base, is_local_mutation_allowed)?;
2259 is_local_mutation_allowed,
2264 self.is_mutable(&proj.base, is_local_mutation_allowed)
2272 /// If `place` is a field projection, and the field is being projected from a closure type,
2273 /// then returns the index of the field being projected. Note that this closure will always
2274 /// be `self` in the current MIR, because that is the only time we directly access the fields
2275 /// of a closure type.
2276 pub fn is_upvar_field_projection(&self, place: &Place<'tcx>) -> Option<Field> {
2277 let (place, by_ref) = if let Place::Projection(ref proj) = place {
2278 if let ProjectionElem::Deref = proj.elem {
2288 Place::Projection(ref proj) => match proj.elem {
2289 ProjectionElem::Field(field, _ty) => {
2290 let tcx = self.infcx.tcx;
2291 let base_ty = proj.base.ty(self.mir, tcx).ty;
2293 if (base_ty.is_closure() || base_ty.is_generator()) &&
2294 (!by_ref || self.upvars[field.index()].by_ref)
2308 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2309 enum NoMovePathFound {
2313 /// The degree of overlap between 2 places for borrow-checking.
2315 /// The places might partially overlap - in this case, we give
2316 /// up and say that they might conflict. This occurs when
2317 /// different fields of a union are borrowed. For example,
2318 /// if `u` is a union, we have no way of telling how disjoint
2319 /// `u.a.x` and `a.b.y` are.
2321 /// The places have the same type, and are either completely disjoint
2322 /// or equal - i.e., they can't "partially" overlap as can occur with
2323 /// unions. This is the "base case" on which we recur for extensions
2326 /// The places are disjoint, so we know all extensions of them
2327 /// will also be disjoint.