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, Ident, 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_receiver_is_total_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 = <[_]>::into_vec(::alloc::boxed::box_new([(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_verbose(
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 <[_]>::into_vec(::alloc::boxed::box_new([(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 | DefKind::ConstParam | DefKind::Static { .. } | DefKind::AssocConst,
1161 _,
1162 )) = path.res
1163 else {
1164 return;
1165 };
1166 let Ok(base_str) = self.infcx.tcx.sess.source_map().span_to_snippet(base.span) else {
1167 return;
1168 };
1169
1170 let mut final_field_count = fields.len();
1176 let Some(variant) = def.variants().iter().find(|variant| variant.def_id == def_id) else {
1177 return;
1180 };
1181 let mut sugg = ::alloc::vec::Vec::new()vec![];
1182 for field in &variant.fields {
1183 let field_ty = field.ty(self.infcx.tcx, args);
1187 let ident = field.ident(self.infcx.tcx);
1188 if field_ty == ty && fields.iter().all(|field| field.ident.name != ident.name) {
1189 sugg.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}.{0}.clone()", ident,
base_str))
})format!("{ident}: {base_str}.{ident}.clone()"));
1191 final_field_count += 1;
1192 }
1193 }
1194 let (span, sugg) = match fields {
1195 [.., last] => (
1196 if final_field_count == variant.fields.len() {
1197 last.span.shrink_to_hi().with_hi(base.span.hi())
1199 } else {
1200 last.span.shrink_to_hi()
1201 },
1202 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", sugg.join(", ")))
})format!(", {}", sugg.join(", ")),
1203 ),
1204 [] => (
1206 expr.span.with_lo(struct_qpath.span().hi()),
1207 if final_field_count == variant.fields.len() {
1208 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{ {0} }}", sugg.join(", ")))
})format!(" {{ {} }}", sugg.join(", "))
1210 } else {
1211 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{ {0}, ..{1} }}",
sugg.join(", "), base_str))
})format!(" {{ {}, ..{base_str} }}", sugg.join(", "))
1212 },
1213 ),
1214 };
1215 let prefix = if !self.implements_clone(ty) {
1216 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`");
1217 if let ty::Adt(def, _) = ty.kind() {
1218 err.span_note(self.infcx.tcx.def_span(def.did()), msg);
1219 } else {
1220 err.note(msg);
1221 }
1222 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if `{0}` implemented `Clone`, you could ",
ty))
})format!("if `{ty}` implemented `Clone`, you could ")
1223 } else {
1224 String::new()
1225 };
1226 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!(
1227 "{prefix}clone the value from the field instead of using the functional record update \
1228 syntax",
1229 );
1230 err.span_suggestion_verbose(span, msg, sugg, Applicability::MachineApplicable);
1231 }
1232
1233 pub(crate) fn suggest_cloning(
1234 &self,
1235 err: &mut Diag<'_>,
1236 place: PlaceRef<'tcx>,
1237 ty: Ty<'tcx>,
1238 expr: &'tcx hir::Expr<'tcx>,
1239 use_spans: Option<UseSpans<'tcx>>,
1240 ) {
1241 if let hir::ExprKind::Struct(_, _, hir::StructTailExpr::Base(_)) = expr.kind {
1242 self.suggest_cloning_on_functional_record_update(err, ty, expr);
1247 return;
1248 }
1249
1250 if self.implements_clone(ty) {
1251 if self.in_move_closure(expr) {
1252 if let Some(name) = self.describe_place(place) {
1253 self.suggest_clone_of_captured_var_in_move_closure(err, &name, use_spans);
1254 }
1255 } else {
1256 self.suggest_cloning_inner(err, ty, expr);
1257 }
1258 } else if let ty::Adt(def, args) = ty.kind()
1259 && let Some(local_did) = def.did().as_local()
1260 && def.variants().iter().all(|variant| {
1261 variant
1262 .fields
1263 .iter()
1264 .all(|field| self.implements_clone(field.ty(self.infcx.tcx, args)))
1265 })
1266 {
1267 let ty_span = self.infcx.tcx.def_span(def.did());
1268 let mut span: MultiSpan = ty_span.into();
1269 let mut derive_clone = false;
1270 self.infcx.tcx.for_each_relevant_impl(
1271 self.infcx.tcx.lang_items().clone_trait().unwrap(),
1272 ty,
1273 |def_id| {
1274 if self.infcx.tcx.is_automatically_derived(def_id) {
1275 derive_clone = true;
1276 span.push_span_label(
1277 self.infcx.tcx.def_span(def_id),
1278 "derived `Clone` adds implicit bounds on type parameters",
1279 );
1280 if let Some(generics) = self.infcx.tcx.hir_get_generics(local_did) {
1281 for param in generics.params {
1282 if let hir::GenericParamKind::Type { .. } = param.kind {
1283 span.push_span_label(
1284 param.span,
1285 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("introduces an implicit `{0}: Clone` bound",
param.name.ident()))
})format!(
1286 "introduces an implicit `{}: Clone` bound",
1287 param.name.ident()
1288 ),
1289 );
1290 }
1291 }
1292 }
1293 }
1294 },
1295 );
1296 let msg = if !derive_clone {
1297 span.push_span_label(
1298 ty_span,
1299 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider {0}implementing `Clone` for this type",
if derive_clone { "manually " } else { "" }))
})format!(
1300 "consider {}implementing `Clone` for this type",
1301 if derive_clone { "manually " } else { "" }
1302 ),
1303 );
1304 ::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")
1305 } else {
1306 ::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")
1307 };
1308 span.push_span_label(expr.span, "you could clone this value");
1309 err.span_note(span, msg);
1310 if derive_clone {
1311 err.help("consider manually implementing `Clone` to avoid undesired bounds");
1312 }
1313 } else if let ty::Param(param) = ty.kind()
1314 && let Some(_clone_trait_def) = self.infcx.tcx.lang_items().clone_trait()
1315 && let generics = self.infcx.tcx.generics_of(self.mir_def_id())
1316 && let generic_param = generics.type_param(*param, self.infcx.tcx)
1317 && let param_span = self.infcx.tcx.def_span(generic_param.def_id)
1318 && if let Some(UseSpans::FnSelfUse { kind, .. }) = use_spans
1319 && let CallKind::FnCall { fn_trait_id, self_ty } = kind
1320 && let ty::Param(_) = self_ty.kind()
1321 && ty == self_ty
1322 && self.infcx.tcx.fn_trait_kind_from_def_id(fn_trait_id).is_some()
1323 {
1324 false
1326 } else {
1327 true
1328 }
1329 {
1330 let mut span: MultiSpan = param_span.into();
1331 span.push_span_label(
1332 param_span,
1333 "consider constraining this type parameter with `Clone`",
1334 );
1335 span.push_span_label(expr.span, "you could clone this value");
1336 err.span_help(
1337 span,
1338 ::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"),
1339 );
1340 } else if let ty::Adt(_, _) = ty.kind()
1341 && let Some(clone_trait) = self.infcx.tcx.lang_items().clone_trait()
1342 {
1343 let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1346 let cause = ObligationCause::misc(expr.span, self.mir_def_id());
1347 ocx.register_bound(cause, self.infcx.param_env, ty, clone_trait);
1348 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1349 if errors.iter().all(|error| {
1350 match error.obligation.predicate.as_clause().and_then(|c| c.as_trait_clause()) {
1351 Some(clause) => match clause.self_ty().skip_binder().kind() {
1352 ty::Adt(def, _) => def.did().is_local() && clause.def_id() == clone_trait,
1353 _ => false,
1354 },
1355 None => false,
1356 }
1357 }) {
1358 let mut type_spans = ::alloc::vec::Vec::new()vec![];
1359 let mut types = FxIndexSet::default();
1360 for clause in errors
1361 .iter()
1362 .filter_map(|e| e.obligation.predicate.as_clause())
1363 .filter_map(|c| c.as_trait_clause())
1364 {
1365 let ty::Adt(def, _) = clause.self_ty().skip_binder().kind() else { continue };
1366 type_spans.push(self.infcx.tcx.def_span(def.did()));
1367 types.insert(
1368 self.infcx
1369 .tcx
1370 .short_string(clause.self_ty().skip_binder(), &mut err.long_ty_path()),
1371 );
1372 }
1373 let mut span: MultiSpan = type_spans.clone().into();
1374 for sp in type_spans {
1375 span.push_span_label(sp, "consider implementing `Clone` for this type");
1376 }
1377 span.push_span_label(expr.span, "you could clone this value");
1378 let types: Vec<_> = types.into_iter().collect();
1379 let msg = match &types[..] {
1380 [only] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", only))
})format!("`{only}`"),
1381 [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!(
1382 "{} and `{last}`",
1383 head.iter().map(|t| format!("`{t}`")).collect::<Vec<_>>().join(", ")
1384 ),
1385 [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1386 };
1387 err.span_note(
1388 span,
1389 ::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"),
1390 );
1391 }
1392 }
1393 }
1394
1395 pub(crate) fn implements_clone(&self, ty: Ty<'tcx>) -> bool {
1396 let Some(clone_trait_def) = self.infcx.tcx.lang_items().clone_trait() else { return false };
1397 self.infcx
1398 .type_implements_trait(clone_trait_def, [ty], self.infcx.param_env)
1399 .must_apply_modulo_regions()
1400 }
1401
1402 pub(crate) fn clone_on_reference(&self, expr: &hir::Expr<'_>) -> Option<Span> {
1405 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1406 if let hir::ExprKind::MethodCall(segment, rcvr, args, span) = expr.kind
1407 && let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id)
1408 && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
1409 && rcvr_ty == expr_ty
1410 && segment.ident.name == sym::clone
1411 && args.is_empty()
1412 {
1413 Some(span)
1414 } else {
1415 None
1416 }
1417 }
1418
1419 fn in_move_closure(&self, expr: &hir::Expr<'_>) -> bool {
1420 for (_, node) in self.infcx.tcx.hir_parent_iter(expr.hir_id) {
1421 if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) = node
1422 && let hir::CaptureBy::Value { .. } = closure.capture_clause
1423 {
1424 return true;
1426 }
1427 }
1428 false
1429 }
1430
1431 fn suggest_cloning_inner(
1432 &self,
1433 err: &mut Diag<'_>,
1434 ty: Ty<'tcx>,
1435 expr: &hir::Expr<'_>,
1436 ) -> bool {
1437 let tcx = self.infcx.tcx;
1438 if let Some(_) = self.clone_on_reference(expr) {
1439 return false;
1442 }
1443 if self.in_move_closure(expr) {
1446 return false;
1447 }
1448 if let hir::ExprKind::Closure(_) = expr.kind {
1451 return false;
1452 }
1453 let mut suggestion =
1455 if let Some(symbol) = tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1456 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}.clone()", symbol))
})format!(": {symbol}.clone()")
1457 } else {
1458 ".clone()".to_owned()
1459 };
1460 let mut sugg = Vec::with_capacity(2);
1461 let mut inner_expr = expr;
1462 let mut is_raw_ptr = false;
1463 let typeck_result = self.infcx.tcx.typeck(self.mir_def_id());
1464 while let hir::ExprKind::AddrOf(.., inner) | hir::ExprKind::Unary(hir::UnOp::Deref, inner) =
1466 &inner_expr.kind
1467 {
1468 if let hir::ExprKind::AddrOf(_, hir::Mutability::Mut, _) = inner_expr.kind {
1469 return false;
1472 }
1473 inner_expr = inner;
1474 if let Some(inner_type) = typeck_result.node_type_opt(inner.hir_id) {
1475 if #[allow(non_exhaustive_omitted_patterns)] match inner_type.kind() {
ty::RawPtr(..) => true,
_ => false,
}matches!(inner_type.kind(), ty::RawPtr(..)) {
1476 is_raw_ptr = true;
1477 break;
1478 }
1479 }
1480 }
1481 if inner_expr.span.lo() != expr.span.lo() && !is_raw_ptr {
1484 sugg.push((expr.span.with_hi(inner_expr.span.lo()), String::new()));
1486 }
1487 let span = if inner_expr.span.hi() != expr.span.hi() {
1489 if is_raw_ptr {
1491 expr.span.shrink_to_hi()
1492 } else {
1493 expr.span.with_lo(inner_expr.span.hi())
1495 }
1496 } else {
1497 if is_raw_ptr {
1498 sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
1499 suggestion = ").clone()".to_string();
1500 }
1501 expr.span.shrink_to_hi()
1502 };
1503 sugg.push((span, suggestion));
1504 let msg = if let ty::Adt(def, _) = ty.kind()
1505 && [tcx.get_diagnostic_item(sym::Arc), tcx.get_diagnostic_item(sym::Rc)]
1506 .contains(&Some(def.did()))
1507 {
1508 "clone the value to increment its reference count"
1509 } else {
1510 "consider cloning the value if the performance cost is acceptable"
1511 };
1512 err.multipart_suggestion_verbose(msg, sugg, Applicability::MachineApplicable);
1513 true
1514 }
1515
1516 fn suggest_adding_bounds(&self, err: &mut Diag<'_>, ty: Ty<'tcx>, def_id: DefId, span: Span) {
1517 let tcx = self.infcx.tcx;
1518 let generics = tcx.generics_of(self.mir_def_id());
1519
1520 let Some(hir_generics) = tcx
1521 .typeck_root_def_id(self.mir_def_id().to_def_id())
1522 .as_local()
1523 .and_then(|def_id| tcx.hir_get_generics(def_id))
1524 else {
1525 return;
1526 };
1527 let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1529 let cause = ObligationCause::misc(span, self.mir_def_id());
1530
1531 ocx.register_bound(cause, self.infcx.param_env, ty, def_id);
1532 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1533
1534 let predicates: Result<Vec<_>, _> = errors
1536 .into_iter()
1537 .map(|err| match err.obligation.predicate.kind().skip_binder() {
1538 PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => {
1539 match *predicate.self_ty().kind() {
1540 ty::Param(param_ty) => Ok((
1541 generics.type_param(param_ty, tcx),
1542 predicate.trait_ref.print_trait_sugared().to_string(),
1543 Some(predicate.trait_ref.def_id),
1544 )),
1545 _ => Err(()),
1546 }
1547 }
1548 _ => Err(()),
1549 })
1550 .collect();
1551
1552 if let Ok(predicates) = predicates {
1553 suggest_constraining_type_params(
1554 tcx,
1555 hir_generics,
1556 err,
1557 predicates.iter().map(|(param, constraint, def_id)| {
1558 (param.name.as_str(), &**constraint, *def_id)
1559 }),
1560 None,
1561 );
1562 }
1563 }
1564
1565 pub(crate) fn report_move_out_while_borrowed(
1566 &mut self,
1567 location: Location,
1568 (place, span): (Place<'tcx>, Span),
1569 borrow: &BorrowData<'tcx>,
1570 ) {
1571 {
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:1571",
"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(1571u32),
::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!(
1572 "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
1573 location, place, span, borrow
1574 );
1575 let value_msg = self.describe_any_place(place.as_ref());
1576 let borrow_msg = self.describe_any_place(borrow.borrowed_place.as_ref());
1577
1578 let borrow_spans = self.retrieve_borrow_spans(borrow);
1579 let borrow_span = borrow_spans.args_or_use();
1580
1581 let move_spans = self.move_spans(place.as_ref(), location);
1582 let span = move_spans.args_or_use();
1583
1584 let mut err = self.cannot_move_when_borrowed(
1585 span,
1586 borrow_span,
1587 &self.describe_any_place(place.as_ref()),
1588 &borrow_msg,
1589 &value_msg,
1590 );
1591 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1592
1593 borrow_spans.var_path_only_subdiag(&mut err, crate::InitializationRequiringAction::Borrow);
1594
1595 move_spans.var_subdiag(&mut err, None, |kind, var_span| {
1596 use crate::session_diagnostics::CaptureVarCause::*;
1597 match kind {
1598 hir::ClosureKind::Coroutine(_) => MoveUseInCoroutine { var_span },
1599 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1600 MoveUseInClosure { var_span }
1601 }
1602 }
1603 });
1604
1605 self.explain_why_borrow_contains_point(location, borrow, None)
1606 .add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
1607 self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
1608 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1609 if let Some(expr) = self.find_expr(borrow_span) {
1610 if let hir::ExprKind::AddrOf(_, _, borrowed_expr) = expr.kind
1612 && let Some(ty) = typeck_results.expr_ty_opt(borrowed_expr)
1613 {
1614 self.suggest_cloning(&mut err, place.as_ref(), ty, borrowed_expr, Some(move_spans));
1615 } else if typeck_results.expr_adjustments(expr).first().is_some_and(|adj| {
1616 #[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!(
1617 adj.kind,
1618 ty::adjustment::Adjust::Borrow(ty::adjustment::AutoBorrow::Ref(
1619 ty::adjustment::AutoBorrowMutability::Not
1620 | ty::adjustment::AutoBorrowMutability::Mut {
1621 allow_two_phase_borrow: ty::adjustment::AllowTwoPhase::No
1622 }
1623 ))
1624 )
1625 }) && let Some(ty) = typeck_results.expr_ty_opt(expr)
1626 {
1627 self.suggest_cloning(&mut err, place.as_ref(), ty, expr, Some(move_spans));
1628 }
1629 }
1630 self.buffer_error(err);
1631 }
1632
1633 pub(crate) fn report_use_while_mutably_borrowed(
1634 &self,
1635 location: Location,
1636 (place, _span): (Place<'tcx>, Span),
1637 borrow: &BorrowData<'tcx>,
1638 ) -> Diag<'infcx> {
1639 let borrow_spans = self.retrieve_borrow_spans(borrow);
1640 let borrow_span = borrow_spans.args_or_use();
1641
1642 let use_spans = self.move_spans(place.as_ref(), location);
1645 let span = use_spans.var_or_use();
1646
1647 let mut err = self.cannot_use_when_mutably_borrowed(
1651 span,
1652 &self.describe_any_place(place.as_ref()),
1653 borrow_span,
1654 &self.describe_any_place(borrow.borrowed_place.as_ref()),
1655 );
1656 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1657
1658 borrow_spans.var_subdiag(&mut err, Some(borrow.kind), |kind, var_span| {
1659 use crate::session_diagnostics::CaptureVarCause::*;
1660 let place = &borrow.borrowed_place;
1661 let desc_place = self.describe_any_place(place.as_ref());
1662 match kind {
1663 hir::ClosureKind::Coroutine(_) => {
1664 BorrowUsePlaceCoroutine { place: desc_place, var_span, is_single_var: true }
1665 }
1666 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1667 BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: true }
1668 }
1669 }
1670 });
1671
1672 self.explain_why_borrow_contains_point(location, borrow, None)
1673 .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
1674 err
1675 }
1676
1677 pub(crate) fn report_conflicting_borrow(
1678 &self,
1679 location: Location,
1680 (place, span): (Place<'tcx>, Span),
1681 gen_borrow_kind: BorrowKind,
1682 issued_borrow: &BorrowData<'tcx>,
1683 ) -> Diag<'infcx> {
1684 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
1685 let issued_span = issued_spans.args_or_use();
1686
1687 let borrow_spans = self.borrow_spans(span, location);
1688 let span = borrow_spans.args_or_use();
1689
1690 let container_name = if issued_spans.for_coroutine() || borrow_spans.for_coroutine() {
1691 "coroutine"
1692 } else {
1693 "closure"
1694 };
1695
1696 let (desc_place, msg_place, msg_borrow, union_type_name) =
1697 self.describe_place_for_conflicting_borrow(place, issued_borrow.borrowed_place);
1698
1699 let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
1700 let second_borrow_desc = if explanation.is_explained() { "second " } else { "" };
1701
1702 let first_borrow_desc;
1704 let mut err = match (gen_borrow_kind, issued_borrow.kind) {
1705 (
1706 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1707 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1708 ) => {
1709 first_borrow_desc = "mutable ";
1710 let mut err = self.cannot_reborrow_already_borrowed(
1711 span,
1712 &desc_place,
1713 &msg_place,
1714 "immutable",
1715 issued_span,
1716 "it",
1717 "mutable",
1718 &msg_borrow,
1719 None,
1720 );
1721 self.suggest_slice_method_if_applicable(
1722 &mut err,
1723 place,
1724 issued_borrow.borrowed_place,
1725 span,
1726 issued_span,
1727 );
1728 err
1729 }
1730 (
1731 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1732 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1733 ) => {
1734 first_borrow_desc = "immutable ";
1735 let mut err = self.cannot_reborrow_already_borrowed(
1736 span,
1737 &desc_place,
1738 &msg_place,
1739 "mutable",
1740 issued_span,
1741 "it",
1742 "immutable",
1743 &msg_borrow,
1744 None,
1745 );
1746 self.suggest_slice_method_if_applicable(
1747 &mut err,
1748 place,
1749 issued_borrow.borrowed_place,
1750 span,
1751 issued_span,
1752 );
1753 self.suggest_binding_for_closure_capture_self(&mut err, &issued_spans);
1754 self.suggest_using_closure_argument_instead_of_capture(
1755 &mut err,
1756 issued_borrow.borrowed_place,
1757 &issued_spans,
1758 );
1759 err
1760 }
1761
1762 (
1763 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1764 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1765 ) => {
1766 first_borrow_desc = "first ";
1767 let mut err = self.cannot_mutably_borrow_multiply(
1768 span,
1769 &desc_place,
1770 &msg_place,
1771 issued_span,
1772 &msg_borrow,
1773 None,
1774 );
1775 self.suggest_slice_method_if_applicable(
1776 &mut err,
1777 place,
1778 issued_borrow.borrowed_place,
1779 span,
1780 issued_span,
1781 );
1782 self.suggest_using_closure_argument_instead_of_capture(
1783 &mut err,
1784 issued_borrow.borrowed_place,
1785 &issued_spans,
1786 );
1787 self.explain_iterator_advancement_in_for_loop_if_applicable(
1788 &mut err,
1789 span,
1790 &issued_spans,
1791 );
1792 err
1793 }
1794
1795 (
1796 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1797 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1798 ) => {
1799 first_borrow_desc = "first ";
1800 self.cannot_uniquely_borrow_by_two_closures(span, &desc_place, issued_span, None)
1801 }
1802
1803 (BorrowKind::Mut { .. }, BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
1804 if let Some(immutable_section_description) =
1805 self.classify_immutable_section(issued_borrow.assigned_place)
1806 {
1807 let mut err = self.cannot_mutate_in_immutable_section(
1808 span,
1809 issued_span,
1810 &desc_place,
1811 immutable_section_description,
1812 "mutably borrow",
1813 );
1814 borrow_spans.var_subdiag(
1815 &mut err,
1816 Some(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }),
1817 |kind, var_span| {
1818 use crate::session_diagnostics::CaptureVarCause::*;
1819 match kind {
1820 hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1821 place: desc_place,
1822 var_span,
1823 is_single_var: true,
1824 },
1825 hir::ClosureKind::Closure
1826 | hir::ClosureKind::CoroutineClosure(_) => BorrowUsePlaceClosure {
1827 place: desc_place,
1828 var_span,
1829 is_single_var: true,
1830 },
1831 }
1832 },
1833 );
1834 return err;
1835 } else {
1836 first_borrow_desc = "immutable ";
1837 self.cannot_reborrow_already_borrowed(
1838 span,
1839 &desc_place,
1840 &msg_place,
1841 "mutable",
1842 issued_span,
1843 "it",
1844 "immutable",
1845 &msg_borrow,
1846 None,
1847 )
1848 }
1849 }
1850
1851 (BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }, _) => {
1852 first_borrow_desc = "first ";
1853 self.cannot_uniquely_borrow_by_one_closure(
1854 span,
1855 container_name,
1856 &desc_place,
1857 "",
1858 issued_span,
1859 "it",
1860 "",
1861 None,
1862 )
1863 }
1864
1865 (
1866 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1867 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1868 ) => {
1869 first_borrow_desc = "first ";
1870 self.cannot_reborrow_already_uniquely_borrowed(
1871 span,
1872 container_name,
1873 &desc_place,
1874 "",
1875 "immutable",
1876 issued_span,
1877 "",
1878 None,
1879 second_borrow_desc,
1880 )
1881 }
1882
1883 (BorrowKind::Mut { .. }, BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }) => {
1884 first_borrow_desc = "first ";
1885 self.cannot_reborrow_already_uniquely_borrowed(
1886 span,
1887 container_name,
1888 &desc_place,
1889 "",
1890 "mutable",
1891 issued_span,
1892 "",
1893 None,
1894 second_borrow_desc,
1895 )
1896 }
1897
1898 (
1899 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1900 BorrowKind::Shared | BorrowKind::Fake(_),
1901 )
1902 | (
1903 BorrowKind::Fake(FakeBorrowKind::Shallow),
1904 BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_),
1905 ) => {
1906 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1907 }
1908 };
1909 self.note_due_to_edition_2024_opaque_capture_rules(issued_borrow, &mut err);
1910
1911 if issued_spans == borrow_spans {
1912 borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
1913 use crate::session_diagnostics::CaptureVarCause::*;
1914 match kind {
1915 hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1916 place: desc_place,
1917 var_span,
1918 is_single_var: false,
1919 },
1920 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1921 BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: false }
1922 }
1923 }
1924 });
1925 } else {
1926 issued_spans.var_subdiag(&mut err, Some(issued_borrow.kind), |kind, var_span| {
1927 use crate::session_diagnostics::CaptureVarCause::*;
1928 let borrow_place = &issued_borrow.borrowed_place;
1929 let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
1930 match kind {
1931 hir::ClosureKind::Coroutine(_) => {
1932 FirstBorrowUsePlaceCoroutine { place: borrow_place_desc, var_span }
1933 }
1934 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1935 FirstBorrowUsePlaceClosure { place: borrow_place_desc, var_span }
1936 }
1937 }
1938 });
1939
1940 borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
1941 use crate::session_diagnostics::CaptureVarCause::*;
1942 match kind {
1943 hir::ClosureKind::Coroutine(_) => {
1944 SecondBorrowUsePlaceCoroutine { place: desc_place, var_span }
1945 }
1946 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1947 SecondBorrowUsePlaceClosure { place: desc_place, var_span }
1948 }
1949 }
1950 });
1951 }
1952
1953 if union_type_name != "" {
1954 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!(
1955 "{msg_place} is a field of the union `{union_type_name}`, so it overlaps the field {msg_borrow}",
1956 ));
1957 }
1958
1959 explanation.add_explanation_to_diagnostic(
1960 &self,
1961 &mut err,
1962 first_borrow_desc,
1963 None,
1964 Some((issued_span, span)),
1965 );
1966
1967 self.suggest_using_local_if_applicable(&mut err, location, issued_borrow, explanation);
1968 self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
1969
1970 err
1971 }
1972
1973 fn suggest_copy_for_type_in_cloned_ref(&self, err: &mut Diag<'infcx>, place: Place<'tcx>) {
1974 let tcx = self.infcx.tcx;
1975 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
1976
1977 struct FindUselessClone<'tcx> {
1978 tcx: TyCtxt<'tcx>,
1979 typeck_results: &'tcx ty::TypeckResults<'tcx>,
1980 clones: Vec<&'tcx hir::Expr<'tcx>>,
1981 }
1982 impl<'tcx> FindUselessClone<'tcx> {
1983 fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
1984 Self { tcx, typeck_results: tcx.typeck(def_id), clones: ::alloc::vec::Vec::new()vec![] }
1985 }
1986 }
1987 impl<'tcx> Visitor<'tcx> for FindUselessClone<'tcx> {
1988 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1989 if let hir::ExprKind::MethodCall(..) = ex.kind
1990 && let Some(method_def_id) =
1991 self.typeck_results.type_dependent_def_id(ex.hir_id)
1992 && self.tcx.is_lang_item(self.tcx.parent(method_def_id), LangItem::Clone)
1993 {
1994 self.clones.push(ex);
1995 }
1996 hir::intravisit::walk_expr(self, ex);
1997 }
1998 }
1999
2000 let mut expr_finder = FindUselessClone::new(tcx, self.mir_def_id());
2001
2002 let body = tcx.hir_body(body_id).value;
2003 expr_finder.visit_expr(body);
2004
2005 struct Holds<'tcx> {
2006 ty: Ty<'tcx>,
2007 }
2008
2009 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for Holds<'tcx> {
2010 type Result = std::ops::ControlFlow<()>;
2011
2012 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
2013 if t == self.ty {
2014 return ControlFlow::Break(());
2015 }
2016 t.super_visit_with(self)
2017 }
2018 }
2019
2020 let mut types_to_constrain = FxIndexSet::default();
2021
2022 let local_ty = self.body.local_decls[place.local].ty;
2023 let typeck_results = tcx.typeck(self.mir_def_id());
2024 let clone = tcx.require_lang_item(LangItem::Clone, body.span);
2025 for expr in expr_finder.clones {
2026 if let hir::ExprKind::MethodCall(_, rcvr, _, span) = expr.kind
2027 && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
2028 && let Some(ty) = typeck_results.node_type_opt(expr.hir_id)
2029 && rcvr_ty == ty
2030 && let ty::Ref(_, inner, _) = rcvr_ty.kind()
2031 && let inner = inner.peel_refs()
2032 && (Holds { ty: inner }).visit_ty(local_ty).is_break()
2033 && let None =
2034 self.infcx.type_implements_trait_shallow(clone, inner, self.infcx.param_env)
2035 {
2036 err.span_label(
2037 span,
2038 ::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!(
2039 "this call doesn't do anything, the result is still `{rcvr_ty}` \
2040 because `{inner}` doesn't implement `Clone`",
2041 ),
2042 );
2043 types_to_constrain.insert(inner);
2044 }
2045 }
2046 for ty in types_to_constrain {
2047 self.suggest_adding_bounds_or_derive(err, ty, clone, body.span);
2048 }
2049 }
2050
2051 pub(crate) fn suggest_adding_bounds_or_derive(
2052 &self,
2053 err: &mut Diag<'_>,
2054 ty: Ty<'tcx>,
2055 trait_def_id: DefId,
2056 span: Span,
2057 ) {
2058 self.suggest_adding_bounds(err, ty, trait_def_id, span);
2059 if let ty::Adt(..) = ty.kind() {
2060 let trait_ref =
2062 ty::Binder::dummy(ty::TraitRef::new(self.infcx.tcx, trait_def_id, [ty]));
2063 let obligation = Obligation::new(
2064 self.infcx.tcx,
2065 ObligationCause::dummy(),
2066 self.infcx.param_env,
2067 trait_ref,
2068 );
2069 self.infcx.err_ctxt().suggest_derive(
2070 &obligation,
2071 err,
2072 trait_ref.upcast(self.infcx.tcx),
2073 );
2074 }
2075 }
2076
2077 #[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(2077u32),
::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:2095",
"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(2095u32),
::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:2124",
"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(2124u32),
::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:2128",
"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(2128u32),
::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:2138",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2138u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["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:2142",
"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(2142u32),
::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:2145",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(2145u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("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:2152",
"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(2152u32),
::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:2155",
"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(2155u32),
::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:2165",
"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(2165u32),
::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))]
2078 fn suggest_using_local_if_applicable(
2079 &self,
2080 err: &mut Diag<'_>,
2081 location: Location,
2082 issued_borrow: &BorrowData<'tcx>,
2083 explanation: BorrowExplanation<'tcx>,
2084 ) {
2085 let used_in_call = matches!(
2086 explanation,
2087 BorrowExplanation::UsedLater(
2088 _,
2089 LaterUseKind::Call | LaterUseKind::Other,
2090 _call_span,
2091 _
2092 )
2093 );
2094 if !used_in_call {
2095 debug!("not later used in call");
2096 return;
2097 }
2098 if matches!(
2099 self.body.local_decls[issued_borrow.borrowed_place.local].local_info(),
2100 LocalInfo::IfThenRescopeTemp { .. }
2101 ) {
2102 return;
2104 }
2105
2106 let use_span = if let BorrowExplanation::UsedLater(_, LaterUseKind::Other, use_span, _) =
2107 explanation
2108 {
2109 Some(use_span)
2110 } else {
2111 None
2112 };
2113
2114 let outer_call_loc =
2115 if let TwoPhaseActivation::ActivatedAt(loc) = issued_borrow.activation_location {
2116 loc
2117 } else {
2118 issued_borrow.reserve_location
2119 };
2120 let outer_call_stmt = self.body.stmt_at(outer_call_loc);
2121
2122 let inner_param_location = location;
2123 let Some(inner_param_stmt) = self.body.stmt_at(inner_param_location).left() else {
2124 debug!("`inner_param_location` {:?} is not for a statement", inner_param_location);
2125 return;
2126 };
2127 let Some(&inner_param) = inner_param_stmt.kind.as_assign().map(|(p, _)| p) else {
2128 debug!(
2129 "`inner_param_location` {:?} is not for an assignment: {:?}",
2130 inner_param_location, inner_param_stmt
2131 );
2132 return;
2133 };
2134 let inner_param_uses = find_all_local_uses::find(self.body, inner_param.local);
2135 let Some((inner_call_loc, inner_call_term)) =
2136 inner_param_uses.into_iter().find_map(|loc| {
2137 let Either::Right(term) = self.body.stmt_at(loc) else {
2138 debug!("{:?} is a statement, so it can't be a call", loc);
2139 return None;
2140 };
2141 let TerminatorKind::Call { args, .. } = &term.kind else {
2142 debug!("not a call: {:?}", term);
2143 return None;
2144 };
2145 debug!("checking call args for uses of inner_param: {:?}", args);
2146 args.iter()
2147 .map(|a| &a.node)
2148 .any(|a| a == &Operand::Move(inner_param))
2149 .then_some((loc, term))
2150 })
2151 else {
2152 debug!("no uses of inner_param found as a by-move call arg");
2153 return;
2154 };
2155 debug!("===> outer_call_loc = {:?}, inner_call_loc = {:?}", outer_call_loc, inner_call_loc);
2156
2157 let inner_call_span = inner_call_term.source_info.span;
2158 let outer_call_span = match use_span {
2159 Some(span) => span,
2160 None => outer_call_stmt.either(|s| s.source_info, |t| t.source_info).span,
2161 };
2162 if outer_call_span == inner_call_span || !outer_call_span.contains(inner_call_span) {
2163 debug!(
2166 "outer span {:?} does not strictly contain inner span {:?}",
2167 outer_call_span, inner_call_span
2168 );
2169 return;
2170 }
2171 err.span_help(
2172 inner_call_span,
2173 format!(
2174 "try adding a local storing this{}...",
2175 if use_span.is_some() { "" } else { " argument" }
2176 ),
2177 );
2178 err.span_help(
2179 outer_call_span,
2180 format!(
2181 "...and then using that local {}",
2182 if use_span.is_some() { "here" } else { "as the argument to this call" }
2183 ),
2184 );
2185 }
2186
2187 pub(crate) fn find_expr(&self, span: Span) -> Option<&'tcx hir::Expr<'tcx>> {
2188 let tcx = self.infcx.tcx;
2189 let body_id = tcx.hir_node(self.mir_hir_id()).body_id()?;
2190 let mut expr_finder = FindExprBySpan::new(span, tcx);
2191 expr_finder.visit_expr(tcx.hir_body(body_id).value);
2192 expr_finder.result
2193 }
2194
2195 fn suggest_slice_method_if_applicable(
2196 &self,
2197 err: &mut Diag<'_>,
2198 place: Place<'tcx>,
2199 borrowed_place: Place<'tcx>,
2200 span: Span,
2201 issued_span: Span,
2202 ) {
2203 let tcx = self.infcx.tcx;
2204
2205 let has_split_at_mut = |ty: Ty<'tcx>| {
2206 let ty = ty.peel_refs();
2207 match ty.kind() {
2208 ty::Array(..) | ty::Slice(..) => true,
2209 ty::Adt(def, _) if tcx.get_diagnostic_item(sym::Vec) == Some(def.did()) => true,
2210 _ if ty == tcx.types.str_ => true,
2211 _ => false,
2212 }
2213 };
2214 if let ([ProjectionElem::Index(index1)], [ProjectionElem::Index(index2)])
2215 | (
2216 [ProjectionElem::Deref, ProjectionElem::Index(index1)],
2217 [ProjectionElem::Deref, ProjectionElem::Index(index2)],
2218 ) = (&place.projection[..], &borrowed_place.projection[..])
2219 {
2220 let decl1 = &self.body.local_decls[*index1];
2221 let decl2 = &self.body.local_decls[*index2];
2222
2223 let mut note_default_suggestion = || {
2224 err.help(
2225 "consider using `.split_at_mut(position)` or similar method to obtain two \
2226 mutable non-overlapping sub-slices",
2227 )
2228 .help(
2229 "consider using `.swap(index_1, index_2)` to swap elements at the specified \
2230 indices",
2231 );
2232 };
2233
2234 let Some(index1) = self.find_expr(decl1.source_info.span) else {
2235 note_default_suggestion();
2236 return;
2237 };
2238
2239 let Some(index2) = self.find_expr(decl2.source_info.span) else {
2240 note_default_suggestion();
2241 return;
2242 };
2243
2244 let sm = tcx.sess.source_map();
2245
2246 let Ok(index1_str) = sm.span_to_snippet(index1.span) else {
2247 note_default_suggestion();
2248 return;
2249 };
2250
2251 let Ok(index2_str) = sm.span_to_snippet(index2.span) else {
2252 note_default_suggestion();
2253 return;
2254 };
2255
2256 let Some(object) = tcx.hir_parent_id_iter(index1.hir_id).find_map(|id| {
2257 if let hir::Node::Expr(expr) = tcx.hir_node(id)
2258 && let hir::ExprKind::Index(obj, ..) = expr.kind
2259 {
2260 Some(obj)
2261 } else {
2262 None
2263 }
2264 }) else {
2265 note_default_suggestion();
2266 return;
2267 };
2268
2269 let Ok(obj_str) = sm.span_to_snippet(object.span) else {
2270 note_default_suggestion();
2271 return;
2272 };
2273
2274 let Some(swap_call) = tcx.hir_parent_id_iter(object.hir_id).find_map(|id| {
2275 if let hir::Node::Expr(call) = tcx.hir_node(id)
2276 && let hir::ExprKind::Call(callee, ..) = call.kind
2277 && let hir::ExprKind::Path(qpath) = callee.kind
2278 && let hir::QPath::Resolved(None, res) = qpath
2279 && let hir::def::Res::Def(_, did) = res.res
2280 && tcx.is_diagnostic_item(sym::mem_swap, did)
2281 {
2282 Some(call)
2283 } else {
2284 None
2285 }
2286 }) else {
2287 let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2288 let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2289 let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2290 let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2291 if !idx1.equivalent_for_indexing(idx2) {
2292 err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2293 }
2294 return;
2295 };
2296
2297 err.span_suggestion(
2298 swap_call.span,
2299 "use `.swap()` to swap elements at the specified indices instead",
2300 ::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})"),
2301 Applicability::MachineApplicable,
2302 );
2303 return;
2304 }
2305 let place_ty = PlaceRef::ty(&place.as_ref(), self.body, tcx).ty;
2306 let borrowed_place_ty = PlaceRef::ty(&borrowed_place.as_ref(), self.body, tcx).ty;
2307 if !has_split_at_mut(place_ty) && !has_split_at_mut(borrowed_place_ty) {
2308 return;
2310 }
2311 let Some(index1) = self.find_expr(span) else { return };
2312 let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2313 let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2314 let Some(index2) = self.find_expr(issued_span) else { return };
2315 let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2316 let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2317 if idx1.equivalent_for_indexing(idx2) {
2318 return;
2320 }
2321 err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2322 }
2323
2324 pub(crate) fn explain_iterator_advancement_in_for_loop_if_applicable(
2335 &self,
2336 err: &mut Diag<'_>,
2337 span: Span,
2338 issued_spans: &UseSpans<'tcx>,
2339 ) {
2340 let issue_span = issued_spans.args_or_use();
2341 let tcx = self.infcx.tcx;
2342
2343 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2344 let typeck_results = tcx.typeck(self.mir_def_id());
2345
2346 struct ExprFinder<'hir> {
2347 tcx: TyCtxt<'hir>,
2348 issue_span: Span,
2349 expr_span: Span,
2350 body_expr: Option<&'hir hir::Expr<'hir>> = None,
2351 loop_bind: Option<&'hir Ident> = None,
2352 loop_span: Option<Span> = None,
2353 head_span: Option<Span> = None,
2354 pat_span: Option<Span> = None,
2355 head: Option<&'hir hir::Expr<'hir>> = None,
2356 }
2357 impl<'hir> Visitor<'hir> for ExprFinder<'hir> {
2358 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2359 if let hir::ExprKind::Call(path, [arg]) = ex.kind
2372 && let hir::ExprKind::Path(qpath) = path.kind
2373 && self.tcx.qpath_is_lang_item(qpath, LangItem::IntoIterIntoIter)
2374 && arg.span.contains(self.issue_span)
2375 && ex.span.desugaring_kind() == Some(DesugaringKind::ForLoop)
2376 {
2377 self.head = Some(arg);
2379 }
2380 if let hir::ExprKind::Loop(
2381 hir::Block { stmts: [stmt, ..], .. },
2382 _,
2383 hir::LoopSource::ForLoop,
2384 _,
2385 ) = ex.kind
2386 && let hir::StmtKind::Expr(hir::Expr {
2387 kind: hir::ExprKind::Match(call, [_, bind, ..], _),
2388 span: head_span,
2389 ..
2390 }) = stmt.kind
2391 && let hir::ExprKind::Call(path, _args) = call.kind
2392 && let hir::ExprKind::Path(qpath) = path.kind
2393 && self.tcx.qpath_is_lang_item(qpath, LangItem::IteratorNext)
2394 && let hir::PatKind::Struct(qpath, [field, ..], _) = bind.pat.kind
2395 && self.tcx.qpath_is_lang_item(qpath, LangItem::OptionSome)
2396 && call.span.contains(self.issue_span)
2397 {
2398 if let PatField {
2400 pat: hir::Pat { kind: hir::PatKind::Binding(_, _, ident, ..), .. },
2401 ..
2402 } = field
2403 {
2404 self.loop_bind = Some(ident);
2405 }
2406 self.head_span = Some(*head_span);
2407 self.pat_span = Some(bind.pat.span);
2408 self.loop_span = Some(stmt.span);
2409 }
2410
2411 if let hir::ExprKind::MethodCall(body_call, recv, ..) = ex.kind
2412 && body_call.ident.name == sym::next
2413 && recv.span.source_equal(self.expr_span)
2414 {
2415 self.body_expr = Some(ex);
2416 }
2417
2418 hir::intravisit::walk_expr(self, ex);
2419 }
2420 }
2421 let mut finder = ExprFinder { tcx, expr_span: span, issue_span, .. };
2422 finder.visit_expr(tcx.hir_body(body_id).value);
2423
2424 if let Some(body_expr) = finder.body_expr
2425 && let Some(loop_span) = finder.loop_span
2426 && let Some(def_id) = typeck_results.type_dependent_def_id(body_expr.hir_id)
2427 && let Some(trait_did) = tcx.trait_of_assoc(def_id)
2428 && tcx.is_diagnostic_item(sym::Iterator, trait_did)
2429 {
2430 if let Some(loop_bind) = finder.loop_bind {
2431 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!(
2432 "a for loop advances the iterator for you, the result is stored in `{}`",
2433 loop_bind.name,
2434 ));
2435 } else {
2436 err.note(
2437 "a for loop advances the iterator for you, the result is stored in its pattern",
2438 );
2439 }
2440 let msg = "if you want to call `next` on a iterator within the loop, consider using \
2441 `while let`";
2442 if let Some(head) = finder.head
2443 && let Some(pat_span) = finder.pat_span
2444 && loop_span.contains(body_expr.span)
2445 && loop_span.contains(head.span)
2446 {
2447 let sm = self.infcx.tcx.sess.source_map();
2448
2449 let mut sugg = ::alloc::vec::Vec::new()vec![];
2450 if let hir::ExprKind::Path(hir::QPath::Resolved(None, _)) = head.kind {
2451 sugg.push((loop_span.with_hi(pat_span.lo()), "while let Some(".to_string()));
2455 sugg.push((
2456 pat_span.shrink_to_hi().with_hi(head.span.lo()),
2457 ") = ".to_string(),
2458 ));
2459 sugg.push((head.span.shrink_to_hi(), ".next()".to_string()));
2460 } else {
2461 let indent = if let Some(indent) = sm.indentation_before(loop_span) {
2463 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}", indent))
})format!("\n{indent}")
2464 } else {
2465 " ".to_string()
2466 };
2467 let Ok(head_str) = sm.span_to_snippet(head.span) else {
2468 err.help(msg);
2469 return;
2470 };
2471 sugg.push((
2472 loop_span.with_hi(pat_span.lo()),
2473 ::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("),
2474 ));
2475 sugg.push((
2476 pat_span.shrink_to_hi().with_hi(head.span.hi()),
2477 ") = iter.next()".to_string(),
2478 ));
2479 if let hir::ExprKind::MethodCall(_, recv, ..) = body_expr.kind
2482 && let hir::ExprKind::Path(hir::QPath::Resolved(None, ..)) = recv.kind
2483 {
2484 sugg.push((recv.span, "iter".to_string()));
2488 }
2489 }
2490 err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2491 } else {
2492 err.help(msg);
2493 }
2494 }
2495 }
2496
2497 fn suggest_using_closure_argument_instead_of_capture(
2514 &self,
2515 err: &mut Diag<'_>,
2516 borrowed_place: Place<'tcx>,
2517 issued_spans: &UseSpans<'tcx>,
2518 ) {
2519 let &UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2520 let tcx = self.infcx.tcx;
2521
2522 let local = borrowed_place.local;
2524 let local_ty = self.body.local_decls[local].ty;
2525
2526 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2528
2529 let body_expr = tcx.hir_body(body_id).value;
2530
2531 struct ClosureFinder<'hir> {
2532 tcx: TyCtxt<'hir>,
2533 borrow_span: Span,
2534 res: Option<(&'hir hir::Expr<'hir>, &'hir hir::Closure<'hir>)>,
2535 error_path: Option<(&'hir hir::Expr<'hir>, &'hir hir::QPath<'hir>)>,
2537 }
2538 impl<'hir> Visitor<'hir> for ClosureFinder<'hir> {
2539 type NestedFilter = OnlyBodies;
2540
2541 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
2542 self.tcx
2543 }
2544
2545 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2546 if let hir::ExprKind::Path(qpath) = &ex.kind
2547 && ex.span == self.borrow_span
2548 {
2549 self.error_path = Some((ex, qpath));
2550 }
2551
2552 if let hir::ExprKind::Closure(closure) = ex.kind
2553 && ex.span.contains(self.borrow_span)
2554 && self.res.as_ref().is_none_or(|(prev_res, _)| prev_res.span.contains(ex.span))
2558 {
2559 self.res = Some((ex, closure));
2560 }
2561
2562 hir::intravisit::walk_expr(self, ex);
2563 }
2564 }
2565
2566 let mut finder =
2568 ClosureFinder { tcx, borrow_span: capture_kind_span, res: None, error_path: None };
2569 finder.visit_expr(body_expr);
2570 let Some((closure_expr, closure)) = finder.res else { return };
2571
2572 let typeck_results = tcx.typeck(self.mir_def_id());
2573
2574 if let hir::Node::Expr(parent) = tcx.parent_hir_node(closure_expr.hir_id)
2577 && let hir::ExprKind::MethodCall(_, recv, ..) = parent.kind
2578 {
2579 let recv_ty = typeck_results.expr_ty(recv);
2580
2581 if recv_ty.peel_refs() != local_ty {
2582 return;
2583 }
2584 }
2585
2586 let ty::Closure(_, args) = typeck_results.expr_ty(closure_expr).kind() else {
2588 return;
2590 };
2591 let sig = args.as_closure().sig();
2592 let tupled_params = tcx.instantiate_bound_regions_with_erased(
2593 sig.inputs().iter().next().unwrap().map_bound(|&b| b),
2594 );
2595 let ty::Tuple(params) = tupled_params.kind() else { return };
2596
2597 let Some(this_name) = params.iter().zip(tcx.hir_body_param_idents(closure.body)).find_map(
2599 |(param_ty, ident)| {
2600 if param_ty.peel_refs() == local_ty { ident } else { None }
2602 },
2603 ) else {
2604 return;
2605 };
2606
2607 let spans;
2608 if let Some((_path_expr, qpath)) = finder.error_path
2609 && let hir::QPath::Resolved(_, path) = qpath
2610 && let hir::def::Res::Local(local_id) = path.res
2611 {
2612 struct VariableUseFinder {
2615 local_id: hir::HirId,
2616 spans: Vec<Span>,
2617 }
2618 impl<'hir> Visitor<'hir> for VariableUseFinder {
2619 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2620 if let hir::ExprKind::Path(qpath) = &ex.kind
2621 && let hir::QPath::Resolved(_, path) = qpath
2622 && let hir::def::Res::Local(local_id) = path.res
2623 && local_id == self.local_id
2624 {
2625 self.spans.push(ex.span);
2626 }
2627
2628 hir::intravisit::walk_expr(self, ex);
2629 }
2630 }
2631
2632 let mut finder = VariableUseFinder { local_id, spans: Vec::new() };
2633 finder.visit_expr(tcx.hir_body(closure.body).value);
2634
2635 spans = finder.spans;
2636 } else {
2637 spans = <[_]>::into_vec(::alloc::boxed::box_new([capture_kind_span]))vec![capture_kind_span];
2638 }
2639
2640 err.multipart_suggestion(
2641 "try using the closure argument",
2642 iter::zip(spans, iter::repeat(this_name.to_string())).collect(),
2643 Applicability::MaybeIncorrect,
2644 );
2645 }
2646
2647 fn suggest_binding_for_closure_capture_self(
2648 &self,
2649 err: &mut Diag<'_>,
2650 issued_spans: &UseSpans<'tcx>,
2651 ) {
2652 let UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2653
2654 struct ExpressionFinder<'tcx> {
2655 capture_span: Span,
2656 closure_change_spans: Vec<Span> = ::alloc::vec::Vec::new()vec![],
2657 closure_arg_span: Option<Span> = None,
2658 in_closure: bool = false,
2659 suggest_arg: String = String::new(),
2660 tcx: TyCtxt<'tcx>,
2661 closure_local_id: Option<hir::HirId> = None,
2662 closure_call_changes: Vec<(Span, String)> = ::alloc::vec::Vec::new()vec![],
2663 }
2664 impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
2665 fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
2666 if e.span.contains(self.capture_span)
2667 && let hir::ExprKind::Closure(&hir::Closure {
2668 kind: hir::ClosureKind::Closure,
2669 body,
2670 fn_arg_span,
2671 fn_decl: hir::FnDecl { inputs, .. },
2672 ..
2673 }) = e.kind
2674 && let hir::Node::Expr(body) = self.tcx.hir_node(body.hir_id)
2675 {
2676 self.suggest_arg = "this: &Self".to_string();
2677 if inputs.len() > 0 {
2678 self.suggest_arg.push_str(", ");
2679 }
2680 self.in_closure = true;
2681 self.closure_arg_span = fn_arg_span;
2682 self.visit_expr(body);
2683 self.in_closure = false;
2684 }
2685 if let hir::Expr { kind: hir::ExprKind::Path(path), .. } = e
2686 && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2687 && seg.ident.name == kw::SelfLower
2688 && self.in_closure
2689 {
2690 self.closure_change_spans.push(e.span);
2691 }
2692 hir::intravisit::walk_expr(self, e);
2693 }
2694
2695 fn visit_local(&mut self, local: &'hir hir::LetStmt<'hir>) {
2696 if let hir::Pat { kind: hir::PatKind::Binding(_, hir_id, _ident, _), .. } =
2697 local.pat
2698 && let Some(init) = local.init
2699 && let &hir::Expr {
2700 kind:
2701 hir::ExprKind::Closure(&hir::Closure {
2702 kind: hir::ClosureKind::Closure,
2703 ..
2704 }),
2705 ..
2706 } = init
2707 && init.span.contains(self.capture_span)
2708 {
2709 self.closure_local_id = Some(*hir_id);
2710 }
2711
2712 hir::intravisit::walk_local(self, local);
2713 }
2714
2715 fn visit_stmt(&mut self, s: &'hir hir::Stmt<'hir>) {
2716 if let hir::StmtKind::Semi(e) = s.kind
2717 && let hir::ExprKind::Call(
2718 hir::Expr { kind: hir::ExprKind::Path(path), .. },
2719 args,
2720 ) = e.kind
2721 && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2722 && let Res::Local(hir_id) = seg.res
2723 && Some(hir_id) == self.closure_local_id
2724 {
2725 let (span, arg_str) = if args.len() > 0 {
2726 (args[0].span.shrink_to_lo(), "self, ".to_string())
2727 } else {
2728 let span = e.span.trim_start(seg.ident.span).unwrap_or(e.span);
2729 (span, "(self)".to_string())
2730 };
2731 self.closure_call_changes.push((span, arg_str));
2732 }
2733 hir::intravisit::walk_stmt(self, s);
2734 }
2735 }
2736
2737 if let hir::Node::ImplItem(hir::ImplItem {
2738 kind: hir::ImplItemKind::Fn(_fn_sig, body_id),
2739 ..
2740 }) = self.infcx.tcx.hir_node(self.mir_hir_id())
2741 && let hir::Node::Expr(expr) = self.infcx.tcx.hir_node(body_id.hir_id)
2742 {
2743 let mut finder =
2744 ExpressionFinder { capture_span: *capture_kind_span, tcx: self.infcx.tcx, .. };
2745 finder.visit_expr(expr);
2746
2747 if finder.closure_change_spans.is_empty() || finder.closure_call_changes.is_empty() {
2748 return;
2749 }
2750
2751 let sm = self.infcx.tcx.sess.source_map();
2752 let sugg = finder
2753 .closure_arg_span
2754 .map(|span| (sm.next_point(span.shrink_to_lo()).shrink_to_hi(), finder.suggest_arg))
2755 .into_iter()
2756 .chain(
2757 finder.closure_change_spans.into_iter().map(|span| (span, "this".to_string())),
2758 )
2759 .chain(finder.closure_call_changes)
2760 .collect();
2761
2762 err.multipart_suggestion_verbose(
2763 "try explicitly passing `&Self` into the closure as an argument",
2764 sugg,
2765 Applicability::MachineApplicable,
2766 );
2767 }
2768 }
2769
2770 fn describe_place_for_conflicting_borrow(
2799 &self,
2800 first_borrowed_place: Place<'tcx>,
2801 second_borrowed_place: Place<'tcx>,
2802 ) -> (String, String, String, String) {
2803 let union_ty = |place_base| {
2806 let ty = PlaceRef::ty(&place_base, self.body, self.infcx.tcx).ty;
2809 ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
2810 };
2811
2812 Some(())
2816 .filter(|_| {
2817 first_borrowed_place != second_borrowed_place
2820 })
2821 .and_then(|_| {
2822 for (place_base, elem) in first_borrowed_place.iter_projections().rev() {
2827 match elem {
2828 ProjectionElem::Field(field, _) if union_ty(place_base).is_some() => {
2829 return Some((place_base, field));
2830 }
2831 _ => {}
2832 }
2833 }
2834 None
2835 })
2836 .and_then(|(target_base, target_field)| {
2837 for (place_base, elem) in second_borrowed_place.iter_projections().rev() {
2840 if let ProjectionElem::Field(field, _) = elem
2841 && let Some(union_ty) = union_ty(place_base)
2842 {
2843 if field != target_field && place_base == target_base {
2844 return Some((
2845 self.describe_any_place(place_base),
2846 self.describe_any_place(first_borrowed_place.as_ref()),
2847 self.describe_any_place(second_borrowed_place.as_ref()),
2848 union_ty.to_string(),
2849 ));
2850 }
2851 }
2852 }
2853 None
2854 })
2855 .unwrap_or_else(|| {
2856 (
2859 self.describe_any_place(first_borrowed_place.as_ref()),
2860 "".to_string(),
2861 "".to_string(),
2862 "".to_string(),
2863 )
2864 })
2865 }
2866
2867 #[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(2873u32),
::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:2890",
"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(2890u32),
::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:2926",
"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(2926u32),
::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))]
2874 pub(crate) fn report_borrowed_value_does_not_live_long_enough(
2875 &mut self,
2876 location: Location,
2877 borrow: &BorrowData<'tcx>,
2878 place_span: (Place<'tcx>, Span),
2879 kind: Option<WriteKind>,
2880 ) {
2881 let drop_span = place_span.1;
2882 let borrowed_local = borrow.borrowed_place.local;
2883
2884 let borrow_spans = self.retrieve_borrow_spans(borrow);
2885 let borrow_span = borrow_spans.var_or_use_path_span();
2886
2887 let proper_span = self.body.local_decls[borrowed_local].source_info.span;
2888
2889 if self.access_place_error_reported.contains(&(Place::from(borrowed_local), borrow_span)) {
2890 debug!(
2891 "suppressing access_place error when borrow doesn't live long enough for {:?}",
2892 borrow_span
2893 );
2894 return;
2895 }
2896
2897 self.access_place_error_reported.insert((Place::from(borrowed_local), borrow_span));
2898
2899 if self.body.local_decls[borrowed_local].is_ref_to_thread_local() {
2900 let err =
2901 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span);
2902 self.buffer_error(err);
2903 return;
2904 }
2905
2906 if let StorageDeadOrDrop::Destructor(dropped_ty) =
2907 self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
2908 {
2909 if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
2914 self.report_borrow_conflicts_with_destructor(
2915 location, borrow, place_span, kind, dropped_ty,
2916 );
2917 return;
2918 }
2919 }
2920
2921 let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
2922
2923 let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
2924 let explanation = self.explain_why_borrow_contains_point(location, borrow, kind_place);
2925
2926 debug!(?place_desc, ?explanation);
2927
2928 let mut err = match (place_desc, explanation) {
2929 (
2939 Some(name),
2940 BorrowExplanation::UsedLater(_, LaterUseKind::ClosureCapture, var_or_use_span, _),
2941 ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
2942 .report_escaping_closure_capture(
2943 borrow_spans,
2944 borrow_span,
2945 &RegionName {
2946 name: self.synthesize_region_name(),
2947 source: RegionNameSource::Static,
2948 },
2949 ConstraintCategory::CallArgument(None),
2950 var_or_use_span,
2951 &format!("`{name}`"),
2952 "block",
2953 ),
2954 (
2955 Some(name),
2956 BorrowExplanation::MustBeValidFor {
2957 category:
2958 category @ (ConstraintCategory::Return(_)
2959 | ConstraintCategory::CallArgument(_)
2960 | ConstraintCategory::OpaqueType),
2961 from_closure: false,
2962 ref region_name,
2963 span,
2964 ..
2965 },
2966 ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
2967 .report_escaping_closure_capture(
2968 borrow_spans,
2969 borrow_span,
2970 region_name,
2971 category,
2972 span,
2973 &format!("`{name}`"),
2974 "function",
2975 ),
2976 (
2977 name,
2978 BorrowExplanation::MustBeValidFor {
2979 category: ConstraintCategory::Assignment,
2980 from_closure: false,
2981 region_name:
2982 RegionName {
2983 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
2984 ..
2985 },
2986 span,
2987 ..
2988 },
2989 ) => self.report_escaping_data(borrow_span, &name, upvar_span, upvar_name, span),
2990 (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
2991 location,
2992 &name,
2993 borrow,
2994 drop_span,
2995 borrow_spans,
2996 explanation,
2997 ),
2998 (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
2999 location,
3000 borrow,
3001 drop_span,
3002 borrow_spans,
3003 proper_span,
3004 explanation,
3005 ),
3006 };
3007 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
3008
3009 self.buffer_error(err);
3010 }
3011
3012 #[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(3012u32),
::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))]
3013 fn report_local_value_does_not_live_long_enough(
3014 &self,
3015 location: Location,
3016 name: &str,
3017 borrow: &BorrowData<'tcx>,
3018 drop_span: Span,
3019 borrow_spans: UseSpans<'tcx>,
3020 explanation: BorrowExplanation<'tcx>,
3021 ) -> Diag<'infcx> {
3022 let borrow_span = borrow_spans.var_or_use_path_span();
3023 if let BorrowExplanation::MustBeValidFor {
3024 category,
3025 span,
3026 ref opt_place_desc,
3027 from_closure: false,
3028 ..
3029 } = explanation
3030 && let Err(diag) = self.try_report_cannot_return_reference_to_local(
3031 borrow,
3032 borrow_span,
3033 span,
3034 category,
3035 opt_place_desc.as_ref(),
3036 )
3037 {
3038 return diag;
3039 }
3040
3041 let name = format!("`{name}`");
3042
3043 let mut err = self.path_does_not_live_long_enough(borrow_span, &name);
3044
3045 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
3046 let region_name = annotation.emit(self, &mut err);
3047
3048 err.span_label(
3049 borrow_span,
3050 format!("{name} would have to be valid for `{region_name}`..."),
3051 );
3052
3053 err.span_label(
3054 drop_span,
3055 format!(
3056 "...but {name} will be dropped here, when the {} returns",
3057 self.infcx
3058 .tcx
3059 .opt_item_name(self.mir_def_id().to_def_id())
3060 .map(|name| format!("function `{name}`"))
3061 .unwrap_or_else(|| {
3062 match &self.infcx.tcx.def_kind(self.mir_def_id()) {
3063 DefKind::Closure
3064 if self
3065 .infcx
3066 .tcx
3067 .is_coroutine(self.mir_def_id().to_def_id()) =>
3068 {
3069 "enclosing coroutine"
3070 }
3071 DefKind::Closure => "enclosing closure",
3072 kind => bug!("expected closure or coroutine, found {:?}", kind),
3073 }
3074 .to_string()
3075 })
3076 ),
3077 );
3078
3079 err.note(
3080 "functions cannot return a borrow to data owned within the function's scope, \
3081 functions can only return borrows to data passed as arguments",
3082 );
3083 err.note(
3084 "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
3085 references-and-borrowing.html#dangling-references>",
3086 );
3087
3088 if let BorrowExplanation::MustBeValidFor { .. } = explanation {
3089 } else {
3090 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3091 }
3092 } else {
3093 err.span_label(borrow_span, "borrowed value does not live long enough");
3094 err.span_label(drop_span, format!("{name} dropped here while still borrowed"));
3095
3096 borrow_spans.args_subdiag(&mut err, |args_span| {
3097 crate::session_diagnostics::CaptureArgLabel::Capture {
3098 is_within: borrow_spans.for_coroutine(),
3099 args_span,
3100 }
3101 });
3102
3103 explanation.add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
3104
3105 if let BorrowExplanation::UsedLater(_dropped_local, _, _, _) = explanation {
3107 for (local, local_decl) in self.body.local_decls.iter_enumerated() {
3109 if let ty::Adt(adt_def, args) = local_decl.ty.kind()
3110 && self.infcx.tcx.is_diagnostic_item(sym::Vec, adt_def.did())
3111 && args.len() > 0
3112 {
3113 let vec_inner_ty = args.type_at(0);
3114 if vec_inner_ty.is_ref() {
3116 let local_place = local.into();
3117 if let Some(local_name) = self.describe_place(local_place) {
3118 err.span_label(
3119 local_decl.source_info.span,
3120 format!("variable `{local_name}` declared here"),
3121 );
3122 err.note(
3123 format!(
3124 "`{local_name}` is a collection that stores borrowed references, \
3125 but {name} does not live long enough to be stored in it"
3126 )
3127 );
3128 err.help(
3129 "buffer reuse with borrowed references requires unsafe code or restructuring"
3130 );
3131 break;
3132 }
3133 }
3134 }
3135 }
3136 }
3137 }
3138
3139 err
3140 }
3141
3142 fn report_borrow_conflicts_with_destructor(
3143 &mut self,
3144 location: Location,
3145 borrow: &BorrowData<'tcx>,
3146 (place, drop_span): (Place<'tcx>, Span),
3147 kind: Option<WriteKind>,
3148 dropped_ty: Ty<'tcx>,
3149 ) {
3150 {
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:3150",
"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(3150u32),
::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!(
3151 "report_borrow_conflicts_with_destructor(\
3152 {:?}, {:?}, ({:?}, {:?}), {:?}\
3153 )",
3154 location, borrow, place, drop_span, kind,
3155 );
3156
3157 let borrow_spans = self.retrieve_borrow_spans(borrow);
3158 let borrow_span = borrow_spans.var_or_use();
3159
3160 let mut err = self.cannot_borrow_across_destructor(borrow_span);
3161
3162 let what_was_dropped = match self.describe_place(place.as_ref()) {
3163 Some(name) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
})format!("`{name}`"),
3164 None => String::from("temporary value"),
3165 };
3166
3167 let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
3168 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!(
3169 "here, drop of {what_was_dropped} needs exclusive access to `{borrowed}`, \
3170 because the type `{dropped_ty}` implements the `Drop` trait"
3171 ),
3172 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!(
3173 "here is drop of {what_was_dropped}; whose type `{dropped_ty}` implements the `Drop` trait"
3174 ),
3175 };
3176 err.span_label(drop_span, label);
3177
3178 let explanation =
3180 self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
3181 match explanation {
3182 BorrowExplanation::UsedLater { .. }
3183 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3184 err.note("consider using a `let` binding to create a longer lived value");
3185 }
3186 _ => {}
3187 }
3188
3189 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3190
3191 self.buffer_error(err);
3192 }
3193
3194 fn report_thread_local_value_does_not_live_long_enough(
3195 &self,
3196 drop_span: Span,
3197 borrow_span: Span,
3198 ) -> Diag<'infcx> {
3199 {
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:3199",
"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(3199u32),
::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!(
3200 "report_thread_local_value_does_not_live_long_enough(\
3201 {:?}, {:?}\
3202 )",
3203 drop_span, borrow_span
3204 );
3205
3206 let sm = self.infcx.tcx.sess.source_map();
3211 let end_of_function = if drop_span.is_empty()
3212 && let Ok(adjusted_span) = sm.span_extend_prev_while(drop_span, |c| c == '}')
3213 {
3214 adjusted_span
3215 } else {
3216 drop_span
3217 };
3218 self.thread_local_value_does_not_live_long_enough(borrow_span)
3219 .with_span_label(
3220 borrow_span,
3221 "thread-local variables cannot be borrowed beyond the end of the function",
3222 )
3223 .with_span_label(end_of_function, "end of enclosing function is here")
3224 }
3225
3226 #[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(3226u32),
::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_verbose(msg,
<[_]>::into_vec(::alloc::boxed::box_new([(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))]
3227 fn report_temporary_value_does_not_live_long_enough(
3228 &self,
3229 location: Location,
3230 borrow: &BorrowData<'tcx>,
3231 drop_span: Span,
3232 borrow_spans: UseSpans<'tcx>,
3233 proper_span: Span,
3234 explanation: BorrowExplanation<'tcx>,
3235 ) -> Diag<'infcx> {
3236 if let BorrowExplanation::MustBeValidFor { category, span, from_closure: false, .. } =
3237 explanation
3238 {
3239 if let Err(diag) = self.try_report_cannot_return_reference_to_local(
3240 borrow,
3241 proper_span,
3242 span,
3243 category,
3244 None,
3245 ) {
3246 return diag;
3247 }
3248 }
3249
3250 let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
3251 err.span_label(proper_span, "creates a temporary value which is freed while still in use");
3252 err.span_label(drop_span, "temporary value is freed at the end of this statement");
3253
3254 match explanation {
3255 BorrowExplanation::UsedLater(..)
3256 | BorrowExplanation::UsedLaterInLoop(..)
3257 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3258 let sm = self.infcx.tcx.sess.source_map();
3260 let mut suggested = false;
3261 let msg = "consider using a `let` binding to create a longer lived value";
3262
3263 struct NestedStatementVisitor<'tcx> {
3272 span: Span,
3273 current: usize,
3274 found: usize,
3275 prop_expr: Option<&'tcx hir::Expr<'tcx>>,
3276 call: Option<&'tcx hir::Expr<'tcx>>,
3277 }
3278
3279 impl<'tcx> Visitor<'tcx> for NestedStatementVisitor<'tcx> {
3280 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
3281 self.current += 1;
3282 walk_block(self, block);
3283 self.current -= 1;
3284 }
3285 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
3286 if let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind {
3287 if self.span == rcvr.span.source_callsite() {
3288 self.call = Some(expr);
3289 }
3290 }
3291 if self.span == expr.span.source_callsite() {
3292 self.found = self.current;
3293 if self.prop_expr.is_none() {
3294 self.prop_expr = Some(expr);
3295 }
3296 }
3297 walk_expr(self, expr);
3298 }
3299 }
3300 let source_info = self.body.source_info(location);
3301 let proper_span = proper_span.source_callsite();
3302 if let Some(scope) = self.body.source_scopes.get(source_info.scope)
3303 && let ClearCrossCrate::Set(scope_data) = &scope.local_data
3304 && let Some(id) = self.infcx.tcx.hir_node(scope_data.lint_root).body_id()
3305 && let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir_body(id).value.kind
3306 {
3307 for stmt in block.stmts {
3308 let mut visitor = NestedStatementVisitor {
3309 span: proper_span,
3310 current: 0,
3311 found: 0,
3312 prop_expr: None,
3313 call: None,
3314 };
3315 visitor.visit_stmt(stmt);
3316
3317 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
3318 let expr_ty: Option<Ty<'_>> =
3319 visitor.prop_expr.map(|expr| typeck_results.expr_ty(expr).peel_refs());
3320
3321 if visitor.found == 0
3322 && stmt.span.contains(proper_span)
3323 && let Some(p) = sm.span_to_margin(stmt.span)
3324 && let Ok(s) = sm.span_to_snippet(proper_span)
3325 {
3326 if let Some(call) = visitor.call
3327 && let hir::ExprKind::MethodCall(path, _, [], _) = call.kind
3328 && path.ident.name == sym::iter
3329 && let Some(ty) = expr_ty
3330 {
3331 err.span_suggestion_verbose(
3332 path.ident.span,
3333 format!(
3334 "consider consuming the `{ty}` when turning it into an \
3335 `Iterator`",
3336 ),
3337 "into_iter",
3338 Applicability::MaybeIncorrect,
3339 );
3340 }
3341
3342 let mutability = if matches!(borrow.kind(), BorrowKind::Mut { .. }) {
3343 "mut "
3344 } else {
3345 ""
3346 };
3347
3348 let addition =
3349 format!("let {}binding = {};\n{}", mutability, s, " ".repeat(p));
3350 err.multipart_suggestion_verbose(
3351 msg,
3352 vec![
3353 (stmt.span.shrink_to_lo(), addition),
3354 (proper_span, "binding".to_string()),
3355 ],
3356 Applicability::MaybeIncorrect,
3357 );
3358
3359 suggested = true;
3360 break;
3361 }
3362 }
3363 }
3364 if !suggested {
3365 err.note(msg);
3366 }
3367 }
3368 _ => {}
3369 }
3370 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3371
3372 borrow_spans.args_subdiag(&mut err, |args_span| {
3373 crate::session_diagnostics::CaptureArgLabel::Capture {
3374 is_within: borrow_spans.for_coroutine(),
3375 args_span,
3376 }
3377 });
3378
3379 err
3380 }
3381
3382 fn try_report_cannot_return_reference_to_local(
3383 &self,
3384 borrow: &BorrowData<'tcx>,
3385 borrow_span: Span,
3386 return_span: Span,
3387 category: ConstraintCategory<'tcx>,
3388 opt_place_desc: Option<&String>,
3389 ) -> Result<(), Diag<'infcx>> {
3390 let return_kind = match category {
3391 ConstraintCategory::Return(_) => "return",
3392 ConstraintCategory::Yield => "yield",
3393 _ => return Ok(()),
3394 };
3395
3396 let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
3398 "reference to"
3399 } else {
3400 "value referencing"
3401 };
3402
3403 let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
3404 let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
3405 match self.body.local_kind(local) {
3406 LocalKind::Temp if self.body.local_decls[local].is_user_variable() => {
3407 "local variable "
3408 }
3409 LocalKind::Arg
3410 if !self.upvars.is_empty() && local == ty::CAPTURE_STRUCT_LOCAL =>
3411 {
3412 "variable captured by `move` "
3413 }
3414 LocalKind::Arg => "function parameter ",
3415 LocalKind::ReturnPointer | LocalKind::Temp => {
3416 ::rustc_middle::util::bug::bug_fmt(format_args!("temporary or return pointer with a name"))bug!("temporary or return pointer with a name")
3417 }
3418 }
3419 } else {
3420 "local data "
3421 };
3422 (::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"))
3423 } else {
3424 let local = borrow.borrowed_place.local;
3425 match self.body.local_kind(local) {
3426 LocalKind::Arg => (
3427 "function parameter".to_string(),
3428 "function parameter borrowed here".to_string(),
3429 ),
3430 LocalKind::Temp
3431 if self.body.local_decls[local].is_user_variable()
3432 && !self.body.local_decls[local]
3433 .source_info
3434 .span
3435 .in_external_macro(self.infcx.tcx.sess.source_map()) =>
3436 {
3437 ("local binding".to_string(), "local binding introduced here".to_string())
3438 }
3439 LocalKind::ReturnPointer | LocalKind::Temp => {
3440 ("temporary value".to_string(), "temporary value created here".to_string())
3441 }
3442 }
3443 };
3444
3445 let mut err = self.cannot_return_reference_to_local(
3446 return_span,
3447 return_kind,
3448 reference_desc,
3449 &place_desc,
3450 );
3451
3452 if return_span != borrow_span {
3453 err.span_label(borrow_span, note);
3454
3455 let tcx = self.infcx.tcx;
3456
3457 let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
3458
3459 if let Some(iter_trait) = tcx.get_diagnostic_item(sym::Iterator)
3461 && self
3462 .infcx
3463 .type_implements_trait(iter_trait, [return_ty], self.infcx.param_env)
3464 .must_apply_modulo_regions()
3465 {
3466 err.span_suggestion_hidden(
3467 return_span.shrink_to_hi(),
3468 "use `.collect()` to allocate the iterator",
3469 ".collect::<Vec<_>>()",
3470 Applicability::MaybeIncorrect,
3471 );
3472 }
3473 }
3474
3475 Err(err)
3476 }
3477
3478 #[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(3478u32),
::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))]
3479 fn report_escaping_closure_capture(
3480 &self,
3481 use_span: UseSpans<'tcx>,
3482 var_span: Span,
3483 fr_name: &RegionName,
3484 category: ConstraintCategory<'tcx>,
3485 constraint_span: Span,
3486 captured_var: &str,
3487 scope: &str,
3488 ) -> Diag<'infcx> {
3489 let tcx = self.infcx.tcx;
3490 let args_span = use_span.args_or_use();
3491
3492 let (sugg_span, suggestion) = match tcx.sess.source_map().span_to_snippet(args_span) {
3493 Ok(string) => {
3494 let coro_prefix = if let Some(sub) = string.strip_prefix("async") {
3495 let trimmed_sub = sub.trim_end();
3496 if trimmed_sub.ends_with("gen") {
3497 Some((trimmed_sub.len() + 5) as _)
3499 } else {
3500 Some(5)
3502 }
3503 } else if string.starts_with("gen") {
3504 Some(3)
3506 } else if string.starts_with("static") {
3507 Some(6)
3510 } else {
3511 None
3512 };
3513 if let Some(n) = coro_prefix {
3514 let pos = args_span.lo() + BytePos(n);
3515 (args_span.with_lo(pos).with_hi(pos), " move")
3516 } else {
3517 (args_span.shrink_to_lo(), "move ")
3518 }
3519 }
3520 Err(_) => (args_span, "move |<args>| <body>"),
3521 };
3522 let kind = match use_span.coroutine_kind() {
3523 Some(coroutine_kind) => match coroutine_kind {
3524 CoroutineKind::Desugared(CoroutineDesugaring::Gen, kind) => match kind {
3525 CoroutineSource::Block => "gen block",
3526 CoroutineSource::Closure => "gen closure",
3527 CoroutineSource::Fn => {
3528 bug!("gen block/closure expected, but gen function found.")
3529 }
3530 },
3531 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, kind) => match kind {
3532 CoroutineSource::Block => "async gen block",
3533 CoroutineSource::Closure => "async gen closure",
3534 CoroutineSource::Fn => {
3535 bug!("gen block/closure expected, but gen function found.")
3536 }
3537 },
3538 CoroutineKind::Desugared(CoroutineDesugaring::Async, async_kind) => {
3539 match async_kind {
3540 CoroutineSource::Block => "async block",
3541 CoroutineSource::Closure => "async closure",
3542 CoroutineSource::Fn => {
3543 bug!("async block/closure expected, but async function found.")
3544 }
3545 }
3546 }
3547 CoroutineKind::Coroutine(_) => "coroutine",
3548 },
3549 None => "closure",
3550 };
3551
3552 let mut err = self.cannot_capture_in_long_lived_closure(
3553 args_span,
3554 kind,
3555 captured_var,
3556 var_span,
3557 scope,
3558 );
3559 err.span_suggestion_verbose(
3560 sugg_span,
3561 format!(
3562 "to force the {kind} to take ownership of {captured_var} (and any \
3563 other referenced variables), use the `move` keyword"
3564 ),
3565 suggestion,
3566 Applicability::MachineApplicable,
3567 );
3568
3569 match category {
3570 ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
3571 let msg = format!("{kind} is returned here");
3572 err.span_note(constraint_span, msg);
3573 }
3574 ConstraintCategory::CallArgument(_) => {
3575 fr_name.highlight_region_name(&mut err);
3576 if matches!(
3577 use_span.coroutine_kind(),
3578 Some(CoroutineKind::Desugared(CoroutineDesugaring::Async, _))
3579 ) {
3580 err.note(
3581 "async blocks are not executed immediately and must either take a \
3582 reference or ownership of outside variables they use",
3583 );
3584 } else {
3585 let msg = format!("{scope} requires argument type to outlive `{fr_name}`");
3586 err.span_note(constraint_span, msg);
3587 }
3588 }
3589 _ => bug!(
3590 "report_escaping_closure_capture called with unexpected constraint \
3591 category: `{:?}`",
3592 category
3593 ),
3594 }
3595
3596 err
3597 }
3598
3599 fn report_escaping_data(
3600 &self,
3601 borrow_span: Span,
3602 name: &Option<String>,
3603 upvar_span: Span,
3604 upvar_name: Symbol,
3605 escape_span: Span,
3606 ) -> Diag<'infcx> {
3607 let tcx = self.infcx.tcx;
3608
3609 let escapes_from = tcx.def_descr(self.mir_def_id().to_def_id());
3610
3611 let mut err =
3612 borrowck_errors::borrowed_data_escapes_closure(tcx, escape_span, escapes_from);
3613
3614 err.span_label(
3615 upvar_span,
3616 ::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"),
3617 );
3618
3619 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"));
3620
3621 if let Some(name) = name {
3622 err.span_label(
3623 escape_span,
3624 ::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"),
3625 );
3626 } else {
3627 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"));
3628 }
3629
3630 err
3631 }
3632
3633 fn get_moved_indexes(
3634 &self,
3635 location: Location,
3636 mpi: MovePathIndex,
3637 ) -> (Vec<MoveSite>, Vec<Location>) {
3638 fn predecessor_locations<'tcx>(
3639 body: &mir::Body<'tcx>,
3640 location: Location,
3641 ) -> impl Iterator<Item = Location> {
3642 if location.statement_index == 0 {
3643 let predecessors = body.basic_blocks.predecessors()[location.block].to_vec();
3644 Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb)))
3645 } else {
3646 Either::Right(std::iter::once(Location {
3647 statement_index: location.statement_index - 1,
3648 ..location
3649 }))
3650 }
3651 }
3652
3653 let mut mpis = <[_]>::into_vec(::alloc::boxed::box_new([mpi]))vec![mpi];
3654 let move_paths = &self.move_data.move_paths;
3655 mpis.extend(move_paths[mpi].parents(move_paths).map(|(mpi, _)| mpi));
3656
3657 let mut stack = Vec::new();
3658 let mut back_edge_stack = Vec::new();
3659
3660 predecessor_locations(self.body, location).for_each(|predecessor| {
3661 if location.dominates(predecessor, self.dominators()) {
3662 back_edge_stack.push(predecessor)
3663 } else {
3664 stack.push(predecessor);
3665 }
3666 });
3667
3668 let mut reached_start = false;
3669
3670 let mut is_argument = false;
3672 for arg in self.body.args_iter() {
3673 if let Some(path) = self.move_data.rev_lookup.find_local(arg) {
3674 if mpis.contains(&path) {
3675 is_argument = true;
3676 }
3677 }
3678 }
3679
3680 let mut visited = FxIndexSet::default();
3681 let mut move_locations = FxIndexSet::default();
3682 let mut reinits = ::alloc::vec::Vec::new()vec![];
3683 let mut result = ::alloc::vec::Vec::new()vec![];
3684
3685 let mut dfs_iter = |result: &mut Vec<MoveSite>, location: Location, is_back_edge: bool| {
3686 {
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:3686",
"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(3686u32),
::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!(
3687 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
3688 location, is_back_edge
3689 );
3690
3691 if !visited.insert(location) {
3692 return true;
3693 }
3694
3695 let stmt_kind =
3697 self.body[location.block].statements.get(location.statement_index).map(|s| &s.kind);
3698 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
3699 } else {
3703 for moi in &self.move_data.loc_map[location] {
3711 {
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:3711",
"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(3711u32),
::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);
3712 let path = self.move_data.moves[*moi].path;
3713 if mpis.contains(&path) {
3714 {
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:3714",
"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(3714u32),
::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!(
3715 "report_use_of_moved_or_uninitialized: found {:?}",
3716 move_paths[path].place
3717 );
3718 result.push(MoveSite { moi: *moi, traversed_back_edge: is_back_edge });
3719 move_locations.insert(location);
3720
3721 return true;
3738 }
3739 }
3740 }
3741
3742 let mut any_match = false;
3744 for ii in &self.move_data.init_loc_map[location] {
3745 let init = self.move_data.inits[*ii];
3746 match init.kind {
3747 InitKind::Deep | InitKind::NonPanicPathOnly => {
3748 if mpis.contains(&init.path) {
3749 any_match = true;
3750 }
3751 }
3752 InitKind::Shallow => {
3753 if mpi == init.path {
3754 any_match = true;
3755 }
3756 }
3757 }
3758 }
3759 if any_match {
3760 reinits.push(location);
3761 return true;
3762 }
3763 false
3764 };
3765
3766 while let Some(location) = stack.pop() {
3767 if dfs_iter(&mut result, location, false) {
3768 continue;
3769 }
3770
3771 let mut has_predecessor = false;
3772 predecessor_locations(self.body, location).for_each(|predecessor| {
3773 if location.dominates(predecessor, self.dominators()) {
3774 back_edge_stack.push(predecessor)
3775 } else {
3776 stack.push(predecessor);
3777 }
3778 has_predecessor = true;
3779 });
3780
3781 if !has_predecessor {
3782 reached_start = true;
3783 }
3784 }
3785 if (is_argument || !reached_start) && result.is_empty() {
3786 while let Some(location) = back_edge_stack.pop() {
3793 if dfs_iter(&mut result, location, true) {
3794 continue;
3795 }
3796
3797 predecessor_locations(self.body, location)
3798 .for_each(|predecessor| back_edge_stack.push(predecessor));
3799 }
3800 }
3801
3802 let reinits_reachable = reinits
3804 .into_iter()
3805 .filter(|reinit| {
3806 let mut visited = FxIndexSet::default();
3807 let mut stack = <[_]>::into_vec(::alloc::boxed::box_new([*reinit]))vec![*reinit];
3808 while let Some(location) = stack.pop() {
3809 if !visited.insert(location) {
3810 continue;
3811 }
3812 if move_locations.contains(&location) {
3813 return true;
3814 }
3815 stack.extend(predecessor_locations(self.body, location));
3816 }
3817 false
3818 })
3819 .collect::<Vec<Location>>();
3820 (result, reinits_reachable)
3821 }
3822
3823 pub(crate) fn report_illegal_mutation_of_borrowed(
3824 &mut self,
3825 location: Location,
3826 (place, span): (Place<'tcx>, Span),
3827 loan: &BorrowData<'tcx>,
3828 ) {
3829 let loan_spans = self.retrieve_borrow_spans(loan);
3830 let loan_span = loan_spans.args_or_use();
3831
3832 let descr_place = self.describe_any_place(place.as_ref());
3833 if let BorrowKind::Fake(_) = loan.kind
3834 && let Some(section) = self.classify_immutable_section(loan.assigned_place)
3835 {
3836 let mut err = self.cannot_mutate_in_immutable_section(
3837 span,
3838 loan_span,
3839 &descr_place,
3840 section,
3841 "assign",
3842 );
3843
3844 loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3845 use crate::session_diagnostics::CaptureVarCause::*;
3846 match kind {
3847 hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3848 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3849 BorrowUseInClosure { var_span }
3850 }
3851 }
3852 });
3853
3854 self.buffer_error(err);
3855
3856 return;
3857 }
3858
3859 let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place);
3860 self.note_due_to_edition_2024_opaque_capture_rules(loan, &mut err);
3861
3862 loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3863 use crate::session_diagnostics::CaptureVarCause::*;
3864 match kind {
3865 hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3866 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3867 BorrowUseInClosure { var_span }
3868 }
3869 }
3870 });
3871
3872 self.explain_why_borrow_contains_point(location, loan, None)
3873 .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3874
3875 self.explain_deref_coercion(loan, &mut err);
3876
3877 self.buffer_error(err);
3878 }
3879
3880 fn explain_deref_coercion(&mut self, loan: &BorrowData<'tcx>, err: &mut Diag<'_>) {
3881 let tcx = self.infcx.tcx;
3882 if let Some(Terminator { kind: TerminatorKind::Call { call_source, fn_span, .. }, .. }) =
3883 &self.body[loan.reserve_location.block].terminator
3884 && let Some((method_did, method_args)) = mir::find_self_call(
3885 tcx,
3886 self.body,
3887 loan.assigned_place.local,
3888 loan.reserve_location.block,
3889 )
3890 && let CallKind::DerefCoercion { deref_target_span, deref_target_ty, .. } = call_kind(
3891 self.infcx.tcx,
3892 self.infcx.typing_env(self.infcx.param_env),
3893 method_did,
3894 method_args,
3895 *fn_span,
3896 call_source.from_hir_call(),
3897 self.infcx.tcx.fn_arg_idents(method_did)[0],
3898 )
3899 {
3900 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}`"));
3901 if let Some(deref_target_span) = deref_target_span {
3902 err.span_note(deref_target_span, "deref defined here");
3903 }
3904 }
3905 }
3906
3907 pub(crate) fn report_illegal_reassignment(
3914 &mut self,
3915 (place, span): (Place<'tcx>, Span),
3916 assigned_span: Span,
3917 err_place: Place<'tcx>,
3918 ) {
3919 let (from_arg, local_decl) = match err_place.as_local() {
3920 Some(local) => {
3921 (self.body.local_kind(local) == LocalKind::Arg, Some(&self.body.local_decls[local]))
3922 }
3923 None => (false, None),
3924 };
3925
3926 let (place_description, assigned_span) = match local_decl {
3930 Some(LocalDecl {
3931 local_info:
3932 ClearCrossCrate::Set(
3933 box LocalInfo::User(BindingForm::Var(VarBindingForm {
3934 opt_match_place: None,
3935 ..
3936 }))
3937 | box LocalInfo::StaticRef { .. }
3938 | box LocalInfo::Boring,
3939 ),
3940 ..
3941 })
3942 | None => (self.describe_any_place(place.as_ref()), assigned_span),
3943 Some(decl) => (self.describe_any_place(err_place.as_ref()), decl.source_info.span),
3944 };
3945 let mut err = self.cannot_reassign_immutable(span, &place_description, from_arg);
3946 let msg = if from_arg {
3947 "cannot assign to immutable argument"
3948 } else {
3949 "cannot assign twice to immutable variable"
3950 };
3951 if span != assigned_span && !from_arg {
3952 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}"));
3953 }
3954 if let Some(decl) = local_decl
3955 && decl.can_be_made_mutable()
3956 {
3957 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!(
3958 decl.local_info(),
3959 LocalInfo::User(BindingForm::Var(VarBindingForm {
3960 opt_match_place: Some((_, match_span)),
3961 ..
3962 })) if matches!(match_span.desugaring_kind(), Some(DesugaringKind::ForLoop))
3963 );
3964 let message = if is_for_loop
3965 && let Ok(binding_name) =
3966 self.infcx.tcx.sess.source_map().span_to_snippet(decl.source_info.span)
3967 {
3968 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("(mut {0}) ", binding_name))
})format!("(mut {}) ", binding_name)
3969 } else {
3970 "mut ".to_string()
3971 };
3972 err.span_suggestion_verbose(
3973 decl.source_info.span.shrink_to_lo(),
3974 "consider making this binding mutable",
3975 message,
3976 Applicability::MachineApplicable,
3977 );
3978
3979 if !from_arg
3980 && !is_for_loop
3981 && #[allow(non_exhaustive_omitted_patterns)] match decl.local_info() {
LocalInfo::User(BindingForm::Var(VarBindingForm {
opt_match_place: Some((Some(_), _)), .. })) => true,
_ => false,
}matches!(
3982 decl.local_info(),
3983 LocalInfo::User(BindingForm::Var(VarBindingForm {
3984 opt_match_place: Some((Some(_), _)),
3985 ..
3986 }))
3987 )
3988 {
3989 err.span_suggestion_verbose(
3990 decl.source_info.span.shrink_to_lo(),
3991 "to modify the original value, take a borrow instead",
3992 "ref mut ".to_string(),
3993 Applicability::MaybeIncorrect,
3994 );
3995 }
3996 }
3997 err.span_label(span, msg);
3998 self.buffer_error(err);
3999 }
4000
4001 fn classify_drop_access_kind(&self, place: PlaceRef<'tcx>) -> StorageDeadOrDrop<'tcx> {
4002 let tcx = self.infcx.tcx;
4003 let (kind, _place_ty) = place.projection.iter().fold(
4004 (LocalStorageDead, PlaceTy::from_ty(self.body.local_decls[place.local].ty)),
4005 |(kind, place_ty), &elem| {
4006 (
4007 match elem {
4008 ProjectionElem::Deref => match kind {
4009 StorageDeadOrDrop::LocalStorageDead
4010 | StorageDeadOrDrop::BoxedStorageDead => {
4011 if !place_ty.ty.is_box() {
{
::core::panicking::panic_fmt(format_args!("Drop of value behind a reference or raw pointer"));
}
};assert!(
4012 place_ty.ty.is_box(),
4013 "Drop of value behind a reference or raw pointer"
4014 );
4015 StorageDeadOrDrop::BoxedStorageDead
4016 }
4017 StorageDeadOrDrop::Destructor(_) => kind,
4018 },
4019 ProjectionElem::OpaqueCast { .. }
4020 | ProjectionElem::Field(..)
4021 | ProjectionElem::Downcast(..) => {
4022 match place_ty.ty.kind() {
4023 ty::Adt(def, _) if def.has_dtor(tcx) => {
4024 match kind {
4026 StorageDeadOrDrop::Destructor(_) => kind,
4027 StorageDeadOrDrop::LocalStorageDead
4028 | StorageDeadOrDrop::BoxedStorageDead => {
4029 StorageDeadOrDrop::Destructor(place_ty.ty)
4030 }
4031 }
4032 }
4033 _ => kind,
4034 }
4035 }
4036 ProjectionElem::ConstantIndex { .. }
4037 | ProjectionElem::Subslice { .. }
4038 | ProjectionElem::Index(_)
4039 | ProjectionElem::UnwrapUnsafeBinder(_) => kind,
4040 },
4041 place_ty.projection_ty(tcx, elem),
4042 )
4043 },
4044 );
4045 kind
4046 }
4047
4048 fn classify_immutable_section(&self, place: Place<'tcx>) -> Option<&'static str> {
4050 use rustc_middle::mir::visit::Visitor;
4051 struct FakeReadCauseFinder<'tcx> {
4052 place: Place<'tcx>,
4053 cause: Option<FakeReadCause>,
4054 }
4055 impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'tcx> {
4056 fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
4057 match statement {
4058 Statement { kind: StatementKind::FakeRead(box (cause, place)), .. }
4059 if *place == self.place =>
4060 {
4061 self.cause = Some(*cause);
4062 }
4063 _ => (),
4064 }
4065 }
4066 }
4067 let mut visitor = FakeReadCauseFinder { place, cause: None };
4068 visitor.visit_body(self.body);
4069 match visitor.cause {
4070 Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
4071 Some(FakeReadCause::ForIndex) => Some("indexing expression"),
4072 _ => None,
4073 }
4074 }
4075
4076 fn annotate_argument_and_return_for_borrow(
4079 &self,
4080 borrow: &BorrowData<'tcx>,
4081 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4082 let fallback = || {
4084 let is_closure = self.infcx.tcx.is_closure_like(self.mir_def_id().to_def_id());
4085 if is_closure {
4086 None
4087 } else {
4088 let ty = self.infcx.tcx.type_of(self.mir_def_id()).instantiate_identity();
4089 match ty.kind() {
4090 ty::FnDef(_, _) | ty::FnPtr(..) => self.annotate_fn_sig(
4091 self.mir_def_id(),
4092 self.infcx.tcx.fn_sig(self.mir_def_id()).instantiate_identity(),
4093 ),
4094 _ => None,
4095 }
4096 }
4097 };
4098
4099 let location = borrow.reserve_location;
4106 {
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:4106",
"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(4106u32),
::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);
4107 if let Some(Statement { kind: StatementKind::Assign(box (reservation, _)), .. }) =
4108 &self.body[location.block].statements.get(location.statement_index)
4109 {
4110 {
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:4110",
"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(4110u32),
::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);
4111 let mut target = match reservation.as_local() {
4113 Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
4114 _ => return None,
4115 };
4116
4117 let mut annotated_closure = None;
4120 for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
4121 {
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:4121",
"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(4121u32),
::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!(
4122 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
4123 target, stmt
4124 );
4125 if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind
4126 && let Some(assigned_to) = place.as_local()
4127 {
4128 {
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:4128",
"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(4128u32),
::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!(
4129 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
4130 rvalue={:?}",
4131 assigned_to, rvalue
4132 );
4133 if let Rvalue::Aggregate(box AggregateKind::Closure(def_id, args), operands) =
4135 rvalue
4136 {
4137 let def_id = def_id.expect_local();
4138 for operand in operands {
4139 let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4140 operand
4141 else {
4142 continue;
4143 };
4144 {
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:4144",
"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(4144u32),
::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!(
4145 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4146 assigned_from
4147 );
4148
4149 let Some(assigned_from_local) = assigned_from.local_or_deref_local()
4151 else {
4152 continue;
4153 };
4154
4155 if assigned_from_local != target {
4156 continue;
4157 }
4158
4159 annotated_closure =
4163 self.annotate_fn_sig(def_id, args.as_closure().sig());
4164 {
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:4164",
"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(4164u32),
::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!(
4165 "annotate_argument_and_return_for_borrow: \
4166 annotated_closure={:?} assigned_from_local={:?} \
4167 assigned_to={:?}",
4168 annotated_closure, assigned_from_local, assigned_to
4169 );
4170
4171 if assigned_to == mir::RETURN_PLACE {
4172 return annotated_closure;
4175 } else {
4176 target = assigned_to;
4178 }
4179 }
4180
4181 continue;
4184 }
4185
4186 let assigned_from = match rvalue {
4188 Rvalue::Ref(_, _, assigned_from) => assigned_from,
4189 Rvalue::Use(operand) => match operand {
4190 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
4191 assigned_from
4192 }
4193 _ => continue,
4194 },
4195 _ => continue,
4196 };
4197 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4197",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4197u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_from={0:?}",
assigned_from) as &dyn Value))])
});
} else { ; }
};debug!(
4198 "annotate_argument_and_return_for_borrow: \
4199 assigned_from={:?}",
4200 assigned_from,
4201 );
4202
4203 let Some(assigned_from_local) = assigned_from.local_or_deref_local() else {
4205 continue;
4206 };
4207 {
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:4207",
"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(4207u32),
::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!(
4208 "annotate_argument_and_return_for_borrow: \
4209 assigned_from_local={:?}",
4210 assigned_from_local,
4211 );
4212
4213 if assigned_from_local != target {
4216 continue;
4217 }
4218
4219 {
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:4221",
"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(4221u32),
::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!(
4222 "annotate_argument_and_return_for_borrow: \
4223 assigned_from_local={:?} assigned_to={:?}",
4224 assigned_from_local, assigned_to
4225 );
4226 if assigned_to == mir::RETURN_PLACE {
4227 return annotated_closure.or_else(fallback);
4230 }
4231
4232 target = assigned_to;
4235 }
4236 }
4237
4238 let terminator = &self.body[location.block].terminator();
4240 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4240",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4240u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: target={0:?} terminator={1:?}",
target, terminator) as &dyn Value))])
});
} else { ; }
};debug!(
4241 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
4242 target, terminator
4243 );
4244 if let TerminatorKind::Call { destination, target: Some(_), args, .. } =
4245 &terminator.kind
4246 && let Some(assigned_to) = destination.as_local()
4247 {
4248 {
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:4248",
"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(4248u32),
::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!(
4249 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
4250 assigned_to, args
4251 );
4252 for operand in args {
4253 let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4254 &operand.node
4255 else {
4256 continue;
4257 };
4258 {
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:4258",
"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(4258u32),
::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!(
4259 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4260 assigned_from,
4261 );
4262
4263 if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
4264 {
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:4264",
"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(4264u32),
::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!(
4265 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
4266 assigned_from_local,
4267 );
4268
4269 if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
4270 return annotated_closure.or_else(fallback);
4271 }
4272 }
4273 }
4274 }
4275 }
4276
4277 {
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:4279",
"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(4279u32),
::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");
4280 None
4281 }
4282
4283 fn annotate_fn_sig(
4286 &self,
4287 did: LocalDefId,
4288 sig: ty::PolyFnSig<'tcx>,
4289 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4290 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4290",
"rustc_borrowck::diagnostics::conflict_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
::tracing_core::__macro_support::Option::Some(4290u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("annotate_fn_sig: did={0:?} sig={1:?}",
did, sig) as &dyn Value))])
});
} else { ; }
};debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
4291 let is_closure = self.infcx.tcx.is_closure_like(did.to_def_id());
4292 let fn_hir_id = self.infcx.tcx.local_def_id_to_hir_id(did);
4293 let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(fn_hir_id)?;
4294
4295 let return_ty = sig.output();
4318 match return_ty.skip_binder().kind() {
4319 ty::Ref(return_region, _, _)
4320 if return_region.is_named(self.infcx.tcx) && !is_closure =>
4321 {
4322 let mut arguments = Vec::new();
4325 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
4326 if let ty::Ref(argument_region, _, _) = argument.kind()
4327 && argument_region == return_region
4328 {
4329 match &fn_decl.inputs[index].kind {
4333 hir::TyKind::Ref(lifetime, _) => {
4334 arguments.push((*argument, lifetime.ident.span));
4337 }
4338 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
4340 if let Res::SelfTyAlias { alias_to, .. } = path.res
4341 && let Some(alias_to) = alias_to.as_local()
4342 && let hir::Impl { self_ty, .. } = self
4343 .infcx
4344 .tcx
4345 .hir_node_by_def_id(alias_to)
4346 .expect_item()
4347 .expect_impl()
4348 && let hir::TyKind::Ref(lifetime, _) = self_ty.kind
4349 {
4350 arguments.push((*argument, lifetime.ident.span));
4351 }
4352 }
4353 _ => {
4354 }
4356 }
4357 }
4358 }
4359
4360 if arguments.is_empty() {
4362 return None;
4363 }
4364
4365 let return_ty = sig.output().skip_binder();
4368 let mut return_span = fn_decl.output.span();
4369 if let hir::FnRetTy::Return(ty) = &fn_decl.output
4370 && let hir::TyKind::Ref(lifetime, _) = ty.kind
4371 {
4372 return_span = lifetime.ident.span;
4373 }
4374
4375 Some(AnnotatedBorrowFnSignature::NamedFunction {
4376 arguments,
4377 return_ty,
4378 return_span,
4379 })
4380 }
4381 ty::Ref(_, _, _) if is_closure => {
4382 let argument_span = fn_decl.inputs.first()?.span;
4386 let argument_ty = sig.inputs().skip_binder().first()?;
4387
4388 if let ty::Tuple(elems) = argument_ty.kind() {
4391 let &argument_ty = elems.first()?;
4392 if let ty::Ref(_, _, _) = argument_ty.kind() {
4393 return Some(AnnotatedBorrowFnSignature::Closure {
4394 argument_ty,
4395 argument_span,
4396 });
4397 }
4398 }
4399
4400 None
4401 }
4402 ty::Ref(_, _, _) => {
4403 let argument_span = fn_decl.inputs.first()?.span;
4406 let argument_ty = *sig.inputs().skip_binder().first()?;
4407
4408 let return_span = fn_decl.output.span();
4409 let return_ty = sig.output().skip_binder();
4410
4411 match argument_ty.kind() {
4413 ty::Ref(_, _, _) => {}
4414 _ => return None,
4415 }
4416
4417 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
4418 argument_ty,
4419 argument_span,
4420 return_ty,
4421 return_span,
4422 })
4423 }
4424 _ => {
4425 None
4428 }
4429 }
4430 }
4431}
4432
4433#[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)]
4434enum AnnotatedBorrowFnSignature<'tcx> {
4435 NamedFunction {
4436 arguments: Vec<(Ty<'tcx>, Span)>,
4437 return_ty: Ty<'tcx>,
4438 return_span: Span,
4439 },
4440 AnonymousFunction {
4441 argument_ty: Ty<'tcx>,
4442 argument_span: Span,
4443 return_ty: Ty<'tcx>,
4444 return_span: Span,
4445 },
4446 Closure {
4447 argument_ty: Ty<'tcx>,
4448 argument_span: Span,
4449 },
4450}
4451
4452impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
4453 pub(crate) fn emit(&self, cx: &MirBorrowckCtxt<'_, '_, 'tcx>, diag: &mut Diag<'_>) -> String {
4456 match self {
4457 &AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
4458 diag.span_label(
4459 argument_span,
4460 ::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)),
4461 );
4462
4463 cx.get_region_name_for_ty(argument_ty, 0)
4464 }
4465 &AnnotatedBorrowFnSignature::AnonymousFunction {
4466 argument_ty,
4467 argument_span,
4468 return_ty,
4469 return_span,
4470 } => {
4471 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
4472 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}`"));
4473
4474 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
4475 let types_equal = return_ty_name == argument_ty_name;
4476 diag.span_label(
4477 return_span,
4478 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}has type `{1}`",
if types_equal { "also " } else { "" }, return_ty_name))
})format!(
4479 "{}has type `{}`",
4480 if types_equal { "also " } else { "" },
4481 return_ty_name,
4482 ),
4483 );
4484
4485 diag.note(
4486 "argument and return type have the same lifetime due to lifetime elision rules",
4487 );
4488 diag.note(
4489 "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
4490 lifetime-syntax.html#lifetime-elision>",
4491 );
4492
4493 cx.get_region_name_for_ty(return_ty, 0)
4494 }
4495 AnnotatedBorrowFnSignature::NamedFunction { arguments, return_ty, return_span } => {
4496 let region_name = cx.get_region_name_for_ty(*return_ty, 0);
4498 for (_, argument_span) in arguments {
4499 diag.span_label(*argument_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("has lifetime `{0}`", region_name))
})format!("has lifetime `{region_name}`"));
4500 }
4501
4502 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}`",));
4503
4504 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!(
4505 "use data from the highlighted arguments which match the `{region_name}` lifetime of \
4506 the return type",
4507 ));
4508
4509 region_name
4510 }
4511 }
4512 }
4513}
4514
4515struct ReferencedStatementsVisitor<'a>(&'a [Span]);
4517
4518impl<'v> Visitor<'v> for ReferencedStatementsVisitor<'_> {
4519 type Result = ControlFlow<()>;
4520 fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) -> Self::Result {
4521 match s.kind {
4522 hir::StmtKind::Semi(expr) if self.0.contains(&expr.span) => ControlFlow::Break(()),
4523 _ => ControlFlow::Continue(()),
4524 }
4525 }
4526}
4527
4528struct BreakFinder {
4532 found_breaks: Vec<(hir::Destination, Span)>,
4533 found_continues: Vec<(hir::Destination, Span)>,
4534}
4535impl<'hir> Visitor<'hir> for BreakFinder {
4536 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
4537 match ex.kind {
4538 hir::ExprKind::Break(destination, _)
4539 if !ex.span.is_desugaring(DesugaringKind::ForLoop) =>
4540 {
4541 self.found_breaks.push((destination, ex.span));
4542 }
4543 hir::ExprKind::Continue(destination) => {
4544 self.found_continues.push((destination, ex.span));
4545 }
4546 _ => {}
4547 }
4548 hir::intravisit::walk_expr(self, ex);
4549 }
4550}
4551
4552struct ConditionVisitor<'tcx> {
4555 tcx: TyCtxt<'tcx>,
4556 spans: Vec<Span>,
4557 name: String,
4558 errors: Vec<(Span, String)>,
4559}
4560
4561impl<'v, 'tcx> Visitor<'v> for ConditionVisitor<'tcx> {
4562 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
4563 match ex.kind {
4564 hir::ExprKind::If(cond, body, None) => {
4565 if ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break() {
4568 self.errors.push((
4569 cond.span,
4570 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this `if` condition is `false`, {0} is not initialized",
self.name))
})format!(
4571 "if this `if` condition is `false`, {} is not initialized",
4572 self.name,
4573 ),
4574 ));
4575 self.errors.push((
4576 ex.span.shrink_to_hi(),
4577 ::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),
4578 ));
4579 }
4580 }
4581 hir::ExprKind::If(cond, body, Some(other)) => {
4582 let a = ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break();
4585 let b = ReferencedStatementsVisitor(&self.spans).visit_expr(other).is_break();
4586 match (a, b) {
4587 (true, true) | (false, false) => {}
4588 (true, false) => {
4589 if other.span.is_desugaring(DesugaringKind::WhileLoop) {
4590 self.errors.push((
4591 cond.span,
4592 ::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!(
4593 "if this condition isn't met and the `while` loop runs 0 \
4594 times, {} is not initialized",
4595 self.name
4596 ),
4597 ));
4598 } else {
4599 self.errors.push((
4600 body.span.shrink_to_hi().until(other.span),
4601 ::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!(
4602 "if the `if` condition is `false` and this `else` arm is \
4603 executed, {} is not initialized",
4604 self.name
4605 ),
4606 ));
4607 }
4608 }
4609 (false, true) => {
4610 self.errors.push((
4611 cond.span,
4612 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this condition is `true`, {0} is not initialized",
self.name))
})format!(
4613 "if this condition is `true`, {} is not initialized",
4614 self.name
4615 ),
4616 ));
4617 }
4618 }
4619 }
4620 hir::ExprKind::Match(e, arms, loop_desugar) => {
4621 let results: Vec<bool> = arms
4624 .iter()
4625 .map(|arm| ReferencedStatementsVisitor(&self.spans).visit_arm(arm).is_break())
4626 .collect();
4627 if results.iter().any(|x| *x) && !results.iter().all(|x| *x) {
4628 for (arm, seen) in arms.iter().zip(results) {
4629 if !seen {
4630 if loop_desugar == hir::MatchSource::ForLoopDesugar {
4631 self.errors.push((
4632 e.span,
4633 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if the `for` loop runs 0 times, {0} is not initialized",
self.name))
})format!(
4634 "if the `for` loop runs 0 times, {} is not initialized",
4635 self.name
4636 ),
4637 ));
4638 } else if let Some(guard) = &arm.guard {
4639 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!(
4640 self.tcx.hir_node(arm.body.hir_id),
4641 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4642 ) {
4643 continue;
4644 }
4645 self.errors.push((
4646 arm.pat.span.to(guard.span),
4647 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this pattern and condition are matched, {0} is not initialized",
self.name))
})format!(
4648 "if this pattern and condition are matched, {} is not \
4649 initialized",
4650 self.name
4651 ),
4652 ));
4653 } else {
4654 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!(
4655 self.tcx.hir_node(arm.body.hir_id),
4656 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4657 ) {
4658 continue;
4659 }
4660 self.errors.push((
4661 arm.pat.span,
4662 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this pattern is matched, {0} is not initialized",
self.name))
})format!(
4663 "if this pattern is matched, {} is not initialized",
4664 self.name
4665 ),
4666 ));
4667 }
4668 }
4669 }
4670 }
4671 }
4672 _ => {}
4677 }
4678 walk_expr(self, ex);
4679 }
4680}