]> git.proxmox.com Git - rustc.git/blame - src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs
New upstream version 1.45.0+dfsg1
[rustc.git] / src / librustc_mir / borrow_check / diagnostics / conflict_errors.rs
CommitLineData
f9f354fc 1use either::Either;
dc9dc135 2use rustc_data_structures::fx::FxHashSet;
dc9dc135 3use rustc_errors::{Applicability, DiagnosticBuilder};
dfeec247
XL
4use rustc_hir as hir;
5use rustc_hir::def_id::DefId;
6use rustc_hir::{AsyncGeneratorKind, GeneratorKind};
7use rustc_index::vec::Idx;
ba9703b0
XL
8use rustc_middle::mir::{
9 self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, ConstraintCategory,
10 FakeReadCause, Local, LocalDecl, LocalInfo, LocalKind, Location, Operand, Place, PlaceRef,
11 ProjectionElem, Rvalue, Statement, StatementKind, TerminatorKind, VarBindingForm,
12};
f9f354fc 13use rustc_middle::ty::{self, suggest_constraining_type_param, Ty};
dfeec247
XL
14use rustc_span::source_map::DesugaringKind;
15use rustc_span::Span;
dc9dc135 16
dc9dc135 17use crate::dataflow::drop_flag_effects;
dfeec247 18use crate::dataflow::indexes::{MoveOutIndex, MovePathIndex};
416331ca 19use crate::util::borrowck_errors;
dc9dc135 20
60c5eb7d 21use crate::borrow_check::{
dfeec247
XL
22 borrow_set::BorrowData, prefixes::IsPrefixOf, InitializationRequiringAction, MirBorrowckCtxt,
23 PrefixSet, WriteKind,
60c5eb7d
XL
24};
25
26use super::{
dfeec247 27 explain_borrow::BorrowExplanation, IncludingDowncast, RegionName, RegionNameSource, UseSpans,
60c5eb7d
XL
28};
29
dc9dc135
XL
30#[derive(Debug)]
31struct MoveSite {
32 /// Index of the "move out" that we found. The `MoveData` can
33 /// then tell us where the move occurred.
34 moi: MoveOutIndex,
35
36 /// `true` if we traversed a back edge while walking from the point
37 /// of error to the move site.
dfeec247 38 traversed_back_edge: bool,
dc9dc135
XL
39}
40
41/// Which case a StorageDeadOrDrop is for.
42#[derive(Copy, Clone, PartialEq, Eq, Debug)]
43enum StorageDeadOrDrop<'tcx> {
44 LocalStorageDead,
45 BoxedStorageDead,
46 Destructor(Ty<'tcx>),
47}
48
49impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
60c5eb7d 50 pub(in crate::borrow_check) fn report_use_of_moved_or_uninitialized(
dc9dc135
XL
51 &mut self,
52 location: Location,
53 desired_action: InitializationRequiringAction,
74b04a01 54 (moved_place, used_place, span): (PlaceRef<'tcx>, PlaceRef<'tcx>, Span),
dc9dc135
XL
55 mpi: MovePathIndex,
56 ) {
57 debug!(
58 "report_use_of_moved_or_uninitialized: location={:?} desired_action={:?} \
59 moved_place={:?} used_place={:?} span={:?} mpi={:?}",
60 location, desired_action, moved_place, used_place, span, mpi
61 );
62
dfeec247
XL
63 let use_spans =
64 self.move_spans(moved_place, location).or_else(|| self.borrow_spans(span, location));
dc9dc135
XL
65 let span = use_spans.args_or_use();
66
67 let move_site_vec = self.get_moved_indexes(location, mpi);
dfeec247
XL
68 debug!("report_use_of_moved_or_uninitialized: move_site_vec={:?}", move_site_vec);
69 let move_out_indices: Vec<_> =
70 move_site_vec.iter().map(|move_site| move_site.moi).collect();
dc9dc135
XL
71
72 if move_out_indices.is_empty() {
60c5eb7d 73 let root_place = PlaceRef { projection: &[], ..used_place };
dc9dc135 74
e74abb32 75 if !self.uninitialized_error_reported.insert(root_place) {
dc9dc135
XL
76 debug!(
77 "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
78 root_place
79 );
80 return;
81 }
82
dfeec247
XL
83 let item_msg =
84 match self.describe_place_with_options(used_place, IncludingDowncast(true)) {
85 Some(name) => format!("`{}`", name),
86 None => "value".to_owned(),
87 };
416331ca 88 let mut err = self.cannot_act_on_uninitialized_variable(
dc9dc135
XL
89 span,
90 desired_action.as_noun(),
dfeec247
XL
91 &self
92 .describe_place_with_options(moved_place, IncludingDowncast(true))
dc9dc135 93 .unwrap_or_else(|| "_".to_owned()),
dc9dc135 94 );
e1599b0c 95 err.span_label(span, format!("use of possibly-uninitialized {}", item_msg));
dc9dc135
XL
96
97 use_spans.var_span_label(
98 &mut err,
99 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
100 );
101
102 err.buffer(&mut self.errors_buffer);
103 } else {
104 if let Some((reported_place, _)) = self.move_error_reported.get(&move_out_indices) {
dfeec247 105 if self.prefixes(*reported_place, PrefixSet::All).any(|p| p == used_place) {
dc9dc135
XL
106 debug!(
107 "report_use_of_moved_or_uninitialized place: error suppressed \
108 mois={:?}",
109 move_out_indices
110 );
111 return;
112 }
113 }
114
115 let msg = ""; //FIXME: add "partially " or "collaterally "
116
416331ca 117 let mut err = self.cannot_act_on_moved_value(
dc9dc135
XL
118 span,
119 desired_action.as_noun(),
120 msg,
416331ca 121 self.describe_place_with_options(moved_place, IncludingDowncast(true)),
dc9dc135
XL
122 );
123
dfeec247 124 self.add_moved_or_invoked_closure_note(location, used_place, &mut err);
dc9dc135
XL
125
126 let mut is_loop_move = false;
127 let is_partial_move = move_site_vec.iter().any(|move_site| {
128 let move_out = self.move_data.moves[(*move_site).moi];
129 let moved_place = &self.move_data.move_paths[move_out.path].place;
dfeec247 130 used_place != moved_place.as_ref() && used_place.is_prefix_of(moved_place.as_ref())
dc9dc135
XL
131 });
132 for move_site in &move_site_vec {
133 let move_out = self.move_data.moves[(*move_site).moi];
134 let moved_place = &self.move_data.move_paths[move_out.path].place;
135
416331ca 136 let move_spans = self.move_spans(moved_place.as_ref(), move_out.source);
dc9dc135
XL
137 let move_span = move_spans.args_or_use();
138
dfeec247 139 let move_msg = if move_spans.for_closure() { " into closure" } else { "" };
dc9dc135
XL
140
141 if span == move_span {
142 err.span_label(
143 span,
144 format!("value moved{} here, in previous iteration of loop", move_msg),
145 );
146 is_loop_move = true;
147 } else if move_site.traversed_back_edge {
148 err.span_label(
149 move_span,
dfeec247 150 format!("value moved{} here, in previous iteration of loop", move_msg),
dc9dc135
XL
151 );
152 } else {
153 err.span_label(move_span, format!("value moved{} here", move_msg));
154 move_spans.var_span_label(
155 &mut err,
156 format!("variable moved due to use{}", move_spans.describe()),
157 );
158 }
416331ca 159 if Some(DesugaringKind::ForLoop) == move_span.desugaring_kind() {
e1599b0c
XL
160 let sess = self.infcx.tcx.sess;
161 if let Ok(snippet) = sess.source_map().span_to_snippet(move_span) {
dc9dc135
XL
162 err.span_suggestion(
163 move_span,
164 "consider borrowing to avoid moving into the for loop",
165 format!("&{}", snippet),
166 Applicability::MaybeIncorrect,
167 );
168 }
169 }
170 }
171
172 use_spans.var_span_label(
173 &mut err,
174 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
175 );
176
177 if !is_loop_move {
178 err.span_label(
179 span,
180 format!(
181 "value {} here {}",
182 desired_action.as_verb_in_past_tense(),
183 if is_partial_move { "after partial move" } else { "after move" },
184 ),
185 );
186 }
187
dfeec247 188 let ty =
f9f354fc 189 Place::ty_from(used_place.local, used_place.projection, self.body, self.infcx.tcx)
dfeec247 190 .ty;
e74abb32 191 let needs_note = match ty.kind {
dc9dc135 192 ty::Closure(id, _) => {
f9f354fc
XL
193 let tables = self.infcx.tcx.typeck_tables_of(id.expect_local());
194 let hir_id = self.infcx.tcx.hir().as_local_hir_id(id.expect_local());
dc9dc135
XL
195
196 tables.closure_kind_origins().get(hir_id).is_none()
197 }
198 _ => true,
199 };
200
201 if needs_note {
202 let mpi = self.move_data.moves[move_out_indices[0]].path;
203 let place = &self.move_data.move_paths[mpi].place;
204
f9f354fc 205 let ty = place.ty(self.body, self.infcx.tcx).ty;
416331ca
XL
206 let opt_name =
207 self.describe_place_with_options(place.as_ref(), IncludingDowncast(true));
dc9dc135
XL
208 let note_msg = match opt_name {
209 Some(ref name) => format!("`{}`", name),
210 None => "value".to_owned(),
211 };
e74abb32 212 if let ty::Param(param_ty) = ty.kind {
dc9dc135
XL
213 let tcx = self.infcx.tcx;
214 let generics = tcx.generics_of(self.mir_def_id);
60c5eb7d
XL
215 let param = generics.type_param(&param_ty, tcx);
216 if let Some(generics) =
f9f354fc 217 tcx.hir().get_generics(tcx.closure_base_def_id(self.mir_def_id.to_def_id()))
dfeec247 218 {
60c5eb7d 219 suggest_constraining_type_param(
74b04a01 220 tcx,
60c5eb7d
XL
221 generics,
222 &mut err,
223 &param.name.as_str(),
224 "Copy",
74b04a01 225 None,
dc9dc135
XL
226 );
227 }
228 }
e74abb32
XL
229 let span = if let Some(local) = place.as_local() {
230 let decl = &self.body.local_decls[local];
dc9dc135
XL
231 Some(decl.source_info.span)
232 } else {
233 None
234 };
dfeec247 235 self.note_type_does_not_implement_copy(&mut err, &note_msg, ty, span);
dc9dc135
XL
236 }
237
dfeec247
XL
238 if let Some((_, mut old_err)) =
239 self.move_error_reported.insert(move_out_indices, (used_place, err))
dc9dc135
XL
240 {
241 // Cancel the old error so it doesn't ICE.
242 old_err.cancel();
243 }
244 }
245 }
246
60c5eb7d 247 pub(in crate::borrow_check) fn report_move_out_while_borrowed(
dc9dc135
XL
248 &mut self,
249 location: Location,
ba9703b0 250 (place, span): (Place<'tcx>, Span),
dc9dc135
XL
251 borrow: &BorrowData<'tcx>,
252 ) {
253 debug!(
254 "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
255 location, place, span, borrow
256 );
ba9703b0
XL
257 let value_msg = self.describe_any_place(place.as_ref());
258 let borrow_msg = self.describe_any_place(borrow.borrowed_place.as_ref());
dc9dc135
XL
259
260 let borrow_spans = self.retrieve_borrow_spans(borrow);
261 let borrow_span = borrow_spans.args_or_use();
262
416331ca 263 let move_spans = self.move_spans(place.as_ref(), location);
dc9dc135
XL
264 let span = move_spans.args_or_use();
265
ba9703b0
XL
266 let mut err =
267 self.cannot_move_when_borrowed(span, &self.describe_any_place(place.as_ref()));
dc9dc135
XL
268 err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
269 err.span_label(span, format!("move out of {} occurs here", value_msg));
270
271 borrow_spans.var_span_label(
272 &mut err,
dfeec247 273 format!("borrow occurs due to use{}", borrow_spans.describe()),
dc9dc135
XL
274 );
275
dfeec247
XL
276 move_spans
277 .var_span_label(&mut err, format!("move occurs due to use{}", move_spans.describe()));
dc9dc135 278
dfeec247
XL
279 self.explain_why_borrow_contains_point(location, borrow, None)
280 .add_explanation_to_diagnostic(
281 self.infcx.tcx,
282 &self.body,
283 &self.local_names,
284 &mut err,
285 "",
286 Some(borrow_span),
287 );
dc9dc135
XL
288 err.buffer(&mut self.errors_buffer);
289 }
290
60c5eb7d 291 pub(in crate::borrow_check) fn report_use_while_mutably_borrowed(
dc9dc135
XL
292 &mut self,
293 location: Location,
ba9703b0 294 (place, _span): (Place<'tcx>, Span),
dc9dc135
XL
295 borrow: &BorrowData<'tcx>,
296 ) -> DiagnosticBuilder<'cx> {
dc9dc135
XL
297 let borrow_spans = self.retrieve_borrow_spans(borrow);
298 let borrow_span = borrow_spans.args_or_use();
299
300 // Conflicting borrows are reported separately, so only check for move
301 // captures.
416331ca 302 let use_spans = self.move_spans(place.as_ref(), location);
dc9dc135
XL
303 let span = use_spans.var_or_use();
304
416331ca 305 let mut err = self.cannot_use_when_mutably_borrowed(
dc9dc135 306 span,
ba9703b0 307 &self.describe_any_place(place.as_ref()),
dc9dc135 308 borrow_span,
ba9703b0 309 &self.describe_any_place(borrow.borrowed_place.as_ref()),
dc9dc135
XL
310 );
311
312 borrow_spans.var_span_label(&mut err, {
313 let place = &borrow.borrowed_place;
ba9703b0
XL
314 let desc_place = self.describe_any_place(place.as_ref());
315 format!("borrow occurs due to use of {}{}", desc_place, borrow_spans.describe())
dc9dc135
XL
316 });
317
318 self.explain_why_borrow_contains_point(location, borrow, None)
60c5eb7d
XL
319 .add_explanation_to_diagnostic(
320 self.infcx.tcx,
321 &self.body,
322 &self.local_names,
323 &mut err,
324 "",
325 None,
326 );
dc9dc135
XL
327 err
328 }
329
60c5eb7d 330 pub(in crate::borrow_check) fn report_conflicting_borrow(
dc9dc135
XL
331 &mut self,
332 location: Location,
ba9703b0 333 (place, span): (Place<'tcx>, Span),
dc9dc135
XL
334 gen_borrow_kind: BorrowKind,
335 issued_borrow: &BorrowData<'tcx>,
336 ) -> DiagnosticBuilder<'cx> {
337 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
338 let issued_span = issued_spans.args_or_use();
339
340 let borrow_spans = self.borrow_spans(span, location);
341 let span = borrow_spans.args_or_use();
342
343 let container_name = if issued_spans.for_generator() || borrow_spans.for_generator() {
344 "generator"
345 } else {
346 "closure"
347 };
348
349 let (desc_place, msg_place, msg_borrow, union_type_name) =
ba9703b0 350 self.describe_place_for_conflicting_borrow(place, issued_borrow.borrowed_place);
dc9dc135
XL
351
352 let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
dfeec247 353 let second_borrow_desc = if explanation.is_explained() { "second " } else { "" };
dc9dc135
XL
354
355 // FIXME: supply non-"" `opt_via` when appropriate
dc9dc135 356 let first_borrow_desc;
dfeec247 357 let mut err = match (gen_borrow_kind, issued_borrow.kind) {
60c5eb7d 358 (BorrowKind::Shared, BorrowKind::Mut { .. }) => {
dc9dc135 359 first_borrow_desc = "mutable ";
416331ca 360 self.cannot_reborrow_already_borrowed(
dc9dc135
XL
361 span,
362 &desc_place,
363 &msg_place,
60c5eb7d 364 "immutable",
dc9dc135
XL
365 issued_span,
366 "it",
60c5eb7d 367 "mutable",
dc9dc135
XL
368 &msg_borrow,
369 None,
dc9dc135
XL
370 )
371 }
60c5eb7d 372 (BorrowKind::Mut { .. }, BorrowKind::Shared) => {
dc9dc135 373 first_borrow_desc = "immutable ";
416331ca 374 self.cannot_reborrow_already_borrowed(
dc9dc135
XL
375 span,
376 &desc_place,
377 &msg_place,
60c5eb7d 378 "mutable",
dc9dc135
XL
379 issued_span,
380 "it",
60c5eb7d 381 "immutable",
dc9dc135
XL
382 &msg_borrow,
383 None,
dc9dc135
XL
384 )
385 }
386
60c5eb7d 387 (BorrowKind::Mut { .. }, BorrowKind::Mut { .. }) => {
dc9dc135 388 first_borrow_desc = "first ";
74b04a01 389 let mut err = self.cannot_mutably_borrow_multiply(
dc9dc135
XL
390 span,
391 &desc_place,
392 &msg_place,
393 issued_span,
394 &msg_borrow,
395 None,
74b04a01
XL
396 );
397 self.suggest_split_at_mut_if_applicable(
398 &mut err,
ba9703b0
XL
399 place,
400 issued_borrow.borrowed_place,
74b04a01
XL
401 );
402 err
dc9dc135
XL
403 }
404
60c5eb7d 405 (BorrowKind::Unique, BorrowKind::Unique) => {
dc9dc135 406 first_borrow_desc = "first ";
dfeec247 407 self.cannot_uniquely_borrow_by_two_closures(span, &desc_place, issued_span, None)
dc9dc135
XL
408 }
409
ba9703b0 410 (BorrowKind::Mut { .. } | BorrowKind::Unique, BorrowKind::Shallow) => {
dfeec247 411 if let Some(immutable_section_description) =
ba9703b0 412 self.classify_immutable_section(issued_borrow.assigned_place)
dfeec247 413 {
60c5eb7d
XL
414 let mut err = self.cannot_mutate_in_immutable_section(
415 span,
416 issued_span,
417 &desc_place,
418 immutable_section_description,
419 "mutably borrow",
420 );
421 borrow_spans.var_span_label(
422 &mut err,
423 format!(
ba9703b0 424 "borrow occurs due to use of {}{}",
60c5eb7d
XL
425 desc_place,
426 borrow_spans.describe(),
427 ),
428 );
dc9dc135 429
60c5eb7d
XL
430 return err;
431 } else {
432 first_borrow_desc = "immutable ";
433 self.cannot_reborrow_already_borrowed(
434 span,
435 &desc_place,
436 &msg_place,
437 "mutable",
438 issued_span,
439 "it",
440 "immutable",
441 &msg_borrow,
442 None,
443 )
444 }
dc9dc135
XL
445 }
446
60c5eb7d 447 (BorrowKind::Unique, _) => {
dc9dc135 448 first_borrow_desc = "first ";
416331ca 449 self.cannot_uniquely_borrow_by_one_closure(
dc9dc135
XL
450 span,
451 container_name,
452 &desc_place,
453 "",
454 issued_span,
455 "it",
456 "",
457 None,
dc9dc135 458 )
dfeec247 459 }
dc9dc135 460
60c5eb7d 461 (BorrowKind::Shared, BorrowKind::Unique) => {
dc9dc135 462 first_borrow_desc = "first ";
416331ca 463 self.cannot_reborrow_already_uniquely_borrowed(
dc9dc135
XL
464 span,
465 container_name,
466 &desc_place,
467 "",
60c5eb7d 468 "immutable",
dc9dc135
XL
469 issued_span,
470 "",
471 None,
472 second_borrow_desc,
dc9dc135
XL
473 )
474 }
475
60c5eb7d 476 (BorrowKind::Mut { .. }, BorrowKind::Unique) => {
dc9dc135 477 first_borrow_desc = "first ";
416331ca 478 self.cannot_reborrow_already_uniquely_borrowed(
dc9dc135
XL
479 span,
480 container_name,
481 &desc_place,
482 "",
60c5eb7d 483 "mutable",
dc9dc135
XL
484 issued_span,
485 "",
486 None,
487 second_borrow_desc,
dc9dc135
XL
488 )
489 }
490
ba9703b0
XL
491 (BorrowKind::Shared, BorrowKind::Shared | BorrowKind::Shallow)
492 | (
493 BorrowKind::Shallow,
494 BorrowKind::Mut { .. }
495 | BorrowKind::Unique
496 | BorrowKind::Shared
497 | BorrowKind::Shallow,
498 ) => unreachable!(),
dc9dc135
XL
499 };
500
501 if issued_spans == borrow_spans {
502 borrow_spans.var_span_label(
503 &mut err,
ba9703b0 504 format!("borrows occur due to use of {}{}", desc_place, borrow_spans.describe()),
dc9dc135
XL
505 );
506 } else {
507 let borrow_place = &issued_borrow.borrowed_place;
ba9703b0 508 let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
dc9dc135
XL
509 issued_spans.var_span_label(
510 &mut err,
511 format!(
ba9703b0 512 "first borrow occurs due to use of {}{}",
dc9dc135
XL
513 borrow_place_desc,
514 issued_spans.describe(),
515 ),
516 );
517
518 borrow_spans.var_span_label(
519 &mut err,
520 format!(
ba9703b0 521 "second borrow occurs due to use of {}{}",
dc9dc135
XL
522 desc_place,
523 borrow_spans.describe(),
524 ),
525 );
526 }
527
528 if union_type_name != "" {
529 err.note(&format!(
ba9703b0 530 "{} is a field of the union `{}`, so it overlaps the field {}",
dc9dc135
XL
531 msg_place, union_type_name, msg_borrow,
532 ));
533 }
534
535 explanation.add_explanation_to_diagnostic(
536 self.infcx.tcx,
60c5eb7d
XL
537 &self.body,
538 &self.local_names,
dc9dc135
XL
539 &mut err,
540 first_borrow_desc,
541 None,
542 );
543
544 err
545 }
546
74b04a01
XL
547 fn suggest_split_at_mut_if_applicable(
548 &self,
549 err: &mut DiagnosticBuilder<'_>,
ba9703b0
XL
550 place: Place<'tcx>,
551 borrowed_place: Place<'tcx>,
74b04a01 552 ) {
ba9703b0
XL
553 if let ([ProjectionElem::Index(_)], [ProjectionElem::Index(_)]) =
554 (&place.projection[..], &borrowed_place.projection[..])
555 {
556 err.help(
557 "consider using `.split_at_mut(position)` or similar method to obtain \
74b04a01 558 two mutable non-overlapping sub-slices",
ba9703b0 559 );
74b04a01
XL
560 }
561 }
562
dc9dc135
XL
563 /// Returns the description of the root place for a conflicting borrow and the full
564 /// descriptions of the places that caused the conflict.
565 ///
566 /// In the simplest case, where there are no unions involved, if a mutable borrow of `x` is
567 /// attempted while a shared borrow is live, then this function will return:
568 ///
569 /// ("x", "", "")
570 ///
571 /// In the simple union case, if a mutable borrow of a union field `x.z` is attempted while
572 /// a shared borrow of another field `x.y`, then this function will return:
573 ///
574 /// ("x", "x.z", "x.y")
575 ///
576 /// In the more complex union case, where the union is a field of a struct, then if a mutable
577 /// borrow of a union field in a struct `x.u.z` is attempted while a shared borrow of
578 /// another field `x.u.y`, then this function will return:
579 ///
580 /// ("x.u", "x.u.z", "x.u.y")
581 ///
582 /// This is used when creating error messages like below:
583 ///
f9f354fc
XL
584 /// ```text
585 /// cannot borrow `a.u` (via `a.u.z.c`) as immutable because it is also borrowed as
586 /// mutable (via `a.u.s.b`) [E0502]
587 /// ```
60c5eb7d 588 pub(in crate::borrow_check) fn describe_place_for_conflicting_borrow(
dc9dc135 589 &self,
ba9703b0
XL
590 first_borrowed_place: Place<'tcx>,
591 second_borrowed_place: Place<'tcx>,
dc9dc135
XL
592 ) -> (String, String, String, String) {
593 // Define a small closure that we can use to check if the type of a place
594 // is a union.
416331ca 595 let union_ty = |place_base, place_projection| {
f9f354fc 596 let ty = Place::ty_from(place_base, place_projection, self.body, self.infcx.tcx).ty;
dc9dc135
XL
597 ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
598 };
dc9dc135
XL
599
600 // Start with an empty tuple, so we can use the functions on `Option` to reduce some
601 // code duplication (particularly around returning an empty description in the failure
602 // case).
603 Some(())
604 .filter(|_| {
605 // If we have a conflicting borrow of the same place, then we don't want to add
606 // an extraneous "via x.y" to our diagnostics, so filter out this case.
607 first_borrowed_place != second_borrowed_place
608 })
609 .and_then(|_| {
610 // We're going to want to traverse the first borrowed place to see if we can find
611 // field access to a union. If we find that, then we will keep the place of the
612 // union being accessed and the field that was being accessed so we can check the
613 // second borrowed place for the same union and a access to a different field.
dfeec247 614 let Place { local, projection } = first_borrowed_place;
416331ca 615
e74abb32 616 let mut cursor = projection.as_ref();
e1599b0c
XL
617 while let [proj_base @ .., elem] = cursor {
618 cursor = proj_base;
416331ca 619
dc9dc135 620 match elem {
ba9703b0
XL
621 ProjectionElem::Field(field, _) if union_ty(local, proj_base).is_some() => {
622 return Some((PlaceRef { local, projection: proj_base }, field));
dfeec247
XL
623 }
624 _ => {}
dc9dc135
XL
625 }
626 }
627 None
628 })
629 .and_then(|(target_base, target_field)| {
630 // With the place of a union and a field access into it, we traverse the second
631 // borrowed place and look for a access to a different field of the same union.
ba9703b0 632 let Place { local, ref projection } = second_borrowed_place;
416331ca 633
74b04a01 634 let mut cursor = &projection[..];
e1599b0c
XL
635 while let [proj_base @ .., elem] = cursor {
636 cursor = proj_base;
416331ca 637
dc9dc135 638 if let ProjectionElem::Field(field, _) = elem {
ba9703b0 639 if let Some(union_ty) = union_ty(local, proj_base) {
416331ca 640 if field != target_field
ba9703b0 641 && local == target_base.local
dfeec247
XL
642 && proj_base == target_base.projection
643 {
dc9dc135 644 return Some((
ba9703b0
XL
645 self.describe_any_place(PlaceRef {
646 local,
647 projection: proj_base,
648 }),
649 self.describe_any_place(first_borrowed_place.as_ref()),
650 self.describe_any_place(second_borrowed_place.as_ref()),
dc9dc135
XL
651 union_ty.to_string(),
652 ));
653 }
654 }
655 }
dc9dc135
XL
656 }
657 None
658 })
659 .unwrap_or_else(|| {
660 // If we didn't find a field access into a union, or both places match, then
661 // only return the description of the first place.
662 (
ba9703b0 663 self.describe_any_place(first_borrowed_place.as_ref()),
dc9dc135
XL
664 "".to_string(),
665 "".to_string(),
666 "".to_string(),
667 )
668 })
669 }
670
671 /// Reports StorageDeadOrDrop of `place` conflicts with `borrow`.
672 ///
673 /// This means that some data referenced by `borrow` needs to live
674 /// past the point where the StorageDeadOrDrop of `place` occurs.
675 /// This is usually interpreted as meaning that `place` has too
676 /// short a lifetime. (But sometimes it is more useful to report
677 /// it as a more direct conflict between the execution of a
678 /// `Drop::drop` with an aliasing borrow.)
60c5eb7d 679 pub(in crate::borrow_check) fn report_borrowed_value_does_not_live_long_enough(
dc9dc135
XL
680 &mut self,
681 location: Location,
682 borrow: &BorrowData<'tcx>,
ba9703b0 683 place_span: (Place<'tcx>, Span),
dc9dc135
XL
684 kind: Option<WriteKind>,
685 ) {
686 debug!(
687 "report_borrowed_value_does_not_live_long_enough(\
688 {:?}, {:?}, {:?}, {:?}\
689 )",
690 location, borrow, place_span, kind
691 );
692
693 let drop_span = place_span.1;
dfeec247
XL
694 let root_place =
695 self.prefixes(borrow.borrowed_place.as_ref(), PrefixSet::All).last().unwrap();
dc9dc135
XL
696
697 let borrow_spans = self.retrieve_borrow_spans(borrow);
698 let borrow_span = borrow_spans.var_or_use();
699
e1599b0c 700 assert!(root_place.projection.is_empty());
74b04a01 701 let proper_span = self.body.local_decls[root_place.local].source_info.span;
dc9dc135 702
e74abb32
XL
703 let root_place_projection = self.infcx.tcx.intern_place_elems(root_place.projection);
704
dfeec247 705 if self.access_place_error_reported.contains(&(
74b04a01 706 Place { local: root_place.local, projection: root_place_projection },
dfeec247
XL
707 borrow_span,
708 )) {
dc9dc135
XL
709 debug!(
710 "suppressing access_place error when borrow doesn't live long enough for {:?}",
711 borrow_span
712 );
713 return;
714 }
715
dfeec247 716 self.access_place_error_reported.insert((
74b04a01 717 Place { local: root_place.local, projection: root_place_projection },
dfeec247
XL
718 borrow_span,
719 ));
dc9dc135 720
dfeec247
XL
721 let borrowed_local = borrow.borrowed_place.local;
722 if self.body.local_decls[borrowed_local].is_ref_to_thread_local() {
723 let err =
724 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span);
725 err.buffer(&mut self.errors_buffer);
726 return;
727 }
60c5eb7d 728
dc9dc135 729 if let StorageDeadOrDrop::Destructor(dropped_ty) =
416331ca 730 self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
dc9dc135
XL
731 {
732 // If a borrow of path `B` conflicts with drop of `D` (and
733 // we're not in the uninteresting case where `B` is a
734 // prefix of `D`), then report this as a more interesting
735 // destructor conflict.
416331ca 736 if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
dc9dc135
XL
737 self.report_borrow_conflicts_with_destructor(
738 location, borrow, place_span, kind, dropped_ty,
739 );
740 return;
741 }
742 }
743
416331ca 744 let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
dc9dc135
XL
745
746 let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
747 let explanation = self.explain_why_borrow_contains_point(location, &borrow, kind_place);
748
e74abb32
XL
749 debug!(
750 "report_borrowed_value_does_not_live_long_enough(place_desc: {:?}, explanation: {:?})",
dfeec247 751 place_desc, explanation
e74abb32 752 );
dc9dc135 753 let err = match (place_desc, explanation) {
dc9dc135
XL
754 // If the outlives constraint comes from inside the closure,
755 // for example:
756 //
757 // let x = 0;
758 // let y = &x;
759 // Box::new(|| y) as Box<Fn() -> &'static i32>
760 //
761 // then just use the normal error. The closure isn't escaping
762 // and `move` will not help here.
763 (
764 Some(ref name),
765 BorrowExplanation::MustBeValidFor {
ba9703b0
XL
766 category:
767 category
768 @
769 (ConstraintCategory::Return
770 | ConstraintCategory::CallArgument
771 | ConstraintCategory::OpaqueType),
dc9dc135
XL
772 from_closure: false,
773 ref region_name,
774 span,
775 ..
776 },
ba9703b0
XL
777 ) if borrow_spans.for_generator() | borrow_spans.for_closure() => self
778 .report_escaping_closure_capture(
779 borrow_spans,
780 borrow_span,
781 region_name,
782 category,
e74abb32 783 span,
ba9703b0
XL
784 &format!("`{}`", name),
785 ),
dc9dc135
XL
786 (
787 ref name,
788 BorrowExplanation::MustBeValidFor {
789 category: ConstraintCategory::Assignment,
790 from_closure: false,
dfeec247
XL
791 region_name:
792 RegionName {
793 source:
794 RegionNameSource::AnonRegionFromUpvar(upvar_span, ref upvar_name),
795 ..
796 },
dc9dc135
XL
797 span,
798 ..
799 },
800 ) => self.report_escaping_data(borrow_span, name, upvar_span, upvar_name, span),
801 (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
802 location,
803 &name,
804 &borrow,
805 drop_span,
806 borrow_spans,
807 explanation,
808 ),
809 (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
810 location,
811 &borrow,
812 drop_span,
813 borrow_spans,
814 proper_span,
815 explanation,
816 ),
817 };
818
819 err.buffer(&mut self.errors_buffer);
820 }
821
822 fn report_local_value_does_not_live_long_enough(
823 &mut self,
824 location: Location,
825 name: &str,
826 borrow: &BorrowData<'tcx>,
827 drop_span: Span,
828 borrow_spans: UseSpans,
829 explanation: BorrowExplanation,
830 ) -> DiagnosticBuilder<'cx> {
831 debug!(
832 "report_local_value_does_not_live_long_enough(\
833 {:?}, {:?}, {:?}, {:?}, {:?}\
834 )",
835 location, name, borrow, drop_span, borrow_spans
836 );
837
838 let borrow_span = borrow_spans.var_or_use();
839 if let BorrowExplanation::MustBeValidFor {
840 category,
841 span,
842 ref opt_place_desc,
843 from_closure: false,
844 ..
dfeec247
XL
845 } = explanation
846 {
dc9dc135
XL
847 if let Some(diag) = self.try_report_cannot_return_reference_to_local(
848 borrow,
849 borrow_span,
850 span,
851 category,
852 opt_place_desc.as_ref(),
853 ) {
854 return diag;
855 }
856 }
857
dfeec247 858 let mut err = self.path_does_not_live_long_enough(borrow_span, &format!("`{}`", name));
dc9dc135
XL
859
860 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
861 let region_name = annotation.emit(self, &mut err);
862
863 err.span_label(
864 borrow_span,
865 format!("`{}` would have to be valid for `{}`...", name, region_name),
866 );
867
f9f354fc
XL
868 let fn_hir_id = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id);
869 err.span_label(
870 drop_span,
871 format!(
872 "...but `{}` will be dropped here, when the {} returns",
873 name,
874 self.infcx
875 .tcx
876 .hir()
877 .opt_name(fn_hir_id)
878 .map(|name| format!("function `{}`", name))
879 .unwrap_or_else(|| {
880 match &self
881 .infcx
882 .tcx
883 .typeck_tables_of(self.mir_def_id)
884 .node_type(fn_hir_id)
885 .kind
886 {
887 ty::Closure(..) => "enclosing closure",
888 ty::Generator(..) => "enclosing generator",
889 kind => bug!("expected closure or generator, found {:?}", kind),
890 }
891 .to_string()
892 })
893 ),
894 );
dc9dc135 895
f9f354fc
XL
896 err.note(
897 "functions cannot return a borrow to data owned within the function's scope, \
898 functions can only return borrows to data passed as arguments",
899 );
900 err.note(
901 "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
902 references-and-borrowing.html#dangling-references>",
903 );
dc9dc135
XL
904
905 if let BorrowExplanation::MustBeValidFor { .. } = explanation {
906 } else {
907 explanation.add_explanation_to_diagnostic(
908 self.infcx.tcx,
60c5eb7d
XL
909 &self.body,
910 &self.local_names,
dc9dc135
XL
911 &mut err,
912 "",
913 None,
914 );
915 }
916 } else {
917 err.span_label(borrow_span, "borrowed value does not live long enough");
dfeec247 918 err.span_label(drop_span, format!("`{}` dropped here while still borrowed", name));
dc9dc135 919
dfeec247 920 let within = if borrow_spans.for_generator() { " by generator" } else { "" };
dc9dc135 921
dfeec247 922 borrow_spans.args_span_label(&mut err, format!("value captured here{}", within));
dc9dc135
XL
923
924 explanation.add_explanation_to_diagnostic(
dfeec247
XL
925 self.infcx.tcx,
926 &self.body,
927 &self.local_names,
928 &mut err,
929 "",
930 None,
931 );
dc9dc135
XL
932 }
933
934 err
935 }
936
937 fn report_borrow_conflicts_with_destructor(
938 &mut self,
939 location: Location,
940 borrow: &BorrowData<'tcx>,
ba9703b0 941 (place, drop_span): (Place<'tcx>, Span),
dc9dc135
XL
942 kind: Option<WriteKind>,
943 dropped_ty: Ty<'tcx>,
944 ) {
945 debug!(
946 "report_borrow_conflicts_with_destructor(\
947 {:?}, {:?}, ({:?}, {:?}), {:?}\
948 )",
949 location, borrow, place, drop_span, kind,
950 );
951
952 let borrow_spans = self.retrieve_borrow_spans(borrow);
953 let borrow_span = borrow_spans.var_or_use();
954
416331ca 955 let mut err = self.cannot_borrow_across_destructor(borrow_span);
dc9dc135 956
416331ca 957 let what_was_dropped = match self.describe_place(place.as_ref()) {
60c5eb7d 958 Some(name) => format!("`{}`", name),
dc9dc135
XL
959 None => String::from("temporary value"),
960 };
961
416331ca 962 let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
dc9dc135
XL
963 Some(borrowed) => format!(
964 "here, drop of {D} needs exclusive access to `{B}`, \
965 because the type `{T}` implements the `Drop` trait",
966 D = what_was_dropped,
967 T = dropped_ty,
968 B = borrowed
969 ),
970 None => format!(
971 "here is drop of {D}; whose type `{T}` implements the `Drop` trait",
972 D = what_was_dropped,
973 T = dropped_ty
974 ),
975 };
976 err.span_label(drop_span, label);
977
978 // Only give this note and suggestion if they could be relevant.
979 let explanation =
980 self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
981 match explanation {
982 BorrowExplanation::UsedLater { .. }
983 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
984 err.note("consider using a `let` binding to create a longer lived value");
985 }
986 _ => {}
987 }
988
60c5eb7d
XL
989 explanation.add_explanation_to_diagnostic(
990 self.infcx.tcx,
991 &self.body,
992 &self.local_names,
993 &mut err,
994 "",
995 None,
996 );
dc9dc135
XL
997
998 err.buffer(&mut self.errors_buffer);
999 }
1000
1001 fn report_thread_local_value_does_not_live_long_enough(
1002 &mut self,
1003 drop_span: Span,
1004 borrow_span: Span,
1005 ) -> DiagnosticBuilder<'cx> {
1006 debug!(
1007 "report_thread_local_value_does_not_live_long_enough(\
1008 {:?}, {:?}\
1009 )",
1010 drop_span, borrow_span
1011 );
1012
416331ca 1013 let mut err = self.thread_local_value_does_not_live_long_enough(borrow_span);
dc9dc135
XL
1014
1015 err.span_label(
1016 borrow_span,
1017 "thread-local variables cannot be borrowed beyond the end of the function",
1018 );
1019 err.span_label(drop_span, "end of enclosing function is here");
1020
1021 err
1022 }
1023
1024 fn report_temporary_value_does_not_live_long_enough(
1025 &mut self,
1026 location: Location,
1027 borrow: &BorrowData<'tcx>,
1028 drop_span: Span,
1029 borrow_spans: UseSpans,
1030 proper_span: Span,
1031 explanation: BorrowExplanation,
1032 ) -> DiagnosticBuilder<'cx> {
1033 debug!(
1034 "report_temporary_value_does_not_live_long_enough(\
1035 {:?}, {:?}, {:?}, {:?}\
1036 )",
1037 location, borrow, drop_span, proper_span
1038 );
1039
dfeec247
XL
1040 if let BorrowExplanation::MustBeValidFor { category, span, from_closure: false, .. } =
1041 explanation
1042 {
dc9dc135
XL
1043 if let Some(diag) = self.try_report_cannot_return_reference_to_local(
1044 borrow,
1045 proper_span,
1046 span,
1047 category,
1048 None,
1049 ) {
1050 return diag;
1051 }
1052 }
1053
416331ca 1054 let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
dfeec247
XL
1055 err.span_label(proper_span, "creates a temporary which is freed while still in use");
1056 err.span_label(drop_span, "temporary value is freed at the end of this statement");
dc9dc135
XL
1057
1058 match explanation {
1059 BorrowExplanation::UsedLater(..)
1060 | BorrowExplanation::UsedLaterInLoop(..)
1061 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1062 // Only give this note and suggestion if it could be relevant.
1063 err.note("consider using a `let` binding to create a longer lived value");
1064 }
1065 _ => {}
1066 }
60c5eb7d
XL
1067 explanation.add_explanation_to_diagnostic(
1068 self.infcx.tcx,
1069 &self.body,
1070 &self.local_names,
1071 &mut err,
1072 "",
1073 None,
1074 );
dc9dc135 1075
dfeec247 1076 let within = if borrow_spans.for_generator() { " by generator" } else { "" };
dc9dc135 1077
dfeec247 1078 borrow_spans.args_span_label(&mut err, format!("value captured here{}", within));
dc9dc135
XL
1079
1080 err
1081 }
1082
1083 fn try_report_cannot_return_reference_to_local(
1084 &self,
1085 borrow: &BorrowData<'tcx>,
1086 borrow_span: Span,
1087 return_span: Span,
1088 category: ConstraintCategory,
1089 opt_place_desc: Option<&String>,
1090 ) -> Option<DiagnosticBuilder<'cx>> {
dc9dc135
XL
1091 let return_kind = match category {
1092 ConstraintCategory::Return => "return",
1093 ConstraintCategory::Yield => "yield",
1094 _ => return None,
1095 };
1096
1097 // FIXME use a better heuristic than Spans
dfeec247
XL
1098 let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
1099 "reference to"
1100 } else {
1101 "value referencing"
1102 };
dc9dc135
XL
1103
1104 let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
e74abb32
XL
1105 let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
1106 match self.body.local_kind(local) {
dfeec247
XL
1107 LocalKind::ReturnPointer | LocalKind::Temp => {
1108 bug!("temporary or return pointer with a name")
1109 }
e74abb32 1110 LocalKind::Var => "local variable ",
dfeec247 1111 LocalKind::Arg if !self.upvars.is_empty() && local == Local::new(1) => {
e74abb32
XL
1112 "variable captured by `move` "
1113 }
dfeec247 1114 LocalKind::Arg => "function parameter ",
dc9dc135 1115 }
e74abb32
XL
1116 } else {
1117 "local data "
dc9dc135
XL
1118 };
1119 (
1120 format!("{}`{}`", local_kind, place_desc),
1121 format!("`{}` is borrowed here", place_desc),
1122 )
1123 } else {
dfeec247
XL
1124 let root_place =
1125 self.prefixes(borrow.borrowed_place.as_ref(), PrefixSet::All).last().unwrap();
1126 let local = root_place.local;
74b04a01 1127 match self.body.local_kind(local) {
dfeec247
XL
1128 LocalKind::ReturnPointer | LocalKind::Temp => {
1129 ("temporary value".to_string(), "temporary value created here".to_string())
1130 }
dc9dc135
XL
1131 LocalKind::Arg => (
1132 "function parameter".to_string(),
1133 "function parameter borrowed here".to_string(),
1134 ),
dfeec247
XL
1135 LocalKind::Var => {
1136 ("local binding".to_string(), "local binding introduced here".to_string())
1137 }
dc9dc135
XL
1138 }
1139 };
1140
416331ca 1141 let mut err = self.cannot_return_reference_to_local(
dc9dc135
XL
1142 return_span,
1143 return_kind,
1144 reference_desc,
1145 &place_desc,
dc9dc135
XL
1146 );
1147
1148 if return_span != borrow_span {
1149 err.span_label(borrow_span, note);
1150 }
1151
1152 Some(err)
1153 }
1154
1155 fn report_escaping_closure_capture(
1156 &mut self,
e74abb32 1157 use_span: UseSpans,
dc9dc135
XL
1158 var_span: Span,
1159 fr_name: &RegionName,
1160 category: ConstraintCategory,
1161 constraint_span: Span,
1162 captured_var: &str,
1163 ) -> DiagnosticBuilder<'cx> {
1164 let tcx = self.infcx.tcx;
e74abb32 1165 let args_span = use_span.args_or_use();
dc9dc135
XL
1166
1167 let suggestion = match tcx.sess.source_map().span_to_snippet(args_span) {
e1599b0c
XL
1168 Ok(mut string) => {
1169 if string.starts_with("async ") {
1170 string.insert_str(6, "move ");
1171 } else if string.starts_with("async|") {
1172 string.insert_str(5, " move");
1173 } else {
1174 string.insert_str(0, "move ");
1175 };
1176 string
dfeec247
XL
1177 }
1178 Err(_) => "move |<args>| <body>".to_string(),
dc9dc135 1179 };
e74abb32
XL
1180 let kind = match use_span.generator_kind() {
1181 Some(generator_kind) => match generator_kind {
1182 GeneratorKind::Async(async_kind) => match async_kind {
1183 AsyncGeneratorKind::Block => "async block",
1184 AsyncGeneratorKind::Closure => "async closure",
74b04a01 1185 _ => bug!("async block/closure expected, but async function found."),
e74abb32
XL
1186 },
1187 GeneratorKind::Gen => "generator",
dfeec247 1188 },
e74abb32
XL
1189 None => "closure",
1190 };
ba9703b0
XL
1191
1192 let mut err =
1193 self.cannot_capture_in_long_lived_closure(args_span, kind, captured_var, var_span);
dc9dc135
XL
1194 err.span_suggestion(
1195 args_span,
e74abb32
XL
1196 &format!(
1197 "to force the {} to take ownership of {} (and any \
1198 other referenced variables), use the `move` keyword",
dfeec247 1199 kind, captured_var
e74abb32 1200 ),
dc9dc135
XL
1201 suggestion,
1202 Applicability::MachineApplicable,
1203 );
1204
60c5eb7d 1205 let msg = match category {
ba9703b0
XL
1206 ConstraintCategory::Return | ConstraintCategory::OpaqueType => {
1207 format!("{} is returned here", kind)
1208 }
dc9dc135
XL
1209 ConstraintCategory::CallArgument => {
1210 fr_name.highlight_region_name(&mut err);
60c5eb7d 1211 format!("function requires argument type to outlive `{}`", fr_name)
dc9dc135 1212 }
dfeec247
XL
1213 _ => bug!(
1214 "report_escaping_closure_capture called with unexpected constraint \
74b04a01 1215 category: `{:?}`",
dfeec247
XL
1216 category
1217 ),
60c5eb7d
XL
1218 };
1219 err.span_note(constraint_span, &msg);
dc9dc135
XL
1220 err
1221 }
1222
1223 fn report_escaping_data(
1224 &mut self,
1225 borrow_span: Span,
1226 name: &Option<String>,
1227 upvar_span: Span,
1228 upvar_name: &str,
1229 escape_span: Span,
1230 ) -> DiagnosticBuilder<'cx> {
1231 let tcx = self.infcx.tcx;
1232
f9f354fc 1233 let (_, escapes_from) = tcx.article_and_description(self.mir_def_id.to_def_id());
dc9dc135 1234
dfeec247
XL
1235 let mut err =
1236 borrowck_errors::borrowed_data_escapes_closure(tcx, escape_span, escapes_from);
dc9dc135
XL
1237
1238 err.span_label(
1239 upvar_span,
74b04a01 1240 format!("`{}` declared here, outside of the {} body", upvar_name, escapes_from),
dc9dc135
XL
1241 );
1242
dfeec247 1243 err.span_label(borrow_span, format!("borrow is only valid in the {} body", escapes_from));
dc9dc135
XL
1244
1245 if let Some(name) = name {
1246 err.span_label(
1247 escape_span,
1248 format!("reference to `{}` escapes the {} body here", name, escapes_from),
1249 );
1250 } else {
1251 err.span_label(
1252 escape_span,
1253 format!("reference escapes the {} body here", escapes_from),
1254 );
1255 }
1256
1257 err
1258 }
1259
1260 fn get_moved_indexes(&mut self, location: Location, mpi: MovePathIndex) -> Vec<MoveSite> {
f9f354fc
XL
1261 fn predecessor_locations(
1262 body: &'a mir::Body<'tcx>,
1263 location: Location,
1264 ) -> impl Iterator<Item = Location> + 'a {
1265 if location.statement_index == 0 {
1266 let predecessors = body.predecessors()[location.block].to_vec();
1267 Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb)))
1268 } else {
1269 Either::Right(std::iter::once(Location {
1270 statement_index: location.statement_index - 1,
1271 ..location
1272 }))
1273 }
1274 }
1275
dc9dc135 1276 let mut stack = Vec::new();
f9f354fc 1277 stack.extend(predecessor_locations(self.body, location).map(|predecessor| {
dc9dc135
XL
1278 let is_back_edge = location.dominates(predecessor, &self.dominators);
1279 (predecessor, is_back_edge)
1280 }));
1281
1282 let mut visited = FxHashSet::default();
1283 let mut result = vec![];
1284
1285 'dfs: while let Some((location, is_back_edge)) = stack.pop() {
1286 debug!(
1287 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
1288 location, is_back_edge
1289 );
1290
1291 if !visited.insert(location) {
1292 continue;
1293 }
1294
1295 // check for moves
dfeec247
XL
1296 let stmt_kind =
1297 self.body[location.block].statements.get(location.statement_index).map(|s| &s.kind);
dc9dc135
XL
1298 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
1299 // this analysis only tries to find moves explicitly
1300 // written by the user, so we ignore the move-outs
1301 // created by `StorageDead` and at the beginning
1302 // of a function.
1303 } else {
1304 // If we are found a use of a.b.c which was in error, then we want to look for
1305 // moves not only of a.b.c but also a.b and a.
1306 //
1307 // Note that the moves data already includes "parent" paths, so we don't have to
1308 // worry about the other case: that is, if there is a move of a.b.c, it is already
1309 // marked as a move of a.b and a as well, so we will generate the correct errors
1310 // there.
1311 let mut mpis = vec![mpi];
1312 let move_paths = &self.move_data.move_paths;
74b04a01 1313 mpis.extend(move_paths[mpi].parents(move_paths).map(|(mpi, _)| mpi));
dc9dc135
XL
1314
1315 for moi in &self.move_data.loc_map[location] {
1316 debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
1317 if mpis.contains(&self.move_data.moves[*moi].path) {
1318 debug!("report_use_of_moved_or_uninitialized: found");
dfeec247 1319 result.push(MoveSite { moi: *moi, traversed_back_edge: is_back_edge });
dc9dc135
XL
1320
1321 // Strictly speaking, we could continue our DFS here. There may be
1322 // other moves that can reach the point of error. But it is kind of
1323 // confusing to highlight them.
1324 //
1325 // Example:
1326 //
1327 // ```
1328 // let a = vec![];
1329 // let b = a;
1330 // let c = a;
1331 // drop(a); // <-- current point of error
1332 // ```
1333 //
1334 // Because we stop the DFS here, we only highlight `let c = a`,
1335 // and not `let b = a`. We will of course also report an error at
1336 // `let c = a` which highlights `let b = a` as the move.
1337 continue 'dfs;
1338 }
1339 }
1340 }
1341
1342 // check for inits
1343 let mut any_match = false;
1344 drop_flag_effects::for_location_inits(
1345 self.infcx.tcx,
60c5eb7d 1346 &self.body,
dc9dc135
XL
1347 self.move_data,
1348 location,
1349 |m| {
1350 if m == mpi {
1351 any_match = true;
1352 }
1353 },
1354 );
1355 if any_match {
1356 continue 'dfs;
1357 }
1358
f9f354fc 1359 stack.extend(predecessor_locations(self.body, location).map(|predecessor| {
dc9dc135
XL
1360 let back_edge = location.dominates(predecessor, &self.dominators);
1361 (predecessor, is_back_edge || back_edge)
1362 }));
1363 }
1364
1365 result
1366 }
1367
60c5eb7d 1368 pub(in crate::borrow_check) fn report_illegal_mutation_of_borrowed(
dc9dc135
XL
1369 &mut self,
1370 location: Location,
ba9703b0 1371 (place, span): (Place<'tcx>, Span),
dc9dc135
XL
1372 loan: &BorrowData<'tcx>,
1373 ) {
1374 let loan_spans = self.retrieve_borrow_spans(loan);
1375 let loan_span = loan_spans.args_or_use();
1376
ba9703b0 1377 let descr_place = self.describe_any_place(place.as_ref());
dc9dc135 1378 if loan.kind == BorrowKind::Shallow {
ba9703b0 1379 if let Some(section) = self.classify_immutable_section(loan.assigned_place) {
60c5eb7d
XL
1380 let mut err = self.cannot_mutate_in_immutable_section(
1381 span,
1382 loan_span,
ba9703b0 1383 &descr_place,
60c5eb7d
XL
1384 section,
1385 "assign",
1386 );
1387 loan_spans.var_span_label(
1388 &mut err,
1389 format!("borrow occurs due to use{}", loan_spans.describe()),
1390 );
dc9dc135 1391
60c5eb7d 1392 err.buffer(&mut self.errors_buffer);
dc9dc135 1393
60c5eb7d
XL
1394 return;
1395 }
dc9dc135
XL
1396 }
1397
ba9703b0 1398 let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place);
dc9dc135 1399
dfeec247
XL
1400 loan_spans
1401 .var_span_label(&mut err, format!("borrow occurs due to use{}", loan_spans.describe()));
1402
1403 self.explain_why_borrow_contains_point(location, loan, None).add_explanation_to_diagnostic(
1404 self.infcx.tcx,
1405 &self.body,
1406 &self.local_names,
dc9dc135 1407 &mut err,
dfeec247
XL
1408 "",
1409 None,
dc9dc135
XL
1410 );
1411
dc9dc135
XL
1412 err.buffer(&mut self.errors_buffer);
1413 }
1414
1415 /// Reports an illegal reassignment; for example, an assignment to
1416 /// (part of) a non-`mut` local that occurs potentially after that
1417 /// local has already been initialized. `place` is the path being
1418 /// assigned; `err_place` is a place providing a reason why
1419 /// `place` is not mutable (e.g., the non-`mut` local `x` in an
1420 /// assignment to `x.f`).
60c5eb7d 1421 pub(in crate::borrow_check) fn report_illegal_reassignment(
dc9dc135
XL
1422 &mut self,
1423 _location: Location,
ba9703b0 1424 (place, span): (Place<'tcx>, Span),
dc9dc135 1425 assigned_span: Span,
ba9703b0 1426 err_place: Place<'tcx>,
dc9dc135 1427 ) {
60c5eb7d
XL
1428 let (from_arg, local_decl, local_name) = match err_place.as_local() {
1429 Some(local) => (
1430 self.body.local_kind(local) == LocalKind::Arg,
1431 Some(&self.body.local_decls[local]),
1432 self.local_names[local],
1433 ),
1434 None => (false, None, None),
dc9dc135
XL
1435 };
1436
1437 // If root local is initialized immediately (everything apart from let
1438 // PATTERN;) then make the error refer to that local, rather than the
1439 // place being assigned later.
1440 let (place_description, assigned_span) = match local_decl {
ba9703b0 1441 Some(LocalDecl {
dfeec247 1442 local_info:
f9f354fc 1443 Some(box LocalInfo::User(
ba9703b0
XL
1444 ClearCrossCrate::Clear
1445 | ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1446 opt_match_place: None,
1447 ..
1448 })),
f9f354fc
XL
1449 ))
1450 | Some(box LocalInfo::StaticRef { .. })
1451 | None,
dc9dc135
XL
1452 ..
1453 })
ba9703b0
XL
1454 | None => (self.describe_any_place(place.as_ref()), assigned_span),
1455 Some(decl) => (self.describe_any_place(err_place.as_ref()), decl.source_info.span),
dc9dc135
XL
1456 };
1457
ba9703b0 1458 let mut err = self.cannot_reassign_immutable(span, &place_description, from_arg);
dc9dc135
XL
1459 let msg = if from_arg {
1460 "cannot assign to immutable argument"
1461 } else {
1462 "cannot assign twice to immutable variable"
1463 };
1464 if span != assigned_span {
1465 if !from_arg {
ba9703b0 1466 err.span_label(assigned_span, format!("first assignment to {}", place_description));
dc9dc135
XL
1467 }
1468 }
1469 if let Some(decl) = local_decl {
60c5eb7d 1470 if let Some(name) = local_name {
dc9dc135
XL
1471 if decl.can_be_made_mutable() {
1472 err.span_suggestion(
1473 decl.source_info.span,
1474 "make this binding mutable",
1475 format!("mut {}", name),
1476 Applicability::MachineApplicable,
1477 );
1478 }
1479 }
1480 }
1481 err.span_label(span, msg);
1482 err.buffer(&mut self.errors_buffer);
1483 }
1484
74b04a01 1485 fn classify_drop_access_kind(&self, place: PlaceRef<'tcx>) -> StorageDeadOrDrop<'tcx> {
dc9dc135 1486 let tcx = self.infcx.tcx;
416331ca 1487 match place.projection {
dfeec247 1488 [] => StorageDeadOrDrop::LocalStorageDead,
e1599b0c
XL
1489 [proj_base @ .., elem] => {
1490 // FIXME(spastorino) make this iterate
416331ca 1491 let base_access = self.classify_drop_access_kind(PlaceRef {
dfeec247 1492 local: place.local,
e1599b0c 1493 projection: proj_base,
416331ca 1494 });
dc9dc135
XL
1495 match elem {
1496 ProjectionElem::Deref => match base_access {
1497 StorageDeadOrDrop::LocalStorageDead
1498 | StorageDeadOrDrop::BoxedStorageDead => {
1499 assert!(
f9f354fc 1500 Place::ty_from(place.local, proj_base, self.body, tcx).ty.is_box(),
dc9dc135
XL
1501 "Drop of value behind a reference or raw pointer"
1502 );
1503 StorageDeadOrDrop::BoxedStorageDead
1504 }
1505 StorageDeadOrDrop::Destructor(_) => base_access,
1506 },
1507 ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
f9f354fc 1508 let base_ty = Place::ty_from(place.local, proj_base, self.body, tcx).ty;
e74abb32 1509 match base_ty.kind {
dc9dc135
XL
1510 ty::Adt(def, _) if def.has_dtor(tcx) => {
1511 // Report the outermost adt with a destructor
1512 match base_access {
1513 StorageDeadOrDrop::Destructor(_) => base_access,
1514 StorageDeadOrDrop::LocalStorageDead
1515 | StorageDeadOrDrop::BoxedStorageDead => {
1516 StorageDeadOrDrop::Destructor(base_ty)
1517 }
1518 }
1519 }
1520 _ => base_access,
1521 }
1522 }
1523
1524 ProjectionElem::ConstantIndex { .. }
1525 | ProjectionElem::Subslice { .. }
1526 | ProjectionElem::Index(_) => base_access,
1527 }
1528 }
1529 }
1530 }
1531
60c5eb7d 1532 /// Describe the reason for the fake borrow that was assigned to `place`.
ba9703b0
XL
1533 fn classify_immutable_section(&self, place: Place<'tcx>) -> Option<&'static str> {
1534 use rustc_middle::mir::visit::Visitor;
1535 struct FakeReadCauseFinder<'tcx> {
1536 place: Place<'tcx>,
60c5eb7d
XL
1537 cause: Option<FakeReadCause>,
1538 }
ba9703b0 1539 impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'tcx> {
60c5eb7d
XL
1540 fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
1541 match statement {
ba9703b0
XL
1542 Statement { kind: StatementKind::FakeRead(cause, box place), .. }
1543 if *place == self.place =>
dfeec247 1544 {
60c5eb7d
XL
1545 self.cause = Some(*cause);
1546 }
1547 _ => (),
1548 }
1549 }
1550 }
1551 let mut visitor = FakeReadCauseFinder { place, cause: None };
ba9703b0 1552 visitor.visit_body(&self.body);
60c5eb7d
XL
1553 match visitor.cause {
1554 Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
1555 Some(FakeReadCause::ForIndex) => Some("indexing expression"),
1556 _ => None,
1557 }
1558 }
1559
dc9dc135
XL
1560 /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1561 /// borrow of local value that does not live long enough.
1562 fn annotate_argument_and_return_for_borrow(
1563 &self,
1564 borrow: &BorrowData<'tcx>,
1565 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1566 // Define a fallback for when we can't match a closure.
1567 let fallback = || {
f9f354fc 1568 let is_closure = self.infcx.tcx.is_closure(self.mir_def_id.to_def_id());
dc9dc135
XL
1569 if is_closure {
1570 None
1571 } else {
1572 let ty = self.infcx.tcx.type_of(self.mir_def_id);
e74abb32 1573 match ty.kind {
f9f354fc
XL
1574 ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig(
1575 self.mir_def_id.to_def_id(),
1576 self.infcx.tcx.fn_sig(self.mir_def_id),
1577 ),
dc9dc135
XL
1578 _ => None,
1579 }
1580 }
1581 };
1582
1583 // In order to determine whether we need to annotate, we need to check whether the reserve
1584 // place was an assignment into a temporary.
1585 //
1586 // If it was, we check whether or not that temporary is eventually assigned into the return
1587 // place. If it was, we can add annotations about the function's return type and arguments
1588 // and it'll make sense.
1589 let location = borrow.reserve_location;
dfeec247
XL
1590 debug!("annotate_argument_and_return_for_borrow: location={:?}", location);
1591 if let Some(&Statement { kind: StatementKind::Assign(box (ref reservation, _)), .. }) =
1592 &self.body[location.block].statements.get(location.statement_index)
dc9dc135 1593 {
dfeec247 1594 debug!("annotate_argument_and_return_for_borrow: reservation={:?}", reservation);
dc9dc135 1595 // Check that the initial assignment of the reserve location is into a temporary.
e74abb32
XL
1596 let mut target = match reservation.as_local() {
1597 Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
dc9dc135
XL
1598 _ => return None,
1599 };
1600
1601 // Next, look through the rest of the block, checking if we are assigning the
1602 // `target` (that is, the place that contains our borrow) to anything.
1603 let mut annotated_closure = None;
dfeec247 1604 for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
dc9dc135
XL
1605 debug!(
1606 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1607 target, stmt
1608 );
dfeec247 1609 if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind {
e74abb32
XL
1610 if let Some(assigned_to) = place.as_local() {
1611 debug!(
1612 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1613 rvalue={:?}",
1614 assigned_to, rvalue
1615 );
1616 // Check if our `target` was captured by a closure.
1617 if let Rvalue::Aggregate(
1618 box AggregateKind::Closure(def_id, substs),
1619 operands,
1620 ) = rvalue
1621 {
1622 for operand in operands {
1623 let assigned_from = match operand {
1624 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1625 assigned_from
1626 }
1627 _ => continue,
1628 };
1629 debug!(
1630 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
dc9dc135 1631 assigned_from
e74abb32 1632 );
dc9dc135 1633
e74abb32
XL
1634 // Find the local from the operand.
1635 let assigned_from_local = match assigned_from.local_or_deref_local()
1636 {
1637 Some(local) => local,
1638 None => continue,
1639 };
dc9dc135 1640
e74abb32
XL
1641 if assigned_from_local != target {
1642 continue;
1643 }
dc9dc135 1644
e74abb32
XL
1645 // If a closure captured our `target` and then assigned
1646 // into a place then we should annotate the closure in
1647 // case it ends up being assigned into the return place.
ba9703b0
XL
1648 annotated_closure =
1649 self.annotate_fn_sig(*def_id, substs.as_closure().sig());
e74abb32
XL
1650 debug!(
1651 "annotate_argument_and_return_for_borrow: \
1652 annotated_closure={:?} assigned_from_local={:?} \
1653 assigned_to={:?}",
1654 annotated_closure, assigned_from_local, assigned_to
1655 );
1656
1657 if assigned_to == mir::RETURN_PLACE {
1658 // If it was assigned directly into the return place, then
1659 // return now.
1660 return annotated_closure;
1661 } else {
1662 // Otherwise, update the target.
1663 target = assigned_to;
1664 }
dc9dc135 1665 }
dc9dc135 1666
e74abb32
XL
1667 // If none of our closure's operands matched, then skip to the next
1668 // statement.
1669 continue;
1670 }
dc9dc135 1671
e74abb32
XL
1672 // Otherwise, look at other types of assignment.
1673 let assigned_from = match rvalue {
1674 Rvalue::Ref(_, _, assigned_from) => assigned_from,
1675 Rvalue::Use(operand) => match operand {
1676 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1677 assigned_from
1678 }
1679 _ => continue,
1680 },
dc9dc135 1681 _ => continue,
e74abb32
XL
1682 };
1683 debug!(
1684 "annotate_argument_and_return_for_borrow: \
1685 assigned_from={:?}",
1686 assigned_from,
1687 );
dc9dc135 1688
e74abb32
XL
1689 // Find the local from the rvalue.
1690 let assigned_from_local = match assigned_from.local_or_deref_local() {
1691 Some(local) => local,
1692 None => continue,
1693 };
1694 debug!(
1695 "annotate_argument_and_return_for_borrow: \
1696 assigned_from_local={:?}",
1697 assigned_from_local,
1698 );
dc9dc135 1699
e74abb32
XL
1700 // Check if our local matches the target - if so, we've assigned our
1701 // borrow to a new place.
1702 if assigned_from_local != target {
1703 continue;
1704 }
dc9dc135 1705
e74abb32
XL
1706 // If we assigned our `target` into a new place, then we should
1707 // check if it was the return place.
1708 debug!(
1709 "annotate_argument_and_return_for_borrow: \
1710 assigned_from_local={:?} assigned_to={:?}",
1711 assigned_from_local, assigned_to
1712 );
1713 if assigned_to == mir::RETURN_PLACE {
1714 // If it was then return the annotated closure if there was one,
1715 // else, annotate this function.
1716 return annotated_closure.or_else(fallback);
1717 }
dc9dc135 1718
e74abb32
XL
1719 // If we didn't assign into the return place, then we just update
1720 // the target.
1721 target = assigned_to;
1722 }
dc9dc135
XL
1723 }
1724 }
1725
1726 // Check the terminator if we didn't find anything in the statements.
1727 let terminator = &self.body[location.block].terminator();
1728 debug!(
1729 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
1730 target, terminator
1731 );
dfeec247
XL
1732 if let TerminatorKind::Call { destination: Some((place, _)), args, .. } =
1733 &terminator.kind
dc9dc135 1734 {
e74abb32 1735 if let Some(assigned_to) = place.as_local() {
dc9dc135 1736 debug!(
e74abb32
XL
1737 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
1738 assigned_to, args
dc9dc135 1739 );
e74abb32
XL
1740 for operand in args {
1741 let assigned_from = match operand {
1742 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1743 assigned_from
1744 }
1745 _ => continue,
1746 };
dc9dc135 1747 debug!(
e74abb32
XL
1748 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1749 assigned_from,
dc9dc135
XL
1750 );
1751
e74abb32
XL
1752 if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
1753 debug!(
1754 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
1755 assigned_from_local,
1756 );
1757
1758 if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
1759 return annotated_closure.or_else(fallback);
1760 }
dc9dc135
XL
1761 }
1762 }
1763 }
1764 }
1765 }
1766
1767 // If we haven't found an assignment into the return place, then we need not add
1768 // any annotations.
1769 debug!("annotate_argument_and_return_for_borrow: none found");
1770 None
1771 }
1772
1773 /// Annotate the first argument and return type of a function signature if they are
1774 /// references.
1775 fn annotate_fn_sig(
1776 &self,
1777 did: DefId,
1778 sig: ty::PolyFnSig<'tcx>,
1779 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1780 debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
1781 let is_closure = self.infcx.tcx.is_closure(did);
f9f354fc 1782 let fn_hir_id = self.infcx.tcx.hir().as_local_hir_id(did.as_local()?);
dc9dc135
XL
1783 let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
1784
1785 // We need to work out which arguments to highlight. We do this by looking
1786 // at the return type, where there are three cases:
1787 //
1788 // 1. If there are named arguments, then we should highlight the return type and
1789 // highlight any of the arguments that are also references with that lifetime.
1790 // If there are no arguments that have the same lifetime as the return type,
1791 // then don't highlight anything.
1792 // 2. The return type is a reference with an anonymous lifetime. If this is
1793 // the case, then we can take advantage of (and teach) the lifetime elision
1794 // rules.
1795 //
1796 // We know that an error is being reported. So the arguments and return type
1797 // must satisfy the elision rules. Therefore, if there is a single argument
1798 // then that means the return type and first (and only) argument have the same
1799 // lifetime and the borrow isn't meeting that, we can highlight the argument
1800 // and return type.
1801 //
1802 // If there are multiple arguments then the first argument must be self (else
1803 // it would not satisfy the elision rules), so we can highlight self and the
1804 // return type.
1805 // 3. The return type is not a reference. In this case, we don't highlight
1806 // anything.
1807 let return_ty = sig.output();
e74abb32 1808 match return_ty.skip_binder().kind {
dc9dc135
XL
1809 ty::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
1810 // This is case 1 from above, return type is a named reference so we need to
1811 // search for relevant arguments.
1812 let mut arguments = Vec::new();
1813 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
e74abb32 1814 if let ty::Ref(argument_region, _, _) = argument.kind {
dc9dc135 1815 if argument_region == return_region {
ba9703b0 1816 // Need to use the `rustc_middle::ty` types to compare against the
dfeec247 1817 // `return_region`. Then use the `rustc_hir` type to get only
dc9dc135 1818 // the lifetime span.
e74abb32 1819 if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].kind {
dc9dc135
XL
1820 // With access to the lifetime, we can get
1821 // the span of it.
1822 arguments.push((*argument, lifetime.span));
1823 } else {
1824 bug!("ty type is a ref but hir type is not");
1825 }
1826 }
1827 }
1828 }
1829
1830 // We need to have arguments. This shouldn't happen, but it's worth checking.
1831 if arguments.is_empty() {
1832 return None;
1833 }
1834
1835 // We use a mix of the HIR and the Ty types to get information
1836 // as the HIR doesn't have full types for closure arguments.
1837 let return_ty = *sig.output().skip_binder();
1838 let mut return_span = fn_decl.output.span();
74b04a01 1839 if let hir::FnRetTy::Return(ty) = &fn_decl.output {
e74abb32 1840 if let hir::TyKind::Rptr(lifetime, _) = ty.kind {
dc9dc135
XL
1841 return_span = lifetime.span;
1842 }
1843 }
1844
1845 Some(AnnotatedBorrowFnSignature::NamedFunction {
1846 arguments,
1847 return_ty,
1848 return_span,
1849 })
1850 }
1851 ty::Ref(_, _, _) if is_closure => {
1852 // This is case 2 from above but only for closures, return type is anonymous
1853 // reference so we select
1854 // the first argument.
1855 let argument_span = fn_decl.inputs.first()?.span;
1856 let argument_ty = sig.inputs().skip_binder().first()?;
1857
1858 // Closure arguments are wrapped in a tuple, so we need to get the first
1859 // from that.
e74abb32 1860 if let ty::Tuple(elems) = argument_ty.kind {
dc9dc135 1861 let argument_ty = elems.first()?.expect_ty();
e74abb32 1862 if let ty::Ref(_, _, _) = argument_ty.kind {
dc9dc135
XL
1863 return Some(AnnotatedBorrowFnSignature::Closure {
1864 argument_ty,
1865 argument_span,
1866 });
1867 }
1868 }
1869
1870 None
1871 }
1872 ty::Ref(_, _, _) => {
1873 // This is also case 2 from above but for functions, return type is still an
1874 // anonymous reference so we select the first argument.
1875 let argument_span = fn_decl.inputs.first()?.span;
1876 let argument_ty = sig.inputs().skip_binder().first()?;
1877
1878 let return_span = fn_decl.output.span();
1879 let return_ty = *sig.output().skip_binder();
1880
1881 // We expect the first argument to be a reference.
e74abb32 1882 match argument_ty.kind {
dc9dc135
XL
1883 ty::Ref(_, _, _) => {}
1884 _ => return None,
1885 }
1886
1887 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
1888 argument_ty,
1889 argument_span,
1890 return_ty,
1891 return_span,
1892 })
1893 }
1894 _ => {
1895 // This is case 3 from above, return type is not a reference so don't highlight
1896 // anything.
1897 None
1898 }
1899 }
1900 }
1901}
1902
1903#[derive(Debug)]
1904enum AnnotatedBorrowFnSignature<'tcx> {
1905 NamedFunction {
1906 arguments: Vec<(Ty<'tcx>, Span)>,
1907 return_ty: Ty<'tcx>,
1908 return_span: Span,
1909 },
1910 AnonymousFunction {
1911 argument_ty: Ty<'tcx>,
1912 argument_span: Span,
1913 return_ty: Ty<'tcx>,
1914 return_span: Span,
1915 },
1916 Closure {
1917 argument_ty: Ty<'tcx>,
1918 argument_span: Span,
1919 },
1920}
1921
1922impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
1923 /// Annotate the provided diagnostic with information about borrow from the fn signature that
1924 /// helps explain.
60c5eb7d 1925 pub(in crate::borrow_check) fn emit(
dc9dc135
XL
1926 &self,
1927 cx: &mut MirBorrowckCtxt<'_, 'tcx>,
1928 diag: &mut DiagnosticBuilder<'_>,
1929 ) -> String {
1930 match self {
dfeec247 1931 AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
dc9dc135
XL
1932 diag.span_label(
1933 *argument_span,
1934 format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
1935 );
1936
1937 cx.get_region_name_for_ty(argument_ty, 0)
1938 }
1939 AnnotatedBorrowFnSignature::AnonymousFunction {
1940 argument_ty,
1941 argument_span,
1942 return_ty,
1943 return_span,
1944 } => {
1945 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
1946 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
1947
1948 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
1949 let types_equal = return_ty_name == argument_ty_name;
1950 diag.span_label(
1951 *return_span,
1952 format!(
1953 "{}has type `{}`",
1954 if types_equal { "also " } else { "" },
1955 return_ty_name,
1956 ),
1957 );
1958
1959 diag.note(
1960 "argument and return type have the same lifetime due to lifetime elision rules",
1961 );
1962 diag.note(
1963 "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
1964 lifetime-syntax.html#lifetime-elision>",
1965 );
1966
1967 cx.get_region_name_for_ty(return_ty, 0)
1968 }
dfeec247 1969 AnnotatedBorrowFnSignature::NamedFunction { arguments, return_ty, return_span } => {
dc9dc135
XL
1970 // Region of return type and arguments checked to be the same earlier.
1971 let region_name = cx.get_region_name_for_ty(return_ty, 0);
1972 for (_, argument_span) in arguments {
1973 diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
1974 }
1975
dfeec247 1976 diag.span_label(*return_span, format!("also has lifetime `{}`", region_name,));
dc9dc135
XL
1977
1978 diag.help(&format!(
1979 "use data from the highlighted arguments which match the `{}` lifetime of \
1980 the return type",
1981 region_name,
1982 ));
1983
1984 region_name
1985 }
1986 }
1987 }
1988}