1#![allow(internal_features)]
5#![feature(default_field_values)]
6#![feature(deref_patterns)]
7#![feature(file_buffered)]
8#![feature(negative_impls)]
9#![feature(never_type)]
10#![feature(option_into_flat_iter)]
11#![feature(rustc_attrs)]
12#![feature(stmt_expr_attributes)]
13#![feature(try_blocks)]
14use std::borrow::Cow;
17use std::cell::{OnceCell, RefCell};
18use std::marker::PhantomData;
19use std::ops::{ControlFlow, Deref};
20use std::rc::Rc;
21
22use borrow_set::LocalsStateAtExit;
23use polonius_engine::AllFacts;
24use root_cx::BorrowCheckRootCtxt;
25use rustc_abi::FieldIdx;
26use rustc_data_structures::frozen::Frozen;
27use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
28use rustc_data_structures::graph::dominators::Dominators;
29use rustc_hir as hir;
30use rustc_hir::CRATE_HIR_ID;
31use rustc_hir::def_id::LocalDefId;
32use rustc_index::bit_set::MixedBitSet;
33use rustc_index::{IndexSlice, IndexVec};
34use rustc_infer::infer::outlives::env::RegionBoundPairs;
35use rustc_infer::infer::{
36 InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin, TyCtxtInferExt,
37};
38use rustc_middle::mir::*;
39use rustc_middle::query::Providers;
40use rustc_middle::ty::{
41 self, ParamEnv, RegionUtilitiesExt, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitable,
42 TypingMode, fold_regions,
43};
44use rustc_middle::{bug, span_bug};
45use rustc_mir_dataflow::impls::{EverInitializedPlaces, MaybeUninitializedPlaces};
46use rustc_mir_dataflow::move_paths::{
47 InitIndex, InitLocation, LookupResult, MoveData, MovePathIndex,
48};
49use rustc_mir_dataflow::points::DenseLocationMap;
50use rustc_mir_dataflow::{Analysis, EntryStates, Results, ResultsVisitor, visit_results};
51use rustc_session::lint::builtin::{TAIL_EXPR_DROP_ORDER, UNUSED_MUT};
52use rustc_span::{ErrorGuaranteed, Span, Symbol};
53use rustc_trait_selection::traits::query::type_op::{QueryTypeOp, TypeOp, TypeOpOutput};
54use smallvec::SmallVec;
55use tracing::{debug, instrument};
56
57use crate::borrow_set::{BorrowData, BorrowSet};
58use crate::consumers::{BodyWithBorrowckFacts, RustcFacts};
59use crate::dataflow::{BorrowIndex, Borrowck, BorrowckDomain, Borrows};
60use crate::diagnostics::{
61 AccessKind, BorrowckDiagnosticsBuffer, IllegalMoveOriginKind, MoveError, RegionName,
62};
63use crate::path_utils::*;
64use crate::place_ext::PlaceExt;
65use crate::places_conflict::{PlaceConflictBias, places_conflict};
66use crate::polonius::PoloniusContext;
67use crate::polonius::legacy::{
68 PoloniusFacts, PoloniusFactsExt, PoloniusLocationTable, PoloniusOutput,
69};
70use crate::prefixes::PrefixSet;
71use crate::region_infer::RegionInferenceContext;
72use crate::region_infer::opaque_types::DeferredOpaqueTypeError;
73use crate::renumber::RegionCtxt;
74use crate::session_diagnostics::VarNeedNotMut;
75use crate::type_check::free_region_relations::UniversalRegionRelations;
76use crate::type_check::{Locations, MirTypeckRegionConstraints, MirTypeckResults};
77
78mod borrow_set;
79mod borrowck_errors;
80mod constraints;
81mod dataflow;
82mod def_use;
83mod diagnostics;
84mod handle_placeholders;
85mod nll;
86mod path_utils;
87mod place_ext;
88mod places_conflict;
89mod polonius;
90mod prefixes;
91mod region_infer;
92mod renumber;
93mod root_cx;
94mod session_diagnostics;
95mod type_check;
96mod universal_regions;
97mod used_muts;
98
99pub mod consumers;
101
102struct TyCtxtConsts<'tcx>(PhantomData<&'tcx ()>);
104
105impl<'tcx> TyCtxtConsts<'tcx> {
106 const DEREF_PROJECTION: &'tcx [PlaceElem<'tcx>; 1] = &[ProjectionElem::Deref];
107}
108
109pub fn provide(providers: &mut Providers) {
110 *providers = Providers { mir_borrowck, ..*providers };
111}
112
113fn mir_borrowck(
117 tcx: TyCtxt<'_>,
118 def: LocalDefId,
119) -> Result<&FxIndexMap<LocalDefId, ty::DefinitionSiteHiddenType<'_>>, ErrorGuaranteed> {
120 if !!tcx.is_typeck_child(def.to_def_id()) {
::core::panicking::panic("assertion failed: !tcx.is_typeck_child(def.to_def_id())")
};assert!(!tcx.is_typeck_child(def.to_def_id()));
121 if tcx.is_trivial_const(def) {
122 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:122",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(122u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Skipping borrowck because of trivial const")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("Skipping borrowck because of trivial const");
123 let opaque_types = Default::default();
124 return Ok(tcx.arena.alloc(opaque_types));
125 }
126 let (input_body, _) = tcx.mir_promoted(def);
127 {
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:127",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(127u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("run query mir_borrowck: {0}",
tcx.def_path_str(def)) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("run query mir_borrowck: {}", tcx.def_path_str(def));
128
129 tcx.ensure_result().check_coroutine_obligations(def)?;
133
134 let input_body: &Body<'_> = &input_body.borrow();
135 if let Some(guar) = input_body.tainted_by_errors {
136 {
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:136",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(136u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Skipping borrowck because of tainted body")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("Skipping borrowck because of tainted body");
137 Err(guar)
138 } else if input_body.should_skip() {
139 {
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:139",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(139u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Skipping borrowck because of injected body")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("Skipping borrowck because of injected body");
140 let opaque_types = Default::default();
141 Ok(tcx.arena.alloc(opaque_types))
142 } else {
143 let tainted_by_errors = Default::default();
144 let mut root_cx = BorrowCheckRootCtxt::new(tcx, def, None, &tainted_by_errors);
145 root_cx.do_mir_borrowck();
146 root_cx.finalize()
147 }
148}
149
150#[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)]
153struct PropagatedBorrowCheckResults<'tcx> {
154 closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
155 used_mut_upvars: SmallVec<[FieldIdx; 8]>,
156}
157
158type DeferredClosureRequirements<'tcx> = Vec<(LocalDefId, ty::GenericArgsRef<'tcx>, Locations)>;
159
160#[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)]
203pub struct ClosureRegionRequirements<'tcx> {
204 pub num_external_vids: usize,
210
211 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
214}
215
216#[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)]
219pub struct ClosureOutlivesRequirement<'tcx> {
220 pub subject: ClosureOutlivesSubject<'tcx>,
222
223 pub outlived_free_region: ty::RegionVid,
225
226 pub blame_span: Span,
228
229 pub category: ConstraintCategory<'tcx>,
231}
232
233#[cfg(target_pointer_width = "64")]
235const _: [(); 16] = [(); ::std::mem::size_of::<ConstraintCategory<'_>>()];rustc_data_structures::static_assert_size!(ConstraintCategory<'_>, 16);
236
237#[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)]
240pub enum ClosureOutlivesSubject<'tcx> {
241 Ty(ClosureOutlivesSubjectTy<'tcx>),
245
246 Region(ty::RegionVid),
249}
250
251#[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)]
257pub struct ClosureOutlivesSubjectTy<'tcx> {
258 inner: Ty<'tcx>,
259}
260impl<'tcx, I> !TypeVisitable<I> for ClosureOutlivesSubjectTy<'tcx> {}
263impl<'tcx, I> !TypeFoldable<I> for ClosureOutlivesSubjectTy<'tcx> {}
264
265impl<'tcx> ClosureOutlivesSubjectTy<'tcx> {
266 pub fn bind(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Self {
269 let inner = fold_regions(tcx, ty, |r, depth| match r.kind() {
270 ty::ReVar(vid) => {
271 let br = ty::BoundRegion {
272 var: ty::BoundVar::from_usize(vid.index()),
273 kind: ty::BoundRegionKind::Anon,
274 };
275 ty::Region::new_bound(tcx, depth, br)
276 }
277 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected region in ClosureOutlivesSubjectTy: {0:?}",
r))bug!("unexpected region in ClosureOutlivesSubjectTy: {r:?}"),
278 });
279
280 Self { inner }
281 }
282
283 pub fn instantiate(
284 self,
285 tcx: TyCtxt<'tcx>,
286 mut map: impl FnMut(ty::RegionVid) -> ty::Region<'tcx>,
287 ) -> Ty<'tcx> {
288 fold_regions(tcx, self.inner, |r, depth| match r.kind() {
289 ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn), br) => {
290 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);
291 map(ty::RegionVid::from_usize(br.var.index()))
292 }
293 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected region {0:?}", r))bug!("unexpected region {r:?}"),
294 })
295 }
296}
297
298struct CollectRegionConstraintsResult<'tcx> {
299 infcx: BorrowckInferCtxt<'tcx>,
300 body_owned: Body<'tcx>,
301 promoted: IndexVec<Promoted, Body<'tcx>>,
302 move_data: MoveData<'tcx>,
303 borrow_set: BorrowSet<'tcx>,
304 location_table: PoloniusLocationTable,
305 location_map: Rc<DenseLocationMap>,
306 universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
307 region_bound_pairs: Frozen<RegionBoundPairs<'tcx>>,
308 known_type_outlives_obligations: Frozen<Vec<ty::PolyTypeOutlivesPredicate<'tcx>>>,
309 constraints: MirTypeckRegionConstraints<'tcx>,
310 deferred_closure_requirements: DeferredClosureRequirements<'tcx>,
311 deferred_opaque_type_errors: Vec<DeferredOpaqueTypeError<'tcx>>,
312 polonius_facts: Option<AllFacts<RustcFacts>>,
313 polonius_context: Option<PoloniusContext>,
314}
315
316fn borrowck_collect_region_constraints<'tcx>(
320 root_cx: &mut BorrowCheckRootCtxt<'_, 'tcx>,
321 def: LocalDefId,
322) -> CollectRegionConstraintsResult<'tcx> {
323 let tcx = root_cx.tcx;
324 let infcx = BorrowckInferCtxt::new(tcx, def, root_cx.root_def_id());
325 let (input_body, promoted) = tcx.mir_promoted(def);
326 let input_body: &Body<'_> = &input_body.borrow();
327 let input_promoted: &IndexSlice<_, _> = &promoted.borrow();
328 if let Some(e) = input_body.tainted_by_errors {
329 infcx.set_tainted_by_errors(e);
330 }
331
332 let mut body_owned = input_body.clone();
337 let mut promoted = input_promoted.to_owned();
338 let universal_regions = nll::replace_regions_in_mir(&infcx, &mut body_owned, &mut promoted);
339 let body = &body_owned; let location_table = PoloniusLocationTable::new(body);
342
343 let move_data = MoveData::gather_moves(body, tcx, |_| true);
344
345 let locals_are_invalidated_at_exit = tcx.hir_body_owner_kind(def).is_fn_or_closure();
346 let borrow_set = BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &move_data);
347
348 let location_map = Rc::new(DenseLocationMap::new(body));
349
350 let polonius_input = root_cx.consumer.as_ref().map_or(false, |c| c.polonius_input())
351 || infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled();
352 let mut polonius_facts =
353 (polonius_input || PoloniusFacts::enabled(infcx.tcx)).then_some(PoloniusFacts::default());
354
355 let MirTypeckResults {
357 constraints,
358 universal_region_relations,
359 region_bound_pairs,
360 known_type_outlives_obligations,
361 deferred_closure_requirements,
362 polonius_context,
363 } = type_check::type_check(
364 root_cx,
365 &infcx,
366 body,
367 &promoted,
368 universal_regions,
369 &location_table,
370 &borrow_set,
371 &mut polonius_facts,
372 &move_data,
373 Rc::clone(&location_map),
374 );
375
376 CollectRegionConstraintsResult {
377 infcx,
378 body_owned,
379 promoted,
380 move_data,
381 borrow_set,
382 location_table,
383 location_map,
384 universal_region_relations,
385 region_bound_pairs,
386 known_type_outlives_obligations,
387 constraints,
388 deferred_closure_requirements,
389 deferred_opaque_type_errors: Default::default(),
390 polonius_facts,
391 polonius_context,
392 }
393}
394
395fn borrowck_check_region_constraints<'diag, 'tcx>(
399 root_cx: &mut BorrowCheckRootCtxt<'diag, 'tcx>,
400 diags_buffer: &mut BorrowckDiagnosticsBuffer<'diag, 'tcx>,
401 CollectRegionConstraintsResult {
402 infcx,
403 body_owned,
404 promoted,
405 move_data,
406 borrow_set,
407 location_table,
408 location_map,
409 universal_region_relations,
410 region_bound_pairs: _,
411 known_type_outlives_obligations: _,
412 constraints,
413 deferred_closure_requirements,
414 deferred_opaque_type_errors,
415 polonius_facts,
416 polonius_context,
417 }: CollectRegionConstraintsResult<'tcx>,
418) -> PropagatedBorrowCheckResults<'tcx> {
419 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());
420 if !deferred_closure_requirements.is_empty() {
::core::panicking::panic("assertion failed: deferred_closure_requirements.is_empty()")
};assert!(deferred_closure_requirements.is_empty());
421 let tcx = root_cx.tcx;
422 let body = &body_owned;
423 let def = body.source.def_id().expect_local();
424
425 let nll::NllOutput {
428 regioncx,
429 polonius_input,
430 polonius_output,
431 opt_closure_req,
432 nll_errors,
433 polonius_context,
434 } = nll::compute_regions(
435 root_cx,
436 &infcx,
437 body,
438 &location_table,
439 &move_data,
440 &borrow_set,
441 location_map,
442 universal_region_relations,
443 constraints,
444 polonius_facts,
445 polonius_context,
446 );
447
448 nll::dump_nll_mir(&infcx, body, ®ioncx, &opt_closure_req, &borrow_set);
451 polonius::dump_polonius_mir(
452 &infcx,
453 body,
454 ®ioncx,
455 &opt_closure_req,
456 &borrow_set,
457 polonius_context.as_ref(),
458 );
459
460 nll::dump_annotation(&infcx, body, ®ioncx, &opt_closure_req);
463
464 let movable_coroutine = body.coroutine.is_some()
465 && tcx.coroutine_movability(def.to_def_id()) == hir::Movability::Movable;
466
467 for promoted_body in &promoted {
470 use rustc_middle::mir::visit::Visitor;
471 let move_data = MoveData::gather_moves(promoted_body, tcx, |_| true);
475 let mut promoted_mbcx = MirBorrowckCtxt {
476 root_cx,
477 infcx: &infcx,
478 body: promoted_body,
479 move_data: &move_data,
480 location_table: &location_table,
482 movable_coroutine,
483 fn_self_span_reported: Default::default(),
484 access_place_error_reported: Default::default(),
485 reservation_error_reported: Default::default(),
486 uninitialized_error_reported: Default::default(),
487 regioncx: ®ioncx,
488 used_mut: Default::default(),
489 used_mut_upvars: SmallVec::new(),
490 borrow_set: &borrow_set,
491 upvars: &[],
492 local_names: OnceCell::from(IndexVec::from_elem(None, &promoted_body.local_decls)),
493 region_names: RefCell::default(),
494 next_region_name: RefCell::new(1),
495 polonius_output: None,
496 move_errors: Vec::new(),
497 diags_buffer,
498 polonius_context: polonius_context.as_ref(),
499 };
500 struct MoveVisitor<'a, 'b, 'diag, 'tcx> {
501 ctxt: &'a mut MirBorrowckCtxt<'b, 'diag, 'tcx>,
502 }
503
504 impl<'tcx> Visitor<'tcx> for MoveVisitor<'_, '_, '_, 'tcx> {
505 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
506 if let Operand::Move(place) = operand {
507 self.ctxt.check_movable_place(location, *place);
508 }
509 }
510 }
511 MoveVisitor { ctxt: &mut promoted_mbcx }.visit_body(promoted_body);
512 promoted_mbcx.report_move_errors();
513 }
514
515 let mut mbcx = MirBorrowckCtxt {
516 root_cx,
517 infcx: &infcx,
518 body,
519 move_data: &move_data,
520 location_table: &location_table,
521 movable_coroutine,
522 fn_self_span_reported: Default::default(),
523 access_place_error_reported: Default::default(),
524 reservation_error_reported: Default::default(),
525 uninitialized_error_reported: Default::default(),
526 regioncx: ®ioncx,
527 used_mut: Default::default(),
528 used_mut_upvars: SmallVec::new(),
529 borrow_set: &borrow_set,
530 upvars: tcx.closure_captures(def),
531 local_names: OnceCell::new(),
532 region_names: RefCell::default(),
533 next_region_name: RefCell::new(1),
534 move_errors: Vec::new(),
535 diags_buffer,
536 polonius_output: polonius_output.as_deref(),
537 polonius_context: polonius_context.as_ref(),
538 };
539
540 if nll_errors.is_empty() {
542 mbcx.report_opaque_type_errors(deferred_opaque_type_errors);
543 } else {
544 mbcx.report_region_errors(nll_errors);
545 }
546
547 let flow_results = get_flow_results(tcx, body, &move_data, &borrow_set, ®ioncx);
548 visit_results(
549 body,
550 traversal::reverse_postorder(body).map(|(bb, _)| bb),
551 &flow_results,
552 &mut mbcx,
553 );
554
555 mbcx.report_move_errors();
556
557 let temporary_used_locals: FxIndexSet<Local> = mbcx
563 .used_mut
564 .iter()
565 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
566 .cloned()
567 .collect();
568 let unused_mut_locals =
572 mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
573 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
574
575 {
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:575",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(575u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("mbcx.used_mut: {0:?}",
mbcx.used_mut) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
576 mbcx.lint_unused_mut();
577
578 let result = PropagatedBorrowCheckResults {
579 closure_requirements: opt_closure_req,
580 used_mut_upvars: mbcx.used_mut_upvars,
581 };
582
583 if let Some(guar) = infcx.tainted_by_errors() {
584 root_cx.set_tainted_by_errors(guar);
585 }
586
587 if let Some(consumer) = &mut root_cx.consumer {
588 consumer.insert_body(
589 def,
590 BodyWithBorrowckFacts {
591 body: body_owned,
592 promoted,
593 borrow_set,
594 region_inference_context: regioncx,
595 location_table: polonius_input.as_ref().map(|_| location_table),
596 input_facts: polonius_input,
597 output_facts: polonius_output,
598 },
599 );
600 }
601
602 {
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:602",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(602u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("do_mir_borrowck: result = {0:#?}",
result) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("do_mir_borrowck: result = {:#?}", result);
603
604 result
605}
606
607fn get_flow_results<'a, 'tcx>(
608 tcx: TyCtxt<'tcx>,
609 body: &'a Body<'tcx>,
610 move_data: &'a MoveData<'tcx>,
611 borrow_set: &'a BorrowSet<'tcx>,
612 regioncx: &RegionInferenceContext<'tcx>,
613) -> Results<'tcx, Borrowck<'a, 'tcx>> {
614 let borrows = Borrows::new(tcx, body, regioncx, borrow_set).iterate_to_fixpoint(
617 tcx,
618 body,
619 Some("borrowck"),
620 );
621 let uninits = MaybeUninitializedPlaces::new(tcx, body, move_data).iterate_to_fixpoint(
622 tcx,
623 body,
624 Some("borrowck"),
625 );
626 let ever_inits = EverInitializedPlaces::new(body, move_data).iterate_to_fixpoint(
627 tcx,
628 body,
629 Some("borrowck"),
630 );
631
632 let analysis = Borrowck {
633 borrows: borrows.analysis,
634 uninits: uninits.analysis,
635 ever_inits: ever_inits.analysis,
636 };
637
638 {
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());
639 {
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());
640 let entry_states: EntryStates<_> =
641 ::itertools::__std_iter::Iterator::map(::itertools::__std_iter::Iterator::zip(::itertools::__std_iter::IntoIterator::into_iter(borrows.entry_states),
::itertools::__std_iter::Iterator::zip(::itertools::__std_iter::IntoIterator::into_iter(uninits.entry_states),
::itertools::__std_iter::IntoIterator::into_iter(ever_inits.entry_states))),
|(b, (b, a))| (b, b, a))itertools::izip!(borrows.entry_states, uninits.entry_states, ever_inits.entry_states)
642 .map(|(borrows, uninits, ever_inits)| BorrowckDomain { borrows, uninits, ever_inits })
643 .collect();
644
645 Results { analysis, entry_states }
646}
647
648pub(crate) struct BorrowckInferCtxt<'tcx> {
649 pub(crate) infcx: InferCtxt<'tcx>,
650 pub(crate) root_def_id: LocalDefId,
651 pub(crate) param_env: ParamEnv<'tcx>,
652 pub(crate) reg_var_to_origin: RefCell<FxIndexMap<ty::RegionVid, RegionCtxt>>,
653}
654
655impl<'tcx> BorrowckInferCtxt<'tcx> {
656 pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId, root_def_id: LocalDefId) -> Self {
657 let typing_mode = if tcx.use_typing_mode_post_typeck_until_borrowck() {
658 TypingMode::borrowck(tcx, def_id)
659 } else {
660 TypingMode::analysis_in_body(tcx, def_id)
661 };
662 let infcx = tcx.infer_ctxt().build(typing_mode);
663 let param_env = tcx.param_env(def_id);
664 BorrowckInferCtxt {
665 infcx,
666 root_def_id,
667 reg_var_to_origin: RefCell::new(Default::default()),
668 param_env,
669 }
670 }
671
672 pub(crate) fn next_region_var<F>(
673 &self,
674 origin: RegionVariableOrigin<'tcx>,
675 get_ctxt_fn: F,
676 ) -> ty::Region<'tcx>
677 where
678 F: Fn() -> RegionCtxt,
679 {
680 let next_region = self.infcx.next_region_var(origin);
681 let vid = next_region.as_var();
682
683 if truecfg!(debug_assertions) {
684 {
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:684",
"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(&["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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("inserting vid {0:?} with origin {1:?} into var_to_origin",
vid, origin) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("inserting vid {:?} with origin {:?} into var_to_origin", vid, origin);
685 let ctxt = get_ctxt_fn();
686 let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
687 {
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);
688 }
689
690 next_region
691 }
692
693 #[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(693u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::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:706",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(706u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("inserting vid {0:?} with origin {1:?} into var_to_origin",
vid, origin) as &dyn ::tracing::field::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")]
694 pub(crate) fn next_nll_region_var<F>(
695 &self,
696 origin: NllRegionVariableOrigin<'tcx>,
697 get_ctxt_fn: F,
698 ) -> ty::Region<'tcx>
699 where
700 F: Fn() -> RegionCtxt,
701 {
702 let next_region = self.infcx.next_nll_region_var(origin);
703 let vid = next_region.as_var();
704
705 if cfg!(debug_assertions) {
706 debug!("inserting vid {:?} with origin {:?} into var_to_origin", vid, origin);
707 let ctxt = get_ctxt_fn();
708 let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
709 assert_eq!(var_to_origin.insert(vid, ctxt), None);
710 }
711
712 next_region
713 }
714
715 fn fully_perform<Q: QueryTypeOp<'tcx> + TypeVisitable<TyCtxt<'tcx>>>(
716 &self,
717 q: Q,
718 span: Span,
719 ) -> Result<TypeOpOutput<'tcx, ty::ParamEnvAnd<'tcx, Q>>, ErrorGuaranteed> {
720 self.param_env.and(q).fully_perform(&self.infcx, self.root_def_id, span)
721 }
722}
723
724impl<'tcx> Deref for BorrowckInferCtxt<'tcx> {
725 type Target = InferCtxt<'tcx>;
726
727 fn deref(&self) -> &Self::Target {
728 &self.infcx
729 }
730}
731
732pub(crate) struct MirBorrowckCtxt<'a, 'diag, 'tcx> {
733 root_cx: &'a BorrowCheckRootCtxt<'diag, 'tcx>,
734 infcx: &'a BorrowckInferCtxt<'tcx>,
735 body: &'a Body<'tcx>,
736 move_data: &'a MoveData<'tcx>,
737
738 location_table: &'a PoloniusLocationTable,
741
742 movable_coroutine: bool,
743 access_place_error_reported: FxIndexSet<(Place<'tcx>, Span)>,
749 reservation_error_reported: FxIndexSet<Place<'tcx>>,
757 fn_self_span_reported: FxIndexSet<Span>,
761 uninitialized_error_reported: FxIndexSet<Local>,
764 used_mut: FxIndexSet<Local>,
767 used_mut_upvars: SmallVec<[FieldIdx; 8]>,
770 regioncx: &'a RegionInferenceContext<'tcx>,
773
774 borrow_set: &'a BorrowSet<'tcx>,
776
777 upvars: &'tcx [&'tcx ty::CapturedPlace<'tcx>],
779
780 local_names: OnceCell<IndexVec<Local, Option<Symbol>>>,
782
783 region_names: RefCell<FxIndexMap<RegionVid, RegionName>>,
786
787 next_region_name: RefCell<usize>,
789
790 diags_buffer: &'a mut BorrowckDiagnosticsBuffer<'diag, 'tcx>,
791 move_errors: Vec<MoveError<'tcx>>,
792
793 polonius_output: Option<&'a PoloniusOutput>,
795 polonius_context: Option<&'a PoloniusContext>,
797}
798
799impl<'a, 'tcx> ResultsVisitor<'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<'a, '_, 'tcx> {
805 fn visit_after_early_statement_effect(
806 &mut self,
807 _analysis: &Borrowck<'a, 'tcx>,
808 state: &BorrowckDomain,
809 stmt: &Statement<'tcx>,
810 location: Location,
811 ) {
812 {
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:812",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(812u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("MirBorrowckCtxt::process_statement({0:?}, {1:?}): {2:?}",
location, stmt, state) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, state);
813 let span = stmt.source_info.span;
814
815 self.check_activations(location, span, state);
816
817 match &stmt.kind {
818 StatementKind::Assign((lhs, rhs)) => {
819 self.consume_rvalue(location, (rhs, span), state);
820
821 self.mutate_place(location, (*lhs, span), Shallow(None), state);
822 }
823 StatementKind::FakeRead((_, place)) => {
824 self.check_if_path_or_subpath_is_moved(
835 location,
836 InitializationRequiringAction::Use,
837 (place.as_ref(), span),
838 state,
839 );
840 }
841 StatementKind::Intrinsic(kind) => match kind {
842 NonDivergingIntrinsic::Assume(op) => {
843 self.consume_operand(location, (op, span), state);
844 }
845 NonDivergingIntrinsic::CopyNonOverlapping(..) => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("Unexpected CopyNonOverlapping, should only appear after lower_intrinsics"))span_bug!(
846 span,
847 "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
848 ),
849 },
850 StatementKind::AscribeUserType(..) => {}
852 StatementKind::PlaceMention(..) => {}
854 StatementKind::Coverage(..) => {}
856 StatementKind::ConstEvalCounter | StatementKind::StorageLive(..) => {}
858 StatementKind::BackwardIncompatibleDropHint {
860 place,
861 reason: BackwardIncompatibleDropReason::Edition2024,
862 } => {
863 self.check_backward_incompatible_drop(location, **place, state);
864 }
865 StatementKind::StorageDead(local) => {
866 self.access_place(
867 location,
868 (Place::from(*local), span),
869 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
870 LocalMutationIsAllowed::Yes,
871 state,
872 );
873 }
874 StatementKind::Nop | StatementKind::SetDiscriminant { .. } => {
875 ::rustc_middle::util::bug::bug_fmt(format_args!("Statement not allowed in this MIR phase"))bug!("Statement not allowed in this MIR phase")
876 }
877 }
878 }
879
880 fn visit_after_early_terminator_effect(
881 &mut self,
882 _analysis: &Borrowck<'a, 'tcx>,
883 state: &BorrowckDomain,
884 term: &Terminator<'tcx>,
885 loc: Location,
886 ) {
887 {
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:887",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(887u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("MirBorrowckCtxt::process_terminator({0:?}, {1:?}): {2:?}",
loc, term, state) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, state);
888 let span = term.source_info.span;
889
890 self.check_activations(loc, span, state);
891
892 match &term.kind {
893 TerminatorKind::SwitchInt { discr, targets: _ } => {
894 self.consume_operand(loc, (discr, span), state);
895 }
896 TerminatorKind::Drop { place, target: _, unwind: _, replace, drop: _ } => {
897 {
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:897",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(897u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_terminator_drop loc: {0:?} term: {1:?} place: {2:?} span: {3:?}",
loc, term, place, span) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
898 "visit_terminator_drop \
899 loc: {:?} term: {:?} place: {:?} span: {:?}",
900 loc, term, place, span
901 );
902
903 let write_kind =
904 if *replace { WriteKind::Replace } else { WriteKind::StorageDeadOrDrop };
905 self.access_place(
906 loc,
907 (*place, span),
908 (AccessDepth::Drop, Write(write_kind)),
909 LocalMutationIsAllowed::Yes,
910 state,
911 );
912 }
913 TerminatorKind::Call {
914 func,
915 args,
916 destination,
917 target: _,
918 unwind: _,
919 call_source: _,
920 fn_span: _,
921 } => {
922 self.consume_operand(loc, (func, span), state);
923 for arg in args {
924 self.consume_operand(loc, (&arg.node, arg.span), state);
925 }
926 self.mutate_place(loc, (*destination, span), Deep, state);
927 }
928 TerminatorKind::TailCall { func, args, fn_span: _ } => {
929 self.consume_operand(loc, (func, span), state);
930 for arg in args {
931 self.consume_operand(loc, (&arg.node, arg.span), state);
932 }
933 }
934 TerminatorKind::Assert { cond, expected: _, msg, target: _, unwind: _ } => {
935 self.consume_operand(loc, (cond, span), state);
936 if let AssertKind::BoundsCheck { len, index } = &**msg {
937 self.consume_operand(loc, (len, span), state);
938 self.consume_operand(loc, (index, span), state);
939 }
940 }
941
942 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
943 self.consume_operand(loc, (value, span), state);
944 self.mutate_place(loc, (*resume_arg, span), Deep, state);
945 }
946
947 TerminatorKind::InlineAsm {
948 asm_macro: _,
949 template: _,
950 operands,
951 options: _,
952 line_spans: _,
953 targets: _,
954 unwind: _,
955 } => {
956 for op in operands {
957 match op {
958 InlineAsmOperand::In { reg: _, value } => {
959 self.consume_operand(loc, (value, span), state);
960 }
961 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
962 if let Some(place) = place {
963 self.mutate_place(loc, (*place, span), Shallow(None), state);
964 }
965 }
966 InlineAsmOperand::InOut { reg: _, late: _, in_value, out_place } => {
967 self.consume_operand(loc, (in_value, span), state);
968 if let &Some(out_place) = out_place {
969 self.mutate_place(loc, (out_place, span), Shallow(None), state);
970 }
971 }
972 InlineAsmOperand::Const { value: _ }
973 | InlineAsmOperand::SymFn { value: _ }
974 | InlineAsmOperand::SymStatic { def_id: _ }
975 | InlineAsmOperand::Label { target_index: _ } => {}
976 }
977 }
978 }
979
980 TerminatorKind::Goto { target: _ }
981 | TerminatorKind::UnwindTerminate(_)
982 | TerminatorKind::Unreachable
983 | TerminatorKind::UnwindResume
984 | TerminatorKind::Return
985 | TerminatorKind::CoroutineDrop
986 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
987 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
988 }
990 }
991 }
992
993 fn visit_after_primary_terminator_effect(
994 &mut self,
995 _analysis: &Borrowck<'a, 'tcx>,
996 state: &BorrowckDomain,
997 term: &Terminator<'tcx>,
998 loc: Location,
999 ) {
1000 let span = term.source_info.span;
1001
1002 match term.kind {
1003 TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
1004 if self.movable_coroutine {
1005 for i in state.borrows.iter() {
1007 let borrow = &self.borrow_set[i];
1008 self.check_for_local_borrow(borrow, span);
1009 }
1010 }
1011 }
1012
1013 TerminatorKind::UnwindResume
1014 | TerminatorKind::Return
1015 | TerminatorKind::TailCall { .. }
1016 | TerminatorKind::CoroutineDrop => {
1017 match self.borrow_set.locals_state_at_exit() {
1018 LocalsStateAtExit::AllAreInvalidated => {
1019 for i in state.borrows.iter() {
1024 let borrow = &self.borrow_set[i];
1025 self.check_for_invalidation_at_exit(loc, borrow, span);
1026 }
1027 }
1028 LocalsStateAtExit::SomeAreInvalidated { has_storage_dead_or_moved: _ } => {}
1031 }
1032 }
1033
1034 TerminatorKind::UnwindTerminate(_)
1035 | TerminatorKind::Assert { .. }
1036 | TerminatorKind::Call { .. }
1037 | TerminatorKind::Drop { .. }
1038 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
1039 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
1040 | TerminatorKind::Goto { .. }
1041 | TerminatorKind::SwitchInt { .. }
1042 | TerminatorKind::Unreachable
1043 | TerminatorKind::InlineAsm { .. } => {}
1044 }
1045 }
1046}
1047
1048use self::AccessDepth::{Deep, Shallow};
1049use self::ReadOrWrite::{Activation, Read, Reservation, Write};
1050
1051#[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)]
1052enum ArtificialField {
1053 ArrayLength,
1054 FakeBorrow,
1055}
1056
1057#[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)]
1058enum AccessDepth {
1059 Shallow(Option<ArtificialField>),
1065
1066 Deep,
1070
1071 Drop,
1074}
1075
1076#[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)]
1079enum ReadOrWrite {
1080 Read(ReadKind),
1083
1084 Write(WriteKind),
1088
1089 Reservation(WriteKind),
1093 Activation(WriteKind, BorrowIndex),
1094}
1095
1096#[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)]
1099enum ReadKind {
1100 Borrow(BorrowKind),
1101 Copy,
1102}
1103
1104#[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)]
1107enum WriteKind {
1108 StorageDeadOrDrop,
1109 Replace,
1110 MutableBorrow(BorrowKind),
1111 Mutate,
1112 Move,
1113}
1114
1115#[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)]
1123enum LocalMutationIsAllowed {
1124 Yes,
1125 ExceptUpvars,
1128 No,
1129}
1130
1131#[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)]
1132enum InitializationRequiringAction {
1133 Borrow,
1134 MatchOn,
1135 Use,
1136 Assignment,
1137 PartialAssignment,
1138}
1139
1140#[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)]
1141struct RootPlace<'tcx> {
1142 place_local: Local,
1143 place_projection: &'tcx [PlaceElem<'tcx>],
1144 is_local_mutation_allowed: LocalMutationIsAllowed,
1145}
1146
1147impl InitializationRequiringAction {
1148 fn as_noun(self) -> &'static str {
1149 match self {
1150 InitializationRequiringAction::Borrow => "borrow",
1151 InitializationRequiringAction::MatchOn => "use", InitializationRequiringAction::Use => "use",
1153 InitializationRequiringAction::Assignment => "assign",
1154 InitializationRequiringAction::PartialAssignment => "assign to part",
1155 }
1156 }
1157
1158 fn as_verb_in_past_tense(self) -> &'static str {
1159 match self {
1160 InitializationRequiringAction::Borrow => "borrowed",
1161 InitializationRequiringAction::MatchOn => "matched on",
1162 InitializationRequiringAction::Use => "used",
1163 InitializationRequiringAction::Assignment => "assigned",
1164 InitializationRequiringAction::PartialAssignment => "partially assigned",
1165 }
1166 }
1167
1168 fn as_general_verb_in_past_tense(self) -> &'static str {
1169 match self {
1170 InitializationRequiringAction::Borrow
1171 | InitializationRequiringAction::MatchOn
1172 | InitializationRequiringAction::Use => "used",
1173 InitializationRequiringAction::Assignment => "assigned",
1174 InitializationRequiringAction::PartialAssignment => "partially assigned",
1175 }
1176 }
1177}
1178
1179impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
1180 fn body(&self) -> &'a Body<'tcx> {
1181 self.body
1182 }
1183
1184 fn access_place(
1191 &mut self,
1192 location: Location,
1193 place_span: (Place<'tcx>, Span),
1194 kind: (AccessDepth, ReadOrWrite),
1195 is_local_mutation_allowed: LocalMutationIsAllowed,
1196 state: &BorrowckDomain,
1197 ) {
1198 let (sd, rw) = kind;
1199
1200 if let Activation(_, borrow_index) = rw {
1201 if self.reservation_error_reported.contains(&place_span.0) {
1202 {
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:1202",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1202u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
});
} else { ; }
};debug!(
1203 "skipping access_place for activation of invalid reservation \
1204 place: {:?} borrow_index: {:?}",
1205 place_span.0, borrow_index
1206 );
1207 return;
1208 }
1209 }
1210
1211 if !self.access_place_error_reported.is_empty()
1214 && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
1215 {
1216 {
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:1216",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1216u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("access_place: suppressing error place_span=`{0:?}` kind=`{1:?}`",
place_span, kind) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1217 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
1218 place_span, kind
1219 );
1220
1221 if rw == ReadOrWrite::Write(WriteKind::Mutate)
1225 && let Ok(root_place) =
1226 self.is_mutable(place_span.0.as_ref(), is_local_mutation_allowed)
1227 {
1228 self.add_used_mut(root_place, state);
1229 }
1230
1231 return;
1232 }
1233
1234 let mutability_error = self.check_access_permissions(
1235 place_span,
1236 rw,
1237 is_local_mutation_allowed,
1238 state,
1239 location,
1240 );
1241 let conflict_error = self.check_access_for_conflict(location, place_span, sd, rw, state);
1242
1243 if conflict_error || mutability_error {
1244 {
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:1244",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1244u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("access_place: logging error place_span=`{0:?}` kind=`{1:?}`",
place_span, kind) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
1245 self.access_place_error_reported.insert((place_span.0, place_span.1));
1246 }
1247 }
1248
1249 fn borrows_in_scope<'s>(
1250 &self,
1251 location: Location,
1252 state: &'s BorrowckDomain,
1253 ) -> Cow<'s, MixedBitSet<BorrowIndex>> {
1254 if let Some(polonius) = &self.polonius_output {
1255 let location = self.location_table.start_index(location);
1257 let mut polonius_output = MixedBitSet::new_empty(self.borrow_set.len());
1258 for &idx in polonius.errors_at(location) {
1259 polonius_output.insert(idx);
1260 }
1261 Cow::Owned(polonius_output)
1262 } else {
1263 Cow::Borrowed(&state.borrows)
1264 }
1265 }
1266
1267 #[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(1267u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("location")
}> =
::tracing::__macro_support::FieldName::new("location");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("place_span")
}> =
::tracing::__macro_support::FieldName::new("place_span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("sd")
}> =
::tracing::__macro_support::FieldName::new("sd");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("rw")
}> =
::tracing::__macro_support::FieldName::new("rw");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sd)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rw)
as &dyn ::tracing::field::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);
{
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:1279",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1279u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("borrows_in_scope")
}> =
::tracing::__macro_support::FieldName::new("borrows_in_scope");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("location")
}> =
::tracing::__macro_support::FieldName::new("location");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrows_in_scope)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
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:1296",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1296u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::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:1350",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1350u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("recording invalid reservation of place: {0:?}",
place_span.0) as &dyn ::tracing::field::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:1358",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1358u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("observing check_place for activation of borrow_index: {0:?}",
activating) as &dyn ::tracing::field::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))]
1268 fn check_access_for_conflict(
1269 &mut self,
1270 location: Location,
1271 place_span: (Place<'tcx>, Span),
1272 sd: AccessDepth,
1273 rw: ReadOrWrite,
1274 state: &BorrowckDomain,
1275 ) -> bool {
1276 let mut error_reported = false;
1277
1278 let borrows_in_scope = self.borrows_in_scope(location, state);
1279 debug!(?borrows_in_scope, ?location);
1280
1281 each_borrow_involving_path(
1282 self,
1283 self.infcx.tcx,
1284 self.body,
1285 (sd, place_span.0),
1286 self.borrow_set,
1287 |borrow_index| borrows_in_scope.contains(borrow_index),
1288 |this, borrow_index, borrow| match (rw, borrow.kind) {
1289 (Activation(_, activating), _) if activating == borrow_index => {
1296 debug!(
1297 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1298 skipping {:?} b/c activation of same borrow_index",
1299 place_span,
1300 sd,
1301 rw,
1302 (borrow_index, borrow),
1303 );
1304 ControlFlow::Continue(())
1305 }
1306
1307 (Read(_), BorrowKind::Shared | BorrowKind::Fake(_))
1308 | (
1309 Read(ReadKind::Borrow(BorrowKind::Fake(FakeBorrowKind::Shallow))),
1310 BorrowKind::Mut { .. },
1311 ) => ControlFlow::Continue(()),
1312
1313 (Reservation(_), BorrowKind::Fake(_) | BorrowKind::Shared) => {
1314 ControlFlow::Continue(())
1317 }
1318
1319 (Write(WriteKind::Move), BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
1320 ControlFlow::Continue(())
1322 }
1323
1324 (Read(kind), BorrowKind::Mut { .. }) => {
1325 if !is_active(this.dominators(), borrow, location) {
1327 assert!(borrow.kind.is_two_phase_borrow());
1328 return ControlFlow::Continue(());
1329 }
1330
1331 error_reported = true;
1332 match kind {
1333 ReadKind::Copy => {
1334 let err = this
1335 .report_use_while_mutably_borrowed(location, place_span, borrow);
1336 this.buffer_error(err);
1337 }
1338 ReadKind::Borrow(bk) => {
1339 let err =
1340 this.report_conflicting_borrow(location, place_span, bk, borrow);
1341 this.buffer_error(err);
1342 }
1343 }
1344 ControlFlow::Break(())
1345 }
1346
1347 (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1348 match rw {
1349 Reservation(..) => {
1350 debug!(
1351 "recording invalid reservation of \
1352 place: {:?}",
1353 place_span.0
1354 );
1355 this.reservation_error_reported.insert(place_span.0);
1356 }
1357 Activation(_, activating) => {
1358 debug!(
1359 "observing check_place for activation of \
1360 borrow_index: {:?}",
1361 activating
1362 );
1363 }
1364 Read(..) | Write(..) => {}
1365 }
1366
1367 error_reported = true;
1368 match kind {
1369 WriteKind::MutableBorrow(bk) => {
1370 let err =
1371 this.report_conflicting_borrow(location, place_span, bk, borrow);
1372 this.buffer_error(err);
1373 }
1374 WriteKind::StorageDeadOrDrop => this
1375 .report_borrowed_value_does_not_live_long_enough(
1376 location,
1377 borrow,
1378 place_span,
1379 Some(WriteKind::StorageDeadOrDrop),
1380 ),
1381 WriteKind::Mutate => {
1382 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1383 }
1384 WriteKind::Move => {
1385 this.report_move_out_while_borrowed(location, place_span, borrow)
1386 }
1387 WriteKind::Replace => {
1388 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1389 }
1390 }
1391 ControlFlow::Break(())
1392 }
1393 },
1394 );
1395
1396 error_reported
1397 }
1398
1399 #[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(1401u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("location")
}> =
::tracing::__macro_support::FieldName::new("location");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("place")
}> =
::tracing::__macro_support::FieldName::new("place");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
as &dyn ::tracing::field::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))]
1402 fn check_backward_incompatible_drop(
1403 &mut self,
1404 location: Location,
1405 place: Place<'tcx>,
1406 state: &BorrowckDomain,
1407 ) {
1408 let tcx = self.infcx.tcx;
1409 let sd = if place.ty(self.body, tcx).ty.needs_drop(tcx, self.body.typing_env(tcx)) {
1413 AccessDepth::Drop
1414 } else {
1415 AccessDepth::Shallow(None)
1416 };
1417
1418 let borrows_in_scope = self.borrows_in_scope(location, state);
1419
1420 each_borrow_involving_path(
1423 self,
1424 self.infcx.tcx,
1425 self.body,
1426 (sd, place),
1427 self.borrow_set,
1428 |borrow_index| borrows_in_scope.contains(borrow_index),
1429 |this, _borrow_index, borrow| {
1430 if matches!(borrow.kind, BorrowKind::Fake(_)) {
1431 return ControlFlow::Continue(());
1432 }
1433 let borrowed = this.retrieve_borrow_spans(borrow).var_or_use_path_span();
1434 let explain = this.explain_why_borrow_contains_point(
1435 location,
1436 borrow,
1437 Some((WriteKind::StorageDeadOrDrop, place)),
1438 );
1439 this.infcx.tcx.emit_node_span_lint(
1440 TAIL_EXPR_DROP_ORDER,
1441 CRATE_HIR_ID,
1442 borrowed,
1443 session_diagnostics::TailExprDropOrder {
1444 borrowed,
1445 callback: |diag| {
1446 explain.add_explanation_to_diagnostic(&this, diag, "", None, None);
1447 },
1448 },
1449 );
1450 ControlFlow::Break(())
1452 },
1453 );
1454 }
1455
1456 fn mutate_place(
1457 &mut self,
1458 location: Location,
1459 place_span: (Place<'tcx>, Span),
1460 kind: AccessDepth,
1461 state: &BorrowckDomain,
1462 ) {
1463 self.check_if_assigned_path_is_moved(location, place_span, state);
1465
1466 self.access_place(
1467 location,
1468 place_span,
1469 (kind, Write(WriteKind::Mutate)),
1470 LocalMutationIsAllowed::No,
1471 state,
1472 );
1473 }
1474
1475 fn consume_rvalue(
1476 &mut self,
1477 location: Location,
1478 (rvalue, span): (&Rvalue<'tcx>, Span),
1479 state: &BorrowckDomain,
1480 ) {
1481 match rvalue {
1482 &Rvalue::Ref(_ , bk, place) => {
1483 let access_kind = match bk {
1484 BorrowKind::Fake(FakeBorrowKind::Shallow) => {
1485 (Shallow(Some(ArtificialField::FakeBorrow)), Read(ReadKind::Borrow(bk)))
1486 }
1487 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep) => {
1488 (Deep, Read(ReadKind::Borrow(bk)))
1489 }
1490 BorrowKind::Mut { .. } => {
1491 let wk = WriteKind::MutableBorrow(bk);
1492 if bk.is_two_phase_borrow() {
1493 (Deep, Reservation(wk))
1494 } else {
1495 (Deep, Write(wk))
1496 }
1497 }
1498 };
1499
1500 self.access_place(
1501 location,
1502 (place, span),
1503 access_kind,
1504 LocalMutationIsAllowed::No,
1505 state,
1506 );
1507
1508 let action = if bk == BorrowKind::Fake(FakeBorrowKind::Shallow) {
1509 InitializationRequiringAction::MatchOn
1510 } else {
1511 InitializationRequiringAction::Borrow
1512 };
1513
1514 self.check_if_path_or_subpath_is_moved(
1515 location,
1516 action,
1517 (place.as_ref(), span),
1518 state,
1519 );
1520 }
1521
1522 &Rvalue::Reborrow(_target, mutability, place) => {
1523 let access_kind = (
1524 Deep,
1525 if mutability == Mutability::Mut {
1526 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1527 kind: MutBorrowKind::Default,
1528 }))
1529 } else {
1530 Read(ReadKind::Borrow(BorrowKind::Shared))
1531 },
1532 );
1533
1534 self.access_place(
1535 location,
1536 (place, span),
1537 access_kind,
1538 LocalMutationIsAllowed::Yes,
1539 state,
1540 );
1541
1542 let action = InitializationRequiringAction::Borrow;
1543
1544 self.check_if_path_or_subpath_is_moved(
1545 location,
1546 action,
1547 (place.as_ref(), span),
1548 state,
1549 );
1550 }
1551
1552 &Rvalue::RawPtr(kind, place) => {
1553 let access_kind = match kind {
1554 RawPtrKind::Mut => (
1555 Deep,
1556 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1557 kind: MutBorrowKind::Default,
1558 })),
1559 ),
1560 RawPtrKind::Const => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1561 RawPtrKind::FakeForPtrMetadata => {
1562 (Shallow(Some(ArtificialField::ArrayLength)), Read(ReadKind::Copy))
1563 }
1564 };
1565
1566 self.access_place(
1567 location,
1568 (place, span),
1569 access_kind,
1570 LocalMutationIsAllowed::No,
1571 state,
1572 );
1573
1574 self.check_if_path_or_subpath_is_moved(
1575 location,
1576 InitializationRequiringAction::Borrow,
1577 (place.as_ref(), span),
1578 state,
1579 );
1580 }
1581
1582 Rvalue::ThreadLocalRef(_) => {}
1583
1584 Rvalue::Use(operand, _)
1585 | Rvalue::Repeat(operand, _)
1586 | Rvalue::UnaryOp(_ , operand)
1587 | Rvalue::Cast(_ , operand, _ ) => {
1588 self.consume_operand(location, (operand, span), state)
1589 }
1590
1591 &Rvalue::Discriminant(place) => {
1592 let af = match *rvalue {
1593 Rvalue::Discriminant(..) => None,
1594 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1595 };
1596 self.access_place(
1597 location,
1598 (place, span),
1599 (Shallow(af), Read(ReadKind::Copy)),
1600 LocalMutationIsAllowed::No,
1601 state,
1602 );
1603 self.check_if_path_or_subpath_is_moved(
1604 location,
1605 InitializationRequiringAction::Use,
1606 (place.as_ref(), span),
1607 state,
1608 );
1609 }
1610
1611 Rvalue::BinaryOp(_bin_op, (operand1, operand2)) => {
1612 self.consume_operand(location, (operand1, span), state);
1613 self.consume_operand(location, (operand2, span), state);
1614 }
1615
1616 Rvalue::Aggregate(aggregate_kind, operands) => {
1617 match **aggregate_kind {
1621 AggregateKind::Closure(def_id, _)
1622 | AggregateKind::CoroutineClosure(def_id, _)
1623 | AggregateKind::Coroutine(def_id, _) => {
1624 let def_id = def_id.expect_local();
1625 let used_mut_upvars = self.root_cx.used_mut_upvars(def_id);
1626 {
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:1626",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1626u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0:?} used_mut_upvars={1:?}",
def_id, used_mut_upvars) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1627 for field in used_mut_upvars.clone() {
1631 self.propagate_closure_used_mut_upvar(&operands[field]);
1632 }
1633 }
1634 AggregateKind::Adt(..)
1635 | AggregateKind::Array(..)
1636 | AggregateKind::Tuple { .. }
1637 | AggregateKind::RawPtr(..) => (),
1638 }
1639
1640 for operand in operands {
1641 self.consume_operand(location, (operand, span), state);
1642 }
1643 }
1644
1645 Rvalue::WrapUnsafeBinder(op, _) => {
1646 self.consume_operand(location, (op, span), state);
1647 }
1648
1649 Rvalue::CopyForDeref(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("`CopyForDeref` in borrowck"))bug!("`CopyForDeref` in borrowck"),
1650 }
1651 }
1652
1653 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1654 let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1655 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1663 this.used_mut_upvars.push(field);
1664 return;
1665 }
1666
1667 for (place_ref, proj) in place.iter_projections().rev() {
1668 if proj == ProjectionElem::Deref {
1670 match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1671 ty::Ref(_, _, hir::Mutability::Mut) => return,
1673
1674 _ => {}
1675 }
1676 }
1677
1678 if let Some(field) = this.is_upvar_field_projection(place_ref) {
1680 this.used_mut_upvars.push(field);
1681 return;
1682 }
1683 }
1684
1685 this.used_mut.insert(place.local);
1687 };
1688
1689 match *operand {
1693 Operand::Move(place) | Operand::Copy(place) => {
1694 match place.as_local() {
1695 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1696 if self.body.local_decls[local].ty.is_mutable_ptr() {
1697 return;
1699 }
1700 let Some(temp_mpi) = self.move_data.rev_lookup.find_local(local) else {
1716 ::rustc_middle::util::bug::bug_fmt(format_args!("temporary should be tracked"));bug!("temporary should be tracked");
1717 };
1718 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1719 &self.move_data.inits[init_index]
1720 } else {
1721 ::rustc_middle::util::bug::bug_fmt(format_args!("temporary should be initialized exactly once"))bug!("temporary should be initialized exactly once")
1722 };
1723
1724 let InitLocation::Statement(loc) = init.location else {
1725 ::rustc_middle::util::bug::bug_fmt(format_args!("temporary initialized in arguments"))bug!("temporary initialized in arguments")
1726 };
1727
1728 let body = self.body;
1729 let bbd = &body[loc.block];
1730 let stmt = &bbd.statements[loc.statement_index];
1731 {
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:1731",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1731u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("temporary assigned in: stmt={0:?}",
stmt) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("temporary assigned in: stmt={:?}", stmt);
1732
1733 match stmt.kind {
1734 StatementKind::Assign((
1735 _,
1736 Rvalue::Ref(_, _, source)
1737 | Rvalue::Use(Operand::Copy(source) | Operand::Move(source), _),
1738 )) => {
1739 propagate_closure_used_mut_place(self, source);
1740 }
1741 _ => {
1742 ::rustc_middle::util::bug::bug_fmt(format_args!("closures should only capture user variables or references to user variables"));bug!(
1743 "closures should only capture user variables \
1744 or references to user variables"
1745 );
1746 }
1747 }
1748 }
1749 _ => propagate_closure_used_mut_place(self, place),
1750 }
1751 }
1752 Operand::Constant(..) | Operand::RuntimeChecks(_) => {}
1753 }
1754 }
1755
1756 fn consume_operand(
1757 &mut self,
1758 location: Location,
1759 (operand, span): (&Operand<'tcx>, Span),
1760 state: &BorrowckDomain,
1761 ) {
1762 match *operand {
1763 Operand::Copy(place) => {
1764 self.access_place(
1767 location,
1768 (place, span),
1769 (Deep, Read(ReadKind::Copy)),
1770 LocalMutationIsAllowed::No,
1771 state,
1772 );
1773
1774 self.check_if_path_or_subpath_is_moved(
1776 location,
1777 InitializationRequiringAction::Use,
1778 (place.as_ref(), span),
1779 state,
1780 );
1781 }
1782 Operand::Move(place) => {
1783 self.check_movable_place(location, place);
1785
1786 self.access_place(
1788 location,
1789 (place, span),
1790 (Deep, Write(WriteKind::Move)),
1791 LocalMutationIsAllowed::Yes,
1792 state,
1793 );
1794
1795 self.check_if_path_or_subpath_is_moved(
1797 location,
1798 InitializationRequiringAction::Use,
1799 (place.as_ref(), span),
1800 state,
1801 );
1802 }
1803 Operand::Constant(_) | Operand::RuntimeChecks(_) => {}
1804 }
1805 }
1806
1807 #[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(1809u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("location")
}> =
::tracing::__macro_support::FieldName::new("location");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("borrow")
}> =
::tracing::__macro_support::FieldName::new("borrow");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::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:1845",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1845u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_for_invalidation_at_exit({0:?}): INVALID",
place) as &dyn ::tracing::field::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))]
1810 fn check_for_invalidation_at_exit(
1811 &mut self,
1812 location: Location,
1813 borrow: &BorrowData<'tcx>,
1814 span: Span,
1815 ) {
1816 let place = borrow.borrowed_place;
1817 let mut root_place = PlaceRef { local: place.local, projection: &[] };
1818
1819 let might_be_alive = if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1825 root_place.projection = TyCtxtConsts::DEREF_PROJECTION;
1829 true
1830 } else {
1831 false
1832 };
1833
1834 let sd = if might_be_alive { Deep } else { Shallow(None) };
1835
1836 if places_conflict::borrow_conflicts_with_place(
1837 self.infcx.tcx,
1838 self.body,
1839 place,
1840 borrow.kind,
1841 root_place,
1842 sd,
1843 places_conflict::PlaceConflictBias::Overlap,
1844 ) {
1845 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1846 let span = self.infcx.tcx.sess.source_map().end_point(span);
1849 self.report_borrowed_value_does_not_live_long_enough(
1850 location,
1851 borrow,
1852 (place, span),
1853 None,
1854 )
1855 }
1856 }
1857
1858 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1861 {
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:1861",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1861u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_for_local_borrow({0:?})",
borrow) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_for_local_borrow({:?})", borrow);
1862
1863 if borrow_of_local_data(borrow.borrowed_place) {
1864 let err = self.cannot_borrow_across_coroutine_yield(
1865 self.retrieve_borrow_spans(borrow).var_or_use(),
1866 yield_span,
1867 );
1868
1869 self.buffer_error(err);
1870 }
1871 }
1872
1873 fn check_activations(&mut self, location: Location, span: Span, state: &BorrowckDomain) {
1874 for &borrow_index in self.borrow_set.activations_at_location(&location) {
1878 let borrow = &self.borrow_set[borrow_index];
1879
1880 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 {
1882 BorrowKind::Shared | BorrowKind::Fake(_) => false,
1883 BorrowKind::Mut { .. } => true,
1884 });
1885
1886 self.access_place(
1887 location,
1888 (borrow.borrowed_place, span),
1889 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1890 LocalMutationIsAllowed::No,
1891 state,
1892 );
1893 }
1897 }
1898
1899 fn check_movable_place(&mut self, location: Location, place: Place<'tcx>) {
1900 use IllegalMoveOriginKind::*;
1901
1902 let body = self.body;
1903 let tcx = self.infcx.tcx;
1904 let mut place_ty = PlaceTy::from_ty(body.local_decls[place.local].ty);
1905 for (place_ref, elem) in place.iter_projections() {
1906 match elem {
1907 ProjectionElem::Deref => match place_ty.ty.kind() {
1908 ty::Ref(..) | ty::RawPtr(..) => {
1909 self.move_errors.push(MoveError::new(
1910 place,
1911 location,
1912 BorrowedContent {
1913 target_place: place_ref.project_deeper(&[elem], tcx),
1914 },
1915 ));
1916 return;
1917 }
1918 ty::Adt(adt, _) => {
1919 if !adt.is_box() {
1920 ::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");
1921 }
1922 }
1923 ty::Bool
1924 | ty::Char
1925 | ty::Int(_)
1926 | ty::Uint(_)
1927 | ty::Float(_)
1928 | ty::Foreign(_)
1929 | ty::Str
1930 | ty::Array(_, _)
1931 | ty::Pat(_, _)
1932 | ty::Slice(_)
1933 | ty::FnDef(_, _)
1934 | ty::FnPtr(..)
1935 | ty::Dynamic(_, _)
1936 | ty::Closure(_, _)
1937 | ty::CoroutineClosure(_, _)
1938 | ty::Coroutine(_, _)
1939 | ty::CoroutineWitness(..)
1940 | ty::Never
1941 | ty::Tuple(_)
1942 | ty::UnsafeBinder(_)
1943 | ty::Alias(_, _)
1944 | ty::Param(_)
1945 | ty::Bound(_, _)
1946 | ty::Infer(_)
1947 | ty::Error(_)
1948 | ty::Placeholder(_) => {
1949 ::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:#?}")
1950 }
1951 },
1952 ProjectionElem::Field(_, _) => match place_ty.ty.kind() {
1953 ty::Adt(adt, _) => {
1954 if adt.has_dtor(tcx) {
1955 self.move_errors.push(MoveError::new(
1956 place,
1957 location,
1958 InteriorOfTypeWithDestructor { container_ty: place_ty.ty },
1959 ));
1960 return;
1961 }
1962 }
1963 ty::Closure(..)
1964 | ty::CoroutineClosure(..)
1965 | ty::Coroutine(_, _)
1966 | ty::Tuple(_) => (),
1967 ty::Bool
1968 | ty::Char
1969 | ty::Int(_)
1970 | ty::Uint(_)
1971 | ty::Float(_)
1972 | ty::Foreign(_)
1973 | ty::Str
1974 | ty::Array(_, _)
1975 | ty::Pat(_, _)
1976 | ty::Slice(_)
1977 | ty::RawPtr(_, _)
1978 | ty::Ref(_, _, _)
1979 | ty::FnDef(_, _)
1980 | ty::FnPtr(..)
1981 | ty::Dynamic(_, _)
1982 | ty::CoroutineWitness(..)
1983 | ty::Never
1984 | ty::UnsafeBinder(_)
1985 | ty::Alias(_, _)
1986 | ty::Param(_)
1987 | ty::Bound(_, _)
1988 | ty::Infer(_)
1989 | ty::Error(_)
1990 | 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!(
1991 "When Place contains ProjectionElem::Field it's type shouldn't be {place_ty:#?}"
1992 ),
1993 },
1994 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
1995 match place_ty.ty.kind() {
1996 ty::Slice(_) => {
1997 self.move_errors.push(MoveError::new(
1998 place,
1999 location,
2000 InteriorOfSliceOrArray { ty: place_ty.ty, is_index: false },
2001 ));
2002 return;
2003 }
2004 ty::Array(_, _) => (),
2005 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected type {0:#?}",
place_ty.ty))bug!("Unexpected type {:#?}", place_ty.ty),
2006 }
2007 }
2008 ProjectionElem::Index(_) => match place_ty.ty.kind() {
2009 ty::Array(..) | ty::Slice(..) => {
2010 self.move_errors.push(MoveError::new(
2011 place,
2012 location,
2013 InteriorOfSliceOrArray { ty: place_ty.ty, is_index: true },
2014 ));
2015 return;
2016 }
2017 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected type {0:#?}",
place_ty))bug!("Unexpected type {place_ty:#?}"),
2018 },
2019 ProjectionElem::OpaqueCast(_)
2023 | ProjectionElem::Downcast(_, _)
2024 | ProjectionElem::UnwrapUnsafeBinder(_) => (),
2025 }
2026
2027 place_ty = place_ty.projection_ty(tcx, elem);
2028 }
2029 }
2030
2031 fn check_if_full_path_is_moved(
2032 &mut self,
2033 location: Location,
2034 desired_action: InitializationRequiringAction,
2035 place_span: (PlaceRef<'tcx>, Span),
2036 state: &BorrowckDomain,
2037 ) {
2038 let maybe_uninits = &state.uninits;
2039
2040 {
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:2075",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2075u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_if_full_path_is_moved place: {0:?}",
place_span.0) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
2076 let (prefix, mpi) = self.move_path_closest_to(place_span.0);
2077 if maybe_uninits.contains(mpi) {
2078 self.report_use_of_moved_or_uninitialized(
2079 location,
2080 desired_action,
2081 (prefix, place_span.0, place_span.1),
2082 mpi,
2083 );
2084 } }
2091
2092 fn check_if_subslice_element_is_moved(
2098 &mut self,
2099 location: Location,
2100 desired_action: InitializationRequiringAction,
2101 place_span: (PlaceRef<'tcx>, Span),
2102 maybe_uninits: &MixedBitSet<MovePathIndex>,
2103 from: u64,
2104 to: u64,
2105 ) {
2106 if let Some(mpi) = self.move_path_for_place(place_span.0) {
2107 let move_paths = &self.move_data.move_paths;
2108
2109 let root_path = &move_paths[mpi];
2110 for (child_mpi, child_move_path) in root_path.children(move_paths) {
2111 let last_proj = child_move_path.place.projection.last().unwrap();
2112 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
2113 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`.");
2114
2115 if (from..to).contains(offset) {
2116 let uninit_child =
2117 self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
2118 maybe_uninits.contains(mpi)
2119 });
2120
2121 if let Some(uninit_child) = uninit_child {
2122 self.report_use_of_moved_or_uninitialized(
2123 location,
2124 desired_action,
2125 (place_span.0, place_span.0, place_span.1),
2126 uninit_child,
2127 );
2128 return; }
2130 }
2131 }
2132 }
2133 }
2134 }
2135
2136 fn check_if_path_or_subpath_is_moved(
2137 &mut self,
2138 location: Location,
2139 desired_action: InitializationRequiringAction,
2140 place_span: (PlaceRef<'tcx>, Span),
2141 state: &BorrowckDomain,
2142 ) {
2143 let maybe_uninits = &state.uninits;
2144
2145 self.check_if_full_path_is_moved(location, desired_action, place_span, state);
2161
2162 if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
2163 place_span.0.last_projection()
2164 {
2165 let place_ty = place_base.ty(self.body(), self.infcx.tcx);
2166 if let ty::Array(..) = place_ty.ty.kind() {
2167 self.check_if_subslice_element_is_moved(
2168 location,
2169 desired_action,
2170 (place_base, place_span.1),
2171 maybe_uninits,
2172 from,
2173 to,
2174 );
2175 return;
2176 }
2177 }
2178
2179 {
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:2188",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2188u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_if_path_or_subpath_is_moved place: {0:?}",
place_span.0) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
2189 if let Some(mpi) = self.move_path_for_place(place_span.0) {
2190 let uninit_mpi = self
2191 .move_data
2192 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
2193
2194 if let Some(uninit_mpi) = uninit_mpi {
2195 self.report_use_of_moved_or_uninitialized(
2196 location,
2197 desired_action,
2198 (place_span.0, place_span.0, place_span.1),
2199 uninit_mpi,
2200 );
2201 return; }
2203 }
2204 }
2205
2206 fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
2217 match self.move_data.rev_lookup.find(place) {
2218 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
2219 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
2220 }
2221 LookupResult::Parent(None) => {
::core::panicking::panic_fmt(format_args!("should have move path for every Local"));
}panic!("should have move path for every Local"),
2222 }
2223 }
2224
2225 fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
2226 match self.move_data.rev_lookup.find(place) {
2231 LookupResult::Parent(_) => None,
2232 LookupResult::Exact(mpi) => Some(mpi),
2233 }
2234 }
2235
2236 fn check_if_assigned_path_is_moved(
2237 &mut self,
2238 location: Location,
2239 (place, span): (Place<'tcx>, Span),
2240 state: &BorrowckDomain,
2241 ) {
2242 {
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:2242",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2242u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_if_assigned_path_is_moved place: {0:?}",
place) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_if_assigned_path_is_moved place: {:?}", place);
2243
2244 for (place_base, elem) in place.iter_projections().rev() {
2246 match elem {
2247 ProjectionElem::Index(_)
2248 | ProjectionElem::OpaqueCast(_)
2249 | ProjectionElem::ConstantIndex { .. }
2251 | ProjectionElem::Downcast(_, _) =>
2255 {}
2256
2257 ProjectionElem::UnwrapUnsafeBinder(_) => {
2258 check_parent_of_field(self, location, place_base, span, state);
2259 }
2260
2261 ProjectionElem::Deref => {
2263 self.check_if_full_path_is_moved(
2264 location,
2265 InitializationRequiringAction::Use,
2266 (place_base, span),
2267 state,
2268 );
2269 break;
2272 }
2273
2274 ProjectionElem::Subslice { .. } => {
2275 {
::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:?}");
2276 }
2277
2278 ProjectionElem::Field(..) => {
2279 let tcx = self.infcx.tcx;
2283 let base_ty = place_base.ty(self.body(), tcx).ty;
2284 match base_ty.kind() {
2285 ty::Adt(def, _) if def.has_dtor(tcx) => {
2286 self.check_if_path_or_subpath_is_moved(
2287 location,
2288 InitializationRequiringAction::Assignment,
2289 (place_base, span),
2290 state,
2291 );
2292
2293 break;
2296 }
2297
2298 ty::Adt(..) | ty::Tuple(..) => {
2301 check_parent_of_field(self, location, place_base, span, state);
2302 }
2303
2304 _ => {}
2305 }
2306 }
2307 }
2308 }
2309
2310 fn check_parent_of_field<'a, 'tcx>(
2311 this: &mut MirBorrowckCtxt<'a, '_, 'tcx>,
2312 location: Location,
2313 base: PlaceRef<'tcx>,
2314 span: Span,
2315 state: &BorrowckDomain,
2316 ) {
2317 let maybe_uninits = &state.uninits;
2349
2350 let mut shortest_uninit_seen = None;
2353 for prefix in this.prefixes(base, PrefixSet::Shallow) {
2354 let Some(mpi) = this.move_path_for_place(prefix) else { continue };
2355
2356 if maybe_uninits.contains(mpi) {
2357 {
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:2357",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2357u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
});
} else { ; }
};debug!(
2358 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
2359 shortest_uninit_seen,
2360 Some((prefix, mpi))
2361 );
2362 shortest_uninit_seen = Some((prefix, mpi));
2363 } else {
2364 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2364",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2364u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_parent_of_field {0:?} is definitely initialized",
(prefix, mpi)) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
2365 }
2366 }
2367
2368 if let Some((prefix, mpi)) = shortest_uninit_seen {
2369 let tcx = this.infcx.tcx;
2375 if base.ty(this.body(), tcx).ty.is_union()
2376 && this.move_data.move_out_path_map[mpi].iter().any(|moi| {
2377 this.move_data.move_outs[*moi].source.is_predecessor_of(location, this.body)
2378 })
2379 {
2380 return;
2381 }
2382
2383 this.report_use_of_moved_or_uninitialized(
2384 location,
2385 InitializationRequiringAction::PartialAssignment,
2386 (prefix, base, span),
2387 mpi,
2388 );
2389
2390 this.used_mut.insert(base.local);
2394 }
2395 }
2396 }
2397
2398 fn check_access_permissions(
2402 &mut self,
2403 (place, span): (Place<'tcx>, Span),
2404 kind: ReadOrWrite,
2405 is_local_mutation_allowed: LocalMutationIsAllowed,
2406 state: &BorrowckDomain,
2407 location: Location,
2408 ) -> bool {
2409 {
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:2409",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2409u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
});
} else { ; }
};debug!(
2410 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
2411 place, kind, is_local_mutation_allowed
2412 );
2413
2414 let error_access;
2415 let the_place_err;
2416
2417 match kind {
2418 Reservation(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind }))
2419 | Write(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind })) => {
2420 let is_local_mutation_allowed = match mut_borrow_kind {
2421 MutBorrowKind::ClosureCapture => LocalMutationIsAllowed::Yes,
2425 MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow => {
2426 is_local_mutation_allowed
2427 }
2428 };
2429 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2430 Ok(root_place) => {
2431 self.add_used_mut(root_place, state);
2432 return false;
2433 }
2434 Err(place_err) => {
2435 error_access = AccessKind::MutableBorrow;
2436 the_place_err = place_err;
2437 }
2438 }
2439 }
2440 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
2441 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2442 Ok(root_place) => {
2443 self.add_used_mut(root_place, state);
2444 return false;
2445 }
2446 Err(place_err) => {
2447 error_access = AccessKind::Mutate;
2448 the_place_err = place_err;
2449 }
2450 }
2451 }
2452
2453 Reservation(
2454 WriteKind::Move
2455 | WriteKind::Replace
2456 | WriteKind::StorageDeadOrDrop
2457 | WriteKind::MutableBorrow(BorrowKind::Shared)
2458 | WriteKind::MutableBorrow(BorrowKind::Fake(_)),
2459 )
2460 | Write(
2461 WriteKind::Move
2462 | WriteKind::Replace
2463 | WriteKind::StorageDeadOrDrop
2464 | WriteKind::MutableBorrow(BorrowKind::Shared)
2465 | WriteKind::MutableBorrow(BorrowKind::Fake(_)),
2466 ) => {
2467 if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err()
2468 && !self.has_buffered_diags()
2469 {
2470 self.dcx().span_delayed_bug(
2476 span,
2477 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Accessing `{0:?}` with the kind `{1:?}` shouldn\'t be possible",
place, kind))
})format!(
2478 "Accessing `{place:?}` with the kind `{kind:?}` shouldn't be possible",
2479 ),
2480 );
2481 }
2482 return false;
2483 }
2484 Activation(..) => {
2485 return false;
2487 }
2488 Read(
2489 ReadKind::Borrow(BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_))
2490 | ReadKind::Copy,
2491 ) => {
2492 return false;
2494 }
2495 }
2496
2497 let previously_initialized = self.is_local_ever_initialized(place.local, state);
2502
2503 if let Some(init_index) = previously_initialized {
2505 if let (AccessKind::Mutate, Some(_)) = (error_access, place.as_local()) {
2506 let init = &self.move_data.inits[init_index];
2509 let assigned_span = init.span(self.body);
2510 self.report_illegal_reassignment((place, span), assigned_span, place);
2511 } else {
2512 self.report_mutability_error(place, span, the_place_err, error_access, location)
2513 }
2514 true
2515 } else {
2516 false
2517 }
2518 }
2519
2520 fn is_local_ever_initialized(&self, local: Local, state: &BorrowckDomain) -> Option<InitIndex> {
2521 let mpi = self.move_data.rev_lookup.find_local(local)?;
2522 let ii = &self.move_data.init_path_map[mpi];
2523 ii.into_iter().find(|&&index| state.ever_inits.contains(index)).copied()
2524 }
2525
2526 fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, state: &BorrowckDomain) {
2528 match root_place {
2529 RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2530 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2534 && self.is_local_ever_initialized(local, state).is_some()
2535 {
2536 self.used_mut.insert(local);
2537 }
2538 }
2539 RootPlace {
2540 place_local: _,
2541 place_projection: _,
2542 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2543 } => {}
2544 RootPlace {
2545 place_local,
2546 place_projection: place_projection @ [.., _],
2547 is_local_mutation_allowed: _,
2548 } => {
2549 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2550 local: place_local,
2551 projection: place_projection,
2552 }) {
2553 self.used_mut_upvars.push(field);
2554 }
2555 }
2556 }
2557 }
2558
2559 fn is_mutable(
2562 &self,
2563 place: PlaceRef<'tcx>,
2564 is_local_mutation_allowed: LocalMutationIsAllowed,
2565 ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2566 {
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:2566",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2566u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("is_mutable: place={0:?}, is_local...={1:?}",
place, is_local_mutation_allowed) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2567 match place.last_projection() {
2568 None => {
2569 let local = &self.body.local_decls[place.local];
2570 match local.mutability {
2571 Mutability::Not => match is_local_mutation_allowed {
2572 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2573 place_local: place.local,
2574 place_projection: place.projection,
2575 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2576 }),
2577 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2578 place_local: place.local,
2579 place_projection: place.projection,
2580 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2581 }),
2582 LocalMutationIsAllowed::No => Err(place),
2583 },
2584 Mutability::Mut => Ok(RootPlace {
2585 place_local: place.local,
2586 place_projection: place.projection,
2587 is_local_mutation_allowed,
2588 }),
2589 }
2590 }
2591 Some((place_base, elem)) => {
2592 match elem {
2593 ProjectionElem::Deref => {
2594 let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2595
2596 match base_ty.kind() {
2598 ty::Ref(_, _, mutbl) => {
2599 match mutbl {
2600 hir::Mutability::Not => Err(place),
2602 hir::Mutability::Mut => {
2605 let mode = match self.is_upvar_field_projection(place) {
2606 Some(field)
2607 if self.upvars[field.index()].is_by_ref() =>
2608 {
2609 is_local_mutation_allowed
2610 }
2611 _ => LocalMutationIsAllowed::Yes,
2612 };
2613
2614 self.is_mutable(place_base, mode)
2615 }
2616 }
2617 }
2618 ty::RawPtr(_, mutbl) => {
2619 match mutbl {
2620 hir::Mutability::Not => Err(place),
2622 hir::Mutability::Mut => Ok(RootPlace {
2625 place_local: place.local,
2626 place_projection: place.projection,
2627 is_local_mutation_allowed,
2628 }),
2629 }
2630 }
2631 _ if base_ty.is_box() => {
2633 self.is_mutable(place_base, is_local_mutation_allowed)
2634 }
2635 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Deref of unexpected type: {0:?}",
base_ty))bug!("Deref of unexpected type: {:?}", base_ty),
2637 }
2638 }
2639 ProjectionElem::Field(FieldIdx::ZERO, _)
2642 if let Some(adt) =
2643 place_base.ty(self.body(), self.infcx.tcx).ty.ty_adt_def()
2644 && adt.is_pin()
2645 && self.infcx.tcx.features().pin_ergonomics() =>
2646 {
2647 self.is_mutable(place_base, is_local_mutation_allowed)
2648 }
2649 ProjectionElem::Field(..)
2652 | ProjectionElem::Index(..)
2653 | ProjectionElem::ConstantIndex { .. }
2654 | ProjectionElem::Subslice { .. }
2655 | ProjectionElem::OpaqueCast { .. }
2656 | ProjectionElem::Downcast(..)
2657 | ProjectionElem::UnwrapUnsafeBinder(_) => {
2658 let upvar_field_projection = self.is_upvar_field_projection(place);
2659 if let Some(field) = upvar_field_projection {
2660 let upvar = &self.upvars[field.index()];
2661 {
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:2661",
"rustc_borrowck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2661u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
});
} else { ; }
};debug!(
2662 "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2663 place={:?}, place_base={:?}",
2664 upvar, is_local_mutation_allowed, place, place_base
2665 );
2666 match (upvar.mutability, is_local_mutation_allowed) {
2667 (
2668 Mutability::Not,
2669 LocalMutationIsAllowed::No
2670 | LocalMutationIsAllowed::ExceptUpvars,
2671 ) => Err(place),
2672 (Mutability::Not, LocalMutationIsAllowed::Yes)
2673 | (Mutability::Mut, _) => {
2674 let _ =
2693 self.is_mutable(place_base, is_local_mutation_allowed)?;
2694 Ok(RootPlace {
2695 place_local: place.local,
2696 place_projection: place.projection,
2697 is_local_mutation_allowed,
2698 })
2699 }
2700 }
2701 } else {
2702 self.is_mutable(place_base, is_local_mutation_allowed)
2703 }
2704 }
2705 }
2706 }
2707 }
2708 }
2709
2710 fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<FieldIdx> {
2715 path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2716 }
2717
2718 fn dominators(&self) -> &Dominators<BasicBlock> {
2719 self.body.basic_blocks.dominators()
2721 }
2722
2723 fn lint_unused_mut(&self) {
2724 let tcx = self.infcx.tcx;
2725 let body = self.body;
2726 for local in body.mut_vars_and_args_iter().filter(|local| !self.used_mut.contains(local)) {
2727 let local_decl = &body.local_decls[local];
2728 let ClearCrossCrate::Set(SourceScopeLocalData { lint_root, .. }) =
2729 body.source_scopes[local_decl.source_info.scope].local_data
2730 else {
2731 continue;
2732 };
2733
2734 if self.local_excluded_from_unused_mut_lint(local) {
2736 continue;
2737 }
2738
2739 let span = local_decl.source_info.span;
2740 if span.desugaring_kind().is_some() {
2741 continue;
2743 }
2744
2745 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
2746
2747 tcx.emit_node_span_lint(UNUSED_MUT, lint_root, span, VarNeedNotMut { span: mut_span })
2748 }
2749 }
2750}
2751
2752enum Overlap {
2754 Arbitrary,
2760 EqualOrDisjoint,
2765 Disjoint,
2768}