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
64 .find_use_path(ctx.sema.db, item_for_path_search(ctx.sema.db, item_in_ns)?)?;
66 let expr = use_trivial_constructor(
68 ide_db::helpers::mod_path_to_ast(&type_path),
72 Some(format!("{}: {}", f.name()?.syntax(), expr))
76 let params = field_list
79 .filter_map(|(i, f)| {
80 if trivial_constructors[i].is_none() {
81 Some(format!("{}: {}", f.name()?.syntax(), f.ty()?.syntax()))
88 let fields = field_list
91 .filter_map(|(i, f)| {
92 let contructor = trivial_constructors[i].clone();
93 if contructor.is_some() {
96 Some(f.name()?.to_string())
101 format_to!(buf, " {}fn new({}) -> Self {{ Self {{ {} }} }}", vis, params, fields);
103 let start_offset = impl_def
104 .and_then(|impl_def| find_impl_block_start(impl_def, &mut buf))
106 buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf);
107 strukt.syntax().text_range().end()
110 match ctx.config.snippet_cap {
111 None => builder.insert(start_offset, buf),
113 buf = buf.replace("fn new", "fn $0new");
114 builder.insert_snippet(cap, start_offset, buf);
122 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
127 fn test_generate_new_with_zst_fields() {
133 struct Foo { empty: Empty $0}
138 struct Foo { empty: Empty }
141 fn $0new() -> Self { Self { empty: Empty } }
150 struct Foo { baz: String, empty: Empty $0}
155 struct Foo { baz: String, empty: Empty }
158 fn $0new(baz: String) -> Self { Self { baz, empty: Empty } }
167 struct Foo { empty: Empty $0}
172 struct Foo { empty: Empty }
175 fn $0new() -> Self { Self { empty: Empty::Bar } }
180 // make sure the assist only works on unit variants
186 struct Foo { empty: Empty $0}
191 struct Foo { empty: Empty }
194 fn $0new(empty: Empty) -> Self { Self { empty } }
201 enum Empty { Bar {} }
203 struct Foo { empty: Empty $0}
206 enum Empty { Bar {} }
208 struct Foo { empty: Empty }
211 fn $0new(empty: Empty) -> Self { Self { empty } }
218 fn test_generate_new() {
228 fn $0new() -> Self { Self { } }
235 struct Foo<T: Clone> {$0}
238 struct Foo<T: Clone> {}
240 impl<T: Clone> Foo<T> {
241 fn $0new() -> Self { Self { } }
248 struct Foo<'a, T: Foo<'a>> {$0}
251 struct Foo<'a, T: Foo<'a>> {}
253 impl<'a, T: Foo<'a>> Foo<'a, T> {
254 fn $0new() -> Self { Self { } }
261 struct Foo { baz: String $0}
264 struct Foo { baz: String }
267 fn $0new(baz: String) -> Self { Self { baz } }
274 struct Foo { baz: String, qux: Vec<i32> $0}
277 struct Foo { baz: String, qux: Vec<i32> }
280 fn $0new(baz: String, qux: Vec<i32>) -> Self { Self { baz, qux } }
287 fn check_that_visibility_modifiers_dont_get_brought_in() {
291 struct Foo { pub baz: String, pub qux: Vec<i32> $0}
294 struct Foo { pub baz: String, pub qux: Vec<i32> }
297 fn $0new(baz: String, qux: Vec<i32>) -> Self { Self { baz, qux } }
304 fn check_it_reuses_existing_impls() {
316 fn $0new() -> Self { Self { } }
333 fn $0new() -> Self { Self { } }
356 fn $0new() -> Self { Self { } }
368 fn check_visibility_of_new_fn_based_on_struct() {
378 pub fn $0new() -> Self { Self { } }
385 pub(crate) struct Foo {$0}
388 pub(crate) struct Foo {}
391 pub(crate) fn $0new() -> Self { Self { } }
398 fn generate_new_not_applicable_if_fn_exists() {
399 check_assist_not_applicable(
412 check_assist_not_applicable(
427 fn generate_new_target() {
431 struct SomeThingIrrelevant;
432 /// Has a lifetime parameter
433 struct Foo<'a, T: Foo<'a>> {$0}
434 struct EvenMoreIrrelevant;
436 "/// Has a lifetime parameter
437 struct Foo<'a, T: Foo<'a>> {}",
442 fn test_unrelated_new() {
446 pub struct AstId<N: AstNode> {
448 file_ast_id: FileAstId<N>,
451 impl<N: AstNode> AstId<N> {
452 pub fn new(file_id: HirFileId, file_ast_id: FileAstId<N>) -> AstId<N> {
453 AstId { file_id, file_ast_id }
457 pub struct Source<T> {
458 pub file_id: HirFileId,$0
463 pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> Source<U> {
464 Source { file_id: self.file_id, ast: f(self.ast) }
469 pub struct AstId<N: AstNode> {
471 file_ast_id: FileAstId<N>,
474 impl<N: AstNode> AstId<N> {
475 pub fn new(file_id: HirFileId, file_ast_id: FileAstId<N>) -> AstId<N> {
476 AstId { file_id, file_ast_id }
480 pub struct Source<T> {
481 pub file_id: HirFileId,
486 pub fn $0new(file_id: HirFileId, ast: T) -> Self { Self { file_id, ast } }
488 pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> Source<U> {
489 Source { file_id: self.file_id, ast: f(self.ast) }