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, Body, Mutability, Operand, Place, PlaceBase, PlaceRef,
16 use rustc::mir::{Field, Projection, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
17 use rustc::mir::{Terminator, TerminatorKind};
18 use rustc::ty::query::Providers;
19 use rustc::ty::{self, TyCtxt};
21 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, Level};
22 use rustc_data_structures::bit_set::BitSet;
23 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
24 use rustc_data_structures::graph::dominators::Dominators;
25 use rustc_data_structures::indexed_vec::IndexVec;
26 use smallvec::SmallVec;
28 use std::collections::BTreeMap;
32 use syntax::ast::Name;
33 use syntax_pos::{Span, DUMMY_SP};
35 use crate::dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex};
36 use crate::dataflow::move_paths::{HasMoveData, InitLocation, LookupResult, MoveData, MoveError};
37 use crate::dataflow::Borrows;
38 use crate::dataflow::DataflowResultsConsumer;
39 use crate::dataflow::FlowAtLocation;
40 use crate::dataflow::MoveDataParamEnv;
41 use crate::dataflow::{do_dataflow, DebugFormatted};
42 use crate::dataflow::EverInitializedPlaces;
43 use crate::dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
45 use self::borrow_set::{BorrowData, BorrowSet};
46 use self::flows::Flows;
47 use self::location::LocationTable;
48 use self::prefixes::PrefixSet;
49 use self::MutateMode::{JustWrite, WriteAndRead};
50 use self::mutability_errors::AccessKind;
52 use self::path_utils::*;
60 mod mutability_errors;
63 crate mod places_conflict;
69 // FIXME(eddyb) perhaps move this somewhere more centrally.
76 /// If true, the capture is behind a reference.
79 mutability: Mutability,
82 pub fn provide(providers: &mut Providers<'_>) {
83 *providers = Providers {
89 fn mir_borrowck(tcx: TyCtxt<'_>, def_id: DefId) -> BorrowCheckResult<'_> {
90 let (input_body, promoted) = tcx.mir_validated(def_id);
91 debug!("run query mir_borrowck: {}", tcx.def_path_str(def_id));
93 let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
94 let input_body: &Body<'_> = &input_body.borrow();
95 let promoted: &IndexVec<_, _> = &promoted.borrow();
96 do_mir_borrowck(&infcx, input_body, promoted, def_id)
98 debug!("mir_borrowck done");
103 fn do_mir_borrowck<'a, 'tcx>(
104 infcx: &InferCtxt<'a, 'tcx>,
105 input_body: &Body<'tcx>,
106 input_promoted: &IndexVec<Promoted, Body<'tcx>>,
108 ) -> BorrowCheckResult<'tcx> {
109 debug!("do_mir_borrowck(def_id = {:?})", def_id);
112 let attributes = tcx.get_attrs(def_id);
113 let param_env = tcx.param_env(def_id);
116 .as_local_hir_id(def_id)
117 .expect("do_mir_borrowck: non-local DefId");
119 // Gather the upvars of a closure, if any.
120 let tables = tcx.typeck_tables_of(def_id);
121 let upvars: Vec<_> = tables
125 .flat_map(|v| v.values())
127 let var_hir_id = upvar_id.var_path.hir_id;
128 let capture = tables.upvar_capture(*upvar_id);
129 let by_ref = match capture {
130 ty::UpvarCapture::ByValue => false,
131 ty::UpvarCapture::ByRef(..) => true,
133 let mut upvar = Upvar {
134 name: tcx.hir().name(var_hir_id),
137 mutability: Mutability::Not,
139 let bm = *tables.pat_binding_modes().get(var_hir_id)
140 .expect("missing binding mode");
141 if bm == ty::BindByValue(hir::MutMutable) {
142 upvar.mutability = Mutability::Mut;
148 // Replace all regions with fresh inference variables. This
149 // requires first making our own copy of the MIR. This copy will
150 // be modified (in place) to contain non-lexical lifetimes. It
151 // will have a lifetime tied to the inference context.
152 let mut body: Body<'tcx> = input_body.clone();
153 let mut promoted: IndexVec<Promoted, Body<'tcx>> = input_promoted.clone();
154 let free_regions = nll::replace_regions_in_mir(infcx, def_id, param_env, &mut body, &mut promoted);
155 let body = &body; // no further changes
156 let location_table = &LocationTable::new(body);
158 let mut errors_buffer = Vec::new();
159 let (move_data, move_errors): (MoveData<'tcx>, Option<Vec<(Place<'tcx>, MoveError<'tcx>)>>) =
160 match MoveData::gather_moves(body, tcx) {
161 Ok(move_data) => (move_data, None),
162 Err((move_data, move_errors)) => (move_data, Some(move_errors)),
165 let mdpe = MoveDataParamEnv {
166 move_data: move_data,
167 param_env: param_env,
170 let dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
171 let mut flow_inits = FlowAtLocation::new(do_dataflow(
177 MaybeInitializedPlaces::new(tcx, body, &mdpe),
178 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
181 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
182 let borrow_set = Rc::new(BorrowSet::build(
183 tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
185 // If we are in non-lexical mode, compute the non-lexical lifetimes.
186 let (regioncx, polonius_output, opt_closure_req) = nll::compute_regions(
201 // The various `flow_*` structures can be large. We drop `flow_inits` here
202 // so it doesn't overlap with the others below. This reduces peak memory
203 // usage significantly on some benchmarks.
206 let regioncx = Rc::new(regioncx);
208 let flow_borrows = FlowAtLocation::new(do_dataflow(
214 Borrows::new(tcx, body, param_env, regioncx.clone(), &borrow_set),
215 |rs, i| DebugFormatted::new(&rs.location(i)),
217 let flow_uninits = FlowAtLocation::new(do_dataflow(
223 MaybeUninitializedPlaces::new(tcx, body, &mdpe),
224 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
226 let flow_ever_inits = FlowAtLocation::new(do_dataflow(
232 EverInitializedPlaces::new(tcx, body, &mdpe),
233 |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
236 let movable_generator = match tcx.hir().get(id) {
237 Node::Expr(&hir::Expr {
238 node: hir::ExprKind::Closure(.., Some(hir::GeneratorMovability::Static)),
244 let dominators = body.dominators();
246 let mut mbcx = MirBorrowckCtxt {
251 move_data: &mdpe.move_data,
254 locals_are_invalidated_at_exit,
255 access_place_error_reported: Default::default(),
256 reservation_error_reported: Default::default(),
257 reservation_warnings: Default::default(),
258 move_error_reported: BTreeMap::new(),
259 uninitialized_error_reported: Default::default(),
261 disable_error_downgrading: false,
262 nonlexical_regioncx: regioncx,
263 used_mut: Default::default(),
264 used_mut_upvars: SmallVec::new(),
270 let mut state = Flows::new(
277 if let Some(errors) = move_errors {
278 mbcx.report_move_errors(errors);
280 mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
282 // Convert any reservation warnings into lints.
283 let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
284 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
285 let mut initial_diag =
286 mbcx.report_conflicting_borrow(location, (&place, span), bk, &borrow);
288 let lint_root = if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
289 let scope = mbcx.body.source_info(location).scope;
295 // Span and message don't matter; we overwrite them below anyway
296 let mut diag = mbcx.infcx.tcx.struct_span_lint_hir(
297 MUTABLE_BORROW_RESERVATION_CONFLICT, lint_root, DUMMY_SP, "");
299 diag.message = initial_diag.styled_message().clone();
300 diag.span = initial_diag.span.clone();
302 initial_diag.cancel();
303 diag.buffer(&mut mbcx.errors_buffer);
306 // For each non-user used mutable variable, check if it's been assigned from
307 // a user-declared local. If so, then put that local into the used_mut set.
308 // Note that this set is expected to be small - only upvars from closures
309 // would have a chance of erroneously adding non-user-defined mutable vars
311 let temporary_used_locals: FxHashSet<Local> = mbcx.used_mut.iter()
312 .filter(|&local| mbcx.body.local_decls[*local].is_user_variable.is_none())
315 // For the remaining unused locals that are marked as mutable, we avoid linting any that
316 // were never initialized. These locals may have been removed as unreachable code; or will be
317 // linted as unused variables.
318 let unused_mut_locals = mbcx.body.mut_vars_iter()
319 .filter(|local| !mbcx.used_mut.contains(local))
321 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
323 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
324 let used_mut = mbcx.used_mut;
325 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
326 if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
327 let local_decl = &mbcx.body.local_decls[local];
329 // Skip implicit `self` argument for closures
330 if local.index() == 1 && tcx.is_closure(mbcx.mir_def_id) {
334 // Skip over locals that begin with an underscore or have no name
335 match local_decl.name {
336 Some(name) => if name.as_str().starts_with("_") {
342 let span = local_decl.source_info.span;
343 if span.desugaring_kind().is_some() {
344 // If the `mut` arises as part of a desugaring, we should ignore it.
348 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
349 tcx.struct_span_lint_hir(
351 vsi[local_decl.source_info.scope].lint_root,
353 "variable does not need to be mutable",
355 .span_suggestion_short(
359 Applicability::MachineApplicable,
365 // Buffer any move errors that we collected and de-duplicated.
366 for (_, (_, diag)) in mbcx.move_error_reported {
367 diag.buffer(&mut mbcx.errors_buffer);
370 if !mbcx.errors_buffer.is_empty() {
371 mbcx.errors_buffer.sort_by_key(|diag| diag.span.primary_span());
373 if !mbcx.disable_error_downgrading && tcx.migrate_borrowck() {
374 // When borrowck=migrate, check if AST-borrowck would
375 // error on the given code.
377 // rust-lang/rust#55492, rust-lang/rust#58776 check the base def id
378 // for errors. AST borrowck is responsible for aggregating
379 // `signalled_any_error` from all of the nested closures here.
380 let base_def_id = tcx.closure_base_def_id(def_id);
382 match tcx.borrowck(base_def_id).signalled_any_error {
383 SignalledError::NoErrorsSeen => {
384 // if AST-borrowck signalled no errors, then
385 // downgrade all the buffered MIR-borrowck errors
388 for err in mbcx.errors_buffer.iter_mut() {
389 downgrade_if_error(err);
392 SignalledError::SawSomeError => {
393 // if AST-borrowck signalled a (cancelled) error,
394 // then we will just emit the buffered
395 // MIR-borrowck errors as normal.
400 for diag in mbcx.errors_buffer.drain(..) {
401 DiagnosticBuilder::new_diagnostic(mbcx.infcx.tcx.sess.diagnostic(), diag).emit();
405 let result = BorrowCheckResult {
406 closure_requirements: opt_closure_req,
407 used_mut_upvars: mbcx.used_mut_upvars,
410 debug!("do_mir_borrowck: result = {:#?}", result);
415 fn downgrade_if_error(diag: &mut Diagnostic) {
417 diag.level = Level::Warning;
419 "this error has been downgraded to a warning for backwards \
420 compatibility with previous releases",
422 "this represents potential undefined behavior in your code and \
423 this warning will become a hard error in the future",
425 "for more information, try `rustc --explain E0729`"
430 crate struct MirBorrowckCtxt<'cx, 'tcx> {
431 crate infcx: &'cx InferCtxt<'cx, 'tcx>,
432 body: &'cx Body<'tcx>,
434 param_env: ty::ParamEnv<'tcx>,
435 move_data: &'cx MoveData<'tcx>,
437 /// Map from MIR `Location` to `LocationIndex`; created
438 /// when MIR borrowck begins.
439 location_table: &'cx LocationTable,
441 movable_generator: bool,
442 /// This keeps track of whether local variables are free-ed when the function
443 /// exits even without a `StorageDead`, which appears to be the case for
446 /// I'm not sure this is the right approach - @eddyb could you try and
448 locals_are_invalidated_at_exit: bool,
449 /// This field keeps track of when borrow errors are reported in the access_place function
450 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
451 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
452 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
454 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
455 /// This field keeps track of when borrow conflict errors are reported
456 /// for reservations, so that we don't report seemingly duplicate
457 /// errors for corresponding activations.
459 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
460 // but it is currently inconvenient to track down the `BorrowIndex`
461 // at the time we detect and report a reservation error.
462 reservation_error_reported: FxHashSet<Place<'tcx>>,
463 /// Migration warnings to be reported for #56254. We delay reporting these
464 /// so that we can suppress the warning if there's a corresponding error
465 /// for the activation of the borrow.
466 reservation_warnings: FxHashMap<
468 (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)
470 /// This field keeps track of move errors that are to be reported for given move indicies.
472 /// There are situations where many errors can be reported for a single move out (see #53807)
473 /// and we want only the best of those errors.
475 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
476 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
477 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
478 /// all move errors have been reported, any diagnostics in this map are added to the buffer
481 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
482 /// when errors in the map are being re-added to the error buffer so that errors with the
483 /// same primary span come out in a consistent order.
484 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'cx, 'tcx>, DiagnosticBuilder<'cx>)>,
485 /// This field keeps track of errors reported in the checking of uninitialized variables,
486 /// so that we don't report seemingly duplicate errors.
487 uninitialized_error_reported: FxHashSet<PlaceRef<'cx, 'tcx>>,
488 /// Errors to be reported buffer
489 errors_buffer: Vec<Diagnostic>,
490 /// If there are no errors reported by the HIR borrow checker, we downgrade
491 /// all NLL errors to warnings. Setting this flag disables downgrading.
492 disable_error_downgrading: bool,
493 /// This field keeps track of all the local variables that are declared mut and are mutated.
494 /// Used for the warning issued by an unused mutable local variable.
495 used_mut: FxHashSet<Local>,
496 /// If the function we're checking is a closure, then we'll need to report back the list of
497 /// mutable upvars that have been used. This field keeps track of them.
498 used_mut_upvars: SmallVec<[Field; 8]>,
499 /// Non-lexical region inference context, if NLL is enabled. This
500 /// contains the results from region inference and lets us e.g.
501 /// find out which CFG points are contained in each borrow region.
502 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
504 /// The set of borrows extracted from the MIR
505 borrow_set: Rc<BorrowSet<'tcx>>,
507 /// Dominators for MIR
508 dominators: Dominators<BasicBlock>,
510 /// Information about upvars not necessarily preserved in types or MIR
515 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
516 // 2. loans made in overlapping scopes do not conflict
517 // 3. assignments do not affect things loaned out as immutable
518 // 4. moves do not affect things loaned out in any way
519 impl<'cx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
520 type FlowState = Flows<'cx, 'tcx>;
522 fn body(&self) -> &'cx Body<'tcx> {
526 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
527 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
530 fn visit_statement_entry(
533 stmt: &'cx Statement<'tcx>,
534 flow_state: &Self::FlowState,
537 "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
538 location, stmt, flow_state
540 let span = stmt.source_info.span;
542 self.check_activations(location, span, flow_state);
545 StatementKind::Assign(ref lhs, ref rhs) => {
560 StatementKind::FakeRead(_, ref place) => {
561 // Read for match doesn't access any memory and is used to
562 // assert that a place is safe and live. So we don't have to
563 // do any checks here.
565 // FIXME: Remove check that the place is initialized. This is
566 // needed for now because matches don't have never patterns yet.
567 // So this is the only place we prevent
571 self.check_if_path_or_subpath_is_moved(
573 InitializationRequiringAction::Use,
574 (place.as_ref(), span),
578 StatementKind::SetDiscriminant {
590 StatementKind::InlineAsm(ref asm) => {
591 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
593 // FIXME(eddyb) indirect inline asm outputs should
594 // be encoded through MIR place derefs instead.
598 (Deep, Read(ReadKind::Copy)),
599 LocalMutationIsAllowed::No,
602 self.check_if_path_or_subpath_is_moved(
604 InitializationRequiringAction::Use,
605 (output.as_ref(), o.span),
612 if o.is_rw { Deep } else { Shallow(None) },
613 if o.is_rw { WriteAndRead } else { JustWrite },
618 for (_, input) in asm.inputs.iter() {
619 self.consume_operand(location, (input, span), flow_state);
623 | StatementKind::AscribeUserType(..)
624 | StatementKind::Retag { .. }
625 | StatementKind::StorageLive(..) => {
626 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
629 StatementKind::StorageDead(local) => {
632 (&Place::from(local), span),
633 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
634 LocalMutationIsAllowed::Yes,
641 fn visit_terminator_entry(
644 term: &'cx Terminator<'tcx>,
645 flow_state: &Self::FlowState,
649 "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
650 location, term, flow_state
652 let span = term.source_info.span;
654 self.check_activations(location, span, flow_state);
657 TerminatorKind::SwitchInt {
663 self.consume_operand(loc, (discr, span), flow_state);
665 TerminatorKind::Drop {
666 location: ref drop_place,
670 let gcx = self.infcx.tcx.global_tcx();
672 // Compute the type with accurate region information.
673 let drop_place_ty = drop_place.ty(self.body, self.infcx.tcx);
675 // Erase the regions.
676 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
678 // "Lift" into the gcx -- once regions are erased, this type should be in the
679 // global arenas; this "lift" operation basically just asserts that is true, but
680 // that is useful later.
681 gcx.lift_to_global(&drop_place_ty).unwrap();
683 debug!("visit_terminator_drop \
684 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
685 loc, term, drop_place, drop_place_ty, span);
690 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
691 LocalMutationIsAllowed::Yes,
695 TerminatorKind::DropAndReplace {
696 location: ref drop_place,
697 value: ref new_value,
708 self.consume_operand(
714 TerminatorKind::Call {
721 self.consume_operand(loc, (func, span), flow_state);
723 self.consume_operand(
729 if let Some((ref dest, _ /*bb*/)) = *destination {
739 TerminatorKind::Assert {
746 self.consume_operand(loc, (cond, span), flow_state);
747 use rustc::mir::interpret::PanicInfo;
748 if let PanicInfo::BoundsCheck { ref len, ref index } = *msg {
749 self.consume_operand(loc, (len, span), flow_state);
750 self.consume_operand(loc, (index, span), flow_state);
754 TerminatorKind::Yield {
759 self.consume_operand(loc, (value, span), flow_state);
761 if self.movable_generator {
762 // Look for any active borrows to locals
763 let borrow_set = self.borrow_set.clone();
764 flow_state.with_outgoing_borrows(|borrows| {
766 let borrow = &borrow_set[i];
767 self.check_for_local_borrow(borrow, span);
773 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
774 // Returning from the function implicitly kills storage for all locals and statics.
775 // Often, the storage will already have been killed by an explicit
776 // StorageDead, but we don't always emit those (notably on unwind paths),
777 // so this "extra check" serves as a kind of backup.
778 let borrow_set = self.borrow_set.clone();
779 flow_state.with_outgoing_borrows(|borrows| {
781 let borrow = &borrow_set[i];
782 self.check_for_invalidation_at_exit(loc, borrow, span);
786 TerminatorKind::Goto { target: _ }
787 | TerminatorKind::Abort
788 | TerminatorKind::Unreachable
789 | TerminatorKind::FalseEdges {
793 | TerminatorKind::FalseUnwind {
797 // no data used, thus irrelevant to borrowck
803 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
809 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
810 use self::AccessDepth::{Deep, Shallow};
812 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
813 enum ArtificialField {
818 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
820 /// From the RFC: "A *shallow* access means that the immediate
821 /// fields reached at P are accessed, but references or pointers
822 /// found within are not dereferenced. Right now, the only access
823 /// that is shallow is an assignment like `x = ...;`, which would
824 /// be a *shallow write* of `x`."
825 Shallow(Option<ArtificialField>),
827 /// From the RFC: "A *deep* access means that all data reachable
828 /// through the given place may be invalidated or accesses by
832 /// Access is Deep only when there is a Drop implementation that
833 /// can reach the data behind the reference.
837 /// Kind of access to a value: read or write
838 /// (For informational purposes only)
839 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
841 /// From the RFC: "A *read* means that the existing data may be
842 /// read, but will not be changed."
845 /// From the RFC: "A *write* means that the data may be mutated to
846 /// new values or otherwise invalidated (for example, it could be
847 /// de-initialized, as in a move operation).
850 /// For two-phase borrows, we distinguish a reservation (which is treated
851 /// like a Read) from an activation (which is treated like a write), and
852 /// each of those is furthermore distinguished from Reads/Writes above.
853 Reservation(WriteKind),
854 Activation(WriteKind, BorrowIndex),
857 /// Kind of read access to a value
858 /// (For informational purposes only)
859 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
865 /// Kind of write access to a value
866 /// (For informational purposes only)
867 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
870 MutableBorrow(BorrowKind),
875 /// When checking permissions for a place access, this flag is used to indicate that an immutable
876 /// local place can be mutated.
878 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
879 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
880 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
881 // `is_declared_mutable()`.
882 // - Take flow state into consideration in `is_assignable()` for local variables.
883 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
884 enum LocalMutationIsAllowed {
886 /// We want use of immutable upvars to cause a "write to immutable upvar"
887 /// error, not an "reassignment" error.
892 #[derive(Copy, Clone, Debug)]
893 enum InitializationRequiringAction {
902 struct RootPlace<'d, 'tcx> {
903 place_base: &'d PlaceBase<'tcx>,
904 place_projection: &'d Option<Box<Projection<'tcx>>>,
905 is_local_mutation_allowed: LocalMutationIsAllowed,
908 impl InitializationRequiringAction {
909 fn as_noun(self) -> &'static str {
911 InitializationRequiringAction::Update => "update",
912 InitializationRequiringAction::Borrow => "borrow",
913 InitializationRequiringAction::MatchOn => "use", // no good noun
914 InitializationRequiringAction::Use => "use",
915 InitializationRequiringAction::Assignment => "assign",
916 InitializationRequiringAction::PartialAssignment => "assign to part",
920 fn as_verb_in_past_tense(self) -> &'static str {
922 InitializationRequiringAction::Update => "updated",
923 InitializationRequiringAction::Borrow => "borrowed",
924 InitializationRequiringAction::MatchOn => "matched on",
925 InitializationRequiringAction::Use => "used",
926 InitializationRequiringAction::Assignment => "assigned",
927 InitializationRequiringAction::PartialAssignment => "partially assigned",
932 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
933 /// If there are no errors reported by the HIR borrow checker, we downgrade
934 /// all NLL errors to warnings. Calling this disables downgrading.
935 crate fn disable_error_downgrading(&mut self) {
936 self.disable_error_downgrading = true;
939 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
940 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
941 /// place is initialized and (b) it is not borrowed in some way that would prevent this
944 /// Returns `true` if an error is reported.
948 place_span: (&Place<'tcx>, Span),
949 kind: (AccessDepth, ReadOrWrite),
950 is_local_mutation_allowed: LocalMutationIsAllowed,
951 flow_state: &Flows<'cx, 'tcx>,
955 if let Activation(_, borrow_index) = rw {
956 if self.reservation_error_reported.contains(&place_span.0) {
958 "skipping access_place for activation of invalid reservation \
959 place: {:?} borrow_index: {:?}",
960 place_span.0, borrow_index
966 // Check is_empty() first because it's the common case, and doing that
967 // way we avoid the clone() call.
968 if !self.access_place_error_reported.is_empty() &&
970 .access_place_error_reported
971 .contains(&(place_span.0.clone(), place_span.1))
974 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
980 let mutability_error =
981 self.check_access_permissions(
984 is_local_mutation_allowed,
989 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
991 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
992 // Suppress this warning when there's an error being emited for the
993 // same borrow: fixing the error is likely to fix the warning.
994 self.reservation_warnings.remove(&borrow_idx);
997 if conflict_error || mutability_error {
999 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
1003 self.access_place_error_reported
1004 .insert((place_span.0.clone(), place_span.1));
1008 fn check_access_for_conflict(
1011 place_span: (&Place<'tcx>, Span),
1014 flow_state: &Flows<'cx, 'tcx>,
1017 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1018 location, place_span, sd, rw,
1021 let mut error_reported = false;
1022 let tcx = self.infcx.tcx;
1023 let body = self.body;
1024 let param_env = self.param_env;
1025 let location_table = self.location_table.start_index(location);
1026 let borrow_set = self.borrow_set.clone();
1027 each_borrow_involving_path(
1035 flow_state.borrows_in_scope(location_table),
1036 |this, borrow_index, borrow| match (rw, borrow.kind) {
1037 // Obviously an activation is compatible with its own
1038 // reservation (or even prior activating uses of same
1039 // borrow); so don't check if they interfere.
1041 // NOTE: *reservations* do conflict with themselves;
1042 // thus aren't injecting unsoundenss w/ this check.)
1043 (Activation(_, activating), _) if activating == borrow_index => {
1045 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1046 skipping {:?} b/c activation of same borrow_index",
1050 (borrow_index, borrow),
1055 (Read(_), BorrowKind::Shared)
1056 | (Read(_), BorrowKind::Shallow)
1057 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
1058 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
1062 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1063 // Handled by initialization checks.
1067 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
1068 // Reading from mere reservations of mutable-borrows is OK.
1069 if !is_active(&this.dominators, borrow, location) {
1070 assert!(allow_two_phase_borrow(borrow.kind));
1071 return Control::Continue;
1074 error_reported = true;
1077 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1078 .buffer(&mut this.errors_buffer);
1080 ReadKind::Borrow(bk) => {
1081 this.report_conflicting_borrow(location, place_span, bk, borrow)
1082 .buffer(&mut this.errors_buffer);
1088 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
1089 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared) if {
1090 tcx.migrate_borrowck() && this.borrow_set.location_map.contains_key(&location)
1092 let bi = this.borrow_set.location_map[&location];
1094 "recording invalid reservation of place: {:?} with \
1095 borrow index {:?} as warning",
1099 // rust-lang/rust#56254 - This was previously permitted on
1100 // the 2018 edition so we emit it as a warning. We buffer
1101 // these sepately so that we only emit a warning if borrow
1102 // checking was otherwise successful.
1103 this.reservation_warnings.insert(
1105 (place_span.0.clone(), place_span.1, location, bk, borrow.clone()),
1108 // Don't suppress actual errors.
1112 (Reservation(kind), _)
1113 | (Activation(kind, _), _)
1114 | (Write(kind), _) => {
1116 Reservation(..) => {
1118 "recording invalid reservation of \
1122 this.reservation_error_reported.insert(place_span.0.clone());
1124 Activation(_, activating) => {
1126 "observing check_place for activation of \
1127 borrow_index: {:?}",
1131 Read(..) | Write(..) => {}
1134 error_reported = true;
1136 WriteKind::MutableBorrow(bk) => {
1137 this.report_conflicting_borrow(location, place_span, bk, borrow)
1138 .buffer(&mut this.errors_buffer);
1140 WriteKind::StorageDeadOrDrop => {
1141 this.report_borrowed_value_does_not_live_long_enough(
1147 WriteKind::Mutate => {
1148 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1150 WriteKind::Move => {
1151 this.report_move_out_while_borrowed(location, place_span, borrow)
1165 place_span: (&'cx Place<'tcx>, Span),
1168 flow_state: &Flows<'cx, 'tcx>,
1170 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1172 MutateMode::WriteAndRead => {
1173 self.check_if_path_or_subpath_is_moved(
1175 InitializationRequiringAction::Update,
1176 (place_span.0.as_ref(), place_span.1),
1180 MutateMode::JustWrite => {
1181 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1185 // Special case: you can assign a immutable local variable
1186 // (e.g., `x = ...`) so long as it has never been initialized
1187 // before (at this point in the flow).
1189 base: PlaceBase::Local(local),
1192 if let Mutability::Not = self.body.local_decls[*local].mutability {
1193 // check for reassignments to immutable local variables
1194 self.check_if_reassignment_to_immutable_state(
1204 // Otherwise, use the normal access permission rules.
1208 (kind, Write(WriteKind::Mutate)),
1209 LocalMutationIsAllowed::No,
1217 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1218 flow_state: &Flows<'cx, 'tcx>,
1221 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1222 let access_kind = match bk {
1223 BorrowKind::Shallow => {
1224 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1226 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1227 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1228 let wk = WriteKind::MutableBorrow(bk);
1229 if allow_two_phase_borrow(bk) {
1230 (Deep, Reservation(wk))
1241 LocalMutationIsAllowed::No,
1245 let action = if bk == BorrowKind::Shallow {
1246 InitializationRequiringAction::MatchOn
1248 InitializationRequiringAction::Borrow
1251 self.check_if_path_or_subpath_is_moved(
1254 (place.as_ref(), span),
1259 Rvalue::Use(ref operand)
1260 | Rvalue::Repeat(ref operand, _)
1261 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1262 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1263 self.consume_operand(location, (operand, span), flow_state)
1266 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1267 let af = match *rvalue {
1268 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1269 Rvalue::Discriminant(..) => None,
1270 _ => unreachable!(),
1275 (Shallow(af), Read(ReadKind::Copy)),
1276 LocalMutationIsAllowed::No,
1279 self.check_if_path_or_subpath_is_moved(
1281 InitializationRequiringAction::Use,
1282 (place.as_ref(), span),
1287 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1288 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1289 self.consume_operand(location, (operand1, span), flow_state);
1290 self.consume_operand(location, (operand2, span), flow_state);
1293 Rvalue::NullaryOp(_op, _ty) => {
1294 // nullary ops take no dynamic input; no borrowck effect.
1296 // FIXME: is above actually true? Do we want to track
1297 // the fact that uninitialized data can be created via
1301 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1302 // We need to report back the list of mutable upvars that were
1303 // moved into the closure and subsequently used by the closure,
1304 // in order to populate our used_mut set.
1305 match **aggregate_kind {
1306 AggregateKind::Closure(def_id, _)
1307 | AggregateKind::Generator(def_id, _, _) => {
1308 let BorrowCheckResult {
1310 } = self.infcx.tcx.mir_borrowck(def_id);
1311 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1312 for field in used_mut_upvars {
1313 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1316 AggregateKind::Adt(..)
1317 | AggregateKind::Array(..)
1318 | AggregateKind::Tuple { .. } => (),
1321 for operand in operands {
1322 self.consume_operand(location, (operand, span), flow_state);
1328 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1329 let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1330 if place.projection.is_some() {
1331 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1332 this.used_mut_upvars.push(field);
1334 } else if let PlaceBase::Local(local) = place.base {
1335 this.used_mut.insert(local);
1339 // This relies on the current way that by-value
1340 // captures of a closure are copied/moved directly
1341 // when generating MIR.
1343 Operand::Move(Place {
1344 base: PlaceBase::Local(local),
1347 Operand::Copy(Place {
1348 base: PlaceBase::Local(local),
1350 }) if self.body.local_decls[local].is_user_variable.is_none() => {
1351 if self.body.local_decls[local].ty.is_mutable_ptr() {
1352 // The variable will be marked as mutable by the borrow.
1355 // This is an edge case where we have a `move` closure
1356 // inside a non-move closure, and the inner closure
1357 // contains a mutation:
1360 // || { move || { i += 1; }; };
1362 // In this case our usual strategy of assuming that the
1363 // variable will be captured by mutable reference is
1364 // wrong, since `i` can be copied into the inner
1365 // closure from a shared reference.
1367 // As such we have to search for the local that this
1368 // capture comes from and mark it as being used as mut.
1370 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1371 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1372 &self.move_data.inits[init_index]
1374 bug!("temporary should be initialized exactly once")
1377 let loc = match init.location {
1378 InitLocation::Statement(stmt) => stmt,
1379 _ => bug!("temporary initialized in arguments"),
1382 let bbd = &self.body[loc.block];
1383 let stmt = &bbd.statements[loc.statement_index];
1384 debug!("temporary assigned in: stmt={:?}", stmt);
1386 if let StatementKind::Assign(_, box Rvalue::Ref(_, _, ref source)) = stmt.kind {
1387 propagate_closure_used_mut_place(self, source);
1389 bug!("closures should only capture user variables \
1390 or references to user variables");
1393 Operand::Move(ref place)
1394 | Operand::Copy(ref place) => {
1395 propagate_closure_used_mut_place(self, place);
1397 Operand::Constant(..) => {}
1404 (operand, span): (&'cx Operand<'tcx>, Span),
1405 flow_state: &Flows<'cx, 'tcx>,
1408 Operand::Copy(ref place) => {
1409 // copy of place: check if this is "copy of frozen path"
1410 // (FIXME: see check_loans.rs)
1414 (Deep, Read(ReadKind::Copy)),
1415 LocalMutationIsAllowed::No,
1419 // Finally, check if path was already moved.
1420 self.check_if_path_or_subpath_is_moved(
1422 InitializationRequiringAction::Use,
1423 (place.as_ref(), span),
1427 Operand::Move(ref place) => {
1428 // move of place: check if this is move of already borrowed path
1432 (Deep, Write(WriteKind::Move)),
1433 LocalMutationIsAllowed::Yes,
1437 // Finally, check if path was already moved.
1438 self.check_if_path_or_subpath_is_moved(
1440 InitializationRequiringAction::Use,
1441 (place.as_ref(), span),
1445 Operand::Constant(_) => {}
1449 /// Checks whether a borrow of this place is invalidated when the function
1451 fn check_for_invalidation_at_exit(
1454 borrow: &BorrowData<'tcx>,
1457 debug!("check_for_invalidation_at_exit({:?})", borrow);
1458 let place = &borrow.borrowed_place;
1459 let root_place = self.prefixes(place.as_ref(), PrefixSet::All).last().unwrap();
1461 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1462 // we just know that all locals are dropped at function exit (otherwise
1463 // we'll have a memory leak) and assume that all statics have a destructor.
1465 // FIXME: allow thread-locals to borrow other thread locals?
1467 assert!(root_place.projection.is_none());
1468 let (might_be_alive, will_be_dropped) = match root_place.base {
1469 PlaceBase::Static(box Static {
1470 kind: StaticKind::Promoted(..),
1475 PlaceBase::Static(box Static {
1476 kind: StaticKind::Static,
1479 // Thread-locals might be dropped after the function exits, but
1480 // "true" statics will never be.
1481 (true, self.is_place_thread_local(root_place))
1483 PlaceBase::Local(_) => {
1484 // Locals are always dropped at function exit, and if they
1485 // have a destructor it would've been called already.
1486 (false, self.locals_are_invalidated_at_exit)
1490 if !will_be_dropped {
1492 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1498 let sd = if might_be_alive { Deep } else { Shallow(None) };
1500 if places_conflict::borrow_conflicts_with_place(
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.cannot_borrow_across_generator_yield(
1530 self.retrieve_borrow_spans(borrow).var_or_use(),
1534 err.buffer(&mut self.errors_buffer);
1538 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1539 // Two-phase borrow support: For each activation that is newly
1540 // generated at this statement, check if it interferes with
1542 let borrow_set = self.borrow_set.clone();
1543 for &borrow_index in borrow_set.activations_at_location(location) {
1544 let borrow = &borrow_set[borrow_index];
1546 // only mutable borrows should be 2-phase
1547 assert!(match borrow.kind {
1548 BorrowKind::Shared | BorrowKind::Shallow => false,
1549 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1554 (&borrow.borrowed_place, span),
1557 Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1559 LocalMutationIsAllowed::No,
1562 // We do not need to call `check_if_path_or_subpath_is_moved`
1563 // again, as we already called it when we made the
1564 // initial reservation.
1569 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
1570 fn check_if_reassignment_to_immutable_state(
1574 place_span: (&Place<'tcx>, Span),
1575 flow_state: &Flows<'cx, 'tcx>,
1577 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1579 // Check if any of the initializiations of `local` have happened yet:
1580 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1581 // And, if so, report an error.
1582 let init = &self.move_data.inits[init_index];
1583 let span = init.span(&self.body);
1584 self.report_illegal_reassignment(
1585 location, place_span, span, place_span.0
1590 fn check_if_full_path_is_moved(
1593 desired_action: InitializationRequiringAction,
1594 place_span: (PlaceRef<'cx, 'tcx>, Span),
1595 flow_state: &Flows<'cx, 'tcx>,
1597 let maybe_uninits = &flow_state.uninits;
1601 // 1. Move of `a.b.c`, use of `a.b.c`
1602 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1603 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1604 // partial initialization support, one might have `a.x`
1605 // initialized but not `a.b`.
1609 // 4. Move of `a.b.c`, use of `a.b.d`
1610 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1611 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1612 // must have been initialized for the use to be sound.
1613 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1615 // The dataflow tracks shallow prefixes distinctly (that is,
1616 // field-accesses on P distinctly from P itself), in order to
1617 // track substructure initialization separately from the whole
1620 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1621 // which we have a MovePath is `a.b`, then that means that the
1622 // initialization state of `a.b` is all we need to inspect to
1623 // know if `a.b.c` is valid (and from that we infer that the
1624 // dereference and `.d` access is also valid, since we assume
1625 // `a.b.c` is assigned a reference to a initialized and
1626 // well-formed record structure.)
1628 // Therefore, if we seek out the *closest* prefix for which we
1629 // have a MovePath, that should capture the initialization
1630 // state for the place scenario.
1632 // This code covers scenarios 1, 2, and 3.
1634 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1635 match self.move_path_closest_to(place_span.0) {
1636 Ok((prefix, mpi)) => {
1637 if maybe_uninits.contains(mpi) {
1638 self.report_use_of_moved_or_uninitialized(
1641 (prefix, place_span.0, place_span.1),
1644 return; // don't bother finding other problems.
1647 Err(NoMovePathFound::ReachedStatic) => {
1648 // Okay: we do not build MoveData for static variables
1649 } // Only query longest prefix with a MovePath, not further
1650 // ancestors; dataflow recurs on children when parents
1651 // move (to support partial (re)inits).
1653 // (I.e., querying parents breaks scenario 7; but may want
1654 // to do such a query based on partial-init feature-gate.)
1658 fn check_if_path_or_subpath_is_moved(
1661 desired_action: InitializationRequiringAction,
1662 place_span: (PlaceRef<'cx, 'tcx>, Span),
1663 flow_state: &Flows<'cx, 'tcx>,
1665 let maybe_uninits = &flow_state.uninits;
1669 // 1. Move of `a.b.c`, use of `a` or `a.b`
1670 // partial initialization support, one might have `a.x`
1671 // initialized but not `a.b`.
1672 // 2. All bad scenarios from `check_if_full_path_is_moved`
1676 // 3. Move of `a.b.c`, use of `a.b.d`
1677 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1678 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1679 // must have been initialized for the use to be sound.
1680 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1682 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1684 // A move of any shallow suffix of `place` also interferes
1685 // with an attempt to use `place`. This is scenario 3 above.
1687 // (Distinct from handling of scenarios 1+2+4 above because
1688 // `place` does not interfere with suffixes of its prefixes,
1689 // e.g., `a.b.c` does not interfere with `a.b.d`)
1691 // This code covers scenario 1.
1693 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1694 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1695 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1696 self.report_use_of_moved_or_uninitialized(
1699 (place_span.0, place_span.0, place_span.1),
1702 return; // don't bother finding other problems.
1707 /// Currently MoveData does not store entries for all places in
1708 /// the input MIR. For example it will currently filter out
1709 /// places that are Copy; thus we do not track places of shared
1710 /// reference type. This routine will walk up a place along its
1711 /// prefixes, searching for a foundational place that *is*
1712 /// tracked in the MoveData.
1714 /// An Err result includes a tag indicated why the search failed.
1715 /// Currently this can only occur if the place is built off of a
1716 /// static variable, as we do not track those in the MoveData.
1717 fn move_path_closest_to(
1719 place: PlaceRef<'cx, 'tcx>,
1720 ) -> Result<(PlaceRef<'cx, 'tcx>, MovePathIndex), NoMovePathFound> {
1721 let mut last_prefix = place.base;
1723 for prefix in self.prefixes(place, PrefixSet::All) {
1724 if let Some(mpi) = self.move_path_for_place(prefix) {
1725 return Ok((prefix, mpi));
1728 last_prefix = prefix.base;
1732 PlaceBase::Local(_) => panic!("should have move path for every Local"),
1733 PlaceBase::Static(_) => Err(NoMovePathFound::ReachedStatic),
1737 fn move_path_for_place(&mut self, place: PlaceRef<'cx, 'tcx>) -> Option<MovePathIndex> {
1738 // If returns None, then there is no move path corresponding
1739 // to a direct owner of `place` (which means there is nothing
1740 // that borrowck tracks for its analysis).
1742 match self.move_data.rev_lookup.find(place) {
1743 LookupResult::Parent(_) => None,
1744 LookupResult::Exact(mpi) => Some(mpi),
1748 fn check_if_assigned_path_is_moved(
1751 (place, span): (&'cx Place<'tcx>, Span),
1752 flow_state: &Flows<'cx, 'tcx>,
1754 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1755 // recur down place; dispatch to external checks when necessary
1756 let mut place_projection = &place.projection;
1758 // None case => assigning to `x` does not require `x` be initialized.
1759 while let Some(proj) = place_projection {
1760 let Projection { ref base, ref elem } = **proj;
1762 ProjectionElem::Index(_/*operand*/) |
1763 ProjectionElem::ConstantIndex { .. } |
1764 // assigning to P[i] requires P to be valid.
1765 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1766 // assigning to (P->variant) is okay if assigning to `P` is okay
1768 // FIXME: is this true even if P is a adt with a dtor?
1771 // assigning to (*P) requires P to be initialized
1772 ProjectionElem::Deref => {
1773 self.check_if_full_path_is_moved(
1774 location, InitializationRequiringAction::Use,
1778 }, span), flow_state);
1779 // (base initialized; no need to
1784 ProjectionElem::Subslice { .. } => {
1785 panic!("we don't allow assignments to subslices, location: {:?}",
1789 ProjectionElem::Field(..) => {
1790 // if type of `P` has a dtor, then
1791 // assigning to `P.f` requires `P` itself
1792 // be already initialized
1793 let tcx = self.infcx.tcx;
1794 let base_ty = Place::ty_from(&place.base, base, self.body, tcx).ty;
1796 ty::Adt(def, _) if def.has_dtor(tcx) => {
1797 self.check_if_path_or_subpath_is_moved(
1798 location, InitializationRequiringAction::Assignment,
1802 }, span), flow_state);
1804 // (base initialized; no need to
1809 // Once `let s; s.x = V; read(s.x);`,
1810 // is allowed, remove this match arm.
1811 ty::Adt(..) | ty::Tuple(..) => {
1812 check_parent_of_field(self, location, PlaceRef {
1815 }, span, flow_state);
1817 if let PlaceBase::Local(local) = place.base {
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);
1835 place_projection = base;
1838 fn check_parent_of_field<'cx, 'tcx>(
1839 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1841 base: PlaceRef<'cx, 'tcx>,
1843 flow_state: &Flows<'cx, '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, _) =
1903 Place::ty_from(base.base, base.projection, this.body, tcx).ty.sty
1906 if this.move_data.path_map[mpi].iter().any(|moi| {
1907 this.move_data.moves[*moi].source.is_predecessor_of(
1908 location, this.body,
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, '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 PlaceBase::Local(local) = place.base {
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.as_ref(), 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.as_ref(), 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.as_ref(), 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(
2066 flow_state: &Flows<'cx, 'tcx>,
2067 ) -> 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>(&mut self, root_place: RootPlace<'d, 'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2082 place_base: PlaceBase::Local(local),
2083 place_projection: None,
2084 is_local_mutation_allowed,
2086 // If the local may have been initialized, and it is now currently being
2087 // mutated, then it is justified to be annotated with the `mut`
2088 // keyword, since the mutation may be a possible reassignment.
2089 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes &&
2090 self.is_local_ever_initialized(*local, flow_state).is_some()
2092 self.used_mut.insert(*local);
2097 place_projection: _,
2098 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2102 place_projection: place_projection @ Some(_),
2103 is_local_mutation_allowed: _,
2105 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2107 projection: &place_projection,
2109 self.used_mut_upvars.push(field);
2113 place_base: PlaceBase::Static(..),
2114 place_projection: None,
2115 is_local_mutation_allowed: _,
2120 /// Whether this value can be written or borrowed mutably.
2121 /// Returns the root place if the place passed in is a projection.
2124 place: PlaceRef<'d, 'tcx>,
2125 is_local_mutation_allowed: LocalMutationIsAllowed,
2126 ) -> Result<RootPlace<'d, 'tcx>, PlaceRef<'d, 'tcx>> {
2129 base: PlaceBase::Local(local),
2132 let local = &self.body.local_decls[*local];
2133 match local.mutability {
2134 Mutability::Not => match is_local_mutation_allowed {
2135 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2136 place_base: place.base,
2137 place_projection: place.projection,
2138 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2140 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2141 place_base: place.base,
2142 place_projection: place.projection,
2143 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2145 LocalMutationIsAllowed::No => Err(place),
2147 Mutability::Mut => Ok(RootPlace {
2148 place_base: place.base,
2149 place_projection: place.projection,
2150 is_local_mutation_allowed,
2154 // The rules for promotion are made by `qualify_consts`, there wouldn't even be a
2155 // `Place::Promoted` if the promotion weren't 100% legal. So we just forward this
2157 base: PlaceBase::Static(box Static {
2158 kind: StaticKind::Promoted(..),
2164 place_base: place.base,
2165 place_projection: place.projection,
2166 is_local_mutation_allowed,
2169 base: PlaceBase::Static(box Static {
2170 kind: StaticKind::Static,
2176 if !self.infcx.tcx.is_mutable_static(*def_id) {
2180 place_base: place.base,
2181 place_projection: place.projection,
2182 is_local_mutation_allowed,
2188 projection: Some(proj),
2191 ProjectionElem::Deref => {
2193 Place::ty_from(place.base, &proj.base, self.body, self.infcx.tcx).ty;
2195 // Check the kind of deref to decide
2197 ty::Ref(_, _, mutbl) => {
2199 // Shared borrowed data is never mutable
2200 hir::MutImmutable => Err(place),
2201 // Mutably borrowed data is mutable, but only if we have a
2202 // unique path to the `&mut`
2203 hir::MutMutable => {
2204 let mode = match self.is_upvar_field_projection(place) {
2206 if self.upvars[field.index()].by_ref =>
2208 is_local_mutation_allowed
2210 _ => LocalMutationIsAllowed::Yes,
2213 self.is_mutable(PlaceRef {
2215 projection: &proj.base,
2220 ty::RawPtr(tnm) => {
2222 // `*const` raw pointers are not mutable
2223 hir::MutImmutable => Err(place),
2224 // `*mut` raw pointers are always mutable, regardless of
2225 // context. The users have to check by themselves.
2226 hir::MutMutable => {
2228 place_base: place.base,
2229 place_projection: place.projection,
2230 is_local_mutation_allowed,
2235 // `Box<T>` owns its content, so mutable if its location is mutable
2236 _ if base_ty.is_box() => {
2237 self.is_mutable(PlaceRef {
2239 projection: &proj.base,
2240 }, is_local_mutation_allowed)
2242 // Deref should only be for reference, pointers or boxes
2243 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2246 // All other projections are owned by their base path, so mutable if
2247 // base path is mutable
2248 ProjectionElem::Field(..)
2249 | ProjectionElem::Index(..)
2250 | ProjectionElem::ConstantIndex { .. }
2251 | ProjectionElem::Subslice { .. }
2252 | ProjectionElem::Downcast(..) => {
2253 let upvar_field_projection = self.is_upvar_field_projection(place);
2254 if let Some(field) = upvar_field_projection {
2255 let upvar = &self.upvars[field.index()];
2257 "upvar.mutability={:?} local_mutation_is_allowed={:?} \
2259 upvar, is_local_mutation_allowed, place
2261 match (upvar.mutability, is_local_mutation_allowed) {
2262 (Mutability::Not, LocalMutationIsAllowed::No)
2263 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2266 (Mutability::Not, LocalMutationIsAllowed::Yes)
2267 | (Mutability::Mut, _) => {
2268 // Subtle: this is an upvar
2269 // reference, so it looks like
2270 // `self.foo` -- we want to double
2271 // check that the location `*self`
2272 // is mutable (i.e., this is not a
2273 // `Fn` closure). But if that
2274 // check succeeds, we want to
2275 // *blame* the mutability on
2276 // `place` (that is,
2277 // `self.foo`). This is used to
2278 // propagate the info about
2279 // whether mutability declarations
2280 // are used outwards, so that we register
2281 // the outer variable as mutable. Otherwise a
2282 // test like this fails to record the `mut`
2286 // fn foo<F: FnOnce()>(_f: F) { }
2288 // let var = Vec::new();
2294 let _ = self.is_mutable(PlaceRef {
2296 projection: &proj.base,
2297 }, is_local_mutation_allowed)?;
2299 place_base: place.base,
2300 place_projection: place.projection,
2301 is_local_mutation_allowed,
2306 self.is_mutable(PlaceRef {
2308 projection: &proj.base,
2309 }, is_local_mutation_allowed)
2317 /// If `place` is a field projection, and the field is being projected from a closure type,
2318 /// then returns the index of the field being projected. Note that this closure will always
2319 /// be `self` in the current MIR, because that is the only time we directly access the fields
2320 /// of a closure type.
2321 pub fn is_upvar_field_projection(&self, place_ref: PlaceRef<'cx, 'tcx>) -> Option<Field> {
2322 let mut place_projection = place_ref.projection;
2323 let mut by_ref = false;
2325 if let Some(box Projection {
2327 elem: ProjectionElem::Deref,
2328 }) = place_projection {
2329 place_projection = &base;
2333 match place_projection {
2334 Some(box Projection {
2336 elem: ProjectionElem::Field(field, _ty),
2338 let tcx = self.infcx.tcx;
2339 let base_ty = Place::ty_from(place_ref.base, &base, self.body, tcx).ty;
2341 if (base_ty.is_closure() || base_ty.is_generator()) &&
2342 (!by_ref || self.upvars[field.index()].by_ref) {
2354 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2355 enum NoMovePathFound {
2359 /// The degree of overlap between 2 places for borrow-checking.
2361 /// The places might partially overlap - in this case, we give
2362 /// up and say that they might conflict. This occurs when
2363 /// different fields of a union are borrowed. For example,
2364 /// if `u` is a union, we have no way of telling how disjoint
2365 /// `u.a.x` and `a.b.y` are.
2367 /// The places have the same type, and are either completely disjoint
2368 /// or equal - i.e., they can't "partially" overlap as can occur with
2369 /// unions. This is the "base case" on which we recur for extensions
2372 /// The places are disjoint, so we know all extensions of them
2373 /// will also be disjoint.