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::*;
59 mod mutability_errors;
62 crate mod places_conflict;
68 // FIXME(eddyb) perhaps move this somewhere more centrally.
75 /// If true, the capture is behind a reference.
78 mutability: Mutability,
81 pub fn provide(providers: &mut Providers<'_>) {
82 *providers = Providers {
88 fn mir_borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> BorrowCheckResult<'tcx> {
89 let input_mir = tcx.mir_validated(def_id);
90 debug!("run query mir_borrowck: {}", tcx.def_path_str(def_id));
92 // We are not borrow checking the automatically generated struct/variant constructors
93 // because we want to accept structs such as this (taken from the `linked-hash-map`
96 // struct Qey<Q: ?Sized>(Q);
98 // MIR of this struct constructor looks something like this:
100 // fn Qey(_1: Q) -> Qey<Q>{
101 // let mut _0: Qey<Q>; // return place
104 // (_0.0: Q) = move _1; // bb0[0]: scope 0 at src/main.rs:1:1: 1:26
105 // return; // bb0[1]: scope 0 at src/main.rs:1:1: 1:26
109 // The problem here is that `(_0.0: Q) = move _1;` is valid only if `Q` is
110 // of statically known size, which is not known to be true because of the
111 // `Q: ?Sized` constraint. However, it is true because the constructor can be
112 // called only when `Q` is of statically known size.
113 if tcx.is_constructor(def_id) {
114 return BorrowCheckResult {
115 closure_requirements: None,
116 used_mut_upvars: SmallVec::new(),
120 let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
121 let input_mir: &Mir<'_> = &input_mir.borrow();
122 do_mir_borrowck(&infcx, input_mir, def_id)
124 debug!("mir_borrowck done");
129 fn do_mir_borrowck<'a, 'gcx, 'tcx>(
130 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
131 input_mir: &Mir<'gcx>,
133 ) -> BorrowCheckResult<'gcx> {
134 debug!("do_mir_borrowck(def_id = {:?})", def_id);
137 let attributes = tcx.get_attrs(def_id);
138 let param_env = tcx.param_env(def_id);
141 .as_local_hir_id(def_id)
142 .expect("do_mir_borrowck: non-local DefId");
144 // Gather the upvars of a closure, if any.
145 let tables = tcx.typeck_tables_of(def_id);
146 let upvars: Vec<_> = tables
152 let var_hir_id = upvar_id.var_path.hir_id;
153 let var_node_id = tcx.hir().hir_to_node_id(var_hir_id);
154 let capture = tables.upvar_capture(*upvar_id);
155 let by_ref = match capture {
156 ty::UpvarCapture::ByValue => false,
157 ty::UpvarCapture::ByRef(..) => true,
159 let mut upvar = Upvar {
160 name: tcx.hir().name(var_node_id),
163 mutability: Mutability::Not,
165 let bm = *tables.pat_binding_modes().get(var_hir_id)
166 .expect("missing binding mode");
167 if bm == ty::BindByValue(hir::MutMutable) {
168 upvar.mutability = Mutability::Mut;
174 // Replace all regions with fresh inference variables. This
175 // requires first making our own copy of the MIR. This copy will
176 // be modified (in place) to contain non-lexical lifetimes. It
177 // will have a lifetime tied to the inference context.
178 let mut mir: Mir<'tcx> = input_mir.clone();
179 let free_regions = nll::replace_regions_in_mir(infcx, def_id, param_env, &mut mir);
180 let mir = &mir; // no further changes
181 let location_table = &LocationTable::new(mir);
183 let mut errors_buffer = Vec::new();
184 let (move_data, move_errors): (MoveData<'tcx>, Option<Vec<(Place<'tcx>, MoveError<'tcx>)>>) =
185 match MoveData::gather_moves(mir, tcx) {
186 Ok(move_data) => (move_data, None),
187 Err((move_data, move_errors)) => (move_data, Some(move_errors)),
190 let mdpe = MoveDataParamEnv {
191 move_data: move_data,
192 param_env: param_env,
195 let dead_unwinds = BitSet::new_empty(mir.basic_blocks().len());
196 let mut flow_inits = FlowAtLocation::new(do_dataflow(
202 MaybeInitializedPlaces::new(tcx, mir, &mdpe),
203 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
206 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind_by_hir_id(id).is_fn_or_closure();
207 let borrow_set = Rc::new(BorrowSet::build(
208 tcx, mir, locals_are_invalidated_at_exit, &mdpe.move_data));
210 // If we are in non-lexical mode, compute the non-lexical lifetimes.
211 let (regioncx, polonius_output, opt_closure_req) = nll::compute_regions(
225 // The various `flow_*` structures can be large. We drop `flow_inits` here
226 // so it doesn't overlap with the others below. This reduces peak memory
227 // usage significantly on some benchmarks.
230 let regioncx = Rc::new(regioncx);
232 let flow_borrows = FlowAtLocation::new(do_dataflow(
238 Borrows::new(tcx, mir, regioncx.clone(), &borrow_set),
239 |rs, i| DebugFormatted::new(&rs.location(i)),
241 let flow_uninits = FlowAtLocation::new(do_dataflow(
247 MaybeUninitializedPlaces::new(tcx, mir, &mdpe),
248 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
250 let flow_ever_inits = FlowAtLocation::new(do_dataflow(
256 EverInitializedPlaces::new(tcx, mir, &mdpe),
257 |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
260 let movable_generator = match tcx.hir().get_by_hir_id(id) {
261 Node::Expr(&hir::Expr {
262 node: hir::ExprKind::Closure(.., Some(hir::GeneratorMovability::Static)),
268 let dominators = mir.dominators();
270 let mut mbcx = MirBorrowckCtxt {
274 move_data: &mdpe.move_data,
277 locals_are_invalidated_at_exit,
278 access_place_error_reported: Default::default(),
279 reservation_error_reported: Default::default(),
280 reservation_warnings: Default::default(),
281 move_error_reported: BTreeMap::new(),
282 uninitialized_error_reported: Default::default(),
284 nonlexical_regioncx: regioncx,
285 used_mut: Default::default(),
286 used_mut_upvars: SmallVec::new(),
292 let mut state = Flows::new(
299 if let Some(errors) = move_errors {
300 mbcx.report_move_errors(errors);
302 mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
304 // Convert any reservation warnings into lints.
305 let reservation_warnings = mem::replace(&mut mbcx.reservation_warnings, Default::default());
306 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
307 let mut initial_diag =
308 mbcx.report_conflicting_borrow(location, (&place, span), bk, &borrow);
310 let lint_root = if let ClearCrossCrate::Set(ref vsi) = mbcx.mir.source_scope_local_data {
311 let scope = mbcx.mir.source_info(location).scope;
317 // Span and message don't matter; we overwrite them below anyway
318 let mut diag = mbcx.infcx.tcx.struct_span_lint_hir(
319 MUTABLE_BORROW_RESERVATION_CONFLICT, lint_root, DUMMY_SP, "");
321 diag.message = initial_diag.styled_message().clone();
322 diag.span = initial_diag.span.clone();
324 initial_diag.cancel();
325 diag.buffer(&mut mbcx.errors_buffer);
328 // For each non-user used mutable variable, check if it's been assigned from
329 // a user-declared local. If so, then put that local into the used_mut set.
330 // Note that this set is expected to be small - only upvars from closures
331 // would have a chance of erroneously adding non-user-defined mutable vars
333 let temporary_used_locals: FxHashSet<Local> = mbcx.used_mut.iter()
334 .filter(|&local| mbcx.mir.local_decls[*local].is_user_variable.is_none())
337 // For the remaining unused locals that are marked as mutable, we avoid linting any that
338 // were never initialized. These locals may have been removed as unreachable code; or will be
339 // linted as unused variables.
340 let unused_mut_locals = mbcx.mir.mut_vars_iter()
341 .filter(|local| !mbcx.used_mut.contains(local))
343 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
345 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
346 let used_mut = mbcx.used_mut;
347 for local in mbcx.mir.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
348 if let ClearCrossCrate::Set(ref vsi) = mbcx.mir.source_scope_local_data {
349 let local_decl = &mbcx.mir.local_decls[local];
351 // Skip implicit `self` argument for closures
352 if local.index() == 1 && tcx.is_closure(mbcx.mir_def_id) {
356 // Skip over locals that begin with an underscore or have no name
357 match local_decl.name {
358 Some(name) => if name.as_str().starts_with("_") {
364 let span = local_decl.source_info.span;
365 if span.compiler_desugaring_kind().is_some() {
366 // If the `mut` arises as part of a desugaring, we should ignore it.
370 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
371 tcx.struct_span_lint_hir(
373 vsi[local_decl.source_info.scope].lint_root,
375 "variable does not need to be mutable",
377 .span_suggestion_short(
381 Applicability::MachineApplicable,
387 // Buffer any move errors that we collected and de-duplicated.
388 for (_, (_, diag)) in mbcx.move_error_reported {
389 diag.buffer(&mut mbcx.errors_buffer);
392 if !mbcx.errors_buffer.is_empty() {
393 mbcx.errors_buffer.sort_by_key(|diag| diag.span.primary_span());
395 if tcx.migrate_borrowck() {
396 // When borrowck=migrate, check if AST-borrowck would
397 // error on the given code.
399 // rust-lang/rust#55492, rust-lang/rust#58776 check the base def id
400 // for errors. AST borrowck is responsible for aggregating
401 // `signalled_any_error` from all of the nested closures here.
402 let base_def_id = tcx.closure_base_def_id(def_id);
404 match tcx.borrowck(base_def_id).signalled_any_error {
405 SignalledError::NoErrorsSeen => {
406 // if AST-borrowck signalled no errors, then
407 // downgrade all the buffered MIR-borrowck errors
410 for err in mbcx.errors_buffer.iter_mut() {
411 downgrade_if_error(err);
414 SignalledError::SawSomeError => {
415 // if AST-borrowck signalled a (cancelled) error,
416 // then we will just emit the buffered
417 // MIR-borrowck errors as normal.
422 for diag in mbcx.errors_buffer.drain(..) {
423 DiagnosticBuilder::new_diagnostic(mbcx.infcx.tcx.sess.diagnostic(), diag).emit();
427 let result = BorrowCheckResult {
428 closure_requirements: opt_closure_req,
429 used_mut_upvars: mbcx.used_mut_upvars,
432 debug!("do_mir_borrowck: result = {:#?}", result);
437 fn downgrade_if_error(diag: &mut Diagnostic) {
439 diag.level = Level::Warning;
441 "this error has been downgraded to a warning for backwards \
442 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",
447 "for more information, try `rustc --explain E0729`"
452 pub struct MirBorrowckCtxt<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
453 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
456 move_data: &'cx MoveData<'tcx>,
458 /// Map from MIR `Location` to `LocationIndex`; created
459 /// when MIR borrowck begins.
460 location_table: &'cx LocationTable,
462 movable_generator: bool,
463 /// This keeps track of whether local variables are free-ed when the function
464 /// exits even without a `StorageDead`, which appears to be the case for
467 /// I'm not sure this is the right approach - @eddyb could you try and
469 locals_are_invalidated_at_exit: bool,
470 /// This field keeps track of when borrow errors are reported in the access_place function
471 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
472 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
473 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
475 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
476 /// This field keeps track of when borrow conflict errors are reported
477 /// for reservations, so that we don't report seemingly duplicate
478 /// errors for corresponding activations.
480 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
481 // but it is currently inconvenient to track down the `BorrowIndex`
482 // at the time we detect and report a reservation error.
483 reservation_error_reported: FxHashSet<Place<'tcx>>,
484 /// Migration warnings to be reported for #56254. We delay reporting these
485 /// so that we can suppress the warning if there's a corresponding error
486 /// for the activation of the borrow.
487 reservation_warnings: FxHashMap<
489 (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)
491 /// This field keeps track of move errors that are to be reported for given move indicies.
493 /// There are situations where many errors can be reported for a single move out (see #53807)
494 /// and we want only the best of those errors.
496 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
497 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
498 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
499 /// all move errors have been reported, any diagnostics in this map are added to the buffer
502 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
503 /// when errors in the map are being re-added to the error buffer so that errors with the
504 /// same primary span come out in a consistent order.
505 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (Place<'tcx>, DiagnosticBuilder<'cx>)>,
506 /// This field keeps track of errors reported in the checking of uninitialized variables,
507 /// so that we don't report seemingly duplicate errors.
508 uninitialized_error_reported: FxHashSet<Place<'tcx>>,
509 /// Errors to be reported buffer
510 errors_buffer: Vec<Diagnostic>,
511 /// This field keeps track of all the local variables that are declared mut and are mutated.
512 /// Used for the warning issued by an unused mutable local variable.
513 used_mut: FxHashSet<Local>,
514 /// If the function we're checking is a closure, then we'll need to report back the list of
515 /// mutable upvars that have been used. This field keeps track of them.
516 used_mut_upvars: SmallVec<[Field; 8]>,
517 /// Non-lexical region inference context, if NLL is enabled. This
518 /// contains the results from region inference and lets us e.g.
519 /// find out which CFG points are contained in each borrow region.
520 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
522 /// The set of borrows extracted from the MIR
523 borrow_set: Rc<BorrowSet<'tcx>>,
525 /// Dominators for MIR
526 dominators: Dominators<BasicBlock>,
528 /// Information about upvars not necessarily preserved in types or MIR
533 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
534 // 2. loans made in overlapping scopes do not conflict
535 // 3. assignments do not affect things loaned out as immutable
536 // 4. moves do not affect things loaned out in any way
537 impl<'cx, 'gcx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
538 type FlowState = Flows<'cx, 'gcx, 'tcx>;
540 fn mir(&self) -> &'cx Mir<'tcx> {
544 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
545 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
548 fn visit_statement_entry(
551 stmt: &Statement<'tcx>,
552 flow_state: &Self::FlowState,
555 "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
556 location, stmt, flow_state
558 let span = stmt.source_info.span;
560 self.check_activations(location, span, flow_state);
563 StatementKind::Assign(ref lhs, ref rhs) => {
578 StatementKind::FakeRead(_, ref place) => {
579 // Read for match doesn't access any memory and is used to
580 // assert that a place is safe and live. So we don't have to
581 // do any checks here.
583 // FIXME: Remove check that the place is initialized. This is
584 // needed for now because matches don't have never patterns yet.
585 // So this is the only place we prevent
589 self.check_if_path_or_subpath_is_moved(
591 InitializationRequiringAction::Use,
596 StatementKind::SetDiscriminant {
608 StatementKind::InlineAsm(ref asm) => {
609 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
611 // FIXME(eddyb) indirect inline asm outputs should
612 // be encoded through MIR place derefs instead.
616 (Deep, Read(ReadKind::Copy)),
617 LocalMutationIsAllowed::No,
620 self.check_if_path_or_subpath_is_moved(
622 InitializationRequiringAction::Use,
630 if o.is_rw { Deep } else { Shallow(None) },
631 if o.is_rw { WriteAndRead } else { JustWrite },
636 for (_, input) in asm.inputs.iter() {
637 self.consume_operand(location, (input, span), flow_state);
641 | StatementKind::AscribeUserType(..)
642 | StatementKind::Retag { .. }
643 | StatementKind::StorageLive(..) => {
644 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
647 StatementKind::StorageDead(local) => {
650 (&Place::Base(PlaceBase::Local(local)), span),
651 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
652 LocalMutationIsAllowed::Yes,
659 fn visit_terminator_entry(
662 term: &Terminator<'tcx>,
663 flow_state: &Self::FlowState,
667 "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
668 location, term, flow_state
670 let span = term.source_info.span;
672 self.check_activations(location, span, flow_state);
675 TerminatorKind::SwitchInt {
681 self.consume_operand(loc, (discr, span), flow_state);
683 TerminatorKind::Drop {
684 location: ref drop_place,
688 let gcx = self.infcx.tcx.global_tcx();
690 // Compute the type with accurate region information.
691 let drop_place_ty = drop_place.ty(self.mir, self.infcx.tcx);
693 // Erase the regions.
694 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
696 // "Lift" into the gcx -- once regions are erased, this type should be in the
697 // global arenas; this "lift" operation basically just asserts that is true, but
698 // that is useful later.
699 let drop_place_ty = gcx.lift(&drop_place_ty).unwrap();
701 debug!("visit_terminator_drop \
702 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
703 loc, term, drop_place, drop_place_ty, span);
708 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
709 LocalMutationIsAllowed::Yes,
713 TerminatorKind::DropAndReplace {
714 location: ref drop_place,
715 value: ref new_value,
726 self.consume_operand(
732 TerminatorKind::Call {
739 self.consume_operand(loc, (func, span), flow_state);
741 self.consume_operand(
747 if let Some((ref dest, _ /*bb*/)) = *destination {
757 TerminatorKind::Assert {
764 self.consume_operand(loc, (cond, span), flow_state);
765 use rustc::mir::interpret::InterpError::BoundsCheck;
766 if let BoundsCheck { ref len, ref index } = *msg {
767 self.consume_operand(loc, (len, span), flow_state);
768 self.consume_operand(loc, (index, span), flow_state);
772 TerminatorKind::Yield {
777 self.consume_operand(loc, (value, span), flow_state);
779 if self.movable_generator {
780 // Look for any active borrows to locals
781 let borrow_set = self.borrow_set.clone();
782 flow_state.with_outgoing_borrows(|borrows| {
784 let borrow = &borrow_set[i];
785 self.check_for_local_borrow(borrow, span);
791 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
792 // Returning from the function implicitly kills storage for all locals and statics.
793 // Often, the storage will already have been killed by an explicit
794 // StorageDead, but we don't always emit those (notably on unwind paths),
795 // so this "extra check" serves as a kind of backup.
796 let borrow_set = self.borrow_set.clone();
797 flow_state.with_outgoing_borrows(|borrows| {
799 let borrow = &borrow_set[i];
800 self.check_for_invalidation_at_exit(loc, borrow, span);
804 TerminatorKind::Goto { target: _ }
805 | TerminatorKind::Abort
806 | TerminatorKind::Unreachable
807 | TerminatorKind::FalseEdges {
809 imaginary_targets: _,
811 | TerminatorKind::FalseUnwind {
815 // no data used, thus irrelevant to borrowck
821 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
827 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
828 use self::AccessDepth::{Deep, Shallow};
830 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
831 enum ArtificialField {
836 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
838 /// From the RFC: "A *shallow* access means that the immediate
839 /// fields reached at P are accessed, but references or pointers
840 /// found within are not dereferenced. Right now, the only access
841 /// that is shallow is an assignment like `x = ...;`, which would
842 /// be a *shallow write* of `x`."
843 Shallow(Option<ArtificialField>),
845 /// From the RFC: "A *deep* access means that all data reachable
846 /// through the given place may be invalidated or accesses by
850 /// Access is Deep only when there is a Drop implementation that
851 /// can reach the data behind the reference.
855 /// Kind of access to a value: read or write
856 /// (For informational purposes only)
857 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
859 /// From the RFC: "A *read* means that the existing data may be
860 /// read, but will not be changed."
863 /// From the RFC: "A *write* means that the data may be mutated to
864 /// new values or otherwise invalidated (for example, it could be
865 /// de-initialized, as in a move operation).
868 /// For two-phase borrows, we distinguish a reservation (which is treated
869 /// like a Read) from an activation (which is treated like a write), and
870 /// each of those is furthermore distinguished from Reads/Writes above.
871 Reservation(WriteKind),
872 Activation(WriteKind, BorrowIndex),
875 /// Kind of read access to a value
876 /// (For informational purposes only)
877 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
883 /// Kind of write access to a value
884 /// (For informational purposes only)
885 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
888 MutableBorrow(BorrowKind),
893 /// When checking permissions for a place access, this flag is used to indicate that an immutable
894 /// local place can be mutated.
896 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
897 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
898 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
899 // `is_declared_mutable()`.
900 // - Take flow state into consideration in `is_assignable()` for local variables.
901 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
902 enum LocalMutationIsAllowed {
904 /// We want use of immutable upvars to cause a "write to immutable upvar"
905 /// error, not an "reassignment" error.
910 #[derive(Copy, Clone, Debug)]
911 enum InitializationRequiringAction {
920 struct RootPlace<'d, 'tcx: 'd> {
921 place: &'d Place<'tcx>,
922 is_local_mutation_allowed: LocalMutationIsAllowed,
925 impl InitializationRequiringAction {
926 fn as_noun(self) -> &'static str {
928 InitializationRequiringAction::Update => "update",
929 InitializationRequiringAction::Borrow => "borrow",
930 InitializationRequiringAction::MatchOn => "use", // no good noun
931 InitializationRequiringAction::Use => "use",
932 InitializationRequiringAction::Assignment => "assign",
933 InitializationRequiringAction::PartialAssignment => "assign to part",
937 fn as_verb_in_past_tense(self) -> &'static str {
939 InitializationRequiringAction::Update => "updated",
940 InitializationRequiringAction::Borrow => "borrowed",
941 InitializationRequiringAction::MatchOn => "matched on",
942 InitializationRequiringAction::Use => "used",
943 InitializationRequiringAction::Assignment => "assigned",
944 InitializationRequiringAction::PartialAssignment => "partially assigned",
949 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
950 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
951 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
952 /// place is initialized and (b) it is not borrowed in some way that would prevent this
955 /// Returns `true` if an error is reported.
959 place_span: (&Place<'tcx>, Span),
960 kind: (AccessDepth, ReadOrWrite),
961 is_local_mutation_allowed: LocalMutationIsAllowed,
962 flow_state: &Flows<'cx, 'gcx, 'tcx>,
966 if let Activation(_, borrow_index) = rw {
967 if self.reservation_error_reported.contains(&place_span.0) {
969 "skipping access_place for activation of invalid reservation \
970 place: {:?} borrow_index: {:?}",
971 place_span.0, borrow_index
977 // Check is_empty() first because it's the common case, and doing that
978 // way we avoid the clone() call.
979 if !self.access_place_error_reported.is_empty() &&
981 .access_place_error_reported
982 .contains(&(place_span.0.clone(), place_span.1))
985 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
991 let mutability_error =
992 self.check_access_permissions(
995 is_local_mutation_allowed,
1000 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
1002 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
1003 // Suppress this warning when there's an error being emited for the
1004 // same borrow: fixing the error is likely to fix the warning.
1005 self.reservation_warnings.remove(&borrow_idx);
1008 if conflict_error || mutability_error {
1010 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
1014 self.access_place_error_reported
1015 .insert((place_span.0.clone(), place_span.1));
1019 fn check_access_for_conflict(
1022 place_span: (&Place<'tcx>, Span),
1025 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1028 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1029 location, place_span, sd, rw,
1032 let mut error_reported = false;
1033 let tcx = self.infcx.tcx;
1035 let location_table = self.location_table.start_index(location);
1036 let borrow_set = self.borrow_set.clone();
1037 each_borrow_involving_path(
1044 flow_state.borrows_in_scope(location_table),
1045 |this, borrow_index, borrow| match (rw, borrow.kind) {
1046 // Obviously an activation is compatible with its own
1047 // reservation (or even prior activating uses of same
1048 // borrow); so don't check if they interfere.
1050 // NOTE: *reservations* do conflict with themselves;
1051 // thus aren't injecting unsoundenss w/ this check.)
1052 (Activation(_, activating), _) if activating == borrow_index => {
1054 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1055 skipping {:?} b/c activation of same borrow_index",
1059 (borrow_index, borrow),
1064 (Read(_), BorrowKind::Shared)
1065 | (Read(_), BorrowKind::Shallow)
1066 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
1067 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
1071 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1072 // Handled by initialization checks.
1076 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
1077 // Reading from mere reservations of mutable-borrows is OK.
1078 if !is_active(&this.dominators, borrow, location) {
1079 assert!(allow_two_phase_borrow(borrow.kind));
1080 return Control::Continue;
1083 error_reported = true;
1086 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1087 .buffer(&mut this.errors_buffer);
1089 ReadKind::Borrow(bk) => {
1090 this.report_conflicting_borrow(location, place_span, bk, borrow)
1091 .buffer(&mut this.errors_buffer);
1097 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
1098 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared) if {
1099 tcx.migrate_borrowck()
1101 let bi = this.borrow_set.location_map[&location];
1103 "recording invalid reservation of place: {:?} with \
1104 borrow index {:?} as warning",
1108 // rust-lang/rust#56254 - This was previously permitted on
1109 // the 2018 edition so we emit it as a warning. We buffer
1110 // these sepately so that we only emit a warning if borrow
1111 // checking was otherwise successful.
1112 this.reservation_warnings.insert(
1114 (place_span.0.clone(), place_span.1, location, bk, borrow.clone()),
1117 // Don't suppress actual errors.
1121 (Reservation(kind), _)
1122 | (Activation(kind, _), _)
1123 | (Write(kind), _) => {
1125 Reservation(..) => {
1127 "recording invalid reservation of \
1131 this.reservation_error_reported.insert(place_span.0.clone());
1133 Activation(_, activating) => {
1135 "observing check_place for activation of \
1136 borrow_index: {:?}",
1140 Read(..) | Write(..) => {}
1143 error_reported = true;
1145 WriteKind::MutableBorrow(bk) => {
1146 this.report_conflicting_borrow(location, place_span, bk, borrow)
1147 .buffer(&mut this.errors_buffer);
1149 WriteKind::StorageDeadOrDrop => {
1150 this.report_borrowed_value_does_not_live_long_enough(
1156 WriteKind::Mutate => {
1157 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1159 WriteKind::Move => {
1160 this.report_move_out_while_borrowed(location, place_span, borrow)
1174 place_span: (&Place<'tcx>, Span),
1177 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1179 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1181 MutateMode::WriteAndRead => {
1182 self.check_if_path_or_subpath_is_moved(
1184 InitializationRequiringAction::Update,
1189 MutateMode::JustWrite => {
1190 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1194 // Special case: you can assign a immutable local variable
1195 // (e.g., `x = ...`) so long as it has never been initialized
1196 // before (at this point in the flow).
1197 if let &Place::Base(PlaceBase::Local(local)) = place_span.0 {
1198 if let Mutability::Not = self.mir.local_decls[local].mutability {
1199 // check for reassignments to immutable local variables
1200 self.check_if_reassignment_to_immutable_state(
1210 // Otherwise, use the normal access permission rules.
1214 (kind, Write(WriteKind::Mutate)),
1215 LocalMutationIsAllowed::No,
1223 (rvalue, span): (&Rvalue<'tcx>, Span),
1224 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1227 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1228 let access_kind = match bk {
1229 BorrowKind::Shallow => {
1230 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1232 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1233 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1234 let wk = WriteKind::MutableBorrow(bk);
1235 if allow_two_phase_borrow(bk) {
1236 (Deep, Reservation(wk))
1247 LocalMutationIsAllowed::No,
1251 let action = if bk == BorrowKind::Shallow {
1252 InitializationRequiringAction::MatchOn
1254 InitializationRequiringAction::Borrow
1257 self.check_if_path_or_subpath_is_moved(
1265 Rvalue::Use(ref operand)
1266 | Rvalue::Repeat(ref operand, _)
1267 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1268 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1269 self.consume_operand(location, (operand, span), flow_state)
1272 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1273 let af = match *rvalue {
1274 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1275 Rvalue::Discriminant(..) => None,
1276 _ => unreachable!(),
1281 (Shallow(af), Read(ReadKind::Copy)),
1282 LocalMutationIsAllowed::No,
1285 self.check_if_path_or_subpath_is_moved(
1287 InitializationRequiringAction::Use,
1293 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1294 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1295 self.consume_operand(location, (operand1, span), flow_state);
1296 self.consume_operand(location, (operand2, span), flow_state);
1299 Rvalue::NullaryOp(_op, _ty) => {
1300 // nullary ops take no dynamic input; no borrowck effect.
1302 // FIXME: is above actually true? Do we want to track
1303 // the fact that uninitialized data can be created via
1307 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1308 // We need to report back the list of mutable upvars that were
1309 // moved into the closure and subsequently used by the closure,
1310 // in order to populate our used_mut set.
1311 match **aggregate_kind {
1312 AggregateKind::Closure(def_id, _)
1313 | AggregateKind::Generator(def_id, _, _) => {
1314 let BorrowCheckResult {
1316 } = self.infcx.tcx.mir_borrowck(def_id);
1317 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1318 for field in used_mut_upvars {
1319 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1322 AggregateKind::Adt(..)
1323 | AggregateKind::Array(..)
1324 | AggregateKind::Tuple { .. } => (),
1327 for operand in operands {
1328 self.consume_operand(location, (operand, span), flow_state);
1334 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1335 let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1337 Place::Projection { .. } => {
1338 if let Some(field) = this.is_upvar_field_projection(place) {
1339 this.used_mut_upvars.push(field);
1342 Place::Base(PlaceBase::Local(local)) => {
1343 this.used_mut.insert(local);
1345 Place::Base(PlaceBase::Static(_)) => {}
1349 // This relies on the current way that by-value
1350 // captures of a closure are copied/moved directly
1351 // when generating MIR.
1353 Operand::Move(Place::Base(PlaceBase::Local(local)))
1354 | Operand::Copy(Place::Base(PlaceBase::Local(local)))
1355 if self.mir.local_decls[local].is_user_variable.is_none() =>
1357 if self.mir.local_decls[local].ty.is_mutable_pointer() {
1358 // The variable will be marked as mutable by the borrow.
1361 // This is an edge case where we have a `move` closure
1362 // inside a non-move closure, and the inner closure
1363 // contains a mutation:
1366 // || { move || { i += 1; }; };
1368 // In this case our usual strategy of assuming that the
1369 // variable will be captured by mutable reference is
1370 // wrong, since `i` can be copied into the inner
1371 // closure from a shared reference.
1373 // As such we have to search for the local that this
1374 // capture comes from and mark it as being used as mut.
1376 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1377 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1378 &self.move_data.inits[init_index]
1380 bug!("temporary should be initialized exactly once")
1383 let loc = match init.location {
1384 InitLocation::Statement(stmt) => stmt,
1385 _ => bug!("temporary initialized in arguments"),
1388 let bbd = &self.mir[loc.block];
1389 let stmt = &bbd.statements[loc.statement_index];
1390 debug!("temporary assigned in: stmt={:?}", stmt);
1392 if let StatementKind::Assign(_, box Rvalue::Ref(_, _, ref source)) = stmt.kind {
1393 propagate_closure_used_mut_place(self, source);
1395 bug!("closures should only capture user variables \
1396 or references to user variables");
1399 Operand::Move(ref place)
1400 | Operand::Copy(ref place) => {
1401 propagate_closure_used_mut_place(self, place);
1403 Operand::Constant(..) => {}
1410 (operand, span): (&Operand<'tcx>, Span),
1411 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1414 Operand::Copy(ref place) => {
1415 // copy of place: check if this is "copy of frozen path"
1416 // (FIXME: see check_loans.rs)
1420 (Deep, Read(ReadKind::Copy)),
1421 LocalMutationIsAllowed::No,
1425 // Finally, check if path was already moved.
1426 self.check_if_path_or_subpath_is_moved(
1428 InitializationRequiringAction::Use,
1433 Operand::Move(ref place) => {
1434 // move of place: check if this is move of already borrowed path
1438 (Deep, Write(WriteKind::Move)),
1439 LocalMutationIsAllowed::Yes,
1443 // Finally, check if path was already moved.
1444 self.check_if_path_or_subpath_is_moved(
1446 InitializationRequiringAction::Use,
1451 Operand::Constant(_) => {}
1455 /// Checks whether a borrow of this place is invalidated when the function
1457 fn check_for_invalidation_at_exit(
1460 borrow: &BorrowData<'tcx>,
1463 debug!("check_for_invalidation_at_exit({:?})", borrow);
1464 let place = &borrow.borrowed_place;
1465 let root_place = self.prefixes(place, PrefixSet::All).last().unwrap();
1467 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1468 // we just know that all locals are dropped at function exit (otherwise
1469 // we'll have a memory leak) and assume that all statics have a destructor.
1471 // FIXME: allow thread-locals to borrow other thread locals?
1472 let (might_be_alive, will_be_dropped) = match root_place {
1473 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Promoted(_), .. })) => {
1476 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(_), .. })) => {
1477 // Thread-locals might be dropped after the function exits, but
1478 // "true" statics will never be.
1479 (true, self.is_place_thread_local(&root_place))
1481 Place::Base(PlaceBase::Local(_)) => {
1482 // Locals are always dropped at function exit, and if they
1483 // have a destructor it would've been called already.
1484 (false, self.locals_are_invalidated_at_exit)
1486 Place::Projection(..) => {
1487 bug!("root of {:?} is a projection ({:?})?", place, root_place)
1491 if !will_be_dropped {
1493 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1499 let sd = if might_be_alive { Deep } else { Shallow(None) };
1501 if places_conflict::borrow_conflicts_with_place(
1508 places_conflict::PlaceConflictBias::Overlap,
1510 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1511 // FIXME: should be talking about the region lifetime instead
1512 // of just a span here.
1513 let span = self.infcx.tcx.sess.source_map().end_point(span);
1514 self.report_borrowed_value_does_not_live_long_enough(
1523 /// Reports an error if this is a borrow of local data.
1524 /// This is called for all Yield statements on movable generators
1525 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1526 debug!("check_for_local_borrow({:?})", borrow);
1528 if borrow_of_local_data(&borrow.borrowed_place) {
1529 let err = self.infcx.tcx
1530 .cannot_borrow_across_generator_yield(
1531 self.retrieve_borrow_spans(borrow).var_or_use(),
1536 err.buffer(&mut self.errors_buffer);
1540 fn check_activations(
1544 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1546 // Two-phase borrow support: For each activation that is newly
1547 // generated at this statement, check if it interferes with
1549 let borrow_set = self.borrow_set.clone();
1550 for &borrow_index in borrow_set.activations_at_location(location) {
1551 let borrow = &borrow_set[borrow_index];
1553 // only mutable borrows should be 2-phase
1554 assert!(match borrow.kind {
1555 BorrowKind::Shared | BorrowKind::Shallow => false,
1556 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1561 (&borrow.borrowed_place, span),
1564 Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1566 LocalMutationIsAllowed::No,
1569 // We do not need to call `check_if_path_or_subpath_is_moved`
1570 // again, as we already called it when we made the
1571 // initial reservation.
1576 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1577 fn check_if_reassignment_to_immutable_state(
1581 place_span: (&Place<'tcx>, Span),
1582 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1584 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1586 // Check if any of the initializiations of `local` have happened yet:
1587 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1588 // And, if so, report an error.
1589 let init = &self.move_data.inits[init_index];
1590 let span = init.span(&self.mir);
1591 self.report_illegal_reassignment(
1592 location, place_span, span, place_span.0
1597 fn check_if_full_path_is_moved(
1600 desired_action: InitializationRequiringAction,
1601 place_span: (&Place<'tcx>, Span),
1602 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1604 let maybe_uninits = &flow_state.uninits;
1608 // 1. Move of `a.b.c`, use of `a.b.c`
1609 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1610 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1611 // partial initialization support, one might have `a.x`
1612 // initialized but not `a.b`.
1616 // 4. Move of `a.b.c`, use of `a.b.d`
1617 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1618 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1619 // must have been initialized for the use to be sound.
1620 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1622 // The dataflow tracks shallow prefixes distinctly (that is,
1623 // field-accesses on P distinctly from P itself), in order to
1624 // track substructure initialization separately from the whole
1627 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1628 // which we have a MovePath is `a.b`, then that means that the
1629 // initialization state of `a.b` is all we need to inspect to
1630 // know if `a.b.c` is valid (and from that we infer that the
1631 // dereference and `.d` access is also valid, since we assume
1632 // `a.b.c` is assigned a reference to a initialized and
1633 // well-formed record structure.)
1635 // Therefore, if we seek out the *closest* prefix for which we
1636 // have a MovePath, that should capture the initialization
1637 // state for the place scenario.
1639 // This code covers scenarios 1, 2, and 3.
1641 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1642 match self.move_path_closest_to(place_span.0) {
1643 Ok((prefix, mpi)) => {
1644 if maybe_uninits.contains(mpi) {
1645 self.report_use_of_moved_or_uninitialized(
1648 (prefix, place_span.0, place_span.1),
1651 return; // don't bother finding other problems.
1654 Err(NoMovePathFound::ReachedStatic) => {
1655 // Okay: we do not build MoveData for static variables
1656 } // Only query longest prefix with a MovePath, not further
1657 // ancestors; dataflow recurs on children when parents
1658 // move (to support partial (re)inits).
1660 // (I.e., querying parents breaks scenario 7; but may want
1661 // to do such a query based on partial-init feature-gate.)
1665 fn check_if_path_or_subpath_is_moved(
1668 desired_action: InitializationRequiringAction,
1669 place_span: (&Place<'tcx>, Span),
1670 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1672 let maybe_uninits = &flow_state.uninits;
1676 // 1. Move of `a.b.c`, use of `a` or `a.b`
1677 // partial initialization support, one might have `a.x`
1678 // initialized but not `a.b`.
1679 // 2. All bad scenarios from `check_if_full_path_is_moved`
1683 // 3. Move of `a.b.c`, use of `a.b.d`
1684 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1685 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1686 // must have been initialized for the use to be sound.
1687 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1689 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1691 // A move of any shallow suffix of `place` also interferes
1692 // with an attempt to use `place`. This is scenario 3 above.
1694 // (Distinct from handling of scenarios 1+2+4 above because
1695 // `place` does not interfere with suffixes of its prefixes,
1696 // e.g., `a.b.c` does not interfere with `a.b.d`)
1698 // This code covers scenario 1.
1700 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1701 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1702 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1703 self.report_use_of_moved_or_uninitialized(
1706 (place_span.0, place_span.0, place_span.1),
1709 return; // don't bother finding other problems.
1714 /// Currently MoveData does not store entries for all places in
1715 /// the input MIR. For example it will currently filter out
1716 /// places that are Copy; thus we do not track places of shared
1717 /// reference type. This routine will walk up a place along its
1718 /// prefixes, searching for a foundational place that *is*
1719 /// tracked in the MoveData.
1721 /// An Err result includes a tag indicated why the search failed.
1722 /// Currently this can only occur if the place is built off of a
1723 /// static variable, as we do not track those in the MoveData.
1724 fn move_path_closest_to<'a>(
1726 place: &'a Place<'tcx>,
1727 ) -> Result<(&'a Place<'tcx>, MovePathIndex), NoMovePathFound> where 'cx: 'a {
1728 let mut last_prefix = place;
1729 for prefix in self.prefixes(place, PrefixSet::All) {
1730 if let Some(mpi) = self.move_path_for_place(prefix) {
1731 return Ok((prefix, mpi));
1733 last_prefix = prefix;
1735 match *last_prefix {
1736 Place::Base(PlaceBase::Local(_)) => panic!("should have move path for every Local"),
1737 Place::Projection(_) => panic!("PrefixSet::All meant don't stop for Projection"),
1738 Place::Base(PlaceBase::Static(_)) => Err(NoMovePathFound::ReachedStatic),
1742 fn move_path_for_place(&mut self, place: &Place<'tcx>) -> Option<MovePathIndex> {
1743 // If returns None, then there is no move path corresponding
1744 // to a direct owner of `place` (which means there is nothing
1745 // that borrowck tracks for its analysis).
1747 match self.move_data.rev_lookup.find(place) {
1748 LookupResult::Parent(_) => None,
1749 LookupResult::Exact(mpi) => Some(mpi),
1753 fn check_if_assigned_path_is_moved(
1756 (place, span): (&Place<'tcx>, Span),
1757 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1759 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1760 // recur down place; dispatch to external checks when necessary
1761 let mut place = place;
1764 Place::Base(PlaceBase::Local(_)) | Place::Base(PlaceBase::Static(_)) => {
1765 // assigning to `x` does not require `x` be initialized.
1768 Place::Projection(ref proj) => {
1769 let Projection { ref base, ref elem } = **proj;
1771 ProjectionElem::Index(_/*operand*/) |
1772 ProjectionElem::ConstantIndex { .. } |
1773 // assigning to P[i] requires P to be valid.
1774 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1775 // assigning to (P->variant) is okay if assigning to `P` is okay
1777 // FIXME: is this true even if P is a adt with a dtor?
1780 // assigning to (*P) requires P to be initialized
1781 ProjectionElem::Deref => {
1782 self.check_if_full_path_is_moved(
1783 location, InitializationRequiringAction::Use,
1784 (base, span), flow_state);
1785 // (base initialized; no need to
1790 ProjectionElem::Subslice { .. } => {
1791 panic!("we don't allow assignments to subslices, location: {:?}",
1795 ProjectionElem::Field(..) => {
1796 // if type of `P` has a dtor, then
1797 // assigning to `P.f` requires `P` itself
1798 // be already initialized
1799 let tcx = self.infcx.tcx;
1800 match base.ty(self.mir, tcx).ty.sty {
1801 ty::Adt(def, _) if def.has_dtor(tcx) => {
1802 self.check_if_path_or_subpath_is_moved(
1803 location, InitializationRequiringAction::Assignment,
1804 (base, span), flow_state);
1806 // (base initialized; no need to
1812 // Once `let s; s.x = V; read(s.x);`,
1813 // is allowed, remove this match arm.
1814 ty::Adt(..) | ty::Tuple(..) => {
1815 check_parent_of_field(self, location, base, span, flow_state);
1817 if let Some(local) = place.base_local() {
1818 // rust-lang/rust#21232,
1819 // #54499, #54986: during
1820 // period where we reject
1821 // partial initialization, do
1822 // not complain about
1823 // unnecessary `mut` on an
1824 // attempt to do a partial
1826 self.used_mut.insert(local);
1840 fn check_parent_of_field<'cx, 'gcx, 'tcx>(
1841 this: &mut MirBorrowckCtxt<'cx, 'gcx, 'tcx>,
1845 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1847 // rust-lang/rust#21232: Until Rust allows reads from the
1848 // initialized parts of partially initialized structs, we
1849 // will, starting with the 2018 edition, reject attempts
1850 // to write to structs that are not fully initialized.
1852 // In other words, *until* we allow this:
1854 // 1. `let mut s; s.x = Val; read(s.x);`
1856 // we will for now disallow this:
1858 // 2. `let mut s; s.x = Val;`
1862 // 3. `let mut s = ...; drop(s); s.x=Val;`
1864 // This does not use check_if_path_or_subpath_is_moved,
1865 // because we want to *allow* reinitializations of fields:
1866 // e.g., want to allow
1868 // `let mut s = ...; drop(s.x); s.x=Val;`
1870 // This does not use check_if_full_path_is_moved on
1871 // `base`, because that would report an error about the
1872 // `base` as a whole, but in this scenario we *really*
1873 // want to report an error about the actual thing that was
1874 // moved, which may be some prefix of `base`.
1876 // Shallow so that we'll stop at any dereference; we'll
1877 // report errors about issues with such bases elsewhere.
1878 let maybe_uninits = &flow_state.uninits;
1880 // Find the shortest uninitialized prefix you can reach
1881 // without going over a Deref.
1882 let mut shortest_uninit_seen = None;
1883 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1884 let mpi = match this.move_path_for_place(prefix) {
1885 Some(mpi) => mpi, None => continue,
1888 if maybe_uninits.contains(mpi) {
1889 debug!("check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1890 shortest_uninit_seen, Some((prefix, mpi)));
1891 shortest_uninit_seen = Some((prefix, mpi));
1893 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1897 if let Some((prefix, mpi)) = shortest_uninit_seen {
1898 // Check for a reassignment into a uninitialized field of a union (for example,
1899 // after a move out). In this case, do not report a error here. There is an
1900 // exception, if this is the first assignment into the union (that is, there is
1901 // no move out from an earlier location) then this is an attempt at initialization
1902 // of the union - we should error in that case.
1903 let tcx = this.infcx.tcx;
1904 if let ty::Adt(def, _) = base.ty(this.mir, tcx).ty.sty {
1906 if this.move_data.path_map[mpi].iter().any(|moi| {
1907 this.move_data.moves[*moi].source.is_predecessor_of(
1916 this.report_use_of_moved_or_uninitialized(
1918 InitializationRequiringAction::PartialAssignment,
1919 (prefix, base, span),
1926 /// Checks the permissions for the given place and read or write kind
1928 /// Returns `true` if an error is reported.
1929 fn check_access_permissions(
1931 (place, span): (&Place<'tcx>, Span),
1933 is_local_mutation_allowed: LocalMutationIsAllowed,
1934 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1938 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1939 place, kind, is_local_mutation_allowed
1945 // rust-lang/rust#21232, #54986: during period where we reject
1946 // partial initialization, do not complain about mutability
1947 // errors except for actual mutation (as opposed to an attempt
1948 // to do a partial initialization).
1949 let previously_initialized = if let Some(local) = place.base_local() {
1950 self.is_local_ever_initialized(local, flow_state).is_some()
1956 Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1957 | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
1958 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1959 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. })) => {
1960 let is_local_mutation_allowed = match borrow_kind {
1961 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1962 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1963 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1965 match self.is_mutable(place, is_local_mutation_allowed) {
1967 self.add_used_mut(root_place, flow_state);
1971 error_access = AccessKind::MutableBorrow;
1972 the_place_err = place_err;
1976 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1977 match self.is_mutable(place, is_local_mutation_allowed) {
1979 self.add_used_mut(root_place, flow_state);
1983 error_access = AccessKind::Mutate;
1984 the_place_err = place_err;
1989 Reservation(wk @ WriteKind::Move)
1990 | Write(wk @ WriteKind::Move)
1991 | Reservation(wk @ WriteKind::StorageDeadOrDrop)
1992 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1993 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow))
1994 | Write(wk @ WriteKind::StorageDeadOrDrop)
1995 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1996 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
1997 if let (Err(_place_err), true) = (
1998 self.is_mutable(place, is_local_mutation_allowed),
1999 self.errors_buffer.is_empty()
2001 if self.infcx.tcx.migrate_borrowck() {
2002 // rust-lang/rust#46908: In pure NLL mode this
2003 // code path should be unreachable (and thus
2004 // we signal an ICE in the else branch
2005 // here). But we can legitimately get here
2006 // under borrowck=migrate mode, so instead of
2007 // ICE'ing we instead report a legitimate
2008 // error (which will then be downgraded to a
2009 // warning by the migrate machinery).
2010 error_access = match wk {
2011 WriteKind::MutableBorrow(_) => AccessKind::MutableBorrow,
2012 WriteKind::Move => AccessKind::Move,
2013 WriteKind::StorageDeadOrDrop |
2014 WriteKind::Mutate => AccessKind::Mutate,
2016 self.report_mutability_error(
2026 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2035 // permission checks are done at Reservation point.
2038 Read(ReadKind::Borrow(BorrowKind::Unique))
2039 | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
2040 | Read(ReadKind::Borrow(BorrowKind::Shared))
2041 | Read(ReadKind::Borrow(BorrowKind::Shallow))
2042 | Read(ReadKind::Copy) => {
2043 // Access authorized
2048 // at this point, we have set up the error reporting state.
2049 return if previously_initialized {
2050 self.report_mutability_error(
2063 fn is_local_ever_initialized(&self,
2065 flow_state: &Flows<'cx, 'gcx, 'tcx>)
2066 -> Option<InitIndex>
2068 let mpi = self.move_data.rev_lookup.find_local(local);
2069 let ii = &self.move_data.init_path_map[mpi];
2071 if flow_state.ever_inits.contains(index) {
2078 /// Adds the place into the used mutable variables set
2079 fn add_used_mut<'d>(
2081 root_place: RootPlace<'d, 'tcx>,
2082 flow_state: &Flows<'cx, 'gcx, 'tcx>,
2086 place: Place::Base(PlaceBase::Local(local)),
2087 is_local_mutation_allowed,
2089 // If the local may have been initialized, and it is now currently being
2090 // mutated, then it is justified to be annotated with the `mut`
2091 // keyword, since the mutation may be a possible reassignment.
2092 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes &&
2093 self.is_local_ever_initialized(*local, flow_state).is_some()
2095 self.used_mut.insert(*local);
2100 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2103 place: place @ Place::Projection(_),
2104 is_local_mutation_allowed: _,
2106 if let Some(field) = self.is_upvar_field_projection(place) {
2107 self.used_mut_upvars.push(field);
2111 place: Place::Base(PlaceBase::Static(..)),
2112 is_local_mutation_allowed: _,
2117 /// Whether this value can be written or borrowed mutably.
2118 /// Returns the root place if the place passed in is a projection.
2121 place: &'d Place<'tcx>,
2122 is_local_mutation_allowed: LocalMutationIsAllowed,
2123 ) -> Result<RootPlace<'d, 'tcx>, &'d Place<'tcx>> {
2125 Place::Base(PlaceBase::Local(local)) => {
2126 let local = &self.mir.local_decls[local];
2127 match local.mutability {
2128 Mutability::Not => match is_local_mutation_allowed {
2129 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2131 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2133 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2135 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2137 LocalMutationIsAllowed::No => Err(place),
2139 Mutability::Mut => Ok(RootPlace {
2141 is_local_mutation_allowed,
2145 // The rules for promotion are made by `qualify_consts`, there wouldn't even be a
2146 // `Place::Promoted` if the promotion weren't 100% legal. So we just forward this
2147 Place::Base(PlaceBase::Static(box Static{kind: StaticKind::Promoted(_), ..})) =>
2150 is_local_mutation_allowed,
2152 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(def_id), .. })) => {
2153 if !self.infcx.tcx.is_mutable_static(def_id) {
2158 is_local_mutation_allowed,
2162 Place::Projection(ref proj) => {
2164 ProjectionElem::Deref => {
2165 let base_ty = proj.base.ty(self.mir, self.infcx.tcx).ty;
2167 // Check the kind of deref to decide
2169 ty::Ref(_, _, mutbl) => {
2171 // Shared borrowed data is never mutable
2172 hir::MutImmutable => Err(place),
2173 // Mutably borrowed data is mutable, but only if we have a
2174 // unique path to the `&mut`
2175 hir::MutMutable => {
2176 let mode = match self.is_upvar_field_projection(place) {
2178 if self.upvars[field.index()].by_ref =>
2180 is_local_mutation_allowed
2182 _ => LocalMutationIsAllowed::Yes,
2185 self.is_mutable(&proj.base, mode)
2189 ty::RawPtr(tnm) => {
2191 // `*const` raw pointers are not mutable
2192 hir::MutImmutable => Err(place),
2193 // `*mut` raw pointers are always mutable, regardless of
2194 // context. The users have to check by themselves.
2195 hir::MutMutable => {
2198 is_local_mutation_allowed,
2203 // `Box<T>` owns its content, so mutable if its location is mutable
2204 _ if base_ty.is_box() => {
2205 self.is_mutable(&proj.base, is_local_mutation_allowed)
2207 // Deref should only be for reference, pointers or boxes
2208 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2211 // All other projections are owned by their base path, so mutable if
2212 // base path is mutable
2213 ProjectionElem::Field(..)
2214 | ProjectionElem::Index(..)
2215 | ProjectionElem::ConstantIndex { .. }
2216 | ProjectionElem::Subslice { .. }
2217 | ProjectionElem::Downcast(..) => {
2218 let upvar_field_projection = self.is_upvar_field_projection(place);
2219 if let Some(field) = upvar_field_projection {
2220 let upvar = &self.upvars[field.index()];
2222 "upvar.mutability={:?} local_mutation_is_allowed={:?} place={:?}",
2223 upvar, is_local_mutation_allowed, place
2225 match (upvar.mutability, is_local_mutation_allowed) {
2226 (Mutability::Not, LocalMutationIsAllowed::No)
2227 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2230 (Mutability::Not, LocalMutationIsAllowed::Yes)
2231 | (Mutability::Mut, _) => {
2232 // Subtle: this is an upvar
2233 // reference, so it looks like
2234 // `self.foo` -- we want to double
2235 // check that the location `*self`
2236 // is mutable (i.e., this is not a
2237 // `Fn` closure). But if that
2238 // check succeeds, we want to
2239 // *blame* the mutability on
2240 // `place` (that is,
2241 // `self.foo`). This is used to
2242 // propagate the info about
2243 // whether mutability declarations
2244 // are used outwards, so that we register
2245 // the outer variable as mutable. Otherwise a
2246 // test like this fails to record the `mut`
2250 // fn foo<F: FnOnce()>(_f: F) { }
2252 // let var = Vec::new();
2258 let _ = self.is_mutable(&proj.base, is_local_mutation_allowed)?;
2261 is_local_mutation_allowed,
2266 self.is_mutable(&proj.base, is_local_mutation_allowed)
2274 /// If `place` is a field projection, and the field is being projected from a closure type,
2275 /// then returns the index of the field being projected. Note that this closure will always
2276 /// be `self` in the current MIR, because that is the only time we directly access the fields
2277 /// of a closure type.
2278 pub fn is_upvar_field_projection(&self, place: &Place<'tcx>) -> Option<Field> {
2279 let (place, by_ref) = if let Place::Projection(ref proj) = place {
2280 if let ProjectionElem::Deref = proj.elem {
2290 Place::Projection(ref proj) => match proj.elem {
2291 ProjectionElem::Field(field, _ty) => {
2292 let tcx = self.infcx.tcx;
2293 let base_ty = proj.base.ty(self.mir, tcx).ty;
2295 if (base_ty.is_closure() || base_ty.is_generator()) &&
2296 (!by_ref || self.upvars[field.index()].by_ref)
2310 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2311 enum NoMovePathFound {
2315 /// The degree of overlap between 2 places for borrow-checking.
2317 /// The places might partially overlap - in this case, we give
2318 /// up and say that they might conflict. This occurs when
2319 /// different fields of a union are borrowed. For example,
2320 /// if `u` is a union, we have no way of telling how disjoint
2321 /// `u.a.x` and `a.b.y` are.
2323 /// The places have the same type, and are either completely disjoint
2324 /// or equal - i.e., they can't "partially" overlap as can occur with
2325 /// unions. This is the "base case" on which we recur for extensions
2328 /// The places are disjoint, so we know all extensions of them
2329 /// will also be disjoint.