-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
conflict_errors.rs
2026 lines (1840 loc) · 76.1 KB
/
conflict_errors.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use rustc::hir;
use rustc::hir::def_id::DefId;
use rustc::mir::{
self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, ConstraintCategory, Local,
LocalDecl, LocalKind, Location, Operand, Place, PlaceBase, PlaceRef, ProjectionElem, Rvalue,
Statement, StatementKind, TerminatorKind, VarBindingForm,
};
use rustc::ty::{self, Ty};
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::indexed_vec::Idx;
use rustc_errors::{Applicability, DiagnosticBuilder};
use syntax_pos::Span;
use syntax::source_map::DesugaringKind;
use super::nll::explain_borrow::BorrowExplanation;
use super::nll::region_infer::{RegionName, RegionNameSource};
use super::prefixes::IsPrefixOf;
use super::WriteKind;
use super::borrow_set::BorrowData;
use super::MirBorrowckCtxt;
use super::{InitializationRequiringAction, PrefixSet};
use super::error_reporting::{IncludingDowncast, UseSpans};
use crate::dataflow::drop_flag_effects;
use crate::dataflow::indexes::{MovePathIndex, MoveOutIndex};
use crate::util::borrowck_errors;
#[derive(Debug)]
struct MoveSite {
/// Index of the "move out" that we found. The `MoveData` can
/// then tell us where the move occurred.
moi: MoveOutIndex,
/// `true` if we traversed a back edge while walking from the point
/// of error to the move site.
traversed_back_edge: bool
}
/// Which case a StorageDeadOrDrop is for.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum StorageDeadOrDrop<'tcx> {
LocalStorageDead,
BoxedStorageDead,
Destructor(Ty<'tcx>),
}
impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
pub(super) fn report_use_of_moved_or_uninitialized(
&mut self,
location: Location,
desired_action: InitializationRequiringAction,
(moved_place, used_place, span): (PlaceRef<'cx, 'tcx>, PlaceRef<'cx, 'tcx>, Span),
mpi: MovePathIndex,
) {
debug!(
"report_use_of_moved_or_uninitialized: location={:?} desired_action={:?} \
moved_place={:?} used_place={:?} span={:?} mpi={:?}",
location, desired_action, moved_place, used_place, span, mpi
);
let use_spans = self.move_spans(moved_place, location)
.or_else(|| self.borrow_spans(span, location));
let span = use_spans.args_or_use();
let move_site_vec = self.get_moved_indexes(location, mpi);
debug!(
"report_use_of_moved_or_uninitialized: move_site_vec={:?}",
move_site_vec
);
let move_out_indices: Vec<_> = move_site_vec
.iter()
.map(|move_site| move_site.moi)
.collect();
if move_out_indices.is_empty() {
let root_place = self
.prefixes(used_place, PrefixSet::All)
.last()
.unwrap();
if self.uninitialized_error_reported.contains(&root_place) {
debug!(
"report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
root_place
);
return;
}
self.uninitialized_error_reported.insert(root_place);
let item_msg = match self.describe_place_with_options(used_place,
IncludingDowncast(true)) {
Some(name) => format!("`{}`", name),
None => "value".to_owned(),
};
let mut err = self.cannot_act_on_uninitialized_variable(
span,
desired_action.as_noun(),
&self.describe_place_with_options(moved_place, IncludingDowncast(true))
.unwrap_or_else(|| "_".to_owned()),
);
err.span_label(span, format!("use of possibly-uninitialized {}", item_msg));
use_spans.var_span_label(
&mut err,
format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
);
// This error should not be downgraded to a warning,
// even in migrate mode.
self.disable_error_downgrading();
err.buffer(&mut self.errors_buffer);
} else {
if let Some((reported_place, _)) = self.move_error_reported.get(&move_out_indices) {
if self.prefixes(*reported_place, PrefixSet::All)
.any(|p| p == used_place)
{
debug!(
"report_use_of_moved_or_uninitialized place: error suppressed \
mois={:?}",
move_out_indices
);
return;
}
}
let msg = ""; //FIXME: add "partially " or "collaterally "
let mut err = self.cannot_act_on_moved_value(
span,
desired_action.as_noun(),
msg,
self.describe_place_with_options(moved_place, IncludingDowncast(true)),
);
self.add_moved_or_invoked_closure_note(
location,
used_place,
&mut err,
);
let mut is_loop_move = false;
let is_partial_move = move_site_vec.iter().any(|move_site| {
let move_out = self.move_data.moves[(*move_site).moi];
let moved_place = &self.move_data.move_paths[move_out.path].place;
used_place != moved_place.as_ref()
&& used_place.is_prefix_of(moved_place.as_ref())
});
for move_site in &move_site_vec {
let move_out = self.move_data.moves[(*move_site).moi];
let moved_place = &self.move_data.move_paths[move_out.path].place;
let move_spans = self.move_spans(moved_place.as_ref(), move_out.source);
let move_span = move_spans.args_or_use();
let move_msg = if move_spans.for_closure() {
" into closure"
} else {
""
};
if span == move_span {
err.span_label(
span,
format!("value moved{} here, in previous iteration of loop", move_msg),
);
is_loop_move = true;
} else if move_site.traversed_back_edge {
err.span_label(
move_span,
format!(
"value moved{} here, in previous iteration of loop",
move_msg
),
);
} else {
err.span_label(move_span, format!("value moved{} here", move_msg));
move_spans.var_span_label(
&mut err,
format!("variable moved due to use{}", move_spans.describe()),
);
}
if Some(DesugaringKind::ForLoop) == move_span.desugaring_kind() {
if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
err.span_suggestion(
move_span,
"consider borrowing to avoid moving into the for loop",
format!("&{}", snippet),
Applicability::MaybeIncorrect,
);
}
}
}
use_spans.var_span_label(
&mut err,
format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
);
if !is_loop_move {
err.span_label(
span,
format!(
"value {} here {}",
desired_action.as_verb_in_past_tense(),
if is_partial_move { "after partial move" } else { "after move" },
),
);
}
let ty =
Place::ty_from(used_place.base, used_place.projection, self.body, self.infcx.tcx)
.ty;
let needs_note = match ty.sty {
ty::Closure(id, _) => {
let tables = self.infcx.tcx.typeck_tables_of(id);
let hir_id = self.infcx.tcx.hir().as_local_hir_id(id).unwrap();
tables.closure_kind_origins().get(hir_id).is_none()
}
_ => true,
};
if needs_note {
let mpi = self.move_data.moves[move_out_indices[0]].path;
let place = &self.move_data.move_paths[mpi].place;
let ty = place.ty(self.body, self.infcx.tcx).ty;
let opt_name =
self.describe_place_with_options(place.as_ref(), IncludingDowncast(true));
let note_msg = match opt_name {
Some(ref name) => format!("`{}`", name),
None => "value".to_owned(),
};
if let ty::Param(param_ty) = ty.sty {
let tcx = self.infcx.tcx;
let generics = tcx.generics_of(self.mir_def_id);
let def_id = generics.type_param(¶m_ty, tcx).def_id;
if let Some(sp) = tcx.hir().span_if_local(def_id) {
err.span_label(
sp,
"consider adding a `Copy` constraint to this type argument",
);
}
}
let span = if let Place {
base: PlaceBase::Local(local),
projection: box [],
} = place {
let decl = &self.body.local_decls[*local];
Some(decl.source_info.span)
} else {
None
};
self.note_type_does_not_implement_copy(
&mut err,
¬e_msg,
ty,
span,
);
}
if let Some((_, mut old_err)) = self.move_error_reported
.insert(move_out_indices, (used_place, err))
{
// Cancel the old error so it doesn't ICE.
old_err.cancel();
}
}
}
pub(super) fn report_move_out_while_borrowed(
&mut self,
location: Location,
(place, span): (&Place<'tcx>, Span),
borrow: &BorrowData<'tcx>,
) {
debug!(
"report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
location, place, span, borrow
);
let value_msg = match self.describe_place(place.as_ref()) {
Some(name) => format!("`{}`", name),
None => "value".to_owned(),
};
let borrow_msg = match self.describe_place(borrow.borrowed_place.as_ref()) {
Some(name) => format!("`{}`", name),
None => "value".to_owned(),
};
let borrow_spans = self.retrieve_borrow_spans(borrow);
let borrow_span = borrow_spans.args_or_use();
let move_spans = self.move_spans(place.as_ref(), location);
let span = move_spans.args_or_use();
let mut err = self.cannot_move_when_borrowed(
span,
&self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
);
err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
err.span_label(span, format!("move out of {} occurs here", value_msg));
borrow_spans.var_span_label(
&mut err,
format!("borrow occurs due to use{}", borrow_spans.describe())
);
move_spans.var_span_label(
&mut err,
format!("move occurs due to use{}", move_spans.describe())
);
self.explain_why_borrow_contains_point(
location,
borrow,
None,
).add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", Some(borrow_span));
err.buffer(&mut self.errors_buffer);
}
pub(super) fn report_use_while_mutably_borrowed(
&mut self,
location: Location,
(place, _span): (&Place<'tcx>, Span),
borrow: &BorrowData<'tcx>,
) -> DiagnosticBuilder<'cx> {
let borrow_spans = self.retrieve_borrow_spans(borrow);
let borrow_span = borrow_spans.args_or_use();
// Conflicting borrows are reported separately, so only check for move
// captures.
let use_spans = self.move_spans(place.as_ref(), location);
let span = use_spans.var_or_use();
let mut err = self.cannot_use_when_mutably_borrowed(
span,
&self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
borrow_span,
&self.describe_place(borrow.borrowed_place.as_ref())
.unwrap_or_else(|| "_".to_owned()),
);
borrow_spans.var_span_label(&mut err, {
let place = &borrow.borrowed_place;
let desc_place =
self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned());
format!("borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe())
});
self.explain_why_borrow_contains_point(location, borrow, None)
.add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", None);
err
}
pub(super) fn report_conflicting_borrow(
&mut self,
location: Location,
(place, span): (&Place<'tcx>, Span),
gen_borrow_kind: BorrowKind,
issued_borrow: &BorrowData<'tcx>,
) -> DiagnosticBuilder<'cx> {
let issued_spans = self.retrieve_borrow_spans(issued_borrow);
let issued_span = issued_spans.args_or_use();
let borrow_spans = self.borrow_spans(span, location);
let span = borrow_spans.args_or_use();
let container_name = if issued_spans.for_generator() || borrow_spans.for_generator() {
"generator"
} else {
"closure"
};
let (desc_place, msg_place, msg_borrow, union_type_name) =
self.describe_place_for_conflicting_borrow(place, &issued_borrow.borrowed_place);
let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
let second_borrow_desc = if explanation.is_explained() {
"second "
} else {
""
};
// FIXME: supply non-"" `opt_via` when appropriate
let first_borrow_desc;
let mut err = match (
gen_borrow_kind,
"immutable",
"mutable",
issued_borrow.kind,
"immutable",
"mutable",
) {
(BorrowKind::Shared, lft, _, BorrowKind::Mut { .. }, _, rgt) => {
first_borrow_desc = "mutable ";
self.cannot_reborrow_already_borrowed(
span,
&desc_place,
&msg_place,
lft,
issued_span,
"it",
rgt,
&msg_borrow,
None,
)
}
(BorrowKind::Mut { .. }, _, lft, BorrowKind::Shared, rgt, _) => {
first_borrow_desc = "immutable ";
self.cannot_reborrow_already_borrowed(
span,
&desc_place,
&msg_place,
lft,
issued_span,
"it",
rgt,
&msg_borrow,
None,
)
}
(BorrowKind::Mut { .. }, _, _, BorrowKind::Mut { .. }, _, _) => {
first_borrow_desc = "first ";
self.cannot_mutably_borrow_multiply(
span,
&desc_place,
&msg_place,
issued_span,
&msg_borrow,
None,
)
}
(BorrowKind::Unique, _, _, BorrowKind::Unique, _, _) => {
first_borrow_desc = "first ";
self.cannot_uniquely_borrow_by_two_closures(
span,
&desc_place,
issued_span,
None,
)
}
(BorrowKind::Mut { .. }, _, _, BorrowKind::Shallow, _, _)
| (BorrowKind::Unique, _, _, BorrowKind::Shallow, _, _) => {
let mut err = self.cannot_mutate_in_match_guard(
span,
issued_span,
&desc_place,
"mutably borrow",
);
borrow_spans.var_span_label(
&mut err,
format!(
"borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe()
),
);
return err;
}
(BorrowKind::Unique, _, _, _, _, _) => {
first_borrow_desc = "first ";
self.cannot_uniquely_borrow_by_one_closure(
span,
container_name,
&desc_place,
"",
issued_span,
"it",
"",
None,
)
},
(BorrowKind::Shared, lft, _, BorrowKind::Unique, _, _) => {
first_borrow_desc = "first ";
self.cannot_reborrow_already_uniquely_borrowed(
span,
container_name,
&desc_place,
"",
lft,
issued_span,
"",
None,
second_borrow_desc,
)
}
(BorrowKind::Mut { .. }, _, lft, BorrowKind::Unique, _, _) => {
first_borrow_desc = "first ";
self.cannot_reborrow_already_uniquely_borrowed(
span,
container_name,
&desc_place,
"",
lft,
issued_span,
"",
None,
second_borrow_desc,
)
}
(BorrowKind::Shared, _, _, BorrowKind::Shared, _, _)
| (BorrowKind::Shared, _, _, BorrowKind::Shallow, _, _)
| (BorrowKind::Shallow, _, _, BorrowKind::Mut { .. }, _, _)
| (BorrowKind::Shallow, _, _, BorrowKind::Unique, _, _)
| (BorrowKind::Shallow, _, _, BorrowKind::Shared, _, _)
| (BorrowKind::Shallow, _, _, BorrowKind::Shallow, _, _) => unreachable!(),
};
if issued_spans == borrow_spans {
borrow_spans.var_span_label(
&mut err,
format!("borrows occur due to use of `{}`{}", desc_place, borrow_spans.describe()),
);
} else {
let borrow_place = &issued_borrow.borrowed_place;
let borrow_place_desc = self.describe_place(borrow_place.as_ref())
.unwrap_or_else(|| "_".to_owned());
issued_spans.var_span_label(
&mut err,
format!(
"first borrow occurs due to use of `{}`{}",
borrow_place_desc,
issued_spans.describe(),
),
);
borrow_spans.var_span_label(
&mut err,
format!(
"second borrow occurs due to use of `{}`{}",
desc_place,
borrow_spans.describe(),
),
);
}
if union_type_name != "" {
err.note(&format!(
"`{}` is a field of the union `{}`, so it overlaps the field `{}`",
msg_place, union_type_name, msg_borrow,
));
}
explanation.add_explanation_to_diagnostic(
self.infcx.tcx,
self.body,
&mut err,
first_borrow_desc,
None,
);
err
}
/// Returns the description of the root place for a conflicting borrow and the full
/// descriptions of the places that caused the conflict.
///
/// In the simplest case, where there are no unions involved, if a mutable borrow of `x` is
/// attempted while a shared borrow is live, then this function will return:
///
/// ("x", "", "")
///
/// In the simple union case, if a mutable borrow of a union field `x.z` is attempted while
/// a shared borrow of another field `x.y`, then this function will return:
///
/// ("x", "x.z", "x.y")
///
/// In the more complex union case, where the union is a field of a struct, then if a mutable
/// borrow of a union field in a struct `x.u.z` is attempted while a shared borrow of
/// another field `x.u.y`, then this function will return:
///
/// ("x.u", "x.u.z", "x.u.y")
///
/// This is used when creating error messages like below:
///
/// > cannot borrow `a.u` (via `a.u.z.c`) as immutable because it is also borrowed as
/// > mutable (via `a.u.s.b`) [E0502]
pub(super) fn describe_place_for_conflicting_borrow(
&self,
first_borrowed_place: &Place<'tcx>,
second_borrowed_place: &Place<'tcx>,
) -> (String, String, String, String) {
// Define a small closure that we can use to check if the type of a place
// is a union.
let union_ty = |place_base, place_projection| {
let ty = Place::ty_from(place_base, place_projection, self.body, self.infcx.tcx).ty;
ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
};
let describe_place = |place| self.describe_place(place).unwrap_or_else(|| "_".to_owned());
// Start with an empty tuple, so we can use the functions on `Option` to reduce some
// code duplication (particularly around returning an empty description in the failure
// case).
Some(())
.filter(|_| {
// If we have a conflicting borrow of the same place, then we don't want to add
// an extraneous "via x.y" to our diagnostics, so filter out this case.
first_borrowed_place != second_borrowed_place
})
.and_then(|_| {
// We're going to want to traverse the first borrowed place to see if we can find
// field access to a union. If we find that, then we will keep the place of the
// union being accessed and the field that was being accessed so we can check the
// second borrowed place for the same union and a access to a different field.
let Place {
base,
projection,
} = first_borrowed_place;
let mut cursor = &**projection;
while let [proj_base @ .., elem] = cursor {
cursor = proj_base;
match elem {
ProjectionElem::Field(field, _) if union_ty(base, proj_base).is_some() => {
return Some((PlaceRef {
base: base,
projection: proj_base,
}, field));
},
_ => {},
}
}
None
})
.and_then(|(target_base, target_field)| {
// With the place of a union and a field access into it, we traverse the second
// borrowed place and look for a access to a different field of the same union.
let Place {
base,
projection,
} = second_borrowed_place;
let mut cursor = &**projection;
while let [proj_base @ .., elem] = cursor {
cursor = proj_base;
if let ProjectionElem::Field(field, _) = elem {
if let Some(union_ty) = union_ty(base, proj_base) {
if field != target_field
&& base == target_base.base
&& proj_base == target_base.projection {
// FIXME when we avoid clone reuse describe_place closure
let describe_base_place = self.describe_place(PlaceRef {
base: base,
projection: proj_base,
}).unwrap_or_else(|| "_".to_owned());
return Some((
describe_base_place,
describe_place(first_borrowed_place.as_ref()),
describe_place(second_borrowed_place.as_ref()),
union_ty.to_string(),
));
}
}
}
}
None
})
.unwrap_or_else(|| {
// If we didn't find a field access into a union, or both places match, then
// only return the description of the first place.
(
describe_place(first_borrowed_place.as_ref()),
"".to_string(),
"".to_string(),
"".to_string(),
)
})
}
/// Reports StorageDeadOrDrop of `place` conflicts with `borrow`.
///
/// This means that some data referenced by `borrow` needs to live
/// past the point where the StorageDeadOrDrop of `place` occurs.
/// This is usually interpreted as meaning that `place` has too
/// short a lifetime. (But sometimes it is more useful to report
/// it as a more direct conflict between the execution of a
/// `Drop::drop` with an aliasing borrow.)
pub(super) fn report_borrowed_value_does_not_live_long_enough(
&mut self,
location: Location,
borrow: &BorrowData<'tcx>,
place_span: (&Place<'tcx>, Span),
kind: Option<WriteKind>,
) {
debug!(
"report_borrowed_value_does_not_live_long_enough(\
{:?}, {:?}, {:?}, {:?}\
)",
location, borrow, place_span, kind
);
let drop_span = place_span.1;
let root_place = self.prefixes(borrow.borrowed_place.as_ref(), PrefixSet::All)
.last()
.unwrap();
let borrow_spans = self.retrieve_borrow_spans(borrow);
let borrow_span = borrow_spans.var_or_use();
assert!(root_place.projection.is_empty());
let proper_span = match root_place.base {
PlaceBase::Local(local) => self.body.local_decls[*local].source_info.span,
_ => drop_span,
};
if self.access_place_error_reported
.contains(&(Place {
base: root_place.base.clone(),
projection: root_place.projection.to_vec().into_boxed_slice(),
}, borrow_span))
{
debug!(
"suppressing access_place error when borrow doesn't live long enough for {:?}",
borrow_span
);
return;
}
self.access_place_error_reported
.insert((Place {
base: root_place.base.clone(),
projection: root_place.projection.to_vec().into_boxed_slice(),
}, borrow_span));
if let StorageDeadOrDrop::Destructor(dropped_ty) =
self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
{
// If a borrow of path `B` conflicts with drop of `D` (and
// we're not in the uninteresting case where `B` is a
// prefix of `D`), then report this as a more interesting
// destructor conflict.
if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
self.report_borrow_conflicts_with_destructor(
location, borrow, place_span, kind, dropped_ty,
);
return;
}
}
let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
let explanation = self.explain_why_borrow_contains_point(location, &borrow, kind_place);
let err = match (place_desc, explanation) {
(Some(_), _) if self.is_place_thread_local(root_place) => {
self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span)
}
// If the outlives constraint comes from inside the closure,
// for example:
//
// let x = 0;
// let y = &x;
// Box::new(|| y) as Box<Fn() -> &'static i32>
//
// then just use the normal error. The closure isn't escaping
// and `move` will not help here.
(
Some(ref name),
BorrowExplanation::MustBeValidFor {
category: category @ ConstraintCategory::Return,
from_closure: false,
ref region_name,
span,
..
},
)
| (
Some(ref name),
BorrowExplanation::MustBeValidFor {
category: category @ ConstraintCategory::CallArgument,
from_closure: false,
ref region_name,
span,
..
},
) if borrow_spans.for_closure() => self.report_escaping_closure_capture(
borrow_spans.args_or_use(),
borrow_span,
region_name,
category,
span,
&format!("`{}`", name),
),
(
ref name,
BorrowExplanation::MustBeValidFor {
category: ConstraintCategory::Assignment,
from_closure: false,
region_name: RegionName {
source: RegionNameSource::AnonRegionFromUpvar(upvar_span, ref upvar_name),
..
},
span,
..
},
) => self.report_escaping_data(borrow_span, name, upvar_span, upvar_name, span),
(Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
location,
&name,
&borrow,
drop_span,
borrow_spans,
explanation,
),
(None, explanation) => self.report_temporary_value_does_not_live_long_enough(
location,
&borrow,
drop_span,
borrow_spans,
proper_span,
explanation,
),
};
err.buffer(&mut self.errors_buffer);
}
fn report_local_value_does_not_live_long_enough(
&mut self,
location: Location,
name: &str,
borrow: &BorrowData<'tcx>,
drop_span: Span,
borrow_spans: UseSpans,
explanation: BorrowExplanation,
) -> DiagnosticBuilder<'cx> {
debug!(
"report_local_value_does_not_live_long_enough(\
{:?}, {:?}, {:?}, {:?}, {:?}\
)",
location, name, borrow, drop_span, borrow_spans
);
let borrow_span = borrow_spans.var_or_use();
if let BorrowExplanation::MustBeValidFor {
category,
span,
ref opt_place_desc,
from_closure: false,
..
} = explanation {
if let Some(diag) = self.try_report_cannot_return_reference_to_local(
borrow,
borrow_span,
span,
category,
opt_place_desc.as_ref(),
) {
return diag;
}
}
let mut err = self.path_does_not_live_long_enough(
borrow_span,
&format!("`{}`", name),
);
if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
let region_name = annotation.emit(self, &mut err);
err.span_label(
borrow_span,
format!("`{}` would have to be valid for `{}`...", name, region_name),
);
if let Some(fn_hir_id) = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id) {
err.span_label(
drop_span,
format!(
"...but `{}` will be dropped here, when the function `{}` returns",
name,
self.infcx.tcx.hir().name(fn_hir_id),
),
);
err.note(
"functions cannot return a borrow to data owned within the function's scope, \
functions can only return borrows to data passed as arguments",
);
err.note(
"to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
references-and-borrowing.html#dangling-references>",
);
} else {
err.span_label(
drop_span,
format!("...but `{}` dropped here while still borrowed", name),
);
}
if let BorrowExplanation::MustBeValidFor { .. } = explanation {
} else {
explanation.add_explanation_to_diagnostic(
self.infcx.tcx,
self.body,
&mut err,
"",
None,
);
}
} else {
err.span_label(borrow_span, "borrowed value does not live long enough");
err.span_label(
drop_span,
format!("`{}` dropped here while still borrowed", name),
);
let within = if borrow_spans.for_generator() {
" by generator"
} else {
""
};
borrow_spans.args_span_label(
&mut err,
format!("value captured here{}", within),
);
explanation.add_explanation_to_diagnostic(
self.infcx.tcx, self.body, &mut err, "", None);
}
err
}
fn report_borrow_conflicts_with_destructor(
&mut self,
location: Location,
borrow: &BorrowData<'tcx>,
(place, drop_span): (&Place<'tcx>, Span),
kind: Option<WriteKind>,
dropped_ty: Ty<'tcx>,
) {
debug!(
"report_borrow_conflicts_with_destructor(\
{:?}, {:?}, ({:?}, {:?}), {:?}\
)",
location, borrow, place, drop_span, kind,
);
let borrow_spans = self.retrieve_borrow_spans(borrow);
let borrow_span = borrow_spans.var_or_use();
let mut err = self.cannot_borrow_across_destructor(borrow_span);
let what_was_dropped = match self.describe_place(place.as_ref()) {
Some(name) => format!("`{}`", name.as_str()),
None => String::from("temporary value"),
};
let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
Some(borrowed) => format!(
"here, drop of {D} needs exclusive access to `{B}`, \
because the type `{T}` implements the `Drop` trait",
D = what_was_dropped,
T = dropped_ty,
B = borrowed
),
None => format!(
"here is drop of {D}; whose type `{T}` implements the `Drop` trait",
D = what_was_dropped,
T = dropped_ty
),
};
err.span_label(drop_span, label);
// Only give this note and suggestion if they could be relevant.
let explanation =
self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
match explanation {
BorrowExplanation::UsedLater { .. }
| BorrowExplanation::UsedLaterWhenDropped { .. } => {
err.note("consider using a `let` binding to create a longer lived value");
}
_ => {}
}
explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", None);
err.buffer(&mut self.errors_buffer);
}
fn report_thread_local_value_does_not_live_long_enough(
&mut self,
drop_span: Span,
borrow_span: Span,
) -> DiagnosticBuilder<'cx> {
debug!(
"report_thread_local_value_does_not_live_long_enough(\