1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
3 use crate::borrow_check::nll::region_infer::RegionInferenceContext;
4 use rustc::hir::{self, HirId};
6 use rustc::hir::def_id::DefId;
7 use rustc::infer::InferCtxt;
8 use rustc::lint::builtin::UNUSED_MUT;
9 use rustc::lint::builtin::{MUTABLE_BORROW_RESERVATION_CONFLICT};
10 use rustc::middle::borrowck::SignalledError;
11 use rustc::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
13 ClearCrossCrate, Local, Location, Body, Mutability, Operand, Place, PlaceBase, PlaceRef,
16 use rustc::mir::{Field, Projection, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
17 use rustc::mir::{Terminator, TerminatorKind};
18 use rustc::ty::query::Providers;
19 use rustc::ty::{self, TyCtxt};
21 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, Level};
22 use rustc_data_structures::bit_set::BitSet;
23 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
24 use rustc_data_structures::graph::dominators::Dominators;
25 use rustc_data_structures::indexed_vec::IndexVec;
26 use smallvec::SmallVec;
28 use std::collections::BTreeMap;
32 use syntax::ast::Name;
33 use syntax_pos::{Span, DUMMY_SP};
35 use crate::dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex};
36 use crate::dataflow::move_paths::{HasMoveData, InitLocation, LookupResult, MoveData, MoveError};
37 use crate::dataflow::Borrows;
38 use crate::dataflow::DataflowResultsConsumer;
39 use crate::dataflow::FlowAtLocation;
40 use crate::dataflow::MoveDataParamEnv;
41 use crate::dataflow::{do_dataflow, DebugFormatted};
42 use crate::dataflow::EverInitializedPlaces;
43 use crate::dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
45 use self::borrow_set::{BorrowData, BorrowSet};
46 use self::flows::Flows;
47 use self::location::LocationTable;
48 use self::prefixes::PrefixSet;
49 use self::MutateMode::{JustWrite, WriteAndRead};
50 use self::mutability_errors::AccessKind;
52 use self::path_utils::*;
60 mod mutability_errors;
63 crate mod places_conflict;
69 // FIXME(eddyb) perhaps move this somewhere more centrally.
76 /// If true, the capture is behind a reference.
79 mutability: Mutability,
82 pub fn provide(providers: &mut Providers<'_>) {
83 *providers = Providers {
89 fn mir_borrowck(tcx: TyCtxt<'_>, def_id: DefId) -> BorrowCheckResult<'_> {
90 let (input_body, promoted) = tcx.mir_validated(def_id);
91 debug!("run query mir_borrowck: {}", tcx.def_path_str(def_id));
93 let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
94 let input_body: &Body<'_> = &input_body.borrow();
95 let promoted: &IndexVec<_, _> = &promoted.borrow();
96 do_mir_borrowck(&infcx, input_body, promoted, def_id)
98 debug!("mir_borrowck done");
103 fn do_mir_borrowck<'a, 'tcx>(
104 infcx: &InferCtxt<'a, 'tcx>,
105 input_body: &Body<'tcx>,
106 input_promoted: &IndexVec<Promoted, Body<'tcx>>,
108 ) -> BorrowCheckResult<'tcx> {
109 debug!("do_mir_borrowck(def_id = {:?})", def_id);
112 let attributes = tcx.get_attrs(def_id);
113 let param_env = tcx.param_env(def_id);
116 .as_local_hir_id(def_id)
117 .expect("do_mir_borrowck: non-local DefId");
119 // Gather the upvars of a closure, if any.
120 let tables = tcx.typeck_tables_of(def_id);
121 let upvars: Vec<_> = tables
125 .flat_map(|v| v.values())
127 let var_hir_id = upvar_id.var_path.hir_id;
128 let capture = tables.upvar_capture(*upvar_id);
129 let by_ref = match capture {
130 ty::UpvarCapture::ByValue => false,
131 ty::UpvarCapture::ByRef(..) => true,
133 let mut upvar = Upvar {
134 name: tcx.hir().name(var_hir_id),
137 mutability: Mutability::Not,
139 let bm = *tables.pat_binding_modes().get(var_hir_id)
140 .expect("missing binding mode");
141 if bm == ty::BindByValue(hir::MutMutable) {
142 upvar.mutability = Mutability::Mut;
148 // Replace all regions with fresh inference variables. This
149 // requires first making our own copy of the MIR. This copy will
150 // be modified (in place) to contain non-lexical lifetimes. It
151 // will have a lifetime tied to the inference context.
152 let mut body: Body<'tcx> = input_body.clone();
153 let mut promoted: IndexVec<Promoted, Body<'tcx>> = input_promoted.clone();
155 nll::replace_regions_in_mir(infcx, def_id, param_env, &mut body, &mut promoted);
156 let body = &body; // no further changes
157 let location_table = &LocationTable::new(body);
159 let mut errors_buffer = Vec::new();
160 let (move_data, move_errors): (MoveData<'tcx>, Option<Vec<(Place<'tcx>, MoveError<'tcx>)>>) =
161 match MoveData::gather_moves(body, tcx) {
162 Ok(move_data) => (move_data, None),
163 Err((move_data, move_errors)) => (move_data, Some(move_errors)),
166 let mdpe = MoveDataParamEnv {
167 move_data: move_data,
168 param_env: param_env,
171 let dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
172 let mut flow_inits = FlowAtLocation::new(do_dataflow(
178 MaybeInitializedPlaces::new(tcx, body, &mdpe),
179 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
182 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
183 let borrow_set = Rc::new(BorrowSet::build(
184 tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
186 // If we are in non-lexical mode, compute the non-lexical lifetimes.
187 let (regioncx, polonius_output, opt_closure_req) = nll::compute_regions(
202 // The various `flow_*` structures can be large. We drop `flow_inits` here
203 // so it doesn't overlap with the others below. This reduces peak memory
204 // usage significantly on some benchmarks.
207 let regioncx = Rc::new(regioncx);
209 let flow_borrows = FlowAtLocation::new(do_dataflow(
215 Borrows::new(tcx, body, param_env, regioncx.clone(), &borrow_set),
216 |rs, i| DebugFormatted::new(&rs.location(i)),
218 let flow_uninits = FlowAtLocation::new(do_dataflow(
224 MaybeUninitializedPlaces::new(tcx, body, &mdpe),
225 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
227 let flow_ever_inits = FlowAtLocation::new(do_dataflow(
233 EverInitializedPlaces::new(tcx, body, &mdpe),
234 |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
237 let movable_generator = match tcx.hir().get(id) {
238 Node::Expr(&hir::Expr {
239 node: hir::ExprKind::Closure(.., Some(hir::GeneratorMovability::Static)),
245 let dominators = body.dominators();
247 let mut mbcx = MirBorrowckCtxt {
252 move_data: &mdpe.move_data,
255 locals_are_invalidated_at_exit,
256 access_place_error_reported: Default::default(),
257 reservation_error_reported: Default::default(),
258 reservation_warnings: Default::default(),
259 move_error_reported: BTreeMap::new(),
260 uninitialized_error_reported: Default::default(),
262 disable_error_downgrading: false,
263 nonlexical_regioncx: regioncx,
264 used_mut: Default::default(),
265 used_mut_upvars: SmallVec::new(),
271 let mut state = Flows::new(
278 if let Some(errors) = move_errors {
279 mbcx.report_move_errors(errors);
281 mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
283 // Convert any reservation warnings into lints.
284 let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
285 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
286 let mut initial_diag =
287 mbcx.report_conflicting_borrow(location, (&place, span), bk, &borrow);
289 let lint_root = if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
290 let scope = mbcx.body.source_info(location).scope;
296 // Span and message don't matter; we overwrite them below anyway
297 let mut diag = mbcx.infcx.tcx.struct_span_lint_hir(
298 MUTABLE_BORROW_RESERVATION_CONFLICT, lint_root, DUMMY_SP, "");
300 diag.message = initial_diag.styled_message().clone();
301 diag.span = initial_diag.span.clone();
303 initial_diag.cancel();
304 diag.buffer(&mut mbcx.errors_buffer);
307 // For each non-user used mutable variable, check if it's been assigned from
308 // a user-declared local. If so, then put that local into the used_mut set.
309 // Note that this set is expected to be small - only upvars from closures
310 // would have a chance of erroneously adding non-user-defined mutable vars
312 let temporary_used_locals: FxHashSet<Local> = mbcx.used_mut.iter()
313 .filter(|&local| mbcx.body.local_decls[*local].is_user_variable.is_none())
316 // For the remaining unused locals that are marked as mutable, we avoid linting any that
317 // were never initialized. These locals may have been removed as unreachable code; or will be
318 // linted as unused variables.
319 let unused_mut_locals = mbcx.body.mut_vars_iter()
320 .filter(|local| !mbcx.used_mut.contains(local))
322 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
324 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
325 let used_mut = mbcx.used_mut;
326 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
327 if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
328 let local_decl = &mbcx.body.local_decls[local];
330 // Skip implicit `self` argument for closures
331 if local.index() == 1 && tcx.is_closure(mbcx.mir_def_id) {
335 // Skip over locals that begin with an underscore or have no name
336 match local_decl.name {
337 Some(name) => if name.as_str().starts_with("_") {
343 let span = local_decl.source_info.span;
344 if span.desugaring_kind().is_some() {
345 // If the `mut` arises as part of a desugaring, we should ignore it.
349 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
350 tcx.struct_span_lint_hir(
352 vsi[local_decl.source_info.scope].lint_root,
354 "variable does not need to be mutable",
356 .span_suggestion_short(
360 Applicability::MachineApplicable,
366 // Buffer any move errors that we collected and de-duplicated.
367 for (_, (_, diag)) in mbcx.move_error_reported {
368 diag.buffer(&mut mbcx.errors_buffer);
371 if !mbcx.errors_buffer.is_empty() {
372 mbcx.errors_buffer.sort_by_key(|diag| diag.span.primary_span());
374 if !mbcx.disable_error_downgrading && tcx.migrate_borrowck() {
375 // When borrowck=migrate, check if AST-borrowck would
376 // error on the given code.
378 // rust-lang/rust#55492, rust-lang/rust#58776 check the base def id
379 // for errors. AST borrowck is responsible for aggregating
380 // `signalled_any_error` from all of the nested closures here.
381 let base_def_id = tcx.closure_base_def_id(def_id);
383 match tcx.borrowck(base_def_id).signalled_any_error {
384 SignalledError::NoErrorsSeen => {
385 // if AST-borrowck signalled no errors, then
386 // downgrade all the buffered MIR-borrowck errors
389 for err in mbcx.errors_buffer.iter_mut() {
390 downgrade_if_error(err);
393 SignalledError::SawSomeError => {
394 // if AST-borrowck signalled a (cancelled) error,
395 // then we will just emit the buffered
396 // MIR-borrowck errors as normal.
401 for diag in mbcx.errors_buffer.drain(..) {
402 DiagnosticBuilder::new_diagnostic(mbcx.infcx.tcx.sess.diagnostic(), diag).emit();
406 let result = BorrowCheckResult {
407 closure_requirements: opt_closure_req,
408 used_mut_upvars: mbcx.used_mut_upvars,
411 debug!("do_mir_borrowck: result = {:#?}", result);
416 fn downgrade_if_error(diag: &mut Diagnostic) {
418 diag.level = Level::Warning;
420 "this error has been downgraded to a warning for backwards \
421 compatibility with previous releases",
423 "this represents potential undefined behavior in your code and \
424 this warning will become a hard error in the future",
426 "for more information, try `rustc --explain E0729`"
431 crate struct MirBorrowckCtxt<'cx, 'tcx> {
432 crate infcx: &'cx InferCtxt<'cx, 'tcx>,
433 body: &'cx Body<'tcx>,
435 param_env: ty::ParamEnv<'tcx>,
436 move_data: &'cx MoveData<'tcx>,
438 /// Map from MIR `Location` to `LocationIndex`; created
439 /// when MIR borrowck begins.
440 location_table: &'cx LocationTable,
442 movable_generator: bool,
443 /// This keeps track of whether local variables are free-ed when the function
444 /// exits even without a `StorageDead`, which appears to be the case for
447 /// I'm not sure this is the right approach - @eddyb could you try and
449 locals_are_invalidated_at_exit: bool,
450 /// This field keeps track of when borrow errors are reported in the access_place function
451 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
452 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
453 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
455 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
456 /// This field keeps track of when borrow conflict errors are reported
457 /// for reservations, so that we don't report seemingly duplicate
458 /// errors for corresponding activations.
460 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
461 // but it is currently inconvenient to track down the `BorrowIndex`
462 // at the time we detect and report a reservation error.
463 reservation_error_reported: FxHashSet<Place<'tcx>>,
464 /// Migration warnings to be reported for #56254. We delay reporting these
465 /// so that we can suppress the warning if there's a corresponding error
466 /// for the activation of the borrow.
467 reservation_warnings: FxHashMap<
469 (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)
471 /// This field keeps track of move errors that are to be reported for given move indicies.
473 /// There are situations where many errors can be reported for a single move out (see #53807)
474 /// and we want only the best of those errors.
476 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
477 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
478 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
479 /// all move errors have been reported, any diagnostics in this map are added to the buffer
482 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
483 /// when errors in the map are being re-added to the error buffer so that errors with the
484 /// same primary span come out in a consistent order.
485 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'cx, 'tcx>, DiagnosticBuilder<'cx>)>,
486 /// This field keeps track of errors reported in the checking of uninitialized variables,
487 /// so that we don't report seemingly duplicate errors.
488 uninitialized_error_reported: FxHashSet<PlaceRef<'cx, 'tcx>>,
489 /// Errors to be reported buffer
490 errors_buffer: Vec<Diagnostic>,
491 /// If there are no errors reported by the HIR borrow checker, we downgrade
492 /// all NLL errors to warnings. Setting this flag disables downgrading.
493 disable_error_downgrading: bool,
494 /// This field keeps track of all the local variables that are declared mut and are mutated.
495 /// Used for the warning issued by an unused mutable local variable.
496 used_mut: FxHashSet<Local>,
497 /// If the function we're checking is a closure, then we'll need to report back the list of
498 /// mutable upvars that have been used. This field keeps track of them.
499 used_mut_upvars: SmallVec<[Field; 8]>,
500 /// Non-lexical region inference context, if NLL is enabled. This
501 /// contains the results from region inference and lets us e.g.
502 /// find out which CFG points are contained in each borrow region.
503 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
505 /// The set of borrows extracted from the MIR
506 borrow_set: Rc<BorrowSet<'tcx>>,
508 /// Dominators for MIR
509 dominators: Dominators<BasicBlock>,
511 /// Information about upvars not necessarily preserved in types or MIR
516 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
517 // 2. loans made in overlapping scopes do not conflict
518 // 3. assignments do not affect things loaned out as immutable
519 // 4. moves do not affect things loaned out in any way
520 impl<'cx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
521 type FlowState = Flows<'cx, 'tcx>;
523 fn body(&self) -> &'cx Body<'tcx> {
527 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
528 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
531 fn visit_statement_entry(
534 stmt: &'cx Statement<'tcx>,
535 flow_state: &Self::FlowState,
538 "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
539 location, stmt, flow_state
541 let span = stmt.source_info.span;
543 self.check_activations(location, span, flow_state);
546 StatementKind::Assign(ref lhs, ref rhs) => {
561 StatementKind::FakeRead(_, ref place) => {
562 // Read for match doesn't access any memory and is used to
563 // assert that a place is safe and live. So we don't have to
564 // do any checks here.
566 // FIXME: Remove check that the place is initialized. This is
567 // needed for now because matches don't have never patterns yet.
568 // So this is the only place we prevent
572 self.check_if_path_or_subpath_is_moved(
574 InitializationRequiringAction::Use,
575 (place.as_ref(), span),
579 StatementKind::SetDiscriminant {
591 StatementKind::InlineAsm(ref asm) => {
592 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
594 // FIXME(eddyb) indirect inline asm outputs should
595 // be encoded through MIR place derefs instead.
599 (Deep, Read(ReadKind::Copy)),
600 LocalMutationIsAllowed::No,
603 self.check_if_path_or_subpath_is_moved(
605 InitializationRequiringAction::Use,
606 (output.as_ref(), o.span),
613 if o.is_rw { Deep } else { Shallow(None) },
614 if o.is_rw { WriteAndRead } else { JustWrite },
619 for (_, input) in asm.inputs.iter() {
620 self.consume_operand(location, (input, span), flow_state);
624 | StatementKind::AscribeUserType(..)
625 | StatementKind::Retag { .. }
626 | StatementKind::StorageLive(..) => {
627 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
630 StatementKind::StorageDead(local) => {
633 (&Place::from(local), span),
634 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
635 LocalMutationIsAllowed::Yes,
642 fn visit_terminator_entry(
645 term: &'cx Terminator<'tcx>,
646 flow_state: &Self::FlowState,
650 "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
651 location, term, flow_state
653 let span = term.source_info.span;
655 self.check_activations(location, span, flow_state);
658 TerminatorKind::SwitchInt {
664 self.consume_operand(loc, (discr, span), flow_state);
666 TerminatorKind::Drop {
667 location: ref drop_place,
671 let gcx = self.infcx.tcx.global_tcx();
673 // Compute the type with accurate region information.
674 let drop_place_ty = drop_place.ty(self.body, self.infcx.tcx);
676 // Erase the regions.
677 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
679 // "Lift" into the gcx -- once regions are erased, this type should be in the
680 // global arenas; this "lift" operation basically just asserts that is true, but
681 // that is useful later.
682 gcx.lift_to_global(&drop_place_ty).unwrap();
684 debug!("visit_terminator_drop \
685 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
686 loc, term, drop_place, drop_place_ty, span);
691 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
692 LocalMutationIsAllowed::Yes,
696 TerminatorKind::DropAndReplace {
697 location: ref drop_place,
698 value: ref new_value,
709 self.consume_operand(
715 TerminatorKind::Call {
722 self.consume_operand(loc, (func, span), flow_state);
724 self.consume_operand(
730 if let Some((ref dest, _ /*bb*/)) = *destination {
740 TerminatorKind::Assert {
747 self.consume_operand(loc, (cond, span), flow_state);
748 use rustc::mir::interpret::PanicInfo;
749 if let PanicInfo::BoundsCheck { ref len, ref index } = *msg {
750 self.consume_operand(loc, (len, span), flow_state);
751 self.consume_operand(loc, (index, span), flow_state);
755 TerminatorKind::Yield {
760 self.consume_operand(loc, (value, span), flow_state);
762 if self.movable_generator {
763 // Look for any active borrows to locals
764 let borrow_set = self.borrow_set.clone();
765 flow_state.with_outgoing_borrows(|borrows| {
767 let borrow = &borrow_set[i];
768 self.check_for_local_borrow(borrow, span);
774 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
775 // Returning from the function implicitly kills storage for all locals and statics.
776 // Often, the storage will already have been killed by an explicit
777 // StorageDead, but we don't always emit those (notably on unwind paths),
778 // so this "extra check" serves as a kind of backup.
779 let borrow_set = self.borrow_set.clone();
780 flow_state.with_outgoing_borrows(|borrows| {
782 let borrow = &borrow_set[i];
783 self.check_for_invalidation_at_exit(loc, borrow, span);
787 TerminatorKind::Goto { target: _ }
788 | TerminatorKind::Abort
789 | TerminatorKind::Unreachable
790 | TerminatorKind::FalseEdges {
794 | TerminatorKind::FalseUnwind {
798 // no data used, thus irrelevant to borrowck
804 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
810 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
811 use self::AccessDepth::{Deep, Shallow};
813 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
814 enum ArtificialField {
819 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
821 /// From the RFC: "A *shallow* access means that the immediate
822 /// fields reached at P are accessed, but references or pointers
823 /// found within are not dereferenced. Right now, the only access
824 /// that is shallow is an assignment like `x = ...;`, which would
825 /// be a *shallow write* of `x`."
826 Shallow(Option<ArtificialField>),
828 /// From the RFC: "A *deep* access means that all data reachable
829 /// through the given place may be invalidated or accesses by
833 /// Access is Deep only when there is a Drop implementation that
834 /// can reach the data behind the reference.
838 /// Kind of access to a value: read or write
839 /// (For informational purposes only)
840 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
842 /// From the RFC: "A *read* means that the existing data may be
843 /// read, but will not be changed."
846 /// From the RFC: "A *write* means that the data may be mutated to
847 /// new values or otherwise invalidated (for example, it could be
848 /// de-initialized, as in a move operation).
851 /// For two-phase borrows, we distinguish a reservation (which is treated
852 /// like a Read) from an activation (which is treated like a write), and
853 /// each of those is furthermore distinguished from Reads/Writes above.
854 Reservation(WriteKind),
855 Activation(WriteKind, BorrowIndex),
858 /// Kind of read access to a value
859 /// (For informational purposes only)
860 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
866 /// Kind of write access to a value
867 /// (For informational purposes only)
868 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
871 MutableBorrow(BorrowKind),
876 /// When checking permissions for a place access, this flag is used to indicate that an immutable
877 /// local place can be mutated.
879 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
880 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
881 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
882 // `is_declared_mutable()`.
883 // - Take flow state into consideration in `is_assignable()` for local variables.
884 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
885 enum LocalMutationIsAllowed {
887 /// We want use of immutable upvars to cause a "write to immutable upvar"
888 /// error, not an "reassignment" error.
893 #[derive(Copy, Clone, Debug)]
894 enum InitializationRequiringAction {
903 struct RootPlace<'d, 'tcx> {
904 place_base: &'d PlaceBase<'tcx>,
905 place_projection: &'d Option<Box<Projection<'tcx>>>,
906 is_local_mutation_allowed: LocalMutationIsAllowed,
909 impl InitializationRequiringAction {
910 fn as_noun(self) -> &'static str {
912 InitializationRequiringAction::Update => "update",
913 InitializationRequiringAction::Borrow => "borrow",
914 InitializationRequiringAction::MatchOn => "use", // no good noun
915 InitializationRequiringAction::Use => "use",
916 InitializationRequiringAction::Assignment => "assign",
917 InitializationRequiringAction::PartialAssignment => "assign to part",
921 fn as_verb_in_past_tense(self) -> &'static str {
923 InitializationRequiringAction::Update => "updated",
924 InitializationRequiringAction::Borrow => "borrowed",
925 InitializationRequiringAction::MatchOn => "matched on",
926 InitializationRequiringAction::Use => "used",
927 InitializationRequiringAction::Assignment => "assigned",
928 InitializationRequiringAction::PartialAssignment => "partially assigned",
933 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
934 /// If there are no errors reported by the HIR borrow checker, we downgrade
935 /// all NLL errors to warnings. Calling this disables downgrading.
936 crate fn disable_error_downgrading(&mut self) {
937 self.disable_error_downgrading = true;
940 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
941 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
942 /// place is initialized and (b) it is not borrowed in some way that would prevent this
945 /// Returns `true` if an error is reported.
949 place_span: (&Place<'tcx>, Span),
950 kind: (AccessDepth, ReadOrWrite),
951 is_local_mutation_allowed: LocalMutationIsAllowed,
952 flow_state: &Flows<'cx, 'tcx>,
956 if let Activation(_, borrow_index) = rw {
957 if self.reservation_error_reported.contains(&place_span.0) {
959 "skipping access_place for activation of invalid reservation \
960 place: {:?} borrow_index: {:?}",
961 place_span.0, borrow_index
967 // Check is_empty() first because it's the common case, and doing that
968 // way we avoid the clone() call.
969 if !self.access_place_error_reported.is_empty() &&
971 .access_place_error_reported
972 .contains(&(place_span.0.clone(), place_span.1))
975 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
981 let mutability_error =
982 self.check_access_permissions(
985 is_local_mutation_allowed,
990 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
992 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
993 // Suppress this warning when there's an error being emited for the
994 // same borrow: fixing the error is likely to fix the warning.
995 self.reservation_warnings.remove(&borrow_idx);
998 if conflict_error || mutability_error {
1000 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
1004 self.access_place_error_reported
1005 .insert((place_span.0.clone(), place_span.1));
1009 fn check_access_for_conflict(
1012 place_span: (&Place<'tcx>, Span),
1015 flow_state: &Flows<'cx, 'tcx>,
1018 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1019 location, place_span, sd, rw,
1022 let mut error_reported = false;
1023 let tcx = self.infcx.tcx;
1024 let body = self.body;
1025 let param_env = self.param_env;
1026 let location_table = self.location_table.start_index(location);
1027 let borrow_set = self.borrow_set.clone();
1028 each_borrow_involving_path(
1036 flow_state.borrows_in_scope(location_table),
1037 |this, borrow_index, borrow| match (rw, borrow.kind) {
1038 // Obviously an activation is compatible with its own
1039 // reservation (or even prior activating uses of same
1040 // borrow); so don't check if they interfere.
1042 // NOTE: *reservations* do conflict with themselves;
1043 // thus aren't injecting unsoundenss w/ this check.)
1044 (Activation(_, activating), _) if activating == borrow_index => {
1046 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1047 skipping {:?} b/c activation of same borrow_index",
1051 (borrow_index, borrow),
1056 (Read(_), BorrowKind::Shared)
1057 | (Read(_), BorrowKind::Shallow)
1058 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
1059 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
1063 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1064 // Handled by initialization checks.
1068 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
1069 // Reading from mere reservations of mutable-borrows is OK.
1070 if !is_active(&this.dominators, borrow, location) {
1071 assert!(allow_two_phase_borrow(borrow.kind));
1072 return Control::Continue;
1075 error_reported = true;
1078 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1079 .buffer(&mut this.errors_buffer);
1081 ReadKind::Borrow(bk) => {
1082 this.report_conflicting_borrow(location, place_span, bk, borrow)
1083 .buffer(&mut this.errors_buffer);
1089 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
1090 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared) if {
1091 tcx.migrate_borrowck() && this.borrow_set.location_map.contains_key(&location)
1093 let bi = this.borrow_set.location_map[&location];
1095 "recording invalid reservation of place: {:?} with \
1096 borrow index {:?} as warning",
1100 // rust-lang/rust#56254 - This was previously permitted on
1101 // the 2018 edition so we emit it as a warning. We buffer
1102 // these sepately so that we only emit a warning if borrow
1103 // checking was otherwise successful.
1104 this.reservation_warnings.insert(
1106 (place_span.0.clone(), place_span.1, location, bk, borrow.clone()),
1109 // Don't suppress actual errors.
1113 (Reservation(kind), _)
1114 | (Activation(kind, _), _)
1115 | (Write(kind), _) => {
1117 Reservation(..) => {
1119 "recording invalid reservation of \
1123 this.reservation_error_reported.insert(place_span.0.clone());
1125 Activation(_, activating) => {
1127 "observing check_place for activation of \
1128 borrow_index: {:?}",
1132 Read(..) | Write(..) => {}
1135 error_reported = true;
1137 WriteKind::MutableBorrow(bk) => {
1138 this.report_conflicting_borrow(location, place_span, bk, borrow)
1139 .buffer(&mut this.errors_buffer);
1141 WriteKind::StorageDeadOrDrop => {
1142 this.report_borrowed_value_does_not_live_long_enough(
1148 WriteKind::Mutate => {
1149 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1151 WriteKind::Move => {
1152 this.report_move_out_while_borrowed(location, place_span, borrow)
1166 place_span: (&'cx Place<'tcx>, Span),
1169 flow_state: &Flows<'cx, 'tcx>,
1171 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1173 MutateMode::WriteAndRead => {
1174 self.check_if_path_or_subpath_is_moved(
1176 InitializationRequiringAction::Update,
1177 (place_span.0.as_ref(), place_span.1),
1181 MutateMode::JustWrite => {
1182 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1186 // Special case: you can assign a immutable local variable
1187 // (e.g., `x = ...`) so long as it has never been initialized
1188 // before (at this point in the flow).
1190 base: PlaceBase::Local(local),
1193 if let Mutability::Not = self.body.local_decls[*local].mutability {
1194 // check for reassignments to immutable local variables
1195 self.check_if_reassignment_to_immutable_state(
1205 // Otherwise, use the normal access permission rules.
1209 (kind, Write(WriteKind::Mutate)),
1210 LocalMutationIsAllowed::No,
1218 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1219 flow_state: &Flows<'cx, 'tcx>,
1222 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1223 let access_kind = match bk {
1224 BorrowKind::Shallow => {
1225 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1227 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1228 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1229 let wk = WriteKind::MutableBorrow(bk);
1230 if allow_two_phase_borrow(bk) {
1231 (Deep, Reservation(wk))
1242 LocalMutationIsAllowed::No,
1246 let action = if bk == BorrowKind::Shallow {
1247 InitializationRequiringAction::MatchOn
1249 InitializationRequiringAction::Borrow
1252 self.check_if_path_or_subpath_is_moved(
1255 (place.as_ref(), span),
1260 Rvalue::Use(ref operand)
1261 | Rvalue::Repeat(ref operand, _)
1262 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1263 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1264 self.consume_operand(location, (operand, span), flow_state)
1267 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1268 let af = match *rvalue {
1269 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1270 Rvalue::Discriminant(..) => None,
1271 _ => unreachable!(),
1276 (Shallow(af), Read(ReadKind::Copy)),
1277 LocalMutationIsAllowed::No,
1280 self.check_if_path_or_subpath_is_moved(
1282 InitializationRequiringAction::Use,
1283 (place.as_ref(), span),
1288 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1289 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1290 self.consume_operand(location, (operand1, span), flow_state);
1291 self.consume_operand(location, (operand2, span), flow_state);
1294 Rvalue::NullaryOp(_op, _ty) => {
1295 // nullary ops take no dynamic input; no borrowck effect.
1297 // FIXME: is above actually true? Do we want to track
1298 // the fact that uninitialized data can be created via
1302 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1303 // We need to report back the list of mutable upvars that were
1304 // moved into the closure and subsequently used by the closure,
1305 // in order to populate our used_mut set.
1306 match **aggregate_kind {
1307 AggregateKind::Closure(def_id, _)
1308 | AggregateKind::Generator(def_id, _, _) => {
1309 let BorrowCheckResult {
1311 } = self.infcx.tcx.mir_borrowck(def_id);
1312 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1313 for field in used_mut_upvars {
1314 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1317 AggregateKind::Adt(..)
1318 | AggregateKind::Array(..)
1319 | AggregateKind::Tuple { .. } => (),
1322 for operand in operands {
1323 self.consume_operand(location, (operand, span), flow_state);
1329 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1330 let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1331 if place.projection.is_some() {
1332 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1333 this.used_mut_upvars.push(field);
1335 } else if let PlaceBase::Local(local) = place.base {
1336 this.used_mut.insert(local);
1340 // This relies on the current way that by-value
1341 // captures of a closure are copied/moved directly
1342 // when generating MIR.
1344 Operand::Move(Place {
1345 base: PlaceBase::Local(local),
1348 Operand::Copy(Place {
1349 base: PlaceBase::Local(local),
1351 }) if self.body.local_decls[local].is_user_variable.is_none() => {
1352 if self.body.local_decls[local].ty.is_mutable_ptr() {
1353 // The variable will be marked as mutable by the borrow.
1356 // This is an edge case where we have a `move` closure
1357 // inside a non-move closure, and the inner closure
1358 // contains a mutation:
1361 // || { move || { i += 1; }; };
1363 // In this case our usual strategy of assuming that the
1364 // variable will be captured by mutable reference is
1365 // wrong, since `i` can be copied into the inner
1366 // closure from a shared reference.
1368 // As such we have to search for the local that this
1369 // capture comes from and mark it as being used as mut.
1371 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1372 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1373 &self.move_data.inits[init_index]
1375 bug!("temporary should be initialized exactly once")
1378 let loc = match init.location {
1379 InitLocation::Statement(stmt) => stmt,
1380 _ => bug!("temporary initialized in arguments"),
1383 let bbd = &self.body[loc.block];
1384 let stmt = &bbd.statements[loc.statement_index];
1385 debug!("temporary assigned in: stmt={:?}", stmt);
1387 if let StatementKind::Assign(_, box Rvalue::Ref(_, _, ref source)) = stmt.kind {
1388 propagate_closure_used_mut_place(self, source);
1390 bug!("closures should only capture user variables \
1391 or references to user variables");
1394 Operand::Move(ref place)
1395 | Operand::Copy(ref place) => {
1396 propagate_closure_used_mut_place(self, place);
1398 Operand::Constant(..) => {}
1405 (operand, span): (&'cx Operand<'tcx>, Span),
1406 flow_state: &Flows<'cx, 'tcx>,
1409 Operand::Copy(ref place) => {
1410 // copy of place: check if this is "copy of frozen path"
1411 // (FIXME: see check_loans.rs)
1415 (Deep, Read(ReadKind::Copy)),
1416 LocalMutationIsAllowed::No,
1420 // Finally, check if path was already moved.
1421 self.check_if_path_or_subpath_is_moved(
1423 InitializationRequiringAction::Use,
1424 (place.as_ref(), span),
1428 Operand::Move(ref place) => {
1429 // move of place: check if this is move of already borrowed path
1433 (Deep, Write(WriteKind::Move)),
1434 LocalMutationIsAllowed::Yes,
1438 // Finally, check if path was already moved.
1439 self.check_if_path_or_subpath_is_moved(
1441 InitializationRequiringAction::Use,
1442 (place.as_ref(), span),
1446 Operand::Constant(_) => {}
1450 /// Checks whether a borrow of this place is invalidated when the function
1452 fn check_for_invalidation_at_exit(
1455 borrow: &BorrowData<'tcx>,
1458 debug!("check_for_invalidation_at_exit({:?})", borrow);
1459 let place = &borrow.borrowed_place;
1460 let root_place = self.prefixes(place.as_ref(), PrefixSet::All).last().unwrap();
1462 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1463 // we just know that all locals are dropped at function exit (otherwise
1464 // we'll have a memory leak) and assume that all statics have a destructor.
1466 // FIXME: allow thread-locals to borrow other thread locals?
1468 assert!(root_place.projection.is_none());
1469 let (might_be_alive, will_be_dropped) = match root_place.base {
1470 PlaceBase::Static(box Static {
1471 kind: StaticKind::Promoted(..),
1476 PlaceBase::Static(box Static {
1477 kind: StaticKind::Static,
1480 // Thread-locals might be dropped after the function exits, but
1481 // "true" statics will never be.
1482 (true, self.is_place_thread_local(root_place))
1484 PlaceBase::Local(_) => {
1485 // Locals are always dropped at function exit, and if they
1486 // have a destructor it would've been called already.
1487 (false, self.locals_are_invalidated_at_exit)
1491 if !will_be_dropped {
1493 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1499 let sd = if might_be_alive { Deep } else { Shallow(None) };
1501 if places_conflict::borrow_conflicts_with_place(
1509 places_conflict::PlaceConflictBias::Overlap,
1511 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1512 // FIXME: should be talking about the region lifetime instead
1513 // of just a span here.
1514 let span = self.infcx.tcx.sess.source_map().end_point(span);
1515 self.report_borrowed_value_does_not_live_long_enough(
1524 /// Reports an error if this is a borrow of local data.
1525 /// This is called for all Yield statements on movable generators
1526 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1527 debug!("check_for_local_borrow({:?})", borrow);
1529 if borrow_of_local_data(&borrow.borrowed_place) {
1530 let err = self.cannot_borrow_across_generator_yield(
1531 self.retrieve_borrow_spans(borrow).var_or_use(),
1535 err.buffer(&mut self.errors_buffer);
1539 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1540 // Two-phase borrow support: For each activation that is newly
1541 // generated at this statement, check if it interferes with
1543 let borrow_set = self.borrow_set.clone();
1544 for &borrow_index in borrow_set.activations_at_location(location) {
1545 let borrow = &borrow_set[borrow_index];
1547 // only mutable borrows should be 2-phase
1548 assert!(match borrow.kind {
1549 BorrowKind::Shared | BorrowKind::Shallow => false,
1550 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1555 (&borrow.borrowed_place, span),
1558 Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1560 LocalMutationIsAllowed::No,
1563 // We do not need to call `check_if_path_or_subpath_is_moved`
1564 // again, as we already called it when we made the
1565 // initial reservation.
1570 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
1571 fn check_if_reassignment_to_immutable_state(
1575 place_span: (&Place<'tcx>, Span),
1576 flow_state: &Flows<'cx, 'tcx>,
1578 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1580 // Check if any of the initializiations of `local` have happened yet:
1581 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1582 // And, if so, report an error.
1583 let init = &self.move_data.inits[init_index];
1584 let span = init.span(&self.body);
1585 self.report_illegal_reassignment(
1586 location, place_span, span, place_span.0
1591 fn check_if_full_path_is_moved(
1594 desired_action: InitializationRequiringAction,
1595 place_span: (PlaceRef<'cx, 'tcx>, Span),
1596 flow_state: &Flows<'cx, 'tcx>,
1598 let maybe_uninits = &flow_state.uninits;
1602 // 1. Move of `a.b.c`, use of `a.b.c`
1603 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1604 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1605 // partial initialization support, one might have `a.x`
1606 // initialized but not `a.b`.
1610 // 4. Move of `a.b.c`, use of `a.b.d`
1611 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1612 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1613 // must have been initialized for the use to be sound.
1614 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1616 // The dataflow tracks shallow prefixes distinctly (that is,
1617 // field-accesses on P distinctly from P itself), in order to
1618 // track substructure initialization separately from the whole
1621 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1622 // which we have a MovePath is `a.b`, then that means that the
1623 // initialization state of `a.b` is all we need to inspect to
1624 // know if `a.b.c` is valid (and from that we infer that the
1625 // dereference and `.d` access is also valid, since we assume
1626 // `a.b.c` is assigned a reference to a initialized and
1627 // well-formed record structure.)
1629 // Therefore, if we seek out the *closest* prefix for which we
1630 // have a MovePath, that should capture the initialization
1631 // state for the place scenario.
1633 // This code covers scenarios 1, 2, and 3.
1635 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1636 match self.move_path_closest_to(place_span.0) {
1637 Ok((prefix, mpi)) => {
1638 if maybe_uninits.contains(mpi) {
1639 self.report_use_of_moved_or_uninitialized(
1642 (prefix, place_span.0, place_span.1),
1645 return; // don't bother finding other problems.
1648 Err(NoMovePathFound::ReachedStatic) => {
1649 // Okay: we do not build MoveData for static variables
1650 } // Only query longest prefix with a MovePath, not further
1651 // ancestors; dataflow recurs on children when parents
1652 // move (to support partial (re)inits).
1654 // (I.e., querying parents breaks scenario 7; but may want
1655 // to do such a query based on partial-init feature-gate.)
1659 fn check_if_path_or_subpath_is_moved(
1662 desired_action: InitializationRequiringAction,
1663 place_span: (PlaceRef<'cx, 'tcx>, Span),
1664 flow_state: &Flows<'cx, 'tcx>,
1666 let maybe_uninits = &flow_state.uninits;
1670 // 1. Move of `a.b.c`, use of `a` or `a.b`
1671 // partial initialization support, one might have `a.x`
1672 // initialized but not `a.b`.
1673 // 2. All bad scenarios from `check_if_full_path_is_moved`
1677 // 3. Move of `a.b.c`, use of `a.b.d`
1678 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1679 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1680 // must have been initialized for the use to be sound.
1681 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1683 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1685 // A move of any shallow suffix of `place` also interferes
1686 // with an attempt to use `place`. This is scenario 3 above.
1688 // (Distinct from handling of scenarios 1+2+4 above because
1689 // `place` does not interfere with suffixes of its prefixes,
1690 // e.g., `a.b.c` does not interfere with `a.b.d`)
1692 // This code covers scenario 1.
1694 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1695 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1696 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1697 self.report_use_of_moved_or_uninitialized(
1700 (place_span.0, place_span.0, place_span.1),
1703 return; // don't bother finding other problems.
1708 /// Currently MoveData does not store entries for all places in
1709 /// the input MIR. For example it will currently filter out
1710 /// places that are Copy; thus we do not track places of shared
1711 /// reference type. This routine will walk up a place along its
1712 /// prefixes, searching for a foundational place that *is*
1713 /// tracked in the MoveData.
1715 /// An Err result includes a tag indicated why the search failed.
1716 /// Currently this can only occur if the place is built off of a
1717 /// static variable, as we do not track those in the MoveData.
1718 fn move_path_closest_to(
1720 place: PlaceRef<'cx, 'tcx>,
1721 ) -> Result<(PlaceRef<'cx, 'tcx>, MovePathIndex), NoMovePathFound> {
1722 let mut last_prefix = place.base;
1724 for prefix in self.prefixes(place, PrefixSet::All) {
1725 if let Some(mpi) = self.move_path_for_place(prefix) {
1726 return Ok((prefix, mpi));
1729 last_prefix = prefix.base;
1733 PlaceBase::Local(_) => panic!("should have move path for every Local"),
1734 PlaceBase::Static(_) => Err(NoMovePathFound::ReachedStatic),
1738 fn move_path_for_place(&mut self, place: PlaceRef<'cx, 'tcx>) -> Option<MovePathIndex> {
1739 // If returns None, then there is no move path corresponding
1740 // to a direct owner of `place` (which means there is nothing
1741 // that borrowck tracks for its analysis).
1743 match self.move_data.rev_lookup.find(place) {
1744 LookupResult::Parent(_) => None,
1745 LookupResult::Exact(mpi) => Some(mpi),
1749 fn check_if_assigned_path_is_moved(
1752 (place, span): (&'cx Place<'tcx>, Span),
1753 flow_state: &Flows<'cx, 'tcx>,
1755 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1756 // recur down place; dispatch to external checks when necessary
1757 let mut place_projection = &place.projection;
1759 // None case => assigning to `x` does not require `x` be initialized.
1760 while let Some(proj) = place_projection {
1761 let Projection { ref base, ref elem } = **proj;
1763 ProjectionElem::Index(_/*operand*/) |
1764 ProjectionElem::ConstantIndex { .. } |
1765 // assigning to P[i] requires P to be valid.
1766 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1767 // assigning to (P->variant) is okay if assigning to `P` is okay
1769 // FIXME: is this true even if P is a adt with a dtor?
1772 // assigning to (*P) requires P to be initialized
1773 ProjectionElem::Deref => {
1774 self.check_if_full_path_is_moved(
1775 location, InitializationRequiringAction::Use,
1779 }, span), flow_state);
1780 // (base initialized; no need to
1785 ProjectionElem::Subslice { .. } => {
1786 panic!("we don't allow assignments to subslices, location: {:?}",
1790 ProjectionElem::Field(..) => {
1791 // if type of `P` has a dtor, then
1792 // assigning to `P.f` requires `P` itself
1793 // be already initialized
1794 let tcx = self.infcx.tcx;
1795 let base_ty = Place::ty_from(&place.base, base, self.body, tcx).ty;
1797 ty::Adt(def, _) if def.has_dtor(tcx) => {
1798 self.check_if_path_or_subpath_is_moved(
1799 location, InitializationRequiringAction::Assignment,
1803 }, span), flow_state);
1805 // (base initialized; no need to
1810 // Once `let s; s.x = V; read(s.x);`,
1811 // is allowed, remove this match arm.
1812 ty::Adt(..) | ty::Tuple(..) => {
1813 check_parent_of_field(self, location, PlaceRef {
1816 }, span, flow_state);
1818 if let PlaceBase::Local(local) = place.base {
1819 // rust-lang/rust#21232,
1820 // #54499, #54986: during
1821 // period where we reject
1822 // partial initialization, do
1823 // not complain about
1824 // unnecessary `mut` on an
1825 // attempt to do a partial
1827 self.used_mut.insert(local);
1836 place_projection = base;
1839 fn check_parent_of_field<'cx, 'tcx>(
1840 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1842 base: PlaceRef<'cx, 'tcx>,
1844 flow_state: &Flows<'cx, 'tcx>,
1846 // rust-lang/rust#21232: Until Rust allows reads from the
1847 // initialized parts of partially initialized structs, we
1848 // will, starting with the 2018 edition, reject attempts
1849 // to write to structs that are not fully initialized.
1851 // In other words, *until* we allow this:
1853 // 1. `let mut s; s.x = Val; read(s.x);`
1855 // we will for now disallow this:
1857 // 2. `let mut s; s.x = Val;`
1861 // 3. `let mut s = ...; drop(s); s.x=Val;`
1863 // This does not use check_if_path_or_subpath_is_moved,
1864 // because we want to *allow* reinitializations of fields:
1865 // e.g., want to allow
1867 // `let mut s = ...; drop(s.x); s.x=Val;`
1869 // This does not use check_if_full_path_is_moved on
1870 // `base`, because that would report an error about the
1871 // `base` as a whole, but in this scenario we *really*
1872 // want to report an error about the actual thing that was
1873 // moved, which may be some prefix of `base`.
1875 // Shallow so that we'll stop at any dereference; we'll
1876 // report errors about issues with such bases elsewhere.
1877 let maybe_uninits = &flow_state.uninits;
1879 // Find the shortest uninitialized prefix you can reach
1880 // without going over a Deref.
1881 let mut shortest_uninit_seen = None;
1882 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1883 let mpi = match this.move_path_for_place(prefix) {
1884 Some(mpi) => mpi, None => continue,
1887 if maybe_uninits.contains(mpi) {
1888 debug!("check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1889 shortest_uninit_seen, Some((prefix, mpi)));
1890 shortest_uninit_seen = Some((prefix, mpi));
1892 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1896 if let Some((prefix, mpi)) = shortest_uninit_seen {
1897 // Check for a reassignment into a uninitialized field of a union (for example,
1898 // after a move out). In this case, do not report a error here. There is an
1899 // exception, if this is the first assignment into the union (that is, there is
1900 // no move out from an earlier location) then this is an attempt at initialization
1901 // of the union - we should error in that case.
1902 let tcx = this.infcx.tcx;
1903 if let ty::Adt(def, _) =
1904 Place::ty_from(base.base, base.projection, this.body, tcx).ty.sty
1907 if this.move_data.path_map[mpi].iter().any(|moi| {
1908 this.move_data.moves[*moi].source.is_predecessor_of(
1909 location, this.body,
1917 this.report_use_of_moved_or_uninitialized(
1919 InitializationRequiringAction::PartialAssignment,
1920 (prefix, base, span),
1927 /// Checks the permissions for the given place and read or write kind
1929 /// Returns `true` if an error is reported.
1930 fn check_access_permissions(
1932 (place, span): (&Place<'tcx>, Span),
1934 is_local_mutation_allowed: LocalMutationIsAllowed,
1935 flow_state: &Flows<'cx, 'tcx>,
1939 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1940 place, kind, is_local_mutation_allowed
1946 // rust-lang/rust#21232, #54986: during period where we reject
1947 // partial initialization, do not complain about mutability
1948 // errors except for actual mutation (as opposed to an attempt
1949 // to do a partial initialization).
1950 let previously_initialized = if let PlaceBase::Local(local) = place.base {
1951 self.is_local_ever_initialized(local, flow_state).is_some()
1957 Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1958 | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
1959 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1960 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. })) => {
1961 let is_local_mutation_allowed = match borrow_kind {
1962 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1963 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1964 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1966 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1968 self.add_used_mut(root_place, flow_state);
1972 error_access = AccessKind::MutableBorrow;
1973 the_place_err = place_err;
1977 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1978 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1980 self.add_used_mut(root_place, flow_state);
1984 error_access = AccessKind::Mutate;
1985 the_place_err = place_err;
1990 Reservation(wk @ WriteKind::Move)
1991 | Write(wk @ WriteKind::Move)
1992 | Reservation(wk @ WriteKind::StorageDeadOrDrop)
1993 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1994 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow))
1995 | Write(wk @ WriteKind::StorageDeadOrDrop)
1996 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1997 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
1998 if let (Err(place_err), true) = (
1999 self.is_mutable(place.as_ref(), is_local_mutation_allowed),
2000 self.errors_buffer.is_empty()
2002 if self.infcx.tcx.migrate_borrowck() {
2003 // rust-lang/rust#46908: In pure NLL mode this
2004 // code path should be unreachable (and thus
2005 // we signal an ICE in the else branch
2006 // here). But we can legitimately get here
2007 // under borrowck=migrate mode, so instead of
2008 // ICE'ing we instead report a legitimate
2009 // error (which will then be downgraded to a
2010 // warning by the migrate machinery).
2011 error_access = match wk {
2012 WriteKind::MutableBorrow(_) => AccessKind::MutableBorrow,
2013 WriteKind::Move => AccessKind::Move,
2014 WriteKind::StorageDeadOrDrop |
2015 WriteKind::Mutate => AccessKind::Mutate,
2017 self.report_mutability_error(
2027 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2036 // permission checks are done at Reservation point.
2039 Read(ReadKind::Borrow(BorrowKind::Unique))
2040 | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
2041 | Read(ReadKind::Borrow(BorrowKind::Shared))
2042 | Read(ReadKind::Borrow(BorrowKind::Shallow))
2043 | Read(ReadKind::Copy) => {
2044 // Access authorized
2049 // at this point, we have set up the error reporting state.
2050 return if previously_initialized {
2051 self.report_mutability_error(
2064 fn is_local_ever_initialized(
2067 flow_state: &Flows<'cx, 'tcx>,
2068 ) -> Option<InitIndex> {
2069 let mpi = self.move_data.rev_lookup.find_local(local);
2070 let ii = &self.move_data.init_path_map[mpi];
2072 if flow_state.ever_inits.contains(index) {
2079 /// Adds the place into the used mutable variables set
2080 fn add_used_mut<'d>(&mut self, root_place: RootPlace<'d, 'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2083 place_base: PlaceBase::Local(local),
2084 place_projection: None,
2085 is_local_mutation_allowed,
2087 // If the local may have been initialized, and it is now currently being
2088 // mutated, then it is justified to be annotated with the `mut`
2089 // keyword, since the mutation may be a possible reassignment.
2090 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes &&
2091 self.is_local_ever_initialized(*local, flow_state).is_some()
2093 self.used_mut.insert(*local);
2098 place_projection: _,
2099 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2103 place_projection: place_projection @ Some(_),
2104 is_local_mutation_allowed: _,
2106 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2108 projection: &place_projection,
2110 self.used_mut_upvars.push(field);
2114 place_base: PlaceBase::Static(..),
2115 place_projection: None,
2116 is_local_mutation_allowed: _,
2121 /// Whether this value can be written or borrowed mutably.
2122 /// Returns the root place if the place passed in is a projection.
2125 place: PlaceRef<'d, 'tcx>,
2126 is_local_mutation_allowed: LocalMutationIsAllowed,
2127 ) -> Result<RootPlace<'d, 'tcx>, PlaceRef<'d, 'tcx>> {
2130 base: PlaceBase::Local(local),
2133 let local = &self.body.local_decls[*local];
2134 match local.mutability {
2135 Mutability::Not => match is_local_mutation_allowed {
2136 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2137 place_base: place.base,
2138 place_projection: place.projection,
2139 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2141 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2142 place_base: place.base,
2143 place_projection: place.projection,
2144 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2146 LocalMutationIsAllowed::No => Err(place),
2148 Mutability::Mut => Ok(RootPlace {
2149 place_base: place.base,
2150 place_projection: place.projection,
2151 is_local_mutation_allowed,
2155 // The rules for promotion are made by `qualify_consts`, there wouldn't even be a
2156 // `Place::Promoted` if the promotion weren't 100% legal. So we just forward this
2158 base: PlaceBase::Static(box Static {
2159 kind: StaticKind::Promoted(..),
2165 place_base: place.base,
2166 place_projection: place.projection,
2167 is_local_mutation_allowed,
2170 base: PlaceBase::Static(box Static {
2171 kind: StaticKind::Static,
2177 if !self.infcx.tcx.is_mutable_static(*def_id) {
2181 place_base: place.base,
2182 place_projection: place.projection,
2183 is_local_mutation_allowed,
2189 projection: Some(proj),
2192 ProjectionElem::Deref => {
2194 Place::ty_from(place.base, &proj.base, self.body, self.infcx.tcx).ty;
2196 // Check the kind of deref to decide
2198 ty::Ref(_, _, mutbl) => {
2200 // Shared borrowed data is never mutable
2201 hir::MutImmutable => Err(place),
2202 // Mutably borrowed data is mutable, but only if we have a
2203 // unique path to the `&mut`
2204 hir::MutMutable => {
2205 let mode = match self.is_upvar_field_projection(place) {
2207 if self.upvars[field.index()].by_ref =>
2209 is_local_mutation_allowed
2211 _ => LocalMutationIsAllowed::Yes,
2214 self.is_mutable(PlaceRef {
2216 projection: &proj.base,
2221 ty::RawPtr(tnm) => {
2223 // `*const` raw pointers are not mutable
2224 hir::MutImmutable => Err(place),
2225 // `*mut` raw pointers are always mutable, regardless of
2226 // context. The users have to check by themselves.
2227 hir::MutMutable => {
2229 place_base: place.base,
2230 place_projection: place.projection,
2231 is_local_mutation_allowed,
2236 // `Box<T>` owns its content, so mutable if its location is mutable
2237 _ if base_ty.is_box() => {
2238 self.is_mutable(PlaceRef {
2240 projection: &proj.base,
2241 }, is_local_mutation_allowed)
2243 // Deref should only be for reference, pointers or boxes
2244 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2247 // All other projections are owned by their base path, so mutable if
2248 // base path is mutable
2249 ProjectionElem::Field(..)
2250 | ProjectionElem::Index(..)
2251 | ProjectionElem::ConstantIndex { .. }
2252 | ProjectionElem::Subslice { .. }
2253 | ProjectionElem::Downcast(..) => {
2254 let upvar_field_projection = self.is_upvar_field_projection(place);
2255 if let Some(field) = upvar_field_projection {
2256 let upvar = &self.upvars[field.index()];
2258 "upvar.mutability={:?} local_mutation_is_allowed={:?} \
2260 upvar, is_local_mutation_allowed, place
2262 match (upvar.mutability, is_local_mutation_allowed) {
2263 (Mutability::Not, LocalMutationIsAllowed::No)
2264 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2267 (Mutability::Not, LocalMutationIsAllowed::Yes)
2268 | (Mutability::Mut, _) => {
2269 // Subtle: this is an upvar
2270 // reference, so it looks like
2271 // `self.foo` -- we want to double
2272 // check that the location `*self`
2273 // is mutable (i.e., this is not a
2274 // `Fn` closure). But if that
2275 // check succeeds, we want to
2276 // *blame* the mutability on
2277 // `place` (that is,
2278 // `self.foo`). This is used to
2279 // propagate the info about
2280 // whether mutability declarations
2281 // are used outwards, so that we register
2282 // the outer variable as mutable. Otherwise a
2283 // test like this fails to record the `mut`
2287 // fn foo<F: FnOnce()>(_f: F) { }
2289 // let var = Vec::new();
2295 let _ = self.is_mutable(PlaceRef {
2297 projection: &proj.base,
2298 }, is_local_mutation_allowed)?;
2300 place_base: place.base,
2301 place_projection: place.projection,
2302 is_local_mutation_allowed,
2307 self.is_mutable(PlaceRef {
2309 projection: &proj.base,
2310 }, is_local_mutation_allowed)
2318 /// If `place` is a field projection, and the field is being projected from a closure type,
2319 /// then returns the index of the field being projected. Note that this closure will always
2320 /// be `self` in the current MIR, because that is the only time we directly access the fields
2321 /// of a closure type.
2322 pub fn is_upvar_field_projection(&self, place_ref: PlaceRef<'cx, 'tcx>) -> Option<Field> {
2323 let mut place_projection = place_ref.projection;
2324 let mut by_ref = false;
2326 if let Some(box Projection {
2328 elem: ProjectionElem::Deref,
2329 }) = place_projection {
2330 place_projection = &base;
2334 match place_projection {
2335 Some(box Projection {
2337 elem: ProjectionElem::Field(field, _ty),
2339 let tcx = self.infcx.tcx;
2340 let base_ty = Place::ty_from(place_ref.base, &base, self.body, tcx).ty;
2342 if (base_ty.is_closure() || base_ty.is_generator()) &&
2343 (!by_ref || self.upvars[field.index()].by_ref) {
2355 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2356 enum NoMovePathFound {
2360 /// The degree of overlap between 2 places for borrow-checking.
2362 /// The places might partially overlap - in this case, we give
2363 /// up and say that they might conflict. This occurs when
2364 /// different fields of a union are borrowed. For example,
2365 /// if `u` is a union, we have no way of telling how disjoint
2366 /// `u.a.x` and `a.b.y` are.
2368 /// The places have the same type, and are either completely disjoint
2369 /// or equal - i.e., they can't "partially" overlap as can occur with
2370 /// unions. This is the "base case" on which we recur for extensions
2373 /// The places are disjoint, so we know all extensions of them
2374 /// will also be disjoint.