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