From 3f0222565d8a4f8e60c5f175305d29dc9af0b3a5 Mon Sep 17 00:00:00 2001 From: hi-rustin Date: Sat, 15 May 2021 11:29:33 +0800 Subject: Generate the impl block via generate_trait_impl_text --- .../src/handlers/generate_default_from_new.rs | 47 +++++++++++++++++++++- 1 file changed, 45 insertions(+), 2 deletions(-) (limited to 'crates') diff --git a/crates/ide_assists/src/handlers/generate_default_from_new.rs b/crates/ide_assists/src/handlers/generate_default_from_new.rs index dc14552d6..374611fbf 100644 --- a/crates/ide_assists/src/handlers/generate_default_from_new.rs +++ b/crates/ide_assists/src/handlers/generate_default_from_new.rs @@ -7,6 +7,7 @@ use syntax::{ ast::{self, Impl, NameOwner}, AstNode, }; +use crate::utils::generate_trait_impl_text; // Assist: generate_default_from_new // @@ -59,13 +60,21 @@ pub(crate) fn generate_default_from_new(acc: &mut Assists, ctx: &AssistContext) } let insert_location = impl_.syntax().text_range(); - + let code = match ast::Struct::cast(impl_.self_ty().unwrap().syntax().clone()){ + None => { + default_fn_node_for_new(impl_) + } + Some(strukt) => { + generate_trait_impl_text(&ast::Adt::Struct(strukt),"core:default:Default"," fn default() -> Self {{ + Self::new() + }}") + } + }; acc.add( AssistId("generate_default_from_new", crate::AssistKind::Generate), "Generate a Default impl from a new fn", insert_location, move |builder| { - let code = default_fn_node_for_new(impl_); builder.insert(insert_location.end(), code); }, ) @@ -175,6 +184,40 @@ impl Default for Test { ); } + #[test] + fn generate_default3() { + check_pass( + r#" +pub struct Foo { + _bar: *mut T, +} + +impl Foo { + pub fn ne$0w() -> Self { + todo!() + } +} +"#, + r#" +pub struct Foo { + _bar: *mut T, +} + +impl Foo { + pub fn new() -> Self { + todo!() + } +} + +impl Default for Foo { + fn default() -> Self { + Self::new() + } +} +"#, + ); + } + #[test] fn new_function_with_parameters() { cov_mark::check!(new_function_with_parameters); -- cgit v1.2.3