1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
3 use crate::borrow_check::nll::region_infer::RegionInferenceContext;
4 use rustc::hir::{self, HirId};
6 use rustc::hir::def_id::DefId;
7 use rustc::infer::InferCtxt;
8 use rustc::lint::builtin::UNUSED_MUT;
9 use rustc::lint::builtin::{MUTABLE_BORROW_RESERVATION_CONFLICT};
10 use rustc::middle::borrowck::SignalledError;
11 use rustc::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
13 ClearCrossCrate, Local, Location, Body, Mutability, Operand, Place, PlaceBase, Static,
17 use rustc::mir::{Field, Projection, ProjectionElem, Rvalue, Statement, StatementKind};
18 use rustc::mir::{Terminator, TerminatorKind};
19 use rustc::ty::query::Providers;
20 use rustc::ty::{self, TyCtxt};
22 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, Level};
23 use rustc_data_structures::bit_set::BitSet;
24 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
25 use rustc_data_structures::graph::dominators::Dominators;
26 use smallvec::SmallVec;
28 use std::collections::BTreeMap;
32 use syntax::ast::Name;
33 use syntax_pos::{Span, DUMMY_SP};
35 use crate::dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex};
36 use crate::dataflow::move_paths::{HasMoveData, InitLocation, LookupResult, MoveData, MoveError};
37 use crate::dataflow::Borrows;
38 use crate::dataflow::DataflowResultsConsumer;
39 use crate::dataflow::FlowAtLocation;
40 use crate::dataflow::MoveDataParamEnv;
41 use crate::dataflow::{do_dataflow, DebugFormatted};
42 use crate::dataflow::EverInitializedPlaces;
43 use crate::dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
44 use crate::util::borrowck_errors::{BorrowckErrors, Origin};
46 use self::borrow_set::{BorrowData, BorrowSet};
47 use self::flows::Flows;
48 use self::location::LocationTable;
49 use self::prefixes::PrefixSet;
50 use self::MutateMode::{JustWrite, WriteAndRead};
51 use self::mutability_errors::AccessKind;
53 use self::path_utils::*;
61 mod mutability_errors;
64 crate mod places_conflict;
70 // FIXME(eddyb) perhaps move this somewhere more centrally.
77 /// If true, the capture is behind a reference.
80 mutability: Mutability,
83 pub fn provide(providers: &mut Providers<'_>) {
84 *providers = Providers {
90 fn mir_borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> BorrowCheckResult<'tcx> {
91 let input_mir = tcx.mir_validated(def_id);
92 debug!("run query mir_borrowck: {}", tcx.def_path_str(def_id));
94 // We are not borrow checking the automatically generated struct/variant constructors
95 // because we want to accept structs such as this (taken from the `linked-hash-map`
98 // struct Qey<Q: ?Sized>(Q);
100 // MIR of this struct constructor looks something like this:
102 // fn Qey(_1: Q) -> Qey<Q>{
103 // let mut _0: Qey<Q>; // return place
106 // (_0.0: Q) = move _1; // bb0[0]: scope 0 at src/main.rs:1:1: 1:26
107 // return; // bb0[1]: scope 0 at src/main.rs:1:1: 1:26
111 // The problem here is that `(_0.0: Q) = move _1;` is valid only if `Q` is
112 // of statically known size, which is not known to be true because of the
113 // `Q: ?Sized` constraint. However, it is true because the constructor can be
114 // called only when `Q` is of statically known size.
115 if tcx.is_constructor(def_id) {
116 return BorrowCheckResult {
117 closure_requirements: None,
118 used_mut_upvars: SmallVec::new(),
122 let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
123 let input_mir: &Body<'_> = &input_mir.borrow();
124 do_mir_borrowck(&infcx, input_mir, def_id)
126 debug!("mir_borrowck done");
131 fn do_mir_borrowck<'a, 'gcx, 'tcx>(
132 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
133 input_mir: &Body<'gcx>,
135 ) -> BorrowCheckResult<'gcx> {
136 debug!("do_mir_borrowck(def_id = {:?})", def_id);
139 let attributes = tcx.get_attrs(def_id);
140 let param_env = tcx.param_env(def_id);
143 .as_local_hir_id(def_id)
144 .expect("do_mir_borrowck: non-local DefId");
146 // Gather the upvars of a closure, if any.
147 let tables = tcx.typeck_tables_of(def_id);
148 let upvars: Vec<_> = tables
154 let var_hir_id = upvar_id.var_path.hir_id;
155 let var_node_id = tcx.hir().hir_to_node_id(var_hir_id);
156 let capture = tables.upvar_capture(*upvar_id);
157 let by_ref = match capture {
158 ty::UpvarCapture::ByValue => false,
159 ty::UpvarCapture::ByRef(..) => true,
161 let mut upvar = Upvar {
162 name: tcx.hir().name(var_node_id),
165 mutability: Mutability::Not,
167 let bm = *tables.pat_binding_modes().get(var_hir_id)
168 .expect("missing binding mode");
169 if bm == ty::BindByValue(hir::MutMutable) {
170 upvar.mutability = Mutability::Mut;
176 // Replace all regions with fresh inference variables. This
177 // requires first making our own copy of the MIR. This copy will
178 // be modified (in place) to contain non-lexical lifetimes. It
179 // will have a lifetime tied to the inference context.
180 let mut mir: Body<'tcx> = input_mir.clone();
181 let free_regions = nll::replace_regions_in_mir(infcx, def_id, param_env, &mut mir);
182 let mir = &mir; // no further changes
183 let location_table = &LocationTable::new(mir);
185 let mut errors_buffer = Vec::new();
186 let (move_data, move_errors): (MoveData<'tcx>, Option<Vec<(Place<'tcx>, MoveError<'tcx>)>>) =
187 match MoveData::gather_moves(mir, tcx) {
188 Ok(move_data) => (move_data, None),
189 Err((move_data, move_errors)) => (move_data, Some(move_errors)),
192 let mdpe = MoveDataParamEnv {
193 move_data: move_data,
194 param_env: param_env,
197 let dead_unwinds = BitSet::new_empty(mir.basic_blocks().len());
198 let mut flow_inits = FlowAtLocation::new(do_dataflow(
204 MaybeInitializedPlaces::new(tcx, mir, &mdpe),
205 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
208 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind_by_hir_id(id).is_fn_or_closure();
209 let borrow_set = Rc::new(BorrowSet::build(
210 tcx, mir, locals_are_invalidated_at_exit, &mdpe.move_data));
212 // If we are in non-lexical mode, compute the non-lexical lifetimes.
213 let (regioncx, polonius_output, opt_closure_req) = nll::compute_regions(
227 // The various `flow_*` structures can be large. We drop `flow_inits` here
228 // so it doesn't overlap with the others below. This reduces peak memory
229 // usage significantly on some benchmarks.
232 let regioncx = Rc::new(regioncx);
234 let flow_borrows = FlowAtLocation::new(do_dataflow(
240 Borrows::new(tcx, mir, regioncx.clone(), &borrow_set),
241 |rs, i| DebugFormatted::new(&rs.location(i)),
243 let flow_uninits = FlowAtLocation::new(do_dataflow(
249 MaybeUninitializedPlaces::new(tcx, mir, &mdpe),
250 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
252 let flow_ever_inits = FlowAtLocation::new(do_dataflow(
258 EverInitializedPlaces::new(tcx, mir, &mdpe),
259 |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
262 let movable_generator = match tcx.hir().get_by_hir_id(id) {
263 Node::Expr(&hir::Expr {
264 node: hir::ExprKind::Closure(.., Some(hir::GeneratorMovability::Static)),
270 let dominators = mir.dominators();
272 let mut mbcx = MirBorrowckCtxt {
276 move_data: &mdpe.move_data,
279 locals_are_invalidated_at_exit,
280 access_place_error_reported: Default::default(),
281 reservation_error_reported: Default::default(),
282 reservation_warnings: Default::default(),
283 move_error_reported: BTreeMap::new(),
284 uninitialized_error_reported: Default::default(),
286 nonlexical_regioncx: regioncx,
287 used_mut: Default::default(),
288 used_mut_upvars: SmallVec::new(),
294 let mut state = Flows::new(
301 if let Some(errors) = move_errors {
302 mbcx.report_move_errors(errors);
304 mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
306 // Convert any reservation warnings into lints.
307 let reservation_warnings = mem::replace(&mut mbcx.reservation_warnings, Default::default());
308 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
309 let mut initial_diag =
310 mbcx.report_conflicting_borrow(location, (&place, span), bk, &borrow);
312 let lint_root = if let ClearCrossCrate::Set(ref vsi) = mbcx.mir.source_scope_local_data {
313 let scope = mbcx.mir.source_info(location).scope;
319 // Span and message don't matter; we overwrite them below anyway
320 let mut diag = mbcx.infcx.tcx.struct_span_lint_hir(
321 MUTABLE_BORROW_RESERVATION_CONFLICT, lint_root, DUMMY_SP, "");
323 diag.message = initial_diag.styled_message().clone();
324 diag.span = initial_diag.span.clone();
326 initial_diag.cancel();
327 diag.buffer(&mut mbcx.errors_buffer);
330 // For each non-user used mutable variable, check if it's been assigned from
331 // a user-declared local. If so, then put that local into the used_mut set.
332 // Note that this set is expected to be small - only upvars from closures
333 // would have a chance of erroneously adding non-user-defined mutable vars
335 let temporary_used_locals: FxHashSet<Local> = mbcx.used_mut.iter()
336 .filter(|&local| mbcx.mir.local_decls[*local].is_user_variable.is_none())
339 // For the remaining unused locals that are marked as mutable, we avoid linting any that
340 // were never initialized. These locals may have been removed as unreachable code; or will be
341 // linted as unused variables.
342 let unused_mut_locals = mbcx.mir.mut_vars_iter()
343 .filter(|local| !mbcx.used_mut.contains(local))
345 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
347 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
348 let used_mut = mbcx.used_mut;
349 for local in mbcx.mir.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
350 if let ClearCrossCrate::Set(ref vsi) = mbcx.mir.source_scope_local_data {
351 let local_decl = &mbcx.mir.local_decls[local];
353 // Skip implicit `self` argument for closures
354 if local.index() == 1 && tcx.is_closure(mbcx.mir_def_id) {
358 // Skip over locals that begin with an underscore or have no name
359 match local_decl.name {
360 Some(name) => if name.as_str().starts_with("_") {
366 let span = local_decl.source_info.span;
367 if span.compiler_desugaring_kind().is_some() {
368 // If the `mut` arises as part of a desugaring, we should ignore it.
372 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
373 tcx.struct_span_lint_hir(
375 vsi[local_decl.source_info.scope].lint_root,
377 "variable does not need to be mutable",
379 .span_suggestion_short(
383 Applicability::MachineApplicable,
389 // Buffer any move errors that we collected and de-duplicated.
390 for (_, (_, diag)) in mbcx.move_error_reported {
391 diag.buffer(&mut mbcx.errors_buffer);
394 if !mbcx.errors_buffer.is_empty() {
395 mbcx.errors_buffer.sort_by_key(|diag| diag.span.primary_span());
397 if tcx.migrate_borrowck() {
398 // When borrowck=migrate, check if AST-borrowck would
399 // error on the given code.
401 // rust-lang/rust#55492, rust-lang/rust#58776 check the base def id
402 // for errors. AST borrowck is responsible for aggregating
403 // `signalled_any_error` from all of the nested closures here.
404 let base_def_id = tcx.closure_base_def_id(def_id);
406 match tcx.borrowck(base_def_id).signalled_any_error {
407 SignalledError::NoErrorsSeen => {
408 // if AST-borrowck signalled no errors, then
409 // downgrade all the buffered MIR-borrowck errors
412 for err in mbcx.errors_buffer.iter_mut() {
413 downgrade_if_error(err);
416 SignalledError::SawSomeError => {
417 // if AST-borrowck signalled a (cancelled) error,
418 // then we will just emit the buffered
419 // MIR-borrowck errors as normal.
424 for diag in mbcx.errors_buffer.drain(..) {
425 DiagnosticBuilder::new_diagnostic(mbcx.infcx.tcx.sess.diagnostic(), diag).emit();
429 let result = BorrowCheckResult {
430 closure_requirements: opt_closure_req,
431 used_mut_upvars: mbcx.used_mut_upvars,
434 debug!("do_mir_borrowck: result = {:#?}", result);
439 fn downgrade_if_error(diag: &mut Diagnostic) {
441 diag.level = Level::Warning;
443 "this error has been downgraded to a warning for backwards \
444 compatibility with previous releases",
446 "this represents potential undefined behavior in your code and \
447 this warning will become a hard error in the future",
449 "for more information, try `rustc --explain E0729`"
454 pub struct MirBorrowckCtxt<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
455 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
456 mir: &'cx Body<'tcx>,
458 move_data: &'cx MoveData<'tcx>,
460 /// Map from MIR `Location` to `LocationIndex`; created
461 /// when MIR borrowck begins.
462 location_table: &'cx LocationTable,
464 movable_generator: bool,
465 /// This keeps track of whether local variables are free-ed when the function
466 /// exits even without a `StorageDead`, which appears to be the case for
469 /// I'm not sure this is the right approach - @eddyb could you try and
471 locals_are_invalidated_at_exit: bool,
472 /// This field keeps track of when borrow errors are reported in the access_place function
473 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
474 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
475 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
477 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
478 /// This field keeps track of when borrow conflict errors are reported
479 /// for reservations, so that we don't report seemingly duplicate
480 /// errors for corresponding activations.
482 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
483 // but it is currently inconvenient to track down the `BorrowIndex`
484 // at the time we detect and report a reservation error.
485 reservation_error_reported: FxHashSet<Place<'tcx>>,
486 /// Migration warnings to be reported for #56254. We delay reporting these
487 /// so that we can suppress the warning if there's a corresponding error
488 /// for the activation of the borrow.
489 reservation_warnings: FxHashMap<
491 (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)
493 /// This field keeps track of move errors that are to be reported for given move indicies.
495 /// There are situations where many errors can be reported for a single move out (see #53807)
496 /// and we want only the best of those errors.
498 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
499 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
500 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
501 /// all move errors have been reported, any diagnostics in this map are added to the buffer
504 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
505 /// when errors in the map are being re-added to the error buffer so that errors with the
506 /// same primary span come out in a consistent order.
507 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (Place<'tcx>, DiagnosticBuilder<'cx>)>,
508 /// This field keeps track of errors reported in the checking of uninitialized variables,
509 /// so that we don't report seemingly duplicate errors.
510 uninitialized_error_reported: FxHashSet<Place<'tcx>>,
511 /// Errors to be reported buffer
512 errors_buffer: Vec<Diagnostic>,
513 /// This field keeps track of all the local variables that are declared mut and are mutated.
514 /// Used for the warning issued by an unused mutable local variable.
515 used_mut: FxHashSet<Local>,
516 /// If the function we're checking is a closure, then we'll need to report back the list of
517 /// mutable upvars that have been used. This field keeps track of them.
518 used_mut_upvars: SmallVec<[Field; 8]>,
519 /// Non-lexical region inference context, if NLL is enabled. This
520 /// contains the results from region inference and lets us e.g.
521 /// find out which CFG points are contained in each borrow region.
522 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
524 /// The set of borrows extracted from the MIR
525 borrow_set: Rc<BorrowSet<'tcx>>,
527 /// Dominators for MIR
528 dominators: Dominators<BasicBlock>,
530 /// Information about upvars not necessarily preserved in types or MIR
535 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
536 // 2. loans made in overlapping scopes do not conflict
537 // 3. assignments do not affect things loaned out as immutable
538 // 4. moves do not affect things loaned out in any way
539 impl<'cx, 'gcx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
540 type FlowState = Flows<'cx, 'gcx, 'tcx>;
542 fn mir(&self) -> &'cx Body<'tcx> {
546 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
547 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
550 fn visit_statement_entry(
553 stmt: &Statement<'tcx>,
554 flow_state: &Self::FlowState,
557 "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
558 location, stmt, flow_state
560 let span = stmt.source_info.span;
562 self.check_activations(location, span, flow_state);
565 StatementKind::Assign(ref lhs, ref rhs) => {
580 StatementKind::FakeRead(_, ref place) => {
581 // Read for match doesn't access any memory and is used to
582 // assert that a place is safe and live. So we don't have to
583 // do any checks here.
585 // FIXME: Remove check that the place is initialized. This is
586 // needed for now because matches don't have never patterns yet.
587 // So this is the only place we prevent
591 self.check_if_path_or_subpath_is_moved(
593 InitializationRequiringAction::Use,
598 StatementKind::SetDiscriminant {
610 StatementKind::InlineAsm(ref asm) => {
611 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
613 // FIXME(eddyb) indirect inline asm outputs should
614 // be encoded through MIR place derefs instead.
618 (Deep, Read(ReadKind::Copy)),
619 LocalMutationIsAllowed::No,
622 self.check_if_path_or_subpath_is_moved(
624 InitializationRequiringAction::Use,
632 if o.is_rw { Deep } else { Shallow(None) },
633 if o.is_rw { WriteAndRead } else { JustWrite },
638 for (_, input) in asm.inputs.iter() {
639 self.consume_operand(location, (input, span), flow_state);
643 | StatementKind::AscribeUserType(..)
644 | StatementKind::Retag { .. }
645 | StatementKind::StorageLive(..) => {
646 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
649 StatementKind::StorageDead(local) => {
652 (&Place::Base(PlaceBase::Local(local)), span),
653 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
654 LocalMutationIsAllowed::Yes,
661 fn visit_terminator_entry(
664 term: &Terminator<'tcx>,
665 flow_state: &Self::FlowState,
669 "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
670 location, term, flow_state
672 let span = term.source_info.span;
674 self.check_activations(location, span, flow_state);
677 TerminatorKind::SwitchInt {
683 self.consume_operand(loc, (discr, span), flow_state);
685 TerminatorKind::Drop {
686 location: ref drop_place,
690 let gcx = self.infcx.tcx.global_tcx();
692 // Compute the type with accurate region information.
693 let drop_place_ty = drop_place.ty(self.mir, self.infcx.tcx);
695 // Erase the regions.
696 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
698 // "Lift" into the gcx -- once regions are erased, this type should be in the
699 // global arenas; this "lift" operation basically just asserts that is true, but
700 // that is useful later.
701 let drop_place_ty = gcx.lift(&drop_place_ty).unwrap();
703 debug!("visit_terminator_drop \
704 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
705 loc, term, drop_place, drop_place_ty, span);
710 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
711 LocalMutationIsAllowed::Yes,
715 TerminatorKind::DropAndReplace {
716 location: ref drop_place,
717 value: ref new_value,
728 self.consume_operand(
734 TerminatorKind::Call {
741 self.consume_operand(loc, (func, span), flow_state);
743 self.consume_operand(
749 if let Some((ref dest, _ /*bb*/)) = *destination {
759 TerminatorKind::Assert {
766 self.consume_operand(loc, (cond, span), flow_state);
767 use rustc::mir::interpret::InterpError::BoundsCheck;
768 if let BoundsCheck { ref len, ref index } = *msg {
769 self.consume_operand(loc, (len, span), flow_state);
770 self.consume_operand(loc, (index, span), flow_state);
774 TerminatorKind::Yield {
779 self.consume_operand(loc, (value, span), flow_state);
781 if self.movable_generator {
782 // Look for any active borrows to locals
783 let borrow_set = self.borrow_set.clone();
784 flow_state.with_outgoing_borrows(|borrows| {
786 let borrow = &borrow_set[i];
787 self.check_for_local_borrow(borrow, span);
793 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
794 // Returning from the function implicitly kills storage for all locals and statics.
795 // Often, the storage will already have been killed by an explicit
796 // StorageDead, but we don't always emit those (notably on unwind paths),
797 // so this "extra check" serves as a kind of backup.
798 let borrow_set = self.borrow_set.clone();
799 flow_state.with_outgoing_borrows(|borrows| {
801 let borrow = &borrow_set[i];
802 self.check_for_invalidation_at_exit(loc, borrow, span);
806 TerminatorKind::Goto { target: _ }
807 | TerminatorKind::Abort
808 | TerminatorKind::Unreachable
809 | TerminatorKind::FalseEdges {
811 imaginary_targets: _,
813 | TerminatorKind::FalseUnwind {
817 // no data used, thus irrelevant to borrowck
823 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
829 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
830 use self::AccessDepth::{Deep, Shallow};
832 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
833 enum ArtificialField {
838 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
840 /// From the RFC: "A *shallow* access means that the immediate
841 /// fields reached at P are accessed, but references or pointers
842 /// found within are not dereferenced. Right now, the only access
843 /// that is shallow is an assignment like `x = ...;`, which would
844 /// be a *shallow write* of `x`."
845 Shallow(Option<ArtificialField>),
847 /// From the RFC: "A *deep* access means that all data reachable
848 /// through the given place may be invalidated or accesses by
852 /// Access is Deep only when there is a Drop implementation that
853 /// can reach the data behind the reference.
857 /// Kind of access to a value: read or write
858 /// (For informational purposes only)
859 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
861 /// From the RFC: "A *read* means that the existing data may be
862 /// read, but will not be changed."
865 /// From the RFC: "A *write* means that the data may be mutated to
866 /// new values or otherwise invalidated (for example, it could be
867 /// de-initialized, as in a move operation).
870 /// For two-phase borrows, we distinguish a reservation (which is treated
871 /// like a Read) from an activation (which is treated like a write), and
872 /// each of those is furthermore distinguished from Reads/Writes above.
873 Reservation(WriteKind),
874 Activation(WriteKind, BorrowIndex),
877 /// Kind of read access to a value
878 /// (For informational purposes only)
879 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
885 /// Kind of write access to a value
886 /// (For informational purposes only)
887 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
890 MutableBorrow(BorrowKind),
895 /// When checking permissions for a place access, this flag is used to indicate that an immutable
896 /// local place can be mutated.
898 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
899 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
900 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
901 // `is_declared_mutable()`.
902 // - Take flow state into consideration in `is_assignable()` for local variables.
903 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
904 enum LocalMutationIsAllowed {
906 /// We want use of immutable upvars to cause a "write to immutable upvar"
907 /// error, not an "reassignment" error.
912 #[derive(Copy, Clone, Debug)]
913 enum InitializationRequiringAction {
922 struct RootPlace<'d, 'tcx: 'd> {
923 place: &'d Place<'tcx>,
924 is_local_mutation_allowed: LocalMutationIsAllowed,
927 impl InitializationRequiringAction {
928 fn as_noun(self) -> &'static str {
930 InitializationRequiringAction::Update => "update",
931 InitializationRequiringAction::Borrow => "borrow",
932 InitializationRequiringAction::MatchOn => "use", // no good noun
933 InitializationRequiringAction::Use => "use",
934 InitializationRequiringAction::Assignment => "assign",
935 InitializationRequiringAction::PartialAssignment => "assign to part",
939 fn as_verb_in_past_tense(self) -> &'static str {
941 InitializationRequiringAction::Update => "updated",
942 InitializationRequiringAction::Borrow => "borrowed",
943 InitializationRequiringAction::MatchOn => "matched on",
944 InitializationRequiringAction::Use => "used",
945 InitializationRequiringAction::Assignment => "assigned",
946 InitializationRequiringAction::PartialAssignment => "partially assigned",
951 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
952 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
953 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
954 /// place is initialized and (b) it is not borrowed in some way that would prevent this
957 /// Returns `true` if an error is reported.
961 place_span: (&Place<'tcx>, Span),
962 kind: (AccessDepth, ReadOrWrite),
963 is_local_mutation_allowed: LocalMutationIsAllowed,
964 flow_state: &Flows<'cx, 'gcx, 'tcx>,
968 if let Activation(_, borrow_index) = rw {
969 if self.reservation_error_reported.contains(&place_span.0) {
971 "skipping access_place for activation of invalid reservation \
972 place: {:?} borrow_index: {:?}",
973 place_span.0, borrow_index
979 // Check is_empty() first because it's the common case, and doing that
980 // way we avoid the clone() call.
981 if !self.access_place_error_reported.is_empty() &&
983 .access_place_error_reported
984 .contains(&(place_span.0.clone(), place_span.1))
987 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
993 let mutability_error =
994 self.check_access_permissions(
997 is_local_mutation_allowed,
1001 let conflict_error =
1002 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
1004 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
1005 // Suppress this warning when there's an error being emited for the
1006 // same borrow: fixing the error is likely to fix the warning.
1007 self.reservation_warnings.remove(&borrow_idx);
1010 if conflict_error || mutability_error {
1012 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
1016 self.access_place_error_reported
1017 .insert((place_span.0.clone(), place_span.1));
1021 fn check_access_for_conflict(
1024 place_span: (&Place<'tcx>, Span),
1027 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1030 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1031 location, place_span, sd, rw,
1034 let mut error_reported = false;
1035 let tcx = self.infcx.tcx;
1037 let location_table = self.location_table.start_index(location);
1038 let borrow_set = self.borrow_set.clone();
1039 each_borrow_involving_path(
1046 flow_state.borrows_in_scope(location_table),
1047 |this, borrow_index, borrow| match (rw, borrow.kind) {
1048 // Obviously an activation is compatible with its own
1049 // reservation (or even prior activating uses of same
1050 // borrow); so don't check if they interfere.
1052 // NOTE: *reservations* do conflict with themselves;
1053 // thus aren't injecting unsoundenss w/ this check.)
1054 (Activation(_, activating), _) if activating == borrow_index => {
1056 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1057 skipping {:?} b/c activation of same borrow_index",
1061 (borrow_index, borrow),
1066 (Read(_), BorrowKind::Shared)
1067 | (Read(_), BorrowKind::Shallow)
1068 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
1069 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
1073 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1074 // Handled by initialization checks.
1078 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
1079 // Reading from mere reservations of mutable-borrows is OK.
1080 if !is_active(&this.dominators, borrow, location) {
1081 assert!(allow_two_phase_borrow(borrow.kind));
1082 return Control::Continue;
1085 error_reported = true;
1088 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1089 .buffer(&mut this.errors_buffer);
1091 ReadKind::Borrow(bk) => {
1092 this.report_conflicting_borrow(location, place_span, bk, borrow)
1093 .buffer(&mut this.errors_buffer);
1099 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
1100 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared) if {
1101 tcx.migrate_borrowck()
1103 let bi = this.borrow_set.location_map[&location];
1105 "recording invalid reservation of place: {:?} with \
1106 borrow index {:?} as warning",
1110 // rust-lang/rust#56254 - This was previously permitted on
1111 // the 2018 edition so we emit it as a warning. We buffer
1112 // these sepately so that we only emit a warning if borrow
1113 // checking was otherwise successful.
1114 this.reservation_warnings.insert(
1116 (place_span.0.clone(), place_span.1, location, bk, borrow.clone()),
1119 // Don't suppress actual errors.
1123 (Reservation(kind), _)
1124 | (Activation(kind, _), _)
1125 | (Write(kind), _) => {
1127 Reservation(..) => {
1129 "recording invalid reservation of \
1133 this.reservation_error_reported.insert(place_span.0.clone());
1135 Activation(_, activating) => {
1137 "observing check_place for activation of \
1138 borrow_index: {:?}",
1142 Read(..) | Write(..) => {}
1145 error_reported = true;
1147 WriteKind::MutableBorrow(bk) => {
1148 this.report_conflicting_borrow(location, place_span, bk, borrow)
1149 .buffer(&mut this.errors_buffer);
1151 WriteKind::StorageDeadOrDrop => {
1152 this.report_borrowed_value_does_not_live_long_enough(
1158 WriteKind::Mutate => {
1159 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1161 WriteKind::Move => {
1162 this.report_move_out_while_borrowed(location, place_span, borrow)
1176 place_span: (&Place<'tcx>, Span),
1179 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1181 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1183 MutateMode::WriteAndRead => {
1184 self.check_if_path_or_subpath_is_moved(
1186 InitializationRequiringAction::Update,
1191 MutateMode::JustWrite => {
1192 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1196 // Special case: you can assign a immutable local variable
1197 // (e.g., `x = ...`) so long as it has never been initialized
1198 // before (at this point in the flow).
1199 if let &Place::Base(PlaceBase::Local(local)) = place_span.0 {
1200 if let Mutability::Not = self.mir.local_decls[local].mutability {
1201 // check for reassignments to immutable local variables
1202 self.check_if_reassignment_to_immutable_state(
1212 // Otherwise, use the normal access permission rules.
1216 (kind, Write(WriteKind::Mutate)),
1217 LocalMutationIsAllowed::No,
1225 (rvalue, span): (&Rvalue<'tcx>, Span),
1226 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1229 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1230 let access_kind = match bk {
1231 BorrowKind::Shallow => {
1232 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1234 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1235 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1236 let wk = WriteKind::MutableBorrow(bk);
1237 if allow_two_phase_borrow(bk) {
1238 (Deep, Reservation(wk))
1249 LocalMutationIsAllowed::No,
1253 let action = if bk == BorrowKind::Shallow {
1254 InitializationRequiringAction::MatchOn
1256 InitializationRequiringAction::Borrow
1259 self.check_if_path_or_subpath_is_moved(
1267 Rvalue::Use(ref operand)
1268 | Rvalue::Repeat(ref operand, _)
1269 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1270 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1271 self.consume_operand(location, (operand, span), flow_state)
1274 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1275 let af = match *rvalue {
1276 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1277 Rvalue::Discriminant(..) => None,
1278 _ => unreachable!(),
1283 (Shallow(af), Read(ReadKind::Copy)),
1284 LocalMutationIsAllowed::No,
1287 self.check_if_path_or_subpath_is_moved(
1289 InitializationRequiringAction::Use,
1295 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1296 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1297 self.consume_operand(location, (operand1, span), flow_state);
1298 self.consume_operand(location, (operand2, span), flow_state);
1301 Rvalue::NullaryOp(_op, _ty) => {
1302 // nullary ops take no dynamic input; no borrowck effect.
1304 // FIXME: is above actually true? Do we want to track
1305 // the fact that uninitialized data can be created via
1309 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1310 // We need to report back the list of mutable upvars that were
1311 // moved into the closure and subsequently used by the closure,
1312 // in order to populate our used_mut set.
1313 match **aggregate_kind {
1314 AggregateKind::Closure(def_id, _)
1315 | AggregateKind::Generator(def_id, _, _) => {
1316 let BorrowCheckResult {
1318 } = self.infcx.tcx.mir_borrowck(def_id);
1319 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1320 for field in used_mut_upvars {
1321 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1324 AggregateKind::Adt(..)
1325 | AggregateKind::Array(..)
1326 | AggregateKind::Tuple { .. } => (),
1329 for operand in operands {
1330 self.consume_operand(location, (operand, span), flow_state);
1336 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1337 let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1339 Place::Projection { .. } => {
1340 if let Some(field) = this.is_upvar_field_projection(place) {
1341 this.used_mut_upvars.push(field);
1344 Place::Base(PlaceBase::Local(local)) => {
1345 this.used_mut.insert(local);
1347 Place::Base(PlaceBase::Static(_)) => {}
1351 // This relies on the current way that by-value
1352 // captures of a closure are copied/moved directly
1353 // when generating MIR.
1355 Operand::Move(Place::Base(PlaceBase::Local(local)))
1356 | Operand::Copy(Place::Base(PlaceBase::Local(local)))
1357 if self.mir.local_decls[local].is_user_variable.is_none() =>
1359 if self.mir.local_decls[local].ty.is_mutable_pointer() {
1360 // The variable will be marked as mutable by the borrow.
1363 // This is an edge case where we have a `move` closure
1364 // inside a non-move closure, and the inner closure
1365 // contains a mutation:
1368 // || { move || { i += 1; }; };
1370 // In this case our usual strategy of assuming that the
1371 // variable will be captured by mutable reference is
1372 // wrong, since `i` can be copied into the inner
1373 // closure from a shared reference.
1375 // As such we have to search for the local that this
1376 // capture comes from and mark it as being used as mut.
1378 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1379 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1380 &self.move_data.inits[init_index]
1382 bug!("temporary should be initialized exactly once")
1385 let loc = match init.location {
1386 InitLocation::Statement(stmt) => stmt,
1387 _ => bug!("temporary initialized in arguments"),
1390 let bbd = &self.mir[loc.block];
1391 let stmt = &bbd.statements[loc.statement_index];
1392 debug!("temporary assigned in: stmt={:?}", stmt);
1394 if let StatementKind::Assign(_, box Rvalue::Ref(_, _, ref source)) = stmt.kind {
1395 propagate_closure_used_mut_place(self, source);
1397 bug!("closures should only capture user variables \
1398 or references to user variables");
1401 Operand::Move(ref place)
1402 | Operand::Copy(ref place) => {
1403 propagate_closure_used_mut_place(self, place);
1405 Operand::Constant(..) => {}
1412 (operand, span): (&Operand<'tcx>, Span),
1413 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1416 Operand::Copy(ref place) => {
1417 // copy of place: check if this is "copy of frozen path"
1418 // (FIXME: see check_loans.rs)
1422 (Deep, Read(ReadKind::Copy)),
1423 LocalMutationIsAllowed::No,
1427 // Finally, check if path was already moved.
1428 self.check_if_path_or_subpath_is_moved(
1430 InitializationRequiringAction::Use,
1435 Operand::Move(ref place) => {
1436 // move of place: check if this is move of already borrowed path
1440 (Deep, Write(WriteKind::Move)),
1441 LocalMutationIsAllowed::Yes,
1445 // Finally, check if path was already moved.
1446 self.check_if_path_or_subpath_is_moved(
1448 InitializationRequiringAction::Use,
1453 Operand::Constant(_) => {}
1457 /// Checks whether a borrow of this place is invalidated when the function
1459 fn check_for_invalidation_at_exit(
1462 borrow: &BorrowData<'tcx>,
1465 debug!("check_for_invalidation_at_exit({:?})", borrow);
1466 let place = &borrow.borrowed_place;
1467 let root_place = self.prefixes(place, PrefixSet::All).last().unwrap();
1469 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1470 // we just know that all locals are dropped at function exit (otherwise
1471 // we'll have a memory leak) and assume that all statics have a destructor.
1473 // FIXME: allow thread-locals to borrow other thread locals?
1474 let (might_be_alive, will_be_dropped) = match root_place {
1475 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Promoted(_), .. })) => {
1478 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(_), .. })) => {
1479 // Thread-locals might be dropped after the function exits, but
1480 // "true" statics will never be.
1481 (true, self.is_place_thread_local(&root_place))
1483 Place::Base(PlaceBase::Local(_)) => {
1484 // Locals are always dropped at function exit, and if they
1485 // have a destructor it would've been called already.
1486 (false, self.locals_are_invalidated_at_exit)
1488 Place::Projection(..) => {
1489 bug!("root of {:?} is a projection ({:?})?", place, root_place)
1493 if !will_be_dropped {
1495 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1501 let sd = if might_be_alive { Deep } else { Shallow(None) };
1503 if places_conflict::borrow_conflicts_with_place(
1510 places_conflict::PlaceConflictBias::Overlap,
1512 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1513 // FIXME: should be talking about the region lifetime instead
1514 // of just a span here.
1515 let span = self.infcx.tcx.sess.source_map().end_point(span);
1516 self.report_borrowed_value_does_not_live_long_enough(
1525 /// Reports an error if this is a borrow of local data.
1526 /// This is called for all Yield statements on movable generators
1527 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1528 debug!("check_for_local_borrow({:?})", borrow);
1530 if borrow_of_local_data(&borrow.borrowed_place) {
1531 let err = self.infcx.tcx
1532 .cannot_borrow_across_generator_yield(
1533 self.retrieve_borrow_spans(borrow).var_or_use(),
1538 err.buffer(&mut self.errors_buffer);
1542 fn check_activations(
1546 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1548 // Two-phase borrow support: For each activation that is newly
1549 // generated at this statement, check if it interferes with
1551 let borrow_set = self.borrow_set.clone();
1552 for &borrow_index in borrow_set.activations_at_location(location) {
1553 let borrow = &borrow_set[borrow_index];
1555 // only mutable borrows should be 2-phase
1556 assert!(match borrow.kind {
1557 BorrowKind::Shared | BorrowKind::Shallow => false,
1558 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1563 (&borrow.borrowed_place, span),
1566 Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1568 LocalMutationIsAllowed::No,
1571 // We do not need to call `check_if_path_or_subpath_is_moved`
1572 // again, as we already called it when we made the
1573 // initial reservation.
1578 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1579 fn check_if_reassignment_to_immutable_state(
1583 place_span: (&Place<'tcx>, Span),
1584 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1586 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1588 // Check if any of the initializiations of `local` have happened yet:
1589 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1590 // And, if so, report an error.
1591 let init = &self.move_data.inits[init_index];
1592 let span = init.span(&self.mir);
1593 self.report_illegal_reassignment(
1594 location, place_span, span, place_span.0
1599 fn check_if_full_path_is_moved(
1602 desired_action: InitializationRequiringAction,
1603 place_span: (&Place<'tcx>, Span),
1604 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1606 let maybe_uninits = &flow_state.uninits;
1610 // 1. Move of `a.b.c`, use of `a.b.c`
1611 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1612 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1613 // partial initialization support, one might have `a.x`
1614 // initialized but not `a.b`.
1618 // 4. Move of `a.b.c`, use of `a.b.d`
1619 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1620 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1621 // must have been initialized for the use to be sound.
1622 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1624 // The dataflow tracks shallow prefixes distinctly (that is,
1625 // field-accesses on P distinctly from P itself), in order to
1626 // track substructure initialization separately from the whole
1629 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1630 // which we have a MovePath is `a.b`, then that means that the
1631 // initialization state of `a.b` is all we need to inspect to
1632 // know if `a.b.c` is valid (and from that we infer that the
1633 // dereference and `.d` access is also valid, since we assume
1634 // `a.b.c` is assigned a reference to a initialized and
1635 // well-formed record structure.)
1637 // Therefore, if we seek out the *closest* prefix for which we
1638 // have a MovePath, that should capture the initialization
1639 // state for the place scenario.
1641 // This code covers scenarios 1, 2, and 3.
1643 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1644 match self.move_path_closest_to(place_span.0) {
1645 Ok((prefix, mpi)) => {
1646 if maybe_uninits.contains(mpi) {
1647 self.report_use_of_moved_or_uninitialized(
1650 (prefix, place_span.0, place_span.1),
1653 return; // don't bother finding other problems.
1656 Err(NoMovePathFound::ReachedStatic) => {
1657 // Okay: we do not build MoveData for static variables
1658 } // Only query longest prefix with a MovePath, not further
1659 // ancestors; dataflow recurs on children when parents
1660 // move (to support partial (re)inits).
1662 // (I.e., querying parents breaks scenario 7; but may want
1663 // to do such a query based on partial-init feature-gate.)
1667 fn check_if_path_or_subpath_is_moved(
1670 desired_action: InitializationRequiringAction,
1671 place_span: (&Place<'tcx>, Span),
1672 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1674 let maybe_uninits = &flow_state.uninits;
1678 // 1. Move of `a.b.c`, use of `a` or `a.b`
1679 // partial initialization support, one might have `a.x`
1680 // initialized but not `a.b`.
1681 // 2. All bad scenarios from `check_if_full_path_is_moved`
1685 // 3. Move of `a.b.c`, use of `a.b.d`
1686 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1687 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1688 // must have been initialized for the use to be sound.
1689 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1691 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1693 // A move of any shallow suffix of `place` also interferes
1694 // with an attempt to use `place`. This is scenario 3 above.
1696 // (Distinct from handling of scenarios 1+2+4 above because
1697 // `place` does not interfere with suffixes of its prefixes,
1698 // e.g., `a.b.c` does not interfere with `a.b.d`)
1700 // This code covers scenario 1.
1702 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1703 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1704 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1705 self.report_use_of_moved_or_uninitialized(
1708 (place_span.0, place_span.0, place_span.1),
1711 return; // don't bother finding other problems.
1716 /// Currently MoveData does not store entries for all places in
1717 /// the input MIR. For example it will currently filter out
1718 /// places that are Copy; thus we do not track places of shared
1719 /// reference type. This routine will walk up a place along its
1720 /// prefixes, searching for a foundational place that *is*
1721 /// tracked in the MoveData.
1723 /// An Err result includes a tag indicated why the search failed.
1724 /// Currently this can only occur if the place is built off of a
1725 /// static variable, as we do not track those in the MoveData.
1726 fn move_path_closest_to<'a>(
1728 place: &'a Place<'tcx>,
1729 ) -> Result<(&'a Place<'tcx>, MovePathIndex), NoMovePathFound> where 'cx: 'a {
1730 let mut last_prefix = place;
1731 for prefix in self.prefixes(place, PrefixSet::All) {
1732 if let Some(mpi) = self.move_path_for_place(prefix) {
1733 return Ok((prefix, mpi));
1735 last_prefix = prefix;
1737 match *last_prefix {
1738 Place::Base(PlaceBase::Local(_)) => panic!("should have move path for every Local"),
1739 Place::Projection(_) => panic!("PrefixSet::All meant don't stop for Projection"),
1740 Place::Base(PlaceBase::Static(_)) => Err(NoMovePathFound::ReachedStatic),
1744 fn move_path_for_place(&mut self, place: &Place<'tcx>) -> Option<MovePathIndex> {
1745 // If returns None, then there is no move path corresponding
1746 // to a direct owner of `place` (which means there is nothing
1747 // that borrowck tracks for its analysis).
1749 match self.move_data.rev_lookup.find(place) {
1750 LookupResult::Parent(_) => None,
1751 LookupResult::Exact(mpi) => Some(mpi),
1755 fn check_if_assigned_path_is_moved(
1758 (place, span): (&Place<'tcx>, Span),
1759 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1761 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1762 // recur down place; dispatch to external checks when necessary
1763 let mut place = place;
1766 Place::Base(PlaceBase::Local(_)) | Place::Base(PlaceBase::Static(_)) => {
1767 // assigning to `x` does not require `x` be initialized.
1770 Place::Projection(ref proj) => {
1771 let Projection { ref base, ref elem } = **proj;
1773 ProjectionElem::Index(_/*operand*/) |
1774 ProjectionElem::ConstantIndex { .. } |
1775 // assigning to P[i] requires P to be valid.
1776 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1777 // assigning to (P->variant) is okay if assigning to `P` is okay
1779 // FIXME: is this true even if P is a adt with a dtor?
1782 // assigning to (*P) requires P to be initialized
1783 ProjectionElem::Deref => {
1784 self.check_if_full_path_is_moved(
1785 location, InitializationRequiringAction::Use,
1786 (base, span), flow_state);
1787 // (base initialized; no need to
1792 ProjectionElem::Subslice { .. } => {
1793 panic!("we don't allow assignments to subslices, location: {:?}",
1797 ProjectionElem::Field(..) => {
1798 // if type of `P` has a dtor, then
1799 // assigning to `P.f` requires `P` itself
1800 // be already initialized
1801 let tcx = self.infcx.tcx;
1802 match base.ty(self.mir, tcx).ty.sty {
1803 ty::Adt(def, _) if def.has_dtor(tcx) => {
1804 self.check_if_path_or_subpath_is_moved(
1805 location, InitializationRequiringAction::Assignment,
1806 (base, span), flow_state);
1808 // (base initialized; no need to
1814 // Once `let s; s.x = V; read(s.x);`,
1815 // is allowed, remove this match arm.
1816 ty::Adt(..) | ty::Tuple(..) => {
1817 check_parent_of_field(self, location, base, span, flow_state);
1819 if let Some(local) = place.base_local() {
1820 // rust-lang/rust#21232,
1821 // #54499, #54986: during
1822 // period where we reject
1823 // partial initialization, do
1824 // not complain about
1825 // unnecessary `mut` on an
1826 // attempt to do a partial
1828 self.used_mut.insert(local);
1842 fn check_parent_of_field<'cx, 'gcx, 'tcx>(
1843 this: &mut MirBorrowckCtxt<'cx, 'gcx, 'tcx>,
1847 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1849 // rust-lang/rust#21232: Until Rust allows reads from the
1850 // initialized parts of partially initialized structs, we
1851 // will, starting with the 2018 edition, reject attempts
1852 // to write to structs that are not fully initialized.
1854 // In other words, *until* we allow this:
1856 // 1. `let mut s; s.x = Val; read(s.x);`
1858 // we will for now disallow this:
1860 // 2. `let mut s; s.x = Val;`
1864 // 3. `let mut s = ...; drop(s); s.x=Val;`
1866 // This does not use check_if_path_or_subpath_is_moved,
1867 // because we want to *allow* reinitializations of fields:
1868 // e.g., want to allow
1870 // `let mut s = ...; drop(s.x); s.x=Val;`
1872 // This does not use check_if_full_path_is_moved on
1873 // `base`, because that would report an error about the
1874 // `base` as a whole, but in this scenario we *really*
1875 // want to report an error about the actual thing that was
1876 // moved, which may be some prefix of `base`.
1878 // Shallow so that we'll stop at any dereference; we'll
1879 // report errors about issues with such bases elsewhere.
1880 let maybe_uninits = &flow_state.uninits;
1882 // Find the shortest uninitialized prefix you can reach
1883 // without going over a Deref.
1884 let mut shortest_uninit_seen = None;
1885 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1886 let mpi = match this.move_path_for_place(prefix) {
1887 Some(mpi) => mpi, None => continue,
1890 if maybe_uninits.contains(mpi) {
1891 debug!("check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1892 shortest_uninit_seen, Some((prefix, mpi)));
1893 shortest_uninit_seen = Some((prefix, mpi));
1895 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1899 if let Some((prefix, mpi)) = shortest_uninit_seen {
1900 // Check for a reassignment into a uninitialized field of a union (for example,
1901 // after a move out). In this case, do not report a error here. There is an
1902 // exception, if this is the first assignment into the union (that is, there is
1903 // no move out from an earlier location) then this is an attempt at initialization
1904 // of the union - we should error in that case.
1905 let tcx = this.infcx.tcx;
1906 if let ty::Adt(def, _) = base.ty(this.mir, tcx).ty.sty {
1908 if this.move_data.path_map[mpi].iter().any(|moi| {
1909 this.move_data.moves[*moi].source.is_predecessor_of(
1918 this.report_use_of_moved_or_uninitialized(
1920 InitializationRequiringAction::PartialAssignment,
1921 (prefix, base, span),
1928 /// Checks the permissions for the given place and read or write kind
1930 /// Returns `true` if an error is reported.
1931 fn check_access_permissions(
1933 (place, span): (&Place<'tcx>, Span),
1935 is_local_mutation_allowed: LocalMutationIsAllowed,
1936 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1940 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1941 place, kind, is_local_mutation_allowed
1947 // rust-lang/rust#21232, #54986: during period where we reject
1948 // partial initialization, do not complain about mutability
1949 // errors except for actual mutation (as opposed to an attempt
1950 // to do a partial initialization).
1951 let previously_initialized = if let Some(local) = place.base_local() {
1952 self.is_local_ever_initialized(local, flow_state).is_some()
1958 Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1959 | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
1960 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
1961 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. })) => {
1962 let is_local_mutation_allowed = match borrow_kind {
1963 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1964 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1965 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1967 match self.is_mutable(place, is_local_mutation_allowed) {
1969 self.add_used_mut(root_place, flow_state);
1973 error_access = AccessKind::MutableBorrow;
1974 the_place_err = place_err;
1978 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1979 match self.is_mutable(place, is_local_mutation_allowed) {
1981 self.add_used_mut(root_place, flow_state);
1985 error_access = AccessKind::Mutate;
1986 the_place_err = place_err;
1991 Reservation(wk @ WriteKind::Move)
1992 | Write(wk @ WriteKind::Move)
1993 | Reservation(wk @ WriteKind::StorageDeadOrDrop)
1994 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1995 | Reservation(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow))
1996 | Write(wk @ WriteKind::StorageDeadOrDrop)
1997 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
1998 | Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
1999 if let (Err(_place_err), true) = (
2000 self.is_mutable(place, is_local_mutation_allowed),
2001 self.errors_buffer.is_empty()
2003 if self.infcx.tcx.migrate_borrowck() {
2004 // rust-lang/rust#46908: In pure NLL mode this
2005 // code path should be unreachable (and thus
2006 // we signal an ICE in the else branch
2007 // here). But we can legitimately get here
2008 // under borrowck=migrate mode, so instead of
2009 // ICE'ing we instead report a legitimate
2010 // error (which will then be downgraded to a
2011 // warning by the migrate machinery).
2012 error_access = match wk {
2013 WriteKind::MutableBorrow(_) => AccessKind::MutableBorrow,
2014 WriteKind::Move => AccessKind::Move,
2015 WriteKind::StorageDeadOrDrop |
2016 WriteKind::Mutate => AccessKind::Mutate,
2018 self.report_mutability_error(
2028 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2037 // permission checks are done at Reservation point.
2040 Read(ReadKind::Borrow(BorrowKind::Unique))
2041 | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
2042 | Read(ReadKind::Borrow(BorrowKind::Shared))
2043 | Read(ReadKind::Borrow(BorrowKind::Shallow))
2044 | Read(ReadKind::Copy) => {
2045 // Access authorized
2050 // at this point, we have set up the error reporting state.
2051 return if previously_initialized {
2052 self.report_mutability_error(
2065 fn is_local_ever_initialized(&self,
2067 flow_state: &Flows<'cx, 'gcx, 'tcx>)
2068 -> Option<InitIndex>
2070 let mpi = self.move_data.rev_lookup.find_local(local);
2071 let ii = &self.move_data.init_path_map[mpi];
2073 if flow_state.ever_inits.contains(index) {
2080 /// Adds the place into the used mutable variables set
2081 fn add_used_mut<'d>(
2083 root_place: RootPlace<'d, 'tcx>,
2084 flow_state: &Flows<'cx, 'gcx, 'tcx>,
2088 place: Place::Base(PlaceBase::Local(local)),
2089 is_local_mutation_allowed,
2091 // If the local may have been initialized, and it is now currently being
2092 // mutated, then it is justified to be annotated with the `mut`
2093 // keyword, since the mutation may be a possible reassignment.
2094 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes &&
2095 self.is_local_ever_initialized(*local, flow_state).is_some()
2097 self.used_mut.insert(*local);
2102 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2105 place: place @ Place::Projection(_),
2106 is_local_mutation_allowed: _,
2108 if let Some(field) = self.is_upvar_field_projection(place) {
2109 self.used_mut_upvars.push(field);
2113 place: Place::Base(PlaceBase::Static(..)),
2114 is_local_mutation_allowed: _,
2119 /// Whether this value can be written or borrowed mutably.
2120 /// Returns the root place if the place passed in is a projection.
2123 place: &'d Place<'tcx>,
2124 is_local_mutation_allowed: LocalMutationIsAllowed,
2125 ) -> Result<RootPlace<'d, 'tcx>, &'d Place<'tcx>> {
2127 Place::Base(PlaceBase::Local(local)) => {
2128 let local = &self.mir.local_decls[local];
2129 match local.mutability {
2130 Mutability::Not => match is_local_mutation_allowed {
2131 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2133 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2135 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2137 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2139 LocalMutationIsAllowed::No => Err(place),
2141 Mutability::Mut => Ok(RootPlace {
2143 is_local_mutation_allowed,
2147 // The rules for promotion are made by `qualify_consts`, there wouldn't even be a
2148 // `Place::Promoted` if the promotion weren't 100% legal. So we just forward this
2149 Place::Base(PlaceBase::Static(box Static{kind: StaticKind::Promoted(_), ..})) =>
2152 is_local_mutation_allowed,
2154 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(def_id), .. })) => {
2155 if !self.infcx.tcx.is_mutable_static(def_id) {
2160 is_local_mutation_allowed,
2164 Place::Projection(ref proj) => {
2166 ProjectionElem::Deref => {
2167 let base_ty = proj.base.ty(self.mir, self.infcx.tcx).ty;
2169 // Check the kind of deref to decide
2171 ty::Ref(_, _, mutbl) => {
2173 // Shared borrowed data is never mutable
2174 hir::MutImmutable => Err(place),
2175 // Mutably borrowed data is mutable, but only if we have a
2176 // unique path to the `&mut`
2177 hir::MutMutable => {
2178 let mode = match self.is_upvar_field_projection(place) {
2180 if self.upvars[field.index()].by_ref =>
2182 is_local_mutation_allowed
2184 _ => LocalMutationIsAllowed::Yes,
2187 self.is_mutable(&proj.base, mode)
2191 ty::RawPtr(tnm) => {
2193 // `*const` raw pointers are not mutable
2194 hir::MutImmutable => Err(place),
2195 // `*mut` raw pointers are always mutable, regardless of
2196 // context. The users have to check by themselves.
2197 hir::MutMutable => {
2200 is_local_mutation_allowed,
2205 // `Box<T>` owns its content, so mutable if its location is mutable
2206 _ if base_ty.is_box() => {
2207 self.is_mutable(&proj.base, is_local_mutation_allowed)
2209 // Deref should only be for reference, pointers or boxes
2210 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2213 // All other projections are owned by their base path, so mutable if
2214 // base path is mutable
2215 ProjectionElem::Field(..)
2216 | ProjectionElem::Index(..)
2217 | ProjectionElem::ConstantIndex { .. }
2218 | ProjectionElem::Subslice { .. }
2219 | ProjectionElem::Downcast(..) => {
2220 let upvar_field_projection = self.is_upvar_field_projection(place);
2221 if let Some(field) = upvar_field_projection {
2222 let upvar = &self.upvars[field.index()];
2224 "upvar.mutability={:?} local_mutation_is_allowed={:?} place={:?}",
2225 upvar, is_local_mutation_allowed, place
2227 match (upvar.mutability, is_local_mutation_allowed) {
2228 (Mutability::Not, LocalMutationIsAllowed::No)
2229 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2232 (Mutability::Not, LocalMutationIsAllowed::Yes)
2233 | (Mutability::Mut, _) => {
2234 // Subtle: this is an upvar
2235 // reference, so it looks like
2236 // `self.foo` -- we want to double
2237 // check that the location `*self`
2238 // is mutable (i.e., this is not a
2239 // `Fn` closure). But if that
2240 // check succeeds, we want to
2241 // *blame* the mutability on
2242 // `place` (that is,
2243 // `self.foo`). This is used to
2244 // propagate the info about
2245 // whether mutability declarations
2246 // are used outwards, so that we register
2247 // the outer variable as mutable. Otherwise a
2248 // test like this fails to record the `mut`
2252 // fn foo<F: FnOnce()>(_f: F) { }
2254 // let var = Vec::new();
2260 let _ = self.is_mutable(&proj.base, is_local_mutation_allowed)?;
2263 is_local_mutation_allowed,
2268 self.is_mutable(&proj.base, is_local_mutation_allowed)
2276 /// If `place` is a field projection, and the field is being projected from a closure type,
2277 /// then returns the index of the field being projected. Note that this closure will always
2278 /// be `self` in the current MIR, because that is the only time we directly access the fields
2279 /// of a closure type.
2280 pub fn is_upvar_field_projection(&self, place: &Place<'tcx>) -> Option<Field> {
2281 let (place, by_ref) = if let Place::Projection(ref proj) = place {
2282 if let ProjectionElem::Deref = proj.elem {
2292 Place::Projection(ref proj) => match proj.elem {
2293 ProjectionElem::Field(field, _ty) => {
2294 let tcx = self.infcx.tcx;
2295 let base_ty = proj.base.ty(self.mir, tcx).ty;
2297 if (base_ty.is_closure() || base_ty.is_generator()) &&
2298 (!by_ref || self.upvars[field.index()].by_ref)
2312 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2313 enum NoMovePathFound {
2317 /// The degree of overlap between 2 places for borrow-checking.
2319 /// The places might partially overlap - in this case, we give
2320 /// up and say that they might conflict. This occurs when
2321 /// different fields of a union are borrowed. For example,
2322 /// if `u` is a union, we have no way of telling how disjoint
2323 /// `u.a.x` and `a.b.y` are.
2325 /// The places have the same type, and are either completely disjoint
2326 /// or equal - i.e., they can't "partially" overlap as can occur with
2327 /// unions. This is the "base case" on which we recur for extensions
2330 /// The places are disjoint, so we know all extensions of them
2331 /// will also be disjoint.