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