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"]
16 #![cfg_attr(not(bootstrap), allow(rustc::potential_query_instability))]
19 extern crate rustc_middle;
23 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
24 use rustc_data_structures::graph::dominators::Dominators;
25 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorReported};
27 use rustc_hir::def_id::LocalDefId;
29 use rustc_index::bit_set::BitSet;
30 use rustc_index::vec::IndexVec;
31 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
32 use rustc_middle::mir::{
33 traversal, Body, ClearCrossCrate, Local, Location, Mutability, Operand, Place, PlaceElem,
34 PlaceRef, VarDebugInfoContents,
36 use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
37 use rustc_middle::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
38 use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind};
39 use rustc_middle::ty::query::Providers;
40 use rustc_middle::ty::{self, CapturedPlace, ParamEnv, RegionVid, TyCtxt};
41 use rustc_session::lint::builtin::{MUTABLE_BORROW_RESERVATION_CONFLICT, UNUSED_MUT};
42 use rustc_span::{Span, Symbol, DUMMY_SP};
45 use smallvec::SmallVec;
46 use std::cell::RefCell;
47 use std::collections::BTreeMap;
52 use rustc_mir_dataflow::impls::{
53 EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces,
55 use rustc_mir_dataflow::move_paths::{InitIndex, MoveOutIndex, MovePathIndex};
56 use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveData, MoveError};
57 use rustc_mir_dataflow::Analysis;
58 use rustc_mir_dataflow::MoveDataParamEnv;
60 use self::diagnostics::{AccessKind, RegionName};
61 use self::location::LocationTable;
62 use self::prefixes::PrefixSet;
63 use self::MutateMode::{JustWrite, WriteAndRead};
66 use self::path_utils::*;
70 mod constraint_generation;
78 mod member_constraints;
87 mod universal_regions;
90 // A public API provided for the Rust compiler consumers.
93 use borrow_set::{BorrowData, BorrowSet};
94 use dataflow::{BorrowIndex, BorrowckFlowState as Flows, BorrowckResults, Borrows};
95 use nll::{PoloniusOutput, ToRegionVid};
96 use place_ext::PlaceExt;
97 use places_conflict::{places_conflict, PlaceConflictBias};
98 use region_infer::RegionInferenceContext;
100 // FIXME(eddyb) perhaps move this somewhere more centrally.
103 place: CapturedPlace<'tcx>,
105 /// If true, the capture is behind a reference.
109 const DEREF_PROJECTION: &[PlaceElem<'_>; 1] = &[ProjectionElem::Deref];
111 pub fn provide(providers: &mut Providers) {
112 *providers = Providers {
113 mir_borrowck: |tcx, did| {
114 if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
115 tcx.mir_borrowck_const_arg(def)
117 mir_borrowck(tcx, ty::WithOptConstParam::unknown(did))
120 mir_borrowck_const_arg: |tcx, (did, param_did)| {
121 mir_borrowck(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
127 fn mir_borrowck<'tcx>(
129 def: ty::WithOptConstParam<LocalDefId>,
130 ) -> &'tcx BorrowCheckResult<'tcx> {
131 let (input_body, promoted) = tcx.mir_promoted(def);
132 debug!("run query mir_borrowck: {}", tcx.def_path_str(def.did.to_def_id()));
134 let opt_closure_req = tcx.infer_ctxt().with_opaque_type_inference(def.did).enter(|infcx| {
135 let input_body: &Body<'_> = &input_body.borrow();
136 let promoted: &IndexVec<_, _> = &promoted.borrow();
137 do_mir_borrowck(&infcx, input_body, promoted, false).0
139 debug!("mir_borrowck done");
141 tcx.arena.alloc(opt_closure_req)
144 /// Perform the actual borrow checking.
146 /// If `return_body_with_facts` is true, then return the body with non-erased
147 /// region ids on which the borrow checking was performed together with Polonius
149 #[instrument(skip(infcx, input_body, input_promoted), level = "debug")]
150 fn do_mir_borrowck<'a, 'tcx>(
151 infcx: &InferCtxt<'a, 'tcx>,
152 input_body: &Body<'tcx>,
153 input_promoted: &IndexVec<Promoted, Body<'tcx>>,
154 return_body_with_facts: bool,
155 ) -> (BorrowCheckResult<'tcx>, Option<Box<BodyWithBorrowckFacts<'tcx>>>) {
156 let def = input_body.source.with_opt_param().as_local().unwrap();
161 let param_env = tcx.param_env(def.did);
162 let id = tcx.hir().local_def_id_to_hir_id(def.did);
164 let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
165 for var_debug_info in &input_body.var_debug_info {
166 if let VarDebugInfoContents::Place(place) = var_debug_info.value {
167 if let Some(local) = place.as_local() {
168 if let Some(prev_name) = local_names[local] {
169 if var_debug_info.name != prev_name {
171 var_debug_info.source_info.span,
172 "local {:?} has many names (`{}` vs `{}`)",
179 local_names[local] = Some(var_debug_info.name);
184 // Gather the upvars of a closure, if any.
185 let tables = tcx.typeck_opt_const_arg(def);
186 if let Some(ErrorReported) = tables.tainted_by_errors {
187 infcx.set_tainted_by_errors();
189 let upvars: Vec<_> = tables
190 .closure_min_captures_flattened(def.did.to_def_id())
191 .map(|captured_place| {
192 let capture = captured_place.info.capture_kind;
193 let by_ref = match capture {
194 ty::UpvarCapture::ByValue(_) => false,
195 ty::UpvarCapture::ByRef(..) => true,
197 Upvar { place: captured_place.clone(), by_ref }
201 // Replace all regions with fresh inference variables. This
202 // requires first making our own copy of the MIR. This copy will
203 // be modified (in place) to contain non-lexical lifetimes. It
204 // will have a lifetime tied to the inference context.
205 let mut body_owned = input_body.clone();
206 let mut promoted = input_promoted.clone();
208 nll::replace_regions_in_mir(infcx, param_env, &mut body_owned, &mut promoted);
209 let body = &body_owned; // no further changes
211 let location_table_owned = LocationTable::new(body);
212 let location_table = &location_table_owned;
214 let mut errors_buffer = Vec::new();
215 let (move_data, move_errors): (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>) =
216 match MoveData::gather_moves(&body, tcx, param_env) {
217 Ok(move_data) => (move_data, Vec::new()),
218 Err((move_data, move_errors)) => (move_data, move_errors),
220 let promoted_errors = promoted
222 .map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env)));
224 let mdpe = MoveDataParamEnv { move_data, param_env };
226 let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe)
227 .into_engine(tcx, &body)
228 .pass_name("borrowck")
229 .iterate_to_fixpoint()
230 .into_results_cursor(&body);
232 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
234 Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
236 let use_polonius = return_body_with_facts || infcx.tcx.sess.opts.debugging_opts.polonius;
238 // Compute non-lexical lifetimes.
246 } = nll::compute_regions(
260 // Dump MIR results into a file, if that is enabled. This let us
261 // write unit-tests, as well as helping with debugging.
262 nll::dump_mir_results(infcx, &body, ®ioncx, &opt_closure_req);
264 // We also have a `#[rustc_regions]` annotation that causes us to dump
266 nll::dump_annotation(
275 // The various `flow_*` structures can be large. We drop `flow_inits` here
276 // so it doesn't overlap with the others below. This reduces peak memory
277 // usage significantly on some benchmarks.
280 let regioncx = Rc::new(regioncx);
282 let flow_borrows = Borrows::new(tcx, body, ®ioncx, &borrow_set)
283 .into_engine(tcx, body)
284 .pass_name("borrowck")
285 .iterate_to_fixpoint();
286 let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &mdpe)
287 .into_engine(tcx, body)
288 .pass_name("borrowck")
289 .iterate_to_fixpoint();
290 let flow_ever_inits = EverInitializedPlaces::new(tcx, body, &mdpe)
291 .into_engine(tcx, body)
292 .pass_name("borrowck")
293 .iterate_to_fixpoint();
295 let movable_generator = !matches!(
297 Node::Expr(&hir::Expr {
298 kind: hir::ExprKind::Closure(.., Some(hir::Movability::Static)),
303 for (idx, move_data_results) in promoted_errors {
304 let promoted_body = &promoted[idx];
306 if let Err((move_data, move_errors)) = move_data_results {
307 let mut promoted_mbcx = MirBorrowckCtxt {
311 move_data: &move_data,
312 location_table, // no need to create a real one for the promoted, it is not used
314 fn_self_span_reported: Default::default(),
315 locals_are_invalidated_at_exit,
316 access_place_error_reported: Default::default(),
317 reservation_error_reported: Default::default(),
318 reservation_warnings: Default::default(),
319 move_error_reported: BTreeMap::new(),
320 uninitialized_error_reported: Default::default(),
322 regioncx: regioncx.clone(),
323 used_mut: Default::default(),
324 used_mut_upvars: SmallVec::new(),
325 borrow_set: Rc::clone(&borrow_set),
326 dominators: Dominators::dummy(), // not used
328 local_names: IndexVec::from_elem(None, &promoted_body.local_decls),
329 region_names: RefCell::default(),
330 next_region_name: RefCell::new(1),
331 polonius_output: None,
333 promoted_mbcx.report_move_errors(move_errors);
334 errors_buffer = promoted_mbcx.errors_buffer;
338 let dominators = body.dominators();
340 let mut mbcx = MirBorrowckCtxt {
344 move_data: &mdpe.move_data,
347 locals_are_invalidated_at_exit,
348 fn_self_span_reported: Default::default(),
349 access_place_error_reported: Default::default(),
350 reservation_error_reported: Default::default(),
351 reservation_warnings: Default::default(),
352 move_error_reported: BTreeMap::new(),
353 uninitialized_error_reported: Default::default(),
355 regioncx: Rc::clone(®ioncx),
356 used_mut: Default::default(),
357 used_mut_upvars: SmallVec::new(),
358 borrow_set: Rc::clone(&borrow_set),
362 region_names: RefCell::default(),
363 next_region_name: RefCell::new(1),
367 // Compute and report region errors, if any.
368 mbcx.report_region_errors(nll_errors);
370 let results = BorrowckResults {
371 ever_inits: flow_ever_inits,
372 uninits: flow_uninits,
373 borrows: flow_borrows,
376 mbcx.report_move_errors(move_errors);
378 rustc_mir_dataflow::visit_results(
380 traversal::reverse_postorder(body).map(|(bb, _)| bb),
385 // Convert any reservation warnings into lints.
386 let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
387 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
388 let mut initial_diag = mbcx.report_conflicting_borrow(location, (place, span), bk, &borrow);
390 let scope = mbcx.body.source_info(location).scope;
391 let lint_root = match &mbcx.body.source_scopes[scope].local_data {
392 ClearCrossCrate::Set(data) => data.lint_root,
396 // Span and message don't matter; we overwrite them below anyway
397 mbcx.infcx.tcx.struct_span_lint_hir(
398 MUTABLE_BORROW_RESERVATION_CONFLICT,
402 let mut diag = lint.build("");
404 diag.message = initial_diag.styled_message().clone();
405 diag.span = initial_diag.span.clone();
407 diag.buffer(&mut mbcx.errors_buffer);
410 initial_diag.cancel();
413 // For each non-user used mutable variable, check if it's been assigned from
414 // a user-declared local. If so, then put that local into the used_mut set.
415 // Note that this set is expected to be small - only upvars from closures
416 // would have a chance of erroneously adding non-user-defined mutable vars
418 let temporary_used_locals: FxHashSet<Local> = mbcx
421 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
424 // For the remaining unused locals that are marked as mutable, we avoid linting any that
425 // were never initialized. These locals may have been removed as unreachable code; or will be
426 // linted as unused variables.
427 let unused_mut_locals =
428 mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
429 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
431 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
432 let used_mut = mbcx.used_mut;
433 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
434 let local_decl = &mbcx.body.local_decls[local];
435 let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data {
436 ClearCrossCrate::Set(data) => data.lint_root,
440 // Skip over locals that begin with an underscore or have no name
441 match mbcx.local_names[local] {
443 if name.as_str().starts_with('_') {
450 let span = local_decl.source_info.span;
451 if span.desugaring_kind().is_some() {
452 // If the `mut` arises as part of a desugaring, we should ignore it.
456 tcx.struct_span_lint_hir(UNUSED_MUT, lint_root, span, |lint| {
457 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
458 lint.build("variable does not need to be mutable")
459 .span_suggestion_short(
463 Applicability::MachineApplicable,
469 // Buffer any move errors that we collected and de-duplicated.
470 for (_, (_, diag)) in mbcx.move_error_reported {
471 diag.buffer(&mut mbcx.errors_buffer);
474 if !mbcx.errors_buffer.is_empty() {
475 mbcx.errors_buffer.sort_by_key(|diag| diag.sort_span);
477 for diag in mbcx.errors_buffer.drain(..) {
478 mbcx.infcx.tcx.sess.diagnostic().emit_diagnostic(&diag);
482 let result = BorrowCheckResult {
483 concrete_opaque_types: opaque_type_values,
484 closure_requirements: opt_closure_req,
485 used_mut_upvars: mbcx.used_mut_upvars,
488 let body_with_facts = if return_body_with_facts {
489 let output_facts = mbcx.polonius_output.expect("Polonius output was not computed");
490 Some(Box::new(BodyWithBorrowckFacts {
492 input_facts: *polonius_input.expect("Polonius input facts were not generated"),
494 location_table: location_table_owned,
500 debug!("do_mir_borrowck: result = {:#?}", result);
502 (result, body_with_facts)
505 /// A `Body` with information computed by the borrow checker. This struct is
506 /// intended to be consumed by compiler consumers.
508 /// We need to include the MIR body here because the region identifiers must
509 /// match the ones in the Polonius facts.
510 pub struct BodyWithBorrowckFacts<'tcx> {
511 /// A mir body that contains region identifiers.
512 pub body: Body<'tcx>,
513 /// Polonius input facts.
514 pub input_facts: AllFacts,
515 /// Polonius output facts.
516 pub output_facts: Rc<self::nll::PoloniusOutput>,
517 /// The table that maps Polonius points to locations in the table.
518 pub location_table: LocationTable,
521 struct MirBorrowckCtxt<'cx, 'tcx> {
522 infcx: &'cx InferCtxt<'cx, 'tcx>,
523 param_env: ParamEnv<'tcx>,
524 body: &'cx Body<'tcx>,
525 move_data: &'cx MoveData<'tcx>,
527 /// Map from MIR `Location` to `LocationIndex`; created
528 /// when MIR borrowck begins.
529 location_table: &'cx LocationTable,
531 movable_generator: bool,
532 /// This keeps track of whether local variables are free-ed when the function
533 /// exits even without a `StorageDead`, which appears to be the case for
536 /// I'm not sure this is the right approach - @eddyb could you try and
538 locals_are_invalidated_at_exit: bool,
539 /// This field keeps track of when borrow errors are reported in the access_place function
540 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
541 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
542 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
544 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
545 /// This field keeps track of when borrow conflict errors are reported
546 /// for reservations, so that we don't report seemingly duplicate
547 /// errors for corresponding activations.
549 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
550 // but it is currently inconvenient to track down the `BorrowIndex`
551 // at the time we detect and report a reservation error.
552 reservation_error_reported: FxHashSet<Place<'tcx>>,
553 /// This fields keeps track of the `Span`s that we have
554 /// used to report extra information for `FnSelfUse`, to avoid
555 /// unnecessarily verbose errors.
556 fn_self_span_reported: FxHashSet<Span>,
557 /// Migration warnings to be reported for #56254. We delay reporting these
558 /// so that we can suppress the warning if there's a corresponding error
559 /// for the activation of the borrow.
560 reservation_warnings:
561 FxHashMap<BorrowIndex, (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)>,
562 /// This field keeps track of move errors that are to be reported for given move indices.
564 /// There are situations where many errors can be reported for a single move out (see #53807)
565 /// and we want only the best of those errors.
567 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
568 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
569 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
570 /// all move errors have been reported, any diagnostics in this map are added to the buffer
573 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
574 /// when errors in the map are being re-added to the error buffer so that errors with the
575 /// same primary span come out in a consistent order.
576 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'cx>)>,
577 /// This field keeps track of errors reported in the checking of uninitialized variables,
578 /// so that we don't report seemingly duplicate errors.
579 uninitialized_error_reported: FxHashSet<PlaceRef<'tcx>>,
580 /// Errors to be reported buffer
581 errors_buffer: Vec<Diagnostic>,
582 /// This field keeps track of all the local variables that are declared mut and are mutated.
583 /// Used for the warning issued by an unused mutable local variable.
584 used_mut: FxHashSet<Local>,
585 /// If the function we're checking is a closure, then we'll need to report back the list of
586 /// mutable upvars that have been used. This field keeps track of them.
587 used_mut_upvars: SmallVec<[Field; 8]>,
588 /// Region inference context. This contains the results from region inference and lets us e.g.
589 /// find out which CFG points are contained in each borrow region.
590 regioncx: Rc<RegionInferenceContext<'tcx>>,
592 /// The set of borrows extracted from the MIR
593 borrow_set: Rc<BorrowSet<'tcx>>,
595 /// Dominators for MIR
596 dominators: Dominators<BasicBlock>,
598 /// Information about upvars not necessarily preserved in types or MIR
599 upvars: Vec<Upvar<'tcx>>,
601 /// Names of local (user) variables (extracted from `var_debug_info`).
602 local_names: IndexVec<Local, Option<Symbol>>,
604 /// Record the region names generated for each region in the given
605 /// MIR def so that we can reuse them later in help/error messages.
606 region_names: RefCell<FxHashMap<RegionVid, RegionName>>,
608 /// The counter for generating new region names.
609 next_region_name: RefCell<usize>,
611 /// Results of Polonius analysis.
612 polonius_output: Option<Rc<PoloniusOutput>>,
616 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
617 // 2. loans made in overlapping scopes do not conflict
618 // 3. assignments do not affect things loaned out as immutable
619 // 4. moves do not affect things loaned out in any way
620 impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
621 type FlowState = Flows<'cx, 'tcx>;
623 fn visit_statement_before_primary_effect(
625 flow_state: &Flows<'cx, 'tcx>,
626 stmt: &'cx Statement<'tcx>,
629 debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state);
630 let span = stmt.source_info.span;
632 self.check_activations(location, span, flow_state);
635 StatementKind::Assign(box (lhs, ref rhs)) => {
636 self.consume_rvalue(location, (rhs, span), flow_state);
638 self.mutate_place(location, (*lhs, span), Shallow(None), JustWrite, flow_state);
640 StatementKind::FakeRead(box (_, ref place)) => {
641 // Read for match doesn't access any memory and is used to
642 // assert that a place is safe and live. So we don't have to
643 // do any checks here.
645 // FIXME: Remove check that the place is initialized. This is
646 // needed for now because matches don't have never patterns yet.
647 // So this is the only place we prevent
651 self.check_if_path_or_subpath_is_moved(
653 InitializationRequiringAction::Use,
654 (place.as_ref(), span),
658 StatementKind::SetDiscriminant { place, variant_index: _ } => {
659 self.mutate_place(location, (**place, span), Shallow(None), JustWrite, flow_state);
661 StatementKind::LlvmInlineAsm(ref asm) => {
662 for (o, output) in iter::zip(&asm.asm.outputs, &*asm.outputs) {
664 // FIXME(eddyb) indirect inline asm outputs should
665 // be encoded through MIR place derefs instead.
669 (Deep, Read(ReadKind::Copy)),
670 LocalMutationIsAllowed::No,
673 self.check_if_path_or_subpath_is_moved(
675 InitializationRequiringAction::Use,
676 (output.as_ref(), o.span),
683 if o.is_rw { Deep } else { Shallow(None) },
684 if o.is_rw { WriteAndRead } else { JustWrite },
689 for (_, input) in asm.inputs.iter() {
690 self.consume_operand(location, (input, span), flow_state);
694 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
699 "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
703 | StatementKind::Coverage(..)
704 | StatementKind::AscribeUserType(..)
705 | StatementKind::Retag { .. }
706 | StatementKind::StorageLive(..) => {
707 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
710 StatementKind::StorageDead(local) => {
713 (Place::from(*local), span),
714 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
715 LocalMutationIsAllowed::Yes,
722 fn visit_terminator_before_primary_effect(
724 flow_state: &Flows<'cx, 'tcx>,
725 term: &'cx Terminator<'tcx>,
728 debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
729 let span = term.source_info.span;
731 self.check_activations(loc, span, flow_state);
734 TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => {
735 self.consume_operand(loc, (discr, span), flow_state);
737 TerminatorKind::Drop { place, target: _, unwind: _ } => {
739 "visit_terminator_drop \
740 loc: {:?} term: {:?} place: {:?} span: {:?}",
741 loc, term, place, span
747 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
748 LocalMutationIsAllowed::Yes,
752 TerminatorKind::DropAndReplace {
754 value: ref new_value,
758 self.mutate_place(loc, (drop_place, span), Deep, JustWrite, flow_state);
759 self.consume_operand(loc, (new_value, span), flow_state);
761 TerminatorKind::Call {
769 self.consume_operand(loc, (func, span), flow_state);
771 self.consume_operand(loc, (arg, span), flow_state);
773 if let Some((dest, _ /*bb*/)) = *destination {
774 self.mutate_place(loc, (dest, span), Deep, JustWrite, flow_state);
777 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
778 self.consume_operand(loc, (cond, span), flow_state);
779 use rustc_middle::mir::AssertKind;
780 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
781 self.consume_operand(loc, (len, span), flow_state);
782 self.consume_operand(loc, (index, span), flow_state);
786 TerminatorKind::Yield { ref value, resume: _, resume_arg, drop: _ } => {
787 self.consume_operand(loc, (value, span), flow_state);
788 self.mutate_place(loc, (resume_arg, span), Deep, JustWrite, flow_state);
791 TerminatorKind::InlineAsm {
800 InlineAsmOperand::In { reg: _, ref value } => {
801 self.consume_operand(loc, (value, span), flow_state);
803 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
804 if let Some(place) = place {
814 InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
815 self.consume_operand(loc, (in_value, span), flow_state);
816 if let Some(out_place) = out_place {
826 InlineAsmOperand::Const { value: _ }
827 | InlineAsmOperand::SymFn { value: _ }
828 | InlineAsmOperand::SymStatic { def_id: _ } => {}
833 TerminatorKind::Goto { target: _ }
834 | TerminatorKind::Abort
835 | TerminatorKind::Unreachable
836 | TerminatorKind::Resume
837 | TerminatorKind::Return
838 | TerminatorKind::GeneratorDrop
839 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
840 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
841 // no data used, thus irrelevant to borrowck
846 fn visit_terminator_after_primary_effect(
848 flow_state: &Flows<'cx, 'tcx>,
849 term: &'cx Terminator<'tcx>,
852 let span = term.source_info.span;
855 TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
856 if self.movable_generator {
857 // Look for any active borrows to locals
858 let borrow_set = self.borrow_set.clone();
859 for i in flow_state.borrows.iter() {
860 let borrow = &borrow_set[i];
861 self.check_for_local_borrow(borrow, span);
866 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
867 // Returning from the function implicitly kills storage for all locals and statics.
868 // Often, the storage will already have been killed by an explicit
869 // StorageDead, but we don't always emit those (notably on unwind paths),
870 // so this "extra check" serves as a kind of backup.
871 let borrow_set = self.borrow_set.clone();
872 for i in flow_state.borrows.iter() {
873 let borrow = &borrow_set[i];
874 self.check_for_invalidation_at_exit(loc, borrow, span);
878 TerminatorKind::Abort
879 | TerminatorKind::Assert { .. }
880 | TerminatorKind::Call { .. }
881 | TerminatorKind::Drop { .. }
882 | TerminatorKind::DropAndReplace { .. }
883 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
884 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
885 | TerminatorKind::Goto { .. }
886 | TerminatorKind::SwitchInt { .. }
887 | TerminatorKind::Unreachable
888 | TerminatorKind::InlineAsm { .. } => {}
893 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
899 use self::AccessDepth::{Deep, Shallow};
900 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
902 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
903 enum ArtificialField {
908 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
910 /// From the RFC: "A *shallow* access means that the immediate
911 /// fields reached at P are accessed, but references or pointers
912 /// found within are not dereferenced. Right now, the only access
913 /// that is shallow is an assignment like `x = ...;`, which would
914 /// be a *shallow write* of `x`."
915 Shallow(Option<ArtificialField>),
917 /// From the RFC: "A *deep* access means that all data reachable
918 /// through the given place may be invalidated or accesses by
922 /// Access is Deep only when there is a Drop implementation that
923 /// can reach the data behind the reference.
927 /// Kind of access to a value: read or write
928 /// (For informational purposes only)
929 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
931 /// From the RFC: "A *read* means that the existing data may be
932 /// read, but will not be changed."
935 /// From the RFC: "A *write* means that the data may be mutated to
936 /// new values or otherwise invalidated (for example, it could be
937 /// de-initialized, as in a move operation).
940 /// For two-phase borrows, we distinguish a reservation (which is treated
941 /// like a Read) from an activation (which is treated like a write), and
942 /// each of those is furthermore distinguished from Reads/Writes above.
943 Reservation(WriteKind),
944 Activation(WriteKind, BorrowIndex),
947 /// Kind of read access to a value
948 /// (For informational purposes only)
949 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
955 /// Kind of write access to a value
956 /// (For informational purposes only)
957 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
960 MutableBorrow(BorrowKind),
965 /// When checking permissions for a place access, this flag is used to indicate that an immutable
966 /// local place can be mutated.
968 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
969 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
970 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
971 // `is_declared_mutable()`.
972 // - Take flow state into consideration in `is_assignable()` for local variables.
973 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
974 enum LocalMutationIsAllowed {
976 /// We want use of immutable upvars to cause a "write to immutable upvar"
977 /// error, not an "reassignment" error.
982 #[derive(Copy, Clone, Debug)]
983 enum InitializationRequiringAction {
992 struct RootPlace<'tcx> {
994 place_projection: &'tcx [PlaceElem<'tcx>],
995 is_local_mutation_allowed: LocalMutationIsAllowed,
998 impl InitializationRequiringAction {
999 fn as_noun(self) -> &'static str {
1001 InitializationRequiringAction::Update => "update",
1002 InitializationRequiringAction::Borrow => "borrow",
1003 InitializationRequiringAction::MatchOn => "use", // no good noun
1004 InitializationRequiringAction::Use => "use",
1005 InitializationRequiringAction::Assignment => "assign",
1006 InitializationRequiringAction::PartialAssignment => "assign to part",
1010 fn as_verb_in_past_tense(self) -> &'static str {
1012 InitializationRequiringAction::Update => "updated",
1013 InitializationRequiringAction::Borrow => "borrowed",
1014 InitializationRequiringAction::MatchOn => "matched on",
1015 InitializationRequiringAction::Use => "used",
1016 InitializationRequiringAction::Assignment => "assigned",
1017 InitializationRequiringAction::PartialAssignment => "partially assigned",
1022 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
1023 fn body(&self) -> &'cx Body<'tcx> {
1027 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
1028 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
1029 /// place is initialized and (b) it is not borrowed in some way that would prevent this
1032 /// Returns `true` if an error is reported.
1036 place_span: (Place<'tcx>, Span),
1037 kind: (AccessDepth, ReadOrWrite),
1038 is_local_mutation_allowed: LocalMutationIsAllowed,
1039 flow_state: &Flows<'cx, 'tcx>,
1041 let (sd, rw) = kind;
1043 if let Activation(_, borrow_index) = rw {
1044 if self.reservation_error_reported.contains(&place_span.0) {
1046 "skipping access_place for activation of invalid reservation \
1047 place: {:?} borrow_index: {:?}",
1048 place_span.0, borrow_index
1054 // Check is_empty() first because it's the common case, and doing that
1055 // way we avoid the clone() call.
1056 if !self.access_place_error_reported.is_empty()
1057 && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
1060 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
1066 let mutability_error = self.check_access_permissions(
1069 is_local_mutation_allowed,
1073 let conflict_error =
1074 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
1076 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
1077 // Suppress this warning when there's an error being emitted for the
1078 // same borrow: fixing the error is likely to fix the warning.
1079 self.reservation_warnings.remove(&borrow_idx);
1082 if conflict_error || mutability_error {
1083 debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
1085 self.access_place_error_reported.insert((place_span.0, place_span.1));
1089 fn check_access_for_conflict(
1092 place_span: (Place<'tcx>, Span),
1095 flow_state: &Flows<'cx, 'tcx>,
1098 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1099 location, place_span, sd, rw,
1102 let mut error_reported = false;
1103 let tcx = self.infcx.tcx;
1104 let body = self.body;
1105 let borrow_set = self.borrow_set.clone();
1107 // Use polonius output if it has been enabled.
1108 let polonius_output = self.polonius_output.clone();
1109 let borrows_in_scope = if let Some(polonius) = &polonius_output {
1110 let location = self.location_table.start_index(location);
1111 Either::Left(polonius.errors_at(location).iter().copied())
1113 Either::Right(flow_state.borrows.iter())
1116 each_borrow_involving_path(
1124 |this, borrow_index, borrow| match (rw, borrow.kind) {
1125 // Obviously an activation is compatible with its own
1126 // reservation (or even prior activating uses of same
1127 // borrow); so don't check if they interfere.
1129 // NOTE: *reservations* do conflict with themselves;
1130 // thus aren't injecting unsoundenss w/ this check.)
1131 (Activation(_, activating), _) if activating == borrow_index => {
1133 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1134 skipping {:?} b/c activation of same borrow_index",
1138 (borrow_index, borrow),
1143 (Read(_), BorrowKind::Shared | BorrowKind::Shallow)
1145 Read(ReadKind::Borrow(BorrowKind::Shallow)),
1146 BorrowKind::Unique | BorrowKind::Mut { .. },
1147 ) => Control::Continue,
1149 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1150 // Handled by initialization checks.
1154 (Read(kind), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
1155 // Reading from mere reservations of mutable-borrows is OK.
1156 if !is_active(&this.dominators, borrow, location) {
1157 assert!(allow_two_phase_borrow(borrow.kind));
1158 return Control::Continue;
1161 error_reported = true;
1164 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1165 .buffer(&mut this.errors_buffer);
1167 ReadKind::Borrow(bk) => {
1168 this.report_conflicting_borrow(location, place_span, bk, borrow)
1169 .buffer(&mut this.errors_buffer);
1176 Reservation(WriteKind::MutableBorrow(bk)),
1177 BorrowKind::Shallow | BorrowKind::Shared,
1178 ) if { tcx.migrate_borrowck() && this.borrow_set.contains(&location) } => {
1179 let bi = this.borrow_set.get_index_of(&location).unwrap();
1181 "recording invalid reservation of place: {:?} with \
1182 borrow index {:?} as warning",
1185 // rust-lang/rust#56254 - This was previously permitted on
1186 // the 2018 edition so we emit it as a warning. We buffer
1187 // these sepately so that we only emit a warning if borrow
1188 // checking was otherwise successful.
1189 this.reservation_warnings
1190 .insert(bi, (place_span.0, place_span.1, location, bk, borrow.clone()));
1192 // Don't suppress actual errors.
1196 (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1198 Reservation(..) => {
1200 "recording invalid reservation of \
1204 this.reservation_error_reported.insert(place_span.0);
1206 Activation(_, activating) => {
1208 "observing check_place for activation of \
1209 borrow_index: {:?}",
1213 Read(..) | Write(..) => {}
1216 error_reported = true;
1218 WriteKind::MutableBorrow(bk) => {
1219 this.report_conflicting_borrow(location, place_span, bk, borrow)
1220 .buffer(&mut this.errors_buffer);
1222 WriteKind::StorageDeadOrDrop => this
1223 .report_borrowed_value_does_not_live_long_enough(
1229 WriteKind::Mutate => {
1230 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1232 WriteKind::Move => {
1233 this.report_move_out_while_borrowed(location, place_span, borrow)
1247 place_span: (Place<'tcx>, Span),
1250 flow_state: &Flows<'cx, 'tcx>,
1252 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1254 MutateMode::WriteAndRead => {
1255 self.check_if_path_or_subpath_is_moved(
1257 InitializationRequiringAction::Update,
1258 (place_span.0.as_ref(), place_span.1),
1262 MutateMode::JustWrite => {
1263 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1267 // Special case: you can assign an immutable local variable
1268 // (e.g., `x = ...`) so long as it has never been initialized
1269 // before (at this point in the flow).
1270 if let Some(local) = place_span.0.as_local() {
1271 if let Mutability::Not = self.body.local_decls[local].mutability {
1272 // check for reassignments to immutable local variables
1273 self.check_if_reassignment_to_immutable_state(
1274 location, local, place_span, flow_state,
1280 // Otherwise, use the normal access permission rules.
1284 (kind, Write(WriteKind::Mutate)),
1285 LocalMutationIsAllowed::No,
1293 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1294 flow_state: &Flows<'cx, 'tcx>,
1297 Rvalue::Ref(_ /*rgn*/, bk, place) => {
1298 let access_kind = match bk {
1299 BorrowKind::Shallow => {
1300 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1302 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1303 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1304 let wk = WriteKind::MutableBorrow(bk);
1305 if allow_two_phase_borrow(bk) {
1306 (Deep, Reservation(wk))
1317 LocalMutationIsAllowed::No,
1321 let action = if bk == BorrowKind::Shallow {
1322 InitializationRequiringAction::MatchOn
1324 InitializationRequiringAction::Borrow
1327 self.check_if_path_or_subpath_is_moved(
1330 (place.as_ref(), span),
1335 Rvalue::AddressOf(mutability, place) => {
1336 let access_kind = match mutability {
1337 Mutability::Mut => (
1339 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1340 allow_two_phase_borrow: false,
1343 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1350 LocalMutationIsAllowed::No,
1354 self.check_if_path_or_subpath_is_moved(
1356 InitializationRequiringAction::Borrow,
1357 (place.as_ref(), span),
1362 Rvalue::ThreadLocalRef(_) => {}
1364 Rvalue::Use(ref operand)
1365 | Rvalue::Repeat(ref operand, _)
1366 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1367 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/)
1368 | Rvalue::ShallowInitBox(ref operand, _ /*ty*/) => {
1369 self.consume_operand(location, (operand, span), flow_state)
1372 Rvalue::Len(place) | Rvalue::Discriminant(place) => {
1373 let af = match *rvalue {
1374 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1375 Rvalue::Discriminant(..) => None,
1376 _ => unreachable!(),
1381 (Shallow(af), Read(ReadKind::Copy)),
1382 LocalMutationIsAllowed::No,
1385 self.check_if_path_or_subpath_is_moved(
1387 InitializationRequiringAction::Use,
1388 (place.as_ref(), span),
1393 Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2))
1394 | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => {
1395 self.consume_operand(location, (operand1, span), flow_state);
1396 self.consume_operand(location, (operand2, span), flow_state);
1399 Rvalue::NullaryOp(_op, _ty) => {
1400 // nullary ops take no dynamic input; no borrowck effect.
1402 // FIXME: is above actually true? Do we want to track
1403 // the fact that uninitialized data can be created via
1407 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1408 // We need to report back the list of mutable upvars that were
1409 // moved into the closure and subsequently used by the closure,
1410 // in order to populate our used_mut set.
1411 match **aggregate_kind {
1412 AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
1413 let BorrowCheckResult { used_mut_upvars, .. } =
1414 self.infcx.tcx.mir_borrowck(def_id.expect_local());
1415 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1416 for field in used_mut_upvars {
1417 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1420 AggregateKind::Adt(..)
1421 | AggregateKind::Array(..)
1422 | AggregateKind::Tuple { .. } => (),
1425 for operand in operands {
1426 self.consume_operand(location, (operand, span), flow_state);
1432 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1433 let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1434 // We have three possibilities here:
1435 // a. We are modifying something through a mut-ref
1436 // b. We are modifying something that is local to our parent
1437 // c. Current body is a nested closure, and we are modifying path starting from
1438 // a Place captured by our parent closure.
1440 // Handle (c), the path being modified is exactly the path captured by our parent
1441 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1442 this.used_mut_upvars.push(field);
1446 for (place_ref, proj) in place.iter_projections().rev() {
1448 if proj == ProjectionElem::Deref {
1449 match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1450 // We aren't modifying a variable directly
1451 ty::Ref(_, _, hir::Mutability::Mut) => return,
1458 if let Some(field) = this.is_upvar_field_projection(place_ref) {
1459 this.used_mut_upvars.push(field);
1465 this.used_mut.insert(place.local);
1468 // This relies on the current way that by-value
1469 // captures of a closure are copied/moved directly
1470 // when generating MIR.
1472 Operand::Move(place) | Operand::Copy(place) => {
1473 match place.as_local() {
1474 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1475 if self.body.local_decls[local].ty.is_mutable_ptr() {
1476 // The variable will be marked as mutable by the borrow.
1479 // This is an edge case where we have a `move` closure
1480 // inside a non-move closure, and the inner closure
1481 // contains a mutation:
1484 // || { move || { i += 1; }; };
1486 // In this case our usual strategy of assuming that the
1487 // variable will be captured by mutable reference is
1488 // wrong, since `i` can be copied into the inner
1489 // closure from a shared reference.
1491 // As such we have to search for the local that this
1492 // capture comes from and mark it as being used as mut.
1494 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1495 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1496 &self.move_data.inits[init_index]
1498 bug!("temporary should be initialized exactly once")
1501 let loc = match init.location {
1502 InitLocation::Statement(stmt) => stmt,
1503 _ => bug!("temporary initialized in arguments"),
1506 let body = self.body;
1507 let bbd = &body[loc.block];
1508 let stmt = &bbd.statements[loc.statement_index];
1509 debug!("temporary assigned in: stmt={:?}", stmt);
1511 if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, source))) = stmt.kind
1513 propagate_closure_used_mut_place(self, source);
1516 "closures should only capture user variables \
1517 or references to user variables"
1521 _ => propagate_closure_used_mut_place(self, place),
1524 Operand::Constant(..) => {}
1531 (operand, span): (&'cx Operand<'tcx>, Span),
1532 flow_state: &Flows<'cx, 'tcx>,
1535 Operand::Copy(place) => {
1536 // copy of place: check if this is "copy of frozen path"
1537 // (FIXME: see check_loans.rs)
1541 (Deep, Read(ReadKind::Copy)),
1542 LocalMutationIsAllowed::No,
1546 // Finally, check if path was already moved.
1547 self.check_if_path_or_subpath_is_moved(
1549 InitializationRequiringAction::Use,
1550 (place.as_ref(), span),
1554 Operand::Move(place) => {
1555 // move of place: check if this is move of already borrowed path
1559 (Deep, Write(WriteKind::Move)),
1560 LocalMutationIsAllowed::Yes,
1564 // Finally, check if path was already moved.
1565 self.check_if_path_or_subpath_is_moved(
1567 InitializationRequiringAction::Use,
1568 (place.as_ref(), span),
1572 Operand::Constant(_) => {}
1576 /// Checks whether a borrow of this place is invalidated when the function
1578 fn check_for_invalidation_at_exit(
1581 borrow: &BorrowData<'tcx>,
1584 debug!("check_for_invalidation_at_exit({:?})", borrow);
1585 let place = borrow.borrowed_place;
1586 let mut root_place = PlaceRef { local: place.local, projection: &[] };
1588 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1589 // we just know that all locals are dropped at function exit (otherwise
1590 // we'll have a memory leak) and assume that all statics have a destructor.
1592 // FIXME: allow thread-locals to borrow other thread locals?
1594 let (might_be_alive, will_be_dropped) =
1595 if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1596 // Thread-locals might be dropped after the function exits
1597 // We have to dereference the outer reference because
1598 // borrows don't conflict behind shared references.
1599 root_place.projection = DEREF_PROJECTION;
1602 (false, self.locals_are_invalidated_at_exit)
1605 if !will_be_dropped {
1606 debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
1610 let sd = if might_be_alive { Deep } else { Shallow(None) };
1612 if places_conflict::borrow_conflicts_with_place(
1619 places_conflict::PlaceConflictBias::Overlap,
1621 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1622 // FIXME: should be talking about the region lifetime instead
1623 // of just a span here.
1624 let span = self.infcx.tcx.sess.source_map().end_point(span);
1625 self.report_borrowed_value_does_not_live_long_enough(
1634 /// Reports an error if this is a borrow of local data.
1635 /// This is called for all Yield expressions on movable generators
1636 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1637 debug!("check_for_local_borrow({:?})", borrow);
1639 if borrow_of_local_data(borrow.borrowed_place) {
1640 let err = self.cannot_borrow_across_generator_yield(
1641 self.retrieve_borrow_spans(borrow).var_or_use(),
1645 err.buffer(&mut self.errors_buffer);
1649 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1650 // Two-phase borrow support: For each activation that is newly
1651 // generated at this statement, check if it interferes with
1653 let borrow_set = self.borrow_set.clone();
1654 for &borrow_index in borrow_set.activations_at_location(location) {
1655 let borrow = &borrow_set[borrow_index];
1657 // only mutable borrows should be 2-phase
1658 assert!(match borrow.kind {
1659 BorrowKind::Shared | BorrowKind::Shallow => false,
1660 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1665 (borrow.borrowed_place, span),
1666 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1667 LocalMutationIsAllowed::No,
1670 // We do not need to call `check_if_path_or_subpath_is_moved`
1671 // again, as we already called it when we made the
1672 // initial reservation.
1676 fn check_if_reassignment_to_immutable_state(
1680 place_span: (Place<'tcx>, Span),
1681 flow_state: &Flows<'cx, 'tcx>,
1683 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1685 // Check if any of the initializiations of `local` have happened yet:
1686 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1687 // And, if so, report an error.
1688 let init = &self.move_data.inits[init_index];
1689 let span = init.span(&self.body);
1690 self.report_illegal_reassignment(location, place_span, span, place_span.0);
1694 fn check_if_full_path_is_moved(
1697 desired_action: InitializationRequiringAction,
1698 place_span: (PlaceRef<'tcx>, Span),
1699 flow_state: &Flows<'cx, 'tcx>,
1701 let maybe_uninits = &flow_state.uninits;
1705 // 1. Move of `a.b.c`, use of `a.b.c`
1706 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1707 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1708 // partial initialization support, one might have `a.x`
1709 // initialized but not `a.b`.
1713 // 4. Move of `a.b.c`, use of `a.b.d`
1714 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1715 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1716 // must have been initialized for the use to be sound.
1717 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1719 // The dataflow tracks shallow prefixes distinctly (that is,
1720 // field-accesses on P distinctly from P itself), in order to
1721 // track substructure initialization separately from the whole
1724 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1725 // which we have a MovePath is `a.b`, then that means that the
1726 // initialization state of `a.b` is all we need to inspect to
1727 // know if `a.b.c` is valid (and from that we infer that the
1728 // dereference and `.d` access is also valid, since we assume
1729 // `a.b.c` is assigned a reference to an initialized and
1730 // well-formed record structure.)
1732 // Therefore, if we seek out the *closest* prefix for which we
1733 // have a MovePath, that should capture the initialization
1734 // state for the place scenario.
1736 // This code covers scenarios 1, 2, and 3.
1738 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1739 let (prefix, mpi) = self.move_path_closest_to(place_span.0);
1740 if maybe_uninits.contains(mpi) {
1741 self.report_use_of_moved_or_uninitialized(
1744 (prefix, place_span.0, place_span.1),
1747 } // Only query longest prefix with a MovePath, not further
1748 // ancestors; dataflow recurs on children when parents
1749 // move (to support partial (re)inits).
1751 // (I.e., querying parents breaks scenario 7; but may want
1752 // to do such a query based on partial-init feature-gate.)
1755 /// Subslices correspond to multiple move paths, so we iterate through the
1756 /// elements of the base array. For each element we check
1758 /// * Does this element overlap with our slice.
1759 /// * Is any part of it uninitialized.
1760 fn check_if_subslice_element_is_moved(
1763 desired_action: InitializationRequiringAction,
1764 place_span: (PlaceRef<'tcx>, Span),
1765 maybe_uninits: &BitSet<MovePathIndex>,
1769 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1770 let move_paths = &self.move_data.move_paths;
1772 let root_path = &move_paths[mpi];
1773 for (child_mpi, child_move_path) in root_path.children(move_paths) {
1774 let last_proj = child_move_path.place.projection.last().unwrap();
1775 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
1776 debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
1778 if (from..to).contains(offset) {
1780 self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
1781 maybe_uninits.contains(mpi)
1784 if let Some(uninit_child) = uninit_child {
1785 self.report_use_of_moved_or_uninitialized(
1788 (place_span.0, place_span.0, place_span.1),
1791 return; // don't bother finding other problems.
1799 fn check_if_path_or_subpath_is_moved(
1802 desired_action: InitializationRequiringAction,
1803 place_span: (PlaceRef<'tcx>, Span),
1804 flow_state: &Flows<'cx, 'tcx>,
1806 let maybe_uninits = &flow_state.uninits;
1810 // 1. Move of `a.b.c`, use of `a` or `a.b`
1811 // partial initialization support, one might have `a.x`
1812 // initialized but not `a.b`.
1813 // 2. All bad scenarios from `check_if_full_path_is_moved`
1817 // 3. Move of `a.b.c`, use of `a.b.d`
1818 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1819 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1820 // must have been initialized for the use to be sound.
1821 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1823 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1825 if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
1826 place_span.0.last_projection()
1828 let place_ty = place_base.ty(self.body(), self.infcx.tcx);
1829 if let ty::Array(..) = place_ty.ty.kind() {
1830 self.check_if_subslice_element_is_moved(
1833 (place_base, place_span.1),
1842 // A move of any shallow suffix of `place` also interferes
1843 // with an attempt to use `place`. This is scenario 3 above.
1845 // (Distinct from handling of scenarios 1+2+4 above because
1846 // `place` does not interfere with suffixes of its prefixes,
1847 // e.g., `a.b.c` does not interfere with `a.b.d`)
1849 // This code covers scenario 1.
1851 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1852 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1853 let uninit_mpi = self
1855 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
1857 if let Some(uninit_mpi) = uninit_mpi {
1858 self.report_use_of_moved_or_uninitialized(
1861 (place_span.0, place_span.0, place_span.1),
1864 return; // don't bother finding other problems.
1869 /// Currently MoveData does not store entries for all places in
1870 /// the input MIR. For example it will currently filter out
1871 /// places that are Copy; thus we do not track places of shared
1872 /// reference type. This routine will walk up a place along its
1873 /// prefixes, searching for a foundational place that *is*
1874 /// tracked in the MoveData.
1876 /// An Err result includes a tag indicated why the search failed.
1877 /// Currently this can only occur if the place is built off of a
1878 /// static variable, as we do not track those in the MoveData.
1879 fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
1880 match self.move_data.rev_lookup.find(place) {
1881 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
1882 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
1884 LookupResult::Parent(None) => panic!("should have move path for every Local"),
1888 fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
1889 // If returns None, then there is no move path corresponding
1890 // to a direct owner of `place` (which means there is nothing
1891 // that borrowck tracks for its analysis).
1893 match self.move_data.rev_lookup.find(place) {
1894 LookupResult::Parent(_) => None,
1895 LookupResult::Exact(mpi) => Some(mpi),
1899 fn check_if_assigned_path_is_moved(
1902 (place, span): (Place<'tcx>, Span),
1903 flow_state: &Flows<'cx, 'tcx>,
1905 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1907 // None case => assigning to `x` does not require `x` be initialized.
1908 for (place_base, elem) in place.iter_projections().rev() {
1910 ProjectionElem::Index(_/*operand*/) |
1911 ProjectionElem::ConstantIndex { .. } |
1912 // assigning to P[i] requires P to be valid.
1913 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1914 // assigning to (P->variant) is okay if assigning to `P` is okay
1916 // FIXME: is this true even if P is an adt with a dtor?
1919 // assigning to (*P) requires P to be initialized
1920 ProjectionElem::Deref => {
1921 self.check_if_full_path_is_moved(
1922 location, InitializationRequiringAction::Use,
1923 (place_base, span), flow_state);
1924 // (base initialized; no need to
1929 ProjectionElem::Subslice { .. } => {
1930 panic!("we don't allow assignments to subslices, location: {:?}",
1934 ProjectionElem::Field(..) => {
1935 // if type of `P` has a dtor, then
1936 // assigning to `P.f` requires `P` itself
1937 // be already initialized
1938 let tcx = self.infcx.tcx;
1939 let base_ty = place_base.ty(self.body(), tcx).ty;
1940 match base_ty.kind() {
1941 ty::Adt(def, _) if def.has_dtor(tcx) => {
1942 self.check_if_path_or_subpath_is_moved(
1943 location, InitializationRequiringAction::Assignment,
1944 (place_base, span), flow_state);
1946 // (base initialized; no need to
1951 // Once `let s; s.x = V; read(s.x);`,
1952 // is allowed, remove this match arm.
1953 ty::Adt(..) | ty::Tuple(..) => {
1954 check_parent_of_field(self, location, place_base, span, flow_state);
1956 // rust-lang/rust#21232, #54499, #54986: during period where we reject
1957 // partial initialization, do not complain about unnecessary `mut` on
1958 // an attempt to do a partial initialization.
1959 self.used_mut.insert(place.local);
1968 fn check_parent_of_field<'cx, 'tcx>(
1969 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1971 base: PlaceRef<'tcx>,
1973 flow_state: &Flows<'cx, 'tcx>,
1975 // rust-lang/rust#21232: Until Rust allows reads from the
1976 // initialized parts of partially initialized structs, we
1977 // will, starting with the 2018 edition, reject attempts
1978 // to write to structs that are not fully initialized.
1980 // In other words, *until* we allow this:
1982 // 1. `let mut s; s.x = Val; read(s.x);`
1984 // we will for now disallow this:
1986 // 2. `let mut s; s.x = Val;`
1990 // 3. `let mut s = ...; drop(s); s.x=Val;`
1992 // This does not use check_if_path_or_subpath_is_moved,
1993 // because we want to *allow* reinitializations of fields:
1994 // e.g., want to allow
1996 // `let mut s = ...; drop(s.x); s.x=Val;`
1998 // This does not use check_if_full_path_is_moved on
1999 // `base`, because that would report an error about the
2000 // `base` as a whole, but in this scenario we *really*
2001 // want to report an error about the actual thing that was
2002 // moved, which may be some prefix of `base`.
2004 // Shallow so that we'll stop at any dereference; we'll
2005 // report errors about issues with such bases elsewhere.
2006 let maybe_uninits = &flow_state.uninits;
2008 // Find the shortest uninitialized prefix you can reach
2009 // without going over a Deref.
2010 let mut shortest_uninit_seen = None;
2011 for prefix in this.prefixes(base, PrefixSet::Shallow) {
2012 let mpi = match this.move_path_for_place(prefix) {
2017 if maybe_uninits.contains(mpi) {
2019 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
2020 shortest_uninit_seen,
2023 shortest_uninit_seen = Some((prefix, mpi));
2025 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
2029 if let Some((prefix, mpi)) = shortest_uninit_seen {
2030 // Check for a reassignment into an uninitialized field of a union (for example,
2031 // after a move out). In this case, do not report an error here. There is an
2032 // exception, if this is the first assignment into the union (that is, there is
2033 // no move out from an earlier location) then this is an attempt at initialization
2034 // of the union - we should error in that case.
2035 let tcx = this.infcx.tcx;
2036 if base.ty(this.body(), tcx).ty.is_union() {
2037 if this.move_data.path_map[mpi].iter().any(|moi| {
2038 this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
2044 this.report_use_of_moved_or_uninitialized(
2046 InitializationRequiringAction::PartialAssignment,
2047 (prefix, base, span),
2054 /// Checks the permissions for the given place and read or write kind
2056 /// Returns `true` if an error is reported.
2057 fn check_access_permissions(
2059 (place, span): (Place<'tcx>, Span),
2061 is_local_mutation_allowed: LocalMutationIsAllowed,
2062 flow_state: &Flows<'cx, 'tcx>,
2066 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
2067 place, kind, is_local_mutation_allowed
2074 Reservation(WriteKind::MutableBorrow(
2075 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
2077 | Write(WriteKind::MutableBorrow(
2078 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
2080 let is_local_mutation_allowed = match borrow_kind {
2081 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
2082 BorrowKind::Mut { .. } => is_local_mutation_allowed,
2083 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
2085 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2087 self.add_used_mut(root_place, flow_state);
2091 error_access = AccessKind::MutableBorrow;
2092 the_place_err = place_err;
2096 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
2097 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2099 self.add_used_mut(root_place, flow_state);
2103 error_access = AccessKind::Mutate;
2104 the_place_err = place_err;
2111 | WriteKind::StorageDeadOrDrop
2112 | WriteKind::MutableBorrow(BorrowKind::Shared)
2113 | WriteKind::MutableBorrow(BorrowKind::Shallow),
2117 | WriteKind::StorageDeadOrDrop
2118 | WriteKind::MutableBorrow(BorrowKind::Shared)
2119 | WriteKind::MutableBorrow(BorrowKind::Shallow),
2121 if let (Err(_), true) = (
2122 self.is_mutable(place.as_ref(), is_local_mutation_allowed),
2123 self.errors_buffer.is_empty(),
2125 // rust-lang/rust#46908: In pure NLL mode this code path should be
2126 // unreachable, but we use `delay_span_bug` because we can hit this when
2127 // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
2128 // enabled. We don't want to ICE for that case, as other errors will have
2129 // been emitted (#52262).
2130 self.infcx.tcx.sess.delay_span_bug(
2133 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2141 // permission checks are done at Reservation point.
2147 | BorrowKind::Mut { .. }
2148 | BorrowKind::Shared
2149 | BorrowKind::Shallow,
2153 // Access authorized
2158 // rust-lang/rust#21232, #54986: during period where we reject
2159 // partial initialization, do not complain about mutability
2160 // errors except for actual mutation (as opposed to an attempt
2161 // to do a partial initialization).
2162 let previously_initialized =
2163 self.is_local_ever_initialized(place.local, flow_state).is_some();
2165 // at this point, we have set up the error reporting state.
2166 if previously_initialized {
2167 self.report_mutability_error(place, span, the_place_err, error_access, location);
2174 fn is_local_ever_initialized(
2177 flow_state: &Flows<'cx, 'tcx>,
2178 ) -> Option<InitIndex> {
2179 let mpi = self.move_data.rev_lookup.find_local(local);
2180 let ii = &self.move_data.init_path_map[mpi];
2182 if flow_state.ever_inits.contains(index) {
2189 /// Adds the place into the used mutable variables set
2190 fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2192 RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2193 // If the local may have been initialized, and it is now currently being
2194 // mutated, then it is justified to be annotated with the `mut`
2195 // keyword, since the mutation may be a possible reassignment.
2196 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2197 && self.is_local_ever_initialized(local, flow_state).is_some()
2199 self.used_mut.insert(local);
2204 place_projection: _,
2205 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2209 place_projection: place_projection @ [.., _],
2210 is_local_mutation_allowed: _,
2212 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2214 projection: place_projection,
2216 self.used_mut_upvars.push(field);
2222 /// Whether this value can be written or borrowed mutably.
2223 /// Returns the root place if the place passed in is a projection.
2226 place: PlaceRef<'tcx>,
2227 is_local_mutation_allowed: LocalMutationIsAllowed,
2228 ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2229 debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2230 match place.last_projection() {
2232 let local = &self.body.local_decls[place.local];
2233 match local.mutability {
2234 Mutability::Not => match is_local_mutation_allowed {
2235 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2236 place_local: place.local,
2237 place_projection: place.projection,
2238 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2240 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2241 place_local: place.local,
2242 place_projection: place.projection,
2243 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2245 LocalMutationIsAllowed::No => Err(place),
2247 Mutability::Mut => Ok(RootPlace {
2248 place_local: place.local,
2249 place_projection: place.projection,
2250 is_local_mutation_allowed,
2254 Some((place_base, elem)) => {
2256 ProjectionElem::Deref => {
2257 let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2259 // Check the kind of deref to decide
2260 match base_ty.kind() {
2261 ty::Ref(_, _, mutbl) => {
2263 // Shared borrowed data is never mutable
2264 hir::Mutability::Not => Err(place),
2265 // Mutably borrowed data is mutable, but only if we have a
2266 // unique path to the `&mut`
2267 hir::Mutability::Mut => {
2268 let mode = match self.is_upvar_field_projection(place) {
2269 Some(field) if self.upvars[field.index()].by_ref => {
2270 is_local_mutation_allowed
2272 _ => LocalMutationIsAllowed::Yes,
2275 self.is_mutable(place_base, mode)
2279 ty::RawPtr(tnm) => {
2281 // `*const` raw pointers are not mutable
2282 hir::Mutability::Not => Err(place),
2283 // `*mut` raw pointers are always mutable, regardless of
2284 // context. The users have to check by themselves.
2285 hir::Mutability::Mut => Ok(RootPlace {
2286 place_local: place.local,
2287 place_projection: place.projection,
2288 is_local_mutation_allowed,
2292 // `Box<T>` owns its content, so mutable if its location is mutable
2293 _ if base_ty.is_box() => {
2294 self.is_mutable(place_base, is_local_mutation_allowed)
2296 // Deref should only be for reference, pointers or boxes
2297 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2300 // All other projections are owned by their base path, so mutable if
2301 // base path is mutable
2302 ProjectionElem::Field(..)
2303 | ProjectionElem::Index(..)
2304 | ProjectionElem::ConstantIndex { .. }
2305 | ProjectionElem::Subslice { .. }
2306 | ProjectionElem::Downcast(..) => {
2307 let upvar_field_projection = self.is_upvar_field_projection(place);
2308 if let Some(field) = upvar_field_projection {
2309 let upvar = &self.upvars[field.index()];
2311 "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2312 place={:?}, place_base={:?}",
2313 upvar, is_local_mutation_allowed, place, place_base
2315 match (upvar.place.mutability, is_local_mutation_allowed) {
2318 LocalMutationIsAllowed::No
2319 | LocalMutationIsAllowed::ExceptUpvars,
2321 (Mutability::Not, LocalMutationIsAllowed::Yes)
2322 | (Mutability::Mut, _) => {
2323 // Subtle: this is an upvar
2324 // reference, so it looks like
2325 // `self.foo` -- we want to double
2326 // check that the location `*self`
2327 // is mutable (i.e., this is not a
2328 // `Fn` closure). But if that
2329 // check succeeds, we want to
2330 // *blame* the mutability on
2331 // `place` (that is,
2332 // `self.foo`). This is used to
2333 // propagate the info about
2334 // whether mutability declarations
2335 // are used outwards, so that we register
2336 // the outer variable as mutable. Otherwise a
2337 // test like this fails to record the `mut`
2341 // fn foo<F: FnOnce()>(_f: F) { }
2343 // let var = Vec::new();
2350 self.is_mutable(place_base, is_local_mutation_allowed)?;
2352 place_local: place.local,
2353 place_projection: place.projection,
2354 is_local_mutation_allowed,
2359 self.is_mutable(place_base, is_local_mutation_allowed)
2367 /// If `place` is a field projection, and the field is being projected from a closure type,
2368 /// then returns the index of the field being projected. Note that this closure will always
2369 /// be `self` in the current MIR, because that is the only time we directly access the fields
2370 /// of a closure type.
2371 fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> {
2372 path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2376 /// The degree of overlap between 2 places for borrow-checking.
2378 /// The places might partially overlap - in this case, we give
2379 /// up and say that they might conflict. This occurs when
2380 /// different fields of a union are borrowed. For example,
2381 /// if `u` is a union, we have no way of telling how disjoint
2382 /// `u.a.x` and `a.b.y` are.
2384 /// The places have the same type, and are either completely disjoint
2385 /// or equal - i.e., they can't "partially" overlap as can occur with
2386 /// unions. This is the "base case" on which we recur for extensions
2389 /// The places are disjoint, so we know all extensions of them
2390 /// will also be disjoint.