Skip to content

Commit a59a97a

Browse files
7708: Updated generate default fn logic.
1 parent 54b4727 commit a59a97a

File tree

1 file changed

+48
-22
lines changed

1 file changed

+48
-22
lines changed

crates/ide_assists/src/handlers/generate_default_from_new.rs

Lines changed: 48 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
use crate::{
22
assist_context::{AssistContext, Assists},
3-
utils, AssistId,
3+
AssistId,
44
};
55
use syntax::{
6-
ast::{self, Adt, Impl, NameOwner},
7-
AstNode, Direction,
6+
ast::{self, Impl, NameOwner},
7+
AstNode,
88
};
99
use test_utils::mark;
1010

@@ -60,28 +60,23 @@ pub(crate) fn generate_default_from_new(acc: &mut Assists, ctx: &AssistContext)
6060
"Generate a Default impl from a new fn",
6161
insert_location,
6262
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);
6765
},
6866
)
6967
}
7068

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 {{
7475
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+
)
8580
}
8681

8782
#[cfg(test)]
@@ -233,7 +228,7 @@ struct Example { _inner: () }
233228
struct Test { value: u32 }
234229
235230
impl Example {
236-
pub fn new$0 () -> Self {
231+
pub fn new$0() -> Self {
237232
Self { _inner: () }
238233
}
239234
}
@@ -243,7 +238,36 @@ struct Example { _inner: () }
243238
struct Test { value: u32 }
244239
245240
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 {
247271
Self { _inner: () }
248272
}
249273
}
@@ -253,6 +277,8 @@ impl Default for Example {
253277
Self::new()
254278
}
255279
}
280+
281+
struct Example { _inner: () }
256282
"#,
257283
);
258284
}

0 commit comments

Comments
 (0)