1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
3 #![allow(rustc::potential_query_instability)]
4 #![feature(box_patterns)]
5 #![feature(let_chains)]
7 #![feature(min_specialization)]
8 #![feature(never_type)]
9 #![feature(rustc_attrs)]
10 #![feature(stmt_expr_attributes)]
11 #![feature(trusted_step)]
12 #![feature(try_blocks)]
13 #![recursion_limit = "256"]
16 extern crate rustc_middle;
20 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
21 use rustc_data_structures::graph::dominators::Dominators;
22 use rustc_errors::{Diagnostic, DiagnosticBuilder, ErrorGuaranteed};
24 use rustc_hir::def_id::LocalDefId;
25 use rustc_index::bit_set::ChunkedBitSet;
26 use rustc_index::vec::IndexVec;
27 use rustc_infer::infer::{DefiningAnchor, InferCtxt, TyCtxtInferExt};
28 use rustc_middle::mir::{
29 traversal, Body, ClearCrossCrate, Local, Location, Mutability, NonDivergingIntrinsic, Operand,
30 Place, PlaceElem, PlaceRef, VarDebugInfoContents,
32 use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
33 use rustc_middle::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
34 use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind};
35 use rustc_middle::ty::query::Providers;
36 use rustc_middle::ty::{self, CapturedPlace, ParamEnv, RegionVid, TyCtxt};
37 use rustc_session::lint::builtin::UNUSED_MUT;
38 use rustc_span::{Span, Symbol};
41 use smallvec::SmallVec;
42 use std::cell::RefCell;
43 use std::collections::BTreeMap;
46 use rustc_mir_dataflow::impls::{
47 EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces,
49 use rustc_mir_dataflow::move_paths::{InitIndex, MoveOutIndex, MovePathIndex};
50 use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveData, MoveError};
51 use rustc_mir_dataflow::Analysis;
52 use rustc_mir_dataflow::MoveDataParamEnv;
54 use crate::session_diagnostics::VarNeedNotMut;
56 use self::diagnostics::{AccessKind, RegionName};
57 use self::location::LocationTable;
58 use self::prefixes::PrefixSet;
61 use self::path_utils::*;
65 mod constraint_generation;
73 mod member_constraints;
81 mod session_diagnostics;
83 mod universal_regions;
86 // A public API provided for the Rust compiler consumers.
89 use borrow_set::{BorrowData, BorrowSet};
90 use dataflow::{BorrowIndex, BorrowckFlowState as Flows, BorrowckResults, Borrows};
91 use nll::{PoloniusOutput, ToRegionVid};
92 use place_ext::PlaceExt;
93 use places_conflict::{places_conflict, PlaceConflictBias};
94 use region_infer::RegionInferenceContext;
96 // FIXME(eddyb) perhaps move this somewhere more centrally.
99 place: CapturedPlace<'tcx>,
101 /// If true, the capture is behind a reference.
105 /// Associate some local constants with the `'tcx` lifetime
106 struct TyCtxtConsts<'tcx>(TyCtxt<'tcx>);
107 impl<'tcx> TyCtxtConsts<'tcx> {
108 const DEREF_PROJECTION: &'tcx [PlaceElem<'tcx>; 1] = &[ProjectionElem::Deref];
111 pub fn provide(providers: &mut Providers) {
112 *providers = Providers {
113 mir_borrowck: |tcx, did| {
114 if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
115 tcx.mir_borrowck_const_arg(def)
117 mir_borrowck(tcx, ty::WithOptConstParam::unknown(did))
120 mir_borrowck_const_arg: |tcx, (did, param_did)| {
121 mir_borrowck(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
127 fn mir_borrowck<'tcx>(
129 def: ty::WithOptConstParam<LocalDefId>,
130 ) -> &'tcx BorrowCheckResult<'tcx> {
131 let (input_body, promoted) = tcx.mir_promoted(def);
132 debug!("run query mir_borrowck: {}", tcx.def_path_str(def.did.to_def_id()));
133 let hir_owner = tcx.hir().local_def_id_to_hir_id(def.did).owner;
135 let opt_closure_req = tcx
137 .with_opaque_type_inference(DefiningAnchor::Bind(hir_owner))
139 let input_body: &Body<'_> = &input_body.borrow();
140 let promoted: &IndexVec<_, _> = &promoted.borrow();
141 do_mir_borrowck(&infcx, input_body, promoted, false).0
143 debug!("mir_borrowck done");
145 tcx.arena.alloc(opt_closure_req)
148 /// Perform the actual borrow checking.
150 /// If `return_body_with_facts` is true, then return the body with non-erased
151 /// region ids on which the borrow checking was performed together with Polonius
153 #[instrument(skip(infcx, input_body, input_promoted), fields(id=?input_body.source.with_opt_param().as_local().unwrap()), level = "debug")]
154 fn do_mir_borrowck<'a, 'tcx>(
155 infcx: &InferCtxt<'a, 'tcx>,
156 input_body: &Body<'tcx>,
157 input_promoted: &IndexVec<Promoted, Body<'tcx>>,
158 return_body_with_facts: bool,
159 ) -> (BorrowCheckResult<'tcx>, Option<Box<BodyWithBorrowckFacts<'tcx>>>) {
160 let def = input_body.source.with_opt_param().as_local().unwrap();
165 let param_env = tcx.param_env(def.did);
167 let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
168 for var_debug_info in &input_body.var_debug_info {
169 if let VarDebugInfoContents::Place(place) = var_debug_info.value {
170 if let Some(local) = place.as_local() {
171 if let Some(prev_name) = local_names[local] && var_debug_info.name != prev_name {
173 var_debug_info.source_info.span,
174 "local {:?} has many names (`{}` vs `{}`)",
180 local_names[local] = Some(var_debug_info.name);
185 let mut errors = error::BorrowckErrors::new();
187 // Gather the upvars of a closure, if any.
188 let tables = tcx.typeck_opt_const_arg(def);
189 if let Some(ErrorGuaranteed { .. }) = tables.tainted_by_errors {
190 infcx.set_tainted_by_errors();
191 errors.set_tainted_by_errors();
193 let upvars: Vec<_> = tables
194 .closure_min_captures_flattened(def.did)
195 .map(|captured_place| {
196 let capture = captured_place.info.capture_kind;
197 let by_ref = match capture {
198 ty::UpvarCapture::ByValue => false,
199 ty::UpvarCapture::ByRef(..) => true,
201 Upvar { place: captured_place.clone(), by_ref }
205 // Replace all regions with fresh inference variables. This
206 // requires first making our own copy of the MIR. This copy will
207 // be modified (in place) to contain non-lexical lifetimes. It
208 // will have a lifetime tied to the inference context.
209 let mut body_owned = input_body.clone();
210 let mut promoted = input_promoted.clone();
212 nll::replace_regions_in_mir(infcx, param_env, &mut body_owned, &mut promoted);
213 let body = &body_owned; // no further changes
215 let location_table_owned = LocationTable::new(body);
216 let location_table = &location_table_owned;
218 let (move_data, move_errors): (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>) =
219 match MoveData::gather_moves(&body, tcx, param_env) {
220 Ok((_, move_data)) => (move_data, Vec::new()),
221 Err((move_data, move_errors)) => (move_data, move_errors),
223 let promoted_errors = promoted
225 .map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env)));
227 let mdpe = MoveDataParamEnv { move_data, param_env };
229 let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe)
230 .into_engine(tcx, &body)
231 .pass_name("borrowck")
232 .iterate_to_fixpoint()
233 .into_results_cursor(&body);
235 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(def.did).is_fn_or_closure();
237 Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
239 let use_polonius = return_body_with_facts || infcx.tcx.sess.opts.unstable_opts.polonius;
241 // Compute non-lexical lifetimes.
249 } = nll::compute_regions(
263 // Dump MIR results into a file, if that is enabled. This let us
264 // write unit-tests, as well as helping with debugging.
265 nll::dump_mir_results(infcx, &body, ®ioncx, &opt_closure_req);
267 // We also have a `#[rustc_regions]` annotation that causes us to dump
269 nll::dump_annotation(
278 // The various `flow_*` structures can be large. We drop `flow_inits` here
279 // so it doesn't overlap with the others below. This reduces peak memory
280 // usage significantly on some benchmarks.
283 let regioncx = Rc::new(regioncx);
285 let flow_borrows = Borrows::new(tcx, body, ®ioncx, &borrow_set)
286 .into_engine(tcx, body)
287 .pass_name("borrowck")
288 .iterate_to_fixpoint();
289 let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &mdpe)
290 .into_engine(tcx, body)
291 .pass_name("borrowck")
292 .iterate_to_fixpoint();
293 let flow_ever_inits = EverInitializedPlaces::new(tcx, body, &mdpe)
294 .into_engine(tcx, body)
295 .pass_name("borrowck")
296 .iterate_to_fixpoint();
298 let movable_generator =
299 // The first argument is the generator type passed by value
300 if let Some(local) = body.local_decls.raw.get(1)
301 // Get the interior types and substs which typeck computed
302 && let ty::Generator(_, _, hir::Movability::Static) = local.ty.kind()
309 for (idx, move_data_results) in promoted_errors {
310 let promoted_body = &promoted[idx];
312 if let Err((move_data, move_errors)) = move_data_results {
313 let mut promoted_mbcx = MirBorrowckCtxt {
317 move_data: &move_data,
318 location_table, // no need to create a real one for the promoted, it is not used
320 fn_self_span_reported: Default::default(),
321 locals_are_invalidated_at_exit,
322 access_place_error_reported: Default::default(),
323 reservation_error_reported: Default::default(),
324 uninitialized_error_reported: Default::default(),
325 regioncx: regioncx.clone(),
326 used_mut: Default::default(),
327 used_mut_upvars: SmallVec::new(),
328 borrow_set: Rc::clone(&borrow_set),
329 dominators: Dominators::dummy(), // not used
331 local_names: IndexVec::from_elem(None, &promoted_body.local_decls),
332 region_names: RefCell::default(),
333 next_region_name: RefCell::new(1),
334 polonius_output: None,
337 promoted_mbcx.report_move_errors(move_errors);
338 errors = promoted_mbcx.errors;
342 let dominators = body.basic_blocks.dominators();
344 let mut mbcx = MirBorrowckCtxt {
348 move_data: &mdpe.move_data,
351 locals_are_invalidated_at_exit,
352 fn_self_span_reported: Default::default(),
353 access_place_error_reported: Default::default(),
354 reservation_error_reported: Default::default(),
355 uninitialized_error_reported: Default::default(),
356 regioncx: Rc::clone(®ioncx),
357 used_mut: Default::default(),
358 used_mut_upvars: SmallVec::new(),
359 borrow_set: Rc::clone(&borrow_set),
363 region_names: RefCell::default(),
364 next_region_name: RefCell::new(1),
369 // Compute and report region errors, if any.
370 mbcx.report_region_errors(nll_errors);
372 let results = BorrowckResults {
373 ever_inits: flow_ever_inits,
374 uninits: flow_uninits,
375 borrows: flow_borrows,
378 mbcx.report_move_errors(move_errors);
380 rustc_mir_dataflow::visit_results(
382 traversal::reverse_postorder(body).map(|(bb, _)| bb),
387 // For each non-user used mutable variable, check if it's been assigned from
388 // a user-declared local. If so, then put that local into the used_mut set.
389 // Note that this set is expected to be small - only upvars from closures
390 // would have a chance of erroneously adding non-user-defined mutable vars
392 let temporary_used_locals: FxHashSet<Local> = mbcx
395 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
398 // For the remaining unused locals that are marked as mutable, we avoid linting any that
399 // were never initialized. These locals may have been removed as unreachable code; or will be
400 // linted as unused variables.
401 let unused_mut_locals =
402 mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
403 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
405 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
406 let used_mut = std::mem::take(&mut mbcx.used_mut);
407 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
408 let local_decl = &mbcx.body.local_decls[local];
409 let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data {
410 ClearCrossCrate::Set(data) => data.lint_root,
414 // Skip over locals that begin with an underscore or have no name
415 match mbcx.local_names[local] {
417 if name.as_str().starts_with('_') {
424 let span = local_decl.source_info.span;
425 if span.desugaring_kind().is_some() {
426 // If the `mut` arises as part of a desugaring, we should ignore it.
430 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
432 tcx.emit_spanned_lint(UNUSED_MUT, lint_root, span, VarNeedNotMut { span: mut_span })
435 let tainted_by_errors = mbcx.emit_errors();
437 let result = BorrowCheckResult {
438 concrete_opaque_types: opaque_type_values,
439 closure_requirements: opt_closure_req,
440 used_mut_upvars: mbcx.used_mut_upvars,
444 let body_with_facts = if return_body_with_facts {
445 let output_facts = mbcx.polonius_output.expect("Polonius output was not computed");
446 Some(Box::new(BodyWithBorrowckFacts {
448 input_facts: *polonius_input.expect("Polonius input facts were not generated"),
450 location_table: location_table_owned,
456 debug!("do_mir_borrowck: result = {:#?}", result);
458 (result, body_with_facts)
461 /// A `Body` with information computed by the borrow checker. This struct is
462 /// intended to be consumed by compiler consumers.
464 /// We need to include the MIR body here because the region identifiers must
465 /// match the ones in the Polonius facts.
466 pub struct BodyWithBorrowckFacts<'tcx> {
467 /// A mir body that contains region identifiers.
468 pub body: Body<'tcx>,
469 /// Polonius input facts.
470 pub input_facts: AllFacts,
471 /// Polonius output facts.
472 pub output_facts: Rc<self::nll::PoloniusOutput>,
473 /// The table that maps Polonius points to locations in the table.
474 pub location_table: LocationTable,
477 struct MirBorrowckCtxt<'cx, 'tcx> {
478 infcx: &'cx InferCtxt<'cx, 'tcx>,
479 param_env: ParamEnv<'tcx>,
480 body: &'cx Body<'tcx>,
481 move_data: &'cx MoveData<'tcx>,
483 /// Map from MIR `Location` to `LocationIndex`; created
484 /// when MIR borrowck begins.
485 location_table: &'cx LocationTable,
487 movable_generator: bool,
488 /// This keeps track of whether local variables are free-ed when the function
489 /// exits even without a `StorageDead`, which appears to be the case for
492 /// I'm not sure this is the right approach - @eddyb could you try and
494 locals_are_invalidated_at_exit: bool,
495 /// This field keeps track of when borrow errors are reported in the access_place function
496 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
497 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
498 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
500 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
501 /// This field keeps track of when borrow conflict errors are reported
502 /// for reservations, so that we don't report seemingly duplicate
503 /// errors for corresponding activations.
505 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
506 // but it is currently inconvenient to track down the `BorrowIndex`
507 // at the time we detect and report a reservation error.
508 reservation_error_reported: FxHashSet<Place<'tcx>>,
509 /// This fields keeps track of the `Span`s that we have
510 /// used to report extra information for `FnSelfUse`, to avoid
511 /// unnecessarily verbose errors.
512 fn_self_span_reported: FxHashSet<Span>,
513 /// This field keeps track of errors reported in the checking of uninitialized variables,
514 /// so that we don't report seemingly duplicate errors.
515 uninitialized_error_reported: FxHashSet<PlaceRef<'tcx>>,
516 /// This field keeps track of all the local variables that are declared mut and are mutated.
517 /// Used for the warning issued by an unused mutable local variable.
518 used_mut: FxHashSet<Local>,
519 /// If the function we're checking is a closure, then we'll need to report back the list of
520 /// mutable upvars that have been used. This field keeps track of them.
521 used_mut_upvars: SmallVec<[Field; 8]>,
522 /// Region inference context. This contains the results from region inference and lets us e.g.
523 /// find out which CFG points are contained in each borrow region.
524 regioncx: Rc<RegionInferenceContext<'tcx>>,
526 /// The set of borrows extracted from the MIR
527 borrow_set: Rc<BorrowSet<'tcx>>,
529 /// Dominators for MIR
530 dominators: Dominators<BasicBlock>,
532 /// Information about upvars not necessarily preserved in types or MIR
533 upvars: Vec<Upvar<'tcx>>,
535 /// Names of local (user) variables (extracted from `var_debug_info`).
536 local_names: IndexVec<Local, Option<Symbol>>,
538 /// Record the region names generated for each region in the given
539 /// MIR def so that we can reuse them later in help/error messages.
540 region_names: RefCell<FxHashMap<RegionVid, RegionName>>,
542 /// The counter for generating new region names.
543 next_region_name: RefCell<usize>,
545 /// Results of Polonius analysis.
546 polonius_output: Option<Rc<PoloniusOutput>>,
548 errors: error::BorrowckErrors<'tcx>,
552 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
553 // 2. loans made in overlapping scopes do not conflict
554 // 3. assignments do not affect things loaned out as immutable
555 // 4. moves do not affect things loaned out in any way
556 impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
557 type FlowState = Flows<'cx, 'tcx>;
559 fn visit_statement_before_primary_effect(
561 flow_state: &Flows<'cx, 'tcx>,
562 stmt: &'cx Statement<'tcx>,
565 debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state);
566 let span = stmt.source_info.span;
568 self.check_activations(location, span, flow_state);
571 StatementKind::Assign(box (lhs, ref rhs)) => {
572 self.consume_rvalue(location, (rhs, span), flow_state);
574 self.mutate_place(location, (*lhs, span), Shallow(None), flow_state);
576 StatementKind::FakeRead(box (_, ref place)) => {
577 // Read for match doesn't access any memory and is used to
578 // assert that a place is safe and live. So we don't have to
579 // do any checks here.
581 // FIXME: Remove check that the place is initialized. This is
582 // needed for now because matches don't have never patterns yet.
583 // So this is the only place we prevent
587 self.check_if_path_or_subpath_is_moved(
589 InitializationRequiringAction::Use,
590 (place.as_ref(), span),
594 StatementKind::Intrinsic(box ref kind) => match kind {
595 // Takes a `bool` argument, and has no return value, thus being irrelevant for borrowck
596 NonDivergingIntrinsic::Assume(..) => {},
597 NonDivergingIntrinsic::CopyNonOverlapping(..) => span_bug!(
599 "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
602 // Only relevant for mir typeck
603 StatementKind::AscribeUserType(..)
604 // Doesn't have any language semantics
605 | StatementKind::Coverage(..)
606 // Does not actually affect borrowck
607 | StatementKind::StorageLive(..) => {}
608 StatementKind::StorageDead(local) => {
611 (Place::from(*local), span),
612 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
613 LocalMutationIsAllowed::Yes,
618 | StatementKind::Retag { .. }
619 | StatementKind::Deinit(..)
620 | StatementKind::SetDiscriminant { .. } => {
621 bug!("Statement not allowed in this MIR phase")
626 fn visit_terminator_before_primary_effect(
628 flow_state: &Flows<'cx, 'tcx>,
629 term: &'cx Terminator<'tcx>,
632 debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
633 let span = term.source_info.span;
635 self.check_activations(loc, span, flow_state);
638 TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => {
639 self.consume_operand(loc, (discr, span), flow_state);
641 TerminatorKind::Drop { place, target: _, unwind: _ } => {
643 "visit_terminator_drop \
644 loc: {:?} term: {:?} place: {:?} span: {:?}",
645 loc, term, place, span
651 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
652 LocalMutationIsAllowed::Yes,
656 TerminatorKind::DropAndReplace {
658 value: ref new_value,
662 self.mutate_place(loc, (drop_place, span), Deep, flow_state);
663 self.consume_operand(loc, (new_value, span), flow_state);
665 TerminatorKind::Call {
674 self.consume_operand(loc, (func, span), flow_state);
676 self.consume_operand(loc, (arg, span), flow_state);
678 self.mutate_place(loc, (destination, span), Deep, flow_state);
680 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
681 self.consume_operand(loc, (cond, span), flow_state);
682 use rustc_middle::mir::AssertKind;
683 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
684 self.consume_operand(loc, (len, span), flow_state);
685 self.consume_operand(loc, (index, span), flow_state);
689 TerminatorKind::Yield { ref value, resume: _, resume_arg, drop: _ } => {
690 self.consume_operand(loc, (value, span), flow_state);
691 self.mutate_place(loc, (resume_arg, span), Deep, flow_state);
694 TerminatorKind::InlineAsm {
704 InlineAsmOperand::In { reg: _, ref value } => {
705 self.consume_operand(loc, (value, span), flow_state);
707 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
708 if let Some(place) = place {
709 self.mutate_place(loc, (place, span), Shallow(None), flow_state);
712 InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
713 self.consume_operand(loc, (in_value, span), flow_state);
714 if let Some(out_place) = out_place {
723 InlineAsmOperand::Const { value: _ }
724 | InlineAsmOperand::SymFn { value: _ }
725 | InlineAsmOperand::SymStatic { def_id: _ } => {}
730 TerminatorKind::Goto { target: _ }
731 | TerminatorKind::Abort
732 | TerminatorKind::Unreachable
733 | TerminatorKind::Resume
734 | TerminatorKind::Return
735 | TerminatorKind::GeneratorDrop
736 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
737 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
738 // no data used, thus irrelevant to borrowck
743 fn visit_terminator_after_primary_effect(
745 flow_state: &Flows<'cx, 'tcx>,
746 term: &'cx Terminator<'tcx>,
749 let span = term.source_info.span;
752 TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
753 if self.movable_generator {
754 // Look for any active borrows to locals
755 let borrow_set = self.borrow_set.clone();
756 for i in flow_state.borrows.iter() {
757 let borrow = &borrow_set[i];
758 self.check_for_local_borrow(borrow, span);
763 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
764 // Returning from the function implicitly kills storage for all locals and statics.
765 // Often, the storage will already have been killed by an explicit
766 // StorageDead, but we don't always emit those (notably on unwind paths),
767 // so this "extra check" serves as a kind of backup.
768 let borrow_set = self.borrow_set.clone();
769 for i in flow_state.borrows.iter() {
770 let borrow = &borrow_set[i];
771 self.check_for_invalidation_at_exit(loc, borrow, span);
775 TerminatorKind::Abort
776 | TerminatorKind::Assert { .. }
777 | TerminatorKind::Call { .. }
778 | TerminatorKind::Drop { .. }
779 | TerminatorKind::DropAndReplace { .. }
780 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
781 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
782 | TerminatorKind::Goto { .. }
783 | TerminatorKind::SwitchInt { .. }
784 | TerminatorKind::Unreachable
785 | TerminatorKind::InlineAsm { .. } => {}
790 use self::AccessDepth::{Deep, Shallow};
791 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
793 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
794 enum ArtificialField {
799 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
801 /// From the RFC: "A *shallow* access means that the immediate
802 /// fields reached at P are accessed, but references or pointers
803 /// found within are not dereferenced. Right now, the only access
804 /// that is shallow is an assignment like `x = ...;`, which would
805 /// be a *shallow write* of `x`."
806 Shallow(Option<ArtificialField>),
808 /// From the RFC: "A *deep* access means that all data reachable
809 /// through the given place may be invalidated or accesses by
813 /// Access is Deep only when there is a Drop implementation that
814 /// can reach the data behind the reference.
818 /// Kind of access to a value: read or write
819 /// (For informational purposes only)
820 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
822 /// From the RFC: "A *read* means that the existing data may be
823 /// read, but will not be changed."
826 /// From the RFC: "A *write* means that the data may be mutated to
827 /// new values or otherwise invalidated (for example, it could be
828 /// de-initialized, as in a move operation).
831 /// For two-phase borrows, we distinguish a reservation (which is treated
832 /// like a Read) from an activation (which is treated like a write), and
833 /// each of those is furthermore distinguished from Reads/Writes above.
834 Reservation(WriteKind),
835 Activation(WriteKind, BorrowIndex),
838 /// Kind of read access to a value
839 /// (For informational purposes only)
840 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
846 /// Kind of write access to a value
847 /// (For informational purposes only)
848 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
851 MutableBorrow(BorrowKind),
856 /// When checking permissions for a place access, this flag is used to indicate that an immutable
857 /// local place can be mutated.
859 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
860 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
861 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
862 // `is_declared_mutable()`.
863 // - Take flow state into consideration in `is_assignable()` for local variables.
864 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
865 enum LocalMutationIsAllowed {
867 /// We want use of immutable upvars to cause a "write to immutable upvar"
868 /// error, not an "reassignment" error.
873 #[derive(Copy, Clone, Debug)]
874 enum InitializationRequiringAction {
882 struct RootPlace<'tcx> {
884 place_projection: &'tcx [PlaceElem<'tcx>],
885 is_local_mutation_allowed: LocalMutationIsAllowed,
888 impl InitializationRequiringAction {
889 fn as_noun(self) -> &'static str {
891 InitializationRequiringAction::Borrow => "borrow",
892 InitializationRequiringAction::MatchOn => "use", // no good noun
893 InitializationRequiringAction::Use => "use",
894 InitializationRequiringAction::Assignment => "assign",
895 InitializationRequiringAction::PartialAssignment => "assign to part",
899 fn as_verb_in_past_tense(self) -> &'static str {
901 InitializationRequiringAction::Borrow => "borrowed",
902 InitializationRequiringAction::MatchOn => "matched on",
903 InitializationRequiringAction::Use => "used",
904 InitializationRequiringAction::Assignment => "assigned",
905 InitializationRequiringAction::PartialAssignment => "partially assigned",
909 fn as_general_verb_in_past_tense(self) -> &'static str {
911 InitializationRequiringAction::Borrow
912 | InitializationRequiringAction::MatchOn
913 | InitializationRequiringAction::Use => "used",
914 InitializationRequiringAction::Assignment => "assigned",
915 InitializationRequiringAction::PartialAssignment => "partially assigned",
920 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
921 fn body(&self) -> &'cx Body<'tcx> {
925 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
926 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
927 /// place is initialized and (b) it is not borrowed in some way that would prevent this
930 /// Returns `true` if an error is reported.
934 place_span: (Place<'tcx>, Span),
935 kind: (AccessDepth, ReadOrWrite),
936 is_local_mutation_allowed: LocalMutationIsAllowed,
937 flow_state: &Flows<'cx, 'tcx>,
941 if let Activation(_, borrow_index) = rw {
942 if self.reservation_error_reported.contains(&place_span.0) {
944 "skipping access_place for activation of invalid reservation \
945 place: {:?} borrow_index: {:?}",
946 place_span.0, borrow_index
952 // Check is_empty() first because it's the common case, and doing that
953 // way we avoid the clone() call.
954 if !self.access_place_error_reported.is_empty()
955 && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
958 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
964 let mutability_error = self.check_access_permissions(
967 is_local_mutation_allowed,
972 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
974 if conflict_error || mutability_error {
975 debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
976 self.access_place_error_reported.insert((place_span.0, place_span.1));
980 #[instrument(level = "debug", skip(self, flow_state))]
981 fn check_access_for_conflict(
984 place_span: (Place<'tcx>, Span),
987 flow_state: &Flows<'cx, 'tcx>,
989 let mut error_reported = false;
990 let tcx = self.infcx.tcx;
991 let body = self.body;
992 let borrow_set = self.borrow_set.clone();
994 // Use polonius output if it has been enabled.
995 let polonius_output = self.polonius_output.clone();
996 let borrows_in_scope = if let Some(polonius) = &polonius_output {
997 let location = self.location_table.start_index(location);
998 Either::Left(polonius.errors_at(location).iter().copied())
1000 Either::Right(flow_state.borrows.iter())
1003 each_borrow_involving_path(
1011 |this, borrow_index, borrow| match (rw, borrow.kind) {
1012 // Obviously an activation is compatible with its own
1013 // reservation (or even prior activating uses of same
1014 // borrow); so don't check if they interfere.
1016 // NOTE: *reservations* do conflict with themselves;
1017 // thus aren't injecting unsoundness w/ this check.)
1018 (Activation(_, activating), _) if activating == borrow_index => {
1020 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1021 skipping {:?} b/c activation of same borrow_index",
1025 (borrow_index, borrow),
1030 (Read(_), BorrowKind::Shared | BorrowKind::Shallow)
1032 Read(ReadKind::Borrow(BorrowKind::Shallow)),
1033 BorrowKind::Unique | BorrowKind::Mut { .. },
1034 ) => Control::Continue,
1036 (Reservation(_), BorrowKind::Shallow | BorrowKind::Shared) => {
1037 // This used to be a future compatibility warning (to be
1038 // disallowed on NLL). See rust-lang/rust#56254
1042 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1043 // Handled by initialization checks.
1047 (Read(kind), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
1048 // Reading from mere reservations of mutable-borrows is OK.
1049 if !is_active(&this.dominators, borrow, location) {
1050 assert!(allow_two_phase_borrow(borrow.kind));
1051 return Control::Continue;
1054 error_reported = true;
1058 .report_use_while_mutably_borrowed(location, place_span, borrow);
1059 this.buffer_error(err);
1061 ReadKind::Borrow(bk) => {
1063 this.report_conflicting_borrow(location, place_span, bk, borrow);
1064 this.buffer_error(err);
1070 (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1072 Reservation(..) => {
1074 "recording invalid reservation of \
1078 this.reservation_error_reported.insert(place_span.0);
1080 Activation(_, activating) => {
1082 "observing check_place for activation of \
1083 borrow_index: {:?}",
1087 Read(..) | Write(..) => {}
1090 error_reported = true;
1092 WriteKind::MutableBorrow(bk) => {
1094 this.report_conflicting_borrow(location, place_span, bk, borrow);
1095 this.buffer_error(err);
1097 WriteKind::StorageDeadOrDrop => this
1098 .report_borrowed_value_does_not_live_long_enough(
1104 WriteKind::Mutate => {
1105 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1107 WriteKind::Move => {
1108 this.report_move_out_while_borrowed(location, place_span, borrow)
1122 place_span: (Place<'tcx>, Span),
1124 flow_state: &Flows<'cx, 'tcx>,
1126 // Write of P[i] or *P requires P init'd.
1127 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1129 // Special case: you can assign an immutable local variable
1130 // (e.g., `x = ...`) so long as it has never been initialized
1131 // before (at this point in the flow).
1132 if let Some(local) = place_span.0.as_local() {
1133 if let Mutability::Not = self.body.local_decls[local].mutability {
1134 // check for reassignments to immutable local variables
1135 self.check_if_reassignment_to_immutable_state(
1136 location, local, place_span, flow_state,
1142 // Otherwise, use the normal access permission rules.
1146 (kind, Write(WriteKind::Mutate)),
1147 LocalMutationIsAllowed::No,
1155 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1156 flow_state: &Flows<'cx, 'tcx>,
1159 Rvalue::Ref(_ /*rgn*/, bk, place) => {
1160 let access_kind = match bk {
1161 BorrowKind::Shallow => {
1162 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1164 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1165 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1166 let wk = WriteKind::MutableBorrow(bk);
1167 if allow_two_phase_borrow(bk) {
1168 (Deep, Reservation(wk))
1179 LocalMutationIsAllowed::No,
1183 let action = if bk == BorrowKind::Shallow {
1184 InitializationRequiringAction::MatchOn
1186 InitializationRequiringAction::Borrow
1189 self.check_if_path_or_subpath_is_moved(
1192 (place.as_ref(), span),
1197 Rvalue::AddressOf(mutability, place) => {
1198 let access_kind = match mutability {
1199 Mutability::Mut => (
1201 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1202 allow_two_phase_borrow: false,
1205 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1212 LocalMutationIsAllowed::No,
1216 self.check_if_path_or_subpath_is_moved(
1218 InitializationRequiringAction::Borrow,
1219 (place.as_ref(), span),
1224 Rvalue::ThreadLocalRef(_) => {}
1226 Rvalue::Use(ref operand)
1227 | Rvalue::Repeat(ref operand, _)
1228 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1229 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/)
1230 | Rvalue::ShallowInitBox(ref operand, _ /*ty*/) => {
1231 self.consume_operand(location, (operand, span), flow_state)
1233 Rvalue::CopyForDeref(place) => {
1237 (Deep, Read(ReadKind::Copy)),
1238 LocalMutationIsAllowed::No,
1242 // Finally, check if path was already moved.
1243 self.check_if_path_or_subpath_is_moved(
1245 InitializationRequiringAction::Use,
1246 (place.as_ref(), span),
1251 Rvalue::Len(place) | Rvalue::Discriminant(place) => {
1252 let af = match *rvalue {
1253 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1254 Rvalue::Discriminant(..) => None,
1255 _ => unreachable!(),
1260 (Shallow(af), Read(ReadKind::Copy)),
1261 LocalMutationIsAllowed::No,
1264 self.check_if_path_or_subpath_is_moved(
1266 InitializationRequiringAction::Use,
1267 (place.as_ref(), span),
1272 Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2))
1273 | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => {
1274 self.consume_operand(location, (operand1, span), flow_state);
1275 self.consume_operand(location, (operand2, span), flow_state);
1278 Rvalue::NullaryOp(_op, _ty) => {
1279 // nullary ops take no dynamic input; no borrowck effect.
1282 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1283 // We need to report back the list of mutable upvars that were
1284 // moved into the closure and subsequently used by the closure,
1285 // in order to populate our used_mut set.
1286 match **aggregate_kind {
1287 AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
1288 let BorrowCheckResult { used_mut_upvars, .. } =
1289 self.infcx.tcx.mir_borrowck(def_id);
1290 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1291 for field in used_mut_upvars {
1292 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1295 AggregateKind::Adt(..)
1296 | AggregateKind::Array(..)
1297 | AggregateKind::Tuple { .. } => (),
1300 for operand in operands {
1301 self.consume_operand(location, (operand, span), flow_state);
1307 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1308 let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1309 // We have three possibilities here:
1310 // a. We are modifying something through a mut-ref
1311 // b. We are modifying something that is local to our parent
1312 // c. Current body is a nested closure, and we are modifying path starting from
1313 // a Place captured by our parent closure.
1315 // Handle (c), the path being modified is exactly the path captured by our parent
1316 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1317 this.used_mut_upvars.push(field);
1321 for (place_ref, proj) in place.iter_projections().rev() {
1323 if proj == ProjectionElem::Deref {
1324 match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1325 // We aren't modifying a variable directly
1326 ty::Ref(_, _, hir::Mutability::Mut) => return,
1333 if let Some(field) = this.is_upvar_field_projection(place_ref) {
1334 this.used_mut_upvars.push(field);
1340 this.used_mut.insert(place.local);
1343 // This relies on the current way that by-value
1344 // captures of a closure are copied/moved directly
1345 // when generating MIR.
1347 Operand::Move(place) | Operand::Copy(place) => {
1348 match place.as_local() {
1349 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1350 if self.body.local_decls[local].ty.is_mutable_ptr() {
1351 // The variable will be marked as mutable by the borrow.
1354 // This is an edge case where we have a `move` closure
1355 // inside a non-move closure, and the inner closure
1356 // contains a mutation:
1359 // || { move || { i += 1; }; };
1361 // In this case our usual strategy of assuming that the
1362 // variable will be captured by mutable reference is
1363 // wrong, since `i` can be copied into the inner
1364 // closure from a shared reference.
1366 // As such we have to search for the local that this
1367 // capture comes from and mark it as being used as mut.
1369 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1370 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1371 &self.move_data.inits[init_index]
1373 bug!("temporary should be initialized exactly once")
1376 let InitLocation::Statement(loc) = init.location else {
1377 bug!("temporary initialized in arguments")
1380 let body = self.body;
1381 let bbd = &body[loc.block];
1382 let stmt = &bbd.statements[loc.statement_index];
1383 debug!("temporary assigned in: stmt={:?}", stmt);
1385 if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, source))) = stmt.kind
1387 propagate_closure_used_mut_place(self, source);
1390 "closures should only capture user variables \
1391 or references to user variables"
1395 _ => 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(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(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 #[instrument(level = "debug", skip(self))]
1453 fn check_for_invalidation_at_exit(
1456 borrow: &BorrowData<'tcx>,
1459 let place = borrow.borrowed_place;
1460 let mut root_place = PlaceRef { local: place.local, projection: &[] };
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 let (might_be_alive, will_be_dropped) =
1469 if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1470 // Thread-locals might be dropped after the function exits
1471 // We have to dereference the outer reference because
1472 // borrows don't conflict behind shared references.
1473 root_place.projection = TyCtxtConsts::DEREF_PROJECTION;
1476 (false, self.locals_are_invalidated_at_exit)
1479 if !will_be_dropped {
1480 debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
1484 let sd = if might_be_alive { Deep } else { Shallow(None) };
1486 if places_conflict::borrow_conflicts_with_place(
1493 places_conflict::PlaceConflictBias::Overlap,
1495 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1496 // FIXME: should be talking about the region lifetime instead
1497 // of just a span here.
1498 let span = self.infcx.tcx.sess.source_map().end_point(span);
1499 self.report_borrowed_value_does_not_live_long_enough(
1508 /// Reports an error if this is a borrow of local data.
1509 /// This is called for all Yield expressions on movable generators
1510 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1511 debug!("check_for_local_borrow({:?})", borrow);
1513 if borrow_of_local_data(borrow.borrowed_place) {
1514 let err = self.cannot_borrow_across_generator_yield(
1515 self.retrieve_borrow_spans(borrow).var_or_use(),
1519 self.buffer_error(err);
1523 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1524 // Two-phase borrow support: For each activation that is newly
1525 // generated at this statement, check if it interferes with
1527 let borrow_set = self.borrow_set.clone();
1528 for &borrow_index in borrow_set.activations_at_location(location) {
1529 let borrow = &borrow_set[borrow_index];
1531 // only mutable borrows should be 2-phase
1532 assert!(match borrow.kind {
1533 BorrowKind::Shared | BorrowKind::Shallow => false,
1534 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1539 (borrow.borrowed_place, span),
1540 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1541 LocalMutationIsAllowed::No,
1544 // We do not need to call `check_if_path_or_subpath_is_moved`
1545 // again, as we already called it when we made the
1546 // initial reservation.
1550 fn check_if_reassignment_to_immutable_state(
1554 place_span: (Place<'tcx>, Span),
1555 flow_state: &Flows<'cx, 'tcx>,
1557 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1559 // Check if any of the initializations of `local` have happened yet:
1560 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1561 // And, if so, report an error.
1562 let init = &self.move_data.inits[init_index];
1563 let span = init.span(&self.body);
1564 self.report_illegal_reassignment(location, place_span, span, place_span.0);
1568 fn check_if_full_path_is_moved(
1571 desired_action: InitializationRequiringAction,
1572 place_span: (PlaceRef<'tcx>, Span),
1573 flow_state: &Flows<'cx, 'tcx>,
1575 let maybe_uninits = &flow_state.uninits;
1579 // 1. Move of `a.b.c`, use of `a.b.c`
1580 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1581 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1582 // partial initialization support, one might have `a.x`
1583 // initialized but not `a.b`.
1587 // 4. Move of `a.b.c`, use of `a.b.d`
1588 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1589 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1590 // must have been initialized for the use to be sound.
1591 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1593 // The dataflow tracks shallow prefixes distinctly (that is,
1594 // field-accesses on P distinctly from P itself), in order to
1595 // track substructure initialization separately from the whole
1598 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1599 // which we have a MovePath is `a.b`, then that means that the
1600 // initialization state of `a.b` is all we need to inspect to
1601 // know if `a.b.c` is valid (and from that we infer that the
1602 // dereference and `.d` access is also valid, since we assume
1603 // `a.b.c` is assigned a reference to an initialized and
1604 // well-formed record structure.)
1606 // Therefore, if we seek out the *closest* prefix for which we
1607 // have a MovePath, that should capture the initialization
1608 // state for the place scenario.
1610 // This code covers scenarios 1, 2, and 3.
1612 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1613 let (prefix, mpi) = self.move_path_closest_to(place_span.0);
1614 if maybe_uninits.contains(mpi) {
1615 self.report_use_of_moved_or_uninitialized(
1618 (prefix, place_span.0, place_span.1),
1621 } // Only query longest prefix with a MovePath, not further
1622 // ancestors; dataflow recurs on children when parents
1623 // move (to support partial (re)inits).
1625 // (I.e., querying parents breaks scenario 7; but may want
1626 // to do such a query based on partial-init feature-gate.)
1629 /// Subslices correspond to multiple move paths, so we iterate through the
1630 /// elements of the base array. For each element we check
1632 /// * Does this element overlap with our slice.
1633 /// * Is any part of it uninitialized.
1634 fn check_if_subslice_element_is_moved(
1637 desired_action: InitializationRequiringAction,
1638 place_span: (PlaceRef<'tcx>, Span),
1639 maybe_uninits: &ChunkedBitSet<MovePathIndex>,
1643 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1644 let move_paths = &self.move_data.move_paths;
1646 let root_path = &move_paths[mpi];
1647 for (child_mpi, child_move_path) in root_path.children(move_paths) {
1648 let last_proj = child_move_path.place.projection.last().unwrap();
1649 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
1650 debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
1652 if (from..to).contains(offset) {
1654 self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
1655 maybe_uninits.contains(mpi)
1658 if let Some(uninit_child) = uninit_child {
1659 self.report_use_of_moved_or_uninitialized(
1662 (place_span.0, place_span.0, place_span.1),
1665 return; // don't bother finding other problems.
1673 fn check_if_path_or_subpath_is_moved(
1676 desired_action: InitializationRequiringAction,
1677 place_span: (PlaceRef<'tcx>, Span),
1678 flow_state: &Flows<'cx, 'tcx>,
1680 let maybe_uninits = &flow_state.uninits;
1684 // 1. Move of `a.b.c`, use of `a` or `a.b`
1685 // partial initialization support, one might have `a.x`
1686 // initialized but not `a.b`.
1687 // 2. All bad scenarios from `check_if_full_path_is_moved`
1691 // 3. Move of `a.b.c`, use of `a.b.d`
1692 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1693 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1694 // must have been initialized for the use to be sound.
1695 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1697 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1699 if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
1700 place_span.0.last_projection()
1702 let place_ty = place_base.ty(self.body(), self.infcx.tcx);
1703 if let ty::Array(..) = place_ty.ty.kind() {
1704 self.check_if_subslice_element_is_moved(
1707 (place_base, place_span.1),
1716 // A move of any shallow suffix of `place` also interferes
1717 // with an attempt to use `place`. This is scenario 3 above.
1719 // (Distinct from handling of scenarios 1+2+4 above because
1720 // `place` does not interfere with suffixes of its prefixes,
1721 // e.g., `a.b.c` does not interfere with `a.b.d`)
1723 // This code covers scenario 1.
1725 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1726 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1727 let uninit_mpi = self
1729 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
1731 if let Some(uninit_mpi) = uninit_mpi {
1732 self.report_use_of_moved_or_uninitialized(
1735 (place_span.0, place_span.0, place_span.1),
1738 return; // don't bother finding other problems.
1743 /// Currently MoveData does not store entries for all places in
1744 /// the input MIR. For example it will currently filter out
1745 /// places that are Copy; thus we do not track places of shared
1746 /// reference type. This routine will walk up a place along its
1747 /// prefixes, searching for a foundational place that *is*
1748 /// tracked in the MoveData.
1750 /// An Err result includes a tag indicated why the search failed.
1751 /// Currently this can only occur if the place is built off of a
1752 /// static variable, as we do not track those in the MoveData.
1753 fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
1754 match self.move_data.rev_lookup.find(place) {
1755 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
1756 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
1758 LookupResult::Parent(None) => panic!("should have move path for every Local"),
1762 fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
1763 // If returns None, then there is no move path corresponding
1764 // to a direct owner of `place` (which means there is nothing
1765 // that borrowck tracks for its analysis).
1767 match self.move_data.rev_lookup.find(place) {
1768 LookupResult::Parent(_) => None,
1769 LookupResult::Exact(mpi) => Some(mpi),
1773 fn check_if_assigned_path_is_moved(
1776 (place, span): (Place<'tcx>, Span),
1777 flow_state: &Flows<'cx, 'tcx>,
1779 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1781 // None case => assigning to `x` does not require `x` be initialized.
1782 for (place_base, elem) in place.iter_projections().rev() {
1784 ProjectionElem::Index(_/*operand*/) |
1785 ProjectionElem::ConstantIndex { .. } |
1786 // assigning to P[i] requires P to be valid.
1787 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1788 // assigning to (P->variant) is okay if assigning to `P` is okay
1790 // FIXME: is this true even if P is an adt with a dtor?
1793 // assigning to (*P) requires P to be initialized
1794 ProjectionElem::Deref => {
1795 self.check_if_full_path_is_moved(
1796 location, InitializationRequiringAction::Use,
1797 (place_base, span), flow_state);
1798 // (base initialized; no need to
1803 ProjectionElem::Subslice { .. } => {
1804 panic!("we don't allow assignments to subslices, location: {:?}",
1808 ProjectionElem::Field(..) => {
1809 // if type of `P` has a dtor, then
1810 // assigning to `P.f` requires `P` itself
1811 // be already initialized
1812 let tcx = self.infcx.tcx;
1813 let base_ty = place_base.ty(self.body(), tcx).ty;
1814 match base_ty.kind() {
1815 ty::Adt(def, _) if def.has_dtor(tcx) => {
1816 self.check_if_path_or_subpath_is_moved(
1817 location, InitializationRequiringAction::Assignment,
1818 (place_base, span), flow_state);
1820 // (base initialized; no need to
1825 // Once `let s; s.x = V; read(s.x);`,
1826 // is allowed, remove this match arm.
1827 ty::Adt(..) | ty::Tuple(..) => {
1828 check_parent_of_field(self, location, place_base, span, flow_state);
1830 // rust-lang/rust#21232, #54499, #54986: during period where we reject
1831 // partial initialization, do not complain about unnecessary `mut` on
1832 // an attempt to do a partial initialization.
1833 self.used_mut.insert(place.local);
1842 fn check_parent_of_field<'cx, 'tcx>(
1843 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1845 base: PlaceRef<'tcx>,
1847 flow_state: &Flows<'cx, '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 Some(mpi) = this.move_path_for_place(prefix) else { continue };
1888 if maybe_uninits.contains(mpi) {
1890 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1891 shortest_uninit_seen,
1894 shortest_uninit_seen = Some((prefix, mpi));
1896 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1900 if let Some((prefix, mpi)) = shortest_uninit_seen {
1901 // Check for a reassignment into an uninitialized field of a union (for example,
1902 // after a move out). In this case, do not report an error here. There is an
1903 // exception, if this is the first assignment into the union (that is, there is
1904 // no move out from an earlier location) then this is an attempt at initialization
1905 // of the union - we should error in that case.
1906 let tcx = this.infcx.tcx;
1907 if base.ty(this.body(), tcx).ty.is_union() {
1908 if this.move_data.path_map[mpi].iter().any(|moi| {
1909 this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
1915 this.report_use_of_moved_or_uninitialized(
1917 InitializationRequiringAction::PartialAssignment,
1918 (prefix, base, span),
1925 /// Checks the permissions for the given place and read or write kind
1927 /// Returns `true` if an error is reported.
1928 fn check_access_permissions(
1930 (place, span): (Place<'tcx>, Span),
1932 is_local_mutation_allowed: LocalMutationIsAllowed,
1933 flow_state: &Flows<'cx, 'tcx>,
1937 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1938 place, kind, is_local_mutation_allowed
1945 Reservation(WriteKind::MutableBorrow(
1946 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
1948 | Write(WriteKind::MutableBorrow(
1949 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
1951 let is_local_mutation_allowed = match borrow_kind {
1952 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1953 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1954 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1956 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1958 self.add_used_mut(root_place, flow_state);
1962 error_access = AccessKind::MutableBorrow;
1963 the_place_err = place_err;
1967 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1968 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1970 self.add_used_mut(root_place, flow_state);
1974 error_access = AccessKind::Mutate;
1975 the_place_err = place_err;
1982 | WriteKind::StorageDeadOrDrop
1983 | WriteKind::MutableBorrow(BorrowKind::Shared)
1984 | WriteKind::MutableBorrow(BorrowKind::Shallow),
1988 | WriteKind::StorageDeadOrDrop
1989 | WriteKind::MutableBorrow(BorrowKind::Shared)
1990 | WriteKind::MutableBorrow(BorrowKind::Shallow),
1992 if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err()
1993 && !self.has_buffered_errors()
1995 // rust-lang/rust#46908: In pure NLL mode this code path should be
1996 // unreachable, but we use `delay_span_bug` because we can hit this when
1997 // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
1998 // enabled. We don't want to ICE for that case, as other errors will have
1999 // been emitted (#52262).
2000 self.infcx.tcx.sess.delay_span_bug(
2003 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2011 // permission checks are done at Reservation point.
2017 | BorrowKind::Mut { .. }
2018 | BorrowKind::Shared
2019 | BorrowKind::Shallow,
2023 // Access authorized
2028 // rust-lang/rust#21232, #54986: during period where we reject
2029 // partial initialization, do not complain about mutability
2030 // errors except for actual mutation (as opposed to an attempt
2031 // to do a partial initialization).
2032 let previously_initialized =
2033 self.is_local_ever_initialized(place.local, flow_state).is_some();
2035 // at this point, we have set up the error reporting state.
2036 if previously_initialized {
2037 self.report_mutability_error(place, span, the_place_err, error_access, location);
2044 fn is_local_ever_initialized(
2047 flow_state: &Flows<'cx, 'tcx>,
2048 ) -> Option<InitIndex> {
2049 let mpi = self.move_data.rev_lookup.find_local(local);
2050 let ii = &self.move_data.init_path_map[mpi];
2052 if flow_state.ever_inits.contains(index) {
2059 /// Adds the place into the used mutable variables set
2060 fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2062 RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2063 // If the local may have been initialized, and it is now currently being
2064 // mutated, then it is justified to be annotated with the `mut`
2065 // keyword, since the mutation may be a possible reassignment.
2066 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2067 && self.is_local_ever_initialized(local, flow_state).is_some()
2069 self.used_mut.insert(local);
2074 place_projection: _,
2075 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2079 place_projection: place_projection @ [.., _],
2080 is_local_mutation_allowed: _,
2082 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2084 projection: place_projection,
2086 self.used_mut_upvars.push(field);
2092 /// Whether this value can be written or borrowed mutably.
2093 /// Returns the root place if the place passed in is a projection.
2096 place: PlaceRef<'tcx>,
2097 is_local_mutation_allowed: LocalMutationIsAllowed,
2098 ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2099 debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2100 match place.last_projection() {
2102 let local = &self.body.local_decls[place.local];
2103 match local.mutability {
2104 Mutability::Not => match is_local_mutation_allowed {
2105 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2106 place_local: place.local,
2107 place_projection: place.projection,
2108 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2110 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2111 place_local: place.local,
2112 place_projection: place.projection,
2113 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2115 LocalMutationIsAllowed::No => Err(place),
2117 Mutability::Mut => Ok(RootPlace {
2118 place_local: place.local,
2119 place_projection: place.projection,
2120 is_local_mutation_allowed,
2124 Some((place_base, elem)) => {
2126 ProjectionElem::Deref => {
2127 let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2129 // Check the kind of deref to decide
2130 match base_ty.kind() {
2131 ty::Ref(_, _, mutbl) => {
2133 // Shared borrowed data is never mutable
2134 hir::Mutability::Not => Err(place),
2135 // Mutably borrowed data is mutable, but only if we have a
2136 // unique path to the `&mut`
2137 hir::Mutability::Mut => {
2138 let mode = match self.is_upvar_field_projection(place) {
2139 Some(field) if self.upvars[field.index()].by_ref => {
2140 is_local_mutation_allowed
2142 _ => LocalMutationIsAllowed::Yes,
2145 self.is_mutable(place_base, mode)
2149 ty::RawPtr(tnm) => {
2151 // `*const` raw pointers are not mutable
2152 hir::Mutability::Not => Err(place),
2153 // `*mut` raw pointers are always mutable, regardless of
2154 // context. The users have to check by themselves.
2155 hir::Mutability::Mut => Ok(RootPlace {
2156 place_local: place.local,
2157 place_projection: place.projection,
2158 is_local_mutation_allowed,
2162 // `Box<T>` owns its content, so mutable if its location is mutable
2163 _ if base_ty.is_box() => {
2164 self.is_mutable(place_base, is_local_mutation_allowed)
2166 // Deref should only be for reference, pointers or boxes
2167 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2170 // All other projections are owned by their base path, so mutable if
2171 // base path is mutable
2172 ProjectionElem::Field(..)
2173 | ProjectionElem::Index(..)
2174 | ProjectionElem::ConstantIndex { .. }
2175 | ProjectionElem::Subslice { .. }
2176 | ProjectionElem::Downcast(..) => {
2177 let upvar_field_projection = self.is_upvar_field_projection(place);
2178 if let Some(field) = upvar_field_projection {
2179 let upvar = &self.upvars[field.index()];
2181 "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2182 place={:?}, place_base={:?}",
2183 upvar, is_local_mutation_allowed, place, place_base
2185 match (upvar.place.mutability, is_local_mutation_allowed) {
2188 LocalMutationIsAllowed::No
2189 | LocalMutationIsAllowed::ExceptUpvars,
2191 (Mutability::Not, LocalMutationIsAllowed::Yes)
2192 | (Mutability::Mut, _) => {
2193 // Subtle: this is an upvar
2194 // reference, so it looks like
2195 // `self.foo` -- we want to double
2196 // check that the location `*self`
2197 // is mutable (i.e., this is not a
2198 // `Fn` closure). But if that
2199 // check succeeds, we want to
2200 // *blame* the mutability on
2201 // `place` (that is,
2202 // `self.foo`). This is used to
2203 // propagate the info about
2204 // whether mutability declarations
2205 // are used outwards, so that we register
2206 // the outer variable as mutable. Otherwise a
2207 // test like this fails to record the `mut`
2211 // fn foo<F: FnOnce()>(_f: F) { }
2213 // let var = Vec::new();
2220 self.is_mutable(place_base, is_local_mutation_allowed)?;
2222 place_local: place.local,
2223 place_projection: place.projection,
2224 is_local_mutation_allowed,
2229 self.is_mutable(place_base, is_local_mutation_allowed)
2237 /// If `place` is a field projection, and the field is being projected from a closure type,
2238 /// then returns the index of the field being projected. Note that this closure will always
2239 /// be `self` in the current MIR, because that is the only time we directly access the fields
2240 /// of a closure type.
2241 fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> {
2242 path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2247 use rustc_errors::ErrorGuaranteed;
2251 pub struct BorrowckErrors<'tcx> {
2252 /// This field keeps track of move errors that are to be reported for given move indices.
2254 /// There are situations where many errors can be reported for a single move out (see #53807)
2255 /// and we want only the best of those errors.
2257 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
2258 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
2259 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
2260 /// all move errors have been reported, any diagnostics in this map are added to the buffer
2263 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
2264 /// when errors in the map are being re-added to the error buffer so that errors with the
2265 /// same primary span come out in a consistent order.
2266 buffered_move_errors:
2267 BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorGuaranteed>)>,
2268 /// Diagnostics to be reported buffer.
2269 buffered: Vec<Diagnostic>,
2270 /// Set to Some if we emit an error during borrowck
2271 tainted_by_errors: Option<ErrorGuaranteed>,
2274 impl BorrowckErrors<'_> {
2275 pub fn new() -> Self {
2277 buffered_move_errors: BTreeMap::new(),
2278 buffered: Default::default(),
2279 tainted_by_errors: None,
2283 // FIXME(eddyb) this is a suboptimal API because `tainted_by_errors` is
2284 // set before any emission actually happens (weakening the guarantee).
2285 pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorGuaranteed>) {
2286 self.tainted_by_errors = Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
2287 t.buffer(&mut self.buffered);
2290 pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) {
2291 t.buffer(&mut self.buffered);
2294 pub fn set_tainted_by_errors(&mut self) {
2295 self.tainted_by_errors = Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
2299 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
2300 pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorGuaranteed>) {
2301 self.errors.buffer_error(t);
2304 pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) {
2305 self.errors.buffer_non_error_diag(t);
2308 pub fn buffer_move_error(
2310 move_out_indices: Vec<MoveOutIndex>,
2311 place_and_err: (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorGuaranteed>),
2313 if let Some((_, diag)) =
2314 self.errors.buffered_move_errors.insert(move_out_indices, place_and_err)
2316 // Cancel the old diagnostic so we don't ICE
2324 pub fn emit_errors(&mut self) -> Option<ErrorGuaranteed> {
2325 // Buffer any move errors that we collected and de-duplicated.
2326 for (_, (_, diag)) in std::mem::take(&mut self.errors.buffered_move_errors) {
2327 // We have already set tainted for this error, so just buffer it.
2328 diag.buffer(&mut self.errors.buffered);
2331 if !self.errors.buffered.is_empty() {
2332 self.errors.buffered.sort_by_key(|diag| diag.sort_span);
2334 for mut diag in self.errors.buffered.drain(..) {
2335 self.infcx.tcx.sess.diagnostic().emit_diagnostic(&mut diag);
2339 self.errors.tainted_by_errors
2342 pub fn has_buffered_errors(&self) -> bool {
2343 self.errors.buffered.is_empty()
2346 pub fn has_move_error(
2348 move_out_indices: &[MoveOutIndex],
2349 ) -> Option<&(PlaceRef<'tcx>, DiagnosticBuilder<'cx, ErrorGuaranteed>)> {
2350 self.errors.buffered_move_errors.get(move_out_indices)
2355 /// The degree of overlap between 2 places for borrow-checking.
2357 /// The places might partially overlap - in this case, we give
2358 /// up and say that they might conflict. This occurs when
2359 /// different fields of a union are borrowed. For example,
2360 /// if `u` is a union, we have no way of telling how disjoint
2361 /// `u.a.x` and `a.b.y` are.
2363 /// The places have the same type, and are either completely disjoint
2364 /// or equal - i.e., they can't "partially" overlap as can occur with
2365 /// unions. This is the "base case" on which we recur for extensions
2368 /// The places are disjoint, so we know all extensions of them
2369 /// will also be disjoint.