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(hir::QPath::LangItem(LangItem::IntoIterIntoIter, _)) =
507 call_expr.kind
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 arg_name = if let Some(var_info) = var_info {
565 var_info.name
566 } else {
567 return;
568 };
569 struct MatchArgFinder {
570 expr_span: Span,
571 match_arg_span: Option<Span>,
572 arg_name: Symbol,
573 }
574 impl Visitor<'_> for MatchArgFinder {
575 fn visit_expr(&mut self, e: &hir::Expr<'_>) {
576 if let hir::ExprKind::Match(expr, ..) = &e.kind
578 && let hir::ExprKind::Path(hir::QPath::Resolved(
579 _,
580 path @ Path { segments: [seg], .. },
581 )) = &expr.kind
582 && seg.ident.name == self.arg_name
583 && self.expr_span.source_callsite().contains(expr.span)
584 {
585 self.match_arg_span = Some(path.span);
586 }
587 hir::intravisit::walk_expr(self, e);
588 }
589 }
590
591 let mut finder = MatchArgFinder { expr_span: move_span, match_arg_span: None, arg_name };
592 finder.visit_expr(body);
593 if let Some(macro_arg_span) = finder.match_arg_span {
594 err.span_suggestion_verbose(
595 macro_arg_span.shrink_to_lo(),
596 "consider borrowing instead of transferring ownership",
597 "&",
598 Applicability::MachineApplicable,
599 );
600 }
601 }
602
603 pub(crate) fn suggest_reborrow(
604 &self,
605 err: &mut Diag<'infcx>,
606 span: Span,
607 moved_place: PlaceRef<'tcx>,
608 ) {
609 err.span_suggestion_verbose(
610 span.shrink_to_lo(),
611 format!(
612 "consider creating a fresh reborrow of {} here",
613 self.describe_place(moved_place)
614 .map(|n| format!("`{n}`"))
615 .unwrap_or_else(|| "the mutable reference".to_string()),
616 ),
617 "&mut *",
618 Applicability::MachineApplicable,
619 );
620 }
621
622 fn suggest_borrow_generic_arg(
629 &self,
630 err: &mut Diag<'_>,
631 typeck: &ty::TypeckResults<'tcx>,
632 call_expr: &hir::Expr<'tcx>,
633 callee_did: DefId,
634 param: ty::ParamTy,
635 moved_place: PlaceRef<'tcx>,
636 moved_arg_pos: usize,
637 moved_arg_ty: Ty<'tcx>,
638 place_span: Span,
639 ) -> Option<ty::Mutability> {
640 let tcx = self.infcx.tcx;
641 let sig = tcx.fn_sig(callee_did).instantiate_identity().skip_binder();
642 let clauses = tcx.predicates_of(callee_did);
643
644 let generic_args = match call_expr.kind {
645 hir::ExprKind::MethodCall(..) => typeck.node_args_opt(call_expr.hir_id)?,
647 hir::ExprKind::Call(callee, _)
650 if let &ty::FnDef(_, args) = typeck.node_type(callee.hir_id).kind() =>
651 {
652 args
653 }
654 _ => return None,
655 };
656
657 if !clauses.instantiate_identity(tcx).predicates.iter().any(|clause| {
660 clause.as_trait_clause().is_some_and(|tc| {
661 tc.self_ty().skip_binder().is_param(param.index)
662 && tc.polarity() == ty::PredicatePolarity::Positive
663 && supertrait_def_ids(tcx, tc.def_id())
664 .flat_map(|trait_did| tcx.associated_items(trait_did).in_definition_order())
665 .any(|item| item.is_method())
666 })
667 }) {
668 return None;
669 }
670
671 if let Some(mutbl) = [ty::Mutability::Not, ty::Mutability::Mut].into_iter().find(|&mutbl| {
673 let re = self.infcx.tcx.lifetimes.re_erased;
674 let ref_ty = Ty::new_ref(self.infcx.tcx, re, moved_arg_ty, mutbl);
675
676 let new_args = tcx.mk_args_from_iter(generic_args.iter().enumerate().map(
679 |(i, arg)| {
680 if i == param.index as usize { ref_ty.into() } else { arg }
681 },
682 ));
683 let can_subst = |ty: Ty<'tcx>| {
684 let old_ty = ty::EarlyBinder::bind(ty).instantiate(tcx, generic_args);
686 let new_ty = ty::EarlyBinder::bind(ty).instantiate(tcx, new_args);
687 if let Ok(old_ty) = tcx.try_normalize_erasing_regions(
688 self.infcx.typing_env(self.infcx.param_env),
689 old_ty,
690 ) && let Ok(new_ty) = tcx.try_normalize_erasing_regions(
691 self.infcx.typing_env(self.infcx.param_env),
692 new_ty,
693 ) {
694 old_ty == new_ty
695 } else {
696 false
697 }
698 };
699 if !can_subst(sig.output())
700 || sig
701 .inputs()
702 .iter()
703 .enumerate()
704 .any(|(i, &input_ty)| i != moved_arg_pos && !can_subst(input_ty))
705 {
706 return false;
707 }
708
709 clauses.instantiate(tcx, new_args).predicates.iter().all(|&(mut clause)| {
711 if let Ok(normalized) = tcx.try_normalize_erasing_regions(
713 self.infcx.typing_env(self.infcx.param_env),
714 clause,
715 ) {
716 clause = normalized;
717 }
718 self.infcx.predicate_must_hold_modulo_regions(&Obligation::new(
719 tcx,
720 ObligationCause::dummy(),
721 self.infcx.param_env,
722 clause,
723 ))
724 })
725 }) {
726 let place_desc = if let Some(desc) = self.describe_place(moved_place) {
727 format!("`{desc}`")
728 } else {
729 "here".to_owned()
730 };
731 err.span_suggestion_verbose(
732 place_span.shrink_to_lo(),
733 format!("consider {}borrowing {place_desc}", mutbl.mutably_str()),
734 mutbl.ref_prefix_str(),
735 Applicability::MaybeIncorrect,
736 );
737 Some(mutbl)
738 } else {
739 None
740 }
741 }
742
743 fn report_use_of_uninitialized(
744 &self,
745 mpi: MovePathIndex,
746 used_place: PlaceRef<'tcx>,
747 moved_place: PlaceRef<'tcx>,
748 desired_action: InitializationRequiringAction,
749 span: Span,
750 use_spans: UseSpans<'tcx>,
751 ) -> Diag<'infcx> {
752 let inits = &self.move_data.init_path_map[mpi];
755 let move_path = &self.move_data.move_paths[mpi];
756 let decl_span = self.body.local_decls[move_path.place.local].source_info.span;
757 let mut spans_set = FxIndexSet::default();
758 for init_idx in inits {
759 let init = &self.move_data.inits[*init_idx];
760 let span = init.span(self.body);
761 if !span.is_dummy() {
762 spans_set.insert(span);
763 }
764 }
765 let spans: Vec<_> = spans_set.into_iter().collect();
766
767 let (name, desc) = match self.describe_place_with_options(
768 moved_place,
769 DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
770 ) {
771 Some(name) => (format!("`{name}`"), format!("`{name}` ")),
772 None => ("the variable".to_string(), String::new()),
773 };
774 let path = match self.describe_place_with_options(
775 used_place,
776 DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
777 ) {
778 Some(name) => format!("`{name}`"),
779 None => "value".to_string(),
780 };
781
782 let tcx = self.infcx.tcx;
785 let body = tcx.hir_body_owned_by(self.mir_def_id());
786 let mut visitor = ConditionVisitor { tcx, spans, name, errors: vec![] };
787 visitor.visit_body(&body);
788 let spans = visitor.spans;
789
790 let mut show_assign_sugg = false;
791 let isnt_initialized = if let InitializationRequiringAction::PartialAssignment
792 | InitializationRequiringAction::Assignment = desired_action
793 {
794 "isn't fully initialized"
798 } else if !spans.iter().any(|i| {
799 !i.contains(span)
806 && !visitor
808 .errors
809 .iter()
810 .map(|(sp, _)| *sp)
811 .any(|sp| span < sp && !sp.contains(span))
812 }) {
813 show_assign_sugg = true;
814 "isn't initialized"
815 } else {
816 "is possibly-uninitialized"
817 };
818
819 let used = desired_action.as_general_verb_in_past_tense();
820 let mut err = struct_span_code_err!(
821 self.dcx(),
822 span,
823 E0381,
824 "{used} binding {desc}{isnt_initialized}"
825 );
826 use_spans.var_path_only_subdiag(&mut err, desired_action);
827
828 if let InitializationRequiringAction::PartialAssignment
829 | InitializationRequiringAction::Assignment = desired_action
830 {
831 err.help(
832 "partial initialization isn't supported, fully initialize the binding with a \
833 default value and mutate it, or use `std::mem::MaybeUninit`",
834 );
835 }
836 err.span_label(span, format!("{path} {used} here but it {isnt_initialized}"));
837
838 let mut shown = false;
839 for (sp, label) in visitor.errors {
840 if sp < span && !sp.overlaps(span) {
841 err.span_label(sp, label);
855 shown = true;
856 }
857 }
858 if !shown {
859 for sp in &spans {
860 if *sp < span && !sp.overlaps(span) {
861 err.span_label(*sp, "binding initialized here in some conditions");
862 }
863 }
864 }
865
866 err.span_label(decl_span, "binding declared here but left uninitialized");
867 if show_assign_sugg {
868 struct LetVisitor {
869 decl_span: Span,
870 sugg_span: Option<Span>,
871 }
872
873 impl<'v> Visitor<'v> for LetVisitor {
874 fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) {
875 if self.sugg_span.is_some() {
876 return;
877 }
878
879 if let hir::StmtKind::Let(hir::LetStmt { span, ty, init: None, pat, .. }) =
882 &ex.kind
883 && let hir::PatKind::Binding(..) = pat.kind
884 && span.contains(self.decl_span)
885 {
886 self.sugg_span = ty.map_or(Some(self.decl_span), |ty| Some(ty.span));
887 }
888 hir::intravisit::walk_stmt(self, ex);
889 }
890 }
891
892 let mut visitor = LetVisitor { decl_span, sugg_span: None };
893 visitor.visit_body(&body);
894 if let Some(span) = visitor.sugg_span {
895 self.suggest_assign_value(&mut err, moved_place, span);
896 }
897 }
898 err
899 }
900
901 fn suggest_assign_value(
902 &self,
903 err: &mut Diag<'_>,
904 moved_place: PlaceRef<'tcx>,
905 sugg_span: Span,
906 ) {
907 let ty = moved_place.ty(self.body, self.infcx.tcx).ty;
908 debug!("ty: {:?}, kind: {:?}", ty, ty.kind());
909
910 let Some(assign_value) = self.infcx.err_ctxt().ty_kind_suggestion(self.infcx.param_env, ty)
911 else {
912 return;
913 };
914
915 err.span_suggestion_verbose(
916 sugg_span.shrink_to_hi(),
917 "consider assigning a value",
918 format!(" = {assign_value}"),
919 Applicability::MaybeIncorrect,
920 );
921 }
922
923 fn suggest_hoisting_call_outside_loop(&self, err: &mut Diag<'_>, expr: &hir::Expr<'_>) -> bool {
928 let tcx = self.infcx.tcx;
929 let mut can_suggest_clone = true;
930
931 let local_hir_id = if let hir::ExprKind::Path(hir::QPath::Resolved(
935 _,
936 hir::Path { res: hir::def::Res::Local(local_hir_id), .. },
937 )) = expr.kind
938 {
939 Some(local_hir_id)
940 } else {
941 None
944 };
945
946 struct Finder {
950 hir_id: hir::HirId,
951 }
952 impl<'hir> Visitor<'hir> for Finder {
953 type Result = ControlFlow<()>;
954 fn visit_pat(&mut self, pat: &'hir hir::Pat<'hir>) -> Self::Result {
955 if pat.hir_id == self.hir_id {
956 return ControlFlow::Break(());
957 }
958 hir::intravisit::walk_pat(self, pat)
959 }
960 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) -> Self::Result {
961 if ex.hir_id == self.hir_id {
962 return ControlFlow::Break(());
963 }
964 hir::intravisit::walk_expr(self, ex)
965 }
966 }
967 let mut parent = None;
969 let mut outer_most_loop: Option<&hir::Expr<'_>> = None;
971 for (_, node) in tcx.hir_parent_iter(expr.hir_id) {
972 let e = match node {
973 hir::Node::Expr(e) => e,
974 hir::Node::LetStmt(hir::LetStmt { els: Some(els), .. }) => {
975 let mut finder = BreakFinder { found_breaks: vec![], found_continues: vec![] };
976 finder.visit_block(els);
977 if !finder.found_breaks.is_empty() {
978 can_suggest_clone = false;
983 }
984 continue;
985 }
986 _ => continue,
987 };
988 if let Some(&hir_id) = local_hir_id {
989 if (Finder { hir_id }).visit_expr(e).is_break() {
990 break;
993 }
994 }
995 if parent.is_none() {
996 parent = Some(e);
997 }
998 match e.kind {
999 hir::ExprKind::Let(_) => {
1000 match tcx.parent_hir_node(e.hir_id) {
1001 hir::Node::Expr(hir::Expr {
1002 kind: hir::ExprKind::If(cond, ..), ..
1003 }) => {
1004 if (Finder { hir_id: expr.hir_id }).visit_expr(cond).is_break() {
1005 can_suggest_clone = false;
1011 }
1012 }
1013 _ => {}
1014 }
1015 }
1016 hir::ExprKind::Loop(..) => {
1017 outer_most_loop = Some(e);
1018 }
1019 _ => {}
1020 }
1021 }
1022 let loop_count: usize = tcx
1023 .hir_parent_iter(expr.hir_id)
1024 .map(|(_, node)| match node {
1025 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Loop(..), .. }) => 1,
1026 _ => 0,
1027 })
1028 .sum();
1029
1030 let sm = tcx.sess.source_map();
1031 if let Some(in_loop) = outer_most_loop {
1032 let mut finder = BreakFinder { found_breaks: vec![], found_continues: vec![] };
1033 finder.visit_expr(in_loop);
1034 let spans = finder
1036 .found_breaks
1037 .iter()
1038 .chain(finder.found_continues.iter())
1039 .map(|(_, span)| *span)
1040 .filter(|span| {
1041 !matches!(
1042 span.desugaring_kind(),
1043 Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop)
1044 )
1045 })
1046 .collect::<Vec<Span>>();
1047 let loop_spans: Vec<_> = tcx
1049 .hir_parent_iter(expr.hir_id)
1050 .filter_map(|(_, node)| match node {
1051 hir::Node::Expr(hir::Expr { span, kind: hir::ExprKind::Loop(..), .. }) => {
1052 Some(*span)
1053 }
1054 _ => None,
1055 })
1056 .collect();
1057 if !spans.is_empty() && loop_count > 1 {
1060 let mut lines: Vec<_> =
1064 loop_spans.iter().map(|sp| sm.lookup_char_pos(sp.lo()).line).collect();
1065 lines.sort();
1066 lines.dedup();
1067 let fmt_span = |span: Span| {
1068 if lines.len() == loop_spans.len() {
1069 format!("line {}", sm.lookup_char_pos(span.lo()).line)
1070 } else {
1071 sm.span_to_diagnostic_string(span)
1072 }
1073 };
1074 let mut spans: MultiSpan = spans.into();
1075 for (desc, elements) in [
1077 ("`break` exits", &finder.found_breaks),
1078 ("`continue` advances", &finder.found_continues),
1079 ] {
1080 for (destination, sp) in elements {
1081 if let Ok(hir_id) = destination.target_id
1082 && let hir::Node::Expr(expr) = tcx.hir_node(hir_id)
1083 && !matches!(
1084 sp.desugaring_kind(),
1085 Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop)
1086 )
1087 {
1088 spans.push_span_label(
1089 *sp,
1090 format!("this {desc} the loop at {}", fmt_span(expr.span)),
1091 );
1092 }
1093 }
1094 }
1095 for span in loop_spans {
1097 spans.push_span_label(sm.guess_head_span(span), "");
1098 }
1099
1100 err.span_note(spans, "verify that your loop breaking logic is correct");
1112 }
1113 if let Some(parent) = parent
1114 && let hir::ExprKind::MethodCall(..) | hir::ExprKind::Call(..) = parent.kind
1115 {
1116 let span = in_loop.span;
1121 if !finder.found_breaks.is_empty()
1122 && let Ok(value) = sm.span_to_snippet(parent.span)
1123 {
1124 let indent = if let Some(indent) = sm.indentation_before(span) {
1127 format!("\n{indent}")
1128 } else {
1129 " ".to_string()
1130 };
1131 err.multipart_suggestion(
1132 "consider moving the expression out of the loop so it is only moved once",
1133 vec![
1134 (span.shrink_to_lo(), format!("let mut value = {value};{indent}")),
1135 (parent.span, "value".to_string()),
1136 ],
1137 Applicability::MaybeIncorrect,
1138 );
1139 }
1140 }
1141 }
1142 can_suggest_clone
1143 }
1144
1145 fn suggest_cloning_on_functional_record_update(
1148 &self,
1149 err: &mut Diag<'_>,
1150 ty: Ty<'tcx>,
1151 expr: &hir::Expr<'_>,
1152 ) {
1153 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1154 let hir::ExprKind::Struct(struct_qpath, fields, hir::StructTailExpr::Base(base)) =
1155 expr.kind
1156 else {
1157 return;
1158 };
1159 let hir::QPath::Resolved(_, path) = struct_qpath else { return };
1160 let hir::def::Res::Def(_, def_id) = path.res else { return };
1161 let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id) else { return };
1162 let ty::Adt(def, args) = expr_ty.kind() else { return };
1163 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = base.kind else { return };
1164 let (hir::def::Res::Local(_)
1165 | hir::def::Res::Def(
1166 DefKind::Const | DefKind::ConstParam | DefKind::Static { .. } | DefKind::AssocConst,
1167 _,
1168 )) = path.res
1169 else {
1170 return;
1171 };
1172 let Ok(base_str) = self.infcx.tcx.sess.source_map().span_to_snippet(base.span) else {
1173 return;
1174 };
1175
1176 let mut final_field_count = fields.len();
1182 let Some(variant) = def.variants().iter().find(|variant| variant.def_id == def_id) else {
1183 return;
1186 };
1187 let mut sugg = vec![];
1188 for field in &variant.fields {
1189 let field_ty = field.ty(self.infcx.tcx, args);
1193 let ident = field.ident(self.infcx.tcx);
1194 if field_ty == ty && fields.iter().all(|field| field.ident.name != ident.name) {
1195 sugg.push(format!("{ident}: {base_str}.{ident}.clone()"));
1197 final_field_count += 1;
1198 }
1199 }
1200 let (span, sugg) = match fields {
1201 [.., last] => (
1202 if final_field_count == variant.fields.len() {
1203 last.span.shrink_to_hi().with_hi(base.span.hi())
1205 } else {
1206 last.span.shrink_to_hi()
1207 },
1208 format!(", {}", sugg.join(", ")),
1209 ),
1210 [] => (
1212 expr.span.with_lo(struct_qpath.span().hi()),
1213 if final_field_count == variant.fields.len() {
1214 format!(" {{ {} }}", sugg.join(", "))
1216 } else {
1217 format!(" {{ {}, ..{base_str} }}", sugg.join(", "))
1218 },
1219 ),
1220 };
1221 let prefix = if !self.implements_clone(ty) {
1222 let msg = format!("`{ty}` doesn't implement `Copy` or `Clone`");
1223 if let ty::Adt(def, _) = ty.kind() {
1224 err.span_note(self.infcx.tcx.def_span(def.did()), msg);
1225 } else {
1226 err.note(msg);
1227 }
1228 format!("if `{ty}` implemented `Clone`, you could ")
1229 } else {
1230 String::new()
1231 };
1232 let msg = format!(
1233 "{prefix}clone the value from the field instead of using the functional record update \
1234 syntax",
1235 );
1236 err.span_suggestion_verbose(span, msg, sugg, Applicability::MachineApplicable);
1237 }
1238
1239 pub(crate) fn suggest_cloning(
1240 &self,
1241 err: &mut Diag<'_>,
1242 place: PlaceRef<'tcx>,
1243 ty: Ty<'tcx>,
1244 expr: &'tcx hir::Expr<'tcx>,
1245 use_spans: Option<UseSpans<'tcx>>,
1246 ) {
1247 if let hir::ExprKind::Struct(_, _, hir::StructTailExpr::Base(_)) = expr.kind {
1248 self.suggest_cloning_on_functional_record_update(err, ty, expr);
1253 return;
1254 }
1255
1256 if self.implements_clone(ty) {
1257 if self.in_move_closure(expr) {
1258 if let Some(name) = self.describe_place(place) {
1259 self.suggest_clone_of_captured_var_in_move_closure(err, &name, use_spans);
1260 }
1261 } else {
1262 self.suggest_cloning_inner(err, ty, expr);
1263 }
1264 } else if let ty::Adt(def, args) = ty.kind()
1265 && def.did().as_local().is_some()
1266 && def.variants().iter().all(|variant| {
1267 variant
1268 .fields
1269 .iter()
1270 .all(|field| self.implements_clone(field.ty(self.infcx.tcx, args)))
1271 })
1272 {
1273 let ty_span = self.infcx.tcx.def_span(def.did());
1274 let mut span: MultiSpan = ty_span.into();
1275 span.push_span_label(ty_span, "consider implementing `Clone` for this type");
1276 span.push_span_label(expr.span, "you could clone this value");
1277 err.span_note(
1278 span,
1279 format!("if `{ty}` implemented `Clone`, you could clone the value"),
1280 );
1281 } else if let ty::Param(param) = ty.kind()
1282 && let Some(_clone_trait_def) = self.infcx.tcx.lang_items().clone_trait()
1283 && let generics = self.infcx.tcx.generics_of(self.mir_def_id())
1284 && let generic_param = generics.type_param(*param, self.infcx.tcx)
1285 && let param_span = self.infcx.tcx.def_span(generic_param.def_id)
1286 && if let Some(UseSpans::FnSelfUse { kind, .. }) = use_spans
1287 && let CallKind::FnCall { fn_trait_id, self_ty } = kind
1288 && let ty::Param(_) = self_ty.kind()
1289 && ty == self_ty
1290 && self.infcx.tcx.fn_trait_kind_from_def_id(fn_trait_id).is_some()
1291 {
1292 false
1294 } else {
1295 true
1296 }
1297 {
1298 let mut span: MultiSpan = param_span.into();
1299 span.push_span_label(
1300 param_span,
1301 "consider constraining this type parameter with `Clone`",
1302 );
1303 span.push_span_label(expr.span, "you could clone this value");
1304 err.span_help(
1305 span,
1306 format!("if `{ty}` implemented `Clone`, you could clone the value"),
1307 );
1308 } else if let ty::Adt(_, _) = ty.kind()
1309 && let Some(clone_trait) = self.infcx.tcx.lang_items().clone_trait()
1310 {
1311 let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1314 let cause = ObligationCause::misc(expr.span, self.mir_def_id());
1315 ocx.register_bound(cause, self.infcx.param_env, ty, clone_trait);
1316 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1317 if errors.iter().all(|error| {
1318 match error.obligation.predicate.as_clause().and_then(|c| c.as_trait_clause()) {
1319 Some(clause) => match clause.self_ty().skip_binder().kind() {
1320 ty::Adt(def, _) => def.did().is_local() && clause.def_id() == clone_trait,
1321 _ => false,
1322 },
1323 None => false,
1324 }
1325 }) {
1326 let mut type_spans = vec![];
1327 let mut types = FxIndexSet::default();
1328 for clause in errors
1329 .iter()
1330 .filter_map(|e| e.obligation.predicate.as_clause())
1331 .filter_map(|c| c.as_trait_clause())
1332 {
1333 let ty::Adt(def, _) = clause.self_ty().skip_binder().kind() else { continue };
1334 type_spans.push(self.infcx.tcx.def_span(def.did()));
1335 types.insert(
1336 self.infcx
1337 .tcx
1338 .short_string(clause.self_ty().skip_binder(), &mut err.long_ty_path()),
1339 );
1340 }
1341 let mut span: MultiSpan = type_spans.clone().into();
1342 for sp in type_spans {
1343 span.push_span_label(sp, "consider implementing `Clone` for this type");
1344 }
1345 span.push_span_label(expr.span, "you could clone this value");
1346 let types: Vec<_> = types.into_iter().collect();
1347 let msg = match &types[..] {
1348 [only] => format!("`{only}`"),
1349 [head @ .., last] => format!(
1350 "{} and `{last}`",
1351 head.iter().map(|t| format!("`{t}`")).collect::<Vec<_>>().join(", ")
1352 ),
1353 [] => unreachable!(),
1354 };
1355 err.span_note(
1356 span,
1357 format!("if {msg} implemented `Clone`, you could clone the value"),
1358 );
1359 }
1360 }
1361 }
1362
1363 pub(crate) fn implements_clone(&self, ty: Ty<'tcx>) -> bool {
1364 let Some(clone_trait_def) = self.infcx.tcx.lang_items().clone_trait() else { return false };
1365 self.infcx
1366 .type_implements_trait(clone_trait_def, [ty], self.infcx.param_env)
1367 .must_apply_modulo_regions()
1368 }
1369
1370 pub(crate) fn clone_on_reference(&self, expr: &hir::Expr<'_>) -> Option<Span> {
1373 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1374 if let hir::ExprKind::MethodCall(segment, rcvr, args, span) = expr.kind
1375 && let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id)
1376 && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
1377 && rcvr_ty == expr_ty
1378 && segment.ident.name == sym::clone
1379 && args.is_empty()
1380 {
1381 Some(span)
1382 } else {
1383 None
1384 }
1385 }
1386
1387 fn in_move_closure(&self, expr: &hir::Expr<'_>) -> bool {
1388 for (_, node) in self.infcx.tcx.hir_parent_iter(expr.hir_id) {
1389 if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) = node
1390 && let hir::CaptureBy::Value { .. } = closure.capture_clause
1391 {
1392 return true;
1394 }
1395 }
1396 false
1397 }
1398
1399 fn suggest_cloning_inner(
1400 &self,
1401 err: &mut Diag<'_>,
1402 ty: Ty<'tcx>,
1403 expr: &hir::Expr<'_>,
1404 ) -> bool {
1405 let tcx = self.infcx.tcx;
1406 if let Some(_) = self.clone_on_reference(expr) {
1407 return false;
1410 }
1411 if self.in_move_closure(expr) {
1414 return false;
1415 }
1416 if let hir::ExprKind::Closure(_) = expr.kind {
1419 return false;
1420 }
1421 let mut suggestion =
1423 if let Some(symbol) = tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1424 format!(": {symbol}.clone()")
1425 } else {
1426 ".clone()".to_owned()
1427 };
1428 let mut sugg = Vec::with_capacity(2);
1429 let mut inner_expr = expr;
1430 let mut is_raw_ptr = false;
1431 let typeck_result = self.infcx.tcx.typeck(self.mir_def_id());
1432 while let hir::ExprKind::AddrOf(.., inner) | hir::ExprKind::Unary(hir::UnOp::Deref, inner) =
1434 &inner_expr.kind
1435 {
1436 if let hir::ExprKind::AddrOf(_, hir::Mutability::Mut, _) = inner_expr.kind {
1437 return false;
1440 }
1441 inner_expr = inner;
1442 if let Some(inner_type) = typeck_result.node_type_opt(inner.hir_id) {
1443 if matches!(inner_type.kind(), ty::RawPtr(..)) {
1444 is_raw_ptr = true;
1445 break;
1446 }
1447 }
1448 }
1449 if inner_expr.span.lo() != expr.span.lo() && !is_raw_ptr {
1452 sugg.push((expr.span.with_hi(inner_expr.span.lo()), String::new()));
1454 }
1455 let span = if inner_expr.span.hi() != expr.span.hi() {
1457 if is_raw_ptr {
1459 expr.span.shrink_to_hi()
1460 } else {
1461 expr.span.with_lo(inner_expr.span.hi())
1463 }
1464 } else {
1465 if is_raw_ptr {
1466 sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
1467 suggestion = ").clone()".to_string();
1468 }
1469 expr.span.shrink_to_hi()
1470 };
1471 sugg.push((span, suggestion));
1472 let msg = if let ty::Adt(def, _) = ty.kind()
1473 && [tcx.get_diagnostic_item(sym::Arc), tcx.get_diagnostic_item(sym::Rc)]
1474 .contains(&Some(def.did()))
1475 {
1476 "clone the value to increment its reference count"
1477 } else {
1478 "consider cloning the value if the performance cost is acceptable"
1479 };
1480 err.multipart_suggestion_verbose(msg, sugg, Applicability::MachineApplicable);
1481 true
1482 }
1483
1484 fn suggest_adding_bounds(&self, err: &mut Diag<'_>, ty: Ty<'tcx>, def_id: DefId, span: Span) {
1485 let tcx = self.infcx.tcx;
1486 let generics = tcx.generics_of(self.mir_def_id());
1487
1488 let Some(hir_generics) = tcx
1489 .typeck_root_def_id(self.mir_def_id().to_def_id())
1490 .as_local()
1491 .and_then(|def_id| tcx.hir_get_generics(def_id))
1492 else {
1493 return;
1494 };
1495 let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1497 let cause = ObligationCause::misc(span, self.mir_def_id());
1498
1499 ocx.register_bound(cause, self.infcx.param_env, ty, def_id);
1500 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1501
1502 let predicates: Result<Vec<_>, _> = errors
1504 .into_iter()
1505 .map(|err| match err.obligation.predicate.kind().skip_binder() {
1506 PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => {
1507 match *predicate.self_ty().kind() {
1508 ty::Param(param_ty) => Ok((
1509 generics.type_param(param_ty, tcx),
1510 predicate.trait_ref.print_trait_sugared().to_string(),
1511 Some(predicate.trait_ref.def_id),
1512 )),
1513 _ => Err(()),
1514 }
1515 }
1516 _ => Err(()),
1517 })
1518 .collect();
1519
1520 if let Ok(predicates) = predicates {
1521 suggest_constraining_type_params(
1522 tcx,
1523 hir_generics,
1524 err,
1525 predicates.iter().map(|(param, constraint, def_id)| {
1526 (param.name.as_str(), &**constraint, *def_id)
1527 }),
1528 None,
1529 );
1530 }
1531 }
1532
1533 pub(crate) fn report_move_out_while_borrowed(
1534 &mut self,
1535 location: Location,
1536 (place, span): (Place<'tcx>, Span),
1537 borrow: &BorrowData<'tcx>,
1538 ) {
1539 debug!(
1540 "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
1541 location, place, span, borrow
1542 );
1543 let value_msg = self.describe_any_place(place.as_ref());
1544 let borrow_msg = self.describe_any_place(borrow.borrowed_place.as_ref());
1545
1546 let borrow_spans = self.retrieve_borrow_spans(borrow);
1547 let borrow_span = borrow_spans.args_or_use();
1548
1549 let move_spans = self.move_spans(place.as_ref(), location);
1550 let span = move_spans.args_or_use();
1551
1552 let mut err = self.cannot_move_when_borrowed(
1553 span,
1554 borrow_span,
1555 &self.describe_any_place(place.as_ref()),
1556 &borrow_msg,
1557 &value_msg,
1558 );
1559 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1560
1561 borrow_spans.var_path_only_subdiag(&mut err, crate::InitializationRequiringAction::Borrow);
1562
1563 move_spans.var_subdiag(&mut err, None, |kind, var_span| {
1564 use crate::session_diagnostics::CaptureVarCause::*;
1565 match kind {
1566 hir::ClosureKind::Coroutine(_) => MoveUseInCoroutine { var_span },
1567 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1568 MoveUseInClosure { var_span }
1569 }
1570 }
1571 });
1572
1573 self.explain_why_borrow_contains_point(location, borrow, None)
1574 .add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
1575 self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
1576 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1577 if let Some(expr) = self.find_expr(borrow_span) {
1578 if let hir::ExprKind::AddrOf(_, _, borrowed_expr) = expr.kind
1580 && let Some(ty) = typeck_results.expr_ty_opt(borrowed_expr)
1581 {
1582 self.suggest_cloning(&mut err, place.as_ref(), ty, borrowed_expr, Some(move_spans));
1583 } else if typeck_results.expr_adjustments(expr).first().is_some_and(|adj| {
1584 matches!(
1585 adj.kind,
1586 ty::adjustment::Adjust::Borrow(ty::adjustment::AutoBorrow::Ref(
1587 ty::adjustment::AutoBorrowMutability::Not
1588 | ty::adjustment::AutoBorrowMutability::Mut {
1589 allow_two_phase_borrow: ty::adjustment::AllowTwoPhase::No
1590 }
1591 ))
1592 )
1593 }) && let Some(ty) = typeck_results.expr_ty_opt(expr)
1594 {
1595 self.suggest_cloning(&mut err, place.as_ref(), ty, expr, Some(move_spans));
1596 }
1597 }
1598 self.buffer_error(err);
1599 }
1600
1601 pub(crate) fn report_use_while_mutably_borrowed(
1602 &self,
1603 location: Location,
1604 (place, _span): (Place<'tcx>, Span),
1605 borrow: &BorrowData<'tcx>,
1606 ) -> Diag<'infcx> {
1607 let borrow_spans = self.retrieve_borrow_spans(borrow);
1608 let borrow_span = borrow_spans.args_or_use();
1609
1610 let use_spans = self.move_spans(place.as_ref(), location);
1613 let span = use_spans.var_or_use();
1614
1615 let mut err = self.cannot_use_when_mutably_borrowed(
1619 span,
1620 &self.describe_any_place(place.as_ref()),
1621 borrow_span,
1622 &self.describe_any_place(borrow.borrowed_place.as_ref()),
1623 );
1624 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1625
1626 borrow_spans.var_subdiag(&mut err, Some(borrow.kind), |kind, var_span| {
1627 use crate::session_diagnostics::CaptureVarCause::*;
1628 let place = &borrow.borrowed_place;
1629 let desc_place = self.describe_any_place(place.as_ref());
1630 match kind {
1631 hir::ClosureKind::Coroutine(_) => {
1632 BorrowUsePlaceCoroutine { place: desc_place, var_span, is_single_var: true }
1633 }
1634 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1635 BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: true }
1636 }
1637 }
1638 });
1639
1640 self.explain_why_borrow_contains_point(location, borrow, None)
1641 .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
1642 err
1643 }
1644
1645 pub(crate) fn report_conflicting_borrow(
1646 &self,
1647 location: Location,
1648 (place, span): (Place<'tcx>, Span),
1649 gen_borrow_kind: BorrowKind,
1650 issued_borrow: &BorrowData<'tcx>,
1651 ) -> Diag<'infcx> {
1652 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
1653 let issued_span = issued_spans.args_or_use();
1654
1655 let borrow_spans = self.borrow_spans(span, location);
1656 let span = borrow_spans.args_or_use();
1657
1658 let container_name = if issued_spans.for_coroutine() || borrow_spans.for_coroutine() {
1659 "coroutine"
1660 } else {
1661 "closure"
1662 };
1663
1664 let (desc_place, msg_place, msg_borrow, union_type_name) =
1665 self.describe_place_for_conflicting_borrow(place, issued_borrow.borrowed_place);
1666
1667 let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
1668 let second_borrow_desc = if explanation.is_explained() { "second " } else { "" };
1669
1670 let first_borrow_desc;
1672 let mut err = match (gen_borrow_kind, issued_borrow.kind) {
1673 (
1674 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1675 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1676 ) => {
1677 first_borrow_desc = "mutable ";
1678 let mut err = self.cannot_reborrow_already_borrowed(
1679 span,
1680 &desc_place,
1681 &msg_place,
1682 "immutable",
1683 issued_span,
1684 "it",
1685 "mutable",
1686 &msg_borrow,
1687 None,
1688 );
1689 self.suggest_slice_method_if_applicable(
1690 &mut err,
1691 place,
1692 issued_borrow.borrowed_place,
1693 span,
1694 issued_span,
1695 );
1696 err
1697 }
1698 (
1699 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1700 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1701 ) => {
1702 first_borrow_desc = "immutable ";
1703 let mut err = self.cannot_reborrow_already_borrowed(
1704 span,
1705 &desc_place,
1706 &msg_place,
1707 "mutable",
1708 issued_span,
1709 "it",
1710 "immutable",
1711 &msg_borrow,
1712 None,
1713 );
1714 self.suggest_slice_method_if_applicable(
1715 &mut err,
1716 place,
1717 issued_borrow.borrowed_place,
1718 span,
1719 issued_span,
1720 );
1721 self.suggest_binding_for_closure_capture_self(&mut err, &issued_spans);
1722 self.suggest_using_closure_argument_instead_of_capture(
1723 &mut err,
1724 issued_borrow.borrowed_place,
1725 &issued_spans,
1726 );
1727 err
1728 }
1729
1730 (
1731 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1732 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1733 ) => {
1734 first_borrow_desc = "first ";
1735 let mut err = self.cannot_mutably_borrow_multiply(
1736 span,
1737 &desc_place,
1738 &msg_place,
1739 issued_span,
1740 &msg_borrow,
1741 None,
1742 );
1743 self.suggest_slice_method_if_applicable(
1744 &mut err,
1745 place,
1746 issued_borrow.borrowed_place,
1747 span,
1748 issued_span,
1749 );
1750 self.suggest_using_closure_argument_instead_of_capture(
1751 &mut err,
1752 issued_borrow.borrowed_place,
1753 &issued_spans,
1754 );
1755 self.explain_iterator_advancement_in_for_loop_if_applicable(
1756 &mut err,
1757 span,
1758 &issued_spans,
1759 );
1760 err
1761 }
1762
1763 (
1764 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1765 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1766 ) => {
1767 first_borrow_desc = "first ";
1768 self.cannot_uniquely_borrow_by_two_closures(span, &desc_place, issued_span, None)
1769 }
1770
1771 (BorrowKind::Mut { .. }, BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
1772 if let Some(immutable_section_description) =
1773 self.classify_immutable_section(issued_borrow.assigned_place)
1774 {
1775 let mut err = self.cannot_mutate_in_immutable_section(
1776 span,
1777 issued_span,
1778 &desc_place,
1779 immutable_section_description,
1780 "mutably borrow",
1781 );
1782 borrow_spans.var_subdiag(
1783 &mut err,
1784 Some(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }),
1785 |kind, var_span| {
1786 use crate::session_diagnostics::CaptureVarCause::*;
1787 match kind {
1788 hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1789 place: desc_place,
1790 var_span,
1791 is_single_var: true,
1792 },
1793 hir::ClosureKind::Closure
1794 | hir::ClosureKind::CoroutineClosure(_) => BorrowUsePlaceClosure {
1795 place: desc_place,
1796 var_span,
1797 is_single_var: true,
1798 },
1799 }
1800 },
1801 );
1802 return err;
1803 } else {
1804 first_borrow_desc = "immutable ";
1805 self.cannot_reborrow_already_borrowed(
1806 span,
1807 &desc_place,
1808 &msg_place,
1809 "mutable",
1810 issued_span,
1811 "it",
1812 "immutable",
1813 &msg_borrow,
1814 None,
1815 )
1816 }
1817 }
1818
1819 (BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }, _) => {
1820 first_borrow_desc = "first ";
1821 self.cannot_uniquely_borrow_by_one_closure(
1822 span,
1823 container_name,
1824 &desc_place,
1825 "",
1826 issued_span,
1827 "it",
1828 "",
1829 None,
1830 )
1831 }
1832
1833 (
1834 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1835 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1836 ) => {
1837 first_borrow_desc = "first ";
1838 self.cannot_reborrow_already_uniquely_borrowed(
1839 span,
1840 container_name,
1841 &desc_place,
1842 "",
1843 "immutable",
1844 issued_span,
1845 "",
1846 None,
1847 second_borrow_desc,
1848 )
1849 }
1850
1851 (BorrowKind::Mut { .. }, BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }) => {
1852 first_borrow_desc = "first ";
1853 self.cannot_reborrow_already_uniquely_borrowed(
1854 span,
1855 container_name,
1856 &desc_place,
1857 "",
1858 "mutable",
1859 issued_span,
1860 "",
1861 None,
1862 second_borrow_desc,
1863 )
1864 }
1865
1866 (
1867 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1868 BorrowKind::Shared | BorrowKind::Fake(_),
1869 )
1870 | (
1871 BorrowKind::Fake(FakeBorrowKind::Shallow),
1872 BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_),
1873 ) => {
1874 unreachable!()
1875 }
1876 };
1877 self.note_due_to_edition_2024_opaque_capture_rules(issued_borrow, &mut err);
1878
1879 if issued_spans == borrow_spans {
1880 borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
1881 use crate::session_diagnostics::CaptureVarCause::*;
1882 match kind {
1883 hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1884 place: desc_place,
1885 var_span,
1886 is_single_var: false,
1887 },
1888 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1889 BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: false }
1890 }
1891 }
1892 });
1893 } else {
1894 issued_spans.var_subdiag(&mut err, Some(issued_borrow.kind), |kind, var_span| {
1895 use crate::session_diagnostics::CaptureVarCause::*;
1896 let borrow_place = &issued_borrow.borrowed_place;
1897 let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
1898 match kind {
1899 hir::ClosureKind::Coroutine(_) => {
1900 FirstBorrowUsePlaceCoroutine { place: borrow_place_desc, var_span }
1901 }
1902 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1903 FirstBorrowUsePlaceClosure { place: borrow_place_desc, var_span }
1904 }
1905 }
1906 });
1907
1908 borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
1909 use crate::session_diagnostics::CaptureVarCause::*;
1910 match kind {
1911 hir::ClosureKind::Coroutine(_) => {
1912 SecondBorrowUsePlaceCoroutine { place: desc_place, var_span }
1913 }
1914 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1915 SecondBorrowUsePlaceClosure { place: desc_place, var_span }
1916 }
1917 }
1918 });
1919 }
1920
1921 if union_type_name != "" {
1922 err.note(format!(
1923 "{msg_place} is a field of the union `{union_type_name}`, so it overlaps the field {msg_borrow}",
1924 ));
1925 }
1926
1927 explanation.add_explanation_to_diagnostic(
1928 &self,
1929 &mut err,
1930 first_borrow_desc,
1931 None,
1932 Some((issued_span, span)),
1933 );
1934
1935 self.suggest_using_local_if_applicable(&mut err, location, issued_borrow, explanation);
1936 self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
1937
1938 err
1939 }
1940
1941 fn suggest_copy_for_type_in_cloned_ref(&self, err: &mut Diag<'infcx>, place: Place<'tcx>) {
1942 let tcx = self.infcx.tcx;
1943 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
1944
1945 struct FindUselessClone<'tcx> {
1946 tcx: TyCtxt<'tcx>,
1947 typeck_results: &'tcx ty::TypeckResults<'tcx>,
1948 clones: Vec<&'tcx hir::Expr<'tcx>>,
1949 }
1950 impl<'tcx> FindUselessClone<'tcx> {
1951 fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
1952 Self { tcx, typeck_results: tcx.typeck(def_id), clones: vec![] }
1953 }
1954 }
1955 impl<'tcx> Visitor<'tcx> for FindUselessClone<'tcx> {
1956 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1957 if let hir::ExprKind::MethodCall(..) = ex.kind
1958 && let Some(method_def_id) =
1959 self.typeck_results.type_dependent_def_id(ex.hir_id)
1960 && self.tcx.is_lang_item(self.tcx.parent(method_def_id), LangItem::Clone)
1961 {
1962 self.clones.push(ex);
1963 }
1964 hir::intravisit::walk_expr(self, ex);
1965 }
1966 }
1967
1968 let mut expr_finder = FindUselessClone::new(tcx, self.mir_def_id());
1969
1970 let body = tcx.hir_body(body_id).value;
1971 expr_finder.visit_expr(body);
1972
1973 struct Holds<'tcx> {
1974 ty: Ty<'tcx>,
1975 }
1976
1977 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for Holds<'tcx> {
1978 type Result = std::ops::ControlFlow<()>;
1979
1980 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1981 if t == self.ty {
1982 return ControlFlow::Break(());
1983 }
1984 t.super_visit_with(self)
1985 }
1986 }
1987
1988 let mut types_to_constrain = FxIndexSet::default();
1989
1990 let local_ty = self.body.local_decls[place.local].ty;
1991 let typeck_results = tcx.typeck(self.mir_def_id());
1992 let clone = tcx.require_lang_item(LangItem::Clone, body.span);
1993 for expr in expr_finder.clones {
1994 if let hir::ExprKind::MethodCall(_, rcvr, _, span) = expr.kind
1995 && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
1996 && let Some(ty) = typeck_results.node_type_opt(expr.hir_id)
1997 && rcvr_ty == ty
1998 && let ty::Ref(_, inner, _) = rcvr_ty.kind()
1999 && let inner = inner.peel_refs()
2000 && (Holds { ty: inner }).visit_ty(local_ty).is_break()
2001 && let None =
2002 self.infcx.type_implements_trait_shallow(clone, inner, self.infcx.param_env)
2003 {
2004 err.span_label(
2005 span,
2006 format!(
2007 "this call doesn't do anything, the result is still `{rcvr_ty}` \
2008 because `{inner}` doesn't implement `Clone`",
2009 ),
2010 );
2011 types_to_constrain.insert(inner);
2012 }
2013 }
2014 for ty in types_to_constrain {
2015 self.suggest_adding_bounds_or_derive(err, ty, clone, body.span);
2016 }
2017 }
2018
2019 pub(crate) fn suggest_adding_bounds_or_derive(
2020 &self,
2021 err: &mut Diag<'_>,
2022 ty: Ty<'tcx>,
2023 trait_def_id: DefId,
2024 span: Span,
2025 ) {
2026 self.suggest_adding_bounds(err, ty, trait_def_id, span);
2027 if let ty::Adt(..) = ty.kind() {
2028 let trait_ref =
2030 ty::Binder::dummy(ty::TraitRef::new(self.infcx.tcx, trait_def_id, [ty]));
2031 let obligation = Obligation::new(
2032 self.infcx.tcx,
2033 ObligationCause::dummy(),
2034 self.infcx.param_env,
2035 trait_ref,
2036 );
2037 self.infcx.err_ctxt().suggest_derive(
2038 &obligation,
2039 err,
2040 trait_ref.upcast(self.infcx.tcx),
2041 );
2042 }
2043 }
2044
2045 #[instrument(level = "debug", skip(self, err))]
2046 fn suggest_using_local_if_applicable(
2047 &self,
2048 err: &mut Diag<'_>,
2049 location: Location,
2050 issued_borrow: &BorrowData<'tcx>,
2051 explanation: BorrowExplanation<'tcx>,
2052 ) {
2053 let used_in_call = matches!(
2054 explanation,
2055 BorrowExplanation::UsedLater(
2056 _,
2057 LaterUseKind::Call | LaterUseKind::Other,
2058 _call_span,
2059 _
2060 )
2061 );
2062 if !used_in_call {
2063 debug!("not later used in call");
2064 return;
2065 }
2066 if matches!(
2067 self.body.local_decls[issued_borrow.borrowed_place.local].local_info(),
2068 LocalInfo::IfThenRescopeTemp { .. }
2069 ) {
2070 return;
2072 }
2073
2074 let use_span = if let BorrowExplanation::UsedLater(_, LaterUseKind::Other, use_span, _) =
2075 explanation
2076 {
2077 Some(use_span)
2078 } else {
2079 None
2080 };
2081
2082 let outer_call_loc =
2083 if let TwoPhaseActivation::ActivatedAt(loc) = issued_borrow.activation_location {
2084 loc
2085 } else {
2086 issued_borrow.reserve_location
2087 };
2088 let outer_call_stmt = self.body.stmt_at(outer_call_loc);
2089
2090 let inner_param_location = location;
2091 let Some(inner_param_stmt) = self.body.stmt_at(inner_param_location).left() else {
2092 debug!("`inner_param_location` {:?} is not for a statement", inner_param_location);
2093 return;
2094 };
2095 let Some(&inner_param) = inner_param_stmt.kind.as_assign().map(|(p, _)| p) else {
2096 debug!(
2097 "`inner_param_location` {:?} is not for an assignment: {:?}",
2098 inner_param_location, inner_param_stmt
2099 );
2100 return;
2101 };
2102 let inner_param_uses = find_all_local_uses::find(self.body, inner_param.local);
2103 let Some((inner_call_loc, inner_call_term)) =
2104 inner_param_uses.into_iter().find_map(|loc| {
2105 let Either::Right(term) = self.body.stmt_at(loc) else {
2106 debug!("{:?} is a statement, so it can't be a call", loc);
2107 return None;
2108 };
2109 let TerminatorKind::Call { args, .. } = &term.kind else {
2110 debug!("not a call: {:?}", term);
2111 return None;
2112 };
2113 debug!("checking call args for uses of inner_param: {:?}", args);
2114 args.iter()
2115 .map(|a| &a.node)
2116 .any(|a| a == &Operand::Move(inner_param))
2117 .then_some((loc, term))
2118 })
2119 else {
2120 debug!("no uses of inner_param found as a by-move call arg");
2121 return;
2122 };
2123 debug!("===> outer_call_loc = {:?}, inner_call_loc = {:?}", outer_call_loc, inner_call_loc);
2124
2125 let inner_call_span = inner_call_term.source_info.span;
2126 let outer_call_span = match use_span {
2127 Some(span) => span,
2128 None => outer_call_stmt.either(|s| s.source_info, |t| t.source_info).span,
2129 };
2130 if outer_call_span == inner_call_span || !outer_call_span.contains(inner_call_span) {
2131 debug!(
2134 "outer span {:?} does not strictly contain inner span {:?}",
2135 outer_call_span, inner_call_span
2136 );
2137 return;
2138 }
2139 err.span_help(
2140 inner_call_span,
2141 format!(
2142 "try adding a local storing this{}...",
2143 if use_span.is_some() { "" } else { " argument" }
2144 ),
2145 );
2146 err.span_help(
2147 outer_call_span,
2148 format!(
2149 "...and then using that local {}",
2150 if use_span.is_some() { "here" } else { "as the argument to this call" }
2151 ),
2152 );
2153 }
2154
2155 pub(crate) fn find_expr(&self, span: Span) -> Option<&'tcx hir::Expr<'tcx>> {
2156 let tcx = self.infcx.tcx;
2157 let body_id = tcx.hir_node(self.mir_hir_id()).body_id()?;
2158 let mut expr_finder = FindExprBySpan::new(span, tcx);
2159 expr_finder.visit_expr(tcx.hir_body(body_id).value);
2160 expr_finder.result
2161 }
2162
2163 fn suggest_slice_method_if_applicable(
2164 &self,
2165 err: &mut Diag<'_>,
2166 place: Place<'tcx>,
2167 borrowed_place: Place<'tcx>,
2168 span: Span,
2169 issued_span: Span,
2170 ) {
2171 let tcx = self.infcx.tcx;
2172
2173 let has_split_at_mut = |ty: Ty<'tcx>| {
2174 let ty = ty.peel_refs();
2175 match ty.kind() {
2176 ty::Array(..) | ty::Slice(..) => true,
2177 ty::Adt(def, _) if tcx.get_diagnostic_item(sym::Vec) == Some(def.did()) => true,
2178 _ if ty == tcx.types.str_ => true,
2179 _ => false,
2180 }
2181 };
2182 if let ([ProjectionElem::Index(index1)], [ProjectionElem::Index(index2)])
2183 | (
2184 [ProjectionElem::Deref, ProjectionElem::Index(index1)],
2185 [ProjectionElem::Deref, ProjectionElem::Index(index2)],
2186 ) = (&place.projection[..], &borrowed_place.projection[..])
2187 {
2188 let decl1 = &self.body.local_decls[*index1];
2189 let decl2 = &self.body.local_decls[*index2];
2190
2191 let mut note_default_suggestion = || {
2192 err.help(
2193 "consider using `.split_at_mut(position)` or similar method to obtain two \
2194 mutable non-overlapping sub-slices",
2195 )
2196 .help(
2197 "consider using `.swap(index_1, index_2)` to swap elements at the specified \
2198 indices",
2199 );
2200 };
2201
2202 let Some(index1) = self.find_expr(decl1.source_info.span) else {
2203 note_default_suggestion();
2204 return;
2205 };
2206
2207 let Some(index2) = self.find_expr(decl2.source_info.span) else {
2208 note_default_suggestion();
2209 return;
2210 };
2211
2212 let sm = tcx.sess.source_map();
2213
2214 let Ok(index1_str) = sm.span_to_snippet(index1.span) else {
2215 note_default_suggestion();
2216 return;
2217 };
2218
2219 let Ok(index2_str) = sm.span_to_snippet(index2.span) else {
2220 note_default_suggestion();
2221 return;
2222 };
2223
2224 let Some(object) = tcx.hir_parent_id_iter(index1.hir_id).find_map(|id| {
2225 if let hir::Node::Expr(expr) = tcx.hir_node(id)
2226 && let hir::ExprKind::Index(obj, ..) = expr.kind
2227 {
2228 Some(obj)
2229 } else {
2230 None
2231 }
2232 }) else {
2233 note_default_suggestion();
2234 return;
2235 };
2236
2237 let Ok(obj_str) = sm.span_to_snippet(object.span) else {
2238 note_default_suggestion();
2239 return;
2240 };
2241
2242 let Some(swap_call) = tcx.hir_parent_id_iter(object.hir_id).find_map(|id| {
2243 if let hir::Node::Expr(call) = tcx.hir_node(id)
2244 && let hir::ExprKind::Call(callee, ..) = call.kind
2245 && let hir::ExprKind::Path(qpath) = callee.kind
2246 && let hir::QPath::Resolved(None, res) = qpath
2247 && let hir::def::Res::Def(_, did) = res.res
2248 && tcx.is_diagnostic_item(sym::mem_swap, did)
2249 {
2250 Some(call)
2251 } else {
2252 None
2253 }
2254 }) else {
2255 let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2256 let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2257 let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2258 let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2259 if !idx1.equivalent_for_indexing(idx2) {
2260 err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2261 }
2262 return;
2263 };
2264
2265 err.span_suggestion(
2266 swap_call.span,
2267 "use `.swap()` to swap elements at the specified indices instead",
2268 format!("{obj_str}.swap({index1_str}, {index2_str})"),
2269 Applicability::MachineApplicable,
2270 );
2271 return;
2272 }
2273 let place_ty = PlaceRef::ty(&place.as_ref(), self.body, tcx).ty;
2274 let borrowed_place_ty = PlaceRef::ty(&borrowed_place.as_ref(), self.body, tcx).ty;
2275 if !has_split_at_mut(place_ty) && !has_split_at_mut(borrowed_place_ty) {
2276 return;
2278 }
2279 let Some(index1) = self.find_expr(span) else { return };
2280 let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2281 let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2282 let Some(index2) = self.find_expr(issued_span) else { return };
2283 let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2284 let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2285 if idx1.equivalent_for_indexing(idx2) {
2286 return;
2288 }
2289 err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2290 }
2291
2292 pub(crate) fn explain_iterator_advancement_in_for_loop_if_applicable(
2303 &self,
2304 err: &mut Diag<'_>,
2305 span: Span,
2306 issued_spans: &UseSpans<'tcx>,
2307 ) {
2308 let issue_span = issued_spans.args_or_use();
2309 let tcx = self.infcx.tcx;
2310
2311 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2312 let typeck_results = tcx.typeck(self.mir_def_id());
2313
2314 struct ExprFinder<'hir> {
2315 issue_span: Span,
2316 expr_span: Span,
2317 body_expr: Option<&'hir hir::Expr<'hir>>,
2318 loop_bind: Option<&'hir Ident>,
2319 loop_span: Option<Span>,
2320 head_span: Option<Span>,
2321 pat_span: Option<Span>,
2322 head: Option<&'hir hir::Expr<'hir>>,
2323 }
2324 impl<'hir> Visitor<'hir> for ExprFinder<'hir> {
2325 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2326 if let hir::ExprKind::Call(path, [arg]) = ex.kind
2339 && let hir::ExprKind::Path(hir::QPath::LangItem(LangItem::IntoIterIntoIter, _)) =
2340 path.kind
2341 && arg.span.contains(self.issue_span)
2342 {
2343 self.head = Some(arg);
2345 }
2346 if let hir::ExprKind::Loop(
2347 hir::Block { stmts: [stmt, ..], .. },
2348 _,
2349 hir::LoopSource::ForLoop,
2350 _,
2351 ) = ex.kind
2352 && let hir::StmtKind::Expr(hir::Expr {
2353 kind: hir::ExprKind::Match(call, [_, bind, ..], _),
2354 span: head_span,
2355 ..
2356 }) = stmt.kind
2357 && let hir::ExprKind::Call(path, _args) = call.kind
2358 && let hir::ExprKind::Path(hir::QPath::LangItem(LangItem::IteratorNext, _)) =
2359 path.kind
2360 && let hir::PatKind::Struct(path, [field, ..], _) = bind.pat.kind
2361 && let hir::QPath::LangItem(LangItem::OptionSome, pat_span) = path
2362 && call.span.contains(self.issue_span)
2363 {
2364 if let PatField {
2366 pat: hir::Pat { kind: hir::PatKind::Binding(_, _, ident, ..), .. },
2367 ..
2368 } = field
2369 {
2370 self.loop_bind = Some(ident);
2371 }
2372 self.head_span = Some(*head_span);
2373 self.pat_span = Some(pat_span);
2374 self.loop_span = Some(stmt.span);
2375 }
2376
2377 if let hir::ExprKind::MethodCall(body_call, recv, ..) = ex.kind
2378 && body_call.ident.name == sym::next
2379 && recv.span.source_equal(self.expr_span)
2380 {
2381 self.body_expr = Some(ex);
2382 }
2383
2384 hir::intravisit::walk_expr(self, ex);
2385 }
2386 }
2387 let mut finder = ExprFinder {
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
3089 err
3090 }
3091
3092 fn report_borrow_conflicts_with_destructor(
3093 &mut self,
3094 location: Location,
3095 borrow: &BorrowData<'tcx>,
3096 (place, drop_span): (Place<'tcx>, Span),
3097 kind: Option<WriteKind>,
3098 dropped_ty: Ty<'tcx>,
3099 ) {
3100 debug!(
3101 "report_borrow_conflicts_with_destructor(\
3102 {:?}, {:?}, ({:?}, {:?}), {:?}\
3103 )",
3104 location, borrow, place, drop_span, kind,
3105 );
3106
3107 let borrow_spans = self.retrieve_borrow_spans(borrow);
3108 let borrow_span = borrow_spans.var_or_use();
3109
3110 let mut err = self.cannot_borrow_across_destructor(borrow_span);
3111
3112 let what_was_dropped = match self.describe_place(place.as_ref()) {
3113 Some(name) => format!("`{name}`"),
3114 None => String::from("temporary value"),
3115 };
3116
3117 let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
3118 Some(borrowed) => format!(
3119 "here, drop of {what_was_dropped} needs exclusive access to `{borrowed}`, \
3120 because the type `{dropped_ty}` implements the `Drop` trait"
3121 ),
3122 None => format!(
3123 "here is drop of {what_was_dropped}; whose type `{dropped_ty}` implements the `Drop` trait"
3124 ),
3125 };
3126 err.span_label(drop_span, label);
3127
3128 let explanation =
3130 self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
3131 match explanation {
3132 BorrowExplanation::UsedLater { .. }
3133 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3134 err.note("consider using a `let` binding to create a longer lived value");
3135 }
3136 _ => {}
3137 }
3138
3139 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3140
3141 self.buffer_error(err);
3142 }
3143
3144 fn report_thread_local_value_does_not_live_long_enough(
3145 &self,
3146 drop_span: Span,
3147 borrow_span: Span,
3148 ) -> Diag<'infcx> {
3149 debug!(
3150 "report_thread_local_value_does_not_live_long_enough(\
3151 {:?}, {:?}\
3152 )",
3153 drop_span, borrow_span
3154 );
3155
3156 let sm = self.infcx.tcx.sess.source_map();
3161 let end_of_function = if drop_span.is_empty()
3162 && let Ok(adjusted_span) = sm.span_extend_prev_while(drop_span, |c| c == '}')
3163 {
3164 adjusted_span
3165 } else {
3166 drop_span
3167 };
3168 self.thread_local_value_does_not_live_long_enough(borrow_span)
3169 .with_span_label(
3170 borrow_span,
3171 "thread-local variables cannot be borrowed beyond the end of the function",
3172 )
3173 .with_span_label(end_of_function, "end of enclosing function is here")
3174 }
3175
3176 #[instrument(level = "debug", skip(self))]
3177 fn report_temporary_value_does_not_live_long_enough(
3178 &self,
3179 location: Location,
3180 borrow: &BorrowData<'tcx>,
3181 drop_span: Span,
3182 borrow_spans: UseSpans<'tcx>,
3183 proper_span: Span,
3184 explanation: BorrowExplanation<'tcx>,
3185 ) -> Diag<'infcx> {
3186 if let BorrowExplanation::MustBeValidFor { category, span, from_closure: false, .. } =
3187 explanation
3188 {
3189 if let Err(diag) = self.try_report_cannot_return_reference_to_local(
3190 borrow,
3191 proper_span,
3192 span,
3193 category,
3194 None,
3195 ) {
3196 return diag;
3197 }
3198 }
3199
3200 let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
3201 err.span_label(proper_span, "creates a temporary value which is freed while still in use");
3202 err.span_label(drop_span, "temporary value is freed at the end of this statement");
3203
3204 match explanation {
3205 BorrowExplanation::UsedLater(..)
3206 | BorrowExplanation::UsedLaterInLoop(..)
3207 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3208 let sm = self.infcx.tcx.sess.source_map();
3210 let mut suggested = false;
3211 let msg = "consider using a `let` binding to create a longer lived value";
3212
3213 struct NestedStatementVisitor<'tcx> {
3222 span: Span,
3223 current: usize,
3224 found: usize,
3225 prop_expr: Option<&'tcx hir::Expr<'tcx>>,
3226 call: Option<&'tcx hir::Expr<'tcx>>,
3227 }
3228
3229 impl<'tcx> Visitor<'tcx> for NestedStatementVisitor<'tcx> {
3230 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
3231 self.current += 1;
3232 walk_block(self, block);
3233 self.current -= 1;
3234 }
3235 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
3236 if let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind {
3237 if self.span == rcvr.span.source_callsite() {
3238 self.call = Some(expr);
3239 }
3240 }
3241 if self.span == expr.span.source_callsite() {
3242 self.found = self.current;
3243 if self.prop_expr.is_none() {
3244 self.prop_expr = Some(expr);
3245 }
3246 }
3247 walk_expr(self, expr);
3248 }
3249 }
3250 let source_info = self.body.source_info(location);
3251 let proper_span = proper_span.source_callsite();
3252 if let Some(scope) = self.body.source_scopes.get(source_info.scope)
3253 && let ClearCrossCrate::Set(scope_data) = &scope.local_data
3254 && let Some(id) = self.infcx.tcx.hir_node(scope_data.lint_root).body_id()
3255 && let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir_body(id).value.kind
3256 {
3257 for stmt in block.stmts {
3258 let mut visitor = NestedStatementVisitor {
3259 span: proper_span,
3260 current: 0,
3261 found: 0,
3262 prop_expr: None,
3263 call: None,
3264 };
3265 visitor.visit_stmt(stmt);
3266
3267 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
3268 let expr_ty: Option<Ty<'_>> =
3269 visitor.prop_expr.map(|expr| typeck_results.expr_ty(expr).peel_refs());
3270
3271 if visitor.found == 0
3272 && stmt.span.contains(proper_span)
3273 && let Some(p) = sm.span_to_margin(stmt.span)
3274 && let Ok(s) = sm.span_to_snippet(proper_span)
3275 {
3276 if let Some(call) = visitor.call
3277 && let hir::ExprKind::MethodCall(path, _, [], _) = call.kind
3278 && path.ident.name == sym::iter
3279 && let Some(ty) = expr_ty
3280 {
3281 err.span_suggestion_verbose(
3282 path.ident.span,
3283 format!(
3284 "consider consuming the `{ty}` when turning it into an \
3285 `Iterator`",
3286 ),
3287 "into_iter",
3288 Applicability::MaybeIncorrect,
3289 );
3290 }
3291
3292 let mutability = if matches!(borrow.kind(), BorrowKind::Mut { .. }) {
3293 "mut "
3294 } else {
3295 ""
3296 };
3297
3298 let addition =
3299 format!("let {}binding = {};\n{}", mutability, s, " ".repeat(p));
3300 err.multipart_suggestion_verbose(
3301 msg,
3302 vec![
3303 (stmt.span.shrink_to_lo(), addition),
3304 (proper_span, "binding".to_string()),
3305 ],
3306 Applicability::MaybeIncorrect,
3307 );
3308
3309 suggested = true;
3310 break;
3311 }
3312 }
3313 }
3314 if !suggested {
3315 err.note(msg);
3316 }
3317 }
3318 _ => {}
3319 }
3320 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3321
3322 borrow_spans.args_subdiag(&mut err, |args_span| {
3323 crate::session_diagnostics::CaptureArgLabel::Capture {
3324 is_within: borrow_spans.for_coroutine(),
3325 args_span,
3326 }
3327 });
3328
3329 err
3330 }
3331
3332 fn try_report_cannot_return_reference_to_local(
3333 &self,
3334 borrow: &BorrowData<'tcx>,
3335 borrow_span: Span,
3336 return_span: Span,
3337 category: ConstraintCategory<'tcx>,
3338 opt_place_desc: Option<&String>,
3339 ) -> Result<(), Diag<'infcx>> {
3340 let return_kind = match category {
3341 ConstraintCategory::Return(_) => "return",
3342 ConstraintCategory::Yield => "yield",
3343 _ => return Ok(()),
3344 };
3345
3346 let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
3348 "reference to"
3349 } else {
3350 "value referencing"
3351 };
3352
3353 let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
3354 let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
3355 match self.body.local_kind(local) {
3356 LocalKind::Temp if self.body.local_decls[local].is_user_variable() => {
3357 "local variable "
3358 }
3359 LocalKind::Arg
3360 if !self.upvars.is_empty() && local == ty::CAPTURE_STRUCT_LOCAL =>
3361 {
3362 "variable captured by `move` "
3363 }
3364 LocalKind::Arg => "function parameter ",
3365 LocalKind::ReturnPointer | LocalKind::Temp => {
3366 bug!("temporary or return pointer with a name")
3367 }
3368 }
3369 } else {
3370 "local data "
3371 };
3372 (format!("{local_kind}`{place_desc}`"), format!("`{place_desc}` is borrowed here"))
3373 } else {
3374 let local = borrow.borrowed_place.local;
3375 match self.body.local_kind(local) {
3376 LocalKind::Arg => (
3377 "function parameter".to_string(),
3378 "function parameter borrowed here".to_string(),
3379 ),
3380 LocalKind::Temp
3381 if self.body.local_decls[local].is_user_variable()
3382 && !self.body.local_decls[local]
3383 .source_info
3384 .span
3385 .in_external_macro(self.infcx.tcx.sess.source_map()) =>
3386 {
3387 ("local binding".to_string(), "local binding introduced here".to_string())
3388 }
3389 LocalKind::ReturnPointer | LocalKind::Temp => {
3390 ("temporary value".to_string(), "temporary value created here".to_string())
3391 }
3392 }
3393 };
3394
3395 let mut err = self.cannot_return_reference_to_local(
3396 return_span,
3397 return_kind,
3398 reference_desc,
3399 &place_desc,
3400 );
3401
3402 if return_span != borrow_span {
3403 err.span_label(borrow_span, note);
3404
3405 let tcx = self.infcx.tcx;
3406
3407 let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
3408
3409 if let Some(iter_trait) = tcx.get_diagnostic_item(sym::Iterator)
3411 && self
3412 .infcx
3413 .type_implements_trait(iter_trait, [return_ty], self.infcx.param_env)
3414 .must_apply_modulo_regions()
3415 {
3416 err.span_suggestion_hidden(
3417 return_span.shrink_to_hi(),
3418 "use `.collect()` to allocate the iterator",
3419 ".collect::<Vec<_>>()",
3420 Applicability::MaybeIncorrect,
3421 );
3422 }
3423 }
3424
3425 Err(err)
3426 }
3427
3428 #[instrument(level = "debug", skip(self))]
3429 fn report_escaping_closure_capture(
3430 &self,
3431 use_span: UseSpans<'tcx>,
3432 var_span: Span,
3433 fr_name: &RegionName,
3434 category: ConstraintCategory<'tcx>,
3435 constraint_span: Span,
3436 captured_var: &str,
3437 scope: &str,
3438 ) -> Diag<'infcx> {
3439 let tcx = self.infcx.tcx;
3440 let args_span = use_span.args_or_use();
3441
3442 let (sugg_span, suggestion) = match tcx.sess.source_map().span_to_snippet(args_span) {
3443 Ok(string) => {
3444 let coro_prefix = if let Some(sub) = string.strip_prefix("async") {
3445 let trimmed_sub = sub.trim_end();
3446 if trimmed_sub.ends_with("gen") {
3447 Some((trimmed_sub.len() + 5) as _)
3449 } else {
3450 Some(5)
3452 }
3453 } else if string.starts_with("gen") {
3454 Some(3)
3456 } else if string.starts_with("static") {
3457 Some(6)
3460 } else {
3461 None
3462 };
3463 if let Some(n) = coro_prefix {
3464 let pos = args_span.lo() + BytePos(n);
3465 (args_span.with_lo(pos).with_hi(pos), " move")
3466 } else {
3467 (args_span.shrink_to_lo(), "move ")
3468 }
3469 }
3470 Err(_) => (args_span, "move |<args>| <body>"),
3471 };
3472 let kind = match use_span.coroutine_kind() {
3473 Some(coroutine_kind) => match coroutine_kind {
3474 CoroutineKind::Desugared(CoroutineDesugaring::Gen, kind) => match kind {
3475 CoroutineSource::Block => "gen block",
3476 CoroutineSource::Closure => "gen closure",
3477 CoroutineSource::Fn => {
3478 bug!("gen block/closure expected, but gen function found.")
3479 }
3480 },
3481 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, kind) => match kind {
3482 CoroutineSource::Block => "async gen block",
3483 CoroutineSource::Closure => "async gen closure",
3484 CoroutineSource::Fn => {
3485 bug!("gen block/closure expected, but gen function found.")
3486 }
3487 },
3488 CoroutineKind::Desugared(CoroutineDesugaring::Async, async_kind) => {
3489 match async_kind {
3490 CoroutineSource::Block => "async block",
3491 CoroutineSource::Closure => "async closure",
3492 CoroutineSource::Fn => {
3493 bug!("async block/closure expected, but async function found.")
3494 }
3495 }
3496 }
3497 CoroutineKind::Coroutine(_) => "coroutine",
3498 },
3499 None => "closure",
3500 };
3501
3502 let mut err = self.cannot_capture_in_long_lived_closure(
3503 args_span,
3504 kind,
3505 captured_var,
3506 var_span,
3507 scope,
3508 );
3509 err.span_suggestion_verbose(
3510 sugg_span,
3511 format!(
3512 "to force the {kind} to take ownership of {captured_var} (and any \
3513 other referenced variables), use the `move` keyword"
3514 ),
3515 suggestion,
3516 Applicability::MachineApplicable,
3517 );
3518
3519 match category {
3520 ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
3521 let msg = format!("{kind} is returned here");
3522 err.span_note(constraint_span, msg);
3523 }
3524 ConstraintCategory::CallArgument(_) => {
3525 fr_name.highlight_region_name(&mut err);
3526 if matches!(
3527 use_span.coroutine_kind(),
3528 Some(CoroutineKind::Desugared(CoroutineDesugaring::Async, _))
3529 ) {
3530 err.note(
3531 "async blocks are not executed immediately and must either take a \
3532 reference or ownership of outside variables they use",
3533 );
3534 } else {
3535 let msg = format!("{scope} requires argument type to outlive `{fr_name}`");
3536 err.span_note(constraint_span, msg);
3537 }
3538 }
3539 _ => bug!(
3540 "report_escaping_closure_capture called with unexpected constraint \
3541 category: `{:?}`",
3542 category
3543 ),
3544 }
3545
3546 err
3547 }
3548
3549 fn report_escaping_data(
3550 &self,
3551 borrow_span: Span,
3552 name: &Option<String>,
3553 upvar_span: Span,
3554 upvar_name: Symbol,
3555 escape_span: Span,
3556 ) -> Diag<'infcx> {
3557 let tcx = self.infcx.tcx;
3558
3559 let escapes_from = tcx.def_descr(self.mir_def_id().to_def_id());
3560
3561 let mut err =
3562 borrowck_errors::borrowed_data_escapes_closure(tcx, escape_span, escapes_from);
3563
3564 err.span_label(
3565 upvar_span,
3566 format!("`{upvar_name}` declared here, outside of the {escapes_from} body"),
3567 );
3568
3569 err.span_label(borrow_span, format!("borrow is only valid in the {escapes_from} body"));
3570
3571 if let Some(name) = name {
3572 err.span_label(
3573 escape_span,
3574 format!("reference to `{name}` escapes the {escapes_from} body here"),
3575 );
3576 } else {
3577 err.span_label(escape_span, format!("reference escapes the {escapes_from} body here"));
3578 }
3579
3580 err
3581 }
3582
3583 fn get_moved_indexes(
3584 &self,
3585 location: Location,
3586 mpi: MovePathIndex,
3587 ) -> (Vec<MoveSite>, Vec<Location>) {
3588 fn predecessor_locations<'tcx>(
3589 body: &mir::Body<'tcx>,
3590 location: Location,
3591 ) -> impl Iterator<Item = Location> {
3592 if location.statement_index == 0 {
3593 let predecessors = body.basic_blocks.predecessors()[location.block].to_vec();
3594 Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb)))
3595 } else {
3596 Either::Right(std::iter::once(Location {
3597 statement_index: location.statement_index - 1,
3598 ..location
3599 }))
3600 }
3601 }
3602
3603 let mut mpis = vec![mpi];
3604 let move_paths = &self.move_data.move_paths;
3605 mpis.extend(move_paths[mpi].parents(move_paths).map(|(mpi, _)| mpi));
3606
3607 let mut stack = Vec::new();
3608 let mut back_edge_stack = Vec::new();
3609
3610 predecessor_locations(self.body, location).for_each(|predecessor| {
3611 if location.dominates(predecessor, self.dominators()) {
3612 back_edge_stack.push(predecessor)
3613 } else {
3614 stack.push(predecessor);
3615 }
3616 });
3617
3618 let mut reached_start = false;
3619
3620 let mut is_argument = false;
3622 for arg in self.body.args_iter() {
3623 if let Some(path) = self.move_data.rev_lookup.find_local(arg) {
3624 if mpis.contains(&path) {
3625 is_argument = true;
3626 }
3627 }
3628 }
3629
3630 let mut visited = FxIndexSet::default();
3631 let mut move_locations = FxIndexSet::default();
3632 let mut reinits = vec![];
3633 let mut result = vec![];
3634
3635 let mut dfs_iter = |result: &mut Vec<MoveSite>, location: Location, is_back_edge: bool| {
3636 debug!(
3637 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
3638 location, is_back_edge
3639 );
3640
3641 if !visited.insert(location) {
3642 return true;
3643 }
3644
3645 let stmt_kind =
3647 self.body[location.block].statements.get(location.statement_index).map(|s| &s.kind);
3648 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
3649 } else {
3653 for moi in &self.move_data.loc_map[location] {
3661 debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
3662 let path = self.move_data.moves[*moi].path;
3663 if mpis.contains(&path) {
3664 debug!(
3665 "report_use_of_moved_or_uninitialized: found {:?}",
3666 move_paths[path].place
3667 );
3668 result.push(MoveSite { moi: *moi, traversed_back_edge: is_back_edge });
3669 move_locations.insert(location);
3670
3671 return true;
3688 }
3689 }
3690 }
3691
3692 let mut any_match = false;
3694 for ii in &self.move_data.init_loc_map[location] {
3695 let init = self.move_data.inits[*ii];
3696 match init.kind {
3697 InitKind::Deep | InitKind::NonPanicPathOnly => {
3698 if mpis.contains(&init.path) {
3699 any_match = true;
3700 }
3701 }
3702 InitKind::Shallow => {
3703 if mpi == init.path {
3704 any_match = true;
3705 }
3706 }
3707 }
3708 }
3709 if any_match {
3710 reinits.push(location);
3711 return true;
3712 }
3713 false
3714 };
3715
3716 while let Some(location) = stack.pop() {
3717 if dfs_iter(&mut result, location, false) {
3718 continue;
3719 }
3720
3721 let mut has_predecessor = false;
3722 predecessor_locations(self.body, location).for_each(|predecessor| {
3723 if location.dominates(predecessor, self.dominators()) {
3724 back_edge_stack.push(predecessor)
3725 } else {
3726 stack.push(predecessor);
3727 }
3728 has_predecessor = true;
3729 });
3730
3731 if !has_predecessor {
3732 reached_start = true;
3733 }
3734 }
3735 if (is_argument || !reached_start) && result.is_empty() {
3736 while let Some(location) = back_edge_stack.pop() {
3743 if dfs_iter(&mut result, location, true) {
3744 continue;
3745 }
3746
3747 predecessor_locations(self.body, location)
3748 .for_each(|predecessor| back_edge_stack.push(predecessor));
3749 }
3750 }
3751
3752 let reinits_reachable = reinits
3754 .into_iter()
3755 .filter(|reinit| {
3756 let mut visited = FxIndexSet::default();
3757 let mut stack = vec![*reinit];
3758 while let Some(location) = stack.pop() {
3759 if !visited.insert(location) {
3760 continue;
3761 }
3762 if move_locations.contains(&location) {
3763 return true;
3764 }
3765 stack.extend(predecessor_locations(self.body, location));
3766 }
3767 false
3768 })
3769 .collect::<Vec<Location>>();
3770 (result, reinits_reachable)
3771 }
3772
3773 pub(crate) fn report_illegal_mutation_of_borrowed(
3774 &mut self,
3775 location: Location,
3776 (place, span): (Place<'tcx>, Span),
3777 loan: &BorrowData<'tcx>,
3778 ) {
3779 let loan_spans = self.retrieve_borrow_spans(loan);
3780 let loan_span = loan_spans.args_or_use();
3781
3782 let descr_place = self.describe_any_place(place.as_ref());
3783 if let BorrowKind::Fake(_) = loan.kind
3784 && let Some(section) = self.classify_immutable_section(loan.assigned_place)
3785 {
3786 let mut err = self.cannot_mutate_in_immutable_section(
3787 span,
3788 loan_span,
3789 &descr_place,
3790 section,
3791 "assign",
3792 );
3793
3794 loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3795 use crate::session_diagnostics::CaptureVarCause::*;
3796 match kind {
3797 hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3798 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3799 BorrowUseInClosure { var_span }
3800 }
3801 }
3802 });
3803
3804 self.buffer_error(err);
3805
3806 return;
3807 }
3808
3809 let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place);
3810 self.note_due_to_edition_2024_opaque_capture_rules(loan, &mut err);
3811
3812 loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3813 use crate::session_diagnostics::CaptureVarCause::*;
3814 match kind {
3815 hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3816 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3817 BorrowUseInClosure { var_span }
3818 }
3819 }
3820 });
3821
3822 self.explain_why_borrow_contains_point(location, loan, None)
3823 .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3824
3825 self.explain_deref_coercion(loan, &mut err);
3826
3827 self.buffer_error(err);
3828 }
3829
3830 fn explain_deref_coercion(&mut self, loan: &BorrowData<'tcx>, err: &mut Diag<'_>) {
3831 let tcx = self.infcx.tcx;
3832 if let Some(Terminator { kind: TerminatorKind::Call { call_source, fn_span, .. }, .. }) =
3833 &self.body[loan.reserve_location.block].terminator
3834 && let Some((method_did, method_args)) = mir::find_self_call(
3835 tcx,
3836 self.body,
3837 loan.assigned_place.local,
3838 loan.reserve_location.block,
3839 )
3840 && let CallKind::DerefCoercion { deref_target_span, deref_target_ty, .. } = call_kind(
3841 self.infcx.tcx,
3842 self.infcx.typing_env(self.infcx.param_env),
3843 method_did,
3844 method_args,
3845 *fn_span,
3846 call_source.from_hir_call(),
3847 self.infcx.tcx.fn_arg_idents(method_did)[0],
3848 )
3849 {
3850 err.note(format!("borrow occurs due to deref coercion to `{deref_target_ty}`"));
3851 if let Some(deref_target_span) = deref_target_span {
3852 err.span_note(deref_target_span, "deref defined here");
3853 }
3854 }
3855 }
3856
3857 pub(crate) fn report_illegal_reassignment(
3864 &mut self,
3865 (place, span): (Place<'tcx>, Span),
3866 assigned_span: Span,
3867 err_place: Place<'tcx>,
3868 ) {
3869 let (from_arg, local_decl) = match err_place.as_local() {
3870 Some(local) => {
3871 (self.body.local_kind(local) == LocalKind::Arg, Some(&self.body.local_decls[local]))
3872 }
3873 None => (false, None),
3874 };
3875
3876 let (place_description, assigned_span) = match local_decl {
3880 Some(LocalDecl {
3881 local_info:
3882 ClearCrossCrate::Set(
3883 box LocalInfo::User(BindingForm::Var(VarBindingForm {
3884 opt_match_place: None,
3885 ..
3886 }))
3887 | box LocalInfo::StaticRef { .. }
3888 | box LocalInfo::Boring,
3889 ),
3890 ..
3891 })
3892 | None => (self.describe_any_place(place.as_ref()), assigned_span),
3893 Some(decl) => (self.describe_any_place(err_place.as_ref()), decl.source_info.span),
3894 };
3895 let mut err = self.cannot_reassign_immutable(span, &place_description, from_arg);
3896 let msg = if from_arg {
3897 "cannot assign to immutable argument"
3898 } else {
3899 "cannot assign twice to immutable variable"
3900 };
3901 if span != assigned_span && !from_arg {
3902 err.span_label(assigned_span, format!("first assignment to {place_description}"));
3903 }
3904 if let Some(decl) = local_decl
3905 && decl.can_be_made_mutable()
3906 {
3907 err.span_suggestion_verbose(
3908 decl.source_info.span.shrink_to_lo(),
3909 "consider making this binding mutable",
3910 "mut ".to_string(),
3911 Applicability::MachineApplicable,
3912 );
3913 if !from_arg
3914 && matches!(
3915 decl.local_info(),
3916 LocalInfo::User(BindingForm::Var(VarBindingForm {
3917 opt_match_place: Some((Some(_), _)),
3918 ..
3919 }))
3920 )
3921 {
3922 err.span_suggestion_verbose(
3923 decl.source_info.span.shrink_to_lo(),
3924 "to modify the original value, take a borrow instead",
3925 "ref mut ".to_string(),
3926 Applicability::MaybeIncorrect,
3927 );
3928 }
3929 }
3930 err.span_label(span, msg);
3931 self.buffer_error(err);
3932 }
3933
3934 fn classify_drop_access_kind(&self, place: PlaceRef<'tcx>) -> StorageDeadOrDrop<'tcx> {
3935 let tcx = self.infcx.tcx;
3936 let (kind, _place_ty) = place.projection.iter().fold(
3937 (LocalStorageDead, PlaceTy::from_ty(self.body.local_decls[place.local].ty)),
3938 |(kind, place_ty), &elem| {
3939 (
3940 match elem {
3941 ProjectionElem::Deref => match kind {
3942 StorageDeadOrDrop::LocalStorageDead
3943 | StorageDeadOrDrop::BoxedStorageDead => {
3944 assert!(
3945 place_ty.ty.is_box(),
3946 "Drop of value behind a reference or raw pointer"
3947 );
3948 StorageDeadOrDrop::BoxedStorageDead
3949 }
3950 StorageDeadOrDrop::Destructor(_) => kind,
3951 },
3952 ProjectionElem::OpaqueCast { .. }
3953 | ProjectionElem::Field(..)
3954 | ProjectionElem::Downcast(..) => {
3955 match place_ty.ty.kind() {
3956 ty::Adt(def, _) if def.has_dtor(tcx) => {
3957 match kind {
3959 StorageDeadOrDrop::Destructor(_) => kind,
3960 StorageDeadOrDrop::LocalStorageDead
3961 | StorageDeadOrDrop::BoxedStorageDead => {
3962 StorageDeadOrDrop::Destructor(place_ty.ty)
3963 }
3964 }
3965 }
3966 _ => kind,
3967 }
3968 }
3969 ProjectionElem::ConstantIndex { .. }
3970 | ProjectionElem::Subslice { .. }
3971 | ProjectionElem::Index(_)
3972 | ProjectionElem::UnwrapUnsafeBinder(_) => kind,
3973 },
3974 place_ty.projection_ty(tcx, elem),
3975 )
3976 },
3977 );
3978 kind
3979 }
3980
3981 fn classify_immutable_section(&self, place: Place<'tcx>) -> Option<&'static str> {
3983 use rustc_middle::mir::visit::Visitor;
3984 struct FakeReadCauseFinder<'tcx> {
3985 place: Place<'tcx>,
3986 cause: Option<FakeReadCause>,
3987 }
3988 impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'tcx> {
3989 fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
3990 match statement {
3991 Statement { kind: StatementKind::FakeRead(box (cause, place)), .. }
3992 if *place == self.place =>
3993 {
3994 self.cause = Some(*cause);
3995 }
3996 _ => (),
3997 }
3998 }
3999 }
4000 let mut visitor = FakeReadCauseFinder { place, cause: None };
4001 visitor.visit_body(self.body);
4002 match visitor.cause {
4003 Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
4004 Some(FakeReadCause::ForIndex) => Some("indexing expression"),
4005 _ => None,
4006 }
4007 }
4008
4009 fn annotate_argument_and_return_for_borrow(
4012 &self,
4013 borrow: &BorrowData<'tcx>,
4014 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4015 let fallback = || {
4017 let is_closure = self.infcx.tcx.is_closure_like(self.mir_def_id().to_def_id());
4018 if is_closure {
4019 None
4020 } else {
4021 let ty = self.infcx.tcx.type_of(self.mir_def_id()).instantiate_identity();
4022 match ty.kind() {
4023 ty::FnDef(_, _) | ty::FnPtr(..) => self.annotate_fn_sig(
4024 self.mir_def_id(),
4025 self.infcx.tcx.fn_sig(self.mir_def_id()).instantiate_identity(),
4026 ),
4027 _ => None,
4028 }
4029 }
4030 };
4031
4032 let location = borrow.reserve_location;
4039 debug!("annotate_argument_and_return_for_borrow: location={:?}", location);
4040 if let Some(Statement { kind: StatementKind::Assign(box (reservation, _)), .. }) =
4041 &self.body[location.block].statements.get(location.statement_index)
4042 {
4043 debug!("annotate_argument_and_return_for_borrow: reservation={:?}", reservation);
4044 let mut target = match reservation.as_local() {
4046 Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
4047 _ => return None,
4048 };
4049
4050 let mut annotated_closure = None;
4053 for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
4054 debug!(
4055 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
4056 target, stmt
4057 );
4058 if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind
4059 && let Some(assigned_to) = place.as_local()
4060 {
4061 debug!(
4062 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
4063 rvalue={:?}",
4064 assigned_to, rvalue
4065 );
4066 if let Rvalue::Aggregate(box AggregateKind::Closure(def_id, args), operands) =
4068 rvalue
4069 {
4070 let def_id = def_id.expect_local();
4071 for operand in operands {
4072 let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4073 operand
4074 else {
4075 continue;
4076 };
4077 debug!(
4078 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4079 assigned_from
4080 );
4081
4082 let Some(assigned_from_local) = assigned_from.local_or_deref_local()
4084 else {
4085 continue;
4086 };
4087
4088 if assigned_from_local != target {
4089 continue;
4090 }
4091
4092 annotated_closure =
4096 self.annotate_fn_sig(def_id, args.as_closure().sig());
4097 debug!(
4098 "annotate_argument_and_return_for_borrow: \
4099 annotated_closure={:?} assigned_from_local={:?} \
4100 assigned_to={:?}",
4101 annotated_closure, assigned_from_local, assigned_to
4102 );
4103
4104 if assigned_to == mir::RETURN_PLACE {
4105 return annotated_closure;
4108 } else {
4109 target = assigned_to;
4111 }
4112 }
4113
4114 continue;
4117 }
4118
4119 let assigned_from = match rvalue {
4121 Rvalue::Ref(_, _, assigned_from) => assigned_from,
4122 Rvalue::Use(operand) => match operand {
4123 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
4124 assigned_from
4125 }
4126 _ => continue,
4127 },
4128 _ => continue,
4129 };
4130 debug!(
4131 "annotate_argument_and_return_for_borrow: \
4132 assigned_from={:?}",
4133 assigned_from,
4134 );
4135
4136 let Some(assigned_from_local) = assigned_from.local_or_deref_local() else {
4138 continue;
4139 };
4140 debug!(
4141 "annotate_argument_and_return_for_borrow: \
4142 assigned_from_local={:?}",
4143 assigned_from_local,
4144 );
4145
4146 if assigned_from_local != target {
4149 continue;
4150 }
4151
4152 debug!(
4155 "annotate_argument_and_return_for_borrow: \
4156 assigned_from_local={:?} assigned_to={:?}",
4157 assigned_from_local, assigned_to
4158 );
4159 if assigned_to == mir::RETURN_PLACE {
4160 return annotated_closure.or_else(fallback);
4163 }
4164
4165 target = assigned_to;
4168 }
4169 }
4170
4171 let terminator = &self.body[location.block].terminator();
4173 debug!(
4174 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
4175 target, terminator
4176 );
4177 if let TerminatorKind::Call { destination, target: Some(_), args, .. } =
4178 &terminator.kind
4179 && let Some(assigned_to) = destination.as_local()
4180 {
4181 debug!(
4182 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
4183 assigned_to, args
4184 );
4185 for operand in args {
4186 let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4187 &operand.node
4188 else {
4189 continue;
4190 };
4191 debug!(
4192 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4193 assigned_from,
4194 );
4195
4196 if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
4197 debug!(
4198 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
4199 assigned_from_local,
4200 );
4201
4202 if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
4203 return annotated_closure.or_else(fallback);
4204 }
4205 }
4206 }
4207 }
4208 }
4209
4210 debug!("annotate_argument_and_return_for_borrow: none found");
4213 None
4214 }
4215
4216 fn annotate_fn_sig(
4219 &self,
4220 did: LocalDefId,
4221 sig: ty::PolyFnSig<'tcx>,
4222 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4223 debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
4224 let is_closure = self.infcx.tcx.is_closure_like(did.to_def_id());
4225 let fn_hir_id = self.infcx.tcx.local_def_id_to_hir_id(did);
4226 let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(fn_hir_id)?;
4227
4228 let return_ty = sig.output();
4251 match return_ty.skip_binder().kind() {
4252 ty::Ref(return_region, _, _)
4253 if return_region.is_named(self.infcx.tcx) && !is_closure =>
4254 {
4255 let mut arguments = Vec::new();
4258 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
4259 if let ty::Ref(argument_region, _, _) = argument.kind()
4260 && argument_region == return_region
4261 {
4262 match &fn_decl.inputs[index].kind {
4266 hir::TyKind::Ref(lifetime, _) => {
4267 arguments.push((*argument, lifetime.ident.span));
4270 }
4271 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
4273 if let Res::SelfTyAlias { alias_to, .. } = path.res
4274 && let Some(alias_to) = alias_to.as_local()
4275 && let hir::Impl { self_ty, .. } = self
4276 .infcx
4277 .tcx
4278 .hir_node_by_def_id(alias_to)
4279 .expect_item()
4280 .expect_impl()
4281 && let hir::TyKind::Ref(lifetime, _) = self_ty.kind
4282 {
4283 arguments.push((*argument, lifetime.ident.span));
4284 }
4285 }
4286 _ => {
4287 }
4289 }
4290 }
4291 }
4292
4293 if arguments.is_empty() {
4295 return None;
4296 }
4297
4298 let return_ty = sig.output().skip_binder();
4301 let mut return_span = fn_decl.output.span();
4302 if let hir::FnRetTy::Return(ty) = &fn_decl.output
4303 && let hir::TyKind::Ref(lifetime, _) = ty.kind
4304 {
4305 return_span = lifetime.ident.span;
4306 }
4307
4308 Some(AnnotatedBorrowFnSignature::NamedFunction {
4309 arguments,
4310 return_ty,
4311 return_span,
4312 })
4313 }
4314 ty::Ref(_, _, _) if is_closure => {
4315 let argument_span = fn_decl.inputs.first()?.span;
4319 let argument_ty = sig.inputs().skip_binder().first()?;
4320
4321 if let ty::Tuple(elems) = argument_ty.kind() {
4324 let &argument_ty = elems.first()?;
4325 if let ty::Ref(_, _, _) = argument_ty.kind() {
4326 return Some(AnnotatedBorrowFnSignature::Closure {
4327 argument_ty,
4328 argument_span,
4329 });
4330 }
4331 }
4332
4333 None
4334 }
4335 ty::Ref(_, _, _) => {
4336 let argument_span = fn_decl.inputs.first()?.span;
4339 let argument_ty = *sig.inputs().skip_binder().first()?;
4340
4341 let return_span = fn_decl.output.span();
4342 let return_ty = sig.output().skip_binder();
4343
4344 match argument_ty.kind() {
4346 ty::Ref(_, _, _) => {}
4347 _ => return None,
4348 }
4349
4350 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
4351 argument_ty,
4352 argument_span,
4353 return_ty,
4354 return_span,
4355 })
4356 }
4357 _ => {
4358 None
4361 }
4362 }
4363 }
4364}
4365
4366#[derive(Debug)]
4367enum AnnotatedBorrowFnSignature<'tcx> {
4368 NamedFunction {
4369 arguments: Vec<(Ty<'tcx>, Span)>,
4370 return_ty: Ty<'tcx>,
4371 return_span: Span,
4372 },
4373 AnonymousFunction {
4374 argument_ty: Ty<'tcx>,
4375 argument_span: Span,
4376 return_ty: Ty<'tcx>,
4377 return_span: Span,
4378 },
4379 Closure {
4380 argument_ty: Ty<'tcx>,
4381 argument_span: Span,
4382 },
4383}
4384
4385impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
4386 pub(crate) fn emit(&self, cx: &MirBorrowckCtxt<'_, '_, 'tcx>, diag: &mut Diag<'_>) -> String {
4389 match self {
4390 &AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
4391 diag.span_label(
4392 argument_span,
4393 format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
4394 );
4395
4396 cx.get_region_name_for_ty(argument_ty, 0)
4397 }
4398 &AnnotatedBorrowFnSignature::AnonymousFunction {
4399 argument_ty,
4400 argument_span,
4401 return_ty,
4402 return_span,
4403 } => {
4404 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
4405 diag.span_label(argument_span, format!("has type `{argument_ty_name}`"));
4406
4407 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
4408 let types_equal = return_ty_name == argument_ty_name;
4409 diag.span_label(
4410 return_span,
4411 format!(
4412 "{}has type `{}`",
4413 if types_equal { "also " } else { "" },
4414 return_ty_name,
4415 ),
4416 );
4417
4418 diag.note(
4419 "argument and return type have the same lifetime due to lifetime elision rules",
4420 );
4421 diag.note(
4422 "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
4423 lifetime-syntax.html#lifetime-elision>",
4424 );
4425
4426 cx.get_region_name_for_ty(return_ty, 0)
4427 }
4428 AnnotatedBorrowFnSignature::NamedFunction { arguments, return_ty, return_span } => {
4429 let region_name = cx.get_region_name_for_ty(*return_ty, 0);
4431 for (_, argument_span) in arguments {
4432 diag.span_label(*argument_span, format!("has lifetime `{region_name}`"));
4433 }
4434
4435 diag.span_label(*return_span, format!("also has lifetime `{region_name}`",));
4436
4437 diag.help(format!(
4438 "use data from the highlighted arguments which match the `{region_name}` lifetime of \
4439 the return type",
4440 ));
4441
4442 region_name
4443 }
4444 }
4445 }
4446}
4447
4448struct ReferencedStatementsVisitor<'a>(&'a [Span]);
4450
4451impl<'v> Visitor<'v> for ReferencedStatementsVisitor<'_> {
4452 type Result = ControlFlow<()>;
4453 fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) -> Self::Result {
4454 match s.kind {
4455 hir::StmtKind::Semi(expr) if self.0.contains(&expr.span) => ControlFlow::Break(()),
4456 _ => ControlFlow::Continue(()),
4457 }
4458 }
4459}
4460
4461struct BreakFinder {
4465 found_breaks: Vec<(hir::Destination, Span)>,
4466 found_continues: Vec<(hir::Destination, Span)>,
4467}
4468impl<'hir> Visitor<'hir> for BreakFinder {
4469 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
4470 match ex.kind {
4471 hir::ExprKind::Break(destination, _) => {
4472 self.found_breaks.push((destination, ex.span));
4473 }
4474 hir::ExprKind::Continue(destination) => {
4475 self.found_continues.push((destination, ex.span));
4476 }
4477 _ => {}
4478 }
4479 hir::intravisit::walk_expr(self, ex);
4480 }
4481}
4482
4483struct ConditionVisitor<'tcx> {
4486 tcx: TyCtxt<'tcx>,
4487 spans: Vec<Span>,
4488 name: String,
4489 errors: Vec<(Span, String)>,
4490}
4491
4492impl<'v, 'tcx> Visitor<'v> for ConditionVisitor<'tcx> {
4493 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
4494 match ex.kind {
4495 hir::ExprKind::If(cond, body, None) => {
4496 if ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break() {
4499 self.errors.push((
4500 cond.span,
4501 format!(
4502 "if this `if` condition is `false`, {} is not initialized",
4503 self.name,
4504 ),
4505 ));
4506 self.errors.push((
4507 ex.span.shrink_to_hi(),
4508 format!("an `else` arm might be missing here, initializing {}", self.name),
4509 ));
4510 }
4511 }
4512 hir::ExprKind::If(cond, body, Some(other)) => {
4513 let a = ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break();
4516 let b = ReferencedStatementsVisitor(&self.spans).visit_expr(other).is_break();
4517 match (a, b) {
4518 (true, true) | (false, false) => {}
4519 (true, false) => {
4520 if other.span.is_desugaring(DesugaringKind::WhileLoop) {
4521 self.errors.push((
4522 cond.span,
4523 format!(
4524 "if this condition isn't met and the `while` loop runs 0 \
4525 times, {} is not initialized",
4526 self.name
4527 ),
4528 ));
4529 } else {
4530 self.errors.push((
4531 body.span.shrink_to_hi().until(other.span),
4532 format!(
4533 "if the `if` condition is `false` and this `else` arm is \
4534 executed, {} is not initialized",
4535 self.name
4536 ),
4537 ));
4538 }
4539 }
4540 (false, true) => {
4541 self.errors.push((
4542 cond.span,
4543 format!(
4544 "if this condition is `true`, {} is not initialized",
4545 self.name
4546 ),
4547 ));
4548 }
4549 }
4550 }
4551 hir::ExprKind::Match(e, arms, loop_desugar) => {
4552 let results: Vec<bool> = arms
4555 .iter()
4556 .map(|arm| ReferencedStatementsVisitor(&self.spans).visit_arm(arm).is_break())
4557 .collect();
4558 if results.iter().any(|x| *x) && !results.iter().all(|x| *x) {
4559 for (arm, seen) in arms.iter().zip(results) {
4560 if !seen {
4561 if loop_desugar == hir::MatchSource::ForLoopDesugar {
4562 self.errors.push((
4563 e.span,
4564 format!(
4565 "if the `for` loop runs 0 times, {} is not initialized",
4566 self.name
4567 ),
4568 ));
4569 } else if let Some(guard) = &arm.guard {
4570 if matches!(
4571 self.tcx.hir_node(arm.body.hir_id),
4572 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4573 ) {
4574 continue;
4575 }
4576 self.errors.push((
4577 arm.pat.span.to(guard.span),
4578 format!(
4579 "if this pattern and condition are matched, {} is not \
4580 initialized",
4581 self.name
4582 ),
4583 ));
4584 } else {
4585 if matches!(
4586 self.tcx.hir_node(arm.body.hir_id),
4587 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4588 ) {
4589 continue;
4590 }
4591 self.errors.push((
4592 arm.pat.span,
4593 format!(
4594 "if this pattern is matched, {} is not initialized",
4595 self.name
4596 ),
4597 ));
4598 }
4599 }
4600 }
4601 }
4602 }
4603 _ => {}
4608 }
4609 walk_expr(self, ex);
4610 }
4611}