#![allow(internal_features)]
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use alloc::borrow::Cow;
use core::cell::{OnceCell, RefCell};
use core::marker::PhantomData;
use core::ops::{ControlFlow, Deref};
use alloc::rc::Rc;
use borrow_set::LocalsStateAtExit;
use crate::polonius_engine::AllFacts;
use root_cx::BorrowCheckRootCtxt;
use crate::rustc_abi::FieldIdx;
use crate::rustc_data_structures::frozen::Frozen;
use crate::rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
use crate::rustc_data_structures::graph::dominators::Dominators;
use crate::rustc_hir as hir;
use crate::rustc_hir::CRATE_HIR_ID;
use crate::rustc_hir::def_id::LocalDefId;
use crate::rustc_index::bit_set::MixedBitSet;
use crate::rustc_index::{IndexSlice, IndexVec};
use crate::rustc_infer::infer::outlives::env::RegionBoundPairs;
use crate::rustc_infer::infer::{
InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin, TyCtxtInferExt,
};
use crate::rustc_lint_defs::builtin::{TAIL_EXPR_DROP_ORDER, UNUSED_MUT};
use crate::rustc_middle::mir::*;
use crate::rustc_middle::query::Providers;
use crate::rustc_middle::ty::{
self, ParamEnv, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitable, TypingMode, fold_regions,
};
use crate::rustc_middle::{bug, span_bug};
use crate::rustc_mir_dataflow::impls::{EverInitializedPlaces, MaybeUninitializedPlaces};
use crate::rustc_mir_dataflow::move_paths::{
InitIndex, InitLocation, LookupResult, MoveData, MovePathIndex,
};
use crate::rustc_mir_dataflow::points::DenseLocationMap;
use crate::rustc_mir_dataflow::{Analysis, EntryStates, Results, ResultsVisitor, visit_results};
use crate::rustc_span::{ErrorGuaranteed, Span, Symbol};
use crate::rustc_trait_selection::traits::query::type_op::{QueryTypeOp, TypeOp, TypeOpOutput};
use smallvec::SmallVec;
use tracing::{debug, instrument};
use crate::rustc_borrowck::borrow_set::{BorrowData, BorrowSet};
use crate::rustc_borrowck::consumers::{BodyWithBorrowckFacts, RustcFacts};
use crate::rustc_borrowck::dataflow::{BorrowIndex, Borrowck, BorrowckDomain, Borrows};
use crate::rustc_borrowck::diagnostics::{
AccessKind, BorrowckDiagnosticsBuffer, IllegalMoveOriginKind, MoveError, RegionName,
};
use crate::rustc_borrowck::implied_bounds::mir_borrowck_implied_outlives_bounds;
use crate::rustc_borrowck::path_utils::*;
use crate::rustc_borrowck::place_ext::PlaceExt;
use crate::rustc_borrowck::places_conflict::{PlaceConflictBias, places_conflict};
use crate::rustc_borrowck::polonius::PoloniusContext;
use crate::rustc_borrowck::polonius::legacy::{
PoloniusFacts, PoloniusFactsExt, PoloniusLocationTable, PoloniusOutput,
};
use crate::rustc_borrowck::prefixes::PrefixSet;
use crate::rustc_borrowck::region_infer::RegionInferenceContext;
use crate::rustc_borrowck::region_infer::opaque_types::DeferredOpaqueTypeError;
use crate::rustc_borrowck::renumber::RegionCtxt;
use crate::rustc_borrowck::session_diagnostics::VarNeedNotMut;
use crate::rustc_borrowck::type_check::free_region_relations::UniversalRegionRelations;
use crate::rustc_borrowck::type_check::{Locations, MirTypeckRegionConstraints, MirTypeckResults};
mod borrow_set;
mod borrowck_errors;
mod constraints;
mod dataflow;
mod def_use;
mod diagnostics;
mod handle_placeholders;
mod implied_bounds;
mod nll;
mod path_utils;
mod place_ext;
mod places_conflict;
mod polonius;
mod prefixes;
mod region_infer;
mod renumber;
mod root_cx;
mod session_diagnostics;
mod type_check;
mod universal_regions;
mod used_muts;
pub mod consumers;
struct TyCtxtConsts<'tcx>(PhantomData<&'tcx ()>);
impl<'tcx> TyCtxtConsts<'tcx> {
const DEREF_PROJECTION: &'tcx [PlaceElem<'tcx>; 1] = &[ProjectionElem::Deref];
}
pub fn provide(providers: &mut Providers) {
*providers = Providers { mir_borrowck, mir_borrowck_implied_outlives_bounds, ..*providers };
}
fn mir_borrowck(
tcx: TyCtxt<'_>,
def: LocalDefId,
) -> Result<&FxIndexMap<LocalDefId, ty::DefinitionSiteHiddenType<'_>>, ErrorGuaranteed> {
assert!(!tcx.is_typeck_child(def.to_def_id()));
if tcx.is_trivial_const(def) {
debug!("Skipping borrowck because of trivial const");
let opaque_types = Default::default();
return Ok(tcx.arena.alloc(opaque_types));
}
let (input_body, _) = tcx.mir_promoted(def);
debug!("run query mir_borrowck: {}", tcx.def_path_str(def));
tcx.ensure_result().check_coroutine_obligations(def)?;
let input_body: &Body<'_> = &input_body.borrow();
if let Some(guar) = input_body.tainted_by_errors {
debug!("Skipping borrowck because of tainted body");
Err(guar)
} else if input_body.should_skip() {
debug!("Skipping borrowck because of injected body");
let opaque_types = Default::default();
Ok(tcx.arena.alloc(opaque_types))
} else {
let tainted_by_errors = Default::default();
let mut root_cx = BorrowCheckRootCtxt::new(tcx, def, None, &tainted_by_errors);
root_cx.do_mir_borrowck();
root_cx.finalize()
}
}
#[derive(Debug)]
struct PropagatedBorrowCheckResults<'tcx> {
closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
used_mut_upvars: SmallVec<[FieldIdx; 8]>,
}
type DeferredClosureRequirements<'tcx> = Vec<(LocalDefId, ty::GenericArgsRef<'tcx>, Locations)>;
#[derive(Clone, Debug)]
pub struct ClosureRegionRequirements<'tcx> {
pub num_external_vids: usize,
pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
}
#[derive(Copy, Clone, Debug)]
pub struct ClosureOutlivesRequirement<'tcx> {
pub subject: ClosureOutlivesSubject<'tcx>,
pub outlived_free_region: ty::RegionVid,
pub blame_span: Span,
pub category: ConstraintCategory<'tcx>,
}
#[cfg(target_pointer_width = "64")]
crate::static_assert_size!(ConstraintCategory<'_>, 16);
#[derive(Copy, Clone, Debug)]
pub enum ClosureOutlivesSubject<'tcx> {
Ty(ClosureOutlivesSubjectTy<'tcx>),
Region(ty::RegionVid),
}
#[derive(Copy, Clone, Debug)]
pub struct ClosureOutlivesSubjectTy<'tcx> {
inner: Ty<'tcx>,
}
impl<'tcx> ClosureOutlivesSubjectTy<'tcx> {
pub fn bind(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Self {
let inner = fold_regions(tcx, ty, |r, depth| match r.kind() {
ty::ReVar(vid) => {
let br = ty::BoundRegion {
var: ty::BoundVar::from_usize(vid.index()),
kind: ty::BoundRegionKind::Anon,
};
ty::Region::new_bound(tcx, depth, br)
}
_ => bug!("unexpected region in ClosureOutlivesSubjectTy: {r:?}"),
});
Self { inner }
}
pub fn instantiate(
self,
tcx: TyCtxt<'tcx>,
mut map: impl FnMut(ty::RegionVid) -> ty::Region<'tcx>,
) -> Ty<'tcx> {
fold_regions(tcx, self.inner, |r, depth| match r.kind() {
ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn), br) => {
debug_assert_eq!(debruijn, depth);
map(ty::RegionVid::from_usize(br.var.index()))
}
_ => bug!("unexpected region {r:?}"),
})
}
}
struct CollectRegionConstraintsResult<'tcx> {
infcx: BorrowckInferCtxt<'tcx>,
body_owned: Body<'tcx>,
promoted: IndexVec<Promoted, Body<'tcx>>,
move_data: MoveData<'tcx>,
borrow_set: BorrowSet<'tcx>,
location_table: PoloniusLocationTable,
location_map: Rc<DenseLocationMap>,
universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
region_bound_pairs: Frozen<RegionBoundPairs<'tcx>>,
known_type_outlives_obligations: Frozen<Vec<ty::PolyTypeOutlivesClause<'tcx>>>,
constraints: MirTypeckRegionConstraints<'tcx>,
deferred_closure_requirements: DeferredClosureRequirements<'tcx>,
deferred_opaque_type_errors: Vec<DeferredOpaqueTypeError<'tcx>>,
polonius_facts: Option<AllFacts<RustcFacts>>,
polonius_context: Option<PoloniusContext>,
}
fn borrowck_collect_region_constraints<'tcx>(
root_cx: &mut BorrowCheckRootCtxt<'_, 'tcx>,
def: LocalDefId,
) -> CollectRegionConstraintsResult<'tcx> {
let tcx = root_cx.tcx;
let infcx = BorrowckInferCtxt::new(tcx, def, root_cx.root_def_id());
let (input_body, promoted) = tcx.mir_promoted(def);
let input_body: &Body<'_> = &input_body.borrow();
let input_promoted: &IndexSlice<_, _> = &promoted.borrow();
if let Some(e) = input_body.tainted_by_errors {
infcx.set_tainted_by_errors(e);
}
let mut body_owned = input_body.clone();
let mut promoted = input_promoted.to_owned();
let universal_regions = nll::replace_regions_in_mir(&infcx, &mut body_owned, &mut promoted);
let body = &body_owned;
let location_table = PoloniusLocationTable::new(body);
let move_data = MoveData::gather_moves(body, tcx, |_| true);
let locals_are_invalidated_at_exit = tcx.hir_body_owner_kind(def).is_fn_or_closure();
let borrow_set = BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &move_data);
let location_map = Rc::new(DenseLocationMap::new(body));
let polonius_input = root_cx.consumer.as_ref().map_or(false, |c| c.polonius_input())
|| infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled();
let mut polonius_facts =
(polonius_input || PoloniusFacts::enabled(infcx.tcx)).then_some(PoloniusFacts::default());
let MirTypeckResults {
constraints,
universal_region_relations,
region_bound_pairs,
known_type_outlives_obligations,
deferred_closure_requirements,
polonius_context,
} = type_check::type_check(
root_cx,
&infcx,
body,
&promoted,
universal_regions,
&location_table,
&borrow_set,
&mut polonius_facts,
&move_data,
Rc::clone(&location_map),
);
CollectRegionConstraintsResult {
infcx,
body_owned,
promoted,
move_data,
borrow_set,
location_table,
location_map,
universal_region_relations,
region_bound_pairs,
known_type_outlives_obligations,
constraints,
deferred_closure_requirements,
deferred_opaque_type_errors: Default::default(),
polonius_facts,
polonius_context,
}
}
fn borrowck_check_region_constraints<'diag, 'tcx>(
root_cx: &mut BorrowCheckRootCtxt<'diag, 'tcx>,
diags_buffer: &mut BorrowckDiagnosticsBuffer<'diag, 'tcx>,
CollectRegionConstraintsResult {
infcx,
body_owned,
promoted,
move_data,
borrow_set,
location_table,
location_map,
universal_region_relations,
region_bound_pairs: _,
known_type_outlives_obligations: _,
constraints,
deferred_closure_requirements,
deferred_opaque_type_errors,
polonius_facts,
polonius_context,
}: CollectRegionConstraintsResult<'tcx>,
) -> PropagatedBorrowCheckResults<'tcx> {
assert!(!infcx.has_opaque_types_in_storage());
assert!(deferred_closure_requirements.is_empty());
let tcx = root_cx.tcx;
let body = &body_owned;
let def = body.source.def_id().expect_local();
let nll::NllOutput {
regioncx,
polonius_input,
polonius_output,
opt_closure_req,
nll_errors,
polonius_context,
} = nll::compute_regions(
root_cx,
&infcx,
body,
&location_table,
&move_data,
&borrow_set,
location_map,
universal_region_relations,
constraints,
polonius_facts,
polonius_context,
);
nll::dump_nll_mir(&infcx, body, ®ioncx, &opt_closure_req, &borrow_set);
nll::dump_annotation(&infcx, body, ®ioncx, &opt_closure_req);
let movable_coroutine = body.coroutine.is_some()
&& tcx.coroutine_movability(def.to_def_id()) == hir::Movability::Movable;
for promoted_body in &promoted {
use crate::rustc_middle::mir::visit::Visitor;
let move_data = MoveData::gather_moves(promoted_body, tcx, |_| true);
let mut promoted_mbcx = MirBorrowckCtxt {
root_cx,
infcx: &infcx,
body: promoted_body,
move_data: &move_data,
location_table: &location_table,
movable_coroutine,
fn_self_span_reported: Default::default(),
access_place_error_reported: Default::default(),
reservation_error_reported: Default::default(),
uninitialized_error_reported: Default::default(),
regioncx: ®ioncx,
used_mut: Default::default(),
used_mut_upvars: SmallVec::new(),
borrow_set: &borrow_set,
upvars: &[],
local_names: OnceCell::from(IndexVec::from_elem(None, &promoted_body.local_decls)),
region_names: RefCell::default(),
next_region_name: RefCell::new(1),
polonius_output: None,
move_errors: Vec::new(),
diags_buffer,
polonius_context: polonius_context.as_ref(),
};
struct MoveVisitor<'a, 'b, 'diag, 'tcx> {
ctxt: &'a mut MirBorrowckCtxt<'b, 'diag, 'tcx>,
}
impl<'tcx> Visitor<'tcx> for MoveVisitor<'_, '_, '_, 'tcx> {
fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
if let Operand::Move(place) = operand {
self.ctxt.check_movable_place(location, *place);
}
}
}
MoveVisitor { ctxt: &mut promoted_mbcx }.visit_body(promoted_body);
promoted_mbcx.report_move_errors();
}
let mut mbcx = MirBorrowckCtxt {
root_cx,
infcx: &infcx,
body,
move_data: &move_data,
location_table: &location_table,
movable_coroutine,
fn_self_span_reported: Default::default(),
access_place_error_reported: Default::default(),
reservation_error_reported: Default::default(),
uninitialized_error_reported: Default::default(),
regioncx: ®ioncx,
used_mut: Default::default(),
used_mut_upvars: SmallVec::new(),
borrow_set: &borrow_set,
upvars: tcx.closure_captures(def),
local_names: OnceCell::new(),
region_names: RefCell::default(),
next_region_name: RefCell::new(1),
move_errors: Vec::new(),
diags_buffer,
polonius_output: polonius_output.as_deref(),
polonius_context: polonius_context.as_ref(),
};
if nll_errors.is_empty() {
mbcx.report_opaque_type_errors(deferred_opaque_type_errors);
} else {
mbcx.report_region_errors(nll_errors);
}
let flow_results = get_flow_results(tcx, body, &move_data, &borrow_set, ®ioncx);
visit_results(
body,
traversal::reverse_postorder(body).map(|(bb, _)| bb),
&flow_results,
&mut mbcx,
);
mbcx.report_move_errors();
let temporary_used_locals: FxIndexSet<Local> = mbcx
.used_mut
.iter()
.filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
.cloned()
.collect();
let unused_mut_locals =
mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
mbcx.lint_unused_mut();
let result = PropagatedBorrowCheckResults {
closure_requirements: opt_closure_req,
used_mut_upvars: mbcx.used_mut_upvars,
};
if let Some(guar) = infcx.tainted_by_errors() {
root_cx.set_tainted_by_errors(guar);
}
if let Some(consumer) = &mut root_cx.consumer {
consumer.insert_body(
def,
BodyWithBorrowckFacts {
body: body_owned,
promoted,
borrow_set,
region_inference_context: regioncx,
location_table: polonius_input.as_ref().map(|_| location_table),
input_facts: polonius_input,
output_facts: polonius_output,
},
);
}
debug!("do_mir_borrowck: result = {:#?}", result);
result
}
fn get_flow_results<'a, 'tcx>(
tcx: TyCtxt<'tcx>,
body: &'a Body<'tcx>,
move_data: &'a MoveData<'tcx>,
borrow_set: &'a BorrowSet<'tcx>,
regioncx: &RegionInferenceContext<'tcx>,
) -> Results<'tcx, Borrowck<'a, 'tcx>> {
let borrows = {
let _timer = tcx.prof.generic_activity("borrowck_dataflow_borrows");
Borrows::new(tcx, body, regioncx, borrow_set).iterate_to_fixpoint(
tcx,
body,
Some("borrowck"),
)
};
let uninits = {
let _timer = tcx.prof.generic_activity("borrowck_dataflow_maybe_uninits");
MaybeUninitializedPlaces::new(tcx, body, move_data).iterate_to_fixpoint(
tcx,
body,
Some("borrowck"),
)
};
let ever_inits = {
let _timer = tcx.prof.generic_activity("borrowck_dataflow_ever_inits");
EverInitializedPlaces::new(body, move_data).iterate_to_fixpoint(tcx, body, Some("borrowck"))
};
let analysis = Borrowck {
borrows: borrows.analysis,
uninits: uninits.analysis,
ever_inits: ever_inits.analysis,
};
assert_eq!(borrows.entry_states.len(), uninits.entry_states.len());
assert_eq!(borrows.entry_states.len(), ever_inits.entry_states.len());
let entry_states: EntryStates<_> =
itertools::izip!(borrows.entry_states, uninits.entry_states, ever_inits.entry_states)
.map(|(borrows, uninits, ever_inits)| BorrowckDomain { borrows, uninits, ever_inits })
.collect();
Results { analysis, entry_states }
}
pub(crate) struct BorrowckInferCtxt<'tcx> {
pub(crate) infcx: InferCtxt<'tcx>,
pub(crate) root_def_id: LocalDefId,
pub(crate) param_env: ParamEnv<'tcx>,
pub(crate) reg_var_to_origin: RefCell<FxIndexMap<ty::RegionVid, RegionCtxt>>,
}
impl<'tcx> BorrowckInferCtxt<'tcx> {
pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId, root_def_id: LocalDefId) -> Self {
let typing_mode = if tcx.use_typing_mode_post_typeck_until_borrowck() {
TypingMode::borrowck(tcx, def_id)
} else {
TypingMode::analysis_in_body(tcx, def_id)
};
let infcx = tcx.infer_ctxt().build(typing_mode);
let param_env = tcx.param_env(def_id);
BorrowckInferCtxt {
infcx,
root_def_id,
reg_var_to_origin: RefCell::new(Default::default()),
param_env,
}
}
pub(crate) fn next_region_var<F>(
&self,
origin: RegionVariableOrigin<'tcx>,
get_ctxt_fn: F,
) -> ty::Region<'tcx>
where
F: Fn() -> RegionCtxt,
{
let next_region = self.infcx.next_region_var(origin);
let vid = next_region.as_var();
if cfg!(debug_assertions) {
debug!("inserting vid {:?} with origin {:?} into var_to_origin", vid, origin);
let ctxt = get_ctxt_fn();
let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
assert_eq!(var_to_origin.insert(vid, ctxt), None);
}
next_region
}
#[instrument(skip(self, get_ctxt_fn), level = "debug")]
pub(crate) fn next_nll_region_var<F>(
&self,
origin: NllRegionVariableOrigin<'tcx>,
get_ctxt_fn: F,
) -> ty::Region<'tcx>
where
F: Fn() -> RegionCtxt,
{
let next_region = self.infcx.next_nll_region_var(origin);
let vid = next_region.as_var();
if cfg!(debug_assertions) {
debug!("inserting vid {:?} with origin {:?} into var_to_origin", vid, origin);
let ctxt = get_ctxt_fn();
let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
assert_eq!(var_to_origin.insert(vid, ctxt), None);
}
next_region
}
fn fully_perform<Q: QueryTypeOp<'tcx> + TypeVisitable<TyCtxt<'tcx>>>(
&self,
q: Q,
span: Span,
) -> Result<TypeOpOutput<'tcx, ty::ParamEnvAnd<'tcx, Q>>, ErrorGuaranteed> {
self.param_env.and(q).fully_perform(&self.infcx, self.root_def_id, span)
}
}
impl<'tcx> Deref for BorrowckInferCtxt<'tcx> {
type Target = InferCtxt<'tcx>;
fn deref(&self) -> &Self::Target {
&self.infcx
}
}
pub(crate) struct MirBorrowckCtxt<'a, 'diag, 'tcx> {
root_cx: &'a BorrowCheckRootCtxt<'diag, 'tcx>,
infcx: &'a BorrowckInferCtxt<'tcx>,
body: &'a Body<'tcx>,
move_data: &'a MoveData<'tcx>,
location_table: &'a PoloniusLocationTable,
movable_coroutine: bool,
access_place_error_reported: FxIndexSet<(Place<'tcx>, Span)>,
reservation_error_reported: FxIndexSet<Place<'tcx>>,
fn_self_span_reported: FxIndexSet<Span>,
uninitialized_error_reported: FxIndexSet<Local>,
used_mut: FxIndexSet<Local>,
used_mut_upvars: SmallVec<[FieldIdx; 8]>,
regioncx: &'a RegionInferenceContext<'tcx>,
borrow_set: &'a BorrowSet<'tcx>,
upvars: &'tcx [&'tcx ty::CapturedPlace<'tcx>],
local_names: OnceCell<IndexVec<Local, Option<Symbol>>>,
region_names: RefCell<FxIndexMap<RegionVid, RegionName>>,
next_region_name: RefCell<usize>,
diags_buffer: &'a mut BorrowckDiagnosticsBuffer<'diag, 'tcx>,
move_errors: Vec<MoveError<'tcx>>,
polonius_output: Option<&'a PoloniusOutput>,
polonius_context: Option<&'a PoloniusContext>,
}
impl<'a, 'tcx> ResultsVisitor<'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<'a, '_, 'tcx> {
fn visit_after_early_statement_effect(
&mut self,
state: &BorrowckDomain,
stmt: &Statement<'tcx>,
location: Location,
) {
debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, state);
let span = stmt.source_info.span;
self.check_activations(location, span, state);
match &stmt.kind {
StatementKind::Assign(assign) => {
let (lhs, rhs) = &**assign;
self.consume_rvalue(location, (rhs, span), state);
self.mutate_place(location, (*lhs, span), Shallow(None), state);
}
StatementKind::FakeRead(fake_read) => {
let (_, place) = &**fake_read;
self.check_if_path_or_subpath_is_moved(
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
state,
);
}
StatementKind::Intrinsic(kind) => match &**kind {
NonDivergingIntrinsic::Assume(op) => {
self.consume_operand(location, (op, span), state);
}
NonDivergingIntrinsic::CopyNonOverlapping(..) => span_bug!(
span,
"Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
),
},
StatementKind::AscribeUserType(..) => {}
StatementKind::PlaceMention(..) => {}
StatementKind::Coverage(..) => {}
StatementKind::ConstEvalCounter | StatementKind::StorageLive(..) => {}
StatementKind::BackwardIncompatibleDropHint {
place,
reason: BackwardIncompatibleDropReason::Edition2024,
} => {
self.check_backward_incompatible_drop(location, **place, state);
}
StatementKind::StorageDead(local) => {
self.access_place(
location,
(Place::from(*local), span),
(Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
LocalMutationIsAllowed::Yes,
state,
);
}
StatementKind::Nop | StatementKind::SetDiscriminant { .. } => {
bug!("Statement not allowed in this MIR phase")
}
}
}
fn visit_after_early_terminator_effect(
&mut self,
state: &BorrowckDomain,
term: &Terminator<'tcx>,
loc: Location,
) {
debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, state);
let span = term.source_info.span;
self.check_activations(loc, span, state);
match &term.kind {
TerminatorKind::SwitchInt { discr, targets: _ } => {
self.consume_operand(loc, (discr, span), state);
}
TerminatorKind::Drop { place, target: _, unwind: _, replace, drop: _ } => {
debug!(
"visit_terminator_drop \
loc: {:?} term: {:?} place: {:?} span: {:?}",
loc, term, place, span
);
let write_kind =
if *replace { WriteKind::Replace } else { WriteKind::StorageDeadOrDrop };
self.access_place(
loc,
(*place, span),
(AccessDepth::Drop, Write(write_kind)),
LocalMutationIsAllowed::Yes,
state,
);
}
TerminatorKind::Call {
func,
args,
destination,
target: _,
unwind: _,
call_source: _,
fn_span: _,
} => {
self.consume_operand(loc, (func, span), state);
for arg in args {
self.consume_operand(loc, (&arg.node, arg.span), state);
}
self.mutate_place(loc, (*destination, span), Deep, state);
}
TerminatorKind::TailCall { func, args, fn_span: _ } => {
self.consume_operand(loc, (func, span), state);
for arg in args {
self.consume_operand(loc, (&arg.node, arg.span), state);
}
}
TerminatorKind::Assert { cond, expected: _, msg, target: _, unwind: _ } => {
self.consume_operand(loc, (cond, span), state);
if let AssertKind::BoundsCheck { len, index } = &**msg {
self.consume_operand(loc, (len, span), state);
self.consume_operand(loc, (index, span), state);
}
}
TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
self.consume_operand(loc, (value, span), state);
self.mutate_place(loc, (*resume_arg, span), Deep, state);
}
TerminatorKind::InlineAsm {
asm_macro: _,
template: _,
operands,
options: _,
line_spans: _,
targets: _,
unwind: _,
} => {
for op in operands {
match op {
InlineAsmOperand::In { reg: _, value } => {
self.consume_operand(loc, (value, span), state);
}
InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
if let Some(place) = place {
self.mutate_place(loc, (*place, span), Shallow(None), state);
}
}
InlineAsmOperand::InOut { reg: _, late: _, in_value, out_place } => {
self.consume_operand(loc, (in_value, span), state);
if let &Some(out_place) = out_place {
self.mutate_place(loc, (out_place, span), Shallow(None), state);
}
}
InlineAsmOperand::Const { value: _ }
| InlineAsmOperand::SymFn { value: _ }
| InlineAsmOperand::SymStatic { def_id: _ }
| InlineAsmOperand::Label { target_index: _ } => {}
}
}
}
TerminatorKind::Goto { target: _ }
| TerminatorKind::UnwindTerminate(_)
| TerminatorKind::Unreachable
| TerminatorKind::UnwindResume
| TerminatorKind::Return
| TerminatorKind::CoroutineDrop
| TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
| TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
}
}
}
fn visit_after_primary_terminator_effect(
&mut self,
state: &BorrowckDomain,
term: &Terminator<'tcx>,
loc: Location,
) {
let span = term.source_info.span;
match term.kind {
TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
if self.movable_coroutine {
for i in state.borrows.iter() {
let borrow = &self.borrow_set[i];
self.check_for_local_borrow(borrow, span);
}
}
}
TerminatorKind::UnwindResume
| TerminatorKind::Return
| TerminatorKind::TailCall { .. }
| TerminatorKind::CoroutineDrop => {
match self.borrow_set.locals_state_at_exit() {
LocalsStateAtExit::AllAreInvalidated => {
for i in state.borrows.iter() {
let borrow = &self.borrow_set[i];
self.check_for_invalidation_at_exit(loc, borrow, span);
}
}
LocalsStateAtExit::SomeAreInvalidated { has_storage_dead_or_moved: _ } => {}
}
}
TerminatorKind::UnwindTerminate(_)
| TerminatorKind::Assert { .. }
| TerminatorKind::Call { .. }
| TerminatorKind::Drop { .. }
| TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
| TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
| TerminatorKind::Goto { .. }
| TerminatorKind::SwitchInt { .. }
| TerminatorKind::Unreachable
| TerminatorKind::InlineAsm { .. } => {}
}
}
}
use self::AccessDepth::{Deep, Shallow};
use self::ReadOrWrite::{Activation, Read, Reservation, Write};
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum ArtificialField {
ArrayLength,
FakeBorrow,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum AccessDepth {
Shallow(Option<ArtificialField>),
Deep,
Drop,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum ReadOrWrite {
Read(ReadKind),
Write(WriteKind),
Reservation(WriteKind),
Activation(WriteKind, BorrowIndex),
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum ReadKind {
Borrow(BorrowKind),
Copy,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum WriteKind {
StorageDeadOrDrop,
Replace,
MutableBorrow(BorrowKind),
Mutate,
Move,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum LocalMutationIsAllowed {
Yes,
ExceptUpvars,
No,
}
#[derive(Copy, Clone, Debug)]
enum InitializationRequiringAction {
Borrow,
MatchOn,
Use,
Assignment,
PartialAssignment,
}
#[derive(Debug)]
struct RootPlace<'tcx> {
place_local: Local,
place_projection: &'tcx [PlaceElem<'tcx>],
is_local_mutation_allowed: LocalMutationIsAllowed,
}
impl InitializationRequiringAction {
fn as_noun(self) -> &'static str {
match self {
InitializationRequiringAction::Borrow => "borrow",
InitializationRequiringAction::MatchOn => "use", InitializationRequiringAction::Use => "use",
InitializationRequiringAction::Assignment => "assign",
InitializationRequiringAction::PartialAssignment => "assign to part",
}
}
fn as_verb_in_past_tense(self) -> &'static str {
match self {
InitializationRequiringAction::Borrow => "borrowed",
InitializationRequiringAction::MatchOn => "matched on",
InitializationRequiringAction::Use => "used",
InitializationRequiringAction::Assignment => "assigned",
InitializationRequiringAction::PartialAssignment => "partially assigned",
}
}
fn as_general_verb_in_past_tense(self) -> &'static str {
match self {
InitializationRequiringAction::Borrow
| InitializationRequiringAction::MatchOn
| InitializationRequiringAction::Use => "used",
InitializationRequiringAction::Assignment => "assigned",
InitializationRequiringAction::PartialAssignment => "partially assigned",
}
}
}
impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
fn body(&self) -> &'a Body<'tcx> {
self.body
}
fn access_place(
&mut self,
location: Location,
place_span: (Place<'tcx>, Span),
kind: (AccessDepth, ReadOrWrite),
is_local_mutation_allowed: LocalMutationIsAllowed,
state: &BorrowckDomain,
) {
let (sd, rw) = kind;
if let Activation(_, borrow_index) = rw {
if self.reservation_error_reported.contains(&place_span.0) {
debug!(
"skipping access_place for activation of invalid reservation \
place: {:?} borrow_index: {:?}",
place_span.0, borrow_index
);
return;
}
}
if !self.access_place_error_reported.is_empty()
&& self.access_place_error_reported.contains(&(place_span.0, place_span.1))
{
debug!(
"access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
place_span, kind
);
if rw == ReadOrWrite::Write(WriteKind::Mutate)
&& let Ok(root_place) =
self.is_mutable(place_span.0.as_ref(), is_local_mutation_allowed)
{
self.add_used_mut(root_place, state);
}
return;
}
let mutability_error = self.check_access_permissions(
place_span,
rw,
is_local_mutation_allowed,
state,
location,
);
let conflict_error = self.check_access_for_conflict(location, place_span, sd, rw, state);
if conflict_error || mutability_error {
debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
self.access_place_error_reported.insert((place_span.0, place_span.1));
}
}
fn borrows_in_scope<'s>(
&self,
location: Location,
state: &'s BorrowckDomain,
) -> Cow<'s, MixedBitSet<BorrowIndex>> {
if let Some(polonius) = &self.polonius_output {
let location = self.location_table.start_index(location);
let mut polonius_output = MixedBitSet::new_empty(self.borrow_set.len());
for &idx in polonius.errors_at(location) {
polonius_output.insert(idx);
}
Cow::Owned(polonius_output)
} else {
Cow::Borrowed(&state.borrows)
}
}
#[instrument(level = "debug", skip(self, state))]
fn check_access_for_conflict(
&mut self,
location: Location,
place_span: (Place<'tcx>, Span),
sd: AccessDepth,
rw: ReadOrWrite,
state: &BorrowckDomain,
) -> bool {
let mut error_reported = false;
let borrows_in_scope = self.borrows_in_scope(location, state);
debug!(?borrows_in_scope, ?location);
each_borrow_involving_path(
self,
self.infcx.tcx,
self.body,
(sd, place_span.0),
self.borrow_set,
|borrow_index| borrows_in_scope.contains(borrow_index),
|this, borrow_index, borrow| match (rw, borrow.kind) {
(Activation(_, activating), _) if activating == borrow_index => {
debug!(
"check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
skipping {:?} b/c activation of same borrow_index",
place_span,
sd,
rw,
(borrow_index, borrow),
);
ControlFlow::Continue(())
}
(Read(_), BorrowKind::Shared | BorrowKind::Fake(_))
| (
Read(ReadKind::Borrow(BorrowKind::Fake(FakeBorrowKind::Shallow))),
BorrowKind::Mut { .. },
) => ControlFlow::Continue(()),
(Reservation(_), BorrowKind::Fake(_) | BorrowKind::Shared) => {
ControlFlow::Continue(())
}
(Write(WriteKind::Move), BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
ControlFlow::Continue(())
}
(Read(kind), BorrowKind::Mut { .. }) => {
if !is_active(this.dominators(), borrow, location) {
assert!(borrow.kind.is_two_phase_borrow());
return ControlFlow::Continue(());
}
error_reported = true;
match kind {
ReadKind::Copy => {
let err = this
.report_use_while_mutably_borrowed(location, place_span, borrow);
this.buffer_error(err);
}
ReadKind::Borrow(bk) => {
let err =
this.report_conflicting_borrow(location, place_span, bk, borrow);
this.buffer_error(err);
}
}
ControlFlow::Break(())
}
(Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
match rw {
Reservation(..) => {
debug!(
"recording invalid reservation of \
place: {:?}",
place_span.0
);
this.reservation_error_reported.insert(place_span.0);
}
Activation(_, activating) => {
debug!(
"observing check_place for activation of \
borrow_index: {:?}",
activating
);
}
Read(..) | Write(..) => {}
}
error_reported = true;
match kind {
WriteKind::MutableBorrow(bk) => {
let err =
this.report_conflicting_borrow(location, place_span, bk, borrow);
this.buffer_error(err);
}
WriteKind::StorageDeadOrDrop => this
.report_borrowed_value_does_not_live_long_enough(
location,
borrow,
place_span,
Some(WriteKind::StorageDeadOrDrop),
),
WriteKind::Mutate => {
this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
}
WriteKind::Move => {
this.report_move_out_while_borrowed(location, place_span, borrow)
}
WriteKind::Replace => {
this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
}
}
ControlFlow::Break(())
}
},
);
error_reported
}
#[instrument(level = "debug", skip(self, state))]
fn check_backward_incompatible_drop(
&mut self,
location: Location,
place: Place<'tcx>,
state: &BorrowckDomain,
) {
let tcx = self.infcx.tcx;
let sd = if place.ty(self.body, tcx).ty.needs_drop(tcx, self.body.typing_env(tcx)) {
AccessDepth::Drop
} else {
AccessDepth::Shallow(None)
};
let borrows_in_scope = self.borrows_in_scope(location, state);
each_borrow_involving_path(
self,
self.infcx.tcx,
self.body,
(sd, place),
self.borrow_set,
|borrow_index| borrows_in_scope.contains(borrow_index),
|this, _borrow_index, borrow| {
if matches!(borrow.kind, BorrowKind::Fake(_)) {
return ControlFlow::Continue(());
}
let borrowed = this.retrieve_borrow_spans(borrow).var_or_use_path_span();
let explain = this.explain_why_borrow_contains_point(
location,
borrow,
Some((WriteKind::StorageDeadOrDrop, place)),
);
this.infcx.tcx.emit_node_span_lint(
TAIL_EXPR_DROP_ORDER,
CRATE_HIR_ID,
borrowed,
session_diagnostics::TailExprDropOrder {
borrowed,
callback: |diag| {
explain.add_explanation_to_diagnostic(&this, diag, "", None, None);
},
},
);
ControlFlow::Break(())
},
);
}
fn mutate_place(
&mut self,
location: Location,
place_span: (Place<'tcx>, Span),
kind: AccessDepth,
state: &BorrowckDomain,
) {
self.check_if_assigned_path_is_moved(location, place_span, state);
self.access_place(
location,
place_span,
(kind, Write(WriteKind::Mutate)),
LocalMutationIsAllowed::No,
state,
);
}
fn consume_rvalue(
&mut self,
location: Location,
(rvalue, span): (&Rvalue<'tcx>, Span),
state: &BorrowckDomain,
) {
match rvalue {
&Rvalue::Ref(_ , bk, place) => {
let access_kind = match bk {
BorrowKind::Fake(FakeBorrowKind::Shallow) => {
(Shallow(Some(ArtificialField::FakeBorrow)), Read(ReadKind::Borrow(bk)))
}
BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep) => {
(Deep, Read(ReadKind::Borrow(bk)))
}
BorrowKind::Mut { .. } => {
let wk = WriteKind::MutableBorrow(bk);
if bk.is_two_phase_borrow() {
(Deep, Reservation(wk))
} else {
(Deep, Write(wk))
}
}
};
self.access_place(
location,
(place, span),
access_kind,
LocalMutationIsAllowed::No,
state,
);
let action = if bk == BorrowKind::Fake(FakeBorrowKind::Shallow) {
InitializationRequiringAction::MatchOn
} else {
InitializationRequiringAction::Borrow
};
self.check_if_path_or_subpath_is_moved(
location,
action,
(place.as_ref(), span),
state,
);
}
&Rvalue::Reborrow(_target, mutability, place) => {
let access_kind = (
Deep,
if mutability == Mutability::Mut {
Write(WriteKind::MutableBorrow(BorrowKind::Mut {
kind: MutBorrowKind::Default,
}))
} else {
Read(ReadKind::Borrow(BorrowKind::Shared))
},
);
self.access_place(
location,
(place, span),
access_kind,
LocalMutationIsAllowed::Yes,
state,
);
let action = InitializationRequiringAction::Borrow;
self.check_if_path_or_subpath_is_moved(
location,
action,
(place.as_ref(), span),
state,
);
}
&Rvalue::RawPtr(kind, place) => {
let access_kind = match kind {
RawPtrKind::Mut => (
Deep,
Write(WriteKind::MutableBorrow(BorrowKind::Mut {
kind: MutBorrowKind::Default,
})),
),
RawPtrKind::Const => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
RawPtrKind::FakeForPtrMetadata => {
(Shallow(Some(ArtificialField::ArrayLength)), Read(ReadKind::Copy))
}
};
self.access_place(
location,
(place, span),
access_kind,
LocalMutationIsAllowed::No,
state,
);
self.check_if_path_or_subpath_is_moved(
location,
InitializationRequiringAction::Borrow,
(place.as_ref(), span),
state,
);
}
Rvalue::ThreadLocalRef(_) => {}
Rvalue::Use(operand, _)
| Rvalue::Repeat(operand, _)
| Rvalue::UnaryOp(_ , operand)
| Rvalue::Cast(_ , operand, _ ) => {
self.consume_operand(location, (operand, span), state)
}
&Rvalue::Discriminant(place) => {
let af = match *rvalue {
Rvalue::Discriminant(..) => None,
_ => unreachable!(),
};
self.access_place(
location,
(place, span),
(Shallow(af), Read(ReadKind::Copy)),
LocalMutationIsAllowed::No,
state,
);
self.check_if_path_or_subpath_is_moved(
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
state,
);
}
Rvalue::BinaryOp(_bin_op, operands) => {
let (operand1, operand2) = &**operands;
self.consume_operand(location, (operand1, span), state);
self.consume_operand(location, (operand2, span), state);
}
Rvalue::Aggregate(aggregate_kind, operands) => {
match **aggregate_kind {
AggregateKind::Closure(def_id, _)
| AggregateKind::CoroutineClosure(def_id, _)
| AggregateKind::Coroutine(def_id, _) => {
let def_id = def_id.expect_local();
let used_mut_upvars = self.root_cx.used_mut_upvars(def_id);
debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
for field in used_mut_upvars.clone() {
self.propagate_closure_used_mut_upvar(&operands[field]);
}
}
AggregateKind::Adt(..)
| AggregateKind::Array(..)
| AggregateKind::Tuple { .. }
| AggregateKind::RawPtr(..) => (),
}
for operand in operands {
self.consume_operand(location, (operand, span), state);
}
}
Rvalue::WrapUnsafeBinder(op, _) => {
self.consume_operand(location, (op, span), state);
}
Rvalue::CopyForDeref(_) => bug!("`CopyForDeref` in borrowck"),
}
}
fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
this.used_mut_upvars.push(field);
return;
}
for (place_ref, proj) in place.iter_projections().rev() {
if proj == ProjectionElem::Deref {
match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
ty::Ref(_, _, hir::Mutability::Mut) => return,
_ => {}
}
}
if let Some(field) = this.is_upvar_field_projection(place_ref) {
this.used_mut_upvars.push(field);
return;
}
}
this.used_mut.insert(place.local);
};
match *operand {
Operand::Move(place) | Operand::Copy(place) => {
match place.as_local() {
Some(local) if !self.body.local_decls[local].is_user_variable() => {
if self.body.local_decls[local].ty.is_mutable_ptr() {
return;
}
let Some(temp_mpi) = self.move_data.rev_lookup.find_local(local) else {
bug!("temporary should be tracked");
};
let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
&self.move_data.inits[init_index]
} else {
bug!("temporary should be initialized exactly once")
};
let InitLocation::Statement(loc) = init.location else {
bug!("temporary initialized in arguments")
};
let body = self.body;
let bbd = &body[loc.block];
let stmt = &bbd.statements[loc.statement_index];
debug!("temporary assigned in: stmt={:?}", stmt);
let source = match &stmt.kind {
StatementKind::Assign(assign) => match assign.1 {
Rvalue::Ref(_, _, source)
| Rvalue::Use(Operand::Copy(source) | Operand::Move(source), _) => {
Some(source)
}
_ => None,
},
_ => None,
};
match source {
Some(source) => {
propagate_closure_used_mut_place(self, source);
}
None => {
bug!(
"closures should only capture user variables \
or references to user variables"
);
}
}
}
_ => propagate_closure_used_mut_place(self, place),
}
}
Operand::Constant(..) | Operand::RuntimeChecks(_) => {}
}
}
fn consume_operand(
&mut self,
location: Location,
(operand, span): (&Operand<'tcx>, Span),
state: &BorrowckDomain,
) {
match *operand {
Operand::Copy(place) => {
self.access_place(
location,
(place, span),
(Deep, Read(ReadKind::Copy)),
LocalMutationIsAllowed::No,
state,
);
self.check_if_path_or_subpath_is_moved(
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
state,
);
}
Operand::Move(place) => {
self.check_movable_place(location, place);
self.access_place(
location,
(place, span),
(Deep, Write(WriteKind::Move)),
LocalMutationIsAllowed::Yes,
state,
);
self.check_if_path_or_subpath_is_moved(
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
state,
);
}
Operand::Constant(_) | Operand::RuntimeChecks(_) => {}
}
}
#[instrument(level = "debug", skip(self))]
fn check_for_invalidation_at_exit(
&mut self,
location: Location,
borrow: &BorrowData<'tcx>,
span: Span,
) {
let place = borrow.borrowed_place;
let mut root_place = PlaceRef { local: place.local, projection: &[] };
let might_be_alive = if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
root_place.projection = TyCtxtConsts::DEREF_PROJECTION;
true
} else {
false
};
let sd = if might_be_alive { Deep } else { Shallow(None) };
if places_conflict::borrow_conflicts_with_place(
self.infcx.tcx,
self.body,
place,
borrow.kind,
root_place,
sd,
places_conflict::PlaceConflictBias::Overlap,
) {
debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
let span = self.infcx.tcx.sess.source_map().end_point(span);
self.report_borrowed_value_does_not_live_long_enough(
location,
borrow,
(place, span),
None,
)
}
}
fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
debug!("check_for_local_borrow({:?})", borrow);
if borrow_of_local_data(borrow.borrowed_place) {
let err = self.cannot_borrow_across_coroutine_yield(
self.retrieve_borrow_spans(borrow).var_or_use(),
yield_span,
);
self.buffer_error(err);
}
}
fn check_activations(&mut self, location: Location, span: Span, state: &BorrowckDomain) {
for &borrow_index in self.borrow_set.activations_at_location(&location) {
let borrow = &self.borrow_set[borrow_index];
assert!(match borrow.kind {
BorrowKind::Shared | BorrowKind::Fake(_) => false,
BorrowKind::Mut { .. } => true,
});
self.access_place(
location,
(borrow.borrowed_place, span),
(Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
LocalMutationIsAllowed::No,
state,
);
}
}
fn check_movable_place(&mut self, location: Location, place: Place<'tcx>) {
use IllegalMoveOriginKind::*;
let body = self.body;
let tcx = self.infcx.tcx;
let mut place_ty = PlaceTy::from_ty(body.local_decls[place.local].ty);
for (place_ref, elem) in place.iter_projections() {
match elem {
ProjectionElem::Deref => match place_ty.ty.kind() {
ty::Ref(..) | ty::RawPtr(..) => {
self.move_errors.push(MoveError::new(
place,
location,
BorrowedContent {
target_place: place_ref.project_deeper(&[elem], tcx),
},
));
return;
}
ty::Adt(adt, _) => {
if !adt.is_box() {
bug!("Adt should be a box type when Place is deref");
}
}
ty::Bool
| ty::Char
| ty::Int(_)
| ty::Uint(_)
| ty::Float(_)
| ty::Foreign(_)
| ty::Str
| ty::Array(_, _)
| ty::Pat(_, _)
| ty::Slice(_)
| ty::FnDef(_, _)
| ty::FnPtr(..)
| ty::Dynamic(_, _)
| ty::Closure(_, _)
| ty::CoroutineClosure(_, _)
| ty::Coroutine(_, _)
| ty::CoroutineWitness(..)
| ty::Never
| ty::Tuple(_)
| ty::UnsafeBinder(_)
| ty::Alias(_, _)
| ty::Param(_)
| ty::Bound(_, _)
| ty::Infer(_)
| ty::Error(_)
| ty::Placeholder(_) => {
bug!("When Place is Deref it's type shouldn't be {place_ty:#?}")
}
},
ProjectionElem::Field(_, _) => match place_ty.ty.kind() {
ty::Adt(adt, _) => {
if adt.has_dtor(tcx) {
self.move_errors.push(MoveError::new(
place,
location,
InteriorOfTypeWithDestructor { container_ty: place_ty.ty },
));
return;
}
}
ty::Closure(..)
| ty::CoroutineClosure(..)
| ty::Coroutine(_, _)
| ty::Tuple(_) => (),
ty::Bool
| ty::Char
| ty::Int(_)
| ty::Uint(_)
| ty::Float(_)
| ty::Foreign(_)
| ty::Str
| ty::Array(_, _)
| ty::Pat(_, _)
| ty::Slice(_)
| ty::RawPtr(_, _)
| ty::Ref(_, _, _)
| ty::FnDef(_, _)
| ty::FnPtr(..)
| ty::Dynamic(_, _)
| ty::CoroutineWitness(..)
| ty::Never
| ty::UnsafeBinder(_)
| ty::Alias(_, _)
| ty::Param(_)
| ty::Bound(_, _)
| ty::Infer(_)
| ty::Error(_)
| ty::Placeholder(_) => bug!(
"When Place contains ProjectionElem::Field it's type shouldn't be {place_ty:#?}"
),
},
ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
match place_ty.ty.kind() {
ty::Slice(_) => {
self.move_errors.push(MoveError::new(
place,
location,
InteriorOfSliceOrArray { ty: place_ty.ty, is_index: false },
));
return;
}
ty::Array(_, _) => (),
_ => bug!("Unexpected type {:#?}", place_ty.ty),
}
}
ProjectionElem::Index(_) => match place_ty.ty.kind() {
ty::Array(..) | ty::Slice(..) => {
self.move_errors.push(MoveError::new(
place,
location,
InteriorOfSliceOrArray { ty: place_ty.ty, is_index: true },
));
return;
}
_ => bug!("Unexpected type {place_ty:#?}"),
},
ProjectionElem::OpaqueCast(_)
| ProjectionElem::Downcast(_, _)
| ProjectionElem::UnwrapUnsafeBinder(_)
| ProjectionElem::PhantomDeref => (),
}
place_ty = place_ty.projection_ty(tcx, elem);
}
}
fn check_if_full_path_is_moved(
&mut self,
location: Location,
desired_action: InitializationRequiringAction,
place_span: (PlaceRef<'tcx>, Span),
state: &BorrowckDomain,
) {
let maybe_uninits = &state.uninits;
debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
let (prefix, mpi) = self.move_path_closest_to(place_span.0);
if maybe_uninits.contains(mpi) {
self.report_use_of_moved_or_uninitialized(
location,
desired_action,
(prefix, place_span.0, place_span.1),
mpi,
);
} }
fn check_if_subslice_element_is_moved(
&mut self,
location: Location,
desired_action: InitializationRequiringAction,
place_span: (PlaceRef<'tcx>, Span),
maybe_uninits: &MixedBitSet<MovePathIndex>,
from: u64,
to: u64,
) {
if let Some(mpi) = self.move_path_for_place(place_span.0) {
let move_paths = &self.move_data.move_paths;
let root_path = &move_paths[mpi];
for (child_mpi, child_move_path) in root_path.children(move_paths) {
let last_proj = child_move_path.place.projection.last().unwrap();
if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
if (from..to).contains(offset) {
let uninit_child =
self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
maybe_uninits.contains(mpi)
});
if let Some(uninit_child) = uninit_child {
self.report_use_of_moved_or_uninitialized(
location,
desired_action,
(place_span.0, place_span.0, place_span.1),
uninit_child,
);
return; }
}
}
}
}
}
fn check_if_path_or_subpath_is_moved(
&mut self,
location: Location,
desired_action: InitializationRequiringAction,
place_span: (PlaceRef<'tcx>, Span),
state: &BorrowckDomain,
) {
let maybe_uninits = &state.uninits;
self.check_if_full_path_is_moved(location, desired_action, place_span, state);
if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
place_span.0.last_projection()
{
let place_ty = place_base.ty(self.body(), self.infcx.tcx);
if let ty::Array(..) = place_ty.ty.kind() {
self.check_if_subslice_element_is_moved(
location,
desired_action,
(place_base, place_span.1),
maybe_uninits,
from,
to,
);
return;
}
}
debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
if let Some(mpi) = self.move_path_for_place(place_span.0) {
let uninit_mpi = self
.move_data
.find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
if let Some(uninit_mpi) = uninit_mpi {
self.report_use_of_moved_or_uninitialized(
location,
desired_action,
(place_span.0, place_span.0, place_span.1),
uninit_mpi,
);
return; }
}
}
fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
match self.move_data.rev_lookup.find(place) {
LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
(self.move_data.move_paths[mpi].place.as_ref(), mpi)
}
LookupResult::Parent(None) => panic!("should have move path for every Local"),
}
}
fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
match self.move_data.rev_lookup.find(place) {
LookupResult::Parent(_) => None,
LookupResult::Exact(mpi) => Some(mpi),
}
}
fn check_if_assigned_path_is_moved(
&mut self,
location: Location,
(place, span): (Place<'tcx>, Span),
state: &BorrowckDomain,
) {
debug!("check_if_assigned_path_is_moved place: {:?}", place);
for (place_base, elem) in place.iter_projections().rev() {
match elem {
ProjectionElem::Index(_)
| ProjectionElem::OpaqueCast(_)
| ProjectionElem::ConstantIndex { .. }
| ProjectionElem::Downcast(_, _) =>
{}
ProjectionElem::UnwrapUnsafeBinder(_) => {
check_parent_of_field(self, location, place_base, span, state);
}
ProjectionElem::Deref => {
self.check_if_full_path_is_moved(
location,
InitializationRequiringAction::Use,
(place_base, span),
state,
);
break;
}
ProjectionElem::PhantomDeref => {
panic!("we don't allow assignments to PhantomDeref, location {location:?}");
}
ProjectionElem::Subslice { .. } => {
panic!("we don't allow assignments to subslices, location: {location:?}");
}
ProjectionElem::Field(..) => {
let tcx = self.infcx.tcx;
let base_ty = place_base.ty(self.body(), tcx).ty;
match base_ty.kind() {
ty::Adt(def, _) if def.has_dtor(tcx) => {
self.check_if_path_or_subpath_is_moved(
location,
InitializationRequiringAction::Assignment,
(place_base, span),
state,
);
break;
}
ty::Adt(..) | ty::Tuple(..) => {
check_parent_of_field(self, location, place_base, span, state);
}
_ => {}
}
}
}
}
fn check_parent_of_field<'a, 'tcx>(
this: &mut MirBorrowckCtxt<'a, '_, 'tcx>,
location: Location,
base: PlaceRef<'tcx>,
span: Span,
state: &BorrowckDomain,
) {
let maybe_uninits = &state.uninits;
let mut shortest_uninit_seen = None;
for prefix in this.prefixes(base, PrefixSet::Shallow) {
let Some(mpi) = this.move_path_for_place(prefix) else { continue };
if maybe_uninits.contains(mpi) {
debug!(
"check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
shortest_uninit_seen,
Some((prefix, mpi))
);
shortest_uninit_seen = Some((prefix, mpi));
} else {
debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
}
}
if let Some((prefix, mpi)) = shortest_uninit_seen {
let tcx = this.infcx.tcx;
if base.ty(this.body(), tcx).ty.is_union()
&& this.move_data.move_out_path_map[mpi].iter().any(|moi| {
this.move_data.move_outs[*moi].source.is_predecessor_of(location, this.body)
})
{
return;
}
this.report_use_of_moved_or_uninitialized(
location,
InitializationRequiringAction::PartialAssignment,
(prefix, base, span),
mpi,
);
this.used_mut.insert(base.local);
}
}
}
fn check_access_permissions(
&mut self,
(place, span): (Place<'tcx>, Span),
kind: ReadOrWrite,
is_local_mutation_allowed: LocalMutationIsAllowed,
state: &BorrowckDomain,
location: Location,
) -> bool {
debug!(
"check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
place, kind, is_local_mutation_allowed
);
let error_access;
let the_place_err;
match kind {
Reservation(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind }))
| Write(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind })) => {
let is_local_mutation_allowed = match mut_borrow_kind {
MutBorrowKind::ClosureCapture => LocalMutationIsAllowed::Yes,
MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow => {
is_local_mutation_allowed
}
};
match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
Ok(root_place) => {
self.add_used_mut(root_place, state);
return false;
}
Err(place_err) => {
error_access = AccessKind::MutableBorrow;
the_place_err = place_err;
}
}
}
Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
Ok(root_place) => {
self.add_used_mut(root_place, state);
return false;
}
Err(place_err) => {
error_access = AccessKind::Mutate;
the_place_err = place_err;
}
}
}
Reservation(
WriteKind::Move
| WriteKind::Replace
| WriteKind::StorageDeadOrDrop
| WriteKind::MutableBorrow(BorrowKind::Shared)
| WriteKind::MutableBorrow(BorrowKind::Fake(_)),
)
| Write(
WriteKind::Move
| WriteKind::Replace
| WriteKind::StorageDeadOrDrop
| WriteKind::MutableBorrow(BorrowKind::Shared)
| WriteKind::MutableBorrow(BorrowKind::Fake(_)),
) => {
if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err()
&& !self.has_buffered_diags()
{
self.dcx().span_delayed_bug(
span,
format!(
"Accessing `{place:?}` with the kind `{kind:?}` shouldn't be possible",
),
);
}
return false;
}
Activation(..) => {
return false;
}
Read(
ReadKind::Borrow(BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_))
| ReadKind::Copy,
) => {
return false;
}
}
let previously_initialized = state.ever_inits.contains(place.local);
if previously_initialized {
if let (AccessKind::Mutate, Some(_)) = (error_access, place.as_local()) {
let init_index = self.first_reaching_init(place.local, location).unwrap();
let init = &self.move_data.inits[init_index];
let assigned_span = init.span(self.body);
self.report_illegal_reassignment((place, span), assigned_span, place);
} else {
self.report_mutability_error(place, span, the_place_err, error_access, location)
}
true
} else {
false
}
}
fn first_reaching_init(&self, local: Local, location: Location) -> Option<InitIndex> {
let mpi = self.move_data.rev_lookup.find_local(local)?;
self.move_data.init_path_map[mpi].iter().copied().find(|&ii| {
let init = self.move_data.inits[ii];
EverInitializedPlaces::init_reaches_location(self.body, local, init, location)
})
}
fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, state: &BorrowckDomain) {
match root_place {
RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
&& state.ever_inits.contains(local)
{
self.used_mut.insert(local);
}
}
RootPlace {
place_local: _,
place_projection: _,
is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
} => {}
RootPlace {
place_local,
place_projection: place_projection @ [.., _],
is_local_mutation_allowed: _,
} => {
if let Some(field) = self.is_upvar_field_projection(PlaceRef {
local: place_local,
projection: place_projection,
}) {
self.used_mut_upvars.push(field);
}
}
}
}
fn is_mutable(
&self,
place: PlaceRef<'tcx>,
is_local_mutation_allowed: LocalMutationIsAllowed,
) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
match place.last_projection() {
None => {
let local = &self.body.local_decls[place.local];
match local.mutability {
Mutability::Not => match is_local_mutation_allowed {
LocalMutationIsAllowed::Yes => Ok(RootPlace {
place_local: place.local,
place_projection: place.projection,
is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
}),
LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
place_local: place.local,
place_projection: place.projection,
is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
}),
LocalMutationIsAllowed::No => Err(place),
},
Mutability::Mut => Ok(RootPlace {
place_local: place.local,
place_projection: place.projection,
is_local_mutation_allowed,
}),
}
}
Some((place_base, elem)) => {
match elem {
ProjectionElem::Deref => {
let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
match base_ty.kind() {
ty::Ref(_, _, mutbl) => {
match mutbl {
hir::Mutability::Not => Err(place),
hir::Mutability::Mut => {
let mode = match self.is_upvar_field_projection(place) {
Some(field)
if self.upvars[field.index()].is_by_ref() =>
{
is_local_mutation_allowed
}
_ => LocalMutationIsAllowed::Yes,
};
self.is_mutable(place_base, mode)
}
}
}
ty::RawPtr(_, mutbl) => {
match mutbl {
hir::Mutability::Not => Err(place),
hir::Mutability::Mut => Ok(RootPlace {
place_local: place.local,
place_projection: place.projection,
is_local_mutation_allowed,
}),
}
}
_ if base_ty.is_box() => {
self.is_mutable(place_base, is_local_mutation_allowed)
}
_ => bug!("Deref of unexpected type: {:?}", base_ty),
}
}
ProjectionElem::PhantomDeref => {
bug!("encountered PhantomDeref in is_mutable")
}
ProjectionElem::Field(FieldIdx::ZERO, _)
if let Some(adt) =
place_base.ty(self.body(), self.infcx.tcx).ty.ty_adt_def()
&& adt.is_pin()
&& self.infcx.tcx.features().pin_ergonomics() =>
{
self.is_mutable(place_base, is_local_mutation_allowed)
}
ProjectionElem::Field(..)
| ProjectionElem::Index(..)
| ProjectionElem::ConstantIndex { .. }
| ProjectionElem::Subslice { .. }
| ProjectionElem::OpaqueCast { .. }
| ProjectionElem::Downcast(..)
| ProjectionElem::UnwrapUnsafeBinder(_) => {
let upvar_field_projection = self.is_upvar_field_projection(place);
if let Some(field) = upvar_field_projection {
let upvar = &self.upvars[field.index()];
debug!(
"is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
place={:?}, place_base={:?}",
upvar, is_local_mutation_allowed, place, place_base
);
match (upvar.mutability, is_local_mutation_allowed) {
(
Mutability::Not,
LocalMutationIsAllowed::No
| LocalMutationIsAllowed::ExceptUpvars,
) => Err(place),
(Mutability::Not, LocalMutationIsAllowed::Yes)
| (Mutability::Mut, _) => {
let _ =
self.is_mutable(place_base, is_local_mutation_allowed)?;
Ok(RootPlace {
place_local: place.local,
place_projection: place.projection,
is_local_mutation_allowed,
})
}
}
} else {
self.is_mutable(place_base, is_local_mutation_allowed)
}
}
}
}
}
}
fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<FieldIdx> {
path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
}
fn dominators(&self) -> &Dominators<BasicBlock> {
self.body.basic_blocks.dominators()
}
fn lint_unused_mut(&self) {
let tcx = self.infcx.tcx;
let body = self.body;
for local in body.mut_vars_and_args_iter().filter(|local| !self.used_mut.contains(local)) {
let local_decl = &body.local_decls[local];
let ClearCrossCrate::Set(SourceScopeLocalData { lint_root, .. }) =
body.source_scopes[local_decl.source_info.scope].local_data
else {
continue;
};
if self.local_excluded_from_unused_mut_lint(local) {
continue;
}
let span = local_decl.source_info.span;
if span.desugaring_kind().is_some() {
continue;
}
let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
tcx.emit_node_span_lint(UNUSED_MUT, lint_root, span, VarNeedNotMut { span: mut_span })
}
}
}
enum Overlap {
Arbitrary,
EqualOrDisjoint,
Disjoint,
}