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 indent = enum_ast.indent_level();
105 let generic_params = enum_ast
106 .generic_param_list()
107 .and_then(|known_generics| extract_generic_params(&known_generics, &field_list));
108 let generics = generic_params.as_ref().map(|generics| generics.clone_for_update());
110 create_struct_def(variant_name.clone(), &variant, &field_list, generics, &enum_ast);
111 def.reindent_to(indent);
113 let start_offset = &variant.parent_enum().syntax().clone();
115 ted::Position::before(start_offset),
117 def.syntax().clone().into(),
118 make::tokens::whitespace(&format!("\n\n{}", indent)).into(),
122 update_variant(&variant, generic_params.map(|g| g.clone_for_update()));
127 fn extract_field_list_if_applicable(
128 variant: &ast::Variant,
129 ) -> Option<Either<ast::RecordFieldList, ast::TupleFieldList>> {
130 match variant.kind() {
131 ast::StructKind::Record(field_list) if field_list.fields().next().is_some() => {
132 Some(Either::Left(field_list))
134 ast::StructKind::Tuple(field_list) if field_list.fields().count() > 1 => {
135 Some(Either::Right(field_list))
141 fn existing_definition(db: &RootDatabase, variant_name: &ast::Name, variant: &Variant) -> bool {
147 .filter(|(_, def)| match def {
148 // only check type-namespace
149 hir::ScopeDef::ModuleDef(def) => matches!(
153 | ModuleDef::Variant(_)
154 | ModuleDef::Trait(_)
155 | ModuleDef::TypeAlias(_)
156 | ModuleDef::BuiltinType(_)
160 .any(|(name, _)| name.to_string() == variant_name.to_string())
163 fn extract_generic_params(
164 known_generics: &ast::GenericParamList,
165 field_list: &Either<ast::RecordFieldList, ast::TupleFieldList>,
166 ) -> Option<ast::GenericParamList> {
167 let mut generics = known_generics.generic_params().map(|param| (param, false)).collect_vec();
169 let tagged_one = match field_list {
170 Either::Left(field_list) => field_list
172 .filter_map(|f| f.ty())
173 .fold(false, |tagged, ty| tag_generics_in_variant(&ty, &mut generics) || tagged),
174 Either::Right(field_list) => field_list
176 .filter_map(|f| f.ty())
177 .fold(false, |tagged, ty| tag_generics_in_variant(&ty, &mut generics) || tagged),
180 let generics = generics.into_iter().filter_map(|(param, tag)| tag.then(|| param));
181 tagged_one.then(|| make::generic_param_list(generics))
184 fn tag_generics_in_variant(ty: &ast::Type, generics: &mut [(ast::GenericParam, bool)]) -> bool {
185 let mut tagged_one = false;
187 for token in ty.syntax().descendants_with_tokens().filter_map(SyntaxElement::into_token) {
188 for (param, tag) in generics.iter_mut().filter(|(_, tag)| !tag) {
190 ast::GenericParam::LifetimeParam(lt)
191 if matches!(token.kind(), T![lifetime_ident]) =>
193 if let Some(lt) = lt.lifetime() {
194 if lt.text().as_str() == token.text() {
201 param if matches!(token.kind(), T![ident]) => {
203 ast::GenericParam::ConstParam(konst) => konst
205 .map(|name| name.text().as_str() == token.text())
206 .unwrap_or_default(),
207 ast::GenericParam::TypeParam(ty) => ty
209 .map(|name| name.text().as_str() == token.text())
210 .unwrap_or_default(),
211 ast::GenericParam::LifetimeParam(lt) => lt
213 .map(|lt| lt.text().as_str() == token.text())
214 .unwrap_or_default(),
229 fn create_struct_def(
230 variant_name: ast::Name,
231 variant: &ast::Variant,
232 field_list: &Either<ast::RecordFieldList, ast::TupleFieldList>,
233 generics: Option<ast::GenericParamList>,
236 let enum_vis = enum_.visibility();
238 let insert_vis = |node: &'_ SyntaxNode, vis: &'_ SyntaxNode| {
239 let vis = vis.clone_for_update();
240 ted::insert(ted::Position::before(node), vis);
243 // for fields without any existing visibility, use visibility of enum
244 let field_list: ast::FieldList = match field_list {
245 Either::Left(field_list) => {
246 let field_list = field_list.clone_for_update();
248 if let Some(vis) = &enum_vis {
251 .filter(|field| field.visibility().is_none())
252 .filter_map(|field| field.name())
253 .for_each(|it| insert_vis(it.syntax(), vis.syntax()));
258 Either::Right(field_list) => {
259 let field_list = field_list.clone_for_update();
261 if let Some(vis) = &enum_vis {
264 .filter(|field| field.visibility().is_none())
265 .filter_map(|field| field.ty())
266 .for_each(|it| insert_vis(it.syntax(), vis.syntax()));
273 field_list.reindent_to(IndentLevel::single());
275 let strukt = make::struct_(enum_vis, variant_name, generics, field_list).clone_for_update();
277 // FIXME: Consider making this an actual function somewhere (like in `AttrsOwnerEdit`) after some deliberation
278 let attrs_and_docs = |node: &SyntaxNode| {
279 let mut select_next_ws = false;
280 node.children_with_tokens().filter(move |child| {
281 let accept = match child.kind() {
283 select_next_ws = true;
286 WHITESPACE if select_next_ws => true,
289 select_next_ws = false;
295 // copy attributes & comments from variant
296 let variant_attrs = attrs_and_docs(variant.syntax())
297 .map(|tok| match tok.kind() {
298 WHITESPACE => make::tokens::single_newline().into(),
302 ted::insert_all(ted::Position::first_child_of(strukt.syntax()), variant_attrs);
304 // copy attributes from enum
306 ted::Position::first_child_of(strukt.syntax()),
307 enum_.attrs().map(|it| it.syntax().clone_for_update().into()).collect(),
312 fn update_variant(variant: &ast::Variant, generics: Option<ast::GenericParamList>) -> Option<()> {
313 let name = variant.name()?;
315 .filter(|generics| generics.generic_params().count() > 0)
317 let mut generic_str = String::with_capacity(8);
319 for (p, more) in generics.generic_params().with_position().map(|p| match p {
320 Position::First(p) | Position::Middle(p) => (p, true),
321 Position::Last(p) | Position::Only(p) => (p, false),
324 ast::GenericParam::ConstParam(konst) => {
325 if let Some(name) = konst.name() {
326 generic_str.push_str(name.text().as_str());
329 ast::GenericParam::LifetimeParam(lt) => {
330 if let Some(lt) = lt.lifetime() {
331 generic_str.push_str(lt.text().as_str());
334 ast::GenericParam::TypeParam(ty) => {
335 if let Some(name) = ty.name() {
336 generic_str.push_str(name.text().as_str());
341 generic_str.push_str(", ");
345 make::ty(&format!("{}<{}>", &name.text(), &generic_str))
347 .unwrap_or_else(|| make::ty(&name.text()));
349 let tuple_field = make::tuple_field(None, ty);
350 let replacement = make::variant(
352 Some(ast::FieldList::TupleFieldList(make::tuple_field_list(iter::once(tuple_field)))),
355 ted::replace(variant.syntax(), replacement.syntax());
360 insert_use_cfg: InsertUseConfig,
361 segment: ast::PathSegment,
363 import: Option<(ImportScope, hir::ModPath)>,
365 if let Some((scope, path)) = import {
366 insert_use(&scope, mod_path_to_ast(&path), &insert_use_cfg);
368 // deep clone to prevent cycle
369 let path = make::path_from_segments(iter::once(segment.clone_subtree()), false);
370 ted::insert_raw(ted::Position::before(segment.syntax()), path.clone_for_update().syntax());
371 ted::insert_raw(ted::Position::before(segment.syntax()), make::token(T!['(']));
372 ted::insert_raw(ted::Position::after(&node), make::token(T![')']));
375 fn process_references(
376 ctx: &AssistContext<'_>,
377 builder: &mut SourceChangeBuilder,
378 visited_modules: &mut FxHashSet<Module>,
379 enum_module_def: &ModuleDef,
380 variant_hir_name: &Name,
381 refs: Vec<FileReference>,
382 ) -> Vec<(ast::PathSegment, SyntaxNode, Option<(ImportScope, hir::ModPath)>)> {
383 // we have to recollect here eagerly as we are about to edit the tree we need to calculate the changes
384 // and corresponding nodes up front
386 .flat_map(|reference| {
387 let (segment, scope_node, module) = reference_to_node(&ctx.sema, reference)?;
388 let segment = builder.make_mut(segment);
389 let scope_node = builder.make_syntax_mut(scope_node);
390 if !visited_modules.contains(&module) {
391 let mod_path = module.find_use_path_prefixed(
394 ctx.config.insert_use.prefix_kind,
396 if let Some(mut mod_path) = mod_path {
397 mod_path.pop_segment();
398 mod_path.push_segment(variant_hir_name.clone());
399 let scope = ImportScope::find_insert_use_container(&scope_node, &ctx.sema)?;
400 visited_modules.insert(module);
401 return Some((segment, scope_node, Some((scope, mod_path))));
404 Some((segment, scope_node, None))
409 fn reference_to_node(
410 sema: &hir::Semantics<'_, RootDatabase>,
411 reference: FileReference,
412 ) -> Option<(ast::PathSegment, SyntaxNode, hir::Module)> {
414 reference.name.as_name_ref()?.syntax().parent().and_then(ast::PathSegment::cast)?;
415 let parent = segment.parent_path().syntax().parent()?;
416 let expr_or_pat = match_ast! {
418 ast::PathExpr(_it) => parent.parent()?,
419 ast::RecordExpr(_it) => parent,
420 ast::TupleStructPat(_it) => parent,
421 ast::RecordPat(_it) => parent,
425 let module = sema.scope(&expr_or_pat)?.module();
426 Some((segment, expr_or_pat, module))
431 use crate::tests::{check_assist, check_assist_not_applicable};
436 fn test_extract_struct_several_fields_tuple() {
438 extract_struct_from_enum_variant,
439 "enum A { $0One(u32, u32) }",
440 r#"struct One(u32, u32);
442 enum A { One(One) }"#,
447 fn test_extract_struct_several_fields_named() {
449 extract_struct_from_enum_variant,
450 "enum A { $0One { foo: u32, bar: u32 } }",
451 r#"struct One{ foo: u32, bar: u32 }
453 enum A { One(One) }"#,
458 fn test_extract_struct_one_field_named() {
460 extract_struct_from_enum_variant,
461 "enum A { $0One { foo: u32 } }",
462 r#"struct One{ foo: u32 }
464 enum A { One(One) }"#,
469 fn test_extract_struct_carries_over_generics() {
471 extract_struct_from_enum_variant,
472 r"enum En<T> { Var { a: T$0 } }",
473 r#"struct Var<T>{ a: T }
475 enum En<T> { Var(Var<T>) }"#,
480 fn test_extract_struct_carries_over_attributes() {
482 extract_struct_from_enum_variant,
485 enum Enum { Variant{ field: u32$0 } }"#,
486 r#"#[derive(Debug)]#[derive(Clone)] struct Variant{ field: u32 }
490 enum Enum { Variant(Variant) }"#,
495 fn test_extract_struct_indent_to_parent_enum() {
497 extract_struct_from_enum_variant,
516 fn test_extract_struct_indent_to_parent_enum_in_mod() {
518 extract_struct_from_enum_variant,
541 fn test_extract_struct_keep_comments_and_attrs_one_field_named() {
543 extract_struct_from_enum_variant,
570 fn test_extract_struct_keep_comments_and_attrs_several_fields_named() {
572 extract_struct_from_enum_variant,
605 fn test_extract_struct_keep_comments_and_attrs_several_fields_tuple() {
607 extract_struct_from_enum_variant,
608 "enum A { $0One(/* comment */ #[attr] u32, /* another */ u32 /* tail */) }",
610 struct One(/* comment */ #[attr] u32, /* another */ u32 /* tail */);
612 enum A { One(One) }"#,
617 fn test_extract_struct_keep_comments_and_attrs_on_variant_struct() {
619 extract_struct_from_enum_variant,
646 fn test_extract_struct_keep_comments_and_attrs_on_variant_tuple() {
648 extract_struct_from_enum_variant,
662 struct One(u32, u32);
671 fn test_extract_struct_keep_existing_visibility_named() {
673 extract_struct_from_enum_variant,
674 "enum A { $0One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 } }",
676 struct One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 }
678 enum A { One(One) }"#,
683 fn test_extract_struct_keep_existing_visibility_tuple() {
685 extract_struct_from_enum_variant,
686 "enum A { $0One(u32, pub(crate) u32, pub(super) u32, u32) }",
688 struct One(u32, pub(crate) u32, pub(super) u32, u32);
690 enum A { One(One) }"#,
695 fn test_extract_enum_variant_name_value_namespace() {
697 extract_struct_from_enum_variant,
698 r#"const One: () = ();
699 enum A { $0One(u32, u32) }"#,
700 r#"const One: () = ();
701 struct One(u32, u32);
703 enum A { One(One) }"#,
708 fn test_extract_struct_no_visibility() {
710 extract_struct_from_enum_variant,
711 "enum A { $0One(u32, u32) }",
713 struct One(u32, u32);
715 enum A { One(One) }"#,
720 fn test_extract_struct_pub_visibility() {
722 extract_struct_from_enum_variant,
723 "pub enum A { $0One(u32, u32) }",
725 pub struct One(pub u32, pub u32);
727 pub enum A { One(One) }"#,
732 fn test_extract_struct_pub_in_mod_visibility() {
734 extract_struct_from_enum_variant,
735 "pub(in something) enum A { $0One{ a: u32, b: u32 } }",
737 pub(in something) struct One{ pub(in something) a: u32, pub(in something) b: u32 }
739 pub(in something) enum A { One(One) }"#,
744 fn test_extract_struct_pub_crate_visibility() {
746 extract_struct_from_enum_variant,
747 "pub(crate) enum A { $0One{ a: u32, b: u32, c: u32 } }",
749 pub(crate) struct One{ pub(crate) a: u32, pub(crate) b: u32, pub(crate) c: u32 }
751 pub(crate) enum A { One(One) }"#,
756 fn test_extract_struct_with_complex_imports() {
758 extract_struct_from_enum_variant,
761 let m = my_other_mod::MyEnum::MyField(1, 1);
764 pub mod my_other_mod {
766 let m = MyEnum::MyField(1, 1);
776 let m = my_mod::my_other_mod::MyEnum::MyField(1, 1);
778 r#"use my_mod::my_other_mod::MyField;
781 use self::my_other_mod::MyField;
784 let m = my_other_mod::MyEnum::MyField(MyField(1, 1));
787 pub mod my_other_mod {
789 let m = MyEnum::MyField(MyField(1, 1));
792 pub struct MyField(pub u8, pub u8);
801 let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1));
807 fn extract_record_fix_references() {
809 extract_struct_from_enum_variant,
812 $0V { i: i32, j: i32 }
816 let E::V { i, j } = E::V { i: 9, j: 2 };
820 struct V{ i: i32, j: i32 }
827 let E::V(V { i, j }) = E::V(V { i: 9, j: 2 });
834 fn extract_record_fix_references2() {
836 extract_struct_from_enum_variant,
843 let E::V(i, j) = E::V(9, 2);
854 let E::V(V(i, j)) = E::V(V(9, 2));
861 fn test_several_files() {
863 extract_struct_from_enum_variant,
889 let e = E::V(V(9, 2));
896 fn test_several_files_record() {
898 extract_struct_from_enum_variant,
902 $0V { i: i32, j: i32 }
909 let e = E::V { i: 9, j: 2 };
914 struct V{ i: i32, j: i32 }
924 let e = E::V(V { i: 9, j: 2 });
931 fn test_extract_struct_record_nested_call_exp() {
933 extract_struct_from_enum_variant,
935 enum A { $0One { a: u32, b: u32 } }
940 let _ = B(A::One { a: 1, b: 2 });
944 struct One{ a: u32, b: u32 }
951 let _ = B(A::One(One { a: 1, b: 2 }));
958 fn test_extract_enum_not_applicable_for_element_with_no_fields() {
959 check_assist_not_applicable(extract_struct_from_enum_variant, r#"enum A { $0One }"#);
963 fn test_extract_enum_not_applicable_if_struct_exists() {
964 cov_mark::check!(test_extract_enum_not_applicable_if_struct_exists);
965 check_assist_not_applicable(
966 extract_struct_from_enum_variant,
969 enum A { $0One(u8, u32) }
975 fn test_extract_not_applicable_one_field() {
976 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0One(u32) }");
980 fn test_extract_not_applicable_no_field_tuple() {
981 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None() }");
985 fn test_extract_not_applicable_no_field_named() {
986 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None {} }");
990 fn test_extract_struct_only_copies_needed_generics() {
992 extract_struct_from_enum_variant,
995 $0A { a: &'a &'x mut () },
1001 struct A<'a, 'x>{ a: &'a &'x mut () }
1003 enum X<'a, 'b, 'x> {
1013 fn test_extract_struct_with_liftime_type_const() {
1015 extract_struct_from_enum_variant,
1017 enum X<'b, T, V, const C: usize> {
1018 $0A { a: T, b: X<'b>, c: [u8; C] },
1023 struct A<'b, T, const C: usize>{ a: T, b: X<'b>, c: [u8; C] }
1025 enum X<'b, T, V, const C: usize> {
1034 fn test_extract_struct_without_generics() {
1036 extract_struct_from_enum_variant,
1057 fn test_extract_struct_keeps_trait_bounds() {
1059 extract_struct_from_enum_variant,
1061 enum En<T: TraitT, V: TraitV> {
1067 struct A<T: TraitT>{ a: T }
1069 enum En<T: TraitT, V: TraitV> {