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};
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 = 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 do_mir_borrowck(&infcx, input_body, def_id)
97 debug!("mir_borrowck done");
102 fn do_mir_borrowck<'a, 'tcx>(
103 infcx: &InferCtxt<'a, 'tcx>,
104 input_body: &Body<'tcx>,
106 ) -> BorrowCheckResult<'tcx> {
107 debug!("do_mir_borrowck(def_id = {:?})", def_id);
110 let attributes = tcx.get_attrs(def_id);
111 let param_env = tcx.param_env(def_id);
114 .as_local_hir_id(def_id)
115 .expect("do_mir_borrowck: non-local DefId");
117 // Gather the upvars of a closure, if any.
118 let tables = tcx.typeck_tables_of(def_id);
119 let upvars: Vec<_> = tables
123 .flat_map(|v| v.values())
125 let var_hir_id = upvar_id.var_path.hir_id;
126 let capture = tables.upvar_capture(*upvar_id);
127 let by_ref = match capture {
128 ty::UpvarCapture::ByValue => false,
129 ty::UpvarCapture::ByRef(..) => true,
131 let mut upvar = Upvar {
132 name: tcx.hir().name(var_hir_id),
135 mutability: Mutability::Not,
137 let bm = *tables.pat_binding_modes().get(var_hir_id)
138 .expect("missing binding mode");
139 if bm == ty::BindByValue(hir::MutMutable) {
140 upvar.mutability = Mutability::Mut;
146 // Replace all regions with fresh inference variables. This
147 // requires first making our own copy of the MIR. This copy will
148 // be modified (in place) to contain non-lexical lifetimes. It
149 // will have a lifetime tied to the inference context.
150 let mut body: Body<'tcx> = input_body.clone();
151 let free_regions = nll::replace_regions_in_mir(infcx, def_id, param_env, &mut body);
152 let body = &body; // no further changes
153 let location_table = &LocationTable::new(body);
155 let mut errors_buffer = Vec::new();
156 let (move_data, move_errors): (MoveData<'tcx>, Option<Vec<(Place<'tcx>, MoveError<'tcx>)>>) =
157 match MoveData::gather_moves(body, tcx) {
158 Ok(move_data) => (move_data, None),
159 Err((move_data, move_errors)) => (move_data, Some(move_errors)),
162 let mdpe = MoveDataParamEnv {
163 move_data: move_data,
164 param_env: param_env,
167 let dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
168 let mut flow_inits = FlowAtLocation::new(do_dataflow(
174 MaybeInitializedPlaces::new(tcx, body, &mdpe),
175 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
178 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
179 let borrow_set = Rc::new(BorrowSet::build(
180 tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
182 // If we are in non-lexical mode, compute the non-lexical lifetimes.
183 let (regioncx, polonius_output, opt_closure_req) = nll::compute_regions(
197 // The various `flow_*` structures can be large. We drop `flow_inits` here
198 // so it doesn't overlap with the others below. This reduces peak memory
199 // usage significantly on some benchmarks.
202 let regioncx = Rc::new(regioncx);
204 let flow_borrows = FlowAtLocation::new(do_dataflow(
210 Borrows::new(tcx, body, regioncx.clone(), &borrow_set),
211 |rs, i| DebugFormatted::new(&rs.location(i)),
213 let flow_uninits = FlowAtLocation::new(do_dataflow(
219 MaybeUninitializedPlaces::new(tcx, body, &mdpe),
220 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
222 let flow_ever_inits = FlowAtLocation::new(do_dataflow(
228 EverInitializedPlaces::new(tcx, body, &mdpe),
229 |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
232 let movable_generator = match tcx.hir().get(id) {
233 Node::Expr(&hir::Expr {
234 node: hir::ExprKind::Closure(.., Some(hir::GeneratorMovability::Static)),
240 let dominators = body.dominators();
242 let mut mbcx = MirBorrowckCtxt {
246 move_data: &mdpe.move_data,
249 locals_are_invalidated_at_exit,
250 access_place_error_reported: Default::default(),
251 reservation_error_reported: Default::default(),
252 reservation_warnings: Default::default(),
253 move_error_reported: BTreeMap::new(),
254 uninitialized_error_reported: Default::default(),
256 nonlexical_regioncx: regioncx,
257 used_mut: Default::default(),
258 used_mut_upvars: SmallVec::new(),
264 let mut state = Flows::new(
271 if let Some(errors) = move_errors {
272 mbcx.report_move_errors(errors);
274 mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
276 // Convert any reservation warnings into lints.
277 let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
278 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
279 let mut initial_diag =
280 mbcx.report_conflicting_borrow(location, (&place, span), bk, &borrow);
282 let lint_root = if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
283 let scope = mbcx.body.source_info(location).scope;
289 // Span and message don't matter; we overwrite them below anyway
290 let mut diag = mbcx.infcx.tcx.struct_span_lint_hir(
291 MUTABLE_BORROW_RESERVATION_CONFLICT, lint_root, DUMMY_SP, "");
293 diag.message = initial_diag.styled_message().clone();
294 diag.span = initial_diag.span.clone();
296 initial_diag.cancel();
297 diag.buffer(&mut mbcx.errors_buffer);
300 // For each non-user used mutable variable, check if it's been assigned from
301 // a user-declared local. If so, then put that local into the used_mut set.
302 // Note that this set is expected to be small - only upvars from closures
303 // would have a chance of erroneously adding non-user-defined mutable vars
305 let temporary_used_locals: FxHashSet<Local> = mbcx.used_mut.iter()
306 .filter(|&local| mbcx.body.local_decls[*local].is_user_variable.is_none())
309 // For the remaining unused locals that are marked as mutable, we avoid linting any that
310 // were never initialized. These locals may have been removed as unreachable code; or will be
311 // linted as unused variables.
312 let unused_mut_locals = mbcx.body.mut_vars_iter()
313 .filter(|local| !mbcx.used_mut.contains(local))
315 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
317 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
318 let used_mut = mbcx.used_mut;
319 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
320 if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
321 let local_decl = &mbcx.body.local_decls[local];
323 // Skip implicit `self` argument for closures
324 if local.index() == 1 && tcx.is_closure(mbcx.mir_def_id) {
328 // Skip over locals that begin with an underscore or have no name
329 match local_decl.name {
330 Some(name) => if name.as_str().starts_with("_") {
336 let span = local_decl.source_info.span;
337 if span.desugaring_kind().is_some() {
338 // If the `mut` arises as part of a desugaring, we should ignore it.
342 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
343 tcx.struct_span_lint_hir(
345 vsi[local_decl.source_info.scope].lint_root,
347 "variable does not need to be mutable",
349 .span_suggestion_short(
353 Applicability::MachineApplicable,
359 // Buffer any move errors that we collected and de-duplicated.
360 for (_, (_, diag)) in mbcx.move_error_reported {
361 diag.buffer(&mut mbcx.errors_buffer);
364 if !mbcx.errors_buffer.is_empty() {
365 mbcx.errors_buffer.sort_by_key(|diag| diag.span.primary_span());
367 if tcx.migrate_borrowck() {
368 // When borrowck=migrate, check if AST-borrowck would
369 // error on the given code.
371 // rust-lang/rust#55492, rust-lang/rust#58776 check the base def id
372 // for errors. AST borrowck is responsible for aggregating
373 // `signalled_any_error` from all of the nested closures here.
374 let base_def_id = tcx.closure_base_def_id(def_id);
376 match tcx.borrowck(base_def_id).signalled_any_error {
377 SignalledError::NoErrorsSeen => {
378 // if AST-borrowck signalled no errors, then
379 // downgrade all the buffered MIR-borrowck errors
382 for err in mbcx.errors_buffer.iter_mut() {
383 downgrade_if_error(err);
386 SignalledError::SawSomeError => {
387 // if AST-borrowck signalled a (cancelled) error,
388 // then we will just emit the buffered
389 // MIR-borrowck errors as normal.
394 for diag in mbcx.errors_buffer.drain(..) {
395 DiagnosticBuilder::new_diagnostic(mbcx.infcx.tcx.sess.diagnostic(), diag).emit();
399 let result = BorrowCheckResult {
400 closure_requirements: opt_closure_req,
401 used_mut_upvars: mbcx.used_mut_upvars,
404 debug!("do_mir_borrowck: result = {:#?}", result);
409 fn downgrade_if_error(diag: &mut Diagnostic) {
411 diag.level = Level::Warning;
413 "this error has been downgraded to a warning for backwards \
414 compatibility with previous releases",
416 "this represents potential undefined behavior in your code and \
417 this warning will become a hard error in the future",
419 "for more information, try `rustc --explain E0729`"
424 crate struct MirBorrowckCtxt<'cx, 'tcx> {
425 crate infcx: &'cx InferCtxt<'cx, 'tcx>,
426 body: &'cx Body<'tcx>,
428 move_data: &'cx MoveData<'tcx>,
430 /// Map from MIR `Location` to `LocationIndex`; created
431 /// when MIR borrowck begins.
432 location_table: &'cx LocationTable,
434 movable_generator: bool,
435 /// This keeps track of whether local variables are free-ed when the function
436 /// exits even without a `StorageDead`, which appears to be the case for
439 /// I'm not sure this is the right approach - @eddyb could you try and
441 locals_are_invalidated_at_exit: bool,
442 /// This field keeps track of when borrow errors are reported in the access_place function
443 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
444 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
445 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
447 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
448 /// This field keeps track of when borrow conflict errors are reported
449 /// for reservations, so that we don't report seemingly duplicate
450 /// errors for corresponding activations.
452 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
453 // but it is currently inconvenient to track down the `BorrowIndex`
454 // at the time we detect and report a reservation error.
455 reservation_error_reported: FxHashSet<Place<'tcx>>,
456 /// Migration warnings to be reported for #56254. We delay reporting these
457 /// so that we can suppress the warning if there's a corresponding error
458 /// for the activation of the borrow.
459 reservation_warnings: FxHashMap<
461 (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)
463 /// This field keeps track of move errors that are to be reported for given move indicies.
465 /// There are situations where many errors can be reported for a single move out (see #53807)
466 /// and we want only the best of those errors.
468 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
469 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
470 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
471 /// all move errors have been reported, any diagnostics in this map are added to the buffer
474 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
475 /// when errors in the map are being re-added to the error buffer so that errors with the
476 /// same primary span come out in a consistent order.
477 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (Place<'tcx>, DiagnosticBuilder<'cx>)>,
478 /// This field keeps track of errors reported in the checking of uninitialized variables,
479 /// so that we don't report seemingly duplicate errors.
480 uninitialized_error_reported: FxHashSet<Place<'tcx>>,
481 /// Errors to be reported buffer
482 errors_buffer: Vec<Diagnostic>,
483 /// This field keeps track of all the local variables that are declared mut and are mutated.
484 /// Used for the warning issued by an unused mutable local variable.
485 used_mut: FxHashSet<Local>,
486 /// If the function we're checking is a closure, then we'll need to report back the list of
487 /// mutable upvars that have been used. This field keeps track of them.
488 used_mut_upvars: SmallVec<[Field; 8]>,
489 /// Non-lexical region inference context, if NLL is enabled. This
490 /// contains the results from region inference and lets us e.g.
491 /// find out which CFG points are contained in each borrow region.
492 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
494 /// The set of borrows extracted from the MIR
495 borrow_set: Rc<BorrowSet<'tcx>>,
497 /// Dominators for MIR
498 dominators: Dominators<BasicBlock>,
500 /// Information about upvars not necessarily preserved in types or MIR
505 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
506 // 2. loans made in overlapping scopes do not conflict
507 // 3. assignments do not affect things loaned out as immutable
508 // 4. moves do not affect things loaned out in any way
509 impl<'cx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
510 type FlowState = Flows<'cx, 'tcx>;
512 fn body(&self) -> &'cx Body<'tcx> {
516 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
517 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
520 fn visit_statement_entry(
523 stmt: &Statement<'tcx>,
524 flow_state: &Self::FlowState,
527 "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
528 location, stmt, flow_state
530 let span = stmt.source_info.span;
532 self.check_activations(location, span, flow_state);
535 StatementKind::Assign(ref lhs, ref rhs) => {
550 StatementKind::FakeRead(_, ref place) => {
551 // Read for match doesn't access any memory and is used to
552 // assert that a place is safe and live. So we don't have to
553 // do any checks here.
555 // FIXME: Remove check that the place is initialized. This is
556 // needed for now because matches don't have never patterns yet.
557 // So this is the only place we prevent
561 self.check_if_path_or_subpath_is_moved(
563 InitializationRequiringAction::Use,
568 StatementKind::SetDiscriminant {
580 StatementKind::InlineAsm(ref asm) => {
581 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
583 // FIXME(eddyb) indirect inline asm outputs should
584 // be encoded through MIR place derefs instead.
588 (Deep, Read(ReadKind::Copy)),
589 LocalMutationIsAllowed::No,
592 self.check_if_path_or_subpath_is_moved(
594 InitializationRequiringAction::Use,
602 if o.is_rw { Deep } else { Shallow(None) },
603 if o.is_rw { WriteAndRead } else { JustWrite },
608 for (_, input) in asm.inputs.iter() {
609 self.consume_operand(location, (input, span), flow_state);
613 | StatementKind::AscribeUserType(..)
614 | StatementKind::Retag { .. }
615 | StatementKind::StorageLive(..) => {
616 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
619 StatementKind::StorageDead(local) => {
622 (&Place::from(local), span),
623 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
624 LocalMutationIsAllowed::Yes,
631 fn visit_terminator_entry(
634 term: &Terminator<'tcx>,
635 flow_state: &Self::FlowState,
639 "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
640 location, term, flow_state
642 let span = term.source_info.span;
644 self.check_activations(location, span, flow_state);
647 TerminatorKind::SwitchInt {
653 self.consume_operand(loc, (discr, span), flow_state);
655 TerminatorKind::Drop {
656 location: ref drop_place,
660 let gcx = self.infcx.tcx.global_tcx();
662 // Compute the type with accurate region information.
663 let drop_place_ty = drop_place.ty(self.body, self.infcx.tcx);
665 // Erase the regions.
666 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
668 // "Lift" into the gcx -- once regions are erased, this type should be in the
669 // global arenas; this "lift" operation basically just asserts that is true, but
670 // that is useful later.
671 gcx.lift_to_global(&drop_place_ty).unwrap();
673 debug!("visit_terminator_drop \
674 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
675 loc, term, drop_place, drop_place_ty, span);
680 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
681 LocalMutationIsAllowed::Yes,
685 TerminatorKind::DropAndReplace {
686 location: ref drop_place,
687 value: ref new_value,
698 self.consume_operand(
704 TerminatorKind::Call {
711 self.consume_operand(loc, (func, span), flow_state);
713 self.consume_operand(
719 if let Some((ref dest, _ /*bb*/)) = *destination {
729 TerminatorKind::Assert {
736 self.consume_operand(loc, (cond, span), flow_state);
737 use rustc::mir::interpret::InterpError::BoundsCheck;
738 if let BoundsCheck { ref len, ref index } = *msg {
739 self.consume_operand(loc, (len, span), flow_state);
740 self.consume_operand(loc, (index, span), flow_state);
744 TerminatorKind::Yield {
749 self.consume_operand(loc, (value, span), flow_state);
751 if self.movable_generator {
752 // Look for any active borrows to locals
753 let borrow_set = self.borrow_set.clone();
754 flow_state.with_outgoing_borrows(|borrows| {
756 let borrow = &borrow_set[i];
757 self.check_for_local_borrow(borrow, span);
763 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
764 // Returning from the function implicitly kills storage for all locals and statics.
765 // Often, the storage will already have been killed by an explicit
766 // StorageDead, but we don't always emit those (notably on unwind paths),
767 // so this "extra check" serves as a kind of backup.
768 let borrow_set = self.borrow_set.clone();
769 flow_state.with_outgoing_borrows(|borrows| {
771 let borrow = &borrow_set[i];
772 self.check_for_invalidation_at_exit(loc, borrow, span);
776 TerminatorKind::Goto { target: _ }
777 | TerminatorKind::Abort
778 | TerminatorKind::Unreachable
779 | TerminatorKind::FalseEdges {
783 | TerminatorKind::FalseUnwind {
787 // no data used, thus irrelevant to borrowck
793 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
799 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
800 use self::AccessDepth::{Deep, Shallow};
802 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
803 enum ArtificialField {
808 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
810 /// From the RFC: "A *shallow* access means that the immediate
811 /// fields reached at P are accessed, but references or pointers
812 /// found within are not dereferenced. Right now, the only access
813 /// that is shallow is an assignment like `x = ...;`, which would
814 /// be a *shallow write* of `x`."
815 Shallow(Option<ArtificialField>),
817 /// From the RFC: "A *deep* access means that all data reachable
818 /// through the given place may be invalidated or accesses by
822 /// Access is Deep only when there is a Drop implementation that
823 /// can reach the data behind the reference.
827 /// Kind of access to a value: read or write
828 /// (For informational purposes only)
829 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
831 /// From the RFC: "A *read* means that the existing data may be
832 /// read, but will not be changed."
835 /// From the RFC: "A *write* means that the data may be mutated to
836 /// new values or otherwise invalidated (for example, it could be
837 /// de-initialized, as in a move operation).
840 /// For two-phase borrows, we distinguish a reservation (which is treated
841 /// like a Read) from an activation (which is treated like a write), and
842 /// each of those is furthermore distinguished from Reads/Writes above.
843 Reservation(WriteKind),
844 Activation(WriteKind, BorrowIndex),
847 /// Kind of read access to a value
848 /// (For informational purposes only)
849 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
855 /// Kind of write access to a value
856 /// (For informational purposes only)
857 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
860 MutableBorrow(BorrowKind),
865 /// When checking permissions for a place access, this flag is used to indicate that an immutable
866 /// local place can be mutated.
868 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
869 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
870 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
871 // `is_declared_mutable()`.
872 // - Take flow state into consideration in `is_assignable()` for local variables.
873 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
874 enum LocalMutationIsAllowed {
876 /// We want use of immutable upvars to cause a "write to immutable upvar"
877 /// error, not an "reassignment" error.
882 #[derive(Copy, Clone, Debug)]
883 enum InitializationRequiringAction {
892 struct RootPlace<'d, 'tcx> {
893 place: &'d Place<'tcx>,
894 is_local_mutation_allowed: LocalMutationIsAllowed,
897 impl InitializationRequiringAction {
898 fn as_noun(self) -> &'static str {
900 InitializationRequiringAction::Update => "update",
901 InitializationRequiringAction::Borrow => "borrow",
902 InitializationRequiringAction::MatchOn => "use", // no good noun
903 InitializationRequiringAction::Use => "use",
904 InitializationRequiringAction::Assignment => "assign",
905 InitializationRequiringAction::PartialAssignment => "assign to part",
909 fn as_verb_in_past_tense(self) -> &'static str {
911 InitializationRequiringAction::Update => "updated",
912 InitializationRequiringAction::Borrow => "borrowed",
913 InitializationRequiringAction::MatchOn => "matched on",
914 InitializationRequiringAction::Use => "used",
915 InitializationRequiringAction::Assignment => "assigned",
916 InitializationRequiringAction::PartialAssignment => "partially assigned",
921 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
922 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
923 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
924 /// place is initialized and (b) it is not borrowed in some way that would prevent this
927 /// Returns `true` if an error is reported.
931 place_span: (&Place<'tcx>, Span),
932 kind: (AccessDepth, ReadOrWrite),
933 is_local_mutation_allowed: LocalMutationIsAllowed,
934 flow_state: &Flows<'cx, 'tcx>,
938 if let Activation(_, borrow_index) = rw {
939 if self.reservation_error_reported.contains(&place_span.0) {
941 "skipping access_place for activation of invalid reservation \
942 place: {:?} borrow_index: {:?}",
943 place_span.0, borrow_index
949 // Check is_empty() first because it's the common case, and doing that
950 // way we avoid the clone() call.
951 if !self.access_place_error_reported.is_empty() &&
953 .access_place_error_reported
954 .contains(&(place_span.0.clone(), place_span.1))
957 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
963 let mutability_error =
964 self.check_access_permissions(
967 is_local_mutation_allowed,
972 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
974 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
975 // Suppress this warning when there's an error being emited for the
976 // same borrow: fixing the error is likely to fix the warning.
977 self.reservation_warnings.remove(&borrow_idx);
980 if conflict_error || mutability_error {
982 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
986 self.access_place_error_reported
987 .insert((place_span.0.clone(), place_span.1));
991 fn check_access_for_conflict(
994 place_span: (&Place<'tcx>, Span),
997 flow_state: &Flows<'cx, 'tcx>,
1000 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1001 location, place_span, sd, rw,
1004 let mut error_reported = false;
1005 let tcx = self.infcx.tcx;
1006 let body = self.body;
1007 let location_table = self.location_table.start_index(location);
1008 let borrow_set = self.borrow_set.clone();
1009 each_borrow_involving_path(
1016 flow_state.borrows_in_scope(location_table),
1017 |this, borrow_index, borrow| match (rw, borrow.kind) {
1018 // Obviously an activation is compatible with its own
1019 // reservation (or even prior activating uses of same
1020 // borrow); so don't check if they interfere.
1022 // NOTE: *reservations* do conflict with themselves;
1023 // thus aren't injecting unsoundenss w/ this check.)
1024 (Activation(_, activating), _) if activating == borrow_index => {
1026 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1027 skipping {:?} b/c activation of same borrow_index",
1031 (borrow_index, borrow),
1036 (Read(_), BorrowKind::Shared)
1037 | (Read(_), BorrowKind::Shallow)
1038 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
1039 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
1043 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1044 // Handled by initialization checks.
1048 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
1049 // Reading from mere reservations of mutable-borrows is OK.
1050 if !is_active(&this.dominators, borrow, location) {
1051 assert!(allow_two_phase_borrow(borrow.kind));
1052 return Control::Continue;
1055 error_reported = true;
1058 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1059 .buffer(&mut this.errors_buffer);
1061 ReadKind::Borrow(bk) => {
1062 this.report_conflicting_borrow(location, place_span, bk, borrow)
1063 .buffer(&mut this.errors_buffer);
1069 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
1070 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared) if {
1071 tcx.migrate_borrowck() && this.borrow_set.location_map.contains_key(&location)
1073 let bi = this.borrow_set.location_map[&location];
1075 "recording invalid reservation of place: {:?} with \
1076 borrow index {:?} as warning",
1080 // rust-lang/rust#56254 - This was previously permitted on
1081 // the 2018 edition so we emit it as a warning. We buffer
1082 // these sepately so that we only emit a warning if borrow
1083 // checking was otherwise successful.
1084 this.reservation_warnings.insert(
1086 (place_span.0.clone(), place_span.1, location, bk, borrow.clone()),
1089 // Don't suppress actual errors.
1093 (Reservation(kind), _)
1094 | (Activation(kind, _), _)
1095 | (Write(kind), _) => {
1097 Reservation(..) => {
1099 "recording invalid reservation of \
1103 this.reservation_error_reported.insert(place_span.0.clone());
1105 Activation(_, activating) => {
1107 "observing check_place for activation of \
1108 borrow_index: {:?}",
1112 Read(..) | Write(..) => {}
1115 error_reported = true;
1117 WriteKind::MutableBorrow(bk) => {
1118 this.report_conflicting_borrow(location, place_span, bk, borrow)
1119 .buffer(&mut this.errors_buffer);
1121 WriteKind::StorageDeadOrDrop => {
1122 this.report_borrowed_value_does_not_live_long_enough(
1128 WriteKind::Mutate => {
1129 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1131 WriteKind::Move => {
1132 this.report_move_out_while_borrowed(location, place_span, borrow)
1146 place_span: (&Place<'tcx>, Span),
1149 flow_state: &Flows<'cx, 'tcx>,
1151 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1153 MutateMode::WriteAndRead => {
1154 self.check_if_path_or_subpath_is_moved(
1156 InitializationRequiringAction::Update,
1161 MutateMode::JustWrite => {
1162 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1166 // Special case: you can assign a immutable local variable
1167 // (e.g., `x = ...`) so long as it has never been initialized
1168 // before (at this point in the flow).
1169 if let &Place::Base(PlaceBase::Local(local)) = place_span.0 {
1170 if let Mutability::Not = self.body.local_decls[local].mutability {
1171 // check for reassignments to immutable local variables
1172 self.check_if_reassignment_to_immutable_state(
1182 // Otherwise, use the normal access permission rules.
1186 (kind, Write(WriteKind::Mutate)),
1187 LocalMutationIsAllowed::No,
1195 (rvalue, span): (&Rvalue<'tcx>, Span),
1196 flow_state: &Flows<'cx, 'tcx>,
1199 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1200 let access_kind = match bk {
1201 BorrowKind::Shallow => {
1202 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1204 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1205 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1206 let wk = WriteKind::MutableBorrow(bk);
1207 if allow_two_phase_borrow(bk) {
1208 (Deep, Reservation(wk))
1219 LocalMutationIsAllowed::No,
1223 let action = if bk == BorrowKind::Shallow {
1224 InitializationRequiringAction::MatchOn
1226 InitializationRequiringAction::Borrow
1229 self.check_if_path_or_subpath_is_moved(
1237 Rvalue::Use(ref operand)
1238 | Rvalue::Repeat(ref operand, _)
1239 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1240 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1241 self.consume_operand(location, (operand, span), flow_state)
1244 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1245 let af = match *rvalue {
1246 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1247 Rvalue::Discriminant(..) => None,
1248 _ => unreachable!(),
1253 (Shallow(af), Read(ReadKind::Copy)),
1254 LocalMutationIsAllowed::No,
1257 self.check_if_path_or_subpath_is_moved(
1259 InitializationRequiringAction::Use,
1265 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1266 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1267 self.consume_operand(location, (operand1, span), flow_state);
1268 self.consume_operand(location, (operand2, span), flow_state);
1271 Rvalue::NullaryOp(_op, _ty) => {
1272 // nullary ops take no dynamic input; no borrowck effect.
1274 // FIXME: is above actually true? Do we want to track
1275 // the fact that uninitialized data can be created via
1279 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1280 // We need to report back the list of mutable upvars that were
1281 // moved into the closure and subsequently used by the closure,
1282 // in order to populate our used_mut set.
1283 match **aggregate_kind {
1284 AggregateKind::Closure(def_id, _)
1285 | AggregateKind::Generator(def_id, _, _) => {
1286 let BorrowCheckResult {
1288 } = self.infcx.tcx.mir_borrowck(def_id);
1289 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1290 for field in used_mut_upvars {
1291 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1294 AggregateKind::Adt(..)
1295 | AggregateKind::Array(..)
1296 | AggregateKind::Tuple { .. } => (),
1299 for operand in operands {
1300 self.consume_operand(location, (operand, span), flow_state);
1306 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1307 let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1309 Place::Projection { .. } => {
1310 if let Some(field) = this.is_upvar_field_projection(place) {
1311 this.used_mut_upvars.push(field);
1314 Place::Base(PlaceBase::Local(local)) => {
1315 this.used_mut.insert(local);
1317 Place::Base(PlaceBase::Static(_)) => {}
1321 // This relies on the current way that by-value
1322 // captures of a closure are copied/moved directly
1323 // when generating MIR.
1325 Operand::Move(Place::Base(PlaceBase::Local(local)))
1326 | Operand::Copy(Place::Base(PlaceBase::Local(local)))
1327 if self.body.local_decls[local].is_user_variable.is_none() =>
1329 if self.body.local_decls[local].ty.is_mutable_pointer() {
1330 // The variable will be marked as mutable by the borrow.
1333 // This is an edge case where we have a `move` closure
1334 // inside a non-move closure, and the inner closure
1335 // contains a mutation:
1338 // || { move || { i += 1; }; };
1340 // In this case our usual strategy of assuming that the
1341 // variable will be captured by mutable reference is
1342 // wrong, since `i` can be copied into the inner
1343 // closure from a shared reference.
1345 // As such we have to search for the local that this
1346 // capture comes from and mark it as being used as mut.
1348 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1349 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1350 &self.move_data.inits[init_index]
1352 bug!("temporary should be initialized exactly once")
1355 let loc = match init.location {
1356 InitLocation::Statement(stmt) => stmt,
1357 _ => bug!("temporary initialized in arguments"),
1360 let bbd = &self.body[loc.block];
1361 let stmt = &bbd.statements[loc.statement_index];
1362 debug!("temporary assigned in: stmt={:?}", stmt);
1364 if let StatementKind::Assign(_, box Rvalue::Ref(_, _, ref source)) = stmt.kind {
1365 propagate_closure_used_mut_place(self, source);
1367 bug!("closures should only capture user variables \
1368 or references to user variables");
1371 Operand::Move(ref place)
1372 | Operand::Copy(ref place) => {
1373 propagate_closure_used_mut_place(self, place);
1375 Operand::Constant(..) => {}
1382 (operand, span): (&Operand<'tcx>, Span),
1383 flow_state: &Flows<'cx, 'tcx>,
1386 Operand::Copy(ref place) => {
1387 // copy of place: check if this is "copy of frozen path"
1388 // (FIXME: see check_loans.rs)
1392 (Deep, Read(ReadKind::Copy)),
1393 LocalMutationIsAllowed::No,
1397 // Finally, check if path was already moved.
1398 self.check_if_path_or_subpath_is_moved(
1400 InitializationRequiringAction::Use,
1405 Operand::Move(ref place) => {
1406 // move of place: check if this is move of already borrowed path
1410 (Deep, Write(WriteKind::Move)),
1411 LocalMutationIsAllowed::Yes,
1415 // Finally, check if path was already moved.
1416 self.check_if_path_or_subpath_is_moved(
1418 InitializationRequiringAction::Use,
1423 Operand::Constant(_) => {}
1427 /// Checks whether a borrow of this place is invalidated when the function
1429 fn check_for_invalidation_at_exit(
1432 borrow: &BorrowData<'tcx>,
1435 debug!("check_for_invalidation_at_exit({:?})", borrow);
1436 let place = &borrow.borrowed_place;
1437 let root_place = self.prefixes(place, PrefixSet::All).last().unwrap();
1439 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1440 // we just know that all locals are dropped at function exit (otherwise
1441 // we'll have a memory leak) and assume that all statics have a destructor.
1443 // FIXME: allow thread-locals to borrow other thread locals?
1444 let (might_be_alive, will_be_dropped) = match root_place {
1445 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Promoted(_), .. })) => {
1448 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(_), .. })) => {
1449 // Thread-locals might be dropped after the function exits, but
1450 // "true" statics will never be.
1451 (true, self.is_place_thread_local(&root_place))
1453 Place::Base(PlaceBase::Local(_)) => {
1454 // Locals are always dropped at function exit, and if they
1455 // have a destructor it would've been called already.
1456 (false, self.locals_are_invalidated_at_exit)
1458 Place::Projection(..) => {
1459 bug!("root of {:?} is a projection ({:?})?", place, root_place)
1463 if !will_be_dropped {
1465 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1471 let sd = if might_be_alive { Deep } else { Shallow(None) };
1473 if places_conflict::borrow_conflicts_with_place(
1480 places_conflict::PlaceConflictBias::Overlap,
1482 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1483 // FIXME: should be talking about the region lifetime instead
1484 // of just a span here.
1485 let span = self.infcx.tcx.sess.source_map().end_point(span);
1486 self.report_borrowed_value_does_not_live_long_enough(
1495 /// Reports an error if this is a borrow of local data.
1496 /// This is called for all Yield statements on movable generators
1497 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1498 debug!("check_for_local_borrow({:?})", borrow);
1500 if borrow_of_local_data(&borrow.borrowed_place) {
1501 let err = self.cannot_borrow_across_generator_yield(
1502 self.retrieve_borrow_spans(borrow).var_or_use(),
1506 err.buffer(&mut self.errors_buffer);
1510 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1511 // Two-phase borrow support: For each activation that is newly
1512 // generated at this statement, check if it interferes with
1514 let borrow_set = self.borrow_set.clone();
1515 for &borrow_index in borrow_set.activations_at_location(location) {
1516 let borrow = &borrow_set[borrow_index];
1518 // only mutable borrows should be 2-phase
1519 assert!(match borrow.kind {
1520 BorrowKind::Shared | BorrowKind::Shallow => false,
1521 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1526 (&borrow.borrowed_place, span),
1529 Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1531 LocalMutationIsAllowed::No,
1534 // We do not need to call `check_if_path_or_subpath_is_moved`
1535 // again, as we already called it when we made the
1536 // initial reservation.
1541 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
1542 fn check_if_reassignment_to_immutable_state(
1546 place_span: (&Place<'tcx>, Span),
1547 flow_state: &Flows<'cx, 'tcx>,
1549 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1551 // Check if any of the initializiations of `local` have happened yet:
1552 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1553 // And, if so, report an error.
1554 let init = &self.move_data.inits[init_index];
1555 let span = init.span(&self.body);
1556 self.report_illegal_reassignment(
1557 location, place_span, span, place_span.0
1562 fn check_if_full_path_is_moved(
1565 desired_action: InitializationRequiringAction,
1566 place_span: (&Place<'tcx>, Span),
1567 flow_state: &Flows<'cx, 'tcx>,
1569 let maybe_uninits = &flow_state.uninits;
1573 // 1. Move of `a.b.c`, use of `a.b.c`
1574 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1575 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1576 // partial initialization support, one might have `a.x`
1577 // initialized but not `a.b`.
1581 // 4. Move of `a.b.c`, use of `a.b.d`
1582 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1583 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1584 // must have been initialized for the use to be sound.
1585 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1587 // The dataflow tracks shallow prefixes distinctly (that is,
1588 // field-accesses on P distinctly from P itself), in order to
1589 // track substructure initialization separately from the whole
1592 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1593 // which we have a MovePath is `a.b`, then that means that the
1594 // initialization state of `a.b` is all we need to inspect to
1595 // know if `a.b.c` is valid (and from that we infer that the
1596 // dereference and `.d` access is also valid, since we assume
1597 // `a.b.c` is assigned a reference to a initialized and
1598 // well-formed record structure.)
1600 // Therefore, if we seek out the *closest* prefix for which we
1601 // have a MovePath, that should capture the initialization
1602 // state for the place scenario.
1604 // This code covers scenarios 1, 2, and 3.
1606 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1607 match self.move_path_closest_to(place_span.0) {
1608 Ok((prefix, mpi)) => {
1609 if maybe_uninits.contains(mpi) {
1610 self.report_use_of_moved_or_uninitialized(
1613 (prefix, place_span.0, place_span.1),
1616 return; // don't bother finding other problems.
1619 Err(NoMovePathFound::ReachedStatic) => {
1620 // Okay: we do not build MoveData for static variables
1621 } // Only query longest prefix with a MovePath, not further
1622 // ancestors; dataflow recurs on children when parents
1623 // move (to support partial (re)inits).
1625 // (I.e., querying parents breaks scenario 7; but may want
1626 // to do such a query based on partial-init feature-gate.)
1630 fn check_if_path_or_subpath_is_moved(
1633 desired_action: InitializationRequiringAction,
1634 place_span: (&Place<'tcx>, Span),
1635 flow_state: &Flows<'cx, 'tcx>,
1637 let maybe_uninits = &flow_state.uninits;
1641 // 1. Move of `a.b.c`, use of `a` or `a.b`
1642 // partial initialization support, one might have `a.x`
1643 // initialized but not `a.b`.
1644 // 2. All bad scenarios from `check_if_full_path_is_moved`
1648 // 3. Move of `a.b.c`, use of `a.b.d`
1649 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1650 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1651 // must have been initialized for the use to be sound.
1652 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1654 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1656 // A move of any shallow suffix of `place` also interferes
1657 // with an attempt to use `place`. This is scenario 3 above.
1659 // (Distinct from handling of scenarios 1+2+4 above because
1660 // `place` does not interfere with suffixes of its prefixes,
1661 // e.g., `a.b.c` does not interfere with `a.b.d`)
1663 // This code covers scenario 1.
1665 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1666 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1667 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1668 self.report_use_of_moved_or_uninitialized(
1671 (place_span.0, place_span.0, place_span.1),
1674 return; // don't bother finding other problems.
1679 /// Currently MoveData does not store entries for all places in
1680 /// the input MIR. For example it will currently filter out
1681 /// places that are Copy; thus we do not track places of shared
1682 /// reference type. This routine will walk up a place along its
1683 /// prefixes, searching for a foundational place that *is*
1684 /// tracked in the MoveData.
1686 /// An Err result includes a tag indicated why the search failed.
1687 /// Currently this can only occur if the place is built off of a
1688 /// static variable, as we do not track those in the MoveData.
1689 fn move_path_closest_to<'a>(
1691 place: &'a Place<'tcx>,
1692 ) -> Result<(&'a Place<'tcx>, MovePathIndex), NoMovePathFound> where 'cx: 'a {
1693 let mut last_prefix = place;
1694 for prefix in self.prefixes(place, PrefixSet::All) {
1695 if let Some(mpi) = self.move_path_for_place(prefix) {
1696 return Ok((prefix, mpi));
1698 last_prefix = prefix;
1700 match *last_prefix {
1701 Place::Base(PlaceBase::Local(_)) => panic!("should have move path for every Local"),
1702 Place::Projection(_) => panic!("PrefixSet::All meant don't stop for Projection"),
1703 Place::Base(PlaceBase::Static(_)) => Err(NoMovePathFound::ReachedStatic),
1707 fn move_path_for_place(&mut self, place: &Place<'tcx>) -> Option<MovePathIndex> {
1708 // If returns None, then there is no move path corresponding
1709 // to a direct owner of `place` (which means there is nothing
1710 // that borrowck tracks for its analysis).
1712 match self.move_data.rev_lookup.find(place) {
1713 LookupResult::Parent(_) => None,
1714 LookupResult::Exact(mpi) => Some(mpi),
1718 fn check_if_assigned_path_is_moved(
1721 (place, span): (&Place<'tcx>, Span),
1722 flow_state: &Flows<'cx, 'tcx>,
1724 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1725 // recur down place; dispatch to external checks when necessary
1726 let mut place = place;
1729 Place::Base(PlaceBase::Local(_)) | Place::Base(PlaceBase::Static(_)) => {
1730 // assigning to `x` does not require `x` be initialized.
1733 Place::Projection(ref proj) => {
1734 let Projection { ref base, ref elem } = **proj;
1736 ProjectionElem::Index(_/*operand*/) |
1737 ProjectionElem::ConstantIndex { .. } |
1738 // assigning to P[i] requires P to be valid.
1739 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1740 // assigning to (P->variant) is okay if assigning to `P` is okay
1742 // FIXME: is this true even if P is a adt with a dtor?
1745 // assigning to (*P) requires P to be initialized
1746 ProjectionElem::Deref => {
1747 self.check_if_full_path_is_moved(
1748 location, InitializationRequiringAction::Use,
1749 (base, span), flow_state);
1750 // (base initialized; no need to
1755 ProjectionElem::Subslice { .. } => {
1756 panic!("we don't allow assignments to subslices, location: {:?}",
1760 ProjectionElem::Field(..) => {
1761 // if type of `P` has a dtor, then
1762 // assigning to `P.f` requires `P` itself
1763 // be already initialized
1764 let tcx = self.infcx.tcx;
1765 match base.ty(self.body, tcx).ty.sty {
1766 ty::Adt(def, _) if def.has_dtor(tcx) => {
1767 self.check_if_path_or_subpath_is_moved(
1768 location, InitializationRequiringAction::Assignment,
1769 (base, span), flow_state);
1771 // (base initialized; no need to
1777 // Once `let s; s.x = V; read(s.x);`,
1778 // is allowed, remove this match arm.
1779 ty::Adt(..) | ty::Tuple(..) => {
1780 check_parent_of_field(self, location, base, span, flow_state);
1782 if let Some(local) = place.base_local() {
1783 // rust-lang/rust#21232,
1784 // #54499, #54986: during
1785 // period where we reject
1786 // partial initialization, do
1787 // not complain about
1788 // unnecessary `mut` on an
1789 // attempt to do a partial
1791 self.used_mut.insert(local);
1805 fn check_parent_of_field<'cx, 'tcx>(
1806 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1810 flow_state: &Flows<'cx, 'tcx>,
1812 // rust-lang/rust#21232: Until Rust allows reads from the
1813 // initialized parts of partially initialized structs, we
1814 // will, starting with the 2018 edition, reject attempts
1815 // to write to structs that are not fully initialized.
1817 // In other words, *until* we allow this:
1819 // 1. `let mut s; s.x = Val; read(s.x);`
1821 // we will for now disallow this:
1823 // 2. `let mut s; s.x = Val;`
1827 // 3. `let mut s = ...; drop(s); s.x=Val;`
1829 // This does not use check_if_path_or_subpath_is_moved,
1830 // because we want to *allow* reinitializations of fields:
1831 // e.g., want to allow
1833 // `let mut s = ...; drop(s.x); s.x=Val;`
1835 // This does not use check_if_full_path_is_moved on
1836 // `base`, because that would report an error about the
1837 // `base` as a whole, but in this scenario we *really*
1838 // want to report an error about the actual thing that was
1839 // moved, which may be some prefix of `base`.
1841 // Shallow so that we'll stop at any dereference; we'll
1842 // report errors about issues with such bases elsewhere.
1843 let maybe_uninits = &flow_state.uninits;
1845 // Find the shortest uninitialized prefix you can reach
1846 // without going over a Deref.
1847 let mut shortest_uninit_seen = None;
1848 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1849 let mpi = match this.move_path_for_place(prefix) {
1850 Some(mpi) => mpi, None => continue,
1853 if maybe_uninits.contains(mpi) {
1854 debug!("check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1855 shortest_uninit_seen, Some((prefix, mpi)));
1856 shortest_uninit_seen = Some((prefix, mpi));
1858 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1862 if let Some((prefix, mpi)) = shortest_uninit_seen {
1863 // Check for a reassignment into a uninitialized field of a union (for example,
1864 // after a move out). In this case, do not report a error here. There is an
1865 // exception, if this is the first assignment into the union (that is, there is
1866 // no move out from an earlier location) then this is an attempt at initialization
1867 // of the union - we should error in that case.
1868 let tcx = this.infcx.tcx;
1869 if let ty::Adt(def, _) = base.ty(this.body, tcx).ty.sty {
1871 if this.move_data.path_map[mpi].iter().any(|moi| {
1872 this.move_data.moves[*moi].source.is_predecessor_of(
1873 location, this.body,
1881 this.report_use_of_moved_or_uninitialized(
1883 InitializationRequiringAction::PartialAssignment,
1884 (prefix, base, span),
1891 /// Checks the permissions for the given place and read or write kind
1893 /// Returns `true` if an error is reported.
1894 fn check_access_permissions(
1896 (place, span): (&Place<'tcx>, Span),
1898 is_local_mutation_allowed: LocalMutationIsAllowed,
1899 flow_state: &Flows<'cx, 'tcx>,
1903 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1904 place, kind, is_local_mutation_allowed
1910 // rust-lang/rust#21232, #54986: during period where we reject
1911 // partial initialization, do not complain about mutability
1912 // errors except for actual mutation (as opposed to an attempt
1913 // to do a partial initialization).
1914 let previously_initialized = if let Some(local) = place.base_local() {
1915 self.is_local_ever_initialized(local, flow_state).is_some()
1921 Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1922 | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
1923 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1924 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. })) => {
1925 let is_local_mutation_allowed = match borrow_kind {
1926 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1927 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1928 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1930 match self.is_mutable(place, is_local_mutation_allowed) {
1932 self.add_used_mut(root_place, flow_state);
1936 error_access = AccessKind::MutableBorrow;
1937 the_place_err = place_err;
1941 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1942 match self.is_mutable(place, is_local_mutation_allowed) {
1944 self.add_used_mut(root_place, flow_state);
1948 error_access = AccessKind::Mutate;
1949 the_place_err = place_err;
1954 Reservation(wk @ WriteKind::Move)
1955 | Write(wk @ WriteKind::Move)
1956 | Reservation(wk @ WriteKind::StorageDeadOrDrop)
1957 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1958 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow))
1959 | Write(wk @ WriteKind::StorageDeadOrDrop)
1960 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1961 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
1962 if let (Err(_place_err), true) = (
1963 self.is_mutable(place, is_local_mutation_allowed),
1964 self.errors_buffer.is_empty()
1966 if self.infcx.tcx.migrate_borrowck() {
1967 // rust-lang/rust#46908: In pure NLL mode this
1968 // code path should be unreachable (and thus
1969 // we signal an ICE in the else branch
1970 // here). But we can legitimately get here
1971 // under borrowck=migrate mode, so instead of
1972 // ICE'ing we instead report a legitimate
1973 // error (which will then be downgraded to a
1974 // warning by the migrate machinery).
1975 error_access = match wk {
1976 WriteKind::MutableBorrow(_) => AccessKind::MutableBorrow,
1977 WriteKind::Move => AccessKind::Move,
1978 WriteKind::StorageDeadOrDrop |
1979 WriteKind::Mutate => AccessKind::Mutate,
1981 self.report_mutability_error(
1991 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2000 // permission checks are done at Reservation point.
2003 Read(ReadKind::Borrow(BorrowKind::Unique))
2004 | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
2005 | Read(ReadKind::Borrow(BorrowKind::Shared))
2006 | Read(ReadKind::Borrow(BorrowKind::Shallow))
2007 | Read(ReadKind::Copy) => {
2008 // Access authorized
2013 // at this point, we have set up the error reporting state.
2014 return if previously_initialized {
2015 self.report_mutability_error(
2028 fn is_local_ever_initialized(
2031 flow_state: &Flows<'cx, 'tcx>,
2032 ) -> Option<InitIndex> {
2033 let mpi = self.move_data.rev_lookup.find_local(local);
2034 let ii = &self.move_data.init_path_map[mpi];
2036 if flow_state.ever_inits.contains(index) {
2043 /// Adds the place into the used mutable variables set
2044 fn add_used_mut<'d>(&mut self, root_place: RootPlace<'d, 'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2047 place: Place::Base(PlaceBase::Local(local)),
2048 is_local_mutation_allowed,
2050 // If the local may have been initialized, and it is now currently being
2051 // mutated, then it is justified to be annotated with the `mut`
2052 // keyword, since the mutation may be a possible reassignment.
2053 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes &&
2054 self.is_local_ever_initialized(*local, flow_state).is_some()
2056 self.used_mut.insert(*local);
2061 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2064 place: place @ Place::Projection(_),
2065 is_local_mutation_allowed: _,
2067 if let Some(field) = self.is_upvar_field_projection(place) {
2068 self.used_mut_upvars.push(field);
2072 place: Place::Base(PlaceBase::Static(..)),
2073 is_local_mutation_allowed: _,
2078 /// Whether this value can be written or borrowed mutably.
2079 /// Returns the root place if the place passed in is a projection.
2082 place: &'d Place<'tcx>,
2083 is_local_mutation_allowed: LocalMutationIsAllowed,
2084 ) -> Result<RootPlace<'d, 'tcx>, &'d Place<'tcx>> {
2086 Place::Base(PlaceBase::Local(local)) => {
2087 let local = &self.body.local_decls[local];
2088 match local.mutability {
2089 Mutability::Not => match is_local_mutation_allowed {
2090 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2092 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2094 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2096 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2098 LocalMutationIsAllowed::No => Err(place),
2100 Mutability::Mut => Ok(RootPlace {
2102 is_local_mutation_allowed,
2106 // The rules for promotion are made by `qualify_consts`, there wouldn't even be a
2107 // `Place::Promoted` if the promotion weren't 100% legal. So we just forward this
2108 Place::Base(PlaceBase::Static(box Static{kind: StaticKind::Promoted(_), ..})) =>
2111 is_local_mutation_allowed,
2113 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(def_id), .. })) => {
2114 if !self.infcx.tcx.is_mutable_static(def_id) {
2119 is_local_mutation_allowed,
2123 Place::Projection(ref proj) => {
2125 ProjectionElem::Deref => {
2126 let base_ty = proj.base.ty(self.body, self.infcx.tcx).ty;
2128 // Check the kind of deref to decide
2130 ty::Ref(_, _, mutbl) => {
2132 // Shared borrowed data is never mutable
2133 hir::MutImmutable => Err(place),
2134 // Mutably borrowed data is mutable, but only if we have a
2135 // unique path to the `&mut`
2136 hir::MutMutable => {
2137 let mode = match self.is_upvar_field_projection(place) {
2139 if self.upvars[field.index()].by_ref =>
2141 is_local_mutation_allowed
2143 _ => LocalMutationIsAllowed::Yes,
2146 self.is_mutable(&proj.base, mode)
2150 ty::RawPtr(tnm) => {
2152 // `*const` raw pointers are not mutable
2153 hir::MutImmutable => Err(place),
2154 // `*mut` raw pointers are always mutable, regardless of
2155 // context. The users have to check by themselves.
2156 hir::MutMutable => {
2159 is_local_mutation_allowed,
2164 // `Box<T>` owns its content, so mutable if its location is mutable
2165 _ if base_ty.is_box() => {
2166 self.is_mutable(&proj.base, is_local_mutation_allowed)
2168 // Deref should only be for reference, pointers or boxes
2169 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2172 // All other projections are owned by their base path, so mutable if
2173 // base path is mutable
2174 ProjectionElem::Field(..)
2175 | ProjectionElem::Index(..)
2176 | ProjectionElem::ConstantIndex { .. }
2177 | ProjectionElem::Subslice { .. }
2178 | ProjectionElem::Downcast(..) => {
2179 let upvar_field_projection = self.is_upvar_field_projection(place);
2180 if let Some(field) = upvar_field_projection {
2181 let upvar = &self.upvars[field.index()];
2183 "upvar.mutability={:?} local_mutation_is_allowed={:?} place={:?}",
2184 upvar, is_local_mutation_allowed, place
2186 match (upvar.mutability, is_local_mutation_allowed) {
2187 (Mutability::Not, LocalMutationIsAllowed::No)
2188 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2191 (Mutability::Not, LocalMutationIsAllowed::Yes)
2192 | (Mutability::Mut, _) => {
2193 // Subtle: this is an upvar
2194 // reference, so it looks like
2195 // `self.foo` -- we want to double
2196 // check that the location `*self`
2197 // is mutable (i.e., this is not a
2198 // `Fn` closure). But if that
2199 // check succeeds, we want to
2200 // *blame* the mutability on
2201 // `place` (that is,
2202 // `self.foo`). This is used to
2203 // propagate the info about
2204 // whether mutability declarations
2205 // are used outwards, so that we register
2206 // the outer variable as mutable. Otherwise a
2207 // test like this fails to record the `mut`
2211 // fn foo<F: FnOnce()>(_f: F) { }
2213 // let var = Vec::new();
2219 let _ = self.is_mutable(&proj.base, is_local_mutation_allowed)?;
2222 is_local_mutation_allowed,
2227 self.is_mutable(&proj.base, is_local_mutation_allowed)
2235 /// If `place` is a field projection, and the field is being projected from a closure type,
2236 /// then returns the index of the field being projected. Note that this closure will always
2237 /// be `self` in the current MIR, because that is the only time we directly access the fields
2238 /// of a closure type.
2239 pub fn is_upvar_field_projection(&self, place: &Place<'tcx>) -> Option<Field> {
2240 let (place, by_ref) = if let Place::Projection(ref proj) = place {
2241 if let ProjectionElem::Deref = proj.elem {
2251 Place::Projection(ref proj) => match proj.elem {
2252 ProjectionElem::Field(field, _ty) => {
2253 let tcx = self.infcx.tcx;
2254 let base_ty = proj.base.ty(self.body, tcx).ty;
2256 if (base_ty.is_closure() || base_ty.is_generator()) &&
2257 (!by_ref || self.upvars[field.index()].by_ref)
2271 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2272 enum NoMovePathFound {
2276 /// The degree of overlap between 2 places for borrow-checking.
2278 /// The places might partially overlap - in this case, we give
2279 /// up and say that they might conflict. This occurs when
2280 /// different fields of a union are borrowed. For example,
2281 /// if `u` is a union, we have no way of telling how disjoint
2282 /// `u.a.x` and `a.b.y` are.
2284 /// The places have the same type, and are either completely disjoint
2285 /// or equal - i.e., they can't "partially" overlap as can occur with
2286 /// unions. This is the "base case" on which we recur for extensions
2289 /// The places are disjoint, so we know all extensions of them
2290 /// will also be disjoint.