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, Static,
17 use rustc::mir::{Field, Projection, ProjectionElem, Rvalue, Statement, StatementKind};
18 use rustc::mir::{Terminator, TerminatorKind};
19 use rustc::ty::query::Providers;
20 use rustc::ty::{self, TyCtxt};
22 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, Level};
23 use rustc_data_structures::bit_set::BitSet;
24 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
25 use rustc_data_structures::graph::dominators::Dominators;
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};
44 use crate::util::borrowck_errors::{BorrowckErrors, Origin};
46 use self::borrow_set::{BorrowData, BorrowSet};
47 use self::flows::Flows;
48 use self::location::LocationTable;
49 use self::prefixes::PrefixSet;
50 use self::MutateMode::{JustWrite, WriteAndRead};
51 use self::mutability_errors::AccessKind;
53 use self::path_utils::*;
61 mod mutability_errors;
64 crate mod places_conflict;
70 // FIXME(eddyb) perhaps move this somewhere more centrally.
77 /// If true, the capture is behind a reference.
80 mutability: Mutability,
83 pub fn provide(providers: &mut Providers<'_>) {
84 *providers = Providers {
90 fn mir_borrowck<'tcx>(tcx: TyCtxt<'tcx, 'tcx, 'tcx>, def_id: DefId) -> BorrowCheckResult<'tcx> {
91 let input_body = tcx.mir_validated(def_id);
92 debug!("run query mir_borrowck: {}", tcx.def_path_str(def_id));
94 let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
95 let input_body: &Body<'_> = &input_body.borrow();
96 do_mir_borrowck(&infcx, input_body, def_id)
98 debug!("mir_borrowck done");
103 fn do_mir_borrowck<'a, 'gcx, 'tcx>(
104 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
105 input_body: &Body<'gcx>,
107 ) -> BorrowCheckResult<'gcx> {
108 debug!("do_mir_borrowck(def_id = {:?})", def_id);
111 let attributes = tcx.get_attrs(def_id);
112 let param_env = tcx.param_env(def_id);
115 .as_local_hir_id(def_id)
116 .expect("do_mir_borrowck: non-local DefId");
118 // Gather the upvars of a closure, if any.
119 let tables = tcx.typeck_tables_of(def_id);
120 let upvars: Vec<_> = tables
124 .flat_map(|v| v.values())
126 let var_hir_id = upvar_id.var_path.hir_id;
127 let var_node_id = tcx.hir().hir_to_node_id(var_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_node_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 free_regions = nll::replace_regions_in_mir(infcx, def_id, param_env, &mut body);
154 let body = &body; // no further changes
155 let location_table = &LocationTable::new(body);
157 let mut errors_buffer = Vec::new();
158 let (move_data, move_errors): (MoveData<'tcx>, Option<Vec<(Place<'tcx>, MoveError<'tcx>)>>) =
159 match MoveData::gather_moves(body, tcx) {
160 Ok(move_data) => (move_data, None),
161 Err((move_data, move_errors)) => (move_data, Some(move_errors)),
164 let mdpe = MoveDataParamEnv {
165 move_data: move_data,
166 param_env: param_env,
169 let dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
170 let mut flow_inits = FlowAtLocation::new(do_dataflow(
176 MaybeInitializedPlaces::new(tcx, body, &mdpe),
177 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
180 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind_by_hir_id(id).is_fn_or_closure();
181 let borrow_set = Rc::new(BorrowSet::build(
182 tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
184 // If we are in non-lexical mode, compute the non-lexical lifetimes.
185 let (regioncx, polonius_output, opt_closure_req) = nll::compute_regions(
199 // The various `flow_*` structures can be large. We drop `flow_inits` here
200 // so it doesn't overlap with the others below. This reduces peak memory
201 // usage significantly on some benchmarks.
204 let regioncx = Rc::new(regioncx);
206 let flow_borrows = FlowAtLocation::new(do_dataflow(
212 Borrows::new(tcx, body, regioncx.clone(), &borrow_set),
213 |rs, i| DebugFormatted::new(&rs.location(i)),
215 let flow_uninits = FlowAtLocation::new(do_dataflow(
221 MaybeUninitializedPlaces::new(tcx, body, &mdpe),
222 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
224 let flow_ever_inits = FlowAtLocation::new(do_dataflow(
230 EverInitializedPlaces::new(tcx, body, &mdpe),
231 |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
234 let movable_generator = match tcx.hir().get_by_hir_id(id) {
235 Node::Expr(&hir::Expr {
236 node: hir::ExprKind::Closure(.., Some(hir::GeneratorMovability::Static)),
242 let dominators = body.dominators();
244 let mut mbcx = MirBorrowckCtxt {
248 move_data: &mdpe.move_data,
251 locals_are_invalidated_at_exit,
252 access_place_error_reported: Default::default(),
253 reservation_error_reported: Default::default(),
254 reservation_warnings: Default::default(),
255 move_error_reported: BTreeMap::new(),
256 uninitialized_error_reported: Default::default(),
258 nonlexical_regioncx: regioncx,
259 used_mut: Default::default(),
260 used_mut_upvars: SmallVec::new(),
266 let mut state = Flows::new(
273 if let Some(errors) = move_errors {
274 mbcx.report_move_errors(errors);
276 mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
278 // Convert any reservation warnings into lints.
279 let reservation_warnings = mem::replace(&mut mbcx.reservation_warnings, Default::default());
280 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
281 let mut initial_diag =
282 mbcx.report_conflicting_borrow(location, (&place, span), bk, &borrow);
284 let lint_root = if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
285 let scope = mbcx.body.source_info(location).scope;
291 // Span and message don't matter; we overwrite them below anyway
292 let mut diag = mbcx.infcx.tcx.struct_span_lint_hir(
293 MUTABLE_BORROW_RESERVATION_CONFLICT, lint_root, DUMMY_SP, "");
295 diag.message = initial_diag.styled_message().clone();
296 diag.span = initial_diag.span.clone();
298 initial_diag.cancel();
299 diag.buffer(&mut mbcx.errors_buffer);
302 // For each non-user used mutable variable, check if it's been assigned from
303 // a user-declared local. If so, then put that local into the used_mut set.
304 // Note that this set is expected to be small - only upvars from closures
305 // would have a chance of erroneously adding non-user-defined mutable vars
307 let temporary_used_locals: FxHashSet<Local> = mbcx.used_mut.iter()
308 .filter(|&local| mbcx.body.local_decls[*local].is_user_variable.is_none())
311 // For the remaining unused locals that are marked as mutable, we avoid linting any that
312 // were never initialized. These locals may have been removed as unreachable code; or will be
313 // linted as unused variables.
314 let unused_mut_locals = mbcx.body.mut_vars_iter()
315 .filter(|local| !mbcx.used_mut.contains(local))
317 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
319 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
320 let used_mut = mbcx.used_mut;
321 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
322 if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
323 let local_decl = &mbcx.body.local_decls[local];
325 // Skip implicit `self` argument for closures
326 if local.index() == 1 && tcx.is_closure(mbcx.mir_def_id) {
330 // Skip over locals that begin with an underscore or have no name
331 match local_decl.name {
332 Some(name) => if name.as_str().starts_with("_") {
338 let span = local_decl.source_info.span;
339 if span.compiler_desugaring_kind().is_some() {
340 // If the `mut` arises as part of a desugaring, we should ignore it.
344 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
345 tcx.struct_span_lint_hir(
347 vsi[local_decl.source_info.scope].lint_root,
349 "variable does not need to be mutable",
351 .span_suggestion_short(
355 Applicability::MachineApplicable,
361 // Buffer any move errors that we collected and de-duplicated.
362 for (_, (_, diag)) in mbcx.move_error_reported {
363 diag.buffer(&mut mbcx.errors_buffer);
366 if !mbcx.errors_buffer.is_empty() {
367 mbcx.errors_buffer.sort_by_key(|diag| diag.span.primary_span());
369 if tcx.migrate_borrowck() {
370 // When borrowck=migrate, check if AST-borrowck would
371 // error on the given code.
373 // rust-lang/rust#55492, rust-lang/rust#58776 check the base def id
374 // for errors. AST borrowck is responsible for aggregating
375 // `signalled_any_error` from all of the nested closures here.
376 let base_def_id = tcx.closure_base_def_id(def_id);
378 match tcx.borrowck(base_def_id).signalled_any_error {
379 SignalledError::NoErrorsSeen => {
380 // if AST-borrowck signalled no errors, then
381 // downgrade all the buffered MIR-borrowck errors
384 for err in mbcx.errors_buffer.iter_mut() {
385 downgrade_if_error(err);
388 SignalledError::SawSomeError => {
389 // if AST-borrowck signalled a (cancelled) error,
390 // then we will just emit the buffered
391 // MIR-borrowck errors as normal.
396 for diag in mbcx.errors_buffer.drain(..) {
397 DiagnosticBuilder::new_diagnostic(mbcx.infcx.tcx.sess.diagnostic(), diag).emit();
401 let result = BorrowCheckResult {
402 closure_requirements: opt_closure_req,
403 used_mut_upvars: mbcx.used_mut_upvars,
406 debug!("do_mir_borrowck: result = {:#?}", result);
411 fn downgrade_if_error(diag: &mut Diagnostic) {
413 diag.level = Level::Warning;
415 "this error has been downgraded to a warning for backwards \
416 compatibility with previous releases",
418 "this represents potential undefined behavior in your code and \
419 this warning will become a hard error in the future",
421 "for more information, try `rustc --explain E0729`"
426 pub struct MirBorrowckCtxt<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
427 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
428 body: &'cx Body<'tcx>,
430 move_data: &'cx MoveData<'tcx>,
432 /// Map from MIR `Location` to `LocationIndex`; created
433 /// when MIR borrowck begins.
434 location_table: &'cx LocationTable,
436 movable_generator: bool,
437 /// This keeps track of whether local variables are free-ed when the function
438 /// exits even without a `StorageDead`, which appears to be the case for
441 /// I'm not sure this is the right approach - @eddyb could you try and
443 locals_are_invalidated_at_exit: bool,
444 /// This field keeps track of when borrow errors are reported in the access_place function
445 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
446 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
447 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
449 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
450 /// This field keeps track of when borrow conflict errors are reported
451 /// for reservations, so that we don't report seemingly duplicate
452 /// errors for corresponding activations.
454 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
455 // but it is currently inconvenient to track down the `BorrowIndex`
456 // at the time we detect and report a reservation error.
457 reservation_error_reported: FxHashSet<Place<'tcx>>,
458 /// Migration warnings to be reported for #56254. We delay reporting these
459 /// so that we can suppress the warning if there's a corresponding error
460 /// for the activation of the borrow.
461 reservation_warnings: FxHashMap<
463 (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)
465 /// This field keeps track of move errors that are to be reported for given move indicies.
467 /// There are situations where many errors can be reported for a single move out (see #53807)
468 /// and we want only the best of those errors.
470 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
471 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
472 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
473 /// all move errors have been reported, any diagnostics in this map are added to the buffer
476 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
477 /// when errors in the map are being re-added to the error buffer so that errors with the
478 /// same primary span come out in a consistent order.
479 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (Place<'tcx>, DiagnosticBuilder<'cx>)>,
480 /// This field keeps track of errors reported in the checking of uninitialized variables,
481 /// so that we don't report seemingly duplicate errors.
482 uninitialized_error_reported: FxHashSet<Place<'tcx>>,
483 /// Errors to be reported buffer
484 errors_buffer: Vec<Diagnostic>,
485 /// This field keeps track of all the local variables that are declared mut and are mutated.
486 /// Used for the warning issued by an unused mutable local variable.
487 used_mut: FxHashSet<Local>,
488 /// If the function we're checking is a closure, then we'll need to report back the list of
489 /// mutable upvars that have been used. This field keeps track of them.
490 used_mut_upvars: SmallVec<[Field; 8]>,
491 /// Non-lexical region inference context, if NLL is enabled. This
492 /// contains the results from region inference and lets us e.g.
493 /// find out which CFG points are contained in each borrow region.
494 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
496 /// The set of borrows extracted from the MIR
497 borrow_set: Rc<BorrowSet<'tcx>>,
499 /// Dominators for MIR
500 dominators: Dominators<BasicBlock>,
502 /// Information about upvars not necessarily preserved in types or MIR
507 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
508 // 2. loans made in overlapping scopes do not conflict
509 // 3. assignments do not affect things loaned out as immutable
510 // 4. moves do not affect things loaned out in any way
511 impl<'cx, 'gcx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
512 type FlowState = Flows<'cx, 'gcx, 'tcx>;
514 fn body(&self) -> &'cx Body<'tcx> {
518 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
519 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
522 fn visit_statement_entry(
525 stmt: &Statement<'tcx>,
526 flow_state: &Self::FlowState,
529 "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
530 location, stmt, flow_state
532 let span = stmt.source_info.span;
534 self.check_activations(location, span, flow_state);
537 StatementKind::Assign(ref lhs, ref rhs) => {
552 StatementKind::FakeRead(_, ref place) => {
553 // Read for match doesn't access any memory and is used to
554 // assert that a place is safe and live. So we don't have to
555 // do any checks here.
557 // FIXME: Remove check that the place is initialized. This is
558 // needed for now because matches don't have never patterns yet.
559 // So this is the only place we prevent
563 self.check_if_path_or_subpath_is_moved(
565 InitializationRequiringAction::Use,
570 StatementKind::SetDiscriminant {
582 StatementKind::InlineAsm(ref asm) => {
583 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
585 // FIXME(eddyb) indirect inline asm outputs should
586 // be encoded through MIR place derefs instead.
590 (Deep, Read(ReadKind::Copy)),
591 LocalMutationIsAllowed::No,
594 self.check_if_path_or_subpath_is_moved(
596 InitializationRequiringAction::Use,
604 if o.is_rw { Deep } else { Shallow(None) },
605 if o.is_rw { WriteAndRead } else { JustWrite },
610 for (_, input) in asm.inputs.iter() {
611 self.consume_operand(location, (input, span), flow_state);
615 | StatementKind::AscribeUserType(..)
616 | StatementKind::Retag { .. }
617 | StatementKind::StorageLive(..) => {
618 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
621 StatementKind::StorageDead(local) => {
624 (&Place::Base(PlaceBase::Local(local)), span),
625 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
626 LocalMutationIsAllowed::Yes,
633 fn visit_terminator_entry(
636 term: &Terminator<'tcx>,
637 flow_state: &Self::FlowState,
641 "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
642 location, term, flow_state
644 let span = term.source_info.span;
646 self.check_activations(location, span, flow_state);
649 TerminatorKind::SwitchInt {
655 self.consume_operand(loc, (discr, span), flow_state);
657 TerminatorKind::Drop {
658 location: ref drop_place,
662 let gcx = self.infcx.tcx.global_tcx();
664 // Compute the type with accurate region information.
665 let drop_place_ty = drop_place.ty(self.body, self.infcx.tcx);
667 // Erase the regions.
668 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
670 // "Lift" into the gcx -- once regions are erased, this type should be in the
671 // global arenas; this "lift" operation basically just asserts that is true, but
672 // that is useful later.
673 let drop_place_ty = gcx.lift(&drop_place_ty).unwrap();
675 debug!("visit_terminator_drop \
676 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
677 loc, term, drop_place, drop_place_ty, span);
682 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
683 LocalMutationIsAllowed::Yes,
687 TerminatorKind::DropAndReplace {
688 location: ref drop_place,
689 value: ref new_value,
700 self.consume_operand(
706 TerminatorKind::Call {
713 self.consume_operand(loc, (func, span), flow_state);
715 self.consume_operand(
721 if let Some((ref dest, _ /*bb*/)) = *destination {
731 TerminatorKind::Assert {
738 self.consume_operand(loc, (cond, span), flow_state);
739 use rustc::mir::interpret::InterpError::BoundsCheck;
740 if let BoundsCheck { ref len, ref index } = *msg {
741 self.consume_operand(loc, (len, span), flow_state);
742 self.consume_operand(loc, (index, span), flow_state);
746 TerminatorKind::Yield {
751 self.consume_operand(loc, (value, span), flow_state);
753 if self.movable_generator {
754 // Look for any active borrows to locals
755 let borrow_set = self.borrow_set.clone();
756 flow_state.with_outgoing_borrows(|borrows| {
758 let borrow = &borrow_set[i];
759 self.check_for_local_borrow(borrow, span);
765 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
766 // Returning from the function implicitly kills storage for all locals and statics.
767 // Often, the storage will already have been killed by an explicit
768 // StorageDead, but we don't always emit those (notably on unwind paths),
769 // so this "extra check" serves as a kind of backup.
770 let borrow_set = self.borrow_set.clone();
771 flow_state.with_outgoing_borrows(|borrows| {
773 let borrow = &borrow_set[i];
774 self.check_for_invalidation_at_exit(loc, borrow, span);
778 TerminatorKind::Goto { target: _ }
779 | TerminatorKind::Abort
780 | TerminatorKind::Unreachable
781 | TerminatorKind::FalseEdges {
783 imaginary_targets: _,
785 | TerminatorKind::FalseUnwind {
789 // no data used, thus irrelevant to borrowck
795 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
801 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
802 use self::AccessDepth::{Deep, Shallow};
804 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
805 enum ArtificialField {
810 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
812 /// From the RFC: "A *shallow* access means that the immediate
813 /// fields reached at P are accessed, but references or pointers
814 /// found within are not dereferenced. Right now, the only access
815 /// that is shallow is an assignment like `x = ...;`, which would
816 /// be a *shallow write* of `x`."
817 Shallow(Option<ArtificialField>),
819 /// From the RFC: "A *deep* access means that all data reachable
820 /// through the given place may be invalidated or accesses by
824 /// Access is Deep only when there is a Drop implementation that
825 /// can reach the data behind the reference.
829 /// Kind of access to a value: read or write
830 /// (For informational purposes only)
831 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
833 /// From the RFC: "A *read* means that the existing data may be
834 /// read, but will not be changed."
837 /// From the RFC: "A *write* means that the data may be mutated to
838 /// new values or otherwise invalidated (for example, it could be
839 /// de-initialized, as in a move operation).
842 /// For two-phase borrows, we distinguish a reservation (which is treated
843 /// like a Read) from an activation (which is treated like a write), and
844 /// each of those is furthermore distinguished from Reads/Writes above.
845 Reservation(WriteKind),
846 Activation(WriteKind, BorrowIndex),
849 /// Kind of read access to a value
850 /// (For informational purposes only)
851 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
857 /// Kind of write access to a value
858 /// (For informational purposes only)
859 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
862 MutableBorrow(BorrowKind),
867 /// When checking permissions for a place access, this flag is used to indicate that an immutable
868 /// local place can be mutated.
870 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
871 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
872 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
873 // `is_declared_mutable()`.
874 // - Take flow state into consideration in `is_assignable()` for local variables.
875 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
876 enum LocalMutationIsAllowed {
878 /// We want use of immutable upvars to cause a "write to immutable upvar"
879 /// error, not an "reassignment" error.
884 #[derive(Copy, Clone, Debug)]
885 enum InitializationRequiringAction {
894 struct RootPlace<'d, 'tcx: 'd> {
895 place: &'d Place<'tcx>,
896 is_local_mutation_allowed: LocalMutationIsAllowed,
899 impl InitializationRequiringAction {
900 fn as_noun(self) -> &'static str {
902 InitializationRequiringAction::Update => "update",
903 InitializationRequiringAction::Borrow => "borrow",
904 InitializationRequiringAction::MatchOn => "use", // no good noun
905 InitializationRequiringAction::Use => "use",
906 InitializationRequiringAction::Assignment => "assign",
907 InitializationRequiringAction::PartialAssignment => "assign to part",
911 fn as_verb_in_past_tense(self) -> &'static str {
913 InitializationRequiringAction::Update => "updated",
914 InitializationRequiringAction::Borrow => "borrowed",
915 InitializationRequiringAction::MatchOn => "matched on",
916 InitializationRequiringAction::Use => "used",
917 InitializationRequiringAction::Assignment => "assigned",
918 InitializationRequiringAction::PartialAssignment => "partially assigned",
923 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
924 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
925 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
926 /// place is initialized and (b) it is not borrowed in some way that would prevent this
929 /// Returns `true` if an error is reported.
933 place_span: (&Place<'tcx>, Span),
934 kind: (AccessDepth, ReadOrWrite),
935 is_local_mutation_allowed: LocalMutationIsAllowed,
936 flow_state: &Flows<'cx, 'gcx, 'tcx>,
940 if let Activation(_, borrow_index) = rw {
941 if self.reservation_error_reported.contains(&place_span.0) {
943 "skipping access_place for activation of invalid reservation \
944 place: {:?} borrow_index: {:?}",
945 place_span.0, borrow_index
951 // Check is_empty() first because it's the common case, and doing that
952 // way we avoid the clone() call.
953 if !self.access_place_error_reported.is_empty() &&
955 .access_place_error_reported
956 .contains(&(place_span.0.clone(), place_span.1))
959 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
965 let mutability_error =
966 self.check_access_permissions(
969 is_local_mutation_allowed,
974 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
976 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
977 // Suppress this warning when there's an error being emited for the
978 // same borrow: fixing the error is likely to fix the warning.
979 self.reservation_warnings.remove(&borrow_idx);
982 if conflict_error || mutability_error {
984 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
988 self.access_place_error_reported
989 .insert((place_span.0.clone(), place_span.1));
993 fn check_access_for_conflict(
996 place_span: (&Place<'tcx>, Span),
999 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1002 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1003 location, place_span, sd, rw,
1006 let mut error_reported = false;
1007 let tcx = self.infcx.tcx;
1008 let body = self.body;
1009 let location_table = self.location_table.start_index(location);
1010 let borrow_set = self.borrow_set.clone();
1011 each_borrow_involving_path(
1018 flow_state.borrows_in_scope(location_table),
1019 |this, borrow_index, borrow| match (rw, borrow.kind) {
1020 // Obviously an activation is compatible with its own
1021 // reservation (or even prior activating uses of same
1022 // borrow); so don't check if they interfere.
1024 // NOTE: *reservations* do conflict with themselves;
1025 // thus aren't injecting unsoundenss w/ this check.)
1026 (Activation(_, activating), _) if activating == borrow_index => {
1028 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1029 skipping {:?} b/c activation of same borrow_index",
1033 (borrow_index, borrow),
1038 (Read(_), BorrowKind::Shared)
1039 | (Read(_), BorrowKind::Shallow)
1040 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
1041 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
1045 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1046 // Handled by initialization checks.
1050 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
1051 // Reading from mere reservations of mutable-borrows is OK.
1052 if !is_active(&this.dominators, borrow, location) {
1053 assert!(allow_two_phase_borrow(borrow.kind));
1054 return Control::Continue;
1057 error_reported = true;
1060 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1061 .buffer(&mut this.errors_buffer);
1063 ReadKind::Borrow(bk) => {
1064 this.report_conflicting_borrow(location, place_span, bk, borrow)
1065 .buffer(&mut this.errors_buffer);
1071 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
1072 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared) if {
1073 tcx.migrate_borrowck()
1075 let bi = this.borrow_set.location_map[&location];
1077 "recording invalid reservation of place: {:?} with \
1078 borrow index {:?} as warning",
1082 // rust-lang/rust#56254 - This was previously permitted on
1083 // the 2018 edition so we emit it as a warning. We buffer
1084 // these sepately so that we only emit a warning if borrow
1085 // checking was otherwise successful.
1086 this.reservation_warnings.insert(
1088 (place_span.0.clone(), place_span.1, location, bk, borrow.clone()),
1091 // Don't suppress actual errors.
1095 (Reservation(kind), _)
1096 | (Activation(kind, _), _)
1097 | (Write(kind), _) => {
1099 Reservation(..) => {
1101 "recording invalid reservation of \
1105 this.reservation_error_reported.insert(place_span.0.clone());
1107 Activation(_, activating) => {
1109 "observing check_place for activation of \
1110 borrow_index: {:?}",
1114 Read(..) | Write(..) => {}
1117 error_reported = true;
1119 WriteKind::MutableBorrow(bk) => {
1120 this.report_conflicting_borrow(location, place_span, bk, borrow)
1121 .buffer(&mut this.errors_buffer);
1123 WriteKind::StorageDeadOrDrop => {
1124 this.report_borrowed_value_does_not_live_long_enough(
1130 WriteKind::Mutate => {
1131 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1133 WriteKind::Move => {
1134 this.report_move_out_while_borrowed(location, place_span, borrow)
1148 place_span: (&Place<'tcx>, Span),
1151 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1153 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1155 MutateMode::WriteAndRead => {
1156 self.check_if_path_or_subpath_is_moved(
1158 InitializationRequiringAction::Update,
1163 MutateMode::JustWrite => {
1164 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1168 // Special case: you can assign a immutable local variable
1169 // (e.g., `x = ...`) so long as it has never been initialized
1170 // before (at this point in the flow).
1171 if let &Place::Base(PlaceBase::Local(local)) = place_span.0 {
1172 if let Mutability::Not = self.body.local_decls[local].mutability {
1173 // check for reassignments to immutable local variables
1174 self.check_if_reassignment_to_immutable_state(
1184 // Otherwise, use the normal access permission rules.
1188 (kind, Write(WriteKind::Mutate)),
1189 LocalMutationIsAllowed::No,
1197 (rvalue, span): (&Rvalue<'tcx>, Span),
1198 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1201 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1202 let access_kind = match bk {
1203 BorrowKind::Shallow => {
1204 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1206 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1207 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1208 let wk = WriteKind::MutableBorrow(bk);
1209 if allow_two_phase_borrow(bk) {
1210 (Deep, Reservation(wk))
1221 LocalMutationIsAllowed::No,
1225 let action = if bk == BorrowKind::Shallow {
1226 InitializationRequiringAction::MatchOn
1228 InitializationRequiringAction::Borrow
1231 self.check_if_path_or_subpath_is_moved(
1239 Rvalue::Use(ref operand)
1240 | Rvalue::Repeat(ref operand, _)
1241 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1242 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1243 self.consume_operand(location, (operand, span), flow_state)
1246 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1247 let af = match *rvalue {
1248 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1249 Rvalue::Discriminant(..) => None,
1250 _ => unreachable!(),
1255 (Shallow(af), Read(ReadKind::Copy)),
1256 LocalMutationIsAllowed::No,
1259 self.check_if_path_or_subpath_is_moved(
1261 InitializationRequiringAction::Use,
1267 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1268 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1269 self.consume_operand(location, (operand1, span), flow_state);
1270 self.consume_operand(location, (operand2, span), flow_state);
1273 Rvalue::NullaryOp(_op, _ty) => {
1274 // nullary ops take no dynamic input; no borrowck effect.
1276 // FIXME: is above actually true? Do we want to track
1277 // the fact that uninitialized data can be created via
1281 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1282 // We need to report back the list of mutable upvars that were
1283 // moved into the closure and subsequently used by the closure,
1284 // in order to populate our used_mut set.
1285 match **aggregate_kind {
1286 AggregateKind::Closure(def_id, _)
1287 | AggregateKind::Generator(def_id, _, _) => {
1288 let BorrowCheckResult {
1290 } = self.infcx.tcx.mir_borrowck(def_id);
1291 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1292 for field in used_mut_upvars {
1293 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1296 AggregateKind::Adt(..)
1297 | AggregateKind::Array(..)
1298 | AggregateKind::Tuple { .. } => (),
1301 for operand in operands {
1302 self.consume_operand(location, (operand, span), flow_state);
1308 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1309 let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1311 Place::Projection { .. } => {
1312 if let Some(field) = this.is_upvar_field_projection(place) {
1313 this.used_mut_upvars.push(field);
1316 Place::Base(PlaceBase::Local(local)) => {
1317 this.used_mut.insert(local);
1319 Place::Base(PlaceBase::Static(_)) => {}
1323 // This relies on the current way that by-value
1324 // captures of a closure are copied/moved directly
1325 // when generating MIR.
1327 Operand::Move(Place::Base(PlaceBase::Local(local)))
1328 | Operand::Copy(Place::Base(PlaceBase::Local(local)))
1329 if self.body.local_decls[local].is_user_variable.is_none() =>
1331 if self.body.local_decls[local].ty.is_mutable_pointer() {
1332 // The variable will be marked as mutable by the borrow.
1335 // This is an edge case where we have a `move` closure
1336 // inside a non-move closure, and the inner closure
1337 // contains a mutation:
1340 // || { move || { i += 1; }; };
1342 // In this case our usual strategy of assuming that the
1343 // variable will be captured by mutable reference is
1344 // wrong, since `i` can be copied into the inner
1345 // closure from a shared reference.
1347 // As such we have to search for the local that this
1348 // capture comes from and mark it as being used as mut.
1350 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1351 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1352 &self.move_data.inits[init_index]
1354 bug!("temporary should be initialized exactly once")
1357 let loc = match init.location {
1358 InitLocation::Statement(stmt) => stmt,
1359 _ => bug!("temporary initialized in arguments"),
1362 let bbd = &self.body[loc.block];
1363 let stmt = &bbd.statements[loc.statement_index];
1364 debug!("temporary assigned in: stmt={:?}", stmt);
1366 if let StatementKind::Assign(_, box Rvalue::Ref(_, _, ref source)) = stmt.kind {
1367 propagate_closure_used_mut_place(self, source);
1369 bug!("closures should only capture user variables \
1370 or references to user variables");
1373 Operand::Move(ref place)
1374 | Operand::Copy(ref place) => {
1375 propagate_closure_used_mut_place(self, place);
1377 Operand::Constant(..) => {}
1384 (operand, span): (&Operand<'tcx>, Span),
1385 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1388 Operand::Copy(ref place) => {
1389 // copy of place: check if this is "copy of frozen path"
1390 // (FIXME: see check_loans.rs)
1394 (Deep, Read(ReadKind::Copy)),
1395 LocalMutationIsAllowed::No,
1399 // Finally, check if path was already moved.
1400 self.check_if_path_or_subpath_is_moved(
1402 InitializationRequiringAction::Use,
1407 Operand::Move(ref place) => {
1408 // move of place: check if this is move of already borrowed path
1412 (Deep, Write(WriteKind::Move)),
1413 LocalMutationIsAllowed::Yes,
1417 // Finally, check if path was already moved.
1418 self.check_if_path_or_subpath_is_moved(
1420 InitializationRequiringAction::Use,
1425 Operand::Constant(_) => {}
1429 /// Checks whether a borrow of this place is invalidated when the function
1431 fn check_for_invalidation_at_exit(
1434 borrow: &BorrowData<'tcx>,
1437 debug!("check_for_invalidation_at_exit({:?})", borrow);
1438 let place = &borrow.borrowed_place;
1439 let root_place = self.prefixes(place, PrefixSet::All).last().unwrap();
1441 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1442 // we just know that all locals are dropped at function exit (otherwise
1443 // we'll have a memory leak) and assume that all statics have a destructor.
1445 // FIXME: allow thread-locals to borrow other thread locals?
1446 let (might_be_alive, will_be_dropped) = match root_place {
1447 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Promoted(_), .. })) => {
1450 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(_), .. })) => {
1451 // Thread-locals might be dropped after the function exits, but
1452 // "true" statics will never be.
1453 (true, self.is_place_thread_local(&root_place))
1455 Place::Base(PlaceBase::Local(_)) => {
1456 // Locals are always dropped at function exit, and if they
1457 // have a destructor it would've been called already.
1458 (false, self.locals_are_invalidated_at_exit)
1460 Place::Projection(..) => {
1461 bug!("root of {:?} is a projection ({:?})?", place, root_place)
1465 if !will_be_dropped {
1467 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1473 let sd = if might_be_alive { Deep } else { Shallow(None) };
1475 if places_conflict::borrow_conflicts_with_place(
1482 places_conflict::PlaceConflictBias::Overlap,
1484 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1485 // FIXME: should be talking about the region lifetime instead
1486 // of just a span here.
1487 let span = self.infcx.tcx.sess.source_map().end_point(span);
1488 self.report_borrowed_value_does_not_live_long_enough(
1497 /// Reports an error if this is a borrow of local data.
1498 /// This is called for all Yield statements on movable generators
1499 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1500 debug!("check_for_local_borrow({:?})", borrow);
1502 if borrow_of_local_data(&borrow.borrowed_place) {
1503 let err = self.infcx.tcx
1504 .cannot_borrow_across_generator_yield(
1505 self.retrieve_borrow_spans(borrow).var_or_use(),
1510 err.buffer(&mut self.errors_buffer);
1514 fn check_activations(
1518 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1520 // Two-phase borrow support: For each activation that is newly
1521 // generated at this statement, check if it interferes with
1523 let borrow_set = self.borrow_set.clone();
1524 for &borrow_index in borrow_set.activations_at_location(location) {
1525 let borrow = &borrow_set[borrow_index];
1527 // only mutable borrows should be 2-phase
1528 assert!(match borrow.kind {
1529 BorrowKind::Shared | BorrowKind::Shallow => false,
1530 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1535 (&borrow.borrowed_place, span),
1538 Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1540 LocalMutationIsAllowed::No,
1543 // We do not need to call `check_if_path_or_subpath_is_moved`
1544 // again, as we already called it when we made the
1545 // initial reservation.
1550 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1551 fn check_if_reassignment_to_immutable_state(
1555 place_span: (&Place<'tcx>, Span),
1556 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1558 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1560 // Check if any of the initializiations of `local` have happened yet:
1561 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1562 // And, if so, report an error.
1563 let init = &self.move_data.inits[init_index];
1564 let span = init.span(&self.body);
1565 self.report_illegal_reassignment(
1566 location, place_span, span, place_span.0
1571 fn check_if_full_path_is_moved(
1574 desired_action: InitializationRequiringAction,
1575 place_span: (&Place<'tcx>, Span),
1576 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1578 let maybe_uninits = &flow_state.uninits;
1582 // 1. Move of `a.b.c`, use of `a.b.c`
1583 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1584 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1585 // partial initialization support, one might have `a.x`
1586 // initialized but not `a.b`.
1590 // 4. Move of `a.b.c`, use of `a.b.d`
1591 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1592 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1593 // must have been initialized for the use to be sound.
1594 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1596 // The dataflow tracks shallow prefixes distinctly (that is,
1597 // field-accesses on P distinctly from P itself), in order to
1598 // track substructure initialization separately from the whole
1601 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1602 // which we have a MovePath is `a.b`, then that means that the
1603 // initialization state of `a.b` is all we need to inspect to
1604 // know if `a.b.c` is valid (and from that we infer that the
1605 // dereference and `.d` access is also valid, since we assume
1606 // `a.b.c` is assigned a reference to a initialized and
1607 // well-formed record structure.)
1609 // Therefore, if we seek out the *closest* prefix for which we
1610 // have a MovePath, that should capture the initialization
1611 // state for the place scenario.
1613 // This code covers scenarios 1, 2, and 3.
1615 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1616 match self.move_path_closest_to(place_span.0) {
1617 Ok((prefix, mpi)) => {
1618 if maybe_uninits.contains(mpi) {
1619 self.report_use_of_moved_or_uninitialized(
1622 (prefix, place_span.0, place_span.1),
1625 return; // don't bother finding other problems.
1628 Err(NoMovePathFound::ReachedStatic) => {
1629 // Okay: we do not build MoveData for static variables
1630 } // Only query longest prefix with a MovePath, not further
1631 // ancestors; dataflow recurs on children when parents
1632 // move (to support partial (re)inits).
1634 // (I.e., querying parents breaks scenario 7; but may want
1635 // to do such a query based on partial-init feature-gate.)
1639 fn check_if_path_or_subpath_is_moved(
1642 desired_action: InitializationRequiringAction,
1643 place_span: (&Place<'tcx>, Span),
1644 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1646 let maybe_uninits = &flow_state.uninits;
1650 // 1. Move of `a.b.c`, use of `a` or `a.b`
1651 // partial initialization support, one might have `a.x`
1652 // initialized but not `a.b`.
1653 // 2. All bad scenarios from `check_if_full_path_is_moved`
1657 // 3. Move of `a.b.c`, use of `a.b.d`
1658 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1659 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1660 // must have been initialized for the use to be sound.
1661 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1663 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1665 // A move of any shallow suffix of `place` also interferes
1666 // with an attempt to use `place`. This is scenario 3 above.
1668 // (Distinct from handling of scenarios 1+2+4 above because
1669 // `place` does not interfere with suffixes of its prefixes,
1670 // e.g., `a.b.c` does not interfere with `a.b.d`)
1672 // This code covers scenario 1.
1674 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1675 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1676 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1677 self.report_use_of_moved_or_uninitialized(
1680 (place_span.0, place_span.0, place_span.1),
1683 return; // don't bother finding other problems.
1688 /// Currently MoveData does not store entries for all places in
1689 /// the input MIR. For example it will currently filter out
1690 /// places that are Copy; thus we do not track places of shared
1691 /// reference type. This routine will walk up a place along its
1692 /// prefixes, searching for a foundational place that *is*
1693 /// tracked in the MoveData.
1695 /// An Err result includes a tag indicated why the search failed.
1696 /// Currently this can only occur if the place is built off of a
1697 /// static variable, as we do not track those in the MoveData.
1698 fn move_path_closest_to<'a>(
1700 place: &'a Place<'tcx>,
1701 ) -> Result<(&'a Place<'tcx>, MovePathIndex), NoMovePathFound> where 'cx: 'a {
1702 let mut last_prefix = place;
1703 for prefix in self.prefixes(place, PrefixSet::All) {
1704 if let Some(mpi) = self.move_path_for_place(prefix) {
1705 return Ok((prefix, mpi));
1707 last_prefix = prefix;
1709 match *last_prefix {
1710 Place::Base(PlaceBase::Local(_)) => panic!("should have move path for every Local"),
1711 Place::Projection(_) => panic!("PrefixSet::All meant don't stop for Projection"),
1712 Place::Base(PlaceBase::Static(_)) => Err(NoMovePathFound::ReachedStatic),
1716 fn move_path_for_place(&mut self, place: &Place<'tcx>) -> Option<MovePathIndex> {
1717 // If returns None, then there is no move path corresponding
1718 // to a direct owner of `place` (which means there is nothing
1719 // that borrowck tracks for its analysis).
1721 match self.move_data.rev_lookup.find(place) {
1722 LookupResult::Parent(_) => None,
1723 LookupResult::Exact(mpi) => Some(mpi),
1727 fn check_if_assigned_path_is_moved(
1730 (place, span): (&Place<'tcx>, Span),
1731 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1733 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1734 // recur down place; dispatch to external checks when necessary
1735 let mut place = place;
1738 Place::Base(PlaceBase::Local(_)) | Place::Base(PlaceBase::Static(_)) => {
1739 // assigning to `x` does not require `x` be initialized.
1742 Place::Projection(ref proj) => {
1743 let Projection { ref base, ref elem } = **proj;
1745 ProjectionElem::Index(_/*operand*/) |
1746 ProjectionElem::ConstantIndex { .. } |
1747 // assigning to P[i] requires P to be valid.
1748 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1749 // assigning to (P->variant) is okay if assigning to `P` is okay
1751 // FIXME: is this true even if P is a adt with a dtor?
1754 // assigning to (*P) requires P to be initialized
1755 ProjectionElem::Deref => {
1756 self.check_if_full_path_is_moved(
1757 location, InitializationRequiringAction::Use,
1758 (base, span), flow_state);
1759 // (base initialized; no need to
1764 ProjectionElem::Subslice { .. } => {
1765 panic!("we don't allow assignments to subslices, location: {:?}",
1769 ProjectionElem::Field(..) => {
1770 // if type of `P` has a dtor, then
1771 // assigning to `P.f` requires `P` itself
1772 // be already initialized
1773 let tcx = self.infcx.tcx;
1774 match base.ty(self.body, tcx).ty.sty {
1775 ty::Adt(def, _) if def.has_dtor(tcx) => {
1776 self.check_if_path_or_subpath_is_moved(
1777 location, InitializationRequiringAction::Assignment,
1778 (base, span), flow_state);
1780 // (base initialized; no need to
1786 // Once `let s; s.x = V; read(s.x);`,
1787 // is allowed, remove this match arm.
1788 ty::Adt(..) | ty::Tuple(..) => {
1789 check_parent_of_field(self, location, base, span, flow_state);
1791 if let Some(local) = place.base_local() {
1792 // rust-lang/rust#21232,
1793 // #54499, #54986: during
1794 // period where we reject
1795 // partial initialization, do
1796 // not complain about
1797 // unnecessary `mut` on an
1798 // attempt to do a partial
1800 self.used_mut.insert(local);
1814 fn check_parent_of_field<'cx, 'gcx, 'tcx>(
1815 this: &mut MirBorrowckCtxt<'cx, 'gcx, 'tcx>,
1819 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1821 // rust-lang/rust#21232: Until Rust allows reads from the
1822 // initialized parts of partially initialized structs, we
1823 // will, starting with the 2018 edition, reject attempts
1824 // to write to structs that are not fully initialized.
1826 // In other words, *until* we allow this:
1828 // 1. `let mut s; s.x = Val; read(s.x);`
1830 // we will for now disallow this:
1832 // 2. `let mut s; s.x = Val;`
1836 // 3. `let mut s = ...; drop(s); s.x=Val;`
1838 // This does not use check_if_path_or_subpath_is_moved,
1839 // because we want to *allow* reinitializations of fields:
1840 // e.g., want to allow
1842 // `let mut s = ...; drop(s.x); s.x=Val;`
1844 // This does not use check_if_full_path_is_moved on
1845 // `base`, because that would report an error about the
1846 // `base` as a whole, but in this scenario we *really*
1847 // want to report an error about the actual thing that was
1848 // moved, which may be some prefix of `base`.
1850 // Shallow so that we'll stop at any dereference; we'll
1851 // report errors about issues with such bases elsewhere.
1852 let maybe_uninits = &flow_state.uninits;
1854 // Find the shortest uninitialized prefix you can reach
1855 // without going over a Deref.
1856 let mut shortest_uninit_seen = None;
1857 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1858 let mpi = match this.move_path_for_place(prefix) {
1859 Some(mpi) => mpi, None => continue,
1862 if maybe_uninits.contains(mpi) {
1863 debug!("check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1864 shortest_uninit_seen, Some((prefix, mpi)));
1865 shortest_uninit_seen = Some((prefix, mpi));
1867 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1871 if let Some((prefix, mpi)) = shortest_uninit_seen {
1872 // Check for a reassignment into a uninitialized field of a union (for example,
1873 // after a move out). In this case, do not report a error here. There is an
1874 // exception, if this is the first assignment into the union (that is, there is
1875 // no move out from an earlier location) then this is an attempt at initialization
1876 // of the union - we should error in that case.
1877 let tcx = this.infcx.tcx;
1878 if let ty::Adt(def, _) = base.ty(this.body, tcx).ty.sty {
1880 if this.move_data.path_map[mpi].iter().any(|moi| {
1881 this.move_data.moves[*moi].source.is_predecessor_of(
1882 location, this.body,
1890 this.report_use_of_moved_or_uninitialized(
1892 InitializationRequiringAction::PartialAssignment,
1893 (prefix, base, span),
1900 /// Checks the permissions for the given place and read or write kind
1902 /// Returns `true` if an error is reported.
1903 fn check_access_permissions(
1905 (place, span): (&Place<'tcx>, Span),
1907 is_local_mutation_allowed: LocalMutationIsAllowed,
1908 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1912 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1913 place, kind, is_local_mutation_allowed
1919 // rust-lang/rust#21232, #54986: during period where we reject
1920 // partial initialization, do not complain about mutability
1921 // errors except for actual mutation (as opposed to an attempt
1922 // to do a partial initialization).
1923 let previously_initialized = if let Some(local) = place.base_local() {
1924 self.is_local_ever_initialized(local, flow_state).is_some()
1930 Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1931 | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
1932 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1933 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. })) => {
1934 let is_local_mutation_allowed = match borrow_kind {
1935 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1936 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1937 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1939 match self.is_mutable(place, is_local_mutation_allowed) {
1941 self.add_used_mut(root_place, flow_state);
1945 error_access = AccessKind::MutableBorrow;
1946 the_place_err = place_err;
1950 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1951 match self.is_mutable(place, is_local_mutation_allowed) {
1953 self.add_used_mut(root_place, flow_state);
1957 error_access = AccessKind::Mutate;
1958 the_place_err = place_err;
1963 Reservation(wk @ WriteKind::Move)
1964 | Write(wk @ WriteKind::Move)
1965 | Reservation(wk @ WriteKind::StorageDeadOrDrop)
1966 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1967 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow))
1968 | Write(wk @ WriteKind::StorageDeadOrDrop)
1969 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1970 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
1971 if let (Err(_place_err), true) = (
1972 self.is_mutable(place, is_local_mutation_allowed),
1973 self.errors_buffer.is_empty()
1975 if self.infcx.tcx.migrate_borrowck() {
1976 // rust-lang/rust#46908: In pure NLL mode this
1977 // code path should be unreachable (and thus
1978 // we signal an ICE in the else branch
1979 // here). But we can legitimately get here
1980 // under borrowck=migrate mode, so instead of
1981 // ICE'ing we instead report a legitimate
1982 // error (which will then be downgraded to a
1983 // warning by the migrate machinery).
1984 error_access = match wk {
1985 WriteKind::MutableBorrow(_) => AccessKind::MutableBorrow,
1986 WriteKind::Move => AccessKind::Move,
1987 WriteKind::StorageDeadOrDrop |
1988 WriteKind::Mutate => AccessKind::Mutate,
1990 self.report_mutability_error(
2000 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2009 // permission checks are done at Reservation point.
2012 Read(ReadKind::Borrow(BorrowKind::Unique))
2013 | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
2014 | Read(ReadKind::Borrow(BorrowKind::Shared))
2015 | Read(ReadKind::Borrow(BorrowKind::Shallow))
2016 | Read(ReadKind::Copy) => {
2017 // Access authorized
2022 // at this point, we have set up the error reporting state.
2023 return if previously_initialized {
2024 self.report_mutability_error(
2037 fn is_local_ever_initialized(&self,
2039 flow_state: &Flows<'cx, 'gcx, 'tcx>)
2040 -> Option<InitIndex>
2042 let mpi = self.move_data.rev_lookup.find_local(local);
2043 let ii = &self.move_data.init_path_map[mpi];
2045 if flow_state.ever_inits.contains(index) {
2052 /// Adds the place into the used mutable variables set
2053 fn add_used_mut<'d>(
2055 root_place: RootPlace<'d, 'tcx>,
2056 flow_state: &Flows<'cx, 'gcx, 'tcx>,
2060 place: Place::Base(PlaceBase::Local(local)),
2061 is_local_mutation_allowed,
2063 // If the local may have been initialized, and it is now currently being
2064 // mutated, then it is justified to be annotated with the `mut`
2065 // keyword, since the mutation may be a possible reassignment.
2066 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes &&
2067 self.is_local_ever_initialized(*local, flow_state).is_some()
2069 self.used_mut.insert(*local);
2074 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2077 place: place @ Place::Projection(_),
2078 is_local_mutation_allowed: _,
2080 if let Some(field) = self.is_upvar_field_projection(place) {
2081 self.used_mut_upvars.push(field);
2085 place: Place::Base(PlaceBase::Static(..)),
2086 is_local_mutation_allowed: _,
2091 /// Whether this value can be written or borrowed mutably.
2092 /// Returns the root place if the place passed in is a projection.
2095 place: &'d Place<'tcx>,
2096 is_local_mutation_allowed: LocalMutationIsAllowed,
2097 ) -> Result<RootPlace<'d, 'tcx>, &'d Place<'tcx>> {
2099 Place::Base(PlaceBase::Local(local)) => {
2100 let local = &self.body.local_decls[local];
2101 match local.mutability {
2102 Mutability::Not => match is_local_mutation_allowed {
2103 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2105 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2107 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2109 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2111 LocalMutationIsAllowed::No => Err(place),
2113 Mutability::Mut => Ok(RootPlace {
2115 is_local_mutation_allowed,
2119 // The rules for promotion are made by `qualify_consts`, there wouldn't even be a
2120 // `Place::Promoted` if the promotion weren't 100% legal. So we just forward this
2121 Place::Base(PlaceBase::Static(box Static{kind: StaticKind::Promoted(_), ..})) =>
2124 is_local_mutation_allowed,
2126 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(def_id), .. })) => {
2127 if !self.infcx.tcx.is_mutable_static(def_id) {
2132 is_local_mutation_allowed,
2136 Place::Projection(ref proj) => {
2138 ProjectionElem::Deref => {
2139 let base_ty = proj.base.ty(self.body, self.infcx.tcx).ty;
2141 // Check the kind of deref to decide
2143 ty::Ref(_, _, mutbl) => {
2145 // Shared borrowed data is never mutable
2146 hir::MutImmutable => Err(place),
2147 // Mutably borrowed data is mutable, but only if we have a
2148 // unique path to the `&mut`
2149 hir::MutMutable => {
2150 let mode = match self.is_upvar_field_projection(place) {
2152 if self.upvars[field.index()].by_ref =>
2154 is_local_mutation_allowed
2156 _ => LocalMutationIsAllowed::Yes,
2159 self.is_mutable(&proj.base, mode)
2163 ty::RawPtr(tnm) => {
2165 // `*const` raw pointers are not mutable
2166 hir::MutImmutable => Err(place),
2167 // `*mut` raw pointers are always mutable, regardless of
2168 // context. The users have to check by themselves.
2169 hir::MutMutable => {
2172 is_local_mutation_allowed,
2177 // `Box<T>` owns its content, so mutable if its location is mutable
2178 _ if base_ty.is_box() => {
2179 self.is_mutable(&proj.base, is_local_mutation_allowed)
2181 // Deref should only be for reference, pointers or boxes
2182 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2185 // All other projections are owned by their base path, so mutable if
2186 // base path is mutable
2187 ProjectionElem::Field(..)
2188 | ProjectionElem::Index(..)
2189 | ProjectionElem::ConstantIndex { .. }
2190 | ProjectionElem::Subslice { .. }
2191 | ProjectionElem::Downcast(..) => {
2192 let upvar_field_projection = self.is_upvar_field_projection(place);
2193 if let Some(field) = upvar_field_projection {
2194 let upvar = &self.upvars[field.index()];
2196 "upvar.mutability={:?} local_mutation_is_allowed={:?} place={:?}",
2197 upvar, is_local_mutation_allowed, place
2199 match (upvar.mutability, is_local_mutation_allowed) {
2200 (Mutability::Not, LocalMutationIsAllowed::No)
2201 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2204 (Mutability::Not, LocalMutationIsAllowed::Yes)
2205 | (Mutability::Mut, _) => {
2206 // Subtle: this is an upvar
2207 // reference, so it looks like
2208 // `self.foo` -- we want to double
2209 // check that the location `*self`
2210 // is mutable (i.e., this is not a
2211 // `Fn` closure). But if that
2212 // check succeeds, we want to
2213 // *blame* the mutability on
2214 // `place` (that is,
2215 // `self.foo`). This is used to
2216 // propagate the info about
2217 // whether mutability declarations
2218 // are used outwards, so that we register
2219 // the outer variable as mutable. Otherwise a
2220 // test like this fails to record the `mut`
2224 // fn foo<F: FnOnce()>(_f: F) { }
2226 // let var = Vec::new();
2232 let _ = self.is_mutable(&proj.base, is_local_mutation_allowed)?;
2235 is_local_mutation_allowed,
2240 self.is_mutable(&proj.base, is_local_mutation_allowed)
2248 /// If `place` is a field projection, and the field is being projected from a closure type,
2249 /// then returns the index of the field being projected. Note that this closure will always
2250 /// be `self` in the current MIR, because that is the only time we directly access the fields
2251 /// of a closure type.
2252 pub fn is_upvar_field_projection(&self, place: &Place<'tcx>) -> Option<Field> {
2253 let (place, by_ref) = if let Place::Projection(ref proj) = place {
2254 if let ProjectionElem::Deref = proj.elem {
2264 Place::Projection(ref proj) => match proj.elem {
2265 ProjectionElem::Field(field, _ty) => {
2266 let tcx = self.infcx.tcx;
2267 let base_ty = proj.base.ty(self.body, tcx).ty;
2269 if (base_ty.is_closure() || base_ty.is_generator()) &&
2270 (!by_ref || self.upvars[field.index()].by_ref)
2284 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2285 enum NoMovePathFound {
2289 /// The degree of overlap between 2 places for borrow-checking.
2291 /// The places might partially overlap - in this case, we give
2292 /// up and say that they might conflict. This occurs when
2293 /// different fields of a union are borrowed. For example,
2294 /// if `u` is a union, we have no way of telling how disjoint
2295 /// `u.a.x` and `a.b.y` are.
2297 /// The places have the same type, and are either completely disjoint
2298 /// or equal - i.e., they can't "partially" overlap as can occur with
2299 /// unions. This is the "base case" on which we recur for extensions
2302 /// The places are disjoint, so we know all extensions of them
2303 /// will also be disjoint.