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, call_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, Some(parent_expr.hir_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), Some(call.hir_id), args, 0)
423 } else {
424 (None, 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 Some(generic_args) = call_id.and_then(|id| typeck.node_args_opt(id))
463 && let Some(ref_mutability) = self.suggest_borrow_generic_arg(
464 err,
465 def_id,
466 generic_args,
467 param,
468 moved_place,
469 pos + offset,
470 ty,
471 expr.span,
472 )
473 {
474 can_suggest_clone = ref_mutability.is_mut();
475 } else if let Some(local_def_id) = def_id.as_local()
476 && let node = self.infcx.tcx.hir_node_by_def_id(local_def_id)
477 && let Some(fn_decl) = node.fn_decl()
478 && let Some(ident) = node.ident()
479 && let Some(arg) = fn_decl.inputs.get(pos + offset)
480 {
481 let mut span: MultiSpan = arg.span.into();
484 span.push_span_label(
485 arg.span,
486 "this parameter takes ownership of the value".to_string(),
487 );
488 let descr = match node.fn_kind() {
489 Some(hir::intravisit::FnKind::ItemFn(..)) | None => "function",
490 Some(hir::intravisit::FnKind::Method(..)) => "method",
491 Some(hir::intravisit::FnKind::Closure) => "closure",
492 };
493 span.push_span_label(ident.span, format!("in this {descr}"));
494 err.span_note(
495 span,
496 format!(
497 "consider changing this parameter type in {descr} `{ident}` to \
498 borrow instead if owning the value isn't necessary",
499 ),
500 );
501 }
502 }
503 if let hir::Node::Expr(parent_expr) = parent
504 && let hir::ExprKind::Call(call_expr, _) = parent_expr.kind
505 && let hir::ExprKind::Path(hir::QPath::LangItem(LangItem::IntoIterIntoIter, _)) =
506 call_expr.kind
507 {
508 } else if let UseSpans::FnSelfUse { kind: CallKind::Normal { .. }, .. } = move_spans
510 {
511 } else if moved_or_invoked_closure {
513 } else if let UseSpans::ClosureUse {
515 closure_kind:
516 ClosureKind::Coroutine(CoroutineKind::Desugared(_, CoroutineSource::Block)),
517 ..
518 } = move_spans
519 && can_suggest_clone
520 {
521 self.suggest_cloning(err, place.as_ref(), ty, expr, Some(move_spans));
522 } else if self.suggest_hoisting_call_outside_loop(err, expr) && can_suggest_clone {
523 self.suggest_cloning(err, place.as_ref(), ty, expr, Some(move_spans));
526 }
527 }
528
529 self.suggest_ref_for_dbg_args(expr, place, move_span, err);
530
531 if let Some(pat) = finder.pat
533 && !move_span.is_dummy()
534 && !self.infcx.tcx.sess.source_map().is_imported(move_span)
535 {
536 let mut sugg = vec![(pat.span.shrink_to_lo(), "ref ".to_string())];
537 if let Some(pat) = finder.parent_pat {
538 sugg.insert(0, (pat.span.shrink_to_lo(), "ref ".to_string()));
539 }
540 err.multipart_suggestion_verbose(
541 "borrow this binding in the pattern to avoid moving the value",
542 sugg,
543 Applicability::MachineApplicable,
544 );
545 }
546 }
547 }
548
549 fn suggest_ref_for_dbg_args(
553 &self,
554 body: &hir::Expr<'_>,
555 place: &Place<'tcx>,
556 move_span: Span,
557 err: &mut Diag<'infcx>,
558 ) {
559 let var_info = self.body.var_debug_info.iter().find(|info| match info.value {
560 VarDebugInfoContents::Place(ref p) => p == place,
561 _ => false,
562 });
563 let arg_name = if let Some(var_info) = var_info {
564 var_info.name
565 } else {
566 return;
567 };
568 struct MatchArgFinder {
569 expr_span: Span,
570 match_arg_span: Option<Span>,
571 arg_name: Symbol,
572 }
573 impl Visitor<'_> for MatchArgFinder {
574 fn visit_expr(&mut self, e: &hir::Expr<'_>) {
575 if let hir::ExprKind::Match(expr, ..) = &e.kind
577 && let hir::ExprKind::Path(hir::QPath::Resolved(
578 _,
579 path @ Path { segments: [seg], .. },
580 )) = &expr.kind
581 && seg.ident.name == self.arg_name
582 && self.expr_span.source_callsite().contains(expr.span)
583 {
584 self.match_arg_span = Some(path.span);
585 }
586 hir::intravisit::walk_expr(self, e);
587 }
588 }
589
590 let mut finder = MatchArgFinder { expr_span: move_span, match_arg_span: None, arg_name };
591 finder.visit_expr(body);
592 if let Some(macro_arg_span) = finder.match_arg_span {
593 err.span_suggestion_verbose(
594 macro_arg_span.shrink_to_lo(),
595 "consider borrowing instead of transferring ownership",
596 "&",
597 Applicability::MachineApplicable,
598 );
599 }
600 }
601
602 pub(crate) fn suggest_reborrow(
603 &self,
604 err: &mut Diag<'infcx>,
605 span: Span,
606 moved_place: PlaceRef<'tcx>,
607 ) {
608 err.span_suggestion_verbose(
609 span.shrink_to_lo(),
610 format!(
611 "consider creating a fresh reborrow of {} here",
612 self.describe_place(moved_place)
613 .map(|n| format!("`{n}`"))
614 .unwrap_or_else(|| "the mutable reference".to_string()),
615 ),
616 "&mut *",
617 Applicability::MachineApplicable,
618 );
619 }
620
621 fn suggest_borrow_generic_arg(
628 &self,
629 err: &mut Diag<'_>,
630 callee_did: DefId,
631 generic_args: ty::GenericArgsRef<'tcx>,
632 param: ty::ParamTy,
633 moved_place: PlaceRef<'tcx>,
634 moved_arg_pos: usize,
635 moved_arg_ty: Ty<'tcx>,
636 place_span: Span,
637 ) -> Option<ty::Mutability> {
638 let tcx = self.infcx.tcx;
639 let sig = tcx.fn_sig(callee_did).instantiate_identity().skip_binder();
640 let clauses = tcx.predicates_of(callee_did);
641
642 if !clauses.instantiate_identity(tcx).predicates.iter().any(|clause| {
645 clause.as_trait_clause().is_some_and(|tc| {
646 tc.self_ty().skip_binder().is_param(param.index)
647 && tc.polarity() == ty::PredicatePolarity::Positive
648 && supertrait_def_ids(tcx, tc.def_id())
649 .flat_map(|trait_did| tcx.associated_items(trait_did).in_definition_order())
650 .any(|item| item.is_method())
651 })
652 }) {
653 return None;
654 }
655
656 if let Some(mutbl) = [ty::Mutability::Not, ty::Mutability::Mut].into_iter().find(|&mutbl| {
658 let re = self.infcx.tcx.lifetimes.re_erased;
659 let ref_ty = Ty::new_ref(self.infcx.tcx, re, moved_arg_ty, mutbl);
660
661 let new_args = tcx.mk_args_from_iter(generic_args.iter().enumerate().map(
664 |(i, arg)| {
665 if i == param.index as usize { ref_ty.into() } else { arg }
666 },
667 ));
668 let can_subst = |ty: Ty<'tcx>| {
669 let old_ty = ty::EarlyBinder::bind(ty).instantiate(tcx, generic_args);
671 let new_ty = ty::EarlyBinder::bind(ty).instantiate(tcx, new_args);
672 if let Ok(old_ty) = tcx.try_normalize_erasing_regions(
673 self.infcx.typing_env(self.infcx.param_env),
674 old_ty,
675 ) && let Ok(new_ty) = tcx.try_normalize_erasing_regions(
676 self.infcx.typing_env(self.infcx.param_env),
677 new_ty,
678 ) {
679 old_ty == new_ty
680 } else {
681 false
682 }
683 };
684 if !can_subst(sig.output())
685 || sig
686 .inputs()
687 .iter()
688 .enumerate()
689 .any(|(i, &input_ty)| i != moved_arg_pos && !can_subst(input_ty))
690 {
691 return false;
692 }
693
694 clauses.instantiate(tcx, new_args).predicates.iter().all(|&(mut clause)| {
696 if let Ok(normalized) = tcx.try_normalize_erasing_regions(
698 self.infcx.typing_env(self.infcx.param_env),
699 clause,
700 ) {
701 clause = normalized;
702 }
703 self.infcx.predicate_must_hold_modulo_regions(&Obligation::new(
704 tcx,
705 ObligationCause::dummy(),
706 self.infcx.param_env,
707 clause,
708 ))
709 })
710 }) {
711 let place_desc = if let Some(desc) = self.describe_place(moved_place) {
712 format!("`{desc}`")
713 } else {
714 "here".to_owned()
715 };
716 err.span_suggestion_verbose(
717 place_span.shrink_to_lo(),
718 format!("consider {}borrowing {place_desc}", mutbl.mutably_str()),
719 mutbl.ref_prefix_str(),
720 Applicability::MaybeIncorrect,
721 );
722 Some(mutbl)
723 } else {
724 None
725 }
726 }
727
728 fn report_use_of_uninitialized(
729 &self,
730 mpi: MovePathIndex,
731 used_place: PlaceRef<'tcx>,
732 moved_place: PlaceRef<'tcx>,
733 desired_action: InitializationRequiringAction,
734 span: Span,
735 use_spans: UseSpans<'tcx>,
736 ) -> Diag<'infcx> {
737 let inits = &self.move_data.init_path_map[mpi];
740 let move_path = &self.move_data.move_paths[mpi];
741 let decl_span = self.body.local_decls[move_path.place.local].source_info.span;
742 let mut spans_set = FxIndexSet::default();
743 for init_idx in inits {
744 let init = &self.move_data.inits[*init_idx];
745 let span = init.span(self.body);
746 if !span.is_dummy() {
747 spans_set.insert(span);
748 }
749 }
750 let spans: Vec<_> = spans_set.into_iter().collect();
751
752 let (name, desc) = match self.describe_place_with_options(
753 moved_place,
754 DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
755 ) {
756 Some(name) => (format!("`{name}`"), format!("`{name}` ")),
757 None => ("the variable".to_string(), String::new()),
758 };
759 let path = match self.describe_place_with_options(
760 used_place,
761 DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
762 ) {
763 Some(name) => format!("`{name}`"),
764 None => "value".to_string(),
765 };
766
767 let tcx = self.infcx.tcx;
770 let body = tcx.hir_body_owned_by(self.mir_def_id());
771 let mut visitor = ConditionVisitor { tcx, spans, name, errors: vec![] };
772 visitor.visit_body(&body);
773 let spans = visitor.spans;
774
775 let mut show_assign_sugg = false;
776 let isnt_initialized = if let InitializationRequiringAction::PartialAssignment
777 | InitializationRequiringAction::Assignment = desired_action
778 {
779 "isn't fully initialized"
783 } else if !spans.iter().any(|i| {
784 !i.contains(span)
791 && !visitor
793 .errors
794 .iter()
795 .map(|(sp, _)| *sp)
796 .any(|sp| span < sp && !sp.contains(span))
797 }) {
798 show_assign_sugg = true;
799 "isn't initialized"
800 } else {
801 "is possibly-uninitialized"
802 };
803
804 let used = desired_action.as_general_verb_in_past_tense();
805 let mut err = struct_span_code_err!(
806 self.dcx(),
807 span,
808 E0381,
809 "{used} binding {desc}{isnt_initialized}"
810 );
811 use_spans.var_path_only_subdiag(&mut err, desired_action);
812
813 if let InitializationRequiringAction::PartialAssignment
814 | InitializationRequiringAction::Assignment = desired_action
815 {
816 err.help(
817 "partial initialization isn't supported, fully initialize the binding with a \
818 default value and mutate it, or use `std::mem::MaybeUninit`",
819 );
820 }
821 err.span_label(span, format!("{path} {used} here but it {isnt_initialized}"));
822
823 let mut shown = false;
824 for (sp, label) in visitor.errors {
825 if sp < span && !sp.overlaps(span) {
826 err.span_label(sp, label);
840 shown = true;
841 }
842 }
843 if !shown {
844 for sp in &spans {
845 if *sp < span && !sp.overlaps(span) {
846 err.span_label(*sp, "binding initialized here in some conditions");
847 }
848 }
849 }
850
851 err.span_label(decl_span, "binding declared here but left uninitialized");
852 if show_assign_sugg {
853 struct LetVisitor {
854 decl_span: Span,
855 sugg_span: Option<Span>,
856 }
857
858 impl<'v> Visitor<'v> for LetVisitor {
859 fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) {
860 if self.sugg_span.is_some() {
861 return;
862 }
863
864 if let hir::StmtKind::Let(hir::LetStmt { span, ty, init: None, pat, .. }) =
867 &ex.kind
868 && let hir::PatKind::Binding(..) = pat.kind
869 && span.contains(self.decl_span)
870 {
871 self.sugg_span = ty.map_or(Some(self.decl_span), |ty| Some(ty.span));
872 }
873 hir::intravisit::walk_stmt(self, ex);
874 }
875 }
876
877 let mut visitor = LetVisitor { decl_span, sugg_span: None };
878 visitor.visit_body(&body);
879 if let Some(span) = visitor.sugg_span {
880 self.suggest_assign_value(&mut err, moved_place, span);
881 }
882 }
883 err
884 }
885
886 fn suggest_assign_value(
887 &self,
888 err: &mut Diag<'_>,
889 moved_place: PlaceRef<'tcx>,
890 sugg_span: Span,
891 ) {
892 let ty = moved_place.ty(self.body, self.infcx.tcx).ty;
893 debug!("ty: {:?}, kind: {:?}", ty, ty.kind());
894
895 let Some(assign_value) = self.infcx.err_ctxt().ty_kind_suggestion(self.infcx.param_env, ty)
896 else {
897 return;
898 };
899
900 err.span_suggestion_verbose(
901 sugg_span.shrink_to_hi(),
902 "consider assigning a value",
903 format!(" = {assign_value}"),
904 Applicability::MaybeIncorrect,
905 );
906 }
907
908 fn suggest_hoisting_call_outside_loop(&self, err: &mut Diag<'_>, expr: &hir::Expr<'_>) -> bool {
913 let tcx = self.infcx.tcx;
914 let mut can_suggest_clone = true;
915
916 let local_hir_id = if let hir::ExprKind::Path(hir::QPath::Resolved(
920 _,
921 hir::Path { res: hir::def::Res::Local(local_hir_id), .. },
922 )) = expr.kind
923 {
924 Some(local_hir_id)
925 } else {
926 None
929 };
930
931 struct Finder {
935 hir_id: hir::HirId,
936 }
937 impl<'hir> Visitor<'hir> for Finder {
938 type Result = ControlFlow<()>;
939 fn visit_pat(&mut self, pat: &'hir hir::Pat<'hir>) -> Self::Result {
940 if pat.hir_id == self.hir_id {
941 return ControlFlow::Break(());
942 }
943 hir::intravisit::walk_pat(self, pat)
944 }
945 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) -> Self::Result {
946 if ex.hir_id == self.hir_id {
947 return ControlFlow::Break(());
948 }
949 hir::intravisit::walk_expr(self, ex)
950 }
951 }
952 let mut parent = None;
954 let mut outer_most_loop: Option<&hir::Expr<'_>> = None;
956 for (_, node) in tcx.hir_parent_iter(expr.hir_id) {
957 let e = match node {
958 hir::Node::Expr(e) => e,
959 hir::Node::LetStmt(hir::LetStmt { els: Some(els), .. }) => {
960 let mut finder = BreakFinder { found_breaks: vec![], found_continues: vec![] };
961 finder.visit_block(els);
962 if !finder.found_breaks.is_empty() {
963 can_suggest_clone = false;
968 }
969 continue;
970 }
971 _ => continue,
972 };
973 if let Some(&hir_id) = local_hir_id {
974 if (Finder { hir_id }).visit_expr(e).is_break() {
975 break;
978 }
979 }
980 if parent.is_none() {
981 parent = Some(e);
982 }
983 match e.kind {
984 hir::ExprKind::Let(_) => {
985 match tcx.parent_hir_node(e.hir_id) {
986 hir::Node::Expr(hir::Expr {
987 kind: hir::ExprKind::If(cond, ..), ..
988 }) => {
989 if (Finder { hir_id: expr.hir_id }).visit_expr(cond).is_break() {
990 can_suggest_clone = false;
996 }
997 }
998 _ => {}
999 }
1000 }
1001 hir::ExprKind::Loop(..) => {
1002 outer_most_loop = Some(e);
1003 }
1004 _ => {}
1005 }
1006 }
1007 let loop_count: usize = tcx
1008 .hir_parent_iter(expr.hir_id)
1009 .map(|(_, node)| match node {
1010 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Loop(..), .. }) => 1,
1011 _ => 0,
1012 })
1013 .sum();
1014
1015 let sm = tcx.sess.source_map();
1016 if let Some(in_loop) = outer_most_loop {
1017 let mut finder = BreakFinder { found_breaks: vec![], found_continues: vec![] };
1018 finder.visit_expr(in_loop);
1019 let spans = finder
1021 .found_breaks
1022 .iter()
1023 .chain(finder.found_continues.iter())
1024 .map(|(_, span)| *span)
1025 .filter(|span| {
1026 !matches!(
1027 span.desugaring_kind(),
1028 Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop)
1029 )
1030 })
1031 .collect::<Vec<Span>>();
1032 let loop_spans: Vec<_> = tcx
1034 .hir_parent_iter(expr.hir_id)
1035 .filter_map(|(_, node)| match node {
1036 hir::Node::Expr(hir::Expr { span, kind: hir::ExprKind::Loop(..), .. }) => {
1037 Some(*span)
1038 }
1039 _ => None,
1040 })
1041 .collect();
1042 if !spans.is_empty() && loop_count > 1 {
1045 let mut lines: Vec<_> =
1049 loop_spans.iter().map(|sp| sm.lookup_char_pos(sp.lo()).line).collect();
1050 lines.sort();
1051 lines.dedup();
1052 let fmt_span = |span: Span| {
1053 if lines.len() == loop_spans.len() {
1054 format!("line {}", sm.lookup_char_pos(span.lo()).line)
1055 } else {
1056 sm.span_to_diagnostic_string(span)
1057 }
1058 };
1059 let mut spans: MultiSpan = spans.into();
1060 for (desc, elements) in [
1062 ("`break` exits", &finder.found_breaks),
1063 ("`continue` advances", &finder.found_continues),
1064 ] {
1065 for (destination, sp) in elements {
1066 if let Ok(hir_id) = destination.target_id
1067 && let hir::Node::Expr(expr) = tcx.hir_node(hir_id)
1068 && !matches!(
1069 sp.desugaring_kind(),
1070 Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop)
1071 )
1072 {
1073 spans.push_span_label(
1074 *sp,
1075 format!("this {desc} the loop at {}", fmt_span(expr.span)),
1076 );
1077 }
1078 }
1079 }
1080 for span in loop_spans {
1082 spans.push_span_label(sm.guess_head_span(span), "");
1083 }
1084
1085 err.span_note(spans, "verify that your loop breaking logic is correct");
1097 }
1098 if let Some(parent) = parent
1099 && let hir::ExprKind::MethodCall(..) | hir::ExprKind::Call(..) = parent.kind
1100 {
1101 let span = in_loop.span;
1106 if !finder.found_breaks.is_empty()
1107 && let Ok(value) = sm.span_to_snippet(parent.span)
1108 {
1109 let indent = if let Some(indent) = sm.indentation_before(span) {
1112 format!("\n{indent}")
1113 } else {
1114 " ".to_string()
1115 };
1116 err.multipart_suggestion(
1117 "consider moving the expression out of the loop so it is only moved once",
1118 vec![
1119 (span.shrink_to_lo(), format!("let mut value = {value};{indent}")),
1120 (parent.span, "value".to_string()),
1121 ],
1122 Applicability::MaybeIncorrect,
1123 );
1124 }
1125 }
1126 }
1127 can_suggest_clone
1128 }
1129
1130 fn suggest_cloning_on_functional_record_update(
1133 &self,
1134 err: &mut Diag<'_>,
1135 ty: Ty<'tcx>,
1136 expr: &hir::Expr<'_>,
1137 ) {
1138 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1139 let hir::ExprKind::Struct(struct_qpath, fields, hir::StructTailExpr::Base(base)) =
1140 expr.kind
1141 else {
1142 return;
1143 };
1144 let hir::QPath::Resolved(_, path) = struct_qpath else { return };
1145 let hir::def::Res::Def(_, def_id) = path.res else { return };
1146 let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id) else { return };
1147 let ty::Adt(def, args) = expr_ty.kind() else { return };
1148 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = base.kind else { return };
1149 let (hir::def::Res::Local(_)
1150 | hir::def::Res::Def(
1151 DefKind::Const | DefKind::ConstParam | DefKind::Static { .. } | DefKind::AssocConst,
1152 _,
1153 )) = path.res
1154 else {
1155 return;
1156 };
1157 let Ok(base_str) = self.infcx.tcx.sess.source_map().span_to_snippet(base.span) else {
1158 return;
1159 };
1160
1161 let mut final_field_count = fields.len();
1167 let Some(variant) = def.variants().iter().find(|variant| variant.def_id == def_id) else {
1168 return;
1171 };
1172 let mut sugg = vec![];
1173 for field in &variant.fields {
1174 let field_ty = field.ty(self.infcx.tcx, args);
1178 let ident = field.ident(self.infcx.tcx);
1179 if field_ty == ty && fields.iter().all(|field| field.ident.name != ident.name) {
1180 sugg.push(format!("{ident}: {base_str}.{ident}.clone()"));
1182 final_field_count += 1;
1183 }
1184 }
1185 let (span, sugg) = match fields {
1186 [.., last] => (
1187 if final_field_count == variant.fields.len() {
1188 last.span.shrink_to_hi().with_hi(base.span.hi())
1190 } else {
1191 last.span.shrink_to_hi()
1192 },
1193 format!(", {}", sugg.join(", ")),
1194 ),
1195 [] => (
1197 expr.span.with_lo(struct_qpath.span().hi()),
1198 if final_field_count == variant.fields.len() {
1199 format!(" {{ {} }}", sugg.join(", "))
1201 } else {
1202 format!(" {{ {}, ..{base_str} }}", sugg.join(", "))
1203 },
1204 ),
1205 };
1206 let prefix = if !self.implements_clone(ty) {
1207 let msg = format!("`{ty}` doesn't implement `Copy` or `Clone`");
1208 if let ty::Adt(def, _) = ty.kind() {
1209 err.span_note(self.infcx.tcx.def_span(def.did()), msg);
1210 } else {
1211 err.note(msg);
1212 }
1213 format!("if `{ty}` implemented `Clone`, you could ")
1214 } else {
1215 String::new()
1216 };
1217 let msg = format!(
1218 "{prefix}clone the value from the field instead of using the functional record update \
1219 syntax",
1220 );
1221 err.span_suggestion_verbose(span, msg, sugg, Applicability::MachineApplicable);
1222 }
1223
1224 pub(crate) fn suggest_cloning(
1225 &self,
1226 err: &mut Diag<'_>,
1227 place: PlaceRef<'tcx>,
1228 ty: Ty<'tcx>,
1229 expr: &'tcx hir::Expr<'tcx>,
1230 use_spans: Option<UseSpans<'tcx>>,
1231 ) {
1232 if let hir::ExprKind::Struct(_, _, hir::StructTailExpr::Base(_)) = expr.kind {
1233 self.suggest_cloning_on_functional_record_update(err, ty, expr);
1238 return;
1239 }
1240
1241 if self.implements_clone(ty) {
1242 if self.in_move_closure(expr) {
1243 if let Some(name) = self.describe_place(place) {
1244 self.suggest_clone_of_captured_var_in_move_closure(err, &name, use_spans);
1245 }
1246 } else {
1247 self.suggest_cloning_inner(err, ty, expr);
1248 }
1249 } else if let ty::Adt(def, args) = ty.kind()
1250 && def.did().as_local().is_some()
1251 && def.variants().iter().all(|variant| {
1252 variant
1253 .fields
1254 .iter()
1255 .all(|field| self.implements_clone(field.ty(self.infcx.tcx, args)))
1256 })
1257 {
1258 let ty_span = self.infcx.tcx.def_span(def.did());
1259 let mut span: MultiSpan = ty_span.into();
1260 span.push_span_label(ty_span, "consider implementing `Clone` for this type");
1261 span.push_span_label(expr.span, "you could clone this value");
1262 err.span_note(
1263 span,
1264 format!("if `{ty}` implemented `Clone`, you could clone the value"),
1265 );
1266 } else if let ty::Param(param) = ty.kind()
1267 && let Some(_clone_trait_def) = self.infcx.tcx.lang_items().clone_trait()
1268 && let generics = self.infcx.tcx.generics_of(self.mir_def_id())
1269 && let generic_param = generics.type_param(*param, self.infcx.tcx)
1270 && let param_span = self.infcx.tcx.def_span(generic_param.def_id)
1271 && if let Some(UseSpans::FnSelfUse { kind, .. }) = use_spans
1272 && let CallKind::FnCall { fn_trait_id, self_ty } = kind
1273 && let ty::Param(_) = self_ty.kind()
1274 && ty == self_ty
1275 && self.infcx.tcx.fn_trait_kind_from_def_id(fn_trait_id).is_some()
1276 {
1277 false
1279 } else {
1280 true
1281 }
1282 {
1283 let mut span: MultiSpan = param_span.into();
1284 span.push_span_label(
1285 param_span,
1286 "consider constraining this type parameter with `Clone`",
1287 );
1288 span.push_span_label(expr.span, "you could clone this value");
1289 err.span_help(
1290 span,
1291 format!("if `{ty}` implemented `Clone`, you could clone the value"),
1292 );
1293 } else if let ty::Adt(_, _) = ty.kind()
1294 && let Some(clone_trait) = self.infcx.tcx.lang_items().clone_trait()
1295 {
1296 let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1299 let cause = ObligationCause::misc(expr.span, self.mir_def_id());
1300 ocx.register_bound(cause, self.infcx.param_env, ty, clone_trait);
1301 let errors = ocx.select_all_or_error();
1302 if errors.iter().all(|error| {
1303 match error.obligation.predicate.as_clause().and_then(|c| c.as_trait_clause()) {
1304 Some(clause) => match clause.self_ty().skip_binder().kind() {
1305 ty::Adt(def, _) => def.did().is_local() && clause.def_id() == clone_trait,
1306 _ => false,
1307 },
1308 None => false,
1309 }
1310 }) {
1311 let mut type_spans = vec![];
1312 let mut types = FxIndexSet::default();
1313 for clause in errors
1314 .iter()
1315 .filter_map(|e| e.obligation.predicate.as_clause())
1316 .filter_map(|c| c.as_trait_clause())
1317 {
1318 let ty::Adt(def, _) = clause.self_ty().skip_binder().kind() else { continue };
1319 type_spans.push(self.infcx.tcx.def_span(def.did()));
1320 types.insert(
1321 self.infcx
1322 .tcx
1323 .short_string(clause.self_ty().skip_binder(), &mut err.long_ty_path()),
1324 );
1325 }
1326 let mut span: MultiSpan = type_spans.clone().into();
1327 for sp in type_spans {
1328 span.push_span_label(sp, "consider implementing `Clone` for this type");
1329 }
1330 span.push_span_label(expr.span, "you could clone this value");
1331 let types: Vec<_> = types.into_iter().collect();
1332 let msg = match &types[..] {
1333 [only] => format!("`{only}`"),
1334 [head @ .., last] => format!(
1335 "{} and `{last}`",
1336 head.iter().map(|t| format!("`{t}`")).collect::<Vec<_>>().join(", ")
1337 ),
1338 [] => unreachable!(),
1339 };
1340 err.span_note(
1341 span,
1342 format!("if {msg} implemented `Clone`, you could clone the value"),
1343 );
1344 }
1345 }
1346 }
1347
1348 pub(crate) fn implements_clone(&self, ty: Ty<'tcx>) -> bool {
1349 let Some(clone_trait_def) = self.infcx.tcx.lang_items().clone_trait() else { return false };
1350 self.infcx
1351 .type_implements_trait(clone_trait_def, [ty], self.infcx.param_env)
1352 .must_apply_modulo_regions()
1353 }
1354
1355 pub(crate) fn clone_on_reference(&self, expr: &hir::Expr<'_>) -> Option<Span> {
1358 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1359 if let hir::ExprKind::MethodCall(segment, rcvr, args, span) = expr.kind
1360 && let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id)
1361 && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
1362 && rcvr_ty == expr_ty
1363 && segment.ident.name == sym::clone
1364 && args.is_empty()
1365 {
1366 Some(span)
1367 } else {
1368 None
1369 }
1370 }
1371
1372 fn in_move_closure(&self, expr: &hir::Expr<'_>) -> bool {
1373 for (_, node) in self.infcx.tcx.hir_parent_iter(expr.hir_id) {
1374 if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) = node
1375 && let hir::CaptureBy::Value { .. } = closure.capture_clause
1376 {
1377 return true;
1379 }
1380 }
1381 false
1382 }
1383
1384 fn suggest_cloning_inner(
1385 &self,
1386 err: &mut Diag<'_>,
1387 ty: Ty<'tcx>,
1388 expr: &hir::Expr<'_>,
1389 ) -> bool {
1390 let tcx = self.infcx.tcx;
1391 if let Some(_) = self.clone_on_reference(expr) {
1392 return false;
1395 }
1396 if self.in_move_closure(expr) {
1399 return false;
1400 }
1401 if let hir::ExprKind::Closure(_) = expr.kind {
1404 return false;
1405 }
1406 let mut suggestion =
1408 if let Some(symbol) = tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1409 format!(": {symbol}.clone()")
1410 } else {
1411 ".clone()".to_owned()
1412 };
1413 let mut sugg = Vec::with_capacity(2);
1414 let mut inner_expr = expr;
1415 let mut is_raw_ptr = false;
1416 let typeck_result = self.infcx.tcx.typeck(self.mir_def_id());
1417 while let hir::ExprKind::AddrOf(.., inner) | hir::ExprKind::Unary(hir::UnOp::Deref, inner) =
1419 &inner_expr.kind
1420 {
1421 if let hir::ExprKind::AddrOf(_, hir::Mutability::Mut, _) = inner_expr.kind {
1422 return false;
1425 }
1426 inner_expr = inner;
1427 if let Some(inner_type) = typeck_result.node_type_opt(inner.hir_id) {
1428 if matches!(inner_type.kind(), ty::RawPtr(..)) {
1429 is_raw_ptr = true;
1430 break;
1431 }
1432 }
1433 }
1434 if inner_expr.span.lo() != expr.span.lo() && !is_raw_ptr {
1437 sugg.push((expr.span.with_hi(inner_expr.span.lo()), String::new()));
1439 }
1440 let span = if inner_expr.span.hi() != expr.span.hi() {
1442 if is_raw_ptr {
1444 expr.span.shrink_to_hi()
1445 } else {
1446 expr.span.with_lo(inner_expr.span.hi())
1448 }
1449 } else {
1450 if is_raw_ptr {
1451 sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
1452 suggestion = ").clone()".to_string();
1453 }
1454 expr.span.shrink_to_hi()
1455 };
1456 sugg.push((span, suggestion));
1457 let msg = if let ty::Adt(def, _) = ty.kind()
1458 && [tcx.get_diagnostic_item(sym::Arc), tcx.get_diagnostic_item(sym::Rc)]
1459 .contains(&Some(def.did()))
1460 {
1461 "clone the value to increment its reference count"
1462 } else {
1463 "consider cloning the value if the performance cost is acceptable"
1464 };
1465 err.multipart_suggestion_verbose(msg, sugg, Applicability::MachineApplicable);
1466 true
1467 }
1468
1469 fn suggest_adding_bounds(&self, err: &mut Diag<'_>, ty: Ty<'tcx>, def_id: DefId, span: Span) {
1470 let tcx = self.infcx.tcx;
1471 let generics = tcx.generics_of(self.mir_def_id());
1472
1473 let Some(hir_generics) = tcx
1474 .typeck_root_def_id(self.mir_def_id().to_def_id())
1475 .as_local()
1476 .and_then(|def_id| tcx.hir_get_generics(def_id))
1477 else {
1478 return;
1479 };
1480 let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1482 let cause = ObligationCause::misc(span, self.mir_def_id());
1483
1484 ocx.register_bound(cause, self.infcx.param_env, ty, def_id);
1485 let errors = ocx.select_all_or_error();
1486
1487 let predicates: Result<Vec<_>, _> = errors
1489 .into_iter()
1490 .map(|err| match err.obligation.predicate.kind().skip_binder() {
1491 PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => {
1492 match *predicate.self_ty().kind() {
1493 ty::Param(param_ty) => Ok((
1494 generics.type_param(param_ty, tcx),
1495 predicate.trait_ref.print_trait_sugared().to_string(),
1496 Some(predicate.trait_ref.def_id),
1497 )),
1498 _ => Err(()),
1499 }
1500 }
1501 _ => Err(()),
1502 })
1503 .collect();
1504
1505 if let Ok(predicates) = predicates {
1506 suggest_constraining_type_params(
1507 tcx,
1508 hir_generics,
1509 err,
1510 predicates.iter().map(|(param, constraint, def_id)| {
1511 (param.name.as_str(), &**constraint, *def_id)
1512 }),
1513 None,
1514 );
1515 }
1516 }
1517
1518 pub(crate) fn report_move_out_while_borrowed(
1519 &mut self,
1520 location: Location,
1521 (place, span): (Place<'tcx>, Span),
1522 borrow: &BorrowData<'tcx>,
1523 ) {
1524 debug!(
1525 "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
1526 location, place, span, borrow
1527 );
1528 let value_msg = self.describe_any_place(place.as_ref());
1529 let borrow_msg = self.describe_any_place(borrow.borrowed_place.as_ref());
1530
1531 let borrow_spans = self.retrieve_borrow_spans(borrow);
1532 let borrow_span = borrow_spans.args_or_use();
1533
1534 let move_spans = self.move_spans(place.as_ref(), location);
1535 let span = move_spans.args_or_use();
1536
1537 let mut err = self.cannot_move_when_borrowed(
1538 span,
1539 borrow_span,
1540 &self.describe_any_place(place.as_ref()),
1541 &borrow_msg,
1542 &value_msg,
1543 );
1544 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1545
1546 borrow_spans.var_path_only_subdiag(&mut err, crate::InitializationRequiringAction::Borrow);
1547
1548 move_spans.var_subdiag(&mut err, None, |kind, var_span| {
1549 use crate::session_diagnostics::CaptureVarCause::*;
1550 match kind {
1551 hir::ClosureKind::Coroutine(_) => MoveUseInCoroutine { var_span },
1552 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1553 MoveUseInClosure { var_span }
1554 }
1555 }
1556 });
1557
1558 self.explain_why_borrow_contains_point(location, borrow, None)
1559 .add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
1560 self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
1561 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1562 if let Some(expr) = self.find_expr(borrow_span) {
1563 if let hir::ExprKind::AddrOf(_, _, borrowed_expr) = expr.kind
1565 && let Some(ty) = typeck_results.expr_ty_opt(borrowed_expr)
1566 {
1567 self.suggest_cloning(&mut err, place.as_ref(), ty, borrowed_expr, Some(move_spans));
1568 } else if typeck_results.expr_adjustments(expr).first().is_some_and(|adj| {
1569 matches!(
1570 adj.kind,
1571 ty::adjustment::Adjust::Borrow(ty::adjustment::AutoBorrow::Ref(
1572 ty::adjustment::AutoBorrowMutability::Not
1573 | ty::adjustment::AutoBorrowMutability::Mut {
1574 allow_two_phase_borrow: ty::adjustment::AllowTwoPhase::No
1575 }
1576 ))
1577 )
1578 }) && let Some(ty) = typeck_results.expr_ty_opt(expr)
1579 {
1580 self.suggest_cloning(&mut err, place.as_ref(), ty, expr, Some(move_spans));
1581 }
1582 }
1583 self.buffer_error(err);
1584 }
1585
1586 pub(crate) fn report_use_while_mutably_borrowed(
1587 &self,
1588 location: Location,
1589 (place, _span): (Place<'tcx>, Span),
1590 borrow: &BorrowData<'tcx>,
1591 ) -> Diag<'infcx> {
1592 let borrow_spans = self.retrieve_borrow_spans(borrow);
1593 let borrow_span = borrow_spans.args_or_use();
1594
1595 let use_spans = self.move_spans(place.as_ref(), location);
1598 let span = use_spans.var_or_use();
1599
1600 let mut err = self.cannot_use_when_mutably_borrowed(
1604 span,
1605 &self.describe_any_place(place.as_ref()),
1606 borrow_span,
1607 &self.describe_any_place(borrow.borrowed_place.as_ref()),
1608 );
1609 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1610
1611 borrow_spans.var_subdiag(&mut err, Some(borrow.kind), |kind, var_span| {
1612 use crate::session_diagnostics::CaptureVarCause::*;
1613 let place = &borrow.borrowed_place;
1614 let desc_place = self.describe_any_place(place.as_ref());
1615 match kind {
1616 hir::ClosureKind::Coroutine(_) => {
1617 BorrowUsePlaceCoroutine { place: desc_place, var_span, is_single_var: true }
1618 }
1619 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1620 BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: true }
1621 }
1622 }
1623 });
1624
1625 self.explain_why_borrow_contains_point(location, borrow, None)
1626 .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
1627 err
1628 }
1629
1630 pub(crate) fn report_conflicting_borrow(
1631 &self,
1632 location: Location,
1633 (place, span): (Place<'tcx>, Span),
1634 gen_borrow_kind: BorrowKind,
1635 issued_borrow: &BorrowData<'tcx>,
1636 ) -> Diag<'infcx> {
1637 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
1638 let issued_span = issued_spans.args_or_use();
1639
1640 let borrow_spans = self.borrow_spans(span, location);
1641 let span = borrow_spans.args_or_use();
1642
1643 let container_name = if issued_spans.for_coroutine() || borrow_spans.for_coroutine() {
1644 "coroutine"
1645 } else {
1646 "closure"
1647 };
1648
1649 let (desc_place, msg_place, msg_borrow, union_type_name) =
1650 self.describe_place_for_conflicting_borrow(place, issued_borrow.borrowed_place);
1651
1652 let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
1653 let second_borrow_desc = if explanation.is_explained() { "second " } else { "" };
1654
1655 let first_borrow_desc;
1657 let mut err = match (gen_borrow_kind, issued_borrow.kind) {
1658 (
1659 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1660 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1661 ) => {
1662 first_borrow_desc = "mutable ";
1663 let mut err = self.cannot_reborrow_already_borrowed(
1664 span,
1665 &desc_place,
1666 &msg_place,
1667 "immutable",
1668 issued_span,
1669 "it",
1670 "mutable",
1671 &msg_borrow,
1672 None,
1673 );
1674 self.suggest_slice_method_if_applicable(
1675 &mut err,
1676 place,
1677 issued_borrow.borrowed_place,
1678 span,
1679 issued_span,
1680 );
1681 err
1682 }
1683 (
1684 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1685 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1686 ) => {
1687 first_borrow_desc = "immutable ";
1688 let mut err = self.cannot_reborrow_already_borrowed(
1689 span,
1690 &desc_place,
1691 &msg_place,
1692 "mutable",
1693 issued_span,
1694 "it",
1695 "immutable",
1696 &msg_borrow,
1697 None,
1698 );
1699 self.suggest_slice_method_if_applicable(
1700 &mut err,
1701 place,
1702 issued_borrow.borrowed_place,
1703 span,
1704 issued_span,
1705 );
1706 self.suggest_binding_for_closure_capture_self(&mut err, &issued_spans);
1707 self.suggest_using_closure_argument_instead_of_capture(
1708 &mut err,
1709 issued_borrow.borrowed_place,
1710 &issued_spans,
1711 );
1712 err
1713 }
1714
1715 (
1716 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1717 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1718 ) => {
1719 first_borrow_desc = "first ";
1720 let mut err = self.cannot_mutably_borrow_multiply(
1721 span,
1722 &desc_place,
1723 &msg_place,
1724 issued_span,
1725 &msg_borrow,
1726 None,
1727 );
1728 self.suggest_slice_method_if_applicable(
1729 &mut err,
1730 place,
1731 issued_borrow.borrowed_place,
1732 span,
1733 issued_span,
1734 );
1735 self.suggest_using_closure_argument_instead_of_capture(
1736 &mut err,
1737 issued_borrow.borrowed_place,
1738 &issued_spans,
1739 );
1740 self.explain_iterator_advancement_in_for_loop_if_applicable(
1741 &mut err,
1742 span,
1743 &issued_spans,
1744 );
1745 err
1746 }
1747
1748 (
1749 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1750 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1751 ) => {
1752 first_borrow_desc = "first ";
1753 self.cannot_uniquely_borrow_by_two_closures(span, &desc_place, issued_span, None)
1754 }
1755
1756 (BorrowKind::Mut { .. }, BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
1757 if let Some(immutable_section_description) =
1758 self.classify_immutable_section(issued_borrow.assigned_place)
1759 {
1760 let mut err = self.cannot_mutate_in_immutable_section(
1761 span,
1762 issued_span,
1763 &desc_place,
1764 immutable_section_description,
1765 "mutably borrow",
1766 );
1767 borrow_spans.var_subdiag(
1768 &mut err,
1769 Some(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }),
1770 |kind, var_span| {
1771 use crate::session_diagnostics::CaptureVarCause::*;
1772 match kind {
1773 hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1774 place: desc_place,
1775 var_span,
1776 is_single_var: true,
1777 },
1778 hir::ClosureKind::Closure
1779 | hir::ClosureKind::CoroutineClosure(_) => BorrowUsePlaceClosure {
1780 place: desc_place,
1781 var_span,
1782 is_single_var: true,
1783 },
1784 }
1785 },
1786 );
1787 return err;
1788 } else {
1789 first_borrow_desc = "immutable ";
1790 self.cannot_reborrow_already_borrowed(
1791 span,
1792 &desc_place,
1793 &msg_place,
1794 "mutable",
1795 issued_span,
1796 "it",
1797 "immutable",
1798 &msg_borrow,
1799 None,
1800 )
1801 }
1802 }
1803
1804 (BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }, _) => {
1805 first_borrow_desc = "first ";
1806 self.cannot_uniquely_borrow_by_one_closure(
1807 span,
1808 container_name,
1809 &desc_place,
1810 "",
1811 issued_span,
1812 "it",
1813 "",
1814 None,
1815 )
1816 }
1817
1818 (
1819 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1820 BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1821 ) => {
1822 first_borrow_desc = "first ";
1823 self.cannot_reborrow_already_uniquely_borrowed(
1824 span,
1825 container_name,
1826 &desc_place,
1827 "",
1828 "immutable",
1829 issued_span,
1830 "",
1831 None,
1832 second_borrow_desc,
1833 )
1834 }
1835
1836 (BorrowKind::Mut { .. }, BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }) => {
1837 first_borrow_desc = "first ";
1838 self.cannot_reborrow_already_uniquely_borrowed(
1839 span,
1840 container_name,
1841 &desc_place,
1842 "",
1843 "mutable",
1844 issued_span,
1845 "",
1846 None,
1847 second_borrow_desc,
1848 )
1849 }
1850
1851 (
1852 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1853 BorrowKind::Shared | BorrowKind::Fake(_),
1854 )
1855 | (
1856 BorrowKind::Fake(FakeBorrowKind::Shallow),
1857 BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_),
1858 ) => {
1859 unreachable!()
1860 }
1861 };
1862 self.note_due_to_edition_2024_opaque_capture_rules(issued_borrow, &mut err);
1863
1864 if issued_spans == borrow_spans {
1865 borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
1866 use crate::session_diagnostics::CaptureVarCause::*;
1867 match kind {
1868 hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1869 place: desc_place,
1870 var_span,
1871 is_single_var: false,
1872 },
1873 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1874 BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: false }
1875 }
1876 }
1877 });
1878 } else {
1879 issued_spans.var_subdiag(&mut err, Some(issued_borrow.kind), |kind, var_span| {
1880 use crate::session_diagnostics::CaptureVarCause::*;
1881 let borrow_place = &issued_borrow.borrowed_place;
1882 let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
1883 match kind {
1884 hir::ClosureKind::Coroutine(_) => {
1885 FirstBorrowUsePlaceCoroutine { place: borrow_place_desc, var_span }
1886 }
1887 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1888 FirstBorrowUsePlaceClosure { place: borrow_place_desc, var_span }
1889 }
1890 }
1891 });
1892
1893 borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
1894 use crate::session_diagnostics::CaptureVarCause::*;
1895 match kind {
1896 hir::ClosureKind::Coroutine(_) => {
1897 SecondBorrowUsePlaceCoroutine { place: desc_place, var_span }
1898 }
1899 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1900 SecondBorrowUsePlaceClosure { place: desc_place, var_span }
1901 }
1902 }
1903 });
1904 }
1905
1906 if union_type_name != "" {
1907 err.note(format!(
1908 "{msg_place} is a field of the union `{union_type_name}`, so it overlaps the field {msg_borrow}",
1909 ));
1910 }
1911
1912 explanation.add_explanation_to_diagnostic(
1913 &self,
1914 &mut err,
1915 first_borrow_desc,
1916 None,
1917 Some((issued_span, span)),
1918 );
1919
1920 self.suggest_using_local_if_applicable(&mut err, location, issued_borrow, explanation);
1921 self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
1922
1923 err
1924 }
1925
1926 fn suggest_copy_for_type_in_cloned_ref(&self, err: &mut Diag<'infcx>, place: Place<'tcx>) {
1927 let tcx = self.infcx.tcx;
1928 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
1929
1930 struct FindUselessClone<'tcx> {
1931 tcx: TyCtxt<'tcx>,
1932 typeck_results: &'tcx ty::TypeckResults<'tcx>,
1933 clones: Vec<&'tcx hir::Expr<'tcx>>,
1934 }
1935 impl<'tcx> FindUselessClone<'tcx> {
1936 fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
1937 Self { tcx, typeck_results: tcx.typeck(def_id), clones: vec![] }
1938 }
1939 }
1940 impl<'tcx> Visitor<'tcx> for FindUselessClone<'tcx> {
1941 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1942 if let hir::ExprKind::MethodCall(..) = ex.kind
1943 && let Some(method_def_id) =
1944 self.typeck_results.type_dependent_def_id(ex.hir_id)
1945 && self.tcx.is_lang_item(self.tcx.parent(method_def_id), LangItem::Clone)
1946 {
1947 self.clones.push(ex);
1948 }
1949 hir::intravisit::walk_expr(self, ex);
1950 }
1951 }
1952
1953 let mut expr_finder = FindUselessClone::new(tcx, self.mir_def_id());
1954
1955 let body = tcx.hir_body(body_id).value;
1956 expr_finder.visit_expr(body);
1957
1958 struct Holds<'tcx> {
1959 ty: Ty<'tcx>,
1960 }
1961
1962 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for Holds<'tcx> {
1963 type Result = std::ops::ControlFlow<()>;
1964
1965 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1966 if t == self.ty {
1967 return ControlFlow::Break(());
1968 }
1969 t.super_visit_with(self)
1970 }
1971 }
1972
1973 let mut types_to_constrain = FxIndexSet::default();
1974
1975 let local_ty = self.body.local_decls[place.local].ty;
1976 let typeck_results = tcx.typeck(self.mir_def_id());
1977 let clone = tcx.require_lang_item(LangItem::Clone, body.span);
1978 for expr in expr_finder.clones {
1979 if let hir::ExprKind::MethodCall(_, rcvr, _, span) = expr.kind
1980 && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
1981 && let Some(ty) = typeck_results.node_type_opt(expr.hir_id)
1982 && rcvr_ty == ty
1983 && let ty::Ref(_, inner, _) = rcvr_ty.kind()
1984 && let inner = inner.peel_refs()
1985 && (Holds { ty: inner }).visit_ty(local_ty).is_break()
1986 && let None =
1987 self.infcx.type_implements_trait_shallow(clone, inner, self.infcx.param_env)
1988 {
1989 err.span_label(
1990 span,
1991 format!(
1992 "this call doesn't do anything, the result is still `{rcvr_ty}` \
1993 because `{inner}` doesn't implement `Clone`",
1994 ),
1995 );
1996 types_to_constrain.insert(inner);
1997 }
1998 }
1999 for ty in types_to_constrain {
2000 self.suggest_adding_bounds_or_derive(err, ty, clone, body.span);
2001 }
2002 }
2003
2004 pub(crate) fn suggest_adding_bounds_or_derive(
2005 &self,
2006 err: &mut Diag<'_>,
2007 ty: Ty<'tcx>,
2008 trait_def_id: DefId,
2009 span: Span,
2010 ) {
2011 self.suggest_adding_bounds(err, ty, trait_def_id, span);
2012 if let ty::Adt(..) = ty.kind() {
2013 let trait_ref =
2015 ty::Binder::dummy(ty::TraitRef::new(self.infcx.tcx, trait_def_id, [ty]));
2016 let obligation = Obligation::new(
2017 self.infcx.tcx,
2018 ObligationCause::dummy(),
2019 self.infcx.param_env,
2020 trait_ref,
2021 );
2022 self.infcx.err_ctxt().suggest_derive(
2023 &obligation,
2024 err,
2025 trait_ref.upcast(self.infcx.tcx),
2026 );
2027 }
2028 }
2029
2030 #[instrument(level = "debug", skip(self, err))]
2031 fn suggest_using_local_if_applicable(
2032 &self,
2033 err: &mut Diag<'_>,
2034 location: Location,
2035 issued_borrow: &BorrowData<'tcx>,
2036 explanation: BorrowExplanation<'tcx>,
2037 ) {
2038 let used_in_call = matches!(
2039 explanation,
2040 BorrowExplanation::UsedLater(
2041 _,
2042 LaterUseKind::Call | LaterUseKind::Other,
2043 _call_span,
2044 _
2045 )
2046 );
2047 if !used_in_call {
2048 debug!("not later used in call");
2049 return;
2050 }
2051 if matches!(
2052 self.body.local_decls[issued_borrow.borrowed_place.local].local_info(),
2053 LocalInfo::IfThenRescopeTemp { .. }
2054 ) {
2055 return;
2057 }
2058
2059 let use_span = if let BorrowExplanation::UsedLater(_, LaterUseKind::Other, use_span, _) =
2060 explanation
2061 {
2062 Some(use_span)
2063 } else {
2064 None
2065 };
2066
2067 let outer_call_loc =
2068 if let TwoPhaseActivation::ActivatedAt(loc) = issued_borrow.activation_location {
2069 loc
2070 } else {
2071 issued_borrow.reserve_location
2072 };
2073 let outer_call_stmt = self.body.stmt_at(outer_call_loc);
2074
2075 let inner_param_location = location;
2076 let Some(inner_param_stmt) = self.body.stmt_at(inner_param_location).left() else {
2077 debug!("`inner_param_location` {:?} is not for a statement", inner_param_location);
2078 return;
2079 };
2080 let Some(&inner_param) = inner_param_stmt.kind.as_assign().map(|(p, _)| p) else {
2081 debug!(
2082 "`inner_param_location` {:?} is not for an assignment: {:?}",
2083 inner_param_location, inner_param_stmt
2084 );
2085 return;
2086 };
2087 let inner_param_uses = find_all_local_uses::find(self.body, inner_param.local);
2088 let Some((inner_call_loc, inner_call_term)) =
2089 inner_param_uses.into_iter().find_map(|loc| {
2090 let Either::Right(term) = self.body.stmt_at(loc) else {
2091 debug!("{:?} is a statement, so it can't be a call", loc);
2092 return None;
2093 };
2094 let TerminatorKind::Call { args, .. } = &term.kind else {
2095 debug!("not a call: {:?}", term);
2096 return None;
2097 };
2098 debug!("checking call args for uses of inner_param: {:?}", args);
2099 args.iter()
2100 .map(|a| &a.node)
2101 .any(|a| a == &Operand::Move(inner_param))
2102 .then_some((loc, term))
2103 })
2104 else {
2105 debug!("no uses of inner_param found as a by-move call arg");
2106 return;
2107 };
2108 debug!("===> outer_call_loc = {:?}, inner_call_loc = {:?}", outer_call_loc, inner_call_loc);
2109
2110 let inner_call_span = inner_call_term.source_info.span;
2111 let outer_call_span = match use_span {
2112 Some(span) => span,
2113 None => outer_call_stmt.either(|s| s.source_info, |t| t.source_info).span,
2114 };
2115 if outer_call_span == inner_call_span || !outer_call_span.contains(inner_call_span) {
2116 debug!(
2119 "outer span {:?} does not strictly contain inner span {:?}",
2120 outer_call_span, inner_call_span
2121 );
2122 return;
2123 }
2124 err.span_help(
2125 inner_call_span,
2126 format!(
2127 "try adding a local storing this{}...",
2128 if use_span.is_some() { "" } else { " argument" }
2129 ),
2130 );
2131 err.span_help(
2132 outer_call_span,
2133 format!(
2134 "...and then using that local {}",
2135 if use_span.is_some() { "here" } else { "as the argument to this call" }
2136 ),
2137 );
2138 }
2139
2140 pub(crate) fn find_expr(&self, span: Span) -> Option<&'tcx hir::Expr<'tcx>> {
2141 let tcx = self.infcx.tcx;
2142 let body_id = tcx.hir_node(self.mir_hir_id()).body_id()?;
2143 let mut expr_finder = FindExprBySpan::new(span, tcx);
2144 expr_finder.visit_expr(tcx.hir_body(body_id).value);
2145 expr_finder.result
2146 }
2147
2148 fn suggest_slice_method_if_applicable(
2149 &self,
2150 err: &mut Diag<'_>,
2151 place: Place<'tcx>,
2152 borrowed_place: Place<'tcx>,
2153 span: Span,
2154 issued_span: Span,
2155 ) {
2156 let tcx = self.infcx.tcx;
2157
2158 let has_split_at_mut = |ty: Ty<'tcx>| {
2159 let ty = ty.peel_refs();
2160 match ty.kind() {
2161 ty::Array(..) | ty::Slice(..) => true,
2162 ty::Adt(def, _) if tcx.get_diagnostic_item(sym::Vec) == Some(def.did()) => true,
2163 _ if ty == tcx.types.str_ => true,
2164 _ => false,
2165 }
2166 };
2167 if let ([ProjectionElem::Index(index1)], [ProjectionElem::Index(index2)])
2168 | (
2169 [ProjectionElem::Deref, ProjectionElem::Index(index1)],
2170 [ProjectionElem::Deref, ProjectionElem::Index(index2)],
2171 ) = (&place.projection[..], &borrowed_place.projection[..])
2172 {
2173 let decl1 = &self.body.local_decls[*index1];
2174 let decl2 = &self.body.local_decls[*index2];
2175
2176 let mut note_default_suggestion = || {
2177 err.help(
2178 "consider using `.split_at_mut(position)` or similar method to obtain two \
2179 mutable non-overlapping sub-slices",
2180 )
2181 .help(
2182 "consider using `.swap(index_1, index_2)` to swap elements at the specified \
2183 indices",
2184 );
2185 };
2186
2187 let Some(index1) = self.find_expr(decl1.source_info.span) else {
2188 note_default_suggestion();
2189 return;
2190 };
2191
2192 let Some(index2) = self.find_expr(decl2.source_info.span) else {
2193 note_default_suggestion();
2194 return;
2195 };
2196
2197 let sm = tcx.sess.source_map();
2198
2199 let Ok(index1_str) = sm.span_to_snippet(index1.span) else {
2200 note_default_suggestion();
2201 return;
2202 };
2203
2204 let Ok(index2_str) = sm.span_to_snippet(index2.span) else {
2205 note_default_suggestion();
2206 return;
2207 };
2208
2209 let Some(object) = tcx.hir_parent_id_iter(index1.hir_id).find_map(|id| {
2210 if let hir::Node::Expr(expr) = tcx.hir_node(id)
2211 && let hir::ExprKind::Index(obj, ..) = expr.kind
2212 {
2213 Some(obj)
2214 } else {
2215 None
2216 }
2217 }) else {
2218 note_default_suggestion();
2219 return;
2220 };
2221
2222 let Ok(obj_str) = sm.span_to_snippet(object.span) else {
2223 note_default_suggestion();
2224 return;
2225 };
2226
2227 let Some(swap_call) = tcx.hir_parent_id_iter(object.hir_id).find_map(|id| {
2228 if let hir::Node::Expr(call) = tcx.hir_node(id)
2229 && let hir::ExprKind::Call(callee, ..) = call.kind
2230 && let hir::ExprKind::Path(qpath) = callee.kind
2231 && let hir::QPath::Resolved(None, res) = qpath
2232 && let hir::def::Res::Def(_, did) = res.res
2233 && tcx.is_diagnostic_item(sym::mem_swap, did)
2234 {
2235 Some(call)
2236 } else {
2237 None
2238 }
2239 }) else {
2240 let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2241 let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2242 let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2243 let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2244 if !idx1.equivalent_for_indexing(idx2) {
2245 err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2246 }
2247 return;
2248 };
2249
2250 err.span_suggestion(
2251 swap_call.span,
2252 "use `.swap()` to swap elements at the specified indices instead",
2253 format!("{obj_str}.swap({index1_str}, {index2_str})"),
2254 Applicability::MachineApplicable,
2255 );
2256 return;
2257 }
2258 let place_ty = PlaceRef::ty(&place.as_ref(), self.body, tcx).ty;
2259 let borrowed_place_ty = PlaceRef::ty(&borrowed_place.as_ref(), self.body, tcx).ty;
2260 if !has_split_at_mut(place_ty) && !has_split_at_mut(borrowed_place_ty) {
2261 return;
2263 }
2264 let Some(index1) = self.find_expr(span) else { return };
2265 let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2266 let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2267 let Some(index2) = self.find_expr(issued_span) else { return };
2268 let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2269 let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2270 if idx1.equivalent_for_indexing(idx2) {
2271 return;
2273 }
2274 err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2275 }
2276
2277 pub(crate) fn explain_iterator_advancement_in_for_loop_if_applicable(
2288 &self,
2289 err: &mut Diag<'_>,
2290 span: Span,
2291 issued_spans: &UseSpans<'tcx>,
2292 ) {
2293 let issue_span = issued_spans.args_or_use();
2294 let tcx = self.infcx.tcx;
2295
2296 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2297 let typeck_results = tcx.typeck(self.mir_def_id());
2298
2299 struct ExprFinder<'hir> {
2300 issue_span: Span,
2301 expr_span: Span,
2302 body_expr: Option<&'hir hir::Expr<'hir>>,
2303 loop_bind: Option<&'hir Ident>,
2304 loop_span: Option<Span>,
2305 head_span: Option<Span>,
2306 pat_span: Option<Span>,
2307 head: Option<&'hir hir::Expr<'hir>>,
2308 }
2309 impl<'hir> Visitor<'hir> for ExprFinder<'hir> {
2310 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2311 if let hir::ExprKind::Call(path, [arg]) = ex.kind
2324 && let hir::ExprKind::Path(hir::QPath::LangItem(LangItem::IntoIterIntoIter, _)) =
2325 path.kind
2326 && arg.span.contains(self.issue_span)
2327 {
2328 self.head = Some(arg);
2330 }
2331 if let hir::ExprKind::Loop(
2332 hir::Block { stmts: [stmt, ..], .. },
2333 _,
2334 hir::LoopSource::ForLoop,
2335 _,
2336 ) = ex.kind
2337 && let hir::StmtKind::Expr(hir::Expr {
2338 kind: hir::ExprKind::Match(call, [_, bind, ..], _),
2339 span: head_span,
2340 ..
2341 }) = stmt.kind
2342 && let hir::ExprKind::Call(path, _args) = call.kind
2343 && let hir::ExprKind::Path(hir::QPath::LangItem(LangItem::IteratorNext, _)) =
2344 path.kind
2345 && let hir::PatKind::Struct(path, [field, ..], _) = bind.pat.kind
2346 && let hir::QPath::LangItem(LangItem::OptionSome, pat_span) = path
2347 && call.span.contains(self.issue_span)
2348 {
2349 if let PatField {
2351 pat: hir::Pat { kind: hir::PatKind::Binding(_, _, ident, ..), .. },
2352 ..
2353 } = field
2354 {
2355 self.loop_bind = Some(ident);
2356 }
2357 self.head_span = Some(*head_span);
2358 self.pat_span = Some(pat_span);
2359 self.loop_span = Some(stmt.span);
2360 }
2361
2362 if let hir::ExprKind::MethodCall(body_call, recv, ..) = ex.kind
2363 && body_call.ident.name == sym::next
2364 && recv.span.source_equal(self.expr_span)
2365 {
2366 self.body_expr = Some(ex);
2367 }
2368
2369 hir::intravisit::walk_expr(self, ex);
2370 }
2371 }
2372 let mut finder = ExprFinder {
2373 expr_span: span,
2374 issue_span,
2375 loop_bind: None,
2376 body_expr: None,
2377 head_span: None,
2378 loop_span: None,
2379 pat_span: None,
2380 head: None,
2381 };
2382 finder.visit_expr(tcx.hir_body(body_id).value);
2383
2384 if let Some(body_expr) = finder.body_expr
2385 && let Some(loop_span) = finder.loop_span
2386 && let Some(def_id) = typeck_results.type_dependent_def_id(body_expr.hir_id)
2387 && let Some(trait_did) = tcx.trait_of_assoc(def_id)
2388 && tcx.is_diagnostic_item(sym::Iterator, trait_did)
2389 {
2390 if let Some(loop_bind) = finder.loop_bind {
2391 err.note(format!(
2392 "a for loop advances the iterator for you, the result is stored in `{}`",
2393 loop_bind.name,
2394 ));
2395 } else {
2396 err.note(
2397 "a for loop advances the iterator for you, the result is stored in its pattern",
2398 );
2399 }
2400 let msg = "if you want to call `next` on a iterator within the loop, consider using \
2401 `while let`";
2402 if let Some(head) = finder.head
2403 && let Some(pat_span) = finder.pat_span
2404 && loop_span.contains(body_expr.span)
2405 && loop_span.contains(head.span)
2406 {
2407 let sm = self.infcx.tcx.sess.source_map();
2408
2409 let mut sugg = vec![];
2410 if let hir::ExprKind::Path(hir::QPath::Resolved(None, _)) = head.kind {
2411 sugg.push((loop_span.with_hi(pat_span.lo()), "while let Some(".to_string()));
2415 sugg.push((
2416 pat_span.shrink_to_hi().with_hi(head.span.lo()),
2417 ") = ".to_string(),
2418 ));
2419 sugg.push((head.span.shrink_to_hi(), ".next()".to_string()));
2420 } else {
2421 let indent = if let Some(indent) = sm.indentation_before(loop_span) {
2423 format!("\n{indent}")
2424 } else {
2425 " ".to_string()
2426 };
2427 let Ok(head_str) = sm.span_to_snippet(head.span) else {
2428 err.help(msg);
2429 return;
2430 };
2431 sugg.push((
2432 loop_span.with_hi(pat_span.lo()),
2433 format!("let iter = {head_str};{indent}while let Some("),
2434 ));
2435 sugg.push((
2436 pat_span.shrink_to_hi().with_hi(head.span.hi()),
2437 ") = iter.next()".to_string(),
2438 ));
2439 if let hir::ExprKind::MethodCall(_, recv, ..) = body_expr.kind
2442 && let hir::ExprKind::Path(hir::QPath::Resolved(None, ..)) = recv.kind
2443 {
2444 sugg.push((recv.span, "iter".to_string()));
2448 }
2449 }
2450 err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2451 } else {
2452 err.help(msg);
2453 }
2454 }
2455 }
2456
2457 fn suggest_using_closure_argument_instead_of_capture(
2474 &self,
2475 err: &mut Diag<'_>,
2476 borrowed_place: Place<'tcx>,
2477 issued_spans: &UseSpans<'tcx>,
2478 ) {
2479 let &UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2480 let tcx = self.infcx.tcx;
2481
2482 let local = borrowed_place.local;
2484 let local_ty = self.body.local_decls[local].ty;
2485
2486 let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2488
2489 let body_expr = tcx.hir_body(body_id).value;
2490
2491 struct ClosureFinder<'hir> {
2492 tcx: TyCtxt<'hir>,
2493 borrow_span: Span,
2494 res: Option<(&'hir hir::Expr<'hir>, &'hir hir::Closure<'hir>)>,
2495 error_path: Option<(&'hir hir::Expr<'hir>, &'hir hir::QPath<'hir>)>,
2497 }
2498 impl<'hir> Visitor<'hir> for ClosureFinder<'hir> {
2499 type NestedFilter = OnlyBodies;
2500
2501 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
2502 self.tcx
2503 }
2504
2505 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2506 if let hir::ExprKind::Path(qpath) = &ex.kind
2507 && ex.span == self.borrow_span
2508 {
2509 self.error_path = Some((ex, qpath));
2510 }
2511
2512 if let hir::ExprKind::Closure(closure) = ex.kind
2513 && ex.span.contains(self.borrow_span)
2514 && self.res.as_ref().is_none_or(|(prev_res, _)| prev_res.span.contains(ex.span))
2518 {
2519 self.res = Some((ex, closure));
2520 }
2521
2522 hir::intravisit::walk_expr(self, ex);
2523 }
2524 }
2525
2526 let mut finder =
2528 ClosureFinder { tcx, borrow_span: capture_kind_span, res: None, error_path: None };
2529 finder.visit_expr(body_expr);
2530 let Some((closure_expr, closure)) = finder.res else { return };
2531
2532 let typeck_results = tcx.typeck(self.mir_def_id());
2533
2534 if let hir::Node::Expr(parent) = tcx.parent_hir_node(closure_expr.hir_id)
2537 && let hir::ExprKind::MethodCall(_, recv, ..) = parent.kind
2538 {
2539 let recv_ty = typeck_results.expr_ty(recv);
2540
2541 if recv_ty.peel_refs() != local_ty {
2542 return;
2543 }
2544 }
2545
2546 let ty::Closure(_, args) = typeck_results.expr_ty(closure_expr).kind() else {
2548 return;
2550 };
2551 let sig = args.as_closure().sig();
2552 let tupled_params = tcx.instantiate_bound_regions_with_erased(
2553 sig.inputs().iter().next().unwrap().map_bound(|&b| b),
2554 );
2555 let ty::Tuple(params) = tupled_params.kind() else { return };
2556
2557 let Some(this_name) = params.iter().zip(tcx.hir_body_param_idents(closure.body)).find_map(
2559 |(param_ty, ident)| {
2560 if param_ty.peel_refs() == local_ty { ident } else { None }
2562 },
2563 ) else {
2564 return;
2565 };
2566
2567 let spans;
2568 if let Some((_path_expr, qpath)) = finder.error_path
2569 && let hir::QPath::Resolved(_, path) = qpath
2570 && let hir::def::Res::Local(local_id) = path.res
2571 {
2572 struct VariableUseFinder {
2575 local_id: hir::HirId,
2576 spans: Vec<Span>,
2577 }
2578 impl<'hir> Visitor<'hir> for VariableUseFinder {
2579 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2580 if let hir::ExprKind::Path(qpath) = &ex.kind
2581 && let hir::QPath::Resolved(_, path) = qpath
2582 && let hir::def::Res::Local(local_id) = path.res
2583 && local_id == self.local_id
2584 {
2585 self.spans.push(ex.span);
2586 }
2587
2588 hir::intravisit::walk_expr(self, ex);
2589 }
2590 }
2591
2592 let mut finder = VariableUseFinder { local_id, spans: Vec::new() };
2593 finder.visit_expr(tcx.hir_body(closure.body).value);
2594
2595 spans = finder.spans;
2596 } else {
2597 spans = vec![capture_kind_span];
2598 }
2599
2600 err.multipart_suggestion(
2601 "try using the closure argument",
2602 iter::zip(spans, iter::repeat(this_name.to_string())).collect(),
2603 Applicability::MaybeIncorrect,
2604 );
2605 }
2606
2607 fn suggest_binding_for_closure_capture_self(
2608 &self,
2609 err: &mut Diag<'_>,
2610 issued_spans: &UseSpans<'tcx>,
2611 ) {
2612 let UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2613
2614 struct ExpressionFinder<'tcx> {
2615 capture_span: Span,
2616 closure_change_spans: Vec<Span>,
2617 closure_arg_span: Option<Span>,
2618 in_closure: bool,
2619 suggest_arg: String,
2620 tcx: TyCtxt<'tcx>,
2621 closure_local_id: Option<hir::HirId>,
2622 closure_call_changes: Vec<(Span, String)>,
2623 }
2624 impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
2625 fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
2626 if e.span.contains(self.capture_span)
2627 && let hir::ExprKind::Closure(&hir::Closure {
2628 kind: hir::ClosureKind::Closure,
2629 body,
2630 fn_arg_span,
2631 fn_decl: hir::FnDecl { inputs, .. },
2632 ..
2633 }) = e.kind
2634 && let hir::Node::Expr(body) = self.tcx.hir_node(body.hir_id)
2635 {
2636 self.suggest_arg = "this: &Self".to_string();
2637 if inputs.len() > 0 {
2638 self.suggest_arg.push_str(", ");
2639 }
2640 self.in_closure = true;
2641 self.closure_arg_span = fn_arg_span;
2642 self.visit_expr(body);
2643 self.in_closure = false;
2644 }
2645 if let hir::Expr { kind: hir::ExprKind::Path(path), .. } = e
2646 && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2647 && seg.ident.name == kw::SelfLower
2648 && self.in_closure
2649 {
2650 self.closure_change_spans.push(e.span);
2651 }
2652 hir::intravisit::walk_expr(self, e);
2653 }
2654
2655 fn visit_local(&mut self, local: &'hir hir::LetStmt<'hir>) {
2656 if let hir::Pat { kind: hir::PatKind::Binding(_, hir_id, _ident, _), .. } =
2657 local.pat
2658 && let Some(init) = local.init
2659 && let &hir::Expr {
2660 kind:
2661 hir::ExprKind::Closure(&hir::Closure {
2662 kind: hir::ClosureKind::Closure,
2663 ..
2664 }),
2665 ..
2666 } = init
2667 && init.span.contains(self.capture_span)
2668 {
2669 self.closure_local_id = Some(*hir_id);
2670 }
2671
2672 hir::intravisit::walk_local(self, local);
2673 }
2674
2675 fn visit_stmt(&mut self, s: &'hir hir::Stmt<'hir>) {
2676 if let hir::StmtKind::Semi(e) = s.kind
2677 && let hir::ExprKind::Call(
2678 hir::Expr { kind: hir::ExprKind::Path(path), .. },
2679 args,
2680 ) = e.kind
2681 && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2682 && let Res::Local(hir_id) = seg.res
2683 && Some(hir_id) == self.closure_local_id
2684 {
2685 let (span, arg_str) = if args.len() > 0 {
2686 (args[0].span.shrink_to_lo(), "self, ".to_string())
2687 } else {
2688 let span = e.span.trim_start(seg.ident.span).unwrap_or(e.span);
2689 (span, "(self)".to_string())
2690 };
2691 self.closure_call_changes.push((span, arg_str));
2692 }
2693 hir::intravisit::walk_stmt(self, s);
2694 }
2695 }
2696
2697 if let hir::Node::ImplItem(hir::ImplItem {
2698 kind: hir::ImplItemKind::Fn(_fn_sig, body_id),
2699 ..
2700 }) = self.infcx.tcx.hir_node(self.mir_hir_id())
2701 && let hir::Node::Expr(expr) = self.infcx.tcx.hir_node(body_id.hir_id)
2702 {
2703 let mut finder = ExpressionFinder {
2704 capture_span: *capture_kind_span,
2705 closure_change_spans: vec![],
2706 closure_arg_span: None,
2707 in_closure: false,
2708 suggest_arg: String::new(),
2709 closure_local_id: None,
2710 closure_call_changes: vec![],
2711 tcx: self.infcx.tcx,
2712 };
2713 finder.visit_expr(expr);
2714
2715 if finder.closure_change_spans.is_empty() || finder.closure_call_changes.is_empty() {
2716 return;
2717 }
2718
2719 let sm = self.infcx.tcx.sess.source_map();
2720 let sugg = finder
2721 .closure_arg_span
2722 .map(|span| (sm.next_point(span.shrink_to_lo()).shrink_to_hi(), finder.suggest_arg))
2723 .into_iter()
2724 .chain(
2725 finder.closure_change_spans.into_iter().map(|span| (span, "this".to_string())),
2726 )
2727 .chain(finder.closure_call_changes)
2728 .collect();
2729
2730 err.multipart_suggestion_verbose(
2731 "try explicitly passing `&Self` into the closure as an argument",
2732 sugg,
2733 Applicability::MachineApplicable,
2734 );
2735 }
2736 }
2737
2738 fn describe_place_for_conflicting_borrow(
2767 &self,
2768 first_borrowed_place: Place<'tcx>,
2769 second_borrowed_place: Place<'tcx>,
2770 ) -> (String, String, String, String) {
2771 let union_ty = |place_base| {
2774 let ty = PlaceRef::ty(&place_base, self.body, self.infcx.tcx).ty;
2777 ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
2778 };
2779
2780 Some(())
2784 .filter(|_| {
2785 first_borrowed_place != second_borrowed_place
2788 })
2789 .and_then(|_| {
2790 for (place_base, elem) in first_borrowed_place.iter_projections().rev() {
2795 match elem {
2796 ProjectionElem::Field(field, _) if union_ty(place_base).is_some() => {
2797 return Some((place_base, field));
2798 }
2799 _ => {}
2800 }
2801 }
2802 None
2803 })
2804 .and_then(|(target_base, target_field)| {
2805 for (place_base, elem) in second_borrowed_place.iter_projections().rev() {
2808 if let ProjectionElem::Field(field, _) = elem
2809 && let Some(union_ty) = union_ty(place_base)
2810 {
2811 if field != target_field && place_base == target_base {
2812 return Some((
2813 self.describe_any_place(place_base),
2814 self.describe_any_place(first_borrowed_place.as_ref()),
2815 self.describe_any_place(second_borrowed_place.as_ref()),
2816 union_ty.to_string(),
2817 ));
2818 }
2819 }
2820 }
2821 None
2822 })
2823 .unwrap_or_else(|| {
2824 (
2827 self.describe_any_place(first_borrowed_place.as_ref()),
2828 "".to_string(),
2829 "".to_string(),
2830 "".to_string(),
2831 )
2832 })
2833 }
2834
2835 #[instrument(level = "debug", skip(self))]
2842 pub(crate) fn report_borrowed_value_does_not_live_long_enough(
2843 &mut self,
2844 location: Location,
2845 borrow: &BorrowData<'tcx>,
2846 place_span: (Place<'tcx>, Span),
2847 kind: Option<WriteKind>,
2848 ) {
2849 let drop_span = place_span.1;
2850 let borrowed_local = borrow.borrowed_place.local;
2851
2852 let borrow_spans = self.retrieve_borrow_spans(borrow);
2853 let borrow_span = borrow_spans.var_or_use_path_span();
2854
2855 let proper_span = self.body.local_decls[borrowed_local].source_info.span;
2856
2857 if self.access_place_error_reported.contains(&(Place::from(borrowed_local), borrow_span)) {
2858 debug!(
2859 "suppressing access_place error when borrow doesn't live long enough for {:?}",
2860 borrow_span
2861 );
2862 return;
2863 }
2864
2865 self.access_place_error_reported.insert((Place::from(borrowed_local), borrow_span));
2866
2867 if self.body.local_decls[borrowed_local].is_ref_to_thread_local() {
2868 let err =
2869 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span);
2870 self.buffer_error(err);
2871 return;
2872 }
2873
2874 if let StorageDeadOrDrop::Destructor(dropped_ty) =
2875 self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
2876 {
2877 if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
2882 self.report_borrow_conflicts_with_destructor(
2883 location, borrow, place_span, kind, dropped_ty,
2884 );
2885 return;
2886 }
2887 }
2888
2889 let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
2890
2891 let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
2892 let explanation = self.explain_why_borrow_contains_point(location, borrow, kind_place);
2893
2894 debug!(?place_desc, ?explanation);
2895
2896 let mut err = match (place_desc, explanation) {
2897 (
2907 Some(name),
2908 BorrowExplanation::UsedLater(_, LaterUseKind::ClosureCapture, var_or_use_span, _),
2909 ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
2910 .report_escaping_closure_capture(
2911 borrow_spans,
2912 borrow_span,
2913 &RegionName {
2914 name: self.synthesize_region_name(),
2915 source: RegionNameSource::Static,
2916 },
2917 ConstraintCategory::CallArgument(None),
2918 var_or_use_span,
2919 &format!("`{name}`"),
2920 "block",
2921 ),
2922 (
2923 Some(name),
2924 BorrowExplanation::MustBeValidFor {
2925 category:
2926 category @ (ConstraintCategory::Return(_)
2927 | ConstraintCategory::CallArgument(_)
2928 | ConstraintCategory::OpaqueType),
2929 from_closure: false,
2930 ref region_name,
2931 span,
2932 ..
2933 },
2934 ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
2935 .report_escaping_closure_capture(
2936 borrow_spans,
2937 borrow_span,
2938 region_name,
2939 category,
2940 span,
2941 &format!("`{name}`"),
2942 "function",
2943 ),
2944 (
2945 name,
2946 BorrowExplanation::MustBeValidFor {
2947 category: ConstraintCategory::Assignment,
2948 from_closure: false,
2949 region_name:
2950 RegionName {
2951 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
2952 ..
2953 },
2954 span,
2955 ..
2956 },
2957 ) => self.report_escaping_data(borrow_span, &name, upvar_span, upvar_name, span),
2958 (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
2959 location,
2960 &name,
2961 borrow,
2962 drop_span,
2963 borrow_spans,
2964 explanation,
2965 ),
2966 (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
2967 location,
2968 borrow,
2969 drop_span,
2970 borrow_spans,
2971 proper_span,
2972 explanation,
2973 ),
2974 };
2975 self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
2976
2977 self.buffer_error(err);
2978 }
2979
2980 fn report_local_value_does_not_live_long_enough(
2981 &self,
2982 location: Location,
2983 name: &str,
2984 borrow: &BorrowData<'tcx>,
2985 drop_span: Span,
2986 borrow_spans: UseSpans<'tcx>,
2987 explanation: BorrowExplanation<'tcx>,
2988 ) -> Diag<'infcx> {
2989 debug!(
2990 "report_local_value_does_not_live_long_enough(\
2991 {:?}, {:?}, {:?}, {:?}, {:?}\
2992 )",
2993 location, name, borrow, drop_span, borrow_spans
2994 );
2995
2996 let borrow_span = borrow_spans.var_or_use_path_span();
2997 if let BorrowExplanation::MustBeValidFor {
2998 category,
2999 span,
3000 ref opt_place_desc,
3001 from_closure: false,
3002 ..
3003 } = explanation
3004 && let Err(diag) = self.try_report_cannot_return_reference_to_local(
3005 borrow,
3006 borrow_span,
3007 span,
3008 category,
3009 opt_place_desc.as_ref(),
3010 )
3011 {
3012 return diag;
3013 }
3014
3015 let name = format!("`{name}`");
3016
3017 let mut err = self.path_does_not_live_long_enough(borrow_span, &name);
3018
3019 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
3020 let region_name = annotation.emit(self, &mut err);
3021
3022 err.span_label(
3023 borrow_span,
3024 format!("{name} would have to be valid for `{region_name}`..."),
3025 );
3026
3027 err.span_label(
3028 drop_span,
3029 format!(
3030 "...but {name} will be dropped here, when the {} returns",
3031 self.infcx
3032 .tcx
3033 .opt_item_name(self.mir_def_id().to_def_id())
3034 .map(|name| format!("function `{name}`"))
3035 .unwrap_or_else(|| {
3036 match &self.infcx.tcx.def_kind(self.mir_def_id()) {
3037 DefKind::Closure
3038 if self
3039 .infcx
3040 .tcx
3041 .is_coroutine(self.mir_def_id().to_def_id()) =>
3042 {
3043 "enclosing coroutine"
3044 }
3045 DefKind::Closure => "enclosing closure",
3046 kind => bug!("expected closure or coroutine, found {:?}", kind),
3047 }
3048 .to_string()
3049 })
3050 ),
3051 );
3052
3053 err.note(
3054 "functions cannot return a borrow to data owned within the function's scope, \
3055 functions can only return borrows to data passed as arguments",
3056 );
3057 err.note(
3058 "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
3059 references-and-borrowing.html#dangling-references>",
3060 );
3061
3062 if let BorrowExplanation::MustBeValidFor { .. } = explanation {
3063 } else {
3064 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3065 }
3066 } else {
3067 err.span_label(borrow_span, "borrowed value does not live long enough");
3068 err.span_label(drop_span, format!("{name} dropped here while still borrowed"));
3069
3070 borrow_spans.args_subdiag(&mut err, |args_span| {
3071 crate::session_diagnostics::CaptureArgLabel::Capture {
3072 is_within: borrow_spans.for_coroutine(),
3073 args_span,
3074 }
3075 });
3076
3077 explanation.add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
3078 }
3079
3080 err
3081 }
3082
3083 fn report_borrow_conflicts_with_destructor(
3084 &mut self,
3085 location: Location,
3086 borrow: &BorrowData<'tcx>,
3087 (place, drop_span): (Place<'tcx>, Span),
3088 kind: Option<WriteKind>,
3089 dropped_ty: Ty<'tcx>,
3090 ) {
3091 debug!(
3092 "report_borrow_conflicts_with_destructor(\
3093 {:?}, {:?}, ({:?}, {:?}), {:?}\
3094 )",
3095 location, borrow, place, drop_span, kind,
3096 );
3097
3098 let borrow_spans = self.retrieve_borrow_spans(borrow);
3099 let borrow_span = borrow_spans.var_or_use();
3100
3101 let mut err = self.cannot_borrow_across_destructor(borrow_span);
3102
3103 let what_was_dropped = match self.describe_place(place.as_ref()) {
3104 Some(name) => format!("`{name}`"),
3105 None => String::from("temporary value"),
3106 };
3107
3108 let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
3109 Some(borrowed) => format!(
3110 "here, drop of {what_was_dropped} needs exclusive access to `{borrowed}`, \
3111 because the type `{dropped_ty}` implements the `Drop` trait"
3112 ),
3113 None => format!(
3114 "here is drop of {what_was_dropped}; whose type `{dropped_ty}` implements the `Drop` trait"
3115 ),
3116 };
3117 err.span_label(drop_span, label);
3118
3119 let explanation =
3121 self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
3122 match explanation {
3123 BorrowExplanation::UsedLater { .. }
3124 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3125 err.note("consider using a `let` binding to create a longer lived value");
3126 }
3127 _ => {}
3128 }
3129
3130 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3131
3132 self.buffer_error(err);
3133 }
3134
3135 fn report_thread_local_value_does_not_live_long_enough(
3136 &self,
3137 drop_span: Span,
3138 borrow_span: Span,
3139 ) -> Diag<'infcx> {
3140 debug!(
3141 "report_thread_local_value_does_not_live_long_enough(\
3142 {:?}, {:?}\
3143 )",
3144 drop_span, borrow_span
3145 );
3146
3147 let sm = self.infcx.tcx.sess.source_map();
3152 let end_of_function = if drop_span.is_empty()
3153 && let Ok(adjusted_span) = sm.span_extend_prev_while(drop_span, |c| c == '}')
3154 {
3155 adjusted_span
3156 } else {
3157 drop_span
3158 };
3159 self.thread_local_value_does_not_live_long_enough(borrow_span)
3160 .with_span_label(
3161 borrow_span,
3162 "thread-local variables cannot be borrowed beyond the end of the function",
3163 )
3164 .with_span_label(end_of_function, "end of enclosing function is here")
3165 }
3166
3167 #[instrument(level = "debug", skip(self))]
3168 fn report_temporary_value_does_not_live_long_enough(
3169 &self,
3170 location: Location,
3171 borrow: &BorrowData<'tcx>,
3172 drop_span: Span,
3173 borrow_spans: UseSpans<'tcx>,
3174 proper_span: Span,
3175 explanation: BorrowExplanation<'tcx>,
3176 ) -> Diag<'infcx> {
3177 if let BorrowExplanation::MustBeValidFor { category, span, from_closure: false, .. } =
3178 explanation
3179 {
3180 if let Err(diag) = self.try_report_cannot_return_reference_to_local(
3181 borrow,
3182 proper_span,
3183 span,
3184 category,
3185 None,
3186 ) {
3187 return diag;
3188 }
3189 }
3190
3191 let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
3192 err.span_label(proper_span, "creates a temporary value which is freed while still in use");
3193 err.span_label(drop_span, "temporary value is freed at the end of this statement");
3194
3195 match explanation {
3196 BorrowExplanation::UsedLater(..)
3197 | BorrowExplanation::UsedLaterInLoop(..)
3198 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3199 let sm = self.infcx.tcx.sess.source_map();
3201 let mut suggested = false;
3202 let msg = "consider using a `let` binding to create a longer lived value";
3203
3204 struct NestedStatementVisitor<'tcx> {
3213 span: Span,
3214 current: usize,
3215 found: usize,
3216 prop_expr: Option<&'tcx hir::Expr<'tcx>>,
3217 call: Option<&'tcx hir::Expr<'tcx>>,
3218 }
3219
3220 impl<'tcx> Visitor<'tcx> for NestedStatementVisitor<'tcx> {
3221 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
3222 self.current += 1;
3223 walk_block(self, block);
3224 self.current -= 1;
3225 }
3226 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
3227 if let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind {
3228 if self.span == rcvr.span.source_callsite() {
3229 self.call = Some(expr);
3230 }
3231 }
3232 if self.span == expr.span.source_callsite() {
3233 self.found = self.current;
3234 if self.prop_expr.is_none() {
3235 self.prop_expr = Some(expr);
3236 }
3237 }
3238 walk_expr(self, expr);
3239 }
3240 }
3241 let source_info = self.body.source_info(location);
3242 let proper_span = proper_span.source_callsite();
3243 if let Some(scope) = self.body.source_scopes.get(source_info.scope)
3244 && let ClearCrossCrate::Set(scope_data) = &scope.local_data
3245 && let Some(id) = self.infcx.tcx.hir_node(scope_data.lint_root).body_id()
3246 && let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir_body(id).value.kind
3247 {
3248 for stmt in block.stmts {
3249 let mut visitor = NestedStatementVisitor {
3250 span: proper_span,
3251 current: 0,
3252 found: 0,
3253 prop_expr: None,
3254 call: None,
3255 };
3256 visitor.visit_stmt(stmt);
3257
3258 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
3259 let expr_ty: Option<Ty<'_>> =
3260 visitor.prop_expr.map(|expr| typeck_results.expr_ty(expr).peel_refs());
3261
3262 if visitor.found == 0
3263 && stmt.span.contains(proper_span)
3264 && let Some(p) = sm.span_to_margin(stmt.span)
3265 && let Ok(s) = sm.span_to_snippet(proper_span)
3266 {
3267 if let Some(call) = visitor.call
3268 && let hir::ExprKind::MethodCall(path, _, [], _) = call.kind
3269 && path.ident.name == sym::iter
3270 && let Some(ty) = expr_ty
3271 {
3272 err.span_suggestion_verbose(
3273 path.ident.span,
3274 format!(
3275 "consider consuming the `{ty}` when turning it into an \
3276 `Iterator`",
3277 ),
3278 "into_iter",
3279 Applicability::MaybeIncorrect,
3280 );
3281 }
3282
3283 let mutability = if matches!(borrow.kind(), BorrowKind::Mut { .. }) {
3284 "mut "
3285 } else {
3286 ""
3287 };
3288
3289 let addition =
3290 format!("let {}binding = {};\n{}", mutability, s, " ".repeat(p));
3291 err.multipart_suggestion_verbose(
3292 msg,
3293 vec![
3294 (stmt.span.shrink_to_lo(), addition),
3295 (proper_span, "binding".to_string()),
3296 ],
3297 Applicability::MaybeIncorrect,
3298 );
3299
3300 suggested = true;
3301 break;
3302 }
3303 }
3304 }
3305 if !suggested {
3306 err.note(msg);
3307 }
3308 }
3309 _ => {}
3310 }
3311 explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3312
3313 borrow_spans.args_subdiag(&mut err, |args_span| {
3314 crate::session_diagnostics::CaptureArgLabel::Capture {
3315 is_within: borrow_spans.for_coroutine(),
3316 args_span,
3317 }
3318 });
3319
3320 err
3321 }
3322
3323 fn try_report_cannot_return_reference_to_local(
3324 &self,
3325 borrow: &BorrowData<'tcx>,
3326 borrow_span: Span,
3327 return_span: Span,
3328 category: ConstraintCategory<'tcx>,
3329 opt_place_desc: Option<&String>,
3330 ) -> Result<(), Diag<'infcx>> {
3331 let return_kind = match category {
3332 ConstraintCategory::Return(_) => "return",
3333 ConstraintCategory::Yield => "yield",
3334 _ => return Ok(()),
3335 };
3336
3337 let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
3339 "reference to"
3340 } else {
3341 "value referencing"
3342 };
3343
3344 let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
3345 let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
3346 match self.body.local_kind(local) {
3347 LocalKind::Temp if self.body.local_decls[local].is_user_variable() => {
3348 "local variable "
3349 }
3350 LocalKind::Arg
3351 if !self.upvars.is_empty() && local == ty::CAPTURE_STRUCT_LOCAL =>
3352 {
3353 "variable captured by `move` "
3354 }
3355 LocalKind::Arg => "function parameter ",
3356 LocalKind::ReturnPointer | LocalKind::Temp => {
3357 bug!("temporary or return pointer with a name")
3358 }
3359 }
3360 } else {
3361 "local data "
3362 };
3363 (format!("{local_kind}`{place_desc}`"), format!("`{place_desc}` is borrowed here"))
3364 } else {
3365 let local = borrow.borrowed_place.local;
3366 match self.body.local_kind(local) {
3367 LocalKind::Arg => (
3368 "function parameter".to_string(),
3369 "function parameter borrowed here".to_string(),
3370 ),
3371 LocalKind::Temp
3372 if self.body.local_decls[local].is_user_variable()
3373 && !self.body.local_decls[local]
3374 .source_info
3375 .span
3376 .in_external_macro(self.infcx.tcx.sess.source_map()) =>
3377 {
3378 ("local binding".to_string(), "local binding introduced here".to_string())
3379 }
3380 LocalKind::ReturnPointer | LocalKind::Temp => {
3381 ("temporary value".to_string(), "temporary value created here".to_string())
3382 }
3383 }
3384 };
3385
3386 let mut err = self.cannot_return_reference_to_local(
3387 return_span,
3388 return_kind,
3389 reference_desc,
3390 &place_desc,
3391 );
3392
3393 if return_span != borrow_span {
3394 err.span_label(borrow_span, note);
3395
3396 let tcx = self.infcx.tcx;
3397
3398 let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
3399
3400 if let Some(iter_trait) = tcx.get_diagnostic_item(sym::Iterator)
3402 && self
3403 .infcx
3404 .type_implements_trait(iter_trait, [return_ty], self.infcx.param_env)
3405 .must_apply_modulo_regions()
3406 {
3407 err.span_suggestion_hidden(
3408 return_span.shrink_to_hi(),
3409 "use `.collect()` to allocate the iterator",
3410 ".collect::<Vec<_>>()",
3411 Applicability::MaybeIncorrect,
3412 );
3413 }
3414 }
3415
3416 Err(err)
3417 }
3418
3419 #[instrument(level = "debug", skip(self))]
3420 fn report_escaping_closure_capture(
3421 &self,
3422 use_span: UseSpans<'tcx>,
3423 var_span: Span,
3424 fr_name: &RegionName,
3425 category: ConstraintCategory<'tcx>,
3426 constraint_span: Span,
3427 captured_var: &str,
3428 scope: &str,
3429 ) -> Diag<'infcx> {
3430 let tcx = self.infcx.tcx;
3431 let args_span = use_span.args_or_use();
3432
3433 let (sugg_span, suggestion) = match tcx.sess.source_map().span_to_snippet(args_span) {
3434 Ok(string) => {
3435 let coro_prefix = if let Some(sub) = string.strip_prefix("async") {
3436 let trimmed_sub = sub.trim_end();
3437 if trimmed_sub.ends_with("gen") {
3438 Some((trimmed_sub.len() + 5) as _)
3440 } else {
3441 Some(5)
3443 }
3444 } else if string.starts_with("gen") {
3445 Some(3)
3447 } else if string.starts_with("static") {
3448 Some(6)
3451 } else {
3452 None
3453 };
3454 if let Some(n) = coro_prefix {
3455 let pos = args_span.lo() + BytePos(n);
3456 (args_span.with_lo(pos).with_hi(pos), " move")
3457 } else {
3458 (args_span.shrink_to_lo(), "move ")
3459 }
3460 }
3461 Err(_) => (args_span, "move |<args>| <body>"),
3462 };
3463 let kind = match use_span.coroutine_kind() {
3464 Some(coroutine_kind) => match coroutine_kind {
3465 CoroutineKind::Desugared(CoroutineDesugaring::Gen, kind) => match kind {
3466 CoroutineSource::Block => "gen block",
3467 CoroutineSource::Closure => "gen closure",
3468 CoroutineSource::Fn => {
3469 bug!("gen block/closure expected, but gen function found.")
3470 }
3471 },
3472 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, kind) => match kind {
3473 CoroutineSource::Block => "async gen block",
3474 CoroutineSource::Closure => "async gen closure",
3475 CoroutineSource::Fn => {
3476 bug!("gen block/closure expected, but gen function found.")
3477 }
3478 },
3479 CoroutineKind::Desugared(CoroutineDesugaring::Async, async_kind) => {
3480 match async_kind {
3481 CoroutineSource::Block => "async block",
3482 CoroutineSource::Closure => "async closure",
3483 CoroutineSource::Fn => {
3484 bug!("async block/closure expected, but async function found.")
3485 }
3486 }
3487 }
3488 CoroutineKind::Coroutine(_) => "coroutine",
3489 },
3490 None => "closure",
3491 };
3492
3493 let mut err = self.cannot_capture_in_long_lived_closure(
3494 args_span,
3495 kind,
3496 captured_var,
3497 var_span,
3498 scope,
3499 );
3500 err.span_suggestion_verbose(
3501 sugg_span,
3502 format!(
3503 "to force the {kind} to take ownership of {captured_var} (and any \
3504 other referenced variables), use the `move` keyword"
3505 ),
3506 suggestion,
3507 Applicability::MachineApplicable,
3508 );
3509
3510 match category {
3511 ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
3512 let msg = format!("{kind} is returned here");
3513 err.span_note(constraint_span, msg);
3514 }
3515 ConstraintCategory::CallArgument(_) => {
3516 fr_name.highlight_region_name(&mut err);
3517 if matches!(
3518 use_span.coroutine_kind(),
3519 Some(CoroutineKind::Desugared(CoroutineDesugaring::Async, _))
3520 ) {
3521 err.note(
3522 "async blocks are not executed immediately and must either take a \
3523 reference or ownership of outside variables they use",
3524 );
3525 } else {
3526 let msg = format!("{scope} requires argument type to outlive `{fr_name}`");
3527 err.span_note(constraint_span, msg);
3528 }
3529 }
3530 _ => bug!(
3531 "report_escaping_closure_capture called with unexpected constraint \
3532 category: `{:?}`",
3533 category
3534 ),
3535 }
3536
3537 err
3538 }
3539
3540 fn report_escaping_data(
3541 &self,
3542 borrow_span: Span,
3543 name: &Option<String>,
3544 upvar_span: Span,
3545 upvar_name: Symbol,
3546 escape_span: Span,
3547 ) -> Diag<'infcx> {
3548 let tcx = self.infcx.tcx;
3549
3550 let escapes_from = tcx.def_descr(self.mir_def_id().to_def_id());
3551
3552 let mut err =
3553 borrowck_errors::borrowed_data_escapes_closure(tcx, escape_span, escapes_from);
3554
3555 err.span_label(
3556 upvar_span,
3557 format!("`{upvar_name}` declared here, outside of the {escapes_from} body"),
3558 );
3559
3560 err.span_label(borrow_span, format!("borrow is only valid in the {escapes_from} body"));
3561
3562 if let Some(name) = name {
3563 err.span_label(
3564 escape_span,
3565 format!("reference to `{name}` escapes the {escapes_from} body here"),
3566 );
3567 } else {
3568 err.span_label(escape_span, format!("reference escapes the {escapes_from} body here"));
3569 }
3570
3571 err
3572 }
3573
3574 fn get_moved_indexes(
3575 &self,
3576 location: Location,
3577 mpi: MovePathIndex,
3578 ) -> (Vec<MoveSite>, Vec<Location>) {
3579 fn predecessor_locations<'tcx>(
3580 body: &mir::Body<'tcx>,
3581 location: Location,
3582 ) -> impl Iterator<Item = Location> {
3583 if location.statement_index == 0 {
3584 let predecessors = body.basic_blocks.predecessors()[location.block].to_vec();
3585 Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb)))
3586 } else {
3587 Either::Right(std::iter::once(Location {
3588 statement_index: location.statement_index - 1,
3589 ..location
3590 }))
3591 }
3592 }
3593
3594 let mut mpis = vec![mpi];
3595 let move_paths = &self.move_data.move_paths;
3596 mpis.extend(move_paths[mpi].parents(move_paths).map(|(mpi, _)| mpi));
3597
3598 let mut stack = Vec::new();
3599 let mut back_edge_stack = Vec::new();
3600
3601 predecessor_locations(self.body, location).for_each(|predecessor| {
3602 if location.dominates(predecessor, self.dominators()) {
3603 back_edge_stack.push(predecessor)
3604 } else {
3605 stack.push(predecessor);
3606 }
3607 });
3608
3609 let mut reached_start = false;
3610
3611 let mut is_argument = false;
3613 for arg in self.body.args_iter() {
3614 if let Some(path) = self.move_data.rev_lookup.find_local(arg) {
3615 if mpis.contains(&path) {
3616 is_argument = true;
3617 }
3618 }
3619 }
3620
3621 let mut visited = FxIndexSet::default();
3622 let mut move_locations = FxIndexSet::default();
3623 let mut reinits = vec![];
3624 let mut result = vec![];
3625
3626 let mut dfs_iter = |result: &mut Vec<MoveSite>, location: Location, is_back_edge: bool| {
3627 debug!(
3628 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
3629 location, is_back_edge
3630 );
3631
3632 if !visited.insert(location) {
3633 return true;
3634 }
3635
3636 let stmt_kind =
3638 self.body[location.block].statements.get(location.statement_index).map(|s| &s.kind);
3639 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
3640 } else {
3644 for moi in &self.move_data.loc_map[location] {
3652 debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
3653 let path = self.move_data.moves[*moi].path;
3654 if mpis.contains(&path) {
3655 debug!(
3656 "report_use_of_moved_or_uninitialized: found {:?}",
3657 move_paths[path].place
3658 );
3659 result.push(MoveSite { moi: *moi, traversed_back_edge: is_back_edge });
3660 move_locations.insert(location);
3661
3662 return true;
3679 }
3680 }
3681 }
3682
3683 let mut any_match = false;
3685 for ii in &self.move_data.init_loc_map[location] {
3686 let init = self.move_data.inits[*ii];
3687 match init.kind {
3688 InitKind::Deep | InitKind::NonPanicPathOnly => {
3689 if mpis.contains(&init.path) {
3690 any_match = true;
3691 }
3692 }
3693 InitKind::Shallow => {
3694 if mpi == init.path {
3695 any_match = true;
3696 }
3697 }
3698 }
3699 }
3700 if any_match {
3701 reinits.push(location);
3702 return true;
3703 }
3704 false
3705 };
3706
3707 while let Some(location) = stack.pop() {
3708 if dfs_iter(&mut result, location, false) {
3709 continue;
3710 }
3711
3712 let mut has_predecessor = false;
3713 predecessor_locations(self.body, location).for_each(|predecessor| {
3714 if location.dominates(predecessor, self.dominators()) {
3715 back_edge_stack.push(predecessor)
3716 } else {
3717 stack.push(predecessor);
3718 }
3719 has_predecessor = true;
3720 });
3721
3722 if !has_predecessor {
3723 reached_start = true;
3724 }
3725 }
3726 if (is_argument || !reached_start) && result.is_empty() {
3727 while let Some(location) = back_edge_stack.pop() {
3734 if dfs_iter(&mut result, location, true) {
3735 continue;
3736 }
3737
3738 predecessor_locations(self.body, location)
3739 .for_each(|predecessor| back_edge_stack.push(predecessor));
3740 }
3741 }
3742
3743 let reinits_reachable = reinits
3745 .into_iter()
3746 .filter(|reinit| {
3747 let mut visited = FxIndexSet::default();
3748 let mut stack = vec![*reinit];
3749 while let Some(location) = stack.pop() {
3750 if !visited.insert(location) {
3751 continue;
3752 }
3753 if move_locations.contains(&location) {
3754 return true;
3755 }
3756 stack.extend(predecessor_locations(self.body, location));
3757 }
3758 false
3759 })
3760 .collect::<Vec<Location>>();
3761 (result, reinits_reachable)
3762 }
3763
3764 pub(crate) fn report_illegal_mutation_of_borrowed(
3765 &mut self,
3766 location: Location,
3767 (place, span): (Place<'tcx>, Span),
3768 loan: &BorrowData<'tcx>,
3769 ) {
3770 let loan_spans = self.retrieve_borrow_spans(loan);
3771 let loan_span = loan_spans.args_or_use();
3772
3773 let descr_place = self.describe_any_place(place.as_ref());
3774 if let BorrowKind::Fake(_) = loan.kind
3775 && let Some(section) = self.classify_immutable_section(loan.assigned_place)
3776 {
3777 let mut err = self.cannot_mutate_in_immutable_section(
3778 span,
3779 loan_span,
3780 &descr_place,
3781 section,
3782 "assign",
3783 );
3784
3785 loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3786 use crate::session_diagnostics::CaptureVarCause::*;
3787 match kind {
3788 hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3789 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3790 BorrowUseInClosure { var_span }
3791 }
3792 }
3793 });
3794
3795 self.buffer_error(err);
3796
3797 return;
3798 }
3799
3800 let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place);
3801 self.note_due_to_edition_2024_opaque_capture_rules(loan, &mut err);
3802
3803 loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3804 use crate::session_diagnostics::CaptureVarCause::*;
3805 match kind {
3806 hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3807 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3808 BorrowUseInClosure { var_span }
3809 }
3810 }
3811 });
3812
3813 self.explain_why_borrow_contains_point(location, loan, None)
3814 .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3815
3816 self.explain_deref_coercion(loan, &mut err);
3817
3818 self.buffer_error(err);
3819 }
3820
3821 fn explain_deref_coercion(&mut self, loan: &BorrowData<'tcx>, err: &mut Diag<'_>) {
3822 let tcx = self.infcx.tcx;
3823 if let Some(Terminator { kind: TerminatorKind::Call { call_source, fn_span, .. }, .. }) =
3824 &self.body[loan.reserve_location.block].terminator
3825 && let Some((method_did, method_args)) = mir::find_self_call(
3826 tcx,
3827 self.body,
3828 loan.assigned_place.local,
3829 loan.reserve_location.block,
3830 )
3831 && let CallKind::DerefCoercion { deref_target_span, deref_target_ty, .. } = call_kind(
3832 self.infcx.tcx,
3833 self.infcx.typing_env(self.infcx.param_env),
3834 method_did,
3835 method_args,
3836 *fn_span,
3837 call_source.from_hir_call(),
3838 self.infcx.tcx.fn_arg_idents(method_did)[0],
3839 )
3840 {
3841 err.note(format!("borrow occurs due to deref coercion to `{deref_target_ty}`"));
3842 if let Some(deref_target_span) = deref_target_span {
3843 err.span_note(deref_target_span, "deref defined here");
3844 }
3845 }
3846 }
3847
3848 pub(crate) fn report_illegal_reassignment(
3855 &mut self,
3856 (place, span): (Place<'tcx>, Span),
3857 assigned_span: Span,
3858 err_place: Place<'tcx>,
3859 ) {
3860 let (from_arg, local_decl) = match err_place.as_local() {
3861 Some(local) => {
3862 (self.body.local_kind(local) == LocalKind::Arg, Some(&self.body.local_decls[local]))
3863 }
3864 None => (false, None),
3865 };
3866
3867 let (place_description, assigned_span) = match local_decl {
3871 Some(LocalDecl {
3872 local_info:
3873 ClearCrossCrate::Set(
3874 box LocalInfo::User(BindingForm::Var(VarBindingForm {
3875 opt_match_place: None,
3876 ..
3877 }))
3878 | box LocalInfo::StaticRef { .. }
3879 | box LocalInfo::Boring,
3880 ),
3881 ..
3882 })
3883 | None => (self.describe_any_place(place.as_ref()), assigned_span),
3884 Some(decl) => (self.describe_any_place(err_place.as_ref()), decl.source_info.span),
3885 };
3886 let mut err = self.cannot_reassign_immutable(span, &place_description, from_arg);
3887 let msg = if from_arg {
3888 "cannot assign to immutable argument"
3889 } else {
3890 "cannot assign twice to immutable variable"
3891 };
3892 if span != assigned_span && !from_arg {
3893 err.span_label(assigned_span, format!("first assignment to {place_description}"));
3894 }
3895 if let Some(decl) = local_decl
3896 && decl.can_be_made_mutable()
3897 {
3898 err.span_suggestion_verbose(
3899 decl.source_info.span.shrink_to_lo(),
3900 "consider making this binding mutable",
3901 "mut ".to_string(),
3902 Applicability::MachineApplicable,
3903 );
3904 if !from_arg
3905 && matches!(
3906 decl.local_info(),
3907 LocalInfo::User(BindingForm::Var(VarBindingForm {
3908 opt_match_place: Some((Some(_), _)),
3909 ..
3910 }))
3911 )
3912 {
3913 err.span_suggestion_verbose(
3914 decl.source_info.span.shrink_to_lo(),
3915 "to modify the original value, take a borrow instead",
3916 "ref mut ".to_string(),
3917 Applicability::MaybeIncorrect,
3918 );
3919 }
3920 }
3921 err.span_label(span, msg);
3922 self.buffer_error(err);
3923 }
3924
3925 fn classify_drop_access_kind(&self, place: PlaceRef<'tcx>) -> StorageDeadOrDrop<'tcx> {
3926 let tcx = self.infcx.tcx;
3927 let (kind, _place_ty) = place.projection.iter().fold(
3928 (LocalStorageDead, PlaceTy::from_ty(self.body.local_decls[place.local].ty)),
3929 |(kind, place_ty), &elem| {
3930 (
3931 match elem {
3932 ProjectionElem::Deref => match kind {
3933 StorageDeadOrDrop::LocalStorageDead
3934 | StorageDeadOrDrop::BoxedStorageDead => {
3935 assert!(
3936 place_ty.ty.is_box(),
3937 "Drop of value behind a reference or raw pointer"
3938 );
3939 StorageDeadOrDrop::BoxedStorageDead
3940 }
3941 StorageDeadOrDrop::Destructor(_) => kind,
3942 },
3943 ProjectionElem::OpaqueCast { .. }
3944 | ProjectionElem::Field(..)
3945 | ProjectionElem::Downcast(..) => {
3946 match place_ty.ty.kind() {
3947 ty::Adt(def, _) if def.has_dtor(tcx) => {
3948 match kind {
3950 StorageDeadOrDrop::Destructor(_) => kind,
3951 StorageDeadOrDrop::LocalStorageDead
3952 | StorageDeadOrDrop::BoxedStorageDead => {
3953 StorageDeadOrDrop::Destructor(place_ty.ty)
3954 }
3955 }
3956 }
3957 _ => kind,
3958 }
3959 }
3960 ProjectionElem::ConstantIndex { .. }
3961 | ProjectionElem::Subslice { .. }
3962 | ProjectionElem::Subtype(_)
3963 | ProjectionElem::Index(_)
3964 | ProjectionElem::UnwrapUnsafeBinder(_) => kind,
3965 },
3966 place_ty.projection_ty(tcx, elem),
3967 )
3968 },
3969 );
3970 kind
3971 }
3972
3973 fn classify_immutable_section(&self, place: Place<'tcx>) -> Option<&'static str> {
3975 use rustc_middle::mir::visit::Visitor;
3976 struct FakeReadCauseFinder<'tcx> {
3977 place: Place<'tcx>,
3978 cause: Option<FakeReadCause>,
3979 }
3980 impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'tcx> {
3981 fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
3982 match statement {
3983 Statement { kind: StatementKind::FakeRead(box (cause, place)), .. }
3984 if *place == self.place =>
3985 {
3986 self.cause = Some(*cause);
3987 }
3988 _ => (),
3989 }
3990 }
3991 }
3992 let mut visitor = FakeReadCauseFinder { place, cause: None };
3993 visitor.visit_body(self.body);
3994 match visitor.cause {
3995 Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
3996 Some(FakeReadCause::ForIndex) => Some("indexing expression"),
3997 _ => None,
3998 }
3999 }
4000
4001 fn annotate_argument_and_return_for_borrow(
4004 &self,
4005 borrow: &BorrowData<'tcx>,
4006 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4007 let fallback = || {
4009 let is_closure = self.infcx.tcx.is_closure_like(self.mir_def_id().to_def_id());
4010 if is_closure {
4011 None
4012 } else {
4013 let ty = self.infcx.tcx.type_of(self.mir_def_id()).instantiate_identity();
4014 match ty.kind() {
4015 ty::FnDef(_, _) | ty::FnPtr(..) => self.annotate_fn_sig(
4016 self.mir_def_id(),
4017 self.infcx.tcx.fn_sig(self.mir_def_id()).instantiate_identity(),
4018 ),
4019 _ => None,
4020 }
4021 }
4022 };
4023
4024 let location = borrow.reserve_location;
4031 debug!("annotate_argument_and_return_for_borrow: location={:?}", location);
4032 if let Some(Statement { kind: StatementKind::Assign(box (reservation, _)), .. }) =
4033 &self.body[location.block].statements.get(location.statement_index)
4034 {
4035 debug!("annotate_argument_and_return_for_borrow: reservation={:?}", reservation);
4036 let mut target = match reservation.as_local() {
4038 Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
4039 _ => return None,
4040 };
4041
4042 let mut annotated_closure = None;
4045 for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
4046 debug!(
4047 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
4048 target, stmt
4049 );
4050 if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind
4051 && let Some(assigned_to) = place.as_local()
4052 {
4053 debug!(
4054 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
4055 rvalue={:?}",
4056 assigned_to, rvalue
4057 );
4058 if let Rvalue::Aggregate(box AggregateKind::Closure(def_id, args), operands) =
4060 rvalue
4061 {
4062 let def_id = def_id.expect_local();
4063 for operand in operands {
4064 let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4065 operand
4066 else {
4067 continue;
4068 };
4069 debug!(
4070 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4071 assigned_from
4072 );
4073
4074 let Some(assigned_from_local) = assigned_from.local_or_deref_local()
4076 else {
4077 continue;
4078 };
4079
4080 if assigned_from_local != target {
4081 continue;
4082 }
4083
4084 annotated_closure =
4088 self.annotate_fn_sig(def_id, args.as_closure().sig());
4089 debug!(
4090 "annotate_argument_and_return_for_borrow: \
4091 annotated_closure={:?} assigned_from_local={:?} \
4092 assigned_to={:?}",
4093 annotated_closure, assigned_from_local, assigned_to
4094 );
4095
4096 if assigned_to == mir::RETURN_PLACE {
4097 return annotated_closure;
4100 } else {
4101 target = assigned_to;
4103 }
4104 }
4105
4106 continue;
4109 }
4110
4111 let assigned_from = match rvalue {
4113 Rvalue::Ref(_, _, assigned_from) => assigned_from,
4114 Rvalue::Use(operand) => match operand {
4115 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
4116 assigned_from
4117 }
4118 _ => continue,
4119 },
4120 _ => continue,
4121 };
4122 debug!(
4123 "annotate_argument_and_return_for_borrow: \
4124 assigned_from={:?}",
4125 assigned_from,
4126 );
4127
4128 let Some(assigned_from_local) = assigned_from.local_or_deref_local() else {
4130 continue;
4131 };
4132 debug!(
4133 "annotate_argument_and_return_for_borrow: \
4134 assigned_from_local={:?}",
4135 assigned_from_local,
4136 );
4137
4138 if assigned_from_local != target {
4141 continue;
4142 }
4143
4144 debug!(
4147 "annotate_argument_and_return_for_borrow: \
4148 assigned_from_local={:?} assigned_to={:?}",
4149 assigned_from_local, assigned_to
4150 );
4151 if assigned_to == mir::RETURN_PLACE {
4152 return annotated_closure.or_else(fallback);
4155 }
4156
4157 target = assigned_to;
4160 }
4161 }
4162
4163 let terminator = &self.body[location.block].terminator();
4165 debug!(
4166 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
4167 target, terminator
4168 );
4169 if let TerminatorKind::Call { destination, target: Some(_), args, .. } =
4170 &terminator.kind
4171 && let Some(assigned_to) = destination.as_local()
4172 {
4173 debug!(
4174 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
4175 assigned_to, args
4176 );
4177 for operand in args {
4178 let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4179 &operand.node
4180 else {
4181 continue;
4182 };
4183 debug!(
4184 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4185 assigned_from,
4186 );
4187
4188 if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
4189 debug!(
4190 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
4191 assigned_from_local,
4192 );
4193
4194 if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
4195 return annotated_closure.or_else(fallback);
4196 }
4197 }
4198 }
4199 }
4200 }
4201
4202 debug!("annotate_argument_and_return_for_borrow: none found");
4205 None
4206 }
4207
4208 fn annotate_fn_sig(
4211 &self,
4212 did: LocalDefId,
4213 sig: ty::PolyFnSig<'tcx>,
4214 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4215 debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
4216 let is_closure = self.infcx.tcx.is_closure_like(did.to_def_id());
4217 let fn_hir_id = self.infcx.tcx.local_def_id_to_hir_id(did);
4218 let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(fn_hir_id)?;
4219
4220 let return_ty = sig.output();
4243 match return_ty.skip_binder().kind() {
4244 ty::Ref(return_region, _, _)
4245 if return_region.is_named(self.infcx.tcx) && !is_closure =>
4246 {
4247 let mut arguments = Vec::new();
4250 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
4251 if let ty::Ref(argument_region, _, _) = argument.kind()
4252 && argument_region == return_region
4253 {
4254 match &fn_decl.inputs[index].kind {
4258 hir::TyKind::Ref(lifetime, _) => {
4259 arguments.push((*argument, lifetime.ident.span));
4262 }
4263 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
4265 if let Res::SelfTyAlias { alias_to, .. } = path.res
4266 && let Some(alias_to) = alias_to.as_local()
4267 && let hir::Impl { self_ty, .. } = self
4268 .infcx
4269 .tcx
4270 .hir_node_by_def_id(alias_to)
4271 .expect_item()
4272 .expect_impl()
4273 && let hir::TyKind::Ref(lifetime, _) = self_ty.kind
4274 {
4275 arguments.push((*argument, lifetime.ident.span));
4276 }
4277 }
4278 _ => {
4279 }
4281 }
4282 }
4283 }
4284
4285 if arguments.is_empty() {
4287 return None;
4288 }
4289
4290 let return_ty = sig.output().skip_binder();
4293 let mut return_span = fn_decl.output.span();
4294 if let hir::FnRetTy::Return(ty) = &fn_decl.output
4295 && let hir::TyKind::Ref(lifetime, _) = ty.kind
4296 {
4297 return_span = lifetime.ident.span;
4298 }
4299
4300 Some(AnnotatedBorrowFnSignature::NamedFunction {
4301 arguments,
4302 return_ty,
4303 return_span,
4304 })
4305 }
4306 ty::Ref(_, _, _) if is_closure => {
4307 let argument_span = fn_decl.inputs.first()?.span;
4311 let argument_ty = sig.inputs().skip_binder().first()?;
4312
4313 if let ty::Tuple(elems) = argument_ty.kind() {
4316 let &argument_ty = elems.first()?;
4317 if let ty::Ref(_, _, _) = argument_ty.kind() {
4318 return Some(AnnotatedBorrowFnSignature::Closure {
4319 argument_ty,
4320 argument_span,
4321 });
4322 }
4323 }
4324
4325 None
4326 }
4327 ty::Ref(_, _, _) => {
4328 let argument_span = fn_decl.inputs.first()?.span;
4331 let argument_ty = *sig.inputs().skip_binder().first()?;
4332
4333 let return_span = fn_decl.output.span();
4334 let return_ty = sig.output().skip_binder();
4335
4336 match argument_ty.kind() {
4338 ty::Ref(_, _, _) => {}
4339 _ => return None,
4340 }
4341
4342 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
4343 argument_ty,
4344 argument_span,
4345 return_ty,
4346 return_span,
4347 })
4348 }
4349 _ => {
4350 None
4353 }
4354 }
4355 }
4356}
4357
4358#[derive(Debug)]
4359enum AnnotatedBorrowFnSignature<'tcx> {
4360 NamedFunction {
4361 arguments: Vec<(Ty<'tcx>, Span)>,
4362 return_ty: Ty<'tcx>,
4363 return_span: Span,
4364 },
4365 AnonymousFunction {
4366 argument_ty: Ty<'tcx>,
4367 argument_span: Span,
4368 return_ty: Ty<'tcx>,
4369 return_span: Span,
4370 },
4371 Closure {
4372 argument_ty: Ty<'tcx>,
4373 argument_span: Span,
4374 },
4375}
4376
4377impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
4378 pub(crate) fn emit(&self, cx: &MirBorrowckCtxt<'_, '_, 'tcx>, diag: &mut Diag<'_>) -> String {
4381 match self {
4382 &AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
4383 diag.span_label(
4384 argument_span,
4385 format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
4386 );
4387
4388 cx.get_region_name_for_ty(argument_ty, 0)
4389 }
4390 &AnnotatedBorrowFnSignature::AnonymousFunction {
4391 argument_ty,
4392 argument_span,
4393 return_ty,
4394 return_span,
4395 } => {
4396 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
4397 diag.span_label(argument_span, format!("has type `{argument_ty_name}`"));
4398
4399 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
4400 let types_equal = return_ty_name == argument_ty_name;
4401 diag.span_label(
4402 return_span,
4403 format!(
4404 "{}has type `{}`",
4405 if types_equal { "also " } else { "" },
4406 return_ty_name,
4407 ),
4408 );
4409
4410 diag.note(
4411 "argument and return type have the same lifetime due to lifetime elision rules",
4412 );
4413 diag.note(
4414 "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
4415 lifetime-syntax.html#lifetime-elision>",
4416 );
4417
4418 cx.get_region_name_for_ty(return_ty, 0)
4419 }
4420 AnnotatedBorrowFnSignature::NamedFunction { arguments, return_ty, return_span } => {
4421 let region_name = cx.get_region_name_for_ty(*return_ty, 0);
4423 for (_, argument_span) in arguments {
4424 diag.span_label(*argument_span, format!("has lifetime `{region_name}`"));
4425 }
4426
4427 diag.span_label(*return_span, format!("also has lifetime `{region_name}`",));
4428
4429 diag.help(format!(
4430 "use data from the highlighted arguments which match the `{region_name}` lifetime of \
4431 the return type",
4432 ));
4433
4434 region_name
4435 }
4436 }
4437 }
4438}
4439
4440struct ReferencedStatementsVisitor<'a>(&'a [Span]);
4442
4443impl<'v> Visitor<'v> for ReferencedStatementsVisitor<'_> {
4444 type Result = ControlFlow<()>;
4445 fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) -> Self::Result {
4446 match s.kind {
4447 hir::StmtKind::Semi(expr) if self.0.contains(&expr.span) => ControlFlow::Break(()),
4448 _ => ControlFlow::Continue(()),
4449 }
4450 }
4451}
4452
4453struct BreakFinder {
4457 found_breaks: Vec<(hir::Destination, Span)>,
4458 found_continues: Vec<(hir::Destination, Span)>,
4459}
4460impl<'hir> Visitor<'hir> for BreakFinder {
4461 fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
4462 match ex.kind {
4463 hir::ExprKind::Break(destination, _) => {
4464 self.found_breaks.push((destination, ex.span));
4465 }
4466 hir::ExprKind::Continue(destination) => {
4467 self.found_continues.push((destination, ex.span));
4468 }
4469 _ => {}
4470 }
4471 hir::intravisit::walk_expr(self, ex);
4472 }
4473}
4474
4475struct ConditionVisitor<'tcx> {
4478 tcx: TyCtxt<'tcx>,
4479 spans: Vec<Span>,
4480 name: String,
4481 errors: Vec<(Span, String)>,
4482}
4483
4484impl<'v, 'tcx> Visitor<'v> for ConditionVisitor<'tcx> {
4485 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
4486 match ex.kind {
4487 hir::ExprKind::If(cond, body, None) => {
4488 if ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break() {
4491 self.errors.push((
4492 cond.span,
4493 format!(
4494 "if this `if` condition is `false`, {} is not initialized",
4495 self.name,
4496 ),
4497 ));
4498 self.errors.push((
4499 ex.span.shrink_to_hi(),
4500 format!("an `else` arm might be missing here, initializing {}", self.name),
4501 ));
4502 }
4503 }
4504 hir::ExprKind::If(cond, body, Some(other)) => {
4505 let a = ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break();
4508 let b = ReferencedStatementsVisitor(&self.spans).visit_expr(other).is_break();
4509 match (a, b) {
4510 (true, true) | (false, false) => {}
4511 (true, false) => {
4512 if other.span.is_desugaring(DesugaringKind::WhileLoop) {
4513 self.errors.push((
4514 cond.span,
4515 format!(
4516 "if this condition isn't met and the `while` loop runs 0 \
4517 times, {} is not initialized",
4518 self.name
4519 ),
4520 ));
4521 } else {
4522 self.errors.push((
4523 body.span.shrink_to_hi().until(other.span),
4524 format!(
4525 "if the `if` condition is `false` and this `else` arm is \
4526 executed, {} is not initialized",
4527 self.name
4528 ),
4529 ));
4530 }
4531 }
4532 (false, true) => {
4533 self.errors.push((
4534 cond.span,
4535 format!(
4536 "if this condition is `true`, {} is not initialized",
4537 self.name
4538 ),
4539 ));
4540 }
4541 }
4542 }
4543 hir::ExprKind::Match(e, arms, loop_desugar) => {
4544 let results: Vec<bool> = arms
4547 .iter()
4548 .map(|arm| ReferencedStatementsVisitor(&self.spans).visit_arm(arm).is_break())
4549 .collect();
4550 if results.iter().any(|x| *x) && !results.iter().all(|x| *x) {
4551 for (arm, seen) in arms.iter().zip(results) {
4552 if !seen {
4553 if loop_desugar == hir::MatchSource::ForLoopDesugar {
4554 self.errors.push((
4555 e.span,
4556 format!(
4557 "if the `for` loop runs 0 times, {} is not initialized",
4558 self.name
4559 ),
4560 ));
4561 } else if let Some(guard) = &arm.guard {
4562 if matches!(
4563 self.tcx.hir_node(arm.body.hir_id),
4564 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4565 ) {
4566 continue;
4567 }
4568 self.errors.push((
4569 arm.pat.span.to(guard.span),
4570 format!(
4571 "if this pattern and condition are matched, {} is not \
4572 initialized",
4573 self.name
4574 ),
4575 ));
4576 } else {
4577 if matches!(
4578 self.tcx.hir_node(arm.body.hir_id),
4579 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4580 ) {
4581 continue;
4582 }
4583 self.errors.push((
4584 arm.pat.span,
4585 format!(
4586 "if this pattern is matched, {} is not initialized",
4587 self.name
4588 ),
4589 ));
4590 }
4591 }
4592 }
4593 }
4594 }
4595 _ => {}
4600 }
4601 walk_expr(self, ex);
4602 }
4603}