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