1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
3 #![feature(bool_to_option)]
4 #![feature(box_patterns)]
5 #![feature(crate_visibility_modifier)]
7 #![feature(min_specialization)]
8 #![feature(stmt_expr_attributes)]
9 #![feature(trusted_step)]
10 #![feature(try_blocks)]
11 #![recursion_limit = "256"]
12 #![cfg_attr(not(bootstrap), allow(rustc::potential_query_instability))]
15 extern crate rustc_middle;
19 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
20 use rustc_data_structures::graph::dominators::Dominators;
21 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorReported};
23 use rustc_hir::def_id::LocalDefId;
25 use rustc_index::bit_set::BitSet;
26 use rustc_index::vec::IndexVec;
27 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
28 use rustc_middle::mir::{
29 traversal, Body, ClearCrossCrate, Local, Location, Mutability, Operand, Place, PlaceElem,
30 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::{MUTABLE_BORROW_RESERVATION_CONFLICT, UNUSED_MUT};
38 use rustc_span::{Span, Symbol, DUMMY_SP};
41 use smallvec::SmallVec;
42 use std::cell::RefCell;
43 use std::collections::BTreeMap;
47 use rustc_mir_dataflow::impls::{
48 EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces,
50 use rustc_mir_dataflow::move_paths::{InitIndex, MoveOutIndex, MovePathIndex};
51 use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveData, MoveError};
52 use rustc_mir_dataflow::Analysis;
53 use rustc_mir_dataflow::MoveDataParamEnv;
55 use self::diagnostics::{AccessKind, RegionName};
56 use self::location::LocationTable;
57 use self::prefixes::PrefixSet;
60 use self::path_utils::*;
64 mod constraint_generation;
72 mod member_constraints;
81 mod universal_regions;
84 // A public API provided for the Rust compiler consumers.
87 use borrow_set::{BorrowData, BorrowSet};
88 use dataflow::{BorrowIndex, BorrowckFlowState as Flows, BorrowckResults, Borrows};
89 use nll::{PoloniusOutput, ToRegionVid};
90 use place_ext::PlaceExt;
91 use places_conflict::{places_conflict, PlaceConflictBias};
92 use region_infer::RegionInferenceContext;
94 // FIXME(eddyb) perhaps move this somewhere more centrally.
97 place: CapturedPlace<'tcx>,
99 /// If true, the capture is behind a reference.
103 const DEREF_PROJECTION: &[PlaceElem<'_>; 1] = &[ProjectionElem::Deref];
105 pub fn provide(providers: &mut Providers) {
106 *providers = Providers {
107 mir_borrowck: |tcx, did| {
108 if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
109 tcx.mir_borrowck_const_arg(def)
111 mir_borrowck(tcx, ty::WithOptConstParam::unknown(did))
114 mir_borrowck_const_arg: |tcx, (did, param_did)| {
115 mir_borrowck(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
121 fn mir_borrowck<'tcx>(
123 def: ty::WithOptConstParam<LocalDefId>,
124 ) -> &'tcx BorrowCheckResult<'tcx> {
125 let (input_body, promoted) = tcx.mir_promoted(def);
126 debug!("run query mir_borrowck: {}", tcx.def_path_str(def.did.to_def_id()));
128 let opt_closure_req = tcx.infer_ctxt().with_opaque_type_inference(def.did).enter(|infcx| {
129 let input_body: &Body<'_> = &input_body.borrow();
130 let promoted: &IndexVec<_, _> = &promoted.borrow();
131 do_mir_borrowck(&infcx, input_body, promoted, false).0
133 debug!("mir_borrowck done");
135 tcx.arena.alloc(opt_closure_req)
138 /// Perform the actual borrow checking.
140 /// If `return_body_with_facts` is true, then return the body with non-erased
141 /// region ids on which the borrow checking was performed together with Polonius
143 #[instrument(skip(infcx, input_body, input_promoted), level = "debug")]
144 fn do_mir_borrowck<'a, 'tcx>(
145 infcx: &InferCtxt<'a, 'tcx>,
146 input_body: &Body<'tcx>,
147 input_promoted: &IndexVec<Promoted, Body<'tcx>>,
148 return_body_with_facts: bool,
149 ) -> (BorrowCheckResult<'tcx>, Option<Box<BodyWithBorrowckFacts<'tcx>>>) {
150 let def = input_body.source.with_opt_param().as_local().unwrap();
155 let param_env = tcx.param_env(def.did);
156 let id = tcx.hir().local_def_id_to_hir_id(def.did);
158 let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
159 for var_debug_info in &input_body.var_debug_info {
160 if let VarDebugInfoContents::Place(place) = var_debug_info.value {
161 if let Some(local) = place.as_local() {
162 if let Some(prev_name) = local_names[local] {
163 if var_debug_info.name != prev_name {
165 var_debug_info.source_info.span,
166 "local {:?} has many names (`{}` vs `{}`)",
173 local_names[local] = Some(var_debug_info.name);
178 // Gather the upvars of a closure, if any.
179 let tables = tcx.typeck_opt_const_arg(def);
180 if let Some(ErrorReported) = tables.tainted_by_errors {
181 infcx.set_tainted_by_errors();
183 let upvars: Vec<_> = tables
184 .closure_min_captures_flattened(def.did.to_def_id())
185 .map(|captured_place| {
186 let capture = captured_place.info.capture_kind;
187 let by_ref = match capture {
188 ty::UpvarCapture::ByValue => false,
189 ty::UpvarCapture::ByRef(..) => true,
191 Upvar { place: captured_place.clone(), by_ref }
195 // Replace all regions with fresh inference variables. This
196 // requires first making our own copy of the MIR. This copy will
197 // be modified (in place) to contain non-lexical lifetimes. It
198 // will have a lifetime tied to the inference context.
199 let mut body_owned = input_body.clone();
200 let mut promoted = input_promoted.clone();
202 nll::replace_regions_in_mir(infcx, param_env, &mut body_owned, &mut promoted);
203 let body = &body_owned; // no further changes
205 let location_table_owned = LocationTable::new(body);
206 let location_table = &location_table_owned;
208 let mut errors_buffer = Vec::new();
209 let (move_data, move_errors): (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>) =
210 match MoveData::gather_moves(&body, tcx, param_env) {
211 Ok(move_data) => (move_data, Vec::new()),
212 Err((move_data, move_errors)) => (move_data, move_errors),
214 let promoted_errors = promoted
216 .map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env)));
218 let mdpe = MoveDataParamEnv { move_data, param_env };
220 let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe)
221 .into_engine(tcx, &body)
222 .pass_name("borrowck")
223 .iterate_to_fixpoint()
224 .into_results_cursor(&body);
226 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
228 Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
230 let use_polonius = return_body_with_facts || infcx.tcx.sess.opts.debugging_opts.polonius;
232 // Compute non-lexical lifetimes.
240 } = nll::compute_regions(
254 // Dump MIR results into a file, if that is enabled. This let us
255 // write unit-tests, as well as helping with debugging.
256 nll::dump_mir_results(infcx, &body, ®ioncx, &opt_closure_req);
258 // We also have a `#[rustc_regions]` annotation that causes us to dump
260 nll::dump_annotation(
269 // The various `flow_*` structures can be large. We drop `flow_inits` here
270 // so it doesn't overlap with the others below. This reduces peak memory
271 // usage significantly on some benchmarks.
274 let regioncx = Rc::new(regioncx);
276 let flow_borrows = Borrows::new(tcx, body, ®ioncx, &borrow_set)
277 .into_engine(tcx, body)
278 .pass_name("borrowck")
279 .iterate_to_fixpoint();
280 let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &mdpe)
281 .into_engine(tcx, body)
282 .pass_name("borrowck")
283 .iterate_to_fixpoint();
284 let flow_ever_inits = EverInitializedPlaces::new(tcx, body, &mdpe)
285 .into_engine(tcx, body)
286 .pass_name("borrowck")
287 .iterate_to_fixpoint();
289 let movable_generator = !matches!(
291 Node::Expr(&hir::Expr {
292 kind: hir::ExprKind::Closure(.., Some(hir::Movability::Static)),
297 for (idx, move_data_results) in promoted_errors {
298 let promoted_body = &promoted[idx];
300 if let Err((move_data, move_errors)) = move_data_results {
301 let mut promoted_mbcx = MirBorrowckCtxt {
305 move_data: &move_data,
306 location_table, // no need to create a real one for the promoted, it is not used
308 fn_self_span_reported: Default::default(),
309 locals_are_invalidated_at_exit,
310 access_place_error_reported: Default::default(),
311 reservation_error_reported: Default::default(),
312 reservation_warnings: Default::default(),
313 move_error_reported: BTreeMap::new(),
314 uninitialized_error_reported: Default::default(),
316 tainted_by_errors: false,
317 regioncx: regioncx.clone(),
318 used_mut: Default::default(),
319 used_mut_upvars: SmallVec::new(),
320 borrow_set: Rc::clone(&borrow_set),
321 dominators: Dominators::dummy(), // not used
323 local_names: IndexVec::from_elem(None, &promoted_body.local_decls),
324 region_names: RefCell::default(),
325 next_region_name: RefCell::new(1),
326 polonius_output: None,
328 promoted_mbcx.report_move_errors(move_errors);
329 errors_buffer = promoted_mbcx.errors_buffer;
333 let dominators = body.dominators();
335 let mut mbcx = MirBorrowckCtxt {
339 move_data: &mdpe.move_data,
342 locals_are_invalidated_at_exit,
343 fn_self_span_reported: Default::default(),
344 access_place_error_reported: Default::default(),
345 reservation_error_reported: Default::default(),
346 reservation_warnings: Default::default(),
347 move_error_reported: BTreeMap::new(),
348 uninitialized_error_reported: Default::default(),
350 tainted_by_errors: false,
351 regioncx: Rc::clone(®ioncx),
352 used_mut: Default::default(),
353 used_mut_upvars: SmallVec::new(),
354 borrow_set: Rc::clone(&borrow_set),
358 region_names: RefCell::default(),
359 next_region_name: RefCell::new(1),
363 // Compute and report region errors, if any.
364 mbcx.report_region_errors(nll_errors);
366 let results = BorrowckResults {
367 ever_inits: flow_ever_inits,
368 uninits: flow_uninits,
369 borrows: flow_borrows,
372 mbcx.report_move_errors(move_errors);
374 rustc_mir_dataflow::visit_results(
376 traversal::reverse_postorder(body).map(|(bb, _)| bb),
381 // Convert any reservation warnings into lints.
382 let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
383 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
384 let mut initial_diag = mbcx.report_conflicting_borrow(location, (place, span), bk, &borrow);
386 let scope = mbcx.body.source_info(location).scope;
387 let lint_root = match &mbcx.body.source_scopes[scope].local_data {
388 ClearCrossCrate::Set(data) => data.lint_root,
392 // Span and message don't matter; we overwrite them below anyway
393 mbcx.infcx.tcx.struct_span_lint_hir(
394 MUTABLE_BORROW_RESERVATION_CONFLICT,
398 let mut diag = lint.build("");
400 diag.message = initial_diag.styled_message().clone();
401 diag.span = initial_diag.span.clone();
403 mbcx.buffer_error(diag);
406 initial_diag.cancel();
409 // For each non-user used mutable variable, check if it's been assigned from
410 // a user-declared local. If so, then put that local into the used_mut set.
411 // Note that this set is expected to be small - only upvars from closures
412 // would have a chance of erroneously adding non-user-defined mutable vars
414 let temporary_used_locals: FxHashSet<Local> = mbcx
417 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
420 // For the remaining unused locals that are marked as mutable, we avoid linting any that
421 // were never initialized. These locals may have been removed as unreachable code; or will be
422 // linted as unused variables.
423 let unused_mut_locals =
424 mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
425 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
427 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
428 let used_mut = std::mem::take(&mut mbcx.used_mut);
429 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
430 let local_decl = &mbcx.body.local_decls[local];
431 let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data {
432 ClearCrossCrate::Set(data) => data.lint_root,
436 // Skip over locals that begin with an underscore or have no name
437 match mbcx.local_names[local] {
439 if name.as_str().starts_with('_') {
446 let span = local_decl.source_info.span;
447 if span.desugaring_kind().is_some() {
448 // If the `mut` arises as part of a desugaring, we should ignore it.
452 tcx.struct_span_lint_hir(UNUSED_MUT, lint_root, span, |lint| {
453 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
454 lint.build("variable does not need to be mutable")
455 .span_suggestion_short(
459 Applicability::MachineApplicable,
465 // Buffer any move errors that we collected and de-duplicated.
466 for (_, (_, diag)) in std::mem::take(&mut mbcx.move_error_reported) {
467 mbcx.buffer_error(diag);
470 if !mbcx.errors_buffer.is_empty() {
471 mbcx.errors_buffer.sort_by_key(|diag| diag.sort_span);
473 for diag in mbcx.errors_buffer.drain(..) {
474 mbcx.infcx.tcx.sess.diagnostic().emit_diagnostic(&diag);
478 let result = BorrowCheckResult {
479 concrete_opaque_types: opaque_type_values,
480 closure_requirements: opt_closure_req,
481 used_mut_upvars: mbcx.used_mut_upvars,
482 tainted_by_errors: mbcx.tainted_by_errors,
485 let body_with_facts = if return_body_with_facts {
486 let output_facts = mbcx.polonius_output.expect("Polonius output was not computed");
487 Some(Box::new(BodyWithBorrowckFacts {
489 input_facts: *polonius_input.expect("Polonius input facts were not generated"),
491 location_table: location_table_owned,
497 debug!("do_mir_borrowck: result = {:#?}", result);
499 (result, body_with_facts)
502 /// A `Body` with information computed by the borrow checker. This struct is
503 /// intended to be consumed by compiler consumers.
505 /// We need to include the MIR body here because the region identifiers must
506 /// match the ones in the Polonius facts.
507 pub struct BodyWithBorrowckFacts<'tcx> {
508 /// A mir body that contains region identifiers.
509 pub body: Body<'tcx>,
510 /// Polonius input facts.
511 pub input_facts: AllFacts,
512 /// Polonius output facts.
513 pub output_facts: Rc<self::nll::PoloniusOutput>,
514 /// The table that maps Polonius points to locations in the table.
515 pub location_table: LocationTable,
518 struct MirBorrowckCtxt<'cx, 'tcx> {
519 infcx: &'cx InferCtxt<'cx, 'tcx>,
520 param_env: ParamEnv<'tcx>,
521 body: &'cx Body<'tcx>,
522 move_data: &'cx MoveData<'tcx>,
524 /// Map from MIR `Location` to `LocationIndex`; created
525 /// when MIR borrowck begins.
526 location_table: &'cx LocationTable,
528 movable_generator: bool,
529 /// This keeps track of whether local variables are free-ed when the function
530 /// exits even without a `StorageDead`, which appears to be the case for
533 /// I'm not sure this is the right approach - @eddyb could you try and
535 locals_are_invalidated_at_exit: bool,
536 /// This field keeps track of when borrow errors are reported in the access_place function
537 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
538 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
539 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
541 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
542 /// This field keeps track of when borrow conflict errors are reported
543 /// for reservations, so that we don't report seemingly duplicate
544 /// errors for corresponding activations.
546 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
547 // but it is currently inconvenient to track down the `BorrowIndex`
548 // at the time we detect and report a reservation error.
549 reservation_error_reported: FxHashSet<Place<'tcx>>,
550 /// This fields keeps track of the `Span`s that we have
551 /// used to report extra information for `FnSelfUse`, to avoid
552 /// unnecessarily verbose errors.
553 fn_self_span_reported: FxHashSet<Span>,
554 /// Migration warnings to be reported for #56254. We delay reporting these
555 /// so that we can suppress the warning if there's a corresponding error
556 /// for the activation of the borrow.
557 reservation_warnings:
558 FxHashMap<BorrowIndex, (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)>,
559 /// This field keeps track of move errors that are to be reported for given move indices.
561 /// There are situations where many errors can be reported for a single move out (see #53807)
562 /// and we want only the best of those errors.
564 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
565 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
566 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
567 /// all move errors have been reported, any diagnostics in this map are added to the buffer
570 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
571 /// when errors in the map are being re-added to the error buffer so that errors with the
572 /// same primary span come out in a consistent order.
573 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'cx>)>,
574 /// This field keeps track of errors reported in the checking of uninitialized variables,
575 /// so that we don't report seemingly duplicate errors.
576 uninitialized_error_reported: FxHashSet<PlaceRef<'tcx>>,
577 /// Errors to be reported buffer
578 errors_buffer: Vec<Diagnostic>,
579 /// Set to true if we emit an error during borrowck
580 tainted_by_errors: bool,
581 /// This field keeps track of all the local variables that are declared mut and are mutated.
582 /// Used for the warning issued by an unused mutable local variable.
583 used_mut: FxHashSet<Local>,
584 /// If the function we're checking is a closure, then we'll need to report back the list of
585 /// mutable upvars that have been used. This field keeps track of them.
586 used_mut_upvars: SmallVec<[Field; 8]>,
587 /// Region inference context. This contains the results from region inference and lets us e.g.
588 /// find out which CFG points are contained in each borrow region.
589 regioncx: Rc<RegionInferenceContext<'tcx>>,
591 /// The set of borrows extracted from the MIR
592 borrow_set: Rc<BorrowSet<'tcx>>,
594 /// Dominators for MIR
595 dominators: Dominators<BasicBlock>,
597 /// Information about upvars not necessarily preserved in types or MIR
598 upvars: Vec<Upvar<'tcx>>,
600 /// Names of local (user) variables (extracted from `var_debug_info`).
601 local_names: IndexVec<Local, Option<Symbol>>,
603 /// Record the region names generated for each region in the given
604 /// MIR def so that we can reuse them later in help/error messages.
605 region_names: RefCell<FxHashMap<RegionVid, RegionName>>,
607 /// The counter for generating new region names.
608 next_region_name: RefCell<usize>,
610 /// Results of Polonius analysis.
611 polonius_output: Option<Rc<PoloniusOutput>>,
615 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
616 // 2. loans made in overlapping scopes do not conflict
617 // 3. assignments do not affect things loaned out as immutable
618 // 4. moves do not affect things loaned out in any way
619 impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
620 type FlowState = Flows<'cx, 'tcx>;
622 fn visit_statement_before_primary_effect(
624 flow_state: &Flows<'cx, 'tcx>,
625 stmt: &'cx Statement<'tcx>,
628 debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state);
629 let span = stmt.source_info.span;
631 self.check_activations(location, span, flow_state);
634 StatementKind::Assign(box (lhs, ref rhs)) => {
635 self.consume_rvalue(location, (rhs, span), flow_state);
637 self.mutate_place(location, (*lhs, span), Shallow(None), flow_state);
639 StatementKind::FakeRead(box (_, ref place)) => {
640 // Read for match doesn't access any memory and is used to
641 // assert that a place is safe and live. So we don't have to
642 // do any checks here.
644 // FIXME: Remove check that the place is initialized. This is
645 // needed for now because matches don't have never patterns yet.
646 // So this is the only place we prevent
650 self.check_if_path_or_subpath_is_moved(
652 InitializationRequiringAction::Use,
653 (place.as_ref(), span),
657 StatementKind::SetDiscriminant { place, variant_index: _ } => {
658 self.mutate_place(location, (**place, span), Shallow(None), flow_state);
660 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
665 "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
669 | StatementKind::Coverage(..)
670 | StatementKind::AscribeUserType(..)
671 | StatementKind::Retag { .. }
672 | StatementKind::StorageLive(..) => {
673 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
676 StatementKind::StorageDead(local) => {
679 (Place::from(*local), span),
680 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
681 LocalMutationIsAllowed::Yes,
688 fn visit_terminator_before_primary_effect(
690 flow_state: &Flows<'cx, 'tcx>,
691 term: &'cx Terminator<'tcx>,
694 debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
695 let span = term.source_info.span;
697 self.check_activations(loc, span, flow_state);
700 TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => {
701 self.consume_operand(loc, (discr, span), flow_state);
703 TerminatorKind::Drop { place, target: _, unwind: _ } => {
705 "visit_terminator_drop \
706 loc: {:?} term: {:?} place: {:?} span: {:?}",
707 loc, term, place, span
713 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
714 LocalMutationIsAllowed::Yes,
718 TerminatorKind::DropAndReplace {
720 value: ref new_value,
724 self.mutate_place(loc, (drop_place, span), Deep, flow_state);
725 self.consume_operand(loc, (new_value, span), flow_state);
727 TerminatorKind::Call {
735 self.consume_operand(loc, (func, span), flow_state);
737 self.consume_operand(loc, (arg, span), flow_state);
739 if let Some((dest, _ /*bb*/)) = *destination {
740 self.mutate_place(loc, (dest, span), Deep, flow_state);
743 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
744 self.consume_operand(loc, (cond, span), flow_state);
745 use rustc_middle::mir::AssertKind;
746 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
747 self.consume_operand(loc, (len, span), flow_state);
748 self.consume_operand(loc, (index, span), flow_state);
752 TerminatorKind::Yield { ref value, resume: _, resume_arg, drop: _ } => {
753 self.consume_operand(loc, (value, span), flow_state);
754 self.mutate_place(loc, (resume_arg, span), Deep, flow_state);
757 TerminatorKind::InlineAsm {
767 InlineAsmOperand::In { reg: _, ref value } => {
768 self.consume_operand(loc, (value, span), flow_state);
770 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
771 if let Some(place) = place {
772 self.mutate_place(loc, (place, span), Shallow(None), flow_state);
775 InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
776 self.consume_operand(loc, (in_value, span), flow_state);
777 if let Some(out_place) = out_place {
786 InlineAsmOperand::Const { value: _ }
787 | InlineAsmOperand::SymFn { value: _ }
788 | InlineAsmOperand::SymStatic { def_id: _ } => {}
793 TerminatorKind::Goto { target: _ }
794 | TerminatorKind::Abort
795 | TerminatorKind::Unreachable
796 | TerminatorKind::Resume
797 | TerminatorKind::Return
798 | TerminatorKind::GeneratorDrop
799 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
800 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
801 // no data used, thus irrelevant to borrowck
806 fn visit_terminator_after_primary_effect(
808 flow_state: &Flows<'cx, 'tcx>,
809 term: &'cx Terminator<'tcx>,
812 let span = term.source_info.span;
815 TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
816 if self.movable_generator {
817 // Look for any active borrows to locals
818 let borrow_set = self.borrow_set.clone();
819 for i in flow_state.borrows.iter() {
820 let borrow = &borrow_set[i];
821 self.check_for_local_borrow(borrow, span);
826 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
827 // Returning from the function implicitly kills storage for all locals and statics.
828 // Often, the storage will already have been killed by an explicit
829 // StorageDead, but we don't always emit those (notably on unwind paths),
830 // so this "extra check" serves as a kind of backup.
831 let borrow_set = self.borrow_set.clone();
832 for i in flow_state.borrows.iter() {
833 let borrow = &borrow_set[i];
834 self.check_for_invalidation_at_exit(loc, borrow, span);
838 TerminatorKind::Abort
839 | TerminatorKind::Assert { .. }
840 | TerminatorKind::Call { .. }
841 | TerminatorKind::Drop { .. }
842 | TerminatorKind::DropAndReplace { .. }
843 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
844 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
845 | TerminatorKind::Goto { .. }
846 | TerminatorKind::SwitchInt { .. }
847 | TerminatorKind::Unreachable
848 | TerminatorKind::InlineAsm { .. } => {}
853 use self::AccessDepth::{Deep, Shallow};
854 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
856 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
857 enum ArtificialField {
862 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
864 /// From the RFC: "A *shallow* access means that the immediate
865 /// fields reached at P are accessed, but references or pointers
866 /// found within are not dereferenced. Right now, the only access
867 /// that is shallow is an assignment like `x = ...;`, which would
868 /// be a *shallow write* of `x`."
869 Shallow(Option<ArtificialField>),
871 /// From the RFC: "A *deep* access means that all data reachable
872 /// through the given place may be invalidated or accesses by
876 /// Access is Deep only when there is a Drop implementation that
877 /// can reach the data behind the reference.
881 /// Kind of access to a value: read or write
882 /// (For informational purposes only)
883 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
885 /// From the RFC: "A *read* means that the existing data may be
886 /// read, but will not be changed."
889 /// From the RFC: "A *write* means that the data may be mutated to
890 /// new values or otherwise invalidated (for example, it could be
891 /// de-initialized, as in a move operation).
894 /// For two-phase borrows, we distinguish a reservation (which is treated
895 /// like a Read) from an activation (which is treated like a write), and
896 /// each of those is furthermore distinguished from Reads/Writes above.
897 Reservation(WriteKind),
898 Activation(WriteKind, BorrowIndex),
901 /// Kind of read access to a value
902 /// (For informational purposes only)
903 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
909 /// Kind of write access to a value
910 /// (For informational purposes only)
911 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
914 MutableBorrow(BorrowKind),
919 /// When checking permissions for a place access, this flag is used to indicate that an immutable
920 /// local place can be mutated.
922 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
923 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
924 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
925 // `is_declared_mutable()`.
926 // - Take flow state into consideration in `is_assignable()` for local variables.
927 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
928 enum LocalMutationIsAllowed {
930 /// We want use of immutable upvars to cause a "write to immutable upvar"
931 /// error, not an "reassignment" error.
936 #[derive(Copy, Clone, Debug)]
937 enum InitializationRequiringAction {
945 struct RootPlace<'tcx> {
947 place_projection: &'tcx [PlaceElem<'tcx>],
948 is_local_mutation_allowed: LocalMutationIsAllowed,
951 impl InitializationRequiringAction {
952 fn as_noun(self) -> &'static str {
954 InitializationRequiringAction::Borrow => "borrow",
955 InitializationRequiringAction::MatchOn => "use", // no good noun
956 InitializationRequiringAction::Use => "use",
957 InitializationRequiringAction::Assignment => "assign",
958 InitializationRequiringAction::PartialAssignment => "assign to part",
962 fn as_verb_in_past_tense(self) -> &'static str {
964 InitializationRequiringAction::Borrow => "borrowed",
965 InitializationRequiringAction::MatchOn => "matched on",
966 InitializationRequiringAction::Use => "used",
967 InitializationRequiringAction::Assignment => "assigned",
968 InitializationRequiringAction::PartialAssignment => "partially assigned",
973 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
974 fn body(&self) -> &'cx Body<'tcx> {
978 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
979 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
980 /// place is initialized and (b) it is not borrowed in some way that would prevent this
983 /// Returns `true` if an error is reported.
987 place_span: (Place<'tcx>, Span),
988 kind: (AccessDepth, ReadOrWrite),
989 is_local_mutation_allowed: LocalMutationIsAllowed,
990 flow_state: &Flows<'cx, 'tcx>,
994 if let Activation(_, borrow_index) = rw {
995 if self.reservation_error_reported.contains(&place_span.0) {
997 "skipping access_place for activation of invalid reservation \
998 place: {:?} borrow_index: {:?}",
999 place_span.0, borrow_index
1005 // Check is_empty() first because it's the common case, and doing that
1006 // way we avoid the clone() call.
1007 if !self.access_place_error_reported.is_empty()
1008 && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
1011 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
1017 let mutability_error = self.check_access_permissions(
1020 is_local_mutation_allowed,
1024 let conflict_error =
1025 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
1027 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
1028 // Suppress this warning when there's an error being emitted for the
1029 // same borrow: fixing the error is likely to fix the warning.
1030 self.reservation_warnings.remove(&borrow_idx);
1033 if conflict_error || mutability_error {
1034 debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
1036 self.set_tainted_by_errors();
1037 self.access_place_error_reported.insert((place_span.0, place_span.1));
1041 fn check_access_for_conflict(
1044 place_span: (Place<'tcx>, Span),
1047 flow_state: &Flows<'cx, 'tcx>,
1050 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1051 location, place_span, sd, rw,
1054 let mut error_reported = false;
1055 let tcx = self.infcx.tcx;
1056 let body = self.body;
1057 let borrow_set = self.borrow_set.clone();
1059 // Use polonius output if it has been enabled.
1060 let polonius_output = self.polonius_output.clone();
1061 let borrows_in_scope = if let Some(polonius) = &polonius_output {
1062 let location = self.location_table.start_index(location);
1063 Either::Left(polonius.errors_at(location).iter().copied())
1065 Either::Right(flow_state.borrows.iter())
1068 each_borrow_involving_path(
1076 |this, borrow_index, borrow| match (rw, borrow.kind) {
1077 // Obviously an activation is compatible with its own
1078 // reservation (or even prior activating uses of same
1079 // borrow); so don't check if they interfere.
1081 // NOTE: *reservations* do conflict with themselves;
1082 // thus aren't injecting unsoundenss w/ this check.)
1083 (Activation(_, activating), _) if activating == borrow_index => {
1085 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1086 skipping {:?} b/c activation of same borrow_index",
1090 (borrow_index, borrow),
1095 (Read(_), BorrowKind::Shared | BorrowKind::Shallow)
1097 Read(ReadKind::Borrow(BorrowKind::Shallow)),
1098 BorrowKind::Unique | BorrowKind::Mut { .. },
1099 ) => Control::Continue,
1101 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1102 // Handled by initialization checks.
1106 (Read(kind), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
1107 // Reading from mere reservations of mutable-borrows is OK.
1108 if !is_active(&this.dominators, borrow, location) {
1109 assert!(allow_two_phase_borrow(borrow.kind));
1110 return Control::Continue;
1113 error_reported = true;
1117 .report_use_while_mutably_borrowed(location, place_span, borrow);
1118 this.buffer_error(err);
1120 ReadKind::Borrow(bk) => {
1122 this.report_conflicting_borrow(location, place_span, bk, borrow);
1123 this.buffer_error(err);
1130 Reservation(WriteKind::MutableBorrow(bk)),
1131 BorrowKind::Shallow | BorrowKind::Shared,
1132 ) if { tcx.migrate_borrowck() && this.borrow_set.contains(&location) } => {
1133 let bi = this.borrow_set.get_index_of(&location).unwrap();
1135 "recording invalid reservation of place: {:?} with \
1136 borrow index {:?} as warning",
1139 // rust-lang/rust#56254 - This was previously permitted on
1140 // the 2018 edition so we emit it as a warning. We buffer
1141 // these sepately so that we only emit a warning if borrow
1142 // checking was otherwise successful.
1143 this.reservation_warnings
1144 .insert(bi, (place_span.0, place_span.1, location, bk, borrow.clone()));
1146 // Don't suppress actual errors.
1150 (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1152 Reservation(..) => {
1154 "recording invalid reservation of \
1158 this.reservation_error_reported.insert(place_span.0);
1160 Activation(_, activating) => {
1162 "observing check_place for activation of \
1163 borrow_index: {:?}",
1167 Read(..) | Write(..) => {}
1170 error_reported = true;
1172 WriteKind::MutableBorrow(bk) => {
1174 this.report_conflicting_borrow(location, place_span, bk, borrow);
1175 this.buffer_error(err);
1177 WriteKind::StorageDeadOrDrop => this
1178 .report_borrowed_value_does_not_live_long_enough(
1184 WriteKind::Mutate => {
1185 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1187 WriteKind::Move => {
1188 this.report_move_out_while_borrowed(location, place_span, borrow)
1202 place_span: (Place<'tcx>, Span),
1204 flow_state: &Flows<'cx, 'tcx>,
1206 // Write of P[i] or *P requires P init'd.
1207 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1209 // Special case: you can assign an immutable local variable
1210 // (e.g., `x = ...`) so long as it has never been initialized
1211 // before (at this point in the flow).
1212 if let Some(local) = place_span.0.as_local() {
1213 if let Mutability::Not = self.body.local_decls[local].mutability {
1214 // check for reassignments to immutable local variables
1215 self.check_if_reassignment_to_immutable_state(
1216 location, local, place_span, flow_state,
1222 // Otherwise, use the normal access permission rules.
1226 (kind, Write(WriteKind::Mutate)),
1227 LocalMutationIsAllowed::No,
1235 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1236 flow_state: &Flows<'cx, 'tcx>,
1239 Rvalue::Ref(_ /*rgn*/, bk, place) => {
1240 let access_kind = match bk {
1241 BorrowKind::Shallow => {
1242 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1244 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1245 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1246 let wk = WriteKind::MutableBorrow(bk);
1247 if allow_two_phase_borrow(bk) {
1248 (Deep, Reservation(wk))
1259 LocalMutationIsAllowed::No,
1263 let action = if bk == BorrowKind::Shallow {
1264 InitializationRequiringAction::MatchOn
1266 InitializationRequiringAction::Borrow
1269 self.check_if_path_or_subpath_is_moved(
1272 (place.as_ref(), span),
1277 Rvalue::AddressOf(mutability, place) => {
1278 let access_kind = match mutability {
1279 Mutability::Mut => (
1281 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1282 allow_two_phase_borrow: false,
1285 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1292 LocalMutationIsAllowed::No,
1296 self.check_if_path_or_subpath_is_moved(
1298 InitializationRequiringAction::Borrow,
1299 (place.as_ref(), span),
1304 Rvalue::ThreadLocalRef(_) => {}
1306 Rvalue::Use(ref operand)
1307 | Rvalue::Repeat(ref operand, _)
1308 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1309 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/)
1310 | Rvalue::ShallowInitBox(ref operand, _ /*ty*/) => {
1311 self.consume_operand(location, (operand, span), flow_state)
1314 Rvalue::Len(place) | Rvalue::Discriminant(place) => {
1315 let af = match *rvalue {
1316 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1317 Rvalue::Discriminant(..) => None,
1318 _ => unreachable!(),
1323 (Shallow(af), Read(ReadKind::Copy)),
1324 LocalMutationIsAllowed::No,
1327 self.check_if_path_or_subpath_is_moved(
1329 InitializationRequiringAction::Use,
1330 (place.as_ref(), span),
1335 Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2))
1336 | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => {
1337 self.consume_operand(location, (operand1, span), flow_state);
1338 self.consume_operand(location, (operand2, span), flow_state);
1341 Rvalue::NullaryOp(_op, _ty) => {
1342 // nullary ops take no dynamic input; no borrowck effect.
1345 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1346 // We need to report back the list of mutable upvars that were
1347 // moved into the closure and subsequently used by the closure,
1348 // in order to populate our used_mut set.
1349 match **aggregate_kind {
1350 AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
1351 let BorrowCheckResult { used_mut_upvars, .. } =
1352 self.infcx.tcx.mir_borrowck(def_id.expect_local());
1353 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1354 for field in used_mut_upvars {
1355 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1358 AggregateKind::Adt(..)
1359 | AggregateKind::Array(..)
1360 | AggregateKind::Tuple { .. } => (),
1363 for operand in operands {
1364 self.consume_operand(location, (operand, span), flow_state);
1370 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1371 let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1372 // We have three possibilities here:
1373 // a. We are modifying something through a mut-ref
1374 // b. We are modifying something that is local to our parent
1375 // c. Current body is a nested closure, and we are modifying path starting from
1376 // a Place captured by our parent closure.
1378 // Handle (c), the path being modified is exactly the path captured by our parent
1379 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1380 this.used_mut_upvars.push(field);
1384 for (place_ref, proj) in place.iter_projections().rev() {
1386 if proj == ProjectionElem::Deref {
1387 match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1388 // We aren't modifying a variable directly
1389 ty::Ref(_, _, hir::Mutability::Mut) => return,
1396 if let Some(field) = this.is_upvar_field_projection(place_ref) {
1397 this.used_mut_upvars.push(field);
1403 this.used_mut.insert(place.local);
1406 // This relies on the current way that by-value
1407 // captures of a closure are copied/moved directly
1408 // when generating MIR.
1410 Operand::Move(place) | Operand::Copy(place) => {
1411 match place.as_local() {
1412 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1413 if self.body.local_decls[local].ty.is_mutable_ptr() {
1414 // The variable will be marked as mutable by the borrow.
1417 // This is an edge case where we have a `move` closure
1418 // inside a non-move closure, and the inner closure
1419 // contains a mutation:
1422 // || { move || { i += 1; }; };
1424 // In this case our usual strategy of assuming that the
1425 // variable will be captured by mutable reference is
1426 // wrong, since `i` can be copied into the inner
1427 // closure from a shared reference.
1429 // As such we have to search for the local that this
1430 // capture comes from and mark it as being used as mut.
1432 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1433 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1434 &self.move_data.inits[init_index]
1436 bug!("temporary should be initialized exactly once")
1439 let InitLocation::Statement(loc) = init.location else {
1440 bug!("temporary initialized in arguments")
1443 let body = self.body;
1444 let bbd = &body[loc.block];
1445 let stmt = &bbd.statements[loc.statement_index];
1446 debug!("temporary assigned in: stmt={:?}", stmt);
1448 if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, source))) = stmt.kind
1450 propagate_closure_used_mut_place(self, source);
1453 "closures should only capture user variables \
1454 or references to user variables"
1458 _ => propagate_closure_used_mut_place(self, place),
1461 Operand::Constant(..) => {}
1468 (operand, span): (&'cx Operand<'tcx>, Span),
1469 flow_state: &Flows<'cx, 'tcx>,
1472 Operand::Copy(place) => {
1473 // copy of place: check if this is "copy of frozen path"
1474 // (FIXME: see check_loans.rs)
1478 (Deep, Read(ReadKind::Copy)),
1479 LocalMutationIsAllowed::No,
1483 // Finally, check if path was already moved.
1484 self.check_if_path_or_subpath_is_moved(
1486 InitializationRequiringAction::Use,
1487 (place.as_ref(), span),
1491 Operand::Move(place) => {
1492 // move of place: check if this is move of already borrowed path
1496 (Deep, Write(WriteKind::Move)),
1497 LocalMutationIsAllowed::Yes,
1501 // Finally, check if path was already moved.
1502 self.check_if_path_or_subpath_is_moved(
1504 InitializationRequiringAction::Use,
1505 (place.as_ref(), span),
1509 Operand::Constant(_) => {}
1513 /// Checks whether a borrow of this place is invalidated when the function
1515 fn check_for_invalidation_at_exit(
1518 borrow: &BorrowData<'tcx>,
1521 debug!("check_for_invalidation_at_exit({:?})", borrow);
1522 let place = borrow.borrowed_place;
1523 let mut root_place = PlaceRef { local: place.local, projection: &[] };
1525 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1526 // we just know that all locals are dropped at function exit (otherwise
1527 // we'll have a memory leak) and assume that all statics have a destructor.
1529 // FIXME: allow thread-locals to borrow other thread locals?
1531 let (might_be_alive, will_be_dropped) =
1532 if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1533 // Thread-locals might be dropped after the function exits
1534 // We have to dereference the outer reference because
1535 // borrows don't conflict behind shared references.
1536 root_place.projection = DEREF_PROJECTION;
1539 (false, self.locals_are_invalidated_at_exit)
1542 if !will_be_dropped {
1543 debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
1547 let sd = if might_be_alive { Deep } else { Shallow(None) };
1549 if places_conflict::borrow_conflicts_with_place(
1556 places_conflict::PlaceConflictBias::Overlap,
1558 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1559 // FIXME: should be talking about the region lifetime instead
1560 // of just a span here.
1561 let span = self.infcx.tcx.sess.source_map().end_point(span);
1562 self.report_borrowed_value_does_not_live_long_enough(
1571 /// Reports an error if this is a borrow of local data.
1572 /// This is called for all Yield expressions on movable generators
1573 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1574 debug!("check_for_local_borrow({:?})", borrow);
1576 if borrow_of_local_data(borrow.borrowed_place) {
1577 let err = self.cannot_borrow_across_generator_yield(
1578 self.retrieve_borrow_spans(borrow).var_or_use(),
1582 self.buffer_error(err);
1586 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1587 // Two-phase borrow support: For each activation that is newly
1588 // generated at this statement, check if it interferes with
1590 let borrow_set = self.borrow_set.clone();
1591 for &borrow_index in borrow_set.activations_at_location(location) {
1592 let borrow = &borrow_set[borrow_index];
1594 // only mutable borrows should be 2-phase
1595 assert!(match borrow.kind {
1596 BorrowKind::Shared | BorrowKind::Shallow => false,
1597 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1602 (borrow.borrowed_place, span),
1603 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1604 LocalMutationIsAllowed::No,
1607 // We do not need to call `check_if_path_or_subpath_is_moved`
1608 // again, as we already called it when we made the
1609 // initial reservation.
1613 fn check_if_reassignment_to_immutable_state(
1617 place_span: (Place<'tcx>, Span),
1618 flow_state: &Flows<'cx, 'tcx>,
1620 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1622 // Check if any of the initializiations of `local` have happened yet:
1623 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1624 // And, if so, report an error.
1625 let init = &self.move_data.inits[init_index];
1626 let span = init.span(&self.body);
1627 self.report_illegal_reassignment(location, place_span, span, place_span.0);
1631 fn check_if_full_path_is_moved(
1634 desired_action: InitializationRequiringAction,
1635 place_span: (PlaceRef<'tcx>, Span),
1636 flow_state: &Flows<'cx, 'tcx>,
1638 let maybe_uninits = &flow_state.uninits;
1642 // 1. Move of `a.b.c`, use of `a.b.c`
1643 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1644 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1645 // partial initialization support, one might have `a.x`
1646 // initialized but not `a.b`.
1650 // 4. Move of `a.b.c`, use of `a.b.d`
1651 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1652 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1653 // must have been initialized for the use to be sound.
1654 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1656 // The dataflow tracks shallow prefixes distinctly (that is,
1657 // field-accesses on P distinctly from P itself), in order to
1658 // track substructure initialization separately from the whole
1661 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1662 // which we have a MovePath is `a.b`, then that means that the
1663 // initialization state of `a.b` is all we need to inspect to
1664 // know if `a.b.c` is valid (and from that we infer that the
1665 // dereference and `.d` access is also valid, since we assume
1666 // `a.b.c` is assigned a reference to an initialized and
1667 // well-formed record structure.)
1669 // Therefore, if we seek out the *closest* prefix for which we
1670 // have a MovePath, that should capture the initialization
1671 // state for the place scenario.
1673 // This code covers scenarios 1, 2, and 3.
1675 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1676 let (prefix, mpi) = self.move_path_closest_to(place_span.0);
1677 if maybe_uninits.contains(mpi) {
1678 self.report_use_of_moved_or_uninitialized(
1681 (prefix, place_span.0, place_span.1),
1684 } // Only query longest prefix with a MovePath, not further
1685 // ancestors; dataflow recurs on children when parents
1686 // move (to support partial (re)inits).
1688 // (I.e., querying parents breaks scenario 7; but may want
1689 // to do such a query based on partial-init feature-gate.)
1692 /// Subslices correspond to multiple move paths, so we iterate through the
1693 /// elements of the base array. For each element we check
1695 /// * Does this element overlap with our slice.
1696 /// * Is any part of it uninitialized.
1697 fn check_if_subslice_element_is_moved(
1700 desired_action: InitializationRequiringAction,
1701 place_span: (PlaceRef<'tcx>, Span),
1702 maybe_uninits: &BitSet<MovePathIndex>,
1706 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1707 let move_paths = &self.move_data.move_paths;
1709 let root_path = &move_paths[mpi];
1710 for (child_mpi, child_move_path) in root_path.children(move_paths) {
1711 let last_proj = child_move_path.place.projection.last().unwrap();
1712 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
1713 debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
1715 if (from..to).contains(offset) {
1717 self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
1718 maybe_uninits.contains(mpi)
1721 if let Some(uninit_child) = uninit_child {
1722 self.report_use_of_moved_or_uninitialized(
1725 (place_span.0, place_span.0, place_span.1),
1728 return; // don't bother finding other problems.
1736 fn check_if_path_or_subpath_is_moved(
1739 desired_action: InitializationRequiringAction,
1740 place_span: (PlaceRef<'tcx>, Span),
1741 flow_state: &Flows<'cx, 'tcx>,
1743 let maybe_uninits = &flow_state.uninits;
1747 // 1. Move of `a.b.c`, use of `a` or `a.b`
1748 // partial initialization support, one might have `a.x`
1749 // initialized but not `a.b`.
1750 // 2. All bad scenarios from `check_if_full_path_is_moved`
1754 // 3. Move of `a.b.c`, use of `a.b.d`
1755 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1756 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1757 // must have been initialized for the use to be sound.
1758 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1760 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1762 if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
1763 place_span.0.last_projection()
1765 let place_ty = place_base.ty(self.body(), self.infcx.tcx);
1766 if let ty::Array(..) = place_ty.ty.kind() {
1767 self.check_if_subslice_element_is_moved(
1770 (place_base, place_span.1),
1779 // A move of any shallow suffix of `place` also interferes
1780 // with an attempt to use `place`. This is scenario 3 above.
1782 // (Distinct from handling of scenarios 1+2+4 above because
1783 // `place` does not interfere with suffixes of its prefixes,
1784 // e.g., `a.b.c` does not interfere with `a.b.d`)
1786 // This code covers scenario 1.
1788 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1789 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1790 let uninit_mpi = self
1792 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
1794 if let Some(uninit_mpi) = uninit_mpi {
1795 self.report_use_of_moved_or_uninitialized(
1798 (place_span.0, place_span.0, place_span.1),
1801 return; // don't bother finding other problems.
1806 /// Currently MoveData does not store entries for all places in
1807 /// the input MIR. For example it will currently filter out
1808 /// places that are Copy; thus we do not track places of shared
1809 /// reference type. This routine will walk up a place along its
1810 /// prefixes, searching for a foundational place that *is*
1811 /// tracked in the MoveData.
1813 /// An Err result includes a tag indicated why the search failed.
1814 /// Currently this can only occur if the place is built off of a
1815 /// static variable, as we do not track those in the MoveData.
1816 fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
1817 match self.move_data.rev_lookup.find(place) {
1818 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
1819 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
1821 LookupResult::Parent(None) => panic!("should have move path for every Local"),
1825 fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
1826 // If returns None, then there is no move path corresponding
1827 // to a direct owner of `place` (which means there is nothing
1828 // that borrowck tracks for its analysis).
1830 match self.move_data.rev_lookup.find(place) {
1831 LookupResult::Parent(_) => None,
1832 LookupResult::Exact(mpi) => Some(mpi),
1836 fn check_if_assigned_path_is_moved(
1839 (place, span): (Place<'tcx>, Span),
1840 flow_state: &Flows<'cx, 'tcx>,
1842 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1844 // None case => assigning to `x` does not require `x` be initialized.
1845 for (place_base, elem) in place.iter_projections().rev() {
1847 ProjectionElem::Index(_/*operand*/) |
1848 ProjectionElem::ConstantIndex { .. } |
1849 // assigning to P[i] requires P to be valid.
1850 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1851 // assigning to (P->variant) is okay if assigning to `P` is okay
1853 // FIXME: is this true even if P is an adt with a dtor?
1856 // assigning to (*P) requires P to be initialized
1857 ProjectionElem::Deref => {
1858 self.check_if_full_path_is_moved(
1859 location, InitializationRequiringAction::Use,
1860 (place_base, span), flow_state);
1861 // (base initialized; no need to
1866 ProjectionElem::Subslice { .. } => {
1867 panic!("we don't allow assignments to subslices, location: {:?}",
1871 ProjectionElem::Field(..) => {
1872 // if type of `P` has a dtor, then
1873 // assigning to `P.f` requires `P` itself
1874 // be already initialized
1875 let tcx = self.infcx.tcx;
1876 let base_ty = place_base.ty(self.body(), tcx).ty;
1877 match base_ty.kind() {
1878 ty::Adt(def, _) if def.has_dtor(tcx) => {
1879 self.check_if_path_or_subpath_is_moved(
1880 location, InitializationRequiringAction::Assignment,
1881 (place_base, span), flow_state);
1883 // (base initialized; no need to
1888 // Once `let s; s.x = V; read(s.x);`,
1889 // is allowed, remove this match arm.
1890 ty::Adt(..) | ty::Tuple(..) => {
1891 check_parent_of_field(self, location, place_base, span, flow_state);
1893 // rust-lang/rust#21232, #54499, #54986: during period where we reject
1894 // partial initialization, do not complain about unnecessary `mut` on
1895 // an attempt to do a partial initialization.
1896 self.used_mut.insert(place.local);
1905 fn check_parent_of_field<'cx, 'tcx>(
1906 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1908 base: PlaceRef<'tcx>,
1910 flow_state: &Flows<'cx, 'tcx>,
1912 // rust-lang/rust#21232: Until Rust allows reads from the
1913 // initialized parts of partially initialized structs, we
1914 // will, starting with the 2018 edition, reject attempts
1915 // to write to structs that are not fully initialized.
1917 // In other words, *until* we allow this:
1919 // 1. `let mut s; s.x = Val; read(s.x);`
1921 // we will for now disallow this:
1923 // 2. `let mut s; s.x = Val;`
1927 // 3. `let mut s = ...; drop(s); s.x=Val;`
1929 // This does not use check_if_path_or_subpath_is_moved,
1930 // because we want to *allow* reinitializations of fields:
1931 // e.g., want to allow
1933 // `let mut s = ...; drop(s.x); s.x=Val;`
1935 // This does not use check_if_full_path_is_moved on
1936 // `base`, because that would report an error about the
1937 // `base` as a whole, but in this scenario we *really*
1938 // want to report an error about the actual thing that was
1939 // moved, which may be some prefix of `base`.
1941 // Shallow so that we'll stop at any dereference; we'll
1942 // report errors about issues with such bases elsewhere.
1943 let maybe_uninits = &flow_state.uninits;
1945 // Find the shortest uninitialized prefix you can reach
1946 // without going over a Deref.
1947 let mut shortest_uninit_seen = None;
1948 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1949 let mpi = match this.move_path_for_place(prefix) {
1954 if maybe_uninits.contains(mpi) {
1956 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1957 shortest_uninit_seen,
1960 shortest_uninit_seen = Some((prefix, mpi));
1962 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1966 if let Some((prefix, mpi)) = shortest_uninit_seen {
1967 // Check for a reassignment into an uninitialized field of a union (for example,
1968 // after a move out). In this case, do not report an error here. There is an
1969 // exception, if this is the first assignment into the union (that is, there is
1970 // no move out from an earlier location) then this is an attempt at initialization
1971 // of the union - we should error in that case.
1972 let tcx = this.infcx.tcx;
1973 if base.ty(this.body(), tcx).ty.is_union() {
1974 if this.move_data.path_map[mpi].iter().any(|moi| {
1975 this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
1981 this.report_use_of_moved_or_uninitialized(
1983 InitializationRequiringAction::PartialAssignment,
1984 (prefix, base, span),
1991 /// Checks the permissions for the given place and read or write kind
1993 /// Returns `true` if an error is reported.
1994 fn check_access_permissions(
1996 (place, span): (Place<'tcx>, Span),
1998 is_local_mutation_allowed: LocalMutationIsAllowed,
1999 flow_state: &Flows<'cx, 'tcx>,
2003 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
2004 place, kind, is_local_mutation_allowed
2011 Reservation(WriteKind::MutableBorrow(
2012 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
2014 | Write(WriteKind::MutableBorrow(
2015 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
2017 let is_local_mutation_allowed = match borrow_kind {
2018 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
2019 BorrowKind::Mut { .. } => is_local_mutation_allowed,
2020 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
2022 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2024 self.add_used_mut(root_place, flow_state);
2028 error_access = AccessKind::MutableBorrow;
2029 the_place_err = place_err;
2033 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
2034 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2036 self.add_used_mut(root_place, flow_state);
2040 error_access = AccessKind::Mutate;
2041 the_place_err = place_err;
2048 | WriteKind::StorageDeadOrDrop
2049 | WriteKind::MutableBorrow(BorrowKind::Shared)
2050 | WriteKind::MutableBorrow(BorrowKind::Shallow),
2054 | WriteKind::StorageDeadOrDrop
2055 | WriteKind::MutableBorrow(BorrowKind::Shared)
2056 | WriteKind::MutableBorrow(BorrowKind::Shallow),
2058 if let (Err(_), true) = (
2059 self.is_mutable(place.as_ref(), is_local_mutation_allowed),
2060 self.errors_buffer.is_empty(),
2062 // rust-lang/rust#46908: In pure NLL mode this code path should be
2063 // unreachable, but we use `delay_span_bug` because we can hit this when
2064 // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
2065 // enabled. We don't want to ICE for that case, as other errors will have
2066 // been emitted (#52262).
2067 self.infcx.tcx.sess.delay_span_bug(
2070 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2078 // permission checks are done at Reservation point.
2084 | BorrowKind::Mut { .. }
2085 | BorrowKind::Shared
2086 | BorrowKind::Shallow,
2090 // Access authorized
2095 // rust-lang/rust#21232, #54986: during period where we reject
2096 // partial initialization, do not complain about mutability
2097 // errors except for actual mutation (as opposed to an attempt
2098 // to do a partial initialization).
2099 let previously_initialized =
2100 self.is_local_ever_initialized(place.local, flow_state).is_some();
2102 // at this point, we have set up the error reporting state.
2103 if previously_initialized {
2104 self.report_mutability_error(place, span, the_place_err, error_access, location);
2111 fn is_local_ever_initialized(
2114 flow_state: &Flows<'cx, 'tcx>,
2115 ) -> Option<InitIndex> {
2116 let mpi = self.move_data.rev_lookup.find_local(local);
2117 let ii = &self.move_data.init_path_map[mpi];
2119 if flow_state.ever_inits.contains(index) {
2126 /// Adds the place into the used mutable variables set
2127 fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2129 RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2130 // If the local may have been initialized, and it is now currently being
2131 // mutated, then it is justified to be annotated with the `mut`
2132 // keyword, since the mutation may be a possible reassignment.
2133 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2134 && self.is_local_ever_initialized(local, flow_state).is_some()
2136 self.used_mut.insert(local);
2141 place_projection: _,
2142 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2146 place_projection: place_projection @ [.., _],
2147 is_local_mutation_allowed: _,
2149 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2151 projection: place_projection,
2153 self.used_mut_upvars.push(field);
2159 /// Whether this value can be written or borrowed mutably.
2160 /// Returns the root place if the place passed in is a projection.
2163 place: PlaceRef<'tcx>,
2164 is_local_mutation_allowed: LocalMutationIsAllowed,
2165 ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2166 debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2167 match place.last_projection() {
2169 let local = &self.body.local_decls[place.local];
2170 match local.mutability {
2171 Mutability::Not => match is_local_mutation_allowed {
2172 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2173 place_local: place.local,
2174 place_projection: place.projection,
2175 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2177 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2178 place_local: place.local,
2179 place_projection: place.projection,
2180 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2182 LocalMutationIsAllowed::No => Err(place),
2184 Mutability::Mut => Ok(RootPlace {
2185 place_local: place.local,
2186 place_projection: place.projection,
2187 is_local_mutation_allowed,
2191 Some((place_base, elem)) => {
2193 ProjectionElem::Deref => {
2194 let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2196 // Check the kind of deref to decide
2197 match base_ty.kind() {
2198 ty::Ref(_, _, mutbl) => {
2200 // Shared borrowed data is never mutable
2201 hir::Mutability::Not => Err(place),
2202 // Mutably borrowed data is mutable, but only if we have a
2203 // unique path to the `&mut`
2204 hir::Mutability::Mut => {
2205 let mode = match self.is_upvar_field_projection(place) {
2206 Some(field) if self.upvars[field.index()].by_ref => {
2207 is_local_mutation_allowed
2209 _ => LocalMutationIsAllowed::Yes,
2212 self.is_mutable(place_base, mode)
2216 ty::RawPtr(tnm) => {
2218 // `*const` raw pointers are not mutable
2219 hir::Mutability::Not => Err(place),
2220 // `*mut` raw pointers are always mutable, regardless of
2221 // context. The users have to check by themselves.
2222 hir::Mutability::Mut => Ok(RootPlace {
2223 place_local: place.local,
2224 place_projection: place.projection,
2225 is_local_mutation_allowed,
2229 // `Box<T>` owns its content, so mutable if its location is mutable
2230 _ if base_ty.is_box() => {
2231 self.is_mutable(place_base, is_local_mutation_allowed)
2233 // Deref should only be for reference, pointers or boxes
2234 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2237 // All other projections are owned by their base path, so mutable if
2238 // base path is mutable
2239 ProjectionElem::Field(..)
2240 | ProjectionElem::Index(..)
2241 | ProjectionElem::ConstantIndex { .. }
2242 | ProjectionElem::Subslice { .. }
2243 | ProjectionElem::Downcast(..) => {
2244 let upvar_field_projection = self.is_upvar_field_projection(place);
2245 if let Some(field) = upvar_field_projection {
2246 let upvar = &self.upvars[field.index()];
2248 "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2249 place={:?}, place_base={:?}",
2250 upvar, is_local_mutation_allowed, place, place_base
2252 match (upvar.place.mutability, is_local_mutation_allowed) {
2255 LocalMutationIsAllowed::No
2256 | LocalMutationIsAllowed::ExceptUpvars,
2258 (Mutability::Not, LocalMutationIsAllowed::Yes)
2259 | (Mutability::Mut, _) => {
2260 // Subtle: this is an upvar
2261 // reference, so it looks like
2262 // `self.foo` -- we want to double
2263 // check that the location `*self`
2264 // is mutable (i.e., this is not a
2265 // `Fn` closure). But if that
2266 // check succeeds, we want to
2267 // *blame* the mutability on
2268 // `place` (that is,
2269 // `self.foo`). This is used to
2270 // propagate the info about
2271 // whether mutability declarations
2272 // are used outwards, so that we register
2273 // the outer variable as mutable. Otherwise a
2274 // test like this fails to record the `mut`
2278 // fn foo<F: FnOnce()>(_f: F) { }
2280 // let var = Vec::new();
2287 self.is_mutable(place_base, is_local_mutation_allowed)?;
2289 place_local: place.local,
2290 place_projection: place.projection,
2291 is_local_mutation_allowed,
2296 self.is_mutable(place_base, is_local_mutation_allowed)
2304 /// If `place` is a field projection, and the field is being projected from a closure type,
2305 /// then returns the index of the field being projected. Note that this closure will always
2306 /// be `self` in the current MIR, because that is the only time we directly access the fields
2307 /// of a closure type.
2308 fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> {
2309 path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2312 pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_>) {
2313 self.tainted_by_errors = true;
2314 t.buffer(&mut self.errors_buffer);
2317 pub fn set_tainted_by_errors(&mut self) {
2318 self.tainted_by_errors = true;
2322 /// The degree of overlap between 2 places for borrow-checking.
2324 /// The places might partially overlap - in this case, we give
2325 /// up and say that they might conflict. This occurs when
2326 /// different fields of a union are borrowed. For example,
2327 /// if `u` is a union, we have no way of telling how disjoint
2328 /// `u.a.x` and `a.b.y` are.
2330 /// The places have the same type, and are either completely disjoint
2331 /// or equal - i.e., they can't "partially" overlap as can occur with
2332 /// unions. This is the "base case" on which we recur for extensions
2335 /// The places are disjoint, so we know all extensions of them
2336 /// will also be disjoint.