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