4 use hir
::{Module, ModuleDef, Name, Variant}
;
7 helpers
::mod_path_to_ast
,
8 imports
::insert_use
::{insert_use, ImportScope, InsertUseConfig}
,
10 FxHashSet
, RootDatabase
,
12 use itertools
::Itertools
;
15 self, edit
::IndentLevel
, edit_in_place
::Indent
, make
, AstNode
, HasAttrs
, HasGenericParams
,
16 HasName
, HasVisibility
,
18 match_ast
, ted
, SyntaxElement
,
23 use crate::{assist_context::SourceChangeBuilder, AssistContext, AssistId, AssistKind, Assists}
;
25 // Assist: extract_struct_from_enum_variant
27 // Extracts a struct from enum variant.
30 // enum A { $0One(u32, u32) }
34 // struct One(u32, u32);
36 // enum A { One(One) }
38 pub(crate) fn extract_struct_from_enum_variant(
40 ctx
: &AssistContext
<'_
>,
42 let variant
= ctx
.find_node_at_offset
::<ast
::Variant
>()?
;
43 let field_list
= extract_field_list_if_applicable(&variant
)?
;
45 let variant_name
= variant
.name()?
;
46 let variant_hir
= ctx
.sema
.to_def(&variant
)?
;
47 if existing_definition(ctx
.db(), &variant_name
, &variant_hir
) {
48 cov_mark
::hit
!(test_extract_enum_not_applicable_if_struct_exists
);
52 let enum_ast
= variant
.parent_enum();
53 let enum_hir
= ctx
.sema
.to_def(&enum_ast
)?
;
54 let target
= variant
.syntax().text_range();
56 AssistId("extract_struct_from_enum_variant", AssistKind
::RefactorRewrite
),
57 "Extract struct from enum variant",
60 let variant_hir_name
= variant_hir
.name(ctx
.db());
61 let enum_module_def
= ModuleDef
::from(enum_hir
);
62 let usages
= Definition
::Variant(variant_hir
).usages(&ctx
.sema
).all();
64 let mut visited_modules_set
= FxHashSet
::default();
65 let current_module
= enum_hir
.module(ctx
.db());
66 visited_modules_set
.insert(current_module
);
67 // record file references of the file the def resides in, we only want to swap to the edited file in the builder once
68 let mut def_file_references
= None
;
69 for (file_id
, references
) in usages
{
70 if file_id
== ctx
.file_id() {
71 def_file_references
= Some(references
);
74 builder
.edit_file(file_id
);
75 let processed
= process_references(
78 &mut visited_modules_set
,
83 processed
.into_iter().for_each(|(path
, node
, import
)| {
84 apply_references(ctx
.config
.insert_use
, path
, node
, import
)
87 builder
.edit_file(ctx
.file_id());
89 let variant
= builder
.make_mut(variant
.clone());
90 if let Some(references
) = def_file_references
{
91 let processed
= process_references(
94 &mut visited_modules_set
,
99 processed
.into_iter().for_each(|(path
, node
, import
)| {
100 apply_references(ctx
.config
.insert_use
, path
, node
, import
)
104 let generic_params
= enum_ast
105 .generic_param_list()
106 .and_then(|known_generics
| extract_generic_params(&known_generics
, &field_list
));
107 let generics
= generic_params
.as_ref().map(|generics
| generics
.clone_for_update());
109 create_struct_def(variant_name
.clone(), &variant
, &field_list
, generics
, &enum_ast
);
111 let enum_ast
= variant
.parent_enum();
112 let indent
= enum_ast
.indent_level();
113 def
.reindent_to(indent
);
116 ted
::Position
::before(enum_ast
.syntax()),
118 def
.syntax().clone().into(),
119 make
::tokens
::whitespace(&format
!("\n\n{indent}")).into(),
123 update_variant(&variant
, generic_params
.map(|g
| g
.clone_for_update()));
128 fn extract_field_list_if_applicable(
129 variant
: &ast
::Variant
,
130 ) -> Option
<Either
<ast
::RecordFieldList
, ast
::TupleFieldList
>> {
131 match variant
.kind() {
132 ast
::StructKind
::Record(field_list
) if field_list
.fields().next().is_some() => {
133 Some(Either
::Left(field_list
))
135 ast
::StructKind
::Tuple(field_list
) if field_list
.fields().count() > 1 => {
136 Some(Either
::Right(field_list
))
142 fn existing_definition(db
: &RootDatabase
, variant_name
: &ast
::Name
, variant
: &Variant
) -> bool
{
148 .filter(|(_
, def
)| match def
{
149 // only check type-namespace
150 hir
::ScopeDef
::ModuleDef(def
) => matches
!(
154 | ModuleDef
::Variant(_
)
155 | ModuleDef
::Trait(_
)
156 | ModuleDef
::TypeAlias(_
)
157 | ModuleDef
::BuiltinType(_
)
161 .any(|(name
, _
)| name
.to_string() == variant_name
.to_string())
164 fn extract_generic_params(
165 known_generics
: &ast
::GenericParamList
,
166 field_list
: &Either
<ast
::RecordFieldList
, ast
::TupleFieldList
>,
167 ) -> Option
<ast
::GenericParamList
> {
168 let mut generics
= known_generics
.generic_params().map(|param
| (param
, false)).collect_vec();
170 let tagged_one
= match field_list
{
171 Either
::Left(field_list
) => field_list
173 .filter_map(|f
| f
.ty())
174 .fold(false, |tagged
, ty
| tag_generics_in_variant(&ty
, &mut generics
) || tagged
),
175 Either
::Right(field_list
) => field_list
177 .filter_map(|f
| f
.ty())
178 .fold(false, |tagged
, ty
| tag_generics_in_variant(&ty
, &mut generics
) || tagged
),
181 let generics
= generics
.into_iter().filter_map(|(param
, tag
)| tag
.then(|| param
));
182 tagged_one
.then(|| make
::generic_param_list(generics
))
185 fn tag_generics_in_variant(ty
: &ast
::Type
, generics
: &mut [(ast
::GenericParam
, bool
)]) -> bool
{
186 let mut tagged_one
= false;
188 for token
in ty
.syntax().descendants_with_tokens().filter_map(SyntaxElement
::into_token
) {
189 for (param
, tag
) in generics
.iter_mut().filter(|(_
, tag
)| !tag
) {
191 ast
::GenericParam
::LifetimeParam(lt
)
192 if matches
!(token
.kind(), T
![lifetime_ident
]) =>
194 if let Some(lt
) = lt
.lifetime() {
195 if lt
.text().as_str() == token
.text() {
202 param
if matches
!(token
.kind(), T
![ident
]) => {
204 ast
::GenericParam
::ConstParam(konst
) => konst
206 .map(|name
| name
.text().as_str() == token
.text())
207 .unwrap_or_default(),
208 ast
::GenericParam
::TypeParam(ty
) => ty
210 .map(|name
| name
.text().as_str() == token
.text())
211 .unwrap_or_default(),
212 ast
::GenericParam
::LifetimeParam(lt
) => lt
214 .map(|lt
| lt
.text().as_str() == token
.text())
215 .unwrap_or_default(),
230 fn create_struct_def(
232 variant
: &ast
::Variant
,
233 field_list
: &Either
<ast
::RecordFieldList
, ast
::TupleFieldList
>,
234 generics
: Option
<ast
::GenericParamList
>,
237 let enum_vis
= enum_
.visibility();
239 let insert_vis
= |node
: &'_ SyntaxNode
, vis
: &'_ SyntaxNode
| {
240 let vis
= vis
.clone_for_update();
241 ted
::insert(ted
::Position
::before(node
), vis
);
244 // for fields without any existing visibility, use visibility of enum
245 let field_list
: ast
::FieldList
= match field_list
{
246 Either
::Left(field_list
) => {
247 let field_list
= field_list
.clone_for_update();
249 if let Some(vis
) = &enum_vis
{
252 .filter(|field
| field
.visibility().is_none())
253 .filter_map(|field
| field
.name())
254 .for_each(|it
| insert_vis(it
.syntax(), vis
.syntax()));
259 Either
::Right(field_list
) => {
260 let field_list
= field_list
.clone_for_update();
262 if let Some(vis
) = &enum_vis
{
265 .filter(|field
| field
.visibility().is_none())
266 .filter_map(|field
| field
.ty())
267 .for_each(|it
| insert_vis(it
.syntax(), vis
.syntax()));
273 field_list
.reindent_to(IndentLevel
::single());
275 let strukt
= make
::struct_(enum_vis
, name
, generics
, field_list
).clone_for_update();
277 // take comments from variant
279 ted
::Position
::first_child_of(strukt
.syntax()),
280 take_all_comments(variant
.syntax()),
283 // copy attributes from enum
285 ted
::Position
::first_child_of(strukt
.syntax()),
289 vec
![it
.syntax().clone_for_update().into(), make
::tokens
::single_newline().into()]
297 fn update_variant(variant
: &ast
::Variant
, generics
: Option
<ast
::GenericParamList
>) -> Option
<()> {
298 let name
= variant
.name()?
;
300 .filter(|generics
| generics
.generic_params().count() > 0)
301 .map(|generics
| make
::ty(&format
!("{}{}", &name
.text(), generics
.to_generic_args())))
302 .unwrap_or_else(|| make
::ty(&name
.text()));
304 // change from a record to a tuple field list
305 let tuple_field
= make
::tuple_field(None
, ty
);
306 let field_list
= make
::tuple_field_list(iter
::once(tuple_field
)).clone_for_update();
307 ted
::replace(variant
.field_list()?
.syntax(), field_list
.syntax());
309 // remove any ws after the name
310 if let Some(ws
) = name
312 .siblings_with_tokens(syntax
::Direction
::Next
)
313 .find_map(|tok
| tok
.into_token().filter(|tok
| tok
.kind() == WHITESPACE
))
315 ted
::remove(SyntaxElement
::Token(ws
));
321 // Note: this also detaches whitespace after comments,
322 // since `SyntaxNode::splice_children` (and by extension `ted::insert_all_raw`)
323 // detaches nodes. If we only took the comments, we'd leave behind the old whitespace.
324 fn take_all_comments(node
: &SyntaxNode
) -> Vec
<SyntaxElement
> {
325 let mut remove_next_ws
= false;
326 node
.children_with_tokens()
327 .filter_map(move |child
| match child
.kind() {
329 remove_next_ws
= true;
333 WHITESPACE
if remove_next_ws
=> {
334 remove_next_ws
= false;
336 Some(make
::tokens
::single_newline().into())
339 remove_next_ws
= false;
347 insert_use_cfg
: InsertUseConfig
,
348 segment
: ast
::PathSegment
,
350 import
: Option
<(ImportScope
, hir
::ModPath
)>,
352 if let Some((scope
, path
)) = import
{
353 insert_use(&scope
, mod_path_to_ast(&path
), &insert_use_cfg
);
355 // deep clone to prevent cycle
356 let path
= make
::path_from_segments(iter
::once(segment
.clone_subtree()), false);
357 ted
::insert_raw(ted
::Position
::before(segment
.syntax()), path
.clone_for_update().syntax());
358 ted
::insert_raw(ted
::Position
::before(segment
.syntax()), make
::token(T
!['
('
]));
359 ted
::insert_raw(ted
::Position
::after(&node
), make
::token(T
!['
)'
]));
362 fn process_references(
363 ctx
: &AssistContext
<'_
>,
364 builder
: &mut SourceChangeBuilder
,
365 visited_modules
: &mut FxHashSet
<Module
>,
366 enum_module_def
: &ModuleDef
,
367 variant_hir_name
: &Name
,
368 refs
: Vec
<FileReference
>,
369 ) -> Vec
<(ast
::PathSegment
, SyntaxNode
, Option
<(ImportScope
, hir
::ModPath
)>)> {
370 // we have to recollect here eagerly as we are about to edit the tree we need to calculate the changes
371 // and corresponding nodes up front
373 .flat_map(|reference
| {
374 let (segment
, scope_node
, module
) = reference_to_node(&ctx
.sema
, reference
)?
;
375 let segment
= builder
.make_mut(segment
);
376 let scope_node
= builder
.make_syntax_mut(scope_node
);
377 if !visited_modules
.contains(&module
) {
378 let mod_path
= module
.find_use_path_prefixed(
381 ctx
.config
.insert_use
.prefix_kind
,
382 ctx
.config
.prefer_no_std
,
384 if let Some(mut mod_path
) = mod_path
{
385 mod_path
.pop_segment();
386 mod_path
.push_segment(variant_hir_name
.clone());
387 let scope
= ImportScope
::find_insert_use_container(&scope_node
, &ctx
.sema
)?
;
388 visited_modules
.insert(module
);
389 return Some((segment
, scope_node
, Some((scope
, mod_path
))));
392 Some((segment
, scope_node
, None
))
397 fn reference_to_node(
398 sema
: &hir
::Semantics
<'_
, RootDatabase
>,
399 reference
: FileReference
,
400 ) -> Option
<(ast
::PathSegment
, SyntaxNode
, hir
::Module
)> {
402 reference
.name
.as_name_ref()?
.syntax().parent().and_then(ast
::PathSegment
::cast
)?
;
403 let parent
= segment
.parent_path().syntax().parent()?
;
404 let expr_or_pat
= match_ast
! {
406 ast
::PathExpr(_it
) => parent
.parent()?
,
407 ast
::RecordExpr(_it
) => parent
,
408 ast
::TupleStructPat(_it
) => parent
,
409 ast
::RecordPat(_it
) => parent
,
413 let module
= sema
.scope(&expr_or_pat
)?
.module();
414 Some((segment
, expr_or_pat
, module
))
419 use crate::tests
::{check_assist, check_assist_not_applicable}
;
424 fn test_extract_struct_several_fields_tuple() {
426 extract_struct_from_enum_variant
,
427 "enum A { $0One(u32, u32) }",
428 r
#"struct One(u32, u32);
430 enum A { One(One) }"#,
435 fn test_extract_struct_several_fields_named() {
437 extract_struct_from_enum_variant
,
438 "enum A { $0One { foo: u32, bar: u32 } }",
439 r
#"struct One{ foo: u32, bar: u32 }
441 enum A { One(One) }"#,
446 fn test_extract_struct_one_field_named() {
448 extract_struct_from_enum_variant
,
449 "enum A { $0One { foo: u32 } }",
450 r
#"struct One{ foo: u32 }
452 enum A { One(One) }"#,
457 fn test_extract_struct_carries_over_generics() {
459 extract_struct_from_enum_variant
,
460 r
"enum En<T> { Var { a: T$0 } }",
461 r
#"struct Var<T>{ a: T }
463 enum En<T> { Var(Var<T>) }"#,
468 fn test_extract_struct_carries_over_attributes() {
470 extract_struct_from_enum_variant
,
474 enum Enum { Variant{ field: u32$0 } }"#,
478 struct Variant{ field: u32 }
482 enum Enum { Variant(Variant) }"#,
487 fn test_extract_struct_indent_to_parent_enum() {
489 extract_struct_from_enum_variant
,
508 fn test_extract_struct_indent_to_parent_enum_in_mod() {
510 extract_struct_from_enum_variant
,
533 fn test_extract_struct_keep_comments_and_attrs_one_field_named() {
535 extract_struct_from_enum_variant
,
562 fn test_extract_struct_keep_comments_and_attrs_several_fields_named() {
564 extract_struct_from_enum_variant
,
597 fn test_extract_struct_keep_comments_and_attrs_several_fields_tuple() {
599 extract_struct_from_enum_variant
,
600 "enum A { $0One(/* comment */ #[attr] u32, /* another */ u32 /* tail */) }",
602 struct One(/* comment */ #[attr] u32, /* another */ u32 /* tail */);
604 enum A { One(One) }"#,
609 fn test_extract_struct_move_struct_variant_comments() {
611 extract_struct_from_enum_variant
,
638 fn test_extract_struct_move_tuple_variant_comments() {
640 extract_struct_from_enum_variant
,
653 struct One(u32, u32);
663 fn test_extract_struct_keep_existing_visibility_named() {
665 extract_struct_from_enum_variant
,
666 "enum A { $0One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 } }",
668 struct One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 }
670 enum A { One(One) }"#,
675 fn test_extract_struct_keep_existing_visibility_tuple() {
677 extract_struct_from_enum_variant
,
678 "enum A { $0One(u32, pub(crate) u32, pub(super) u32, u32) }",
680 struct One(u32, pub(crate) u32, pub(super) u32, u32);
682 enum A { One(One) }"#,
687 fn test_extract_enum_variant_name_value_namespace() {
689 extract_struct_from_enum_variant
,
690 r
#"const One: () = ();
691 enum A { $0One(u32, u32) }"#,
692 r
#"const One: () = ();
693 struct One(u32, u32);
695 enum A { One(One) }"#,
700 fn test_extract_struct_no_visibility() {
702 extract_struct_from_enum_variant
,
703 "enum A { $0One(u32, u32) }",
705 struct One(u32, u32);
707 enum A { One(One) }"#,
712 fn test_extract_struct_pub_visibility() {
714 extract_struct_from_enum_variant
,
715 "pub enum A { $0One(u32, u32) }",
717 pub struct One(pub u32, pub u32);
719 pub enum A { One(One) }"#,
724 fn test_extract_struct_pub_in_mod_visibility() {
726 extract_struct_from_enum_variant
,
727 "pub(in something) enum A { $0One{ a: u32, b: u32 } }",
729 pub(in something) struct One{ pub(in something) a: u32, pub(in something) b: u32 }
731 pub(in something) enum A { One(One) }"#,
736 fn test_extract_struct_pub_crate_visibility() {
738 extract_struct_from_enum_variant
,
739 "pub(crate) enum A { $0One{ a: u32, b: u32, c: u32 } }",
741 pub(crate) struct One{ pub(crate) a: u32, pub(crate) b: u32, pub(crate) c: u32 }
743 pub(crate) enum A { One(One) }"#,
748 fn test_extract_struct_with_complex_imports() {
750 extract_struct_from_enum_variant
,
753 let m = my_other_mod::MyEnum::MyField(1, 1);
756 pub mod my_other_mod {
758 let m = MyEnum::MyField(1, 1);
768 let m = my_mod::my_other_mod::MyEnum::MyField(1, 1);
770 r
#"use my_mod::my_other_mod::MyField;
773 use self::my_other_mod::MyField;
776 let m = my_other_mod::MyEnum::MyField(MyField(1, 1));
779 pub mod my_other_mod {
781 let m = MyEnum::MyField(MyField(1, 1));
784 pub struct MyField(pub u8, pub u8);
793 let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1));
799 fn extract_record_fix_references() {
801 extract_struct_from_enum_variant
,
804 $0V { i: i32, j: i32 }
808 let E::V { i, j } = E::V { i: 9, j: 2 };
812 struct V{ i: i32, j: i32 }
819 let E::V(V { i, j }) = E::V(V { i: 9, j: 2 });
826 fn extract_record_fix_references2() {
828 extract_struct_from_enum_variant
,
835 let E::V(i, j) = E::V(9, 2);
846 let E::V(V(i, j)) = E::V(V(9, 2));
853 fn test_several_files() {
855 extract_struct_from_enum_variant
,
881 let e = E::V(V(9, 2));
888 fn test_several_files_record() {
890 extract_struct_from_enum_variant
,
894 $0V { i: i32, j: i32 }
901 let e = E::V { i: 9, j: 2 };
906 struct V{ i: i32, j: i32 }
916 let e = E::V(V { i: 9, j: 2 });
923 fn test_extract_struct_record_nested_call_exp() {
925 extract_struct_from_enum_variant
,
927 enum A { $0One { a: u32, b: u32 } }
932 let _ = B(A::One { a: 1, b: 2 });
936 struct One{ a: u32, b: u32 }
943 let _ = B(A::One(One { a: 1, b: 2 }));
950 fn test_extract_enum_not_applicable_for_element_with_no_fields() {
951 check_assist_not_applicable(extract_struct_from_enum_variant
, r
#"enum A { $0One }"#);
955 fn test_extract_enum_not_applicable_if_struct_exists() {
956 cov_mark
::check
!(test_extract_enum_not_applicable_if_struct_exists
);
957 check_assist_not_applicable(
958 extract_struct_from_enum_variant
,
961 enum A { $0One(u8, u32) }
967 fn test_extract_not_applicable_one_field() {
968 check_assist_not_applicable(extract_struct_from_enum_variant
, r
"enum A { $0One(u32) }");
972 fn test_extract_not_applicable_no_field_tuple() {
973 check_assist_not_applicable(extract_struct_from_enum_variant
, r
"enum A { $0None() }");
977 fn test_extract_not_applicable_no_field_named() {
978 check_assist_not_applicable(extract_struct_from_enum_variant
, r
"enum A { $0None {} }");
982 fn test_extract_struct_only_copies_needed_generics() {
984 extract_struct_from_enum_variant
,
987 $0A { a: &'a &'x mut () },
993 struct A<'a, 'x>{ a: &'a &'x mut () }
1005 fn test_extract_struct_with_liftime_type_const() {
1007 extract_struct_from_enum_variant
,
1009 enum X<'b, T, V, const C: usize> {
1010 $0A { a: T, b: X<'b>, c: [u8; C] },
1015 struct A<'b, T, const C: usize>{ a: T, b: X<'b>, c: [u8; C] }
1017 enum X<'b, T, V, const C: usize> {
1026 fn test_extract_struct_without_generics() {
1028 extract_struct_from_enum_variant
,
1049 fn test_extract_struct_keeps_trait_bounds() {
1051 extract_struct_from_enum_variant
,
1053 enum En<T: TraitT, V: TraitV> {
1059 struct A<T: TraitT>{ a: T }
1061 enum En<T: TraitT, V: TraitV> {