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