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