Skip to content

Commit 793a5e6

Browse files
authored
Rollup merge of #68819 - estebank:split_at_mut, r=oli-obk
Suggest `split_at_mut` on multiple mutable index access cc #58792.
2 parents a25ce40 + 0f73133 commit 793a5e6

File tree

3 files changed

+48
-2
lines changed

3 files changed

+48
-2
lines changed

src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs

+25-2
Original file line numberDiff line numberDiff line change
@@ -397,14 +397,20 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
397397

398398
(BorrowKind::Mut { .. }, BorrowKind::Mut { .. }) => {
399399
first_borrow_desc = "first ";
400-
self.cannot_mutably_borrow_multiply(
400+
let mut err = self.cannot_mutably_borrow_multiply(
401401
span,
402402
&desc_place,
403403
&msg_place,
404404
issued_span,
405405
&msg_borrow,
406406
None,
407-
)
407+
);
408+
self.suggest_split_at_mut_if_applicable(
409+
&mut err,
410+
&place,
411+
&issued_borrow.borrowed_place,
412+
);
413+
err
408414
}
409415

410416
(BorrowKind::Unique, BorrowKind::Unique) => {
@@ -549,6 +555,23 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
549555
err
550556
}
551557

558+
fn suggest_split_at_mut_if_applicable(
559+
&self,
560+
err: &mut DiagnosticBuilder<'_>,
561+
place: &Place<'tcx>,
562+
borrowed_place: &Place<'tcx>,
563+
) {
564+
match (&place.projection[..], &borrowed_place.projection[..]) {
565+
([ProjectionElem::Index(_)], [ProjectionElem::Index(_)]) => {
566+
err.help(
567+
"consider using `.split_at_mut(position)` or similar method to obtain \
568+
two mutable non-overlapping sub-slices",
569+
);
570+
}
571+
_ => {}
572+
}
573+
}
574+
552575
/// Returns the description of the root place for a conflicting borrow and the full
553576
/// descriptions of the places that caused the conflict.
554577
///
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
fn main() {
2+
let mut foo = [1, 2, 3, 4];
3+
let a = &mut foo[2];
4+
let b = &mut foo[3]; //~ ERROR cannot borrow `foo[_]` as mutable more than once at a time
5+
*a = 5;
6+
*b = 6;
7+
println!("{:?} {:?}", a, b);
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error[E0499]: cannot borrow `foo[_]` as mutable more than once at a time
2+
--> $DIR/suggest-split-at-mut.rs:4:13
3+
|
4+
LL | let a = &mut foo[2];
5+
| ----------- first mutable borrow occurs here
6+
LL | let b = &mut foo[3];
7+
| ^^^^^^^^^^^ second mutable borrow occurs here
8+
LL | *a = 5;
9+
| ------ first borrow later used here
10+
|
11+
= help: consider using `.split_at_mut(position)` or similar method to obtain two mutable non-overlapping sub-slices
12+
13+
error: aborting due to previous error
14+
15+
For more information about this error, try `rustc --explain E0499`.

0 commit comments

Comments
 (0)