Skip to content

Commit d5151b7

Browse files
Rollup merge of #163191 - chenyukang:yukang-fix-as-mut-closure-suggestion, r=nnethercote
Enhance mutable closure suggestions with as_mut() support This PR changed `can_use_as_ref` to support `as_mut` when `as_ref` is not proper.
2 parents 8f07588 + 87e95d6 commit d5151b7

4 files changed

Lines changed: 202 additions & 10 deletions

File tree

‎compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs‎

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2856,7 +2856,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
28562856
true
28572857
}
28582858

2859-
/// Identify some cases where `as_ref()` would be appropriate and suggest it.
2859+
/// Identify some cases where `as_ref()` or `as_mut()` would be appropriate and suggest it.
28602860
///
28612861
/// Given the following code:
28622862
/// ```compile_fail,E0308
@@ -2872,7 +2872,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
28722872
/// ```ignore (illustrative)
28732873
/// opt.map(|param| { takes_ref(param) });
28742874
/// ```
2875-
fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Vec<(Span, String)>, &'static str)> {
2875+
fn can_use_as_ref_or_mut(
2876+
&self,
2877+
expr: &hir::Expr<'_>,
2878+
mutability: hir::Mutability,
2879+
) -> Option<(Vec<(Span, String)>, &'static str)> {
28762880
let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind else {
28772881
return None;
28782882
};
@@ -2909,21 +2913,30 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
29092913
return None;
29102914
};
29112915

2912-
let self_ty = self.typeck_results.borrow().expr_ty_opt(receiver)?;
2916+
let mut self_ty = self.typeck_results.borrow().expr_ty_opt(receiver)?;
2917+
while let ty::Ref(_, inner, ref_mutability) = self_ty.kind() {
2918+
// `as_mut()` cannot borrow through a shared reference,
2919+
// also we cannot suggest `as_ref()` either when the reference is shared
2920+
if mutability.is_mut() && ref_mutability.is_not() {
2921+
return None;
2922+
}
2923+
self_ty = *inner;
2924+
}
29132925
let name = method_path.ident.name;
2914-
let is_as_ref_able = match self_ty.peel_refs().kind() {
2926+
let can_borrow = match self_ty.kind() {
29152927
ty::Adt(def, _) => {
29162928
(self.tcx.is_diagnostic_item(sym::Option, def.did())
29172929
|| self.tcx.is_diagnostic_item(sym::Result, def.did()))
29182930
&& (name == sym::map || name == sym::and_then)
29192931
}
29202932
_ => false,
29212933
};
2922-
if is_as_ref_able {
2923-
Some((
2924-
vec![(method_path.ident.span.shrink_to_lo(), "as_ref().".to_string())],
2925-
"consider using `as_ref` instead",
2926-
))
2934+
if can_borrow {
2935+
let (suggestion, message) = match mutability {
2936+
hir::Mutability::Not => ("as_ref().", "consider using `as_ref` instead"),
2937+
hir::Mutability::Mut => ("as_mut().", "consider using `as_mut` instead"),
2938+
};
2939+
Some((vec![(method_path.ident.span.shrink_to_lo(), suggestion.to_string())], message))
29272940
} else {
29282941
None
29292942
}
@@ -3114,7 +3127,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
31143127
return Some((suggs, help, app, mutref));
31153128
}
31163129

3117-
if let Some((sugg, msg)) = self.can_use_as_ref(expr) {
3130+
if let Some((sugg, msg)) = self.can_use_as_ref_or_mut(expr, mutability) {
31183131
return Some((
31193132
sugg,
31203133
msg.to_string(),
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Borrowing a container for a closure argument must preserve the expected mutability.
2+
//@ run-rustfix
3+
4+
#![allow(unused_mut)]
5+
6+
fn append(value: &mut String) {
7+
value.push('!');
8+
}
9+
10+
fn increment(value: &mut i32) {
11+
*value += 1;
12+
}
13+
14+
fn main() {
15+
let mut option = Some(String::new());
16+
let _ = option.as_mut().map(|arg| append(arg));
17+
//~^ ERROR mismatched types
18+
let _ = (&mut option).as_mut().and_then(|arg| Some(append(arg)));
19+
//~^ ERROR mismatched types
20+
21+
let mut result: Result<_, ()> = Ok(String::new());
22+
let _ = result.as_mut().map(|arg| append(arg));
23+
//~^ ERROR mismatched types
24+
let _ = (&mut result).as_mut().and_then(|arg| Ok(append(arg)));
25+
//~^ ERROR mismatched types
26+
27+
// A shared reference cannot supply `as_mut()`. Borrow the copied argument instead.
28+
let shared = &Some(0);
29+
let _ = shared.map(|mut arg| increment(&mut arg));
30+
//~^ ERROR mismatched types
31+
let nested = &mut &Some(0);
32+
let _ = nested.map(|mut arg| increment(&mut arg));
33+
//~^ ERROR mismatched types
34+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Borrowing a container for a closure argument must preserve the expected mutability.
2+
//@ run-rustfix
3+
4+
#![allow(unused_mut)]
5+
6+
fn append(value: &mut String) {
7+
value.push('!');
8+
}
9+
10+
fn increment(value: &mut i32) {
11+
*value += 1;
12+
}
13+
14+
fn main() {
15+
let mut option = Some(String::new());
16+
let _ = option.map(|arg| append(arg));
17+
//~^ ERROR mismatched types
18+
let _ = (&mut option).and_then(|arg| Some(append(arg)));
19+
//~^ ERROR mismatched types
20+
21+
let mut result: Result<_, ()> = Ok(String::new());
22+
let _ = result.map(|arg| append(arg));
23+
//~^ ERROR mismatched types
24+
let _ = (&mut result).and_then(|arg| Ok(append(arg)));
25+
//~^ ERROR mismatched types
26+
27+
// A shared reference cannot supply `as_mut()`. Borrow the copied argument instead.
28+
let shared = &Some(0);
29+
let _ = shared.map(|mut arg| increment(arg));
30+
//~^ ERROR mismatched types
31+
let nested = &mut &Some(0);
32+
let _ = nested.map(|mut arg| increment(arg));
33+
//~^ ERROR mismatched types
34+
}
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
error[E0308]: mismatched types
2+
--> $DIR/as-mut-closure.rs:16:37
3+
|
4+
LL | let _ = option.map(|arg| append(arg));
5+
| ------ ^^^ expected `&mut String`, found `String`
6+
| |
7+
| arguments to this function are incorrect
8+
|
9+
note: function defined here
10+
--> $DIR/as-mut-closure.rs:6:4
11+
|
12+
LL | fn append(value: &mut String) {
13+
| ^^^^^^ ------------------
14+
help: consider using `as_mut` instead
15+
|
16+
LL | let _ = option.as_mut().map(|arg| append(arg));
17+
| +++++++++
18+
19+
error[E0308]: mismatched types
20+
--> $DIR/as-mut-closure.rs:18:54
21+
|
22+
LL | let _ = (&mut option).and_then(|arg| Some(append(arg)));
23+
| ------ ^^^ expected `&mut String`, found `String`
24+
| |
25+
| arguments to this function are incorrect
26+
|
27+
note: function defined here
28+
--> $DIR/as-mut-closure.rs:6:4
29+
|
30+
LL | fn append(value: &mut String) {
31+
| ^^^^^^ ------------------
32+
help: consider using `as_mut` instead
33+
|
34+
LL | let _ = (&mut option).as_mut().and_then(|arg| Some(append(arg)));
35+
| +++++++++
36+
37+
error[E0308]: mismatched types
38+
--> $DIR/as-mut-closure.rs:22:37
39+
|
40+
LL | let _ = result.map(|arg| append(arg));
41+
| ------ ^^^ expected `&mut String`, found `String`
42+
| |
43+
| arguments to this function are incorrect
44+
|
45+
note: function defined here
46+
--> $DIR/as-mut-closure.rs:6:4
47+
|
48+
LL | fn append(value: &mut String) {
49+
| ^^^^^^ ------------------
50+
help: consider using `as_mut` instead
51+
|
52+
LL | let _ = result.as_mut().map(|arg| append(arg));
53+
| +++++++++
54+
55+
error[E0308]: mismatched types
56+
--> $DIR/as-mut-closure.rs:24:52
57+
|
58+
LL | let _ = (&mut result).and_then(|arg| Ok(append(arg)));
59+
| ------ ^^^ expected `&mut String`, found `String`
60+
| |
61+
| arguments to this function are incorrect
62+
|
63+
note: function defined here
64+
--> $DIR/as-mut-closure.rs:6:4
65+
|
66+
LL | fn append(value: &mut String) {
67+
| ^^^^^^ ------------------
68+
help: consider using `as_mut` instead
69+
|
70+
LL | let _ = (&mut result).as_mut().and_then(|arg| Ok(append(arg)));
71+
| +++++++++
72+
73+
error[E0308]: mismatched types
74+
--> $DIR/as-mut-closure.rs:29:44
75+
|
76+
LL | let _ = shared.map(|mut arg| increment(arg));
77+
| --------- ^^^ expected `&mut i32`, found integer
78+
| |
79+
| arguments to this function are incorrect
80+
|
81+
note: function defined here
82+
--> $DIR/as-mut-closure.rs:10:4
83+
|
84+
LL | fn increment(value: &mut i32) {
85+
| ^^^^^^^^^ ---------------
86+
help: consider mutably borrowing here
87+
|
88+
LL | let _ = shared.map(|mut arg| increment(&mut arg));
89+
| ++++
90+
91+
error[E0308]: mismatched types
92+
--> $DIR/as-mut-closure.rs:32:44
93+
|
94+
LL | let _ = nested.map(|mut arg| increment(arg));
95+
| --------- ^^^ expected `&mut i32`, found integer
96+
| |
97+
| arguments to this function are incorrect
98+
|
99+
note: function defined here
100+
--> $DIR/as-mut-closure.rs:10:4
101+
|
102+
LL | fn increment(value: &mut i32) {
103+
| ^^^^^^^^^ ---------------
104+
help: consider mutably borrowing here
105+
|
106+
LL | let _ = nested.map(|mut arg| increment(&mut arg));
107+
| ++++
108+
109+
error: aborting due to 6 previous errors
110+
111+
For more information about this error, try `rustc --explain E0308`.

0 commit comments

Comments
 (0)