1#![allow(internal_features)]
5#![cfg_attr(bootstrap, feature(assert_matches))]
6#![feature(box_patterns)]
7#![feature(default_field_values)]
8#![feature(file_buffered)]
9#![feature(if_let_guard)]
10#![feature(negative_impls)]
11#![feature(never_type)]
12#![feature(rustc_attrs)]
13#![feature(stmt_expr_attributes)]
14#![feature(try_blocks)]
15use std::borrow::Cow;
18use std::cell::{OnceCell, RefCell};
19use std::marker::PhantomData;
20use std::ops::{ControlFlow, Deref};
21use std::rc::Rc;
22
23use borrow_set::LocalsStateAtExit;
24use polonius_engine::AllFacts;
25use root_cx::BorrowCheckRootCtxt;
26use rustc_abi::FieldIdx;
27use rustc_data_structures::frozen::Frozen;
28use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
29use rustc_data_structures::graph::dominators::Dominators;
30use rustc_errors::LintDiagnostic;
31use rustc_hir as hir;
32use rustc_hir::CRATE_HIR_ID;
33use rustc_hir::def_id::LocalDefId;
34use rustc_index::bit_set::MixedBitSet;
35use rustc_index::{IndexSlice, IndexVec};
36use rustc_infer::infer::outlives::env::RegionBoundPairs;
37use rustc_infer::infer::{
38 InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin, TyCtxtInferExt,
39};
40use rustc_middle::mir::*;
41use rustc_middle::query::Providers;
42use rustc_middle::ty::{
43 self, ParamEnv, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitable, TypingMode, fold_regions,
44};
45use rustc_middle::{bug, span_bug};
46use rustc_mir_dataflow::impls::{EverInitializedPlaces, MaybeUninitializedPlaces};
47use rustc_mir_dataflow::move_paths::{
48 InitIndex, InitLocation, LookupResult, MoveData, MovePathIndex,
49};
50use rustc_mir_dataflow::points::DenseLocationMap;
51use rustc_mir_dataflow::{Analysis, EntryStates, Results, ResultsVisitor, visit_results};
52use rustc_session::lint::builtin::{TAIL_EXPR_DROP_ORDER, UNUSED_MUT};
53use rustc_span::{ErrorGuaranteed, Span, Symbol};
54use smallvec::SmallVec;
55use tracing::{debug, instrument};
56
57use crate::borrow_set::{BorrowData, BorrowSet};
58use crate::consumers::{BodyWithBorrowckFacts, RustcFacts};
59use crate::dataflow::{BorrowIndex, Borrowck, BorrowckDomain, Borrows};
60use crate::diagnostics::{
61 AccessKind, BorrowckDiagnosticsBuffer, IllegalMoveOriginKind, MoveError, RegionName,
62};
63use crate::path_utils::*;
64use crate::place_ext::PlaceExt;
65use crate::places_conflict::{PlaceConflictBias, places_conflict};
66use crate::polonius::PoloniusContext;
67use crate::polonius::legacy::{
68 PoloniusFacts, PoloniusFactsExt, PoloniusLocationTable, PoloniusOutput,
69};
70use crate::prefixes::PrefixSet;
71use crate::region_infer::RegionInferenceContext;
72use crate::region_infer::opaque_types::DeferredOpaqueTypeError;
73use crate::renumber::RegionCtxt;
74use crate::session_diagnostics::VarNeedNotMut;
75use crate::type_check::free_region_relations::UniversalRegionRelations;
76use crate::type_check::{Locations, MirTypeckRegionConstraints, MirTypeckResults};
77
78mod borrow_set;
79mod borrowck_errors;
80mod constraints;
81mod dataflow;
82mod def_use;
83mod diagnostics;
84mod handle_placeholders;
85mod nll;
86mod path_utils;
87mod place_ext;
88mod places_conflict;
89mod polonius;
90mod prefixes;
91mod region_infer;
92mod renumber;
93mod root_cx;
94mod session_diagnostics;
95mod type_check;
96mod universal_regions;
97mod used_muts;
98
99pub mod consumers;
101
102struct TyCtxtConsts<'tcx>(PhantomData<&'tcx ()>);
104
105impl<'tcx> TyCtxtConsts<'tcx> {
106 const DEREF_PROJECTION: &'tcx [PlaceElem<'tcx>; 1] = &[ProjectionElem::Deref];
107}
108
109pub fn provide(providers: &mut Providers) {
110 *providers = Providers { mir_borrowck, ..*providers };
111}
112
113fn mir_borrowck(
117 tcx: TyCtxt<'_>,
118 def: LocalDefId,
119) -> Result<&FxIndexMap<LocalDefId, ty::DefinitionSiteHiddenType<'_>>, ErrorGuaranteed> {
120 if !!tcx.is_typeck_child(def.to_def_id()) {
::core::panicking::panic("assertion failed: !tcx.is_typeck_child(def.to_def_id())")
};assert!(!tcx.is_typeck_child(def.to_def_id()));
121 let (input_body, _) = tcx.mir_promoted(def);
122 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:122",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(122u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("run query mir_borrowck: {0}",
tcx.def_path_str(def)) as &dyn Value))])
});
} else { ; }
};debug!("run query mir_borrowck: {}", tcx.def_path_str(def));
123
124 tcx.check_coroutine_obligations(def)?;
128
129 let input_body: &Body<'_> = &input_body.borrow();
130 if let Some(guar) = input_body.tainted_by_errors {
131 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:131",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(131u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Skipping borrowck because of tainted body")
as &dyn Value))])
});
} else { ; }
};debug!("Skipping borrowck because of tainted body");
132 Err(guar)
133 } else if input_body.should_skip() {
134 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:134",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(134u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Skipping borrowck because of injected body")
as &dyn Value))])
});
} else { ; }
};debug!("Skipping borrowck because of injected body");
135 let opaque_types = Default::default();
136 Ok(tcx.arena.alloc(opaque_types))
137 } else {
138 let mut root_cx = BorrowCheckRootCtxt::new(tcx, def, None);
139 root_cx.do_mir_borrowck();
140 root_cx.finalize()
141 }
142}
143
144#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for PropagatedBorrowCheckResults<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"PropagatedBorrowCheckResults", "closure_requirements",
&self.closure_requirements, "used_mut_upvars",
&&self.used_mut_upvars)
}
}Debug)]
147struct PropagatedBorrowCheckResults<'tcx> {
148 closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
149 used_mut_upvars: SmallVec<[FieldIdx; 8]>,
150}
151
152type DeferredClosureRequirements<'tcx> = Vec<(LocalDefId, ty::GenericArgsRef<'tcx>, Locations)>;
153
154#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ClosureRegionRequirements<'tcx> {
#[inline]
fn clone(&self) -> ClosureRegionRequirements<'tcx> {
ClosureRegionRequirements {
num_external_vids: ::core::clone::Clone::clone(&self.num_external_vids),
outlives_requirements: ::core::clone::Clone::clone(&self.outlives_requirements),
}
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ClosureRegionRequirements<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ClosureRegionRequirements", "num_external_vids",
&self.num_external_vids, "outlives_requirements",
&&self.outlives_requirements)
}
}Debug)]
197pub struct ClosureRegionRequirements<'tcx> {
198 pub num_external_vids: usize,
204
205 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
208}
209
210#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for ClosureOutlivesRequirement<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for ClosureOutlivesRequirement<'tcx> {
#[inline]
fn clone(&self) -> ClosureOutlivesRequirement<'tcx> {
let _:
::core::clone::AssertParamIsClone<ClosureOutlivesSubject<'tcx>>;
let _: ::core::clone::AssertParamIsClone<ty::RegionVid>;
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<ConstraintCategory<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ClosureOutlivesRequirement<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"ClosureOutlivesRequirement", "subject", &self.subject,
"outlived_free_region", &self.outlived_free_region, "blame_span",
&self.blame_span, "category", &&self.category)
}
}Debug)]
213pub struct ClosureOutlivesRequirement<'tcx> {
214 pub subject: ClosureOutlivesSubject<'tcx>,
216
217 pub outlived_free_region: ty::RegionVid,
219
220 pub blame_span: Span,
222
223 pub category: ConstraintCategory<'tcx>,
225}
226
227#[cfg(target_pointer_width = "64")]
229const _: [(); 16] = [(); ::std::mem::size_of::<ConstraintCategory<'_>>()];rustc_data_structures::static_assert_size!(ConstraintCategory<'_>, 16);
230
231#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for ClosureOutlivesSubject<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for ClosureOutlivesSubject<'tcx> {
#[inline]
fn clone(&self) -> ClosureOutlivesSubject<'tcx> {
let _:
::core::clone::AssertParamIsClone<ClosureOutlivesSubjectTy<'tcx>>;
let _: ::core::clone::AssertParamIsClone<ty::RegionVid>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ClosureOutlivesSubject<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ClosureOutlivesSubject::Ty(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ty",
&__self_0),
ClosureOutlivesSubject::Region(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Region",
&__self_0),
}
}
}Debug)]
234pub enum ClosureOutlivesSubject<'tcx> {
235 Ty(ClosureOutlivesSubjectTy<'tcx>),
239
240 Region(ty::RegionVid),
243}
244
245#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for ClosureOutlivesSubjectTy<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for ClosureOutlivesSubjectTy<'tcx> {
#[inline]
fn clone(&self) -> ClosureOutlivesSubjectTy<'tcx> {
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ClosureOutlivesSubjectTy<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"ClosureOutlivesSubjectTy", "inner", &&self.inner)
}
}Debug)]
251pub struct ClosureOutlivesSubjectTy<'tcx> {
252 inner: Ty<'tcx>,
253}
254impl<'tcx, I> !TypeVisitable<I> for ClosureOutlivesSubjectTy<'tcx> {}
257impl<'tcx, I> !TypeFoldable<I> for ClosureOutlivesSubjectTy<'tcx> {}
258
259impl<'tcx> ClosureOutlivesSubjectTy<'tcx> {
260 pub fn bind(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Self {
263 let inner = fold_regions(tcx, ty, |r, depth| match r.kind() {
264 ty::ReVar(vid) => {
265 let br = ty::BoundRegion {
266 var: ty::BoundVar::from_usize(vid.index()),
267 kind: ty::BoundRegionKind::Anon,
268 };
269 ty::Region::new_bound(tcx, depth, br)
270 }
271 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected region in ClosureOutlivesSubjectTy: {0:?}",
r))bug!("unexpected region in ClosureOutlivesSubjectTy: {r:?}"),
272 });
273
274 Self { inner }
275 }
276
277 pub fn instantiate(
278 self,
279 tcx: TyCtxt<'tcx>,
280 mut map: impl FnMut(ty::RegionVid) -> ty::Region<'tcx>,
281 ) -> Ty<'tcx> {
282 fold_regions(tcx, self.inner, |r, depth| match r.kind() {
283 ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn), br) => {
284 if true {
match (&debruijn, &depth) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(debruijn, depth);
285 map(ty::RegionVid::from_usize(br.var.index()))
286 }
287 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected region {0:?}", r))bug!("unexpected region {r:?}"),
288 })
289 }
290}
291
292struct CollectRegionConstraintsResult<'tcx> {
293 infcx: BorrowckInferCtxt<'tcx>,
294 body_owned: Body<'tcx>,
295 promoted: IndexVec<Promoted, Body<'tcx>>,
296 move_data: MoveData<'tcx>,
297 borrow_set: BorrowSet<'tcx>,
298 location_table: PoloniusLocationTable,
299 location_map: Rc<DenseLocationMap>,
300 universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
301 region_bound_pairs: Frozen<RegionBoundPairs<'tcx>>,
302 known_type_outlives_obligations: Frozen<Vec<ty::PolyTypeOutlivesPredicate<'tcx>>>,
303 constraints: MirTypeckRegionConstraints<'tcx>,
304 deferred_closure_requirements: DeferredClosureRequirements<'tcx>,
305 deferred_opaque_type_errors: Vec<DeferredOpaqueTypeError<'tcx>>,
306 polonius_facts: Option<AllFacts<RustcFacts>>,
307 polonius_context: Option<PoloniusContext>,
308}
309
310fn borrowck_collect_region_constraints<'tcx>(
314 root_cx: &mut BorrowCheckRootCtxt<'tcx>,
315 def: LocalDefId,
316) -> CollectRegionConstraintsResult<'tcx> {
317 let tcx = root_cx.tcx;
318 let infcx = BorrowckInferCtxt::new(tcx, def, root_cx.root_def_id());
319 let (input_body, promoted) = tcx.mir_promoted(def);
320 let input_body: &Body<'_> = &input_body.borrow();
321 let input_promoted: &IndexSlice<_, _> = &promoted.borrow();
322 if let Some(e) = input_body.tainted_by_errors {
323 infcx.set_tainted_by_errors(e);
324 root_cx.set_tainted_by_errors(e);
325 }
326
327 let mut body_owned = input_body.clone();
332 let mut promoted = input_promoted.to_owned();
333 let universal_regions = nll::replace_regions_in_mir(&infcx, &mut body_owned, &mut promoted);
334 let body = &body_owned; let location_table = PoloniusLocationTable::new(body);
337
338 let move_data = MoveData::gather_moves(body, tcx, |_| true);
339
340 let locals_are_invalidated_at_exit = tcx.hir_body_owner_kind(def).is_fn_or_closure();
341 let borrow_set = BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &move_data);
342
343 let location_map = Rc::new(DenseLocationMap::new(body));
344
345 let polonius_input = root_cx.consumer.as_ref().map_or(false, |c| c.polonius_input())
346 || infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled();
347 let mut polonius_facts =
348 (polonius_input || PoloniusFacts::enabled(infcx.tcx)).then_some(PoloniusFacts::default());
349
350 let MirTypeckResults {
352 constraints,
353 universal_region_relations,
354 region_bound_pairs,
355 known_type_outlives_obligations,
356 deferred_closure_requirements,
357 polonius_context,
358 } = type_check::type_check(
359 root_cx,
360 &infcx,
361 body,
362 &promoted,
363 universal_regions,
364 &location_table,
365 &borrow_set,
366 &mut polonius_facts,
367 &move_data,
368 Rc::clone(&location_map),
369 );
370
371 CollectRegionConstraintsResult {
372 infcx,
373 body_owned,
374 promoted,
375 move_data,
376 borrow_set,
377 location_table,
378 location_map,
379 universal_region_relations,
380 region_bound_pairs,
381 known_type_outlives_obligations,
382 constraints,
383 deferred_closure_requirements,
384 deferred_opaque_type_errors: Default::default(),
385 polonius_facts,
386 polonius_context,
387 }
388}
389
390fn borrowck_check_region_constraints<'tcx>(
394 root_cx: &mut BorrowCheckRootCtxt<'tcx>,
395 CollectRegionConstraintsResult {
396 infcx,
397 body_owned,
398 promoted,
399 move_data,
400 borrow_set,
401 location_table,
402 location_map,
403 universal_region_relations,
404 region_bound_pairs: _,
405 known_type_outlives_obligations: _,
406 constraints,
407 deferred_closure_requirements,
408 deferred_opaque_type_errors,
409 polonius_facts,
410 polonius_context,
411 }: CollectRegionConstraintsResult<'tcx>,
412) -> PropagatedBorrowCheckResults<'tcx> {
413 if !!infcx.has_opaque_types_in_storage() {
::core::panicking::panic("assertion failed: !infcx.has_opaque_types_in_storage()")
};assert!(!infcx.has_opaque_types_in_storage());
414 if !deferred_closure_requirements.is_empty() {
::core::panicking::panic("assertion failed: deferred_closure_requirements.is_empty()")
};assert!(deferred_closure_requirements.is_empty());
415 let tcx = root_cx.tcx;
416 let body = &body_owned;
417 let def = body.source.def_id().expect_local();
418
419 let nll::NllOutput {
422 regioncx,
423 polonius_input,
424 polonius_output,
425 opt_closure_req,
426 nll_errors,
427 polonius_context,
428 } = nll::compute_regions(
429 root_cx,
430 &infcx,
431 body,
432 &location_table,
433 &move_data,
434 &borrow_set,
435 location_map,
436 universal_region_relations,
437 constraints,
438 polonius_facts,
439 polonius_context,
440 );
441
442 nll::dump_nll_mir(&infcx, body, ®ioncx, &opt_closure_req, &borrow_set);
445 polonius::dump_polonius_mir(
446 &infcx,
447 body,
448 ®ioncx,
449 &opt_closure_req,
450 &borrow_set,
451 polonius_context.as_ref(),
452 );
453
454 nll::dump_annotation(&infcx, body, ®ioncx, &opt_closure_req);
457
458 let movable_coroutine = body.coroutine.is_some()
459 && tcx.coroutine_movability(def.to_def_id()) == hir::Movability::Movable;
460
461 let diags_buffer = &mut BorrowckDiagnosticsBuffer::default();
462 for promoted_body in &promoted {
465 use rustc_middle::mir::visit::Visitor;
466 let move_data = MoveData::gather_moves(promoted_body, tcx, |_| true);
470 let mut promoted_mbcx = MirBorrowckCtxt {
471 root_cx,
472 infcx: &infcx,
473 body: promoted_body,
474 move_data: &move_data,
475 location_table: &location_table,
477 movable_coroutine,
478 fn_self_span_reported: Default::default(),
479 access_place_error_reported: Default::default(),
480 reservation_error_reported: Default::default(),
481 uninitialized_error_reported: Default::default(),
482 regioncx: ®ioncx,
483 used_mut: Default::default(),
484 used_mut_upvars: SmallVec::new(),
485 borrow_set: &borrow_set,
486 upvars: &[],
487 local_names: OnceCell::from(IndexVec::from_elem(None, &promoted_body.local_decls)),
488 region_names: RefCell::default(),
489 next_region_name: RefCell::new(1),
490 polonius_output: None,
491 move_errors: Vec::new(),
492 diags_buffer,
493 polonius_context: polonius_context.as_ref(),
494 };
495 struct MoveVisitor<'a, 'b, 'infcx, 'tcx> {
496 ctxt: &'a mut MirBorrowckCtxt<'b, 'infcx, 'tcx>,
497 }
498
499 impl<'tcx> Visitor<'tcx> for MoveVisitor<'_, '_, '_, 'tcx> {
500 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
501 if let Operand::Move(place) = operand {
502 self.ctxt.check_movable_place(location, *place);
503 }
504 }
505 }
506 MoveVisitor { ctxt: &mut promoted_mbcx }.visit_body(promoted_body);
507 promoted_mbcx.report_move_errors();
508 }
509
510 let mut mbcx = MirBorrowckCtxt {
511 root_cx,
512 infcx: &infcx,
513 body,
514 move_data: &move_data,
515 location_table: &location_table,
516 movable_coroutine,
517 fn_self_span_reported: Default::default(),
518 access_place_error_reported: Default::default(),
519 reservation_error_reported: Default::default(),
520 uninitialized_error_reported: Default::default(),
521 regioncx: ®ioncx,
522 used_mut: Default::default(),
523 used_mut_upvars: SmallVec::new(),
524 borrow_set: &borrow_set,
525 upvars: tcx.closure_captures(def),
526 local_names: OnceCell::new(),
527 region_names: RefCell::default(),
528 next_region_name: RefCell::new(1),
529 move_errors: Vec::new(),
530 diags_buffer,
531 polonius_output: polonius_output.as_deref(),
532 polonius_context: polonius_context.as_ref(),
533 };
534
535 if nll_errors.is_empty() {
537 mbcx.report_opaque_type_errors(deferred_opaque_type_errors);
538 } else {
539 mbcx.report_region_errors(nll_errors);
540 }
541
542 let flow_results = get_flow_results(tcx, body, &move_data, &borrow_set, ®ioncx);
543 visit_results(
544 body,
545 traversal::reverse_postorder(body).map(|(bb, _)| bb),
546 &flow_results,
547 &mut mbcx,
548 );
549
550 mbcx.report_move_errors();
551
552 let temporary_used_locals: FxIndexSet<Local> = mbcx
558 .used_mut
559 .iter()
560 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
561 .cloned()
562 .collect();
563 let unused_mut_locals =
567 mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
568 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
569
570 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:570",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(570u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("mbcx.used_mut: {0:?}",
mbcx.used_mut) as &dyn Value))])
});
} else { ; }
};debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
571 mbcx.lint_unused_mut();
572 if let Some(guar) = mbcx.emit_errors() {
573 mbcx.root_cx.set_tainted_by_errors(guar);
574 }
575
576 let result = PropagatedBorrowCheckResults {
577 closure_requirements: opt_closure_req,
578 used_mut_upvars: mbcx.used_mut_upvars,
579 };
580
581 if let Some(consumer) = &mut root_cx.consumer {
582 consumer.insert_body(
583 def,
584 BodyWithBorrowckFacts {
585 body: body_owned,
586 promoted,
587 borrow_set,
588 region_inference_context: regioncx,
589 location_table: polonius_input.as_ref().map(|_| location_table),
590 input_facts: polonius_input,
591 output_facts: polonius_output,
592 },
593 );
594 }
595
596 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:596",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(596u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("do_mir_borrowck: result = {0:#?}",
result) as &dyn Value))])
});
} else { ; }
};debug!("do_mir_borrowck: result = {:#?}", result);
597
598 result
599}
600
601fn get_flow_results<'a, 'tcx>(
602 tcx: TyCtxt<'tcx>,
603 body: &'a Body<'tcx>,
604 move_data: &'a MoveData<'tcx>,
605 borrow_set: &'a BorrowSet<'tcx>,
606 regioncx: &RegionInferenceContext<'tcx>,
607) -> Results<'tcx, Borrowck<'a, 'tcx>> {
608 let borrows = Borrows::new(tcx, body, regioncx, borrow_set).iterate_to_fixpoint(
611 tcx,
612 body,
613 Some("borrowck"),
614 );
615 let uninits = MaybeUninitializedPlaces::new(tcx, body, move_data).iterate_to_fixpoint(
616 tcx,
617 body,
618 Some("borrowck"),
619 );
620 let ever_inits = EverInitializedPlaces::new(body, move_data).iterate_to_fixpoint(
621 tcx,
622 body,
623 Some("borrowck"),
624 );
625
626 let analysis = Borrowck {
627 borrows: borrows.analysis,
628 uninits: uninits.analysis,
629 ever_inits: ever_inits.analysis,
630 };
631
632 match (&borrows.entry_states.len(), &uninits.entry_states.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(borrows.entry_states.len(), uninits.entry_states.len());
633 match (&borrows.entry_states.len(), &ever_inits.entry_states.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(borrows.entry_states.len(), ever_inits.entry_states.len());
634 let entry_states: EntryStates<_> =
635 ::itertools::__std_iter::IntoIterator::into_iter(borrows.entry_states).zip(uninits.entry_states).zip(ever_inits.entry_states).map(|((a,
b), b)| (a, b, b))itertools::izip!(borrows.entry_states, uninits.entry_states, ever_inits.entry_states)
636 .map(|(borrows, uninits, ever_inits)| BorrowckDomain { borrows, uninits, ever_inits })
637 .collect();
638
639 Results { analysis, entry_states }
640}
641
642pub(crate) struct BorrowckInferCtxt<'tcx> {
643 pub(crate) infcx: InferCtxt<'tcx>,
644 pub(crate) root_def_id: LocalDefId,
645 pub(crate) param_env: ParamEnv<'tcx>,
646 pub(crate) reg_var_to_origin: RefCell<FxIndexMap<ty::RegionVid, RegionCtxt>>,
647}
648
649impl<'tcx> BorrowckInferCtxt<'tcx> {
650 pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId, root_def_id: LocalDefId) -> Self {
651 let typing_mode = if tcx.use_typing_mode_borrowck() {
652 TypingMode::borrowck(tcx, def_id)
653 } else {
654 TypingMode::analysis_in_body(tcx, def_id)
655 };
656 let infcx = tcx.infer_ctxt().build(typing_mode);
657 let param_env = tcx.param_env(def_id);
658 BorrowckInferCtxt {
659 infcx,
660 root_def_id,
661 reg_var_to_origin: RefCell::new(Default::default()),
662 param_env,
663 }
664 }
665
666 pub(crate) fn next_region_var<F>(
667 &self,
668 origin: RegionVariableOrigin<'tcx>,
669 get_ctxt_fn: F,
670 ) -> ty::Region<'tcx>
671 where
672 F: Fn() -> RegionCtxt,
673 {
674 let next_region = self.infcx.next_region_var(origin);
675 let vid = next_region.as_var();
676
677 if truecfg!(debug_assertions) {
678 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:678",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(678u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inserting vid {0:?} with origin {1:?} into var_to_origin",
vid, origin) as &dyn Value))])
});
} else { ; }
};debug!("inserting vid {:?} with origin {:?} into var_to_origin", vid, origin);
679 let ctxt = get_ctxt_fn();
680 let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
681 match (&var_to_origin.insert(vid, ctxt), &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(var_to_origin.insert(vid, ctxt), None);
682 }
683
684 next_region
685 }
686
687 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("next_nll_region_var",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(687u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["origin"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ty::Region<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let next_region = self.infcx.next_nll_region_var(origin);
let vid = next_region.as_var();
if true {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:700",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(700u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inserting vid {0:?} with origin {1:?} into var_to_origin",
vid, origin) as &dyn Value))])
});
} else { ; }
};
let ctxt = get_ctxt_fn();
let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
match (&var_to_origin.insert(vid, ctxt), &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
}
next_region
}
}
}#[instrument(skip(self, get_ctxt_fn), level = "debug")]
688 pub(crate) fn next_nll_region_var<F>(
689 &self,
690 origin: NllRegionVariableOrigin<'tcx>,
691 get_ctxt_fn: F,
692 ) -> ty::Region<'tcx>
693 where
694 F: Fn() -> RegionCtxt,
695 {
696 let next_region = self.infcx.next_nll_region_var(origin);
697 let vid = next_region.as_var();
698
699 if cfg!(debug_assertions) {
700 debug!("inserting vid {:?} with origin {:?} into var_to_origin", vid, origin);
701 let ctxt = get_ctxt_fn();
702 let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
703 assert_eq!(var_to_origin.insert(vid, ctxt), None);
704 }
705
706 next_region
707 }
708}
709
710impl<'tcx> Deref for BorrowckInferCtxt<'tcx> {
711 type Target = InferCtxt<'tcx>;
712
713 fn deref(&self) -> &Self::Target {
714 &self.infcx
715 }
716}
717
718struct MirBorrowckCtxt<'a, 'infcx, 'tcx> {
719 root_cx: &'a mut BorrowCheckRootCtxt<'tcx>,
720 infcx: &'infcx BorrowckInferCtxt<'tcx>,
721 body: &'a Body<'tcx>,
722 move_data: &'a MoveData<'tcx>,
723
724 location_table: &'a PoloniusLocationTable,
727
728 movable_coroutine: bool,
729 access_place_error_reported: FxIndexSet<(Place<'tcx>, Span)>,
735 reservation_error_reported: FxIndexSet<Place<'tcx>>,
743 fn_self_span_reported: FxIndexSet<Span>,
747 uninitialized_error_reported: FxIndexSet<Local>,
750 used_mut: FxIndexSet<Local>,
753 used_mut_upvars: SmallVec<[FieldIdx; 8]>,
756 regioncx: &'a RegionInferenceContext<'tcx>,
759
760 borrow_set: &'a BorrowSet<'tcx>,
762
763 upvars: &'tcx [&'tcx ty::CapturedPlace<'tcx>],
765
766 local_names: OnceCell<IndexVec<Local, Option<Symbol>>>,
768
769 region_names: RefCell<FxIndexMap<RegionVid, RegionName>>,
772
773 next_region_name: RefCell<usize>,
775
776 diags_buffer: &'a mut BorrowckDiagnosticsBuffer<'infcx, 'tcx>,
777 move_errors: Vec<MoveError<'tcx>>,
778
779 polonius_output: Option<&'a PoloniusOutput>,
781 polonius_context: Option<&'a PoloniusContext>,
783}
784
785impl<'a, 'tcx> ResultsVisitor<'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<'a, '_, 'tcx> {
791 fn visit_after_early_statement_effect(
792 &mut self,
793 _analysis: &Borrowck<'a, 'tcx>,
794 state: &BorrowckDomain,
795 stmt: &Statement<'tcx>,
796 location: Location,
797 ) {
798 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:798",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(798u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("MirBorrowckCtxt::process_statement({0:?}, {1:?}): {2:?}",
location, stmt, state) as &dyn Value))])
});
} else { ; }
};debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, state);
799 let span = stmt.source_info.span;
800
801 self.check_activations(location, span, state);
802
803 match &stmt.kind {
804 StatementKind::Assign(box (lhs, rhs)) => {
805 self.consume_rvalue(location, (rhs, span), state);
806
807 self.mutate_place(location, (*lhs, span), Shallow(None), state);
808 }
809 StatementKind::FakeRead(box (_, place)) => {
810 self.check_if_path_or_subpath_is_moved(
821 location,
822 InitializationRequiringAction::Use,
823 (place.as_ref(), span),
824 state,
825 );
826 }
827 StatementKind::Intrinsic(box kind) => match kind {
828 NonDivergingIntrinsic::Assume(op) => {
829 self.consume_operand(location, (op, span), state);
830 }
831 NonDivergingIntrinsic::CopyNonOverlapping(..) => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("Unexpected CopyNonOverlapping, should only appear after lower_intrinsics"))span_bug!(
832 span,
833 "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
834 )
835 }
836 StatementKind::AscribeUserType(..)
838 | StatementKind::PlaceMention(..)
840 | StatementKind::Coverage(..)
842 | StatementKind::ConstEvalCounter
844 | StatementKind::StorageLive(..) => {}
845 StatementKind::BackwardIncompatibleDropHint { place, reason: BackwardIncompatibleDropReason::Edition2024 } => {
847 self.check_backward_incompatible_drop(location, **place, state);
848 }
849 StatementKind::StorageDead(local) => {
850 self.access_place(
851 location,
852 (Place::from(*local), span),
853 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
854 LocalMutationIsAllowed::Yes,
855 state,
856 );
857 }
858 StatementKind::Nop
859 | StatementKind::Retag { .. }
860 | StatementKind::SetDiscriminant { .. } => {
861 ::rustc_middle::util::bug::bug_fmt(format_args!("Statement not allowed in this MIR phase"))bug!("Statement not allowed in this MIR phase")
862 }
863 }
864 }
865
866 fn visit_after_early_terminator_effect(
867 &mut self,
868 _analysis: &Borrowck<'a, 'tcx>,
869 state: &BorrowckDomain,
870 term: &Terminator<'tcx>,
871 loc: Location,
872 ) {
873 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:873",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(873u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("MirBorrowckCtxt::process_terminator({0:?}, {1:?}): {2:?}",
loc, term, state) as &dyn Value))])
});
} else { ; }
};debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, state);
874 let span = term.source_info.span;
875
876 self.check_activations(loc, span, state);
877
878 match &term.kind {
879 TerminatorKind::SwitchInt { discr, targets: _ } => {
880 self.consume_operand(loc, (discr, span), state);
881 }
882 TerminatorKind::Drop {
883 place,
884 target: _,
885 unwind: _,
886 replace,
887 drop: _,
888 async_fut: _,
889 } => {
890 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:890",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(890u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("visit_terminator_drop loc: {0:?} term: {1:?} place: {2:?} span: {3:?}",
loc, term, place, span) as &dyn Value))])
});
} else { ; }
};debug!(
891 "visit_terminator_drop \
892 loc: {:?} term: {:?} place: {:?} span: {:?}",
893 loc, term, place, span
894 );
895
896 let write_kind =
897 if *replace { WriteKind::Replace } else { WriteKind::StorageDeadOrDrop };
898 self.access_place(
899 loc,
900 (*place, span),
901 (AccessDepth::Drop, Write(write_kind)),
902 LocalMutationIsAllowed::Yes,
903 state,
904 );
905 }
906 TerminatorKind::Call {
907 func,
908 args,
909 destination,
910 target: _,
911 unwind: _,
912 call_source: _,
913 fn_span: _,
914 } => {
915 self.consume_operand(loc, (func, span), state);
916 for arg in args {
917 self.consume_operand(loc, (&arg.node, arg.span), state);
918 }
919 self.mutate_place(loc, (*destination, span), Deep, state);
920 }
921 TerminatorKind::TailCall { func, args, fn_span: _ } => {
922 self.consume_operand(loc, (func, span), state);
923 for arg in args {
924 self.consume_operand(loc, (&arg.node, arg.span), state);
925 }
926 }
927 TerminatorKind::Assert { cond, expected: _, msg, target: _, unwind: _ } => {
928 self.consume_operand(loc, (cond, span), state);
929 if let AssertKind::BoundsCheck { len, index } = &**msg {
930 self.consume_operand(loc, (len, span), state);
931 self.consume_operand(loc, (index, span), state);
932 }
933 }
934
935 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
936 self.consume_operand(loc, (value, span), state);
937 self.mutate_place(loc, (*resume_arg, span), Deep, state);
938 }
939
940 TerminatorKind::InlineAsm {
941 asm_macro: _,
942 template: _,
943 operands,
944 options: _,
945 line_spans: _,
946 targets: _,
947 unwind: _,
948 } => {
949 for op in operands {
950 match op {
951 InlineAsmOperand::In { reg: _, value } => {
952 self.consume_operand(loc, (value, span), state);
953 }
954 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
955 if let Some(place) = place {
956 self.mutate_place(loc, (*place, span), Shallow(None), state);
957 }
958 }
959 InlineAsmOperand::InOut { reg: _, late: _, in_value, out_place } => {
960 self.consume_operand(loc, (in_value, span), state);
961 if let &Some(out_place) = out_place {
962 self.mutate_place(loc, (out_place, span), Shallow(None), state);
963 }
964 }
965 InlineAsmOperand::Const { value: _ }
966 | InlineAsmOperand::SymFn { value: _ }
967 | InlineAsmOperand::SymStatic { def_id: _ }
968 | InlineAsmOperand::Label { target_index: _ } => {}
969 }
970 }
971 }
972
973 TerminatorKind::Goto { target: _ }
974 | TerminatorKind::UnwindTerminate(_)
975 | TerminatorKind::Unreachable
976 | TerminatorKind::UnwindResume
977 | TerminatorKind::Return
978 | TerminatorKind::CoroutineDrop
979 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
980 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
981 }
983 }
984 }
985
986 fn visit_after_primary_terminator_effect(
987 &mut self,
988 _analysis: &Borrowck<'a, 'tcx>,
989 state: &BorrowckDomain,
990 term: &Terminator<'tcx>,
991 loc: Location,
992 ) {
993 let span = term.source_info.span;
994
995 match term.kind {
996 TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
997 if self.movable_coroutine {
998 for i in state.borrows.iter() {
1000 let borrow = &self.borrow_set[i];
1001 self.check_for_local_borrow(borrow, span);
1002 }
1003 }
1004 }
1005
1006 TerminatorKind::UnwindResume
1007 | TerminatorKind::Return
1008 | TerminatorKind::TailCall { .. }
1009 | TerminatorKind::CoroutineDrop => {
1010 match self.borrow_set.locals_state_at_exit() {
1011 LocalsStateAtExit::AllAreInvalidated => {
1012 for i in state.borrows.iter() {
1017 let borrow = &self.borrow_set[i];
1018 self.check_for_invalidation_at_exit(loc, borrow, span);
1019 }
1020 }
1021 LocalsStateAtExit::SomeAreInvalidated { has_storage_dead_or_moved: _ } => {}
1024 }
1025 }
1026
1027 TerminatorKind::UnwindTerminate(_)
1028 | TerminatorKind::Assert { .. }
1029 | TerminatorKind::Call { .. }
1030 | TerminatorKind::Drop { .. }
1031 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
1032 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
1033 | TerminatorKind::Goto { .. }
1034 | TerminatorKind::SwitchInt { .. }
1035 | TerminatorKind::Unreachable
1036 | TerminatorKind::InlineAsm { .. } => {}
1037 }
1038 }
1039}
1040
1041use self::AccessDepth::{Deep, Shallow};
1042use self::ReadOrWrite::{Activation, Read, Reservation, Write};
1043
1044#[derive(#[automatically_derived]
impl ::core::marker::Copy for ArtificialField { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ArtificialField {
#[inline]
fn clone(&self) -> ArtificialField { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ArtificialField {
#[inline]
fn eq(&self, other: &ArtificialField) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ArtificialField {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for ArtificialField {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ArtificialField::ArrayLength => "ArrayLength",
ArtificialField::FakeBorrow => "FakeBorrow",
})
}
}Debug)]
1045enum ArtificialField {
1046 ArrayLength,
1047 FakeBorrow,
1048}
1049
1050#[derive(#[automatically_derived]
impl ::core::marker::Copy for AccessDepth { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AccessDepth {
#[inline]
fn clone(&self) -> AccessDepth {
let _: ::core::clone::AssertParamIsClone<Option<ArtificialField>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for AccessDepth {
#[inline]
fn eq(&self, other: &AccessDepth) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(AccessDepth::Shallow(__self_0),
AccessDepth::Shallow(__arg1_0)) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AccessDepth {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Option<ArtificialField>>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for AccessDepth {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
AccessDepth::Shallow(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Shallow", &__self_0),
AccessDepth::Deep => ::core::fmt::Formatter::write_str(f, "Deep"),
AccessDepth::Drop => ::core::fmt::Formatter::write_str(f, "Drop"),
}
}
}Debug)]
1051enum AccessDepth {
1052 Shallow(Option<ArtificialField>),
1058
1059 Deep,
1063
1064 Drop,
1067}
1068
1069#[derive(#[automatically_derived]
impl ::core::marker::Copy for ReadOrWrite { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ReadOrWrite {
#[inline]
fn clone(&self) -> ReadOrWrite {
let _: ::core::clone::AssertParamIsClone<ReadKind>;
let _: ::core::clone::AssertParamIsClone<WriteKind>;
let _: ::core::clone::AssertParamIsClone<BorrowIndex>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ReadOrWrite {
#[inline]
fn eq(&self, other: &ReadOrWrite) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ReadOrWrite::Read(__self_0), ReadOrWrite::Read(__arg1_0)) =>
__self_0 == __arg1_0,
(ReadOrWrite::Write(__self_0), ReadOrWrite::Write(__arg1_0))
=> __self_0 == __arg1_0,
(ReadOrWrite::Reservation(__self_0),
ReadOrWrite::Reservation(__arg1_0)) => __self_0 == __arg1_0,
(ReadOrWrite::Activation(__self_0, __self_1),
ReadOrWrite::Activation(__arg1_0, __arg1_1)) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ReadOrWrite {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ReadKind>;
let _: ::core::cmp::AssertParamIsEq<WriteKind>;
let _: ::core::cmp::AssertParamIsEq<BorrowIndex>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for ReadOrWrite {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ReadOrWrite::Read(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Read",
&__self_0),
ReadOrWrite::Write(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Write",
&__self_0),
ReadOrWrite::Reservation(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Reservation", &__self_0),
ReadOrWrite::Activation(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Activation", __self_0, &__self_1),
}
}
}Debug)]
1072enum ReadOrWrite {
1073 Read(ReadKind),
1076
1077 Write(WriteKind),
1081
1082 Reservation(WriteKind),
1086 Activation(WriteKind, BorrowIndex),
1087}
1088
1089#[derive(#[automatically_derived]
impl ::core::marker::Copy for ReadKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ReadKind {
#[inline]
fn clone(&self) -> ReadKind {
let _: ::core::clone::AssertParamIsClone<BorrowKind>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ReadKind {
#[inline]
fn eq(&self, other: &ReadKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ReadKind::Borrow(__self_0), ReadKind::Borrow(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ReadKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<BorrowKind>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for ReadKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ReadKind::Borrow(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Borrow",
&__self_0),
ReadKind::Copy => ::core::fmt::Formatter::write_str(f, "Copy"),
}
}
}Debug)]
1092enum ReadKind {
1093 Borrow(BorrowKind),
1094 Copy,
1095}
1096
1097#[derive(#[automatically_derived]
impl ::core::marker::Copy for WriteKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for WriteKind {
#[inline]
fn clone(&self) -> WriteKind {
let _: ::core::clone::AssertParamIsClone<BorrowKind>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for WriteKind {
#[inline]
fn eq(&self, other: &WriteKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(WriteKind::MutableBorrow(__self_0),
WriteKind::MutableBorrow(__arg1_0)) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for WriteKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<BorrowKind>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for WriteKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
WriteKind::StorageDeadOrDrop =>
::core::fmt::Formatter::write_str(f, "StorageDeadOrDrop"),
WriteKind::Replace =>
::core::fmt::Formatter::write_str(f, "Replace"),
WriteKind::MutableBorrow(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"MutableBorrow", &__self_0),
WriteKind::Mutate =>
::core::fmt::Formatter::write_str(f, "Mutate"),
WriteKind::Move => ::core::fmt::Formatter::write_str(f, "Move"),
}
}
}Debug)]
1100enum WriteKind {
1101 StorageDeadOrDrop,
1102 Replace,
1103 MutableBorrow(BorrowKind),
1104 Mutate,
1105 Move,
1106}
1107
1108#[derive(#[automatically_derived]
impl ::core::marker::Copy for LocalMutationIsAllowed { }Copy, #[automatically_derived]
impl ::core::clone::Clone for LocalMutationIsAllowed {
#[inline]
fn clone(&self) -> LocalMutationIsAllowed { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for LocalMutationIsAllowed {
#[inline]
fn eq(&self, other: &LocalMutationIsAllowed) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for LocalMutationIsAllowed {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for LocalMutationIsAllowed {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
LocalMutationIsAllowed::Yes => "Yes",
LocalMutationIsAllowed::ExceptUpvars => "ExceptUpvars",
LocalMutationIsAllowed::No => "No",
})
}
}Debug)]
1116enum LocalMutationIsAllowed {
1117 Yes,
1118 ExceptUpvars,
1121 No,
1122}
1123
1124#[derive(#[automatically_derived]
impl ::core::marker::Copy for InitializationRequiringAction { }Copy, #[automatically_derived]
impl ::core::clone::Clone for InitializationRequiringAction {
#[inline]
fn clone(&self) -> InitializationRequiringAction { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for InitializationRequiringAction {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
InitializationRequiringAction::Borrow => "Borrow",
InitializationRequiringAction::MatchOn => "MatchOn",
InitializationRequiringAction::Use => "Use",
InitializationRequiringAction::Assignment => "Assignment",
InitializationRequiringAction::PartialAssignment =>
"PartialAssignment",
})
}
}Debug)]
1125enum InitializationRequiringAction {
1126 Borrow,
1127 MatchOn,
1128 Use,
1129 Assignment,
1130 PartialAssignment,
1131}
1132
1133#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for RootPlace<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "RootPlace",
"place_local", &self.place_local, "place_projection",
&self.place_projection, "is_local_mutation_allowed",
&&self.is_local_mutation_allowed)
}
}Debug)]
1134struct RootPlace<'tcx> {
1135 place_local: Local,
1136 place_projection: &'tcx [PlaceElem<'tcx>],
1137 is_local_mutation_allowed: LocalMutationIsAllowed,
1138}
1139
1140impl InitializationRequiringAction {
1141 fn as_noun(self) -> &'static str {
1142 match self {
1143 InitializationRequiringAction::Borrow => "borrow",
1144 InitializationRequiringAction::MatchOn => "use", InitializationRequiringAction::Use => "use",
1146 InitializationRequiringAction::Assignment => "assign",
1147 InitializationRequiringAction::PartialAssignment => "assign to part",
1148 }
1149 }
1150
1151 fn as_verb_in_past_tense(self) -> &'static str {
1152 match self {
1153 InitializationRequiringAction::Borrow => "borrowed",
1154 InitializationRequiringAction::MatchOn => "matched on",
1155 InitializationRequiringAction::Use => "used",
1156 InitializationRequiringAction::Assignment => "assigned",
1157 InitializationRequiringAction::PartialAssignment => "partially assigned",
1158 }
1159 }
1160
1161 fn as_general_verb_in_past_tense(self) -> &'static str {
1162 match self {
1163 InitializationRequiringAction::Borrow
1164 | InitializationRequiringAction::MatchOn
1165 | InitializationRequiringAction::Use => "used",
1166 InitializationRequiringAction::Assignment => "assigned",
1167 InitializationRequiringAction::PartialAssignment => "partially assigned",
1168 }
1169 }
1170}
1171
1172impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
1173 fn body(&self) -> &'a Body<'tcx> {
1174 self.body
1175 }
1176
1177 fn access_place(
1184 &mut self,
1185 location: Location,
1186 place_span: (Place<'tcx>, Span),
1187 kind: (AccessDepth, ReadOrWrite),
1188 is_local_mutation_allowed: LocalMutationIsAllowed,
1189 state: &BorrowckDomain,
1190 ) {
1191 let (sd, rw) = kind;
1192
1193 if let Activation(_, borrow_index) = rw {
1194 if self.reservation_error_reported.contains(&place_span.0) {
1195 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1195",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1195u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("skipping access_place for activation of invalid reservation place: {0:?} borrow_index: {1:?}",
place_span.0, borrow_index) as &dyn Value))])
});
} else { ; }
};debug!(
1196 "skipping access_place for activation of invalid reservation \
1197 place: {:?} borrow_index: {:?}",
1198 place_span.0, borrow_index
1199 );
1200 return;
1201 }
1202 }
1203
1204 if !self.access_place_error_reported.is_empty()
1207 && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
1208 {
1209 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1209",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1209u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("access_place: suppressing error place_span=`{0:?}` kind=`{1:?}`",
place_span, kind) as &dyn Value))])
});
} else { ; }
};debug!(
1210 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
1211 place_span, kind
1212 );
1213
1214 if rw == ReadOrWrite::Write(WriteKind::Mutate)
1218 && let Ok(root_place) =
1219 self.is_mutable(place_span.0.as_ref(), is_local_mutation_allowed)
1220 {
1221 self.add_used_mut(root_place, state);
1222 }
1223
1224 return;
1225 }
1226
1227 let mutability_error = self.check_access_permissions(
1228 place_span,
1229 rw,
1230 is_local_mutation_allowed,
1231 state,
1232 location,
1233 );
1234 let conflict_error = self.check_access_for_conflict(location, place_span, sd, rw, state);
1235
1236 if conflict_error || mutability_error {
1237 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1237",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1237u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("access_place: logging error place_span=`{0:?}` kind=`{1:?}`",
place_span, kind) as &dyn Value))])
});
} else { ; }
};debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
1238 self.access_place_error_reported.insert((place_span.0, place_span.1));
1239 }
1240 }
1241
1242 fn borrows_in_scope<'s>(
1243 &self,
1244 location: Location,
1245 state: &'s BorrowckDomain,
1246 ) -> Cow<'s, MixedBitSet<BorrowIndex>> {
1247 if let Some(polonius) = &self.polonius_output {
1248 let location = self.location_table.start_index(location);
1250 let mut polonius_output = MixedBitSet::new_empty(self.borrow_set.len());
1251 for &idx in polonius.errors_at(location) {
1252 polonius_output.insert(idx);
1253 }
1254 Cow::Owned(polonius_output)
1255 } else {
1256 Cow::Borrowed(&state.borrows)
1257 }
1258 }
1259
1260 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_access_for_conflict",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1260u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["location",
"place_span", "sd", "rw"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sd)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rw)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
let mut error_reported = false;
let borrows_in_scope = self.borrows_in_scope(location, state);
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
=> {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1288",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1288u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_access_for_conflict place_span: {0:?} sd: {1:?} rw: {2:?} skipping {3:?} b/c activation of same borrow_index",
place_span, sd, rw, (borrow_index, borrow)) as
&dyn Value))])
});
} else { ; }
};
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) {
if !borrow.kind.is_two_phase_borrow() {
::core::panicking::panic("assertion failed: 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(..) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1342",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1342u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("recording invalid reservation of place: {0:?}",
place_span.0) as &dyn Value))])
});
} else { ; }
};
this.reservation_error_reported.insert(place_span.0);
}
Activation(_, activating) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1350",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1350u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("observing check_place for activation of borrow_index: {0:?}",
activating) as &dyn Value))])
});
} else { ; }
};
}
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))]
1261 fn check_access_for_conflict(
1262 &mut self,
1263 location: Location,
1264 place_span: (Place<'tcx>, Span),
1265 sd: AccessDepth,
1266 rw: ReadOrWrite,
1267 state: &BorrowckDomain,
1268 ) -> bool {
1269 let mut error_reported = false;
1270
1271 let borrows_in_scope = self.borrows_in_scope(location, state);
1272
1273 each_borrow_involving_path(
1274 self,
1275 self.infcx.tcx,
1276 self.body,
1277 (sd, place_span.0),
1278 self.borrow_set,
1279 |borrow_index| borrows_in_scope.contains(borrow_index),
1280 |this, borrow_index, borrow| match (rw, borrow.kind) {
1281 (Activation(_, activating), _) if activating == borrow_index => {
1288 debug!(
1289 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1290 skipping {:?} b/c activation of same borrow_index",
1291 place_span,
1292 sd,
1293 rw,
1294 (borrow_index, borrow),
1295 );
1296 ControlFlow::Continue(())
1297 }
1298
1299 (Read(_), BorrowKind::Shared | BorrowKind::Fake(_))
1300 | (
1301 Read(ReadKind::Borrow(BorrowKind::Fake(FakeBorrowKind::Shallow))),
1302 BorrowKind::Mut { .. },
1303 ) => ControlFlow::Continue(()),
1304
1305 (Reservation(_), BorrowKind::Fake(_) | BorrowKind::Shared) => {
1306 ControlFlow::Continue(())
1309 }
1310
1311 (Write(WriteKind::Move), BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
1312 ControlFlow::Continue(())
1314 }
1315
1316 (Read(kind), BorrowKind::Mut { .. }) => {
1317 if !is_active(this.dominators(), borrow, location) {
1319 assert!(borrow.kind.is_two_phase_borrow());
1320 return ControlFlow::Continue(());
1321 }
1322
1323 error_reported = true;
1324 match kind {
1325 ReadKind::Copy => {
1326 let err = this
1327 .report_use_while_mutably_borrowed(location, place_span, borrow);
1328 this.buffer_error(err);
1329 }
1330 ReadKind::Borrow(bk) => {
1331 let err =
1332 this.report_conflicting_borrow(location, place_span, bk, borrow);
1333 this.buffer_error(err);
1334 }
1335 }
1336 ControlFlow::Break(())
1337 }
1338
1339 (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1340 match rw {
1341 Reservation(..) => {
1342 debug!(
1343 "recording invalid reservation of \
1344 place: {:?}",
1345 place_span.0
1346 );
1347 this.reservation_error_reported.insert(place_span.0);
1348 }
1349 Activation(_, activating) => {
1350 debug!(
1351 "observing check_place for activation of \
1352 borrow_index: {:?}",
1353 activating
1354 );
1355 }
1356 Read(..) | Write(..) => {}
1357 }
1358
1359 error_reported = true;
1360 match kind {
1361 WriteKind::MutableBorrow(bk) => {
1362 let err =
1363 this.report_conflicting_borrow(location, place_span, bk, borrow);
1364 this.buffer_error(err);
1365 }
1366 WriteKind::StorageDeadOrDrop => this
1367 .report_borrowed_value_does_not_live_long_enough(
1368 location,
1369 borrow,
1370 place_span,
1371 Some(WriteKind::StorageDeadOrDrop),
1372 ),
1373 WriteKind::Mutate => {
1374 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1375 }
1376 WriteKind::Move => {
1377 this.report_move_out_while_borrowed(location, place_span, borrow)
1378 }
1379 WriteKind::Replace => {
1380 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1381 }
1382 }
1383 ControlFlow::Break(())
1384 }
1385 },
1386 );
1387
1388 error_reported
1389 }
1390
1391 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_backward_incompatible_drop",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1393u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["location", "place"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
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 #[allow(non_exhaustive_omitted_patterns)] match borrow.kind
{
BorrowKind::Fake(_) => true,
_ => false,
} {
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.node_span_lint(TAIL_EXPR_DROP_ORDER,
CRATE_HIR_ID, borrowed,
|diag|
{
session_diagnostics::TailExprDropOrder {
borrowed,
}.decorate_lint(diag);
explain.add_explanation_to_diagnostic(&this, diag, "", None,
None);
});
ControlFlow::Break(())
});
}
}
}#[instrument(level = "debug", skip(self, state))]
1394 fn check_backward_incompatible_drop(
1395 &mut self,
1396 location: Location,
1397 place: Place<'tcx>,
1398 state: &BorrowckDomain,
1399 ) {
1400 let tcx = self.infcx.tcx;
1401 let sd = if place.ty(self.body, tcx).ty.needs_drop(tcx, self.body.typing_env(tcx)) {
1405 AccessDepth::Drop
1406 } else {
1407 AccessDepth::Shallow(None)
1408 };
1409
1410 let borrows_in_scope = self.borrows_in_scope(location, state);
1411
1412 each_borrow_involving_path(
1415 self,
1416 self.infcx.tcx,
1417 self.body,
1418 (sd, place),
1419 self.borrow_set,
1420 |borrow_index| borrows_in_scope.contains(borrow_index),
1421 |this, _borrow_index, borrow| {
1422 if matches!(borrow.kind, BorrowKind::Fake(_)) {
1423 return ControlFlow::Continue(());
1424 }
1425 let borrowed = this.retrieve_borrow_spans(borrow).var_or_use_path_span();
1426 let explain = this.explain_why_borrow_contains_point(
1427 location,
1428 borrow,
1429 Some((WriteKind::StorageDeadOrDrop, place)),
1430 );
1431 this.infcx.tcx.node_span_lint(
1432 TAIL_EXPR_DROP_ORDER,
1433 CRATE_HIR_ID,
1434 borrowed,
1435 |diag| {
1436 session_diagnostics::TailExprDropOrder { borrowed }.decorate_lint(diag);
1437 explain.add_explanation_to_diagnostic(&this, diag, "", None, None);
1438 },
1439 );
1440 ControlFlow::Break(())
1442 },
1443 );
1444 }
1445
1446 fn mutate_place(
1447 &mut self,
1448 location: Location,
1449 place_span: (Place<'tcx>, Span),
1450 kind: AccessDepth,
1451 state: &BorrowckDomain,
1452 ) {
1453 self.check_if_assigned_path_is_moved(location, place_span, state);
1455
1456 self.access_place(
1457 location,
1458 place_span,
1459 (kind, Write(WriteKind::Mutate)),
1460 LocalMutationIsAllowed::No,
1461 state,
1462 );
1463 }
1464
1465 fn consume_rvalue(
1466 &mut self,
1467 location: Location,
1468 (rvalue, span): (&Rvalue<'tcx>, Span),
1469 state: &BorrowckDomain,
1470 ) {
1471 match rvalue {
1472 &Rvalue::Ref(_ , bk, place) => {
1473 let access_kind = match bk {
1474 BorrowKind::Fake(FakeBorrowKind::Shallow) => {
1475 (Shallow(Some(ArtificialField::FakeBorrow)), Read(ReadKind::Borrow(bk)))
1476 }
1477 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep) => {
1478 (Deep, Read(ReadKind::Borrow(bk)))
1479 }
1480 BorrowKind::Mut { .. } => {
1481 let wk = WriteKind::MutableBorrow(bk);
1482 if bk.is_two_phase_borrow() {
1483 (Deep, Reservation(wk))
1484 } else {
1485 (Deep, Write(wk))
1486 }
1487 }
1488 };
1489
1490 self.access_place(
1491 location,
1492 (place, span),
1493 access_kind,
1494 LocalMutationIsAllowed::No,
1495 state,
1496 );
1497
1498 let action = if bk == BorrowKind::Fake(FakeBorrowKind::Shallow) {
1499 InitializationRequiringAction::MatchOn
1500 } else {
1501 InitializationRequiringAction::Borrow
1502 };
1503
1504 self.check_if_path_or_subpath_is_moved(
1505 location,
1506 action,
1507 (place.as_ref(), span),
1508 state,
1509 );
1510 }
1511
1512 &Rvalue::RawPtr(kind, place) => {
1513 let access_kind = match kind {
1514 RawPtrKind::Mut => (
1515 Deep,
1516 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1517 kind: MutBorrowKind::Default,
1518 })),
1519 ),
1520 RawPtrKind::Const => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1521 RawPtrKind::FakeForPtrMetadata => {
1522 (Shallow(Some(ArtificialField::ArrayLength)), Read(ReadKind::Copy))
1523 }
1524 };
1525
1526 self.access_place(
1527 location,
1528 (place, span),
1529 access_kind,
1530 LocalMutationIsAllowed::No,
1531 state,
1532 );
1533
1534 self.check_if_path_or_subpath_is_moved(
1535 location,
1536 InitializationRequiringAction::Borrow,
1537 (place.as_ref(), span),
1538 state,
1539 );
1540 }
1541
1542 Rvalue::ThreadLocalRef(_) => {}
1543
1544 Rvalue::Use(operand)
1545 | Rvalue::Repeat(operand, _)
1546 | Rvalue::UnaryOp(_ , operand)
1547 | Rvalue::Cast(_ , operand, _ )
1548 | Rvalue::ShallowInitBox(operand, _ ) => {
1549 self.consume_operand(location, (operand, span), state)
1550 }
1551
1552 &Rvalue::Discriminant(place) => {
1553 let af = match *rvalue {
1554 Rvalue::Discriminant(..) => None,
1555 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1556 };
1557 self.access_place(
1558 location,
1559 (place, span),
1560 (Shallow(af), Read(ReadKind::Copy)),
1561 LocalMutationIsAllowed::No,
1562 state,
1563 );
1564 self.check_if_path_or_subpath_is_moved(
1565 location,
1566 InitializationRequiringAction::Use,
1567 (place.as_ref(), span),
1568 state,
1569 );
1570 }
1571
1572 Rvalue::BinaryOp(_bin_op, box (operand1, operand2)) => {
1573 self.consume_operand(location, (operand1, span), state);
1574 self.consume_operand(location, (operand2, span), state);
1575 }
1576
1577 Rvalue::Aggregate(aggregate_kind, operands) => {
1578 match **aggregate_kind {
1582 AggregateKind::Closure(def_id, _)
1583 | AggregateKind::CoroutineClosure(def_id, _)
1584 | AggregateKind::Coroutine(def_id, _) => {
1585 let def_id = def_id.expect_local();
1586 let used_mut_upvars = self.root_cx.used_mut_upvars(def_id);
1587 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1587",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1587u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0:?} used_mut_upvars={1:?}",
def_id, used_mut_upvars) as &dyn Value))])
});
} else { ; }
};debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1588 for field in used_mut_upvars.clone() {
1592 self.propagate_closure_used_mut_upvar(&operands[field]);
1593 }
1594 }
1595 AggregateKind::Adt(..)
1596 | AggregateKind::Array(..)
1597 | AggregateKind::Tuple { .. }
1598 | AggregateKind::RawPtr(..) => (),
1599 }
1600
1601 for operand in operands {
1602 self.consume_operand(location, (operand, span), state);
1603 }
1604 }
1605
1606 Rvalue::WrapUnsafeBinder(op, _) => {
1607 self.consume_operand(location, (op, span), state);
1608 }
1609
1610 Rvalue::CopyForDeref(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("`CopyForDeref` in borrowck"))bug!("`CopyForDeref` in borrowck"),
1611 }
1612 }
1613
1614 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1615 let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1616 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1624 this.used_mut_upvars.push(field);
1625 return;
1626 }
1627
1628 for (place_ref, proj) in place.iter_projections().rev() {
1629 if proj == ProjectionElem::Deref {
1631 match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1632 ty::Ref(_, _, hir::Mutability::Mut) => return,
1634
1635 _ => {}
1636 }
1637 }
1638
1639 if let Some(field) = this.is_upvar_field_projection(place_ref) {
1641 this.used_mut_upvars.push(field);
1642 return;
1643 }
1644 }
1645
1646 this.used_mut.insert(place.local);
1648 };
1649
1650 match *operand {
1654 Operand::Move(place) | Operand::Copy(place) => {
1655 match place.as_local() {
1656 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1657 if self.body.local_decls[local].ty.is_mutable_ptr() {
1658 return;
1660 }
1661 let Some(temp_mpi) = self.move_data.rev_lookup.find_local(local) else {
1677 ::rustc_middle::util::bug::bug_fmt(format_args!("temporary should be tracked"));bug!("temporary should be tracked");
1678 };
1679 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1680 &self.move_data.inits[init_index]
1681 } else {
1682 ::rustc_middle::util::bug::bug_fmt(format_args!("temporary should be initialized exactly once"))bug!("temporary should be initialized exactly once")
1683 };
1684
1685 let InitLocation::Statement(loc) = init.location else {
1686 ::rustc_middle::util::bug::bug_fmt(format_args!("temporary initialized in arguments"))bug!("temporary initialized in arguments")
1687 };
1688
1689 let body = self.body;
1690 let bbd = &body[loc.block];
1691 let stmt = &bbd.statements[loc.statement_index];
1692 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1692",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1692u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("temporary assigned in: stmt={0:?}",
stmt) as &dyn Value))])
});
} else { ; }
};debug!("temporary assigned in: stmt={:?}", stmt);
1693
1694 match stmt.kind {
1695 StatementKind::Assign(box (
1696 _,
1697 Rvalue::Ref(_, _, source)
1698 | Rvalue::Use(Operand::Copy(source) | Operand::Move(source)),
1699 )) => {
1700 propagate_closure_used_mut_place(self, source);
1701 }
1702 _ => {
1703 ::rustc_middle::util::bug::bug_fmt(format_args!("closures should only capture user variables or references to user variables"));bug!(
1704 "closures should only capture user variables \
1705 or references to user variables"
1706 );
1707 }
1708 }
1709 }
1710 _ => propagate_closure_used_mut_place(self, place),
1711 }
1712 }
1713 Operand::Constant(..) | Operand::RuntimeChecks(_) => {}
1714 }
1715 }
1716
1717 fn consume_operand(
1718 &mut self,
1719 location: Location,
1720 (operand, span): (&Operand<'tcx>, Span),
1721 state: &BorrowckDomain,
1722 ) {
1723 match *operand {
1724 Operand::Copy(place) => {
1725 self.access_place(
1728 location,
1729 (place, span),
1730 (Deep, Read(ReadKind::Copy)),
1731 LocalMutationIsAllowed::No,
1732 state,
1733 );
1734
1735 self.check_if_path_or_subpath_is_moved(
1737 location,
1738 InitializationRequiringAction::Use,
1739 (place.as_ref(), span),
1740 state,
1741 );
1742 }
1743 Operand::Move(place) => {
1744 self.check_movable_place(location, place);
1746
1747 self.access_place(
1749 location,
1750 (place, span),
1751 (Deep, Write(WriteKind::Move)),
1752 LocalMutationIsAllowed::Yes,
1753 state,
1754 );
1755
1756 self.check_if_path_or_subpath_is_moved(
1758 location,
1759 InitializationRequiringAction::Use,
1760 (place.as_ref(), span),
1761 state,
1762 );
1763 }
1764 Operand::Constant(_) | Operand::RuntimeChecks(_) => {}
1765 }
1766 }
1767
1768 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_for_invalidation_at_exit",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1770u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["location", "borrow",
"span"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
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) {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1806",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1806u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_for_invalidation_at_exit({0:?}): INVALID",
place) as &dyn Value))])
});
} else { ; }
};
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)
}
}
}
}#[instrument(level = "debug", skip(self))]
1771 fn check_for_invalidation_at_exit(
1772 &mut self,
1773 location: Location,
1774 borrow: &BorrowData<'tcx>,
1775 span: Span,
1776 ) {
1777 let place = borrow.borrowed_place;
1778 let mut root_place = PlaceRef { local: place.local, projection: &[] };
1779
1780 let might_be_alive = if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1786 root_place.projection = TyCtxtConsts::DEREF_PROJECTION;
1790 true
1791 } else {
1792 false
1793 };
1794
1795 let sd = if might_be_alive { Deep } else { Shallow(None) };
1796
1797 if places_conflict::borrow_conflicts_with_place(
1798 self.infcx.tcx,
1799 self.body,
1800 place,
1801 borrow.kind,
1802 root_place,
1803 sd,
1804 places_conflict::PlaceConflictBias::Overlap,
1805 ) {
1806 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1807 let span = self.infcx.tcx.sess.source_map().end_point(span);
1810 self.report_borrowed_value_does_not_live_long_enough(
1811 location,
1812 borrow,
1813 (place, span),
1814 None,
1815 )
1816 }
1817 }
1818
1819 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1822 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1822",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1822u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_for_local_borrow({0:?})",
borrow) as &dyn Value))])
});
} else { ; }
};debug!("check_for_local_borrow({:?})", borrow);
1823
1824 if borrow_of_local_data(borrow.borrowed_place) {
1825 let err = self.cannot_borrow_across_coroutine_yield(
1826 self.retrieve_borrow_spans(borrow).var_or_use(),
1827 yield_span,
1828 );
1829
1830 self.buffer_error(err);
1831 }
1832 }
1833
1834 fn check_activations(&mut self, location: Location, span: Span, state: &BorrowckDomain) {
1835 for &borrow_index in self.borrow_set.activations_at_location(location) {
1839 let borrow = &self.borrow_set[borrow_index];
1840
1841 if !match borrow.kind {
BorrowKind::Shared | BorrowKind::Fake(_) => false,
BorrowKind::Mut { .. } => true,
} {
::core::panicking::panic("assertion failed: match borrow.kind {\n BorrowKind::Shared | BorrowKind::Fake(_) => false,\n BorrowKind::Mut { .. } => true,\n}")
};assert!(match borrow.kind {
1843 BorrowKind::Shared | BorrowKind::Fake(_) => false,
1844 BorrowKind::Mut { .. } => true,
1845 });
1846
1847 self.access_place(
1848 location,
1849 (borrow.borrowed_place, span),
1850 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1851 LocalMutationIsAllowed::No,
1852 state,
1853 );
1854 }
1858 }
1859
1860 fn check_movable_place(&mut self, location: Location, place: Place<'tcx>) {
1861 use IllegalMoveOriginKind::*;
1862
1863 let body = self.body;
1864 let tcx = self.infcx.tcx;
1865 let mut place_ty = PlaceTy::from_ty(body.local_decls[place.local].ty);
1866 for (place_ref, elem) in place.iter_projections() {
1867 match elem {
1868 ProjectionElem::Deref => match place_ty.ty.kind() {
1869 ty::Ref(..) | ty::RawPtr(..) => {
1870 self.move_errors.push(MoveError::new(
1871 place,
1872 location,
1873 BorrowedContent {
1874 target_place: place_ref.project_deeper(&[elem], tcx),
1875 },
1876 ));
1877 return;
1878 }
1879 ty::Adt(adt, _) => {
1880 if !adt.is_box() {
1881 ::rustc_middle::util::bug::bug_fmt(format_args!("Adt should be a box type when Place is deref"));bug!("Adt should be a box type when Place is deref");
1882 }
1883 }
1884 ty::Bool
1885 | ty::Char
1886 | ty::Int(_)
1887 | ty::Uint(_)
1888 | ty::Float(_)
1889 | ty::Foreign(_)
1890 | ty::Str
1891 | ty::Array(_, _)
1892 | ty::Pat(_, _)
1893 | ty::Slice(_)
1894 | ty::FnDef(_, _)
1895 | ty::FnPtr(..)
1896 | ty::Dynamic(_, _)
1897 | ty::Closure(_, _)
1898 | ty::CoroutineClosure(_, _)
1899 | ty::Coroutine(_, _)
1900 | ty::CoroutineWitness(..)
1901 | ty::Never
1902 | ty::Tuple(_)
1903 | ty::UnsafeBinder(_)
1904 | ty::Alias(_, _)
1905 | ty::Param(_)
1906 | ty::Bound(_, _)
1907 | ty::Infer(_)
1908 | ty::Error(_)
1909 | ty::Placeholder(_) => {
1910 ::rustc_middle::util::bug::bug_fmt(format_args!("When Place is Deref it\'s type shouldn\'t be {0:#?}",
place_ty))bug!("When Place is Deref it's type shouldn't be {place_ty:#?}")
1911 }
1912 },
1913 ProjectionElem::Field(_, _) => match place_ty.ty.kind() {
1914 ty::Adt(adt, _) => {
1915 if adt.has_dtor(tcx) {
1916 self.move_errors.push(MoveError::new(
1917 place,
1918 location,
1919 InteriorOfTypeWithDestructor { container_ty: place_ty.ty },
1920 ));
1921 return;
1922 }
1923 }
1924 ty::Closure(..)
1925 | ty::CoroutineClosure(..)
1926 | ty::Coroutine(_, _)
1927 | ty::Tuple(_) => (),
1928 ty::Bool
1929 | ty::Char
1930 | ty::Int(_)
1931 | ty::Uint(_)
1932 | ty::Float(_)
1933 | ty::Foreign(_)
1934 | ty::Str
1935 | ty::Array(_, _)
1936 | ty::Pat(_, _)
1937 | ty::Slice(_)
1938 | ty::RawPtr(_, _)
1939 | ty::Ref(_, _, _)
1940 | ty::FnDef(_, _)
1941 | ty::FnPtr(..)
1942 | ty::Dynamic(_, _)
1943 | ty::CoroutineWitness(..)
1944 | ty::Never
1945 | ty::UnsafeBinder(_)
1946 | ty::Alias(_, _)
1947 | ty::Param(_)
1948 | ty::Bound(_, _)
1949 | ty::Infer(_)
1950 | ty::Error(_)
1951 | ty::Placeholder(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("When Place contains ProjectionElem::Field it\'s type shouldn\'t be {0:#?}",
place_ty))bug!(
1952 "When Place contains ProjectionElem::Field it's type shouldn't be {place_ty:#?}"
1953 ),
1954 },
1955 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
1956 match place_ty.ty.kind() {
1957 ty::Slice(_) => {
1958 self.move_errors.push(MoveError::new(
1959 place,
1960 location,
1961 InteriorOfSliceOrArray { ty: place_ty.ty, is_index: false },
1962 ));
1963 return;
1964 }
1965 ty::Array(_, _) => (),
1966 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected type {0:#?}",
place_ty.ty))bug!("Unexpected type {:#?}", place_ty.ty),
1967 }
1968 }
1969 ProjectionElem::Index(_) => match place_ty.ty.kind() {
1970 ty::Array(..) | ty::Slice(..) => {
1971 self.move_errors.push(MoveError::new(
1972 place,
1973 location,
1974 InteriorOfSliceOrArray { ty: place_ty.ty, is_index: true },
1975 ));
1976 return;
1977 }
1978 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected type {0:#?}",
place_ty))bug!("Unexpected type {place_ty:#?}"),
1979 },
1980 ProjectionElem::OpaqueCast(_)
1984 | ProjectionElem::Downcast(_, _)
1985 | ProjectionElem::UnwrapUnsafeBinder(_) => (),
1986 }
1987
1988 place_ty = place_ty.projection_ty(tcx, elem);
1989 }
1990 }
1991
1992 fn check_if_full_path_is_moved(
1993 &mut self,
1994 location: Location,
1995 desired_action: InitializationRequiringAction,
1996 place_span: (PlaceRef<'tcx>, Span),
1997 state: &BorrowckDomain,
1998 ) {
1999 let maybe_uninits = &state.uninits;
2000
2001 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2036",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2036u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_if_full_path_is_moved place: {0:?}",
place_span.0) as &dyn Value))])
});
} else { ; }
};debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
2037 let (prefix, mpi) = self.move_path_closest_to(place_span.0);
2038 if maybe_uninits.contains(mpi) {
2039 self.report_use_of_moved_or_uninitialized(
2040 location,
2041 desired_action,
2042 (prefix, place_span.0, place_span.1),
2043 mpi,
2044 );
2045 } }
2052
2053 fn check_if_subslice_element_is_moved(
2059 &mut self,
2060 location: Location,
2061 desired_action: InitializationRequiringAction,
2062 place_span: (PlaceRef<'tcx>, Span),
2063 maybe_uninits: &MixedBitSet<MovePathIndex>,
2064 from: u64,
2065 to: u64,
2066 ) {
2067 if let Some(mpi) = self.move_path_for_place(place_span.0) {
2068 let move_paths = &self.move_data.move_paths;
2069
2070 let root_path = &move_paths[mpi];
2071 for (child_mpi, child_move_path) in root_path.children(move_paths) {
2072 let last_proj = child_move_path.place.projection.last().unwrap();
2073 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
2074 if true {
if !!from_end {
{
::core::panicking::panic_fmt(format_args!("Array constant indexing shouldn\'t be `from_end`."));
}
};
};debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
2075
2076 if (from..to).contains(offset) {
2077 let uninit_child =
2078 self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
2079 maybe_uninits.contains(mpi)
2080 });
2081
2082 if let Some(uninit_child) = uninit_child {
2083 self.report_use_of_moved_or_uninitialized(
2084 location,
2085 desired_action,
2086 (place_span.0, place_span.0, place_span.1),
2087 uninit_child,
2088 );
2089 return; }
2091 }
2092 }
2093 }
2094 }
2095 }
2096
2097 fn check_if_path_or_subpath_is_moved(
2098 &mut self,
2099 location: Location,
2100 desired_action: InitializationRequiringAction,
2101 place_span: (PlaceRef<'tcx>, Span),
2102 state: &BorrowckDomain,
2103 ) {
2104 let maybe_uninits = &state.uninits;
2105
2106 self.check_if_full_path_is_moved(location, desired_action, place_span, state);
2122
2123 if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
2124 place_span.0.last_projection()
2125 {
2126 let place_ty = place_base.ty(self.body(), self.infcx.tcx);
2127 if let ty::Array(..) = place_ty.ty.kind() {
2128 self.check_if_subslice_element_is_moved(
2129 location,
2130 desired_action,
2131 (place_base, place_span.1),
2132 maybe_uninits,
2133 from,
2134 to,
2135 );
2136 return;
2137 }
2138 }
2139
2140 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2149",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2149u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_if_path_or_subpath_is_moved place: {0:?}",
place_span.0) as &dyn Value))])
});
} else { ; }
};debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
2150 if let Some(mpi) = self.move_path_for_place(place_span.0) {
2151 let uninit_mpi = self
2152 .move_data
2153 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
2154
2155 if let Some(uninit_mpi) = uninit_mpi {
2156 self.report_use_of_moved_or_uninitialized(
2157 location,
2158 desired_action,
2159 (place_span.0, place_span.0, place_span.1),
2160 uninit_mpi,
2161 );
2162 return; }
2164 }
2165 }
2166
2167 fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
2178 match self.move_data.rev_lookup.find(place) {
2179 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
2180 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
2181 }
2182 LookupResult::Parent(None) => {
::core::panicking::panic_fmt(format_args!("should have move path for every Local"));
}panic!("should have move path for every Local"),
2183 }
2184 }
2185
2186 fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
2187 match self.move_data.rev_lookup.find(place) {
2192 LookupResult::Parent(_) => None,
2193 LookupResult::Exact(mpi) => Some(mpi),
2194 }
2195 }
2196
2197 fn check_if_assigned_path_is_moved(
2198 &mut self,
2199 location: Location,
2200 (place, span): (Place<'tcx>, Span),
2201 state: &BorrowckDomain,
2202 ) {
2203 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2203",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2203u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_if_assigned_path_is_moved place: {0:?}",
place) as &dyn Value))])
});
} else { ; }
};debug!("check_if_assigned_path_is_moved place: {:?}", place);
2204
2205 for (place_base, elem) in place.iter_projections().rev() {
2207 match elem {
2208 ProjectionElem::Index(_) |
2209 ProjectionElem::OpaqueCast(_) |
2210 ProjectionElem::ConstantIndex { .. } |
2211 ProjectionElem::Downcast(_, _) =>
2213 { }
2217
2218 ProjectionElem::UnwrapUnsafeBinder(_) => {
2219 check_parent_of_field(self, location, place_base, span, state);
2220 }
2221
2222 ProjectionElem::Deref => {
2224 self.check_if_full_path_is_moved(
2225 location, InitializationRequiringAction::Use,
2226 (place_base, span), state);
2227 break;
2230 }
2231
2232 ProjectionElem::Subslice { .. } => {
2233 {
::core::panicking::panic_fmt(format_args!("we don\'t allow assignments to subslices, location: {0:?}",
location));
};panic!("we don't allow assignments to subslices, location: {location:?}");
2234 }
2235
2236 ProjectionElem::Field(..) => {
2237 let tcx = self.infcx.tcx;
2241 let base_ty = place_base.ty(self.body(), tcx).ty;
2242 match base_ty.kind() {
2243 ty::Adt(def, _) if def.has_dtor(tcx) => {
2244 self.check_if_path_or_subpath_is_moved(
2245 location, InitializationRequiringAction::Assignment,
2246 (place_base, span), state);
2247
2248 break;
2251 }
2252
2253 ty::Adt(..) | ty::Tuple(..) => {
2256 check_parent_of_field(self, location, place_base, span, state);
2257 }
2258
2259 _ => {}
2260 }
2261 }
2262 }
2263 }
2264
2265 fn check_parent_of_field<'a, 'tcx>(
2266 this: &mut MirBorrowckCtxt<'a, '_, 'tcx>,
2267 location: Location,
2268 base: PlaceRef<'tcx>,
2269 span: Span,
2270 state: &BorrowckDomain,
2271 ) {
2272 let maybe_uninits = &state.uninits;
2304
2305 let mut shortest_uninit_seen = None;
2308 for prefix in this.prefixes(base, PrefixSet::Shallow) {
2309 let Some(mpi) = this.move_path_for_place(prefix) else { continue };
2310
2311 if maybe_uninits.contains(mpi) {
2312 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2312",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2312u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_parent_of_field updating shortest_uninit_seen from {0:?} to {1:?}",
shortest_uninit_seen, Some((prefix, mpi))) as &dyn Value))])
});
} else { ; }
};debug!(
2313 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
2314 shortest_uninit_seen,
2315 Some((prefix, mpi))
2316 );
2317 shortest_uninit_seen = Some((prefix, mpi));
2318 } else {
2319 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2319",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2319u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_parent_of_field {0:?} is definitely initialized",
(prefix, mpi)) as &dyn Value))])
});
} else { ; }
};debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
2320 }
2321 }
2322
2323 if let Some((prefix, mpi)) = shortest_uninit_seen {
2324 let tcx = this.infcx.tcx;
2330 if base.ty(this.body(), tcx).ty.is_union()
2331 && this.move_data.path_map[mpi].iter().any(|moi| {
2332 this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
2333 })
2334 {
2335 return;
2336 }
2337
2338 this.report_use_of_moved_or_uninitialized(
2339 location,
2340 InitializationRequiringAction::PartialAssignment,
2341 (prefix, base, span),
2342 mpi,
2343 );
2344
2345 this.used_mut.insert(base.local);
2349 }
2350 }
2351 }
2352
2353 fn check_access_permissions(
2357 &mut self,
2358 (place, span): (Place<'tcx>, Span),
2359 kind: ReadOrWrite,
2360 is_local_mutation_allowed: LocalMutationIsAllowed,
2361 state: &BorrowckDomain,
2362 location: Location,
2363 ) -> bool {
2364 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2364",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2364u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_access_permissions({0:?}, {1:?}, is_local_mutation_allowed: {2:?})",
place, kind, is_local_mutation_allowed) as &dyn Value))])
});
} else { ; }
};debug!(
2365 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
2366 place, kind, is_local_mutation_allowed
2367 );
2368
2369 let error_access;
2370 let the_place_err;
2371
2372 match kind {
2373 Reservation(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind }))
2374 | Write(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind })) => {
2375 let is_local_mutation_allowed = match mut_borrow_kind {
2376 MutBorrowKind::ClosureCapture => LocalMutationIsAllowed::Yes,
2380 MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow => {
2381 is_local_mutation_allowed
2382 }
2383 };
2384 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2385 Ok(root_place) => {
2386 self.add_used_mut(root_place, state);
2387 return false;
2388 }
2389 Err(place_err) => {
2390 error_access = AccessKind::MutableBorrow;
2391 the_place_err = place_err;
2392 }
2393 }
2394 }
2395 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
2396 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2397 Ok(root_place) => {
2398 self.add_used_mut(root_place, state);
2399 return false;
2400 }
2401 Err(place_err) => {
2402 error_access = AccessKind::Mutate;
2403 the_place_err = place_err;
2404 }
2405 }
2406 }
2407
2408 Reservation(
2409 WriteKind::Move
2410 | WriteKind::Replace
2411 | WriteKind::StorageDeadOrDrop
2412 | WriteKind::MutableBorrow(BorrowKind::Shared)
2413 | WriteKind::MutableBorrow(BorrowKind::Fake(_)),
2414 )
2415 | Write(
2416 WriteKind::Move
2417 | WriteKind::Replace
2418 | WriteKind::StorageDeadOrDrop
2419 | WriteKind::MutableBorrow(BorrowKind::Shared)
2420 | WriteKind::MutableBorrow(BorrowKind::Fake(_)),
2421 ) => {
2422 if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err()
2423 && !self.has_buffered_diags()
2424 {
2425 self.dcx().span_delayed_bug(
2431 span,
2432 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Accessing `{0:?}` with the kind `{1:?}` shouldn\'t be possible",
place, kind))
})format!(
2433 "Accessing `{place:?}` with the kind `{kind:?}` shouldn't be possible",
2434 ),
2435 );
2436 }
2437 return false;
2438 }
2439 Activation(..) => {
2440 return false;
2442 }
2443 Read(
2444 ReadKind::Borrow(BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_))
2445 | ReadKind::Copy,
2446 ) => {
2447 return false;
2449 }
2450 }
2451
2452 let previously_initialized = self.is_local_ever_initialized(place.local, state);
2457
2458 if let Some(init_index) = previously_initialized {
2460 if let (AccessKind::Mutate, Some(_)) = (error_access, place.as_local()) {
2461 let init = &self.move_data.inits[init_index];
2464 let assigned_span = init.span(self.body);
2465 self.report_illegal_reassignment((place, span), assigned_span, place);
2466 } else {
2467 self.report_mutability_error(place, span, the_place_err, error_access, location)
2468 }
2469 true
2470 } else {
2471 false
2472 }
2473 }
2474
2475 fn is_local_ever_initialized(&self, local: Local, state: &BorrowckDomain) -> Option<InitIndex> {
2476 let mpi = self.move_data.rev_lookup.find_local(local)?;
2477 let ii = &self.move_data.init_path_map[mpi];
2478 ii.into_iter().find(|&&index| state.ever_inits.contains(index)).copied()
2479 }
2480
2481 fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, state: &BorrowckDomain) {
2483 match root_place {
2484 RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2485 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2489 && self.is_local_ever_initialized(local, state).is_some()
2490 {
2491 self.used_mut.insert(local);
2492 }
2493 }
2494 RootPlace {
2495 place_local: _,
2496 place_projection: _,
2497 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2498 } => {}
2499 RootPlace {
2500 place_local,
2501 place_projection: place_projection @ [.., _],
2502 is_local_mutation_allowed: _,
2503 } => {
2504 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2505 local: place_local,
2506 projection: place_projection,
2507 }) {
2508 self.used_mut_upvars.push(field);
2509 }
2510 }
2511 }
2512 }
2513
2514 fn is_mutable(
2517 &self,
2518 place: PlaceRef<'tcx>,
2519 is_local_mutation_allowed: LocalMutationIsAllowed,
2520 ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2521 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2521",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2521u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("is_mutable: place={0:?}, is_local...={1:?}",
place, is_local_mutation_allowed) as &dyn Value))])
});
} else { ; }
};debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2522 match place.last_projection() {
2523 None => {
2524 let local = &self.body.local_decls[place.local];
2525 match local.mutability {
2526 Mutability::Not => match is_local_mutation_allowed {
2527 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2528 place_local: place.local,
2529 place_projection: place.projection,
2530 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2531 }),
2532 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2533 place_local: place.local,
2534 place_projection: place.projection,
2535 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2536 }),
2537 LocalMutationIsAllowed::No => Err(place),
2538 },
2539 Mutability::Mut => Ok(RootPlace {
2540 place_local: place.local,
2541 place_projection: place.projection,
2542 is_local_mutation_allowed,
2543 }),
2544 }
2545 }
2546 Some((place_base, elem)) => {
2547 match elem {
2548 ProjectionElem::Deref => {
2549 let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2550
2551 match base_ty.kind() {
2553 ty::Ref(_, _, mutbl) => {
2554 match mutbl {
2555 hir::Mutability::Not => Err(place),
2557 hir::Mutability::Mut => {
2560 let mode = match self.is_upvar_field_projection(place) {
2561 Some(field)
2562 if self.upvars[field.index()].is_by_ref() =>
2563 {
2564 is_local_mutation_allowed
2565 }
2566 _ => LocalMutationIsAllowed::Yes,
2567 };
2568
2569 self.is_mutable(place_base, mode)
2570 }
2571 }
2572 }
2573 ty::RawPtr(_, mutbl) => {
2574 match mutbl {
2575 hir::Mutability::Not => Err(place),
2577 hir::Mutability::Mut => Ok(RootPlace {
2580 place_local: place.local,
2581 place_projection: place.projection,
2582 is_local_mutation_allowed,
2583 }),
2584 }
2585 }
2586 _ if base_ty.is_box() => {
2588 self.is_mutable(place_base, is_local_mutation_allowed)
2589 }
2590 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Deref of unexpected type: {0:?}",
base_ty))bug!("Deref of unexpected type: {:?}", base_ty),
2592 }
2593 }
2594 ProjectionElem::Field(FieldIdx::ZERO, _)
2597 if let Some(adt) =
2598 place_base.ty(self.body(), self.infcx.tcx).ty.ty_adt_def()
2599 && adt.is_pin()
2600 && self.infcx.tcx.features().pin_ergonomics() =>
2601 {
2602 self.is_mutable(place_base, is_local_mutation_allowed)
2603 }
2604 ProjectionElem::Field(..)
2607 | ProjectionElem::Index(..)
2608 | ProjectionElem::ConstantIndex { .. }
2609 | ProjectionElem::Subslice { .. }
2610 | ProjectionElem::OpaqueCast { .. }
2611 | ProjectionElem::Downcast(..)
2612 | ProjectionElem::UnwrapUnsafeBinder(_) => {
2613 let upvar_field_projection = self.is_upvar_field_projection(place);
2614 if let Some(field) = upvar_field_projection {
2615 let upvar = &self.upvars[field.index()];
2616 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2616",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2616u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("is_mutable: upvar.mutability={0:?} local_mutation_is_allowed={1:?} place={2:?}, place_base={3:?}",
upvar, is_local_mutation_allowed, place, place_base) as
&dyn Value))])
});
} else { ; }
};debug!(
2617 "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2618 place={:?}, place_base={:?}",
2619 upvar, is_local_mutation_allowed, place, place_base
2620 );
2621 match (upvar.mutability, is_local_mutation_allowed) {
2622 (
2623 Mutability::Not,
2624 LocalMutationIsAllowed::No
2625 | LocalMutationIsAllowed::ExceptUpvars,
2626 ) => Err(place),
2627 (Mutability::Not, LocalMutationIsAllowed::Yes)
2628 | (Mutability::Mut, _) => {
2629 let _ =
2648 self.is_mutable(place_base, is_local_mutation_allowed)?;
2649 Ok(RootPlace {
2650 place_local: place.local,
2651 place_projection: place.projection,
2652 is_local_mutation_allowed,
2653 })
2654 }
2655 }
2656 } else {
2657 self.is_mutable(place_base, is_local_mutation_allowed)
2658 }
2659 }
2660 }
2661 }
2662 }
2663 }
2664
2665 fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<FieldIdx> {
2670 path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2671 }
2672
2673 fn dominators(&self) -> &Dominators<BasicBlock> {
2674 self.body.basic_blocks.dominators()
2676 }
2677
2678 fn lint_unused_mut(&self) {
2679 let tcx = self.infcx.tcx;
2680 let body = self.body;
2681 for local in body.mut_vars_and_args_iter().filter(|local| !self.used_mut.contains(local)) {
2682 let local_decl = &body.local_decls[local];
2683 let ClearCrossCrate::Set(SourceScopeLocalData { lint_root, .. }) =
2684 body.source_scopes[local_decl.source_info.scope].local_data
2685 else {
2686 continue;
2687 };
2688
2689 if self.local_excluded_from_unused_mut_lint(local) {
2691 continue;
2692 }
2693
2694 let span = local_decl.source_info.span;
2695 if span.desugaring_kind().is_some() {
2696 continue;
2698 }
2699
2700 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
2701
2702 tcx.emit_node_span_lint(UNUSED_MUT, lint_root, span, VarNeedNotMut { span: mut_span })
2703 }
2704 }
2705}
2706
2707enum Overlap {
2709 Arbitrary,
2715 EqualOrDisjoint,
2720 Disjoint,
2723}