1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
3 #![feature(bool_to_option)]
4 #![feature(box_patterns)]
5 #![cfg_attr(bootstrap, feature(const_panic))]
6 #![feature(crate_visibility_modifier)]
7 #![feature(format_args_capture)]
8 #![feature(in_band_lifetimes)]
11 #![feature(min_specialization)]
12 #![feature(stmt_expr_attributes)]
13 #![feature(trusted_step)]
14 #![feature(try_blocks)]
15 #![recursion_limit = "256"]
18 extern crate rustc_middle;
22 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
23 use rustc_data_structures::graph::dominators::Dominators;
24 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorReported};
26 use rustc_hir::def_id::LocalDefId;
28 use rustc_index::bit_set::BitSet;
29 use rustc_index::vec::IndexVec;
30 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
31 use rustc_middle::mir::{
32 traversal, Body, ClearCrossCrate, Local, Location, Mutability, Operand, Place, PlaceElem,
33 PlaceRef, VarDebugInfoContents,
35 use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
36 use rustc_middle::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
37 use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind};
38 use rustc_middle::ty::query::Providers;
39 use rustc_middle::ty::{self, CapturedPlace, ParamEnv, RegionVid, TyCtxt};
40 use rustc_session::lint::builtin::{MUTABLE_BORROW_RESERVATION_CONFLICT, UNUSED_MUT};
41 use rustc_span::{Span, Symbol, DUMMY_SP};
44 use smallvec::SmallVec;
45 use std::cell::RefCell;
46 use std::collections::BTreeMap;
51 use rustc_mir_dataflow::impls::{
52 EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces,
54 use rustc_mir_dataflow::move_paths::{InitIndex, MoveOutIndex, MovePathIndex};
55 use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveData, MoveError};
56 use rustc_mir_dataflow::Analysis;
57 use rustc_mir_dataflow::MoveDataParamEnv;
59 use self::diagnostics::{AccessKind, RegionName};
60 use self::location::LocationTable;
61 use self::prefixes::PrefixSet;
62 use self::MutateMode::{JustWrite, WriteAndRead};
65 use self::path_utils::*;
69 mod constraint_generation;
77 mod member_constraints;
86 mod universal_regions;
89 // A public API provided for the Rust compiler consumers.
92 use borrow_set::{BorrowData, BorrowSet};
93 use dataflow::{BorrowIndex, BorrowckFlowState as Flows, BorrowckResults, Borrows};
94 use nll::{PoloniusOutput, ToRegionVid};
95 use place_ext::PlaceExt;
96 use places_conflict::{places_conflict, PlaceConflictBias};
97 use region_infer::RegionInferenceContext;
99 // FIXME(eddyb) perhaps move this somewhere more centrally.
102 place: CapturedPlace<'tcx>,
104 /// If true, the capture is behind a reference.
108 const DEREF_PROJECTION: &[PlaceElem<'_>; 1] = &[ProjectionElem::Deref];
110 pub fn provide(providers: &mut Providers) {
111 *providers = Providers {
112 mir_borrowck: |tcx, did| {
113 if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
114 tcx.mir_borrowck_const_arg(def)
116 mir_borrowck(tcx, ty::WithOptConstParam::unknown(did))
119 mir_borrowck_const_arg: |tcx, (did, param_did)| {
120 mir_borrowck(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
126 fn mir_borrowck<'tcx>(
128 def: ty::WithOptConstParam<LocalDefId>,
129 ) -> &'tcx BorrowCheckResult<'tcx> {
130 let (input_body, promoted) = tcx.mir_promoted(def);
131 debug!("run query mir_borrowck: {}", tcx.def_path_str(def.did.to_def_id()));
133 let opt_closure_req = tcx.infer_ctxt().with_opaque_type_inference(def.did).enter(|infcx| {
134 let input_body: &Body<'_> = &input_body.borrow();
135 let promoted: &IndexVec<_, _> = &promoted.borrow();
136 do_mir_borrowck(&infcx, input_body, promoted, false).0
138 debug!("mir_borrowck done");
140 tcx.arena.alloc(opt_closure_req)
143 /// Perform the actual borrow checking.
145 /// If `return_body_with_facts` is true, then return the body with non-erased
146 /// region ids on which the borrow checking was performed together with Polonius
148 #[instrument(skip(infcx, input_body, input_promoted), level = "debug")]
149 fn do_mir_borrowck<'a, 'tcx>(
150 infcx: &InferCtxt<'a, 'tcx>,
151 input_body: &Body<'tcx>,
152 input_promoted: &IndexVec<Promoted, Body<'tcx>>,
153 return_body_with_facts: bool,
154 ) -> (BorrowCheckResult<'tcx>, Option<Box<BodyWithBorrowckFacts<'tcx>>>) {
155 let def = input_body.source.with_opt_param().as_local().unwrap();
160 let param_env = tcx.param_env(def.did);
161 let id = tcx.hir().local_def_id_to_hir_id(def.did);
163 let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
164 for var_debug_info in &input_body.var_debug_info {
165 if let VarDebugInfoContents::Place(place) = var_debug_info.value {
166 if let Some(local) = place.as_local() {
167 if let Some(prev_name) = local_names[local] {
168 if var_debug_info.name != prev_name {
170 var_debug_info.source_info.span,
171 "local {:?} has many names (`{}` vs `{}`)",
178 local_names[local] = Some(var_debug_info.name);
183 // Gather the upvars of a closure, if any.
184 let tables = tcx.typeck_opt_const_arg(def);
185 if let Some(ErrorReported) = tables.tainted_by_errors {
186 infcx.set_tainted_by_errors();
188 let upvars: Vec<_> = tables
189 .closure_min_captures_flattened(def.did.to_def_id())
190 .map(|captured_place| {
191 let capture = captured_place.info.capture_kind;
192 let by_ref = match capture {
193 ty::UpvarCapture::ByValue(_) => false,
194 ty::UpvarCapture::ByRef(..) => true,
196 Upvar { place: captured_place.clone(), by_ref }
200 // Replace all regions with fresh inference variables. This
201 // requires first making our own copy of the MIR. This copy will
202 // be modified (in place) to contain non-lexical lifetimes. It
203 // will have a lifetime tied to the inference context.
204 let mut body_owned = input_body.clone();
205 let mut promoted = input_promoted.clone();
207 nll::replace_regions_in_mir(infcx, param_env, &mut body_owned, &mut promoted);
208 let body = &body_owned; // no further changes
210 let location_table_owned = LocationTable::new(body);
211 let location_table = &location_table_owned;
213 let mut errors_buffer = Vec::new();
214 let (move_data, move_errors): (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>) =
215 match MoveData::gather_moves(&body, tcx, param_env) {
216 Ok(move_data) => (move_data, Vec::new()),
217 Err((move_data, move_errors)) => (move_data, move_errors),
219 let promoted_errors = promoted
221 .map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env)));
223 let mdpe = MoveDataParamEnv { move_data, param_env };
225 let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe)
226 .into_engine(tcx, &body)
227 .pass_name("borrowck")
228 .iterate_to_fixpoint()
229 .into_results_cursor(&body);
231 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
233 Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
235 let use_polonius = return_body_with_facts || infcx.tcx.sess.opts.debugging_opts.polonius;
237 // Compute non-lexical lifetimes.
245 } = nll::compute_regions(
259 // Dump MIR results into a file, if that is enabled. This let us
260 // write unit-tests, as well as helping with debugging.
261 nll::dump_mir_results(infcx, &body, ®ioncx, &opt_closure_req);
263 // We also have a `#[rustc_regions]` annotation that causes us to dump
265 nll::dump_annotation(
274 // The various `flow_*` structures can be large. We drop `flow_inits` here
275 // so it doesn't overlap with the others below. This reduces peak memory
276 // usage significantly on some benchmarks.
279 let regioncx = Rc::new(regioncx);
281 let flow_borrows = Borrows::new(tcx, body, ®ioncx, &borrow_set)
282 .into_engine(tcx, body)
283 .pass_name("borrowck")
284 .iterate_to_fixpoint();
285 let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &mdpe)
286 .into_engine(tcx, body)
287 .pass_name("borrowck")
288 .iterate_to_fixpoint();
289 let flow_ever_inits = EverInitializedPlaces::new(tcx, body, &mdpe)
290 .into_engine(tcx, body)
291 .pass_name("borrowck")
292 .iterate_to_fixpoint();
294 let movable_generator = !matches!(
296 Node::Expr(&hir::Expr {
297 kind: hir::ExprKind::Closure(.., Some(hir::Movability::Static)),
302 for (idx, move_data_results) in promoted_errors {
303 let promoted_body = &promoted[idx];
305 if let Err((move_data, move_errors)) = move_data_results {
306 let mut promoted_mbcx = MirBorrowckCtxt {
310 move_data: &move_data,
311 location_table, // no need to create a real one for the promoted, it is not used
313 fn_self_span_reported: Default::default(),
314 locals_are_invalidated_at_exit,
315 access_place_error_reported: Default::default(),
316 reservation_error_reported: Default::default(),
317 reservation_warnings: Default::default(),
318 move_error_reported: BTreeMap::new(),
319 uninitialized_error_reported: Default::default(),
321 regioncx: regioncx.clone(),
322 used_mut: Default::default(),
323 used_mut_upvars: SmallVec::new(),
324 borrow_set: Rc::clone(&borrow_set),
325 dominators: Dominators::dummy(), // not used
327 local_names: IndexVec::from_elem(None, &promoted_body.local_decls),
328 region_names: RefCell::default(),
329 next_region_name: RefCell::new(1),
330 polonius_output: None,
332 promoted_mbcx.report_move_errors(move_errors);
333 errors_buffer = promoted_mbcx.errors_buffer;
337 let dominators = body.dominators();
339 let mut mbcx = MirBorrowckCtxt {
343 move_data: &mdpe.move_data,
346 locals_are_invalidated_at_exit,
347 fn_self_span_reported: Default::default(),
348 access_place_error_reported: Default::default(),
349 reservation_error_reported: Default::default(),
350 reservation_warnings: Default::default(),
351 move_error_reported: BTreeMap::new(),
352 uninitialized_error_reported: Default::default(),
354 regioncx: Rc::clone(®ioncx),
355 used_mut: Default::default(),
356 used_mut_upvars: SmallVec::new(),
357 borrow_set: Rc::clone(&borrow_set),
361 region_names: RefCell::default(),
362 next_region_name: RefCell::new(1),
366 // Compute and report region errors, if any.
367 mbcx.report_region_errors(nll_errors);
369 let results = BorrowckResults {
370 ever_inits: flow_ever_inits,
371 uninits: flow_uninits,
372 borrows: flow_borrows,
375 mbcx.report_move_errors(move_errors);
377 rustc_mir_dataflow::visit_results(
379 traversal::reverse_postorder(body).map(|(bb, _)| bb),
384 // Convert any reservation warnings into lints.
385 let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
386 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
387 let mut initial_diag = mbcx.report_conflicting_borrow(location, (place, span), bk, &borrow);
389 let scope = mbcx.body.source_info(location).scope;
390 let lint_root = match &mbcx.body.source_scopes[scope].local_data {
391 ClearCrossCrate::Set(data) => data.lint_root,
395 // Span and message don't matter; we overwrite them below anyway
396 mbcx.infcx.tcx.struct_span_lint_hir(
397 MUTABLE_BORROW_RESERVATION_CONFLICT,
401 let mut diag = lint.build("");
403 diag.message = initial_diag.styled_message().clone();
404 diag.span = initial_diag.span.clone();
406 diag.buffer(&mut mbcx.errors_buffer);
409 initial_diag.cancel();
412 // For each non-user used mutable variable, check if it's been assigned from
413 // a user-declared local. If so, then put that local into the used_mut set.
414 // Note that this set is expected to be small - only upvars from closures
415 // would have a chance of erroneously adding non-user-defined mutable vars
417 let temporary_used_locals: FxHashSet<Local> = mbcx
420 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
423 // For the remaining unused locals that are marked as mutable, we avoid linting any that
424 // were never initialized. These locals may have been removed as unreachable code; or will be
425 // linted as unused variables.
426 let unused_mut_locals =
427 mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
428 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
430 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
431 let used_mut = mbcx.used_mut;
432 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
433 let local_decl = &mbcx.body.local_decls[local];
434 let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data {
435 ClearCrossCrate::Set(data) => data.lint_root,
439 // Skip over locals that begin with an underscore or have no name
440 match mbcx.local_names[local] {
442 if name.as_str().starts_with('_') {
449 let span = local_decl.source_info.span;
450 if span.desugaring_kind().is_some() {
451 // If the `mut` arises as part of a desugaring, we should ignore it.
455 tcx.struct_span_lint_hir(UNUSED_MUT, lint_root, span, |lint| {
456 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
457 lint.build("variable does not need to be mutable")
458 .span_suggestion_short(
462 Applicability::MachineApplicable,
468 // Buffer any move errors that we collected and de-duplicated.
469 for (_, (_, diag)) in mbcx.move_error_reported {
470 diag.buffer(&mut mbcx.errors_buffer);
473 if !mbcx.errors_buffer.is_empty() {
474 mbcx.errors_buffer.sort_by_key(|diag| diag.sort_span);
476 for diag in mbcx.errors_buffer.drain(..) {
477 mbcx.infcx.tcx.sess.diagnostic().emit_diagnostic(&diag);
481 let result = BorrowCheckResult {
482 concrete_opaque_types: opaque_type_values,
483 closure_requirements: opt_closure_req,
484 used_mut_upvars: mbcx.used_mut_upvars,
487 let body_with_facts = if return_body_with_facts {
488 let output_facts = mbcx.polonius_output.expect("Polonius output was not computed");
489 Some(Box::new(BodyWithBorrowckFacts {
491 input_facts: *polonius_input.expect("Polonius input facts were not generated"),
493 location_table: location_table_owned,
499 debug!("do_mir_borrowck: result = {:#?}", result);
501 (result, body_with_facts)
504 /// A `Body` with information computed by the borrow checker. This struct is
505 /// intended to be consumed by compiler consumers.
507 /// We need to include the MIR body here because the region identifiers must
508 /// match the ones in the Polonius facts.
509 pub struct BodyWithBorrowckFacts<'tcx> {
510 /// A mir body that contains region identifiers.
511 pub body: Body<'tcx>,
512 /// Polonius input facts.
513 pub input_facts: AllFacts,
514 /// Polonius output facts.
515 pub output_facts: Rc<self::nll::PoloniusOutput>,
516 /// The table that maps Polonius points to locations in the table.
517 pub location_table: LocationTable,
520 struct MirBorrowckCtxt<'cx, 'tcx> {
521 infcx: &'cx InferCtxt<'cx, 'tcx>,
522 param_env: ParamEnv<'tcx>,
523 body: &'cx Body<'tcx>,
524 move_data: &'cx MoveData<'tcx>,
526 /// Map from MIR `Location` to `LocationIndex`; created
527 /// when MIR borrowck begins.
528 location_table: &'cx LocationTable,
530 movable_generator: bool,
531 /// This keeps track of whether local variables are free-ed when the function
532 /// exits even without a `StorageDead`, which appears to be the case for
535 /// I'm not sure this is the right approach - @eddyb could you try and
537 locals_are_invalidated_at_exit: bool,
538 /// This field keeps track of when borrow errors are reported in the access_place function
539 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
540 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
541 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
543 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
544 /// This field keeps track of when borrow conflict errors are reported
545 /// for reservations, so that we don't report seemingly duplicate
546 /// errors for corresponding activations.
548 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
549 // but it is currently inconvenient to track down the `BorrowIndex`
550 // at the time we detect and report a reservation error.
551 reservation_error_reported: FxHashSet<Place<'tcx>>,
552 /// This fields keeps track of the `Span`s that we have
553 /// used to report extra information for `FnSelfUse`, to avoid
554 /// unnecessarily verbose errors.
555 fn_self_span_reported: FxHashSet<Span>,
556 /// Migration warnings to be reported for #56254. We delay reporting these
557 /// so that we can suppress the warning if there's a corresponding error
558 /// for the activation of the borrow.
559 reservation_warnings:
560 FxHashMap<BorrowIndex, (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)>,
561 /// This field keeps track of move errors that are to be reported for given move indices.
563 /// There are situations where many errors can be reported for a single move out (see #53807)
564 /// and we want only the best of those errors.
566 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
567 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
568 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
569 /// all move errors have been reported, any diagnostics in this map are added to the buffer
572 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
573 /// when errors in the map are being re-added to the error buffer so that errors with the
574 /// same primary span come out in a consistent order.
575 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'cx>)>,
576 /// This field keeps track of errors reported in the checking of uninitialized variables,
577 /// so that we don't report seemingly duplicate errors.
578 uninitialized_error_reported: FxHashSet<PlaceRef<'tcx>>,
579 /// Errors to be reported buffer
580 errors_buffer: Vec<Diagnostic>,
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), JustWrite, 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), JustWrite, flow_state);
660 StatementKind::LlvmInlineAsm(ref asm) => {
661 for (o, output) in iter::zip(&asm.asm.outputs, &*asm.outputs) {
663 // FIXME(eddyb) indirect inline asm outputs should
664 // be encoded through MIR place derefs instead.
668 (Deep, Read(ReadKind::Copy)),
669 LocalMutationIsAllowed::No,
672 self.check_if_path_or_subpath_is_moved(
674 InitializationRequiringAction::Use,
675 (output.as_ref(), o.span),
682 if o.is_rw { Deep } else { Shallow(None) },
683 if o.is_rw { WriteAndRead } else { JustWrite },
688 for (_, input) in asm.inputs.iter() {
689 self.consume_operand(location, (input, span), flow_state);
693 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
698 "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
702 | StatementKind::Coverage(..)
703 | StatementKind::AscribeUserType(..)
704 | StatementKind::Retag { .. }
705 | StatementKind::StorageLive(..) => {
706 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
709 StatementKind::StorageDead(local) => {
712 (Place::from(*local), span),
713 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
714 LocalMutationIsAllowed::Yes,
721 fn visit_terminator_before_primary_effect(
723 flow_state: &Flows<'cx, 'tcx>,
724 term: &'cx Terminator<'tcx>,
727 debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
728 let span = term.source_info.span;
730 self.check_activations(loc, span, flow_state);
733 TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => {
734 self.consume_operand(loc, (discr, span), flow_state);
736 TerminatorKind::Drop { place, target: _, unwind: _ } => {
738 "visit_terminator_drop \
739 loc: {:?} term: {:?} place: {:?} span: {:?}",
740 loc, term, place, span
746 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
747 LocalMutationIsAllowed::Yes,
751 TerminatorKind::DropAndReplace {
753 value: ref new_value,
757 self.mutate_place(loc, (drop_place, span), Deep, JustWrite, flow_state);
758 self.consume_operand(loc, (new_value, span), flow_state);
760 TerminatorKind::Call {
768 self.consume_operand(loc, (func, span), flow_state);
770 self.consume_operand(loc, (arg, span), flow_state);
772 if let Some((dest, _ /*bb*/)) = *destination {
773 self.mutate_place(loc, (dest, span), Deep, JustWrite, flow_state);
776 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
777 self.consume_operand(loc, (cond, span), flow_state);
778 use rustc_middle::mir::AssertKind;
779 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
780 self.consume_operand(loc, (len, span), flow_state);
781 self.consume_operand(loc, (index, span), flow_state);
785 TerminatorKind::Yield { ref value, resume: _, resume_arg, drop: _ } => {
786 self.consume_operand(loc, (value, span), flow_state);
787 self.mutate_place(loc, (resume_arg, span), Deep, JustWrite, flow_state);
790 TerminatorKind::InlineAsm {
799 InlineAsmOperand::In { reg: _, ref value } => {
800 self.consume_operand(loc, (value, span), flow_state);
802 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
803 if let Some(place) = place {
813 InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
814 self.consume_operand(loc, (in_value, span), flow_state);
815 if let Some(out_place) = out_place {
825 InlineAsmOperand::Const { value: _ }
826 | InlineAsmOperand::SymFn { value: _ }
827 | InlineAsmOperand::SymStatic { def_id: _ } => {}
832 TerminatorKind::Goto { target: _ }
833 | TerminatorKind::Abort
834 | TerminatorKind::Unreachable
835 | TerminatorKind::Resume
836 | TerminatorKind::Return
837 | TerminatorKind::GeneratorDrop
838 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
839 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
840 // no data used, thus irrelevant to borrowck
845 fn visit_terminator_after_primary_effect(
847 flow_state: &Flows<'cx, 'tcx>,
848 term: &'cx Terminator<'tcx>,
851 let span = term.source_info.span;
854 TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
855 if self.movable_generator {
856 // Look for any active borrows to locals
857 let borrow_set = self.borrow_set.clone();
858 for i in flow_state.borrows.iter() {
859 let borrow = &borrow_set[i];
860 self.check_for_local_borrow(borrow, span);
865 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
866 // Returning from the function implicitly kills storage for all locals and statics.
867 // Often, the storage will already have been killed by an explicit
868 // StorageDead, but we don't always emit those (notably on unwind paths),
869 // so this "extra check" serves as a kind of backup.
870 let borrow_set = self.borrow_set.clone();
871 for i in flow_state.borrows.iter() {
872 let borrow = &borrow_set[i];
873 self.check_for_invalidation_at_exit(loc, borrow, span);
877 TerminatorKind::Abort
878 | TerminatorKind::Assert { .. }
879 | TerminatorKind::Call { .. }
880 | TerminatorKind::Drop { .. }
881 | TerminatorKind::DropAndReplace { .. }
882 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
883 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
884 | TerminatorKind::Goto { .. }
885 | TerminatorKind::SwitchInt { .. }
886 | TerminatorKind::Unreachable
887 | TerminatorKind::InlineAsm { .. } => {}
892 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
898 use self::AccessDepth::{Deep, Shallow};
899 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
901 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
902 enum ArtificialField {
907 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
909 /// From the RFC: "A *shallow* access means that the immediate
910 /// fields reached at P are accessed, but references or pointers
911 /// found within are not dereferenced. Right now, the only access
912 /// that is shallow is an assignment like `x = ...;`, which would
913 /// be a *shallow write* of `x`."
914 Shallow(Option<ArtificialField>),
916 /// From the RFC: "A *deep* access means that all data reachable
917 /// through the given place may be invalidated or accesses by
921 /// Access is Deep only when there is a Drop implementation that
922 /// can reach the data behind the reference.
926 /// Kind of access to a value: read or write
927 /// (For informational purposes only)
928 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
930 /// From the RFC: "A *read* means that the existing data may be
931 /// read, but will not be changed."
934 /// From the RFC: "A *write* means that the data may be mutated to
935 /// new values or otherwise invalidated (for example, it could be
936 /// de-initialized, as in a move operation).
939 /// For two-phase borrows, we distinguish a reservation (which is treated
940 /// like a Read) from an activation (which is treated like a write), and
941 /// each of those is furthermore distinguished from Reads/Writes above.
942 Reservation(WriteKind),
943 Activation(WriteKind, BorrowIndex),
946 /// Kind of read access to a value
947 /// (For informational purposes only)
948 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
954 /// Kind of write access to a value
955 /// (For informational purposes only)
956 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
959 MutableBorrow(BorrowKind),
964 /// When checking permissions for a place access, this flag is used to indicate that an immutable
965 /// local place can be mutated.
967 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
968 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
969 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
970 // `is_declared_mutable()`.
971 // - Take flow state into consideration in `is_assignable()` for local variables.
972 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
973 enum LocalMutationIsAllowed {
975 /// We want use of immutable upvars to cause a "write to immutable upvar"
976 /// error, not an "reassignment" error.
981 #[derive(Copy, Clone, Debug)]
982 enum InitializationRequiringAction {
991 struct RootPlace<'tcx> {
993 place_projection: &'tcx [PlaceElem<'tcx>],
994 is_local_mutation_allowed: LocalMutationIsAllowed,
997 impl InitializationRequiringAction {
998 fn as_noun(self) -> &'static str {
1000 InitializationRequiringAction::Update => "update",
1001 InitializationRequiringAction::Borrow => "borrow",
1002 InitializationRequiringAction::MatchOn => "use", // no good noun
1003 InitializationRequiringAction::Use => "use",
1004 InitializationRequiringAction::Assignment => "assign",
1005 InitializationRequiringAction::PartialAssignment => "assign to part",
1009 fn as_verb_in_past_tense(self) -> &'static str {
1011 InitializationRequiringAction::Update => "updated",
1012 InitializationRequiringAction::Borrow => "borrowed",
1013 InitializationRequiringAction::MatchOn => "matched on",
1014 InitializationRequiringAction::Use => "used",
1015 InitializationRequiringAction::Assignment => "assigned",
1016 InitializationRequiringAction::PartialAssignment => "partially assigned",
1021 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
1022 fn body(&self) -> &'cx Body<'tcx> {
1026 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
1027 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
1028 /// place is initialized and (b) it is not borrowed in some way that would prevent this
1031 /// Returns `true` if an error is reported.
1035 place_span: (Place<'tcx>, Span),
1036 kind: (AccessDepth, ReadOrWrite),
1037 is_local_mutation_allowed: LocalMutationIsAllowed,
1038 flow_state: &Flows<'cx, 'tcx>,
1040 let (sd, rw) = kind;
1042 if let Activation(_, borrow_index) = rw {
1043 if self.reservation_error_reported.contains(&place_span.0) {
1045 "skipping access_place for activation of invalid reservation \
1046 place: {:?} borrow_index: {:?}",
1047 place_span.0, borrow_index
1053 // Check is_empty() first because it's the common case, and doing that
1054 // way we avoid the clone() call.
1055 if !self.access_place_error_reported.is_empty()
1056 && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
1059 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
1065 let mutability_error = self.check_access_permissions(
1068 is_local_mutation_allowed,
1072 let conflict_error =
1073 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
1075 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
1076 // Suppress this warning when there's an error being emitted for the
1077 // same borrow: fixing the error is likely to fix the warning.
1078 self.reservation_warnings.remove(&borrow_idx);
1081 if conflict_error || mutability_error {
1082 debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
1084 self.access_place_error_reported.insert((place_span.0, place_span.1));
1088 fn check_access_for_conflict(
1091 place_span: (Place<'tcx>, Span),
1094 flow_state: &Flows<'cx, 'tcx>,
1097 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1098 location, place_span, sd, rw,
1101 let mut error_reported = false;
1102 let tcx = self.infcx.tcx;
1103 let body = self.body;
1104 let borrow_set = self.borrow_set.clone();
1106 // Use polonius output if it has been enabled.
1107 let polonius_output = self.polonius_output.clone();
1108 let borrows_in_scope = if let Some(polonius) = &polonius_output {
1109 let location = self.location_table.start_index(location);
1110 Either::Left(polonius.errors_at(location).iter().copied())
1112 Either::Right(flow_state.borrows.iter())
1115 each_borrow_involving_path(
1123 |this, borrow_index, borrow| match (rw, borrow.kind) {
1124 // Obviously an activation is compatible with its own
1125 // reservation (or even prior activating uses of same
1126 // borrow); so don't check if they interfere.
1128 // NOTE: *reservations* do conflict with themselves;
1129 // thus aren't injecting unsoundenss w/ this check.)
1130 (Activation(_, activating), _) if activating == borrow_index => {
1132 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1133 skipping {:?} b/c activation of same borrow_index",
1137 (borrow_index, borrow),
1142 (Read(_), BorrowKind::Shared | BorrowKind::Shallow)
1144 Read(ReadKind::Borrow(BorrowKind::Shallow)),
1145 BorrowKind::Unique | BorrowKind::Mut { .. },
1146 ) => Control::Continue,
1148 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1149 // Handled by initialization checks.
1153 (Read(kind), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
1154 // Reading from mere reservations of mutable-borrows is OK.
1155 if !is_active(&this.dominators, borrow, location) {
1156 assert!(allow_two_phase_borrow(borrow.kind));
1157 return Control::Continue;
1160 error_reported = true;
1163 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1164 .buffer(&mut this.errors_buffer);
1166 ReadKind::Borrow(bk) => {
1167 this.report_conflicting_borrow(location, place_span, bk, borrow)
1168 .buffer(&mut this.errors_buffer);
1175 Reservation(WriteKind::MutableBorrow(bk)),
1176 BorrowKind::Shallow | BorrowKind::Shared,
1177 ) if { tcx.migrate_borrowck() && this.borrow_set.contains(&location) } => {
1178 let bi = this.borrow_set.get_index_of(&location).unwrap();
1180 "recording invalid reservation of place: {:?} with \
1181 borrow index {:?} as warning",
1184 // rust-lang/rust#56254 - This was previously permitted on
1185 // the 2018 edition so we emit it as a warning. We buffer
1186 // these sepately so that we only emit a warning if borrow
1187 // checking was otherwise successful.
1188 this.reservation_warnings
1189 .insert(bi, (place_span.0, place_span.1, location, bk, borrow.clone()));
1191 // Don't suppress actual errors.
1195 (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1197 Reservation(..) => {
1199 "recording invalid reservation of \
1203 this.reservation_error_reported.insert(place_span.0);
1205 Activation(_, activating) => {
1207 "observing check_place for activation of \
1208 borrow_index: {:?}",
1212 Read(..) | Write(..) => {}
1215 error_reported = true;
1217 WriteKind::MutableBorrow(bk) => {
1218 this.report_conflicting_borrow(location, place_span, bk, borrow)
1219 .buffer(&mut this.errors_buffer);
1221 WriteKind::StorageDeadOrDrop => this
1222 .report_borrowed_value_does_not_live_long_enough(
1228 WriteKind::Mutate => {
1229 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1231 WriteKind::Move => {
1232 this.report_move_out_while_borrowed(location, place_span, borrow)
1246 place_span: (Place<'tcx>, Span),
1249 flow_state: &Flows<'cx, 'tcx>,
1251 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1253 MutateMode::WriteAndRead => {
1254 self.check_if_path_or_subpath_is_moved(
1256 InitializationRequiringAction::Update,
1257 (place_span.0.as_ref(), place_span.1),
1261 MutateMode::JustWrite => {
1262 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1266 // Special case: you can assign an immutable local variable
1267 // (e.g., `x = ...`) so long as it has never been initialized
1268 // before (at this point in the flow).
1269 if let Some(local) = place_span.0.as_local() {
1270 if let Mutability::Not = self.body.local_decls[local].mutability {
1271 // check for reassignments to immutable local variables
1272 self.check_if_reassignment_to_immutable_state(
1273 location, local, place_span, flow_state,
1279 // Otherwise, use the normal access permission rules.
1283 (kind, Write(WriteKind::Mutate)),
1284 LocalMutationIsAllowed::No,
1292 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1293 flow_state: &Flows<'cx, 'tcx>,
1296 Rvalue::Ref(_ /*rgn*/, bk, place) => {
1297 let access_kind = match bk {
1298 BorrowKind::Shallow => {
1299 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1301 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1302 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1303 let wk = WriteKind::MutableBorrow(bk);
1304 if allow_two_phase_borrow(bk) {
1305 (Deep, Reservation(wk))
1316 LocalMutationIsAllowed::No,
1320 let action = if bk == BorrowKind::Shallow {
1321 InitializationRequiringAction::MatchOn
1323 InitializationRequiringAction::Borrow
1326 self.check_if_path_or_subpath_is_moved(
1329 (place.as_ref(), span),
1334 Rvalue::AddressOf(mutability, place) => {
1335 let access_kind = match mutability {
1336 Mutability::Mut => (
1338 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1339 allow_two_phase_borrow: false,
1342 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1349 LocalMutationIsAllowed::No,
1353 self.check_if_path_or_subpath_is_moved(
1355 InitializationRequiringAction::Borrow,
1356 (place.as_ref(), span),
1361 Rvalue::ThreadLocalRef(_) => {}
1363 Rvalue::Use(ref operand)
1364 | Rvalue::Repeat(ref operand, _)
1365 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1366 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/)
1367 | Rvalue::ShallowInitBox(ref operand, _ /*ty*/) => {
1368 self.consume_operand(location, (operand, span), flow_state)
1371 Rvalue::Len(place) | Rvalue::Discriminant(place) => {
1372 let af = match *rvalue {
1373 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1374 Rvalue::Discriminant(..) => None,
1375 _ => unreachable!(),
1380 (Shallow(af), Read(ReadKind::Copy)),
1381 LocalMutationIsAllowed::No,
1384 self.check_if_path_or_subpath_is_moved(
1386 InitializationRequiringAction::Use,
1387 (place.as_ref(), span),
1392 Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2))
1393 | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => {
1394 self.consume_operand(location, (operand1, span), flow_state);
1395 self.consume_operand(location, (operand2, span), flow_state);
1398 Rvalue::NullaryOp(_op, _ty) => {
1399 // nullary ops take no dynamic input; no borrowck effect.
1401 // FIXME: is above actually true? Do we want to track
1402 // the fact that uninitialized data can be created via
1406 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1407 // We need to report back the list of mutable upvars that were
1408 // moved into the closure and subsequently used by the closure,
1409 // in order to populate our used_mut set.
1410 match **aggregate_kind {
1411 AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
1412 let BorrowCheckResult { used_mut_upvars, .. } =
1413 self.infcx.tcx.mir_borrowck(def_id.expect_local());
1414 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1415 for field in used_mut_upvars {
1416 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1419 AggregateKind::Adt(..)
1420 | AggregateKind::Array(..)
1421 | AggregateKind::Tuple { .. } => (),
1424 for operand in operands {
1425 self.consume_operand(location, (operand, span), flow_state);
1431 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1432 let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1433 // We have three possibilities here:
1434 // a. We are modifying something through a mut-ref
1435 // b. We are modifying something that is local to our parent
1436 // c. Current body is a nested closure, and we are modifying path starting from
1437 // a Place captured by our parent closure.
1439 // Handle (c), the path being modified is exactly the path captured by our parent
1440 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1441 this.used_mut_upvars.push(field);
1445 for (place_ref, proj) in place.iter_projections().rev() {
1447 if proj == ProjectionElem::Deref {
1448 match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1449 // We aren't modifying a variable directly
1450 ty::Ref(_, _, hir::Mutability::Mut) => return,
1457 if let Some(field) = this.is_upvar_field_projection(place_ref) {
1458 this.used_mut_upvars.push(field);
1464 this.used_mut.insert(place.local);
1467 // This relies on the current way that by-value
1468 // captures of a closure are copied/moved directly
1469 // when generating MIR.
1471 Operand::Move(place) | Operand::Copy(place) => {
1472 match place.as_local() {
1473 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1474 if self.body.local_decls[local].ty.is_mutable_ptr() {
1475 // The variable will be marked as mutable by the borrow.
1478 // This is an edge case where we have a `move` closure
1479 // inside a non-move closure, and the inner closure
1480 // contains a mutation:
1483 // || { move || { i += 1; }; };
1485 // In this case our usual strategy of assuming that the
1486 // variable will be captured by mutable reference is
1487 // wrong, since `i` can be copied into the inner
1488 // closure from a shared reference.
1490 // As such we have to search for the local that this
1491 // capture comes from and mark it as being used as mut.
1493 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1494 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1495 &self.move_data.inits[init_index]
1497 bug!("temporary should be initialized exactly once")
1500 let loc = match init.location {
1501 InitLocation::Statement(stmt) => stmt,
1502 _ => bug!("temporary initialized in arguments"),
1505 let body = self.body;
1506 let bbd = &body[loc.block];
1507 let stmt = &bbd.statements[loc.statement_index];
1508 debug!("temporary assigned in: stmt={:?}", stmt);
1510 if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, source))) = stmt.kind
1512 propagate_closure_used_mut_place(self, source);
1515 "closures should only capture user variables \
1516 or references to user variables"
1520 _ => propagate_closure_used_mut_place(self, place),
1523 Operand::Constant(..) => {}
1530 (operand, span): (&'cx Operand<'tcx>, Span),
1531 flow_state: &Flows<'cx, 'tcx>,
1534 Operand::Copy(place) => {
1535 // copy of place: check if this is "copy of frozen path"
1536 // (FIXME: see check_loans.rs)
1540 (Deep, Read(ReadKind::Copy)),
1541 LocalMutationIsAllowed::No,
1545 // Finally, check if path was already moved.
1546 self.check_if_path_or_subpath_is_moved(
1548 InitializationRequiringAction::Use,
1549 (place.as_ref(), span),
1553 Operand::Move(place) => {
1554 // move of place: check if this is move of already borrowed path
1558 (Deep, Write(WriteKind::Move)),
1559 LocalMutationIsAllowed::Yes,
1563 // Finally, check if path was already moved.
1564 self.check_if_path_or_subpath_is_moved(
1566 InitializationRequiringAction::Use,
1567 (place.as_ref(), span),
1571 Operand::Constant(_) => {}
1575 /// Checks whether a borrow of this place is invalidated when the function
1577 fn check_for_invalidation_at_exit(
1580 borrow: &BorrowData<'tcx>,
1583 debug!("check_for_invalidation_at_exit({:?})", borrow);
1584 let place = borrow.borrowed_place;
1585 let mut root_place = PlaceRef { local: place.local, projection: &[] };
1587 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1588 // we just know that all locals are dropped at function exit (otherwise
1589 // we'll have a memory leak) and assume that all statics have a destructor.
1591 // FIXME: allow thread-locals to borrow other thread locals?
1593 let (might_be_alive, will_be_dropped) =
1594 if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1595 // Thread-locals might be dropped after the function exits
1596 // We have to dereference the outer reference because
1597 // borrows don't conflict behind shared references.
1598 root_place.projection = DEREF_PROJECTION;
1601 (false, self.locals_are_invalidated_at_exit)
1604 if !will_be_dropped {
1605 debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
1609 let sd = if might_be_alive { Deep } else { Shallow(None) };
1611 if places_conflict::borrow_conflicts_with_place(
1618 places_conflict::PlaceConflictBias::Overlap,
1620 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1621 // FIXME: should be talking about the region lifetime instead
1622 // of just a span here.
1623 let span = self.infcx.tcx.sess.source_map().end_point(span);
1624 self.report_borrowed_value_does_not_live_long_enough(
1633 /// Reports an error if this is a borrow of local data.
1634 /// This is called for all Yield expressions on movable generators
1635 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1636 debug!("check_for_local_borrow({:?})", borrow);
1638 if borrow_of_local_data(borrow.borrowed_place) {
1639 let err = self.cannot_borrow_across_generator_yield(
1640 self.retrieve_borrow_spans(borrow).var_or_use(),
1644 err.buffer(&mut self.errors_buffer);
1648 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1649 // Two-phase borrow support: For each activation that is newly
1650 // generated at this statement, check if it interferes with
1652 let borrow_set = self.borrow_set.clone();
1653 for &borrow_index in borrow_set.activations_at_location(location) {
1654 let borrow = &borrow_set[borrow_index];
1656 // only mutable borrows should be 2-phase
1657 assert!(match borrow.kind {
1658 BorrowKind::Shared | BorrowKind::Shallow => false,
1659 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1664 (borrow.borrowed_place, span),
1665 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1666 LocalMutationIsAllowed::No,
1669 // We do not need to call `check_if_path_or_subpath_is_moved`
1670 // again, as we already called it when we made the
1671 // initial reservation.
1675 fn check_if_reassignment_to_immutable_state(
1679 place_span: (Place<'tcx>, Span),
1680 flow_state: &Flows<'cx, 'tcx>,
1682 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1684 // Check if any of the initializiations of `local` have happened yet:
1685 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1686 // And, if so, report an error.
1687 let init = &self.move_data.inits[init_index];
1688 let span = init.span(&self.body);
1689 self.report_illegal_reassignment(location, place_span, span, place_span.0);
1693 fn check_if_full_path_is_moved(
1696 desired_action: InitializationRequiringAction,
1697 place_span: (PlaceRef<'tcx>, Span),
1698 flow_state: &Flows<'cx, 'tcx>,
1700 let maybe_uninits = &flow_state.uninits;
1704 // 1. Move of `a.b.c`, use of `a.b.c`
1705 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1706 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1707 // partial initialization support, one might have `a.x`
1708 // initialized but not `a.b`.
1712 // 4. Move of `a.b.c`, use of `a.b.d`
1713 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1714 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1715 // must have been initialized for the use to be sound.
1716 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1718 // The dataflow tracks shallow prefixes distinctly (that is,
1719 // field-accesses on P distinctly from P itself), in order to
1720 // track substructure initialization separately from the whole
1723 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1724 // which we have a MovePath is `a.b`, then that means that the
1725 // initialization state of `a.b` is all we need to inspect to
1726 // know if `a.b.c` is valid (and from that we infer that the
1727 // dereference and `.d` access is also valid, since we assume
1728 // `a.b.c` is assigned a reference to an initialized and
1729 // well-formed record structure.)
1731 // Therefore, if we seek out the *closest* prefix for which we
1732 // have a MovePath, that should capture the initialization
1733 // state for the place scenario.
1735 // This code covers scenarios 1, 2, and 3.
1737 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1738 let (prefix, mpi) = self.move_path_closest_to(place_span.0);
1739 if maybe_uninits.contains(mpi) {
1740 self.report_use_of_moved_or_uninitialized(
1743 (prefix, place_span.0, place_span.1),
1746 } // Only query longest prefix with a MovePath, not further
1747 // ancestors; dataflow recurs on children when parents
1748 // move (to support partial (re)inits).
1750 // (I.e., querying parents breaks scenario 7; but may want
1751 // to do such a query based on partial-init feature-gate.)
1754 /// Subslices correspond to multiple move paths, so we iterate through the
1755 /// elements of the base array. For each element we check
1757 /// * Does this element overlap with our slice.
1758 /// * Is any part of it uninitialized.
1759 fn check_if_subslice_element_is_moved(
1762 desired_action: InitializationRequiringAction,
1763 place_span: (PlaceRef<'tcx>, Span),
1764 maybe_uninits: &BitSet<MovePathIndex>,
1768 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1769 let move_paths = &self.move_data.move_paths;
1771 let root_path = &move_paths[mpi];
1772 for (child_mpi, child_move_path) in root_path.children(move_paths) {
1773 let last_proj = child_move_path.place.projection.last().unwrap();
1774 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
1775 debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
1777 if (from..to).contains(offset) {
1779 self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
1780 maybe_uninits.contains(mpi)
1783 if let Some(uninit_child) = uninit_child {
1784 self.report_use_of_moved_or_uninitialized(
1787 (place_span.0, place_span.0, place_span.1),
1790 return; // don't bother finding other problems.
1798 fn check_if_path_or_subpath_is_moved(
1801 desired_action: InitializationRequiringAction,
1802 place_span: (PlaceRef<'tcx>, Span),
1803 flow_state: &Flows<'cx, 'tcx>,
1805 let maybe_uninits = &flow_state.uninits;
1809 // 1. Move of `a.b.c`, use of `a` or `a.b`
1810 // partial initialization support, one might have `a.x`
1811 // initialized but not `a.b`.
1812 // 2. All bad scenarios from `check_if_full_path_is_moved`
1816 // 3. Move of `a.b.c`, use of `a.b.d`
1817 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1818 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1819 // must have been initialized for the use to be sound.
1820 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1822 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1824 if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
1825 place_span.0.last_projection()
1827 let place_ty = place_base.ty(self.body(), self.infcx.tcx);
1828 if let ty::Array(..) = place_ty.ty.kind() {
1829 self.check_if_subslice_element_is_moved(
1832 (place_base, place_span.1),
1841 // A move of any shallow suffix of `place` also interferes
1842 // with an attempt to use `place`. This is scenario 3 above.
1844 // (Distinct from handling of scenarios 1+2+4 above because
1845 // `place` does not interfere with suffixes of its prefixes,
1846 // e.g., `a.b.c` does not interfere with `a.b.d`)
1848 // This code covers scenario 1.
1850 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1851 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1852 let uninit_mpi = self
1854 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
1856 if let Some(uninit_mpi) = uninit_mpi {
1857 self.report_use_of_moved_or_uninitialized(
1860 (place_span.0, place_span.0, place_span.1),
1863 return; // don't bother finding other problems.
1868 /// Currently MoveData does not store entries for all places in
1869 /// the input MIR. For example it will currently filter out
1870 /// places that are Copy; thus we do not track places of shared
1871 /// reference type. This routine will walk up a place along its
1872 /// prefixes, searching for a foundational place that *is*
1873 /// tracked in the MoveData.
1875 /// An Err result includes a tag indicated why the search failed.
1876 /// Currently this can only occur if the place is built off of a
1877 /// static variable, as we do not track those in the MoveData.
1878 fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
1879 match self.move_data.rev_lookup.find(place) {
1880 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
1881 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
1883 LookupResult::Parent(None) => panic!("should have move path for every Local"),
1887 fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
1888 // If returns None, then there is no move path corresponding
1889 // to a direct owner of `place` (which means there is nothing
1890 // that borrowck tracks for its analysis).
1892 match self.move_data.rev_lookup.find(place) {
1893 LookupResult::Parent(_) => None,
1894 LookupResult::Exact(mpi) => Some(mpi),
1898 fn check_if_assigned_path_is_moved(
1901 (place, span): (Place<'tcx>, Span),
1902 flow_state: &Flows<'cx, 'tcx>,
1904 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1906 // None case => assigning to `x` does not require `x` be initialized.
1907 for (place_base, elem) in place.iter_projections().rev() {
1909 ProjectionElem::Index(_/*operand*/) |
1910 ProjectionElem::ConstantIndex { .. } |
1911 // assigning to P[i] requires P to be valid.
1912 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1913 // assigning to (P->variant) is okay if assigning to `P` is okay
1915 // FIXME: is this true even if P is an adt with a dtor?
1918 // assigning to (*P) requires P to be initialized
1919 ProjectionElem::Deref => {
1920 self.check_if_full_path_is_moved(
1921 location, InitializationRequiringAction::Use,
1922 (place_base, span), flow_state);
1923 // (base initialized; no need to
1928 ProjectionElem::Subslice { .. } => {
1929 panic!("we don't allow assignments to subslices, location: {:?}",
1933 ProjectionElem::Field(..) => {
1934 // if type of `P` has a dtor, then
1935 // assigning to `P.f` requires `P` itself
1936 // be already initialized
1937 let tcx = self.infcx.tcx;
1938 let base_ty = place_base.ty(self.body(), tcx).ty;
1939 match base_ty.kind() {
1940 ty::Adt(def, _) if def.has_dtor(tcx) => {
1941 self.check_if_path_or_subpath_is_moved(
1942 location, InitializationRequiringAction::Assignment,
1943 (place_base, span), flow_state);
1945 // (base initialized; no need to
1950 // Once `let s; s.x = V; read(s.x);`,
1951 // is allowed, remove this match arm.
1952 ty::Adt(..) | ty::Tuple(..) => {
1953 check_parent_of_field(self, location, place_base, span, flow_state);
1955 // rust-lang/rust#21232, #54499, #54986: during period where we reject
1956 // partial initialization, do not complain about unnecessary `mut` on
1957 // an attempt to do a partial initialization.
1958 self.used_mut.insert(place.local);
1967 fn check_parent_of_field<'cx, 'tcx>(
1968 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1970 base: PlaceRef<'tcx>,
1972 flow_state: &Flows<'cx, 'tcx>,
1974 // rust-lang/rust#21232: Until Rust allows reads from the
1975 // initialized parts of partially initialized structs, we
1976 // will, starting with the 2018 edition, reject attempts
1977 // to write to structs that are not fully initialized.
1979 // In other words, *until* we allow this:
1981 // 1. `let mut s; s.x = Val; read(s.x);`
1983 // we will for now disallow this:
1985 // 2. `let mut s; s.x = Val;`
1989 // 3. `let mut s = ...; drop(s); s.x=Val;`
1991 // This does not use check_if_path_or_subpath_is_moved,
1992 // because we want to *allow* reinitializations of fields:
1993 // e.g., want to allow
1995 // `let mut s = ...; drop(s.x); s.x=Val;`
1997 // This does not use check_if_full_path_is_moved on
1998 // `base`, because that would report an error about the
1999 // `base` as a whole, but in this scenario we *really*
2000 // want to report an error about the actual thing that was
2001 // moved, which may be some prefix of `base`.
2003 // Shallow so that we'll stop at any dereference; we'll
2004 // report errors about issues with such bases elsewhere.
2005 let maybe_uninits = &flow_state.uninits;
2007 // Find the shortest uninitialized prefix you can reach
2008 // without going over a Deref.
2009 let mut shortest_uninit_seen = None;
2010 for prefix in this.prefixes(base, PrefixSet::Shallow) {
2011 let mpi = match this.move_path_for_place(prefix) {
2016 if maybe_uninits.contains(mpi) {
2018 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
2019 shortest_uninit_seen,
2022 shortest_uninit_seen = Some((prefix, mpi));
2024 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
2028 if let Some((prefix, mpi)) = shortest_uninit_seen {
2029 // Check for a reassignment into an uninitialized field of a union (for example,
2030 // after a move out). In this case, do not report an error here. There is an
2031 // exception, if this is the first assignment into the union (that is, there is
2032 // no move out from an earlier location) then this is an attempt at initialization
2033 // of the union - we should error in that case.
2034 let tcx = this.infcx.tcx;
2035 if base.ty(this.body(), tcx).ty.is_union() {
2036 if this.move_data.path_map[mpi].iter().any(|moi| {
2037 this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
2043 this.report_use_of_moved_or_uninitialized(
2045 InitializationRequiringAction::PartialAssignment,
2046 (prefix, base, span),
2053 /// Checks the permissions for the given place and read or write kind
2055 /// Returns `true` if an error is reported.
2056 fn check_access_permissions(
2058 (place, span): (Place<'tcx>, Span),
2060 is_local_mutation_allowed: LocalMutationIsAllowed,
2061 flow_state: &Flows<'cx, 'tcx>,
2065 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
2066 place, kind, is_local_mutation_allowed
2073 Reservation(WriteKind::MutableBorrow(
2074 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
2076 | Write(WriteKind::MutableBorrow(
2077 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
2079 let is_local_mutation_allowed = match borrow_kind {
2080 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
2081 BorrowKind::Mut { .. } => is_local_mutation_allowed,
2082 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
2084 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2086 self.add_used_mut(root_place, flow_state);
2090 error_access = AccessKind::MutableBorrow;
2091 the_place_err = place_err;
2095 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
2096 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2098 self.add_used_mut(root_place, flow_state);
2102 error_access = AccessKind::Mutate;
2103 the_place_err = place_err;
2110 | WriteKind::StorageDeadOrDrop
2111 | WriteKind::MutableBorrow(BorrowKind::Shared)
2112 | WriteKind::MutableBorrow(BorrowKind::Shallow),
2116 | WriteKind::StorageDeadOrDrop
2117 | WriteKind::MutableBorrow(BorrowKind::Shared)
2118 | WriteKind::MutableBorrow(BorrowKind::Shallow),
2120 if let (Err(_), true) = (
2121 self.is_mutable(place.as_ref(), is_local_mutation_allowed),
2122 self.errors_buffer.is_empty(),
2124 // rust-lang/rust#46908: In pure NLL mode this code path should be
2125 // unreachable, but we use `delay_span_bug` because we can hit this when
2126 // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
2127 // enabled. We don't want to ICE for that case, as other errors will have
2128 // been emitted (#52262).
2129 self.infcx.tcx.sess.delay_span_bug(
2132 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2140 // permission checks are done at Reservation point.
2146 | BorrowKind::Mut { .. }
2147 | BorrowKind::Shared
2148 | BorrowKind::Shallow,
2152 // Access authorized
2157 // rust-lang/rust#21232, #54986: during period where we reject
2158 // partial initialization, do not complain about mutability
2159 // errors except for actual mutation (as opposed to an attempt
2160 // to do a partial initialization).
2161 let previously_initialized =
2162 self.is_local_ever_initialized(place.local, flow_state).is_some();
2164 // at this point, we have set up the error reporting state.
2165 if previously_initialized {
2166 self.report_mutability_error(place, span, the_place_err, error_access, location);
2173 fn is_local_ever_initialized(
2176 flow_state: &Flows<'cx, 'tcx>,
2177 ) -> Option<InitIndex> {
2178 let mpi = self.move_data.rev_lookup.find_local(local);
2179 let ii = &self.move_data.init_path_map[mpi];
2181 if flow_state.ever_inits.contains(index) {
2188 /// Adds the place into the used mutable variables set
2189 fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2191 RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2192 // If the local may have been initialized, and it is now currently being
2193 // mutated, then it is justified to be annotated with the `mut`
2194 // keyword, since the mutation may be a possible reassignment.
2195 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2196 && self.is_local_ever_initialized(local, flow_state).is_some()
2198 self.used_mut.insert(local);
2203 place_projection: _,
2204 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2208 place_projection: place_projection @ [.., _],
2209 is_local_mutation_allowed: _,
2211 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2213 projection: place_projection,
2215 self.used_mut_upvars.push(field);
2221 /// Whether this value can be written or borrowed mutably.
2222 /// Returns the root place if the place passed in is a projection.
2225 place: PlaceRef<'tcx>,
2226 is_local_mutation_allowed: LocalMutationIsAllowed,
2227 ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2228 debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2229 match place.last_projection() {
2231 let local = &self.body.local_decls[place.local];
2232 match local.mutability {
2233 Mutability::Not => match is_local_mutation_allowed {
2234 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2235 place_local: place.local,
2236 place_projection: place.projection,
2237 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2239 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2240 place_local: place.local,
2241 place_projection: place.projection,
2242 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2244 LocalMutationIsAllowed::No => Err(place),
2246 Mutability::Mut => Ok(RootPlace {
2247 place_local: place.local,
2248 place_projection: place.projection,
2249 is_local_mutation_allowed,
2253 Some((place_base, elem)) => {
2255 ProjectionElem::Deref => {
2256 let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2258 // Check the kind of deref to decide
2259 match base_ty.kind() {
2260 ty::Ref(_, _, mutbl) => {
2262 // Shared borrowed data is never mutable
2263 hir::Mutability::Not => Err(place),
2264 // Mutably borrowed data is mutable, but only if we have a
2265 // unique path to the `&mut`
2266 hir::Mutability::Mut => {
2267 let mode = match self.is_upvar_field_projection(place) {
2268 Some(field) if self.upvars[field.index()].by_ref => {
2269 is_local_mutation_allowed
2271 _ => LocalMutationIsAllowed::Yes,
2274 self.is_mutable(place_base, mode)
2278 ty::RawPtr(tnm) => {
2280 // `*const` raw pointers are not mutable
2281 hir::Mutability::Not => Err(place),
2282 // `*mut` raw pointers are always mutable, regardless of
2283 // context. The users have to check by themselves.
2284 hir::Mutability::Mut => Ok(RootPlace {
2285 place_local: place.local,
2286 place_projection: place.projection,
2287 is_local_mutation_allowed,
2291 // `Box<T>` owns its content, so mutable if its location is mutable
2292 _ if base_ty.is_box() => {
2293 self.is_mutable(place_base, is_local_mutation_allowed)
2295 // Deref should only be for reference, pointers or boxes
2296 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2299 // All other projections are owned by their base path, so mutable if
2300 // base path is mutable
2301 ProjectionElem::Field(..)
2302 | ProjectionElem::Index(..)
2303 | ProjectionElem::ConstantIndex { .. }
2304 | ProjectionElem::Subslice { .. }
2305 | ProjectionElem::Downcast(..) => {
2306 let upvar_field_projection = self.is_upvar_field_projection(place);
2307 if let Some(field) = upvar_field_projection {
2308 let upvar = &self.upvars[field.index()];
2310 "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2311 place={:?}, place_base={:?}",
2312 upvar, is_local_mutation_allowed, place, place_base
2314 match (upvar.place.mutability, is_local_mutation_allowed) {
2317 LocalMutationIsAllowed::No
2318 | LocalMutationIsAllowed::ExceptUpvars,
2320 (Mutability::Not, LocalMutationIsAllowed::Yes)
2321 | (Mutability::Mut, _) => {
2322 // Subtle: this is an upvar
2323 // reference, so it looks like
2324 // `self.foo` -- we want to double
2325 // check that the location `*self`
2326 // is mutable (i.e., this is not a
2327 // `Fn` closure). But if that
2328 // check succeeds, we want to
2329 // *blame* the mutability on
2330 // `place` (that is,
2331 // `self.foo`). This is used to
2332 // propagate the info about
2333 // whether mutability declarations
2334 // are used outwards, so that we register
2335 // the outer variable as mutable. Otherwise a
2336 // test like this fails to record the `mut`
2340 // fn foo<F: FnOnce()>(_f: F) { }
2342 // let var = Vec::new();
2349 self.is_mutable(place_base, is_local_mutation_allowed)?;
2351 place_local: place.local,
2352 place_projection: place.projection,
2353 is_local_mutation_allowed,
2358 self.is_mutable(place_base, is_local_mutation_allowed)
2366 /// If `place` is a field projection, and the field is being projected from a closure type,
2367 /// then returns the index of the field being projected. Note that this closure will always
2368 /// be `self` in the current MIR, because that is the only time we directly access the fields
2369 /// of a closure type.
2370 fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> {
2371 path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2375 /// The degree of overlap between 2 places for borrow-checking.
2377 /// The places might partially overlap - in this case, we give
2378 /// up and say that they might conflict. This occurs when
2379 /// different fields of a union are borrowed. For example,
2380 /// if `u` is a union, we have no way of telling how disjoint
2381 /// `u.a.x` and `a.b.y` are.
2383 /// The places have the same type, and are either completely disjoint
2384 /// or equal - i.e., they can't "partially" overlap as can occur with
2385 /// unions. This is the "base case" on which we recur for extensions
2388 /// The places are disjoint, so we know all extensions of them
2389 /// will also be disjoint.