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
42 let impl_def = find_struct_impl(ctx, &ast::Adt::Struct(strukt.clone()), "new")?;
44 let current_module = ctx.sema.scope(strukt.syntax())?.module();
46 let target = strukt.syntax().text_range();
47 acc.add(AssistId("generate_new", AssistKind::Generate), "Generate `new`", target, |builder| {
48 let mut buf = String::with_capacity(512);
50 if impl_def.is_some() {
54 let vis = strukt.visibility().map_or(String::new(), |v| format!("{} ", v));
56 let trivial_constructors = field_list
59 let ty = ctx.sema.resolve_type(&f.ty()?)?;
61 let item_in_ns = hir::ItemInNs::from(hir::ModuleDef::from(ty.as_adt()?));
63 let type_path = current_module.find_use_path(
65 item_for_path_search(ctx.sema.db, item_in_ns)?,
66 ctx.config.prefer_no_std,
69 let expr = use_trivial_constructor(
71 ide_db::helpers::mod_path_to_ast(&type_path),
75 Some(format!("{}: {}", f.name()?.syntax(), expr))
79 let params = field_list
82 .filter_map(|(i, f)| {
83 if trivial_constructors[i].is_none() {
84 Some(format!("{}: {}", f.name()?.syntax(), f.ty()?.syntax()))
91 let fields = field_list
94 .filter_map(|(i, f)| {
95 let contructor = trivial_constructors[i].clone();
96 if contructor.is_some() {
99 Some(f.name()?.to_string())
104 format_to!(buf, " {}fn new({}) -> Self {{ Self {{ {} }} }}", vis, params, fields);
106 let start_offset = impl_def
107 .and_then(|impl_def| find_impl_block_start(impl_def, &mut buf))
109 buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf);
110 strukt.syntax().text_range().end()
113 match ctx.config.snippet_cap {
114 None => builder.insert(start_offset, buf),
116 buf = buf.replace("fn new", "fn $0new");
117 builder.insert_snippet(cap, start_offset, buf);
125 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
130 fn test_generate_new_with_zst_fields() {
136 struct Foo { empty: Empty $0}
141 struct Foo { empty: Empty }
144 fn $0new() -> Self { Self { empty: Empty } }
153 struct Foo { baz: String, empty: Empty $0}
158 struct Foo { baz: String, empty: Empty }
161 fn $0new(baz: String) -> Self { Self { baz, empty: Empty } }
170 struct Foo { empty: Empty $0}
175 struct Foo { empty: Empty }
178 fn $0new() -> Self { Self { empty: Empty::Bar } }
183 // make sure the assist only works on unit variants
189 struct Foo { empty: Empty $0}
194 struct Foo { empty: Empty }
197 fn $0new(empty: Empty) -> Self { Self { empty } }
204 enum Empty { Bar {} }
206 struct Foo { empty: Empty $0}
209 enum Empty { Bar {} }
211 struct Foo { empty: Empty }
214 fn $0new(empty: Empty) -> Self { Self { empty } }
221 fn test_generate_new() {
231 fn $0new() -> Self { Self { } }
238 struct Foo<T: Clone> {$0}
241 struct Foo<T: Clone> {}
243 impl<T: Clone> Foo<T> {
244 fn $0new() -> Self { Self { } }
251 struct Foo<'a, T: Foo<'a>> {$0}
254 struct Foo<'a, T: Foo<'a>> {}
256 impl<'a, T: Foo<'a>> Foo<'a, T> {
257 fn $0new() -> Self { Self { } }
264 struct Foo { baz: String $0}
267 struct Foo { baz: String }
270 fn $0new(baz: String) -> Self { Self { baz } }
277 struct Foo { baz: String, qux: Vec<i32> $0}
280 struct Foo { baz: String, qux: Vec<i32> }
283 fn $0new(baz: String, qux: Vec<i32>) -> Self { Self { baz, qux } }
290 fn check_that_visibility_modifiers_dont_get_brought_in() {
294 struct Foo { pub baz: String, pub qux: Vec<i32> $0}
297 struct Foo { pub baz: String, pub qux: Vec<i32> }
300 fn $0new(baz: String, qux: Vec<i32>) -> Self { Self { baz, qux } }
307 fn check_it_reuses_existing_impls() {
319 fn $0new() -> Self { Self { } }
336 fn $0new() -> Self { Self { } }
359 fn $0new() -> Self { Self { } }
371 fn check_visibility_of_new_fn_based_on_struct() {
381 pub fn $0new() -> Self { Self { } }
388 pub(crate) struct Foo {$0}
391 pub(crate) struct Foo {}
394 pub(crate) fn $0new() -> Self { Self { } }
401 fn generate_new_not_applicable_if_fn_exists() {
402 check_assist_not_applicable(
415 check_assist_not_applicable(
430 fn generate_new_target() {
434 struct SomeThingIrrelevant;
435 /// Has a lifetime parameter
436 struct Foo<'a, T: Foo<'a>> {$0}
437 struct EvenMoreIrrelevant;
439 "/// Has a lifetime parameter
440 struct Foo<'a, T: Foo<'a>> {}",
445 fn test_unrelated_new() {
449 pub struct AstId<N: AstNode> {
451 file_ast_id: FileAstId<N>,
454 impl<N: AstNode> AstId<N> {
455 pub fn new(file_id: HirFileId, file_ast_id: FileAstId<N>) -> AstId<N> {
456 AstId { file_id, file_ast_id }
460 pub struct Source<T> {
461 pub file_id: HirFileId,$0
466 pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> Source<U> {
467 Source { file_id: self.file_id, ast: f(self.ast) }
472 pub struct AstId<N: AstNode> {
474 file_ast_id: FileAstId<N>,
477 impl<N: AstNode> AstId<N> {
478 pub fn new(file_id: HirFileId, file_ast_id: FileAstId<N>) -> AstId<N> {
479 AstId { file_id, file_ast_id }
483 pub struct Source<T> {
484 pub file_id: HirFileId,
489 pub fn $0new(file_id: HirFileId, ast: T) -> Self { Self { file_id, ast } }
491 pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> Source<U> {
492 Source { file_id: self.file_id, ast: f(self.ast) }