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