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