4 use hir::{Module, ModuleDef, Name, Variant};
8 insert_use::{insert_use, ImportScope, InsertUseConfig},
11 search::FileReference,
14 use itertools::Itertools;
15 use rustc_hash::FxHashSet;
18 self, edit::IndentLevel, edit_in_place::Indent, make, AstNode, HasAttrs, HasGenericParams,
19 HasName, HasTypeBounds, HasVisibility,
22 ted::{self, Position},
27 use crate::{assist_context::AssistBuilder, AssistContext, AssistId, AssistKind, Assists};
29 // Assist: extract_struct_from_enum_variant
31 // Extracts a struct from enum variant.
34 // enum A { $0One(u32, u32) }
38 // struct One(u32, u32);
40 // enum A { One(One) }
42 pub(crate) fn extract_struct_from_enum_variant(
46 let variant = ctx.find_node_at_offset::<ast::Variant>()?;
47 let field_list = extract_field_list_if_applicable(&variant)?;
49 let variant_name = variant.name()?;
50 let variant_hir = ctx.sema.to_def(&variant)?;
51 if existing_definition(ctx.db(), &variant_name, &variant_hir) {
52 cov_mark::hit!(test_extract_enum_not_applicable_if_struct_exists);
56 let enum_ast = variant.parent_enum();
57 let enum_hir = ctx.sema.to_def(&enum_ast)?;
58 let target = variant.syntax().text_range();
60 AssistId("extract_struct_from_enum_variant", AssistKind::RefactorRewrite),
61 "Extract struct from enum variant",
64 let variant_hir_name = variant_hir.name(ctx.db());
65 let enum_module_def = ModuleDef::from(enum_hir);
67 Definition::ModuleDef(ModuleDef::Variant(variant_hir)).usages(&ctx.sema).all();
69 let mut visited_modules_set = FxHashSet::default();
70 let current_module = enum_hir.module(ctx.db());
71 visited_modules_set.insert(current_module);
72 // record file references of the file the def resides in, we only want to swap to the edited file in the builder once
73 let mut def_file_references = None;
74 for (file_id, references) in usages {
75 if file_id == ctx.frange.file_id {
76 def_file_references = Some(references);
79 builder.edit_file(file_id);
80 let processed = process_references(
83 &mut visited_modules_set,
88 processed.into_iter().for_each(|(path, node, import)| {
89 apply_references(ctx.config.insert_use, path, node, import)
92 builder.edit_file(ctx.frange.file_id);
94 let variant = builder.make_mut(variant.clone());
95 if let Some(references) = def_file_references {
96 let processed = process_references(
99 &mut visited_modules_set,
104 processed.into_iter().for_each(|(path, node, import)| {
105 apply_references(ctx.config.insert_use, path, node, import)
109 let indent = enum_ast.indent_level();
110 let def = create_struct_def(variant_name.clone(), &variant, &field_list, &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, enum_ast.generic_param_list());
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 create_struct_def(
164 variant_name: ast::Name,
165 variant: &ast::Variant,
166 field_list: &Either<ast::RecordFieldList, ast::TupleFieldList>,
169 let enum_vis = enum_.visibility();
171 let insert_vis = |node: &'_ SyntaxNode, vis: &'_ SyntaxNode| {
172 let vis = vis.clone_for_update();
173 ted::insert(ted::Position::before(node), vis);
176 // for fields without any existing visibility, use visibility of enum
177 let field_list: ast::FieldList = match field_list {
178 Either::Left(field_list) => {
179 let field_list = field_list.clone_for_update();
181 if let Some(vis) = &enum_vis {
184 .filter(|field| field.visibility().is_none())
185 .filter_map(|field| field.name())
186 .for_each(|it| insert_vis(it.syntax(), vis.syntax()));
191 Either::Right(field_list) => {
192 let field_list = field_list.clone_for_update();
194 if let Some(vis) = &enum_vis {
197 .filter(|field| field.visibility().is_none())
198 .filter_map(|field| field.ty())
199 .for_each(|it| insert_vis(it.syntax(), vis.syntax()));
206 field_list.reindent_to(IndentLevel::single());
208 // FIXME: This uses all the generic params of the enum, but the variant might not use all of them.
209 let strukt = make::struct_(enum_vis, variant_name, enum_.generic_param_list(), field_list)
212 // FIXME: Consider making this an actual function somewhere (like in `AttrsOwnerEdit`) after some deliberation
213 let attrs_and_docs = |node: &SyntaxNode| {
214 let mut select_next_ws = false;
215 node.children_with_tokens().filter(move |child| {
216 let accept = match child.kind() {
218 select_next_ws = true;
221 WHITESPACE if select_next_ws => true,
224 select_next_ws = false;
230 // copy attributes & comments from variant
231 let variant_attrs = attrs_and_docs(variant.syntax())
232 .map(|tok| match tok.kind() {
233 WHITESPACE => make::tokens::single_newline().into(),
237 ted::insert_all(Position::first_child_of(strukt.syntax()), variant_attrs);
239 // copy attributes from enum
241 Position::first_child_of(strukt.syntax()),
242 enum_.attrs().map(|it| it.syntax().clone_for_update().into()).collect(),
247 fn update_variant(variant: &ast::Variant, generic: Option<ast::GenericParamList>) -> Option<()> {
248 let name = variant.name()?;
249 let ty = match generic {
250 // FIXME: This uses all the generic params of the enum, but the variant might not use all of them.
252 let gpl = gpl.clone_for_update();
253 gpl.generic_params().for_each(|gp| {
255 ast::GenericParam::LifetimeParam(it) => it.type_bound_list(),
256 ast::GenericParam::TypeParam(it) => it.type_bound_list(),
257 ast::GenericParam::ConstParam(_) => return,
259 if let Some(tbl) = tbl {
263 make::ty(&format!("{}<{}>", name.text(), gpl.generic_params().join(", ")))
265 None => make::ty(&name.text()),
267 let tuple_field = make::tuple_field(None, ty);
268 let replacement = make::variant(
270 Some(ast::FieldList::TupleFieldList(make::tuple_field_list(iter::once(tuple_field)))),
273 ted::replace(variant.syntax(), replacement.syntax());
278 insert_use_cfg: InsertUseConfig,
279 segment: ast::PathSegment,
281 import: Option<(ImportScope, hir::ModPath)>,
283 if let Some((scope, path)) = import {
284 insert_use(&scope, mod_path_to_ast(&path), &insert_use_cfg);
286 // deep clone to prevent cycle
287 let path = make::path_from_segments(iter::once(segment.clone_subtree()), false);
288 ted::insert_raw(ted::Position::before(segment.syntax()), path.clone_for_update().syntax());
289 ted::insert_raw(ted::Position::before(segment.syntax()), make::token(T!['(']));
290 ted::insert_raw(ted::Position::after(&node), make::token(T![')']));
293 fn process_references(
295 builder: &mut AssistBuilder,
296 visited_modules: &mut FxHashSet<Module>,
297 enum_module_def: &ModuleDef,
298 variant_hir_name: &Name,
299 refs: Vec<FileReference>,
300 ) -> Vec<(ast::PathSegment, SyntaxNode, Option<(ImportScope, hir::ModPath)>)> {
301 // we have to recollect here eagerly as we are about to edit the tree we need to calculate the changes
302 // and corresponding nodes up front
304 .flat_map(|reference| {
305 let (segment, scope_node, module) = reference_to_node(&ctx.sema, reference)?;
306 let segment = builder.make_mut(segment);
307 let scope_node = builder.make_syntax_mut(scope_node);
308 if !visited_modules.contains(&module) {
309 let mod_path = module.find_use_path_prefixed(
312 ctx.config.insert_use.prefix_kind,
314 if let Some(mut mod_path) = mod_path {
315 mod_path.pop_segment();
316 mod_path.push_segment(variant_hir_name.clone());
317 let scope = ImportScope::find_insert_use_container(&scope_node)?;
318 visited_modules.insert(module);
319 return Some((segment, scope_node, Some((scope, mod_path))));
322 Some((segment, scope_node, None))
327 fn reference_to_node(
328 sema: &hir::Semantics<RootDatabase>,
329 reference: FileReference,
330 ) -> Option<(ast::PathSegment, SyntaxNode, hir::Module)> {
332 reference.name.as_name_ref()?.syntax().parent().and_then(ast::PathSegment::cast)?;
333 let parent = segment.parent_path().syntax().parent()?;
334 let expr_or_pat = match_ast! {
336 ast::PathExpr(_it) => parent.parent()?,
337 ast::RecordExpr(_it) => parent,
338 ast::TupleStructPat(_it) => parent,
339 ast::RecordPat(_it) => parent,
343 let module = sema.scope(&expr_or_pat).module()?;
344 Some((segment, expr_or_pat, module))
349 use crate::tests::{check_assist, check_assist_not_applicable};
354 fn test_extract_struct_several_fields_tuple() {
356 extract_struct_from_enum_variant,
357 "enum A { $0One(u32, u32) }",
358 r#"struct One(u32, u32);
360 enum A { One(One) }"#,
365 fn test_extract_struct_several_fields_named() {
367 extract_struct_from_enum_variant,
368 "enum A { $0One { foo: u32, bar: u32 } }",
369 r#"struct One{ foo: u32, bar: u32 }
371 enum A { One(One) }"#,
376 fn test_extract_struct_one_field_named() {
378 extract_struct_from_enum_variant,
379 "enum A { $0One { foo: u32 } }",
380 r#"struct One{ foo: u32 }
382 enum A { One(One) }"#,
387 fn test_extract_struct_carries_over_generics() {
389 extract_struct_from_enum_variant,
390 r"enum En<T> { Var { a: T$0 } }",
391 r#"struct Var<T>{ a: T }
393 enum En<T> { Var(Var<T>) }"#,
398 fn test_extract_struct_carries_over_attributes() {
400 extract_struct_from_enum_variant,
403 enum Enum { Variant{ field: u32$0 } }"#,
404 r#"#[derive(Debug)]#[derive(Clone)] struct Variant{ field: u32 }
408 enum Enum { Variant(Variant) }"#,
413 fn test_extract_struct_indent_to_parent_enum() {
415 extract_struct_from_enum_variant,
434 fn test_extract_struct_indent_to_parent_enum_in_mod() {
436 extract_struct_from_enum_variant,
459 fn test_extract_struct_keep_comments_and_attrs_one_field_named() {
461 extract_struct_from_enum_variant,
488 fn test_extract_struct_keep_comments_and_attrs_several_fields_named() {
490 extract_struct_from_enum_variant,
523 fn test_extract_struct_keep_comments_and_attrs_several_fields_tuple() {
525 extract_struct_from_enum_variant,
526 "enum A { $0One(/* comment */ #[attr] u32, /* another */ u32 /* tail */) }",
528 struct One(/* comment */ #[attr] u32, /* another */ u32 /* tail */);
530 enum A { One(One) }"#,
535 fn test_extract_struct_keep_comments_and_attrs_on_variant_struct() {
537 extract_struct_from_enum_variant,
564 fn test_extract_struct_keep_comments_and_attrs_on_variant_tuple() {
566 extract_struct_from_enum_variant,
580 struct One(u32, u32);
589 fn test_extract_struct_keep_existing_visibility_named() {
591 extract_struct_from_enum_variant,
592 "enum A { $0One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 } }",
594 struct One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 }
596 enum A { One(One) }"#,
601 fn test_extract_struct_keep_existing_visibility_tuple() {
603 extract_struct_from_enum_variant,
604 "enum A { $0One(u32, pub(crate) u32, pub(super) u32, u32) }",
606 struct One(u32, pub(crate) u32, pub(super) u32, u32);
608 enum A { One(One) }"#,
613 fn test_extract_enum_variant_name_value_namespace() {
615 extract_struct_from_enum_variant,
616 r#"const One: () = ();
617 enum A { $0One(u32, u32) }"#,
618 r#"const One: () = ();
619 struct One(u32, u32);
621 enum A { One(One) }"#,
626 fn test_extract_struct_no_visibility() {
628 extract_struct_from_enum_variant,
629 "enum A { $0One(u32, u32) }",
631 struct One(u32, u32);
633 enum A { One(One) }"#,
638 fn test_extract_struct_pub_visibility() {
640 extract_struct_from_enum_variant,
641 "pub enum A { $0One(u32, u32) }",
643 pub struct One(pub u32, pub u32);
645 pub enum A { One(One) }"#,
650 fn test_extract_struct_pub_in_mod_visibility() {
652 extract_struct_from_enum_variant,
653 "pub(in something) enum A { $0One{ a: u32, b: u32 } }",
655 pub(in something) struct One{ pub(in something) a: u32, pub(in something) b: u32 }
657 pub(in something) enum A { One(One) }"#,
662 fn test_extract_struct_pub_crate_visibility() {
664 extract_struct_from_enum_variant,
665 "pub(crate) enum A { $0One{ a: u32, b: u32, c: u32 } }",
667 pub(crate) struct One{ pub(crate) a: u32, pub(crate) b: u32, pub(crate) c: u32 }
669 pub(crate) enum A { One(One) }"#,
674 fn test_extract_struct_with_complex_imports() {
676 extract_struct_from_enum_variant,
679 let m = my_other_mod::MyEnum::MyField(1, 1);
682 pub mod my_other_mod {
684 let m = MyEnum::MyField(1, 1);
694 let m = my_mod::my_other_mod::MyEnum::MyField(1, 1);
696 r#"use my_mod::my_other_mod::MyField;
699 use self::my_other_mod::MyField;
702 let m = my_other_mod::MyEnum::MyField(MyField(1, 1));
705 pub mod my_other_mod {
707 let m = MyEnum::MyField(MyField(1, 1));
710 pub struct MyField(pub u8, pub u8);
719 let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1));
725 fn extract_record_fix_references() {
727 extract_struct_from_enum_variant,
730 $0V { i: i32, j: i32 }
734 let E::V { i, j } = E::V { i: 9, j: 2 };
738 struct V{ i: i32, j: i32 }
745 let E::V(V { i, j }) = E::V(V { i: 9, j: 2 });
752 fn extract_record_fix_references2() {
754 extract_struct_from_enum_variant,
761 let E::V(i, j) = E::V(9, 2);
772 let E::V(V(i, j)) = E::V(V(9, 2));
779 fn test_several_files() {
781 extract_struct_from_enum_variant,
807 let e = E::V(V(9, 2));
814 fn test_several_files_record() {
816 extract_struct_from_enum_variant,
820 $0V { i: i32, j: i32 }
827 let e = E::V { i: 9, j: 2 };
832 struct V{ i: i32, j: i32 }
842 let e = E::V(V { i: 9, j: 2 });
849 fn test_extract_struct_record_nested_call_exp() {
851 extract_struct_from_enum_variant,
853 enum A { $0One { a: u32, b: u32 } }
858 let _ = B(A::One { a: 1, b: 2 });
862 struct One{ a: u32, b: u32 }
869 let _ = B(A::One(One { a: 1, b: 2 }));
876 fn test_extract_enum_not_applicable_for_element_with_no_fields() {
877 check_assist_not_applicable(extract_struct_from_enum_variant, r#"enum A { $0One }"#);
881 fn test_extract_enum_not_applicable_if_struct_exists() {
882 cov_mark::check!(test_extract_enum_not_applicable_if_struct_exists);
883 check_assist_not_applicable(
884 extract_struct_from_enum_variant,
887 enum A { $0One(u8, u32) }
893 fn test_extract_not_applicable_one_field() {
894 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0One(u32) }");
898 fn test_extract_not_applicable_no_field_tuple() {
899 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None() }");
903 fn test_extract_not_applicable_no_field_named() {
904 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None {} }");