]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_borrowck/src/diagnostics/mod.rs
New upstream version 1.74.1+dfsg1
[rustc.git] / compiler / rustc_borrowck / src / diagnostics / mod.rs
1 //! Borrow checker diagnostics.
2
3 use crate::session_diagnostics::{
4 CaptureArgLabel, CaptureReasonLabel, CaptureReasonNote, CaptureReasonSuggest, CaptureVarCause,
5 CaptureVarKind, CaptureVarPathUseCause, OnClosureNote,
6 };
7 use itertools::Itertools;
8 use rustc_errors::{Applicability, Diagnostic};
9 use rustc_hir as hir;
10 use rustc_hir::def::{CtorKind, Namespace};
11 use rustc_hir::GeneratorKind;
12 use rustc_index::IndexSlice;
13 use rustc_infer::infer::LateBoundRegionConversionTime;
14 use rustc_middle::mir::tcx::PlaceTy;
15 use rustc_middle::mir::{
16 AggregateKind, CallSource, ConstOperand, FakeReadCause, Local, LocalInfo, LocalKind, Location,
17 Operand, Place, PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator,
18 TerminatorKind,
19 };
20 use rustc_middle::ty::print::Print;
21 use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
22 use rustc_middle::util::{call_kind, CallDesugaringKind};
23 use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult};
24 use rustc_span::def_id::LocalDefId;
25 use rustc_span::{symbol::sym, Span, Symbol, DUMMY_SP};
26 use rustc_target::abi::{FieldIdx, VariantIdx};
27 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
28 use rustc_trait_selection::traits::{
29 type_known_to_meet_bound_modulo_regions, Obligation, ObligationCause,
30 };
31
32 use super::borrow_set::BorrowData;
33 use super::MirBorrowckCtxt;
34
35 mod find_all_local_uses;
36 mod find_use;
37 mod outlives_suggestion;
38 mod region_name;
39 mod var_name;
40
41 mod bound_region_errors;
42 mod conflict_errors;
43 mod explain_borrow;
44 mod move_errors;
45 mod mutability_errors;
46 mod region_errors;
47
48 pub(crate) use bound_region_errors::{ToUniverseInfo, UniverseInfo};
49 pub(crate) use mutability_errors::AccessKind;
50 pub(crate) use outlives_suggestion::OutlivesSuggestionBuilder;
51 pub(crate) use region_errors::{ErrorConstraintInfo, RegionErrorKind, RegionErrors};
52 pub(crate) use region_name::{RegionName, RegionNameSource};
53 pub(crate) use rustc_middle::util::CallKind;
54
55 pub(super) struct DescribePlaceOpt {
56 pub including_downcast: bool,
57
58 /// Enable/Disable tuple fields.
59 /// For example `x` tuple. if it's `true` `x.0`. Otherwise `x`
60 pub including_tuple_field: bool,
61 }
62
63 pub(super) struct IncludingTupleField(pub(super) bool);
64
65 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
66 /// Adds a suggestion when a closure is invoked twice with a moved variable or when a closure
67 /// is moved after being invoked.
68 ///
69 /// ```text
70 /// note: closure cannot be invoked more than once because it moves the variable `dict` out of
71 /// its environment
72 /// --> $DIR/issue-42065.rs:16:29
73 /// |
74 /// LL | for (key, value) in dict {
75 /// | ^^^^
76 /// ```
77 pub(super) fn add_moved_or_invoked_closure_note(
78 &self,
79 location: Location,
80 place: PlaceRef<'tcx>,
81 diag: &mut Diagnostic,
82 ) -> bool {
83 debug!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location, place);
84 let mut target = place.local_or_deref_local();
85 for stmt in &self.body[location.block].statements[location.statement_index..] {
86 debug!("add_moved_or_invoked_closure_note: stmt={:?} target={:?}", stmt, target);
87 if let StatementKind::Assign(box (into, Rvalue::Use(from))) = &stmt.kind {
88 debug!("add_fnonce_closure_note: into={:?} from={:?}", into, from);
89 match from {
90 Operand::Copy(place) | Operand::Move(place)
91 if target == place.local_or_deref_local() =>
92 {
93 target = into.local_or_deref_local()
94 }
95 _ => {}
96 }
97 }
98 }
99
100 // Check if we are attempting to call a closure after it has been invoked.
101 let terminator = self.body[location.block].terminator();
102 debug!("add_moved_or_invoked_closure_note: terminator={:?}", terminator);
103 if let TerminatorKind::Call {
104 func: Operand::Constant(box ConstOperand { const_, .. }),
105 args,
106 ..
107 } = &terminator.kind
108 {
109 if let ty::FnDef(id, _) = *const_.ty().kind() {
110 debug!("add_moved_or_invoked_closure_note: id={:?}", id);
111 if Some(self.infcx.tcx.parent(id)) == self.infcx.tcx.lang_items().fn_once_trait() {
112 let closure = match args.first() {
113 Some(Operand::Copy(place) | Operand::Move(place))
114 if target == place.local_or_deref_local() =>
115 {
116 place.local_or_deref_local().unwrap()
117 }
118 _ => return false,
119 };
120
121 debug!("add_moved_or_invoked_closure_note: closure={:?}", closure);
122 if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() {
123 let did = did.expect_local();
124 if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) {
125 diag.eager_subdiagnostic(
126 &self.infcx.tcx.sess.parse_sess.span_diagnostic,
127 OnClosureNote::InvokedTwice {
128 place_name: &ty::place_to_string_for_capture(
129 self.infcx.tcx,
130 hir_place,
131 ),
132 span: *span,
133 },
134 );
135 return true;
136 }
137 }
138 }
139 }
140 }
141
142 // Check if we are just moving a closure after it has been invoked.
143 if let Some(target) = target {
144 if let ty::Closure(did, _) = self.body.local_decls[target].ty.kind() {
145 let did = did.expect_local();
146 if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) {
147 diag.eager_subdiagnostic(
148 &self.infcx.tcx.sess.parse_sess.span_diagnostic,
149 OnClosureNote::MovedTwice {
150 place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place),
151 span: *span,
152 },
153 );
154 return true;
155 }
156 }
157 }
158 false
159 }
160
161 /// End-user visible description of `place` if one can be found.
162 /// If the place is a temporary for instance, `"value"` will be returned.
163 pub(super) fn describe_any_place(&self, place_ref: PlaceRef<'tcx>) -> String {
164 match self.describe_place(place_ref) {
165 Some(mut descr) => {
166 // Surround descr with `backticks`.
167 descr.reserve(2);
168 descr.insert(0, '`');
169 descr.push('`');
170 descr
171 }
172 None => "value".to_string(),
173 }
174 }
175
176 /// End-user visible description of `place` if one can be found.
177 /// If the place is a temporary for instance, `None` will be returned.
178 pub(super) fn describe_place(&self, place_ref: PlaceRef<'tcx>) -> Option<String> {
179 self.describe_place_with_options(
180 place_ref,
181 DescribePlaceOpt { including_downcast: false, including_tuple_field: true },
182 )
183 }
184
185 /// End-user visible description of `place` if one can be found. If the place is a temporary
186 /// for instance, `None` will be returned.
187 /// `IncludingDowncast` parameter makes the function return `None` if `ProjectionElem` is
188 /// `Downcast` and `IncludingDowncast` is true
189 pub(super) fn describe_place_with_options(
190 &self,
191 place: PlaceRef<'tcx>,
192 opt: DescribePlaceOpt,
193 ) -> Option<String> {
194 let local = place.local;
195 let mut autoderef_index = None;
196 let mut buf = String::new();
197 let mut ok = self.append_local_to_string(local, &mut buf);
198
199 for (index, elem) in place.projection.into_iter().enumerate() {
200 match elem {
201 ProjectionElem::Deref => {
202 if index == 0 {
203 if self.body.local_decls[local].is_ref_for_guard() {
204 continue;
205 }
206 if let LocalInfo::StaticRef { def_id, .. } =
207 *self.body.local_decls[local].local_info()
208 {
209 buf.push_str(self.infcx.tcx.item_name(def_id).as_str());
210 ok = Ok(());
211 continue;
212 }
213 }
214 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
215 local,
216 projection: place.projection.split_at(index + 1).0,
217 }) {
218 let var_index = field.index();
219 buf = self.upvars[var_index].place.to_string(self.infcx.tcx);
220 ok = Ok(());
221 if !self.upvars[var_index].by_ref {
222 buf.insert(0, '*');
223 }
224 } else {
225 if autoderef_index.is_none() {
226 autoderef_index =
227 match place.projection.into_iter().rev().find_position(|elem| {
228 !matches!(
229 elem,
230 ProjectionElem::Deref | ProjectionElem::Downcast(..)
231 )
232 }) {
233 Some((index, _)) => Some(place.projection.len() - index),
234 None => Some(0),
235 };
236 }
237 if index >= autoderef_index.unwrap() {
238 buf.insert(0, '*');
239 }
240 }
241 }
242 ProjectionElem::Downcast(..) if opt.including_downcast => return None,
243 ProjectionElem::Downcast(..) => (),
244 ProjectionElem::OpaqueCast(..) => (),
245 ProjectionElem::Subtype(..) => (),
246 ProjectionElem::Field(field, _ty) => {
247 // FIXME(project-rfc_2229#36): print capture precisely here.
248 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
249 local,
250 projection: place.projection.split_at(index + 1).0,
251 }) {
252 buf = self.upvars[field.index()].place.to_string(self.infcx.tcx);
253 ok = Ok(());
254 } else {
255 let field_name = self.describe_field(
256 PlaceRef { local, projection: place.projection.split_at(index).0 },
257 *field,
258 IncludingTupleField(opt.including_tuple_field),
259 );
260 if let Some(field_name_str) = field_name {
261 buf.push('.');
262 buf.push_str(&field_name_str);
263 }
264 }
265 }
266 ProjectionElem::Index(index) => {
267 buf.push('[');
268 if self.append_local_to_string(*index, &mut buf).is_err() {
269 buf.push('_');
270 }
271 buf.push(']');
272 }
273 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
274 // Since it isn't possible to borrow an element on a particular index and
275 // then use another while the borrow is held, don't output indices details
276 // to avoid confusing the end-user
277 buf.push_str("[..]");
278 }
279 }
280 }
281 ok.ok().map(|_| buf)
282 }
283
284 fn describe_name(&self, place: PlaceRef<'tcx>) -> Option<Symbol> {
285 for elem in place.projection.into_iter() {
286 match elem {
287 ProjectionElem::Downcast(Some(name), _) => {
288 return Some(*name);
289 }
290 _ => {}
291 }
292 }
293 None
294 }
295
296 /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
297 /// a name, or its name was generated by the compiler, then `Err` is returned
298 fn append_local_to_string(&self, local: Local, buf: &mut String) -> Result<(), ()> {
299 let decl = &self.body.local_decls[local];
300 match self.local_names[local] {
301 Some(name) if !decl.from_compiler_desugaring() => {
302 buf.push_str(name.as_str());
303 Ok(())
304 }
305 _ => Err(()),
306 }
307 }
308
309 /// End-user visible description of the `field`nth field of `base`
310 fn describe_field(
311 &self,
312 place: PlaceRef<'tcx>,
313 field: FieldIdx,
314 including_tuple_field: IncludingTupleField,
315 ) -> Option<String> {
316 let place_ty = match place {
317 PlaceRef { local, projection: [] } => PlaceTy::from_ty(self.body.local_decls[local].ty),
318 PlaceRef { local, projection: [proj_base @ .., elem] } => match elem {
319 ProjectionElem::Deref
320 | ProjectionElem::Index(..)
321 | ProjectionElem::ConstantIndex { .. }
322 | ProjectionElem::Subslice { .. } => {
323 PlaceRef { local, projection: proj_base }.ty(self.body, self.infcx.tcx)
324 }
325 ProjectionElem::Downcast(..) => place.ty(self.body, self.infcx.tcx),
326 ProjectionElem::Subtype(ty) | ProjectionElem::OpaqueCast(ty) => {
327 PlaceTy::from_ty(*ty)
328 }
329 ProjectionElem::Field(_, field_type) => PlaceTy::from_ty(*field_type),
330 },
331 };
332 self.describe_field_from_ty(
333 place_ty.ty,
334 field,
335 place_ty.variant_index,
336 including_tuple_field,
337 )
338 }
339
340 /// End-user visible description of the `field_index`nth field of `ty`
341 fn describe_field_from_ty(
342 &self,
343 ty: Ty<'_>,
344 field: FieldIdx,
345 variant_index: Option<VariantIdx>,
346 including_tuple_field: IncludingTupleField,
347 ) -> Option<String> {
348 if ty.is_box() {
349 // If the type is a box, the field is described from the boxed type
350 self.describe_field_from_ty(ty.boxed_ty(), field, variant_index, including_tuple_field)
351 } else {
352 match *ty.kind() {
353 ty::Adt(def, _) => {
354 let variant = if let Some(idx) = variant_index {
355 assert!(def.is_enum());
356 &def.variant(idx)
357 } else {
358 def.non_enum_variant()
359 };
360 if !including_tuple_field.0 && variant.ctor_kind() == Some(CtorKind::Fn) {
361 return None;
362 }
363 Some(variant.fields[field].name.to_string())
364 }
365 ty::Tuple(_) => Some(field.index().to_string()),
366 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
367 self.describe_field_from_ty(ty, field, variant_index, including_tuple_field)
368 }
369 ty::Array(ty, _) | ty::Slice(ty) => {
370 self.describe_field_from_ty(ty, field, variant_index, including_tuple_field)
371 }
372 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
373 // We won't be borrowck'ing here if the closure came from another crate,
374 // so it's safe to call `expect_local`.
375 //
376 // We know the field exists so it's safe to call operator[] and `unwrap` here.
377 let def_id = def_id.expect_local();
378 let var_id =
379 self.infcx.tcx.closure_captures(def_id)[field.index()].get_root_variable();
380
381 Some(self.infcx.tcx.hir().name(var_id).to_string())
382 }
383 _ => {
384 // Might need a revision when the fields in trait RFC is implemented
385 // (https://github.com/rust-lang/rfcs/pull/1546)
386 bug!("End-user description not implemented for field access on `{:?}`", ty);
387 }
388 }
389 }
390 }
391
392 pub(super) fn borrowed_content_source(
393 &self,
394 deref_base: PlaceRef<'tcx>,
395 ) -> BorrowedContentSource<'tcx> {
396 let tcx = self.infcx.tcx;
397
398 // Look up the provided place and work out the move path index for it,
399 // we'll use this to check whether it was originally from an overloaded
400 // operator.
401 match self.move_data.rev_lookup.find(deref_base) {
402 LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => {
403 debug!("borrowed_content_source: mpi={:?}", mpi);
404
405 for i in &self.move_data.init_path_map[mpi] {
406 let init = &self.move_data.inits[*i];
407 debug!("borrowed_content_source: init={:?}", init);
408 // We're only interested in statements that initialized a value, not the
409 // initializations from arguments.
410 let InitLocation::Statement(loc) = init.location else { continue };
411
412 let bbd = &self.body[loc.block];
413 let is_terminator = bbd.statements.len() == loc.statement_index;
414 debug!(
415 "borrowed_content_source: loc={:?} is_terminator={:?}",
416 loc, is_terminator,
417 );
418 if !is_terminator {
419 continue;
420 } else if let Some(Terminator {
421 kind:
422 TerminatorKind::Call {
423 func,
424 call_source: CallSource::OverloadedOperator,
425 ..
426 },
427 ..
428 }) = &bbd.terminator
429 {
430 if let Some(source) =
431 BorrowedContentSource::from_call(func.ty(self.body, tcx), tcx)
432 {
433 return source;
434 }
435 }
436 }
437 }
438 // Base is a `static` so won't be from an overloaded operator
439 _ => (),
440 };
441
442 // If we didn't find an overloaded deref or index, then assume it's a
443 // built in deref and check the type of the base.
444 let base_ty = deref_base.ty(self.body, tcx).ty;
445 if base_ty.is_unsafe_ptr() {
446 BorrowedContentSource::DerefRawPointer
447 } else if base_ty.is_mutable_ptr() {
448 BorrowedContentSource::DerefMutableRef
449 } else {
450 BorrowedContentSource::DerefSharedRef
451 }
452 }
453
454 /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
455 /// name where required.
456 pub(super) fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
457 let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);
458
459 // We need to add synthesized lifetimes where appropriate. We do
460 // this by hooking into the pretty printer and telling it to label the
461 // lifetimes without names with the value `'0`.
462 if let ty::Ref(region, ..) = ty.kind() {
463 match **region {
464 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
465 | ty::RePlaceholder(ty::PlaceholderRegion {
466 bound: ty::BoundRegion { kind: br, .. },
467 ..
468 }) => printer.region_highlight_mode.highlighting_bound_region(br, counter),
469 _ => {}
470 }
471 }
472
473 ty.print(printer).unwrap().into_buffer()
474 }
475
476 /// Returns the name of the provided `Ty` (that must be a reference)'s region with a
477 /// synthesized lifetime name where required.
478 pub(super) fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
479 let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);
480
481 let region = if let ty::Ref(region, ..) = ty.kind() {
482 match **region {
483 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
484 | ty::RePlaceholder(ty::PlaceholderRegion {
485 bound: ty::BoundRegion { kind: br, .. },
486 ..
487 }) => printer.region_highlight_mode.highlighting_bound_region(br, counter),
488 _ => {}
489 }
490 region
491 } else {
492 bug!("ty for annotation of borrow region is not a reference");
493 };
494
495 region.print(printer).unwrap().into_buffer()
496 }
497 }
498
499 /// The span(s) associated to a use of a place.
500 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
501 pub(super) enum UseSpans<'tcx> {
502 /// The access is caused by capturing a variable for a closure.
503 ClosureUse {
504 /// This is true if the captured variable was from a generator.
505 generator_kind: Option<GeneratorKind>,
506 /// The span of the args of the closure, including the `move` keyword if
507 /// it's present.
508 args_span: Span,
509 /// The span of the use resulting in capture kind
510 /// Check `ty::CaptureInfo` for more details
511 capture_kind_span: Span,
512 /// The span of the use resulting in the captured path
513 /// Check `ty::CaptureInfo` for more details
514 path_span: Span,
515 },
516 /// The access is caused by using a variable as the receiver of a method
517 /// that takes 'self'
518 FnSelfUse {
519 /// The span of the variable being moved
520 var_span: Span,
521 /// The span of the method call on the variable
522 fn_call_span: Span,
523 /// The definition span of the method being called
524 fn_span: Span,
525 kind: CallKind<'tcx>,
526 },
527 /// This access is caused by a `match` or `if let` pattern.
528 PatUse(Span),
529 /// This access has a single span associated to it: common case.
530 OtherUse(Span),
531 }
532
533 impl UseSpans<'_> {
534 pub(super) fn args_or_use(self) -> Span {
535 match self {
536 UseSpans::ClosureUse { args_span: span, .. }
537 | UseSpans::PatUse(span)
538 | UseSpans::OtherUse(span) => span,
539 UseSpans::FnSelfUse { fn_call_span, kind: CallKind::DerefCoercion { .. }, .. } => {
540 fn_call_span
541 }
542 UseSpans::FnSelfUse { var_span, .. } => var_span,
543 }
544 }
545
546 /// Returns the span of `self`, in the case of a `ClosureUse` returns the `path_span`
547 pub(super) fn var_or_use_path_span(self) -> Span {
548 match self {
549 UseSpans::ClosureUse { path_span: span, .. }
550 | UseSpans::PatUse(span)
551 | UseSpans::OtherUse(span) => span,
552 UseSpans::FnSelfUse { fn_call_span, kind: CallKind::DerefCoercion { .. }, .. } => {
553 fn_call_span
554 }
555 UseSpans::FnSelfUse { var_span, .. } => var_span,
556 }
557 }
558
559 /// Returns the span of `self`, in the case of a `ClosureUse` returns the `capture_kind_span`
560 pub(super) fn var_or_use(self) -> Span {
561 match self {
562 UseSpans::ClosureUse { capture_kind_span: span, .. }
563 | UseSpans::PatUse(span)
564 | UseSpans::OtherUse(span) => span,
565 UseSpans::FnSelfUse { fn_call_span, kind: CallKind::DerefCoercion { .. }, .. } => {
566 fn_call_span
567 }
568 UseSpans::FnSelfUse { var_span, .. } => var_span,
569 }
570 }
571
572 pub(super) fn generator_kind(self) -> Option<GeneratorKind> {
573 match self {
574 UseSpans::ClosureUse { generator_kind, .. } => generator_kind,
575 _ => None,
576 }
577 }
578
579 /// Add a span label to the arguments of the closure, if it exists.
580 pub(super) fn args_subdiag(
581 self,
582 err: &mut Diagnostic,
583 f: impl FnOnce(Span) -> CaptureArgLabel,
584 ) {
585 if let UseSpans::ClosureUse { args_span, .. } = self {
586 err.subdiagnostic(f(args_span));
587 }
588 }
589
590 /// Add a span label to the use of the captured variable, if it exists.
591 /// only adds label to the `path_span`
592 pub(super) fn var_path_only_subdiag(
593 self,
594 err: &mut Diagnostic,
595 action: crate::InitializationRequiringAction,
596 ) {
597 use crate::InitializationRequiringAction::*;
598 use CaptureVarPathUseCause::*;
599 if let UseSpans::ClosureUse { generator_kind, path_span, .. } = self {
600 match generator_kind {
601 Some(_) => {
602 err.subdiagnostic(match action {
603 Borrow => BorrowInGenerator { path_span },
604 MatchOn | Use => UseInGenerator { path_span },
605 Assignment => AssignInGenerator { path_span },
606 PartialAssignment => AssignPartInGenerator { path_span },
607 });
608 }
609 None => {
610 err.subdiagnostic(match action {
611 Borrow => BorrowInClosure { path_span },
612 MatchOn | Use => UseInClosure { path_span },
613 Assignment => AssignInClosure { path_span },
614 PartialAssignment => AssignPartInClosure { path_span },
615 });
616 }
617 }
618 }
619 }
620
621 /// Add a subdiagnostic to the use of the captured variable, if it exists.
622 pub(super) fn var_subdiag(
623 self,
624 handler: Option<&rustc_errors::Handler>,
625 err: &mut Diagnostic,
626 kind: Option<rustc_middle::mir::BorrowKind>,
627 f: impl FnOnce(Option<GeneratorKind>, Span) -> CaptureVarCause,
628 ) {
629 if let UseSpans::ClosureUse { generator_kind, capture_kind_span, path_span, .. } = self {
630 if capture_kind_span != path_span {
631 err.subdiagnostic(match kind {
632 Some(kd) => match kd {
633 rustc_middle::mir::BorrowKind::Shared
634 | rustc_middle::mir::BorrowKind::Fake => {
635 CaptureVarKind::Immut { kind_span: capture_kind_span }
636 }
637
638 rustc_middle::mir::BorrowKind::Mut { .. } => {
639 CaptureVarKind::Mut { kind_span: capture_kind_span }
640 }
641 },
642 None => CaptureVarKind::Move { kind_span: capture_kind_span },
643 });
644 };
645 let diag = f(generator_kind, path_span);
646 match handler {
647 Some(hd) => err.eager_subdiagnostic(hd, diag),
648 None => err.subdiagnostic(diag),
649 };
650 }
651 }
652
653 /// Returns `false` if this place is not used in a closure.
654 pub(super) fn for_closure(&self) -> bool {
655 match *self {
656 UseSpans::ClosureUse { generator_kind, .. } => generator_kind.is_none(),
657 _ => false,
658 }
659 }
660
661 /// Returns `false` if this place is not used in a generator.
662 pub(super) fn for_generator(&self) -> bool {
663 match *self {
664 UseSpans::ClosureUse { generator_kind, .. } => generator_kind.is_some(),
665 _ => false,
666 }
667 }
668
669 pub(super) fn or_else<F>(self, if_other: F) -> Self
670 where
671 F: FnOnce() -> Self,
672 {
673 match self {
674 closure @ UseSpans::ClosureUse { .. } => closure,
675 UseSpans::PatUse(_) | UseSpans::OtherUse(_) => if_other(),
676 fn_self @ UseSpans::FnSelfUse { .. } => fn_self,
677 }
678 }
679 }
680
681 pub(super) enum BorrowedContentSource<'tcx> {
682 DerefRawPointer,
683 DerefMutableRef,
684 DerefSharedRef,
685 OverloadedDeref(Ty<'tcx>),
686 OverloadedIndex(Ty<'tcx>),
687 }
688
689 impl<'tcx> BorrowedContentSource<'tcx> {
690 pub(super) fn describe_for_unnamed_place(&self, tcx: TyCtxt<'_>) -> String {
691 match *self {
692 BorrowedContentSource::DerefRawPointer => "a raw pointer".to_string(),
693 BorrowedContentSource::DerefSharedRef => "a shared reference".to_string(),
694 BorrowedContentSource::DerefMutableRef => "a mutable reference".to_string(),
695 BorrowedContentSource::OverloadedDeref(ty) => ty
696 .ty_adt_def()
697 .and_then(|adt| match tcx.get_diagnostic_name(adt.did())? {
698 name @ (sym::Rc | sym::Arc) => Some(format!("an `{name}`")),
699 _ => None,
700 })
701 .unwrap_or_else(|| format!("dereference of `{ty}`")),
702 BorrowedContentSource::OverloadedIndex(ty) => format!("index of `{ty}`"),
703 }
704 }
705
706 pub(super) fn describe_for_named_place(&self) -> Option<&'static str> {
707 match *self {
708 BorrowedContentSource::DerefRawPointer => Some("raw pointer"),
709 BorrowedContentSource::DerefSharedRef => Some("shared reference"),
710 BorrowedContentSource::DerefMutableRef => Some("mutable reference"),
711 // Overloaded deref and index operators should be evaluated into a
712 // temporary. So we don't need a description here.
713 BorrowedContentSource::OverloadedDeref(_)
714 | BorrowedContentSource::OverloadedIndex(_) => None,
715 }
716 }
717
718 pub(super) fn describe_for_immutable_place(&self, tcx: TyCtxt<'_>) -> String {
719 match *self {
720 BorrowedContentSource::DerefRawPointer => "a `*const` pointer".to_string(),
721 BorrowedContentSource::DerefSharedRef => "a `&` reference".to_string(),
722 BorrowedContentSource::DerefMutableRef => {
723 bug!("describe_for_immutable_place: DerefMutableRef isn't immutable")
724 }
725 BorrowedContentSource::OverloadedDeref(ty) => ty
726 .ty_adt_def()
727 .and_then(|adt| match tcx.get_diagnostic_name(adt.did())? {
728 name @ (sym::Rc | sym::Arc) => Some(format!("an `{name}`")),
729 _ => None,
730 })
731 .unwrap_or_else(|| format!("dereference of `{ty}`")),
732 BorrowedContentSource::OverloadedIndex(ty) => format!("an index of `{ty}`"),
733 }
734 }
735
736 fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Self> {
737 match *func.kind() {
738 ty::FnDef(def_id, args) => {
739 let trait_id = tcx.trait_of_item(def_id)?;
740
741 let lang_items = tcx.lang_items();
742 if Some(trait_id) == lang_items.deref_trait()
743 || Some(trait_id) == lang_items.deref_mut_trait()
744 {
745 Some(BorrowedContentSource::OverloadedDeref(args.type_at(0)))
746 } else if Some(trait_id) == lang_items.index_trait()
747 || Some(trait_id) == lang_items.index_mut_trait()
748 {
749 Some(BorrowedContentSource::OverloadedIndex(args.type_at(0)))
750 } else {
751 None
752 }
753 }
754 _ => None,
755 }
756 }
757 }
758
759 ///helper struct for explain_captures()
760 struct CapturedMessageOpt {
761 is_partial_move: bool,
762 is_loop_message: bool,
763 is_move_msg: bool,
764 is_loop_move: bool,
765 maybe_reinitialized_locations_is_empty: bool,
766 }
767
768 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
769 /// Finds the spans associated to a move or copy of move_place at location.
770 pub(super) fn move_spans(
771 &self,
772 moved_place: PlaceRef<'tcx>, // Could also be an upvar.
773 location: Location,
774 ) -> UseSpans<'tcx> {
775 use self::UseSpans::*;
776
777 let Some(stmt) = self.body[location.block].statements.get(location.statement_index) else {
778 return OtherUse(self.body.source_info(location).span);
779 };
780
781 debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
782 if let StatementKind::Assign(box (_, Rvalue::Aggregate(kind, places))) = &stmt.kind
783 && let AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) = **kind
784 {
785 debug!("move_spans: def_id={:?} places={:?}", def_id, places);
786 let def_id = def_id.expect_local();
787 if let Some((args_span, generator_kind, capture_kind_span, path_span)) =
788 self.closure_span(def_id, moved_place, places)
789 {
790 return ClosureUse {
791 generator_kind,
792 args_span,
793 capture_kind_span,
794 path_span,
795 };
796 }
797 }
798
799 // StatementKind::FakeRead only contains a def_id if they are introduced as a result
800 // of pattern matching within a closure.
801 if let StatementKind::FakeRead(box (cause, place)) = stmt.kind {
802 match cause {
803 FakeReadCause::ForMatchedPlace(Some(closure_def_id))
804 | FakeReadCause::ForLet(Some(closure_def_id)) => {
805 debug!("move_spans: def_id={:?} place={:?}", closure_def_id, place);
806 let places = &[Operand::Move(place)];
807 if let Some((args_span, generator_kind, capture_kind_span, path_span)) =
808 self.closure_span(closure_def_id, moved_place, IndexSlice::from_raw(places))
809 {
810 return ClosureUse {
811 generator_kind,
812 args_span,
813 capture_kind_span,
814 path_span,
815 };
816 }
817 }
818 _ => {}
819 }
820 }
821
822 let normal_ret =
823 if moved_place.projection.iter().any(|p| matches!(p, ProjectionElem::Downcast(..))) {
824 PatUse(stmt.source_info.span)
825 } else {
826 OtherUse(stmt.source_info.span)
827 };
828
829 // We are trying to find MIR of the form:
830 // ```
831 // _temp = _moved_val;
832 // ...
833 // FnSelfCall(_temp, ...)
834 // ```
835 //
836 // where `_moved_val` is the place we generated the move error for,
837 // `_temp` is some other local, and `FnSelfCall` is a function
838 // that has a `self` parameter.
839
840 let target_temp = match stmt.kind {
841 StatementKind::Assign(box (temp, _)) if temp.as_local().is_some() => {
842 temp.as_local().unwrap()
843 }
844 _ => return normal_ret,
845 };
846
847 debug!("move_spans: target_temp = {:?}", target_temp);
848
849 if let Some(Terminator {
850 kind: TerminatorKind::Call { fn_span, call_source, .. }, ..
851 }) = &self.body[location.block].terminator
852 {
853 let Some((method_did, method_args)) = rustc_middle::util::find_self_call(
854 self.infcx.tcx,
855 &self.body,
856 target_temp,
857 location.block,
858 ) else {
859 return normal_ret;
860 };
861
862 let kind = call_kind(
863 self.infcx.tcx,
864 self.param_env,
865 method_did,
866 method_args,
867 *fn_span,
868 call_source.from_hir_call(),
869 Some(self.infcx.tcx.fn_arg_names(method_did)[0]),
870 );
871
872 return FnSelfUse {
873 var_span: stmt.source_info.span,
874 fn_call_span: *fn_span,
875 fn_span: self.infcx.tcx.def_span(method_did),
876 kind,
877 };
878 }
879 normal_ret
880 }
881
882 /// Finds the span of arguments of a closure (within `maybe_closure_span`)
883 /// and its usage of the local assigned at `location`.
884 /// This is done by searching in statements succeeding `location`
885 /// and originating from `maybe_closure_span`.
886 pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans<'tcx> {
887 use self::UseSpans::*;
888 debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
889
890 let target = match self.body[location.block].statements.get(location.statement_index) {
891 Some(Statement { kind: StatementKind::Assign(box (place, _)), .. }) => {
892 if let Some(local) = place.as_local() {
893 local
894 } else {
895 return OtherUse(use_span);
896 }
897 }
898 _ => return OtherUse(use_span),
899 };
900
901 if self.body.local_kind(target) != LocalKind::Temp {
902 // operands are always temporaries.
903 return OtherUse(use_span);
904 }
905
906 // drop and replace might have moved the assignment to the next block
907 let maybe_additional_statement =
908 if let TerminatorKind::Drop { target: drop_target, .. } =
909 self.body[location.block].terminator().kind
910 {
911 self.body[drop_target].statements.first()
912 } else {
913 None
914 };
915
916 let statements =
917 self.body[location.block].statements[location.statement_index + 1..].iter();
918
919 for stmt in statements.chain(maybe_additional_statement) {
920 if let StatementKind::Assign(box (_, Rvalue::Aggregate(kind, places))) = &stmt.kind {
921 let (&def_id, is_generator) = match kind {
922 box AggregateKind::Closure(def_id, _) => (def_id, false),
923 box AggregateKind::Generator(def_id, _, _) => (def_id, true),
924 _ => continue,
925 };
926 let def_id = def_id.expect_local();
927
928 debug!(
929 "borrow_spans: def_id={:?} is_generator={:?} places={:?}",
930 def_id, is_generator, places
931 );
932 if let Some((args_span, generator_kind, capture_kind_span, path_span)) =
933 self.closure_span(def_id, Place::from(target).as_ref(), places)
934 {
935 return ClosureUse { generator_kind, args_span, capture_kind_span, path_span };
936 } else {
937 return OtherUse(use_span);
938 }
939 }
940
941 if use_span != stmt.source_info.span {
942 break;
943 }
944 }
945
946 OtherUse(use_span)
947 }
948
949 /// Finds the spans of a captured place within a closure or generator.
950 /// The first span is the location of the use resulting in the capture kind of the capture
951 /// The second span is the location the use resulting in the captured path of the capture
952 fn closure_span(
953 &self,
954 def_id: LocalDefId,
955 target_place: PlaceRef<'tcx>,
956 places: &IndexSlice<FieldIdx, Operand<'tcx>>,
957 ) -> Option<(Span, Option<GeneratorKind>, Span, Span)> {
958 debug!(
959 "closure_span: def_id={:?} target_place={:?} places={:?}",
960 def_id, target_place, places
961 );
962 let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(def_id);
963 let expr = &self.infcx.tcx.hir().expect_expr(hir_id).kind;
964 debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
965 if let hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, .. }) = expr {
966 for (captured_place, place) in
967 self.infcx.tcx.closure_captures(def_id).iter().zip(places)
968 {
969 match place {
970 Operand::Copy(place) | Operand::Move(place)
971 if target_place == place.as_ref() =>
972 {
973 debug!("closure_span: found captured local {:?}", place);
974 let body = self.infcx.tcx.hir().body(body);
975 let generator_kind = body.generator_kind();
976
977 return Some((
978 fn_decl_span,
979 generator_kind,
980 captured_place.get_capture_kind_span(self.infcx.tcx),
981 captured_place.get_path_span(self.infcx.tcx),
982 ));
983 }
984 _ => {}
985 }
986 }
987 }
988 None
989 }
990
991 /// Helper to retrieve span(s) of given borrow from the current MIR
992 /// representation
993 pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans<'tcx> {
994 let span = self.body.source_info(borrow.reserve_location).span;
995 self.borrow_spans(span, borrow.reserve_location)
996 }
997
998 fn explain_captures(
999 &mut self,
1000 err: &mut Diagnostic,
1001 span: Span,
1002 move_span: Span,
1003 move_spans: UseSpans<'tcx>,
1004 moved_place: Place<'tcx>,
1005 msg_opt: CapturedMessageOpt,
1006 ) {
1007 let CapturedMessageOpt {
1008 is_partial_move: is_partial,
1009 is_loop_message,
1010 is_move_msg,
1011 is_loop_move,
1012 maybe_reinitialized_locations_is_empty,
1013 } = msg_opt;
1014 if let UseSpans::FnSelfUse { var_span, fn_call_span, fn_span, kind } = move_spans {
1015 let place_name = self
1016 .describe_place(moved_place.as_ref())
1017 .map(|n| format!("`{n}`"))
1018 .unwrap_or_else(|| "value".to_owned());
1019 match kind {
1020 CallKind::FnCall { fn_trait_id, .. }
1021 if Some(fn_trait_id) == self.infcx.tcx.lang_items().fn_once_trait() =>
1022 {
1023 err.subdiagnostic(CaptureReasonLabel::Call {
1024 fn_call_span,
1025 place_name: &place_name,
1026 is_partial,
1027 is_loop_message,
1028 });
1029 err.subdiagnostic(CaptureReasonNote::FnOnceMoveInCall { var_span });
1030 }
1031 CallKind::Operator { self_arg, .. } => {
1032 let self_arg = self_arg.unwrap();
1033 err.subdiagnostic(CaptureReasonLabel::OperatorUse {
1034 fn_call_span,
1035 place_name: &place_name,
1036 is_partial,
1037 is_loop_message,
1038 });
1039 if self.fn_self_span_reported.insert(fn_span) {
1040 err.subdiagnostic(CaptureReasonNote::LhsMoveByOperator {
1041 span: self_arg.span,
1042 });
1043 }
1044 }
1045 CallKind::Normal { self_arg, desugaring, method_did, method_args } => {
1046 let self_arg = self_arg.unwrap();
1047 let tcx = self.infcx.tcx;
1048 if let Some((CallDesugaringKind::ForLoopIntoIter, _)) = desugaring {
1049 let ty = moved_place.ty(self.body, tcx).ty;
1050 let suggest = match tcx.get_diagnostic_item(sym::IntoIterator) {
1051 Some(def_id) => type_known_to_meet_bound_modulo_regions(
1052 &self.infcx,
1053 self.param_env,
1054 Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty),
1055 def_id,
1056 ),
1057 _ => false,
1058 };
1059 if suggest {
1060 err.subdiagnostic(CaptureReasonSuggest::IterateSlice {
1061 ty,
1062 span: move_span.shrink_to_lo(),
1063 });
1064 }
1065
1066 err.subdiagnostic(CaptureReasonLabel::ImplicitCall {
1067 fn_call_span,
1068 place_name: &place_name,
1069 is_partial,
1070 is_loop_message,
1071 });
1072 // If the moved place was a `&mut` ref, then we can
1073 // suggest to reborrow it where it was moved, so it
1074 // will still be valid by the time we get to the usage.
1075 if let ty::Ref(_, _, hir::Mutability::Mut) =
1076 moved_place.ty(self.body, self.infcx.tcx).ty.kind()
1077 {
1078 // If we are in a loop this will be suggested later.
1079 if !is_loop_move {
1080 err.span_suggestion_verbose(
1081 move_span.shrink_to_lo(),
1082 format!(
1083 "consider creating a fresh reborrow of {} here",
1084 self.describe_place(moved_place.as_ref())
1085 .map(|n| format!("`{n}`"))
1086 .unwrap_or_else(|| "the mutable reference".to_string()),
1087 ),
1088 "&mut *",
1089 Applicability::MachineApplicable,
1090 );
1091 }
1092 }
1093 } else {
1094 if let Some((CallDesugaringKind::Await, _)) = desugaring {
1095 err.subdiagnostic(CaptureReasonLabel::Await {
1096 fn_call_span,
1097 place_name: &place_name,
1098 is_partial,
1099 is_loop_message,
1100 });
1101 } else {
1102 err.subdiagnostic(CaptureReasonLabel::MethodCall {
1103 fn_call_span,
1104 place_name: &place_name,
1105 is_partial,
1106 is_loop_message,
1107 });
1108 }
1109 // Erase and shadow everything that could be passed to the new infcx.
1110 let ty = moved_place.ty(self.body, tcx).ty;
1111
1112 if let ty::Adt(def, args) = ty.kind()
1113 && Some(def.did()) == tcx.lang_items().pin_type()
1114 && let ty::Ref(_, _, hir::Mutability::Mut) = args.type_at(0).kind()
1115 && let self_ty = self.infcx.instantiate_binder_with_fresh_vars(
1116 fn_call_span,
1117 LateBoundRegionConversionTime::FnCall,
1118 tcx.fn_sig(method_did).instantiate(tcx, method_args).input(0),
1119 )
1120 && self.infcx.can_eq(self.param_env, ty, self_ty)
1121 {
1122 err.eager_subdiagnostic(
1123 &self.infcx.tcx.sess.parse_sess.span_diagnostic,
1124 CaptureReasonSuggest::FreshReborrow {
1125 span: move_span.shrink_to_hi(),
1126 });
1127 }
1128 if let Some(clone_trait) = tcx.lang_items().clone_trait()
1129 && let trait_ref = ty::TraitRef::new(tcx, clone_trait, [ty])
1130 && let o = Obligation::new(
1131 tcx,
1132 ObligationCause::dummy(),
1133 self.param_env,
1134 ty::Binder::dummy(trait_ref),
1135 )
1136 && self.infcx.predicate_must_hold_modulo_regions(&o)
1137 {
1138 err.span_suggestion_verbose(
1139 move_span.shrink_to_hi(),
1140 "you can `clone` the value and consume it, but this might not be \
1141 your desired behavior",
1142 ".clone()".to_string(),
1143 Applicability::MaybeIncorrect,
1144 );
1145 }
1146 }
1147 // Avoid pointing to the same function in multiple different
1148 // error messages.
1149 if span != DUMMY_SP && self.fn_self_span_reported.insert(self_arg.span) {
1150 self.explain_iterator_advancement_in_for_loop_if_applicable(
1151 err,
1152 span,
1153 &move_spans,
1154 );
1155
1156 let func = tcx.def_path_str(method_did);
1157 err.subdiagnostic(CaptureReasonNote::FuncTakeSelf {
1158 func,
1159 place_name,
1160 span: self_arg.span,
1161 });
1162 }
1163 let parent_did = tcx.parent(method_did);
1164 let parent_self_ty =
1165 matches!(tcx.def_kind(parent_did), rustc_hir::def::DefKind::Impl { .. })
1166 .then_some(parent_did)
1167 .and_then(|did| match tcx.type_of(did).instantiate_identity().kind() {
1168 ty::Adt(def, ..) => Some(def.did()),
1169 _ => None,
1170 });
1171 let is_option_or_result = parent_self_ty.is_some_and(|def_id| {
1172 matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result))
1173 });
1174 if is_option_or_result && maybe_reinitialized_locations_is_empty {
1175 err.subdiagnostic(CaptureReasonLabel::BorrowContent { var_span });
1176 }
1177 }
1178 // Other desugarings takes &self, which cannot cause a move
1179 _ => {}
1180 }
1181 } else {
1182 if move_span != span || is_loop_message {
1183 err.subdiagnostic(CaptureReasonLabel::MovedHere {
1184 move_span,
1185 is_partial,
1186 is_move_msg,
1187 is_loop_message,
1188 });
1189 }
1190 // If the move error occurs due to a loop, don't show
1191 // another message for the same span
1192 if !is_loop_message {
1193 move_spans.var_subdiag(None, err, None, |kind, var_span| match kind {
1194 Some(_) => CaptureVarCause::PartialMoveUseInGenerator { var_span, is_partial },
1195 None => CaptureVarCause::PartialMoveUseInClosure { var_span, is_partial },
1196 })
1197 }
1198 }
1199 }
1200 }