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, PlaceElem,
14 PlaceRef, Static, StaticKind
16 use rustc::mir::{Field, 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();
155 nll::replace_regions_in_mir(infcx, def_id, param_env, &mut body, &mut promoted);
156 let body = &body; // no further changes
157 let location_table = &LocationTable::new(body);
159 let mut errors_buffer = Vec::new();
160 let (move_data, move_errors): (MoveData<'tcx>, Option<Vec<(Place<'tcx>, MoveError<'tcx>)>>) =
161 match MoveData::gather_moves(body, tcx) {
162 Ok(move_data) => (move_data, None),
163 Err((move_data, move_errors)) => (move_data, Some(move_errors)),
166 let mdpe = MoveDataParamEnv {
171 let dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
172 let mut flow_inits = FlowAtLocation::new(do_dataflow(
178 MaybeInitializedPlaces::new(tcx, body, &mdpe),
179 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
182 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
183 let borrow_set = Rc::new(BorrowSet::build(
184 tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
186 // If we are in non-lexical mode, compute the non-lexical lifetimes.
187 let (regioncx, polonius_output, opt_closure_req) = nll::compute_regions(
202 // The various `flow_*` structures can be large. We drop `flow_inits` here
203 // so it doesn't overlap with the others below. This reduces peak memory
204 // usage significantly on some benchmarks.
207 let regioncx = Rc::new(regioncx);
209 let flow_borrows = FlowAtLocation::new(do_dataflow(
215 Borrows::new(tcx, body, param_env, regioncx.clone(), &borrow_set),
216 |rs, i| DebugFormatted::new(&rs.location(i)),
218 let flow_uninits = FlowAtLocation::new(do_dataflow(
224 MaybeUninitializedPlaces::new(tcx, body, &mdpe),
225 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
227 let flow_ever_inits = FlowAtLocation::new(do_dataflow(
233 EverInitializedPlaces::new(tcx, body, &mdpe),
234 |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
237 let movable_generator = match tcx.hir().get(id) {
238 Node::Expr(&hir::Expr {
239 node: hir::ExprKind::Closure(.., Some(hir::GeneratorMovability::Static)),
245 let dominators = body.dominators();
247 let mut mbcx = MirBorrowckCtxt {
252 move_data: &mdpe.move_data,
255 locals_are_invalidated_at_exit,
256 access_place_error_reported: Default::default(),
257 reservation_error_reported: Default::default(),
258 reservation_warnings: Default::default(),
259 move_error_reported: BTreeMap::new(),
260 uninitialized_error_reported: Default::default(),
262 // Only downgrade errors on Rust 2015 and refuse to do so on Rust 2018.
263 // FIXME(Centril): In Rust 1.40.0, refuse doing so on 2015 as well and
264 // proceed to throwing out the migration infrastructure.
265 disable_error_downgrading: body.span.rust_2018(),
266 nonlexical_regioncx: regioncx,
267 used_mut: Default::default(),
268 used_mut_upvars: SmallVec::new(),
274 let mut state = Flows::new(
281 if let Some(errors) = move_errors {
282 mbcx.report_move_errors(errors);
284 mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
286 // Convert any reservation warnings into lints.
287 let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
288 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
289 let mut initial_diag =
290 mbcx.report_conflicting_borrow(location, (&place, span), bk, &borrow);
292 let lint_root = if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
293 let scope = mbcx.body.source_info(location).scope;
299 // Span and message don't matter; we overwrite them below anyway
300 let mut diag = mbcx.infcx.tcx.struct_span_lint_hir(
301 MUTABLE_BORROW_RESERVATION_CONFLICT, lint_root, DUMMY_SP, "");
303 diag.message = initial_diag.styled_message().clone();
304 diag.span = initial_diag.span.clone();
306 initial_diag.cancel();
307 diag.buffer(&mut mbcx.errors_buffer);
310 // For each non-user used mutable variable, check if it's been assigned from
311 // a user-declared local. If so, then put that local into the used_mut set.
312 // Note that this set is expected to be small - only upvars from closures
313 // would have a chance of erroneously adding non-user-defined mutable vars
315 let temporary_used_locals: FxHashSet<Local> = mbcx.used_mut.iter()
316 .filter(|&local| mbcx.body.local_decls[*local].is_user_variable.is_none())
319 // For the remaining unused locals that are marked as mutable, we avoid linting any that
320 // were never initialized. These locals may have been removed as unreachable code; or will be
321 // linted as unused variables.
322 let unused_mut_locals = mbcx.body.mut_vars_iter()
323 .filter(|local| !mbcx.used_mut.contains(local))
325 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
327 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
328 let used_mut = mbcx.used_mut;
329 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
330 if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
331 let local_decl = &mbcx.body.local_decls[local];
333 // Skip implicit `self` argument for closures
334 if local.index() == 1 && tcx.is_closure(mbcx.mir_def_id) {
338 // Skip over locals that begin with an underscore or have no name
339 match local_decl.name {
340 Some(name) => if name.as_str().starts_with("_") {
346 let span = local_decl.source_info.span;
347 if span.desugaring_kind().is_some() {
348 // If the `mut` arises as part of a desugaring, we should ignore it.
352 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
353 tcx.struct_span_lint_hir(
355 vsi[local_decl.source_info.scope].lint_root,
357 "variable does not need to be mutable",
359 .span_suggestion_short(
363 Applicability::MachineApplicable,
369 // Buffer any move errors that we collected and de-duplicated.
370 for (_, (_, diag)) in mbcx.move_error_reported {
371 diag.buffer(&mut mbcx.errors_buffer);
374 if !mbcx.errors_buffer.is_empty() {
375 mbcx.errors_buffer.sort_by_key(|diag| diag.span.primary_span());
377 if !mbcx.disable_error_downgrading && tcx.migrate_borrowck() {
378 // When borrowck=migrate, check if AST-borrowck would
379 // error on the given code.
381 // rust-lang/rust#55492, rust-lang/rust#58776 check the base def id
382 // for errors. AST borrowck is responsible for aggregating
383 // `signalled_any_error` from all of the nested closures here.
384 let base_def_id = tcx.closure_base_def_id(def_id);
386 match tcx.borrowck(base_def_id).signalled_any_error {
387 SignalledError::NoErrorsSeen => {
388 // if AST-borrowck signalled no errors, then
389 // downgrade all the buffered MIR-borrowck errors
392 for err in mbcx.errors_buffer.iter_mut() {
393 downgrade_if_error(err);
396 SignalledError::SawSomeError => {
397 // if AST-borrowck signalled a (cancelled) error,
398 // then we will just emit the buffered
399 // MIR-borrowck errors as normal.
404 for diag in mbcx.errors_buffer.drain(..) {
405 DiagnosticBuilder::new_diagnostic(mbcx.infcx.tcx.sess.diagnostic(), diag).emit();
409 let result = BorrowCheckResult {
410 closure_requirements: opt_closure_req,
411 used_mut_upvars: mbcx.used_mut_upvars,
414 debug!("do_mir_borrowck: result = {:#?}", result);
419 fn downgrade_if_error(diag: &mut Diagnostic) {
421 diag.level = Level::Warning;
423 "this error has been downgraded to a warning for backwards \
424 compatibility with previous releases",
426 "this represents potential undefined behavior in your code and \
427 this warning will become a hard error in the future",
429 "for more information, try `rustc --explain E0729`"
434 crate struct MirBorrowckCtxt<'cx, 'tcx> {
435 crate infcx: &'cx InferCtxt<'cx, 'tcx>,
436 body: &'cx Body<'tcx>,
438 param_env: ty::ParamEnv<'tcx>,
439 move_data: &'cx MoveData<'tcx>,
441 /// Map from MIR `Location` to `LocationIndex`; created
442 /// when MIR borrowck begins.
443 location_table: &'cx LocationTable,
445 movable_generator: bool,
446 /// This keeps track of whether local variables are free-ed when the function
447 /// exits even without a `StorageDead`, which appears to be the case for
450 /// I'm not sure this is the right approach - @eddyb could you try and
452 locals_are_invalidated_at_exit: bool,
453 /// This field keeps track of when borrow errors are reported in the access_place function
454 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
455 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
456 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
458 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
459 /// This field keeps track of when borrow conflict errors are reported
460 /// for reservations, so that we don't report seemingly duplicate
461 /// errors for corresponding activations.
463 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
464 // but it is currently inconvenient to track down the `BorrowIndex`
465 // at the time we detect and report a reservation error.
466 reservation_error_reported: FxHashSet<Place<'tcx>>,
467 /// Migration warnings to be reported for #56254. We delay reporting these
468 /// so that we can suppress the warning if there's a corresponding error
469 /// for the activation of the borrow.
470 reservation_warnings: FxHashMap<
472 (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)
474 /// This field keeps track of move errors that are to be reported for given move indicies.
476 /// There are situations where many errors can be reported for a single move out (see #53807)
477 /// and we want only the best of those errors.
479 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
480 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
481 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
482 /// all move errors have been reported, any diagnostics in this map are added to the buffer
485 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
486 /// when errors in the map are being re-added to the error buffer so that errors with the
487 /// same primary span come out in a consistent order.
488 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'cx, 'tcx>, DiagnosticBuilder<'cx>)>,
489 /// This field keeps track of errors reported in the checking of uninitialized variables,
490 /// so that we don't report seemingly duplicate errors.
491 uninitialized_error_reported: FxHashSet<PlaceRef<'cx, 'tcx>>,
492 /// Errors to be reported buffer
493 errors_buffer: Vec<Diagnostic>,
494 /// If there are no errors reported by the HIR borrow checker, we downgrade
495 /// all NLL errors to warnings. Setting this flag disables downgrading.
496 disable_error_downgrading: bool,
497 /// This field keeps track of all the local variables that are declared mut and are mutated.
498 /// Used for the warning issued by an unused mutable local variable.
499 used_mut: FxHashSet<Local>,
500 /// If the function we're checking is a closure, then we'll need to report back the list of
501 /// mutable upvars that have been used. This field keeps track of them.
502 used_mut_upvars: SmallVec<[Field; 8]>,
503 /// Non-lexical region inference context, if NLL is enabled. This
504 /// contains the results from region inference and lets us e.g.
505 /// find out which CFG points are contained in each borrow region.
506 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
508 /// The set of borrows extracted from the MIR
509 borrow_set: Rc<BorrowSet<'tcx>>,
511 /// Dominators for MIR
512 dominators: Dominators<BasicBlock>,
514 /// Information about upvars not necessarily preserved in types or MIR
519 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
520 // 2. loans made in overlapping scopes do not conflict
521 // 3. assignments do not affect things loaned out as immutable
522 // 4. moves do not affect things loaned out in any way
523 impl<'cx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
524 type FlowState = Flows<'cx, 'tcx>;
526 fn body(&self) -> &'cx Body<'tcx> {
530 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
531 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
534 fn visit_statement_entry(
537 stmt: &'cx Statement<'tcx>,
538 flow_state: &Self::FlowState,
541 "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
542 location, stmt, flow_state
544 let span = stmt.source_info.span;
546 self.check_activations(location, span, flow_state);
549 StatementKind::Assign(ref lhs, ref rhs) => {
564 StatementKind::FakeRead(_, ref place) => {
565 // Read for match doesn't access any memory and is used to
566 // assert that a place is safe and live. So we don't have to
567 // do any checks here.
569 // FIXME: Remove check that the place is initialized. This is
570 // needed for now because matches don't have never patterns yet.
571 // So this is the only place we prevent
575 self.check_if_path_or_subpath_is_moved(
577 InitializationRequiringAction::Use,
578 (place.as_ref(), span),
582 StatementKind::SetDiscriminant {
594 StatementKind::InlineAsm(ref asm) => {
595 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
597 // FIXME(eddyb) indirect inline asm outputs should
598 // be encoded through MIR place derefs instead.
602 (Deep, Read(ReadKind::Copy)),
603 LocalMutationIsAllowed::No,
606 self.check_if_path_or_subpath_is_moved(
608 InitializationRequiringAction::Use,
609 (output.as_ref(), o.span),
616 if o.is_rw { Deep } else { Shallow(None) },
617 if o.is_rw { WriteAndRead } else { JustWrite },
622 for (_, input) in asm.inputs.iter() {
623 self.consume_operand(location, (input, span), flow_state);
627 | StatementKind::AscribeUserType(..)
628 | StatementKind::Retag { .. }
629 | StatementKind::StorageLive(..) => {
630 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
633 StatementKind::StorageDead(local) => {
636 (&Place::from(local), span),
637 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
638 LocalMutationIsAllowed::Yes,
645 fn visit_terminator_entry(
648 term: &'cx Terminator<'tcx>,
649 flow_state: &Self::FlowState,
653 "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
654 location, term, flow_state
656 let span = term.source_info.span;
658 self.check_activations(location, span, flow_state);
661 TerminatorKind::SwitchInt {
667 self.consume_operand(loc, (discr, span), flow_state);
669 TerminatorKind::Drop {
670 location: ref drop_place,
674 let gcx = self.infcx.tcx.global_tcx();
676 // Compute the type with accurate region information.
677 let drop_place_ty = drop_place.ty(self.body, self.infcx.tcx);
679 // Erase the regions.
680 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
682 // "Lift" into the gcx -- once regions are erased, this type should be in the
683 // global arenas; this "lift" operation basically just asserts that is true, but
684 // that is useful later.
685 gcx.lift_to_global(&drop_place_ty).unwrap();
687 debug!("visit_terminator_drop \
688 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
689 loc, term, drop_place, drop_place_ty, span);
694 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
695 LocalMutationIsAllowed::Yes,
699 TerminatorKind::DropAndReplace {
700 location: ref drop_place,
701 value: ref new_value,
712 self.consume_operand(
718 TerminatorKind::Call {
725 self.consume_operand(loc, (func, span), flow_state);
727 self.consume_operand(
733 if let Some((ref dest, _ /*bb*/)) = *destination {
743 TerminatorKind::Assert {
750 self.consume_operand(loc, (cond, span), flow_state);
751 use rustc::mir::interpret::PanicInfo;
752 if let PanicInfo::BoundsCheck { ref len, ref index } = *msg {
753 self.consume_operand(loc, (len, span), flow_state);
754 self.consume_operand(loc, (index, span), flow_state);
758 TerminatorKind::Yield {
763 self.consume_operand(loc, (value, span), flow_state);
765 if self.movable_generator {
766 // Look for any active borrows to locals
767 let borrow_set = self.borrow_set.clone();
768 flow_state.with_outgoing_borrows(|borrows| {
770 let borrow = &borrow_set[i];
771 self.check_for_local_borrow(borrow, span);
777 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
778 // Returning from the function implicitly kills storage for all locals and statics.
779 // Often, the storage will already have been killed by an explicit
780 // StorageDead, but we don't always emit those (notably on unwind paths),
781 // so this "extra check" serves as a kind of backup.
782 let borrow_set = self.borrow_set.clone();
783 flow_state.with_outgoing_borrows(|borrows| {
785 let borrow = &borrow_set[i];
786 self.check_for_invalidation_at_exit(loc, borrow, span);
790 TerminatorKind::Goto { target: _ }
791 | TerminatorKind::Abort
792 | TerminatorKind::Unreachable
793 | TerminatorKind::FalseEdges {
797 | TerminatorKind::FalseUnwind {
801 // no data used, thus irrelevant to borrowck
807 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
813 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
814 use self::AccessDepth::{Deep, Shallow};
816 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
817 enum ArtificialField {
822 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
824 /// From the RFC: "A *shallow* access means that the immediate
825 /// fields reached at P are accessed, but references or pointers
826 /// found within are not dereferenced. Right now, the only access
827 /// that is shallow is an assignment like `x = ...;`, which would
828 /// be a *shallow write* of `x`."
829 Shallow(Option<ArtificialField>),
831 /// From the RFC: "A *deep* access means that all data reachable
832 /// through the given place may be invalidated or accesses by
836 /// Access is Deep only when there is a Drop implementation that
837 /// can reach the data behind the reference.
841 /// Kind of access to a value: read or write
842 /// (For informational purposes only)
843 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
845 /// From the RFC: "A *read* means that the existing data may be
846 /// read, but will not be changed."
849 /// From the RFC: "A *write* means that the data may be mutated to
850 /// new values or otherwise invalidated (for example, it could be
851 /// de-initialized, as in a move operation).
854 /// For two-phase borrows, we distinguish a reservation (which is treated
855 /// like a Read) from an activation (which is treated like a write), and
856 /// each of those is furthermore distinguished from Reads/Writes above.
857 Reservation(WriteKind),
858 Activation(WriteKind, BorrowIndex),
861 /// Kind of read access to a value
862 /// (For informational purposes only)
863 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
869 /// Kind of write access to a value
870 /// (For informational purposes only)
871 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
874 MutableBorrow(BorrowKind),
879 /// When checking permissions for a place access, this flag is used to indicate that an immutable
880 /// local place can be mutated.
882 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
883 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
884 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
885 // `is_declared_mutable()`.
886 // - Take flow state into consideration in `is_assignable()` for local variables.
887 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
888 enum LocalMutationIsAllowed {
890 /// We want use of immutable upvars to cause a "write to immutable upvar"
891 /// error, not an "reassignment" error.
896 #[derive(Copy, Clone, Debug)]
897 enum InitializationRequiringAction {
906 struct RootPlace<'d, 'tcx> {
907 place_base: &'d PlaceBase<'tcx>,
908 place_projection: &'d [PlaceElem<'tcx>],
909 is_local_mutation_allowed: LocalMutationIsAllowed,
912 impl InitializationRequiringAction {
913 fn as_noun(self) -> &'static str {
915 InitializationRequiringAction::Update => "update",
916 InitializationRequiringAction::Borrow => "borrow",
917 InitializationRequiringAction::MatchOn => "use", // no good noun
918 InitializationRequiringAction::Use => "use",
919 InitializationRequiringAction::Assignment => "assign",
920 InitializationRequiringAction::PartialAssignment => "assign to part",
924 fn as_verb_in_past_tense(self) -> &'static str {
926 InitializationRequiringAction::Update => "updated",
927 InitializationRequiringAction::Borrow => "borrowed",
928 InitializationRequiringAction::MatchOn => "matched on",
929 InitializationRequiringAction::Use => "used",
930 InitializationRequiringAction::Assignment => "assigned",
931 InitializationRequiringAction::PartialAssignment => "partially assigned",
936 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
937 /// If there are no errors reported by the HIR borrow checker, we downgrade
938 /// all NLL errors to warnings. Calling this disables downgrading.
939 crate fn disable_error_downgrading(&mut self) {
940 self.disable_error_downgrading = true;
943 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
944 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
945 /// place is initialized and (b) it is not borrowed in some way that would prevent this
948 /// Returns `true` if an error is reported.
952 place_span: (&Place<'tcx>, Span),
953 kind: (AccessDepth, ReadOrWrite),
954 is_local_mutation_allowed: LocalMutationIsAllowed,
955 flow_state: &Flows<'cx, 'tcx>,
959 if let Activation(_, borrow_index) = rw {
960 if self.reservation_error_reported.contains(&place_span.0) {
962 "skipping access_place for activation of invalid reservation \
963 place: {:?} borrow_index: {:?}",
964 place_span.0, borrow_index
970 // Check is_empty() first because it's the common case, and doing that
971 // way we avoid the clone() call.
972 if !self.access_place_error_reported.is_empty() &&
974 .access_place_error_reported
975 .contains(&(place_span.0.clone(), place_span.1))
978 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
984 let mutability_error =
985 self.check_access_permissions(
988 is_local_mutation_allowed,
993 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
995 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
996 // Suppress this warning when there's an error being emited for the
997 // same borrow: fixing the error is likely to fix the warning.
998 self.reservation_warnings.remove(&borrow_idx);
1001 if conflict_error || mutability_error {
1003 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
1007 self.access_place_error_reported
1008 .insert((place_span.0.clone(), place_span.1));
1012 fn check_access_for_conflict(
1015 place_span: (&Place<'tcx>, Span),
1018 flow_state: &Flows<'cx, 'tcx>,
1021 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1022 location, place_span, sd, rw,
1025 let mut error_reported = false;
1026 let tcx = self.infcx.tcx;
1027 let body = self.body;
1028 let param_env = self.param_env;
1029 let location_table = self.location_table.start_index(location);
1030 let borrow_set = self.borrow_set.clone();
1031 each_borrow_involving_path(
1039 flow_state.borrows_in_scope(location_table),
1040 |this, borrow_index, borrow| match (rw, borrow.kind) {
1041 // Obviously an activation is compatible with its own
1042 // reservation (or even prior activating uses of same
1043 // borrow); so don't check if they interfere.
1045 // NOTE: *reservations* do conflict with themselves;
1046 // thus aren't injecting unsoundenss w/ this check.)
1047 (Activation(_, activating), _) if activating == borrow_index => {
1049 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1050 skipping {:?} b/c activation of same borrow_index",
1054 (borrow_index, borrow),
1059 (Read(_), BorrowKind::Shared)
1060 | (Read(_), BorrowKind::Shallow)
1061 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
1062 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
1066 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1067 // Handled by initialization checks.
1071 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
1072 // Reading from mere reservations of mutable-borrows is OK.
1073 if !is_active(&this.dominators, borrow, location) {
1074 assert!(allow_two_phase_borrow(borrow.kind));
1075 return Control::Continue;
1078 error_reported = true;
1081 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1082 .buffer(&mut this.errors_buffer);
1084 ReadKind::Borrow(bk) => {
1085 this.report_conflicting_borrow(location, place_span, bk, borrow)
1086 .buffer(&mut this.errors_buffer);
1092 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
1093 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared) if {
1094 tcx.migrate_borrowck() && this.borrow_set.location_map.contains_key(&location)
1096 let bi = this.borrow_set.location_map[&location];
1098 "recording invalid reservation of place: {:?} with \
1099 borrow index {:?} as warning",
1103 // rust-lang/rust#56254 - This was previously permitted on
1104 // the 2018 edition so we emit it as a warning. We buffer
1105 // these sepately so that we only emit a warning if borrow
1106 // checking was otherwise successful.
1107 this.reservation_warnings.insert(
1109 (place_span.0.clone(), place_span.1, location, bk, borrow.clone()),
1112 // Don't suppress actual errors.
1116 (Reservation(kind), _)
1117 | (Activation(kind, _), _)
1118 | (Write(kind), _) => {
1120 Reservation(..) => {
1122 "recording invalid reservation of \
1126 this.reservation_error_reported.insert(place_span.0.clone());
1128 Activation(_, activating) => {
1130 "observing check_place for activation of \
1131 borrow_index: {:?}",
1135 Read(..) | Write(..) => {}
1138 error_reported = true;
1140 WriteKind::MutableBorrow(bk) => {
1141 this.report_conflicting_borrow(location, place_span, bk, borrow)
1142 .buffer(&mut this.errors_buffer);
1144 WriteKind::StorageDeadOrDrop => {
1145 this.report_borrowed_value_does_not_live_long_enough(
1151 WriteKind::Mutate => {
1152 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1154 WriteKind::Move => {
1155 this.report_move_out_while_borrowed(location, place_span, borrow)
1169 place_span: (&'cx Place<'tcx>, Span),
1172 flow_state: &Flows<'cx, 'tcx>,
1174 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1176 MutateMode::WriteAndRead => {
1177 self.check_if_path_or_subpath_is_moved(
1179 InitializationRequiringAction::Update,
1180 (place_span.0.as_ref(), place_span.1),
1184 MutateMode::JustWrite => {
1185 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1189 // Special case: you can assign a immutable local variable
1190 // (e.g., `x = ...`) so long as it has never been initialized
1191 // before (at this point in the flow).
1193 base: PlaceBase::Local(local),
1196 if let Mutability::Not = self.body.local_decls[*local].mutability {
1197 // check for reassignments to immutable local variables
1198 self.check_if_reassignment_to_immutable_state(
1208 // Otherwise, use the normal access permission rules.
1212 (kind, Write(WriteKind::Mutate)),
1213 LocalMutationIsAllowed::No,
1221 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1222 flow_state: &Flows<'cx, 'tcx>,
1225 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1226 let access_kind = match bk {
1227 BorrowKind::Shallow => {
1228 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1230 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1231 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1232 let wk = WriteKind::MutableBorrow(bk);
1233 if allow_two_phase_borrow(bk) {
1234 (Deep, Reservation(wk))
1245 LocalMutationIsAllowed::No,
1249 let action = if bk == BorrowKind::Shallow {
1250 InitializationRequiringAction::MatchOn
1252 InitializationRequiringAction::Borrow
1255 self.check_if_path_or_subpath_is_moved(
1258 (place.as_ref(), span),
1263 Rvalue::Use(ref operand)
1264 | Rvalue::Repeat(ref operand, _)
1265 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1266 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1267 self.consume_operand(location, (operand, span), flow_state)
1270 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1271 let af = match *rvalue {
1272 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1273 Rvalue::Discriminant(..) => None,
1274 _ => unreachable!(),
1279 (Shallow(af), Read(ReadKind::Copy)),
1280 LocalMutationIsAllowed::No,
1283 self.check_if_path_or_subpath_is_moved(
1285 InitializationRequiringAction::Use,
1286 (place.as_ref(), span),
1291 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1292 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1293 self.consume_operand(location, (operand1, span), flow_state);
1294 self.consume_operand(location, (operand2, span), flow_state);
1297 Rvalue::NullaryOp(_op, _ty) => {
1298 // nullary ops take no dynamic input; no borrowck effect.
1300 // FIXME: is above actually true? Do we want to track
1301 // the fact that uninitialized data can be created via
1305 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1306 // We need to report back the list of mutable upvars that were
1307 // moved into the closure and subsequently used by the closure,
1308 // in order to populate our used_mut set.
1309 match **aggregate_kind {
1310 AggregateKind::Closure(def_id, _)
1311 | AggregateKind::Generator(def_id, _, _) => {
1312 let BorrowCheckResult {
1314 } = self.infcx.tcx.mir_borrowck(def_id);
1315 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1316 for field in used_mut_upvars {
1317 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1320 AggregateKind::Adt(..)
1321 | AggregateKind::Array(..)
1322 | AggregateKind::Tuple { .. } => (),
1325 for operand in operands {
1326 self.consume_operand(location, (operand, span), flow_state);
1332 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1333 let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1334 if !place.projection.is_empty() {
1335 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1336 this.used_mut_upvars.push(field);
1338 } else if let PlaceBase::Local(local) = place.base {
1339 this.used_mut.insert(local);
1343 // This relies on the current way that by-value
1344 // captures of a closure are copied/moved directly
1345 // when generating MIR.
1347 Operand::Move(Place {
1348 base: PlaceBase::Local(local),
1351 Operand::Copy(Place {
1352 base: PlaceBase::Local(local),
1354 }) if self.body.local_decls[local].is_user_variable.is_none() => {
1355 if self.body.local_decls[local].ty.is_mutable_ptr() {
1356 // The variable will be marked as mutable by the borrow.
1359 // This is an edge case where we have a `move` closure
1360 // inside a non-move closure, and the inner closure
1361 // contains a mutation:
1364 // || { move || { i += 1; }; };
1366 // In this case our usual strategy of assuming that the
1367 // variable will be captured by mutable reference is
1368 // wrong, since `i` can be copied into the inner
1369 // closure from a shared reference.
1371 // As such we have to search for the local that this
1372 // capture comes from and mark it as being used as mut.
1374 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1375 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1376 &self.move_data.inits[init_index]
1378 bug!("temporary should be initialized exactly once")
1381 let loc = match init.location {
1382 InitLocation::Statement(stmt) => stmt,
1383 _ => bug!("temporary initialized in arguments"),
1386 let bbd = &self.body[loc.block];
1387 let stmt = &bbd.statements[loc.statement_index];
1388 debug!("temporary assigned in: stmt={:?}", stmt);
1390 if let StatementKind::Assign(_, box Rvalue::Ref(_, _, ref source)) = stmt.kind {
1391 propagate_closure_used_mut_place(self, source);
1393 bug!("closures should only capture user variables \
1394 or references to user variables");
1397 Operand::Move(ref place)
1398 | Operand::Copy(ref place) => {
1399 propagate_closure_used_mut_place(self, place);
1401 Operand::Constant(..) => {}
1408 (operand, span): (&'cx Operand<'tcx>, Span),
1409 flow_state: &Flows<'cx, 'tcx>,
1412 Operand::Copy(ref place) => {
1413 // copy of place: check if this is "copy of frozen path"
1414 // (FIXME: see check_loans.rs)
1418 (Deep, Read(ReadKind::Copy)),
1419 LocalMutationIsAllowed::No,
1423 // Finally, check if path was already moved.
1424 self.check_if_path_or_subpath_is_moved(
1426 InitializationRequiringAction::Use,
1427 (place.as_ref(), span),
1431 Operand::Move(ref place) => {
1432 // move of place: check if this is move of already borrowed path
1436 (Deep, Write(WriteKind::Move)),
1437 LocalMutationIsAllowed::Yes,
1441 // Finally, check if path was already moved.
1442 self.check_if_path_or_subpath_is_moved(
1444 InitializationRequiringAction::Use,
1445 (place.as_ref(), span),
1449 Operand::Constant(_) => {}
1453 /// Checks whether a borrow of this place is invalidated when the function
1455 fn check_for_invalidation_at_exit(
1458 borrow: &BorrowData<'tcx>,
1461 debug!("check_for_invalidation_at_exit({:?})", borrow);
1462 let place = &borrow.borrowed_place;
1463 let root_place = self.prefixes(place.as_ref(), PrefixSet::All).last().unwrap();
1465 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1466 // we just know that all locals are dropped at function exit (otherwise
1467 // we'll have a memory leak) and assume that all statics have a destructor.
1469 // FIXME: allow thread-locals to borrow other thread locals?
1471 assert!(root_place.projection.is_empty());
1472 let (might_be_alive, will_be_dropped) = match root_place.base {
1473 PlaceBase::Static(box Static {
1474 kind: StaticKind::Promoted(..),
1479 PlaceBase::Static(box Static {
1480 kind: StaticKind::Static,
1483 // Thread-locals might be dropped after the function exits, but
1484 // "true" statics will never be.
1485 (true, self.is_place_thread_local(root_place))
1487 PlaceBase::Local(_) => {
1488 // Locals are always dropped at function exit, and if they
1489 // have a destructor it would've been called already.
1490 (false, self.locals_are_invalidated_at_exit)
1494 if !will_be_dropped {
1496 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1502 let sd = if might_be_alive { Deep } else { Shallow(None) };
1504 if places_conflict::borrow_conflicts_with_place(
1512 places_conflict::PlaceConflictBias::Overlap,
1514 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1515 // FIXME: should be talking about the region lifetime instead
1516 // of just a span here.
1517 let span = self.infcx.tcx.sess.source_map().end_point(span);
1518 self.report_borrowed_value_does_not_live_long_enough(
1527 /// Reports an error if this is a borrow of local data.
1528 /// This is called for all Yield statements on movable generators
1529 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1530 debug!("check_for_local_borrow({:?})", borrow);
1532 if borrow_of_local_data(&borrow.borrowed_place) {
1533 let err = self.cannot_borrow_across_generator_yield(
1534 self.retrieve_borrow_spans(borrow).var_or_use(),
1538 err.buffer(&mut self.errors_buffer);
1542 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1543 // Two-phase borrow support: For each activation that is newly
1544 // generated at this statement, check if it interferes with
1546 let borrow_set = self.borrow_set.clone();
1547 for &borrow_index in borrow_set.activations_at_location(location) {
1548 let borrow = &borrow_set[borrow_index];
1550 // only mutable borrows should be 2-phase
1551 assert!(match borrow.kind {
1552 BorrowKind::Shared | BorrowKind::Shallow => false,
1553 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1558 (&borrow.borrowed_place, span),
1561 Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1563 LocalMutationIsAllowed::No,
1566 // We do not need to call `check_if_path_or_subpath_is_moved`
1567 // again, as we already called it when we made the
1568 // initial reservation.
1573 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
1574 fn check_if_reassignment_to_immutable_state(
1578 place_span: (&Place<'tcx>, Span),
1579 flow_state: &Flows<'cx, 'tcx>,
1581 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1583 // Check if any of the initializiations of `local` have happened yet:
1584 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1585 // And, if so, report an error.
1586 let init = &self.move_data.inits[init_index];
1587 let span = init.span(&self.body);
1588 self.report_illegal_reassignment(
1589 location, place_span, span, place_span.0
1594 fn check_if_full_path_is_moved(
1597 desired_action: InitializationRequiringAction,
1598 place_span: (PlaceRef<'cx, 'tcx>, Span),
1599 flow_state: &Flows<'cx, 'tcx>,
1601 let maybe_uninits = &flow_state.uninits;
1605 // 1. Move of `a.b.c`, use of `a.b.c`
1606 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1607 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1608 // partial initialization support, one might have `a.x`
1609 // initialized but not `a.b`.
1613 // 4. Move of `a.b.c`, use of `a.b.d`
1614 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1615 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1616 // must have been initialized for the use to be sound.
1617 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1619 // The dataflow tracks shallow prefixes distinctly (that is,
1620 // field-accesses on P distinctly from P itself), in order to
1621 // track substructure initialization separately from the whole
1624 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1625 // which we have a MovePath is `a.b`, then that means that the
1626 // initialization state of `a.b` is all we need to inspect to
1627 // know if `a.b.c` is valid (and from that we infer that the
1628 // dereference and `.d` access is also valid, since we assume
1629 // `a.b.c` is assigned a reference to a initialized and
1630 // well-formed record structure.)
1632 // Therefore, if we seek out the *closest* prefix for which we
1633 // have a MovePath, that should capture the initialization
1634 // state for the place scenario.
1636 // This code covers scenarios 1, 2, and 3.
1638 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1639 match self.move_path_closest_to(place_span.0) {
1640 Ok((prefix, mpi)) => {
1641 if maybe_uninits.contains(mpi) {
1642 self.report_use_of_moved_or_uninitialized(
1645 (prefix, place_span.0, place_span.1),
1648 return; // don't bother finding other problems.
1651 Err(NoMovePathFound::ReachedStatic) => {
1652 // Okay: we do not build MoveData for static variables
1653 } // Only query longest prefix with a MovePath, not further
1654 // ancestors; dataflow recurs on children when parents
1655 // move (to support partial (re)inits).
1657 // (I.e., querying parents breaks scenario 7; but may want
1658 // to do such a query based on partial-init feature-gate.)
1662 fn check_if_path_or_subpath_is_moved(
1665 desired_action: InitializationRequiringAction,
1666 place_span: (PlaceRef<'cx, 'tcx>, Span),
1667 flow_state: &Flows<'cx, 'tcx>,
1669 let maybe_uninits = &flow_state.uninits;
1673 // 1. Move of `a.b.c`, use of `a` or `a.b`
1674 // partial initialization support, one might have `a.x`
1675 // initialized but not `a.b`.
1676 // 2. All bad scenarios from `check_if_full_path_is_moved`
1680 // 3. Move of `a.b.c`, use of `a.b.d`
1681 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1682 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1683 // must have been initialized for the use to be sound.
1684 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1686 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1688 // A move of any shallow suffix of `place` also interferes
1689 // with an attempt to use `place`. This is scenario 3 above.
1691 // (Distinct from handling of scenarios 1+2+4 above because
1692 // `place` does not interfere with suffixes of its prefixes,
1693 // e.g., `a.b.c` does not interfere with `a.b.d`)
1695 // This code covers scenario 1.
1697 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1698 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1699 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1700 self.report_use_of_moved_or_uninitialized(
1703 (place_span.0, place_span.0, place_span.1),
1706 return; // don't bother finding other problems.
1711 /// Currently MoveData does not store entries for all places in
1712 /// the input MIR. For example it will currently filter out
1713 /// places that are Copy; thus we do not track places of shared
1714 /// reference type. This routine will walk up a place along its
1715 /// prefixes, searching for a foundational place that *is*
1716 /// tracked in the MoveData.
1718 /// An Err result includes a tag indicated why the search failed.
1719 /// Currently this can only occur if the place is built off of a
1720 /// static variable, as we do not track those in the MoveData.
1721 fn move_path_closest_to(
1723 place: PlaceRef<'cx, 'tcx>,
1724 ) -> Result<(PlaceRef<'cx, 'tcx>, MovePathIndex), NoMovePathFound> {
1725 let mut last_prefix = place.base;
1727 for prefix in self.prefixes(place, PrefixSet::All) {
1728 if let Some(mpi) = self.move_path_for_place(prefix) {
1729 return Ok((prefix, mpi));
1732 last_prefix = prefix.base;
1736 PlaceBase::Local(_) => panic!("should have move path for every Local"),
1737 PlaceBase::Static(_) => Err(NoMovePathFound::ReachedStatic),
1741 fn move_path_for_place(&mut self, place: PlaceRef<'cx, 'tcx>) -> Option<MovePathIndex> {
1742 // If returns None, then there is no move path corresponding
1743 // to a direct owner of `place` (which means there is nothing
1744 // that borrowck tracks for its analysis).
1746 match self.move_data.rev_lookup.find(place) {
1747 LookupResult::Parent(_) => None,
1748 LookupResult::Exact(mpi) => Some(mpi),
1752 fn check_if_assigned_path_is_moved(
1755 (place, span): (&'cx Place<'tcx>, Span),
1756 flow_state: &Flows<'cx, 'tcx>,
1758 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1760 // None case => assigning to `x` does not require `x` be initialized.
1761 for (i, elem) in place.projection.iter().enumerate().rev() {
1763 ProjectionElem::Index(_/*operand*/) |
1764 ProjectionElem::ConstantIndex { .. } |
1765 // assigning to P[i] requires P to be valid.
1766 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1767 // assigning to (P->variant) is okay if assigning to `P` is okay
1769 // FIXME: is this true even if P is a adt with a dtor?
1772 // assigning to (*P) requires P to be initialized
1773 ProjectionElem::Deref => {
1774 let proj_base = &place.projection[..i];
1776 self.check_if_full_path_is_moved(
1777 location, InitializationRequiringAction::Use,
1780 projection: proj_base,
1781 }, span), flow_state);
1782 // (base initialized; no need to
1787 ProjectionElem::Subslice { .. } => {
1788 panic!("we don't allow assignments to subslices, location: {:?}",
1792 ProjectionElem::Field(..) => {
1793 let proj_base = &place.projection[..i];
1794 // if type of `P` has a dtor, then
1795 // assigning to `P.f` requires `P` itself
1796 // be already initialized
1797 let tcx = self.infcx.tcx;
1798 let base_ty = Place::ty_from(&place.base, proj_base, self.body, tcx).ty;
1800 ty::Adt(def, _) if def.has_dtor(tcx) => {
1801 self.check_if_path_or_subpath_is_moved(
1802 location, InitializationRequiringAction::Assignment,
1805 projection: proj_base,
1806 }, span), flow_state);
1808 // (base initialized; no need to
1813 // Once `let s; s.x = V; read(s.x);`,
1814 // is allowed, remove this match arm.
1815 ty::Adt(..) | ty::Tuple(..) => {
1816 check_parent_of_field(self, location, PlaceRef {
1818 projection: proj_base,
1819 }, span, flow_state);
1821 if let PlaceBase::Local(local) = place.base {
1822 // rust-lang/rust#21232,
1823 // #54499, #54986: during
1824 // period where we reject
1825 // partial initialization, do
1826 // not complain about
1827 // unnecessary `mut` on an
1828 // attempt to do a partial
1830 self.used_mut.insert(local);
1840 fn check_parent_of_field<'cx, 'tcx>(
1841 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1843 base: PlaceRef<'cx, 'tcx>,
1845 flow_state: &Flows<'cx, '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, _) =
1905 Place::ty_from(base.base, base.projection, this.body, tcx).ty.sty
1908 if this.move_data.path_map[mpi].iter().any(|moi| {
1909 this.move_data.moves[*moi].source.is_predecessor_of(
1910 location, this.body,
1918 this.report_use_of_moved_or_uninitialized(
1920 InitializationRequiringAction::PartialAssignment,
1921 (prefix, base, span),
1928 /// Checks the permissions for the given place and read or write kind
1930 /// Returns `true` if an error is reported.
1931 fn check_access_permissions(
1933 (place, span): (&Place<'tcx>, Span),
1935 is_local_mutation_allowed: LocalMutationIsAllowed,
1936 flow_state: &Flows<'cx, 'tcx>,
1940 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1941 place, kind, is_local_mutation_allowed
1947 // rust-lang/rust#21232, #54986: during period where we reject
1948 // partial initialization, do not complain about mutability
1949 // errors except for actual mutation (as opposed to an attempt
1950 // to do a partial initialization).
1951 let previously_initialized = if let PlaceBase::Local(local) = place.base {
1952 self.is_local_ever_initialized(local, flow_state).is_some()
1958 Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1959 | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
1960 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1961 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. })) => {
1962 let is_local_mutation_allowed = match borrow_kind {
1963 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1964 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1965 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1967 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1969 self.add_used_mut(root_place, flow_state);
1973 error_access = AccessKind::MutableBorrow;
1974 the_place_err = place_err;
1978 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1979 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1981 self.add_used_mut(root_place, flow_state);
1985 error_access = AccessKind::Mutate;
1986 the_place_err = place_err;
1991 Reservation(wk @ WriteKind::Move)
1992 | Write(wk @ WriteKind::Move)
1993 | Reservation(wk @ WriteKind::StorageDeadOrDrop)
1994 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1995 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow))
1996 | Write(wk @ WriteKind::StorageDeadOrDrop)
1997 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1998 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
1999 if let (Err(place_err), true) = (
2000 self.is_mutable(place.as_ref(), is_local_mutation_allowed),
2001 self.errors_buffer.is_empty()
2003 if self.infcx.tcx.migrate_borrowck() {
2004 // rust-lang/rust#46908: In pure NLL mode this
2005 // code path should be unreachable (and thus
2006 // we signal an ICE in the else branch
2007 // here). But we can legitimately get here
2008 // under borrowck=migrate mode, so instead of
2009 // ICE'ing we instead report a legitimate
2010 // error (which will then be downgraded to a
2011 // warning by the migrate machinery).
2012 error_access = match wk {
2013 WriteKind::MutableBorrow(_) => AccessKind::MutableBorrow,
2014 WriteKind::Move => AccessKind::Move,
2015 WriteKind::StorageDeadOrDrop |
2016 WriteKind::Mutate => AccessKind::Mutate,
2018 self.report_mutability_error(
2028 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2037 // permission checks are done at Reservation point.
2040 Read(ReadKind::Borrow(BorrowKind::Unique))
2041 | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
2042 | Read(ReadKind::Borrow(BorrowKind::Shared))
2043 | Read(ReadKind::Borrow(BorrowKind::Shallow))
2044 | Read(ReadKind::Copy) => {
2045 // Access authorized
2050 // at this point, we have set up the error reporting state.
2051 return if previously_initialized {
2052 self.report_mutability_error(
2065 fn is_local_ever_initialized(
2068 flow_state: &Flows<'cx, 'tcx>,
2069 ) -> Option<InitIndex> {
2070 let mpi = self.move_data.rev_lookup.find_local(local);
2071 let ii = &self.move_data.init_path_map[mpi];
2073 if flow_state.ever_inits.contains(index) {
2080 /// Adds the place into the used mutable variables set
2081 fn add_used_mut<'d>(&mut self, root_place: RootPlace<'d, 'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2084 place_base: PlaceBase::Local(local),
2085 place_projection: [],
2086 is_local_mutation_allowed,
2088 // If the local may have been initialized, and it is now currently being
2089 // mutated, then it is justified to be annotated with the `mut`
2090 // keyword, since the mutation may be a possible reassignment.
2091 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes &&
2092 self.is_local_ever_initialized(*local, flow_state).is_some()
2094 self.used_mut.insert(*local);
2099 place_projection: _,
2100 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2104 place_projection: place_projection @ [.., _],
2105 is_local_mutation_allowed: _,
2107 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2109 projection: &place_projection,
2111 self.used_mut_upvars.push(field);
2115 place_base: PlaceBase::Static(..),
2116 place_projection: [],
2117 is_local_mutation_allowed: _,
2122 /// Whether this value can be written or borrowed mutably.
2123 /// Returns the root place if the place passed in is a projection.
2126 place: PlaceRef<'d, 'tcx>,
2127 is_local_mutation_allowed: LocalMutationIsAllowed,
2128 ) -> Result<RootPlace<'d, 'tcx>, PlaceRef<'d, 'tcx>> {
2131 base: PlaceBase::Local(local),
2134 let local = &self.body.local_decls[*local];
2135 match local.mutability {
2136 Mutability::Not => match is_local_mutation_allowed {
2137 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2138 place_base: place.base,
2139 place_projection: place.projection,
2140 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2142 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2143 place_base: place.base,
2144 place_projection: place.projection,
2145 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2147 LocalMutationIsAllowed::No => Err(place),
2149 Mutability::Mut => Ok(RootPlace {
2150 place_base: place.base,
2151 place_projection: place.projection,
2152 is_local_mutation_allowed,
2156 // The rules for promotion are made by `qualify_consts`, there wouldn't even be a
2157 // `Place::Promoted` if the promotion weren't 100% legal. So we just forward this
2159 base: PlaceBase::Static(box Static {
2160 kind: StaticKind::Promoted(..),
2166 place_base: place.base,
2167 place_projection: place.projection,
2168 is_local_mutation_allowed,
2171 base: PlaceBase::Static(box Static {
2172 kind: StaticKind::Static,
2178 if !self.infcx.tcx.is_mutable_static(*def_id) {
2182 place_base: place.base,
2183 place_projection: place.projection,
2184 is_local_mutation_allowed,
2190 projection: [proj_base @ .., elem],
2193 ProjectionElem::Deref => {
2195 Place::ty_from(place.base, proj_base, self.body, self.infcx.tcx).ty;
2197 // Check the kind of deref to decide
2199 ty::Ref(_, _, mutbl) => {
2201 // Shared borrowed data is never mutable
2202 hir::MutImmutable => Err(place),
2203 // Mutably borrowed data is mutable, but only if we have a
2204 // unique path to the `&mut`
2205 hir::MutMutable => {
2206 let mode = match self.is_upvar_field_projection(place) {
2208 if self.upvars[field.index()].by_ref =>
2210 is_local_mutation_allowed
2212 _ => LocalMutationIsAllowed::Yes,
2215 self.is_mutable(PlaceRef {
2217 projection: proj_base,
2222 ty::RawPtr(tnm) => {
2224 // `*const` raw pointers are not mutable
2225 hir::MutImmutable => Err(place),
2226 // `*mut` raw pointers are always mutable, regardless of
2227 // context. The users have to check by themselves.
2228 hir::MutMutable => {
2230 place_base: place.base,
2231 place_projection: place.projection,
2232 is_local_mutation_allowed,
2237 // `Box<T>` owns its content, so mutable if its location is mutable
2238 _ if base_ty.is_box() => {
2239 self.is_mutable(PlaceRef {
2241 projection: proj_base,
2242 }, is_local_mutation_allowed)
2244 // Deref should only be for reference, pointers or boxes
2245 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2248 // All other projections are owned by their base path, so mutable if
2249 // base path is mutable
2250 ProjectionElem::Field(..)
2251 | ProjectionElem::Index(..)
2252 | ProjectionElem::ConstantIndex { .. }
2253 | ProjectionElem::Subslice { .. }
2254 | ProjectionElem::Downcast(..) => {
2255 let upvar_field_projection = self.is_upvar_field_projection(place);
2256 if let Some(field) = upvar_field_projection {
2257 let upvar = &self.upvars[field.index()];
2259 "upvar.mutability={:?} local_mutation_is_allowed={:?} \
2261 upvar, is_local_mutation_allowed, place
2263 match (upvar.mutability, is_local_mutation_allowed) {
2264 (Mutability::Not, LocalMutationIsAllowed::No)
2265 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2268 (Mutability::Not, LocalMutationIsAllowed::Yes)
2269 | (Mutability::Mut, _) => {
2270 // Subtle: this is an upvar
2271 // reference, so it looks like
2272 // `self.foo` -- we want to double
2273 // check that the location `*self`
2274 // is mutable (i.e., this is not a
2275 // `Fn` closure). But if that
2276 // check succeeds, we want to
2277 // *blame* the mutability on
2278 // `place` (that is,
2279 // `self.foo`). This is used to
2280 // propagate the info about
2281 // whether mutability declarations
2282 // are used outwards, so that we register
2283 // the outer variable as mutable. Otherwise a
2284 // test like this fails to record the `mut`
2288 // fn foo<F: FnOnce()>(_f: F) { }
2290 // let var = Vec::new();
2296 let _ = self.is_mutable(PlaceRef {
2298 projection: proj_base,
2299 }, is_local_mutation_allowed)?;
2301 place_base: place.base,
2302 place_projection: place.projection,
2303 is_local_mutation_allowed,
2308 self.is_mutable(PlaceRef {
2310 projection: proj_base,
2311 }, is_local_mutation_allowed)
2319 /// If `place` is a field projection, and the field is being projected from a closure type,
2320 /// then returns the index of the field being projected. Note that this closure will always
2321 /// be `self` in the current MIR, because that is the only time we directly access the fields
2322 /// of a closure type.
2323 pub fn is_upvar_field_projection(&self, place_ref: PlaceRef<'cx, 'tcx>) -> Option<Field> {
2324 let mut place_projection = place_ref.projection;
2325 let mut by_ref = false;
2327 if let [.., ProjectionElem::Deref] = place_projection {
2328 place_projection = &place_projection[..place_projection.len() - 1];
2332 match place_projection {
2333 [.., ProjectionElem::Field(field, _ty)] => {
2334 let base = &place_projection[..place_projection.len() - 1];
2335 let tcx = self.infcx.tcx;
2336 let base_ty = Place::ty_from(place_ref.base, base, self.body, tcx).ty;
2338 if (base_ty.is_closure() || base_ty.is_generator()) &&
2339 (!by_ref || self.upvars[field.index()].by_ref) {
2351 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2352 enum NoMovePathFound {
2356 /// The degree of overlap between 2 places for borrow-checking.
2358 /// The places might partially overlap - in this case, we give
2359 /// up and say that they might conflict. This occurs when
2360 /// different fields of a union are borrowed. For example,
2361 /// if `u` is a union, we have no way of telling how disjoint
2362 /// `u.a.x` and `a.b.y` are.
2364 /// The places have the same type, and are either completely disjoint
2365 /// or equal - i.e., they can't "partially" overlap as can occur with
2366 /// unions. This is the "base case" on which we recur for extensions
2369 /// The places are disjoint, so we know all extensions of them
2370 /// will also be disjoint.