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, Position};
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)
302 let mut generic_str = String::with_capacity(8);
304 for (p, more) in generics.generic_params().with_position().map(|p| match p {
305 Position::First(p) | Position::Middle(p) => (p, true),
306 Position::Last(p) | Position::Only(p) => (p, false),
309 ast::GenericParam::ConstParam(konst) => {
310 if let Some(name) = konst.name() {
311 generic_str.push_str(name.text().as_str());
314 ast::GenericParam::LifetimeParam(lt) => {
315 if let Some(lt) = lt.lifetime() {
316 generic_str.push_str(lt.text().as_str());
319 ast::GenericParam::TypeParam(ty) => {
320 if let Some(name) = ty.name() {
321 generic_str.push_str(name.text().as_str());
326 generic_str.push_str(", ");
330 make::ty(&format!("{}<{}>", &name.text(), &generic_str))
332 .unwrap_or_else(|| make::ty(&name.text()));
334 // change from a record to a tuple field list
335 let tuple_field = make::tuple_field(None, ty);
336 let field_list = make::tuple_field_list(iter::once(tuple_field)).clone_for_update();
337 ted::replace(variant.field_list()?.syntax(), field_list.syntax());
339 // remove any ws after the name
340 if let Some(ws) = name
342 .siblings_with_tokens(syntax::Direction::Next)
343 .find_map(|tok| tok.into_token().filter(|tok| tok.kind() == WHITESPACE))
345 ted::remove(SyntaxElement::Token(ws));
351 // Note: this also detaches whitespace after comments,
352 // since `SyntaxNode::splice_children` (and by extension `ted::insert_all_raw`)
353 // detaches nodes. If we only took the comments, we'd leave behind the old whitespace.
354 fn take_all_comments(node: &SyntaxNode) -> Vec<SyntaxElement> {
355 let mut remove_next_ws = false;
356 node.children_with_tokens()
357 .filter_map(move |child| match child.kind() {
359 remove_next_ws = true;
363 WHITESPACE if remove_next_ws => {
364 remove_next_ws = false;
366 Some(make::tokens::single_newline().into())
369 remove_next_ws = false;
377 insert_use_cfg: InsertUseConfig,
378 segment: ast::PathSegment,
380 import: Option<(ImportScope, hir::ModPath)>,
382 if let Some((scope, path)) = import {
383 insert_use(&scope, mod_path_to_ast(&path), &insert_use_cfg);
385 // deep clone to prevent cycle
386 let path = make::path_from_segments(iter::once(segment.clone_subtree()), false);
387 ted::insert_raw(ted::Position::before(segment.syntax()), path.clone_for_update().syntax());
388 ted::insert_raw(ted::Position::before(segment.syntax()), make::token(T!['(']));
389 ted::insert_raw(ted::Position::after(&node), make::token(T![')']));
392 fn process_references(
393 ctx: &AssistContext<'_>,
394 builder: &mut SourceChangeBuilder,
395 visited_modules: &mut FxHashSet<Module>,
396 enum_module_def: &ModuleDef,
397 variant_hir_name: &Name,
398 refs: Vec<FileReference>,
399 ) -> Vec<(ast::PathSegment, SyntaxNode, Option<(ImportScope, hir::ModPath)>)> {
400 // we have to recollect here eagerly as we are about to edit the tree we need to calculate the changes
401 // and corresponding nodes up front
403 .flat_map(|reference| {
404 let (segment, scope_node, module) = reference_to_node(&ctx.sema, reference)?;
405 let segment = builder.make_mut(segment);
406 let scope_node = builder.make_syntax_mut(scope_node);
407 if !visited_modules.contains(&module) {
408 let mod_path = module.find_use_path_prefixed(
411 ctx.config.insert_use.prefix_kind,
412 ctx.config.prefer_no_std,
414 if let Some(mut mod_path) = mod_path {
415 mod_path.pop_segment();
416 mod_path.push_segment(variant_hir_name.clone());
417 let scope = ImportScope::find_insert_use_container(&scope_node, &ctx.sema)?;
418 visited_modules.insert(module);
419 return Some((segment, scope_node, Some((scope, mod_path))));
422 Some((segment, scope_node, None))
427 fn reference_to_node(
428 sema: &hir::Semantics<'_, RootDatabase>,
429 reference: FileReference,
430 ) -> Option<(ast::PathSegment, SyntaxNode, hir::Module)> {
432 reference.name.as_name_ref()?.syntax().parent().and_then(ast::PathSegment::cast)?;
433 let parent = segment.parent_path().syntax().parent()?;
434 let expr_or_pat = match_ast! {
436 ast::PathExpr(_it) => parent.parent()?,
437 ast::RecordExpr(_it) => parent,
438 ast::TupleStructPat(_it) => parent,
439 ast::RecordPat(_it) => parent,
443 let module = sema.scope(&expr_or_pat)?.module();
444 Some((segment, expr_or_pat, module))
449 use crate::tests::{check_assist, check_assist_not_applicable};
454 fn test_extract_struct_several_fields_tuple() {
456 extract_struct_from_enum_variant,
457 "enum A { $0One(u32, u32) }",
458 r#"struct One(u32, u32);
460 enum A { One(One) }"#,
465 fn test_extract_struct_several_fields_named() {
467 extract_struct_from_enum_variant,
468 "enum A { $0One { foo: u32, bar: u32 } }",
469 r#"struct One{ foo: u32, bar: u32 }
471 enum A { One(One) }"#,
476 fn test_extract_struct_one_field_named() {
478 extract_struct_from_enum_variant,
479 "enum A { $0One { foo: u32 } }",
480 r#"struct One{ foo: u32 }
482 enum A { One(One) }"#,
487 fn test_extract_struct_carries_over_generics() {
489 extract_struct_from_enum_variant,
490 r"enum En<T> { Var { a: T$0 } }",
491 r#"struct Var<T>{ a: T }
493 enum En<T> { Var(Var<T>) }"#,
498 fn test_extract_struct_carries_over_attributes() {
500 extract_struct_from_enum_variant,
504 enum Enum { Variant{ field: u32$0 } }"#,
508 struct Variant{ field: u32 }
512 enum Enum { Variant(Variant) }"#,
517 fn test_extract_struct_indent_to_parent_enum() {
519 extract_struct_from_enum_variant,
538 fn test_extract_struct_indent_to_parent_enum_in_mod() {
540 extract_struct_from_enum_variant,
563 fn test_extract_struct_keep_comments_and_attrs_one_field_named() {
565 extract_struct_from_enum_variant,
592 fn test_extract_struct_keep_comments_and_attrs_several_fields_named() {
594 extract_struct_from_enum_variant,
627 fn test_extract_struct_keep_comments_and_attrs_several_fields_tuple() {
629 extract_struct_from_enum_variant,
630 "enum A { $0One(/* comment */ #[attr] u32, /* another */ u32 /* tail */) }",
632 struct One(/* comment */ #[attr] u32, /* another */ u32 /* tail */);
634 enum A { One(One) }"#,
639 fn test_extract_struct_move_struct_variant_comments() {
641 extract_struct_from_enum_variant,
668 fn test_extract_struct_move_tuple_variant_comments() {
670 extract_struct_from_enum_variant,
683 struct One(u32, u32);
693 fn test_extract_struct_keep_existing_visibility_named() {
695 extract_struct_from_enum_variant,
696 "enum A { $0One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 } }",
698 struct One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 }
700 enum A { One(One) }"#,
705 fn test_extract_struct_keep_existing_visibility_tuple() {
707 extract_struct_from_enum_variant,
708 "enum A { $0One(u32, pub(crate) u32, pub(super) u32, u32) }",
710 struct One(u32, pub(crate) u32, pub(super) u32, u32);
712 enum A { One(One) }"#,
717 fn test_extract_enum_variant_name_value_namespace() {
719 extract_struct_from_enum_variant,
720 r#"const One: () = ();
721 enum A { $0One(u32, u32) }"#,
722 r#"const One: () = ();
723 struct One(u32, u32);
725 enum A { One(One) }"#,
730 fn test_extract_struct_no_visibility() {
732 extract_struct_from_enum_variant,
733 "enum A { $0One(u32, u32) }",
735 struct One(u32, u32);
737 enum A { One(One) }"#,
742 fn test_extract_struct_pub_visibility() {
744 extract_struct_from_enum_variant,
745 "pub enum A { $0One(u32, u32) }",
747 pub struct One(pub u32, pub u32);
749 pub enum A { One(One) }"#,
754 fn test_extract_struct_pub_in_mod_visibility() {
756 extract_struct_from_enum_variant,
757 "pub(in something) enum A { $0One{ a: u32, b: u32 } }",
759 pub(in something) struct One{ pub(in something) a: u32, pub(in something) b: u32 }
761 pub(in something) enum A { One(One) }"#,
766 fn test_extract_struct_pub_crate_visibility() {
768 extract_struct_from_enum_variant,
769 "pub(crate) enum A { $0One{ a: u32, b: u32, c: u32 } }",
771 pub(crate) struct One{ pub(crate) a: u32, pub(crate) b: u32, pub(crate) c: u32 }
773 pub(crate) enum A { One(One) }"#,
778 fn test_extract_struct_with_complex_imports() {
780 extract_struct_from_enum_variant,
783 let m = my_other_mod::MyEnum::MyField(1, 1);
786 pub mod my_other_mod {
788 let m = MyEnum::MyField(1, 1);
798 let m = my_mod::my_other_mod::MyEnum::MyField(1, 1);
800 r#"use my_mod::my_other_mod::MyField;
803 use self::my_other_mod::MyField;
806 let m = my_other_mod::MyEnum::MyField(MyField(1, 1));
809 pub mod my_other_mod {
811 let m = MyEnum::MyField(MyField(1, 1));
814 pub struct MyField(pub u8, pub u8);
823 let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1));
829 fn extract_record_fix_references() {
831 extract_struct_from_enum_variant,
834 $0V { i: i32, j: i32 }
838 let E::V { i, j } = E::V { i: 9, j: 2 };
842 struct V{ i: i32, j: i32 }
849 let E::V(V { i, j }) = E::V(V { i: 9, j: 2 });
856 fn extract_record_fix_references2() {
858 extract_struct_from_enum_variant,
865 let E::V(i, j) = E::V(9, 2);
876 let E::V(V(i, j)) = E::V(V(9, 2));
883 fn test_several_files() {
885 extract_struct_from_enum_variant,
911 let e = E::V(V(9, 2));
918 fn test_several_files_record() {
920 extract_struct_from_enum_variant,
924 $0V { i: i32, j: i32 }
931 let e = E::V { i: 9, j: 2 };
936 struct V{ i: i32, j: i32 }
946 let e = E::V(V { i: 9, j: 2 });
953 fn test_extract_struct_record_nested_call_exp() {
955 extract_struct_from_enum_variant,
957 enum A { $0One { a: u32, b: u32 } }
962 let _ = B(A::One { a: 1, b: 2 });
966 struct One{ a: u32, b: u32 }
973 let _ = B(A::One(One { a: 1, b: 2 }));
980 fn test_extract_enum_not_applicable_for_element_with_no_fields() {
981 check_assist_not_applicable(extract_struct_from_enum_variant, r#"enum A { $0One }"#);
985 fn test_extract_enum_not_applicable_if_struct_exists() {
986 cov_mark::check!(test_extract_enum_not_applicable_if_struct_exists);
987 check_assist_not_applicable(
988 extract_struct_from_enum_variant,
991 enum A { $0One(u8, u32) }
997 fn test_extract_not_applicable_one_field() {
998 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0One(u32) }");
1002 fn test_extract_not_applicable_no_field_tuple() {
1003 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None() }");
1007 fn test_extract_not_applicable_no_field_named() {
1008 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None {} }");
1012 fn test_extract_struct_only_copies_needed_generics() {
1014 extract_struct_from_enum_variant,
1016 enum X<'a, 'b, 'x> {
1017 $0A { a: &'a &'x mut () },
1023 struct A<'a, 'x>{ a: &'a &'x mut () }
1025 enum X<'a, 'b, 'x> {
1035 fn test_extract_struct_with_liftime_type_const() {
1037 extract_struct_from_enum_variant,
1039 enum X<'b, T, V, const C: usize> {
1040 $0A { a: T, b: X<'b>, c: [u8; C] },
1045 struct A<'b, T, const C: usize>{ a: T, b: X<'b>, c: [u8; C] }
1047 enum X<'b, T, V, const C: usize> {
1056 fn test_extract_struct_without_generics() {
1058 extract_struct_from_enum_variant,
1079 fn test_extract_struct_keeps_trait_bounds() {
1081 extract_struct_from_enum_variant,
1083 enum En<T: TraitT, V: TraitV> {
1089 struct A<T: TraitT>{ a: T }
1091 enum En<T: TraitT, V: TraitV> {