1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
3 #![allow(rustc::potential_query_instability)]
4 #![feature(bool_to_option)]
5 #![feature(box_patterns)]
6 #![feature(crate_visibility_modifier)]
7 #![feature(let_chains)]
9 #![feature(min_specialization)]
10 #![feature(never_type)]
11 #![feature(stmt_expr_attributes)]
12 #![feature(trusted_step)]
13 #![feature(try_blocks)]
14 #![recursion_limit = "256"]
17 extern crate rustc_middle;
21 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
22 use rustc_data_structures::graph::dominators::Dominators;
23 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed};
25 use rustc_hir::def_id::LocalDefId;
26 use rustc_index::bit_set::ChunkedBitSet;
27 use rustc_index::vec::IndexVec;
28 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
29 use rustc_middle::mir::{
30 traversal, Body, ClearCrossCrate, Local, Location, Mutability, Operand, Place, PlaceElem,
31 PlaceRef, VarDebugInfoContents,
33 use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
34 use rustc_middle::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
35 use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind};
36 use rustc_middle::ty::query::Providers;
37 use rustc_middle::ty::{self, CapturedPlace, ParamEnv, RegionVid, TyCtxt};
38 use rustc_session::lint::builtin::{MUTABLE_BORROW_RESERVATION_CONFLICT, UNUSED_MUT};
39 use rustc_span::{Span, Symbol, DUMMY_SP};
42 use smallvec::SmallVec;
43 use std::cell::RefCell;
44 use std::collections::BTreeMap;
48 use rustc_mir_dataflow::impls::{
49 EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces,
51 use rustc_mir_dataflow::move_paths::{InitIndex, MoveOutIndex, MovePathIndex};
52 use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveData, MoveError};
53 use rustc_mir_dataflow::Analysis;
54 use rustc_mir_dataflow::MoveDataParamEnv;
56 use self::diagnostics::{AccessKind, RegionName};
57 use self::location::LocationTable;
58 use self::prefixes::PrefixSet;
61 use self::path_utils::*;
65 mod constraint_generation;
73 mod member_constraints;
82 mod universal_regions;
85 // A public API provided for the Rust compiler consumers.
88 use borrow_set::{BorrowData, BorrowSet};
89 use dataflow::{BorrowIndex, BorrowckFlowState as Flows, BorrowckResults, Borrows};
90 use nll::{PoloniusOutput, ToRegionVid};
91 use place_ext::PlaceExt;
92 use places_conflict::{places_conflict, PlaceConflictBias};
93 use region_infer::RegionInferenceContext;
95 // FIXME(eddyb) perhaps move this somewhere more centrally.
98 place: CapturedPlace<'tcx>,
100 /// If true, the capture is behind a reference.
104 const DEREF_PROJECTION: &[PlaceElem<'_>; 1] = &[ProjectionElem::Deref];
106 pub fn provide(providers: &mut Providers) {
107 *providers = Providers {
108 mir_borrowck: |tcx, did| {
109 if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
110 tcx.mir_borrowck_const_arg(def)
112 mir_borrowck(tcx, ty::WithOptConstParam::unknown(did))
115 mir_borrowck_const_arg: |tcx, (did, param_did)| {
116 mir_borrowck(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
122 fn mir_borrowck<'tcx>(
124 def: ty::WithOptConstParam<LocalDefId>,
125 ) -> &'tcx BorrowCheckResult<'tcx> {
126 let (input_body, promoted) = tcx.mir_promoted(def);
127 debug!("run query mir_borrowck: {}", tcx.def_path_str(def.did.to_def_id()));
128 let hir_owner = tcx.hir().local_def_id_to_hir_id(def.did).owner;
130 let opt_closure_req = tcx.infer_ctxt().with_opaque_type_inference(hir_owner).enter(|infcx| {
131 let input_body: &Body<'_> = &input_body.borrow();
132 let promoted: &IndexVec<_, _> = &promoted.borrow();
133 do_mir_borrowck(&infcx, input_body, promoted, false).0
135 debug!("mir_borrowck done");
137 tcx.arena.alloc(opt_closure_req)
140 /// Perform the actual borrow checking.
142 /// If `return_body_with_facts` is true, then return the body with non-erased
143 /// region ids on which the borrow checking was performed together with Polonius
145 #[instrument(skip(infcx, input_body, input_promoted), fields(id=?input_body.source.with_opt_param().as_local().unwrap()), level = "debug")]
146 fn do_mir_borrowck<'a, 'tcx>(
147 infcx: &InferCtxt<'a, 'tcx>,
148 input_body: &Body<'tcx>,
149 input_promoted: &IndexVec<Promoted, Body<'tcx>>,
150 return_body_with_facts: bool,
151 ) -> (BorrowCheckResult<'tcx>, Option<Box<BodyWithBorrowckFacts<'tcx>>>) {
152 let def = input_body.source.with_opt_param().as_local().unwrap();
157 let param_env = tcx.param_env(def.did);
159 let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
160 for var_debug_info in &input_body.var_debug_info {
161 if let VarDebugInfoContents::Place(place) = var_debug_info.value {
162 if let Some(local) = place.as_local() {
163 if let Some(prev_name) = local_names[local] && var_debug_info.name != prev_name {
165 var_debug_info.source_info.span,
166 "local {:?} has many names (`{}` vs `{}`)",
172 local_names[local] = Some(var_debug_info.name);
177 let mut errors = error::BorrowckErrors::new();
179 // Gather the upvars of a closure, if any.
180 let tables = tcx.typeck_opt_const_arg(def);
181 if let Some(ErrorGuaranteed { .. }) = tables.tainted_by_errors {
182 infcx.set_tainted_by_errors();
183 errors.set_tainted_by_errors();
185 let upvars: Vec<_> = tables
186 .closure_min_captures_flattened(def.did.to_def_id())
187 .map(|captured_place| {
188 let capture = captured_place.info.capture_kind;
189 let by_ref = match capture {
190 ty::UpvarCapture::ByValue => false,
191 ty::UpvarCapture::ByRef(..) => true,
193 Upvar { place: captured_place.clone(), by_ref }
197 // Replace all regions with fresh inference variables. This
198 // requires first making our own copy of the MIR. This copy will
199 // be modified (in place) to contain non-lexical lifetimes. It
200 // will have a lifetime tied to the inference context.
201 let mut body_owned = input_body.clone();
202 let mut promoted = input_promoted.clone();
204 nll::replace_regions_in_mir(infcx, param_env, &mut body_owned, &mut promoted);
205 let body = &body_owned; // no further changes
207 let location_table_owned = LocationTable::new(body);
208 let location_table = &location_table_owned;
210 let (move_data, move_errors): (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>) =
211 match MoveData::gather_moves(&body, tcx, param_env) {
212 Ok(move_data) => (move_data, Vec::new()),
213 Err((move_data, move_errors)) => (move_data, move_errors),
215 let promoted_errors = promoted
217 .map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env)));
219 let mdpe = MoveDataParamEnv { move_data, param_env };
221 let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe)
222 .into_engine(tcx, &body)
223 .pass_name("borrowck")
224 .iterate_to_fixpoint()
225 .into_results_cursor(&body);
227 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(def.did).is_fn_or_closure();
229 Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
231 let use_polonius = return_body_with_facts || infcx.tcx.sess.opts.debugging_opts.polonius;
233 // Compute non-lexical lifetimes.
241 } = nll::compute_regions(
255 // Dump MIR results into a file, if that is enabled. This let us
256 // write unit-tests, as well as helping with debugging.
257 nll::dump_mir_results(infcx, &body, ®ioncx, &opt_closure_req);
259 // We also have a `#[rustc_regions]` annotation that causes us to dump
261 nll::dump_annotation(
270 // The various `flow_*` structures can be large. We drop `flow_inits` here
271 // so it doesn't overlap with the others below. This reduces peak memory
272 // usage significantly on some benchmarks.
275 let regioncx = Rc::new(regioncx);
277 let flow_borrows = Borrows::new(tcx, body, ®ioncx, &borrow_set)
278 .into_engine(tcx, body)
279 .pass_name("borrowck")
280 .iterate_to_fixpoint();
281 let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &mdpe)
282 .into_engine(tcx, body)
283 .pass_name("borrowck")
284 .iterate_to_fixpoint();
285 let flow_ever_inits = EverInitializedPlaces::new(tcx, body, &mdpe)
286 .into_engine(tcx, body)
287 .pass_name("borrowck")
288 .iterate_to_fixpoint();
290 let movable_generator =
291 // The first argument is the generator type passed by value
292 if let Some(local) = body.local_decls.raw.get(1)
293 // Get the interior types and substs which typeck computed
294 && let ty::Generator(_, _, hir::Movability::Static) = local.ty.kind()
301 for (idx, move_data_results) in promoted_errors {
302 let promoted_body = &promoted[idx];
304 if let Err((move_data, move_errors)) = move_data_results {
305 let mut promoted_mbcx = MirBorrowckCtxt {
309 move_data: &move_data,
310 location_table, // no need to create a real one for the promoted, it is not used
312 fn_self_span_reported: Default::default(),
313 locals_are_invalidated_at_exit,
314 access_place_error_reported: Default::default(),
315 reservation_error_reported: Default::default(),
316 reservation_warnings: Default::default(),
317 uninitialized_error_reported: Default::default(),
318 regioncx: regioncx.clone(),
319 used_mut: Default::default(),
320 used_mut_upvars: SmallVec::new(),
321 borrow_set: Rc::clone(&borrow_set),
322 dominators: Dominators::dummy(), // not used
324 local_names: IndexVec::from_elem(None, &promoted_body.local_decls),
325 region_names: RefCell::default(),
326 next_region_name: RefCell::new(1),
327 polonius_output: None,
330 promoted_mbcx.report_move_errors(move_errors);
331 errors = promoted_mbcx.errors;
335 let dominators = body.dominators();
337 let mut mbcx = MirBorrowckCtxt {
341 move_data: &mdpe.move_data,
344 locals_are_invalidated_at_exit,
345 fn_self_span_reported: Default::default(),
346 access_place_error_reported: Default::default(),
347 reservation_error_reported: Default::default(),
348 reservation_warnings: Default::default(),
349 uninitialized_error_reported: Default::default(),
350 regioncx: Rc::clone(®ioncx),
351 used_mut: Default::default(),
352 used_mut_upvars: SmallVec::new(),
353 borrow_set: Rc::clone(&borrow_set),
357 region_names: RefCell::default(),
358 next_region_name: RefCell::new(1),
363 // Compute and report region errors, if any.
364 mbcx.report_region_errors(nll_errors);
366 let results = BorrowckResults {
367 ever_inits: flow_ever_inits,
368 uninits: flow_uninits,
369 borrows: flow_borrows,
372 mbcx.report_move_errors(move_errors);
374 rustc_mir_dataflow::visit_results(
376 traversal::reverse_postorder(body).map(|(bb, _)| bb),
381 // Convert any reservation warnings into lints.
382 let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
383 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
384 let initial_diag = mbcx.report_conflicting_borrow(location, (place, span), bk, &borrow);
386 let scope = mbcx.body.source_info(location).scope;
387 let lint_root = match &mbcx.body.source_scopes[scope].local_data {
388 ClearCrossCrate::Set(data) => data.lint_root,
389 _ => tcx.hir().local_def_id_to_hir_id(def.did),
392 // Span and message don't matter; we overwrite them below anyway
393 mbcx.infcx.tcx.struct_span_lint_hir(
394 MUTABLE_BORROW_RESERVATION_CONFLICT,
398 let mut diag = lint.build("");
400 diag.message = initial_diag.styled_message().clone();
401 diag.span = initial_diag.span.clone();
403 mbcx.buffer_non_error_diag(diag);
406 initial_diag.cancel();
409 // For each non-user used mutable variable, check if it's been assigned from
410 // a user-declared local. If so, then put that local into the used_mut set.
411 // Note that this set is expected to be small - only upvars from closures
412 // would have a chance of erroneously adding non-user-defined mutable vars
414 let temporary_used_locals: FxHashSet<Local> = mbcx
417 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
420 // For the remaining unused locals that are marked as mutable, we avoid linting any that
421 // were never initialized. These locals may have been removed as unreachable code; or will be
422 // linted as unused variables.
423 let unused_mut_locals =
424 mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
425 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
427 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
428 let used_mut = std::mem::take(&mut mbcx.used_mut);
429 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
430 let local_decl = &mbcx.body.local_decls[local];
431 let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data {
432 ClearCrossCrate::Set(data) => data.lint_root,
436 // Skip over locals that begin with an underscore or have no name
437 match mbcx.local_names[local] {
439 if name.as_str().starts_with('_') {
446 let span = local_decl.source_info.span;
447 if span.desugaring_kind().is_some() {
448 // If the `mut` arises as part of a desugaring, we should ignore it.
452 tcx.struct_span_lint_hir(UNUSED_MUT, lint_root, span, |lint| {
453 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
454 lint.build("variable does not need to be mutable")
455 .span_suggestion_short(
459 Applicability::MachineApplicable,
465 let tainted_by_errors = mbcx.emit_errors();
467 let result = BorrowCheckResult {
468 concrete_opaque_types: opaque_type_values,
469 closure_requirements: opt_closure_req,
470 used_mut_upvars: mbcx.used_mut_upvars,
474 let body_with_facts = if return_body_with_facts {
475 let output_facts = mbcx.polonius_output.expect("Polonius output was not computed");
476 Some(Box::new(BodyWithBorrowckFacts {
478 input_facts: *polonius_input.expect("Polonius input facts were not generated"),
480 location_table: location_table_owned,
486 debug!("do_mir_borrowck: result = {:#?}", result);
488 (result, body_with_facts)
491 /// A `Body` with information computed by the borrow checker. This struct is
492 /// intended to be consumed by compiler consumers.
494 /// We need to include the MIR body here because the region identifiers must
495 /// match the ones in the Polonius facts.
496 pub struct BodyWithBorrowckFacts<'tcx> {
497 /// A mir body that contains region identifiers.
498 pub body: Body<'tcx>,
499 /// Polonius input facts.
500 pub input_facts: AllFacts,
501 /// Polonius output facts.
502 pub output_facts: Rc<self::nll::PoloniusOutput>,
503 /// The table that maps Polonius points to locations in the table.
504 pub location_table: LocationTable,
507 struct MirBorrowckCtxt<'cx, 'tcx> {
508 infcx: &'cx InferCtxt<'cx, 'tcx>,
509 param_env: ParamEnv<'tcx>,
510 body: &'cx Body<'tcx>,
511 move_data: &'cx MoveData<'tcx>,
513 /// Map from MIR `Location` to `LocationIndex`; created
514 /// when MIR borrowck begins.
515 location_table: &'cx LocationTable,
517 movable_generator: bool,
518 /// This keeps track of whether local variables are free-ed when the function
519 /// exits even without a `StorageDead`, which appears to be the case for
522 /// I'm not sure this is the right approach - @eddyb could you try and
524 locals_are_invalidated_at_exit: bool,
525 /// This field keeps track of when borrow errors are reported in the access_place function
526 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
527 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
528 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
530 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
531 /// This field keeps track of when borrow conflict errors are reported
532 /// for reservations, so that we don't report seemingly duplicate
533 /// errors for corresponding activations.
535 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
536 // but it is currently inconvenient to track down the `BorrowIndex`
537 // at the time we detect and report a reservation error.
538 reservation_error_reported: FxHashSet<Place<'tcx>>,
539 /// This fields keeps track of the `Span`s that we have
540 /// used to report extra information for `FnSelfUse`, to avoid
541 /// unnecessarily verbose errors.
542 fn_self_span_reported: FxHashSet<Span>,
543 /// Migration warnings to be reported for #56254. We delay reporting these
544 /// so that we can suppress the warning if there's a corresponding error
545 /// for the activation of the borrow.
546 reservation_warnings:
547 FxHashMap<BorrowIndex, (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)>,
548 /// This field keeps track of errors reported in the checking of uninitialized variables,
549 /// so that we don't report seemingly duplicate errors.
550 uninitialized_error_reported: FxHashSet<PlaceRef<'tcx>>,
551 /// This field keeps track of all the local variables that are declared mut and are mutated.
552 /// Used for the warning issued by an unused mutable local variable.
553 used_mut: FxHashSet<Local>,
554 /// If the function we're checking is a closure, then we'll need to report back the list of
555 /// mutable upvars that have been used. This field keeps track of them.
556 used_mut_upvars: SmallVec<[Field; 8]>,
557 /// Region inference context. This contains the results from region inference and lets us e.g.
558 /// find out which CFG points are contained in each borrow region.
559 regioncx: Rc<RegionInferenceContext<'tcx>>,
561 /// The set of borrows extracted from the MIR
562 borrow_set: Rc<BorrowSet<'tcx>>,
564 /// Dominators for MIR
565 dominators: Dominators<BasicBlock>,
567 /// Information about upvars not necessarily preserved in types or MIR
568 upvars: Vec<Upvar<'tcx>>,
570 /// Names of local (user) variables (extracted from `var_debug_info`).
571 local_names: IndexVec<Local, Option<Symbol>>,
573 /// Record the region names generated for each region in the given
574 /// MIR def so that we can reuse them later in help/error messages.
575 region_names: RefCell<FxHashMap<RegionVid, RegionName>>,
577 /// The counter for generating new region names.
578 next_region_name: RefCell<usize>,
580 /// Results of Polonius analysis.
581 polonius_output: Option<Rc<PoloniusOutput>>,
583 errors: error::BorrowckErrors<'tcx>,
587 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
588 // 2. loans made in overlapping scopes do not conflict
589 // 3. assignments do not affect things loaned out as immutable
590 // 4. moves do not affect things loaned out in any way
591 impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
592 type FlowState = Flows<'cx, 'tcx>;
594 fn visit_statement_before_primary_effect(
596 flow_state: &Flows<'cx, 'tcx>,
597 stmt: &'cx Statement<'tcx>,
600 debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state);
601 let span = stmt.source_info.span;
603 self.check_activations(location, span, flow_state);
606 StatementKind::Assign(box (lhs, ref rhs)) => {
607 self.consume_rvalue(location, (rhs, span), flow_state);
609 self.mutate_place(location, (*lhs, span), Shallow(None), flow_state);
611 StatementKind::FakeRead(box (_, ref place)) => {
612 // Read for match doesn't access any memory and is used to
613 // assert that a place is safe and live. So we don't have to
614 // do any checks here.
616 // FIXME: Remove check that the place is initialized. This is
617 // needed for now because matches don't have never patterns yet.
618 // So this is the only place we prevent
622 self.check_if_path_or_subpath_is_moved(
624 InitializationRequiringAction::Use,
625 (place.as_ref(), span),
629 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
634 "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
638 | StatementKind::Coverage(..)
639 | StatementKind::AscribeUserType(..)
640 | StatementKind::Retag { .. }
641 | StatementKind::StorageLive(..) => {
642 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
645 StatementKind::StorageDead(local) => {
648 (Place::from(*local), span),
649 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
650 LocalMutationIsAllowed::Yes,
654 StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => {
655 bug!("Statement not allowed in this MIR phase")
660 fn visit_terminator_before_primary_effect(
662 flow_state: &Flows<'cx, 'tcx>,
663 term: &'cx Terminator<'tcx>,
666 debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
667 let span = term.source_info.span;
669 self.check_activations(loc, span, flow_state);
672 TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => {
673 self.consume_operand(loc, (discr, span), flow_state);
675 TerminatorKind::Drop { place, target: _, unwind: _ } => {
677 "visit_terminator_drop \
678 loc: {:?} term: {:?} place: {:?} span: {:?}",
679 loc, term, place, span
685 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
686 LocalMutationIsAllowed::Yes,
690 TerminatorKind::DropAndReplace {
692 value: ref new_value,
696 self.mutate_place(loc, (drop_place, span), Deep, flow_state);
697 self.consume_operand(loc, (new_value, span), flow_state);
699 TerminatorKind::Call {
707 self.consume_operand(loc, (func, span), flow_state);
709 self.consume_operand(loc, (arg, span), flow_state);
711 if let Some((dest, _ /*bb*/)) = *destination {
712 self.mutate_place(loc, (dest, span), Deep, flow_state);
715 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
716 self.consume_operand(loc, (cond, span), flow_state);
717 use rustc_middle::mir::AssertKind;
718 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
719 self.consume_operand(loc, (len, span), flow_state);
720 self.consume_operand(loc, (index, span), flow_state);
724 TerminatorKind::Yield { ref value, resume: _, resume_arg, drop: _ } => {
725 self.consume_operand(loc, (value, span), flow_state);
726 self.mutate_place(loc, (resume_arg, span), Deep, flow_state);
729 TerminatorKind::InlineAsm {
739 InlineAsmOperand::In { reg: _, ref value } => {
740 self.consume_operand(loc, (value, span), flow_state);
742 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
743 if let Some(place) = place {
744 self.mutate_place(loc, (place, span), Shallow(None), flow_state);
747 InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
748 self.consume_operand(loc, (in_value, span), flow_state);
749 if let Some(out_place) = out_place {
758 InlineAsmOperand::Const { value: _ }
759 | InlineAsmOperand::SymFn { value: _ }
760 | InlineAsmOperand::SymStatic { def_id: _ } => {}
765 TerminatorKind::Goto { target: _ }
766 | TerminatorKind::Abort
767 | TerminatorKind::Unreachable
768 | TerminatorKind::Resume
769 | TerminatorKind::Return
770 | TerminatorKind::GeneratorDrop
771 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
772 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
773 // no data used, thus irrelevant to borrowck
778 fn visit_terminator_after_primary_effect(
780 flow_state: &Flows<'cx, 'tcx>,
781 term: &'cx Terminator<'tcx>,
784 let span = term.source_info.span;
787 TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
788 if self.movable_generator {
789 // Look for any active borrows to locals
790 let borrow_set = self.borrow_set.clone();
791 for i in flow_state.borrows.iter() {
792 let borrow = &borrow_set[i];
793 self.check_for_local_borrow(borrow, span);
798 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
799 // Returning from the function implicitly kills storage for all locals and statics.
800 // Often, the storage will already have been killed by an explicit
801 // StorageDead, but we don't always emit those (notably on unwind paths),
802 // so this "extra check" serves as a kind of backup.
803 let borrow_set = self.borrow_set.clone();
804 for i in flow_state.borrows.iter() {
805 let borrow = &borrow_set[i];
806 self.check_for_invalidation_at_exit(loc, borrow, span);
810 TerminatorKind::Abort
811 | TerminatorKind::Assert { .. }
812 | TerminatorKind::Call { .. }
813 | TerminatorKind::Drop { .. }
814 | TerminatorKind::DropAndReplace { .. }
815 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
816 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
817 | TerminatorKind::Goto { .. }
818 | TerminatorKind::SwitchInt { .. }
819 | TerminatorKind::Unreachable
820 | TerminatorKind::InlineAsm { .. } => {}
825 use self::AccessDepth::{Deep, Shallow};
826 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
828 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
829 enum ArtificialField {
834 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
836 /// From the RFC: "A *shallow* access means that the immediate
837 /// fields reached at P are accessed, but references or pointers
838 /// found within are not dereferenced. Right now, the only access
839 /// that is shallow is an assignment like `x = ...;`, which would
840 /// be a *shallow write* of `x`."
841 Shallow(Option<ArtificialField>),
843 /// From the RFC: "A *deep* access means that all data reachable
844 /// through the given place may be invalidated or accesses by
848 /// Access is Deep only when there is a Drop implementation that
849 /// can reach the data behind the reference.
853 /// Kind of access to a value: read or write
854 /// (For informational purposes only)
855 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
857 /// From the RFC: "A *read* means that the existing data may be
858 /// read, but will not be changed."
861 /// From the RFC: "A *write* means that the data may be mutated to
862 /// new values or otherwise invalidated (for example, it could be
863 /// de-initialized, as in a move operation).
866 /// For two-phase borrows, we distinguish a reservation (which is treated
867 /// like a Read) from an activation (which is treated like a write), and
868 /// each of those is furthermore distinguished from Reads/Writes above.
869 Reservation(WriteKind),
870 Activation(WriteKind, BorrowIndex),
873 /// Kind of read access to a value
874 /// (For informational purposes only)
875 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
881 /// Kind of write access to a value
882 /// (For informational purposes only)
883 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
886 MutableBorrow(BorrowKind),
891 /// When checking permissions for a place access, this flag is used to indicate that an immutable
892 /// local place can be mutated.
894 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
895 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
896 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
897 // `is_declared_mutable()`.
898 // - Take flow state into consideration in `is_assignable()` for local variables.
899 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
900 enum LocalMutationIsAllowed {
902 /// We want use of immutable upvars to cause a "write to immutable upvar"
903 /// error, not an "reassignment" error.
908 #[derive(Copy, Clone, Debug)]
909 enum InitializationRequiringAction {
917 struct RootPlace<'tcx> {
919 place_projection: &'tcx [PlaceElem<'tcx>],
920 is_local_mutation_allowed: LocalMutationIsAllowed,
923 impl InitializationRequiringAction {
924 fn as_noun(self) -> &'static str {
926 InitializationRequiringAction::Borrow => "borrow",
927 InitializationRequiringAction::MatchOn => "use", // no good noun
928 InitializationRequiringAction::Use => "use",
929 InitializationRequiringAction::Assignment => "assign",
930 InitializationRequiringAction::PartialAssignment => "assign to part",
934 fn as_verb_in_past_tense(self) -> &'static str {
936 InitializationRequiringAction::Borrow => "borrowed",
937 InitializationRequiringAction::MatchOn => "matched on",
938 InitializationRequiringAction::Use => "used",
939 InitializationRequiringAction::Assignment => "assigned",
940 InitializationRequiringAction::PartialAssignment => "partially assigned",
945 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
946 fn body(&self) -> &'cx Body<'tcx> {
950 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
951 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
952 /// place is initialized and (b) it is not borrowed in some way that would prevent this
955 /// Returns `true` if an error is reported.
959 place_span: (Place<'tcx>, Span),
960 kind: (AccessDepth, ReadOrWrite),
961 is_local_mutation_allowed: LocalMutationIsAllowed,
962 flow_state: &Flows<'cx, 'tcx>,
966 if let Activation(_, borrow_index) = rw {
967 if self.reservation_error_reported.contains(&place_span.0) {
969 "skipping access_place for activation of invalid reservation \
970 place: {:?} borrow_index: {:?}",
971 place_span.0, borrow_index
977 // Check is_empty() first because it's the common case, and doing that
978 // way we avoid the clone() call.
979 if !self.access_place_error_reported.is_empty()
980 && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
983 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
989 let mutability_error = self.check_access_permissions(
992 is_local_mutation_allowed,
997 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
999 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
1000 // Suppress this warning when there's an error being emitted for the
1001 // same borrow: fixing the error is likely to fix the warning.
1002 self.reservation_warnings.remove(&borrow_idx);
1005 if conflict_error || mutability_error {
1006 debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
1007 self.access_place_error_reported.insert((place_span.0, place_span.1));
1011 fn check_access_for_conflict(
1014 place_span: (Place<'tcx>, Span),
1017 flow_state: &Flows<'cx, 'tcx>,
1020 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1021 location, place_span, sd, rw,
1024 let mut error_reported = false;
1025 let tcx = self.infcx.tcx;
1026 let body = self.body;
1027 let borrow_set = self.borrow_set.clone();
1029 // Use polonius output if it has been enabled.
1030 let polonius_output = self.polonius_output.clone();
1031 let borrows_in_scope = if let Some(polonius) = &polonius_output {
1032 let location = self.location_table.start_index(location);
1033 Either::Left(polonius.errors_at(location).iter().copied())
1035 Either::Right(flow_state.borrows.iter())
1038 each_borrow_involving_path(
1046 |this, borrow_index, borrow| match (rw, borrow.kind) {
1047 // Obviously an activation is compatible with its own
1048 // reservation (or even prior activating uses of same
1049 // borrow); so don't check if they interfere.
1051 // NOTE: *reservations* do conflict with themselves;
1052 // thus aren't injecting unsoundness w/ this check.)
1053 (Activation(_, activating), _) if activating == borrow_index => {
1055 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1056 skipping {:?} b/c activation of same borrow_index",
1060 (borrow_index, borrow),
1065 (Read(_), BorrowKind::Shared | BorrowKind::Shallow)
1067 Read(ReadKind::Borrow(BorrowKind::Shallow)),
1068 BorrowKind::Unique | BorrowKind::Mut { .. },
1069 ) => Control::Continue,
1071 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1072 // Handled by initialization checks.
1076 (Read(kind), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
1077 // Reading from mere reservations of mutable-borrows is OK.
1078 if !is_active(&this.dominators, borrow, location) {
1079 assert!(allow_two_phase_borrow(borrow.kind));
1080 return Control::Continue;
1083 error_reported = true;
1087 .report_use_while_mutably_borrowed(location, place_span, borrow);
1088 this.buffer_error(err);
1090 ReadKind::Borrow(bk) => {
1092 this.report_conflicting_borrow(location, place_span, bk, borrow);
1093 this.buffer_error(err);
1100 Reservation(WriteKind::MutableBorrow(bk)),
1101 BorrowKind::Shallow | BorrowKind::Shared,
1102 ) if { tcx.migrate_borrowck() && this.borrow_set.contains(&location) } => {
1103 let bi = this.borrow_set.get_index_of(&location).unwrap();
1105 "recording invalid reservation of place: {:?} with \
1106 borrow index {:?} as warning",
1109 // rust-lang/rust#56254 - This was previously permitted on
1110 // the 2018 edition so we emit it as a warning. We buffer
1111 // these separately so that we only emit a warning if borrow
1112 // checking was otherwise successful.
1113 this.reservation_warnings
1114 .insert(bi, (place_span.0, place_span.1, location, bk, borrow.clone()));
1116 // Don't suppress actual errors.
1120 (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1122 Reservation(..) => {
1124 "recording invalid reservation of \
1128 this.reservation_error_reported.insert(place_span.0);
1130 Activation(_, activating) => {
1132 "observing check_place for activation of \
1133 borrow_index: {:?}",
1137 Read(..) | Write(..) => {}
1140 error_reported = true;
1142 WriteKind::MutableBorrow(bk) => {
1144 this.report_conflicting_borrow(location, place_span, bk, borrow);
1145 this.buffer_error(err);
1147 WriteKind::StorageDeadOrDrop => this
1148 .report_borrowed_value_does_not_live_long_enough(
1154 WriteKind::Mutate => {
1155 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1157 WriteKind::Move => {
1158 this.report_move_out_while_borrowed(location, place_span, borrow)
1172 place_span: (Place<'tcx>, Span),
1174 flow_state: &Flows<'cx, 'tcx>,
1176 // Write of P[i] or *P requires P init'd.
1177 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1179 // Special case: you can assign an immutable local variable
1180 // (e.g., `x = ...`) so long as it has never been initialized
1181 // before (at this point in the flow).
1182 if let Some(local) = place_span.0.as_local() {
1183 if let Mutability::Not = self.body.local_decls[local].mutability {
1184 // check for reassignments to immutable local variables
1185 self.check_if_reassignment_to_immutable_state(
1186 location, local, place_span, flow_state,
1192 // Otherwise, use the normal access permission rules.
1196 (kind, Write(WriteKind::Mutate)),
1197 LocalMutationIsAllowed::No,
1205 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1206 flow_state: &Flows<'cx, 'tcx>,
1209 Rvalue::Ref(_ /*rgn*/, bk, place) => {
1210 let access_kind = match bk {
1211 BorrowKind::Shallow => {
1212 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1214 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1215 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1216 let wk = WriteKind::MutableBorrow(bk);
1217 if allow_two_phase_borrow(bk) {
1218 (Deep, Reservation(wk))
1229 LocalMutationIsAllowed::No,
1233 let action = if bk == BorrowKind::Shallow {
1234 InitializationRequiringAction::MatchOn
1236 InitializationRequiringAction::Borrow
1239 self.check_if_path_or_subpath_is_moved(
1242 (place.as_ref(), span),
1247 Rvalue::AddressOf(mutability, place) => {
1248 let access_kind = match mutability {
1249 Mutability::Mut => (
1251 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1252 allow_two_phase_borrow: false,
1255 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1262 LocalMutationIsAllowed::No,
1266 self.check_if_path_or_subpath_is_moved(
1268 InitializationRequiringAction::Borrow,
1269 (place.as_ref(), span),
1274 Rvalue::ThreadLocalRef(_) => {}
1276 Rvalue::Use(ref operand)
1277 | Rvalue::Repeat(ref operand, _)
1278 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1279 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/)
1280 | Rvalue::ShallowInitBox(ref operand, _ /*ty*/) => {
1281 self.consume_operand(location, (operand, span), flow_state)
1284 Rvalue::Len(place) | Rvalue::Discriminant(place) => {
1285 let af = match *rvalue {
1286 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1287 Rvalue::Discriminant(..) => None,
1288 _ => unreachable!(),
1293 (Shallow(af), Read(ReadKind::Copy)),
1294 LocalMutationIsAllowed::No,
1297 self.check_if_path_or_subpath_is_moved(
1299 InitializationRequiringAction::Use,
1300 (place.as_ref(), span),
1305 Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2))
1306 | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => {
1307 self.consume_operand(location, (operand1, span), flow_state);
1308 self.consume_operand(location, (operand2, span), flow_state);
1311 Rvalue::NullaryOp(_op, _ty) => {
1312 // nullary ops take no dynamic input; no borrowck effect.
1315 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1316 // We need to report back the list of mutable upvars that were
1317 // moved into the closure and subsequently used by the closure,
1318 // in order to populate our used_mut set.
1319 match **aggregate_kind {
1320 AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
1321 let BorrowCheckResult { used_mut_upvars, .. } =
1322 self.infcx.tcx.mir_borrowck(def_id.expect_local());
1323 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1324 for field in used_mut_upvars {
1325 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1328 AggregateKind::Adt(..)
1329 | AggregateKind::Array(..)
1330 | AggregateKind::Tuple { .. } => (),
1333 for operand in operands {
1334 self.consume_operand(location, (operand, span), flow_state);
1340 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1341 let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1342 // We have three possibilities here:
1343 // a. We are modifying something through a mut-ref
1344 // b. We are modifying something that is local to our parent
1345 // c. Current body is a nested closure, and we are modifying path starting from
1346 // a Place captured by our parent closure.
1348 // Handle (c), the path being modified is exactly the path captured by our parent
1349 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1350 this.used_mut_upvars.push(field);
1354 for (place_ref, proj) in place.iter_projections().rev() {
1356 if proj == ProjectionElem::Deref {
1357 match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1358 // We aren't modifying a variable directly
1359 ty::Ref(_, _, hir::Mutability::Mut) => return,
1366 if let Some(field) = this.is_upvar_field_projection(place_ref) {
1367 this.used_mut_upvars.push(field);
1373 this.used_mut.insert(place.local);
1376 // This relies on the current way that by-value
1377 // captures of a closure are copied/moved directly
1378 // when generating MIR.
1380 Operand::Move(place) | Operand::Copy(place) => {
1381 match place.as_local() {
1382 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1383 if self.body.local_decls[local].ty.is_mutable_ptr() {
1384 // The variable will be marked as mutable by the borrow.
1387 // This is an edge case where we have a `move` closure
1388 // inside a non-move closure, and the inner closure
1389 // contains a mutation:
1392 // || { move || { i += 1; }; };
1394 // In this case our usual strategy of assuming that the
1395 // variable will be captured by mutable reference is
1396 // wrong, since `i` can be copied into the inner
1397 // closure from a shared reference.
1399 // As such we have to search for the local that this
1400 // capture comes from and mark it as being used as mut.
1402 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1403 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1404 &self.move_data.inits[init_index]
1406 bug!("temporary should be initialized exactly once")
1409 let InitLocation::Statement(loc) = init.location else {
1410 bug!("temporary initialized in arguments")
1413 let body = self.body;
1414 let bbd = &body[loc.block];
1415 let stmt = &bbd.statements[loc.statement_index];
1416 debug!("temporary assigned in: stmt={:?}", stmt);
1418 if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, source))) = stmt.kind
1420 propagate_closure_used_mut_place(self, source);
1423 "closures should only capture user variables \
1424 or references to user variables"
1428 _ => propagate_closure_used_mut_place(self, place),
1431 Operand::Constant(..) => {}
1438 (operand, span): (&'cx Operand<'tcx>, Span),
1439 flow_state: &Flows<'cx, 'tcx>,
1442 Operand::Copy(place) => {
1443 // copy of place: check if this is "copy of frozen path"
1444 // (FIXME: see check_loans.rs)
1448 (Deep, Read(ReadKind::Copy)),
1449 LocalMutationIsAllowed::No,
1453 // Finally, check if path was already moved.
1454 self.check_if_path_or_subpath_is_moved(
1456 InitializationRequiringAction::Use,
1457 (place.as_ref(), span),
1461 Operand::Move(place) => {
1462 // move of place: check if this is move of already borrowed path
1466 (Deep, Write(WriteKind::Move)),
1467 LocalMutationIsAllowed::Yes,
1471 // Finally, check if path was already moved.
1472 self.check_if_path_or_subpath_is_moved(
1474 InitializationRequiringAction::Use,
1475 (place.as_ref(), span),
1479 Operand::Constant(_) => {}
1483 /// Checks whether a borrow of this place is invalidated when the function
1485 fn check_for_invalidation_at_exit(
1488 borrow: &BorrowData<'tcx>,
1491 debug!("check_for_invalidation_at_exit({:?})", borrow);
1492 let place = borrow.borrowed_place;
1493 let mut root_place = PlaceRef { local: place.local, projection: &[] };
1495 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1496 // we just know that all locals are dropped at function exit (otherwise
1497 // we'll have a memory leak) and assume that all statics have a destructor.
1499 // FIXME: allow thread-locals to borrow other thread locals?
1501 let (might_be_alive, will_be_dropped) =
1502 if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1503 // Thread-locals might be dropped after the function exits
1504 // We have to dereference the outer reference because
1505 // borrows don't conflict behind shared references.
1506 root_place.projection = DEREF_PROJECTION;
1509 (false, self.locals_are_invalidated_at_exit)
1512 if !will_be_dropped {
1513 debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
1517 let sd = if might_be_alive { Deep } else { Shallow(None) };
1519 if places_conflict::borrow_conflicts_with_place(
1526 places_conflict::PlaceConflictBias::Overlap,
1528 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1529 // FIXME: should be talking about the region lifetime instead
1530 // of just a span here.
1531 let span = self.infcx.tcx.sess.source_map().end_point(span);
1532 self.report_borrowed_value_does_not_live_long_enough(
1541 /// Reports an error if this is a borrow of local data.
1542 /// This is called for all Yield expressions on movable generators
1543 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1544 debug!("check_for_local_borrow({:?})", borrow);
1546 if borrow_of_local_data(borrow.borrowed_place) {
1547 let err = self.cannot_borrow_across_generator_yield(
1548 self.retrieve_borrow_spans(borrow).var_or_use(),
1552 self.buffer_error(err);
1556 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1557 // Two-phase borrow support: For each activation that is newly
1558 // generated at this statement, check if it interferes with
1560 let borrow_set = self.borrow_set.clone();
1561 for &borrow_index in borrow_set.activations_at_location(location) {
1562 let borrow = &borrow_set[borrow_index];
1564 // only mutable borrows should be 2-phase
1565 assert!(match borrow.kind {
1566 BorrowKind::Shared | BorrowKind::Shallow => false,
1567 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1572 (borrow.borrowed_place, span),
1573 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1574 LocalMutationIsAllowed::No,
1577 // We do not need to call `check_if_path_or_subpath_is_moved`
1578 // again, as we already called it when we made the
1579 // initial reservation.
1583 fn check_if_reassignment_to_immutable_state(
1587 place_span: (Place<'tcx>, Span),
1588 flow_state: &Flows<'cx, 'tcx>,
1590 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1592 // Check if any of the initializations of `local` have happened yet:
1593 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1594 // And, if so, report an error.
1595 let init = &self.move_data.inits[init_index];
1596 let span = init.span(&self.body);
1597 self.report_illegal_reassignment(location, place_span, span, place_span.0);
1601 fn check_if_full_path_is_moved(
1604 desired_action: InitializationRequiringAction,
1605 place_span: (PlaceRef<'tcx>, Span),
1606 flow_state: &Flows<'cx, 'tcx>,
1608 let maybe_uninits = &flow_state.uninits;
1612 // 1. Move of `a.b.c`, use of `a.b.c`
1613 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1614 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1615 // partial initialization support, one might have `a.x`
1616 // initialized but not `a.b`.
1620 // 4. Move of `a.b.c`, use of `a.b.d`
1621 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1622 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1623 // must have been initialized for the use to be sound.
1624 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1626 // The dataflow tracks shallow prefixes distinctly (that is,
1627 // field-accesses on P distinctly from P itself), in order to
1628 // track substructure initialization separately from the whole
1631 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1632 // which we have a MovePath is `a.b`, then that means that the
1633 // initialization state of `a.b` is all we need to inspect to
1634 // know if `a.b.c` is valid (and from that we infer that the
1635 // dereference and `.d` access is also valid, since we assume
1636 // `a.b.c` is assigned a reference to an initialized and
1637 // well-formed record structure.)
1639 // Therefore, if we seek out the *closest* prefix for which we
1640 // have a MovePath, that should capture the initialization
1641 // state for the place scenario.
1643 // This code covers scenarios 1, 2, and 3.
1645 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1646 let (prefix, mpi) = self.move_path_closest_to(place_span.0);
1647 if maybe_uninits.contains(mpi) {
1648 self.report_use_of_moved_or_uninitialized(
1651 (prefix, place_span.0, place_span.1),
1654 } // Only query longest prefix with a MovePath, not further
1655 // ancestors; dataflow recurs on children when parents
1656 // move (to support partial (re)inits).
1658 // (I.e., querying parents breaks scenario 7; but may want
1659 // to do such a query based on partial-init feature-gate.)
1662 /// Subslices correspond to multiple move paths, so we iterate through the
1663 /// elements of the base array. For each element we check
1665 /// * Does this element overlap with our slice.
1666 /// * Is any part of it uninitialized.
1667 fn check_if_subslice_element_is_moved(
1670 desired_action: InitializationRequiringAction,
1671 place_span: (PlaceRef<'tcx>, Span),
1672 maybe_uninits: &ChunkedBitSet<MovePathIndex>,
1676 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1677 let move_paths = &self.move_data.move_paths;
1679 let root_path = &move_paths[mpi];
1680 for (child_mpi, child_move_path) in root_path.children(move_paths) {
1681 let last_proj = child_move_path.place.projection.last().unwrap();
1682 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
1683 debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
1685 if (from..to).contains(offset) {
1687 self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
1688 maybe_uninits.contains(mpi)
1691 if let Some(uninit_child) = uninit_child {
1692 self.report_use_of_moved_or_uninitialized(
1695 (place_span.0, place_span.0, place_span.1),
1698 return; // don't bother finding other problems.
1706 fn check_if_path_or_subpath_is_moved(
1709 desired_action: InitializationRequiringAction,
1710 place_span: (PlaceRef<'tcx>, Span),
1711 flow_state: &Flows<'cx, 'tcx>,
1713 let maybe_uninits = &flow_state.uninits;
1717 // 1. Move of `a.b.c`, use of `a` or `a.b`
1718 // partial initialization support, one might have `a.x`
1719 // initialized but not `a.b`.
1720 // 2. All bad scenarios from `check_if_full_path_is_moved`
1724 // 3. Move of `a.b.c`, use of `a.b.d`
1725 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1726 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1727 // must have been initialized for the use to be sound.
1728 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1730 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1732 if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
1733 place_span.0.last_projection()
1735 let place_ty = place_base.ty(self.body(), self.infcx.tcx);
1736 if let ty::Array(..) = place_ty.ty.kind() {
1737 self.check_if_subslice_element_is_moved(
1740 (place_base, place_span.1),
1749 // A move of any shallow suffix of `place` also interferes
1750 // with an attempt to use `place`. This is scenario 3 above.
1752 // (Distinct from handling of scenarios 1+2+4 above because
1753 // `place` does not interfere with suffixes of its prefixes,
1754 // e.g., `a.b.c` does not interfere with `a.b.d`)
1756 // This code covers scenario 1.
1758 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1759 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1760 let uninit_mpi = self
1762 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
1764 if let Some(uninit_mpi) = uninit_mpi {
1765 self.report_use_of_moved_or_uninitialized(
1768 (place_span.0, place_span.0, place_span.1),
1771 return; // don't bother finding other problems.
1776 /// Currently MoveData does not store entries for all places in
1777 /// the input MIR. For example it will currently filter out
1778 /// places that are Copy; thus we do not track places of shared
1779 /// reference type. This routine will walk up a place along its
1780 /// prefixes, searching for a foundational place that *is*
1781 /// tracked in the MoveData.
1783 /// An Err result includes a tag indicated why the search failed.
1784 /// Currently this can only occur if the place is built off of a
1785 /// static variable, as we do not track those in the MoveData.
1786 fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
1787 match self.move_data.rev_lookup.find(place) {
1788 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
1789 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
1791 LookupResult::Parent(None) => panic!("should have move path for every Local"),
1795 fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
1796 // If returns None, then there is no move path corresponding
1797 // to a direct owner of `place` (which means there is nothing
1798 // that borrowck tracks for its analysis).
1800 match self.move_data.rev_lookup.find(place) {
1801 LookupResult::Parent(_) => None,
1802 LookupResult::Exact(mpi) => Some(mpi),
1806 fn check_if_assigned_path_is_moved(
1809 (place, span): (Place<'tcx>, Span),
1810 flow_state: &Flows<'cx, 'tcx>,
1812 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1814 // None case => assigning to `x` does not require `x` be initialized.
1815 for (place_base, elem) in place.iter_projections().rev() {
1817 ProjectionElem::Index(_/*operand*/) |
1818 ProjectionElem::ConstantIndex { .. } |
1819 // assigning to P[i] requires P to be valid.
1820 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1821 // assigning to (P->variant) is okay if assigning to `P` is okay
1823 // FIXME: is this true even if P is an adt with a dtor?
1826 // assigning to (*P) requires P to be initialized
1827 ProjectionElem::Deref => {
1828 self.check_if_full_path_is_moved(
1829 location, InitializationRequiringAction::Use,
1830 (place_base, span), flow_state);
1831 // (base initialized; no need to
1836 ProjectionElem::Subslice { .. } => {
1837 panic!("we don't allow assignments to subslices, location: {:?}",
1841 ProjectionElem::Field(..) => {
1842 // if type of `P` has a dtor, then
1843 // assigning to `P.f` requires `P` itself
1844 // be already initialized
1845 let tcx = self.infcx.tcx;
1846 let base_ty = place_base.ty(self.body(), tcx).ty;
1847 match base_ty.kind() {
1848 ty::Adt(def, _) if def.has_dtor(tcx) => {
1849 self.check_if_path_or_subpath_is_moved(
1850 location, InitializationRequiringAction::Assignment,
1851 (place_base, span), flow_state);
1853 // (base initialized; no need to
1858 // Once `let s; s.x = V; read(s.x);`,
1859 // is allowed, remove this match arm.
1860 ty::Adt(..) | ty::Tuple(..) => {
1861 check_parent_of_field(self, location, place_base, span, flow_state);
1863 // rust-lang/rust#21232, #54499, #54986: during period where we reject
1864 // partial initialization, do not complain about unnecessary `mut` on
1865 // an attempt to do a partial initialization.
1866 self.used_mut.insert(place.local);
1875 fn check_parent_of_field<'cx, 'tcx>(
1876 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1878 base: PlaceRef<'tcx>,
1880 flow_state: &Flows<'cx, 'tcx>,
1882 // rust-lang/rust#21232: Until Rust allows reads from the
1883 // initialized parts of partially initialized structs, we
1884 // will, starting with the 2018 edition, reject attempts
1885 // to write to structs that are not fully initialized.
1887 // In other words, *until* we allow this:
1889 // 1. `let mut s; s.x = Val; read(s.x);`
1891 // we will for now disallow this:
1893 // 2. `let mut s; s.x = Val;`
1897 // 3. `let mut s = ...; drop(s); s.x=Val;`
1899 // This does not use check_if_path_or_subpath_is_moved,
1900 // because we want to *allow* reinitializations of fields:
1901 // e.g., want to allow
1903 // `let mut s = ...; drop(s.x); s.x=Val;`
1905 // This does not use check_if_full_path_is_moved on
1906 // `base`, because that would report an error about the
1907 // `base` as a whole, but in this scenario we *really*
1908 // want to report an error about the actual thing that was
1909 // moved, which may be some prefix of `base`.
1911 // Shallow so that we'll stop at any dereference; we'll
1912 // report errors about issues with such bases elsewhere.
1913 let maybe_uninits = &flow_state.uninits;
1915 // Find the shortest uninitialized prefix you can reach
1916 // without going over a Deref.
1917 let mut shortest_uninit_seen = None;
1918 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1919 let Some(mpi) = this.move_path_for_place(prefix) else { continue };
1921 if maybe_uninits.contains(mpi) {
1923 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1924 shortest_uninit_seen,
1927 shortest_uninit_seen = Some((prefix, mpi));
1929 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1933 if let Some((prefix, mpi)) = shortest_uninit_seen {
1934 // Check for a reassignment into an uninitialized field of a union (for example,
1935 // after a move out). In this case, do not report an error here. There is an
1936 // exception, if this is the first assignment into the union (that is, there is
1937 // no move out from an earlier location) then this is an attempt at initialization
1938 // of the union - we should error in that case.
1939 let tcx = this.infcx.tcx;
1940 if base.ty(this.body(), tcx).ty.is_union() {
1941 if this.move_data.path_map[mpi].iter().any(|moi| {
1942 this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
1948 this.report_use_of_moved_or_uninitialized(
1950 InitializationRequiringAction::PartialAssignment,
1951 (prefix, base, span),
1958 /// Checks the permissions for the given place and read or write kind
1960 /// Returns `true` if an error is reported.
1961 fn check_access_permissions(
1963 (place, span): (Place<'tcx>, Span),
1965 is_local_mutation_allowed: LocalMutationIsAllowed,
1966 flow_state: &Flows<'cx, 'tcx>,
1970 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1971 place, kind, is_local_mutation_allowed
1978 Reservation(WriteKind::MutableBorrow(
1979 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
1981 | Write(WriteKind::MutableBorrow(
1982 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
1984 let is_local_mutation_allowed = match borrow_kind {
1985 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1986 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1987 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1989 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1991 self.add_used_mut(root_place, flow_state);
1995 error_access = AccessKind::MutableBorrow;
1996 the_place_err = place_err;
2000 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
2001 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2003 self.add_used_mut(root_place, flow_state);
2007 error_access = AccessKind::Mutate;
2008 the_place_err = place_err;
2015 | WriteKind::StorageDeadOrDrop
2016 | WriteKind::MutableBorrow(BorrowKind::Shared)
2017 | WriteKind::MutableBorrow(BorrowKind::Shallow),
2021 | WriteKind::StorageDeadOrDrop
2022 | WriteKind::MutableBorrow(BorrowKind::Shared)
2023 | WriteKind::MutableBorrow(BorrowKind::Shallow),
2025 if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err()
2026 && !self.has_buffered_errors()
2028 // rust-lang/rust#46908: In pure NLL mode this code path should be
2029 // unreachable, but we use `delay_span_bug` because we can hit this when
2030 // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
2031 // enabled. We don't want to ICE for that case, as other errors will have
2032 // been emitted (#52262).
2033 self.infcx.tcx.sess.delay_span_bug(
2036 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2044 // permission checks are done at Reservation point.
2050 | BorrowKind::Mut { .. }
2051 | BorrowKind::Shared
2052 | BorrowKind::Shallow,
2056 // Access authorized
2061 // rust-lang/rust#21232, #54986: during period where we reject
2062 // partial initialization, do not complain about mutability
2063 // errors except for actual mutation (as opposed to an attempt
2064 // to do a partial initialization).
2065 let previously_initialized =
2066 self.is_local_ever_initialized(place.local, flow_state).is_some();
2068 // at this point, we have set up the error reporting state.
2069 if previously_initialized {
2070 self.report_mutability_error(place, span, the_place_err, error_access, location);
2077 fn is_local_ever_initialized(
2080 flow_state: &Flows<'cx, 'tcx>,
2081 ) -> Option<InitIndex> {
2082 let mpi = self.move_data.rev_lookup.find_local(local);
2083 let ii = &self.move_data.init_path_map[mpi];
2085 if flow_state.ever_inits.contains(index) {
2092 /// Adds the place into the used mutable variables set
2093 fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2095 RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2096 // If the local may have been initialized, and it is now currently being
2097 // mutated, then it is justified to be annotated with the `mut`
2098 // keyword, since the mutation may be a possible reassignment.
2099 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2100 && self.is_local_ever_initialized(local, flow_state).is_some()
2102 self.used_mut.insert(local);
2107 place_projection: _,
2108 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2112 place_projection: place_projection @ [.., _],
2113 is_local_mutation_allowed: _,
2115 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2117 projection: place_projection,
2119 self.used_mut_upvars.push(field);
2125 /// Whether this value can be written or borrowed mutably.
2126 /// Returns the root place if the place passed in is a projection.
2129 place: PlaceRef<'tcx>,
2130 is_local_mutation_allowed: LocalMutationIsAllowed,
2131 ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2132 debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2133 match place.last_projection() {
2135 let local = &self.body.local_decls[place.local];
2136 match local.mutability {
2137 Mutability::Not => match is_local_mutation_allowed {
2138 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2139 place_local: place.local,
2140 place_projection: place.projection,
2141 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2143 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2144 place_local: place.local,
2145 place_projection: place.projection,
2146 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2148 LocalMutationIsAllowed::No => Err(place),
2150 Mutability::Mut => Ok(RootPlace {
2151 place_local: place.local,
2152 place_projection: place.projection,
2153 is_local_mutation_allowed,
2157 Some((place_base, elem)) => {
2159 ProjectionElem::Deref => {
2160 let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2162 // Check the kind of deref to decide
2163 match base_ty.kind() {
2164 ty::Ref(_, _, mutbl) => {
2166 // Shared borrowed data is never mutable
2167 hir::Mutability::Not => Err(place),
2168 // Mutably borrowed data is mutable, but only if we have a
2169 // unique path to the `&mut`
2170 hir::Mutability::Mut => {
2171 let mode = match self.is_upvar_field_projection(place) {
2172 Some(field) if self.upvars[field.index()].by_ref => {
2173 is_local_mutation_allowed
2175 _ => LocalMutationIsAllowed::Yes,
2178 self.is_mutable(place_base, mode)
2182 ty::RawPtr(tnm) => {
2184 // `*const` raw pointers are not mutable
2185 hir::Mutability::Not => Err(place),
2186 // `*mut` raw pointers are always mutable, regardless of
2187 // context. The users have to check by themselves.
2188 hir::Mutability::Mut => Ok(RootPlace {
2189 place_local: place.local,
2190 place_projection: place.projection,
2191 is_local_mutation_allowed,
2195 // `Box<T>` owns its content, so mutable if its location is mutable
2196 _ if base_ty.is_box() => {
2197 self.is_mutable(place_base, is_local_mutation_allowed)
2199 // Deref should only be for reference, pointers or boxes
2200 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2203 // All other projections are owned by their base path, so mutable if
2204 // base path is mutable
2205 ProjectionElem::Field(..)
2206 | ProjectionElem::Index(..)
2207 | ProjectionElem::ConstantIndex { .. }
2208 | ProjectionElem::Subslice { .. }
2209 | ProjectionElem::Downcast(..) => {
2210 let upvar_field_projection = self.is_upvar_field_projection(place);
2211 if let Some(field) = upvar_field_projection {
2212 let upvar = &self.upvars[field.index()];
2214 "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2215 place={:?}, place_base={:?}",
2216 upvar, is_local_mutation_allowed, place, place_base
2218 match (upvar.place.mutability, is_local_mutation_allowed) {
2221 LocalMutationIsAllowed::No
2222 | LocalMutationIsAllowed::ExceptUpvars,
2224 (Mutability::Not, LocalMutationIsAllowed::Yes)
2225 | (Mutability::Mut, _) => {
2226 // Subtle: this is an upvar
2227 // reference, so it looks like
2228 // `self.foo` -- we want to double
2229 // check that the location `*self`
2230 // is mutable (i.e., this is not a
2231 // `Fn` closure). But if that
2232 // check succeeds, we want to
2233 // *blame* the mutability on
2234 // `place` (that is,
2235 // `self.foo`). This is used to
2236 // propagate the info about
2237 // whether mutability declarations
2238 // are used outwards, so that we register
2239 // the outer variable as mutable. Otherwise a
2240 // test like this fails to record the `mut`
2244 // fn foo<F: FnOnce()>(_f: F) { }
2246 // let var = Vec::new();
2253 self.is_mutable(place_base, is_local_mutation_allowed)?;
2255 place_local: place.local,
2256 place_projection: place.projection,
2257 is_local_mutation_allowed,
2262 self.is_mutable(place_base, is_local_mutation_allowed)
2270 /// If `place` is a field projection, and the field is being projected from a closure type,
2271 /// then returns the index of the field being projected. Note that this closure will always
2272 /// be `self` in the current MIR, because that is the only time we directly access the fields
2273 /// of a closure type.
2274 fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> {
2275 path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2280 use rustc_errors::ErrorGuaranteed;
2284 pub struct BorrowckErrors<'tcx> {
2285 /// This field keeps track of move errors that are to be reported for given move indices.
2287 /// There are situations where many errors can be reported for a single move out (see #53807)
2288 /// and we want only the best of those errors.
2290 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
2291 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
2292 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
2293 /// all move errors have been reported, any diagnostics in this map are added to the buffer
2296 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
2297 /// when errors in the map are being re-added to the error buffer so that errors with the
2298 /// same primary span come out in a consistent order.
2299 buffered_move_errors:
2300 BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorGuaranteed>)>,
2301 /// Diagnostics to be reported buffer.
2302 buffered: Vec<Diagnostic>,
2303 /// Set to Some if we emit an error during borrowck
2304 tainted_by_errors: Option<ErrorGuaranteed>,
2307 impl BorrowckErrors<'_> {
2308 pub fn new() -> Self {
2310 buffered_move_errors: BTreeMap::new(),
2311 buffered: Default::default(),
2312 tainted_by_errors: None,
2316 // FIXME(eddyb) this is a suboptimal API because `tainted_by_errors` is
2317 // set before any emission actually happens (weakening the guarantee).
2318 pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorGuaranteed>) {
2319 self.tainted_by_errors = Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
2320 t.buffer(&mut self.buffered);
2323 pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) {
2324 t.buffer(&mut self.buffered);
2327 pub fn set_tainted_by_errors(&mut self) {
2328 self.tainted_by_errors = Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
2332 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
2333 pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorGuaranteed>) {
2334 self.errors.buffer_error(t);
2337 pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) {
2338 self.errors.buffer_non_error_diag(t);
2341 pub fn buffer_move_error(
2343 move_out_indices: Vec<MoveOutIndex>,
2344 place_and_err: (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorGuaranteed>),
2346 if let Some((_, diag)) =
2347 self.errors.buffered_move_errors.insert(move_out_indices, place_and_err)
2349 // Cancel the old diagnostic so we don't ICE
2357 pub fn emit_errors(&mut self) -> Option<ErrorGuaranteed> {
2358 // Buffer any move errors that we collected and de-duplicated.
2359 for (_, (_, diag)) in std::mem::take(&mut self.errors.buffered_move_errors) {
2360 // We have already set tainted for this error, so just buffer it.
2361 diag.buffer(&mut self.errors.buffered);
2364 if !self.errors.buffered.is_empty() {
2365 self.errors.buffered.sort_by_key(|diag| diag.sort_span);
2367 for mut diag in self.errors.buffered.drain(..) {
2368 self.infcx.tcx.sess.diagnostic().emit_diagnostic(&mut diag);
2372 self.errors.tainted_by_errors
2375 pub fn has_buffered_errors(&self) -> bool {
2376 self.errors.buffered.is_empty()
2379 pub fn has_move_error(
2381 move_out_indices: &[MoveOutIndex],
2382 ) -> Option<&(PlaceRef<'tcx>, DiagnosticBuilder<'cx, ErrorGuaranteed>)> {
2383 self.errors.buffered_move_errors.get(move_out_indices)
2388 /// The degree of overlap between 2 places for borrow-checking.
2390 /// The places might partially overlap - in this case, we give
2391 /// up and say that they might conflict. This occurs when
2392 /// different fields of a union are borrowed. For example,
2393 /// if `u` is a union, we have no way of telling how disjoint
2394 /// `u.a.x` and `a.b.y` are.
2396 /// The places have the same type, and are either completely disjoint
2397 /// or equal - i.e., they can't "partially" overlap as can occur with
2398 /// unions. This is the "base case" on which we recur for extensions
2401 /// The places are disjoint, so we know all extensions of them
2402 /// will also be disjoint.