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