2 imports::import_assets::item_for_path_search, use_trivial_contructor::use_trivial_constructor,
4 use itertools::Itertools;
6 use syntax::ast::{self, AstNode, HasName, HasVisibility, StructKind};
9 utils::{find_impl_block_start, find_struct_impl, generate_impl_text},
10 AssistContext, AssistId, AssistKind, Assists,
13 // Assist: generate_new
15 // Adds a `fn new` for a type.
18 // struct Ctx<T: Clone> {
24 // struct Ctx<T: Clone> {
28 // impl<T: Clone> Ctx<T> {
29 // fn $0new(data: T) -> Self { Self { data } }
32 pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
33 let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
35 // We want to only apply this to non-union structs with named fields
36 let field_list = match strukt.kind() {
37 StructKind::Record(named) => named,
41 // Return early if we've found an existing new fn
43 find_struct_impl(ctx, &ast::Adt::Struct(strukt.clone()), &[String::from("new")])?;
45 let current_module = ctx.sema.scope(strukt.syntax())?.module();
47 let target = strukt.syntax().text_range();
48 acc.add(AssistId("generate_new", AssistKind::Generate), "Generate `new`", target, |builder| {
49 let mut buf = String::with_capacity(512);
51 if impl_def.is_some() {
55 let vis = strukt.visibility().map_or(String::new(), |v| format!("{v} "));
57 let trivial_constructors = field_list
62 let ty = ctx.sema.resolve_type(&f.ty()?)?;
64 let item_in_ns = hir::ItemInNs::from(hir::ModuleDef::from(ty.as_adt()?));
66 let type_path = current_module.find_use_path(
68 item_for_path_search(ctx.sema.db, item_in_ns)?,
69 ctx.config.prefer_no_std,
72 let expr = use_trivial_constructor(
74 ide_db::helpers::mod_path_to_ast(&type_path),
78 Some(format!("{name}: {expr}"))
82 let params = field_list
85 .filter_map(|(i, f)| {
86 if trivial_constructors[i].is_none() {
90 Some(format!("{name}: {ty}"))
97 let fields = field_list
100 .filter_map(|(i, f)| {
101 let contructor = trivial_constructors[i].clone();
102 if contructor.is_some() {
105 Some(f.name()?.to_string())
110 format_to!(buf, " {vis}fn new({params}) -> Self {{ Self {{ {fields} }} }}");
112 let start_offset = impl_def
113 .and_then(|impl_def| find_impl_block_start(impl_def, &mut buf))
115 buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf);
116 strukt.syntax().text_range().end()
119 match ctx.config.snippet_cap {
120 None => builder.insert(start_offset, buf),
122 buf = buf.replace("fn new", "fn $0new");
123 builder.insert_snippet(cap, start_offset, buf);
131 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
136 fn test_generate_new_with_zst_fields() {
142 struct Foo { empty: Empty $0}
147 struct Foo { empty: Empty }
150 fn $0new() -> Self { Self { empty: Empty } }
159 struct Foo { baz: String, empty: Empty $0}
164 struct Foo { baz: String, empty: Empty }
167 fn $0new(baz: String) -> Self { Self { baz, empty: Empty } }
176 struct Foo { empty: Empty $0}
181 struct Foo { empty: Empty }
184 fn $0new() -> Self { Self { empty: Empty::Bar } }
189 // make sure the assist only works on unit variants
195 struct Foo { empty: Empty $0}
200 struct Foo { empty: Empty }
203 fn $0new(empty: Empty) -> Self { Self { empty } }
210 enum Empty { Bar {} }
212 struct Foo { empty: Empty $0}
215 enum Empty { Bar {} }
217 struct Foo { empty: Empty }
220 fn $0new(empty: Empty) -> Self { Self { empty } }
227 fn test_generate_new() {
237 fn $0new() -> Self { Self { } }
244 struct Foo<T: Clone> {$0}
247 struct Foo<T: Clone> {}
249 impl<T: Clone> Foo<T> {
250 fn $0new() -> Self { Self { } }
257 struct Foo<'a, T: Foo<'a>> {$0}
260 struct Foo<'a, T: Foo<'a>> {}
262 impl<'a, T: Foo<'a>> Foo<'a, T> {
263 fn $0new() -> Self { Self { } }
270 struct Foo { baz: String $0}
273 struct Foo { baz: String }
276 fn $0new(baz: String) -> Self { Self { baz } }
283 struct Foo { baz: String, qux: Vec<i32> $0}
286 struct Foo { baz: String, qux: Vec<i32> }
289 fn $0new(baz: String, qux: Vec<i32>) -> Self { Self { baz, qux } }
296 fn check_that_visibility_modifiers_dont_get_brought_in() {
300 struct Foo { pub baz: String, pub qux: Vec<i32> $0}
303 struct Foo { pub baz: String, pub qux: Vec<i32> }
306 fn $0new(baz: String, qux: Vec<i32>) -> Self { Self { baz, qux } }
313 fn check_it_reuses_existing_impls() {
325 fn $0new() -> Self { Self { } }
342 fn $0new() -> Self { Self { } }
365 fn $0new() -> Self { Self { } }
377 fn check_visibility_of_new_fn_based_on_struct() {
387 pub fn $0new() -> Self { Self { } }
394 pub(crate) struct Foo {$0}
397 pub(crate) struct Foo {}
400 pub(crate) fn $0new() -> Self { Self { } }
407 fn generate_new_not_applicable_if_fn_exists() {
408 check_assist_not_applicable(
421 check_assist_not_applicable(
436 fn generate_new_target() {
440 struct SomeThingIrrelevant;
441 /// Has a lifetime parameter
442 struct Foo<'a, T: Foo<'a>> {$0}
443 struct EvenMoreIrrelevant;
445 "/// Has a lifetime parameter
446 struct Foo<'a, T: Foo<'a>> {}",
451 fn test_unrelated_new() {
455 pub struct AstId<N: AstNode> {
457 file_ast_id: FileAstId<N>,
460 impl<N: AstNode> AstId<N> {
461 pub fn new(file_id: HirFileId, file_ast_id: FileAstId<N>) -> AstId<N> {
462 AstId { file_id, file_ast_id }
466 pub struct Source<T> {
467 pub file_id: HirFileId,$0
472 pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> Source<U> {
473 Source { file_id: self.file_id, ast: f(self.ast) }
478 pub struct AstId<N: AstNode> {
480 file_ast_id: FileAstId<N>,
483 impl<N: AstNode> AstId<N> {
484 pub fn new(file_id: HirFileId, file_ast_id: FileAstId<N>) -> AstId<N> {
485 AstId { file_id, file_ast_id }
489 pub struct Source<T> {
490 pub file_id: HirFileId,
495 pub fn $0new(file_id: HirFileId, ast: T) -> Self { Self { file_id, ast } }
497 pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> Source<U> {
498 Source { file_id: self.file_id, ast: f(self.ast) }