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());
101 tuple_fields_text_range.start(),
102 ast::make::tokens::single_newline().text(),
104 edit.insert(tuple_fields_text_range.start(), w.syntax().text());
105 edit.insert(tuple_fields_text_range.start(), ",");
107 tuple_fields_text_range.start(),
108 ast::make::tokens::single_newline().text(),
111 edit.insert(tuple_fields_text_range.start(), ast::make::tokens::single_space().text());
113 strukt.semicolon_token().map(|t| edit.delete(t.text_range()));
115 edit.insert(tuple_fields_text_range.start(), ast::make::tokens::single_space().text());
118 edit.replace(tuple_fields_text_range, record_fields.to_string());
121 fn edit_struct_references(
123 edit: &mut AssistBuilder,
124 strukt: Either<hir::Struct, hir::Variant>,
127 let strukt_def = match strukt {
128 Either::Left(s) => Definition::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Struct(s))),
129 Either::Right(v) => Definition::ModuleDef(hir::ModuleDef::Variant(v)),
131 let usages = strukt_def.usages(&ctx.sema).include_self_refs().all();
133 let edit_node = |edit: &mut AssistBuilder, node: SyntaxNode| -> Option<()> {
136 ast::TupleStructPat(tuple_struct_pat) => {
138 tuple_struct_pat.syntax().text_range(),
139 ast::make::record_pat_with_fields(
140 tuple_struct_pat.path()?,
141 ast::make::record_pat_field_list(tuple_struct_pat.fields().zip(names).map(
143 ast::make::record_pat_field(
144 ast::make::name_ref(&name.to_string()),
153 // for tuple struct creations like Foo(42)
154 ast::CallExpr(call_expr) => {
155 let path = call_expr.syntax().descendants().find_map(ast::PathExpr::cast).and_then(|expr| expr.path())?;
157 // this also includes method calls like Foo::new(42), we should skip them
158 if let Some(name_ref) = path.segment().and_then(|s| s.name_ref()) {
159 match NameRefClass::classify(&ctx.sema, &name_ref) {
160 Some(NameRefClass::Definition(Definition::SelfType(_))) => {},
161 Some(NameRefClass::Definition(def)) if def == strukt_def => {},
166 let arg_list = call_expr.syntax().descendants().find_map(ast::ArgList::cast)?;
169 call_expr.syntax().text_range(),
170 ast::make::record_expr(
172 ast::make::record_expr_field_list(arg_list.args().zip(names).map(
174 ast::make::record_expr_field(
175 ast::make::name_ref(&name.to_string()),
190 for (file_id, refs) in usages {
191 edit.edit_file(file_id);
193 for node in r.name.syntax().ancestors() {
194 if edit_node(edit, node).is_some() {
202 fn edit_field_references(
204 edit: &mut AssistBuilder,
205 fields: impl Iterator<Item = ast::TupleField>,
208 for (field, name) in fields.zip(names) {
209 let field = match ctx.sema.to_def(&field) {
213 let def = Definition::Field(field);
214 let usages = def.usages(&ctx.sema).all();
215 for (file_id, refs) in usages {
216 edit.edit_file(file_id);
218 if let Some(name_ref) = r.name.as_name_ref() {
219 edit.replace(name_ref.syntax().text_range(), name.text());
226 fn generate_names(fields: impl Iterator<Item = ast::TupleField>) -> Vec<ast::Name> {
227 fields.enumerate().map(|(i, _)| ast::make::name(&format!("field{}", i + 1))).collect()
232 use crate::tests::{check_assist, check_assist_not_applicable};
237 fn not_applicable_other_than_tuple_struct() {
238 check_assist_not_applicable(
239 convert_tuple_struct_to_named_struct,
240 r#"struct Foo$0 { bar: u32 };"#,
242 check_assist_not_applicable(convert_tuple_struct_to_named_struct, r#"struct Foo$0;"#);
246 fn convert_simple_struct() {
248 convert_tuple_struct_to_named_struct,
254 fn new(inner: Inner) -> A {
258 fn new_with_default() -> A {
262 fn into_inner(self) -> Inner {
268 struct A { field1: Inner }
271 fn new(inner: Inner) -> A {
275 fn new_with_default() -> A {
279 fn into_inner(self) -> Inner {
287 fn convert_struct_referenced_via_self_kw() {
289 convert_tuple_struct_to_named_struct,
295 fn new(inner: Inner) -> Self {
299 fn new_with_default() -> Self {
303 fn into_inner(self) -> Inner {
309 struct A { field1: Inner }
312 fn new(inner: Inner) -> Self {
313 Self { field1: inner }
316 fn new_with_default() -> Self {
320 fn into_inner(self) -> Inner {
328 fn convert_destructured_struct() {
330 convert_tuple_struct_to_named_struct,
336 fn into_inner(self) -> Inner {
341 fn into_inner_via_self(self) -> Inner {
342 let Self(first) = self;
348 struct A { field1: Inner }
351 fn into_inner(self) -> Inner {
352 let A { field1: first } = self;
356 fn into_inner_via_self(self) -> Inner {
357 let Self { field1: first } = self;
365 fn convert_struct_with_visibility() {
367 convert_tuple_struct_to_named_struct,
369 struct A$0(pub u32, pub(crate) u64);
376 fn into_first(self) -> u32 {
380 fn into_second(self) -> u64 {
385 struct A { pub field1: u32, pub(crate) field2: u64 }
389 A { field1: 42, field2: 42 }
392 fn into_first(self) -> u32 {
396 fn into_second(self) -> u64 {
404 fn convert_struct_with_wrapped_references() {
406 convert_tuple_struct_to_named_struct,
416 fn into_inner(self) -> u32 {
420 fn into_inner_destructed(self) -> u32 {
421 let Outer(Inner(x)) = self;
426 struct Inner { field1: u32 }
431 Self(Inner { field1: 42 })
434 fn into_inner(self) -> u32 {
438 fn into_inner_destructed(self) -> u32 {
439 let Outer(Inner { field1: x }) = self;
446 convert_tuple_struct_to_named_struct,
449 struct Outer$0(Inner);
456 fn into_inner(self) -> u32 {
460 fn into_inner_destructed(self) -> u32 {
461 let Outer(Inner(x)) = self;
467 struct Outer { field1: Inner }
471 Self { field1: Inner(42) }
474 fn into_inner(self) -> u32 {
478 fn into_inner_destructed(self) -> u32 {
479 let Outer { field1: Inner(x) } = self;
487 fn convert_struct_with_multi_file_references() {
489 convert_tuple_struct_to_named_struct,
498 use crate::{A, Inner};
506 struct A { field1: Inner }
511 use crate::{A, Inner};
513 let a = A { field1: Inner };
520 fn convert_struct_with_where_clause() {
522 convert_tuple_struct_to_named_struct,
538 fn not_applicable_other_than_tuple_variant() {
539 check_assist_not_applicable(
540 convert_tuple_struct_to_named_struct,
541 r#"enum Enum { Variant$0 { value: usize } };"#,
543 check_assist_not_applicable(
544 convert_tuple_struct_to_named_struct,
545 r#"enum Enum { Variant$0 }"#,
550 fn convert_simple_variant() {
552 convert_tuple_struct_to_named_struct,
559 fn new(value: usize) -> A {
563 fn new_with_default() -> A {
564 A::new(Default::default())
567 fn value(self) -> usize {
569 A::Variant(value) => value,
575 Variant { field1: usize },
579 fn new(value: usize) -> A {
580 A::Variant { field1: value }
583 fn new_with_default() -> A {
584 A::new(Default::default())
587 fn value(self) -> usize {
589 A::Variant { field1: value } => value,
597 fn convert_variant_referenced_via_self_kw() {
599 convert_tuple_struct_to_named_struct,
606 fn new(value: usize) -> A {
610 fn new_with_default() -> A {
611 Self::new(Default::default())
614 fn value(self) -> usize {
616 Self::Variant(value) => value,
622 Variant { field1: usize },
626 fn new(value: usize) -> A {
627 Self::Variant { field1: value }
630 fn new_with_default() -> A {
631 Self::new(Default::default())
634 fn value(self) -> usize {
636 Self::Variant { field1: value } => value,
644 fn convert_destructured_variant() {
646 convert_tuple_struct_to_named_struct,
653 fn into_inner(self) -> usize {
654 let A::Variant(first) = self;
658 fn into_inner_via_self(self) -> usize {
659 let Self::Variant(first) = self;
665 Variant { field1: usize },
669 fn into_inner(self) -> usize {
670 let A::Variant { field1: first } = self;
674 fn into_inner_via_self(self) -> usize {
675 let Self::Variant { field1: first } = self;
683 fn convert_variant_with_wrapped_references() {
685 convert_tuple_struct_to_named_struct,
696 Self::Variant(Inner::Variant(42))
699 fn into_inner_destructed(self) -> u32 {
700 let Outer::Variant(Inner::Variant(x)) = self;
706 Variant { field1: usize },
714 Self::Variant(Inner::Variant { field1: 42 })
717 fn into_inner_destructed(self) -> u32 {
718 let Outer::Variant(Inner::Variant { field1: x }) = self;
725 convert_tuple_struct_to_named_struct,
736 Self::Variant(Inner::Variant(42))
739 fn into_inner_destructed(self) -> u32 {
740 let Outer::Variant(Inner::Variant(x)) = self;
749 Variant { field1: Inner },
754 Self::Variant { field1: Inner::Variant(42) }
757 fn into_inner_destructed(self) -> u32 {
758 let Outer::Variant { field1: Inner::Variant(x) } = self;
766 fn convert_variant_with_multi_file_references() {
768 convert_tuple_struct_to_named_struct,
779 use crate::{A, Inner};
781 let a = A::Variant(Inner);
788 Variant { field1: Inner },
794 use crate::{A, Inner};
796 let a = A::Variant { field1: Inner };
803 fn convert_directly_used_variant() {
805 convert_tuple_struct_to_named_struct,
816 use crate::{A::Variant, Inner};
818 let a = Variant(Inner);
825 Variant { field1: Inner },
831 use crate::{A::Variant, Inner};
833 let a = Variant { field1: Inner };