1
1
use syntax:: ast:: { self , AstNode } ;
2
2
3
- use crate :: { AssistContext , AssistId , AssistKind , Assists } ;
3
+ use crate :: { utils :: suggest_name , AssistContext , AssistId , AssistKind , Assists } ;
4
4
5
5
// Assist: replace_is_some_with_if_let_some
6
6
//
@@ -16,7 +16,7 @@ use crate::{AssistContext, AssistId, AssistKind, Assists};
16
16
// ```
17
17
// fn main() {
18
18
// let x = Some(1);
19
- // if let Some(${0:_tmp }) = x {}
19
+ // if let Some(${0:x }) = x {}
20
20
// }
21
21
// ```
22
22
pub ( crate ) fn replace_is_method_with_if_let_method (
@@ -35,6 +35,13 @@ pub(crate) fn replace_is_method_with_if_let_method(
35
35
match name_ref. text ( ) . as_str ( ) {
36
36
"is_some" | "is_ok" => {
37
37
let receiver = call_expr. receiver ( ) ?;
38
+
39
+ let var_name = if let ast:: Expr :: PathExpr ( path_expr) = receiver. clone ( ) {
40
+ path_expr. path ( ) ?. to_string ( )
41
+ } else {
42
+ suggest_name:: for_variable ( & receiver, & ctx. sema )
43
+ } ;
44
+
38
45
let target = call_expr. syntax ( ) . text_range ( ) ;
39
46
40
47
let ( assist_id, message, text) = if name_ref. text ( ) == "is_some" {
@@ -44,7 +51,8 @@ pub(crate) fn replace_is_method_with_if_let_method(
44
51
} ;
45
52
46
53
acc. add ( AssistId ( assist_id, AssistKind :: RefactorRewrite ) , message, target, |edit| {
47
- let replacement = format ! ( "let {}({}) = {}" , text, "${0:_tmp}" , receiver) ;
54
+ let var_name = format ! ( "${{0:{}}}" , var_name) ;
55
+ let replacement = format ! ( "let {}({}) = {}" , text, var_name, receiver) ;
48
56
edit. replace ( target, replacement) ;
49
57
} )
50
58
}
@@ -71,7 +79,27 @@ fn main() {
71
79
r#"
72
80
fn main() {
73
81
let x = Some(1);
74
- if let Some(${0:_tmp}) = x {}
82
+ if let Some(${0:x}) = x {}
83
+ }
84
+ "# ,
85
+ ) ;
86
+
87
+ check_assist (
88
+ replace_is_method_with_if_let_method,
89
+ r#"
90
+ fn test() -> Option<i32> {
91
+ Some(1)
92
+ }
93
+ fn main() {
94
+ if test().is_som$0e() {}
95
+ }
96
+ "# ,
97
+ r#"
98
+ fn test() -> Option<i32> {
99
+ Some(1)
100
+ }
101
+ fn main() {
102
+ if let Some(${0:test}) = test() {}
75
103
}
76
104
"# ,
77
105
) ;
@@ -103,7 +131,27 @@ fn main() {
103
131
r#"
104
132
fn main() {
105
133
let x = Ok(1);
106
- if let Ok(${0:_tmp}) = x {}
134
+ if let Ok(${0:x}) = x {}
135
+ }
136
+ "# ,
137
+ ) ;
138
+
139
+ check_assist (
140
+ replace_is_method_with_if_let_method,
141
+ r#"
142
+ fn test() -> Result<i32> {
143
+ Ok(1)
144
+ }
145
+ fn main() {
146
+ if test().is_o$0k() {}
147
+ }
148
+ "# ,
149
+ r#"
150
+ fn test() -> Result<i32> {
151
+ Ok(1)
152
+ }
153
+ fn main() {
154
+ if let Ok(${0:test}) = test() {}
107
155
}
108
156
"# ,
109
157
) ;
0 commit comments