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) -> StorageDeadOrDrop<'tcx> {
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: &StorageDeadOrDrop<'tcx>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(StorageDeadOrDrop::Destructor(__self_0),
StorageDeadOrDrop::Destructor(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for StorageDeadOrDrop<'tcx> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
}
}Eq, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for StorageDeadOrDrop<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
StorageDeadOrDrop::LocalStorageDead =>
::core::fmt::Formatter::write_str(f, "LocalStorageDead"),
StorageDeadOrDrop::BoxedStorageDead =>
::core::fmt::Formatter::write_str(f, "BoxedStorageDead"),
StorageDeadOrDrop::Destructor(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Destructor", &__self_0),
}
}
}Debug)]
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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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_label(sm.guess_head_span(span), "");
1205 }
1206
1207 err.span_note(spans, "verify that your loop breaking logic is correct");
1219 }
1220 if let Some(parent) = parent
1221 && let hir::ExprKind::MethodCall(..) | hir::ExprKind::Call(..) = parent.kind
1222 {
1223 let span = in_loop.span;
1228 if !finder.found_breaks.is_empty()
1229 && let Ok(value) = sm.span_to_snippet(parent.span)
1230 {
1231 let indent = if let Some(indent) = sm.indentation_before(span) {
1234 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}", indent))
})format!("\n{indent}")
1235 } else {
1236 " ".to_string()
1237 };
1238 err.multipart_suggestion(
1239 "consider moving the expression out of the loop so it is only moved once",
1240 ::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![
1241 (span.shrink_to_lo(), format!("let mut value = {value};{indent}")),
1242 (parent.span, "value".to_string()),
1243 ],
1244 Applicability::MaybeIncorrect,
1245 );
1246 }
1247 }
1248 }
1249 can_suggest_clone
1250 }
1251
1252 fn suggest_cloning_on_functional_record_update(
1255 &self,
1256 err: &mut Diag<'_>,
1257 ty: Ty<'tcx>,
1258 expr: &hir::Expr<'_>,
1259 ) {
1260 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1261 let hir::ExprKind::Struct(struct_qpath, fields, hir::StructTailExpr::Base(base)) =
1262 expr.kind
1263 else {
1264 return;
1265 };
1266 let hir::QPath::Resolved(_, path) = struct_qpath else { return };
1267 let hir::def::Res::Def(_, def_id) = path.res else { return };
1268 let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id) else { return };
1269 let ty::Adt(def, args) = expr_ty.kind() else { return };
1270 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = base.kind else { return };
1271 let (hir::def::Res::Local(_)
1272 | hir::def::Res::Def(
1273 DefKind::Const | DefKind::ConstParam | DefKind::Static { .. } | DefKind::AssocConst,
1274 _,
1275 )) = path.res
1276 else {
1277 return;
1278 };
1279 let Ok(base_str) = self.infcx.tcx.sess.source_map().span_to_snippet(base.span) else {
1280 return;
1281 };
1282
1283 let mut final_field_count = fields.len();
1289 let Some(variant) = def.variants().iter().find(|variant| variant.def_id == def_id) else {
1290 return;
1293 };
1294 let mut sugg = ::alloc::vec::Vec::new()vec![];
1295 for field in &variant.fields {
1296 let field_ty = field.ty(self.infcx.tcx, args).skip_norm_wip();
1300 let ident = field.ident(self.infcx.tcx);
1301 if field_ty == ty && fields.iter().all(|field| field.ident.name != ident.name) {
1302 sugg.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}.{0}.clone()", ident,
base_str))
})format!("{ident}: {base_str}.{ident}.clone()"));
1304 final_field_count += 1;
1305 }
1306 }
1307 let (span, sugg) = match fields {
1308 [.., last] => (
1309 if final_field_count == variant.fields.len() {
1310 last.span.shrink_to_hi().with_hi(base.span.hi())
1312 } else {
1313 last.span.shrink_to_hi()
1314 },
1315 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", sugg.join(", ")))
})format!(", {}", sugg.join(", ")),
1316 ),
1317 [] => (
1319 expr.span.with_lo(struct_qpath.span().hi()),
1320 if final_field_count == variant.fields.len() {
1321 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{ {0} }}", sugg.join(", ")))
})format!(" {{ {} }}", sugg.join(", "))
1323 } else {
1324 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{ {0}, ..{1} }}",
sugg.join(", "), base_str))
})format!(" {{ {}, ..{base_str} }}", sugg.join(", "))
1325 },
1326 ),
1327 };
1328 let prefix = if !self.implements_clone(ty) {
1329 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`");
1330 if let ty::Adt(def, _) = ty.kind() {
1331 err.span_note(self.infcx.tcx.def_span(def.did()), msg);
1332 } else {
1333 err.note(msg);
1334 }
1335 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if `{0}` implemented `Clone`, you could ",
ty))
})format!("if `{ty}` implemented `Clone`, you could ")
1336 } else {
1337 String::new()
1338 };
1339 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!(
1340 "{prefix}clone the value from the field instead of using the functional record update \
1341 syntax",
1342 );
1343 err.span_suggestion_verbose(span, msg, sugg, Applicability::MachineApplicable);
1344 }
1345
1346 pub(crate) fn suggest_cloning(
1347 &self,
1348 err: &mut Diag<'_>,
1349 place: PlaceRef<'tcx>,
1350 ty: Ty<'tcx>,
1351 expr: &'tcx hir::Expr<'tcx>,
1352 use_spans: Option<UseSpans<'tcx>>,
1353 ) {
1354 if let hir::ExprKind::Struct(_, _, hir::StructTailExpr::Base(_)) = expr.kind {
1355 self.suggest_cloning_on_functional_record_update(err, ty, expr);
1360 return;
1361 }
1362
1363 if self.implements_clone(ty) {
1364 if self.in_move_closure(expr) {
1365 if let Some(name) = self.describe_place(place) {
1366 self.suggest_clone_of_captured_var_in_move_closure(err, &name, use_spans);
1367 }
1368 } else {
1369 self.suggest_cloning_inner(err, ty, expr);
1370 }
1371 } else if let ty::Adt(def, args) = ty.kind()
1372 && let Some(local_did) = def.did().as_local()
1373 && def.variants().iter().all(|variant| {
1374 variant.fields.iter().all(|field| {
1375 self.implements_clone(field.ty(self.infcx.tcx, args).skip_norm_wip())
1376 })
1377 })
1378 {
1379 let ty_span = self.infcx.tcx.def_span(def.did());
1380 let mut span: MultiSpan = ty_span.into();
1381 let mut derive_clone = false;
1382 self.infcx.tcx.for_each_relevant_impl(
1383 self.infcx.tcx.lang_items().clone_trait().unwrap(),
1384 ty,
1385 |def_id| {
1386 if self.infcx.tcx.is_automatically_derived(def_id) {
1387 derive_clone = true;
1388 span.push_span_label(
1389 self.infcx.tcx.def_span(def_id),
1390 "derived `Clone` adds implicit bounds on type parameters",
1391 );
1392 if let Some(generics) = self.infcx.tcx.hir_get_generics(local_did) {
1393 for param in generics.params {
1394 if let hir::GenericParamKind::Type { .. } = param.kind {
1395 span.push_span_label(
1396 param.span,
1397 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("introduces an implicit `{0}: Clone` bound",
param.name.ident()))
})format!(
1398 "introduces an implicit `{}: Clone` bound",
1399 param.name.ident()
1400 ),
1401 );
1402 }
1403 }
1404 }
1405 }
1406 },
1407 );
1408 let msg = if !derive_clone {
1409 span.push_span_label(
1410 ty_span,
1411 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider {0}implementing `Clone` for this type",
if derive_clone { "manually " } else { "" }))
})format!(
1412 "consider {}implementing `Clone` for this type",
1413 if derive_clone { "manually " } else { "" }
1414 ),
1415 );
1416 ::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")
1417 } else {
1418 ::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")
1419 };
1420 span.push_span_label(expr.span, "you could clone this value");
1421 err.span_note(span, msg);
1422 if derive_clone {
1423 err.help("consider manually implementing `Clone` to avoid undesired bounds");
1424 }
1425 } else if let ty::Param(param) = ty.kind()
1426 && let Some(_clone_trait_def) = self.infcx.tcx.lang_items().clone_trait()
1427 && let generics = self.infcx.tcx.generics_of(self.mir_def_id())
1428 && let generic_param = generics.type_param(*param, self.infcx.tcx)
1429 && let param_span = self.infcx.tcx.def_span(generic_param.def_id)
1430 && if let Some(UseSpans::FnSelfUse { kind, .. }) = use_spans
1431 && let CallKind::FnCall { fn_trait_id, self_ty } = kind
1432 && let ty::Param(_) = self_ty.kind()
1433 && ty == self_ty
1434 && self.infcx.tcx.fn_trait_kind_from_def_id(fn_trait_id).is_some()
1435 {
1436 false
1438 } else {
1439 true
1440 }
1441 {
1442 let mut span: MultiSpan = param_span.into();
1443 span.push_span_label(
1444 param_span,
1445 "consider constraining this type parameter with `Clone`",
1446 );
1447 span.push_span_label(expr.span, "you could clone this value");
1448 err.span_help(
1449 span,
1450 ::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"),
1451 );
1452 } else if let ty::Adt(_, _) = ty.kind()
1453 && let Some(clone_trait) = self.infcx.tcx.lang_items().clone_trait()
1454 {
1455 let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1458 let cause = ObligationCause::misc(expr.span, self.mir_def_id());
1459 ocx.register_bound(cause, self.infcx.param_env, ty, clone_trait);
1460 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1461 if let TraitErrors::HasErrors(errors) = errors
1462 && errors.iter().all(|error| {
1463 match error.obligation.predicate.as_clause().and_then(|c| c.as_trait_clause()) {
1464 Some(clause) => match clause.self_ty().skip_binder().kind() {
1465 ty::Adt(def, _) => {
1466 def.did().is_local() && clause.def_id() == clone_trait
1467 }
1468 _ => false,
1469 },
1470 None => false,
1471 }
1472 })
1473 {
1474 let mut type_spans = ::alloc::vec::Vec::new()vec![];
1475 let mut types = FxIndexSet::default();
1476 for clause in errors
1477 .iter()
1478 .filter_map(|e| e.obligation.predicate.as_clause())
1479 .filter_map(|c| c.as_trait_clause())
1480 {
1481 let ty::Adt(def, _) = clause.self_ty().skip_binder().kind() else { continue };
1482 type_spans.push(self.infcx.tcx.def_span(def.did()));
1483 types.insert(
1484 self.infcx
1485 .tcx
1486 .short_string(clause.self_ty().skip_binder(), &mut err.long_ty_path()),
1487 );
1488 }
1489 let mut span: MultiSpan = type_spans.clone().into();
1490 for sp in type_spans {
1491 span.push_span_label(sp, "consider implementing `Clone` for this type");
1492 }
1493 span.push_span_label(expr.span, "you could clone this value");
1494 let types: Vec<_> = types.into_iter().collect();
1495 let msg = match &types[..] {
1496 [only] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", only))
})format!("`{only}`"),
1497 [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!(
1498 "{} and `{last}`",
1499 head.iter().map(|t| format!("`{t}`")).collect::<Vec<_>>().join(", ")
1500 ),
1501 [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1502 };
1503 err.span_note(
1504 span,
1505 ::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"),
1506 );
1507 }
1508 }
1509 }
1510
1511 pub(crate) fn implements_clone(&self, ty: Ty<'tcx>) -> bool {
1512 let Some(clone_trait_def) = self.infcx.tcx.lang_items().clone_trait() else { return false };
1513 self.infcx
1514 .type_implements_trait(clone_trait_def, [ty], self.infcx.param_env)
1515 .must_apply_modulo_regions()
1516 }
1517
1518 pub(crate) fn clone_on_reference(&self, expr: &hir::Expr<'_>) -> Option<Span> {
1521 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1522 if let hir::ExprKind::MethodCall(segment, rcvr, args, span) = expr.kind
1523 && let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id)
1524 && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
1525 && rcvr_ty == expr_ty
1526 && segment.ident.name == sym::clone
1527 && args.is_empty()
1528 {
1529 Some(span)
1530 } else {
1531 None
1532 }
1533 }
1534
1535 fn in_move_closure(&self, expr: &hir::Expr<'_>) -> bool {
1536 for (_, node) in self.infcx.tcx.hir_parent_iter(expr.hir_id) {
1537 if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) = node
1538 && let hir::CaptureBy::Value { .. } = closure.capture_clause
1539 {
1540 return true;
1542 }
1543 }
1544 false
1545 }
1546
1547 fn suggest_cloning_inner(
1548 &self,
1549 err: &mut Diag<'_>,
1550 ty: Ty<'tcx>,
1551 expr: &hir::Expr<'_>,
1552 ) -> bool {
1553 let tcx = self.infcx.tcx;
1554
1555 if let ExpnKind::Macro(MacroKind::Derive, _) = self.body.span.ctxt().outer_expn_data().kind
1557 {
1558 return false;
1559 }
1560 if let Some(_) = self.clone_on_reference(expr) {
1561 return false;
1564 }
1565 if self.in_move_closure(expr) {
1568 return false;
1569 }
1570 if let hir::ExprKind::Closure(_) = expr.kind {
1573 return false;
1574 }
1575 let mut suggestion =
1577 if let Some(symbol) = tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1578 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}.clone()", symbol))
})format!(": {symbol}.clone()")
1579 } else {
1580 ".clone()".to_owned()
1581 };
1582 let mut sugg = Vec::with_capacity(2);
1583 let mut inner_expr = expr;
1584 let mut is_raw_ptr = false;
1585 let typeck_result = self.infcx.tcx.typeck(self.mir_def_id());
1586 while let hir::ExprKind::AddrOf(.., inner) | hir::ExprKind::Unary(hir::UnOp::Deref, inner) =
1588 &inner_expr.kind
1589 {
1590 if let hir::ExprKind::AddrOf(_, hir::Mutability::Mut, _) = inner_expr.kind {
1591 return false;
1594 }
1595 inner_expr = inner;
1596 if let Some(inner_type) = typeck_result.node_type_opt(inner.hir_id) {
1597 if #[allow(non_exhaustive_omitted_patterns)] match inner_type.kind() {
ty::RawPtr(..) => true,
_ => false,
}matches!(inner_type.kind(), ty::RawPtr(..)) {
1598 is_raw_ptr = true;
1599 break;
1600 }
1601 }
1602 }
1603 if inner_expr.span.lo() != expr.span.lo() && !is_raw_ptr {
1606 sugg.push((expr.span.with_hi(inner_expr.span.lo()), String::new()));
1608 }
1609 let span = if inner_expr.span.hi() != expr.span.hi() {
1611 if is_raw_ptr {
1613 expr.span.shrink_to_hi()
1614 } else {
1615 expr.span.with_lo(inner_expr.span.hi())
1617 }
1618 } else {
1619 if is_raw_ptr {
1620 sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
1621 suggestion = ").clone()".to_string();
1622 }
1623 expr.span.shrink_to_hi()
1624 };
1625 sugg.push((span, suggestion));
1626 let msg = if let ty::Adt(def, _) = ty.kind()
1627 && [tcx.get_diagnostic_item(sym::Arc), tcx.get_diagnostic_item(sym::Rc)]
1628 .contains(&Some(def.did()))
1629 {
1630 "clone the value to increment its reference count"
1631 } else {
1632 "consider cloning the value if the performance cost is acceptable"
1633 };
1634 err.multipart_suggestion(msg, sugg, Applicability::MachineApplicable);
1635 true
1636 }
1637
1638 fn suggest_adding_bounds(&self, err: &mut Diag<'_>, ty: Ty<'tcx>, def_id: DefId, span: Span) {
1639 let tcx = self.infcx.tcx;
1640 let generics = tcx.generics_of(self.mir_def_id());
1641
1642 let Some(hir_generics) =
1643 tcx.hir_get_generics(tcx.typeck_root_def_id_local(self.mir_def_id()))
1644 else {
1645 return;
1646 };
1647 let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1649 let cause = ObligationCause::misc(span, self.mir_def_id());
1650
1651 ocx.register_bound(cause, self.infcx.param_env, ty, def_id);
1652 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1653
1654 let predicates: Result<Vec<_>, _> = errors
1656 .into_iter()
1657 .map(|err| match err.obligation.predicate.kind().skip_binder() {
1658 PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => {
1659 match *predicate.self_ty().kind() {
1660 ty::Param(param_ty) => Ok((
1661 generics.type_param(param_ty, tcx),
1662 predicate.trait_ref.print_trait_sugared().to_string(),
1663 Some(predicate.trait_ref.def_id),
1664 )),
1665 _ => Err(()),
1666 }
1667 }
1668 _ => Err(()),
1669 })
1670 .collect();
1671
1672 if let Ok(predicates) = predicates {
1673 suggest_constraining_type_params(
1674 tcx,
1675 hir_generics,
1676 err,
1677 predicates.iter().map(|(param, constraint, def_id)| {
1678 (param.name.as_str(), &**constraint, *def_id)
1679 }),
1680 None,
1681 );
1682 }
1683 }
1684
1685 pub(crate) fn report_move_out_while_borrowed(
1686 &mut self,
1687 location: Location,
1688 (place, span): (Place<'tcx>, Span),
1689 borrow: &BorrowData<'tcx>,
1690 ) {
1691 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:1691",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(1691u32),
::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!(
1692 "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
1693 location, place, span, borrow
1694 );
1695 let value_msg = self.describe_any_place(place.as_ref());
1696 let borrow_msg = self.describe_any_place(borrow.borrowed_place.as_ref());
1697
1698 let borrow_spans = self.retrieve_borrow_spans(borrow);
1699 let borrow_span = borrow_spans.args_or_use();
1700
1701 let move_spans = self.move_spans(place.as_ref(), location);
1702 let span = move_spans.args_or_use();
1703
1704 let mut err = self.cannot_move_when_borrowed(
1705 span,
1706 borrow_span,
1707 &self.describe_any_place(place.as_ref()),
1708 &borrow_msg,
1709 &value_msg,
1710 );
1711 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1712
1713 borrow_spans.var_path_only_subdiag(&mut err, crate::InitializationRequiringAction::Borrow);
1714
1715 move_spans.var_subdiag(&mut err, None, |kind, var_span| {
1716 use crate::session_diagnostics::CaptureVarCause::*;
1717 match kind {
1718 hir::ClosureKind::Coroutine(_) => MoveUseInCoroutine { var_span },
1719 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1720 MoveUseInClosure { var_span }
1721 }
1722 }
1723 });
1724
1725 self.explain_why_borrow_contains_point(location, borrow, None)
1726 .add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
1727 self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
1728 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1729 if let Some(expr) = self.find_expr(borrow_span) {
1730 if let hir::ExprKind::AddrOf(_, _, borrowed_expr) = expr.kind
1732 && let Some(ty) = typeck_results.expr_ty_opt(borrowed_expr)
1733 {
1734 self.suggest_cloning(&mut err, place.as_ref(), ty, borrowed_expr, Some(move_spans));
1735 } else if typeck_results.expr_adjustments(expr).first().is_some_and(|adj| {
1736 #[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!(
1737 adj.kind,
1738 ty::adjustment::Adjust::Borrow(ty::adjustment::AutoBorrow::Ref(
1739 ty::adjustment::AutoBorrowMutability::Not
1740 | ty::adjustment::AutoBorrowMutability::Mut {
1741 allow_two_phase_borrow: ty::adjustment::AllowTwoPhase::No
1742 }
1743 ))
1744 )
1745 }) && let Some(ty) = typeck_results.expr_ty_opt(expr)
1746 {
1747 self.suggest_cloning(&mut err, place.as_ref(), ty, expr, Some(move_spans));
1748 }
1749 }
1750 self.buffer_error(err);
1751 }
1752
1753 pub(crate) fn report_use_while_mutably_borrowed(
1754 &self,
1755 location: Location,
1756 (place, _span): (Place<'tcx>, Span),
1757 borrow: &BorrowData<'tcx>,
1758 ) -> Diag<'diag> {
1759 let borrow_spans = self.retrieve_borrow_spans(borrow);
1760 let borrow_span = borrow_spans.args_or_use();
1761
1762 let use_spans = self.move_spans(place.as_ref(), location);
1765 let span = use_spans.var_or_use();
1766
1767 let mut err = self.cannot_use_when_mutably_borrowed(
1771 span,
1772 &self.describe_any_place(place.as_ref()),
1773 borrow_span,
1774 &self.describe_any_place(borrow.borrowed_place.as_ref()),
1775 );
1776 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1777
1778 borrow_spans.var_subdiag(&mut err, Some(borrow.kind), |kind, var_span| {
1779 use crate::session_diagnostics::CaptureVarCause::*;
1780 let place = &borrow.borrowed_place;
1781 let desc_place = self.describe_any_place(place.as_ref());
1782 match kind {
1783 hir::ClosureKind::Coroutine(_) => {
1784 BorrowUsePlaceCoroutine { place: desc_place, var_span, is_single_var: true }
1785 }
1786 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1787 BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: true }
1788 }
1789 }
1790 });
1791
1792 self.explain_why_borrow_contains_point(location, borrow, None)
1793 .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
1794 err
1795 }
1796
1797 pub(crate) fn report_conflicting_borrow(
1798 &self,
1799 location: Location,
1800 (place, span): (Place<'tcx>, Span),
1801 gen_borrow_kind: BorrowKind,
1802 issued_borrow: &BorrowData<'tcx>,
1803 ) -> Diag<'diag> {
1804 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
1805 let issued_span = issued_spans.args_or_use();
1806
1807 let borrow_spans = self.borrow_spans(span, location);
1808 let span = borrow_spans.args_or_use();
1809
1810 let container_name = if issued_spans.for_coroutine() || borrow_spans.for_coroutine() {
1811 "coroutine"
1812 } else {
1813 "closure"
1814 };
1815
1816 let (desc_place, msg_place, msg_borrow, union_type_name) =
1817 self.describe_place_for_conflicting_borrow(place, issued_borrow.borrowed_place);
1818
1819 let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
1820 let second_borrow_desc = if explanation.is_explained() { "second " } else { "" };
1821
1822 let first_borrow_desc;
1824 let mut err = match (gen_borrow_kind, issued_borrow.kind) {
1825 (
1826 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1827 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1828 ) => {
1829 first_borrow_desc = "mutable ";
1830 let mut err = self.cannot_reborrow_already_borrowed(
1831 span,
1832 &desc_place,
1833 &msg_place,
1834 "immutable",
1835 issued_span,
1836 "it",
1837 "mutable",
1838 &msg_borrow,
1839 None,
1840 );
1841 self.suggest_slice_method_if_applicable(
1842 &mut err,
1843 place,
1844 issued_borrow.borrowed_place,
1845 span,
1846 issued_span,
1847 );
1848 err
1849 }
1850 (
1851 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1852 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1853 ) => {
1854 first_borrow_desc = "immutable ";
1855 let mut err = self.cannot_reborrow_already_borrowed(
1856 span,
1857 &desc_place,
1858 &msg_place,
1859 "mutable",
1860 issued_span,
1861 "it",
1862 "immutable",
1863 &msg_borrow,
1864 None,
1865 );
1866 self.suggest_slice_method_if_applicable(
1867 &mut err,
1868 place,
1869 issued_borrow.borrowed_place,
1870 span,
1871 issued_span,
1872 );
1873 self.suggest_binding_for_closure_capture_self(&mut err, &issued_spans);
1874 self.suggest_using_closure_argument_instead_of_capture(
1875 &mut err,
1876 issued_borrow.borrowed_place,
1877 &issued_spans,
1878 );
1879 self.explain_iterator_invalidation_in_for_loop_if_applicable(
1880 &mut err,
1881 &issued_spans,
1882 place,
1883 issued_borrow.borrowed_place,
1884 issued_borrow.kind,
1885 span,
1886 );
1887 err
1888 }
1889
1890 (
1891 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1892 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1893 ) => {
1894 first_borrow_desc = "first ";
1895 let mut err = self.cannot_mutably_borrow_multiply(
1896 span,
1897 &desc_place,
1898 &msg_place,
1899 issued_span,
1900 &msg_borrow,
1901 None,
1902 );
1903 self.suggest_slice_method_if_applicable(
1904 &mut err,
1905 place,
1906 issued_borrow.borrowed_place,
1907 span,
1908 issued_span,
1909 );
1910 self.explain_iterator_invalidation_in_for_loop_if_applicable(
1911 &mut err,
1912 &issued_spans,
1913 place,
1914 issued_borrow.borrowed_place,
1915 issued_borrow.kind,
1916 span,
1917 );
1918 self.suggest_using_closure_argument_instead_of_capture(
1919 &mut err,
1920 issued_borrow.borrowed_place,
1921 &issued_spans,
1922 );
1923 self.explain_iterator_advancement_in_for_loop_if_applicable(
1924 &mut err,
1925 span,
1926 &issued_spans,
1927 );
1928 err
1929 }
1930
1931 (
1932 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1933 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1934 ) => {
1935 first_borrow_desc = "first ";
1936 self.cannot_uniquely_borrow_by_two_closures(span, &desc_place, issued_span, None)
1937 }
1938
1939 (BorrowKind::Mut { .. }, BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
1940 if let Some(immutable_section_description) =
1941 self.classify_immutable_section(issued_borrow.assigned_place)
1942 {
1943 let mut err = self.cannot_mutate_in_immutable_section(
1944 span,
1945 issued_span,
1946 &desc_place,
1947 immutable_section_description,
1948 "mutably borrow",
1949 );
1950 borrow_spans.var_subdiag(
1951 &mut err,
1952 Some(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }),
1953 |kind, var_span| {
1954 use crate::session_diagnostics::CaptureVarCause::*;
1955 match kind {
1956 hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1957 place: desc_place,
1958 var_span,
1959 is_single_var: true,
1960 },
1961 hir::ClosureKind::Closure
1962 | hir::ClosureKind::CoroutineClosure(_) => BorrowUsePlaceClosure {
1963 place: desc_place,
1964 var_span,
1965 is_single_var: true,
1966 },
1967 }
1968 },
1969 );
1970 return err;
1971 } else {
1972 first_borrow_desc = "immutable ";
1973 self.cannot_reborrow_already_borrowed(
1974 span,
1975 &desc_place,
1976 &msg_place,
1977 "mutable",
1978 issued_span,
1979 "it",
1980 "immutable",
1981 &msg_borrow,
1982 None,
1983 )
1984 }
1985 }
1986
1987 (BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }, _) => {
1988 first_borrow_desc = "first ";
1989 self.cannot_uniquely_borrow_by_one_closure(
1990 span,
1991 container_name,
1992 &desc_place,
1993 "",
1994 issued_span,
1995 "it",
1996 "",
1997 None,
1998 )
1999 }
2000
2001 (
2002 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
2003 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
2004 ) => {
2005 first_borrow_desc = "first ";
2006 self.cannot_reborrow_already_uniquely_borrowed(
2007 span,
2008 container_name,
2009 &desc_place,
2010 "",
2011 "immutable",
2012 issued_span,
2013 "",
2014 None,
2015 second_borrow_desc,
2016 )
2017 }
2018
2019 (BorrowKind::Mut { .. }, BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }) => {
2020 first_borrow_desc = "first ";
2021 self.cannot_reborrow_already_uniquely_borrowed(
2022 span,
2023 container_name,
2024 &desc_place,
2025 "",
2026 "mutable",
2027 issued_span,
2028 "",
2029 None,
2030 second_borrow_desc,
2031 )
2032 }
2033
2034 (
2035 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
2036 BorrowKind::Shared | BorrowKind::Fake(_),
2037 )
2038 | (
2039 BorrowKind::Fake(FakeBorrowKind::Shallow),
2040 BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_),
2041 ) => {
2042 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
2043 }
2044 };
2045 self.note_due_to_edition_2024_opaque_capture_rules(issued_borrow, &mut err);
2046
2047 if issued_spans == borrow_spans {
2048 borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
2049 use crate::session_diagnostics::CaptureVarCause::*;
2050 match kind {
2051 hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
2052 place: desc_place,
2053 var_span,
2054 is_single_var: false,
2055 },
2056 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
2057 BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: false }
2058 }
2059 }
2060 });
2061 } else {
2062 issued_spans.var_subdiag(&mut err, Some(issued_borrow.kind), |kind, var_span| {
2063 use crate::session_diagnostics::CaptureVarCause::*;
2064 let borrow_place = &issued_borrow.borrowed_place;
2065 let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
2066 match kind {
2067 hir::ClosureKind::Coroutine(_) => {
2068 FirstBorrowUsePlaceCoroutine { place: borrow_place_desc, var_span }
2069 }
2070 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
2071 FirstBorrowUsePlaceClosure { place: borrow_place_desc, var_span }
2072 }
2073 }
2074 });
2075
2076 borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
2077 use crate::session_diagnostics::CaptureVarCause::*;
2078 match kind {
2079 hir::ClosureKind::Coroutine(_) => {
2080 SecondBorrowUsePlaceCoroutine { place: desc_place, var_span }
2081 }
2082 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
2083 SecondBorrowUsePlaceClosure { place: desc_place, var_span }
2084 }
2085 }
2086 });
2087 }
2088
2089 if union_type_name != "" {
2090 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!(
2091 "{msg_place} is a field of the union `{union_type_name}`, so it overlaps the field {msg_borrow}",
2092 ));
2093 }
2094
2095 explanation.add_explanation_to_diagnostic(
2096 &self,
2097 &mut err,
2098 first_borrow_desc,
2099 None,
2100 Some((issued_span, span)),
2101 );
2102
2103 self.suggest_using_local_if_applicable(&mut err, location, issued_borrow, explanation);
2104 self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
2105
2106 err
2107 }
2108
2109 fn suggest_copy_for_type_in_cloned_ref(&self, err: &mut Diag<'_>, place: Place<'tcx>) {
2110 let tcx = self.infcx.tcx;
2111 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2112
2113 struct FindUselessClone<'tcx> {
2114 tcx: TyCtxt<'tcx>,
2115 typeck_results: &'tcx ty::TypeckResults<'tcx>,
2116 clones: Vec<&'tcx hir::Expr<'tcx>>,
2117 }
2118 impl<'tcx> FindUselessClone<'tcx> {
2119 fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
2120 Self { tcx, typeck_results: tcx.typeck(def_id), clones: ::alloc::vec::Vec::new()vec![] }
2121 }
2122 }
2123 impl<'tcx> Visitor<'tcx> for FindUselessClone<'tcx> {
2124 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
2125 if let hir::ExprKind::MethodCall(..) = ex.kind
2126 && let Some(method_def_id) =
2127 self.typeck_results.type_dependent_def_id(ex.hir_id)
2128 && self.tcx.is_lang_item(self.tcx.parent(method_def_id), LangItem::Clone)
2129 {
2130 self.clones.push(ex);
2131 }
2132 hir::intravisit::walk_expr(self, ex);
2133 }
2134 }
2135
2136 let mut expr_finder = FindUselessClone::new(tcx, self.mir_def_id());
2137
2138 let body = tcx.hir_body(body_id).value;
2139 expr_finder.visit_expr(body);
2140
2141 struct Holds<'tcx> {
2142 ty: Ty<'tcx>,
2143 }
2144
2145 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for Holds<'tcx> {
2146 type Result = std::ops::ControlFlow<()>;
2147
2148 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
2149 if t == self.ty {
2150 return ControlFlow::Break(());
2151 }
2152 t.super_visit_with(self)
2153 }
2154 }
2155
2156 let mut types_to_constrain = FxIndexSet::default();
2157
2158 let local_ty = self.body.local_decls[place.local].ty;
2159 let typeck_results = tcx.typeck(self.mir_def_id());
2160 let clone = tcx.require_lang_item(LangItem::Clone, body.span);
2161 for expr in expr_finder.clones {
2162 if let hir::ExprKind::MethodCall(_, rcvr, _, span) = expr.kind
2163 && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
2164 && let Some(ty) = typeck_results.node_type_opt(expr.hir_id)
2165 && rcvr_ty == ty
2166 && let ty::Ref(_, inner, _) = rcvr_ty.kind()
2167 && let inner = inner.peel_refs()
2168 && (Holds { ty: inner }).visit_ty(local_ty).is_break()
2169 && let None =
2170 self.infcx.type_implements_trait_shallow(clone, inner, self.infcx.param_env)
2171 {
2172 err.span_label(
2173 span,
2174 ::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!(
2175 "this call doesn't do anything, the result is still `{rcvr_ty}` \
2176 because `{inner}` doesn't implement `Clone`",
2177 ),
2178 );
2179 types_to_constrain.insert(inner);
2180 }
2181 }
2182 for ty in types_to_constrain {
2183 self.suggest_adding_bounds_or_derive(err, ty, clone, body.span);
2184 }
2185 }
2186
2187 pub(crate) fn suggest_adding_bounds_or_derive(
2188 &self,
2189 err: &mut Diag<'_>,
2190 ty: Ty<'tcx>,
2191 trait_def_id: DefId,
2192 span: Span,
2193 ) {
2194 self.suggest_adding_bounds(err, ty, trait_def_id, span);
2195 if let ty::Adt(..) = ty.kind() {
2196 let trait_ref =
2198 ty::Binder::dummy(ty::TraitRef::new(self.infcx.tcx, trait_def_id, [ty]));
2199 let obligation = Obligation::new(
2200 self.infcx.tcx,
2201 ObligationCause::dummy(),
2202 self.infcx.param_env,
2203 trait_ref,
2204 );
2205 self.infcx.err_ctxt().suggest_derive(
2206 &obligation,
2207 err,
2208 trait_ref.upcast(self.infcx.tcx),
2209 );
2210 }
2211 }
2212
2213 {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2213u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2231",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2231u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2260",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2260u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2264",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2264u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2274",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2274u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2278",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2278u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2281",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2281u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2288",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2288u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2291",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2291u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2301",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2301u32),
::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))]
2214 fn suggest_using_local_if_applicable(
2215 &self,
2216 err: &mut Diag<'_>,
2217 location: Location,
2218 issued_borrow: &BorrowData<'tcx>,
2219 explanation: BorrowExplanation<'tcx>,
2220 ) {
2221 let used_in_call = matches!(
2222 explanation,
2223 BorrowExplanation::UsedLater(
2224 _,
2225 LaterUseKind::Call | LaterUseKind::Other,
2226 _call_span,
2227 _
2228 )
2229 );
2230 if !used_in_call {
2231 debug!("not later used in call");
2232 return;
2233 }
2234 if matches!(
2235 self.body.local_decls[issued_borrow.borrowed_place.local].local_info(),
2236 LocalInfo::IfThenRescopeTemp { .. }
2237 ) {
2238 return;
2240 }
2241
2242 let use_span = if let BorrowExplanation::UsedLater(_, LaterUseKind::Other, use_span, _) =
2243 explanation
2244 {
2245 Some(use_span)
2246 } else {
2247 None
2248 };
2249
2250 let outer_call_loc =
2251 if let TwoPhaseActivation::ActivatedAt(loc) = issued_borrow.activation_location {
2252 loc
2253 } else {
2254 issued_borrow.reserve_location
2255 };
2256 let outer_call_stmt = self.body.stmt_at(outer_call_loc);
2257
2258 let inner_param_location = location;
2259 let Some(inner_param_stmt) = self.body.stmt_at(inner_param_location).left() else {
2260 debug!("`inner_param_location` {:?} is not for a statement", inner_param_location);
2261 return;
2262 };
2263 let Some(&inner_param) = inner_param_stmt.kind.as_assign().map(|(p, _)| p) else {
2264 debug!(
2265 "`inner_param_location` {:?} is not for an assignment: {:?}",
2266 inner_param_location, inner_param_stmt
2267 );
2268 return;
2269 };
2270 let inner_param_uses = find_all_local_uses::find(self.body, inner_param.local);
2271 let Some((inner_call_loc, inner_call_term)) =
2272 inner_param_uses.into_iter().find_map(|loc| {
2273 let Either::Right(term) = self.body.stmt_at(loc) else {
2274 debug!("{:?} is a statement, so it can't be a call", loc);
2275 return None;
2276 };
2277 let TerminatorKind::Call { args, .. } = &term.kind else {
2278 debug!("not a call: {:?}", term);
2279 return None;
2280 };
2281 debug!("checking call args for uses of inner_param: {:?}", args);
2282 args.iter()
2283 .map(|a| &a.node)
2284 .any(|a| a == &Operand::Move(inner_param))
2285 .then_some((loc, term))
2286 })
2287 else {
2288 debug!("no uses of inner_param found as a by-move call arg");
2289 return;
2290 };
2291 debug!("===> outer_call_loc = {:?}, inner_call_loc = {:?}", outer_call_loc, inner_call_loc);
2292
2293 let inner_call_span = inner_call_term.source_info.span;
2294 let outer_call_span = match use_span {
2295 Some(span) => span,
2296 None => outer_call_stmt.either(|s| s.source_info, |t| t.source_info).span,
2297 };
2298 if outer_call_span == inner_call_span || !outer_call_span.contains(inner_call_span) {
2299 debug!(
2302 "outer span {:?} does not strictly contain inner span {:?}",
2303 outer_call_span, inner_call_span
2304 );
2305 return;
2306 }
2307 err.span_help(
2308 inner_call_span,
2309 format!(
2310 "try adding a local storing this{}...",
2311 if use_span.is_some() { "" } else { " argument" }
2312 ),
2313 );
2314 err.span_help(
2315 outer_call_span,
2316 format!(
2317 "...and then using that local {}",
2318 if use_span.is_some() { "here" } else { "as the argument to this call" }
2319 ),
2320 );
2321 }
2322
2323 pub(crate) fn find_expr(&self, span: Span) -> Option<&'tcx hir::Expr<'tcx>> {
2324 let tcx = self.infcx.tcx;
2325 let body_id = tcx.hir_node(self.mir_hir_id()).body_id()?;
2326 let mut expr_finder = FindExprBySpan::new(span, tcx);
2327 expr_finder.visit_expr(tcx.hir_body(body_id).value);
2328 expr_finder.result
2329 }
2330
2331 fn suggest_slice_method_if_applicable(
2332 &self,
2333 err: &mut Diag<'_>,
2334 place: Place<'tcx>,
2335 borrowed_place: Place<'tcx>,
2336 span: Span,
2337 issued_span: Span,
2338 ) {
2339 let tcx = self.infcx.tcx;
2340
2341 let has_split_at_mut = |ty: Ty<'tcx>| {
2342 let ty = ty.peel_refs();
2343 match ty.kind() {
2344 ty::Array(..) | ty::Slice(..) => true,
2345 ty::Adt(def, _) if tcx.get_diagnostic_item(sym::Vec) == Some(def.did()) => true,
2346 _ if ty == tcx.types.str_ => true,
2347 _ => false,
2348 }
2349 };
2350 if let ([ProjectionElem::Index(index1)], [ProjectionElem::Index(index2)])
2351 | (
2352 [ProjectionElem::Deref, ProjectionElem::Index(index1)],
2353 [ProjectionElem::Deref, ProjectionElem::Index(index2)],
2354 ) = (&place.projection[..], &borrowed_place.projection[..])
2355 {
2356 let decl1 = &self.body.local_decls[*index1];
2357 let decl2 = &self.body.local_decls[*index2];
2358
2359 let mut note_default_suggestion = || {
2360 err.help(
2361 "consider using `.split_at_mut(position)` or similar method to obtain two \
2362 mutable non-overlapping sub-slices",
2363 )
2364 .help(
2365 "consider using `.swap(index_1, index_2)` to swap elements at the specified \
2366 indices",
2367 );
2368 };
2369
2370 let Some(index1) = self.find_expr(decl1.source_info.span) else {
2371 note_default_suggestion();
2372 return;
2373 };
2374
2375 let Some(index2) = self.find_expr(decl2.source_info.span) else {
2376 note_default_suggestion();
2377 return;
2378 };
2379
2380 let sm = tcx.sess.source_map();
2381
2382 let Ok(index1_str) = sm.span_to_snippet(index1.span) else {
2383 note_default_suggestion();
2384 return;
2385 };
2386
2387 let Ok(index2_str) = sm.span_to_snippet(index2.span) else {
2388 note_default_suggestion();
2389 return;
2390 };
2391
2392 let Some(object) = tcx.hir_parent_id_iter(index1.hir_id).find_map(|id| {
2393 if let hir::Node::Expr(expr) = tcx.hir_node(id)
2394 && let hir::ExprKind::Index(obj, ..) = expr.kind
2395 {
2396 Some(obj)
2397 } else {
2398 None
2399 }
2400 }) else {
2401 note_default_suggestion();
2402 return;
2403 };
2404
2405 let Ok(obj_str) = sm.span_to_snippet(object.span) else {
2406 note_default_suggestion();
2407 return;
2408 };
2409
2410 let Some(swap_call) = tcx.hir_parent_id_iter(object.hir_id).find_map(|id| {
2411 if let hir::Node::Expr(call) = tcx.hir_node(id)
2412 && let hir::ExprKind::Call(callee, ..) = call.kind
2413 && let hir::ExprKind::Path(qpath) = callee.kind
2414 && let hir::QPath::Resolved(None, res) = qpath
2415 && let hir::def::Res::Def(_, did) = res.res
2416 && tcx.is_diagnostic_item(sym::mem_swap, did)
2417 {
2418 Some(call)
2419 } else {
2420 None
2421 }
2422 }) else {
2423 let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2424 let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2425 let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2426 let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2427 if !idx1.equivalent_for_indexing(idx2) {
2428 err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2429 }
2430 return;
2431 };
2432
2433 err.span_suggestion(
2434 swap_call.span,
2435 "use `.swap()` to swap elements at the specified indices instead",
2436 ::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})"),
2437 Applicability::MachineApplicable,
2438 );
2439 return;
2440 }
2441 let place_ty = PlaceRef::ty(&place.as_ref(), self.body, tcx).ty;
2442 let borrowed_place_ty = PlaceRef::ty(&borrowed_place.as_ref(), self.body, tcx).ty;
2443 if !has_split_at_mut(place_ty) && !has_split_at_mut(borrowed_place_ty) {
2444 return;
2446 }
2447 let Some(index1) = self.find_expr(span) else { return };
2448 let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2449 let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2450 let Some(index2) = self.find_expr(issued_span) else { return };
2451 let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2452 let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2453 if idx1.equivalent_for_indexing(idx2) {
2454 return;
2456 }
2457 err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2458 }
2459
2460 pub(crate) fn explain_iterator_advancement_in_for_loop_if_applicable(
2471 &self,
2472 err: &mut Diag<'_>,
2473 span: Span,
2474 issued_spans: &UseSpans<'tcx>,
2475 ) {
2476 let issue_span = issued_spans.args_or_use();
2477 let tcx = self.infcx.tcx;
2478
2479 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2480 let typeck_results = tcx.typeck(self.mir_def_id());
2481
2482 struct ExprFinder<'hir> {
2483 tcx: TyCtxt<'hir>,
2484 issue_span: Span,
2485 expr_span: Span,
2486 body_expr: Option<&'hir hir::Expr<'hir>> = None,
2487 loop_bind: Option<&'hir Ident> = None,
2488 loop_span: Option<Span> = None,
2489 head_span: Option<Span> = None,
2490 pat_span: Option<Span> = None,
2491 head: Option<&'hir hir::Expr<'hir>> = None,
2492 }
2493 impl<'hir> Visitor<'hir> for ExprFinder<'hir> {
2494 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2495 if let hir::ExprKind::Call(path, [arg]) = ex.kind
2508 && let hir::ExprKind::Path(qpath) = path.kind
2509 && self.tcx.qpath_is_lang_item(qpath, LangItem::IntoIterIntoIter)
2510 && arg.span.contains(self.issue_span)
2511 && ex.span.desugaring_kind() == Some(DesugaringKind::ForLoop)
2512 {
2513 self.head = Some(arg);
2515 }
2516 if let hir::ExprKind::Loop(
2517 hir::Block { stmts: [stmt, ..], .. },
2518 _,
2519 hir::LoopSource::ForLoop,
2520 _,
2521 ) = ex.kind
2522 && let hir::StmtKind::Expr(hir::Expr {
2523 kind: hir::ExprKind::Match(call, [_, bind, ..], _),
2524 span: head_span,
2525 ..
2526 }) = stmt.kind
2527 && let hir::ExprKind::Call(path, _args) = call.kind
2528 && let hir::ExprKind::Path(qpath) = path.kind
2529 && self.tcx.qpath_is_lang_item(qpath, LangItem::IteratorNext)
2530 && let hir::PatKind::Struct(qpath, [field, ..], _) = bind.pat.kind
2531 && self.tcx.qpath_is_lang_item(qpath, LangItem::OptionSome)
2532 && call.span.contains(self.issue_span)
2533 {
2534 if let PatField {
2536 pat: hir::Pat { kind: hir::PatKind::Binding(_, _, ident, ..), .. },
2537 ..
2538 } = field
2539 {
2540 self.loop_bind = Some(ident);
2541 }
2542 self.head_span = Some(*head_span);
2543 self.pat_span = Some(bind.pat.span);
2544 self.loop_span = Some(stmt.span);
2545 }
2546
2547 if let hir::ExprKind::MethodCall(body_call, recv, ..) = ex.kind
2548 && body_call.ident.name == sym::next
2549 && recv.span.source_equal(self.expr_span)
2550 {
2551 self.body_expr = Some(ex);
2552 }
2553
2554 hir::intravisit::walk_expr(self, ex);
2555 }
2556 }
2557 let mut finder = ExprFinder { tcx, expr_span: span, issue_span, .. };
2558 finder.visit_expr(tcx.hir_body(body_id).value);
2559
2560 if let Some(body_expr) = finder.body_expr
2561 && let Some(loop_span) = finder.loop_span
2562 && let Some(def_id) = typeck_results.type_dependent_def_id(body_expr.hir_id)
2563 && let Some(trait_did) = tcx.trait_of_assoc(def_id)
2564 && tcx.is_diagnostic_item(sym::Iterator, trait_did)
2565 {
2566 if let Some(loop_bind) = finder.loop_bind {
2567 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!(
2568 "a for loop advances the iterator for you, the result is stored in `{}`",
2569 loop_bind.name,
2570 ));
2571 } else {
2572 err.note(
2573 "a for loop advances the iterator for you, the result is stored in its pattern",
2574 );
2575 }
2576 let msg = "if you want to call `next` on a iterator within the loop, consider using \
2577 `while let`";
2578 if let Some(head) = finder.head
2579 && let Some(pat_span) = finder.pat_span
2580 && loop_span.contains(body_expr.span)
2581 && loop_span.contains(head.span)
2582 {
2583 let sm = self.infcx.tcx.sess.source_map();
2584
2585 let mut sugg = ::alloc::vec::Vec::new()vec![];
2586 if let hir::ExprKind::Path(hir::QPath::Resolved(None, _)) = head.kind {
2587 sugg.push((loop_span.with_hi(pat_span.lo()), "while let Some(".to_string()));
2591 sugg.push((
2592 pat_span.shrink_to_hi().with_hi(head.span.lo()),
2593 ") = ".to_string(),
2594 ));
2595 sugg.push((head.span.shrink_to_hi(), ".next()".to_string()));
2596 } else {
2597 let indent = if let Some(indent) = sm.indentation_before(loop_span) {
2599 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}", indent))
})format!("\n{indent}")
2600 } else {
2601 " ".to_string()
2602 };
2603 let Ok(head_str) = sm.span_to_snippet(head.span) else {
2604 err.help(msg);
2605 return;
2606 };
2607 sugg.push((
2608 loop_span.with_hi(pat_span.lo()),
2609 ::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("),
2610 ));
2611 sugg.push((
2612 pat_span.shrink_to_hi().with_hi(head.span.hi()),
2613 ") = iter.next()".to_string(),
2614 ));
2615 if let hir::ExprKind::MethodCall(_, recv, ..) = body_expr.kind
2618 && let hir::ExprKind::Path(hir::QPath::Resolved(None, ..)) = recv.kind
2619 {
2620 sugg.push((recv.span, "iter".to_string()));
2624 }
2625 }
2626 err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2627 } else {
2628 err.help(msg);
2629 }
2630 }
2631 }
2632
2633 fn explain_iterator_invalidation_in_for_loop_if_applicable(
2643 &self,
2644 err: &mut Diag<'_>,
2645 issued_spans: &UseSpans<'tcx>,
2646 place: Place<'tcx>,
2647 borrowed_place: Place<'tcx>,
2648 borrow_kind: BorrowKind,
2649 gen_span: Span,
2650 ) {
2651 let issue_span = issued_spans.args_or_use();
2652 let tcx = self.infcx.tcx;
2653
2654 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2655
2656 if let Some(for_span) = find_for_loop_span(tcx, body_id, issue_span)
2657 && place.local == borrowed_place.local
2658 && for_span.contains(gen_span)
2659 {
2660 let place_desc = self.describe_any_place(place.as_ref());
2661 let borrow_kind_str =
2662 if #[allow(non_exhaustive_omitted_patterns)] match borrow_kind {
BorrowKind::Mut { .. } => true,
_ => false,
}matches!(borrow_kind, BorrowKind::Mut { .. }) { "mutably" } else { "immutably" };
2663 err.span_label(
2664 for_span,
2665 ::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!(
2666 "this for loop borrows {place_desc} {borrow_kind_str}, \
2667 preventing mutation within its body"
2668 ),
2669 );
2670 err.help(
2671 "consider using an index-based loop instead, or collecting \
2672 modifications into a separate collection",
2673 );
2674 }
2675 }
2676
2677 fn suggest_using_closure_argument_instead_of_capture(
2694 &self,
2695 err: &mut Diag<'_>,
2696 borrowed_place: Place<'tcx>,
2697 issued_spans: &UseSpans<'tcx>,
2698 ) {
2699 let &UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2700 let tcx = self.infcx.tcx;
2701
2702 let local = borrowed_place.local;
2704 let local_ty = self.body.local_decls[local].ty;
2705
2706 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2708
2709 let body_expr = tcx.hir_body(body_id).value;
2710
2711 struct ClosureFinder<'hir> {
2712 tcx: TyCtxt<'hir>,
2713 borrow_span: Span,
2714 res: Option<(&'hir hir::Expr<'hir>, &'hir hir::Closure<'hir>)>,
2715 error_path: Option<(&'hir hir::Expr<'hir>, &'hir hir::QPath<'hir>)>,
2717 }
2718 impl<'hir> Visitor<'hir> for ClosureFinder<'hir> {
2719 type NestedFilter = OnlyBodies;
2720
2721 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
2722 self.tcx
2723 }
2724
2725 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2726 if let hir::ExprKind::Path(qpath) = &ex.kind
2727 && ex.span == self.borrow_span
2728 {
2729 self.error_path = Some((ex, qpath));
2730 }
2731
2732 if let hir::ExprKind::Closure(closure) = ex.kind
2733 && ex.span.contains(self.borrow_span)
2734 && self.res.as_ref().is_none_or(|(prev_res, _)| prev_res.span.contains(ex.span))
2738 {
2739 self.res = Some((ex, closure));
2740 }
2741
2742 hir::intravisit::walk_expr(self, ex);
2743 }
2744 }
2745
2746 let mut finder =
2748 ClosureFinder { tcx, borrow_span: capture_kind_span, res: None, error_path: None };
2749 finder.visit_expr(body_expr);
2750 let Some((closure_expr, closure)) = finder.res else { return };
2751
2752 let typeck_results = tcx.typeck(self.mir_def_id());
2753
2754 if let hir::Node::Expr(parent) = tcx.parent_hir_node(closure_expr.hir_id)
2757 && let hir::ExprKind::MethodCall(_, recv, ..) = parent.kind
2758 {
2759 let recv_ty = typeck_results.expr_ty(recv);
2760
2761 if recv_ty.peel_refs() != local_ty {
2762 return;
2763 }
2764 }
2765
2766 let ty::Closure(_, args) = typeck_results.expr_ty(closure_expr).kind() else {
2768 return;
2770 };
2771 let sig = args.as_closure().sig();
2772 let tupled_params = tcx.instantiate_bound_regions_with_erased(
2773 sig.inputs().iter().next().unwrap().map_bound(|&b| b),
2774 );
2775 let ty::Tuple(params) = tupled_params.kind() else { return };
2776
2777 let Some(this_name) = params.iter().zip(tcx.hir_body_param_idents(closure.body)).find_map(
2779 |(param_ty, ident)| {
2780 if param_ty.peel_refs() == local_ty { ident } else { None }
2782 },
2783 ) else {
2784 return;
2785 };
2786
2787 let spans;
2788 if let Some((_path_expr, qpath)) = finder.error_path
2789 && let hir::QPath::Resolved(_, path) = qpath
2790 && let hir::def::Res::Local(local_id) = path.res
2791 {
2792 struct VariableUseFinder {
2795 local_id: hir::HirId,
2796 spans: Vec<Span>,
2797 }
2798 impl<'hir> Visitor<'hir> for VariableUseFinder {
2799 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2800 if let hir::ExprKind::Path(qpath) = &ex.kind
2801 && let hir::QPath::Resolved(_, path) = qpath
2802 && let hir::def::Res::Local(local_id) = path.res
2803 && local_id == self.local_id
2804 {
2805 self.spans.push(ex.span);
2806 }
2807
2808 hir::intravisit::walk_expr(self, ex);
2809 }
2810 }
2811
2812 let mut finder = VariableUseFinder { local_id, spans: Vec::new() };
2813 finder.visit_expr(tcx.hir_body(closure.body).value);
2814
2815 spans = finder.spans;
2816 } else {
2817 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];
2818 }
2819
2820 err.multipart_suggestion(
2821 "try using the closure argument",
2822 iter::zip(spans, iter::repeat(this_name.to_string())).collect(),
2823 Applicability::MaybeIncorrect,
2824 );
2825 }
2826
2827 fn suggest_binding_for_closure_capture_self(
2828 &self,
2829 err: &mut Diag<'_>,
2830 issued_spans: &UseSpans<'tcx>,
2831 ) {
2832 let UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2833
2834 struct ExpressionFinder<'tcx> {
2835 capture_span: Span,
2836 closure_change_spans: Vec<Span> = ::alloc::vec::Vec::new()vec![],
2837 closure_arg_span: Option<Span> = None,
2838 in_closure: bool = false,
2839 suggest_arg: String = String::new(),
2840 tcx: TyCtxt<'tcx>,
2841 closure_local_id: Option<hir::HirId> = None,
2842 closure_call_changes: Vec<(Span, String)> = ::alloc::vec::Vec::new()vec![],
2843 }
2844 impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
2845 fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
2846 if e.span.contains(self.capture_span)
2847 && let hir::ExprKind::Closure(&hir::Closure {
2848 kind: hir::ClosureKind::Closure,
2849 body,
2850 fn_arg_span,
2851 fn_decl: hir::FnDecl { inputs, .. },
2852 ..
2853 }) = e.kind
2854 && let hir::Node::Expr(body) = self.tcx.hir_node(body.hir_id)
2855 {
2856 self.suggest_arg = "this: &Self".to_string();
2857 if inputs.len() > 0 {
2858 self.suggest_arg.push_str(", ");
2859 }
2860 self.in_closure = true;
2861 self.closure_arg_span = fn_arg_span;
2862 self.visit_expr(body);
2863 self.in_closure = false;
2864 }
2865 if let hir::Expr { kind: hir::ExprKind::Path(path), .. } = e
2866 && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2867 && seg.ident.name == kw::SelfLower
2868 && self.in_closure
2869 {
2870 self.closure_change_spans.push(e.span);
2871 }
2872 hir::intravisit::walk_expr(self, e);
2873 }
2874
2875 fn visit_local(&mut self, local: &'hir hir::LetStmt<'hir>) {
2876 if let hir::Pat { kind: hir::PatKind::Binding(_, hir_id, _ident, _), .. } =
2877 local.pat
2878 && let Some(init) = local.init
2879 && let &hir::Expr {
2880 kind:
2881 hir::ExprKind::Closure(&hir::Closure {
2882 kind: hir::ClosureKind::Closure,
2883 ..
2884 }),
2885 ..
2886 } = init
2887 && init.span.contains(self.capture_span)
2888 {
2889 self.closure_local_id = Some(*hir_id);
2890 }
2891
2892 hir::intravisit::walk_local(self, local);
2893 }
2894
2895 fn visit_stmt(&mut self, s: &'hir hir::Stmt<'hir>) {
2896 if let hir::StmtKind::Semi(e) = s.kind
2897 && let hir::ExprKind::Call(
2898 hir::Expr { kind: hir::ExprKind::Path(path), .. },
2899 args,
2900 ) = e.kind
2901 && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2902 && let Res::Local(hir_id) = seg.res
2903 && Some(hir_id) == self.closure_local_id
2904 {
2905 let (span, arg_str) = if args.len() > 0 {
2906 (args[0].span.shrink_to_lo(), "self, ".to_string())
2907 } else {
2908 let span = e.span.trim_start(seg.ident.span).unwrap_or(e.span);
2909 (span, "(self)".to_string())
2910 };
2911 self.closure_call_changes.push((span, arg_str));
2912 }
2913 hir::intravisit::walk_stmt(self, s);
2914 }
2915 }
2916
2917 if let hir::Node::ImplItem(hir::ImplItem {
2918 kind: hir::ImplItemKind::Fn(_fn_sig, body_id),
2919 ..
2920 }) = self.infcx.tcx.hir_node(self.mir_hir_id())
2921 && let hir::Node::Expr(expr) = self.infcx.tcx.hir_node(body_id.hir_id)
2922 {
2923 let mut finder =
2924 ExpressionFinder { capture_span: *capture_kind_span, tcx: self.infcx.tcx, .. };
2925 finder.visit_expr(expr);
2926
2927 if finder.closure_change_spans.is_empty() || finder.closure_call_changes.is_empty() {
2928 return;
2929 }
2930
2931 let sm = self.infcx.tcx.sess.source_map();
2932 let sugg = finder
2933 .closure_arg_span
2934 .map(|span| (sm.next_point(span.shrink_to_lo()).shrink_to_hi(), finder.suggest_arg))
2935 .into_iter()
2936 .chain(
2937 finder.closure_change_spans.into_iter().map(|span| (span, "this".to_string())),
2938 )
2939 .chain(finder.closure_call_changes)
2940 .collect();
2941
2942 err.multipart_suggestion(
2943 "try explicitly passing `&Self` into the closure as an argument",
2944 sugg,
2945 Applicability::MachineApplicable,
2946 );
2947 }
2948 }
2949
2950 fn describe_place_for_conflicting_borrow(
2979 &self,
2980 first_borrowed_place: Place<'tcx>,
2981 second_borrowed_place: Place<'tcx>,
2982 ) -> (String, String, String, String) {
2983 let union_ty = |place_base| {
2986 let ty = PlaceRef::ty(&place_base, self.body, self.infcx.tcx).ty;
2989 ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
2990 };
2991
2992 Some(())
2996 .filter(|_| {
2997 first_borrowed_place != second_borrowed_place
3000 })
3001 .and_then(|_| {
3002 for (place_base, elem) in first_borrowed_place.iter_projections().rev() {
3007 match elem {
3008 ProjectionElem::Field(field, _) if union_ty(place_base).is_some() => {
3009 return Some((place_base, field));
3010 }
3011 _ => {}
3012 }
3013 }
3014 None
3015 })
3016 .and_then(|(target_base, target_field)| {
3017 for (place_base, elem) in second_borrowed_place.iter_projections().rev() {
3020 if let ProjectionElem::Field(field, _) = elem
3021 && let Some(union_ty) = union_ty(place_base)
3022 {
3023 if field != target_field && place_base == target_base {
3024 return Some((
3025 self.describe_any_place(place_base),
3026 self.describe_any_place(first_borrowed_place.as_ref()),
3027 self.describe_any_place(second_borrowed_place.as_ref()),
3028 union_ty.to_string(),
3029 ));
3030 }
3031 }
3032 }
3033 None
3034 })
3035 .unwrap_or_else(|| {
3036 (
3039 self.describe_any_place(first_borrowed_place.as_ref()),
3040 "".to_string(),
3041 "".to_string(),
3042 "".to_string(),
3043 )
3044 })
3045 }
3046
3047 {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3053u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3070",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3070u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3106",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3106u32),
::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))]
3054 pub(crate) fn report_borrowed_value_does_not_live_long_enough(
3055 &mut self,
3056 location: Location,
3057 borrow: &BorrowData<'tcx>,
3058 place_span: (Place<'tcx>, Span),
3059 kind: Option<WriteKind>,
3060 ) {
3061 let drop_span = place_span.1;
3062 let borrowed_local = borrow.borrowed_place.local;
3063
3064 let borrow_spans = self.retrieve_borrow_spans(borrow);
3065 let borrow_span = borrow_spans.var_or_use_path_span();
3066
3067 let proper_span = self.body.local_decls[borrowed_local].source_info.span;
3068
3069 if self.access_place_error_reported.contains(&(Place::from(borrowed_local), borrow_span)) {
3070 debug!(
3071 "suppressing access_place error when borrow doesn't live long enough for {:?}",
3072 borrow_span
3073 );
3074 return;
3075 }
3076
3077 self.access_place_error_reported.insert((Place::from(borrowed_local), borrow_span));
3078
3079 if self.body.local_decls[borrowed_local].is_ref_to_thread_local() {
3080 let err =
3081 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span);
3082 self.buffer_error(err);
3083 return;
3084 }
3085
3086 if let StorageDeadOrDrop::Destructor(dropped_ty) =
3087 self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
3088 {
3089 if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
3094 self.report_borrow_conflicts_with_destructor(
3095 location, borrow, place_span, kind, dropped_ty,
3096 );
3097 return;
3098 }
3099 }
3100
3101 let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
3102
3103 let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
3104 let explanation = self.explain_why_borrow_contains_point(location, borrow, kind_place);
3105
3106 debug!(?place_desc, ?explanation);
3107
3108 let mut err = match (place_desc, explanation) {
3109 (
3119 Some(name),
3120 BorrowExplanation::UsedLater(_, LaterUseKind::ClosureCapture, var_or_use_span, _),
3121 ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
3122 .report_escaping_closure_capture(
3123 borrow_spans,
3124 borrow_span,
3125 &RegionName {
3126 name: self.synthesize_region_name(),
3127 source: RegionNameSource::Static,
3128 },
3129 ConstraintCategory::CallArgument(None),
3130 var_or_use_span,
3131 &format!("`{name}`"),
3132 "block",
3133 ),
3134 (
3135 Some(name),
3136 BorrowExplanation::MustBeValidFor { ref best_blame, ref region_name, .. },
3137 ) if let OutlivesConstraint {
3138 category:
3139 category @ (ConstraintCategory::Return(_)
3140 | ConstraintCategory::CallArgument(_)
3141 | ConstraintCategory::OpaqueType),
3142 from_closure: false,
3143 span,
3144 ..
3145 } = best_blame.constraint()
3146 && (borrow_spans.for_coroutine() || borrow_spans.for_closure()) =>
3147 {
3148 self.report_escaping_closure_capture(
3149 borrow_spans,
3150 borrow_span,
3151 region_name,
3152 *category,
3153 *span,
3154 &format!("`{name}`"),
3155 "function",
3156 )
3157 }
3158 (
3159 name,
3160 BorrowExplanation::MustBeValidFor {
3161 ref best_blame,
3162 region_name:
3163 RegionName {
3164 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
3165 ..
3166 },
3167 ..
3168 },
3169 ) if let OutlivesConstraint {
3170 category: ConstraintCategory::Assignment,
3171 from_closure: false,
3172 span,
3173 ..
3174 } = best_blame.constraint() =>
3175 {
3176 self.report_escaping_data(borrow_span, &name, upvar_span, upvar_name, *span)
3177 }
3178 (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
3179 location,
3180 &name,
3181 borrow,
3182 drop_span,
3183 borrow_spans,
3184 explanation,
3185 ),
3186 (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
3187 location,
3188 borrow,
3189 drop_span,
3190 borrow_spans,
3191 proper_span,
3192 explanation,
3193 ),
3194 };
3195 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
3196
3197 self.buffer_error(err);
3198 }
3199
3200 {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3200u32),
::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 =>
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))]
3201 fn report_local_value_does_not_live_long_enough(
3202 &self,
3203 location: Location,
3204 name: &str,
3205 borrow: &BorrowData<'tcx>,
3206 drop_span: Span,
3207 borrow_spans: UseSpans<'tcx>,
3208 explanation: BorrowExplanation<'tcx>,
3209 ) -> Diag<'diag> {
3210 let borrow_span = borrow_spans.var_or_use_path_span();
3211 if let BorrowExplanation::MustBeValidFor { best_blame, opt_place_desc, .. } = &explanation
3212 && let OutlivesConstraint { category, span, from_closure: false, .. } =
3213 best_blame.constraint()
3214 && let Err(diag) = self.try_report_cannot_return_reference_to_local(
3215 borrow,
3216 borrow_span,
3217 *span,
3218 *category,
3219 opt_place_desc.as_ref(),
3220 )
3221 {
3222 return diag;
3223 }
3224
3225 let name = format!("`{name}`");
3226
3227 let mut err = self.path_does_not_live_long_enough(borrow_span, &name);
3228
3229 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
3230 let region_name = annotation.emit(self, &mut err);
3231
3232 err.span_label(
3233 borrow_span,
3234 format!("{name} would have to be valid for `{region_name}`..."),
3235 );
3236
3237 err.span_label(
3238 drop_span,
3239 format!(
3240 "...but {name} will be dropped here, when the {} returns",
3241 self.infcx
3242 .tcx
3243 .opt_item_name(self.mir_def_id().to_def_id())
3244 .map(|name| format!("function `{name}`"))
3245 .unwrap_or_else(|| {
3246 match &self.infcx.tcx.def_kind(self.mir_def_id()) {
3247 DefKind::Closure
3248 if self
3249 .infcx
3250 .tcx
3251 .is_coroutine(self.mir_def_id().to_def_id()) =>
3252 {
3253 "enclosing coroutine"
3254 }
3255 DefKind::Closure => "enclosing closure",
3256 kind => bug!("expected closure or coroutine, found {:?}", kind),
3257 }
3258 .to_string()
3259 })
3260 ),
3261 );
3262
3263 err.note(
3264 "functions cannot return a borrow to data owned within the function's scope, \
3265 functions can only return borrows to data passed as arguments",
3266 );
3267 err.note(
3268 "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
3269 references-and-borrowing.html#dangling-references>",
3270 );
3271
3272 if let BorrowExplanation::MustBeValidFor { .. } = explanation {
3273 } else {
3274 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3275 }
3276 } else {
3277 err.span_label(borrow_span, "borrowed value does not live long enough");
3278 err.span_label(drop_span, format!("{name} dropped here while still borrowed"));
3279
3280 borrow_spans.args_subdiag(&mut err, |args_span| {
3281 crate::session_diagnostics::CaptureArgLabel::Capture {
3282 is_within: borrow_spans.for_coroutine(),
3283 args_span,
3284 }
3285 });
3286
3287 explanation.add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
3288
3289 if let BorrowExplanation::UsedLater(_dropped_local, _, _, _) = explanation {
3291 for (local, local_decl) in self.body.local_decls.iter_enumerated() {
3293 if let ty::Adt(adt_def, args) = local_decl.ty.kind()
3294 && self.infcx.tcx.is_diagnostic_item(sym::Vec, adt_def.did())
3295 && args.len() > 0
3296 {
3297 let vec_inner_ty = args.type_at(0);
3298 if vec_inner_ty.is_ref() {
3300 let local_place = local.into();
3301 if let Some(local_name) = self.describe_place(local_place) {
3302 err.span_label(
3303 local_decl.source_info.span,
3304 format!("variable `{local_name}` declared here"),
3305 );
3306 err.note(
3307 format!(
3308 "`{local_name}` is a collection that stores borrowed references, \
3309 but {name} does not live long enough to be stored in it"
3310 )
3311 );
3312 err.help(
3313 "buffer reuse with borrowed references requires unsafe code or restructuring"
3314 );
3315 break;
3316 }
3317 }
3318 }
3319 }
3320 }
3321 }
3322
3323 err
3324 }
3325
3326 fn report_borrow_conflicts_with_destructor(
3327 &mut self,
3328 location: Location,
3329 borrow: &BorrowData<'tcx>,
3330 (place, drop_span): (Place<'tcx>, Span),
3331 kind: Option<WriteKind>,
3332 dropped_ty: Ty<'tcx>,
3333 ) {
3334 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3334",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3334u32),
::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!(
3335 "report_borrow_conflicts_with_destructor(\
3336 {:?}, {:?}, ({:?}, {:?}), {:?}\
3337 )",
3338 location, borrow, place, drop_span, kind,
3339 );
3340
3341 let borrow_spans = self.retrieve_borrow_spans(borrow);
3342 let borrow_span = borrow_spans.var_or_use();
3343
3344 let mut err = self.cannot_borrow_across_destructor(borrow_span);
3345
3346 let what_was_dropped = match self.describe_place(place.as_ref()) {
3347 Some(name) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
})format!("`{name}`"),
3348 None => String::from("temporary value"),
3349 };
3350
3351 let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
3352 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!(
3353 "here, drop of {what_was_dropped} needs exclusive access to `{borrowed}`, \
3354 because the type `{dropped_ty}` implements the `Drop` trait"
3355 ),
3356 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!(
3357 "here is drop of {what_was_dropped}; whose type `{dropped_ty}` implements the `Drop` trait"
3358 ),
3359 };
3360 err.span_label(drop_span, label);
3361
3362 let explanation =
3364 self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
3365 match explanation {
3366 BorrowExplanation::UsedLater { .. }
3367 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3368 err.note("consider using a `let` binding to create a longer lived value");
3369 }
3370 _ => {}
3371 }
3372
3373 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3374
3375 self.buffer_error(err);
3376 }
3377
3378 fn report_thread_local_value_does_not_live_long_enough(
3379 &self,
3380 drop_span: Span,
3381 borrow_span: Span,
3382 ) -> Diag<'diag> {
3383 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3383",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3383u32),
::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!(
3384 "report_thread_local_value_does_not_live_long_enough(\
3385 {:?}, {:?}\
3386 )",
3387 drop_span, borrow_span
3388 );
3389
3390 let sm = self.infcx.tcx.sess.source_map();
3395 let end_of_function = if drop_span.is_empty()
3396 && let Ok(adjusted_span) = sm.span_extend_prev_while(drop_span, |c| c == '}')
3397 {
3398 adjusted_span
3399 } else {
3400 drop_span
3401 };
3402 self.thread_local_value_does_not_live_long_enough(borrow_span)
3403 .with_span_label(
3404 borrow_span,
3405 "thread-local variables cannot be borrowed beyond the end of the function",
3406 )
3407 .with_span_label(end_of_function, "end of enclosing function is here")
3408 }
3409
3410 {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3410u32),
::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))]
3411 fn report_temporary_value_does_not_live_long_enough(
3412 &self,
3413 location: Location,
3414 borrow: &BorrowData<'tcx>,
3415 drop_span: Span,
3416 borrow_spans: UseSpans<'tcx>,
3417 proper_span: Span,
3418 explanation: BorrowExplanation<'tcx>,
3419 ) -> Diag<'diag> {
3420 if let BorrowExplanation::MustBeValidFor { ref best_blame, .. } = explanation
3421 && let OutlivesConstraint { category, span, from_closure: false, .. } =
3422 best_blame.constraint()
3423 {
3424 if let Err(diag) = self.try_report_cannot_return_reference_to_local(
3425 borrow,
3426 proper_span,
3427 *span,
3428 *category,
3429 None,
3430 ) {
3431 return diag;
3432 }
3433 }
3434
3435 let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
3436 err.span_label(proper_span, "creates a temporary value which is freed while still in use");
3437 err.span_label(drop_span, "temporary value is freed at the end of this statement");
3438
3439 match explanation {
3440 BorrowExplanation::UsedLater(..)
3441 | BorrowExplanation::UsedLaterInLoop(..)
3442 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3443 let sm = self.infcx.tcx.sess.source_map();
3445 let mut suggested = false;
3446 let msg = "consider using a `let` binding to create a longer lived value";
3447
3448 struct NestedStatementVisitor<'tcx> {
3457 span: Span,
3458 current: usize,
3459 found: usize,
3460 prop_expr: Option<&'tcx hir::Expr<'tcx>>,
3461 call: Option<&'tcx hir::Expr<'tcx>>,
3462 }
3463
3464 impl<'tcx> Visitor<'tcx> for NestedStatementVisitor<'tcx> {
3465 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
3466 self.current += 1;
3467 walk_block(self, block);
3468 self.current -= 1;
3469 }
3470 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
3471 if let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind {
3472 if self.span == rcvr.span.source_callsite() {
3473 self.call = Some(expr);
3474 }
3475 }
3476 if self.span == expr.span.source_callsite() {
3477 self.found = self.current;
3478 if self.prop_expr.is_none() {
3479 self.prop_expr = Some(expr);
3480 }
3481 }
3482 walk_expr(self, expr);
3483 }
3484 }
3485 let source_info = self.body.source_info(location);
3486 let proper_span = proper_span.source_callsite();
3487 if let Some(scope) = self.body.source_scopes.get(source_info.scope)
3488 && let ClearCrossCrate::Set(scope_data) = &scope.local_data
3489 && let Some(id) = self.infcx.tcx.hir_node(scope_data.lint_root).body_id()
3490 && let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir_body(id).value.kind
3491 {
3492 for stmt in block.stmts {
3493 let mut visitor = NestedStatementVisitor {
3494 span: proper_span,
3495 current: 0,
3496 found: 0,
3497 prop_expr: None,
3498 call: None,
3499 };
3500 visitor.visit_stmt(stmt);
3501
3502 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
3503 let expr_ty: Option<Ty<'_>> =
3504 visitor.prop_expr.map(|expr| typeck_results.expr_ty(expr).peel_refs());
3505
3506 if visitor.found == 0
3507 && stmt.span.contains(proper_span)
3508 && let Some(p) = sm.span_to_margin(stmt.span)
3509 && let Ok(s) = sm.span_to_snippet(proper_span)
3510 {
3511 if let Some(call) = visitor.call
3512 && let hir::ExprKind::MethodCall(path, _, [], _) = call.kind
3513 && path.ident.name == sym::iter
3514 && let Some(ty) = expr_ty
3515 {
3516 err.span_suggestion_verbose(
3517 path.ident.span,
3518 format!(
3519 "consider consuming the `{ty}` when turning it into an \
3520 `Iterator`",
3521 ),
3522 "into_iter",
3523 Applicability::MaybeIncorrect,
3524 );
3525 }
3526
3527 let mutability = if matches!(borrow.kind(), BorrowKind::Mut { .. }) {
3528 "mut "
3529 } else {
3530 ""
3531 };
3532
3533 let addition =
3534 format!("let {}binding = {};\n{}", mutability, s, " ".repeat(p));
3535 err.multipart_suggestion(
3536 msg,
3537 vec![
3538 (stmt.span.shrink_to_lo(), addition),
3539 (proper_span, "binding".to_string()),
3540 ],
3541 Applicability::MaybeIncorrect,
3542 );
3543
3544 suggested = true;
3545 break;
3546 }
3547 }
3548 }
3549 if !suggested {
3550 err.note(msg);
3551 }
3552 }
3553 _ => {}
3554 }
3555 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3556
3557 borrow_spans.args_subdiag(&mut err, |args_span| {
3558 crate::session_diagnostics::CaptureArgLabel::Capture {
3559 is_within: borrow_spans.for_coroutine(),
3560 args_span,
3561 }
3562 });
3563
3564 err
3565 }
3566
3567 fn try_report_cannot_return_reference_to_local(
3568 &self,
3569 borrow: &BorrowData<'tcx>,
3570 borrow_span: Span,
3571 return_span: Span,
3572 category: ConstraintCategory<'tcx>,
3573 opt_place_desc: Option<&String>,
3574 ) -> Result<(), Diag<'diag>> {
3575 let return_kind = match category {
3576 ConstraintCategory::Return(_) => "return",
3577 ConstraintCategory::Yield => "yield",
3578 _ => return Ok(()),
3579 };
3580
3581 let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
3583 "reference to"
3584 } else {
3585 "value referencing"
3586 };
3587
3588 let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
3589 let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
3590 match self.body.local_kind(local) {
3591 LocalKind::Temp if self.body.local_decls[local].is_user_variable() => {
3592 "local variable "
3593 }
3594 LocalKind::Arg
3595 if !self.upvars.is_empty() && local == ty::CAPTURE_STRUCT_LOCAL =>
3596 {
3597 "variable captured by `move` "
3598 }
3599 LocalKind::Arg => "function parameter ",
3600 LocalKind::ReturnPointer | LocalKind::Temp => {
3601 bug_impl(None, format_args!("temporary or return pointer with a name"),
Location::caller())bug!("temporary or return pointer with a name")
3602 }
3603 }
3604 } else {
3605 "local data "
3606 };
3607 (::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"))
3608 } else {
3609 let local = borrow.borrowed_place.local;
3610 match self.body.local_kind(local) {
3611 LocalKind::Arg => (
3612 "function parameter".to_string(),
3613 "function parameter borrowed here".to_string(),
3614 ),
3615 LocalKind::Temp
3616 if self.body.local_decls[local].is_user_variable()
3617 && !self.body.local_decls[local]
3618 .source_info
3619 .span
3620 .in_external_macro(self.infcx.tcx.sess.source_map()) =>
3621 {
3622 ("local binding".to_string(), "local binding introduced here".to_string())
3623 }
3624 LocalKind::ReturnPointer | LocalKind::Temp => {
3625 ("temporary value".to_string(), "temporary value created here".to_string())
3626 }
3627 }
3628 };
3629
3630 let mut err = self.cannot_return_reference_to_local(
3631 return_span,
3632 return_kind,
3633 reference_desc,
3634 &place_desc,
3635 );
3636
3637 if return_span != borrow_span {
3638 err.span_label(borrow_span, note);
3639
3640 let tcx = self.infcx.tcx;
3641
3642 let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
3643
3644 if let Some(iter_trait) = tcx.get_diagnostic_item(sym::Iterator)
3646 && self
3647 .infcx
3648 .type_implements_trait(iter_trait, [return_ty], self.infcx.param_env)
3649 .must_apply_modulo_regions()
3650 {
3651 err.span_suggestion_hidden(
3652 return_span.shrink_to_hi(),
3653 "use `.collect()` to allocate the iterator",
3654 ".collect::<Vec<_>>()",
3655 Applicability::MaybeIncorrect,
3656 );
3657 }
3658
3659 if let Some(cow_did) = tcx.get_diagnostic_item(sym::Cow)
3660 && let ty::Adt(adt_def, _) = return_ty.kind()
3661 && adt_def.did() == cow_did
3662 {
3663 let typeck = tcx.typeck(self.mir_def_id());
3664 if let Some(expr) = self.find_expr(return_span)
3665 && let Some(def_id) = typeck.type_dependent_def_id(expr.hir_id)
3666 && tcx.is_diagnostic_item(sym::to_owned_method, def_id)
3667 && let Some(to_owned_ident) = expr.method_ident()
3668 {
3669 err.span_suggestion_short(
3670 to_owned_ident.span.shrink_to_lo(),
3671 "try using `.into_owned()` if you meant to convert a `Cow<'_, T>` to an owned `T`",
3672 "in",
3673 Applicability::MaybeIncorrect,
3674 );
3675 }
3676 }
3677 }
3678
3679 Err(err)
3680 }
3681
3682 {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3682u32),
::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 => {
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 => {
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 => {
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);
}
}
_ =>
bug_impl(None,
format_args!("report_escaping_closure_capture called with unexpected constraint category: `{0:?}`",
category), Location::caller()),
}
err
}
}
}#[instrument(level = "debug", skip(self))]
3683 fn report_escaping_closure_capture(
3684 &self,
3685 use_span: UseSpans<'tcx>,
3686 var_span: Span,
3687 fr_name: &RegionName,
3688 category: ConstraintCategory<'tcx>,
3689 constraint_span: Span,
3690 captured_var: &str,
3691 scope: &str,
3692 ) -> Diag<'diag> {
3693 let tcx = self.infcx.tcx;
3694 let args_span = use_span.args_or_use();
3695
3696 let (sugg_span, suggestion) = match tcx.sess.source_map().span_to_snippet(args_span) {
3697 Ok(string) => {
3698 let coro_prefix = if let Some(sub) = string.strip_prefix("async") {
3699 let trimmed_sub = sub.trim_end();
3700 if trimmed_sub.ends_with("gen") {
3701 Some((trimmed_sub.len() + 5) as _)
3703 } else {
3704 Some(5)
3706 }
3707 } else if string.starts_with("gen") {
3708 Some(3)
3710 } else if string.starts_with("static") {
3711 Some(6)
3714 } else {
3715 None
3716 };
3717 if let Some(n) = coro_prefix {
3718 let pos = args_span.lo() + BytePos(n);
3719 (args_span.with_lo(pos).with_hi(pos), " move")
3720 } else {
3721 (args_span.shrink_to_lo(), "move ")
3722 }
3723 }
3724 Err(_) => (args_span, "move |<args>| <body>"),
3725 };
3726 let kind = match use_span.coroutine_kind() {
3727 Some(coroutine_kind) => match coroutine_kind {
3728 CoroutineKind::Desugared(CoroutineDesugaring::Gen, kind) => match kind {
3729 CoroutineSource::Block => "gen block",
3730 CoroutineSource::Closure => "gen closure",
3731 CoroutineSource::Fn => {
3732 bug!("gen block/closure expected, but gen function found.")
3733 }
3734 },
3735 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, kind) => match kind {
3736 CoroutineSource::Block => "async gen block",
3737 CoroutineSource::Closure => "async gen closure",
3738 CoroutineSource::Fn => {
3739 bug!("gen block/closure expected, but gen function found.")
3740 }
3741 },
3742 CoroutineKind::Desugared(CoroutineDesugaring::Async, async_kind) => {
3743 match async_kind {
3744 CoroutineSource::Block => "async block",
3745 CoroutineSource::Closure => "async closure",
3746 CoroutineSource::Fn => {
3747 bug!("async block/closure expected, but async function found.")
3748 }
3749 }
3750 }
3751 CoroutineKind::Coroutine(_) => "coroutine",
3752 },
3753 None => "closure",
3754 };
3755
3756 let mut err = self.cannot_capture_in_long_lived_closure(
3757 args_span,
3758 kind,
3759 captured_var,
3760 var_span,
3761 scope,
3762 );
3763 err.span_suggestion_verbose(
3764 sugg_span,
3765 format!(
3766 "to force the {kind} to take ownership of {captured_var} (and any \
3767 other referenced variables), use the `move` keyword"
3768 ),
3769 suggestion,
3770 Applicability::MachineApplicable,
3771 );
3772
3773 match category {
3774 ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
3775 let msg = format!("{kind} is returned here");
3776 err.span_note(constraint_span, msg);
3777 }
3778 ConstraintCategory::CallArgument(_) => {
3779 fr_name.highlight_region_name(&mut err);
3780 if matches!(
3781 use_span.coroutine_kind(),
3782 Some(CoroutineKind::Desugared(CoroutineDesugaring::Async, _))
3783 ) {
3784 err.note(
3785 "async blocks are not executed immediately and must either take a \
3786 reference or ownership of outside variables they use",
3787 );
3788 } else {
3789 let msg = format!("{scope} requires argument type to outlive `{fr_name}`");
3790 err.span_note(constraint_span, msg);
3791 }
3792 }
3793 _ => bug!(
3794 "report_escaping_closure_capture called with unexpected constraint \
3795 category: `{:?}`",
3796 category
3797 ),
3798 }
3799
3800 err
3801 }
3802
3803 fn report_escaping_data(
3804 &self,
3805 borrow_span: Span,
3806 name: &Option<String>,
3807 upvar_span: Span,
3808 upvar_name: Symbol,
3809 escape_span: Span,
3810 ) -> Diag<'diag> {
3811 let tcx = self.infcx.tcx;
3812
3813 let escapes_from = tcx.def_descr(self.mir_def_id().to_def_id());
3814
3815 let mut err =
3816 borrowck_errors::borrowed_data_escapes_closure(self.dcx(), escape_span, escapes_from);
3817
3818 err.span_label(
3819 upvar_span,
3820 ::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"),
3821 );
3822
3823 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"));
3824
3825 if let Some(name) = name {
3826 err.span_label(
3827 escape_span,
3828 ::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"),
3829 );
3830 } else {
3831 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"));
3832 }
3833
3834 err
3835 }
3836
3837 fn get_moved_indexes(
3838 &self,
3839 location: Location,
3840 mpi: MovePathIndex,
3841 ) -> (Vec<MoveSite>, Vec<Location>) {
3842 fn predecessor_locations<'tcx>(
3843 body: &mir::Body<'tcx>,
3844 location: Location,
3845 ) -> impl Iterator<Item = Location> {
3846 if location.statement_index == 0 {
3847 let predecessors = body.basic_blocks.predecessors()[location.block].to_vec();
3848 Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb)))
3849 } else {
3850 Either::Right(std::iter::once(Location {
3851 statement_index: location.statement_index - 1,
3852 ..location
3853 }))
3854 }
3855 }
3856
3857 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];
3858 let move_paths = &self.move_data.move_paths;
3859 mpis.extend(move_paths[mpi].parents(move_paths).map(|(mpi, _)| mpi));
3860
3861 let mut stack = Vec::new();
3862 let mut back_edge_stack = Vec::new();
3863
3864 predecessor_locations(self.body, location).for_each(|predecessor| {
3865 if location.dominates(predecessor, self.dominators()) {
3866 back_edge_stack.push(predecessor)
3867 } else {
3868 stack.push(predecessor);
3869 }
3870 });
3871
3872 let mut reached_start = false;
3873
3874 let mut is_argument = false;
3876 for arg in self.body.args_iter() {
3877 if let Some(path) = self.move_data.rev_lookup.find_local(arg) {
3878 if mpis.contains(&path) {
3879 is_argument = true;
3880 }
3881 }
3882 }
3883
3884 let mut visited = FxIndexSet::default();
3885 let mut move_locations = FxIndexSet::default();
3886 let mut reinits = ::alloc::vec::Vec::new()vec![];
3887 let mut result = ::alloc::vec::Vec::new()vec![];
3888
3889 let mut dfs_iter = |result: &mut Vec<MoveSite>, location: Location, is_back_edge: bool| {
3890 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3890",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3890u32),
::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!(
3891 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
3892 location, is_back_edge
3893 );
3894
3895 if !visited.insert(location) {
3896 return true;
3897 }
3898
3899 let stmt_kind =
3901 self.body[location.block].statements.get(location.statement_index).map(|s| &s.kind);
3902 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
3903 } else {
3907 for moi in &self.move_data.move_out_loc_map[location] {
3915 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3915",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3915u32),
::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);
3916 let path = self.move_data.move_outs[*moi].path;
3917 if mpis.contains(&path) {
3918 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3918",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(3918u32),
::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!(
3919 "report_use_of_moved_or_uninitialized: found {:?}",
3920 move_paths[path].place
3921 );
3922 result.push(MoveSite { moi: *moi, traversed_back_edge: is_back_edge });
3923 move_locations.insert(location);
3924
3925 return true;
3942 }
3943 }
3944 }
3945
3946 let mut any_match = false;
3948 for ii in &self.move_data.init_loc_map[location] {
3949 let init = self.move_data.inits[*ii];
3950 match init.kind {
3951 InitKind::Deep | InitKind::NonPanicPathOnly => {
3952 if mpis.contains(&init.path) {
3953 any_match = true;
3954 }
3955 }
3956 InitKind::Shallow => {
3957 if mpi == init.path {
3958 any_match = true;
3959 }
3960 }
3961 }
3962 }
3963 if any_match {
3964 reinits.push(location);
3965 return true;
3966 }
3967 false
3968 };
3969
3970 while let Some(location) = stack.pop() {
3971 if dfs_iter(&mut result, location, false) {
3972 continue;
3973 }
3974
3975 let mut has_predecessor = false;
3976 predecessor_locations(self.body, location).for_each(|predecessor| {
3977 if location.dominates(predecessor, self.dominators()) {
3978 back_edge_stack.push(predecessor)
3979 } else {
3980 stack.push(predecessor);
3981 }
3982 has_predecessor = true;
3983 });
3984
3985 if !has_predecessor {
3986 reached_start = true;
3987 }
3988 }
3989 if (is_argument || !reached_start) && result.is_empty() {
3990 while let Some(location) = back_edge_stack.pop() {
3997 if dfs_iter(&mut result, location, true) {
3998 continue;
3999 }
4000
4001 predecessor_locations(self.body, location)
4002 .for_each(|predecessor| back_edge_stack.push(predecessor));
4003 }
4004 }
4005
4006 let reinits_reachable = reinits
4008 .into_iter()
4009 .filter(|reinit| {
4010 let mut visited = FxIndexSet::default();
4011 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];
4012 while let Some(location) = stack.pop() {
4013 if !visited.insert(location) {
4014 continue;
4015 }
4016 if move_locations.contains(&location) {
4017 return true;
4018 }
4019 stack.extend(predecessor_locations(self.body, location));
4020 }
4021 false
4022 })
4023 .collect::<Vec<Location>>();
4024 (result, reinits_reachable)
4025 }
4026
4027 pub(crate) fn report_illegal_mutation_of_borrowed(
4028 &mut self,
4029 location: Location,
4030 (place, span): (Place<'tcx>, Span),
4031 loan: &BorrowData<'tcx>,
4032 ) {
4033 let loan_spans = self.retrieve_borrow_spans(loan);
4034 let loan_span = loan_spans.args_or_use();
4035
4036 let descr_place = self.describe_any_place(place.as_ref());
4037 if let BorrowKind::Fake(_) = loan.kind
4038 && let Some(section) = self.classify_immutable_section(loan.assigned_place)
4039 {
4040 let mut err = self.cannot_mutate_in_immutable_section(
4041 span,
4042 loan_span,
4043 &descr_place,
4044 section,
4045 "assign",
4046 );
4047
4048 loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
4049 use crate::session_diagnostics::CaptureVarCause::*;
4050 match kind {
4051 hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
4052 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
4053 BorrowUseInClosure { var_span }
4054 }
4055 }
4056 });
4057
4058 self.buffer_error(err);
4059
4060 return;
4061 }
4062
4063 let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place);
4064 self.note_due_to_edition_2024_opaque_capture_rules(loan, &mut err);
4065
4066 loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
4067 use crate::session_diagnostics::CaptureVarCause::*;
4068 match kind {
4069 hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
4070 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
4071 BorrowUseInClosure { var_span }
4072 }
4073 }
4074 });
4075
4076 self.explain_why_borrow_contains_point(location, loan, None)
4077 .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
4078
4079 self.explain_deref_coercion(loan, &mut err);
4080
4081 self.buffer_error(err);
4082 }
4083
4084 fn explain_deref_coercion(&mut self, loan: &BorrowData<'tcx>, err: &mut Diag<'_>) {
4085 let tcx = self.infcx.tcx;
4086 if let Some(Terminator { kind: TerminatorKind::Call { call_source, fn_span, .. }, .. }) =
4087 &self.body[loan.reserve_location.block].terminator
4088 && let Some((method_did, method_args)) = mir::find_self_call(
4089 tcx,
4090 self.body,
4091 loan.assigned_place.local,
4092 loan.reserve_location.block,
4093 )
4094 && let CallKind::DerefCoercion { deref_target_span, deref_target_ty, .. } = call_kind(
4095 self.infcx.tcx,
4096 self.infcx.typing_env(self.infcx.param_env),
4097 method_did,
4098 method_args,
4099 *fn_span,
4100 call_source.from_hir_call(),
4101 self.infcx.tcx.fn_arg_idents(method_did)[0],
4102 )
4103 {
4104 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}`"));
4105 if let Some(deref_target_span) = deref_target_span {
4106 err.span_note(deref_target_span, "deref defined here");
4107 }
4108 }
4109 }
4110
4111 pub(crate) fn report_illegal_reassignment(
4118 &mut self,
4119 (place, span): (Place<'tcx>, Span),
4120 assigned_span: Span,
4121 err_place: Place<'tcx>,
4122 ) {
4123 let (from_arg, local_decl) = match err_place.as_local() {
4124 Some(local) => {
4125 (self.body.local_kind(local) == LocalKind::Arg, Some(&self.body.local_decls[local]))
4126 }
4127 None => (false, None),
4128 };
4129
4130 let (place_description, assigned_span) = match local_decl {
4134 Some(LocalDecl {
4135 local_info:
4136 ClearCrossCrate::Set(
4137 LocalInfo::User(BindingForm::Var(VarBindingForm {
4138 opt_match_place: None,
4139 ..
4140 }))
4141 | LocalInfo::StaticRef { .. }
4142 | LocalInfo::Boring,
4143 ),
4144 ..
4145 })
4146 | None => (self.describe_any_place(place.as_ref()), assigned_span),
4147 Some(decl) => (self.describe_any_place(err_place.as_ref()), decl.source_info.span),
4148 };
4149 let mut err = self.cannot_reassign_immutable(span, &place_description, from_arg);
4150 let msg = if from_arg {
4151 "cannot assign to immutable argument"
4152 } else {
4153 "cannot assign twice to immutable variable"
4154 };
4155 if span != assigned_span && !from_arg {
4156 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}"));
4157 }
4158 if let Some(decl) = local_decl
4159 && decl.can_be_made_mutable()
4160 {
4161 let mut is_for_loop = false;
4162 let mut is_immut_ref_pattern = false;
4163 if let LocalInfo::User(BindingForm::Var(VarBindingForm {
4164 opt_match_place: Some((_, match_span)),
4165 ..
4166 })) = *decl.local_info()
4167 {
4168 if #[allow(non_exhaustive_omitted_patterns)] match match_span.desugaring_kind() {
Some(DesugaringKind::ForLoop) => true,
_ => false,
}matches!(match_span.desugaring_kind(), Some(DesugaringKind::ForLoop)) {
4169 is_for_loop = true;
4170 }
4171
4172 if let Some(body) = self.infcx.tcx.hir_maybe_body_owned_by(self.mir_def_id()) {
4173 struct RefPatternFinder<'tcx> {
4174 tcx: TyCtxt<'tcx>,
4175 binding_span: Span,
4176 is_immut_ref_pattern: bool,
4177 }
4178
4179 impl<'tcx> Visitor<'tcx> for RefPatternFinder<'tcx> {
4180 type NestedFilter = OnlyBodies;
4181
4182 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
4183 self.tcx
4184 }
4185
4186 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
4187 if !self.is_immut_ref_pattern
4188 && let hir::PatKind::Binding(_, _, ident, _) = pat.kind
4189 && ident.span == self.binding_span
4190 && #[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!(
4191 self.tcx.parent_hir_node(pat.hir_id),
4192 hir::Node::Pat(hir::Pat {
4193 kind: hir::PatKind::Ref(_, _, hir::Mutability::Not),
4194 ..
4195 })
4196 )
4197 {
4198 self.is_immut_ref_pattern = true;
4199 }
4200 hir::intravisit::walk_pat(self, pat);
4201 }
4202 }
4203
4204 let mut finder = RefPatternFinder {
4205 tcx: self.infcx.tcx,
4206 binding_span: decl.source_info.span,
4207 is_immut_ref_pattern: false,
4208 };
4209
4210 finder.visit_body(body);
4211 is_immut_ref_pattern = finder.is_immut_ref_pattern;
4212 }
4213 }
4214
4215 let (span, message) = if is_immut_ref_pattern
4216 && let Ok(binding_name) =
4217 self.infcx.tcx.sess.source_map().span_to_snippet(decl.source_info.span)
4218 {
4219 (decl.source_info.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("(mut {0})", binding_name))
})format!("(mut {})", binding_name))
4220 } else {
4221 (decl.source_info.span.shrink_to_lo(), "mut ".to_string())
4222 };
4223
4224 err.span_suggestion_verbose(
4225 span,
4226 "consider making this binding mutable",
4227 message,
4228 Applicability::MachineApplicable,
4229 );
4230
4231 if !from_arg
4232 && !is_for_loop
4233 && #[allow(non_exhaustive_omitted_patterns)] match decl.local_info() {
LocalInfo::User(BindingForm::Var(VarBindingForm {
opt_match_place: Some((Some(_), _)), .. })) => true,
_ => false,
}matches!(
4234 decl.local_info(),
4235 LocalInfo::User(BindingForm::Var(VarBindingForm {
4236 opt_match_place: Some((Some(_), _)),
4237 ..
4238 }))
4239 )
4240 {
4241 err.span_suggestion_verbose(
4242 decl.source_info.span.shrink_to_lo(),
4243 "to modify the original value, take a borrow instead",
4244 "ref mut ".to_string(),
4245 Applicability::MaybeIncorrect,
4246 );
4247 }
4248 }
4249 err.span_label(span, msg);
4250 self.buffer_error(err);
4251 }
4252
4253 fn classify_drop_access_kind(&self, place: PlaceRef<'tcx>) -> StorageDeadOrDrop<'tcx> {
4254 let tcx = self.infcx.tcx;
4255 let (kind, _place_ty) = place.projection.iter().fold(
4256 (LocalStorageDead, PlaceTy::from_ty(self.body.local_decls[place.local].ty)),
4257 |(kind, place_ty), &elem| {
4258 (
4259 match elem {
4260 ProjectionElem::Deref => match kind {
4261 StorageDeadOrDrop::LocalStorageDead
4262 | StorageDeadOrDrop::BoxedStorageDead => {
4263 if !place_ty.ty.is_box() {
{
::core::panicking::panic_fmt(format_args!("Drop of value behind a reference or raw pointer"));
}
};assert!(
4264 place_ty.ty.is_box(),
4265 "Drop of value behind a reference or raw pointer"
4266 );
4267 StorageDeadOrDrop::BoxedStorageDead
4268 }
4269 StorageDeadOrDrop::Destructor(_) => kind,
4270 },
4271 ProjectionElem::PhantomDeref => match kind {
4272 StorageDeadOrDrop::LocalStorageDead
4273 | StorageDeadOrDrop::BoxedStorageDead => {
4274 StorageDeadOrDrop::BoxedStorageDead
4275 }
4276 StorageDeadOrDrop::Destructor(_) => kind,
4277 },
4278 ProjectionElem::OpaqueCast { .. }
4279 | ProjectionElem::Field(..)
4280 | ProjectionElem::Downcast(..) => {
4281 match place_ty.ty.kind() {
4282 ty::Adt(def, _) if def.has_dtor(tcx) => {
4283 match kind {
4285 StorageDeadOrDrop::Destructor(_) => kind,
4286 StorageDeadOrDrop::LocalStorageDead
4287 | StorageDeadOrDrop::BoxedStorageDead => {
4288 StorageDeadOrDrop::Destructor(place_ty.ty)
4289 }
4290 }
4291 }
4292 _ => kind,
4293 }
4294 }
4295 ProjectionElem::ConstantIndex { .. }
4296 | ProjectionElem::Subslice { .. }
4297 | ProjectionElem::Index(_)
4298 | ProjectionElem::UnwrapUnsafeBinder(_) => kind,
4299 },
4300 place_ty.projection_ty(tcx, elem),
4301 )
4302 },
4303 );
4304 kind
4305 }
4306
4307 fn classify_immutable_section(&self, place: Place<'tcx>) -> Option<&'static str> {
4309 use rustc_middle::mir::visit::Visitor;
4310 struct FakeReadCauseFinder<'tcx> {
4311 place: Place<'tcx>,
4312 cause: Option<FakeReadCause>,
4313 }
4314 impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'tcx> {
4315 fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
4316 match statement {
4317 Statement { kind: StatementKind::FakeRead((cause, place)), .. }
4318 if *place == self.place =>
4319 {
4320 self.cause = Some(*cause);
4321 }
4322 _ => (),
4323 }
4324 }
4325 }
4326 let mut visitor = FakeReadCauseFinder { place, cause: None };
4327 visitor.visit_body(self.body);
4328 match visitor.cause {
4329 Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
4330 Some(FakeReadCause::ForIndex) => Some("indexing expression"),
4331 _ => None,
4332 }
4333 }
4334
4335 fn annotate_argument_and_return_for_borrow(
4338 &self,
4339 borrow: &BorrowData<'tcx>,
4340 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4341 let fallback = || {
4343 let tcx = self.infcx.tcx;
4344 let is_closure = tcx.is_closure_like(self.mir_def_id().to_def_id());
4345 if is_closure {
4346 None
4347 } else {
4348 let ty = self
4349 .infcx
4350 .tcx
4351 .type_of(self.mir_def_id())
4352 .instantiate_identity()
4353 .skip_norm_wip();
4354 match ty.kind() {
4355 ty::FnDef(_, _) => self.annotate_fn_sig(
4356 self.mir_def_id(),
4357 self.infcx
4358 .tcx
4359 .fn_sig(self.mir_def_id())
4360 .instantiate_identity()
4361 .skip_norm_wip(),
4362 ),
4363 ty::FnPtr(_, _) => self.annotate_fn_sig(self.mir_def_id(), ty.fn_sig(tcx)),
4365 _ => None,
4366 }
4367 }
4368 };
4369
4370 let location = borrow.reserve_location;
4377 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4377",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4377u32),
::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);
4378 if let Some(Statement { kind: StatementKind::Assign((reservation, _)), .. }) =
4379 &self.body[location.block].statements.get(location.statement_index)
4380 {
4381 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4381",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4381u32),
::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);
4382 let mut target = match reservation.as_local() {
4384 Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
4385 _ => return None,
4386 };
4387
4388 let mut annotated_closure = None;
4391 for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
4392 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4392",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4392u32),
::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!(
4393 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
4394 target, stmt
4395 );
4396 if let StatementKind::Assign((place, rvalue)) = &stmt.kind
4397 && let Some(assigned_to) = place.as_local()
4398 {
4399 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4399",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4399u32),
::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!(
4400 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
4401 rvalue={:?}",
4402 assigned_to, rvalue
4403 );
4404 if let Rvalue::Aggregate(AggregateKind::Closure(def_id, args), operands) =
4406 rvalue
4407 {
4408 let def_id = def_id.expect_local();
4409 for operand in operands {
4410 let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4411 operand
4412 else {
4413 continue;
4414 };
4415 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4415",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4415u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__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!(
4416 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4417 assigned_from
4418 );
4419
4420 let Some(assigned_from_local) = assigned_from.local_or_deref_local()
4422 else {
4423 continue;
4424 };
4425
4426 if assigned_from_local != target {
4427 continue;
4428 }
4429
4430 annotated_closure =
4434 self.annotate_fn_sig(def_id, args.as_closure().sig());
4435 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4435",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4435u32),
::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!(
4436 "annotate_argument_and_return_for_borrow: \
4437 annotated_closure={:?} assigned_from_local={:?} \
4438 assigned_to={:?}",
4439 annotated_closure, assigned_from_local, assigned_to
4440 );
4441
4442 if assigned_to == mir::RETURN_PLACE {
4443 return annotated_closure;
4446 } else {
4447 target = assigned_to;
4449 }
4450 }
4451
4452 continue;
4455 }
4456
4457 let assigned_from = match rvalue {
4459 Rvalue::Ref(_, _, assigned_from) => assigned_from,
4460 Rvalue::Use(operand, _) => match operand {
4461 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
4462 assigned_from
4463 }
4464 _ => continue,
4465 },
4466 _ => continue,
4467 };
4468 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4468",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4468u32),
::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!(
4469 "annotate_argument_and_return_for_borrow: \
4470 assigned_from={:?}",
4471 assigned_from,
4472 );
4473
4474 let Some(assigned_from_local) = assigned_from.local_or_deref_local() else {
4476 continue;
4477 };
4478 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4478",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4478u32),
::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!(
4479 "annotate_argument_and_return_for_borrow: \
4480 assigned_from_local={:?}",
4481 assigned_from_local,
4482 );
4483
4484 if assigned_from_local != target {
4487 continue;
4488 }
4489
4490 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4492",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4492u32),
::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!(
4493 "annotate_argument_and_return_for_borrow: \
4494 assigned_from_local={:?} assigned_to={:?}",
4495 assigned_from_local, assigned_to
4496 );
4497 if assigned_to == mir::RETURN_PLACE {
4498 return annotated_closure.or_else(fallback);
4501 }
4502
4503 target = assigned_to;
4506 }
4507 }
4508
4509 let terminator = &self.body[location.block].terminator();
4511 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4511",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4511u32),
::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!(
4512 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
4513 target, terminator
4514 );
4515 if let TerminatorKind::Call { destination, target: Some(_), args, .. } =
4516 &terminator.kind
4517 && let Some(assigned_to) = destination.as_local()
4518 {
4519 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4519",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4519u32),
::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!(
4520 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
4521 assigned_to, args
4522 );
4523 for operand in args {
4524 let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4525 &operand.node
4526 else {
4527 continue;
4528 };
4529 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4529",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4529u32),
::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!(
4530 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4531 assigned_from,
4532 );
4533
4534 if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
4535 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4535",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4535u32),
::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!(
4536 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
4537 assigned_from_local,
4538 );
4539
4540 if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
4541 return annotated_closure.or_else(fallback);
4542 }
4543 }
4544 }
4545 }
4546 }
4547
4548 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4550",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4550u32),
::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");
4551 None
4552 }
4553
4554 fn annotate_fn_sig(
4557 &self,
4558 did: LocalDefId,
4559 sig: ty::PolyFnSig<'tcx>,
4560 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4561 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4561",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4561u32),
::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);
4562 let is_closure = self.infcx.tcx.is_closure_like(did.to_def_id());
4563 let fn_hir_id = self.infcx.tcx.local_def_id_to_hir_id(did);
4564 let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(fn_hir_id)?;
4565
4566 let return_ty = sig.output();
4589 match return_ty.skip_binder().kind() {
4590 ty::Ref(return_region, _, _)
4591 if return_region.is_named(self.infcx.tcx) && !is_closure =>
4592 {
4593 let mut arguments = Vec::new();
4596 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
4597 if let ty::Ref(argument_region, _, _) = argument.kind()
4598 && argument_region == return_region
4599 {
4600 match &fn_decl.inputs[index].kind {
4604 hir::TyKind::Ref(lifetime, _) => {
4605 arguments.push((*argument, lifetime.ident.span));
4608 }
4609 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
4611 if let Res::SelfTyAlias { alias_to, .. } = path.res
4612 && let Some(alias_to) = alias_to.as_local()
4613 && let hir::Impl { self_ty, .. } = self
4614 .infcx
4615 .tcx
4616 .hir_node_by_def_id(alias_to)
4617 .expect_item()
4618 .expect_impl()
4619 && let hir::TyKind::Ref(lifetime, _) = self_ty.kind
4620 {
4621 arguments.push((*argument, lifetime.ident.span));
4622 }
4623 }
4624 _ => {
4625 }
4627 }
4628 }
4629 }
4630
4631 if arguments.is_empty() {
4633 return None;
4634 }
4635
4636 let return_ty = sig.output().skip_binder();
4639 let mut return_span = fn_decl.output.span();
4640 if let hir::FnRetTy::Return(ty) = &fn_decl.output
4641 && let hir::TyKind::Ref(lifetime, _) = ty.kind
4642 {
4643 return_span = lifetime.ident.span;
4644 }
4645
4646 Some(AnnotatedBorrowFnSignature::NamedFunction {
4647 arguments,
4648 return_ty,
4649 return_span,
4650 })
4651 }
4652 ty::Ref(_, _, _) if is_closure => {
4653 let argument_span = fn_decl.inputs.first()?.span;
4657 let argument_ty = sig.inputs().skip_binder().first()?;
4658
4659 if let ty::Tuple(elems) = argument_ty.kind() {
4662 let &argument_ty = elems.first()?;
4663 if let ty::Ref(_, _, _) = argument_ty.kind() {
4664 return Some(AnnotatedBorrowFnSignature::Closure {
4665 argument_ty,
4666 argument_span,
4667 });
4668 }
4669 }
4670
4671 None
4672 }
4673 ty::Ref(_, _, _) => {
4674 let argument_span = fn_decl.inputs.first()?.span;
4677 let argument_ty = *sig.inputs().skip_binder().first()?;
4678
4679 let return_span = fn_decl.output.span();
4680 let return_ty = sig.output().skip_binder();
4681
4682 match argument_ty.kind() {
4684 ty::Ref(_, _, _) => {}
4685 _ => return None,
4686 }
4687
4688 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
4689 argument_ty,
4690 argument_span,
4691 return_ty,
4692 return_span,
4693 })
4694 }
4695 _ => {
4696 None
4699 }
4700 }
4701 }
4702}
4703
4704#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for AnnotatedBorrowFnSignature<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
AnnotatedBorrowFnSignature::NamedFunction {
arguments: __self_0,
return_ty: __self_1,
return_span: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"NamedFunction", "arguments", __self_0, "return_ty",
__self_1, "return_span", &__self_2),
AnnotatedBorrowFnSignature::AnonymousFunction {
argument_ty: __self_0,
argument_span: __self_1,
return_ty: __self_2,
return_span: __self_3 } =>
::core::fmt::Formatter::debug_struct_field4_finish(f,
"AnonymousFunction", "argument_ty", __self_0,
"argument_span", __self_1, "return_ty", __self_2,
"return_span", &__self_3),
AnnotatedBorrowFnSignature::Closure {
argument_ty: __self_0, argument_span: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Closure", "argument_ty", __self_0, "argument_span",
&__self_1),
}
}
}Debug)]
4705enum AnnotatedBorrowFnSignature<'tcx> {
4706 NamedFunction {
4707 arguments: Vec<(Ty<'tcx>, Span)>,
4708 return_ty: Ty<'tcx>,
4709 return_span: Span,
4710 },
4711 AnonymousFunction {
4712 argument_ty: Ty<'tcx>,
4713 argument_span: Span,
4714 return_ty: Ty<'tcx>,
4715 return_span: Span,
4716 },
4717 Closure {
4718 argument_ty: Ty<'tcx>,
4719 argument_span: Span,
4720 },
4721}
4722
4723fn find_for_loop_span<'hir>(
4727 tcx: TyCtxt<'hir>,
4728 body_id: hir::BodyId,
4729 issue_span: Span,
4730) -> Option<Span> {
4731 struct ExprFinder<'hir> {
4732 tcx: TyCtxt<'hir>,
4733 issue_span: Span,
4734 result: Option<Span>,
4735 }
4736 impl<'hir> Visitor<'hir> for ExprFinder<'hir> {
4737 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
4738 if let hir::ExprKind::Match(scrutinee, _, hir::MatchSource::ForLoopDesugar) = ex.kind
4739 && let hir::ExprKind::Call(path, [arg]) = scrutinee.kind
4740 && let hir::ExprKind::Path(qpath) = path.kind
4741 && self.tcx.qpath_is_lang_item(qpath, LangItem::IntoIterIntoIter)
4742 && arg.span.contains(self.issue_span)
4743 {
4744 self.result = Some(ex.span);
4745 return;
4746 }
4747 hir::intravisit::walk_expr(self, ex);
4748 }
4749 }
4750 let mut finder = ExprFinder { tcx, issue_span, result: None };
4751 finder.visit_expr(tcx.hir_body(body_id).value);
4752 finder.result
4753}
4754
4755impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
4756 pub(crate) fn emit(&self, cx: &MirBorrowckCtxt<'_, '_, 'tcx>, diag: &mut Diag<'_>) -> String {
4759 match self {
4760 &AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
4761 diag.span_label(
4762 argument_span,
4763 ::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)),
4764 );
4765
4766 cx.get_region_name_for_ty(argument_ty, 0)
4767 }
4768 &AnnotatedBorrowFnSignature::AnonymousFunction {
4769 argument_ty,
4770 argument_span,
4771 return_ty,
4772 return_span,
4773 } => {
4774 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
4775 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}`"));
4776
4777 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
4778 let types_equal = return_ty_name == argument_ty_name;
4779 diag.span_label(
4780 return_span,
4781 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}has type `{1}`",
if types_equal { "also " } else { "" }, return_ty_name))
})format!(
4782 "{}has type `{}`",
4783 if types_equal { "also " } else { "" },
4784 return_ty_name,
4785 ),
4786 );
4787
4788 diag.note(
4789 "argument and return type have the same lifetime due to lifetime elision rules",
4790 );
4791 diag.note(
4792 "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
4793 lifetime-syntax.html#lifetime-elision>",
4794 );
4795
4796 cx.get_region_name_for_ty(return_ty, 0)
4797 }
4798 AnnotatedBorrowFnSignature::NamedFunction { arguments, return_ty, return_span } => {
4799 let region_name = cx.get_region_name_for_ty(*return_ty, 0);
4801 for (_, argument_span) in arguments {
4802 diag.span_label(*argument_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("has lifetime `{0}`", region_name))
})format!("has lifetime `{region_name}`"));
4803 }
4804
4805 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}`",));
4806
4807 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!(
4808 "use data from the highlighted arguments which match the `{region_name}` lifetime of \
4809 the return type",
4810 ));
4811
4812 region_name
4813 }
4814 }
4815 }
4816}
4817
4818struct ReferencedStatementsVisitor<'a>(&'a [Span]);
4820
4821impl<'v> Visitor<'v> for ReferencedStatementsVisitor<'_> {
4822 type Result = ControlFlow<()>;
4823 fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) -> Self::Result {
4824 match s.kind {
4825 hir::StmtKind::Semi(expr) if self.0.contains(&expr.span) => ControlFlow::Break(()),
4826 _ => ControlFlow::Continue(()),
4827 }
4828 }
4829}
4830
4831struct BreakFinder {
4835 found_breaks: Vec<(hir::Destination, Span)>,
4836 found_continues: Vec<(hir::Destination, Span)>,
4837}
4838impl<'hir> Visitor<'hir> for BreakFinder {
4839 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
4840 match ex.kind {
4841 hir::ExprKind::Break(destination, _)
4842 if !ex.span.is_desugaring(DesugaringKind::ForLoop) =>
4843 {
4844 self.found_breaks.push((destination, ex.span));
4845 }
4846 hir::ExprKind::Continue(destination) => {
4847 self.found_continues.push((destination, ex.span));
4848 }
4849 _ => {}
4850 }
4851 hir::intravisit::walk_expr(self, ex);
4852 }
4853}
4854
4855struct ConditionVisitor<'tcx> {
4858 tcx: TyCtxt<'tcx>,
4859 spans: Vec<Span>,
4860 name: String,
4861 errors: Vec<ConditionError>,
4862}
4863
4864struct ConditionError {
4865 span: Span,
4866 label: String,
4867 kind: ConditionErrorKind,
4868}
4869
4870impl ConditionError {
4871 fn new(span: Span, kind: ConditionErrorKind, label: String) -> Self {
4872 Self { span, label, kind }
4873 }
4874}
4875
4876#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ConditionErrorKind { }
#[automatically_derived]
impl ::core::clone::Clone for ConditionErrorKind {
#[inline]
fn clone(&self) -> ConditionErrorKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ConditionErrorKind { }Copy)]
4877enum ConditionErrorKind {
4878 ConditionValue,
4879 Other,
4880}
4881
4882impl ConditionErrorKind {
4883 fn describes_condition_value(self) -> bool {
4884 #[allow(non_exhaustive_omitted_patterns)] match self {
Self::ConditionValue => true,
_ => false,
}matches!(self, Self::ConditionValue)
4885 }
4886}
4887
4888impl<'v, 'tcx> Visitor<'v> for ConditionVisitor<'tcx> {
4889 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
4890 match ex.kind {
4891 hir::ExprKind::If(cond, body, None) => {
4892 if ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break() {
4895 self.errors.push(ConditionError::new(
4896 cond.span,
4897 ConditionErrorKind::ConditionValue,
4898 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this `if` condition is `false`, {0} is not initialized",
self.name))
})format!(
4899 "if this `if` condition is `false`, {} is not initialized",
4900 self.name,
4901 ),
4902 ));
4903 self.errors.push(ConditionError::new(
4904 ex.span.shrink_to_hi(),
4905 ConditionErrorKind::Other,
4906 ::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),
4907 ));
4908 }
4909 }
4910 hir::ExprKind::If(cond, body, Some(other)) => {
4911 let a = ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break();
4914 let b = ReferencedStatementsVisitor(&self.spans).visit_expr(other).is_break();
4915 match (a, b) {
4916 (true, true) | (false, false) => {}
4917 (true, false) => {
4918 if other.span.is_desugaring(DesugaringKind::WhileLoop) {
4919 self.errors.push(ConditionError::new(
4920 cond.span,
4921 ConditionErrorKind::ConditionValue,
4922 ::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!(
4923 "if this condition isn't met and the `while` loop runs 0 \
4924 times, {} is not initialized",
4925 self.name
4926 ),
4927 ));
4928 } else {
4929 self.errors.push(ConditionError::new(
4930 body.span.shrink_to_hi().until(other.span),
4931 ConditionErrorKind::ConditionValue,
4932 ::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!(
4933 "if the `if` condition is `false` and this `else` arm is \
4934 executed, {} is not initialized",
4935 self.name
4936 ),
4937 ));
4938 }
4939 }
4940 (false, true) => {
4941 self.errors.push(ConditionError::new(
4942 cond.span,
4943 ConditionErrorKind::ConditionValue,
4944 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this condition is `true`, {0} is not initialized",
self.name))
})format!(
4945 "if this condition is `true`, {} is not initialized",
4946 self.name
4947 ),
4948 ));
4949 }
4950 }
4951 }
4952 hir::ExprKind::Match(e, arms, loop_desugar) => {
4953 let results: Vec<bool> = arms
4956 .iter()
4957 .map(|arm| ReferencedStatementsVisitor(&self.spans).visit_arm(arm).is_break())
4958 .collect();
4959 if results.iter().any(|x| *x) && !results.iter().all(|x| *x) {
4960 for (arm, seen) in arms.iter().zip(results) {
4961 if !seen {
4962 if loop_desugar == hir::MatchSource::ForLoopDesugar {
4963 self.errors.push(ConditionError::new(
4964 e.span,
4965 ConditionErrorKind::Other,
4966 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if the `for` loop runs 0 times, {0} is not initialized",
self.name))
})format!(
4967 "if the `for` loop runs 0 times, {} is not initialized",
4968 self.name
4969 ),
4970 ));
4971 } else if let Some(guard) = &arm.guard {
4972 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!(
4973 self.tcx.hir_node(arm.body.hir_id),
4974 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4975 ) {
4976 continue;
4977 }
4978 self.errors.push(ConditionError::new(
4979 arm.pat.span.to(guard.span),
4980 ConditionErrorKind::ConditionValue,
4981 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this pattern and condition are matched, {0} is not initialized",
self.name))
})format!(
4982 "if this pattern and condition are matched, {} is not \
4983 initialized",
4984 self.name
4985 ),
4986 ));
4987 } else {
4988 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!(
4989 self.tcx.hir_node(arm.body.hir_id),
4990 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4991 ) {
4992 continue;
4993 }
4994 self.errors.push(ConditionError::new(
4995 arm.pat.span,
4996 ConditionErrorKind::Other,
4997 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this pattern is matched, {0} is not initialized",
self.name))
})format!(
4998 "if this pattern is matched, {} is not initialized",
4999 self.name
5000 ),
5001 ));
5002 }
5003 }
5004 }
5005 }
5006 }
5007 _ => {}
5012 }
5013 walk_expr(self, ex);
5014 }
5015}