1use std::iter;
4use std::ops::ControlFlow;
5
6use either::Either;
7use hir::{ClosureKind, Path};
8use rustc_data_structures::fx::FxIndexSet;
9use rustc_data_structures::thin_vec::ThinVec;
10use rustc_errors::codes::*;
11use rustc_errors::{Applicability, Diag, MultiSpan, struct_span_code_err};
12use rustc_hir as hir;
13use rustc_hir::attrs::diagnostic::FormatArgs;
14use rustc_hir::def::{DefKind, Res};
15use rustc_hir::intravisit::{Visitor, walk_block, walk_expr};
16use rustc_hir::{
17 CoroutineDesugaring, CoroutineKind, CoroutineSource, LangItem, PatField, find_attr,
18};
19use rustc_middle::bug;
20use rustc_middle::hir::nested_filter::OnlyBodies;
21use rustc_middle::mir::{
22 self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, ConstraintCategory,
23 FakeBorrowKind, FakeReadCause, LocalDecl, LocalInfo, LocalKind, Location, MutBorrowKind,
24 Operand, Place, PlaceRef, PlaceTy, ProjectionElem, Rvalue, Statement, StatementKind,
25 Terminator, TerminatorKind, VarBindingForm, VarDebugInfoContents,
26};
27use rustc_middle::ty::print::PrintTraitRefExt as _;
28use rustc_middle::ty::{
29 self, PredicateKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor, Upcast,
30 suggest_constraining_type_params,
31};
32use rustc_mir_dataflow::move_paths::{InitKind, MoveOutIndex, MovePathIndex};
33use rustc_span::def_id::{DefId, LocalDefId};
34use rustc_span::hygiene::DesugaringKind;
35use rustc_span::{BytePos, ExpnKind, Ident, MacroKind, Span, Symbol, kw, sym};
36use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
37use rustc_trait_selection::error_reporting::traits::FindExprBySpan;
38use rustc_trait_selection::error_reporting::traits::call_kind::CallKind;
39use rustc_trait_selection::infer::InferCtxtExt;
40use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
41use rustc_trait_selection::traits::{
42 Obligation, ObligationCause, ObligationCtxt, supertrait_def_ids,
43};
44use tracing::{debug, instrument};
45
46use super::explain_borrow::{BorrowExplanation, LaterUseKind};
47use super::{DescribePlaceOpt, RegionName, RegionNameSource, UseSpans};
48use crate::borrow_set::{BorrowData, TwoPhaseActivation};
49use crate::diagnostics::conflict_errors::StorageDeadOrDrop::LocalStorageDead;
50use crate::diagnostics::{CapturedMessageOpt, call_kind, find_all_local_uses};
51use crate::prefixes::IsPrefixOf;
52use crate::{InitializationRequiringAction, MirBorrowckCtxt, WriteKind, borrowck_errors};
53
54#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MoveSite {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "MoveSite",
"moi", &self.moi, "traversed_back_edge",
&&self.traversed_back_edge)
}
}Debug)]
55struct MoveSite {
56 moi: MoveOutIndex,
59
60 traversed_back_edge: bool,
63}
64
65#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for StorageDeadOrDrop<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for StorageDeadOrDrop<'tcx> {
#[inline]
fn clone(&self) -> StorageDeadOrDrop<'tcx> {
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for StorageDeadOrDrop<'tcx> {
#[inline]
fn eq(&self, other: &StorageDeadOrDrop<'tcx>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(StorageDeadOrDrop::Destructor(__self_0),
StorageDeadOrDrop::Destructor(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for StorageDeadOrDrop<'tcx> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
}
}Eq, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for StorageDeadOrDrop<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
StorageDeadOrDrop::LocalStorageDead =>
::core::fmt::Formatter::write_str(f, "LocalStorageDead"),
StorageDeadOrDrop::BoxedStorageDead =>
::core::fmt::Formatter::write_str(f, "BoxedStorageDead"),
StorageDeadOrDrop::Destructor(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Destructor", &__self_0),
}
}
}Debug)]
67enum StorageDeadOrDrop<'tcx> {
68 LocalStorageDead,
69 BoxedStorageDead,
70 Destructor(Ty<'tcx>),
71}
72
73impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
74 pub(crate) fn report_use_of_moved_or_uninitialized(
75 &mut self,
76 location: Location,
77 desired_action: InitializationRequiringAction,
78 (moved_place, used_place, span): (PlaceRef<'tcx>, PlaceRef<'tcx>, Span),
79 mpi: MovePathIndex,
80 ) {
81 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:81",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(81u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
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!(
82 "report_use_of_moved_or_uninitialized: location={:?} desired_action={:?} \
83 moved_place={:?} used_place={:?} span={:?} mpi={:?}",
84 location, desired_action, moved_place, used_place, span, mpi
85 );
86
87 let use_spans =
88 self.move_spans(moved_place, location).or_else(|| self.borrow_spans(span, location));
89 let span = use_spans.args_or_use();
90
91 let (move_site_vec, maybe_reinitialized_locations) = self.get_moved_indexes(location, mpi);
92 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:92",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(92u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
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!(
93 "report_use_of_moved_or_uninitialized: move_site_vec={:?} use_spans={:?}",
94 move_site_vec, use_spans
95 );
96 let move_out_indices: Vec<_> =
97 move_site_vec.iter().map(|move_site| move_site.moi).collect();
98
99 if move_out_indices.is_empty() {
100 let root_local = used_place.local;
101
102 if !self.uninitialized_error_reported.insert(root_local) {
103 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:103",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(103u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
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!(
104 "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
105 root_local
106 );
107 return;
108 }
109
110 let err = self.report_use_of_uninitialized(
111 mpi,
112 used_place,
113 moved_place,
114 desired_action,
115 span,
116 use_spans,
117 );
118 self.buffer_error(err);
119 } else {
120 if let Some((reported_place, _)) = self.has_move_error(&move_out_indices) {
121 if used_place.is_prefix_of(*reported_place) {
122 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:122",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(122u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized place: error suppressed mois={0:?}",
move_out_indices) as &dyn Value))])
});
} else { ; }
};debug!(
123 "report_use_of_moved_or_uninitialized place: error suppressed mois={:?}",
124 move_out_indices
125 );
126 return;
127 }
128 }
129
130 let is_partial_move = move_site_vec.iter().any(|move_site| {
131 let move_out = self.move_data.moves[(*move_site).moi];
132 let moved_place = &self.move_data.move_paths[move_out.path].place;
133 let is_box_move = moved_place.as_ref().projection == [ProjectionElem::Deref]
135 && self.body.local_decls[moved_place.local].ty.is_box();
136
137 !is_box_move
138 && used_place != moved_place.as_ref()
139 && used_place.is_prefix_of(moved_place.as_ref())
140 });
141
142 let partial_str = if is_partial_move { "partial " } else { "" };
143 let partially_str = if is_partial_move { "partially " } else { "" };
144
145 let (on_move_message, on_move_label, on_move_notes) = if let ty::Adt(item_def, args) =
146 self.body.local_decls[moved_place.local].ty.kind()
147 && let Some(Some(directive)) = {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(item_def.did(),
&self.infcx.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(OnMove { directive, .. }) => {
break 'done Some(directive);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(self.infcx.tcx, item_def.did(), OnMove { directive, .. } => directive)
148 {
149 let item_name = self.infcx.tcx.item_name(item_def.did()).to_string();
150 let mut generic_args: Vec<_> = self
151 .infcx
152 .tcx
153 .generics_of(item_def.did())
154 .own_params
155 .iter()
156 .filter_map(|param| Some((param.name, args[param.index as usize].to_string())))
157 .collect();
158 generic_args.push((kw::SelfUpper, item_name));
159
160 let args = FormatArgs {
161 this: String::new(),
162 trait_sugared: String::new(),
163 item_context: "",
164 generic_args,
165 };
166 (
167 directive.message.as_ref().map(|e| e.1.format(&args)),
168 directive.label.as_ref().map(|e| e.1.format(&args)),
169 directive.notes.iter().map(|e| e.format(&args)).collect(),
170 )
171 } else {
172 (None, None, ThinVec::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_span: Option<Span>,
908 }
909
910 impl<'v> Visitor<'v> for LetVisitor {
911 fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) {
912 if self.sugg_span.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(..) = pat.kind
921 && span.contains(self.decl_span)
922 {
923 self.sugg_span = ty.map_or(Some(self.decl_span), |ty| Some(ty.span));
924 }
925 hir::intravisit::walk_stmt(self, ex);
926 }
927 }
928
929 let mut visitor = LetVisitor { decl_span, sugg_span: None };
930 visitor.visit_body(&body);
931 if let Some(span) = visitor.sugg_span {
932 self.suggest_assign_value(&mut err, moved_place, span);
933 }
934 }
935 err
936 }
937
938 fn suggest_assign_value(
939 &self,
940 err: &mut Diag<'_>,
941 moved_place: PlaceRef<'tcx>,
942 sugg_span: Span,
943 ) {
944 let ty = moved_place.ty(self.body, self.infcx.tcx).ty;
945 {
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:945",
"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(945u32),
::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());
946
947 let Some(assign_value) = self.infcx.err_ctxt().ty_kind_suggestion(self.infcx.param_env, ty)
948 else {
949 return;
950 };
951
952 err.span_suggestion_verbose(
953 sugg_span.shrink_to_hi(),
954 "consider assigning a value",
955 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" = {0}", assign_value))
})format!(" = {assign_value}"),
956 Applicability::MaybeIncorrect,
957 );
958 }
959
960 fn suggest_hoisting_call_outside_loop(&self, err: &mut Diag<'_>, expr: &hir::Expr<'_>) -> bool {
965 let tcx = self.infcx.tcx;
966 let mut can_suggest_clone = true;
967
968 let local_hir_id = if let hir::ExprKind::Path(hir::QPath::Resolved(
972 _,
973 hir::Path { res: hir::def::Res::Local(local_hir_id), .. },
974 )) = expr.kind
975 {
976 Some(local_hir_id)
977 } else {
978 None
981 };
982
983 struct Finder {
987 hir_id: hir::HirId,
988 }
989 impl<'hir> Visitor<'hir> for Finder {
990 type Result = ControlFlow<()>;
991 fn visit_pat(&mut self, pat: &'hir hir::Pat<'hir>) -> Self::Result {
992 if pat.hir_id == self.hir_id {
993 return ControlFlow::Break(());
994 }
995 hir::intravisit::walk_pat(self, pat)
996 }
997 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) -> Self::Result {
998 if ex.hir_id == self.hir_id {
999 return ControlFlow::Break(());
1000 }
1001 hir::intravisit::walk_expr(self, ex)
1002 }
1003 }
1004 let mut parent = None;
1006 let mut outer_most_loop: Option<&hir::Expr<'_>> = None;
1008 for (_, node) in tcx.hir_parent_iter(expr.hir_id) {
1009 let e = match node {
1010 hir::Node::Expr(e) => e,
1011 hir::Node::LetStmt(hir::LetStmt { els: Some(els), .. }) => {
1012 let mut finder = BreakFinder { found_breaks: ::alloc::vec::Vec::new()vec![], found_continues: ::alloc::vec::Vec::new()vec![] };
1013 finder.visit_block(els);
1014 if !finder.found_breaks.is_empty() {
1015 can_suggest_clone = false;
1020 }
1021 continue;
1022 }
1023 _ => continue,
1024 };
1025 if let Some(&hir_id) = local_hir_id {
1026 if (Finder { hir_id }).visit_expr(e).is_break() {
1027 break;
1030 }
1031 }
1032 if parent.is_none() {
1033 parent = Some(e);
1034 }
1035 match e.kind {
1036 hir::ExprKind::Let(_) => {
1037 match tcx.parent_hir_node(e.hir_id) {
1038 hir::Node::Expr(hir::Expr {
1039 kind: hir::ExprKind::If(cond, ..), ..
1040 }) => {
1041 if (Finder { hir_id: expr.hir_id }).visit_expr(cond).is_break() {
1042 can_suggest_clone = false;
1048 }
1049 }
1050 _ => {}
1051 }
1052 }
1053 hir::ExprKind::Loop(..) => {
1054 outer_most_loop = Some(e);
1055 }
1056 _ => {}
1057 }
1058 }
1059 let loop_count: usize = tcx
1060 .hir_parent_iter(expr.hir_id)
1061 .map(|(_, node)| match node {
1062 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Loop(..), .. }) => 1,
1063 _ => 0,
1064 })
1065 .sum();
1066
1067 let sm = tcx.sess.source_map();
1068 if let Some(in_loop) = outer_most_loop {
1069 let mut finder = BreakFinder { found_breaks: ::alloc::vec::Vec::new()vec![], found_continues: ::alloc::vec::Vec::new()vec![] };
1070 finder.visit_expr(in_loop);
1071 let spans = finder
1073 .found_breaks
1074 .iter()
1075 .chain(finder.found_continues.iter())
1076 .map(|(_, span)| *span)
1077 .filter(|span| {
1078 !#[allow(non_exhaustive_omitted_patterns)] match span.desugaring_kind() {
Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop) => true,
_ => false,
}matches!(
1079 span.desugaring_kind(),
1080 Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop)
1081 )
1082 })
1083 .collect::<Vec<Span>>();
1084 let loop_spans: Vec<_> = tcx
1086 .hir_parent_iter(expr.hir_id)
1087 .filter_map(|(_, node)| match node {
1088 hir::Node::Expr(hir::Expr { span, kind: hir::ExprKind::Loop(..), .. }) => {
1089 Some(*span)
1090 }
1091 _ => None,
1092 })
1093 .collect();
1094 if !spans.is_empty() && loop_count > 1 {
1097 let mut lines: Vec<_> =
1101 loop_spans.iter().map(|sp| sm.lookup_char_pos(sp.lo()).line).collect();
1102 lines.sort();
1103 lines.dedup();
1104 let fmt_span = |span: Span| {
1105 if lines.len() == loop_spans.len() {
1106 ::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)
1107 } else {
1108 sm.span_to_diagnostic_string(span)
1109 }
1110 };
1111 let mut spans: MultiSpan = spans.into();
1112 for (desc, elements) in [
1114 ("`break` exits", &finder.found_breaks),
1115 ("`continue` advances", &finder.found_continues),
1116 ] {
1117 for (destination, sp) in elements {
1118 if let Ok(hir_id) = destination.target_id
1119 && let hir::Node::Expr(expr) = tcx.hir_node(hir_id)
1120 && !#[allow(non_exhaustive_omitted_patterns)] match sp.desugaring_kind() {
Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop) => true,
_ => false,
}matches!(
1121 sp.desugaring_kind(),
1122 Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop)
1123 )
1124 {
1125 spans.push_span_label(
1126 *sp,
1127 ::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)),
1128 );
1129 }
1130 }
1131 }
1132 for span in loop_spans {
1134 spans.push_span_label(sm.guess_head_span(span), "");
1135 }
1136
1137 err.span_note(spans, "verify that your loop breaking logic is correct");
1149 }
1150 if let Some(parent) = parent
1151 && let hir::ExprKind::MethodCall(..) | hir::ExprKind::Call(..) = parent.kind
1152 {
1153 let span = in_loop.span;
1158 if !finder.found_breaks.is_empty()
1159 && let Ok(value) = sm.span_to_snippet(parent.span)
1160 {
1161 let indent = if let Some(indent) = sm.indentation_before(span) {
1164 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}", indent))
})format!("\n{indent}")
1165 } else {
1166 " ".to_string()
1167 };
1168 err.multipart_suggestion(
1169 "consider moving the expression out of the loop so it is only moved once",
1170 ::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![
1171 (span.shrink_to_lo(), format!("let mut value = {value};{indent}")),
1172 (parent.span, "value".to_string()),
1173 ],
1174 Applicability::MaybeIncorrect,
1175 );
1176 }
1177 }
1178 }
1179 can_suggest_clone
1180 }
1181
1182 fn suggest_cloning_on_functional_record_update(
1185 &self,
1186 err: &mut Diag<'_>,
1187 ty: Ty<'tcx>,
1188 expr: &hir::Expr<'_>,
1189 ) {
1190 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1191 let hir::ExprKind::Struct(struct_qpath, fields, hir::StructTailExpr::Base(base)) =
1192 expr.kind
1193 else {
1194 return;
1195 };
1196 let hir::QPath::Resolved(_, path) = struct_qpath else { return };
1197 let hir::def::Res::Def(_, def_id) = path.res else { return };
1198 let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id) else { return };
1199 let ty::Adt(def, args) = expr_ty.kind() else { return };
1200 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = base.kind else { return };
1201 let (hir::def::Res::Local(_)
1202 | hir::def::Res::Def(
1203 DefKind::Const { .. }
1204 | DefKind::ConstParam
1205 | DefKind::Static { .. }
1206 | DefKind::AssocConst { .. },
1207 _,
1208 )) = path.res
1209 else {
1210 return;
1211 };
1212 let Ok(base_str) = self.infcx.tcx.sess.source_map().span_to_snippet(base.span) else {
1213 return;
1214 };
1215
1216 let mut final_field_count = fields.len();
1222 let Some(variant) = def.variants().iter().find(|variant| variant.def_id == def_id) else {
1223 return;
1226 };
1227 let mut sugg = ::alloc::vec::Vec::new()vec![];
1228 for field in &variant.fields {
1229 let field_ty = field.ty(self.infcx.tcx, args);
1233 let ident = field.ident(self.infcx.tcx);
1234 if field_ty == ty && fields.iter().all(|field| field.ident.name != ident.name) {
1235 sugg.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}.{0}.clone()", ident,
base_str))
})format!("{ident}: {base_str}.{ident}.clone()"));
1237 final_field_count += 1;
1238 }
1239 }
1240 let (span, sugg) = match fields {
1241 [.., last] => (
1242 if final_field_count == variant.fields.len() {
1243 last.span.shrink_to_hi().with_hi(base.span.hi())
1245 } else {
1246 last.span.shrink_to_hi()
1247 },
1248 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", sugg.join(", ")))
})format!(", {}", sugg.join(", ")),
1249 ),
1250 [] => (
1252 expr.span.with_lo(struct_qpath.span().hi()),
1253 if final_field_count == variant.fields.len() {
1254 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{ {0} }}", sugg.join(", ")))
})format!(" {{ {} }}", sugg.join(", "))
1256 } else {
1257 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{ {0}, ..{1} }}",
sugg.join(", "), base_str))
})format!(" {{ {}, ..{base_str} }}", sugg.join(", "))
1258 },
1259 ),
1260 };
1261 let prefix = if !self.implements_clone(ty) {
1262 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`");
1263 if let ty::Adt(def, _) = ty.kind() {
1264 err.span_note(self.infcx.tcx.def_span(def.did()), msg);
1265 } else {
1266 err.note(msg);
1267 }
1268 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if `{0}` implemented `Clone`, you could ",
ty))
})format!("if `{ty}` implemented `Clone`, you could ")
1269 } else {
1270 String::new()
1271 };
1272 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!(
1273 "{prefix}clone the value from the field instead of using the functional record update \
1274 syntax",
1275 );
1276 err.span_suggestion_verbose(span, msg, sugg, Applicability::MachineApplicable);
1277 }
1278
1279 pub(crate) fn suggest_cloning(
1280 &self,
1281 err: &mut Diag<'_>,
1282 place: PlaceRef<'tcx>,
1283 ty: Ty<'tcx>,
1284 expr: &'tcx hir::Expr<'tcx>,
1285 use_spans: Option<UseSpans<'tcx>>,
1286 ) {
1287 if let hir::ExprKind::Struct(_, _, hir::StructTailExpr::Base(_)) = expr.kind {
1288 self.suggest_cloning_on_functional_record_update(err, ty, expr);
1293 return;
1294 }
1295
1296 if self.implements_clone(ty) {
1297 if self.in_move_closure(expr) {
1298 if let Some(name) = self.describe_place(place) {
1299 self.suggest_clone_of_captured_var_in_move_closure(err, &name, use_spans);
1300 }
1301 } else {
1302 self.suggest_cloning_inner(err, ty, expr);
1303 }
1304 } else if let ty::Adt(def, args) = ty.kind()
1305 && let Some(local_did) = def.did().as_local()
1306 && def.variants().iter().all(|variant| {
1307 variant
1308 .fields
1309 .iter()
1310 .all(|field| self.implements_clone(field.ty(self.infcx.tcx, args)))
1311 })
1312 {
1313 let ty_span = self.infcx.tcx.def_span(def.did());
1314 let mut span: MultiSpan = ty_span.into();
1315 let mut derive_clone = false;
1316 self.infcx.tcx.for_each_relevant_impl(
1317 self.infcx.tcx.lang_items().clone_trait().unwrap(),
1318 ty,
1319 |def_id| {
1320 if self.infcx.tcx.is_automatically_derived(def_id) {
1321 derive_clone = true;
1322 span.push_span_label(
1323 self.infcx.tcx.def_span(def_id),
1324 "derived `Clone` adds implicit bounds on type parameters",
1325 );
1326 if let Some(generics) = self.infcx.tcx.hir_get_generics(local_did) {
1327 for param in generics.params {
1328 if let hir::GenericParamKind::Type { .. } = param.kind {
1329 span.push_span_label(
1330 param.span,
1331 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("introduces an implicit `{0}: Clone` bound",
param.name.ident()))
})format!(
1332 "introduces an implicit `{}: Clone` bound",
1333 param.name.ident()
1334 ),
1335 );
1336 }
1337 }
1338 }
1339 }
1340 },
1341 );
1342 let msg = if !derive_clone {
1343 span.push_span_label(
1344 ty_span,
1345 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider {0}implementing `Clone` for this type",
if derive_clone { "manually " } else { "" }))
})format!(
1346 "consider {}implementing `Clone` for this type",
1347 if derive_clone { "manually " } else { "" }
1348 ),
1349 );
1350 ::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")
1351 } else {
1352 ::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")
1353 };
1354 span.push_span_label(expr.span, "you could clone this value");
1355 err.span_note(span, msg);
1356 if derive_clone {
1357 err.help("consider manually implementing `Clone` to avoid undesired bounds");
1358 }
1359 } else if let ty::Param(param) = ty.kind()
1360 && let Some(_clone_trait_def) = self.infcx.tcx.lang_items().clone_trait()
1361 && let generics = self.infcx.tcx.generics_of(self.mir_def_id())
1362 && let generic_param = generics.type_param(*param, self.infcx.tcx)
1363 && let param_span = self.infcx.tcx.def_span(generic_param.def_id)
1364 && if let Some(UseSpans::FnSelfUse { kind, .. }) = use_spans
1365 && let CallKind::FnCall { fn_trait_id, self_ty } = kind
1366 && let ty::Param(_) = self_ty.kind()
1367 && ty == self_ty
1368 && self.infcx.tcx.fn_trait_kind_from_def_id(fn_trait_id).is_some()
1369 {
1370 false
1372 } else {
1373 true
1374 }
1375 {
1376 let mut span: MultiSpan = param_span.into();
1377 span.push_span_label(
1378 param_span,
1379 "consider constraining this type parameter with `Clone`",
1380 );
1381 span.push_span_label(expr.span, "you could clone this value");
1382 err.span_help(
1383 span,
1384 ::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"),
1385 );
1386 } else if let ty::Adt(_, _) = ty.kind()
1387 && let Some(clone_trait) = self.infcx.tcx.lang_items().clone_trait()
1388 {
1389 let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1392 let cause = ObligationCause::misc(expr.span, self.mir_def_id());
1393 ocx.register_bound(cause, self.infcx.param_env, ty, clone_trait);
1394 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1395 if errors.iter().all(|error| {
1396 match error.obligation.predicate.as_clause().and_then(|c| c.as_trait_clause()) {
1397 Some(clause) => match clause.self_ty().skip_binder().kind() {
1398 ty::Adt(def, _) => def.did().is_local() && clause.def_id() == clone_trait,
1399 _ => false,
1400 },
1401 None => false,
1402 }
1403 }) {
1404 let mut type_spans = ::alloc::vec::Vec::new()vec![];
1405 let mut types = FxIndexSet::default();
1406 for clause in errors
1407 .iter()
1408 .filter_map(|e| e.obligation.predicate.as_clause())
1409 .filter_map(|c| c.as_trait_clause())
1410 {
1411 let ty::Adt(def, _) = clause.self_ty().skip_binder().kind() else { continue };
1412 type_spans.push(self.infcx.tcx.def_span(def.did()));
1413 types.insert(
1414 self.infcx
1415 .tcx
1416 .short_string(clause.self_ty().skip_binder(), &mut err.long_ty_path()),
1417 );
1418 }
1419 let mut span: MultiSpan = type_spans.clone().into();
1420 for sp in type_spans {
1421 span.push_span_label(sp, "consider implementing `Clone` for this type");
1422 }
1423 span.push_span_label(expr.span, "you could clone this value");
1424 let types: Vec<_> = types.into_iter().collect();
1425 let msg = match &types[..] {
1426 [only] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", only))
})format!("`{only}`"),
1427 [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!(
1428 "{} and `{last}`",
1429 head.iter().map(|t| format!("`{t}`")).collect::<Vec<_>>().join(", ")
1430 ),
1431 [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1432 };
1433 err.span_note(
1434 span,
1435 ::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"),
1436 );
1437 }
1438 }
1439 }
1440
1441 pub(crate) fn implements_clone(&self, ty: Ty<'tcx>) -> bool {
1442 let Some(clone_trait_def) = self.infcx.tcx.lang_items().clone_trait() else { return false };
1443 self.infcx
1444 .type_implements_trait(clone_trait_def, [ty], self.infcx.param_env)
1445 .must_apply_modulo_regions()
1446 }
1447
1448 pub(crate) fn clone_on_reference(&self, expr: &hir::Expr<'_>) -> Option<Span> {
1451 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1452 if let hir::ExprKind::MethodCall(segment, rcvr, args, span) = expr.kind
1453 && let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id)
1454 && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
1455 && rcvr_ty == expr_ty
1456 && segment.ident.name == sym::clone
1457 && args.is_empty()
1458 {
1459 Some(span)
1460 } else {
1461 None
1462 }
1463 }
1464
1465 fn in_move_closure(&self, expr: &hir::Expr<'_>) -> bool {
1466 for (_, node) in self.infcx.tcx.hir_parent_iter(expr.hir_id) {
1467 if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) = node
1468 && let hir::CaptureBy::Value { .. } = closure.capture_clause
1469 {
1470 return true;
1472 }
1473 }
1474 false
1475 }
1476
1477 fn suggest_cloning_inner(
1478 &self,
1479 err: &mut Diag<'_>,
1480 ty: Ty<'tcx>,
1481 expr: &hir::Expr<'_>,
1482 ) -> bool {
1483 let tcx = self.infcx.tcx;
1484
1485 if let ExpnKind::Macro(MacroKind::Derive, _) = self.body.span.ctxt().outer_expn_data().kind
1487 {
1488 return false;
1489 }
1490 if let Some(_) = self.clone_on_reference(expr) {
1491 return false;
1494 }
1495 if self.in_move_closure(expr) {
1498 return false;
1499 }
1500 if let hir::ExprKind::Closure(_) = expr.kind {
1503 return false;
1504 }
1505 let mut suggestion =
1507 if let Some(symbol) = tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1508 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}.clone()", symbol))
})format!(": {symbol}.clone()")
1509 } else {
1510 ".clone()".to_owned()
1511 };
1512 let mut sugg = Vec::with_capacity(2);
1513 let mut inner_expr = expr;
1514 let mut is_raw_ptr = false;
1515 let typeck_result = self.infcx.tcx.typeck(self.mir_def_id());
1516 while let hir::ExprKind::AddrOf(.., inner) | hir::ExprKind::Unary(hir::UnOp::Deref, inner) =
1518 &inner_expr.kind
1519 {
1520 if let hir::ExprKind::AddrOf(_, hir::Mutability::Mut, _) = inner_expr.kind {
1521 return false;
1524 }
1525 inner_expr = inner;
1526 if let Some(inner_type) = typeck_result.node_type_opt(inner.hir_id) {
1527 if #[allow(non_exhaustive_omitted_patterns)] match inner_type.kind() {
ty::RawPtr(..) => true,
_ => false,
}matches!(inner_type.kind(), ty::RawPtr(..)) {
1528 is_raw_ptr = true;
1529 break;
1530 }
1531 }
1532 }
1533 if inner_expr.span.lo() != expr.span.lo() && !is_raw_ptr {
1536 sugg.push((expr.span.with_hi(inner_expr.span.lo()), String::new()));
1538 }
1539 let span = if inner_expr.span.hi() != expr.span.hi() {
1541 if is_raw_ptr {
1543 expr.span.shrink_to_hi()
1544 } else {
1545 expr.span.with_lo(inner_expr.span.hi())
1547 }
1548 } else {
1549 if is_raw_ptr {
1550 sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
1551 suggestion = ").clone()".to_string();
1552 }
1553 expr.span.shrink_to_hi()
1554 };
1555 sugg.push((span, suggestion));
1556 let msg = if let ty::Adt(def, _) = ty.kind()
1557 && [tcx.get_diagnostic_item(sym::Arc), tcx.get_diagnostic_item(sym::Rc)]
1558 .contains(&Some(def.did()))
1559 {
1560 "clone the value to increment its reference count"
1561 } else {
1562 "consider cloning the value if the performance cost is acceptable"
1563 };
1564 err.multipart_suggestion(msg, sugg, Applicability::MachineApplicable);
1565 true
1566 }
1567
1568 fn suggest_adding_bounds(&self, err: &mut Diag<'_>, ty: Ty<'tcx>, def_id: DefId, span: Span) {
1569 let tcx = self.infcx.tcx;
1570 let generics = tcx.generics_of(self.mir_def_id());
1571
1572 let Some(hir_generics) =
1573 tcx.hir_get_generics(tcx.typeck_root_def_id_local(self.mir_def_id()))
1574 else {
1575 return;
1576 };
1577 let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1579 let cause = ObligationCause::misc(span, self.mir_def_id());
1580
1581 ocx.register_bound(cause, self.infcx.param_env, ty, def_id);
1582 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1583
1584 let predicates: Result<Vec<_>, _> = errors
1586 .into_iter()
1587 .map(|err| match err.obligation.predicate.kind().skip_binder() {
1588 PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => {
1589 match *predicate.self_ty().kind() {
1590 ty::Param(param_ty) => Ok((
1591 generics.type_param(param_ty, tcx),
1592 predicate.trait_ref.print_trait_sugared().to_string(),
1593 Some(predicate.trait_ref.def_id),
1594 )),
1595 _ => Err(()),
1596 }
1597 }
1598 _ => Err(()),
1599 })
1600 .collect();
1601
1602 if let Ok(predicates) = predicates {
1603 suggest_constraining_type_params(
1604 tcx,
1605 hir_generics,
1606 err,
1607 predicates.iter().map(|(param, constraint, def_id)| {
1608 (param.name.as_str(), &**constraint, *def_id)
1609 }),
1610 None,
1611 );
1612 }
1613 }
1614
1615 pub(crate) fn report_move_out_while_borrowed(
1616 &mut self,
1617 location: Location,
1618 (place, span): (Place<'tcx>, Span),
1619 borrow: &BorrowData<'tcx>,
1620 ) {
1621 {
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:1621",
"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(1621u32),
::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!(
1622 "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
1623 location, place, span, borrow
1624 );
1625 let value_msg = self.describe_any_place(place.as_ref());
1626 let borrow_msg = self.describe_any_place(borrow.borrowed_place.as_ref());
1627
1628 let borrow_spans = self.retrieve_borrow_spans(borrow);
1629 let borrow_span = borrow_spans.args_or_use();
1630
1631 let move_spans = self.move_spans(place.as_ref(), location);
1632 let span = move_spans.args_or_use();
1633
1634 let mut err = self.cannot_move_when_borrowed(
1635 span,
1636 borrow_span,
1637 &self.describe_any_place(place.as_ref()),
1638 &borrow_msg,
1639 &value_msg,
1640 );
1641 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1642
1643 borrow_spans.var_path_only_subdiag(&mut err, crate::InitializationRequiringAction::Borrow);
1644
1645 move_spans.var_subdiag(&mut err, None, |kind, var_span| {
1646 use crate::session_diagnostics::CaptureVarCause::*;
1647 match kind {
1648 hir::ClosureKind::Coroutine(_) => MoveUseInCoroutine { var_span },
1649 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1650 MoveUseInClosure { var_span }
1651 }
1652 }
1653 });
1654
1655 self.explain_why_borrow_contains_point(location, borrow, None)
1656 .add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
1657 self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
1658 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1659 if let Some(expr) = self.find_expr(borrow_span) {
1660 if let hir::ExprKind::AddrOf(_, _, borrowed_expr) = expr.kind
1662 && let Some(ty) = typeck_results.expr_ty_opt(borrowed_expr)
1663 {
1664 self.suggest_cloning(&mut err, place.as_ref(), ty, borrowed_expr, Some(move_spans));
1665 } else if typeck_results.expr_adjustments(expr).first().is_some_and(|adj| {
1666 #[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!(
1667 adj.kind,
1668 ty::adjustment::Adjust::Borrow(ty::adjustment::AutoBorrow::Ref(
1669 ty::adjustment::AutoBorrowMutability::Not
1670 | ty::adjustment::AutoBorrowMutability::Mut {
1671 allow_two_phase_borrow: ty::adjustment::AllowTwoPhase::No
1672 }
1673 ))
1674 )
1675 }) && let Some(ty) = typeck_results.expr_ty_opt(expr)
1676 {
1677 self.suggest_cloning(&mut err, place.as_ref(), ty, expr, Some(move_spans));
1678 }
1679 }
1680 self.buffer_error(err);
1681 }
1682
1683 pub(crate) fn report_use_while_mutably_borrowed(
1684 &self,
1685 location: Location,
1686 (place, _span): (Place<'tcx>, Span),
1687 borrow: &BorrowData<'tcx>,
1688 ) -> Diag<'infcx> {
1689 let borrow_spans = self.retrieve_borrow_spans(borrow);
1690 let borrow_span = borrow_spans.args_or_use();
1691
1692 let use_spans = self.move_spans(place.as_ref(), location);
1695 let span = use_spans.var_or_use();
1696
1697 let mut err = self.cannot_use_when_mutably_borrowed(
1701 span,
1702 &self.describe_any_place(place.as_ref()),
1703 borrow_span,
1704 &self.describe_any_place(borrow.borrowed_place.as_ref()),
1705 );
1706 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1707
1708 borrow_spans.var_subdiag(&mut err, Some(borrow.kind), |kind, var_span| {
1709 use crate::session_diagnostics::CaptureVarCause::*;
1710 let place = &borrow.borrowed_place;
1711 let desc_place = self.describe_any_place(place.as_ref());
1712 match kind {
1713 hir::ClosureKind::Coroutine(_) => {
1714 BorrowUsePlaceCoroutine { place: desc_place, var_span, is_single_var: true }
1715 }
1716 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1717 BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: true }
1718 }
1719 }
1720 });
1721
1722 self.explain_why_borrow_contains_point(location, borrow, None)
1723 .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
1724 err
1725 }
1726
1727 pub(crate) fn report_conflicting_borrow(
1728 &self,
1729 location: Location,
1730 (place, span): (Place<'tcx>, Span),
1731 gen_borrow_kind: BorrowKind,
1732 issued_borrow: &BorrowData<'tcx>,
1733 ) -> Diag<'infcx> {
1734 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
1735 let issued_span = issued_spans.args_or_use();
1736
1737 let borrow_spans = self.borrow_spans(span, location);
1738 let span = borrow_spans.args_or_use();
1739
1740 let container_name = if issued_spans.for_coroutine() || borrow_spans.for_coroutine() {
1741 "coroutine"
1742 } else {
1743 "closure"
1744 };
1745
1746 let (desc_place, msg_place, msg_borrow, union_type_name) =
1747 self.describe_place_for_conflicting_borrow(place, issued_borrow.borrowed_place);
1748
1749 let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
1750 let second_borrow_desc = if explanation.is_explained() { "second " } else { "" };
1751
1752 let first_borrow_desc;
1754 let mut err = match (gen_borrow_kind, issued_borrow.kind) {
1755 (
1756 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1757 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1758 ) => {
1759 first_borrow_desc = "mutable ";
1760 let mut err = self.cannot_reborrow_already_borrowed(
1761 span,
1762 &desc_place,
1763 &msg_place,
1764 "immutable",
1765 issued_span,
1766 "it",
1767 "mutable",
1768 &msg_borrow,
1769 None,
1770 );
1771 self.suggest_slice_method_if_applicable(
1772 &mut err,
1773 place,
1774 issued_borrow.borrowed_place,
1775 span,
1776 issued_span,
1777 );
1778 err
1779 }
1780 (
1781 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1782 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1783 ) => {
1784 first_borrow_desc = "immutable ";
1785 let mut err = self.cannot_reborrow_already_borrowed(
1786 span,
1787 &desc_place,
1788 &msg_place,
1789 "mutable",
1790 issued_span,
1791 "it",
1792 "immutable",
1793 &msg_borrow,
1794 None,
1795 );
1796 self.suggest_slice_method_if_applicable(
1797 &mut err,
1798 place,
1799 issued_borrow.borrowed_place,
1800 span,
1801 issued_span,
1802 );
1803 self.suggest_binding_for_closure_capture_self(&mut err, &issued_spans);
1804 self.suggest_using_closure_argument_instead_of_capture(
1805 &mut err,
1806 issued_borrow.borrowed_place,
1807 &issued_spans,
1808 );
1809 err
1810 }
1811
1812 (
1813 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1814 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1815 ) => {
1816 first_borrow_desc = "first ";
1817 let mut err = self.cannot_mutably_borrow_multiply(
1818 span,
1819 &desc_place,
1820 &msg_place,
1821 issued_span,
1822 &msg_borrow,
1823 None,
1824 );
1825 self.suggest_slice_method_if_applicable(
1826 &mut err,
1827 place,
1828 issued_borrow.borrowed_place,
1829 span,
1830 issued_span,
1831 );
1832 self.suggest_using_closure_argument_instead_of_capture(
1833 &mut err,
1834 issued_borrow.borrowed_place,
1835 &issued_spans,
1836 );
1837 self.explain_iterator_advancement_in_for_loop_if_applicable(
1838 &mut err,
1839 span,
1840 &issued_spans,
1841 );
1842 err
1843 }
1844
1845 (
1846 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1847 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1848 ) => {
1849 first_borrow_desc = "first ";
1850 self.cannot_uniquely_borrow_by_two_closures(span, &desc_place, issued_span, None)
1851 }
1852
1853 (BorrowKind::Mut { .. }, BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
1854 if let Some(immutable_section_description) =
1855 self.classify_immutable_section(issued_borrow.assigned_place)
1856 {
1857 let mut err = self.cannot_mutate_in_immutable_section(
1858 span,
1859 issued_span,
1860 &desc_place,
1861 immutable_section_description,
1862 "mutably borrow",
1863 );
1864 borrow_spans.var_subdiag(
1865 &mut err,
1866 Some(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }),
1867 |kind, var_span| {
1868 use crate::session_diagnostics::CaptureVarCause::*;
1869 match kind {
1870 hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1871 place: desc_place,
1872 var_span,
1873 is_single_var: true,
1874 },
1875 hir::ClosureKind::Closure
1876 | hir::ClosureKind::CoroutineClosure(_) => BorrowUsePlaceClosure {
1877 place: desc_place,
1878 var_span,
1879 is_single_var: true,
1880 },
1881 }
1882 },
1883 );
1884 return err;
1885 } else {
1886 first_borrow_desc = "immutable ";
1887 self.cannot_reborrow_already_borrowed(
1888 span,
1889 &desc_place,
1890 &msg_place,
1891 "mutable",
1892 issued_span,
1893 "it",
1894 "immutable",
1895 &msg_borrow,
1896 None,
1897 )
1898 }
1899 }
1900
1901 (BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }, _) => {
1902 first_borrow_desc = "first ";
1903 self.cannot_uniquely_borrow_by_one_closure(
1904 span,
1905 container_name,
1906 &desc_place,
1907 "",
1908 issued_span,
1909 "it",
1910 "",
1911 None,
1912 )
1913 }
1914
1915 (
1916 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1917 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1918 ) => {
1919 first_borrow_desc = "first ";
1920 self.cannot_reborrow_already_uniquely_borrowed(
1921 span,
1922 container_name,
1923 &desc_place,
1924 "",
1925 "immutable",
1926 issued_span,
1927 "",
1928 None,
1929 second_borrow_desc,
1930 )
1931 }
1932
1933 (BorrowKind::Mut { .. }, BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }) => {
1934 first_borrow_desc = "first ";
1935 self.cannot_reborrow_already_uniquely_borrowed(
1936 span,
1937 container_name,
1938 &desc_place,
1939 "",
1940 "mutable",
1941 issued_span,
1942 "",
1943 None,
1944 second_borrow_desc,
1945 )
1946 }
1947
1948 (
1949 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1950 BorrowKind::Shared | BorrowKind::Fake(_),
1951 )
1952 | (
1953 BorrowKind::Fake(FakeBorrowKind::Shallow),
1954 BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_),
1955 ) => {
1956 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1957 }
1958 };
1959 self.note_due_to_edition_2024_opaque_capture_rules(issued_borrow, &mut err);
1960
1961 if issued_spans == borrow_spans {
1962 borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
1963 use crate::session_diagnostics::CaptureVarCause::*;
1964 match kind {
1965 hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1966 place: desc_place,
1967 var_span,
1968 is_single_var: false,
1969 },
1970 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1971 BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: false }
1972 }
1973 }
1974 });
1975 } else {
1976 issued_spans.var_subdiag(&mut err, Some(issued_borrow.kind), |kind, var_span| {
1977 use crate::session_diagnostics::CaptureVarCause::*;
1978 let borrow_place = &issued_borrow.borrowed_place;
1979 let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
1980 match kind {
1981 hir::ClosureKind::Coroutine(_) => {
1982 FirstBorrowUsePlaceCoroutine { place: borrow_place_desc, var_span }
1983 }
1984 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1985 FirstBorrowUsePlaceClosure { place: borrow_place_desc, var_span }
1986 }
1987 }
1988 });
1989
1990 borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
1991 use crate::session_diagnostics::CaptureVarCause::*;
1992 match kind {
1993 hir::ClosureKind::Coroutine(_) => {
1994 SecondBorrowUsePlaceCoroutine { place: desc_place, var_span }
1995 }
1996 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1997 SecondBorrowUsePlaceClosure { place: desc_place, var_span }
1998 }
1999 }
2000 });
2001 }
2002
2003 if union_type_name != "" {
2004 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!(
2005 "{msg_place} is a field of the union `{union_type_name}`, so it overlaps the field {msg_borrow}",
2006 ));
2007 }
2008
2009 explanation.add_explanation_to_diagnostic(
2010 &self,
2011 &mut err,
2012 first_borrow_desc,
2013 None,
2014 Some((issued_span, span)),
2015 );
2016
2017 self.suggest_using_local_if_applicable(&mut err, location, issued_borrow, explanation);
2018 self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
2019
2020 err
2021 }
2022
2023 fn suggest_copy_for_type_in_cloned_ref(&self, err: &mut Diag<'infcx>, place: Place<'tcx>) {
2024 let tcx = self.infcx.tcx;
2025 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2026
2027 struct FindUselessClone<'tcx> {
2028 tcx: TyCtxt<'tcx>,
2029 typeck_results: &'tcx ty::TypeckResults<'tcx>,
2030 clones: Vec<&'tcx hir::Expr<'tcx>>,
2031 }
2032 impl<'tcx> FindUselessClone<'tcx> {
2033 fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
2034 Self { tcx, typeck_results: tcx.typeck(def_id), clones: ::alloc::vec::Vec::new()vec![] }
2035 }
2036 }
2037 impl<'tcx> Visitor<'tcx> for FindUselessClone<'tcx> {
2038 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
2039 if let hir::ExprKind::MethodCall(..) = ex.kind
2040 && let Some(method_def_id) =
2041 self.typeck_results.type_dependent_def_id(ex.hir_id)
2042 && self.tcx.is_lang_item(self.tcx.parent(method_def_id), LangItem::Clone)
2043 {
2044 self.clones.push(ex);
2045 }
2046 hir::intravisit::walk_expr(self, ex);
2047 }
2048 }
2049
2050 let mut expr_finder = FindUselessClone::new(tcx, self.mir_def_id());
2051
2052 let body = tcx.hir_body(body_id).value;
2053 expr_finder.visit_expr(body);
2054
2055 struct Holds<'tcx> {
2056 ty: Ty<'tcx>,
2057 }
2058
2059 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for Holds<'tcx> {
2060 type Result = std::ops::ControlFlow<()>;
2061
2062 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
2063 if t == self.ty {
2064 return ControlFlow::Break(());
2065 }
2066 t.super_visit_with(self)
2067 }
2068 }
2069
2070 let mut types_to_constrain = FxIndexSet::default();
2071
2072 let local_ty = self.body.local_decls[place.local].ty;
2073 let typeck_results = tcx.typeck(self.mir_def_id());
2074 let clone = tcx.require_lang_item(LangItem::Clone, body.span);
2075 for expr in expr_finder.clones {
2076 if let hir::ExprKind::MethodCall(_, rcvr, _, span) = expr.kind
2077 && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
2078 && let Some(ty) = typeck_results.node_type_opt(expr.hir_id)
2079 && rcvr_ty == ty
2080 && let ty::Ref(_, inner, _) = rcvr_ty.kind()
2081 && let inner = inner.peel_refs()
2082 && (Holds { ty: inner }).visit_ty(local_ty).is_break()
2083 && let None =
2084 self.infcx.type_implements_trait_shallow(clone, inner, self.infcx.param_env)
2085 {
2086 err.span_label(
2087 span,
2088 ::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!(
2089 "this call doesn't do anything, the result is still `{rcvr_ty}` \
2090 because `{inner}` doesn't implement `Clone`",
2091 ),
2092 );
2093 types_to_constrain.insert(inner);
2094 }
2095 }
2096 for ty in types_to_constrain {
2097 self.suggest_adding_bounds_or_derive(err, ty, clone, body.span);
2098 }
2099 }
2100
2101 pub(crate) fn suggest_adding_bounds_or_derive(
2102 &self,
2103 err: &mut Diag<'_>,
2104 ty: Ty<'tcx>,
2105 trait_def_id: DefId,
2106 span: Span,
2107 ) {
2108 self.suggest_adding_bounds(err, ty, trait_def_id, span);
2109 if let ty::Adt(..) = ty.kind() {
2110 let trait_ref =
2112 ty::Binder::dummy(ty::TraitRef::new(self.infcx.tcx, trait_def_id, [ty]));
2113 let obligation = Obligation::new(
2114 self.infcx.tcx,
2115 ObligationCause::dummy(),
2116 self.infcx.param_env,
2117 trait_ref,
2118 );
2119 self.infcx.err_ctxt().suggest_derive(
2120 &obligation,
2121 err,
2122 trait_ref.upcast(self.infcx.tcx),
2123 );
2124 }
2125 }
2126
2127 #[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(2127u32),
::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:2145",
"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(2145u32),
::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:2174",
"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(2174u32),
::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:2178",
"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(2178u32),
::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:2188",
"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(2188u32),
::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:2192",
"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(2192u32),
::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:2195",
"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(2195u32),
::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:2202",
"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(2202u32),
::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:2205",
"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(2205u32),
::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:2215",
"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(2215u32),
::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))]
2128 fn suggest_using_local_if_applicable(
2129 &self,
2130 err: &mut Diag<'_>,
2131 location: Location,
2132 issued_borrow: &BorrowData<'tcx>,
2133 explanation: BorrowExplanation<'tcx>,
2134 ) {
2135 let used_in_call = matches!(
2136 explanation,
2137 BorrowExplanation::UsedLater(
2138 _,
2139 LaterUseKind::Call | LaterUseKind::Other,
2140 _call_span,
2141 _
2142 )
2143 );
2144 if !used_in_call {
2145 debug!("not later used in call");
2146 return;
2147 }
2148 if matches!(
2149 self.body.local_decls[issued_borrow.borrowed_place.local].local_info(),
2150 LocalInfo::IfThenRescopeTemp { .. }
2151 ) {
2152 return;
2154 }
2155
2156 let use_span = if let BorrowExplanation::UsedLater(_, LaterUseKind::Other, use_span, _) =
2157 explanation
2158 {
2159 Some(use_span)
2160 } else {
2161 None
2162 };
2163
2164 let outer_call_loc =
2165 if let TwoPhaseActivation::ActivatedAt(loc) = issued_borrow.activation_location {
2166 loc
2167 } else {
2168 issued_borrow.reserve_location
2169 };
2170 let outer_call_stmt = self.body.stmt_at(outer_call_loc);
2171
2172 let inner_param_location = location;
2173 let Some(inner_param_stmt) = self.body.stmt_at(inner_param_location).left() else {
2174 debug!("`inner_param_location` {:?} is not for a statement", inner_param_location);
2175 return;
2176 };
2177 let Some(&inner_param) = inner_param_stmt.kind.as_assign().map(|(p, _)| p) else {
2178 debug!(
2179 "`inner_param_location` {:?} is not for an assignment: {:?}",
2180 inner_param_location, inner_param_stmt
2181 );
2182 return;
2183 };
2184 let inner_param_uses = find_all_local_uses::find(self.body, inner_param.local);
2185 let Some((inner_call_loc, inner_call_term)) =
2186 inner_param_uses.into_iter().find_map(|loc| {
2187 let Either::Right(term) = self.body.stmt_at(loc) else {
2188 debug!("{:?} is a statement, so it can't be a call", loc);
2189 return None;
2190 };
2191 let TerminatorKind::Call { args, .. } = &term.kind else {
2192 debug!("not a call: {:?}", term);
2193 return None;
2194 };
2195 debug!("checking call args for uses of inner_param: {:?}", args);
2196 args.iter()
2197 .map(|a| &a.node)
2198 .any(|a| a == &Operand::Move(inner_param))
2199 .then_some((loc, term))
2200 })
2201 else {
2202 debug!("no uses of inner_param found as a by-move call arg");
2203 return;
2204 };
2205 debug!("===> outer_call_loc = {:?}, inner_call_loc = {:?}", outer_call_loc, inner_call_loc);
2206
2207 let inner_call_span = inner_call_term.source_info.span;
2208 let outer_call_span = match use_span {
2209 Some(span) => span,
2210 None => outer_call_stmt.either(|s| s.source_info, |t| t.source_info).span,
2211 };
2212 if outer_call_span == inner_call_span || !outer_call_span.contains(inner_call_span) {
2213 debug!(
2216 "outer span {:?} does not strictly contain inner span {:?}",
2217 outer_call_span, inner_call_span
2218 );
2219 return;
2220 }
2221 err.span_help(
2222 inner_call_span,
2223 format!(
2224 "try adding a local storing this{}...",
2225 if use_span.is_some() { "" } else { " argument" }
2226 ),
2227 );
2228 err.span_help(
2229 outer_call_span,
2230 format!(
2231 "...and then using that local {}",
2232 if use_span.is_some() { "here" } else { "as the argument to this call" }
2233 ),
2234 );
2235 }
2236
2237 pub(crate) fn find_expr(&self, span: Span) -> Option<&'tcx hir::Expr<'tcx>> {
2238 let tcx = self.infcx.tcx;
2239 let body_id = tcx.hir_node(self.mir_hir_id()).body_id()?;
2240 let mut expr_finder = FindExprBySpan::new(span, tcx);
2241 expr_finder.visit_expr(tcx.hir_body(body_id).value);
2242 expr_finder.result
2243 }
2244
2245 fn suggest_slice_method_if_applicable(
2246 &self,
2247 err: &mut Diag<'_>,
2248 place: Place<'tcx>,
2249 borrowed_place: Place<'tcx>,
2250 span: Span,
2251 issued_span: Span,
2252 ) {
2253 let tcx = self.infcx.tcx;
2254
2255 let has_split_at_mut = |ty: Ty<'tcx>| {
2256 let ty = ty.peel_refs();
2257 match ty.kind() {
2258 ty::Array(..) | ty::Slice(..) => true,
2259 ty::Adt(def, _) if tcx.get_diagnostic_item(sym::Vec) == Some(def.did()) => true,
2260 _ if ty == tcx.types.str_ => true,
2261 _ => false,
2262 }
2263 };
2264 if let ([ProjectionElem::Index(index1)], [ProjectionElem::Index(index2)])
2265 | (
2266 [ProjectionElem::Deref, ProjectionElem::Index(index1)],
2267 [ProjectionElem::Deref, ProjectionElem::Index(index2)],
2268 ) = (&place.projection[..], &borrowed_place.projection[..])
2269 {
2270 let decl1 = &self.body.local_decls[*index1];
2271 let decl2 = &self.body.local_decls[*index2];
2272
2273 let mut note_default_suggestion = || {
2274 err.help(
2275 "consider using `.split_at_mut(position)` or similar method to obtain two \
2276 mutable non-overlapping sub-slices",
2277 )
2278 .help(
2279 "consider using `.swap(index_1, index_2)` to swap elements at the specified \
2280 indices",
2281 );
2282 };
2283
2284 let Some(index1) = self.find_expr(decl1.source_info.span) else {
2285 note_default_suggestion();
2286 return;
2287 };
2288
2289 let Some(index2) = self.find_expr(decl2.source_info.span) else {
2290 note_default_suggestion();
2291 return;
2292 };
2293
2294 let sm = tcx.sess.source_map();
2295
2296 let Ok(index1_str) = sm.span_to_snippet(index1.span) else {
2297 note_default_suggestion();
2298 return;
2299 };
2300
2301 let Ok(index2_str) = sm.span_to_snippet(index2.span) else {
2302 note_default_suggestion();
2303 return;
2304 };
2305
2306 let Some(object) = tcx.hir_parent_id_iter(index1.hir_id).find_map(|id| {
2307 if let hir::Node::Expr(expr) = tcx.hir_node(id)
2308 && let hir::ExprKind::Index(obj, ..) = expr.kind
2309 {
2310 Some(obj)
2311 } else {
2312 None
2313 }
2314 }) else {
2315 note_default_suggestion();
2316 return;
2317 };
2318
2319 let Ok(obj_str) = sm.span_to_snippet(object.span) else {
2320 note_default_suggestion();
2321 return;
2322 };
2323
2324 let Some(swap_call) = tcx.hir_parent_id_iter(object.hir_id).find_map(|id| {
2325 if let hir::Node::Expr(call) = tcx.hir_node(id)
2326 && let hir::ExprKind::Call(callee, ..) = call.kind
2327 && let hir::ExprKind::Path(qpath) = callee.kind
2328 && let hir::QPath::Resolved(None, res) = qpath
2329 && let hir::def::Res::Def(_, did) = res.res
2330 && tcx.is_diagnostic_item(sym::mem_swap, did)
2331 {
2332 Some(call)
2333 } else {
2334 None
2335 }
2336 }) else {
2337 let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2338 let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2339 let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2340 let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2341 if !idx1.equivalent_for_indexing(idx2) {
2342 err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2343 }
2344 return;
2345 };
2346
2347 err.span_suggestion(
2348 swap_call.span,
2349 "use `.swap()` to swap elements at the specified indices instead",
2350 ::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})"),
2351 Applicability::MachineApplicable,
2352 );
2353 return;
2354 }
2355 let place_ty = PlaceRef::ty(&place.as_ref(), self.body, tcx).ty;
2356 let borrowed_place_ty = PlaceRef::ty(&borrowed_place.as_ref(), self.body, tcx).ty;
2357 if !has_split_at_mut(place_ty) && !has_split_at_mut(borrowed_place_ty) {
2358 return;
2360 }
2361 let Some(index1) = self.find_expr(span) else { return };
2362 let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2363 let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2364 let Some(index2) = self.find_expr(issued_span) else { return };
2365 let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2366 let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2367 if idx1.equivalent_for_indexing(idx2) {
2368 return;
2370 }
2371 err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2372 }
2373
2374 pub(crate) fn explain_iterator_advancement_in_for_loop_if_applicable(
2385 &self,
2386 err: &mut Diag<'_>,
2387 span: Span,
2388 issued_spans: &UseSpans<'tcx>,
2389 ) {
2390 let issue_span = issued_spans.args_or_use();
2391 let tcx = self.infcx.tcx;
2392
2393 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2394 let typeck_results = tcx.typeck(self.mir_def_id());
2395
2396 struct ExprFinder<'hir> {
2397 tcx: TyCtxt<'hir>,
2398 issue_span: Span,
2399 expr_span: Span,
2400 body_expr: Option<&'hir hir::Expr<'hir>> = None,
2401 loop_bind: Option<&'hir Ident> = None,
2402 loop_span: Option<Span> = None,
2403 head_span: Option<Span> = None,
2404 pat_span: Option<Span> = None,
2405 head: Option<&'hir hir::Expr<'hir>> = None,
2406 }
2407 impl<'hir> Visitor<'hir> for ExprFinder<'hir> {
2408 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2409 if let hir::ExprKind::Call(path, [arg]) = ex.kind
2422 && let hir::ExprKind::Path(qpath) = path.kind
2423 && self.tcx.qpath_is_lang_item(qpath, LangItem::IntoIterIntoIter)
2424 && arg.span.contains(self.issue_span)
2425 && ex.span.desugaring_kind() == Some(DesugaringKind::ForLoop)
2426 {
2427 self.head = Some(arg);
2429 }
2430 if let hir::ExprKind::Loop(
2431 hir::Block { stmts: [stmt, ..], .. },
2432 _,
2433 hir::LoopSource::ForLoop,
2434 _,
2435 ) = ex.kind
2436 && let hir::StmtKind::Expr(hir::Expr {
2437 kind: hir::ExprKind::Match(call, [_, bind, ..], _),
2438 span: head_span,
2439 ..
2440 }) = stmt.kind
2441 && let hir::ExprKind::Call(path, _args) = call.kind
2442 && let hir::ExprKind::Path(qpath) = path.kind
2443 && self.tcx.qpath_is_lang_item(qpath, LangItem::IteratorNext)
2444 && let hir::PatKind::Struct(qpath, [field, ..], _) = bind.pat.kind
2445 && self.tcx.qpath_is_lang_item(qpath, LangItem::OptionSome)
2446 && call.span.contains(self.issue_span)
2447 {
2448 if let PatField {
2450 pat: hir::Pat { kind: hir::PatKind::Binding(_, _, ident, ..), .. },
2451 ..
2452 } = field
2453 {
2454 self.loop_bind = Some(ident);
2455 }
2456 self.head_span = Some(*head_span);
2457 self.pat_span = Some(bind.pat.span);
2458 self.loop_span = Some(stmt.span);
2459 }
2460
2461 if let hir::ExprKind::MethodCall(body_call, recv, ..) = ex.kind
2462 && body_call.ident.name == sym::next
2463 && recv.span.source_equal(self.expr_span)
2464 {
2465 self.body_expr = Some(ex);
2466 }
2467
2468 hir::intravisit::walk_expr(self, ex);
2469 }
2470 }
2471 let mut finder = ExprFinder { tcx, expr_span: span, issue_span, .. };
2472 finder.visit_expr(tcx.hir_body(body_id).value);
2473
2474 if let Some(body_expr) = finder.body_expr
2475 && let Some(loop_span) = finder.loop_span
2476 && let Some(def_id) = typeck_results.type_dependent_def_id(body_expr.hir_id)
2477 && let Some(trait_did) = tcx.trait_of_assoc(def_id)
2478 && tcx.is_diagnostic_item(sym::Iterator, trait_did)
2479 {
2480 if let Some(loop_bind) = finder.loop_bind {
2481 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!(
2482 "a for loop advances the iterator for you, the result is stored in `{}`",
2483 loop_bind.name,
2484 ));
2485 } else {
2486 err.note(
2487 "a for loop advances the iterator for you, the result is stored in its pattern",
2488 );
2489 }
2490 let msg = "if you want to call `next` on a iterator within the loop, consider using \
2491 `while let`";
2492 if let Some(head) = finder.head
2493 && let Some(pat_span) = finder.pat_span
2494 && loop_span.contains(body_expr.span)
2495 && loop_span.contains(head.span)
2496 {
2497 let sm = self.infcx.tcx.sess.source_map();
2498
2499 let mut sugg = ::alloc::vec::Vec::new()vec![];
2500 if let hir::ExprKind::Path(hir::QPath::Resolved(None, _)) = head.kind {
2501 sugg.push((loop_span.with_hi(pat_span.lo()), "while let Some(".to_string()));
2505 sugg.push((
2506 pat_span.shrink_to_hi().with_hi(head.span.lo()),
2507 ") = ".to_string(),
2508 ));
2509 sugg.push((head.span.shrink_to_hi(), ".next()".to_string()));
2510 } else {
2511 let indent = if let Some(indent) = sm.indentation_before(loop_span) {
2513 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}", indent))
})format!("\n{indent}")
2514 } else {
2515 " ".to_string()
2516 };
2517 let Ok(head_str) = sm.span_to_snippet(head.span) else {
2518 err.help(msg);
2519 return;
2520 };
2521 sugg.push((
2522 loop_span.with_hi(pat_span.lo()),
2523 ::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("),
2524 ));
2525 sugg.push((
2526 pat_span.shrink_to_hi().with_hi(head.span.hi()),
2527 ") = iter.next()".to_string(),
2528 ));
2529 if let hir::ExprKind::MethodCall(_, recv, ..) = body_expr.kind
2532 && let hir::ExprKind::Path(hir::QPath::Resolved(None, ..)) = recv.kind
2533 {
2534 sugg.push((recv.span, "iter".to_string()));
2538 }
2539 }
2540 err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2541 } else {
2542 err.help(msg);
2543 }
2544 }
2545 }
2546
2547 fn suggest_using_closure_argument_instead_of_capture(
2564 &self,
2565 err: &mut Diag<'_>,
2566 borrowed_place: Place<'tcx>,
2567 issued_spans: &UseSpans<'tcx>,
2568 ) {
2569 let &UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2570 let tcx = self.infcx.tcx;
2571
2572 let local = borrowed_place.local;
2574 let local_ty = self.body.local_decls[local].ty;
2575
2576 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2578
2579 let body_expr = tcx.hir_body(body_id).value;
2580
2581 struct ClosureFinder<'hir> {
2582 tcx: TyCtxt<'hir>,
2583 borrow_span: Span,
2584 res: Option<(&'hir hir::Expr<'hir>, &'hir hir::Closure<'hir>)>,
2585 error_path: Option<(&'hir hir::Expr<'hir>, &'hir hir::QPath<'hir>)>,
2587 }
2588 impl<'hir> Visitor<'hir> for ClosureFinder<'hir> {
2589 type NestedFilter = OnlyBodies;
2590
2591 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
2592 self.tcx
2593 }
2594
2595 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2596 if let hir::ExprKind::Path(qpath) = &ex.kind
2597 && ex.span == self.borrow_span
2598 {
2599 self.error_path = Some((ex, qpath));
2600 }
2601
2602 if let hir::ExprKind::Closure(closure) = ex.kind
2603 && ex.span.contains(self.borrow_span)
2604 && self.res.as_ref().is_none_or(|(prev_res, _)| prev_res.span.contains(ex.span))
2608 {
2609 self.res = Some((ex, closure));
2610 }
2611
2612 hir::intravisit::walk_expr(self, ex);
2613 }
2614 }
2615
2616 let mut finder =
2618 ClosureFinder { tcx, borrow_span: capture_kind_span, res: None, error_path: None };
2619 finder.visit_expr(body_expr);
2620 let Some((closure_expr, closure)) = finder.res else { return };
2621
2622 let typeck_results = tcx.typeck(self.mir_def_id());
2623
2624 if let hir::Node::Expr(parent) = tcx.parent_hir_node(closure_expr.hir_id)
2627 && let hir::ExprKind::MethodCall(_, recv, ..) = parent.kind
2628 {
2629 let recv_ty = typeck_results.expr_ty(recv);
2630
2631 if recv_ty.peel_refs() != local_ty {
2632 return;
2633 }
2634 }
2635
2636 let ty::Closure(_, args) = typeck_results.expr_ty(closure_expr).kind() else {
2638 return;
2640 };
2641 let sig = args.as_closure().sig();
2642 let tupled_params = tcx.instantiate_bound_regions_with_erased(
2643 sig.inputs().iter().next().unwrap().map_bound(|&b| b),
2644 );
2645 let ty::Tuple(params) = tupled_params.kind() else { return };
2646
2647 let Some(this_name) = params.iter().zip(tcx.hir_body_param_idents(closure.body)).find_map(
2649 |(param_ty, ident)| {
2650 if param_ty.peel_refs() == local_ty { ident } else { None }
2652 },
2653 ) else {
2654 return;
2655 };
2656
2657 let spans;
2658 if let Some((_path_expr, qpath)) = finder.error_path
2659 && let hir::QPath::Resolved(_, path) = qpath
2660 && let hir::def::Res::Local(local_id) = path.res
2661 {
2662 struct VariableUseFinder {
2665 local_id: hir::HirId,
2666 spans: Vec<Span>,
2667 }
2668 impl<'hir> Visitor<'hir> for VariableUseFinder {
2669 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2670 if let hir::ExprKind::Path(qpath) = &ex.kind
2671 && let hir::QPath::Resolved(_, path) = qpath
2672 && let hir::def::Res::Local(local_id) = path.res
2673 && local_id == self.local_id
2674 {
2675 self.spans.push(ex.span);
2676 }
2677
2678 hir::intravisit::walk_expr(self, ex);
2679 }
2680 }
2681
2682 let mut finder = VariableUseFinder { local_id, spans: Vec::new() };
2683 finder.visit_expr(tcx.hir_body(closure.body).value);
2684
2685 spans = finder.spans;
2686 } else {
2687 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];
2688 }
2689
2690 err.multipart_suggestion(
2691 "try using the closure argument",
2692 iter::zip(spans, iter::repeat(this_name.to_string())).collect(),
2693 Applicability::MaybeIncorrect,
2694 );
2695 }
2696
2697 fn suggest_binding_for_closure_capture_self(
2698 &self,
2699 err: &mut Diag<'_>,
2700 issued_spans: &UseSpans<'tcx>,
2701 ) {
2702 let UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2703
2704 struct ExpressionFinder<'tcx> {
2705 capture_span: Span,
2706 closure_change_spans: Vec<Span> = ::alloc::vec::Vec::new()vec![],
2707 closure_arg_span: Option<Span> = None,
2708 in_closure: bool = false,
2709 suggest_arg: String = String::new(),
2710 tcx: TyCtxt<'tcx>,
2711 closure_local_id: Option<hir::HirId> = None,
2712 closure_call_changes: Vec<(Span, String)> = ::alloc::vec::Vec::new()vec![],
2713 }
2714 impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
2715 fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
2716 if e.span.contains(self.capture_span)
2717 && let hir::ExprKind::Closure(&hir::Closure {
2718 kind: hir::ClosureKind::Closure,
2719 body,
2720 fn_arg_span,
2721 fn_decl: hir::FnDecl { inputs, .. },
2722 ..
2723 }) = e.kind
2724 && let hir::Node::Expr(body) = self.tcx.hir_node(body.hir_id)
2725 {
2726 self.suggest_arg = "this: &Self".to_string();
2727 if inputs.len() > 0 {
2728 self.suggest_arg.push_str(", ");
2729 }
2730 self.in_closure = true;
2731 self.closure_arg_span = fn_arg_span;
2732 self.visit_expr(body);
2733 self.in_closure = false;
2734 }
2735 if let hir::Expr { kind: hir::ExprKind::Path(path), .. } = e
2736 && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2737 && seg.ident.name == kw::SelfLower
2738 && self.in_closure
2739 {
2740 self.closure_change_spans.push(e.span);
2741 }
2742 hir::intravisit::walk_expr(self, e);
2743 }
2744
2745 fn visit_local(&mut self, local: &'hir hir::LetStmt<'hir>) {
2746 if let hir::Pat { kind: hir::PatKind::Binding(_, hir_id, _ident, _), .. } =
2747 local.pat
2748 && let Some(init) = local.init
2749 && let &hir::Expr {
2750 kind:
2751 hir::ExprKind::Closure(&hir::Closure {
2752 kind: hir::ClosureKind::Closure,
2753 ..
2754 }),
2755 ..
2756 } = init
2757 && init.span.contains(self.capture_span)
2758 {
2759 self.closure_local_id = Some(*hir_id);
2760 }
2761
2762 hir::intravisit::walk_local(self, local);
2763 }
2764
2765 fn visit_stmt(&mut self, s: &'hir hir::Stmt<'hir>) {
2766 if let hir::StmtKind::Semi(e) = s.kind
2767 && let hir::ExprKind::Call(
2768 hir::Expr { kind: hir::ExprKind::Path(path), .. },
2769 args,
2770 ) = e.kind
2771 && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2772 && let Res::Local(hir_id) = seg.res
2773 && Some(hir_id) == self.closure_local_id
2774 {
2775 let (span, arg_str) = if args.len() > 0 {
2776 (args[0].span.shrink_to_lo(), "self, ".to_string())
2777 } else {
2778 let span = e.span.trim_start(seg.ident.span).unwrap_or(e.span);
2779 (span, "(self)".to_string())
2780 };
2781 self.closure_call_changes.push((span, arg_str));
2782 }
2783 hir::intravisit::walk_stmt(self, s);
2784 }
2785 }
2786
2787 if let hir::Node::ImplItem(hir::ImplItem {
2788 kind: hir::ImplItemKind::Fn(_fn_sig, body_id),
2789 ..
2790 }) = self.infcx.tcx.hir_node(self.mir_hir_id())
2791 && let hir::Node::Expr(expr) = self.infcx.tcx.hir_node(body_id.hir_id)
2792 {
2793 let mut finder =
2794 ExpressionFinder { capture_span: *capture_kind_span, tcx: self.infcx.tcx, .. };
2795 finder.visit_expr(expr);
2796
2797 if finder.closure_change_spans.is_empty() || finder.closure_call_changes.is_empty() {
2798 return;
2799 }
2800
2801 let sm = self.infcx.tcx.sess.source_map();
2802 let sugg = finder
2803 .closure_arg_span
2804 .map(|span| (sm.next_point(span.shrink_to_lo()).shrink_to_hi(), finder.suggest_arg))
2805 .into_iter()
2806 .chain(
2807 finder.closure_change_spans.into_iter().map(|span| (span, "this".to_string())),
2808 )
2809 .chain(finder.closure_call_changes)
2810 .collect();
2811
2812 err.multipart_suggestion(
2813 "try explicitly passing `&Self` into the closure as an argument",
2814 sugg,
2815 Applicability::MachineApplicable,
2816 );
2817 }
2818 }
2819
2820 fn describe_place_for_conflicting_borrow(
2849 &self,
2850 first_borrowed_place: Place<'tcx>,
2851 second_borrowed_place: Place<'tcx>,
2852 ) -> (String, String, String, String) {
2853 let union_ty = |place_base| {
2856 let ty = PlaceRef::ty(&place_base, self.body, self.infcx.tcx).ty;
2859 ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
2860 };
2861
2862 Some(())
2866 .filter(|_| {
2867 first_borrowed_place != second_borrowed_place
2870 })
2871 .and_then(|_| {
2872 for (place_base, elem) in first_borrowed_place.iter_projections().rev() {
2877 match elem {
2878 ProjectionElem::Field(field, _) if union_ty(place_base).is_some() => {
2879 return Some((place_base, field));
2880 }
2881 _ => {}
2882 }
2883 }
2884 None
2885 })
2886 .and_then(|(target_base, target_field)| {
2887 for (place_base, elem) in second_borrowed_place.iter_projections().rev() {
2890 if let ProjectionElem::Field(field, _) = elem
2891 && let Some(union_ty) = union_ty(place_base)
2892 {
2893 if field != target_field && place_base == target_base {
2894 return Some((
2895 self.describe_any_place(place_base),
2896 self.describe_any_place(first_borrowed_place.as_ref()),
2897 self.describe_any_place(second_borrowed_place.as_ref()),
2898 union_ty.to_string(),
2899 ));
2900 }
2901 }
2902 }
2903 None
2904 })
2905 .unwrap_or_else(|| {
2906 (
2909 self.describe_any_place(first_borrowed_place.as_ref()),
2910 "".to_string(),
2911 "".to_string(),
2912 "".to_string(),
2913 )
2914 })
2915 }
2916
2917 #[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(2923u32),
::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:2940",
"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(2940u32),
::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:2976",
"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(2976u32),
::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))]
2924 pub(crate) fn report_borrowed_value_does_not_live_long_enough(
2925 &mut self,
2926 location: Location,
2927 borrow: &BorrowData<'tcx>,
2928 place_span: (Place<'tcx>, Span),
2929 kind: Option<WriteKind>,
2930 ) {
2931 let drop_span = place_span.1;
2932 let borrowed_local = borrow.borrowed_place.local;
2933
2934 let borrow_spans = self.retrieve_borrow_spans(borrow);
2935 let borrow_span = borrow_spans.var_or_use_path_span();
2936
2937 let proper_span = self.body.local_decls[borrowed_local].source_info.span;
2938
2939 if self.access_place_error_reported.contains(&(Place::from(borrowed_local), borrow_span)) {
2940 debug!(
2941 "suppressing access_place error when borrow doesn't live long enough for {:?}",
2942 borrow_span
2943 );
2944 return;
2945 }
2946
2947 self.access_place_error_reported.insert((Place::from(borrowed_local), borrow_span));
2948
2949 if self.body.local_decls[borrowed_local].is_ref_to_thread_local() {
2950 let err =
2951 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span);
2952 self.buffer_error(err);
2953 return;
2954 }
2955
2956 if let StorageDeadOrDrop::Destructor(dropped_ty) =
2957 self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
2958 {
2959 if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
2964 self.report_borrow_conflicts_with_destructor(
2965 location, borrow, place_span, kind, dropped_ty,
2966 );
2967 return;
2968 }
2969 }
2970
2971 let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
2972
2973 let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
2974 let explanation = self.explain_why_borrow_contains_point(location, borrow, kind_place);
2975
2976 debug!(?place_desc, ?explanation);
2977
2978 let mut err = match (place_desc, explanation) {
2979 (
2989 Some(name),
2990 BorrowExplanation::UsedLater(_, LaterUseKind::ClosureCapture, var_or_use_span, _),
2991 ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
2992 .report_escaping_closure_capture(
2993 borrow_spans,
2994 borrow_span,
2995 &RegionName {
2996 name: self.synthesize_region_name(),
2997 source: RegionNameSource::Static,
2998 },
2999 ConstraintCategory::CallArgument(None),
3000 var_or_use_span,
3001 &format!("`{name}`"),
3002 "block",
3003 ),
3004 (
3005 Some(name),
3006 BorrowExplanation::MustBeValidFor {
3007 category:
3008 category @ (ConstraintCategory::Return(_)
3009 | ConstraintCategory::CallArgument(_)
3010 | ConstraintCategory::OpaqueType),
3011 from_closure: false,
3012 ref region_name,
3013 span,
3014 ..
3015 },
3016 ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
3017 .report_escaping_closure_capture(
3018 borrow_spans,
3019 borrow_span,
3020 region_name,
3021 category,
3022 span,
3023 &format!("`{name}`"),
3024 "function",
3025 ),
3026 (
3027 name,
3028 BorrowExplanation::MustBeValidFor {
3029 category: ConstraintCategory::Assignment,
3030 from_closure: false,
3031 region_name:
3032 RegionName {
3033 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
3034 ..
3035 },
3036 span,
3037 ..
3038 },
3039 ) => self.report_escaping_data(borrow_span, &name, upvar_span, upvar_name, span),
3040 (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
3041 location,
3042 &name,
3043 borrow,
3044 drop_span,
3045 borrow_spans,
3046 explanation,
3047 ),
3048 (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
3049 location,
3050 borrow,
3051 drop_span,
3052 borrow_spans,
3053 proper_span,
3054 explanation,
3055 ),
3056 };
3057 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
3058
3059 self.buffer_error(err);
3060 }
3061
3062 #[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(3062u32),
::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))]
3063 fn report_local_value_does_not_live_long_enough(
3064 &self,
3065 location: Location,
3066 name: &str,
3067 borrow: &BorrowData<'tcx>,
3068 drop_span: Span,
3069 borrow_spans: UseSpans<'tcx>,
3070 explanation: BorrowExplanation<'tcx>,
3071 ) -> Diag<'infcx> {
3072 let borrow_span = borrow_spans.var_or_use_path_span();
3073 if let BorrowExplanation::MustBeValidFor {
3074 category,
3075 span,
3076 ref opt_place_desc,
3077 from_closure: false,
3078 ..
3079 } = explanation
3080 && let Err(diag) = self.try_report_cannot_return_reference_to_local(
3081 borrow,
3082 borrow_span,
3083 span,
3084 category,
3085 opt_place_desc.as_ref(),
3086 )
3087 {
3088 return diag;
3089 }
3090
3091 let name = format!("`{name}`");
3092
3093 let mut err = self.path_does_not_live_long_enough(borrow_span, &name);
3094
3095 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
3096 let region_name = annotation.emit(self, &mut err);
3097
3098 err.span_label(
3099 borrow_span,
3100 format!("{name} would have to be valid for `{region_name}`..."),
3101 );
3102
3103 err.span_label(
3104 drop_span,
3105 format!(
3106 "...but {name} will be dropped here, when the {} returns",
3107 self.infcx
3108 .tcx
3109 .opt_item_name(self.mir_def_id().to_def_id())
3110 .map(|name| format!("function `{name}`"))
3111 .unwrap_or_else(|| {
3112 match &self.infcx.tcx.def_kind(self.mir_def_id()) {
3113 DefKind::Closure
3114 if self
3115 .infcx
3116 .tcx
3117 .is_coroutine(self.mir_def_id().to_def_id()) =>
3118 {
3119 "enclosing coroutine"
3120 }
3121 DefKind::Closure => "enclosing closure",
3122 kind => bug!("expected closure or coroutine, found {:?}", kind),
3123 }
3124 .to_string()
3125 })
3126 ),
3127 );
3128
3129 err.note(
3130 "functions cannot return a borrow to data owned within the function's scope, \
3131 functions can only return borrows to data passed as arguments",
3132 );
3133 err.note(
3134 "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
3135 references-and-borrowing.html#dangling-references>",
3136 );
3137
3138 if let BorrowExplanation::MustBeValidFor { .. } = explanation {
3139 } else {
3140 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3141 }
3142 } else {
3143 err.span_label(borrow_span, "borrowed value does not live long enough");
3144 err.span_label(drop_span, format!("{name} dropped here while still borrowed"));
3145
3146 borrow_spans.args_subdiag(&mut err, |args_span| {
3147 crate::session_diagnostics::CaptureArgLabel::Capture {
3148 is_within: borrow_spans.for_coroutine(),
3149 args_span,
3150 }
3151 });
3152
3153 explanation.add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
3154
3155 if let BorrowExplanation::UsedLater(_dropped_local, _, _, _) = explanation {
3157 for (local, local_decl) in self.body.local_decls.iter_enumerated() {
3159 if let ty::Adt(adt_def, args) = local_decl.ty.kind()
3160 && self.infcx.tcx.is_diagnostic_item(sym::Vec, adt_def.did())
3161 && args.len() > 0
3162 {
3163 let vec_inner_ty = args.type_at(0);
3164 if vec_inner_ty.is_ref() {
3166 let local_place = local.into();
3167 if let Some(local_name) = self.describe_place(local_place) {
3168 err.span_label(
3169 local_decl.source_info.span,
3170 format!("variable `{local_name}` declared here"),
3171 );
3172 err.note(
3173 format!(
3174 "`{local_name}` is a collection that stores borrowed references, \
3175 but {name} does not live long enough to be stored in it"
3176 )
3177 );
3178 err.help(
3179 "buffer reuse with borrowed references requires unsafe code or restructuring"
3180 );
3181 break;
3182 }
3183 }
3184 }
3185 }
3186 }
3187 }
3188
3189 err
3190 }
3191
3192 fn report_borrow_conflicts_with_destructor(
3193 &mut self,
3194 location: Location,
3195 borrow: &BorrowData<'tcx>,
3196 (place, drop_span): (Place<'tcx>, Span),
3197 kind: Option<WriteKind>,
3198 dropped_ty: Ty<'tcx>,
3199 ) {
3200 {
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:3200",
"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(3200u32),
::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!(
3201 "report_borrow_conflicts_with_destructor(\
3202 {:?}, {:?}, ({:?}, {:?}), {:?}\
3203 )",
3204 location, borrow, place, drop_span, kind,
3205 );
3206
3207 let borrow_spans = self.retrieve_borrow_spans(borrow);
3208 let borrow_span = borrow_spans.var_or_use();
3209
3210 let mut err = self.cannot_borrow_across_destructor(borrow_span);
3211
3212 let what_was_dropped = match self.describe_place(place.as_ref()) {
3213 Some(name) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
})format!("`{name}`"),
3214 None => String::from("temporary value"),
3215 };
3216
3217 let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
3218 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!(
3219 "here, drop of {what_was_dropped} needs exclusive access to `{borrowed}`, \
3220 because the type `{dropped_ty}` implements the `Drop` trait"
3221 ),
3222 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!(
3223 "here is drop of {what_was_dropped}; whose type `{dropped_ty}` implements the `Drop` trait"
3224 ),
3225 };
3226 err.span_label(drop_span, label);
3227
3228 let explanation =
3230 self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
3231 match explanation {
3232 BorrowExplanation::UsedLater { .. }
3233 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3234 err.note("consider using a `let` binding to create a longer lived value");
3235 }
3236 _ => {}
3237 }
3238
3239 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3240
3241 self.buffer_error(err);
3242 }
3243
3244 fn report_thread_local_value_does_not_live_long_enough(
3245 &self,
3246 drop_span: Span,
3247 borrow_span: Span,
3248 ) -> Diag<'infcx> {
3249 {
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:3249",
"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(3249u32),
::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!(
3250 "report_thread_local_value_does_not_live_long_enough(\
3251 {:?}, {:?}\
3252 )",
3253 drop_span, borrow_span
3254 );
3255
3256 let sm = self.infcx.tcx.sess.source_map();
3261 let end_of_function = if drop_span.is_empty()
3262 && let Ok(adjusted_span) = sm.span_extend_prev_while(drop_span, |c| c == '}')
3263 {
3264 adjusted_span
3265 } else {
3266 drop_span
3267 };
3268 self.thread_local_value_does_not_live_long_enough(borrow_span)
3269 .with_span_label(
3270 borrow_span,
3271 "thread-local variables cannot be borrowed beyond the end of the function",
3272 )
3273 .with_span_label(end_of_function, "end of enclosing function is here")
3274 }
3275
3276 #[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(3276u32),
::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))]
3277 fn report_temporary_value_does_not_live_long_enough(
3278 &self,
3279 location: Location,
3280 borrow: &BorrowData<'tcx>,
3281 drop_span: Span,
3282 borrow_spans: UseSpans<'tcx>,
3283 proper_span: Span,
3284 explanation: BorrowExplanation<'tcx>,
3285 ) -> Diag<'infcx> {
3286 if let BorrowExplanation::MustBeValidFor { category, span, from_closure: false, .. } =
3287 explanation
3288 {
3289 if let Err(diag) = self.try_report_cannot_return_reference_to_local(
3290 borrow,
3291 proper_span,
3292 span,
3293 category,
3294 None,
3295 ) {
3296 return diag;
3297 }
3298 }
3299
3300 let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
3301 err.span_label(proper_span, "creates a temporary value which is freed while still in use");
3302 err.span_label(drop_span, "temporary value is freed at the end of this statement");
3303
3304 match explanation {
3305 BorrowExplanation::UsedLater(..)
3306 | BorrowExplanation::UsedLaterInLoop(..)
3307 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3308 let sm = self.infcx.tcx.sess.source_map();
3310 let mut suggested = false;
3311 let msg = "consider using a `let` binding to create a longer lived value";
3312
3313 struct NestedStatementVisitor<'tcx> {
3322 span: Span,
3323 current: usize,
3324 found: usize,
3325 prop_expr: Option<&'tcx hir::Expr<'tcx>>,
3326 call: Option<&'tcx hir::Expr<'tcx>>,
3327 }
3328
3329 impl<'tcx> Visitor<'tcx> for NestedStatementVisitor<'tcx> {
3330 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
3331 self.current += 1;
3332 walk_block(self, block);
3333 self.current -= 1;
3334 }
3335 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
3336 if let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind {
3337 if self.span == rcvr.span.source_callsite() {
3338 self.call = Some(expr);
3339 }
3340 }
3341 if self.span == expr.span.source_callsite() {
3342 self.found = self.current;
3343 if self.prop_expr.is_none() {
3344 self.prop_expr = Some(expr);
3345 }
3346 }
3347 walk_expr(self, expr);
3348 }
3349 }
3350 let source_info = self.body.source_info(location);
3351 let proper_span = proper_span.source_callsite();
3352 if let Some(scope) = self.body.source_scopes.get(source_info.scope)
3353 && let ClearCrossCrate::Set(scope_data) = &scope.local_data
3354 && let Some(id) = self.infcx.tcx.hir_node(scope_data.lint_root).body_id()
3355 && let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir_body(id).value.kind
3356 {
3357 for stmt in block.stmts {
3358 let mut visitor = NestedStatementVisitor {
3359 span: proper_span,
3360 current: 0,
3361 found: 0,
3362 prop_expr: None,
3363 call: None,
3364 };
3365 visitor.visit_stmt(stmt);
3366
3367 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
3368 let expr_ty: Option<Ty<'_>> =
3369 visitor.prop_expr.map(|expr| typeck_results.expr_ty(expr).peel_refs());
3370
3371 if visitor.found == 0
3372 && stmt.span.contains(proper_span)
3373 && let Some(p) = sm.span_to_margin(stmt.span)
3374 && let Ok(s) = sm.span_to_snippet(proper_span)
3375 {
3376 if let Some(call) = visitor.call
3377 && let hir::ExprKind::MethodCall(path, _, [], _) = call.kind
3378 && path.ident.name == sym::iter
3379 && let Some(ty) = expr_ty
3380 {
3381 err.span_suggestion_verbose(
3382 path.ident.span,
3383 format!(
3384 "consider consuming the `{ty}` when turning it into an \
3385 `Iterator`",
3386 ),
3387 "into_iter",
3388 Applicability::MaybeIncorrect,
3389 );
3390 }
3391
3392 let mutability = if matches!(borrow.kind(), BorrowKind::Mut { .. }) {
3393 "mut "
3394 } else {
3395 ""
3396 };
3397
3398 let addition =
3399 format!("let {}binding = {};\n{}", mutability, s, " ".repeat(p));
3400 err.multipart_suggestion(
3401 msg,
3402 vec![
3403 (stmt.span.shrink_to_lo(), addition),
3404 (proper_span, "binding".to_string()),
3405 ],
3406 Applicability::MaybeIncorrect,
3407 );
3408
3409 suggested = true;
3410 break;
3411 }
3412 }
3413 }
3414 if !suggested {
3415 err.note(msg);
3416 }
3417 }
3418 _ => {}
3419 }
3420 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3421
3422 borrow_spans.args_subdiag(&mut err, |args_span| {
3423 crate::session_diagnostics::CaptureArgLabel::Capture {
3424 is_within: borrow_spans.for_coroutine(),
3425 args_span,
3426 }
3427 });
3428
3429 err
3430 }
3431
3432 fn try_report_cannot_return_reference_to_local(
3433 &self,
3434 borrow: &BorrowData<'tcx>,
3435 borrow_span: Span,
3436 return_span: Span,
3437 category: ConstraintCategory<'tcx>,
3438 opt_place_desc: Option<&String>,
3439 ) -> Result<(), Diag<'infcx>> {
3440 let return_kind = match category {
3441 ConstraintCategory::Return(_) => "return",
3442 ConstraintCategory::Yield => "yield",
3443 _ => return Ok(()),
3444 };
3445
3446 let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
3448 "reference to"
3449 } else {
3450 "value referencing"
3451 };
3452
3453 let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
3454 let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
3455 match self.body.local_kind(local) {
3456 LocalKind::Temp if self.body.local_decls[local].is_user_variable() => {
3457 "local variable "
3458 }
3459 LocalKind::Arg
3460 if !self.upvars.is_empty() && local == ty::CAPTURE_STRUCT_LOCAL =>
3461 {
3462 "variable captured by `move` "
3463 }
3464 LocalKind::Arg => "function parameter ",
3465 LocalKind::ReturnPointer | LocalKind::Temp => {
3466 ::rustc_middle::util::bug::bug_fmt(format_args!("temporary or return pointer with a name"))bug!("temporary or return pointer with a name")
3467 }
3468 }
3469 } else {
3470 "local data "
3471 };
3472 (::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"))
3473 } else {
3474 let local = borrow.borrowed_place.local;
3475 match self.body.local_kind(local) {
3476 LocalKind::Arg => (
3477 "function parameter".to_string(),
3478 "function parameter borrowed here".to_string(),
3479 ),
3480 LocalKind::Temp
3481 if self.body.local_decls[local].is_user_variable()
3482 && !self.body.local_decls[local]
3483 .source_info
3484 .span
3485 .in_external_macro(self.infcx.tcx.sess.source_map()) =>
3486 {
3487 ("local binding".to_string(), "local binding introduced here".to_string())
3488 }
3489 LocalKind::ReturnPointer | LocalKind::Temp => {
3490 ("temporary value".to_string(), "temporary value created here".to_string())
3491 }
3492 }
3493 };
3494
3495 let mut err = self.cannot_return_reference_to_local(
3496 return_span,
3497 return_kind,
3498 reference_desc,
3499 &place_desc,
3500 );
3501
3502 if return_span != borrow_span {
3503 err.span_label(borrow_span, note);
3504
3505 let tcx = self.infcx.tcx;
3506
3507 let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
3508
3509 if let Some(iter_trait) = tcx.get_diagnostic_item(sym::Iterator)
3511 && self
3512 .infcx
3513 .type_implements_trait(iter_trait, [return_ty], self.infcx.param_env)
3514 .must_apply_modulo_regions()
3515 {
3516 err.span_suggestion_hidden(
3517 return_span.shrink_to_hi(),
3518 "use `.collect()` to allocate the iterator",
3519 ".collect::<Vec<_>>()",
3520 Applicability::MaybeIncorrect,
3521 );
3522 }
3523 }
3524
3525 Err(err)
3526 }
3527
3528 #[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(3528u32),
::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))]
3529 fn report_escaping_closure_capture(
3530 &self,
3531 use_span: UseSpans<'tcx>,
3532 var_span: Span,
3533 fr_name: &RegionName,
3534 category: ConstraintCategory<'tcx>,
3535 constraint_span: Span,
3536 captured_var: &str,
3537 scope: &str,
3538 ) -> Diag<'infcx> {
3539 let tcx = self.infcx.tcx;
3540 let args_span = use_span.args_or_use();
3541
3542 let (sugg_span, suggestion) = match tcx.sess.source_map().span_to_snippet(args_span) {
3543 Ok(string) => {
3544 let coro_prefix = if let Some(sub) = string.strip_prefix("async") {
3545 let trimmed_sub = sub.trim_end();
3546 if trimmed_sub.ends_with("gen") {
3547 Some((trimmed_sub.len() + 5) as _)
3549 } else {
3550 Some(5)
3552 }
3553 } else if string.starts_with("gen") {
3554 Some(3)
3556 } else if string.starts_with("static") {
3557 Some(6)
3560 } else {
3561 None
3562 };
3563 if let Some(n) = coro_prefix {
3564 let pos = args_span.lo() + BytePos(n);
3565 (args_span.with_lo(pos).with_hi(pos), " move")
3566 } else {
3567 (args_span.shrink_to_lo(), "move ")
3568 }
3569 }
3570 Err(_) => (args_span, "move |<args>| <body>"),
3571 };
3572 let kind = match use_span.coroutine_kind() {
3573 Some(coroutine_kind) => match coroutine_kind {
3574 CoroutineKind::Desugared(CoroutineDesugaring::Gen, kind) => match kind {
3575 CoroutineSource::Block => "gen block",
3576 CoroutineSource::Closure => "gen closure",
3577 CoroutineSource::Fn => {
3578 bug!("gen block/closure expected, but gen function found.")
3579 }
3580 },
3581 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, kind) => match kind {
3582 CoroutineSource::Block => "async gen block",
3583 CoroutineSource::Closure => "async gen closure",
3584 CoroutineSource::Fn => {
3585 bug!("gen block/closure expected, but gen function found.")
3586 }
3587 },
3588 CoroutineKind::Desugared(CoroutineDesugaring::Async, async_kind) => {
3589 match async_kind {
3590 CoroutineSource::Block => "async block",
3591 CoroutineSource::Closure => "async closure",
3592 CoroutineSource::Fn => {
3593 bug!("async block/closure expected, but async function found.")
3594 }
3595 }
3596 }
3597 CoroutineKind::Coroutine(_) => "coroutine",
3598 },
3599 None => "closure",
3600 };
3601
3602 let mut err = self.cannot_capture_in_long_lived_closure(
3603 args_span,
3604 kind,
3605 captured_var,
3606 var_span,
3607 scope,
3608 );
3609 err.span_suggestion_verbose(
3610 sugg_span,
3611 format!(
3612 "to force the {kind} to take ownership of {captured_var} (and any \
3613 other referenced variables), use the `move` keyword"
3614 ),
3615 suggestion,
3616 Applicability::MachineApplicable,
3617 );
3618
3619 match category {
3620 ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
3621 let msg = format!("{kind} is returned here");
3622 err.span_note(constraint_span, msg);
3623 }
3624 ConstraintCategory::CallArgument(_) => {
3625 fr_name.highlight_region_name(&mut err);
3626 if matches!(
3627 use_span.coroutine_kind(),
3628 Some(CoroutineKind::Desugared(CoroutineDesugaring::Async, _))
3629 ) {
3630 err.note(
3631 "async blocks are not executed immediately and must either take a \
3632 reference or ownership of outside variables they use",
3633 );
3634 } else {
3635 let msg = format!("{scope} requires argument type to outlive `{fr_name}`");
3636 err.span_note(constraint_span, msg);
3637 }
3638 }
3639 _ => bug!(
3640 "report_escaping_closure_capture called with unexpected constraint \
3641 category: `{:?}`",
3642 category
3643 ),
3644 }
3645
3646 err
3647 }
3648
3649 fn report_escaping_data(
3650 &self,
3651 borrow_span: Span,
3652 name: &Option<String>,
3653 upvar_span: Span,
3654 upvar_name: Symbol,
3655 escape_span: Span,
3656 ) -> Diag<'infcx> {
3657 let tcx = self.infcx.tcx;
3658
3659 let escapes_from = tcx.def_descr(self.mir_def_id().to_def_id());
3660
3661 let mut err =
3662 borrowck_errors::borrowed_data_escapes_closure(tcx, escape_span, escapes_from);
3663
3664 err.span_label(
3665 upvar_span,
3666 ::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"),
3667 );
3668
3669 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"));
3670
3671 if let Some(name) = name {
3672 err.span_label(
3673 escape_span,
3674 ::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"),
3675 );
3676 } else {
3677 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"));
3678 }
3679
3680 err
3681 }
3682
3683 fn get_moved_indexes(
3684 &self,
3685 location: Location,
3686 mpi: MovePathIndex,
3687 ) -> (Vec<MoveSite>, Vec<Location>) {
3688 fn predecessor_locations<'tcx>(
3689 body: &mir::Body<'tcx>,
3690 location: Location,
3691 ) -> impl Iterator<Item = Location> {
3692 if location.statement_index == 0 {
3693 let predecessors = body.basic_blocks.predecessors()[location.block].to_vec();
3694 Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb)))
3695 } else {
3696 Either::Right(std::iter::once(Location {
3697 statement_index: location.statement_index - 1,
3698 ..location
3699 }))
3700 }
3701 }
3702
3703 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];
3704 let move_paths = &self.move_data.move_paths;
3705 mpis.extend(move_paths[mpi].parents(move_paths).map(|(mpi, _)| mpi));
3706
3707 let mut stack = Vec::new();
3708 let mut back_edge_stack = Vec::new();
3709
3710 predecessor_locations(self.body, location).for_each(|predecessor| {
3711 if location.dominates(predecessor, self.dominators()) {
3712 back_edge_stack.push(predecessor)
3713 } else {
3714 stack.push(predecessor);
3715 }
3716 });
3717
3718 let mut reached_start = false;
3719
3720 let mut is_argument = false;
3722 for arg in self.body.args_iter() {
3723 if let Some(path) = self.move_data.rev_lookup.find_local(arg) {
3724 if mpis.contains(&path) {
3725 is_argument = true;
3726 }
3727 }
3728 }
3729
3730 let mut visited = FxIndexSet::default();
3731 let mut move_locations = FxIndexSet::default();
3732 let mut reinits = ::alloc::vec::Vec::new()vec![];
3733 let mut result = ::alloc::vec::Vec::new()vec![];
3734
3735 let mut dfs_iter = |result: &mut Vec<MoveSite>, location: Location, is_back_edge: bool| {
3736 {
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:3736",
"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(3736u32),
::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!(
3737 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
3738 location, is_back_edge
3739 );
3740
3741 if !visited.insert(location) {
3742 return true;
3743 }
3744
3745 let stmt_kind =
3747 self.body[location.block].statements.get(location.statement_index).map(|s| &s.kind);
3748 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
3749 } else {
3753 for moi in &self.move_data.loc_map[location] {
3761 {
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:3761",
"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(3761u32),
::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);
3762 let path = self.move_data.moves[*moi].path;
3763 if mpis.contains(&path) {
3764 {
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:3764",
"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(3764u32),
::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!(
3765 "report_use_of_moved_or_uninitialized: found {:?}",
3766 move_paths[path].place
3767 );
3768 result.push(MoveSite { moi: *moi, traversed_back_edge: is_back_edge });
3769 move_locations.insert(location);
3770
3771 return true;
3788 }
3789 }
3790 }
3791
3792 let mut any_match = false;
3794 for ii in &self.move_data.init_loc_map[location] {
3795 let init = self.move_data.inits[*ii];
3796 match init.kind {
3797 InitKind::Deep | InitKind::NonPanicPathOnly => {
3798 if mpis.contains(&init.path) {
3799 any_match = true;
3800 }
3801 }
3802 InitKind::Shallow => {
3803 if mpi == init.path {
3804 any_match = true;
3805 }
3806 }
3807 }
3808 }
3809 if any_match {
3810 reinits.push(location);
3811 return true;
3812 }
3813 false
3814 };
3815
3816 while let Some(location) = stack.pop() {
3817 if dfs_iter(&mut result, location, false) {
3818 continue;
3819 }
3820
3821 let mut has_predecessor = false;
3822 predecessor_locations(self.body, location).for_each(|predecessor| {
3823 if location.dominates(predecessor, self.dominators()) {
3824 back_edge_stack.push(predecessor)
3825 } else {
3826 stack.push(predecessor);
3827 }
3828 has_predecessor = true;
3829 });
3830
3831 if !has_predecessor {
3832 reached_start = true;
3833 }
3834 }
3835 if (is_argument || !reached_start) && result.is_empty() {
3836 while let Some(location) = back_edge_stack.pop() {
3843 if dfs_iter(&mut result, location, true) {
3844 continue;
3845 }
3846
3847 predecessor_locations(self.body, location)
3848 .for_each(|predecessor| back_edge_stack.push(predecessor));
3849 }
3850 }
3851
3852 let reinits_reachable = reinits
3854 .into_iter()
3855 .filter(|reinit| {
3856 let mut visited = FxIndexSet::default();
3857 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];
3858 while let Some(location) = stack.pop() {
3859 if !visited.insert(location) {
3860 continue;
3861 }
3862 if move_locations.contains(&location) {
3863 return true;
3864 }
3865 stack.extend(predecessor_locations(self.body, location));
3866 }
3867 false
3868 })
3869 .collect::<Vec<Location>>();
3870 (result, reinits_reachable)
3871 }
3872
3873 pub(crate) fn report_illegal_mutation_of_borrowed(
3874 &mut self,
3875 location: Location,
3876 (place, span): (Place<'tcx>, Span),
3877 loan: &BorrowData<'tcx>,
3878 ) {
3879 let loan_spans = self.retrieve_borrow_spans(loan);
3880 let loan_span = loan_spans.args_or_use();
3881
3882 let descr_place = self.describe_any_place(place.as_ref());
3883 if let BorrowKind::Fake(_) = loan.kind
3884 && let Some(section) = self.classify_immutable_section(loan.assigned_place)
3885 {
3886 let mut err = self.cannot_mutate_in_immutable_section(
3887 span,
3888 loan_span,
3889 &descr_place,
3890 section,
3891 "assign",
3892 );
3893
3894 loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3895 use crate::session_diagnostics::CaptureVarCause::*;
3896 match kind {
3897 hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3898 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3899 BorrowUseInClosure { var_span }
3900 }
3901 }
3902 });
3903
3904 self.buffer_error(err);
3905
3906 return;
3907 }
3908
3909 let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place);
3910 self.note_due_to_edition_2024_opaque_capture_rules(loan, &mut err);
3911
3912 loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3913 use crate::session_diagnostics::CaptureVarCause::*;
3914 match kind {
3915 hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3916 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3917 BorrowUseInClosure { var_span }
3918 }
3919 }
3920 });
3921
3922 self.explain_why_borrow_contains_point(location, loan, None)
3923 .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3924
3925 self.explain_deref_coercion(loan, &mut err);
3926
3927 self.buffer_error(err);
3928 }
3929
3930 fn explain_deref_coercion(&mut self, loan: &BorrowData<'tcx>, err: &mut Diag<'_>) {
3931 let tcx = self.infcx.tcx;
3932 if let Some(Terminator { kind: TerminatorKind::Call { call_source, fn_span, .. }, .. }) =
3933 &self.body[loan.reserve_location.block].terminator
3934 && let Some((method_did, method_args)) = mir::find_self_call(
3935 tcx,
3936 self.body,
3937 loan.assigned_place.local,
3938 loan.reserve_location.block,
3939 )
3940 && let CallKind::DerefCoercion { deref_target_span, deref_target_ty, .. } = call_kind(
3941 self.infcx.tcx,
3942 self.infcx.typing_env(self.infcx.param_env),
3943 method_did,
3944 method_args,
3945 *fn_span,
3946 call_source.from_hir_call(),
3947 self.infcx.tcx.fn_arg_idents(method_did)[0],
3948 )
3949 {
3950 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}`"));
3951 if let Some(deref_target_span) = deref_target_span {
3952 err.span_note(deref_target_span, "deref defined here");
3953 }
3954 }
3955 }
3956
3957 pub(crate) fn report_illegal_reassignment(
3964 &mut self,
3965 (place, span): (Place<'tcx>, Span),
3966 assigned_span: Span,
3967 err_place: Place<'tcx>,
3968 ) {
3969 let (from_arg, local_decl) = match err_place.as_local() {
3970 Some(local) => {
3971 (self.body.local_kind(local) == LocalKind::Arg, Some(&self.body.local_decls[local]))
3972 }
3973 None => (false, None),
3974 };
3975
3976 let (place_description, assigned_span) = match local_decl {
3980 Some(LocalDecl {
3981 local_info:
3982 ClearCrossCrate::Set(
3983 box LocalInfo::User(BindingForm::Var(VarBindingForm {
3984 opt_match_place: None,
3985 ..
3986 }))
3987 | box LocalInfo::StaticRef { .. }
3988 | box LocalInfo::Boring,
3989 ),
3990 ..
3991 })
3992 | None => (self.describe_any_place(place.as_ref()), assigned_span),
3993 Some(decl) => (self.describe_any_place(err_place.as_ref()), decl.source_info.span),
3994 };
3995 let mut err = self.cannot_reassign_immutable(span, &place_description, from_arg);
3996 let msg = if from_arg {
3997 "cannot assign to immutable argument"
3998 } else {
3999 "cannot assign twice to immutable variable"
4000 };
4001 if span != assigned_span && !from_arg {
4002 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}"));
4003 }
4004 if let Some(decl) = local_decl
4005 && decl.can_be_made_mutable()
4006 {
4007 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!(
4008 decl.local_info(),
4009 LocalInfo::User(BindingForm::Var(VarBindingForm {
4010 opt_match_place: Some((_, match_span)),
4011 ..
4012 })) if matches!(match_span.desugaring_kind(), Some(DesugaringKind::ForLoop))
4013 );
4014 let message = if is_for_loop
4015 && let Ok(binding_name) =
4016 self.infcx.tcx.sess.source_map().span_to_snippet(decl.source_info.span)
4017 {
4018 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("(mut {0}) ", binding_name))
})format!("(mut {}) ", binding_name)
4019 } else {
4020 "mut ".to_string()
4021 };
4022 err.span_suggestion_verbose(
4023 decl.source_info.span.shrink_to_lo(),
4024 "consider making this binding mutable",
4025 message,
4026 Applicability::MachineApplicable,
4027 );
4028
4029 if !from_arg
4030 && !is_for_loop
4031 && #[allow(non_exhaustive_omitted_patterns)] match decl.local_info() {
LocalInfo::User(BindingForm::Var(VarBindingForm {
opt_match_place: Some((Some(_), _)), .. })) => true,
_ => false,
}matches!(
4032 decl.local_info(),
4033 LocalInfo::User(BindingForm::Var(VarBindingForm {
4034 opt_match_place: Some((Some(_), _)),
4035 ..
4036 }))
4037 )
4038 {
4039 err.span_suggestion_verbose(
4040 decl.source_info.span.shrink_to_lo(),
4041 "to modify the original value, take a borrow instead",
4042 "ref mut ".to_string(),
4043 Applicability::MaybeIncorrect,
4044 );
4045 }
4046 }
4047 err.span_label(span, msg);
4048 self.buffer_error(err);
4049 }
4050
4051 fn classify_drop_access_kind(&self, place: PlaceRef<'tcx>) -> StorageDeadOrDrop<'tcx> {
4052 let tcx = self.infcx.tcx;
4053 let (kind, _place_ty) = place.projection.iter().fold(
4054 (LocalStorageDead, PlaceTy::from_ty(self.body.local_decls[place.local].ty)),
4055 |(kind, place_ty), &elem| {
4056 (
4057 match elem {
4058 ProjectionElem::Deref => match kind {
4059 StorageDeadOrDrop::LocalStorageDead
4060 | StorageDeadOrDrop::BoxedStorageDead => {
4061 if !place_ty.ty.is_box() {
{
::core::panicking::panic_fmt(format_args!("Drop of value behind a reference or raw pointer"));
}
};assert!(
4062 place_ty.ty.is_box(),
4063 "Drop of value behind a reference or raw pointer"
4064 );
4065 StorageDeadOrDrop::BoxedStorageDead
4066 }
4067 StorageDeadOrDrop::Destructor(_) => kind,
4068 },
4069 ProjectionElem::OpaqueCast { .. }
4070 | ProjectionElem::Field(..)
4071 | ProjectionElem::Downcast(..) => {
4072 match place_ty.ty.kind() {
4073 ty::Adt(def, _) if def.has_dtor(tcx) => {
4074 match kind {
4076 StorageDeadOrDrop::Destructor(_) => kind,
4077 StorageDeadOrDrop::LocalStorageDead
4078 | StorageDeadOrDrop::BoxedStorageDead => {
4079 StorageDeadOrDrop::Destructor(place_ty.ty)
4080 }
4081 }
4082 }
4083 _ => kind,
4084 }
4085 }
4086 ProjectionElem::ConstantIndex { .. }
4087 | ProjectionElem::Subslice { .. }
4088 | ProjectionElem::Index(_)
4089 | ProjectionElem::UnwrapUnsafeBinder(_) => kind,
4090 },
4091 place_ty.projection_ty(tcx, elem),
4092 )
4093 },
4094 );
4095 kind
4096 }
4097
4098 fn classify_immutable_section(&self, place: Place<'tcx>) -> Option<&'static str> {
4100 use rustc_middle::mir::visit::Visitor;
4101 struct FakeReadCauseFinder<'tcx> {
4102 place: Place<'tcx>,
4103 cause: Option<FakeReadCause>,
4104 }
4105 impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'tcx> {
4106 fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
4107 match statement {
4108 Statement { kind: StatementKind::FakeRead(box (cause, place)), .. }
4109 if *place == self.place =>
4110 {
4111 self.cause = Some(*cause);
4112 }
4113 _ => (),
4114 }
4115 }
4116 }
4117 let mut visitor = FakeReadCauseFinder { place, cause: None };
4118 visitor.visit_body(self.body);
4119 match visitor.cause {
4120 Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
4121 Some(FakeReadCause::ForIndex) => Some("indexing expression"),
4122 _ => None,
4123 }
4124 }
4125
4126 fn annotate_argument_and_return_for_borrow(
4129 &self,
4130 borrow: &BorrowData<'tcx>,
4131 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4132 let fallback = || {
4134 let is_closure = self.infcx.tcx.is_closure_like(self.mir_def_id().to_def_id());
4135 if is_closure {
4136 None
4137 } else {
4138 let ty = self.infcx.tcx.type_of(self.mir_def_id()).instantiate_identity();
4139 match ty.kind() {
4140 ty::FnDef(_, _) | ty::FnPtr(..) => self.annotate_fn_sig(
4141 self.mir_def_id(),
4142 self.infcx.tcx.fn_sig(self.mir_def_id()).instantiate_identity(),
4143 ),
4144 _ => None,
4145 }
4146 }
4147 };
4148
4149 let location = borrow.reserve_location;
4156 {
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:4156",
"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(4156u32),
::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);
4157 if let Some(Statement { kind: StatementKind::Assign(box (reservation, _)), .. }) =
4158 &self.body[location.block].statements.get(location.statement_index)
4159 {
4160 {
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:4160",
"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(4160u32),
::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);
4161 let mut target = match reservation.as_local() {
4163 Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
4164 _ => return None,
4165 };
4166
4167 let mut annotated_closure = None;
4170 for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
4171 {
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:4171",
"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(4171u32),
::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!(
4172 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
4173 target, stmt
4174 );
4175 if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind
4176 && let Some(assigned_to) = place.as_local()
4177 {
4178 {
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:4178",
"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(4178u32),
::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!(
4179 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
4180 rvalue={:?}",
4181 assigned_to, rvalue
4182 );
4183 if let Rvalue::Aggregate(box AggregateKind::Closure(def_id, args), operands) =
4185 rvalue
4186 {
4187 let def_id = def_id.expect_local();
4188 for operand in operands {
4189 let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4190 operand
4191 else {
4192 continue;
4193 };
4194 {
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:4194",
"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(4194u32),
::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!(
4195 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4196 assigned_from
4197 );
4198
4199 let Some(assigned_from_local) = assigned_from.local_or_deref_local()
4201 else {
4202 continue;
4203 };
4204
4205 if assigned_from_local != target {
4206 continue;
4207 }
4208
4209 annotated_closure =
4213 self.annotate_fn_sig(def_id, args.as_closure().sig());
4214 {
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:4214",
"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(4214u32),
::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!(
4215 "annotate_argument_and_return_for_borrow: \
4216 annotated_closure={:?} assigned_from_local={:?} \
4217 assigned_to={:?}",
4218 annotated_closure, assigned_from_local, assigned_to
4219 );
4220
4221 if assigned_to == mir::RETURN_PLACE {
4222 return annotated_closure;
4225 } else {
4226 target = assigned_to;
4228 }
4229 }
4230
4231 continue;
4234 }
4235
4236 let assigned_from = match rvalue {
4238 Rvalue::Ref(_, _, assigned_from) => assigned_from,
4239 Rvalue::Use(operand) => match operand {
4240 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
4241 assigned_from
4242 }
4243 _ => continue,
4244 },
4245 _ => continue,
4246 };
4247 {
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:4247",
"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(4247u32),
::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!(
4248 "annotate_argument_and_return_for_borrow: \
4249 assigned_from={:?}",
4250 assigned_from,
4251 );
4252
4253 let Some(assigned_from_local) = assigned_from.local_or_deref_local() else {
4255 continue;
4256 };
4257 {
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:4257",
"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(4257u32),
::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!(
4258 "annotate_argument_and_return_for_borrow: \
4259 assigned_from_local={:?}",
4260 assigned_from_local,
4261 );
4262
4263 if assigned_from_local != target {
4266 continue;
4267 }
4268
4269 {
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:4271",
"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(4271u32),
::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!(
4272 "annotate_argument_and_return_for_borrow: \
4273 assigned_from_local={:?} assigned_to={:?}",
4274 assigned_from_local, assigned_to
4275 );
4276 if assigned_to == mir::RETURN_PLACE {
4277 return annotated_closure.or_else(fallback);
4280 }
4281
4282 target = assigned_to;
4285 }
4286 }
4287
4288 let terminator = &self.body[location.block].terminator();
4290 {
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:4290",
"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(4290u32),
::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!(
4291 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
4292 target, terminator
4293 );
4294 if let TerminatorKind::Call { destination, target: Some(_), args, .. } =
4295 &terminator.kind
4296 && let Some(assigned_to) = destination.as_local()
4297 {
4298 {
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:4298",
"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(4298u32),
::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!(
4299 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
4300 assigned_to, args
4301 );
4302 for operand in args {
4303 let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4304 &operand.node
4305 else {
4306 continue;
4307 };
4308 {
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:4308",
"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(4308u32),
::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!(
4309 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4310 assigned_from,
4311 );
4312
4313 if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
4314 {
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:4314",
"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(4314u32),
::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!(
4315 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
4316 assigned_from_local,
4317 );
4318
4319 if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
4320 return annotated_closure.or_else(fallback);
4321 }
4322 }
4323 }
4324 }
4325 }
4326
4327 {
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:4329",
"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(4329u32),
::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");
4330 None
4331 }
4332
4333 fn annotate_fn_sig(
4336 &self,
4337 did: LocalDefId,
4338 sig: ty::PolyFnSig<'tcx>,
4339 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
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_fn_sig: did={0:?} sig={1:?}",
did, sig) as &dyn Value))])
});
} else { ; }
};debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
4341 let is_closure = self.infcx.tcx.is_closure_like(did.to_def_id());
4342 let fn_hir_id = self.infcx.tcx.local_def_id_to_hir_id(did);
4343 let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(fn_hir_id)?;
4344
4345 let return_ty = sig.output();
4368 match return_ty.skip_binder().kind() {
4369 ty::Ref(return_region, _, _)
4370 if return_region.is_named(self.infcx.tcx) && !is_closure =>
4371 {
4372 let mut arguments = Vec::new();
4375 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
4376 if let ty::Ref(argument_region, _, _) = argument.kind()
4377 && argument_region == return_region
4378 {
4379 match &fn_decl.inputs[index].kind {
4383 hir::TyKind::Ref(lifetime, _) => {
4384 arguments.push((*argument, lifetime.ident.span));
4387 }
4388 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
4390 if let Res::SelfTyAlias { alias_to, .. } = path.res
4391 && let Some(alias_to) = alias_to.as_local()
4392 && let hir::Impl { self_ty, .. } = self
4393 .infcx
4394 .tcx
4395 .hir_node_by_def_id(alias_to)
4396 .expect_item()
4397 .expect_impl()
4398 && let hir::TyKind::Ref(lifetime, _) = self_ty.kind
4399 {
4400 arguments.push((*argument, lifetime.ident.span));
4401 }
4402 }
4403 _ => {
4404 }
4406 }
4407 }
4408 }
4409
4410 if arguments.is_empty() {
4412 return None;
4413 }
4414
4415 let return_ty = sig.output().skip_binder();
4418 let mut return_span = fn_decl.output.span();
4419 if let hir::FnRetTy::Return(ty) = &fn_decl.output
4420 && let hir::TyKind::Ref(lifetime, _) = ty.kind
4421 {
4422 return_span = lifetime.ident.span;
4423 }
4424
4425 Some(AnnotatedBorrowFnSignature::NamedFunction {
4426 arguments,
4427 return_ty,
4428 return_span,
4429 })
4430 }
4431 ty::Ref(_, _, _) if is_closure => {
4432 let argument_span = fn_decl.inputs.first()?.span;
4436 let argument_ty = sig.inputs().skip_binder().first()?;
4437
4438 if let ty::Tuple(elems) = argument_ty.kind() {
4441 let &argument_ty = elems.first()?;
4442 if let ty::Ref(_, _, _) = argument_ty.kind() {
4443 return Some(AnnotatedBorrowFnSignature::Closure {
4444 argument_ty,
4445 argument_span,
4446 });
4447 }
4448 }
4449
4450 None
4451 }
4452 ty::Ref(_, _, _) => {
4453 let argument_span = fn_decl.inputs.first()?.span;
4456 let argument_ty = *sig.inputs().skip_binder().first()?;
4457
4458 let return_span = fn_decl.output.span();
4459 let return_ty = sig.output().skip_binder();
4460
4461 match argument_ty.kind() {
4463 ty::Ref(_, _, _) => {}
4464 _ => return None,
4465 }
4466
4467 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
4468 argument_ty,
4469 argument_span,
4470 return_ty,
4471 return_span,
4472 })
4473 }
4474 _ => {
4475 None
4478 }
4479 }
4480 }
4481}
4482
4483#[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)]
4484enum AnnotatedBorrowFnSignature<'tcx> {
4485 NamedFunction {
4486 arguments: Vec<(Ty<'tcx>, Span)>,
4487 return_ty: Ty<'tcx>,
4488 return_span: Span,
4489 },
4490 AnonymousFunction {
4491 argument_ty: Ty<'tcx>,
4492 argument_span: Span,
4493 return_ty: Ty<'tcx>,
4494 return_span: Span,
4495 },
4496 Closure {
4497 argument_ty: Ty<'tcx>,
4498 argument_span: Span,
4499 },
4500}
4501
4502impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
4503 pub(crate) fn emit(&self, cx: &MirBorrowckCtxt<'_, '_, 'tcx>, diag: &mut Diag<'_>) -> String {
4506 match self {
4507 &AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
4508 diag.span_label(
4509 argument_span,
4510 ::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)),
4511 );
4512
4513 cx.get_region_name_for_ty(argument_ty, 0)
4514 }
4515 &AnnotatedBorrowFnSignature::AnonymousFunction {
4516 argument_ty,
4517 argument_span,
4518 return_ty,
4519 return_span,
4520 } => {
4521 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
4522 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}`"));
4523
4524 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
4525 let types_equal = return_ty_name == argument_ty_name;
4526 diag.span_label(
4527 return_span,
4528 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}has type `{1}`",
if types_equal { "also " } else { "" }, return_ty_name))
})format!(
4529 "{}has type `{}`",
4530 if types_equal { "also " } else { "" },
4531 return_ty_name,
4532 ),
4533 );
4534
4535 diag.note(
4536 "argument and return type have the same lifetime due to lifetime elision rules",
4537 );
4538 diag.note(
4539 "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
4540 lifetime-syntax.html#lifetime-elision>",
4541 );
4542
4543 cx.get_region_name_for_ty(return_ty, 0)
4544 }
4545 AnnotatedBorrowFnSignature::NamedFunction { arguments, return_ty, return_span } => {
4546 let region_name = cx.get_region_name_for_ty(*return_ty, 0);
4548 for (_, argument_span) in arguments {
4549 diag.span_label(*argument_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("has lifetime `{0}`", region_name))
})format!("has lifetime `{region_name}`"));
4550 }
4551
4552 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}`",));
4553
4554 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!(
4555 "use data from the highlighted arguments which match the `{region_name}` lifetime of \
4556 the return type",
4557 ));
4558
4559 region_name
4560 }
4561 }
4562 }
4563}
4564
4565struct ReferencedStatementsVisitor<'a>(&'a [Span]);
4567
4568impl<'v> Visitor<'v> for ReferencedStatementsVisitor<'_> {
4569 type Result = ControlFlow<()>;
4570 fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) -> Self::Result {
4571 match s.kind {
4572 hir::StmtKind::Semi(expr) if self.0.contains(&expr.span) => ControlFlow::Break(()),
4573 _ => ControlFlow::Continue(()),
4574 }
4575 }
4576}
4577
4578struct BreakFinder {
4582 found_breaks: Vec<(hir::Destination, Span)>,
4583 found_continues: Vec<(hir::Destination, Span)>,
4584}
4585impl<'hir> Visitor<'hir> for BreakFinder {
4586 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
4587 match ex.kind {
4588 hir::ExprKind::Break(destination, _)
4589 if !ex.span.is_desugaring(DesugaringKind::ForLoop) =>
4590 {
4591 self.found_breaks.push((destination, ex.span));
4592 }
4593 hir::ExprKind::Continue(destination) => {
4594 self.found_continues.push((destination, ex.span));
4595 }
4596 _ => {}
4597 }
4598 hir::intravisit::walk_expr(self, ex);
4599 }
4600}
4601
4602struct ConditionVisitor<'tcx> {
4605 tcx: TyCtxt<'tcx>,
4606 spans: Vec<Span>,
4607 name: String,
4608 errors: Vec<(Span, String)>,
4609}
4610
4611impl<'v, 'tcx> Visitor<'v> for ConditionVisitor<'tcx> {
4612 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
4613 match ex.kind {
4614 hir::ExprKind::If(cond, body, None) => {
4615 if ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break() {
4618 self.errors.push((
4619 cond.span,
4620 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this `if` condition is `false`, {0} is not initialized",
self.name))
})format!(
4621 "if this `if` condition is `false`, {} is not initialized",
4622 self.name,
4623 ),
4624 ));
4625 self.errors.push((
4626 ex.span.shrink_to_hi(),
4627 ::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),
4628 ));
4629 }
4630 }
4631 hir::ExprKind::If(cond, body, Some(other)) => {
4632 let a = ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break();
4635 let b = ReferencedStatementsVisitor(&self.spans).visit_expr(other).is_break();
4636 match (a, b) {
4637 (true, true) | (false, false) => {}
4638 (true, false) => {
4639 if other.span.is_desugaring(DesugaringKind::WhileLoop) {
4640 self.errors.push((
4641 cond.span,
4642 ::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!(
4643 "if this condition isn't met and the `while` loop runs 0 \
4644 times, {} is not initialized",
4645 self.name
4646 ),
4647 ));
4648 } else {
4649 self.errors.push((
4650 body.span.shrink_to_hi().until(other.span),
4651 ::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!(
4652 "if the `if` condition is `false` and this `else` arm is \
4653 executed, {} is not initialized",
4654 self.name
4655 ),
4656 ));
4657 }
4658 }
4659 (false, true) => {
4660 self.errors.push((
4661 cond.span,
4662 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this condition is `true`, {0} is not initialized",
self.name))
})format!(
4663 "if this condition is `true`, {} is not initialized",
4664 self.name
4665 ),
4666 ));
4667 }
4668 }
4669 }
4670 hir::ExprKind::Match(e, arms, loop_desugar) => {
4671 let results: Vec<bool> = arms
4674 .iter()
4675 .map(|arm| ReferencedStatementsVisitor(&self.spans).visit_arm(arm).is_break())
4676 .collect();
4677 if results.iter().any(|x| *x) && !results.iter().all(|x| *x) {
4678 for (arm, seen) in arms.iter().zip(results) {
4679 if !seen {
4680 if loop_desugar == hir::MatchSource::ForLoopDesugar {
4681 self.errors.push((
4682 e.span,
4683 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if the `for` loop runs 0 times, {0} is not initialized",
self.name))
})format!(
4684 "if the `for` loop runs 0 times, {} is not initialized",
4685 self.name
4686 ),
4687 ));
4688 } else if let Some(guard) = &arm.guard {
4689 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!(
4690 self.tcx.hir_node(arm.body.hir_id),
4691 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4692 ) {
4693 continue;
4694 }
4695 self.errors.push((
4696 arm.pat.span.to(guard.span),
4697 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this pattern and condition are matched, {0} is not initialized",
self.name))
})format!(
4698 "if this pattern and condition are matched, {} is not \
4699 initialized",
4700 self.name
4701 ),
4702 ));
4703 } else {
4704 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!(
4705 self.tcx.hir_node(arm.body.hir_id),
4706 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4707 ) {
4708 continue;
4709 }
4710 self.errors.push((
4711 arm.pat.span,
4712 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this pattern is matched, {0} is not initialized",
self.name))
})format!(
4713 "if this pattern is matched, {} is not initialized",
4714 self.name
4715 ),
4716 ));
4717 }
4718 }
4719 }
4720 }
4721 }
4722 _ => {}
4727 }
4728 walk_expr(self, ex);
4729 }
4730}