1use std::iter;
4use std::ops::ControlFlow;
5
6use either::Either;
7use hir::{ClosureKind, Path};
8use rustc_data_structures::fx::FxIndexSet;
9use rustc_errors::codes::*;
10use rustc_errors::{Applicability, Diag, MultiSpan, struct_span_code_err};
11use rustc_hir as hir;
12use rustc_hir::attrs::diagnostic::{CustomDiagnostic, FormatArgs};
13use rustc_hir::def::{DefKind, Res};
14use rustc_hir::intravisit::{Visitor, walk_block, walk_expr};
15use rustc_hir::{
16 CoroutineDesugaring, CoroutineKind, CoroutineSource, LangItem, PatField, find_attr,
17};
18use rustc_middle::bug;
19use rustc_middle::hir::nested_filter::OnlyBodies;
20use rustc_middle::mir::{
21 self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, ConstraintCategory,
22 FakeBorrowKind, FakeReadCause, LocalDecl, LocalInfo, LocalKind, Location, MutBorrowKind,
23 Operand, Place, PlaceRef, PlaceTy, ProjectionElem, Rvalue, Statement, StatementKind,
24 Terminator, TerminatorKind, VarBindingForm, VarDebugInfoContents,
25};
26use rustc_middle::ty::print::PrintTraitRefExt as _;
27use rustc_middle::ty::{
28 self, PredicateKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor, Upcast,
29 suggest_constraining_type_params,
30};
31use rustc_mir_dataflow::move_paths::{InitKind, MoveOutIndex, MovePathIndex};
32use rustc_span::def_id::{DefId, LocalDefId};
33use rustc_span::hygiene::DesugaringKind;
34use rustc_span::{BytePos, ExpnKind, Ident, MacroKind, Span, Symbol, kw, sym};
35use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
36use rustc_trait_selection::error_reporting::traits::FindExprBySpan;
37use rustc_trait_selection::error_reporting::traits::call_kind::CallKind;
38use rustc_trait_selection::infer::InferCtxtExt;
39use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
40use rustc_trait_selection::traits::{
41 Obligation, ObligationCause, ObligationCtxt, supertrait_def_ids,
42};
43use tracing::{debug, instrument};
44
45use super::explain_borrow::{BorrowExplanation, LaterUseKind};
46use super::{DescribePlaceOpt, RegionName, RegionNameSource, UseSpans};
47use crate::borrow_set::{BorrowData, TwoPhaseActivation};
48use crate::diagnostics::conflict_errors::StorageDeadOrDrop::LocalStorageDead;
49use crate::diagnostics::{CapturedMessageOpt, call_kind, find_all_local_uses};
50use crate::{InitializationRequiringAction, MirBorrowckCtxt, WriteKind, borrowck_errors};
51
52#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MoveSite {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "MoveSite",
"moi", &self.moi, "traversed_back_edge",
&&self.traversed_back_edge)
}
}Debug)]
53struct MoveSite {
54 moi: MoveOutIndex,
57
58 traversed_back_edge: bool,
61}
62
63#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for StorageDeadOrDrop<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for StorageDeadOrDrop<'tcx> {
#[inline]
fn clone(&self) -> StorageDeadOrDrop<'tcx> {
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for StorageDeadOrDrop<'tcx> {
#[inline]
fn eq(&self, other: &StorageDeadOrDrop<'tcx>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(StorageDeadOrDrop::Destructor(__self_0),
StorageDeadOrDrop::Destructor(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for StorageDeadOrDrop<'tcx> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
}
}Eq, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for StorageDeadOrDrop<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
StorageDeadOrDrop::LocalStorageDead =>
::core::fmt::Formatter::write_str(f, "LocalStorageDead"),
StorageDeadOrDrop::BoxedStorageDead =>
::core::fmt::Formatter::write_str(f, "BoxedStorageDead"),
StorageDeadOrDrop::Destructor(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Destructor", &__self_0),
}
}
}Debug)]
65enum StorageDeadOrDrop<'tcx> {
66 LocalStorageDead,
67 BoxedStorageDead,
68 Destructor(Ty<'tcx>),
69}
70
71impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
72 pub(crate) fn report_use_of_moved_or_uninitialized(
73 &mut self,
74 location: Location,
75 desired_action: InitializationRequiringAction,
76 (moved_place, used_place, span): (PlaceRef<'tcx>, PlaceRef<'tcx>, Span),
77 mpi: MovePathIndex,
78 ) {
79 {
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/diagnostics/conflict_errors.rs:79",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(79u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized: location={0:?} desired_action={1:?} moved_place={2:?} used_place={3:?} span={4:?} mpi={5:?}",
location, desired_action, moved_place, used_place, span,
mpi) as &dyn Value))])
});
} else { ; }
};debug!(
80 "report_use_of_moved_or_uninitialized: location={:?} desired_action={:?} \
81 moved_place={:?} used_place={:?} span={:?} mpi={:?}",
82 location, desired_action, moved_place, used_place, span, mpi
83 );
84
85 let use_spans =
86 self.move_spans(moved_place, location).or_else(|| self.borrow_spans(span, location));
87 let span = use_spans.args_or_use();
88
89 let (move_site_vec, maybe_reinitialized_locations) = self.get_moved_indexes(location, mpi);
90 {
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/diagnostics/conflict_errors.rs:90",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(90u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized: move_site_vec={0:?} use_spans={1:?}",
move_site_vec, use_spans) as &dyn Value))])
});
} else { ; }
};debug!(
91 "report_use_of_moved_or_uninitialized: move_site_vec={:?} use_spans={:?}",
92 move_site_vec, use_spans
93 );
94 let move_out_indices: Vec<_> =
95 move_site_vec.iter().map(|move_site| move_site.moi).collect();
96
97 if move_out_indices.is_empty() {
98 let root_local = used_place.local;
99
100 if !self.uninitialized_error_reported.insert(root_local) {
101 {
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/diagnostics/conflict_errors.rs:101",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(101u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized place: error about {0:?} suppressed",
root_local) as &dyn Value))])
});
} else { ; }
};debug!(
102 "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
103 root_local
104 );
105 return;
106 }
107
108 let err = self.report_use_of_uninitialized(
109 mpi,
110 used_place,
111 moved_place,
112 desired_action,
113 span,
114 use_spans,
115 );
116 self.buffer_error(err);
117 } else {
118 if let Some((reported_place, _)) = self.has_move_error(&move_out_indices) {
119 if used_place.is_prefix_of(*reported_place) {
120 {
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/diagnostics/conflict_errors.rs:120",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(120u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized place: error suppressed mois={0:?}",
move_out_indices) as &dyn Value))])
});
} else { ; }
};debug!(
121 "report_use_of_moved_or_uninitialized place: error suppressed mois={:?}",
122 move_out_indices
123 );
124 return;
125 }
126 }
127
128 let is_partial_move = move_site_vec.iter().any(|move_site| {
129 let move_out = self.move_data.moves[(*move_site).moi];
130 let moved_place = &self.move_data.move_paths[move_out.path].place;
131 let is_box_move = moved_place.as_ref().projection == [ProjectionElem::Deref]
133 && self.body.local_decls[moved_place.local].ty.is_box();
134
135 !is_box_move
136 && used_place != moved_place.as_ref()
137 && used_place.is_prefix_of(moved_place.as_ref())
138 });
139
140 let partial_str = if is_partial_move { "partial " } else { "" };
141 let partially_str = if is_partial_move { "partially " } else { "" };
142
143 let (on_move_message, on_move_label, on_move_notes) = if let ty::Adt(item_def, args) =
144 self.body.local_decls[moved_place.local].ty.kind()
145 && let Some(Some(directive)) = {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(item_def.did(),
&self.infcx.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(OnMove { directive, .. }) => {
break 'done Some(directive);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(self.infcx.tcx, item_def.did(), OnMove { directive, .. } => directive)
146 {
147 let this = self.infcx.tcx.item_name(item_def.did()).to_string();
148 let mut generic_args: Vec<_> = self
149 .infcx
150 .tcx
151 .generics_of(item_def.did())
152 .own_params
153 .iter()
154 .filter_map(|param| Some((param.name, args[param.index as usize].to_string())))
155 .collect();
156 generic_args.push((kw::SelfUpper, this.clone()));
157
158 let args = FormatArgs { this, generic_args, .. };
159 let CustomDiagnostic { message, label, notes, parent_label: _ } =
160 directive.eval(None, &args);
161
162 (message, label, notes)
163 } else {
164 (None, None, Vec::new())
165 };
166
167 let mut err = self.cannot_act_on_moved_value(
168 span,
169 desired_action.as_noun(),
170 partially_str,
171 self.describe_place_with_options(
172 moved_place,
173 DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
174 ),
175 on_move_message,
176 );
177
178 for note in on_move_notes {
179 err.note(note);
180 }
181
182 let reinit_spans = maybe_reinitialized_locations
183 .iter()
184 .take(3)
185 .map(|loc| {
186 self.move_spans(self.move_data.move_paths[mpi].place.as_ref(), *loc)
187 .args_or_use()
188 })
189 .collect::<Vec<Span>>();
190
191 let reinits = maybe_reinitialized_locations.len();
192 if reinits == 1 {
193 err.span_label(reinit_spans[0], "this reinitialization might get skipped");
194 } else if reinits > 1 {
195 err.span_note(
196 MultiSpan::from_spans(reinit_spans),
197 if reinits <= 3 {
198 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("these {0} reinitializations might get skipped",
reinits))
})format!("these {reinits} reinitializations might get skipped")
199 } else {
200 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("these 3 reinitializations and {0} other{1} might get skipped",
reinits - 3, if reinits == 4 { "" } else { "s" }))
})format!(
201 "these 3 reinitializations and {} other{} might get skipped",
202 reinits - 3,
203 if reinits == 4 { "" } else { "s" }
204 )
205 },
206 );
207 }
208
209 let closure = self.add_moved_or_invoked_closure_note(location, used_place, &mut err);
210
211 let mut is_loop_move = false;
212 let mut seen_spans = FxIndexSet::default();
213
214 for move_site in &move_site_vec {
215 let move_out = self.move_data.moves[(*move_site).moi];
216 let moved_place = &self.move_data.move_paths[move_out.path].place;
217
218 let move_spans = self.move_spans(moved_place.as_ref(), move_out.source);
219 let move_span = move_spans.args_or_use();
220
221 let is_move_msg = move_spans.for_closure();
222
223 let is_loop_message = location == move_out.source || move_site.traversed_back_edge;
224
225 if location == move_out.source {
226 is_loop_move = true;
227 }
228
229 let mut has_suggest_reborrow = false;
230 if !seen_spans.contains(&move_span) {
231 self.suggest_ref_or_clone(
232 mpi,
233 &mut err,
234 move_spans,
235 moved_place.as_ref(),
236 &mut has_suggest_reborrow,
237 closure,
238 );
239
240 let msg_opt = CapturedMessageOpt {
241 is_partial_move,
242 is_loop_message,
243 is_move_msg,
244 is_loop_move,
245 has_suggest_reborrow,
246 maybe_reinitialized_locations_is_empty: maybe_reinitialized_locations
247 .is_empty(),
248 };
249 self.explain_captures(
250 &mut err,
251 span,
252 move_span,
253 move_spans,
254 *moved_place,
255 msg_opt,
256 );
257 }
258 seen_spans.insert(move_span);
259 }
260
261 use_spans.var_path_only_subdiag(&mut err, desired_action);
262
263 if !is_loop_move {
264 err.span_label(
265 span,
266 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("value {0} here after {1}move",
desired_action.as_verb_in_past_tense(), partial_str))
})format!(
267 "value {} here after {partial_str}move",
268 desired_action.as_verb_in_past_tense(),
269 ),
270 );
271 }
272
273 let ty = used_place.ty(self.body, self.infcx.tcx).ty;
274 let needs_note = match ty.kind() {
275 ty::Closure(id, _) => {
276 self.infcx.tcx.closure_kind_origin(id.expect_local()).is_none()
277 }
278 _ => true,
279 };
280
281 let mpi = self.move_data.moves[move_out_indices[0]].path;
282 let place = &self.move_data.move_paths[mpi].place;
283 let ty = place.ty(self.body, self.infcx.tcx).ty;
284
285 if self.infcx.param_env.caller_bounds().iter().any(|c| {
286 c.as_trait_clause().is_some_and(|pred| {
287 pred.skip_binder().self_ty() == ty && self.infcx.tcx.is_fn_trait(pred.def_id())
288 })
289 }) {
290 } else {
294 let copy_did = self.infcx.tcx.require_lang_item(LangItem::Copy, span);
295 self.suggest_adding_bounds(&mut err, ty, copy_did, span);
296 }
297
298 let opt_name = self.describe_place_with_options(
299 place.as_ref(),
300 DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
301 );
302 let note_msg = match opt_name {
303 Some(name) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
})format!("`{name}`"),
304 None => "value".to_owned(),
305 };
306 if needs_note {
307 if let Some(local) = place.as_local() {
308 let span = self.body.local_decls[local].source_info.span;
309 if let Some(on_move_label) = on_move_label {
310 err.span_label(span, on_move_label);
311 } else {
312 err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label {
313 is_partial_move,
314 ty,
315 place: ¬e_msg,
316 span,
317 });
318 }
319 } else {
320 err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Note {
321 is_partial_move,
322 ty,
323 place: ¬e_msg,
324 });
325 };
326 }
327
328 if let UseSpans::FnSelfUse {
329 kind: CallKind::DerefCoercion { deref_target_span, deref_target_ty, .. },
330 ..
331 } = use_spans
332 {
333 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} occurs due to deref coercion to `{1}`",
desired_action.as_noun(), deref_target_ty))
})format!(
334 "{} occurs due to deref coercion to `{deref_target_ty}`",
335 desired_action.as_noun(),
336 ));
337
338 if let Some(deref_target_span) = deref_target_span
340 && self.infcx.tcx.sess.source_map().is_span_accessible(deref_target_span)
341 {
342 err.span_note(deref_target_span, "deref defined here");
343 }
344 }
345
346 self.buffer_move_error(move_out_indices, (used_place, err));
347 }
348 }
349
350 fn suggest_ref_or_clone(
351 &self,
352 mpi: MovePathIndex,
353 err: &mut Diag<'infcx>,
354 move_spans: UseSpans<'tcx>,
355 moved_place: PlaceRef<'tcx>,
356 has_suggest_reborrow: &mut bool,
357 moved_or_invoked_closure: bool,
358 ) {
359 let move_span = match move_spans {
360 UseSpans::ClosureUse { capture_kind_span, .. } => capture_kind_span,
361 _ => move_spans.args_or_use(),
362 };
363 struct ExpressionFinder<'hir> {
364 expr_span: Span,
365 expr: Option<&'hir hir::Expr<'hir>>,
366 pat: Option<&'hir hir::Pat<'hir>>,
367 parent_pat: Option<&'hir hir::Pat<'hir>>,
368 tcx: TyCtxt<'hir>,
369 }
370 impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
371 type NestedFilter = OnlyBodies;
372
373 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
374 self.tcx
375 }
376
377 fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
378 if e.span == self.expr_span {
379 self.expr = Some(e);
380 }
381 hir::intravisit::walk_expr(self, e);
382 }
383 fn visit_pat(&mut self, p: &'hir hir::Pat<'hir>) {
384 if p.span == self.expr_span {
385 self.pat = Some(p);
386 }
387 if let hir::PatKind::Binding(hir::BindingMode::NONE, _, i, sub) = p.kind {
388 if i.span == self.expr_span || p.span == self.expr_span {
389 self.pat = Some(p);
390 }
391 if let Some(subpat) = sub
394 && self.pat.is_none()
395 {
396 self.visit_pat(subpat);
397 if self.pat.is_some() {
398 self.parent_pat = Some(p);
399 }
400 return;
401 }
402 }
403 hir::intravisit::walk_pat(self, p);
404 }
405 }
406 let tcx = self.infcx.tcx;
407 if let Some(body) = tcx.hir_maybe_body_owned_by(self.mir_def_id()) {
408 let expr = body.value;
409 let place = &self.move_data.move_paths[mpi].place;
410 let span = place.as_local().map(|local| self.body.local_decls[local].source_info.span);
411 let mut finder = ExpressionFinder {
412 expr_span: move_span,
413 expr: None,
414 pat: None,
415 parent_pat: None,
416 tcx,
417 };
418 finder.visit_expr(expr);
419 if let Some(span) = span
420 && let Some(expr) = finder.expr
421 {
422 for (_, expr) in tcx.hir_parent_iter(expr.hir_id) {
423 if let hir::Node::Expr(expr) = expr {
424 if expr.span.contains(span) {
425 break;
437 }
438 if let hir::ExprKind::Loop(.., loop_span) = expr.kind {
439 err.span_label(loop_span, "inside of this loop");
440 }
441 }
442 }
443 let typeck = self.infcx.tcx.typeck(self.mir_def_id());
444 let parent = self.infcx.tcx.parent_hir_node(expr.hir_id);
445 let (def_id, args, offset) = if let hir::Node::Expr(parent_expr) = parent
446 && let hir::ExprKind::MethodCall(_, _, args, _) = parent_expr.kind
447 {
448 let def_id = typeck.type_dependent_def_id(parent_expr.hir_id);
449 (def_id, args, 1)
450 } else if let hir::Node::Expr(parent_expr) = parent
451 && let hir::ExprKind::Call(call, args) = parent_expr.kind
452 && let ty::FnDef(def_id, _) = typeck.node_type(call.hir_id).kind()
453 {
454 (Some(*def_id), args, 0)
455 } else {
456 (None, &[][..], 0)
457 };
458 let ty = place.ty(self.body, self.infcx.tcx).ty;
459
460 let mut can_suggest_clone = true;
461 if let Some(def_id) = def_id
462 && let Some(pos) = args.iter().position(|arg| arg.hir_id == expr.hir_id)
463 {
464 let arg_param = if self.infcx.tcx.def_kind(def_id).is_fn_like()
467 && let sig =
468 self.infcx.tcx.fn_sig(def_id).instantiate_identity().skip_binder()
469 && let Some(arg_ty) = sig.inputs().get(pos + offset)
470 && let ty::Param(arg_param) = arg_ty.kind()
471 {
472 Some(arg_param)
473 } else {
474 None
475 };
476
477 if let ty::Ref(_, _, hir::Mutability::Mut) = ty.kind()
484 && arg_param.is_some()
485 {
486 *has_suggest_reborrow = true;
487 self.suggest_reborrow(err, expr.span, moved_place);
488 return;
489 }
490
491 if let Some(¶m) = arg_param
494 && let hir::Node::Expr(call_expr) = parent
495 && let Some(ref_mutability) = self.suggest_borrow_generic_arg(
496 err,
497 typeck,
498 call_expr,
499 def_id,
500 param,
501 moved_place,
502 pos + offset,
503 ty,
504 expr.span,
505 )
506 {
507 can_suggest_clone = ref_mutability.is_mut();
508 } else if let Some(local_def_id) = def_id.as_local()
509 && let node = self.infcx.tcx.hir_node_by_def_id(local_def_id)
510 && let Some(fn_decl) = node.fn_decl()
511 && let Some(ident) = node.ident()
512 && let Some(arg) = fn_decl.inputs.get(pos + offset)
513 {
514 let mut span: MultiSpan = arg.span.into();
517 span.push_span_label(
518 arg.span,
519 "this parameter takes ownership of the value".to_string(),
520 );
521 let descr = match node.fn_kind() {
522 Some(hir::intravisit::FnKind::ItemFn(..)) | None => "function",
523 Some(hir::intravisit::FnKind::Method(..)) => "method",
524 Some(hir::intravisit::FnKind::Closure) => "closure",
525 };
526 span.push_span_label(ident.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in this {0}", descr))
})format!("in this {descr}"));
527 err.span_note(
528 span,
529 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider changing this parameter type in {0} `{1}` to borrow instead if owning the value isn\'t necessary",
descr, ident))
})format!(
530 "consider changing this parameter type in {descr} `{ident}` to \
531 borrow instead if owning the value isn't necessary",
532 ),
533 );
534 }
535 }
536 if let hir::Node::Expr(parent_expr) = parent
537 && let hir::ExprKind::Call(call_expr, _) = parent_expr.kind
538 && let hir::ExprKind::Path(qpath) = call_expr.kind
539 && tcx.qpath_is_lang_item(qpath, LangItem::IntoIterIntoIter)
540 {
541 } else if let UseSpans::FnSelfUse { kind: CallKind::Normal { .. }, .. } = move_spans
543 {
544 } else if moved_or_invoked_closure {
546 } else if let UseSpans::ClosureUse {
548 closure_kind:
549 ClosureKind::Coroutine(CoroutineKind::Desugared(_, CoroutineSource::Block)),
550 ..
551 } = move_spans
552 && can_suggest_clone
553 {
554 self.suggest_cloning(err, place.as_ref(), ty, expr, Some(move_spans));
555 } else if self.suggest_hoisting_call_outside_loop(err, expr) && can_suggest_clone {
556 self.suggest_cloning(err, place.as_ref(), ty, expr, Some(move_spans));
559 }
560 }
561
562 self.suggest_ref_for_dbg_args(expr, place, move_span, err);
563
564 if let Some(pat) = finder.pat
566 && !move_span.is_dummy()
567 && !self.infcx.tcx.sess.source_map().is_imported(move_span)
568 {
569 let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(pat.span.shrink_to_lo(), "ref ".to_string())]))vec![(pat.span.shrink_to_lo(), "ref ".to_string())];
570 if let Some(pat) = finder.parent_pat {
571 sugg.insert(0, (pat.span.shrink_to_lo(), "ref ".to_string()));
572 }
573 err.multipart_suggestion(
574 "borrow this binding in the pattern to avoid moving the value",
575 sugg,
576 Applicability::MachineApplicable,
577 );
578 }
579 }
580 }
581
582 fn suggest_ref_for_dbg_args(
586 &self,
587 body: &hir::Expr<'_>,
588 place: &Place<'tcx>,
589 move_span: Span,
590 err: &mut Diag<'infcx>,
591 ) {
592 let var_info = self.body.var_debug_info.iter().find(|info| match info.value {
593 VarDebugInfoContents::Place(ref p) => p == place,
594 _ => false,
595 });
596 let Some(var_info) = var_info else { return };
597 let arg_name = var_info.name;
598 struct MatchArgFinder {
599 expr_span: Span,
600 match_arg_span: Option<Span>,
601 arg_name: Symbol,
602 }
603 impl Visitor<'_> for MatchArgFinder {
604 fn visit_expr(&mut self, e: &hir::Expr<'_>) {
605 if let hir::ExprKind::Match(expr, ..) = &e.kind
607 && let hir::ExprKind::Path(hir::QPath::Resolved(
608 _,
609 path @ Path { segments: [seg], .. },
610 )) = &expr.kind
611 && seg.ident.name == self.arg_name
612 && self.expr_span.source_callsite().contains(expr.span)
613 {
614 self.match_arg_span = Some(path.span);
615 }
616 hir::intravisit::walk_expr(self, e);
617 }
618 }
619
620 let mut finder = MatchArgFinder { expr_span: move_span, match_arg_span: None, arg_name };
621 finder.visit_expr(body);
622 if let Some(macro_arg_span) = finder.match_arg_span {
623 err.span_suggestion_verbose(
624 macro_arg_span.shrink_to_lo(),
625 "consider borrowing instead of transferring ownership",
626 "&",
627 Applicability::MachineApplicable,
628 );
629 }
630 }
631
632 pub(crate) fn suggest_reborrow(
633 &self,
634 err: &mut Diag<'infcx>,
635 span: Span,
636 moved_place: PlaceRef<'tcx>,
637 ) {
638 err.span_suggestion_verbose(
639 span.shrink_to_lo(),
640 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider creating a fresh reborrow of {0} here",
self.describe_place(moved_place).map(|n|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", n))
})).unwrap_or_else(|| "the mutable reference".to_string())))
})format!(
641 "consider creating a fresh reborrow of {} here",
642 self.describe_place(moved_place)
643 .map(|n| format!("`{n}`"))
644 .unwrap_or_else(|| "the mutable reference".to_string()),
645 ),
646 "&mut *",
647 Applicability::MachineApplicable,
648 );
649 }
650
651 fn suggest_borrow_generic_arg(
658 &self,
659 err: &mut Diag<'_>,
660 typeck: &ty::TypeckResults<'tcx>,
661 call_expr: &hir::Expr<'tcx>,
662 callee_did: DefId,
663 param: ty::ParamTy,
664 moved_place: PlaceRef<'tcx>,
665 moved_arg_pos: usize,
666 moved_arg_ty: Ty<'tcx>,
667 place_span: Span,
668 ) -> Option<ty::Mutability> {
669 let tcx = self.infcx.tcx;
670 let sig = tcx.fn_sig(callee_did).instantiate_identity().skip_binder();
671 let clauses = tcx.predicates_of(callee_did);
672
673 let generic_args = match call_expr.kind {
674 hir::ExprKind::MethodCall(..) => typeck.node_args_opt(call_expr.hir_id)?,
676 hir::ExprKind::Call(callee, _)
679 if let &ty::FnDef(_, args) = typeck.node_type(callee.hir_id).kind() =>
680 {
681 args
682 }
683 _ => return None,
684 };
685
686 if !clauses.instantiate_identity(tcx).predicates.iter().any(|clause| {
689 clause.as_trait_clause().is_some_and(|tc| {
690 tc.self_ty().skip_binder().is_param(param.index)
691 && tc.polarity() == ty::PredicatePolarity::Positive
692 && supertrait_def_ids(tcx, tc.def_id())
693 .flat_map(|trait_did| tcx.associated_items(trait_did).in_definition_order())
694 .any(|item| item.is_method())
695 })
696 }) {
697 return None;
698 }
699
700 if let Some(mutbl) = [ty::Mutability::Not, ty::Mutability::Mut].into_iter().find(|&mutbl| {
702 let re = self.infcx.tcx.lifetimes.re_erased;
703 let ref_ty = Ty::new_ref(self.infcx.tcx, re, moved_arg_ty, mutbl);
704
705 let new_args = tcx.mk_args_from_iter(generic_args.iter().enumerate().map(
708 |(i, arg)| {
709 if i == param.index as usize { ref_ty.into() } else { arg }
710 },
711 ));
712 let can_subst = |ty: Ty<'tcx>| {
713 let old_ty = ty::EarlyBinder::bind(ty).instantiate(tcx, generic_args);
715 let new_ty = ty::EarlyBinder::bind(ty).instantiate(tcx, new_args);
716 if let Ok(old_ty) = tcx.try_normalize_erasing_regions(
717 self.infcx.typing_env(self.infcx.param_env),
718 old_ty,
719 ) && let Ok(new_ty) = tcx.try_normalize_erasing_regions(
720 self.infcx.typing_env(self.infcx.param_env),
721 new_ty,
722 ) {
723 old_ty == new_ty
724 } else {
725 false
726 }
727 };
728 if !can_subst(sig.output())
729 || sig
730 .inputs()
731 .iter()
732 .enumerate()
733 .any(|(i, &input_ty)| i != moved_arg_pos && !can_subst(input_ty))
734 {
735 return false;
736 }
737
738 clauses.instantiate(tcx, new_args).predicates.iter().all(|clause| {
740 let normalized = tcx
742 .try_normalize_erasing_regions(
743 self.infcx.typing_env(self.infcx.param_env),
744 *clause,
745 )
746 .unwrap_or_else(|_| clause.skip_norm_wip());
747 self.infcx.predicate_must_hold_modulo_regions(&Obligation::new(
748 tcx,
749 ObligationCause::dummy(),
750 self.infcx.param_env,
751 normalized,
752 ))
753 })
754 }) {
755 let place_desc = if let Some(desc) = self.describe_place(moved_place) {
756 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", desc))
})format!("`{desc}`")
757 } else {
758 "here".to_owned()
759 };
760 err.span_suggestion_verbose(
761 place_span.shrink_to_lo(),
762 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider {0}borrowing {1}",
mutbl.mutably_str(), place_desc))
})format!("consider {}borrowing {place_desc}", mutbl.mutably_str()),
763 mutbl.ref_prefix_str(),
764 Applicability::MaybeIncorrect,
765 );
766 Some(mutbl)
767 } else {
768 None
769 }
770 }
771
772 fn report_use_of_uninitialized(
773 &self,
774 mpi: MovePathIndex,
775 used_place: PlaceRef<'tcx>,
776 moved_place: PlaceRef<'tcx>,
777 desired_action: InitializationRequiringAction,
778 span: Span,
779 use_spans: UseSpans<'tcx>,
780 ) -> Diag<'infcx> {
781 let inits = &self.move_data.init_path_map[mpi];
784 let move_path = &self.move_data.move_paths[mpi];
785 let decl_span = self.body.local_decls[move_path.place.local].source_info.span;
786 let mut spans_set = FxIndexSet::default();
787 for init_idx in inits {
788 let init = &self.move_data.inits[*init_idx];
789 let span = init.span(self.body);
790 if !span.is_dummy() {
791 spans_set.insert(span);
792 }
793 }
794 let spans: Vec<_> = spans_set.into_iter().collect();
795
796 let (name, desc) = match self.describe_place_with_options(
797 moved_place,
798 DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
799 ) {
800 Some(name) => (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
})format!("`{name}`"), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` ", name))
})format!("`{name}` ")),
801 None => ("the variable".to_string(), String::new()),
802 };
803 let path = match self.describe_place_with_options(
804 used_place,
805 DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
806 ) {
807 Some(name) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
})format!("`{name}`"),
808 None => "value".to_string(),
809 };
810
811 let tcx = self.infcx.tcx;
814 let body = tcx.hir_body_owned_by(self.mir_def_id());
815 let mut visitor = ConditionVisitor { tcx, spans, name, errors: ::alloc::vec::Vec::new()vec![] };
816 visitor.visit_body(&body);
817 let spans = visitor.spans;
818
819 let mut show_assign_sugg = false;
820 let isnt_initialized = if let InitializationRequiringAction::PartialAssignment
821 | InitializationRequiringAction::Assignment = desired_action
822 {
823 "isn't fully initialized"
827 } else if !spans.iter().any(|i| {
828 !i.contains(span)
835 && !visitor
837 .errors
838 .iter()
839 .map(|(sp, _)| *sp)
840 .any(|sp| span < sp && !sp.contains(span))
841 }) {
842 show_assign_sugg = true;
843 "isn't initialized"
844 } else {
845 "is possibly-uninitialized"
846 };
847
848 let used = desired_action.as_general_verb_in_past_tense();
849 let mut err = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} binding {1}{2}",
used, desc, isnt_initialized))
})).with_code(E0381)
}struct_span_code_err!(
850 self.dcx(),
851 span,
852 E0381,
853 "{used} binding {desc}{isnt_initialized}"
854 );
855 use_spans.var_path_only_subdiag(&mut err, desired_action);
856
857 if let InitializationRequiringAction::PartialAssignment
858 | InitializationRequiringAction::Assignment = desired_action
859 {
860 err.help(
861 "partial initialization isn't supported, fully initialize the binding with a \
862 default value and mutate it, or use `std::mem::MaybeUninit`",
863 );
864 }
865 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1} here but it {2}", path,
used, isnt_initialized))
})format!("{path} {used} here but it {isnt_initialized}"));
866
867 let mut shown = false;
868 for (sp, label) in visitor.errors {
869 if sp < span && !sp.overlaps(span) {
870 err.span_label(sp, label);
884 shown = true;
885 }
886 }
887 if !shown {
888 for sp in &spans {
889 if *sp < span && !sp.overlaps(span) {
890 err.span_label(*sp, "binding initialized here in some conditions");
891 }
892 }
893 }
894
895 err.span_label(decl_span, "binding declared here but left uninitialized");
896 if show_assign_sugg {
897 struct LetVisitor {
898 decl_span: Span,
899 sugg: Option<(Span, bool)>,
900 }
901
902 impl<'v> Visitor<'v> for LetVisitor {
903 fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) {
904 if self.sugg.is_some() {
905 return;
906 }
907
908 if let hir::StmtKind::Let(hir::LetStmt { span, ty, init: None, pat, .. }) =
911 &ex.kind
912 && let hir::PatKind::Binding(binding_mode, ..) = pat.kind
913 && span.contains(self.decl_span)
914 {
915 let strip_ref = #[allow(non_exhaustive_omitted_patterns)] match binding_mode.0 {
hir::ByRef::Yes(..) => true,
_ => false,
}matches!(binding_mode.0, hir::ByRef::Yes(..));
918 self.sugg =
919 ty.map_or(Some((pat.span, strip_ref)), |ty| Some((ty.span, strip_ref)));
920 }
921 hir::intravisit::walk_stmt(self, ex);
922 }
923 }
924
925 let mut visitor = LetVisitor { decl_span, sugg: None };
926 visitor.visit_body(&body);
927 if let Some((span, strip_ref)) = visitor.sugg {
928 self.suggest_assign_value(&mut err, moved_place, span, strip_ref);
929 }
930 }
931 err
932 }
933
934 fn suggest_assign_value(
935 &self,
936 err: &mut Diag<'_>,
937 moved_place: PlaceRef<'tcx>,
938 sugg_span: Span,
939 strip_ref: bool,
940 ) {
941 let mut ty = moved_place.ty(self.body, self.infcx.tcx).ty;
942 if strip_ref && let ty::Ref(_, inner, _) = ty.kind() {
943 ty = *inner;
944 }
945 {
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/diagnostics/conflict_errors.rs:945",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(945u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("ty: {0:?}, kind: {1:?}",
ty, ty.kind()) as &dyn Value))])
});
} else { ; }
};debug!("ty: {:?}, kind: {:?}", ty, ty.kind());
946
947 let Some(assign_value) = self.infcx.err_ctxt().ty_kind_suggestion(self.infcx.param_env, ty)
948 else {
949 return;
950 };
951
952 err.span_suggestion_verbose(
953 sugg_span.shrink_to_hi(),
954 "consider assigning a value",
955 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" = {0}", assign_value))
})format!(" = {assign_value}"),
956 Applicability::MaybeIncorrect,
957 );
958 }
959
960 fn suggest_hoisting_call_outside_loop(&self, err: &mut Diag<'_>, expr: &hir::Expr<'_>) -> bool {
965 let tcx = self.infcx.tcx;
966 let mut can_suggest_clone = true;
967
968 let local_hir_id = if let hir::ExprKind::Path(hir::QPath::Resolved(
972 _,
973 hir::Path { res: hir::def::Res::Local(local_hir_id), .. },
974 )) = expr.kind
975 {
976 Some(local_hir_id)
977 } else {
978 None
981 };
982
983 struct Finder {
987 hir_id: hir::HirId,
988 }
989 impl<'hir> Visitor<'hir> for Finder {
990 type Result = ControlFlow<()>;
991 fn visit_pat(&mut self, pat: &'hir hir::Pat<'hir>) -> Self::Result {
992 if pat.hir_id == self.hir_id {
993 return ControlFlow::Break(());
994 }
995 hir::intravisit::walk_pat(self, pat)
996 }
997 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) -> Self::Result {
998 if ex.hir_id == self.hir_id {
999 return ControlFlow::Break(());
1000 }
1001 hir::intravisit::walk_expr(self, ex)
1002 }
1003 }
1004 let mut parent = None;
1006 let mut outer_most_loop: Option<&hir::Expr<'_>> = None;
1008 for (_, node) in tcx.hir_parent_iter(expr.hir_id) {
1009 let e = match node {
1010 hir::Node::Expr(e) => e,
1011 hir::Node::LetStmt(hir::LetStmt { els: Some(els), .. }) => {
1012 let mut finder = BreakFinder { found_breaks: ::alloc::vec::Vec::new()vec![], found_continues: ::alloc::vec::Vec::new()vec![] };
1013 finder.visit_block(els);
1014 if !finder.found_breaks.is_empty() {
1015 can_suggest_clone = false;
1020 }
1021 continue;
1022 }
1023 _ => continue,
1024 };
1025 if let Some(&hir_id) = local_hir_id {
1026 if (Finder { hir_id }).visit_expr(e).is_break() {
1027 break;
1030 }
1031 }
1032 if parent.is_none() {
1033 parent = Some(e);
1034 }
1035 match e.kind {
1036 hir::ExprKind::Let(_) => {
1037 match tcx.parent_hir_node(e.hir_id) {
1038 hir::Node::Expr(hir::Expr {
1039 kind: hir::ExprKind::If(cond, ..), ..
1040 }) => {
1041 if (Finder { hir_id: expr.hir_id }).visit_expr(cond).is_break() {
1042 can_suggest_clone = false;
1048 }
1049 }
1050 _ => {}
1051 }
1052 }
1053 hir::ExprKind::Loop(..) => {
1054 outer_most_loop = Some(e);
1055 }
1056 _ => {}
1057 }
1058 }
1059 let loop_count: usize = tcx
1060 .hir_parent_iter(expr.hir_id)
1061 .map(|(_, node)| match node {
1062 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Loop(..), .. }) => 1,
1063 _ => 0,
1064 })
1065 .sum();
1066
1067 let sm = tcx.sess.source_map();
1068 if let Some(in_loop) = outer_most_loop {
1069 let mut finder = BreakFinder { found_breaks: ::alloc::vec::Vec::new()vec![], found_continues: ::alloc::vec::Vec::new()vec![] };
1070 finder.visit_expr(in_loop);
1071 let spans = finder
1073 .found_breaks
1074 .iter()
1075 .chain(finder.found_continues.iter())
1076 .map(|(_, span)| *span)
1077 .filter(|span| {
1078 !#[allow(non_exhaustive_omitted_patterns)] match span.desugaring_kind() {
Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop) => true,
_ => false,
}matches!(
1079 span.desugaring_kind(),
1080 Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop)
1081 )
1082 })
1083 .collect::<Vec<Span>>();
1084 let loop_spans: Vec<_> = tcx
1086 .hir_parent_iter(expr.hir_id)
1087 .filter_map(|(_, node)| match node {
1088 hir::Node::Expr(hir::Expr { span, kind: hir::ExprKind::Loop(..), .. }) => {
1089 Some(*span)
1090 }
1091 _ => None,
1092 })
1093 .collect();
1094 if !spans.is_empty() && loop_count > 1 {
1097 let mut lines: Vec<_> =
1101 loop_spans.iter().map(|sp| sm.lookup_char_pos(sp.lo()).line).collect();
1102 lines.sort();
1103 lines.dedup();
1104 let fmt_span = |span: Span| {
1105 if lines.len() == loop_spans.len() {
1106 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("line {0}",
sm.lookup_char_pos(span.lo()).line))
})format!("line {}", sm.lookup_char_pos(span.lo()).line)
1107 } else {
1108 sm.span_to_diagnostic_string(span)
1109 }
1110 };
1111 let mut spans: MultiSpan = spans.into();
1112 for (desc, elements) in [
1114 ("`break` exits", &finder.found_breaks),
1115 ("`continue` advances", &finder.found_continues),
1116 ] {
1117 for (destination, sp) in elements {
1118 if let Ok(hir_id) = destination.target_id
1119 && let hir::Node::Expr(expr) = tcx.hir_node(hir_id)
1120 && !#[allow(non_exhaustive_omitted_patterns)] match sp.desugaring_kind() {
Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop) => true,
_ => false,
}matches!(
1121 sp.desugaring_kind(),
1122 Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop)
1123 )
1124 {
1125 spans.push_span_label(
1126 *sp,
1127 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this {1} the loop at {0}",
fmt_span(expr.span), desc))
})format!("this {desc} the loop at {}", fmt_span(expr.span)),
1128 );
1129 }
1130 }
1131 }
1132 for span in loop_spans {
1134 spans.push_span_label(sm.guess_head_span(span), "");
1135 }
1136
1137 err.span_note(spans, "verify that your loop breaking logic is correct");
1149 }
1150 if let Some(parent) = parent
1151 && let hir::ExprKind::MethodCall(..) | hir::ExprKind::Call(..) = parent.kind
1152 {
1153 let span = in_loop.span;
1158 if !finder.found_breaks.is_empty()
1159 && let Ok(value) = sm.span_to_snippet(parent.span)
1160 {
1161 let indent = if let Some(indent) = sm.indentation_before(span) {
1164 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}", indent))
})format!("\n{indent}")
1165 } else {
1166 " ".to_string()
1167 };
1168 err.multipart_suggestion(
1169 "consider moving the expression out of the loop so it is only moved once",
1170 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let mut value = {0};{1}",
value, indent))
})), (parent.span, "value".to_string())]))vec![
1171 (span.shrink_to_lo(), format!("let mut value = {value};{indent}")),
1172 (parent.span, "value".to_string()),
1173 ],
1174 Applicability::MaybeIncorrect,
1175 );
1176 }
1177 }
1178 }
1179 can_suggest_clone
1180 }
1181
1182 fn suggest_cloning_on_functional_record_update(
1185 &self,
1186 err: &mut Diag<'_>,
1187 ty: Ty<'tcx>,
1188 expr: &hir::Expr<'_>,
1189 ) {
1190 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1191 let hir::ExprKind::Struct(struct_qpath, fields, hir::StructTailExpr::Base(base)) =
1192 expr.kind
1193 else {
1194 return;
1195 };
1196 let hir::QPath::Resolved(_, path) = struct_qpath else { return };
1197 let hir::def::Res::Def(_, def_id) = path.res else { return };
1198 let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id) else { return };
1199 let ty::Adt(def, args) = expr_ty.kind() else { return };
1200 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = base.kind else { return };
1201 let (hir::def::Res::Local(_)
1202 | hir::def::Res::Def(
1203 DefKind::Const { .. }
1204 | DefKind::ConstParam
1205 | DefKind::Static { .. }
1206 | DefKind::AssocConst { .. },
1207 _,
1208 )) = path.res
1209 else {
1210 return;
1211 };
1212 let Ok(base_str) = self.infcx.tcx.sess.source_map().span_to_snippet(base.span) else {
1213 return;
1214 };
1215
1216 let mut final_field_count = fields.len();
1222 let Some(variant) = def.variants().iter().find(|variant| variant.def_id == def_id) else {
1223 return;
1226 };
1227 let mut sugg = ::alloc::vec::Vec::new()vec![];
1228 for field in &variant.fields {
1229 let field_ty = field.ty(self.infcx.tcx, args).skip_norm_wip();
1233 let ident = field.ident(self.infcx.tcx);
1234 if field_ty == ty && fields.iter().all(|field| field.ident.name != ident.name) {
1235 sugg.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}.{0}.clone()", ident,
base_str))
})format!("{ident}: {base_str}.{ident}.clone()"));
1237 final_field_count += 1;
1238 }
1239 }
1240 let (span, sugg) = match fields {
1241 [.., last] => (
1242 if final_field_count == variant.fields.len() {
1243 last.span.shrink_to_hi().with_hi(base.span.hi())
1245 } else {
1246 last.span.shrink_to_hi()
1247 },
1248 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", sugg.join(", ")))
})format!(", {}", sugg.join(", ")),
1249 ),
1250 [] => (
1252 expr.span.with_lo(struct_qpath.span().hi()),
1253 if final_field_count == variant.fields.len() {
1254 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{ {0} }}", sugg.join(", ")))
})format!(" {{ {} }}", sugg.join(", "))
1256 } else {
1257 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{ {0}, ..{1} }}",
sugg.join(", "), base_str))
})format!(" {{ {}, ..{base_str} }}", sugg.join(", "))
1258 },
1259 ),
1260 };
1261 let prefix = if !self.implements_clone(ty) {
1262 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` doesn\'t implement `Copy` or `Clone`",
ty))
})format!("`{ty}` doesn't implement `Copy` or `Clone`");
1263 if let ty::Adt(def, _) = ty.kind() {
1264 err.span_note(self.infcx.tcx.def_span(def.did()), msg);
1265 } else {
1266 err.note(msg);
1267 }
1268 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if `{0}` implemented `Clone`, you could ",
ty))
})format!("if `{ty}` implemented `Clone`, you could ")
1269 } else {
1270 String::new()
1271 };
1272 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}clone the value from the field instead of using the functional record update syntax",
prefix))
})format!(
1273 "{prefix}clone the value from the field instead of using the functional record update \
1274 syntax",
1275 );
1276 err.span_suggestion_verbose(span, msg, sugg, Applicability::MachineApplicable);
1277 }
1278
1279 pub(crate) fn suggest_cloning(
1280 &self,
1281 err: &mut Diag<'_>,
1282 place: PlaceRef<'tcx>,
1283 ty: Ty<'tcx>,
1284 expr: &'tcx hir::Expr<'tcx>,
1285 use_spans: Option<UseSpans<'tcx>>,
1286 ) {
1287 if let hir::ExprKind::Struct(_, _, hir::StructTailExpr::Base(_)) = expr.kind {
1288 self.suggest_cloning_on_functional_record_update(err, ty, expr);
1293 return;
1294 }
1295
1296 if self.implements_clone(ty) {
1297 if self.in_move_closure(expr) {
1298 if let Some(name) = self.describe_place(place) {
1299 self.suggest_clone_of_captured_var_in_move_closure(err, &name, use_spans);
1300 }
1301 } else {
1302 self.suggest_cloning_inner(err, ty, expr);
1303 }
1304 } else if let ty::Adt(def, args) = ty.kind()
1305 && let Some(local_did) = def.did().as_local()
1306 && def.variants().iter().all(|variant| {
1307 variant.fields.iter().all(|field| {
1308 self.implements_clone(field.ty(self.infcx.tcx, args).skip_norm_wip())
1309 })
1310 })
1311 {
1312 let ty_span = self.infcx.tcx.def_span(def.did());
1313 let mut span: MultiSpan = ty_span.into();
1314 let mut derive_clone = false;
1315 self.infcx.tcx.for_each_relevant_impl(
1316 self.infcx.tcx.lang_items().clone_trait().unwrap(),
1317 ty,
1318 |def_id| {
1319 if self.infcx.tcx.is_automatically_derived(def_id) {
1320 derive_clone = true;
1321 span.push_span_label(
1322 self.infcx.tcx.def_span(def_id),
1323 "derived `Clone` adds implicit bounds on type parameters",
1324 );
1325 if let Some(generics) = self.infcx.tcx.hir_get_generics(local_did) {
1326 for param in generics.params {
1327 if let hir::GenericParamKind::Type { .. } = param.kind {
1328 span.push_span_label(
1329 param.span,
1330 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("introduces an implicit `{0}: Clone` bound",
param.name.ident()))
})format!(
1331 "introduces an implicit `{}: Clone` bound",
1332 param.name.ident()
1333 ),
1334 );
1335 }
1336 }
1337 }
1338 }
1339 },
1340 );
1341 let msg = if !derive_clone {
1342 span.push_span_label(
1343 ty_span,
1344 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider {0}implementing `Clone` for this type",
if derive_clone { "manually " } else { "" }))
})format!(
1345 "consider {}implementing `Clone` for this type",
1346 if derive_clone { "manually " } else { "" }
1347 ),
1348 );
1349 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if `{0}` implemented `Clone`, you could clone the value",
ty))
})format!("if `{ty}` implemented `Clone`, you could clone the value")
1350 } else {
1351 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if all bounds were met, you could clone the value"))
})format!("if all bounds were met, you could clone the value")
1352 };
1353 span.push_span_label(expr.span, "you could clone this value");
1354 err.span_note(span, msg);
1355 if derive_clone {
1356 err.help("consider manually implementing `Clone` to avoid undesired bounds");
1357 }
1358 } else if let ty::Param(param) = ty.kind()
1359 && let Some(_clone_trait_def) = self.infcx.tcx.lang_items().clone_trait()
1360 && let generics = self.infcx.tcx.generics_of(self.mir_def_id())
1361 && let generic_param = generics.type_param(*param, self.infcx.tcx)
1362 && let param_span = self.infcx.tcx.def_span(generic_param.def_id)
1363 && if let Some(UseSpans::FnSelfUse { kind, .. }) = use_spans
1364 && let CallKind::FnCall { fn_trait_id, self_ty } = kind
1365 && let ty::Param(_) = self_ty.kind()
1366 && ty == self_ty
1367 && self.infcx.tcx.fn_trait_kind_from_def_id(fn_trait_id).is_some()
1368 {
1369 false
1371 } else {
1372 true
1373 }
1374 {
1375 let mut span: MultiSpan = param_span.into();
1376 span.push_span_label(
1377 param_span,
1378 "consider constraining this type parameter with `Clone`",
1379 );
1380 span.push_span_label(expr.span, "you could clone this value");
1381 err.span_help(
1382 span,
1383 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if `{0}` implemented `Clone`, you could clone the value",
ty))
})format!("if `{ty}` implemented `Clone`, you could clone the value"),
1384 );
1385 } else if let ty::Adt(_, _) = ty.kind()
1386 && let Some(clone_trait) = self.infcx.tcx.lang_items().clone_trait()
1387 {
1388 let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1391 let cause = ObligationCause::misc(expr.span, self.mir_def_id());
1392 ocx.register_bound(cause, self.infcx.param_env, ty, clone_trait);
1393 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1394 if errors.iter().all(|error| {
1395 match error.obligation.predicate.as_clause().and_then(|c| c.as_trait_clause()) {
1396 Some(clause) => match clause.self_ty().skip_binder().kind() {
1397 ty::Adt(def, _) => def.did().is_local() && clause.def_id() == clone_trait,
1398 _ => false,
1399 },
1400 None => false,
1401 }
1402 }) {
1403 let mut type_spans = ::alloc::vec::Vec::new()vec![];
1404 let mut types = FxIndexSet::default();
1405 for clause in errors
1406 .iter()
1407 .filter_map(|e| e.obligation.predicate.as_clause())
1408 .filter_map(|c| c.as_trait_clause())
1409 {
1410 let ty::Adt(def, _) = clause.self_ty().skip_binder().kind() else { continue };
1411 type_spans.push(self.infcx.tcx.def_span(def.did()));
1412 types.insert(
1413 self.infcx
1414 .tcx
1415 .short_string(clause.self_ty().skip_binder(), &mut err.long_ty_path()),
1416 );
1417 }
1418 let mut span: MultiSpan = type_spans.clone().into();
1419 for sp in type_spans {
1420 span.push_span_label(sp, "consider implementing `Clone` for this type");
1421 }
1422 span.push_span_label(expr.span, "you could clone this value");
1423 let types: Vec<_> = types.into_iter().collect();
1424 let msg = match &types[..] {
1425 [only] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", only))
})format!("`{only}`"),
1426 [head @ .., last] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} and `{1}`",
head.iter().map(|t|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", t))
})).collect::<Vec<_>>().join(", "), last))
})format!(
1427 "{} and `{last}`",
1428 head.iter().map(|t| format!("`{t}`")).collect::<Vec<_>>().join(", ")
1429 ),
1430 [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1431 };
1432 err.span_note(
1433 span,
1434 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if {0} implemented `Clone`, you could clone the value",
msg))
})format!("if {msg} implemented `Clone`, you could clone the value"),
1435 );
1436 }
1437 }
1438 }
1439
1440 pub(crate) fn implements_clone(&self, ty: Ty<'tcx>) -> bool {
1441 let Some(clone_trait_def) = self.infcx.tcx.lang_items().clone_trait() else { return false };
1442 self.infcx
1443 .type_implements_trait(clone_trait_def, [ty], self.infcx.param_env)
1444 .must_apply_modulo_regions()
1445 }
1446
1447 pub(crate) fn clone_on_reference(&self, expr: &hir::Expr<'_>) -> Option<Span> {
1450 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1451 if let hir::ExprKind::MethodCall(segment, rcvr, args, span) = expr.kind
1452 && let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id)
1453 && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
1454 && rcvr_ty == expr_ty
1455 && segment.ident.name == sym::clone
1456 && args.is_empty()
1457 {
1458 Some(span)
1459 } else {
1460 None
1461 }
1462 }
1463
1464 fn in_move_closure(&self, expr: &hir::Expr<'_>) -> bool {
1465 for (_, node) in self.infcx.tcx.hir_parent_iter(expr.hir_id) {
1466 if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) = node
1467 && let hir::CaptureBy::Value { .. } = closure.capture_clause
1468 {
1469 return true;
1471 }
1472 }
1473 false
1474 }
1475
1476 fn suggest_cloning_inner(
1477 &self,
1478 err: &mut Diag<'_>,
1479 ty: Ty<'tcx>,
1480 expr: &hir::Expr<'_>,
1481 ) -> bool {
1482 let tcx = self.infcx.tcx;
1483
1484 if let ExpnKind::Macro(MacroKind::Derive, _) = self.body.span.ctxt().outer_expn_data().kind
1486 {
1487 return false;
1488 }
1489 if let Some(_) = self.clone_on_reference(expr) {
1490 return false;
1493 }
1494 if self.in_move_closure(expr) {
1497 return false;
1498 }
1499 if let hir::ExprKind::Closure(_) = expr.kind {
1502 return false;
1503 }
1504 let mut suggestion =
1506 if let Some(symbol) = tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1507 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}.clone()", symbol))
})format!(": {symbol}.clone()")
1508 } else {
1509 ".clone()".to_owned()
1510 };
1511 let mut sugg = Vec::with_capacity(2);
1512 let mut inner_expr = expr;
1513 let mut is_raw_ptr = false;
1514 let typeck_result = self.infcx.tcx.typeck(self.mir_def_id());
1515 while let hir::ExprKind::AddrOf(.., inner) | hir::ExprKind::Unary(hir::UnOp::Deref, inner) =
1517 &inner_expr.kind
1518 {
1519 if let hir::ExprKind::AddrOf(_, hir::Mutability::Mut, _) = inner_expr.kind {
1520 return false;
1523 }
1524 inner_expr = inner;
1525 if let Some(inner_type) = typeck_result.node_type_opt(inner.hir_id) {
1526 if #[allow(non_exhaustive_omitted_patterns)] match inner_type.kind() {
ty::RawPtr(..) => true,
_ => false,
}matches!(inner_type.kind(), ty::RawPtr(..)) {
1527 is_raw_ptr = true;
1528 break;
1529 }
1530 }
1531 }
1532 if inner_expr.span.lo() != expr.span.lo() && !is_raw_ptr {
1535 sugg.push((expr.span.with_hi(inner_expr.span.lo()), String::new()));
1537 }
1538 let span = if inner_expr.span.hi() != expr.span.hi() {
1540 if is_raw_ptr {
1542 expr.span.shrink_to_hi()
1543 } else {
1544 expr.span.with_lo(inner_expr.span.hi())
1546 }
1547 } else {
1548 if is_raw_ptr {
1549 sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
1550 suggestion = ").clone()".to_string();
1551 }
1552 expr.span.shrink_to_hi()
1553 };
1554 sugg.push((span, suggestion));
1555 let msg = if let ty::Adt(def, _) = ty.kind()
1556 && [tcx.get_diagnostic_item(sym::Arc), tcx.get_diagnostic_item(sym::Rc)]
1557 .contains(&Some(def.did()))
1558 {
1559 "clone the value to increment its reference count"
1560 } else {
1561 "consider cloning the value if the performance cost is acceptable"
1562 };
1563 err.multipart_suggestion(msg, sugg, Applicability::MachineApplicable);
1564 true
1565 }
1566
1567 fn suggest_adding_bounds(&self, err: &mut Diag<'_>, ty: Ty<'tcx>, def_id: DefId, span: Span) {
1568 let tcx = self.infcx.tcx;
1569 let generics = tcx.generics_of(self.mir_def_id());
1570
1571 let Some(hir_generics) =
1572 tcx.hir_get_generics(tcx.typeck_root_def_id_local(self.mir_def_id()))
1573 else {
1574 return;
1575 };
1576 let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1578 let cause = ObligationCause::misc(span, self.mir_def_id());
1579
1580 ocx.register_bound(cause, self.infcx.param_env, ty, def_id);
1581 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1582
1583 let predicates: Result<Vec<_>, _> = errors
1585 .into_iter()
1586 .map(|err| match err.obligation.predicate.kind().skip_binder() {
1587 PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => {
1588 match *predicate.self_ty().kind() {
1589 ty::Param(param_ty) => Ok((
1590 generics.type_param(param_ty, tcx),
1591 predicate.trait_ref.print_trait_sugared().to_string(),
1592 Some(predicate.trait_ref.def_id),
1593 )),
1594 _ => Err(()),
1595 }
1596 }
1597 _ => Err(()),
1598 })
1599 .collect();
1600
1601 if let Ok(predicates) = predicates {
1602 suggest_constraining_type_params(
1603 tcx,
1604 hir_generics,
1605 err,
1606 predicates.iter().map(|(param, constraint, def_id)| {
1607 (param.name.as_str(), &**constraint, *def_id)
1608 }),
1609 None,
1610 );
1611 }
1612 }
1613
1614 pub(crate) fn report_move_out_while_borrowed(
1615 &mut self,
1616 location: Location,
1617 (place, span): (Place<'tcx>, Span),
1618 borrow: &BorrowData<'tcx>,
1619 ) {
1620 {
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/diagnostics/conflict_errors.rs:1620",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(1620u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_move_out_while_borrowed: location={0:?} place={1:?} span={2:?} borrow={3:?}",
location, place, span, borrow) as &dyn Value))])
});
} else { ; }
};debug!(
1621 "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
1622 location, place, span, borrow
1623 );
1624 let value_msg = self.describe_any_place(place.as_ref());
1625 let borrow_msg = self.describe_any_place(borrow.borrowed_place.as_ref());
1626
1627 let borrow_spans = self.retrieve_borrow_spans(borrow);
1628 let borrow_span = borrow_spans.args_or_use();
1629
1630 let move_spans = self.move_spans(place.as_ref(), location);
1631 let span = move_spans.args_or_use();
1632
1633 let mut err = self.cannot_move_when_borrowed(
1634 span,
1635 borrow_span,
1636 &self.describe_any_place(place.as_ref()),
1637 &borrow_msg,
1638 &value_msg,
1639 );
1640 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1641
1642 borrow_spans.var_path_only_subdiag(&mut err, crate::InitializationRequiringAction::Borrow);
1643
1644 move_spans.var_subdiag(&mut err, None, |kind, var_span| {
1645 use crate::session_diagnostics::CaptureVarCause::*;
1646 match kind {
1647 hir::ClosureKind::Coroutine(_) => MoveUseInCoroutine { var_span },
1648 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1649 MoveUseInClosure { var_span }
1650 }
1651 }
1652 });
1653
1654 self.explain_why_borrow_contains_point(location, borrow, None)
1655 .add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
1656 self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
1657 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1658 if let Some(expr) = self.find_expr(borrow_span) {
1659 if let hir::ExprKind::AddrOf(_, _, borrowed_expr) = expr.kind
1661 && let Some(ty) = typeck_results.expr_ty_opt(borrowed_expr)
1662 {
1663 self.suggest_cloning(&mut err, place.as_ref(), ty, borrowed_expr, Some(move_spans));
1664 } else if typeck_results.expr_adjustments(expr).first().is_some_and(|adj| {
1665 #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
ty::adjustment::Adjust::Borrow(ty::adjustment::AutoBorrow::Ref(ty::adjustment::AutoBorrowMutability::Not
| ty::adjustment::AutoBorrowMutability::Mut {
allow_two_phase_borrow: ty::adjustment::AllowTwoPhase::No })) => true,
_ => false,
}matches!(
1666 adj.kind,
1667 ty::adjustment::Adjust::Borrow(ty::adjustment::AutoBorrow::Ref(
1668 ty::adjustment::AutoBorrowMutability::Not
1669 | ty::adjustment::AutoBorrowMutability::Mut {
1670 allow_two_phase_borrow: ty::adjustment::AllowTwoPhase::No
1671 }
1672 ))
1673 )
1674 }) && let Some(ty) = typeck_results.expr_ty_opt(expr)
1675 {
1676 self.suggest_cloning(&mut err, place.as_ref(), ty, expr, Some(move_spans));
1677 }
1678 }
1679 self.buffer_error(err);
1680 }
1681
1682 pub(crate) fn report_use_while_mutably_borrowed(
1683 &self,
1684 location: Location,
1685 (place, _span): (Place<'tcx>, Span),
1686 borrow: &BorrowData<'tcx>,
1687 ) -> Diag<'infcx> {
1688 let borrow_spans = self.retrieve_borrow_spans(borrow);
1689 let borrow_span = borrow_spans.args_or_use();
1690
1691 let use_spans = self.move_spans(place.as_ref(), location);
1694 let span = use_spans.var_or_use();
1695
1696 let mut err = self.cannot_use_when_mutably_borrowed(
1700 span,
1701 &self.describe_any_place(place.as_ref()),
1702 borrow_span,
1703 &self.describe_any_place(borrow.borrowed_place.as_ref()),
1704 );
1705 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1706
1707 borrow_spans.var_subdiag(&mut err, Some(borrow.kind), |kind, var_span| {
1708 use crate::session_diagnostics::CaptureVarCause::*;
1709 let place = &borrow.borrowed_place;
1710 let desc_place = self.describe_any_place(place.as_ref());
1711 match kind {
1712 hir::ClosureKind::Coroutine(_) => {
1713 BorrowUsePlaceCoroutine { place: desc_place, var_span, is_single_var: true }
1714 }
1715 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1716 BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: true }
1717 }
1718 }
1719 });
1720
1721 self.explain_why_borrow_contains_point(location, borrow, None)
1722 .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
1723 err
1724 }
1725
1726 pub(crate) fn report_conflicting_borrow(
1727 &self,
1728 location: Location,
1729 (place, span): (Place<'tcx>, Span),
1730 gen_borrow_kind: BorrowKind,
1731 issued_borrow: &BorrowData<'tcx>,
1732 ) -> Diag<'infcx> {
1733 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
1734 let issued_span = issued_spans.args_or_use();
1735
1736 let borrow_spans = self.borrow_spans(span, location);
1737 let span = borrow_spans.args_or_use();
1738
1739 let container_name = if issued_spans.for_coroutine() || borrow_spans.for_coroutine() {
1740 "coroutine"
1741 } else {
1742 "closure"
1743 };
1744
1745 let (desc_place, msg_place, msg_borrow, union_type_name) =
1746 self.describe_place_for_conflicting_borrow(place, issued_borrow.borrowed_place);
1747
1748 let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
1749 let second_borrow_desc = if explanation.is_explained() { "second " } else { "" };
1750
1751 let first_borrow_desc;
1753 let mut err = match (gen_borrow_kind, issued_borrow.kind) {
1754 (
1755 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1756 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1757 ) => {
1758 first_borrow_desc = "mutable ";
1759 let mut err = self.cannot_reborrow_already_borrowed(
1760 span,
1761 &desc_place,
1762 &msg_place,
1763 "immutable",
1764 issued_span,
1765 "it",
1766 "mutable",
1767 &msg_borrow,
1768 None,
1769 );
1770 self.suggest_slice_method_if_applicable(
1771 &mut err,
1772 place,
1773 issued_borrow.borrowed_place,
1774 span,
1775 issued_span,
1776 );
1777 err
1778 }
1779 (
1780 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1781 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1782 ) => {
1783 first_borrow_desc = "immutable ";
1784 let mut err = self.cannot_reborrow_already_borrowed(
1785 span,
1786 &desc_place,
1787 &msg_place,
1788 "mutable",
1789 issued_span,
1790 "it",
1791 "immutable",
1792 &msg_borrow,
1793 None,
1794 );
1795 self.suggest_slice_method_if_applicable(
1796 &mut err,
1797 place,
1798 issued_borrow.borrowed_place,
1799 span,
1800 issued_span,
1801 );
1802 self.suggest_binding_for_closure_capture_self(&mut err, &issued_spans);
1803 self.suggest_using_closure_argument_instead_of_capture(
1804 &mut err,
1805 issued_borrow.borrowed_place,
1806 &issued_spans,
1807 );
1808 err
1809 }
1810
1811 (
1812 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1813 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1814 ) => {
1815 first_borrow_desc = "first ";
1816 let mut err = self.cannot_mutably_borrow_multiply(
1817 span,
1818 &desc_place,
1819 &msg_place,
1820 issued_span,
1821 &msg_borrow,
1822 None,
1823 );
1824 self.suggest_slice_method_if_applicable(
1825 &mut err,
1826 place,
1827 issued_borrow.borrowed_place,
1828 span,
1829 issued_span,
1830 );
1831 self.suggest_using_closure_argument_instead_of_capture(
1832 &mut err,
1833 issued_borrow.borrowed_place,
1834 &issued_spans,
1835 );
1836 self.explain_iterator_advancement_in_for_loop_if_applicable(
1837 &mut err,
1838 span,
1839 &issued_spans,
1840 );
1841 err
1842 }
1843
1844 (
1845 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1846 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1847 ) => {
1848 first_borrow_desc = "first ";
1849 self.cannot_uniquely_borrow_by_two_closures(span, &desc_place, issued_span, None)
1850 }
1851
1852 (BorrowKind::Mut { .. }, BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
1853 if let Some(immutable_section_description) =
1854 self.classify_immutable_section(issued_borrow.assigned_place)
1855 {
1856 let mut err = self.cannot_mutate_in_immutable_section(
1857 span,
1858 issued_span,
1859 &desc_place,
1860 immutable_section_description,
1861 "mutably borrow",
1862 );
1863 borrow_spans.var_subdiag(
1864 &mut err,
1865 Some(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }),
1866 |kind, var_span| {
1867 use crate::session_diagnostics::CaptureVarCause::*;
1868 match kind {
1869 hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1870 place: desc_place,
1871 var_span,
1872 is_single_var: true,
1873 },
1874 hir::ClosureKind::Closure
1875 | hir::ClosureKind::CoroutineClosure(_) => BorrowUsePlaceClosure {
1876 place: desc_place,
1877 var_span,
1878 is_single_var: true,
1879 },
1880 }
1881 },
1882 );
1883 return err;
1884 } else {
1885 first_borrow_desc = "immutable ";
1886 self.cannot_reborrow_already_borrowed(
1887 span,
1888 &desc_place,
1889 &msg_place,
1890 "mutable",
1891 issued_span,
1892 "it",
1893 "immutable",
1894 &msg_borrow,
1895 None,
1896 )
1897 }
1898 }
1899
1900 (BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }, _) => {
1901 first_borrow_desc = "first ";
1902 self.cannot_uniquely_borrow_by_one_closure(
1903 span,
1904 container_name,
1905 &desc_place,
1906 "",
1907 issued_span,
1908 "it",
1909 "",
1910 None,
1911 )
1912 }
1913
1914 (
1915 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1916 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1917 ) => {
1918 first_borrow_desc = "first ";
1919 self.cannot_reborrow_already_uniquely_borrowed(
1920 span,
1921 container_name,
1922 &desc_place,
1923 "",
1924 "immutable",
1925 issued_span,
1926 "",
1927 None,
1928 second_borrow_desc,
1929 )
1930 }
1931
1932 (BorrowKind::Mut { .. }, BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }) => {
1933 first_borrow_desc = "first ";
1934 self.cannot_reborrow_already_uniquely_borrowed(
1935 span,
1936 container_name,
1937 &desc_place,
1938 "",
1939 "mutable",
1940 issued_span,
1941 "",
1942 None,
1943 second_borrow_desc,
1944 )
1945 }
1946
1947 (
1948 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1949 BorrowKind::Shared | BorrowKind::Fake(_),
1950 )
1951 | (
1952 BorrowKind::Fake(FakeBorrowKind::Shallow),
1953 BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_),
1954 ) => {
1955 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1956 }
1957 };
1958 self.note_due_to_edition_2024_opaque_capture_rules(issued_borrow, &mut err);
1959
1960 if issued_spans == borrow_spans {
1961 borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
1962 use crate::session_diagnostics::CaptureVarCause::*;
1963 match kind {
1964 hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1965 place: desc_place,
1966 var_span,
1967 is_single_var: false,
1968 },
1969 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1970 BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: false }
1971 }
1972 }
1973 });
1974 } else {
1975 issued_spans.var_subdiag(&mut err, Some(issued_borrow.kind), |kind, var_span| {
1976 use crate::session_diagnostics::CaptureVarCause::*;
1977 let borrow_place = &issued_borrow.borrowed_place;
1978 let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
1979 match kind {
1980 hir::ClosureKind::Coroutine(_) => {
1981 FirstBorrowUsePlaceCoroutine { place: borrow_place_desc, var_span }
1982 }
1983 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1984 FirstBorrowUsePlaceClosure { place: borrow_place_desc, var_span }
1985 }
1986 }
1987 });
1988
1989 borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
1990 use crate::session_diagnostics::CaptureVarCause::*;
1991 match kind {
1992 hir::ClosureKind::Coroutine(_) => {
1993 SecondBorrowUsePlaceCoroutine { place: desc_place, var_span }
1994 }
1995 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1996 SecondBorrowUsePlaceClosure { place: desc_place, var_span }
1997 }
1998 }
1999 });
2000 }
2001
2002 if union_type_name != "" {
2003 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is a field of the union `{1}`, so it overlaps the field {2}",
msg_place, union_type_name, msg_borrow))
})format!(
2004 "{msg_place} is a field of the union `{union_type_name}`, so it overlaps the field {msg_borrow}",
2005 ));
2006 }
2007
2008 explanation.add_explanation_to_diagnostic(
2009 &self,
2010 &mut err,
2011 first_borrow_desc,
2012 None,
2013 Some((issued_span, span)),
2014 );
2015
2016 self.suggest_using_local_if_applicable(&mut err, location, issued_borrow, explanation);
2017 self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
2018
2019 err
2020 }
2021
2022 fn suggest_copy_for_type_in_cloned_ref(&self, err: &mut Diag<'infcx>, place: Place<'tcx>) {
2023 let tcx = self.infcx.tcx;
2024 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2025
2026 struct FindUselessClone<'tcx> {
2027 tcx: TyCtxt<'tcx>,
2028 typeck_results: &'tcx ty::TypeckResults<'tcx>,
2029 clones: Vec<&'tcx hir::Expr<'tcx>>,
2030 }
2031 impl<'tcx> FindUselessClone<'tcx> {
2032 fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
2033 Self { tcx, typeck_results: tcx.typeck(def_id), clones: ::alloc::vec::Vec::new()vec![] }
2034 }
2035 }
2036 impl<'tcx> Visitor<'tcx> for FindUselessClone<'tcx> {
2037 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
2038 if let hir::ExprKind::MethodCall(..) = ex.kind
2039 && let Some(method_def_id) =
2040 self.typeck_results.type_dependent_def_id(ex.hir_id)
2041 && self.tcx.is_lang_item(self.tcx.parent(method_def_id), LangItem::Clone)
2042 {
2043 self.clones.push(ex);
2044 }
2045 hir::intravisit::walk_expr(self, ex);
2046 }
2047 }
2048
2049 let mut expr_finder = FindUselessClone::new(tcx, self.mir_def_id());
2050
2051 let body = tcx.hir_body(body_id).value;
2052 expr_finder.visit_expr(body);
2053
2054 struct Holds<'tcx> {
2055 ty: Ty<'tcx>,
2056 }
2057
2058 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for Holds<'tcx> {
2059 type Result = std::ops::ControlFlow<()>;
2060
2061 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
2062 if t == self.ty {
2063 return ControlFlow::Break(());
2064 }
2065 t.super_visit_with(self)
2066 }
2067 }
2068
2069 let mut types_to_constrain = FxIndexSet::default();
2070
2071 let local_ty = self.body.local_decls[place.local].ty;
2072 let typeck_results = tcx.typeck(self.mir_def_id());
2073 let clone = tcx.require_lang_item(LangItem::Clone, body.span);
2074 for expr in expr_finder.clones {
2075 if let hir::ExprKind::MethodCall(_, rcvr, _, span) = expr.kind
2076 && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
2077 && let Some(ty) = typeck_results.node_type_opt(expr.hir_id)
2078 && rcvr_ty == ty
2079 && let ty::Ref(_, inner, _) = rcvr_ty.kind()
2080 && let inner = inner.peel_refs()
2081 && (Holds { ty: inner }).visit_ty(local_ty).is_break()
2082 && let None =
2083 self.infcx.type_implements_trait_shallow(clone, inner, self.infcx.param_env)
2084 {
2085 err.span_label(
2086 span,
2087 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this call doesn\'t do anything, the result is still `{0}` because `{1}` doesn\'t implement `Clone`",
rcvr_ty, inner))
})format!(
2088 "this call doesn't do anything, the result is still `{rcvr_ty}` \
2089 because `{inner}` doesn't implement `Clone`",
2090 ),
2091 );
2092 types_to_constrain.insert(inner);
2093 }
2094 }
2095 for ty in types_to_constrain {
2096 self.suggest_adding_bounds_or_derive(err, ty, clone, body.span);
2097 }
2098 }
2099
2100 pub(crate) fn suggest_adding_bounds_or_derive(
2101 &self,
2102 err: &mut Diag<'_>,
2103 ty: Ty<'tcx>,
2104 trait_def_id: DefId,
2105 span: Span,
2106 ) {
2107 self.suggest_adding_bounds(err, ty, trait_def_id, span);
2108 if let ty::Adt(..) = ty.kind() {
2109 let trait_ref =
2111 ty::Binder::dummy(ty::TraitRef::new(self.infcx.tcx, trait_def_id, [ty]));
2112 let obligation = Obligation::new(
2113 self.infcx.tcx,
2114 ObligationCause::dummy(),
2115 self.infcx.param_env,
2116 trait_ref,
2117 );
2118 self.infcx.err_ctxt().suggest_derive(
2119 &obligation,
2120 err,
2121 trait_ref.upcast(self.infcx.tcx),
2122 );
2123 }
2124 }
2125
2126 #[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("suggest_using_local_if_applicable",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2126u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["location",
"issued_borrow", "explanation"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&issued_borrow)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&explanation)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let used_in_call =
#[allow(non_exhaustive_omitted_patterns)] match explanation {
BorrowExplanation::UsedLater(_,
LaterUseKind::Call | LaterUseKind::Other, _call_span, _) =>
true,
_ => false,
};
if !used_in_call {
{
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/diagnostics/conflict_errors.rs:2144",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2144u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("not later used in call")
as &dyn Value))])
});
} else { ; }
};
return;
}
if #[allow(non_exhaustive_omitted_patterns)] match self.body.local_decls[issued_borrow.borrowed_place.local].local_info()
{
LocalInfo::IfThenRescopeTemp { .. } => true,
_ => false,
} {
return;
}
let use_span =
if let BorrowExplanation::UsedLater(_, LaterUseKind::Other,
use_span, _) = explanation {
Some(use_span)
} else { None };
let outer_call_loc =
if let TwoPhaseActivation::ActivatedAt(loc) =
issued_borrow.activation_location {
loc
} else { issued_borrow.reserve_location };
let outer_call_stmt = self.body.stmt_at(outer_call_loc);
let inner_param_location = location;
let Some(inner_param_stmt) =
self.body.stmt_at(inner_param_location).left() else {
{
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/diagnostics/conflict_errors.rs:2173",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2173u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("`inner_param_location` {0:?} is not for a statement",
inner_param_location) as &dyn Value))])
});
} else { ; }
};
return;
};
let Some(&inner_param) =
inner_param_stmt.kind.as_assign().map(|(p, _)|
p) else {
{
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/diagnostics/conflict_errors.rs:2177",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2177u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("`inner_param_location` {0:?} is not for an assignment: {1:?}",
inner_param_location, inner_param_stmt) as &dyn Value))])
});
} else { ; }
};
return;
};
let inner_param_uses =
find_all_local_uses::find(self.body, inner_param.local);
let Some((inner_call_loc, inner_call_term)) =
inner_param_uses.into_iter().find_map(|loc|
{
let Either::Right(term) =
self.body.stmt_at(loc) else {
{
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/diagnostics/conflict_errors.rs:2187",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2187u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0:?} is a statement, so it can\'t be a call",
loc) as &dyn Value))])
});
} else { ; }
};
return None;
};
let TerminatorKind::Call { args, .. } =
&term.kind else {
{
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/diagnostics/conflict_errors.rs:2191",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2191u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("not a call: {0:?}",
term) as &dyn Value))])
});
} else { ; }
};
return None;
};
{
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/diagnostics/conflict_errors.rs:2194",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2194u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("checking call args for uses of inner_param: {0:?}",
args) as &dyn Value))])
});
} else { ; }
};
args.iter().map(|a|
&a.node).any(|a|
a == &Operand::Move(inner_param)).then_some((loc, term))
}) else {
{
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/diagnostics/conflict_errors.rs:2201",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2201u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("no uses of inner_param found as a by-move call arg")
as &dyn Value))])
});
} else { ; }
};
return;
};
{
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/diagnostics/conflict_errors.rs:2204",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2204u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("===> outer_call_loc = {0:?}, inner_call_loc = {1:?}",
outer_call_loc, inner_call_loc) as &dyn Value))])
});
} else { ; }
};
let inner_call_span = inner_call_term.source_info.span;
let outer_call_span =
match use_span {
Some(span) => span,
None =>
outer_call_stmt.either(|s| s.source_info,
|t| t.source_info).span,
};
if outer_call_span == inner_call_span ||
!outer_call_span.contains(inner_call_span) {
{
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/diagnostics/conflict_errors.rs:2214",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2214u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("outer span {0:?} does not strictly contain inner span {1:?}",
outer_call_span, inner_call_span) as &dyn Value))])
});
} else { ; }
};
return;
}
err.span_help(inner_call_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try adding a local storing this{0}...",
if use_span.is_some() { "" } else { " argument" }))
}));
err.span_help(outer_call_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("...and then using that local {0}",
if use_span.is_some() {
"here"
} else { "as the argument to this call" }))
}));
}
}
}#[instrument(level = "debug", skip(self, err))]
2127 fn suggest_using_local_if_applicable(
2128 &self,
2129 err: &mut Diag<'_>,
2130 location: Location,
2131 issued_borrow: &BorrowData<'tcx>,
2132 explanation: BorrowExplanation<'tcx>,
2133 ) {
2134 let used_in_call = matches!(
2135 explanation,
2136 BorrowExplanation::UsedLater(
2137 _,
2138 LaterUseKind::Call | LaterUseKind::Other,
2139 _call_span,
2140 _
2141 )
2142 );
2143 if !used_in_call {
2144 debug!("not later used in call");
2145 return;
2146 }
2147 if matches!(
2148 self.body.local_decls[issued_borrow.borrowed_place.local].local_info(),
2149 LocalInfo::IfThenRescopeTemp { .. }
2150 ) {
2151 return;
2153 }
2154
2155 let use_span = if let BorrowExplanation::UsedLater(_, LaterUseKind::Other, use_span, _) =
2156 explanation
2157 {
2158 Some(use_span)
2159 } else {
2160 None
2161 };
2162
2163 let outer_call_loc =
2164 if let TwoPhaseActivation::ActivatedAt(loc) = issued_borrow.activation_location {
2165 loc
2166 } else {
2167 issued_borrow.reserve_location
2168 };
2169 let outer_call_stmt = self.body.stmt_at(outer_call_loc);
2170
2171 let inner_param_location = location;
2172 let Some(inner_param_stmt) = self.body.stmt_at(inner_param_location).left() else {
2173 debug!("`inner_param_location` {:?} is not for a statement", inner_param_location);
2174 return;
2175 };
2176 let Some(&inner_param) = inner_param_stmt.kind.as_assign().map(|(p, _)| p) else {
2177 debug!(
2178 "`inner_param_location` {:?} is not for an assignment: {:?}",
2179 inner_param_location, inner_param_stmt
2180 );
2181 return;
2182 };
2183 let inner_param_uses = find_all_local_uses::find(self.body, inner_param.local);
2184 let Some((inner_call_loc, inner_call_term)) =
2185 inner_param_uses.into_iter().find_map(|loc| {
2186 let Either::Right(term) = self.body.stmt_at(loc) else {
2187 debug!("{:?} is a statement, so it can't be a call", loc);
2188 return None;
2189 };
2190 let TerminatorKind::Call { args, .. } = &term.kind else {
2191 debug!("not a call: {:?}", term);
2192 return None;
2193 };
2194 debug!("checking call args for uses of inner_param: {:?}", args);
2195 args.iter()
2196 .map(|a| &a.node)
2197 .any(|a| a == &Operand::Move(inner_param))
2198 .then_some((loc, term))
2199 })
2200 else {
2201 debug!("no uses of inner_param found as a by-move call arg");
2202 return;
2203 };
2204 debug!("===> outer_call_loc = {:?}, inner_call_loc = {:?}", outer_call_loc, inner_call_loc);
2205
2206 let inner_call_span = inner_call_term.source_info.span;
2207 let outer_call_span = match use_span {
2208 Some(span) => span,
2209 None => outer_call_stmt.either(|s| s.source_info, |t| t.source_info).span,
2210 };
2211 if outer_call_span == inner_call_span || !outer_call_span.contains(inner_call_span) {
2212 debug!(
2215 "outer span {:?} does not strictly contain inner span {:?}",
2216 outer_call_span, inner_call_span
2217 );
2218 return;
2219 }
2220 err.span_help(
2221 inner_call_span,
2222 format!(
2223 "try adding a local storing this{}...",
2224 if use_span.is_some() { "" } else { " argument" }
2225 ),
2226 );
2227 err.span_help(
2228 outer_call_span,
2229 format!(
2230 "...and then using that local {}",
2231 if use_span.is_some() { "here" } else { "as the argument to this call" }
2232 ),
2233 );
2234 }
2235
2236 pub(crate) fn find_expr(&self, span: Span) -> Option<&'tcx hir::Expr<'tcx>> {
2237 let tcx = self.infcx.tcx;
2238 let body_id = tcx.hir_node(self.mir_hir_id()).body_id()?;
2239 let mut expr_finder = FindExprBySpan::new(span, tcx);
2240 expr_finder.visit_expr(tcx.hir_body(body_id).value);
2241 expr_finder.result
2242 }
2243
2244 fn suggest_slice_method_if_applicable(
2245 &self,
2246 err: &mut Diag<'_>,
2247 place: Place<'tcx>,
2248 borrowed_place: Place<'tcx>,
2249 span: Span,
2250 issued_span: Span,
2251 ) {
2252 let tcx = self.infcx.tcx;
2253
2254 let has_split_at_mut = |ty: Ty<'tcx>| {
2255 let ty = ty.peel_refs();
2256 match ty.kind() {
2257 ty::Array(..) | ty::Slice(..) => true,
2258 ty::Adt(def, _) if tcx.get_diagnostic_item(sym::Vec) == Some(def.did()) => true,
2259 _ if ty == tcx.types.str_ => true,
2260 _ => false,
2261 }
2262 };
2263 if let ([ProjectionElem::Index(index1)], [ProjectionElem::Index(index2)])
2264 | (
2265 [ProjectionElem::Deref, ProjectionElem::Index(index1)],
2266 [ProjectionElem::Deref, ProjectionElem::Index(index2)],
2267 ) = (&place.projection[..], &borrowed_place.projection[..])
2268 {
2269 let decl1 = &self.body.local_decls[*index1];
2270 let decl2 = &self.body.local_decls[*index2];
2271
2272 let mut note_default_suggestion = || {
2273 err.help(
2274 "consider using `.split_at_mut(position)` or similar method to obtain two \
2275 mutable non-overlapping sub-slices",
2276 )
2277 .help(
2278 "consider using `.swap(index_1, index_2)` to swap elements at the specified \
2279 indices",
2280 );
2281 };
2282
2283 let Some(index1) = self.find_expr(decl1.source_info.span) else {
2284 note_default_suggestion();
2285 return;
2286 };
2287
2288 let Some(index2) = self.find_expr(decl2.source_info.span) else {
2289 note_default_suggestion();
2290 return;
2291 };
2292
2293 let sm = tcx.sess.source_map();
2294
2295 let Ok(index1_str) = sm.span_to_snippet(index1.span) else {
2296 note_default_suggestion();
2297 return;
2298 };
2299
2300 let Ok(index2_str) = sm.span_to_snippet(index2.span) else {
2301 note_default_suggestion();
2302 return;
2303 };
2304
2305 let Some(object) = tcx.hir_parent_id_iter(index1.hir_id).find_map(|id| {
2306 if let hir::Node::Expr(expr) = tcx.hir_node(id)
2307 && let hir::ExprKind::Index(obj, ..) = expr.kind
2308 {
2309 Some(obj)
2310 } else {
2311 None
2312 }
2313 }) else {
2314 note_default_suggestion();
2315 return;
2316 };
2317
2318 let Ok(obj_str) = sm.span_to_snippet(object.span) else {
2319 note_default_suggestion();
2320 return;
2321 };
2322
2323 let Some(swap_call) = tcx.hir_parent_id_iter(object.hir_id).find_map(|id| {
2324 if let hir::Node::Expr(call) = tcx.hir_node(id)
2325 && let hir::ExprKind::Call(callee, ..) = call.kind
2326 && let hir::ExprKind::Path(qpath) = callee.kind
2327 && let hir::QPath::Resolved(None, res) = qpath
2328 && let hir::def::Res::Def(_, did) = res.res
2329 && tcx.is_diagnostic_item(sym::mem_swap, did)
2330 {
2331 Some(call)
2332 } else {
2333 None
2334 }
2335 }) else {
2336 let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2337 let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2338 let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2339 let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2340 if !idx1.equivalent_for_indexing(idx2) {
2341 err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2342 }
2343 return;
2344 };
2345
2346 err.span_suggestion(
2347 swap_call.span,
2348 "use `.swap()` to swap elements at the specified indices instead",
2349 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.swap({1}, {2})", obj_str,
index1_str, index2_str))
})format!("{obj_str}.swap({index1_str}, {index2_str})"),
2350 Applicability::MachineApplicable,
2351 );
2352 return;
2353 }
2354 let place_ty = PlaceRef::ty(&place.as_ref(), self.body, tcx).ty;
2355 let borrowed_place_ty = PlaceRef::ty(&borrowed_place.as_ref(), self.body, tcx).ty;
2356 if !has_split_at_mut(place_ty) && !has_split_at_mut(borrowed_place_ty) {
2357 return;
2359 }
2360 let Some(index1) = self.find_expr(span) else { return };
2361 let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2362 let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2363 let Some(index2) = self.find_expr(issued_span) else { return };
2364 let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2365 let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2366 if idx1.equivalent_for_indexing(idx2) {
2367 return;
2369 }
2370 err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2371 }
2372
2373 pub(crate) fn explain_iterator_advancement_in_for_loop_if_applicable(
2384 &self,
2385 err: &mut Diag<'_>,
2386 span: Span,
2387 issued_spans: &UseSpans<'tcx>,
2388 ) {
2389 let issue_span = issued_spans.args_or_use();
2390 let tcx = self.infcx.tcx;
2391
2392 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2393 let typeck_results = tcx.typeck(self.mir_def_id());
2394
2395 struct ExprFinder<'hir> {
2396 tcx: TyCtxt<'hir>,
2397 issue_span: Span,
2398 expr_span: Span,
2399 body_expr: Option<&'hir hir::Expr<'hir>> = None,
2400 loop_bind: Option<&'hir Ident> = None,
2401 loop_span: Option<Span> = None,
2402 head_span: Option<Span> = None,
2403 pat_span: Option<Span> = None,
2404 head: Option<&'hir hir::Expr<'hir>> = None,
2405 }
2406 impl<'hir> Visitor<'hir> for ExprFinder<'hir> {
2407 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2408 if let hir::ExprKind::Call(path, [arg]) = ex.kind
2421 && let hir::ExprKind::Path(qpath) = path.kind
2422 && self.tcx.qpath_is_lang_item(qpath, LangItem::IntoIterIntoIter)
2423 && arg.span.contains(self.issue_span)
2424 && ex.span.desugaring_kind() == Some(DesugaringKind::ForLoop)
2425 {
2426 self.head = Some(arg);
2428 }
2429 if let hir::ExprKind::Loop(
2430 hir::Block { stmts: [stmt, ..], .. },
2431 _,
2432 hir::LoopSource::ForLoop,
2433 _,
2434 ) = ex.kind
2435 && let hir::StmtKind::Expr(hir::Expr {
2436 kind: hir::ExprKind::Match(call, [_, bind, ..], _),
2437 span: head_span,
2438 ..
2439 }) = stmt.kind
2440 && let hir::ExprKind::Call(path, _args) = call.kind
2441 && let hir::ExprKind::Path(qpath) = path.kind
2442 && self.tcx.qpath_is_lang_item(qpath, LangItem::IteratorNext)
2443 && let hir::PatKind::Struct(qpath, [field, ..], _) = bind.pat.kind
2444 && self.tcx.qpath_is_lang_item(qpath, LangItem::OptionSome)
2445 && call.span.contains(self.issue_span)
2446 {
2447 if let PatField {
2449 pat: hir::Pat { kind: hir::PatKind::Binding(_, _, ident, ..), .. },
2450 ..
2451 } = field
2452 {
2453 self.loop_bind = Some(ident);
2454 }
2455 self.head_span = Some(*head_span);
2456 self.pat_span = Some(bind.pat.span);
2457 self.loop_span = Some(stmt.span);
2458 }
2459
2460 if let hir::ExprKind::MethodCall(body_call, recv, ..) = ex.kind
2461 && body_call.ident.name == sym::next
2462 && recv.span.source_equal(self.expr_span)
2463 {
2464 self.body_expr = Some(ex);
2465 }
2466
2467 hir::intravisit::walk_expr(self, ex);
2468 }
2469 }
2470 let mut finder = ExprFinder { tcx, expr_span: span, issue_span, .. };
2471 finder.visit_expr(tcx.hir_body(body_id).value);
2472
2473 if let Some(body_expr) = finder.body_expr
2474 && let Some(loop_span) = finder.loop_span
2475 && let Some(def_id) = typeck_results.type_dependent_def_id(body_expr.hir_id)
2476 && let Some(trait_did) = tcx.trait_of_assoc(def_id)
2477 && tcx.is_diagnostic_item(sym::Iterator, trait_did)
2478 {
2479 if let Some(loop_bind) = finder.loop_bind {
2480 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a for loop advances the iterator for you, the result is stored in `{0}`",
loop_bind.name))
})format!(
2481 "a for loop advances the iterator for you, the result is stored in `{}`",
2482 loop_bind.name,
2483 ));
2484 } else {
2485 err.note(
2486 "a for loop advances the iterator for you, the result is stored in its pattern",
2487 );
2488 }
2489 let msg = "if you want to call `next` on a iterator within the loop, consider using \
2490 `while let`";
2491 if let Some(head) = finder.head
2492 && let Some(pat_span) = finder.pat_span
2493 && loop_span.contains(body_expr.span)
2494 && loop_span.contains(head.span)
2495 {
2496 let sm = self.infcx.tcx.sess.source_map();
2497
2498 let mut sugg = ::alloc::vec::Vec::new()vec![];
2499 if let hir::ExprKind::Path(hir::QPath::Resolved(None, _)) = head.kind {
2500 sugg.push((loop_span.with_hi(pat_span.lo()), "while let Some(".to_string()));
2504 sugg.push((
2505 pat_span.shrink_to_hi().with_hi(head.span.lo()),
2506 ") = ".to_string(),
2507 ));
2508 sugg.push((head.span.shrink_to_hi(), ".next()".to_string()));
2509 } else {
2510 let indent = if let Some(indent) = sm.indentation_before(loop_span) {
2512 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}", indent))
})format!("\n{indent}")
2513 } else {
2514 " ".to_string()
2515 };
2516 let Ok(head_str) = sm.span_to_snippet(head.span) else {
2517 err.help(msg);
2518 return;
2519 };
2520 sugg.push((
2521 loop_span.with_hi(pat_span.lo()),
2522 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let iter = {0};{1}while let Some(",
head_str, indent))
})format!("let iter = {head_str};{indent}while let Some("),
2523 ));
2524 sugg.push((
2525 pat_span.shrink_to_hi().with_hi(head.span.hi()),
2526 ") = iter.next()".to_string(),
2527 ));
2528 if let hir::ExprKind::MethodCall(_, recv, ..) = body_expr.kind
2531 && let hir::ExprKind::Path(hir::QPath::Resolved(None, ..)) = recv.kind
2532 {
2533 sugg.push((recv.span, "iter".to_string()));
2537 }
2538 }
2539 err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2540 } else {
2541 err.help(msg);
2542 }
2543 }
2544 }
2545
2546 fn suggest_using_closure_argument_instead_of_capture(
2563 &self,
2564 err: &mut Diag<'_>,
2565 borrowed_place: Place<'tcx>,
2566 issued_spans: &UseSpans<'tcx>,
2567 ) {
2568 let &UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2569 let tcx = self.infcx.tcx;
2570
2571 let local = borrowed_place.local;
2573 let local_ty = self.body.local_decls[local].ty;
2574
2575 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2577
2578 let body_expr = tcx.hir_body(body_id).value;
2579
2580 struct ClosureFinder<'hir> {
2581 tcx: TyCtxt<'hir>,
2582 borrow_span: Span,
2583 res: Option<(&'hir hir::Expr<'hir>, &'hir hir::Closure<'hir>)>,
2584 error_path: Option<(&'hir hir::Expr<'hir>, &'hir hir::QPath<'hir>)>,
2586 }
2587 impl<'hir> Visitor<'hir> for ClosureFinder<'hir> {
2588 type NestedFilter = OnlyBodies;
2589
2590 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
2591 self.tcx
2592 }
2593
2594 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2595 if let hir::ExprKind::Path(qpath) = &ex.kind
2596 && ex.span == self.borrow_span
2597 {
2598 self.error_path = Some((ex, qpath));
2599 }
2600
2601 if let hir::ExprKind::Closure(closure) = ex.kind
2602 && ex.span.contains(self.borrow_span)
2603 && self.res.as_ref().is_none_or(|(prev_res, _)| prev_res.span.contains(ex.span))
2607 {
2608 self.res = Some((ex, closure));
2609 }
2610
2611 hir::intravisit::walk_expr(self, ex);
2612 }
2613 }
2614
2615 let mut finder =
2617 ClosureFinder { tcx, borrow_span: capture_kind_span, res: None, error_path: None };
2618 finder.visit_expr(body_expr);
2619 let Some((closure_expr, closure)) = finder.res else { return };
2620
2621 let typeck_results = tcx.typeck(self.mir_def_id());
2622
2623 if let hir::Node::Expr(parent) = tcx.parent_hir_node(closure_expr.hir_id)
2626 && let hir::ExprKind::MethodCall(_, recv, ..) = parent.kind
2627 {
2628 let recv_ty = typeck_results.expr_ty(recv);
2629
2630 if recv_ty.peel_refs() != local_ty {
2631 return;
2632 }
2633 }
2634
2635 let ty::Closure(_, args) = typeck_results.expr_ty(closure_expr).kind() else {
2637 return;
2639 };
2640 let sig = args.as_closure().sig();
2641 let tupled_params = tcx.instantiate_bound_regions_with_erased(
2642 sig.inputs().iter().next().unwrap().map_bound(|&b| b),
2643 );
2644 let ty::Tuple(params) = tupled_params.kind() else { return };
2645
2646 let Some(this_name) = params.iter().zip(tcx.hir_body_param_idents(closure.body)).find_map(
2648 |(param_ty, ident)| {
2649 if param_ty.peel_refs() == local_ty { ident } else { None }
2651 },
2652 ) else {
2653 return;
2654 };
2655
2656 let spans;
2657 if let Some((_path_expr, qpath)) = finder.error_path
2658 && let hir::QPath::Resolved(_, path) = qpath
2659 && let hir::def::Res::Local(local_id) = path.res
2660 {
2661 struct VariableUseFinder {
2664 local_id: hir::HirId,
2665 spans: Vec<Span>,
2666 }
2667 impl<'hir> Visitor<'hir> for VariableUseFinder {
2668 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2669 if let hir::ExprKind::Path(qpath) = &ex.kind
2670 && let hir::QPath::Resolved(_, path) = qpath
2671 && let hir::def::Res::Local(local_id) = path.res
2672 && local_id == self.local_id
2673 {
2674 self.spans.push(ex.span);
2675 }
2676
2677 hir::intravisit::walk_expr(self, ex);
2678 }
2679 }
2680
2681 let mut finder = VariableUseFinder { local_id, spans: Vec::new() };
2682 finder.visit_expr(tcx.hir_body(closure.body).value);
2683
2684 spans = finder.spans;
2685 } else {
2686 spans = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[capture_kind_span]))vec![capture_kind_span];
2687 }
2688
2689 err.multipart_suggestion(
2690 "try using the closure argument",
2691 iter::zip(spans, iter::repeat(this_name.to_string())).collect(),
2692 Applicability::MaybeIncorrect,
2693 );
2694 }
2695
2696 fn suggest_binding_for_closure_capture_self(
2697 &self,
2698 err: &mut Diag<'_>,
2699 issued_spans: &UseSpans<'tcx>,
2700 ) {
2701 let UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2702
2703 struct ExpressionFinder<'tcx> {
2704 capture_span: Span,
2705 closure_change_spans: Vec<Span> = ::alloc::vec::Vec::new()vec![],
2706 closure_arg_span: Option<Span> = None,
2707 in_closure: bool = false,
2708 suggest_arg: String = String::new(),
2709 tcx: TyCtxt<'tcx>,
2710 closure_local_id: Option<hir::HirId> = None,
2711 closure_call_changes: Vec<(Span, String)> = ::alloc::vec::Vec::new()vec![],
2712 }
2713 impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
2714 fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
2715 if e.span.contains(self.capture_span)
2716 && let hir::ExprKind::Closure(&hir::Closure {
2717 kind: hir::ClosureKind::Closure,
2718 body,
2719 fn_arg_span,
2720 fn_decl: hir::FnDecl { inputs, .. },
2721 ..
2722 }) = e.kind
2723 && let hir::Node::Expr(body) = self.tcx.hir_node(body.hir_id)
2724 {
2725 self.suggest_arg = "this: &Self".to_string();
2726 if inputs.len() > 0 {
2727 self.suggest_arg.push_str(", ");
2728 }
2729 self.in_closure = true;
2730 self.closure_arg_span = fn_arg_span;
2731 self.visit_expr(body);
2732 self.in_closure = false;
2733 }
2734 if let hir::Expr { kind: hir::ExprKind::Path(path), .. } = e
2735 && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2736 && seg.ident.name == kw::SelfLower
2737 && self.in_closure
2738 {
2739 self.closure_change_spans.push(e.span);
2740 }
2741 hir::intravisit::walk_expr(self, e);
2742 }
2743
2744 fn visit_local(&mut self, local: &'hir hir::LetStmt<'hir>) {
2745 if let hir::Pat { kind: hir::PatKind::Binding(_, hir_id, _ident, _), .. } =
2746 local.pat
2747 && let Some(init) = local.init
2748 && let &hir::Expr {
2749 kind:
2750 hir::ExprKind::Closure(&hir::Closure {
2751 kind: hir::ClosureKind::Closure,
2752 ..
2753 }),
2754 ..
2755 } = init
2756 && init.span.contains(self.capture_span)
2757 {
2758 self.closure_local_id = Some(*hir_id);
2759 }
2760
2761 hir::intravisit::walk_local(self, local);
2762 }
2763
2764 fn visit_stmt(&mut self, s: &'hir hir::Stmt<'hir>) {
2765 if let hir::StmtKind::Semi(e) = s.kind
2766 && let hir::ExprKind::Call(
2767 hir::Expr { kind: hir::ExprKind::Path(path), .. },
2768 args,
2769 ) = e.kind
2770 && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2771 && let Res::Local(hir_id) = seg.res
2772 && Some(hir_id) == self.closure_local_id
2773 {
2774 let (span, arg_str) = if args.len() > 0 {
2775 (args[0].span.shrink_to_lo(), "self, ".to_string())
2776 } else {
2777 let span = e.span.trim_start(seg.ident.span).unwrap_or(e.span);
2778 (span, "(self)".to_string())
2779 };
2780 self.closure_call_changes.push((span, arg_str));
2781 }
2782 hir::intravisit::walk_stmt(self, s);
2783 }
2784 }
2785
2786 if let hir::Node::ImplItem(hir::ImplItem {
2787 kind: hir::ImplItemKind::Fn(_fn_sig, body_id),
2788 ..
2789 }) = self.infcx.tcx.hir_node(self.mir_hir_id())
2790 && let hir::Node::Expr(expr) = self.infcx.tcx.hir_node(body_id.hir_id)
2791 {
2792 let mut finder =
2793 ExpressionFinder { capture_span: *capture_kind_span, tcx: self.infcx.tcx, .. };
2794 finder.visit_expr(expr);
2795
2796 if finder.closure_change_spans.is_empty() || finder.closure_call_changes.is_empty() {
2797 return;
2798 }
2799
2800 let sm = self.infcx.tcx.sess.source_map();
2801 let sugg = finder
2802 .closure_arg_span
2803 .map(|span| (sm.next_point(span.shrink_to_lo()).shrink_to_hi(), finder.suggest_arg))
2804 .into_iter()
2805 .chain(
2806 finder.closure_change_spans.into_iter().map(|span| (span, "this".to_string())),
2807 )
2808 .chain(finder.closure_call_changes)
2809 .collect();
2810
2811 err.multipart_suggestion(
2812 "try explicitly passing `&Self` into the closure as an argument",
2813 sugg,
2814 Applicability::MachineApplicable,
2815 );
2816 }
2817 }
2818
2819 fn describe_place_for_conflicting_borrow(
2848 &self,
2849 first_borrowed_place: Place<'tcx>,
2850 second_borrowed_place: Place<'tcx>,
2851 ) -> (String, String, String, String) {
2852 let union_ty = |place_base| {
2855 let ty = PlaceRef::ty(&place_base, self.body, self.infcx.tcx).ty;
2858 ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
2859 };
2860
2861 Some(())
2865 .filter(|_| {
2866 first_borrowed_place != second_borrowed_place
2869 })
2870 .and_then(|_| {
2871 for (place_base, elem) in first_borrowed_place.iter_projections().rev() {
2876 match elem {
2877 ProjectionElem::Field(field, _) if union_ty(place_base).is_some() => {
2878 return Some((place_base, field));
2879 }
2880 _ => {}
2881 }
2882 }
2883 None
2884 })
2885 .and_then(|(target_base, target_field)| {
2886 for (place_base, elem) in second_borrowed_place.iter_projections().rev() {
2889 if let ProjectionElem::Field(field, _) = elem
2890 && let Some(union_ty) = union_ty(place_base)
2891 {
2892 if field != target_field && place_base == target_base {
2893 return Some((
2894 self.describe_any_place(place_base),
2895 self.describe_any_place(first_borrowed_place.as_ref()),
2896 self.describe_any_place(second_borrowed_place.as_ref()),
2897 union_ty.to_string(),
2898 ));
2899 }
2900 }
2901 }
2902 None
2903 })
2904 .unwrap_or_else(|| {
2905 (
2908 self.describe_any_place(first_borrowed_place.as_ref()),
2909 "".to_string(),
2910 "".to_string(),
2911 "".to_string(),
2912 )
2913 })
2914 }
2915
2916 #[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("report_borrowed_value_does_not_live_long_enough",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2922u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["location", "borrow",
"place_span", "kind"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let drop_span = place_span.1;
let borrowed_local = borrow.borrowed_place.local;
let borrow_spans = self.retrieve_borrow_spans(borrow);
let borrow_span = borrow_spans.var_or_use_path_span();
let proper_span =
self.body.local_decls[borrowed_local].source_info.span;
if self.access_place_error_reported.contains(&(Place::from(borrowed_local),
borrow_span)) {
{
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/diagnostics/conflict_errors.rs:2939",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2939u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("suppressing access_place error when borrow doesn\'t live long enough for {0:?}",
borrow_span) as &dyn Value))])
});
} else { ; }
};
return;
}
self.access_place_error_reported.insert((Place::from(borrowed_local),
borrow_span));
if self.body.local_decls[borrowed_local].is_ref_to_thread_local()
{
let err =
self.report_thread_local_value_does_not_live_long_enough(drop_span,
borrow_span);
self.buffer_error(err);
return;
}
if let StorageDeadOrDrop::Destructor(dropped_ty) =
self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
{
if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref())
{
self.report_borrow_conflicts_with_destructor(location,
borrow, place_span, kind, dropped_ty);
return;
}
}
let place_desc =
self.describe_place(borrow.borrowed_place.as_ref());
let kind_place =
kind.filter(|_|
place_desc.is_some()).map(|k| (k, place_span.0));
let explanation =
self.explain_why_borrow_contains_point(location, borrow,
kind_place);
{
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/diagnostics/conflict_errors.rs:2975",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2975u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["place_desc",
"explanation"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&place_desc)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&explanation)
as &dyn Value))])
});
} else { ; }
};
let mut err =
match (place_desc, explanation) {
(Some(name),
BorrowExplanation::UsedLater(_,
LaterUseKind::ClosureCapture, var_or_use_span, _)) if
borrow_spans.for_coroutine() || borrow_spans.for_closure()
=>
self.report_escaping_closure_capture(borrow_spans,
borrow_span,
&RegionName {
name: self.synthesize_region_name(),
source: RegionNameSource::Static,
}, ConstraintCategory::CallArgument(None), var_or_use_span,
&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
}), "block"),
(Some(name), BorrowExplanation::MustBeValidFor {
category: category
@
(ConstraintCategory::Return(_) |
ConstraintCategory::CallArgument(_) |
ConstraintCategory::OpaqueType),
from_closure: false,
ref region_name,
span, .. }) if
borrow_spans.for_coroutine() || borrow_spans.for_closure()
=>
self.report_escaping_closure_capture(borrow_spans,
borrow_span, region_name, category, span,
&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
}), "function"),
(name, BorrowExplanation::MustBeValidFor {
category: ConstraintCategory::Assignment,
from_closure: false,
region_name: RegionName {
source: RegionNameSource::AnonRegionFromUpvar(upvar_span,
upvar_name),
..
},
span, .. }) =>
self.report_escaping_data(borrow_span, &name, upvar_span,
upvar_name, span),
(Some(name), explanation) =>
self.report_local_value_does_not_live_long_enough(location,
&name, borrow, drop_span, borrow_spans, explanation),
(None, explanation) =>
self.report_temporary_value_does_not_live_long_enough(location,
borrow, drop_span, borrow_spans, proper_span, explanation),
};
self.note_due_to_edition_2024_opaque_capture_rules(borrow,
&mut err);
self.buffer_error(err);
}
}
}#[instrument(level = "debug", skip(self))]
2923 pub(crate) fn report_borrowed_value_does_not_live_long_enough(
2924 &mut self,
2925 location: Location,
2926 borrow: &BorrowData<'tcx>,
2927 place_span: (Place<'tcx>, Span),
2928 kind: Option<WriteKind>,
2929 ) {
2930 let drop_span = place_span.1;
2931 let borrowed_local = borrow.borrowed_place.local;
2932
2933 let borrow_spans = self.retrieve_borrow_spans(borrow);
2934 let borrow_span = borrow_spans.var_or_use_path_span();
2935
2936 let proper_span = self.body.local_decls[borrowed_local].source_info.span;
2937
2938 if self.access_place_error_reported.contains(&(Place::from(borrowed_local), borrow_span)) {
2939 debug!(
2940 "suppressing access_place error when borrow doesn't live long enough for {:?}",
2941 borrow_span
2942 );
2943 return;
2944 }
2945
2946 self.access_place_error_reported.insert((Place::from(borrowed_local), borrow_span));
2947
2948 if self.body.local_decls[borrowed_local].is_ref_to_thread_local() {
2949 let err =
2950 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span);
2951 self.buffer_error(err);
2952 return;
2953 }
2954
2955 if let StorageDeadOrDrop::Destructor(dropped_ty) =
2956 self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
2957 {
2958 if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
2963 self.report_borrow_conflicts_with_destructor(
2964 location, borrow, place_span, kind, dropped_ty,
2965 );
2966 return;
2967 }
2968 }
2969
2970 let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
2971
2972 let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
2973 let explanation = self.explain_why_borrow_contains_point(location, borrow, kind_place);
2974
2975 debug!(?place_desc, ?explanation);
2976
2977 let mut err = match (place_desc, explanation) {
2978 (
2988 Some(name),
2989 BorrowExplanation::UsedLater(_, LaterUseKind::ClosureCapture, var_or_use_span, _),
2990 ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
2991 .report_escaping_closure_capture(
2992 borrow_spans,
2993 borrow_span,
2994 &RegionName {
2995 name: self.synthesize_region_name(),
2996 source: RegionNameSource::Static,
2997 },
2998 ConstraintCategory::CallArgument(None),
2999 var_or_use_span,
3000 &format!("`{name}`"),
3001 "block",
3002 ),
3003 (
3004 Some(name),
3005 BorrowExplanation::MustBeValidFor {
3006 category:
3007 category @ (ConstraintCategory::Return(_)
3008 | ConstraintCategory::CallArgument(_)
3009 | ConstraintCategory::OpaqueType),
3010 from_closure: false,
3011 ref region_name,
3012 span,
3013 ..
3014 },
3015 ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
3016 .report_escaping_closure_capture(
3017 borrow_spans,
3018 borrow_span,
3019 region_name,
3020 category,
3021 span,
3022 &format!("`{name}`"),
3023 "function",
3024 ),
3025 (
3026 name,
3027 BorrowExplanation::MustBeValidFor {
3028 category: ConstraintCategory::Assignment,
3029 from_closure: false,
3030 region_name:
3031 RegionName {
3032 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
3033 ..
3034 },
3035 span,
3036 ..
3037 },
3038 ) => self.report_escaping_data(borrow_span, &name, upvar_span, upvar_name, span),
3039 (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
3040 location,
3041 &name,
3042 borrow,
3043 drop_span,
3044 borrow_spans,
3045 explanation,
3046 ),
3047 (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
3048 location,
3049 borrow,
3050 drop_span,
3051 borrow_spans,
3052 proper_span,
3053 explanation,
3054 ),
3055 };
3056 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
3057
3058 self.buffer_error(err);
3059 }
3060
3061 #[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("report_local_value_does_not_live_long_enough",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3061u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["location", "name",
"borrow", "drop_span", "borrow_spans"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&name as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&drop_span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow_spans)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Diag<'infcx> = loop {};
return __tracing_attr_fake_return;
}
{
let borrow_span = borrow_spans.var_or_use_path_span();
if let BorrowExplanation::MustBeValidFor {
category, span, ref opt_place_desc, from_closure: false, ..
} = explanation &&
let Err(diag) =
self.try_report_cannot_return_reference_to_local(borrow,
borrow_span, span, category, opt_place_desc.as_ref()) {
return diag;
}
let name =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
});
let mut err =
self.path_does_not_live_long_enough(borrow_span, &name);
if let Some(annotation) =
self.annotate_argument_and_return_for_borrow(borrow) {
let region_name = annotation.emit(self, &mut err);
err.span_label(borrow_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} would have to be valid for `{1}`...",
name, region_name))
}));
err.span_label(drop_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("...but {1} will be dropped here, when the {0} returns",
self.infcx.tcx.opt_item_name(self.mir_def_id().to_def_id()).map(|name|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("function `{0}`", name))
})).unwrap_or_else(||
{
match &self.infcx.tcx.def_kind(self.mir_def_id()) {
DefKind::Closure if
self.infcx.tcx.is_coroutine(self.mir_def_id().to_def_id())
=> {
"enclosing coroutine"
}
DefKind::Closure => "enclosing closure",
kind =>
::rustc_middle::util::bug::bug_fmt(format_args!("expected closure or coroutine, found {0:?}",
kind)),
}.to_string()
}), name))
}));
err.note("functions cannot return a borrow to data owned within the function's scope, \
functions can only return borrows to data passed as arguments");
err.note("to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
references-and-borrowing.html#dangling-references>");
if let BorrowExplanation::MustBeValidFor { .. } = explanation
{} else {
explanation.add_explanation_to_diagnostic(&self, &mut err,
"", None, None);
}
} else {
err.span_label(borrow_span,
"borrowed value does not live long enough");
err.span_label(drop_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} dropped here while still borrowed",
name))
}));
borrow_spans.args_subdiag(&mut err,
|args_span|
{
crate::session_diagnostics::CaptureArgLabel::Capture {
is_within: borrow_spans.for_coroutine(),
args_span,
}
});
explanation.add_explanation_to_diagnostic(&self, &mut err, "",
Some(borrow_span), None);
if let BorrowExplanation::UsedLater(_dropped_local, _, _, _) =
explanation {
for (local, local_decl) in
self.body.local_decls.iter_enumerated() {
if let ty::Adt(adt_def, args) = local_decl.ty.kind() &&
self.infcx.tcx.is_diagnostic_item(sym::Vec, adt_def.did())
&& args.len() > 0 {
let vec_inner_ty = args.type_at(0);
if vec_inner_ty.is_ref() {
let local_place = local.into();
if let Some(local_name) = self.describe_place(local_place) {
err.span_label(local_decl.source_info.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("variable `{0}` declared here",
local_name))
}));
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is a collection that stores borrowed references, but {1} does not live long enough to be stored in it",
local_name, name))
}));
err.help("buffer reuse with borrowed references requires unsafe code or restructuring");
break;
}
}
}
}
}
}
err
}
}
}#[tracing::instrument(level = "debug", skip(self, explanation))]
3062 fn report_local_value_does_not_live_long_enough(
3063 &self,
3064 location: Location,
3065 name: &str,
3066 borrow: &BorrowData<'tcx>,
3067 drop_span: Span,
3068 borrow_spans: UseSpans<'tcx>,
3069 explanation: BorrowExplanation<'tcx>,
3070 ) -> Diag<'infcx> {
3071 let borrow_span = borrow_spans.var_or_use_path_span();
3072 if let BorrowExplanation::MustBeValidFor {
3073 category,
3074 span,
3075 ref opt_place_desc,
3076 from_closure: false,
3077 ..
3078 } = explanation
3079 && let Err(diag) = self.try_report_cannot_return_reference_to_local(
3080 borrow,
3081 borrow_span,
3082 span,
3083 category,
3084 opt_place_desc.as_ref(),
3085 )
3086 {
3087 return diag;
3088 }
3089
3090 let name = format!("`{name}`");
3091
3092 let mut err = self.path_does_not_live_long_enough(borrow_span, &name);
3093
3094 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
3095 let region_name = annotation.emit(self, &mut err);
3096
3097 err.span_label(
3098 borrow_span,
3099 format!("{name} would have to be valid for `{region_name}`..."),
3100 );
3101
3102 err.span_label(
3103 drop_span,
3104 format!(
3105 "...but {name} will be dropped here, when the {} returns",
3106 self.infcx
3107 .tcx
3108 .opt_item_name(self.mir_def_id().to_def_id())
3109 .map(|name| format!("function `{name}`"))
3110 .unwrap_or_else(|| {
3111 match &self.infcx.tcx.def_kind(self.mir_def_id()) {
3112 DefKind::Closure
3113 if self
3114 .infcx
3115 .tcx
3116 .is_coroutine(self.mir_def_id().to_def_id()) =>
3117 {
3118 "enclosing coroutine"
3119 }
3120 DefKind::Closure => "enclosing closure",
3121 kind => bug!("expected closure or coroutine, found {:?}", kind),
3122 }
3123 .to_string()
3124 })
3125 ),
3126 );
3127
3128 err.note(
3129 "functions cannot return a borrow to data owned within the function's scope, \
3130 functions can only return borrows to data passed as arguments",
3131 );
3132 err.note(
3133 "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
3134 references-and-borrowing.html#dangling-references>",
3135 );
3136
3137 if let BorrowExplanation::MustBeValidFor { .. } = explanation {
3138 } else {
3139 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3140 }
3141 } else {
3142 err.span_label(borrow_span, "borrowed value does not live long enough");
3143 err.span_label(drop_span, format!("{name} dropped here while still borrowed"));
3144
3145 borrow_spans.args_subdiag(&mut err, |args_span| {
3146 crate::session_diagnostics::CaptureArgLabel::Capture {
3147 is_within: borrow_spans.for_coroutine(),
3148 args_span,
3149 }
3150 });
3151
3152 explanation.add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
3153
3154 if let BorrowExplanation::UsedLater(_dropped_local, _, _, _) = explanation {
3156 for (local, local_decl) in self.body.local_decls.iter_enumerated() {
3158 if let ty::Adt(adt_def, args) = local_decl.ty.kind()
3159 && self.infcx.tcx.is_diagnostic_item(sym::Vec, adt_def.did())
3160 && args.len() > 0
3161 {
3162 let vec_inner_ty = args.type_at(0);
3163 if vec_inner_ty.is_ref() {
3165 let local_place = local.into();
3166 if let Some(local_name) = self.describe_place(local_place) {
3167 err.span_label(
3168 local_decl.source_info.span,
3169 format!("variable `{local_name}` declared here"),
3170 );
3171 err.note(
3172 format!(
3173 "`{local_name}` is a collection that stores borrowed references, \
3174 but {name} does not live long enough to be stored in it"
3175 )
3176 );
3177 err.help(
3178 "buffer reuse with borrowed references requires unsafe code or restructuring"
3179 );
3180 break;
3181 }
3182 }
3183 }
3184 }
3185 }
3186 }
3187
3188 err
3189 }
3190
3191 fn report_borrow_conflicts_with_destructor(
3192 &mut self,
3193 location: Location,
3194 borrow: &BorrowData<'tcx>,
3195 (place, drop_span): (Place<'tcx>, Span),
3196 kind: Option<WriteKind>,
3197 dropped_ty: Ty<'tcx>,
3198 ) {
3199 {
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/diagnostics/conflict_errors.rs:3199",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3199u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_borrow_conflicts_with_destructor({0:?}, {1:?}, ({2:?}, {3:?}), {4:?})",
location, borrow, place, drop_span, kind) as &dyn Value))])
});
} else { ; }
};debug!(
3200 "report_borrow_conflicts_with_destructor(\
3201 {:?}, {:?}, ({:?}, {:?}), {:?}\
3202 )",
3203 location, borrow, place, drop_span, kind,
3204 );
3205
3206 let borrow_spans = self.retrieve_borrow_spans(borrow);
3207 let borrow_span = borrow_spans.var_or_use();
3208
3209 let mut err = self.cannot_borrow_across_destructor(borrow_span);
3210
3211 let what_was_dropped = match self.describe_place(place.as_ref()) {
3212 Some(name) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
})format!("`{name}`"),
3213 None => String::from("temporary value"),
3214 };
3215
3216 let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
3217 Some(borrowed) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("here, drop of {0} needs exclusive access to `{1}`, because the type `{2}` implements the `Drop` trait",
what_was_dropped, borrowed, dropped_ty))
})format!(
3218 "here, drop of {what_was_dropped} needs exclusive access to `{borrowed}`, \
3219 because the type `{dropped_ty}` implements the `Drop` trait"
3220 ),
3221 None => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("here is drop of {0}; whose type `{1}` implements the `Drop` trait",
what_was_dropped, dropped_ty))
})format!(
3222 "here is drop of {what_was_dropped}; whose type `{dropped_ty}` implements the `Drop` trait"
3223 ),
3224 };
3225 err.span_label(drop_span, label);
3226
3227 let explanation =
3229 self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
3230 match explanation {
3231 BorrowExplanation::UsedLater { .. }
3232 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3233 err.note("consider using a `let` binding to create a longer lived value");
3234 }
3235 _ => {}
3236 }
3237
3238 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3239
3240 self.buffer_error(err);
3241 }
3242
3243 fn report_thread_local_value_does_not_live_long_enough(
3244 &self,
3245 drop_span: Span,
3246 borrow_span: Span,
3247 ) -> Diag<'infcx> {
3248 {
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/diagnostics/conflict_errors.rs:3248",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3248u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_thread_local_value_does_not_live_long_enough({0:?}, {1:?})",
drop_span, borrow_span) as &dyn Value))])
});
} else { ; }
};debug!(
3249 "report_thread_local_value_does_not_live_long_enough(\
3250 {:?}, {:?}\
3251 )",
3252 drop_span, borrow_span
3253 );
3254
3255 let sm = self.infcx.tcx.sess.source_map();
3260 let end_of_function = if drop_span.is_empty()
3261 && let Ok(adjusted_span) = sm.span_extend_prev_while(drop_span, |c| c == '}')
3262 {
3263 adjusted_span
3264 } else {
3265 drop_span
3266 };
3267 self.thread_local_value_does_not_live_long_enough(borrow_span)
3268 .with_span_label(
3269 borrow_span,
3270 "thread-local variables cannot be borrowed beyond the end of the function",
3271 )
3272 .with_span_label(end_of_function, "end of enclosing function is here")
3273 }
3274
3275 #[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("report_temporary_value_does_not_live_long_enough",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3275u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["location", "borrow",
"drop_span", "borrow_spans", "proper_span", "explanation"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&drop_span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow_spans)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&proper_span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&explanation)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Diag<'infcx> = loop {};
return __tracing_attr_fake_return;
}
{
if let BorrowExplanation::MustBeValidFor {
category, span, from_closure: false, .. } = explanation {
if let Err(diag) =
self.try_report_cannot_return_reference_to_local(borrow,
proper_span, span, category, None) {
return diag;
}
}
let mut err =
self.temporary_value_borrowed_for_too_long(proper_span);
err.span_label(proper_span,
"creates a temporary value which is freed while still in use");
err.span_label(drop_span,
"temporary value is freed at the end of this statement");
match explanation {
BorrowExplanation::UsedLater(..) |
BorrowExplanation::UsedLaterInLoop(..) |
BorrowExplanation::UsedLaterWhenDropped { .. } => {
let sm = self.infcx.tcx.sess.source_map();
let mut suggested = false;
let msg =
"consider using a `let` binding to create a longer lived value";
#[doc =
" We check that there\'s a single level of block nesting to ensure always correct"]
#[doc =
" suggestions. If we don\'t, then we only provide a free-form message to avoid"]
#[doc =
" misleading users in cases like `tests/ui/nll/borrowed-temporary-error.rs`."]
#[doc =
" We could expand the analysis to suggest hoising all of the relevant parts of"]
#[doc =
" the users\' code to make the code compile, but that could be too much."]
#[doc =
" We found the `prop_expr` by the way to check whether the expression is a"]
#[doc =
" `FormatArguments`, which is a special case since it\'s generated by the"]
#[doc = " compiler."]
struct NestedStatementVisitor<'tcx> {
span: Span,
current: usize,
found: usize,
prop_expr: Option<&'tcx hir::Expr<'tcx>>,
call: Option<&'tcx hir::Expr<'tcx>>,
}
impl<'tcx> Visitor<'tcx> for NestedStatementVisitor<'tcx> {
fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
self.current += 1;
walk_block(self, block);
self.current -= 1;
}
fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
if let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind
{
if self.span == rcvr.span.source_callsite() {
self.call = Some(expr);
}
}
if self.span == expr.span.source_callsite() {
self.found = self.current;
if self.prop_expr.is_none() { self.prop_expr = Some(expr); }
}
walk_expr(self, expr);
}
}
let source_info = self.body.source_info(location);
let proper_span = proper_span.source_callsite();
if let Some(scope) =
self.body.source_scopes.get(source_info.scope) &&
let ClearCrossCrate::Set(scope_data) = &scope.local_data &&
let Some(id) =
self.infcx.tcx.hir_node(scope_data.lint_root).body_id() &&
let hir::ExprKind::Block(block, _) =
self.infcx.tcx.hir_body(id).value.kind {
for stmt in block.stmts {
let mut visitor =
NestedStatementVisitor {
span: proper_span,
current: 0,
found: 0,
prop_expr: None,
call: None,
};
visitor.visit_stmt(stmt);
let typeck_results =
self.infcx.tcx.typeck(self.mir_def_id());
let expr_ty: Option<Ty<'_>> =
visitor.prop_expr.map(|expr|
typeck_results.expr_ty(expr).peel_refs());
if visitor.found == 0 && stmt.span.contains(proper_span) &&
let Some(p) = sm.span_to_margin(stmt.span) &&
let Ok(s) = sm.span_to_snippet(proper_span) {
if let Some(call) = visitor.call &&
let hir::ExprKind::MethodCall(path, _, [], _) = call.kind &&
path.ident.name == sym::iter && let Some(ty) = expr_ty {
err.span_suggestion_verbose(path.ident.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider consuming the `{0}` when turning it into an `Iterator`",
ty))
}), "into_iter", Applicability::MaybeIncorrect);
}
let mutability =
if #[allow(non_exhaustive_omitted_patterns)] match borrow.kind()
{
BorrowKind::Mut { .. } => true,
_ => false,
} {
"mut "
} else { "" };
let addition =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let {0}binding = {1};\n{2}",
mutability, s, " ".repeat(p)))
});
err.multipart_suggestion(msg,
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(stmt.span.shrink_to_lo(), addition),
(proper_span, "binding".to_string())])),
Applicability::MaybeIncorrect);
suggested = true;
break;
}
}
}
if !suggested { err.note(msg); }
}
_ => {}
}
explanation.add_explanation_to_diagnostic(&self, &mut err, "",
None, None);
borrow_spans.args_subdiag(&mut err,
|args_span|
{
crate::session_diagnostics::CaptureArgLabel::Capture {
is_within: borrow_spans.for_coroutine(),
args_span,
}
});
err
}
}
}#[instrument(level = "debug", skip(self))]
3276 fn report_temporary_value_does_not_live_long_enough(
3277 &self,
3278 location: Location,
3279 borrow: &BorrowData<'tcx>,
3280 drop_span: Span,
3281 borrow_spans: UseSpans<'tcx>,
3282 proper_span: Span,
3283 explanation: BorrowExplanation<'tcx>,
3284 ) -> Diag<'infcx> {
3285 if let BorrowExplanation::MustBeValidFor { category, span, from_closure: false, .. } =
3286 explanation
3287 {
3288 if let Err(diag) = self.try_report_cannot_return_reference_to_local(
3289 borrow,
3290 proper_span,
3291 span,
3292 category,
3293 None,
3294 ) {
3295 return diag;
3296 }
3297 }
3298
3299 let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
3300 err.span_label(proper_span, "creates a temporary value which is freed while still in use");
3301 err.span_label(drop_span, "temporary value is freed at the end of this statement");
3302
3303 match explanation {
3304 BorrowExplanation::UsedLater(..)
3305 | BorrowExplanation::UsedLaterInLoop(..)
3306 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3307 let sm = self.infcx.tcx.sess.source_map();
3309 let mut suggested = false;
3310 let msg = "consider using a `let` binding to create a longer lived value";
3311
3312 struct NestedStatementVisitor<'tcx> {
3321 span: Span,
3322 current: usize,
3323 found: usize,
3324 prop_expr: Option<&'tcx hir::Expr<'tcx>>,
3325 call: Option<&'tcx hir::Expr<'tcx>>,
3326 }
3327
3328 impl<'tcx> Visitor<'tcx> for NestedStatementVisitor<'tcx> {
3329 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
3330 self.current += 1;
3331 walk_block(self, block);
3332 self.current -= 1;
3333 }
3334 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
3335 if let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind {
3336 if self.span == rcvr.span.source_callsite() {
3337 self.call = Some(expr);
3338 }
3339 }
3340 if self.span == expr.span.source_callsite() {
3341 self.found = self.current;
3342 if self.prop_expr.is_none() {
3343 self.prop_expr = Some(expr);
3344 }
3345 }
3346 walk_expr(self, expr);
3347 }
3348 }
3349 let source_info = self.body.source_info(location);
3350 let proper_span = proper_span.source_callsite();
3351 if let Some(scope) = self.body.source_scopes.get(source_info.scope)
3352 && let ClearCrossCrate::Set(scope_data) = &scope.local_data
3353 && let Some(id) = self.infcx.tcx.hir_node(scope_data.lint_root).body_id()
3354 && let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir_body(id).value.kind
3355 {
3356 for stmt in block.stmts {
3357 let mut visitor = NestedStatementVisitor {
3358 span: proper_span,
3359 current: 0,
3360 found: 0,
3361 prop_expr: None,
3362 call: None,
3363 };
3364 visitor.visit_stmt(stmt);
3365
3366 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
3367 let expr_ty: Option<Ty<'_>> =
3368 visitor.prop_expr.map(|expr| typeck_results.expr_ty(expr).peel_refs());
3369
3370 if visitor.found == 0
3371 && stmt.span.contains(proper_span)
3372 && let Some(p) = sm.span_to_margin(stmt.span)
3373 && let Ok(s) = sm.span_to_snippet(proper_span)
3374 {
3375 if let Some(call) = visitor.call
3376 && let hir::ExprKind::MethodCall(path, _, [], _) = call.kind
3377 && path.ident.name == sym::iter
3378 && let Some(ty) = expr_ty
3379 {
3380 err.span_suggestion_verbose(
3381 path.ident.span,
3382 format!(
3383 "consider consuming the `{ty}` when turning it into an \
3384 `Iterator`",
3385 ),
3386 "into_iter",
3387 Applicability::MaybeIncorrect,
3388 );
3389 }
3390
3391 let mutability = if matches!(borrow.kind(), BorrowKind::Mut { .. }) {
3392 "mut "
3393 } else {
3394 ""
3395 };
3396
3397 let addition =
3398 format!("let {}binding = {};\n{}", mutability, s, " ".repeat(p));
3399 err.multipart_suggestion(
3400 msg,
3401 vec![
3402 (stmt.span.shrink_to_lo(), addition),
3403 (proper_span, "binding".to_string()),
3404 ],
3405 Applicability::MaybeIncorrect,
3406 );
3407
3408 suggested = true;
3409 break;
3410 }
3411 }
3412 }
3413 if !suggested {
3414 err.note(msg);
3415 }
3416 }
3417 _ => {}
3418 }
3419 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3420
3421 borrow_spans.args_subdiag(&mut err, |args_span| {
3422 crate::session_diagnostics::CaptureArgLabel::Capture {
3423 is_within: borrow_spans.for_coroutine(),
3424 args_span,
3425 }
3426 });
3427
3428 err
3429 }
3430
3431 fn try_report_cannot_return_reference_to_local(
3432 &self,
3433 borrow: &BorrowData<'tcx>,
3434 borrow_span: Span,
3435 return_span: Span,
3436 category: ConstraintCategory<'tcx>,
3437 opt_place_desc: Option<&String>,
3438 ) -> Result<(), Diag<'infcx>> {
3439 let return_kind = match category {
3440 ConstraintCategory::Return(_) => "return",
3441 ConstraintCategory::Yield => "yield",
3442 _ => return Ok(()),
3443 };
3444
3445 let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
3447 "reference to"
3448 } else {
3449 "value referencing"
3450 };
3451
3452 let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
3453 let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
3454 match self.body.local_kind(local) {
3455 LocalKind::Temp if self.body.local_decls[local].is_user_variable() => {
3456 "local variable "
3457 }
3458 LocalKind::Arg
3459 if !self.upvars.is_empty() && local == ty::CAPTURE_STRUCT_LOCAL =>
3460 {
3461 "variable captured by `move` "
3462 }
3463 LocalKind::Arg => "function parameter ",
3464 LocalKind::ReturnPointer | LocalKind::Temp => {
3465 ::rustc_middle::util::bug::bug_fmt(format_args!("temporary or return pointer with a name"))bug!("temporary or return pointer with a name")
3466 }
3467 }
3468 } else {
3469 "local data "
3470 };
3471 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}`{1}`", local_kind, place_desc))
})format!("{local_kind}`{place_desc}`"), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is borrowed here",
place_desc))
})format!("`{place_desc}` is borrowed here"))
3472 } else {
3473 let local = borrow.borrowed_place.local;
3474 match self.body.local_kind(local) {
3475 LocalKind::Arg => (
3476 "function parameter".to_string(),
3477 "function parameter borrowed here".to_string(),
3478 ),
3479 LocalKind::Temp
3480 if self.body.local_decls[local].is_user_variable()
3481 && !self.body.local_decls[local]
3482 .source_info
3483 .span
3484 .in_external_macro(self.infcx.tcx.sess.source_map()) =>
3485 {
3486 ("local binding".to_string(), "local binding introduced here".to_string())
3487 }
3488 LocalKind::ReturnPointer | LocalKind::Temp => {
3489 ("temporary value".to_string(), "temporary value created here".to_string())
3490 }
3491 }
3492 };
3493
3494 let mut err = self.cannot_return_reference_to_local(
3495 return_span,
3496 return_kind,
3497 reference_desc,
3498 &place_desc,
3499 );
3500
3501 if return_span != borrow_span {
3502 err.span_label(borrow_span, note);
3503
3504 let tcx = self.infcx.tcx;
3505
3506 let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
3507
3508 if let Some(iter_trait) = tcx.get_diagnostic_item(sym::Iterator)
3510 && self
3511 .infcx
3512 .type_implements_trait(iter_trait, [return_ty], self.infcx.param_env)
3513 .must_apply_modulo_regions()
3514 {
3515 err.span_suggestion_hidden(
3516 return_span.shrink_to_hi(),
3517 "use `.collect()` to allocate the iterator",
3518 ".collect::<Vec<_>>()",
3519 Applicability::MaybeIncorrect,
3520 );
3521 }
3522
3523 if let Some(cow_did) = tcx.get_diagnostic_item(sym::Cow)
3524 && let ty::Adt(adt_def, _) = return_ty.kind()
3525 && adt_def.did() == cow_did
3526 {
3527 let typeck = tcx.typeck(self.mir_def_id());
3528 if let Some(expr) = self.find_expr(return_span)
3529 && let Some(def_id) = typeck.type_dependent_def_id(expr.hir_id)
3530 && tcx.is_diagnostic_item(sym::to_owned_method, def_id)
3531 && let Some(to_owned_ident) = expr.method_ident()
3532 {
3533 err.span_suggestion_short(
3534 to_owned_ident.span.shrink_to_lo(),
3535 "try using `.into_owned()` if you meant to convert a `Cow<'_, T>` to an owned `T`",
3536 "in",
3537 Applicability::MaybeIncorrect,
3538 );
3539 }
3540 }
3541 }
3542
3543 Err(err)
3544 }
3545
3546 #[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("report_escaping_closure_capture",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3546u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["use_span",
"var_span", "fr_name", "category", "constraint_span",
"captured_var", "scope"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&var_span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr_name)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&category)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constraint_span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&captured_var as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&scope as
&dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Diag<'infcx> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.infcx.tcx;
let args_span = use_span.args_or_use();
let (sugg_span, suggestion) =
match tcx.sess.source_map().span_to_snippet(args_span) {
Ok(string) => {
let coro_prefix =
if let Some(sub) = string.strip_prefix("async") {
let trimmed_sub = sub.trim_end();
if trimmed_sub.ends_with("gen") {
Some((trimmed_sub.len() + 5) as _)
} else { Some(5) }
} else if string.starts_with("gen") {
Some(3)
} else if string.starts_with("static") {
Some(6)
} else { None };
if let Some(n) = coro_prefix {
let pos = args_span.lo() + BytePos(n);
(args_span.with_lo(pos).with_hi(pos), " move")
} else { (args_span.shrink_to_lo(), "move ") }
}
Err(_) => (args_span, "move |<args>| <body>"),
};
let kind =
match use_span.coroutine_kind() {
Some(coroutine_kind) =>
match coroutine_kind {
CoroutineKind::Desugared(CoroutineDesugaring::Gen, kind) =>
match kind {
CoroutineSource::Block => "gen block",
CoroutineSource::Closure => "gen closure",
CoroutineSource::Fn => {
::rustc_middle::util::bug::bug_fmt(format_args!("gen block/closure expected, but gen function found."))
}
},
CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen,
kind) =>
match kind {
CoroutineSource::Block => "async gen block",
CoroutineSource::Closure => "async gen closure",
CoroutineSource::Fn => {
::rustc_middle::util::bug::bug_fmt(format_args!("gen block/closure expected, but gen function found."))
}
},
CoroutineKind::Desugared(CoroutineDesugaring::Async,
async_kind) => {
match async_kind {
CoroutineSource::Block => "async block",
CoroutineSource::Closure => "async closure",
CoroutineSource::Fn => {
::rustc_middle::util::bug::bug_fmt(format_args!("async block/closure expected, but async function found."))
}
}
}
CoroutineKind::Coroutine(_) => "coroutine",
},
None => "closure",
};
let mut err =
self.cannot_capture_in_long_lived_closure(args_span, kind,
captured_var, var_span, scope);
err.span_suggestion_verbose(sugg_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to force the {0} to take ownership of {1} (and any other referenced variables), use the `move` keyword",
kind, captured_var))
}), suggestion, Applicability::MachineApplicable);
match category {
ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType
=> {
let msg =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is returned here",
kind))
});
err.span_note(constraint_span, msg);
}
ConstraintCategory::CallArgument(_) => {
fr_name.highlight_region_name(&mut err);
if #[allow(non_exhaustive_omitted_patterns)] match use_span.coroutine_kind()
{
Some(CoroutineKind::Desugared(CoroutineDesugaring::Async,
_)) => true,
_ => false,
} {
err.note("async blocks are not executed immediately and must either take a \
reference or ownership of outside variables they use");
} else {
let msg =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} requires argument type to outlive `{1}`",
scope, fr_name))
});
err.span_note(constraint_span, msg);
}
}
_ =>
::rustc_middle::util::bug::bug_fmt(format_args!("report_escaping_closure_capture called with unexpected constraint category: `{0:?}`",
category)),
}
err
}
}
}#[instrument(level = "debug", skip(self))]
3547 fn report_escaping_closure_capture(
3548 &self,
3549 use_span: UseSpans<'tcx>,
3550 var_span: Span,
3551 fr_name: &RegionName,
3552 category: ConstraintCategory<'tcx>,
3553 constraint_span: Span,
3554 captured_var: &str,
3555 scope: &str,
3556 ) -> Diag<'infcx> {
3557 let tcx = self.infcx.tcx;
3558 let args_span = use_span.args_or_use();
3559
3560 let (sugg_span, suggestion) = match tcx.sess.source_map().span_to_snippet(args_span) {
3561 Ok(string) => {
3562 let coro_prefix = if let Some(sub) = string.strip_prefix("async") {
3563 let trimmed_sub = sub.trim_end();
3564 if trimmed_sub.ends_with("gen") {
3565 Some((trimmed_sub.len() + 5) as _)
3567 } else {
3568 Some(5)
3570 }
3571 } else if string.starts_with("gen") {
3572 Some(3)
3574 } else if string.starts_with("static") {
3575 Some(6)
3578 } else {
3579 None
3580 };
3581 if let Some(n) = coro_prefix {
3582 let pos = args_span.lo() + BytePos(n);
3583 (args_span.with_lo(pos).with_hi(pos), " move")
3584 } else {
3585 (args_span.shrink_to_lo(), "move ")
3586 }
3587 }
3588 Err(_) => (args_span, "move |<args>| <body>"),
3589 };
3590 let kind = match use_span.coroutine_kind() {
3591 Some(coroutine_kind) => match coroutine_kind {
3592 CoroutineKind::Desugared(CoroutineDesugaring::Gen, kind) => match kind {
3593 CoroutineSource::Block => "gen block",
3594 CoroutineSource::Closure => "gen closure",
3595 CoroutineSource::Fn => {
3596 bug!("gen block/closure expected, but gen function found.")
3597 }
3598 },
3599 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, kind) => match kind {
3600 CoroutineSource::Block => "async gen block",
3601 CoroutineSource::Closure => "async gen closure",
3602 CoroutineSource::Fn => {
3603 bug!("gen block/closure expected, but gen function found.")
3604 }
3605 },
3606 CoroutineKind::Desugared(CoroutineDesugaring::Async, async_kind) => {
3607 match async_kind {
3608 CoroutineSource::Block => "async block",
3609 CoroutineSource::Closure => "async closure",
3610 CoroutineSource::Fn => {
3611 bug!("async block/closure expected, but async function found.")
3612 }
3613 }
3614 }
3615 CoroutineKind::Coroutine(_) => "coroutine",
3616 },
3617 None => "closure",
3618 };
3619
3620 let mut err = self.cannot_capture_in_long_lived_closure(
3621 args_span,
3622 kind,
3623 captured_var,
3624 var_span,
3625 scope,
3626 );
3627 err.span_suggestion_verbose(
3628 sugg_span,
3629 format!(
3630 "to force the {kind} to take ownership of {captured_var} (and any \
3631 other referenced variables), use the `move` keyword"
3632 ),
3633 suggestion,
3634 Applicability::MachineApplicable,
3635 );
3636
3637 match category {
3638 ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
3639 let msg = format!("{kind} is returned here");
3640 err.span_note(constraint_span, msg);
3641 }
3642 ConstraintCategory::CallArgument(_) => {
3643 fr_name.highlight_region_name(&mut err);
3644 if matches!(
3645 use_span.coroutine_kind(),
3646 Some(CoroutineKind::Desugared(CoroutineDesugaring::Async, _))
3647 ) {
3648 err.note(
3649 "async blocks are not executed immediately and must either take a \
3650 reference or ownership of outside variables they use",
3651 );
3652 } else {
3653 let msg = format!("{scope} requires argument type to outlive `{fr_name}`");
3654 err.span_note(constraint_span, msg);
3655 }
3656 }
3657 _ => bug!(
3658 "report_escaping_closure_capture called with unexpected constraint \
3659 category: `{:?}`",
3660 category
3661 ),
3662 }
3663
3664 err
3665 }
3666
3667 fn report_escaping_data(
3668 &self,
3669 borrow_span: Span,
3670 name: &Option<String>,
3671 upvar_span: Span,
3672 upvar_name: Symbol,
3673 escape_span: Span,
3674 ) -> Diag<'infcx> {
3675 let tcx = self.infcx.tcx;
3676
3677 let escapes_from = tcx.def_descr(self.mir_def_id().to_def_id());
3678
3679 let mut err =
3680 borrowck_errors::borrowed_data_escapes_closure(tcx, escape_span, escapes_from);
3681
3682 err.span_label(
3683 upvar_span,
3684 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` declared here, outside of the {1} body",
upvar_name, escapes_from))
})format!("`{upvar_name}` declared here, outside of the {escapes_from} body"),
3685 );
3686
3687 err.span_label(borrow_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("borrow is only valid in the {0} body",
escapes_from))
})format!("borrow is only valid in the {escapes_from} body"));
3688
3689 if let Some(name) = name {
3690 err.span_label(
3691 escape_span,
3692 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("reference to `{0}` escapes the {1} body here",
name, escapes_from))
})format!("reference to `{name}` escapes the {escapes_from} body here"),
3693 );
3694 } else {
3695 err.span_label(escape_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("reference escapes the {0} body here",
escapes_from))
})format!("reference escapes the {escapes_from} body here"));
3696 }
3697
3698 err
3699 }
3700
3701 fn get_moved_indexes(
3702 &self,
3703 location: Location,
3704 mpi: MovePathIndex,
3705 ) -> (Vec<MoveSite>, Vec<Location>) {
3706 fn predecessor_locations<'tcx>(
3707 body: &mir::Body<'tcx>,
3708 location: Location,
3709 ) -> impl Iterator<Item = Location> {
3710 if location.statement_index == 0 {
3711 let predecessors = body.basic_blocks.predecessors()[location.block].to_vec();
3712 Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb)))
3713 } else {
3714 Either::Right(std::iter::once(Location {
3715 statement_index: location.statement_index - 1,
3716 ..location
3717 }))
3718 }
3719 }
3720
3721 let mut mpis = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[mpi]))vec![mpi];
3722 let move_paths = &self.move_data.move_paths;
3723 mpis.extend(move_paths[mpi].parents(move_paths).map(|(mpi, _)| mpi));
3724
3725 let mut stack = Vec::new();
3726 let mut back_edge_stack = Vec::new();
3727
3728 predecessor_locations(self.body, location).for_each(|predecessor| {
3729 if location.dominates(predecessor, self.dominators()) {
3730 back_edge_stack.push(predecessor)
3731 } else {
3732 stack.push(predecessor);
3733 }
3734 });
3735
3736 let mut reached_start = false;
3737
3738 let mut is_argument = false;
3740 for arg in self.body.args_iter() {
3741 if let Some(path) = self.move_data.rev_lookup.find_local(arg) {
3742 if mpis.contains(&path) {
3743 is_argument = true;
3744 }
3745 }
3746 }
3747
3748 let mut visited = FxIndexSet::default();
3749 let mut move_locations = FxIndexSet::default();
3750 let mut reinits = ::alloc::vec::Vec::new()vec![];
3751 let mut result = ::alloc::vec::Vec::new()vec![];
3752
3753 let mut dfs_iter = |result: &mut Vec<MoveSite>, location: Location, is_back_edge: bool| {
3754 {
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/diagnostics/conflict_errors.rs:3754",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3754u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized: (current_location={0:?}, back_edge={1})",
location, is_back_edge) as &dyn Value))])
});
} else { ; }
};debug!(
3755 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
3756 location, is_back_edge
3757 );
3758
3759 if !visited.insert(location) {
3760 return true;
3761 }
3762
3763 let stmt_kind =
3765 self.body[location.block].statements.get(location.statement_index).map(|s| &s.kind);
3766 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
3767 } else {
3771 for moi in &self.move_data.loc_map[location] {
3779 {
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/diagnostics/conflict_errors.rs:3779",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3779u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized: moi={0:?}",
moi) as &dyn Value))])
});
} else { ; }
};debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
3780 let path = self.move_data.moves[*moi].path;
3781 if mpis.contains(&path) {
3782 {
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/diagnostics/conflict_errors.rs:3782",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3782u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized: found {0:?}",
move_paths[path].place) as &dyn Value))])
});
} else { ; }
};debug!(
3783 "report_use_of_moved_or_uninitialized: found {:?}",
3784 move_paths[path].place
3785 );
3786 result.push(MoveSite { moi: *moi, traversed_back_edge: is_back_edge });
3787 move_locations.insert(location);
3788
3789 return true;
3806 }
3807 }
3808 }
3809
3810 let mut any_match = false;
3812 for ii in &self.move_data.init_loc_map[location] {
3813 let init = self.move_data.inits[*ii];
3814 match init.kind {
3815 InitKind::Deep | InitKind::NonPanicPathOnly => {
3816 if mpis.contains(&init.path) {
3817 any_match = true;
3818 }
3819 }
3820 InitKind::Shallow => {
3821 if mpi == init.path {
3822 any_match = true;
3823 }
3824 }
3825 }
3826 }
3827 if any_match {
3828 reinits.push(location);
3829 return true;
3830 }
3831 false
3832 };
3833
3834 while let Some(location) = stack.pop() {
3835 if dfs_iter(&mut result, location, false) {
3836 continue;
3837 }
3838
3839 let mut has_predecessor = false;
3840 predecessor_locations(self.body, location).for_each(|predecessor| {
3841 if location.dominates(predecessor, self.dominators()) {
3842 back_edge_stack.push(predecessor)
3843 } else {
3844 stack.push(predecessor);
3845 }
3846 has_predecessor = true;
3847 });
3848
3849 if !has_predecessor {
3850 reached_start = true;
3851 }
3852 }
3853 if (is_argument || !reached_start) && result.is_empty() {
3854 while let Some(location) = back_edge_stack.pop() {
3861 if dfs_iter(&mut result, location, true) {
3862 continue;
3863 }
3864
3865 predecessor_locations(self.body, location)
3866 .for_each(|predecessor| back_edge_stack.push(predecessor));
3867 }
3868 }
3869
3870 let reinits_reachable = reinits
3872 .into_iter()
3873 .filter(|reinit| {
3874 let mut visited = FxIndexSet::default();
3875 let mut stack = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[*reinit]))vec![*reinit];
3876 while let Some(location) = stack.pop() {
3877 if !visited.insert(location) {
3878 continue;
3879 }
3880 if move_locations.contains(&location) {
3881 return true;
3882 }
3883 stack.extend(predecessor_locations(self.body, location));
3884 }
3885 false
3886 })
3887 .collect::<Vec<Location>>();
3888 (result, reinits_reachable)
3889 }
3890
3891 pub(crate) fn report_illegal_mutation_of_borrowed(
3892 &mut self,
3893 location: Location,
3894 (place, span): (Place<'tcx>, Span),
3895 loan: &BorrowData<'tcx>,
3896 ) {
3897 let loan_spans = self.retrieve_borrow_spans(loan);
3898 let loan_span = loan_spans.args_or_use();
3899
3900 let descr_place = self.describe_any_place(place.as_ref());
3901 if let BorrowKind::Fake(_) = loan.kind
3902 && let Some(section) = self.classify_immutable_section(loan.assigned_place)
3903 {
3904 let mut err = self.cannot_mutate_in_immutable_section(
3905 span,
3906 loan_span,
3907 &descr_place,
3908 section,
3909 "assign",
3910 );
3911
3912 loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3913 use crate::session_diagnostics::CaptureVarCause::*;
3914 match kind {
3915 hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3916 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3917 BorrowUseInClosure { var_span }
3918 }
3919 }
3920 });
3921
3922 self.buffer_error(err);
3923
3924 return;
3925 }
3926
3927 let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place);
3928 self.note_due_to_edition_2024_opaque_capture_rules(loan, &mut err);
3929
3930 loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3931 use crate::session_diagnostics::CaptureVarCause::*;
3932 match kind {
3933 hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3934 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3935 BorrowUseInClosure { var_span }
3936 }
3937 }
3938 });
3939
3940 self.explain_why_borrow_contains_point(location, loan, None)
3941 .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3942
3943 self.explain_deref_coercion(loan, &mut err);
3944
3945 self.buffer_error(err);
3946 }
3947
3948 fn explain_deref_coercion(&mut self, loan: &BorrowData<'tcx>, err: &mut Diag<'_>) {
3949 let tcx = self.infcx.tcx;
3950 if let Some(Terminator { kind: TerminatorKind::Call { call_source, fn_span, .. }, .. }) =
3951 &self.body[loan.reserve_location.block].terminator
3952 && let Some((method_did, method_args)) = mir::find_self_call(
3953 tcx,
3954 self.body,
3955 loan.assigned_place.local,
3956 loan.reserve_location.block,
3957 )
3958 && let CallKind::DerefCoercion { deref_target_span, deref_target_ty, .. } = call_kind(
3959 self.infcx.tcx,
3960 self.infcx.typing_env(self.infcx.param_env),
3961 method_did,
3962 method_args,
3963 *fn_span,
3964 call_source.from_hir_call(),
3965 self.infcx.tcx.fn_arg_idents(method_did)[0],
3966 )
3967 {
3968 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("borrow occurs due to deref coercion to `{0}`",
deref_target_ty))
})format!("borrow occurs due to deref coercion to `{deref_target_ty}`"));
3969 if let Some(deref_target_span) = deref_target_span {
3970 err.span_note(deref_target_span, "deref defined here");
3971 }
3972 }
3973 }
3974
3975 pub(crate) fn report_illegal_reassignment(
3982 &mut self,
3983 (place, span): (Place<'tcx>, Span),
3984 assigned_span: Span,
3985 err_place: Place<'tcx>,
3986 ) {
3987 let (from_arg, local_decl) = match err_place.as_local() {
3988 Some(local) => {
3989 (self.body.local_kind(local) == LocalKind::Arg, Some(&self.body.local_decls[local]))
3990 }
3991 None => (false, None),
3992 };
3993
3994 let (place_description, assigned_span) = match local_decl {
3998 Some(LocalDecl {
3999 local_info:
4000 ClearCrossCrate::Set(
4001 LocalInfo::User(BindingForm::Var(VarBindingForm {
4002 opt_match_place: None,
4003 ..
4004 }))
4005 | LocalInfo::StaticRef { .. }
4006 | LocalInfo::Boring,
4007 ),
4008 ..
4009 })
4010 | None => (self.describe_any_place(place.as_ref()), assigned_span),
4011 Some(decl) => (self.describe_any_place(err_place.as_ref()), decl.source_info.span),
4012 };
4013 let mut err = self.cannot_reassign_immutable(span, &place_description, from_arg);
4014 let msg = if from_arg {
4015 "cannot assign to immutable argument"
4016 } else {
4017 "cannot assign twice to immutable variable"
4018 };
4019 if span != assigned_span && !from_arg {
4020 err.span_label(assigned_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("first assignment to {0}",
place_description))
})format!("first assignment to {place_description}"));
4021 }
4022 if let Some(decl) = local_decl
4023 && decl.can_be_made_mutable()
4024 {
4025 let mut is_for_loop = false;
4026 let mut is_immut_ref_pattern = false;
4027 if let LocalInfo::User(BindingForm::Var(VarBindingForm {
4028 opt_match_place: Some((_, match_span)),
4029 ..
4030 })) = *decl.local_info()
4031 {
4032 if #[allow(non_exhaustive_omitted_patterns)] match match_span.desugaring_kind() {
Some(DesugaringKind::ForLoop) => true,
_ => false,
}matches!(match_span.desugaring_kind(), Some(DesugaringKind::ForLoop)) {
4033 is_for_loop = true;
4034 }
4035
4036 if let Some(body) = self.infcx.tcx.hir_maybe_body_owned_by(self.mir_def_id()) {
4037 struct RefPatternFinder<'tcx> {
4038 tcx: TyCtxt<'tcx>,
4039 binding_span: Span,
4040 is_immut_ref_pattern: bool,
4041 }
4042
4043 impl<'tcx> Visitor<'tcx> for RefPatternFinder<'tcx> {
4044 type NestedFilter = OnlyBodies;
4045
4046 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
4047 self.tcx
4048 }
4049
4050 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
4051 if !self.is_immut_ref_pattern
4052 && let hir::PatKind::Binding(_, _, ident, _) = pat.kind
4053 && ident.span == self.binding_span
4054 && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.parent_hir_node(pat.hir_id)
{
hir::Node::Pat(hir::Pat {
kind: hir::PatKind::Ref(_, _, hir::Mutability::Not), .. }) => true,
_ => false,
}matches!(
4055 self.tcx.parent_hir_node(pat.hir_id),
4056 hir::Node::Pat(hir::Pat {
4057 kind: hir::PatKind::Ref(_, _, hir::Mutability::Not),
4058 ..
4059 })
4060 )
4061 {
4062 self.is_immut_ref_pattern = true;
4063 }
4064 hir::intravisit::walk_pat(self, pat);
4065 }
4066 }
4067
4068 let mut finder = RefPatternFinder {
4069 tcx: self.infcx.tcx,
4070 binding_span: decl.source_info.span,
4071 is_immut_ref_pattern: false,
4072 };
4073
4074 finder.visit_body(body);
4075 is_immut_ref_pattern = finder.is_immut_ref_pattern;
4076 }
4077 }
4078
4079 let (span, message) = if is_immut_ref_pattern
4080 && let Ok(binding_name) =
4081 self.infcx.tcx.sess.source_map().span_to_snippet(decl.source_info.span)
4082 {
4083 (decl.source_info.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("(mut {0})", binding_name))
})format!("(mut {})", binding_name))
4084 } else {
4085 (decl.source_info.span.shrink_to_lo(), "mut ".to_string())
4086 };
4087
4088 err.span_suggestion_verbose(
4089 span,
4090 "consider making this binding mutable",
4091 message,
4092 Applicability::MachineApplicable,
4093 );
4094
4095 if !from_arg
4096 && !is_for_loop
4097 && #[allow(non_exhaustive_omitted_patterns)] match decl.local_info() {
LocalInfo::User(BindingForm::Var(VarBindingForm {
opt_match_place: Some((Some(_), _)), .. })) => true,
_ => false,
}matches!(
4098 decl.local_info(),
4099 LocalInfo::User(BindingForm::Var(VarBindingForm {
4100 opt_match_place: Some((Some(_), _)),
4101 ..
4102 }))
4103 )
4104 {
4105 err.span_suggestion_verbose(
4106 decl.source_info.span.shrink_to_lo(),
4107 "to modify the original value, take a borrow instead",
4108 "ref mut ".to_string(),
4109 Applicability::MaybeIncorrect,
4110 );
4111 }
4112 }
4113 err.span_label(span, msg);
4114 self.buffer_error(err);
4115 }
4116
4117 fn classify_drop_access_kind(&self, place: PlaceRef<'tcx>) -> StorageDeadOrDrop<'tcx> {
4118 let tcx = self.infcx.tcx;
4119 let (kind, _place_ty) = place.projection.iter().fold(
4120 (LocalStorageDead, PlaceTy::from_ty(self.body.local_decls[place.local].ty)),
4121 |(kind, place_ty), &elem| {
4122 (
4123 match elem {
4124 ProjectionElem::Deref => match kind {
4125 StorageDeadOrDrop::LocalStorageDead
4126 | StorageDeadOrDrop::BoxedStorageDead => {
4127 if !place_ty.ty.is_box() {
{
::core::panicking::panic_fmt(format_args!("Drop of value behind a reference or raw pointer"));
}
};assert!(
4128 place_ty.ty.is_box(),
4129 "Drop of value behind a reference or raw pointer"
4130 );
4131 StorageDeadOrDrop::BoxedStorageDead
4132 }
4133 StorageDeadOrDrop::Destructor(_) => kind,
4134 },
4135 ProjectionElem::OpaqueCast { .. }
4136 | ProjectionElem::Field(..)
4137 | ProjectionElem::Downcast(..) => {
4138 match place_ty.ty.kind() {
4139 ty::Adt(def, _) if def.has_dtor(tcx) => {
4140 match kind {
4142 StorageDeadOrDrop::Destructor(_) => kind,
4143 StorageDeadOrDrop::LocalStorageDead
4144 | StorageDeadOrDrop::BoxedStorageDead => {
4145 StorageDeadOrDrop::Destructor(place_ty.ty)
4146 }
4147 }
4148 }
4149 _ => kind,
4150 }
4151 }
4152 ProjectionElem::ConstantIndex { .. }
4153 | ProjectionElem::Subslice { .. }
4154 | ProjectionElem::Index(_)
4155 | ProjectionElem::UnwrapUnsafeBinder(_) => kind,
4156 },
4157 place_ty.projection_ty(tcx, elem),
4158 )
4159 },
4160 );
4161 kind
4162 }
4163
4164 fn classify_immutable_section(&self, place: Place<'tcx>) -> Option<&'static str> {
4166 use rustc_middle::mir::visit::Visitor;
4167 struct FakeReadCauseFinder<'tcx> {
4168 place: Place<'tcx>,
4169 cause: Option<FakeReadCause>,
4170 }
4171 impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'tcx> {
4172 fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
4173 match statement {
4174 Statement { kind: StatementKind::FakeRead((cause, place)), .. }
4175 if *place == self.place =>
4176 {
4177 self.cause = Some(*cause);
4178 }
4179 _ => (),
4180 }
4181 }
4182 }
4183 let mut visitor = FakeReadCauseFinder { place, cause: None };
4184 visitor.visit_body(self.body);
4185 match visitor.cause {
4186 Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
4187 Some(FakeReadCause::ForIndex) => Some("indexing expression"),
4188 _ => None,
4189 }
4190 }
4191
4192 fn annotate_argument_and_return_for_borrow(
4195 &self,
4196 borrow: &BorrowData<'tcx>,
4197 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4198 let fallback = || {
4200 let is_closure = self.infcx.tcx.is_closure_like(self.mir_def_id().to_def_id());
4201 if is_closure {
4202 None
4203 } else {
4204 let ty = self
4205 .infcx
4206 .tcx
4207 .type_of(self.mir_def_id())
4208 .instantiate_identity()
4209 .skip_norm_wip();
4210 match ty.kind() {
4211 ty::FnDef(_, _) | ty::FnPtr(..) => self.annotate_fn_sig(
4212 self.mir_def_id(),
4213 self.infcx
4214 .tcx
4215 .fn_sig(self.mir_def_id())
4216 .instantiate_identity()
4217 .skip_norm_wip(),
4218 ),
4219 _ => None,
4220 }
4221 }
4222 };
4223
4224 let location = borrow.reserve_location;
4231 {
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/diagnostics/conflict_errors.rs:4231",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4231u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: location={0:?}",
location) as &dyn Value))])
});
} else { ; }
};debug!("annotate_argument_and_return_for_borrow: location={:?}", location);
4232 if let Some(Statement { kind: StatementKind::Assign((reservation, _)), .. }) =
4233 &self.body[location.block].statements.get(location.statement_index)
4234 {
4235 {
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/diagnostics/conflict_errors.rs:4235",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4235u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: reservation={0:?}",
reservation) as &dyn Value))])
});
} else { ; }
};debug!("annotate_argument_and_return_for_borrow: reservation={:?}", reservation);
4236 let mut target = match reservation.as_local() {
4238 Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
4239 _ => return None,
4240 };
4241
4242 let mut annotated_closure = None;
4245 for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
4246 {
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/diagnostics/conflict_errors.rs:4246",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4246u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: target={0:?} stmt={1:?}",
target, stmt) as &dyn Value))])
});
} else { ; }
};debug!(
4247 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
4248 target, stmt
4249 );
4250 if let StatementKind::Assign((place, rvalue)) = &stmt.kind
4251 && let Some(assigned_to) = place.as_local()
4252 {
4253 {
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/diagnostics/conflict_errors.rs:4253",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4253u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_to={0:?} rvalue={1:?}",
assigned_to, rvalue) as &dyn Value))])
});
} else { ; }
};debug!(
4254 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
4255 rvalue={:?}",
4256 assigned_to, rvalue
4257 );
4258 if let Rvalue::Aggregate(AggregateKind::Closure(def_id, args), operands) =
4260 rvalue
4261 {
4262 let def_id = def_id.expect_local();
4263 for operand in operands {
4264 let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4265 operand
4266 else {
4267 continue;
4268 };
4269 {
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/diagnostics/conflict_errors.rs:4269",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4269u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_from={0:?}",
assigned_from) as &dyn Value))])
});
} else { ; }
};debug!(
4270 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4271 assigned_from
4272 );
4273
4274 let Some(assigned_from_local) = assigned_from.local_or_deref_local()
4276 else {
4277 continue;
4278 };
4279
4280 if assigned_from_local != target {
4281 continue;
4282 }
4283
4284 annotated_closure =
4288 self.annotate_fn_sig(def_id, args.as_closure().sig());
4289 {
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/diagnostics/conflict_errors.rs:4289",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4289u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: annotated_closure={0:?} assigned_from_local={1:?} assigned_to={2:?}",
annotated_closure, assigned_from_local, assigned_to) as
&dyn Value))])
});
} else { ; }
};debug!(
4290 "annotate_argument_and_return_for_borrow: \
4291 annotated_closure={:?} assigned_from_local={:?} \
4292 assigned_to={:?}",
4293 annotated_closure, assigned_from_local, assigned_to
4294 );
4295
4296 if assigned_to == mir::RETURN_PLACE {
4297 return annotated_closure;
4300 } else {
4301 target = assigned_to;
4303 }
4304 }
4305
4306 continue;
4309 }
4310
4311 let assigned_from = match rvalue {
4313 Rvalue::Ref(_, _, assigned_from) => assigned_from,
4314 Rvalue::Use(operand, _) => match operand {
4315 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
4316 assigned_from
4317 }
4318 _ => continue,
4319 },
4320 _ => continue,
4321 };
4322 {
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/diagnostics/conflict_errors.rs:4322",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4322u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_from={0:?}",
assigned_from) as &dyn Value))])
});
} else { ; }
};debug!(
4323 "annotate_argument_and_return_for_borrow: \
4324 assigned_from={:?}",
4325 assigned_from,
4326 );
4327
4328 let Some(assigned_from_local) = assigned_from.local_or_deref_local() else {
4330 continue;
4331 };
4332 {
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/diagnostics/conflict_errors.rs:4332",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4332u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_from_local={0:?}",
assigned_from_local) as &dyn Value))])
});
} else { ; }
};debug!(
4333 "annotate_argument_and_return_for_borrow: \
4334 assigned_from_local={:?}",
4335 assigned_from_local,
4336 );
4337
4338 if assigned_from_local != target {
4341 continue;
4342 }
4343
4344 {
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/diagnostics/conflict_errors.rs:4346",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4346u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_from_local={0:?} assigned_to={1:?}",
assigned_from_local, assigned_to) as &dyn Value))])
});
} else { ; }
};debug!(
4347 "annotate_argument_and_return_for_borrow: \
4348 assigned_from_local={:?} assigned_to={:?}",
4349 assigned_from_local, assigned_to
4350 );
4351 if assigned_to == mir::RETURN_PLACE {
4352 return annotated_closure.or_else(fallback);
4355 }
4356
4357 target = assigned_to;
4360 }
4361 }
4362
4363 let terminator = &self.body[location.block].terminator();
4365 {
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/diagnostics/conflict_errors.rs:4365",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4365u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: target={0:?} terminator={1:?}",
target, terminator) as &dyn Value))])
});
} else { ; }
};debug!(
4366 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
4367 target, terminator
4368 );
4369 if let TerminatorKind::Call { destination, target: Some(_), args, .. } =
4370 &terminator.kind
4371 && let Some(assigned_to) = destination.as_local()
4372 {
4373 {
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/diagnostics/conflict_errors.rs:4373",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4373u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_to={0:?} args={1:?}",
assigned_to, args) as &dyn Value))])
});
} else { ; }
};debug!(
4374 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
4375 assigned_to, args
4376 );
4377 for operand in args {
4378 let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4379 &operand.node
4380 else {
4381 continue;
4382 };
4383 {
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/diagnostics/conflict_errors.rs:4383",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4383u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_from={0:?}",
assigned_from) as &dyn Value))])
});
} else { ; }
};debug!(
4384 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4385 assigned_from,
4386 );
4387
4388 if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
4389 {
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/diagnostics/conflict_errors.rs:4389",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4389u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_from_local={0:?}",
assigned_from_local) as &dyn Value))])
});
} else { ; }
};debug!(
4390 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
4391 assigned_from_local,
4392 );
4393
4394 if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
4395 return annotated_closure.or_else(fallback);
4396 }
4397 }
4398 }
4399 }
4400 }
4401
4402 {
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/diagnostics/conflict_errors.rs:4404",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4404u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: none found")
as &dyn Value))])
});
} else { ; }
};debug!("annotate_argument_and_return_for_borrow: none found");
4405 None
4406 }
4407
4408 fn annotate_fn_sig(
4411 &self,
4412 did: LocalDefId,
4413 sig: ty::PolyFnSig<'tcx>,
4414 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4415 {
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/diagnostics/conflict_errors.rs:4415",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4415u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_fn_sig: did={0:?} sig={1:?}",
did, sig) as &dyn Value))])
});
} else { ; }
};debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
4416 let is_closure = self.infcx.tcx.is_closure_like(did.to_def_id());
4417 let fn_hir_id = self.infcx.tcx.local_def_id_to_hir_id(did);
4418 let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(fn_hir_id)?;
4419
4420 let return_ty = sig.output();
4443 match return_ty.skip_binder().kind() {
4444 ty::Ref(return_region, _, _)
4445 if return_region.is_named(self.infcx.tcx) && !is_closure =>
4446 {
4447 let mut arguments = Vec::new();
4450 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
4451 if let ty::Ref(argument_region, _, _) = argument.kind()
4452 && argument_region == return_region
4453 {
4454 match &fn_decl.inputs[index].kind {
4458 hir::TyKind::Ref(lifetime, _) => {
4459 arguments.push((*argument, lifetime.ident.span));
4462 }
4463 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
4465 if let Res::SelfTyAlias { alias_to, .. } = path.res
4466 && let Some(alias_to) = alias_to.as_local()
4467 && let hir::Impl { self_ty, .. } = self
4468 .infcx
4469 .tcx
4470 .hir_node_by_def_id(alias_to)
4471 .expect_item()
4472 .expect_impl()
4473 && let hir::TyKind::Ref(lifetime, _) = self_ty.kind
4474 {
4475 arguments.push((*argument, lifetime.ident.span));
4476 }
4477 }
4478 _ => {
4479 }
4481 }
4482 }
4483 }
4484
4485 if arguments.is_empty() {
4487 return None;
4488 }
4489
4490 let return_ty = sig.output().skip_binder();
4493 let mut return_span = fn_decl.output.span();
4494 if let hir::FnRetTy::Return(ty) = &fn_decl.output
4495 && let hir::TyKind::Ref(lifetime, _) = ty.kind
4496 {
4497 return_span = lifetime.ident.span;
4498 }
4499
4500 Some(AnnotatedBorrowFnSignature::NamedFunction {
4501 arguments,
4502 return_ty,
4503 return_span,
4504 })
4505 }
4506 ty::Ref(_, _, _) if is_closure => {
4507 let argument_span = fn_decl.inputs.first()?.span;
4511 let argument_ty = sig.inputs().skip_binder().first()?;
4512
4513 if let ty::Tuple(elems) = argument_ty.kind() {
4516 let &argument_ty = elems.first()?;
4517 if let ty::Ref(_, _, _) = argument_ty.kind() {
4518 return Some(AnnotatedBorrowFnSignature::Closure {
4519 argument_ty,
4520 argument_span,
4521 });
4522 }
4523 }
4524
4525 None
4526 }
4527 ty::Ref(_, _, _) => {
4528 let argument_span = fn_decl.inputs.first()?.span;
4531 let argument_ty = *sig.inputs().skip_binder().first()?;
4532
4533 let return_span = fn_decl.output.span();
4534 let return_ty = sig.output().skip_binder();
4535
4536 match argument_ty.kind() {
4538 ty::Ref(_, _, _) => {}
4539 _ => return None,
4540 }
4541
4542 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
4543 argument_ty,
4544 argument_span,
4545 return_ty,
4546 return_span,
4547 })
4548 }
4549 _ => {
4550 None
4553 }
4554 }
4555 }
4556}
4557
4558#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for AnnotatedBorrowFnSignature<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
AnnotatedBorrowFnSignature::NamedFunction {
arguments: __self_0,
return_ty: __self_1,
return_span: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"NamedFunction", "arguments", __self_0, "return_ty",
__self_1, "return_span", &__self_2),
AnnotatedBorrowFnSignature::AnonymousFunction {
argument_ty: __self_0,
argument_span: __self_1,
return_ty: __self_2,
return_span: __self_3 } =>
::core::fmt::Formatter::debug_struct_field4_finish(f,
"AnonymousFunction", "argument_ty", __self_0,
"argument_span", __self_1, "return_ty", __self_2,
"return_span", &__self_3),
AnnotatedBorrowFnSignature::Closure {
argument_ty: __self_0, argument_span: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Closure", "argument_ty", __self_0, "argument_span",
&__self_1),
}
}
}Debug)]
4559enum AnnotatedBorrowFnSignature<'tcx> {
4560 NamedFunction {
4561 arguments: Vec<(Ty<'tcx>, Span)>,
4562 return_ty: Ty<'tcx>,
4563 return_span: Span,
4564 },
4565 AnonymousFunction {
4566 argument_ty: Ty<'tcx>,
4567 argument_span: Span,
4568 return_ty: Ty<'tcx>,
4569 return_span: Span,
4570 },
4571 Closure {
4572 argument_ty: Ty<'tcx>,
4573 argument_span: Span,
4574 },
4575}
4576
4577impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
4578 pub(crate) fn emit(&self, cx: &MirBorrowckCtxt<'_, '_, 'tcx>, diag: &mut Diag<'_>) -> String {
4581 match self {
4582 &AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
4583 diag.span_label(
4584 argument_span,
4585 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("has type `{0}`",
cx.get_name_for_ty(argument_ty, 0)))
})format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
4586 );
4587
4588 cx.get_region_name_for_ty(argument_ty, 0)
4589 }
4590 &AnnotatedBorrowFnSignature::AnonymousFunction {
4591 argument_ty,
4592 argument_span,
4593 return_ty,
4594 return_span,
4595 } => {
4596 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
4597 diag.span_label(argument_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("has type `{0}`", argument_ty_name))
})format!("has type `{argument_ty_name}`"));
4598
4599 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
4600 let types_equal = return_ty_name == argument_ty_name;
4601 diag.span_label(
4602 return_span,
4603 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}has type `{1}`",
if types_equal { "also " } else { "" }, return_ty_name))
})format!(
4604 "{}has type `{}`",
4605 if types_equal { "also " } else { "" },
4606 return_ty_name,
4607 ),
4608 );
4609
4610 diag.note(
4611 "argument and return type have the same lifetime due to lifetime elision rules",
4612 );
4613 diag.note(
4614 "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
4615 lifetime-syntax.html#lifetime-elision>",
4616 );
4617
4618 cx.get_region_name_for_ty(return_ty, 0)
4619 }
4620 AnnotatedBorrowFnSignature::NamedFunction { arguments, return_ty, return_span } => {
4621 let region_name = cx.get_region_name_for_ty(*return_ty, 0);
4623 for (_, argument_span) in arguments {
4624 diag.span_label(*argument_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("has lifetime `{0}`", region_name))
})format!("has lifetime `{region_name}`"));
4625 }
4626
4627 diag.span_label(*return_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("also has lifetime `{0}`",
region_name))
})format!("also has lifetime `{region_name}`",));
4628
4629 diag.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use data from the highlighted arguments which match the `{0}` lifetime of the return type",
region_name))
})format!(
4630 "use data from the highlighted arguments which match the `{region_name}` lifetime of \
4631 the return type",
4632 ));
4633
4634 region_name
4635 }
4636 }
4637 }
4638}
4639
4640struct ReferencedStatementsVisitor<'a>(&'a [Span]);
4642
4643impl<'v> Visitor<'v> for ReferencedStatementsVisitor<'_> {
4644 type Result = ControlFlow<()>;
4645 fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) -> Self::Result {
4646 match s.kind {
4647 hir::StmtKind::Semi(expr) if self.0.contains(&expr.span) => ControlFlow::Break(()),
4648 _ => ControlFlow::Continue(()),
4649 }
4650 }
4651}
4652
4653struct BreakFinder {
4657 found_breaks: Vec<(hir::Destination, Span)>,
4658 found_continues: Vec<(hir::Destination, Span)>,
4659}
4660impl<'hir> Visitor<'hir> for BreakFinder {
4661 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
4662 match ex.kind {
4663 hir::ExprKind::Break(destination, _)
4664 if !ex.span.is_desugaring(DesugaringKind::ForLoop) =>
4665 {
4666 self.found_breaks.push((destination, ex.span));
4667 }
4668 hir::ExprKind::Continue(destination) => {
4669 self.found_continues.push((destination, ex.span));
4670 }
4671 _ => {}
4672 }
4673 hir::intravisit::walk_expr(self, ex);
4674 }
4675}
4676
4677struct ConditionVisitor<'tcx> {
4680 tcx: TyCtxt<'tcx>,
4681 spans: Vec<Span>,
4682 name: String,
4683 errors: Vec<(Span, String)>,
4684}
4685
4686impl<'v, 'tcx> Visitor<'v> for ConditionVisitor<'tcx> {
4687 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
4688 match ex.kind {
4689 hir::ExprKind::If(cond, body, None) => {
4690 if ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break() {
4693 self.errors.push((
4694 cond.span,
4695 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this `if` condition is `false`, {0} is not initialized",
self.name))
})format!(
4696 "if this `if` condition is `false`, {} is not initialized",
4697 self.name,
4698 ),
4699 ));
4700 self.errors.push((
4701 ex.span.shrink_to_hi(),
4702 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("an `else` arm might be missing here, initializing {0}",
self.name))
})format!("an `else` arm might be missing here, initializing {}", self.name),
4703 ));
4704 }
4705 }
4706 hir::ExprKind::If(cond, body, Some(other)) => {
4707 let a = ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break();
4710 let b = ReferencedStatementsVisitor(&self.spans).visit_expr(other).is_break();
4711 match (a, b) {
4712 (true, true) | (false, false) => {}
4713 (true, false) => {
4714 if other.span.is_desugaring(DesugaringKind::WhileLoop) {
4715 self.errors.push((
4716 cond.span,
4717 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this condition isn\'t met and the `while` loop runs 0 times, {0} is not initialized",
self.name))
})format!(
4718 "if this condition isn't met and the `while` loop runs 0 \
4719 times, {} is not initialized",
4720 self.name
4721 ),
4722 ));
4723 } else {
4724 self.errors.push((
4725 body.span.shrink_to_hi().until(other.span),
4726 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if the `if` condition is `false` and this `else` arm is executed, {0} is not initialized",
self.name))
})format!(
4727 "if the `if` condition is `false` and this `else` arm is \
4728 executed, {} is not initialized",
4729 self.name
4730 ),
4731 ));
4732 }
4733 }
4734 (false, true) => {
4735 self.errors.push((
4736 cond.span,
4737 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this condition is `true`, {0} is not initialized",
self.name))
})format!(
4738 "if this condition is `true`, {} is not initialized",
4739 self.name
4740 ),
4741 ));
4742 }
4743 }
4744 }
4745 hir::ExprKind::Match(e, arms, loop_desugar) => {
4746 let results: Vec<bool> = arms
4749 .iter()
4750 .map(|arm| ReferencedStatementsVisitor(&self.spans).visit_arm(arm).is_break())
4751 .collect();
4752 if results.iter().any(|x| *x) && !results.iter().all(|x| *x) {
4753 for (arm, seen) in arms.iter().zip(results) {
4754 if !seen {
4755 if loop_desugar == hir::MatchSource::ForLoopDesugar {
4756 self.errors.push((
4757 e.span,
4758 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if the `for` loop runs 0 times, {0} is not initialized",
self.name))
})format!(
4759 "if the `for` loop runs 0 times, {} is not initialized",
4760 self.name
4761 ),
4762 ));
4763 } else if let Some(guard) = &arm.guard {
4764 if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.hir_node(arm.body.hir_id)
{
hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. }) => true,
_ => false,
}matches!(
4765 self.tcx.hir_node(arm.body.hir_id),
4766 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4767 ) {
4768 continue;
4769 }
4770 self.errors.push((
4771 arm.pat.span.to(guard.span),
4772 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this pattern and condition are matched, {0} is not initialized",
self.name))
})format!(
4773 "if this pattern and condition are matched, {} is not \
4774 initialized",
4775 self.name
4776 ),
4777 ));
4778 } else {
4779 if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.hir_node(arm.body.hir_id)
{
hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. }) => true,
_ => false,
}matches!(
4780 self.tcx.hir_node(arm.body.hir_id),
4781 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4782 ) {
4783 continue;
4784 }
4785 self.errors.push((
4786 arm.pat.span,
4787 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this pattern is matched, {0} is not initialized",
self.name))
})format!(
4788 "if this pattern is matched, {} is not initialized",
4789 self.name
4790 ),
4791 ));
4792 }
4793 }
4794 }
4795 }
4796 }
4797 _ => {}
4802 }
4803 walk_expr(self, ex);
4804 }
4805}