1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_data_structures::graph::dominators::Dominators;
5 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorReported};
7 use rustc_hir::def_id::LocalDefId;
8 use rustc_hir::{HirId, Node};
9 use rustc_index::bit_set::BitSet;
10 use rustc_index::vec::IndexVec;
11 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
12 use rustc_middle::mir::{
13 traversal, Body, ClearCrossCrate, Local, Location, Mutability, Operand, Place, PlaceElem,
16 use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
17 use rustc_middle::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
18 use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind};
19 use rustc_middle::ty::query::Providers;
20 use rustc_middle::ty::{self, ParamEnv, RegionVid, TyCtxt};
21 use rustc_session::lint::builtin::{MUTABLE_BORROW_RESERVATION_CONFLICT, UNUSED_MUT};
22 use rustc_span::{Span, Symbol, DUMMY_SP};
25 use smallvec::SmallVec;
26 use std::cell::RefCell;
27 use std::collections::BTreeMap;
32 use crate::dataflow::impls::{
33 Borrows, EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces,
35 use crate::dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex};
36 use crate::dataflow::move_paths::{InitLocation, LookupResult, MoveData, MoveError};
37 use crate::dataflow::MoveDataParamEnv;
38 use crate::dataflow::{Analysis, BorrowckFlowState as Flows, BorrowckResults};
40 use self::diagnostics::{AccessKind, RegionName};
41 use self::location::LocationTable;
42 use self::prefixes::PrefixSet;
43 use self::MutateMode::{JustWrite, WriteAndRead};
45 use self::path_utils::*;
48 mod constraint_generation;
55 mod member_constraints;
64 mod universal_regions;
67 crate use borrow_set::{BorrowData, BorrowSet};
68 crate use nll::{PoloniusOutput, ToRegionVid};
69 crate use place_ext::PlaceExt;
70 crate use places_conflict::{places_conflict, PlaceConflictBias};
71 crate use region_infer::RegionInferenceContext;
73 // FIXME(eddyb) perhaps move this somewhere more centrally.
80 /// If true, the capture is behind a reference.
83 mutability: Mutability,
86 const DEREF_PROJECTION: &[PlaceElem<'_>; 1] = &[ProjectionElem::Deref];
88 pub fn provide(providers: &mut Providers) {
89 *providers = Providers {
90 mir_borrowck: |tcx, did| {
91 if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
92 tcx.mir_borrowck_const_arg(def)
94 mir_borrowck(tcx, ty::WithOptConstParam::unknown(did))
97 mir_borrowck_const_arg: |tcx, (did, param_did)| {
98 mir_borrowck(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
104 fn mir_borrowck<'tcx>(
106 def: ty::WithOptConstParam<LocalDefId>,
107 ) -> &'tcx BorrowCheckResult<'tcx> {
108 let (input_body, promoted) = tcx.mir_promoted(def);
109 debug!("run query mir_borrowck: {}", tcx.def_path_str(def.did.to_def_id()));
111 let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
112 let input_body: &Body<'_> = &input_body.borrow();
113 let promoted: &IndexVec<_, _> = &promoted.borrow();
114 do_mir_borrowck(&infcx, input_body, promoted)
116 debug!("mir_borrowck done");
118 tcx.arena.alloc(opt_closure_req)
121 fn do_mir_borrowck<'a, 'tcx>(
122 infcx: &InferCtxt<'a, 'tcx>,
123 input_body: &Body<'tcx>,
124 input_promoted: &IndexVec<Promoted, Body<'tcx>>,
125 ) -> BorrowCheckResult<'tcx> {
126 let def = input_body.source.with_opt_param().as_local().unwrap();
128 debug!("do_mir_borrowck(def = {:?})", def);
131 let param_env = tcx.param_env(def.did);
132 let id = tcx.hir().local_def_id_to_hir_id(def.did);
134 let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
135 for var_debug_info in &input_body.var_debug_info {
136 if let Some(local) = var_debug_info.place.as_local() {
137 if let Some(prev_name) = local_names[local] {
138 if var_debug_info.name != prev_name {
140 var_debug_info.source_info.span,
141 "local {:?} has many names (`{}` vs `{}`)",
148 local_names[local] = Some(var_debug_info.name);
152 // Gather the upvars of a closure, if any.
153 let tables = tcx.typeck_opt_const_arg(def);
154 if let Some(ErrorReported) = tables.tainted_by_errors {
155 infcx.set_tainted_by_errors();
157 let upvars: Vec<_> = tables
159 .get(&def.did.to_def_id())
161 .flat_map(|v| v.values())
163 let var_hir_id = upvar_id.var_path.hir_id;
164 let capture = tables.upvar_capture(*upvar_id);
165 let by_ref = match capture {
166 ty::UpvarCapture::ByValue(_) => false,
167 ty::UpvarCapture::ByRef(..) => true,
169 let mut upvar = Upvar {
170 name: tcx.hir().name(var_hir_id),
173 mutability: Mutability::Not,
175 let bm = *tables.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
176 if bm == ty::BindByValue(hir::Mutability::Mut) {
177 upvar.mutability = Mutability::Mut;
183 // Replace all regions with fresh inference variables. This
184 // requires first making our own copy of the MIR. This copy will
185 // be modified (in place) to contain non-lexical lifetimes. It
186 // will have a lifetime tied to the inference context.
187 let mut body = input_body.clone();
188 let mut promoted = input_promoted.clone();
189 let free_regions = nll::replace_regions_in_mir(infcx, param_env, &mut body, &mut promoted);
190 let body = &body; // no further changes
192 let location_table = &LocationTable::new(&body);
194 let mut errors_buffer = Vec::new();
195 let (move_data, move_errors): (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>) =
196 match MoveData::gather_moves(&body, tcx, param_env) {
197 Ok(move_data) => (move_data, Vec::new()),
198 Err((move_data, move_errors)) => (move_data, move_errors),
200 let promoted_errors = promoted
202 .map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env)));
204 let mdpe = MoveDataParamEnv { move_data, param_env };
206 let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe)
207 .into_engine(tcx, &body)
208 .pass_name("borrowck")
209 .iterate_to_fixpoint()
210 .into_results_cursor(&body);
212 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
214 Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
216 // Compute non-lexical lifetimes.
223 } = nll::compute_regions(
236 // Dump MIR results into a file, if that is enabled. This let us
237 // write unit-tests, as well as helping with debugging.
238 nll::dump_mir_results(infcx, &body, ®ioncx, &opt_closure_req);
240 // We also have a `#[rustc_regions]` annotation that causes us to dump
242 nll::dump_annotation(
251 // The various `flow_*` structures can be large. We drop `flow_inits` here
252 // so it doesn't overlap with the others below. This reduces peak memory
253 // usage significantly on some benchmarks.
256 let regioncx = Rc::new(regioncx);
258 let flow_borrows = Borrows::new(tcx, &body, regioncx.clone(), &borrow_set)
259 .into_engine(tcx, &body)
260 .pass_name("borrowck")
261 .iterate_to_fixpoint();
262 let flow_uninits = MaybeUninitializedPlaces::new(tcx, &body, &mdpe)
263 .into_engine(tcx, &body)
264 .pass_name("borrowck")
265 .iterate_to_fixpoint();
266 let flow_ever_inits = EverInitializedPlaces::new(tcx, &body, &mdpe)
267 .into_engine(tcx, &body)
268 .pass_name("borrowck")
269 .iterate_to_fixpoint();
271 let movable_generator = match tcx.hir().get(id) {
272 Node::Expr(&hir::Expr {
273 kind: hir::ExprKind::Closure(.., Some(hir::Movability::Static)),
279 for (idx, move_data_results) in promoted_errors {
280 let promoted_body = &promoted[idx];
281 let dominators = promoted_body.dominators();
283 if let Err((move_data, move_errors)) = move_data_results {
284 let mut promoted_mbcx = MirBorrowckCtxt {
288 move_data: &move_data,
289 location_table: &LocationTable::new(promoted_body),
291 fn_self_span_reported: Default::default(),
292 locals_are_invalidated_at_exit,
293 access_place_error_reported: Default::default(),
294 reservation_error_reported: Default::default(),
295 reservation_warnings: Default::default(),
296 move_error_reported: BTreeMap::new(),
297 uninitialized_error_reported: Default::default(),
299 regioncx: regioncx.clone(),
300 used_mut: Default::default(),
301 used_mut_upvars: SmallVec::new(),
302 borrow_set: borrow_set.clone(),
305 local_names: IndexVec::from_elem(None, &promoted_body.local_decls),
306 region_names: RefCell::default(),
307 next_region_name: RefCell::new(1),
308 polonius_output: None,
310 promoted_mbcx.report_move_errors(move_errors);
311 errors_buffer = promoted_mbcx.errors_buffer;
315 let dominators = body.dominators();
317 let mut mbcx = MirBorrowckCtxt {
321 move_data: &mdpe.move_data,
324 locals_are_invalidated_at_exit,
325 fn_self_span_reported: Default::default(),
326 access_place_error_reported: Default::default(),
327 reservation_error_reported: Default::default(),
328 reservation_warnings: Default::default(),
329 move_error_reported: BTreeMap::new(),
330 uninitialized_error_reported: Default::default(),
333 used_mut: Default::default(),
334 used_mut_upvars: SmallVec::new(),
339 region_names: RefCell::default(),
340 next_region_name: RefCell::new(1),
344 // Compute and report region errors, if any.
345 mbcx.report_region_errors(nll_errors);
347 let results = BorrowckResults {
348 ever_inits: flow_ever_inits,
349 uninits: flow_uninits,
350 borrows: flow_borrows,
353 mbcx.report_move_errors(move_errors);
355 dataflow::visit_results(
357 traversal::reverse_postorder(&body).map(|(bb, _)| bb),
362 // Convert any reservation warnings into lints.
363 let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
364 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
365 let mut initial_diag = mbcx.report_conflicting_borrow(location, (place, span), bk, &borrow);
367 let scope = mbcx.body.source_info(location).scope;
368 let lint_root = match &mbcx.body.source_scopes[scope].local_data {
369 ClearCrossCrate::Set(data) => data.lint_root,
373 // Span and message don't matter; we overwrite them below anyway
374 mbcx.infcx.tcx.struct_span_lint_hir(
375 MUTABLE_BORROW_RESERVATION_CONFLICT,
379 let mut diag = lint.build("");
381 diag.message = initial_diag.styled_message().clone();
382 diag.span = initial_diag.span.clone();
384 diag.buffer(&mut mbcx.errors_buffer);
387 initial_diag.cancel();
390 // For each non-user used mutable variable, check if it's been assigned from
391 // a user-declared local. If so, then put that local into the used_mut set.
392 // Note that this set is expected to be small - only upvars from closures
393 // would have a chance of erroneously adding non-user-defined mutable vars
395 let temporary_used_locals: FxHashSet<Local> = mbcx
398 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
401 // For the remaining unused locals that are marked as mutable, we avoid linting any that
402 // were never initialized. These locals may have been removed as unreachable code; or will be
403 // linted as unused variables.
404 let unused_mut_locals =
405 mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
406 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
408 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
409 let used_mut = mbcx.used_mut;
410 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
411 let local_decl = &mbcx.body.local_decls[local];
412 let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data {
413 ClearCrossCrate::Set(data) => data.lint_root,
417 // Skip over locals that begin with an underscore or have no name
418 match mbcx.local_names[local] {
420 if name.as_str().starts_with('_') {
427 let span = local_decl.source_info.span;
428 if span.desugaring_kind().is_some() {
429 // If the `mut` arises as part of a desugaring, we should ignore it.
433 tcx.struct_span_lint_hir(UNUSED_MUT, lint_root, span, |lint| {
434 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
435 lint.build("variable does not need to be mutable")
436 .span_suggestion_short(
440 Applicability::MachineApplicable,
446 // Buffer any move errors that we collected and de-duplicated.
447 for (_, (_, diag)) in mbcx.move_error_reported {
448 diag.buffer(&mut mbcx.errors_buffer);
451 if !mbcx.errors_buffer.is_empty() {
452 mbcx.errors_buffer.sort_by_key(|diag| diag.sort_span);
454 for diag in mbcx.errors_buffer.drain(..) {
455 mbcx.infcx.tcx.sess.diagnostic().emit_diagnostic(&diag);
459 let result = BorrowCheckResult {
460 concrete_opaque_types: opaque_type_values,
461 closure_requirements: opt_closure_req,
462 used_mut_upvars: mbcx.used_mut_upvars,
465 debug!("do_mir_borrowck: result = {:#?}", result);
470 crate struct MirBorrowckCtxt<'cx, 'tcx> {
471 crate infcx: &'cx InferCtxt<'cx, 'tcx>,
472 param_env: ParamEnv<'tcx>,
473 body: &'cx Body<'tcx>,
474 move_data: &'cx MoveData<'tcx>,
476 /// Map from MIR `Location` to `LocationIndex`; created
477 /// when MIR borrowck begins.
478 location_table: &'cx LocationTable,
480 movable_generator: bool,
481 /// This keeps track of whether local variables are free-ed when the function
482 /// exits even without a `StorageDead`, which appears to be the case for
485 /// I'm not sure this is the right approach - @eddyb could you try and
487 locals_are_invalidated_at_exit: bool,
488 /// This field keeps track of when borrow errors are reported in the access_place function
489 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
490 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
491 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
493 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
494 /// This field keeps track of when borrow conflict errors are reported
495 /// for reservations, so that we don't report seemingly duplicate
496 /// errors for corresponding activations.
498 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
499 // but it is currently inconvenient to track down the `BorrowIndex`
500 // at the time we detect and report a reservation error.
501 reservation_error_reported: FxHashSet<Place<'tcx>>,
502 /// This fields keeps track of the `Span`s that we have
503 /// used to report extra information for `FnSelfUse`, to avoid
504 /// unnecessarily verbose errors.
505 fn_self_span_reported: FxHashSet<Span>,
506 /// Migration warnings to be reported for #56254. We delay reporting these
507 /// so that we can suppress the warning if there's a corresponding error
508 /// for the activation of the borrow.
509 reservation_warnings:
510 FxHashMap<BorrowIndex, (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)>,
511 /// This field keeps track of move errors that are to be reported for given move indices.
513 /// There are situations where many errors can be reported for a single move out (see #53807)
514 /// and we want only the best of those errors.
516 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
517 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
518 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
519 /// all move errors have been reported, any diagnostics in this map are added to the buffer
522 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
523 /// when errors in the map are being re-added to the error buffer so that errors with the
524 /// same primary span come out in a consistent order.
525 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'cx>)>,
526 /// This field keeps track of errors reported in the checking of uninitialized variables,
527 /// so that we don't report seemingly duplicate errors.
528 uninitialized_error_reported: FxHashSet<PlaceRef<'tcx>>,
529 /// Errors to be reported buffer
530 errors_buffer: Vec<Diagnostic>,
531 /// This field keeps track of all the local variables that are declared mut and are mutated.
532 /// Used for the warning issued by an unused mutable local variable.
533 used_mut: FxHashSet<Local>,
534 /// If the function we're checking is a closure, then we'll need to report back the list of
535 /// mutable upvars that have been used. This field keeps track of them.
536 used_mut_upvars: SmallVec<[Field; 8]>,
537 /// Region inference context. This contains the results from region inference and lets us e.g.
538 /// find out which CFG points are contained in each borrow region.
539 regioncx: Rc<RegionInferenceContext<'tcx>>,
541 /// The set of borrows extracted from the MIR
542 borrow_set: Rc<BorrowSet<'tcx>>,
544 /// Dominators for MIR
545 dominators: Dominators<BasicBlock>,
547 /// Information about upvars not necessarily preserved in types or MIR
550 /// Names of local (user) variables (extracted from `var_debug_info`).
551 local_names: IndexVec<Local, Option<Symbol>>,
553 /// Record the region names generated for each region in the given
554 /// MIR def so that we can reuse them later in help/error messages.
555 region_names: RefCell<FxHashMap<RegionVid, RegionName>>,
557 /// The counter for generating new region names.
558 next_region_name: RefCell<usize>,
560 /// Results of Polonius analysis.
561 polonius_output: Option<Rc<PoloniusOutput>>,
565 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
566 // 2. loans made in overlapping scopes do not conflict
567 // 3. assignments do not affect things loaned out as immutable
568 // 4. moves do not affect things loaned out in any way
569 impl<'cx, 'tcx> dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
570 type FlowState = Flows<'cx, 'tcx>;
572 fn visit_statement_before_primary_effect(
574 flow_state: &Flows<'cx, 'tcx>,
575 stmt: &'cx Statement<'tcx>,
578 debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state);
579 let span = stmt.source_info.span;
581 self.check_activations(location, span, flow_state);
584 StatementKind::Assign(box (lhs, ref rhs)) => {
585 self.consume_rvalue(location, (rhs, span), flow_state);
587 self.mutate_place(location, (*lhs, span), Shallow(None), JustWrite, flow_state);
589 StatementKind::FakeRead(_, box ref place) => {
590 // Read for match doesn't access any memory and is used to
591 // assert that a place is safe and live. So we don't have to
592 // do any checks here.
594 // FIXME: Remove check that the place is initialized. This is
595 // needed for now because matches don't have never patterns yet.
596 // So this is the only place we prevent
600 self.check_if_path_or_subpath_is_moved(
602 InitializationRequiringAction::Use,
603 (place.as_ref(), span),
607 StatementKind::SetDiscriminant { place, variant_index: _ } => {
608 self.mutate_place(location, (**place, span), Shallow(None), JustWrite, flow_state);
610 StatementKind::LlvmInlineAsm(ref asm) => {
611 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
613 // FIXME(eddyb) indirect inline asm outputs should
614 // be encoded through MIR place derefs instead.
618 (Deep, Read(ReadKind::Copy)),
619 LocalMutationIsAllowed::No,
622 self.check_if_path_or_subpath_is_moved(
624 InitializationRequiringAction::Use,
625 (output.as_ref(), o.span),
632 if o.is_rw { Deep } else { Shallow(None) },
633 if o.is_rw { WriteAndRead } else { JustWrite },
638 for (_, input) in asm.inputs.iter() {
639 self.consume_operand(location, (input, span), flow_state);
643 | StatementKind::Coverage(..)
644 | StatementKind::AscribeUserType(..)
645 | StatementKind::Retag { .. }
646 | StatementKind::StorageLive(..) => {
647 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
650 StatementKind::StorageDead(local) => {
653 (Place::from(*local), span),
654 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
655 LocalMutationIsAllowed::Yes,
662 fn visit_terminator_before_primary_effect(
664 flow_state: &Flows<'cx, 'tcx>,
665 term: &'cx Terminator<'tcx>,
668 debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
669 let span = term.source_info.span;
671 self.check_activations(loc, span, flow_state);
674 TerminatorKind::SwitchInt { ref discr, switch_ty: _, values: _, targets: _ } => {
675 self.consume_operand(loc, (discr, span), flow_state);
677 TerminatorKind::Drop { place: ref drop_place, target: _, unwind: _ } => {
678 let tcx = self.infcx.tcx;
680 // Compute the type with accurate region information.
681 let drop_place_ty = drop_place.ty(self.body, self.infcx.tcx);
683 // Erase the regions.
684 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
686 // "Lift" into the tcx -- once regions are erased, this type should be in the
687 // global arenas; this "lift" operation basically just asserts that is true, but
688 // that is useful later.
689 tcx.lift(&drop_place_ty).unwrap();
692 "visit_terminator_drop \
693 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
694 loc, term, drop_place, drop_place_ty, span
700 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
701 LocalMutationIsAllowed::Yes,
705 TerminatorKind::DropAndReplace {
707 value: ref new_value,
711 self.mutate_place(loc, (drop_place, span), Deep, JustWrite, flow_state);
712 self.consume_operand(loc, (new_value, span), flow_state);
714 TerminatorKind::Call {
722 self.consume_operand(loc, (func, span), flow_state);
724 self.consume_operand(loc, (arg, span), flow_state);
726 if let Some((dest, _ /*bb*/)) = *destination {
727 self.mutate_place(loc, (dest, span), Deep, JustWrite, flow_state);
730 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
731 self.consume_operand(loc, (cond, span), flow_state);
732 use rustc_middle::mir::AssertKind;
733 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
734 self.consume_operand(loc, (len, span), flow_state);
735 self.consume_operand(loc, (index, span), flow_state);
739 TerminatorKind::Yield { ref value, resume: _, resume_arg, drop: _ } => {
740 self.consume_operand(loc, (value, span), flow_state);
741 self.mutate_place(loc, (resume_arg, span), Deep, JustWrite, flow_state);
744 TerminatorKind::InlineAsm {
753 InlineAsmOperand::In { reg: _, ref value }
754 | InlineAsmOperand::Const { ref value } => {
755 self.consume_operand(loc, (value, span), flow_state);
757 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
758 if let Some(place) = place {
768 InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
769 self.consume_operand(loc, (in_value, span), flow_state);
770 if let Some(out_place) = out_place {
780 InlineAsmOperand::SymFn { value: _ }
781 | InlineAsmOperand::SymStatic { def_id: _ } => {}
786 TerminatorKind::Goto { target: _ }
787 | TerminatorKind::Abort
788 | TerminatorKind::Unreachable
789 | TerminatorKind::Resume
790 | TerminatorKind::Return
791 | TerminatorKind::GeneratorDrop
792 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
793 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
794 // no data used, thus irrelevant to borrowck
799 fn visit_terminator_after_primary_effect(
801 flow_state: &Flows<'cx, 'tcx>,
802 term: &'cx Terminator<'tcx>,
805 let span = term.source_info.span;
808 TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
809 if self.movable_generator {
810 // Look for any active borrows to locals
811 let borrow_set = self.borrow_set.clone();
812 for i in flow_state.borrows.iter() {
813 let borrow = &borrow_set[i];
814 self.check_for_local_borrow(borrow, span);
819 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
820 // Returning from the function implicitly kills storage for all locals and statics.
821 // Often, the storage will already have been killed by an explicit
822 // StorageDead, but we don't always emit those (notably on unwind paths),
823 // so this "extra check" serves as a kind of backup.
824 let borrow_set = self.borrow_set.clone();
825 for i in flow_state.borrows.iter() {
826 let borrow = &borrow_set[i];
827 self.check_for_invalidation_at_exit(loc, borrow, span);
831 TerminatorKind::Abort
832 | TerminatorKind::Assert { .. }
833 | TerminatorKind::Call { .. }
834 | TerminatorKind::Drop { .. }
835 | TerminatorKind::DropAndReplace { .. }
836 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
837 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
838 | TerminatorKind::Goto { .. }
839 | TerminatorKind::SwitchInt { .. }
840 | TerminatorKind::Unreachable
841 | TerminatorKind::InlineAsm { .. } => {}
846 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
852 use self::AccessDepth::{Deep, Shallow};
853 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
855 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
856 enum ArtificialField {
861 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
863 /// From the RFC: "A *shallow* access means that the immediate
864 /// fields reached at P are accessed, but references or pointers
865 /// found within are not dereferenced. Right now, the only access
866 /// that is shallow is an assignment like `x = ...;`, which would
867 /// be a *shallow write* of `x`."
868 Shallow(Option<ArtificialField>),
870 /// From the RFC: "A *deep* access means that all data reachable
871 /// through the given place may be invalidated or accesses by
875 /// Access is Deep only when there is a Drop implementation that
876 /// can reach the data behind the reference.
880 /// Kind of access to a value: read or write
881 /// (For informational purposes only)
882 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
884 /// From the RFC: "A *read* means that the existing data may be
885 /// read, but will not be changed."
888 /// From the RFC: "A *write* means that the data may be mutated to
889 /// new values or otherwise invalidated (for example, it could be
890 /// de-initialized, as in a move operation).
893 /// For two-phase borrows, we distinguish a reservation (which is treated
894 /// like a Read) from an activation (which is treated like a write), and
895 /// each of those is furthermore distinguished from Reads/Writes above.
896 Reservation(WriteKind),
897 Activation(WriteKind, BorrowIndex),
900 /// Kind of read access to a value
901 /// (For informational purposes only)
902 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
908 /// Kind of write access to a value
909 /// (For informational purposes only)
910 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
913 MutableBorrow(BorrowKind),
918 /// When checking permissions for a place access, this flag is used to indicate that an immutable
919 /// local place can be mutated.
921 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
922 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
923 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
924 // `is_declared_mutable()`.
925 // - Take flow state into consideration in `is_assignable()` for local variables.
926 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
927 enum LocalMutationIsAllowed {
929 /// We want use of immutable upvars to cause a "write to immutable upvar"
930 /// error, not an "reassignment" error.
935 #[derive(Copy, Clone, Debug)]
936 enum InitializationRequiringAction {
945 struct RootPlace<'tcx> {
947 place_projection: &'tcx [PlaceElem<'tcx>],
948 is_local_mutation_allowed: LocalMutationIsAllowed,
951 impl InitializationRequiringAction {
952 fn as_noun(self) -> &'static str {
954 InitializationRequiringAction::Update => "update",
955 InitializationRequiringAction::Borrow => "borrow",
956 InitializationRequiringAction::MatchOn => "use", // no good noun
957 InitializationRequiringAction::Use => "use",
958 InitializationRequiringAction::Assignment => "assign",
959 InitializationRequiringAction::PartialAssignment => "assign to part",
963 fn as_verb_in_past_tense(self) -> &'static str {
965 InitializationRequiringAction::Update => "updated",
966 InitializationRequiringAction::Borrow => "borrowed",
967 InitializationRequiringAction::MatchOn => "matched on",
968 InitializationRequiringAction::Use => "used",
969 InitializationRequiringAction::Assignment => "assigned",
970 InitializationRequiringAction::PartialAssignment => "partially assigned",
975 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
976 fn body(&self) -> &'cx Body<'tcx> {
980 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
981 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
982 /// place is initialized and (b) it is not borrowed in some way that would prevent this
985 /// Returns `true` if an error is reported.
989 place_span: (Place<'tcx>, Span),
990 kind: (AccessDepth, ReadOrWrite),
991 is_local_mutation_allowed: LocalMutationIsAllowed,
992 flow_state: &Flows<'cx, 'tcx>,
996 if let Activation(_, borrow_index) = rw {
997 if self.reservation_error_reported.contains(&place_span.0) {
999 "skipping access_place for activation of invalid reservation \
1000 place: {:?} borrow_index: {:?}",
1001 place_span.0, borrow_index
1007 // Check is_empty() first because it's the common case, and doing that
1008 // way we avoid the clone() call.
1009 if !self.access_place_error_reported.is_empty()
1010 && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
1013 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
1019 let mutability_error = self.check_access_permissions(
1022 is_local_mutation_allowed,
1026 let conflict_error =
1027 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
1029 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
1030 // Suppress this warning when there's an error being emitted for the
1031 // same borrow: fixing the error is likely to fix the warning.
1032 self.reservation_warnings.remove(&borrow_idx);
1035 if conflict_error || mutability_error {
1036 debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
1038 self.access_place_error_reported.insert((place_span.0, place_span.1));
1042 fn check_access_for_conflict(
1045 place_span: (Place<'tcx>, Span),
1048 flow_state: &Flows<'cx, 'tcx>,
1051 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1052 location, place_span, sd, rw,
1055 let mut error_reported = false;
1056 let tcx = self.infcx.tcx;
1057 let body = self.body;
1058 let borrow_set = self.borrow_set.clone();
1060 // Use polonius output if it has been enabled.
1061 let polonius_output = self.polonius_output.clone();
1062 let borrows_in_scope = if let Some(polonius) = &polonius_output {
1063 let location = self.location_table.start_index(location);
1064 Either::Left(polonius.errors_at(location).iter().copied())
1066 Either::Right(flow_state.borrows.iter())
1069 each_borrow_involving_path(
1077 |this, borrow_index, borrow| match (rw, borrow.kind) {
1078 // Obviously an activation is compatible with its own
1079 // reservation (or even prior activating uses of same
1080 // borrow); so don't check if they interfere.
1082 // NOTE: *reservations* do conflict with themselves;
1083 // thus aren't injecting unsoundenss w/ this check.)
1084 (Activation(_, activating), _) if activating == borrow_index => {
1086 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1087 skipping {:?} b/c activation of same borrow_index",
1091 (borrow_index, borrow),
1096 (Read(_), BorrowKind::Shared | BorrowKind::Shallow)
1098 Read(ReadKind::Borrow(BorrowKind::Shallow)),
1099 BorrowKind::Unique | BorrowKind::Mut { .. },
1100 ) => Control::Continue,
1102 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1103 // Handled by initialization checks.
1107 (Read(kind), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
1108 // Reading from mere reservations of mutable-borrows is OK.
1109 if !is_active(&this.dominators, borrow, location) {
1110 assert!(allow_two_phase_borrow(borrow.kind));
1111 return Control::Continue;
1114 error_reported = true;
1117 this.report_use_while_mutably_borrowed(location, place_span, borrow)
1118 .buffer(&mut this.errors_buffer);
1120 ReadKind::Borrow(bk) => {
1121 this.report_conflicting_borrow(location, place_span, bk, borrow)
1122 .buffer(&mut this.errors_buffer);
1129 Reservation(WriteKind::MutableBorrow(bk)),
1130 BorrowKind::Shallow | BorrowKind::Shared,
1131 ) if { tcx.migrate_borrowck() && this.borrow_set.contains(&location) } => {
1132 let bi = this.borrow_set.get_index_of(&location).unwrap();
1134 "recording invalid reservation of place: {:?} with \
1135 borrow index {:?} as warning",
1138 // rust-lang/rust#56254 - This was previously permitted on
1139 // the 2018 edition so we emit it as a warning. We buffer
1140 // these sepately so that we only emit a warning if borrow
1141 // checking was otherwise successful.
1142 this.reservation_warnings
1143 .insert(bi, (place_span.0, place_span.1, location, bk, borrow.clone()));
1145 // Don't suppress actual errors.
1149 (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1151 Reservation(..) => {
1153 "recording invalid reservation of \
1157 this.reservation_error_reported.insert(place_span.0);
1159 Activation(_, activating) => {
1161 "observing check_place for activation of \
1162 borrow_index: {:?}",
1166 Read(..) | Write(..) => {}
1169 error_reported = true;
1171 WriteKind::MutableBorrow(bk) => {
1172 this.report_conflicting_borrow(location, place_span, bk, borrow)
1173 .buffer(&mut this.errors_buffer);
1175 WriteKind::StorageDeadOrDrop => this
1176 .report_borrowed_value_does_not_live_long_enough(
1182 WriteKind::Mutate => {
1183 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1185 WriteKind::Move => {
1186 this.report_move_out_while_borrowed(location, place_span, borrow)
1200 place_span: (Place<'tcx>, Span),
1203 flow_state: &Flows<'cx, 'tcx>,
1205 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1207 MutateMode::WriteAndRead => {
1208 self.check_if_path_or_subpath_is_moved(
1210 InitializationRequiringAction::Update,
1211 (place_span.0.as_ref(), place_span.1),
1215 MutateMode::JustWrite => {
1216 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1220 // Special case: you can assign a immutable local variable
1221 // (e.g., `x = ...`) so long as it has never been initialized
1222 // before (at this point in the flow).
1223 if let Some(local) = place_span.0.as_local() {
1224 if let Mutability::Not = self.body.local_decls[local].mutability {
1225 // check for reassignments to immutable local variables
1226 self.check_if_reassignment_to_immutable_state(
1227 location, local, place_span, flow_state,
1233 // Otherwise, use the normal access permission rules.
1237 (kind, Write(WriteKind::Mutate)),
1238 LocalMutationIsAllowed::No,
1246 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1247 flow_state: &Flows<'cx, 'tcx>,
1250 Rvalue::Ref(_ /*rgn*/, bk, place) => {
1251 let access_kind = match bk {
1252 BorrowKind::Shallow => {
1253 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1255 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1256 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1257 let wk = WriteKind::MutableBorrow(bk);
1258 if allow_two_phase_borrow(bk) {
1259 (Deep, Reservation(wk))
1270 LocalMutationIsAllowed::No,
1274 let action = if bk == BorrowKind::Shallow {
1275 InitializationRequiringAction::MatchOn
1277 InitializationRequiringAction::Borrow
1280 self.check_if_path_or_subpath_is_moved(
1283 (place.as_ref(), span),
1288 Rvalue::AddressOf(mutability, place) => {
1289 let access_kind = match mutability {
1290 Mutability::Mut => (
1292 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1293 allow_two_phase_borrow: false,
1296 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1303 LocalMutationIsAllowed::No,
1307 self.check_if_path_or_subpath_is_moved(
1309 InitializationRequiringAction::Borrow,
1310 (place.as_ref(), span),
1315 Rvalue::ThreadLocalRef(_) => {}
1317 Rvalue::Use(ref operand)
1318 | Rvalue::Repeat(ref operand, _)
1319 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1320 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1321 self.consume_operand(location, (operand, span), flow_state)
1324 Rvalue::Len(place) | Rvalue::Discriminant(place) => {
1325 let af = match *rvalue {
1326 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1327 Rvalue::Discriminant(..) => None,
1328 _ => unreachable!(),
1333 (Shallow(af), Read(ReadKind::Copy)),
1334 LocalMutationIsAllowed::No,
1337 self.check_if_path_or_subpath_is_moved(
1339 InitializationRequiringAction::Use,
1340 (place.as_ref(), span),
1345 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1346 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1347 self.consume_operand(location, (operand1, span), flow_state);
1348 self.consume_operand(location, (operand2, span), flow_state);
1351 Rvalue::NullaryOp(_op, _ty) => {
1352 // nullary ops take no dynamic input; no borrowck effect.
1354 // FIXME: is above actually true? Do we want to track
1355 // the fact that uninitialized data can be created via
1359 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1360 // We need to report back the list of mutable upvars that were
1361 // moved into the closure and subsequently used by the closure,
1362 // in order to populate our used_mut set.
1363 match **aggregate_kind {
1364 AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
1365 let BorrowCheckResult { used_mut_upvars, .. } =
1366 self.infcx.tcx.mir_borrowck(def_id.expect_local());
1367 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1368 for field in used_mut_upvars {
1369 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1372 AggregateKind::Adt(..)
1373 | AggregateKind::Array(..)
1374 | AggregateKind::Tuple { .. } => (),
1377 for operand in operands {
1378 self.consume_operand(location, (operand, span), flow_state);
1384 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1385 let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1386 if !place.projection.is_empty() {
1387 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1388 this.used_mut_upvars.push(field);
1391 this.used_mut.insert(place.local);
1395 // This relies on the current way that by-value
1396 // captures of a closure are copied/moved directly
1397 // when generating MIR.
1399 Operand::Move(place) | Operand::Copy(place) => {
1400 match place.as_local() {
1401 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1402 if self.body.local_decls[local].ty.is_mutable_ptr() {
1403 // The variable will be marked as mutable by the borrow.
1406 // This is an edge case where we have a `move` closure
1407 // inside a non-move closure, and the inner closure
1408 // contains a mutation:
1411 // || { move || { i += 1; }; };
1413 // In this case our usual strategy of assuming that the
1414 // variable will be captured by mutable reference is
1415 // wrong, since `i` can be copied into the inner
1416 // closure from a shared reference.
1418 // As such we have to search for the local that this
1419 // capture comes from and mark it as being used as mut.
1421 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1422 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1423 &self.move_data.inits[init_index]
1425 bug!("temporary should be initialized exactly once")
1428 let loc = match init.location {
1429 InitLocation::Statement(stmt) => stmt,
1430 _ => bug!("temporary initialized in arguments"),
1433 let body = self.body;
1434 let bbd = &body[loc.block];
1435 let stmt = &bbd.statements[loc.statement_index];
1436 debug!("temporary assigned in: stmt={:?}", stmt);
1438 if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, source))) = stmt.kind
1440 propagate_closure_used_mut_place(self, source);
1443 "closures should only capture user variables \
1444 or references to user variables"
1448 _ => propagate_closure_used_mut_place(self, place),
1451 Operand::Constant(..) => {}
1458 (operand, span): (&'cx Operand<'tcx>, Span),
1459 flow_state: &Flows<'cx, 'tcx>,
1462 Operand::Copy(place) => {
1463 // copy of place: check if this is "copy of frozen path"
1464 // (FIXME: see check_loans.rs)
1468 (Deep, Read(ReadKind::Copy)),
1469 LocalMutationIsAllowed::No,
1473 // Finally, check if path was already moved.
1474 self.check_if_path_or_subpath_is_moved(
1476 InitializationRequiringAction::Use,
1477 (place.as_ref(), span),
1481 Operand::Move(place) => {
1482 // move of place: check if this is move of already borrowed path
1486 (Deep, Write(WriteKind::Move)),
1487 LocalMutationIsAllowed::Yes,
1491 // Finally, check if path was already moved.
1492 self.check_if_path_or_subpath_is_moved(
1494 InitializationRequiringAction::Use,
1495 (place.as_ref(), span),
1499 Operand::Constant(_) => {}
1503 /// Checks whether a borrow of this place is invalidated when the function
1505 fn check_for_invalidation_at_exit(
1508 borrow: &BorrowData<'tcx>,
1511 debug!("check_for_invalidation_at_exit({:?})", borrow);
1512 let place = borrow.borrowed_place;
1513 let mut root_place = PlaceRef { local: place.local, projection: &[] };
1515 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1516 // we just know that all locals are dropped at function exit (otherwise
1517 // we'll have a memory leak) and assume that all statics have a destructor.
1519 // FIXME: allow thread-locals to borrow other thread locals?
1521 let (might_be_alive, will_be_dropped) =
1522 if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1523 // Thread-locals might be dropped after the function exits
1524 // We have to dereference the outer reference because
1525 // borrows don't conflict behind shared references.
1526 root_place.projection = DEREF_PROJECTION;
1529 (false, self.locals_are_invalidated_at_exit)
1532 if !will_be_dropped {
1533 debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
1537 let sd = if might_be_alive { Deep } else { Shallow(None) };
1539 if places_conflict::borrow_conflicts_with_place(
1546 places_conflict::PlaceConflictBias::Overlap,
1548 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1549 // FIXME: should be talking about the region lifetime instead
1550 // of just a span here.
1551 let span = self.infcx.tcx.sess.source_map().end_point(span);
1552 self.report_borrowed_value_does_not_live_long_enough(
1561 /// Reports an error if this is a borrow of local data.
1562 /// This is called for all Yield expressions on movable generators
1563 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1564 debug!("check_for_local_borrow({:?})", borrow);
1566 if borrow_of_local_data(borrow.borrowed_place) {
1567 let err = self.cannot_borrow_across_generator_yield(
1568 self.retrieve_borrow_spans(borrow).var_or_use(),
1572 err.buffer(&mut self.errors_buffer);
1576 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1577 // Two-phase borrow support: For each activation that is newly
1578 // generated at this statement, check if it interferes with
1580 let borrow_set = self.borrow_set.clone();
1581 for &borrow_index in borrow_set.activations_at_location(location) {
1582 let borrow = &borrow_set[borrow_index];
1584 // only mutable borrows should be 2-phase
1585 assert!(match borrow.kind {
1586 BorrowKind::Shared | BorrowKind::Shallow => false,
1587 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1592 (borrow.borrowed_place, span),
1593 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1594 LocalMutationIsAllowed::No,
1597 // We do not need to call `check_if_path_or_subpath_is_moved`
1598 // again, as we already called it when we made the
1599 // initial reservation.
1603 fn check_if_reassignment_to_immutable_state(
1607 place_span: (Place<'tcx>, Span),
1608 flow_state: &Flows<'cx, 'tcx>,
1610 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1612 // Check if any of the initializiations of `local` have happened yet:
1613 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1614 // And, if so, report an error.
1615 let init = &self.move_data.inits[init_index];
1616 let span = init.span(&self.body);
1617 self.report_illegal_reassignment(location, place_span, span, place_span.0);
1621 fn check_if_full_path_is_moved(
1624 desired_action: InitializationRequiringAction,
1625 place_span: (PlaceRef<'tcx>, Span),
1626 flow_state: &Flows<'cx, 'tcx>,
1628 let maybe_uninits = &flow_state.uninits;
1632 // 1. Move of `a.b.c`, use of `a.b.c`
1633 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1634 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1635 // partial initialization support, one might have `a.x`
1636 // initialized but not `a.b`.
1640 // 4. Move of `a.b.c`, use of `a.b.d`
1641 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1642 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1643 // must have been initialized for the use to be sound.
1644 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1646 // The dataflow tracks shallow prefixes distinctly (that is,
1647 // field-accesses on P distinctly from P itself), in order to
1648 // track substructure initialization separately from the whole
1651 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1652 // which we have a MovePath is `a.b`, then that means that the
1653 // initialization state of `a.b` is all we need to inspect to
1654 // know if `a.b.c` is valid (and from that we infer that the
1655 // dereference and `.d` access is also valid, since we assume
1656 // `a.b.c` is assigned a reference to a initialized and
1657 // well-formed record structure.)
1659 // Therefore, if we seek out the *closest* prefix for which we
1660 // have a MovePath, that should capture the initialization
1661 // state for the place scenario.
1663 // This code covers scenarios 1, 2, and 3.
1665 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1666 let (prefix, mpi) = self.move_path_closest_to(place_span.0);
1667 if maybe_uninits.contains(mpi) {
1668 self.report_use_of_moved_or_uninitialized(
1671 (prefix, place_span.0, place_span.1),
1674 } // Only query longest prefix with a MovePath, not further
1675 // ancestors; dataflow recurs on children when parents
1676 // move (to support partial (re)inits).
1678 // (I.e., querying parents breaks scenario 7; but may want
1679 // to do such a query based on partial-init feature-gate.)
1682 /// Subslices correspond to multiple move paths, so we iterate through the
1683 /// elements of the base array. For each element we check
1685 /// * Does this element overlap with our slice.
1686 /// * Is any part of it uninitialized.
1687 fn check_if_subslice_element_is_moved(
1690 desired_action: InitializationRequiringAction,
1691 place_span: (PlaceRef<'tcx>, Span),
1692 maybe_uninits: &BitSet<MovePathIndex>,
1696 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1697 let move_paths = &self.move_data.move_paths;
1699 let root_path = &move_paths[mpi];
1700 for (child_mpi, child_move_path) in root_path.children(move_paths) {
1701 let last_proj = child_move_path.place.projection.last().unwrap();
1702 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
1703 debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
1705 if (from..to).contains(offset) {
1707 self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
1708 maybe_uninits.contains(mpi)
1711 if let Some(uninit_child) = uninit_child {
1712 self.report_use_of_moved_or_uninitialized(
1715 (place_span.0, place_span.0, place_span.1),
1718 return; // don't bother finding other problems.
1726 fn check_if_path_or_subpath_is_moved(
1729 desired_action: InitializationRequiringAction,
1730 place_span: (PlaceRef<'tcx>, Span),
1731 flow_state: &Flows<'cx, 'tcx>,
1733 let maybe_uninits = &flow_state.uninits;
1737 // 1. Move of `a.b.c`, use of `a` or `a.b`
1738 // partial initialization support, one might have `a.x`
1739 // initialized but not `a.b`.
1740 // 2. All bad scenarios from `check_if_full_path_is_moved`
1744 // 3. Move of `a.b.c`, use of `a.b.d`
1745 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1746 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1747 // must have been initialized for the use to be sound.
1748 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1750 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1752 if let [base_proj @ .., ProjectionElem::Subslice { from, to, from_end: false }] =
1753 place_span.0.projection
1756 Place::ty_from(place_span.0.local, base_proj, self.body(), self.infcx.tcx);
1757 if let ty::Array(..) = place_ty.ty.kind() {
1758 let array_place = PlaceRef { local: place_span.0.local, projection: base_proj };
1759 self.check_if_subslice_element_is_moved(
1762 (array_place, place_span.1),
1771 // A move of any shallow suffix of `place` also interferes
1772 // with an attempt to use `place`. This is scenario 3 above.
1774 // (Distinct from handling of scenarios 1+2+4 above because
1775 // `place` does not interfere with suffixes of its prefixes,
1776 // e.g., `a.b.c` does not interfere with `a.b.d`)
1778 // This code covers scenario 1.
1780 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1781 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1782 let uninit_mpi = self
1784 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
1786 if let Some(uninit_mpi) = uninit_mpi {
1787 self.report_use_of_moved_or_uninitialized(
1790 (place_span.0, place_span.0, place_span.1),
1793 return; // don't bother finding other problems.
1798 /// Currently MoveData does not store entries for all places in
1799 /// the input MIR. For example it will currently filter out
1800 /// places that are Copy; thus we do not track places of shared
1801 /// reference type. This routine will walk up a place along its
1802 /// prefixes, searching for a foundational place that *is*
1803 /// tracked in the MoveData.
1805 /// An Err result includes a tag indicated why the search failed.
1806 /// Currently this can only occur if the place is built off of a
1807 /// static variable, as we do not track those in the MoveData.
1808 fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
1809 match self.move_data.rev_lookup.find(place) {
1810 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
1811 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
1813 LookupResult::Parent(None) => panic!("should have move path for every Local"),
1817 fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
1818 // If returns None, then there is no move path corresponding
1819 // to a direct owner of `place` (which means there is nothing
1820 // that borrowck tracks for its analysis).
1822 match self.move_data.rev_lookup.find(place) {
1823 LookupResult::Parent(_) => None,
1824 LookupResult::Exact(mpi) => Some(mpi),
1828 fn check_if_assigned_path_is_moved(
1831 (place, span): (Place<'tcx>, Span),
1832 flow_state: &Flows<'cx, 'tcx>,
1834 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1836 // None case => assigning to `x` does not require `x` be initialized.
1837 let mut cursor = &*place.projection.as_ref();
1838 while let [proj_base @ .., elem] = cursor {
1842 ProjectionElem::Index(_/*operand*/) |
1843 ProjectionElem::ConstantIndex { .. } |
1844 // assigning to P[i] requires P to be valid.
1845 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1846 // assigning to (P->variant) is okay if assigning to `P` is okay
1848 // FIXME: is this true even if P is a adt with a dtor?
1851 // assigning to (*P) requires P to be initialized
1852 ProjectionElem::Deref => {
1853 self.check_if_full_path_is_moved(
1854 location, InitializationRequiringAction::Use,
1857 projection: proj_base,
1858 }, span), flow_state);
1859 // (base initialized; no need to
1864 ProjectionElem::Subslice { .. } => {
1865 panic!("we don't allow assignments to subslices, location: {:?}",
1869 ProjectionElem::Field(..) => {
1870 // if type of `P` has a dtor, then
1871 // assigning to `P.f` requires `P` itself
1872 // be already initialized
1873 let tcx = self.infcx.tcx;
1874 let base_ty = Place::ty_from(place.local, proj_base, self.body(), tcx).ty;
1875 match base_ty.kind() {
1876 ty::Adt(def, _) if def.has_dtor(tcx) => {
1877 self.check_if_path_or_subpath_is_moved(
1878 location, InitializationRequiringAction::Assignment,
1881 projection: proj_base,
1882 }, span), flow_state);
1884 // (base initialized; no need to
1889 // Once `let s; s.x = V; read(s.x);`,
1890 // is allowed, remove this match arm.
1891 ty::Adt(..) | ty::Tuple(..) => {
1892 check_parent_of_field(self, location, PlaceRef {
1894 projection: proj_base,
1895 }, span, flow_state);
1897 // rust-lang/rust#21232, #54499, #54986: during period where we reject
1898 // partial initialization, do not complain about unnecessary `mut` on
1899 // an attempt to do a partial initialization.
1900 self.used_mut.insert(place.local);
1909 fn check_parent_of_field<'cx, 'tcx>(
1910 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1912 base: PlaceRef<'tcx>,
1914 flow_state: &Flows<'cx, 'tcx>,
1916 // rust-lang/rust#21232: Until Rust allows reads from the
1917 // initialized parts of partially initialized structs, we
1918 // will, starting with the 2018 edition, reject attempts
1919 // to write to structs that are not fully initialized.
1921 // In other words, *until* we allow this:
1923 // 1. `let mut s; s.x = Val; read(s.x);`
1925 // we will for now disallow this:
1927 // 2. `let mut s; s.x = Val;`
1931 // 3. `let mut s = ...; drop(s); s.x=Val;`
1933 // This does not use check_if_path_or_subpath_is_moved,
1934 // because we want to *allow* reinitializations of fields:
1935 // e.g., want to allow
1937 // `let mut s = ...; drop(s.x); s.x=Val;`
1939 // This does not use check_if_full_path_is_moved on
1940 // `base`, because that would report an error about the
1941 // `base` as a whole, but in this scenario we *really*
1942 // want to report an error about the actual thing that was
1943 // moved, which may be some prefix of `base`.
1945 // Shallow so that we'll stop at any dereference; we'll
1946 // report errors about issues with such bases elsewhere.
1947 let maybe_uninits = &flow_state.uninits;
1949 // Find the shortest uninitialized prefix you can reach
1950 // without going over a Deref.
1951 let mut shortest_uninit_seen = None;
1952 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1953 let mpi = match this.move_path_for_place(prefix) {
1958 if maybe_uninits.contains(mpi) {
1960 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1961 shortest_uninit_seen,
1964 shortest_uninit_seen = Some((prefix, mpi));
1966 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1970 if let Some((prefix, mpi)) = shortest_uninit_seen {
1971 // Check for a reassignment into a uninitialized field of a union (for example,
1972 // after a move out). In this case, do not report a error here. There is an
1973 // exception, if this is the first assignment into the union (that is, there is
1974 // no move out from an earlier location) then this is an attempt at initialization
1975 // of the union - we should error in that case.
1976 let tcx = this.infcx.tcx;
1977 if let ty::Adt(def, _) =
1978 Place::ty_from(base.local, base.projection, this.body(), tcx).ty.kind()
1981 if this.move_data.path_map[mpi].iter().any(|moi| {
1982 this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
1989 this.report_use_of_moved_or_uninitialized(
1991 InitializationRequiringAction::PartialAssignment,
1992 (prefix, base, span),
1999 /// Checks the permissions for the given place and read or write kind
2001 /// Returns `true` if an error is reported.
2002 fn check_access_permissions(
2004 (place, span): (Place<'tcx>, Span),
2006 is_local_mutation_allowed: LocalMutationIsAllowed,
2007 flow_state: &Flows<'cx, 'tcx>,
2011 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
2012 place, kind, is_local_mutation_allowed
2019 Reservation(WriteKind::MutableBorrow(
2020 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
2022 | Write(WriteKind::MutableBorrow(
2023 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
2025 let is_local_mutation_allowed = match borrow_kind {
2026 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
2027 BorrowKind::Mut { .. } => is_local_mutation_allowed,
2028 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
2030 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2032 self.add_used_mut(root_place, flow_state);
2036 error_access = AccessKind::MutableBorrow;
2037 the_place_err = place_err;
2041 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
2042 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2044 self.add_used_mut(root_place, flow_state);
2048 error_access = AccessKind::Mutate;
2049 the_place_err = place_err;
2056 | WriteKind::StorageDeadOrDrop
2057 | WriteKind::MutableBorrow(BorrowKind::Shared)
2058 | WriteKind::MutableBorrow(BorrowKind::Shallow),
2062 | WriteKind::StorageDeadOrDrop
2063 | WriteKind::MutableBorrow(BorrowKind::Shared)
2064 | WriteKind::MutableBorrow(BorrowKind::Shallow),
2066 if let (Err(_), true) = (
2067 self.is_mutable(place.as_ref(), is_local_mutation_allowed),
2068 self.errors_buffer.is_empty(),
2070 // rust-lang/rust#46908: In pure NLL mode this code path should be
2071 // unreachable, but we use `delay_span_bug` because we can hit this when
2072 // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
2073 // enabled. We don't want to ICE for that case, as other errors will have
2074 // been emitted (#52262).
2075 self.infcx.tcx.sess.delay_span_bug(
2078 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2086 // permission checks are done at Reservation point.
2092 | BorrowKind::Mut { .. }
2093 | BorrowKind::Shared
2094 | BorrowKind::Shallow,
2098 // Access authorized
2103 // rust-lang/rust#21232, #54986: during period where we reject
2104 // partial initialization, do not complain about mutability
2105 // errors except for actual mutation (as opposed to an attempt
2106 // to do a partial initialization).
2107 let previously_initialized =
2108 self.is_local_ever_initialized(place.local, flow_state).is_some();
2110 // at this point, we have set up the error reporting state.
2111 if previously_initialized {
2112 self.report_mutability_error(place, span, the_place_err, error_access, location);
2119 fn is_local_ever_initialized(
2122 flow_state: &Flows<'cx, 'tcx>,
2123 ) -> Option<InitIndex> {
2124 let mpi = self.move_data.rev_lookup.find_local(local);
2125 let ii = &self.move_data.init_path_map[mpi];
2127 if flow_state.ever_inits.contains(index) {
2134 /// Adds the place into the used mutable variables set
2135 fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2137 RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2138 // If the local may have been initialized, and it is now currently being
2139 // mutated, then it is justified to be annotated with the `mut`
2140 // keyword, since the mutation may be a possible reassignment.
2141 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2142 && self.is_local_ever_initialized(local, flow_state).is_some()
2144 self.used_mut.insert(local);
2149 place_projection: _,
2150 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2154 place_projection: place_projection @ [.., _],
2155 is_local_mutation_allowed: _,
2157 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2159 projection: place_projection,
2161 self.used_mut_upvars.push(field);
2167 /// Whether this value can be written or borrowed mutably.
2168 /// Returns the root place if the place passed in is a projection.
2171 place: PlaceRef<'tcx>,
2172 is_local_mutation_allowed: LocalMutationIsAllowed,
2173 ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2175 PlaceRef { local, projection: [] } => {
2176 let local = &self.body.local_decls[local];
2177 match local.mutability {
2178 Mutability::Not => match is_local_mutation_allowed {
2179 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2180 place_local: place.local,
2181 place_projection: place.projection,
2182 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2184 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2185 place_local: place.local,
2186 place_projection: place.projection,
2187 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2189 LocalMutationIsAllowed::No => Err(place),
2191 Mutability::Mut => Ok(RootPlace {
2192 place_local: place.local,
2193 place_projection: place.projection,
2194 is_local_mutation_allowed,
2198 PlaceRef { local: _, projection: [proj_base @ .., elem] } => {
2200 ProjectionElem::Deref => {
2202 Place::ty_from(place.local, proj_base, self.body(), self.infcx.tcx).ty;
2204 // Check the kind of deref to decide
2205 match base_ty.kind() {
2206 ty::Ref(_, _, mutbl) => {
2208 // Shared borrowed data is never mutable
2209 hir::Mutability::Not => Err(place),
2210 // Mutably borrowed data is mutable, but only if we have a
2211 // unique path to the `&mut`
2212 hir::Mutability::Mut => {
2213 let mode = match self.is_upvar_field_projection(place) {
2214 Some(field) if self.upvars[field.index()].by_ref => {
2215 is_local_mutation_allowed
2217 _ => LocalMutationIsAllowed::Yes,
2221 PlaceRef { local: place.local, projection: proj_base },
2227 ty::RawPtr(tnm) => {
2229 // `*const` raw pointers are not mutable
2230 hir::Mutability::Not => Err(place),
2231 // `*mut` raw pointers are always mutable, regardless of
2232 // context. The users have to check by themselves.
2233 hir::Mutability::Mut => Ok(RootPlace {
2234 place_local: place.local,
2235 place_projection: place.projection,
2236 is_local_mutation_allowed,
2240 // `Box<T>` owns its content, so mutable if its location is mutable
2241 _ if base_ty.is_box() => self.is_mutable(
2242 PlaceRef { local: place.local, projection: proj_base },
2243 is_local_mutation_allowed,
2245 // Deref should only be for reference, pointers or boxes
2246 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2249 // All other projections are owned by their base path, so mutable if
2250 // base path is mutable
2251 ProjectionElem::Field(..)
2252 | ProjectionElem::Index(..)
2253 | ProjectionElem::ConstantIndex { .. }
2254 | ProjectionElem::Subslice { .. }
2255 | ProjectionElem::Downcast(..) => {
2256 let upvar_field_projection = self.is_upvar_field_projection(place);
2257 if let Some(field) = upvar_field_projection {
2258 let upvar = &self.upvars[field.index()];
2260 "upvar.mutability={:?} local_mutation_is_allowed={:?} \
2262 upvar, is_local_mutation_allowed, place
2264 match (upvar.mutability, is_local_mutation_allowed) {
2267 LocalMutationIsAllowed::No
2268 | LocalMutationIsAllowed::ExceptUpvars,
2270 (Mutability::Not, LocalMutationIsAllowed::Yes)
2271 | (Mutability::Mut, _) => {
2272 // Subtle: this is an upvar
2273 // reference, so it looks like
2274 // `self.foo` -- we want to double
2275 // check that the location `*self`
2276 // is mutable (i.e., this is not a
2277 // `Fn` closure). But if that
2278 // check succeeds, we want to
2279 // *blame* the mutability on
2280 // `place` (that is,
2281 // `self.foo`). This is used to
2282 // propagate the info about
2283 // whether mutability declarations
2284 // are used outwards, so that we register
2285 // the outer variable as mutable. Otherwise a
2286 // test like this fails to record the `mut`
2290 // fn foo<F: FnOnce()>(_f: F) { }
2292 // let var = Vec::new();
2298 let _ = self.is_mutable(
2299 PlaceRef { local: place.local, projection: proj_base },
2300 is_local_mutation_allowed,
2303 place_local: place.local,
2304 place_projection: place.projection,
2305 is_local_mutation_allowed,
2311 PlaceRef { local: place.local, projection: proj_base },
2312 is_local_mutation_allowed,
2321 /// If `place` is a field projection, and the field is being projected from a closure type,
2322 /// then returns the index of the field being projected. Note that this closure will always
2323 /// be `self` in the current MIR, because that is the only time we directly access the fields
2324 /// of a closure type.
2325 pub fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> {
2326 path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2330 /// The degree of overlap between 2 places for borrow-checking.
2332 /// The places might partially overlap - in this case, we give
2333 /// up and say that they might conflict. This occurs when
2334 /// different fields of a union are borrowed. For example,
2335 /// if `u` is a union, we have no way of telling how disjoint
2336 /// `u.a.x` and `a.b.y` are.
2338 /// The places have the same type, and are either completely disjoint
2339 /// or equal - i.e., they can't "partially" overlap as can occur with
2340 /// unions. This is the "base case" on which we recur for extensions
2343 /// The places are disjoint, so we know all extensions of them
2344 /// will also be disjoint.