2 use ide_db::defs::{Definition, NameRefClass};
4 ast::{self, AstNode, GenericParamsOwner, VisibilityOwner},
8 use crate::{assist_context::AssistBuilder, AssistContext, AssistId, AssistKind, Assists};
10 // Assist: convert_tuple_struct_to_named_struct
12 // Converts tuple struct to struct with named fields, and analogously for tuple enum variants.
15 // struct Point$0(f32, f32);
18 // pub fn new(x: f32, y: f32) -> Self {
22 // pub fn x(&self) -> f32 {
26 // pub fn y(&self) -> f32 {
33 // struct Point { field1: f32, field2: f32 }
36 // pub fn new(x: f32, y: f32) -> Self {
37 // Point { field1: x, field2: y }
40 // pub fn x(&self) -> f32 {
44 // pub fn y(&self) -> f32 {
49 pub(crate) fn convert_tuple_struct_to_named_struct(
54 .find_node_at_offset::<ast::Struct>()
56 .or_else(|| ctx.find_node_at_offset::<ast::Variant>().map(Either::Right))?;
57 let field_list = strukt.as_ref().either(|s| s.field_list(), |v| v.field_list())?;
58 let tuple_fields = match field_list {
59 ast::FieldList::TupleFieldList(it) => it,
60 ast::FieldList::RecordFieldList(_) => return None,
62 let strukt_def = match &strukt {
63 Either::Left(s) => Either::Left(ctx.sema.to_def(s)?),
64 Either::Right(v) => Either::Right(ctx.sema.to_def(v)?),
66 let target = strukt.as_ref().either(|s| s.syntax(), |v| v.syntax()).text_range();
69 AssistId("convert_tuple_struct_to_named_struct", AssistKind::RefactorRewrite),
70 "Convert to named struct",
73 let names = generate_names(tuple_fields.fields());
74 edit_field_references(ctx, edit, tuple_fields.fields(), &names);
75 edit_struct_references(ctx, edit, strukt_def, &names);
76 edit_struct_def(ctx, edit, &strukt, tuple_fields, names);
83 edit: &mut AssistBuilder,
84 strukt: &Either<ast::Struct, ast::Variant>,
85 tuple_fields: ast::TupleFieldList,
86 names: Vec<ast::Name>,
88 let record_fields = tuple_fields
91 .filter_map(|(f, name)| Some(ast::make::record_field(f.visibility(), name, f.ty()?)));
92 let record_fields = ast::make::record_field_list(record_fields);
93 let tuple_fields_text_range = tuple_fields.syntax().text_range();
95 edit.edit_file(ctx.frange.file_id);
97 if let Either::Left(strukt) = strukt {
98 if let Some(w) = strukt.where_clause() {
99 edit.delete(w.syntax().text_range());
100 edit.insert(tuple_fields_text_range.start(), ast::make::tokens::single_newline().text());
101 edit.insert(tuple_fields_text_range.start(), w.syntax().text());
102 edit.insert(tuple_fields_text_range.start(), ",");
103 edit.insert(tuple_fields_text_range.start(), ast::make::tokens::single_newline().text());
105 edit.insert(tuple_fields_text_range.start(), ast::make::tokens::single_space().text());
107 strukt.semicolon_token().map(|t| edit.delete(t.text_range()));
109 edit.insert(tuple_fields_text_range.start(), ast::make::tokens::single_space().text());
112 edit.replace(tuple_fields_text_range, record_fields.to_string());
115 fn edit_struct_references(
117 edit: &mut AssistBuilder,
118 strukt: Either<hir::Struct, hir::Variant>,
121 let strukt_def = match strukt {
122 Either::Left(s) => Definition::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Struct(s))),
123 Either::Right(v) => Definition::ModuleDef(hir::ModuleDef::Variant(v)),
125 let usages = strukt_def.usages(&ctx.sema).include_self_refs().all();
127 let edit_node = |edit: &mut AssistBuilder, node: SyntaxNode| -> Option<()> {
130 ast::TupleStructPat(tuple_struct_pat) => {
132 tuple_struct_pat.syntax().text_range(),
133 ast::make::record_pat_with_fields(
134 tuple_struct_pat.path()?,
135 ast::make::record_pat_field_list(tuple_struct_pat.fields().zip(names).map(
137 ast::make::record_pat_field(
138 ast::make::name_ref(&name.to_string()),
147 // for tuple struct creations like Foo(42)
148 ast::CallExpr(call_expr) => {
149 let path = call_expr.syntax().descendants().find_map(ast::PathExpr::cast).and_then(|expr| expr.path())?;
151 // this also includes method calls like Foo::new(42), we should skip them
152 if let Some(name_ref) = path.segment().and_then(|s| s.name_ref()) {
153 match NameRefClass::classify(&ctx.sema, &name_ref) {
154 Some(NameRefClass::Definition(Definition::SelfType(_))) => {},
155 Some(NameRefClass::Definition(def)) if def == strukt_def => {},
160 let arg_list = call_expr.syntax().descendants().find_map(ast::ArgList::cast)?;
163 call_expr.syntax().text_range(),
164 ast::make::record_expr(
166 ast::make::record_expr_field_list(arg_list.args().zip(names).map(
168 ast::make::record_expr_field(
169 ast::make::name_ref(&name.to_string()),
184 for (file_id, refs) in usages {
185 edit.edit_file(file_id);
187 for node in r.name.syntax().ancestors() {
188 if edit_node(edit, node).is_some() {
196 fn edit_field_references(
198 edit: &mut AssistBuilder,
199 fields: impl Iterator<Item = ast::TupleField>,
202 for (field, name) in fields.zip(names) {
203 let field = match ctx.sema.to_def(&field) {
207 let def = Definition::Field(field);
208 let usages = def.usages(&ctx.sema).all();
209 for (file_id, refs) in usages {
210 edit.edit_file(file_id);
212 if let Some(name_ref) = r.name.as_name_ref() {
213 edit.replace(name_ref.syntax().text_range(), name.text());
220 fn generate_names(fields: impl Iterator<Item = ast::TupleField>) -> Vec<ast::Name> {
221 fields.enumerate().map(|(i, _)| ast::make::name(&format!("field{}", i + 1))).collect()
226 use crate::tests::{check_assist, check_assist_not_applicable};
231 fn not_applicable_other_than_tuple_struct() {
232 check_assist_not_applicable(
233 convert_tuple_struct_to_named_struct,
234 r#"struct Foo$0 { bar: u32 };"#,
236 check_assist_not_applicable(convert_tuple_struct_to_named_struct, r#"struct Foo$0;"#);
240 fn convert_simple_struct() {
242 convert_tuple_struct_to_named_struct,
248 fn new(inner: Inner) -> A {
252 fn new_with_default() -> A {
256 fn into_inner(self) -> Inner {
262 struct A { field1: Inner }
265 fn new(inner: Inner) -> A {
269 fn new_with_default() -> A {
273 fn into_inner(self) -> Inner {
281 fn convert_struct_referenced_via_self_kw() {
283 convert_tuple_struct_to_named_struct,
289 fn new(inner: Inner) -> Self {
293 fn new_with_default() -> Self {
297 fn into_inner(self) -> Inner {
303 struct A { field1: Inner }
306 fn new(inner: Inner) -> Self {
307 Self { field1: inner }
310 fn new_with_default() -> Self {
314 fn into_inner(self) -> Inner {
322 fn convert_destructured_struct() {
324 convert_tuple_struct_to_named_struct,
330 fn into_inner(self) -> Inner {
335 fn into_inner_via_self(self) -> Inner {
336 let Self(first) = self;
342 struct A { field1: Inner }
345 fn into_inner(self) -> Inner {
346 let A { field1: first } = self;
350 fn into_inner_via_self(self) -> Inner {
351 let Self { field1: first } = self;
359 fn convert_struct_with_visibility() {
361 convert_tuple_struct_to_named_struct,
363 struct A$0(pub u32, pub(crate) u64);
370 fn into_first(self) -> u32 {
374 fn into_second(self) -> u64 {
379 struct A { pub field1: u32, pub(crate) field2: u64 }
383 A { field1: 42, field2: 42 }
386 fn into_first(self) -> u32 {
390 fn into_second(self) -> u64 {
398 fn convert_struct_with_wrapped_references() {
400 convert_tuple_struct_to_named_struct,
410 fn into_inner(self) -> u32 {
414 fn into_inner_destructed(self) -> u32 {
415 let Outer(Inner(x)) = self;
420 struct Inner { field1: u32 }
425 Self(Inner { field1: 42 })
428 fn into_inner(self) -> u32 {
432 fn into_inner_destructed(self) -> u32 {
433 let Outer(Inner { field1: x }) = self;
440 convert_tuple_struct_to_named_struct,
443 struct Outer$0(Inner);
450 fn into_inner(self) -> u32 {
454 fn into_inner_destructed(self) -> u32 {
455 let Outer(Inner(x)) = self;
461 struct Outer { field1: Inner }
465 Self { field1: Inner(42) }
468 fn into_inner(self) -> u32 {
472 fn into_inner_destructed(self) -> u32 {
473 let Outer { field1: Inner(x) } = self;
481 fn convert_struct_with_multi_file_references() {
483 convert_tuple_struct_to_named_struct,
492 use crate::{A, Inner};
500 struct A { field1: Inner }
505 use crate::{A, Inner};
507 let a = A { field1: Inner };
514 fn convert_struct_with_where_clause() {
516 convert_tuple_struct_to_named_struct,
532 fn not_applicable_other_than_tuple_variant() {
533 check_assist_not_applicable(
534 convert_tuple_struct_to_named_struct,
535 r#"enum Enum { Variant$0 { value: usize } };"#,
537 check_assist_not_applicable(convert_tuple_struct_to_named_struct, r#"enum Enum { Variant$0 }"#);
541 fn convert_simple_variant() {
543 convert_tuple_struct_to_named_struct,
550 fn new(value: usize) -> A {
554 fn new_with_default() -> A {
555 A::new(Default::default())
558 fn value(self) -> usize {
560 A::Variant(value) => value,
566 Variant { field1: usize },
570 fn new(value: usize) -> A {
571 A::Variant { field1: value }
574 fn new_with_default() -> A {
575 A::new(Default::default())
578 fn value(self) -> usize {
580 A::Variant { field1: value } => value,
588 fn convert_variant_referenced_via_self_kw() {
590 convert_tuple_struct_to_named_struct,
597 fn new(value: usize) -> A {
601 fn new_with_default() -> A {
602 Self::new(Default::default())
605 fn value(self) -> usize {
607 Self::Variant(value) => value,
613 Variant { field1: usize },
617 fn new(value: usize) -> A {
618 Self::Variant { field1: value }
621 fn new_with_default() -> A {
622 Self::new(Default::default())
625 fn value(self) -> usize {
627 Self::Variant { field1: value } => value,
635 fn convert_destructured_variant() {
637 convert_tuple_struct_to_named_struct,
644 fn into_inner(self) -> usize {
645 let A::Variant(first) = self;
649 fn into_inner_via_self(self) -> usize {
650 let Self::Variant(first) = self;
656 Variant { field1: usize },
660 fn into_inner(self) -> usize {
661 let A::Variant { field1: first } = self;
665 fn into_inner_via_self(self) -> usize {
666 let Self::Variant { field1: first } = self;
674 fn convert_variant_with_wrapped_references() {
676 convert_tuple_struct_to_named_struct,
687 Self::Variant(Inner::Variant(42))
690 fn into_inner_destructed(self) -> u32 {
691 let Outer::Variant(Inner::Variant(x)) = self;
697 Variant { field1: usize },
705 Self::Variant(Inner::Variant { field1: 42 })
708 fn into_inner_destructed(self) -> u32 {
709 let Outer::Variant(Inner::Variant { field1: x }) = self;
716 convert_tuple_struct_to_named_struct,
727 Self::Variant(Inner::Variant(42))
730 fn into_inner_destructed(self) -> u32 {
731 let Outer::Variant(Inner::Variant(x)) = self;
740 Variant { field1: Inner },
745 Self::Variant { field1: Inner::Variant(42) }
748 fn into_inner_destructed(self) -> u32 {
749 let Outer::Variant { field1: Inner::Variant(x) } = self;
757 fn convert_variant_with_multi_file_references() {
759 convert_tuple_struct_to_named_struct,
770 use crate::{A, Inner};
772 let a = A::Variant(Inner);
779 Variant { field1: Inner },
785 use crate::{A, Inner};
787 let a = A::Variant { field1: Inner };
794 fn convert_directly_used_variant() {
796 convert_tuple_struct_to_named_struct,
807 use crate::{A::Variant, Inner};
809 let a = Variant(Inner);
816 Variant { field1: Inner },
822 use crate::{A::Variant, Inner};
824 let a = Variant { field1: Inner };