1
1
use crate :: {
2
2
assist_context:: { AssistContext , Assists } ,
3
- utils , AssistId ,
3
+ AssistId ,
4
4
} ;
5
5
use syntax:: {
6
- ast:: { self , Adt , Impl , NameOwner } ,
7
- AstNode , Direction ,
6
+ ast:: { self , Impl , NameOwner } ,
7
+ AstNode ,
8
8
} ;
9
9
use test_utils:: mark;
10
10
@@ -60,28 +60,23 @@ pub(crate) fn generate_default_from_new(acc: &mut Assists, ctx: &AssistContext)
60
60
"Generate a Default impl from a new fn" ,
61
61
insert_location,
62
62
move |builder| {
63
- let default_fn_syntax = default_fn_node_for_new ( impl_) ;
64
- if let Some ( code) = default_fn_syntax {
65
- builder. insert ( insert_location. end ( ) , code)
66
- }
63
+ let code = default_fn_node_for_new ( impl_) ;
64
+ builder. insert ( insert_location. end ( ) , code) ;
67
65
} ,
68
66
)
69
67
}
70
68
71
- fn default_fn_node_for_new ( impl_ : Impl ) -> Option < String > {
72
- // the code string is this way due to formatting reason
73
- let code = r#" fn default() -> Self {
69
+ fn default_fn_node_for_new ( impl_ : Impl ) -> String {
70
+ format ! (
71
+ "
72
+
73
+ impl Default for {} {{
74
+ fn default() -> Self {{
74
75
Self::new()
75
- }"# ;
76
- let struct_name = impl_. self_ty ( ) ?. syntax ( ) . to_string ( ) ;
77
- let struct_ = impl_
78
- . syntax ( )
79
- . siblings ( Direction :: Prev )
80
- . filter_map ( ast:: Struct :: cast)
81
- . find ( |struct_| struct_. name ( ) . unwrap ( ) . text ( ) == struct_name) ?;
82
-
83
- let adt = Adt :: cast ( struct_. syntax ( ) . clone ( ) ) ?;
84
- Some ( utils:: generate_trait_impl_text ( & adt, "Default" , code) )
76
+ }}
77
+ }}" ,
78
+ impl_. self_ty( ) . unwrap( ) . syntax( ) . text( )
79
+ )
85
80
}
86
81
87
82
#[ cfg( test) ]
@@ -233,7 +228,7 @@ struct Example { _inner: () }
233
228
struct Test { value: u32 }
234
229
235
230
impl Example {
236
- pub fn new$0 () -> Self {
231
+ pub fn new$0() -> Self {
237
232
Self { _inner: () }
238
233
}
239
234
}
@@ -243,7 +238,36 @@ struct Example { _inner: () }
243
238
struct Test { value: u32 }
244
239
245
240
impl Example {
246
- pub fn new () -> Self {
241
+ pub fn new() -> Self {
242
+ Self { _inner: () }
243
+ }
244
+ }
245
+
246
+ impl Default for Example {
247
+ fn default() -> Self {
248
+ Self::new()
249
+ }
250
+ }
251
+ "# ,
252
+ ) ;
253
+ }
254
+
255
+ #[ test]
256
+ fn when_struct_is_after_impl ( ) {
257
+ check_assist (
258
+ generate_default_from_new,
259
+ r#"
260
+ impl Example {
261
+ pub fn $0new() -> Self {
262
+ Self { _inner: () }
263
+ }
264
+ }
265
+
266
+ struct Example { _inner: () }
267
+ "# ,
268
+ r#"
269
+ impl Example {
270
+ pub fn new() -> Self {
247
271
Self { _inner: () }
248
272
}
249
273
}
@@ -253,6 +277,8 @@ impl Default for Example {
253
277
Self::new()
254
278
}
255
279
}
280
+
281
+ struct Example { _inner: () }
256
282
"# ,
257
283
) ;
258
284
}
0 commit comments