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