11use syntax:: ast:: { self , AstNode } ;
22
3- use crate :: { AssistContext , AssistId , AssistKind , Assists } ;
3+ use crate :: { utils :: suggest_name , AssistContext , AssistId , AssistKind , Assists } ;
44
55// Assist: replace_is_some_with_if_let_some
66//
@@ -16,7 +16,7 @@ use crate::{AssistContext, AssistId, AssistKind, Assists};
1616// ```
1717// fn main() {
1818// let x = Some(1);
19- // if let Some(${0:_tmp }) = x {}
19+ // if let Some(${0:x }) = x {}
2020// }
2121// ```
2222pub ( crate ) fn replace_is_method_with_if_let_method (
@@ -35,6 +35,13 @@ pub(crate) fn replace_is_method_with_if_let_method(
3535 match name_ref. text ( ) . as_str ( ) {
3636 "is_some" | "is_ok" => {
3737 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+
3845 let target = call_expr. syntax ( ) . text_range ( ) ;
3946
4047 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(
4451 } ;
4552
4653 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) ;
4856 edit. replace ( target, replacement) ;
4957 } )
5058 }
@@ -71,7 +79,27 @@ fn main() {
7179 r#"
7280fn main() {
7381 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() {}
75103}
76104"# ,
77105 ) ;
@@ -103,7 +131,27 @@ fn main() {
103131 r#"
104132fn main() {
105133 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() {}
107155}
108156"# ,
109157 ) ;
0 commit comments