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, AttrsOwner,
19 GenericParamsOwner, NameOwner, TypeBoundsOwner, VisibilityOwner,
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 .map(|it| it.remove());
261 make::ty(&format!("{}<{}>", name.text(), gpl.generic_params().join(", ")))
263 None => make::ty(&name.text()),
265 let tuple_field = make::tuple_field(None, ty);
266 let replacement = make::variant(
268 Some(ast::FieldList::TupleFieldList(make::tuple_field_list(iter::once(tuple_field)))),
271 ted::replace(variant.syntax(), replacement.syntax());
276 insert_use_cfg: InsertUseConfig,
277 segment: ast::PathSegment,
279 import: Option<(ImportScope, hir::ModPath)>,
281 if let Some((scope, path)) = import {
282 insert_use(&scope, mod_path_to_ast(&path), &insert_use_cfg);
284 // deep clone to prevent cycle
285 let path = make::path_from_segments(iter::once(segment.clone_subtree()), false);
286 ted::insert_raw(ted::Position::before(segment.syntax()), path.clone_for_update().syntax());
287 ted::insert_raw(ted::Position::before(segment.syntax()), make::token(T!['(']));
288 ted::insert_raw(ted::Position::after(&node), make::token(T![')']));
291 fn process_references(
293 builder: &mut AssistBuilder,
294 visited_modules: &mut FxHashSet<Module>,
295 enum_module_def: &ModuleDef,
296 variant_hir_name: &Name,
297 refs: Vec<FileReference>,
298 ) -> Vec<(ast::PathSegment, SyntaxNode, Option<(ImportScope, hir::ModPath)>)> {
299 // we have to recollect here eagerly as we are about to edit the tree we need to calculate the changes
300 // and corresponding nodes up front
302 .flat_map(|reference| {
303 let (segment, scope_node, module) = reference_to_node(&ctx.sema, reference)?;
304 let segment = builder.make_mut(segment);
305 let scope_node = builder.make_syntax_mut(scope_node);
306 if !visited_modules.contains(&module) {
307 let mod_path = module.find_use_path_prefixed(
310 ctx.config.insert_use.prefix_kind,
312 if let Some(mut mod_path) = mod_path {
313 mod_path.pop_segment();
314 mod_path.push_segment(variant_hir_name.clone());
315 let scope = ImportScope::find_insert_use_container(&scope_node)?;
316 visited_modules.insert(module);
317 return Some((segment, scope_node, Some((scope, mod_path))));
320 Some((segment, scope_node, None))
325 fn reference_to_node(
326 sema: &hir::Semantics<RootDatabase>,
327 reference: FileReference,
328 ) -> Option<(ast::PathSegment, SyntaxNode, hir::Module)> {
330 reference.name.as_name_ref()?.syntax().parent().and_then(ast::PathSegment::cast)?;
331 let parent = segment.parent_path().syntax().parent()?;
332 let expr_or_pat = match_ast! {
334 ast::PathExpr(_it) => parent.parent()?,
335 ast::RecordExpr(_it) => parent,
336 ast::TupleStructPat(_it) => parent,
337 ast::RecordPat(_it) => parent,
341 let module = sema.scope(&expr_or_pat).module()?;
342 Some((segment, expr_or_pat, module))
347 use crate::tests::{check_assist, check_assist_not_applicable};
352 fn test_extract_struct_several_fields_tuple() {
354 extract_struct_from_enum_variant,
355 "enum A { $0One(u32, u32) }",
356 r#"struct One(u32, u32);
358 enum A { One(One) }"#,
363 fn test_extract_struct_several_fields_named() {
365 extract_struct_from_enum_variant,
366 "enum A { $0One { foo: u32, bar: u32 } }",
367 r#"struct One{ foo: u32, bar: u32 }
369 enum A { One(One) }"#,
374 fn test_extract_struct_one_field_named() {
376 extract_struct_from_enum_variant,
377 "enum A { $0One { foo: u32 } }",
378 r#"struct One{ foo: u32 }
380 enum A { One(One) }"#,
385 fn test_extract_struct_carries_over_generics() {
387 extract_struct_from_enum_variant,
388 r"enum En<T> { Var { a: T$0 } }",
389 r#"struct Var<T>{ a: T }
391 enum En<T> { Var(Var<T>) }"#,
396 fn test_extract_struct_carries_over_attributes() {
398 extract_struct_from_enum_variant,
401 enum Enum { Variant{ field: u32$0 } }"#,
402 r#"#[derive(Debug)]#[derive(Clone)] struct Variant{ field: u32 }
406 enum Enum { Variant(Variant) }"#,
411 fn test_extract_struct_indent_to_parent_enum() {
413 extract_struct_from_enum_variant,
432 fn test_extract_struct_indent_to_parent_enum_in_mod() {
434 extract_struct_from_enum_variant,
457 fn test_extract_struct_keep_comments_and_attrs_one_field_named() {
459 extract_struct_from_enum_variant,
486 fn test_extract_struct_keep_comments_and_attrs_several_fields_named() {
488 extract_struct_from_enum_variant,
521 fn test_extract_struct_keep_comments_and_attrs_several_fields_tuple() {
523 extract_struct_from_enum_variant,
524 "enum A { $0One(/* comment */ #[attr] u32, /* another */ u32 /* tail */) }",
526 struct One(/* comment */ #[attr] u32, /* another */ u32 /* tail */);
528 enum A { One(One) }"#,
533 fn test_extract_struct_keep_comments_and_attrs_on_variant_struct() {
535 extract_struct_from_enum_variant,
562 fn test_extract_struct_keep_comments_and_attrs_on_variant_tuple() {
564 extract_struct_from_enum_variant,
578 struct One(u32, u32);
587 fn test_extract_struct_keep_existing_visibility_named() {
589 extract_struct_from_enum_variant,
590 "enum A { $0One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 } }",
592 struct One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 }
594 enum A { One(One) }"#,
599 fn test_extract_struct_keep_existing_visibility_tuple() {
601 extract_struct_from_enum_variant,
602 "enum A { $0One(u32, pub(crate) u32, pub(super) u32, u32) }",
604 struct One(u32, pub(crate) u32, pub(super) u32, u32);
606 enum A { One(One) }"#,
611 fn test_extract_enum_variant_name_value_namespace() {
613 extract_struct_from_enum_variant,
614 r#"const One: () = ();
615 enum A { $0One(u32, u32) }"#,
616 r#"const One: () = ();
617 struct One(u32, u32);
619 enum A { One(One) }"#,
624 fn test_extract_struct_no_visibility() {
626 extract_struct_from_enum_variant,
627 "enum A { $0One(u32, u32) }",
629 struct One(u32, u32);
631 enum A { One(One) }"#,
636 fn test_extract_struct_pub_visibility() {
638 extract_struct_from_enum_variant,
639 "pub enum A { $0One(u32, u32) }",
641 pub struct One(pub u32, pub u32);
643 pub enum A { One(One) }"#,
648 fn test_extract_struct_pub_in_mod_visibility() {
650 extract_struct_from_enum_variant,
651 "pub(in something) enum A { $0One{ a: u32, b: u32 } }",
653 pub(in something) struct One{ pub(in something) a: u32, pub(in something) b: u32 }
655 pub(in something) enum A { One(One) }"#,
660 fn test_extract_struct_pub_crate_visibility() {
662 extract_struct_from_enum_variant,
663 "pub(crate) enum A { $0One{ a: u32, b: u32, c: u32 } }",
665 pub(crate) struct One{ pub(crate) a: u32, pub(crate) b: u32, pub(crate) c: u32 }
667 pub(crate) enum A { One(One) }"#,
672 fn test_extract_struct_with_complex_imports() {
674 extract_struct_from_enum_variant,
677 let m = my_other_mod::MyEnum::MyField(1, 1);
680 pub mod my_other_mod {
682 let m = MyEnum::MyField(1, 1);
692 let m = my_mod::my_other_mod::MyEnum::MyField(1, 1);
694 r#"use my_mod::my_other_mod::MyField;
697 use self::my_other_mod::MyField;
700 let m = my_other_mod::MyEnum::MyField(MyField(1, 1));
703 pub mod my_other_mod {
705 let m = MyEnum::MyField(MyField(1, 1));
708 pub struct MyField(pub u8, pub u8);
717 let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1));
723 fn extract_record_fix_references() {
725 extract_struct_from_enum_variant,
728 $0V { i: i32, j: i32 }
732 let E::V { i, j } = E::V { i: 9, j: 2 };
736 struct V{ i: i32, j: i32 }
743 let E::V(V { i, j }) = E::V(V { i: 9, j: 2 });
750 fn extract_record_fix_references2() {
752 extract_struct_from_enum_variant,
759 let E::V(i, j) = E::V(9, 2);
770 let E::V(V(i, j)) = E::V(V(9, 2));
777 fn test_several_files() {
779 extract_struct_from_enum_variant,
805 let e = E::V(V(9, 2));
812 fn test_several_files_record() {
814 extract_struct_from_enum_variant,
818 $0V { i: i32, j: i32 }
825 let e = E::V { i: 9, j: 2 };
830 struct V{ i: i32, j: i32 }
840 let e = E::V(V { i: 9, j: 2 });
847 fn test_extract_struct_record_nested_call_exp() {
849 extract_struct_from_enum_variant,
851 enum A { $0One { a: u32, b: u32 } }
856 let _ = B(A::One { a: 1, b: 2 });
860 struct One{ a: u32, b: u32 }
867 let _ = B(A::One(One { a: 1, b: 2 }));
874 fn test_extract_enum_not_applicable_for_element_with_no_fields() {
875 check_assist_not_applicable(extract_struct_from_enum_variant, r#"enum A { $0One }"#);
879 fn test_extract_enum_not_applicable_if_struct_exists() {
880 cov_mark::check!(test_extract_enum_not_applicable_if_struct_exists);
881 check_assist_not_applicable(
882 extract_struct_from_enum_variant,
885 enum A { $0One(u8, u32) }
891 fn test_extract_not_applicable_one_field() {
892 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0One(u32) }");
896 fn test_extract_not_applicable_no_field_tuple() {
897 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None() }");
901 fn test_extract_not_applicable_no_field_named() {
902 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None {} }");