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);
66 let usages = Definition::Variant(variant_hir).usages(&ctx.sema).all();
68 let mut visited_modules_set = FxHashSet::default();
69 let current_module = enum_hir.module(ctx.db());
70 visited_modules_set.insert(current_module);
71 // record file references of the file the def resides in, we only want to swap to the edited file in the builder once
72 let mut def_file_references = None;
73 for (file_id, references) in usages {
74 if file_id == ctx.file_id() {
75 def_file_references = Some(references);
78 builder.edit_file(file_id);
79 let processed = process_references(
82 &mut visited_modules_set,
87 processed.into_iter().for_each(|(path, node, import)| {
88 apply_references(ctx.config.insert_use, path, node, import)
91 builder.edit_file(ctx.file_id());
93 let variant = builder.make_mut(variant.clone());
94 if let Some(references) = def_file_references {
95 let processed = process_references(
98 &mut visited_modules_set,
103 processed.into_iter().for_each(|(path, node, import)| {
104 apply_references(ctx.config.insert_use, path, node, import)
108 let indent = enum_ast.indent_level();
109 let def = create_struct_def(variant_name.clone(), &variant, &field_list, &enum_ast);
110 def.reindent_to(indent);
112 let start_offset = &variant.parent_enum().syntax().clone();
114 ted::Position::before(start_offset),
116 def.syntax().clone().into(),
117 make::tokens::whitespace(&format!("\n\n{}", indent)).into(),
121 update_variant(&variant, enum_ast.generic_param_list());
126 fn extract_field_list_if_applicable(
127 variant: &ast::Variant,
128 ) -> Option<Either<ast::RecordFieldList, ast::TupleFieldList>> {
129 match variant.kind() {
130 ast::StructKind::Record(field_list) if field_list.fields().next().is_some() => {
131 Some(Either::Left(field_list))
133 ast::StructKind::Tuple(field_list) if field_list.fields().count() > 1 => {
134 Some(Either::Right(field_list))
140 fn existing_definition(db: &RootDatabase, variant_name: &ast::Name, variant: &Variant) -> bool {
146 .filter(|(_, def)| match def {
147 // only check type-namespace
148 hir::ScopeDef::ModuleDef(def) => matches!(
152 | ModuleDef::Variant(_)
153 | ModuleDef::Trait(_)
154 | ModuleDef::TypeAlias(_)
155 | ModuleDef::BuiltinType(_)
159 .any(|(name, _)| name.to_string() == variant_name.to_string())
162 fn create_struct_def(
163 variant_name: ast::Name,
164 variant: &ast::Variant,
165 field_list: &Either<ast::RecordFieldList, ast::TupleFieldList>,
168 let enum_vis = enum_.visibility();
170 let insert_vis = |node: &'_ SyntaxNode, vis: &'_ SyntaxNode| {
171 let vis = vis.clone_for_update();
172 ted::insert(ted::Position::before(node), vis);
175 // for fields without any existing visibility, use visibility of enum
176 let field_list: ast::FieldList = match field_list {
177 Either::Left(field_list) => {
178 let field_list = field_list.clone_for_update();
180 if let Some(vis) = &enum_vis {
183 .filter(|field| field.visibility().is_none())
184 .filter_map(|field| field.name())
185 .for_each(|it| insert_vis(it.syntax(), vis.syntax()));
190 Either::Right(field_list) => {
191 let field_list = field_list.clone_for_update();
193 if let Some(vis) = &enum_vis {
196 .filter(|field| field.visibility().is_none())
197 .filter_map(|field| field.ty())
198 .for_each(|it| insert_vis(it.syntax(), vis.syntax()));
205 field_list.reindent_to(IndentLevel::single());
207 // FIXME: This uses all the generic params of the enum, but the variant might not use all of them.
208 let strukt = make::struct_(enum_vis, variant_name, enum_.generic_param_list(), field_list)
211 // FIXME: Consider making this an actual function somewhere (like in `AttrsOwnerEdit`) after some deliberation
212 let attrs_and_docs = |node: &SyntaxNode| {
213 let mut select_next_ws = false;
214 node.children_with_tokens().filter(move |child| {
215 let accept = match child.kind() {
217 select_next_ws = true;
220 WHITESPACE if select_next_ws => true,
223 select_next_ws = false;
229 // copy attributes & comments from variant
230 let variant_attrs = attrs_and_docs(variant.syntax())
231 .map(|tok| match tok.kind() {
232 WHITESPACE => make::tokens::single_newline().into(),
236 ted::insert_all(Position::first_child_of(strukt.syntax()), variant_attrs);
238 // copy attributes from enum
240 Position::first_child_of(strukt.syntax()),
241 enum_.attrs().map(|it| it.syntax().clone_for_update().into()).collect(),
246 fn update_variant(variant: &ast::Variant, generic: Option<ast::GenericParamList>) -> Option<()> {
247 let name = variant.name()?;
248 let ty = match generic {
249 // FIXME: This uses all the generic params of the enum, but the variant might not use all of them.
251 let gpl = gpl.clone_for_update();
252 gpl.generic_params().for_each(|gp| {
254 ast::GenericParam::LifetimeParam(it) => it.type_bound_list(),
255 ast::GenericParam::TypeParam(it) => it.type_bound_list(),
256 ast::GenericParam::ConstParam(_) => return,
258 if let Some(tbl) = tbl {
262 make::ty(&format!("{}<{}>", name.text(), gpl.generic_params().join(", ")))
264 None => make::ty(&name.text()),
266 let tuple_field = make::tuple_field(None, ty);
267 let replacement = make::variant(
269 Some(ast::FieldList::TupleFieldList(make::tuple_field_list(iter::once(tuple_field)))),
272 ted::replace(variant.syntax(), replacement.syntax());
277 insert_use_cfg: InsertUseConfig,
278 segment: ast::PathSegment,
280 import: Option<(ImportScope, hir::ModPath)>,
282 if let Some((scope, path)) = import {
283 insert_use(&scope, mod_path_to_ast(&path), &insert_use_cfg);
285 // deep clone to prevent cycle
286 let path = make::path_from_segments(iter::once(segment.clone_subtree()), false);
287 ted::insert_raw(ted::Position::before(segment.syntax()), path.clone_for_update().syntax());
288 ted::insert_raw(ted::Position::before(segment.syntax()), make::token(T!['(']));
289 ted::insert_raw(ted::Position::after(&node), make::token(T![')']));
292 fn process_references(
294 builder: &mut AssistBuilder,
295 visited_modules: &mut FxHashSet<Module>,
296 enum_module_def: &ModuleDef,
297 variant_hir_name: &Name,
298 refs: Vec<FileReference>,
299 ) -> Vec<(ast::PathSegment, SyntaxNode, Option<(ImportScope, hir::ModPath)>)> {
300 // we have to recollect here eagerly as we are about to edit the tree we need to calculate the changes
301 // and corresponding nodes up front
303 .flat_map(|reference| {
304 let (segment, scope_node, module) = reference_to_node(&ctx.sema, reference)?;
305 let segment = builder.make_mut(segment);
306 let scope_node = builder.make_syntax_mut(scope_node);
307 if !visited_modules.contains(&module) {
308 let mod_path = module.find_use_path_prefixed(
311 ctx.config.insert_use.prefix_kind,
313 if let Some(mut mod_path) = mod_path {
314 mod_path.pop_segment();
315 mod_path.push_segment(variant_hir_name.clone());
316 let scope = ImportScope::find_insert_use_container(&scope_node, &ctx.sema)?;
317 visited_modules.insert(module);
318 return Some((segment, scope_node, Some((scope, mod_path))));
321 Some((segment, scope_node, None))
326 fn reference_to_node(
327 sema: &hir::Semantics<RootDatabase>,
328 reference: FileReference,
329 ) -> Option<(ast::PathSegment, SyntaxNode, hir::Module)> {
331 reference.name.as_name_ref()?.syntax().parent().and_then(ast::PathSegment::cast)?;
332 let parent = segment.parent_path().syntax().parent()?;
333 let expr_or_pat = match_ast! {
335 ast::PathExpr(_it) => parent.parent()?,
336 ast::RecordExpr(_it) => parent,
337 ast::TupleStructPat(_it) => parent,
338 ast::RecordPat(_it) => parent,
342 let module = sema.scope(&expr_or_pat).module()?;
343 Some((segment, expr_or_pat, module))
348 use crate::tests::{check_assist, check_assist_not_applicable};
353 fn test_extract_struct_several_fields_tuple() {
355 extract_struct_from_enum_variant,
356 "enum A { $0One(u32, u32) }",
357 r#"struct One(u32, u32);
359 enum A { One(One) }"#,
364 fn test_extract_struct_several_fields_named() {
366 extract_struct_from_enum_variant,
367 "enum A { $0One { foo: u32, bar: u32 } }",
368 r#"struct One{ foo: u32, bar: u32 }
370 enum A { One(One) }"#,
375 fn test_extract_struct_one_field_named() {
377 extract_struct_from_enum_variant,
378 "enum A { $0One { foo: u32 } }",
379 r#"struct One{ foo: u32 }
381 enum A { One(One) }"#,
386 fn test_extract_struct_carries_over_generics() {
388 extract_struct_from_enum_variant,
389 r"enum En<T> { Var { a: T$0 } }",
390 r#"struct Var<T>{ a: T }
392 enum En<T> { Var(Var<T>) }"#,
397 fn test_extract_struct_carries_over_attributes() {
399 extract_struct_from_enum_variant,
402 enum Enum { Variant{ field: u32$0 } }"#,
403 r#"#[derive(Debug)]#[derive(Clone)] struct Variant{ field: u32 }
407 enum Enum { Variant(Variant) }"#,
412 fn test_extract_struct_indent_to_parent_enum() {
414 extract_struct_from_enum_variant,
433 fn test_extract_struct_indent_to_parent_enum_in_mod() {
435 extract_struct_from_enum_variant,
458 fn test_extract_struct_keep_comments_and_attrs_one_field_named() {
460 extract_struct_from_enum_variant,
487 fn test_extract_struct_keep_comments_and_attrs_several_fields_named() {
489 extract_struct_from_enum_variant,
522 fn test_extract_struct_keep_comments_and_attrs_several_fields_tuple() {
524 extract_struct_from_enum_variant,
525 "enum A { $0One(/* comment */ #[attr] u32, /* another */ u32 /* tail */) }",
527 struct One(/* comment */ #[attr] u32, /* another */ u32 /* tail */);
529 enum A { One(One) }"#,
534 fn test_extract_struct_keep_comments_and_attrs_on_variant_struct() {
536 extract_struct_from_enum_variant,
563 fn test_extract_struct_keep_comments_and_attrs_on_variant_tuple() {
565 extract_struct_from_enum_variant,
579 struct One(u32, u32);
588 fn test_extract_struct_keep_existing_visibility_named() {
590 extract_struct_from_enum_variant,
591 "enum A { $0One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 } }",
593 struct One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 }
595 enum A { One(One) }"#,
600 fn test_extract_struct_keep_existing_visibility_tuple() {
602 extract_struct_from_enum_variant,
603 "enum A { $0One(u32, pub(crate) u32, pub(super) u32, u32) }",
605 struct One(u32, pub(crate) u32, pub(super) u32, u32);
607 enum A { One(One) }"#,
612 fn test_extract_enum_variant_name_value_namespace() {
614 extract_struct_from_enum_variant,
615 r#"const One: () = ();
616 enum A { $0One(u32, u32) }"#,
617 r#"const One: () = ();
618 struct One(u32, u32);
620 enum A { One(One) }"#,
625 fn test_extract_struct_no_visibility() {
627 extract_struct_from_enum_variant,
628 "enum A { $0One(u32, u32) }",
630 struct One(u32, u32);
632 enum A { One(One) }"#,
637 fn test_extract_struct_pub_visibility() {
639 extract_struct_from_enum_variant,
640 "pub enum A { $0One(u32, u32) }",
642 pub struct One(pub u32, pub u32);
644 pub enum A { One(One) }"#,
649 fn test_extract_struct_pub_in_mod_visibility() {
651 extract_struct_from_enum_variant,
652 "pub(in something) enum A { $0One{ a: u32, b: u32 } }",
654 pub(in something) struct One{ pub(in something) a: u32, pub(in something) b: u32 }
656 pub(in something) enum A { One(One) }"#,
661 fn test_extract_struct_pub_crate_visibility() {
663 extract_struct_from_enum_variant,
664 "pub(crate) enum A { $0One{ a: u32, b: u32, c: u32 } }",
666 pub(crate) struct One{ pub(crate) a: u32, pub(crate) b: u32, pub(crate) c: u32 }
668 pub(crate) enum A { One(One) }"#,
673 fn test_extract_struct_with_complex_imports() {
675 extract_struct_from_enum_variant,
678 let m = my_other_mod::MyEnum::MyField(1, 1);
681 pub mod my_other_mod {
683 let m = MyEnum::MyField(1, 1);
693 let m = my_mod::my_other_mod::MyEnum::MyField(1, 1);
695 r#"use my_mod::my_other_mod::MyField;
698 use self::my_other_mod::MyField;
701 let m = my_other_mod::MyEnum::MyField(MyField(1, 1));
704 pub mod my_other_mod {
706 let m = MyEnum::MyField(MyField(1, 1));
709 pub struct MyField(pub u8, pub u8);
718 let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1));
724 fn extract_record_fix_references() {
726 extract_struct_from_enum_variant,
729 $0V { i: i32, j: i32 }
733 let E::V { i, j } = E::V { i: 9, j: 2 };
737 struct V{ i: i32, j: i32 }
744 let E::V(V { i, j }) = E::V(V { i: 9, j: 2 });
751 fn extract_record_fix_references2() {
753 extract_struct_from_enum_variant,
760 let E::V(i, j) = E::V(9, 2);
771 let E::V(V(i, j)) = E::V(V(9, 2));
778 fn test_several_files() {
780 extract_struct_from_enum_variant,
806 let e = E::V(V(9, 2));
813 fn test_several_files_record() {
815 extract_struct_from_enum_variant,
819 $0V { i: i32, j: i32 }
826 let e = E::V { i: 9, j: 2 };
831 struct V{ i: i32, j: i32 }
841 let e = E::V(V { i: 9, j: 2 });
848 fn test_extract_struct_record_nested_call_exp() {
850 extract_struct_from_enum_variant,
852 enum A { $0One { a: u32, b: u32 } }
857 let _ = B(A::One { a: 1, b: 2 });
861 struct One{ a: u32, b: u32 }
868 let _ = B(A::One(One { a: 1, b: 2 }));
875 fn test_extract_enum_not_applicable_for_element_with_no_fields() {
876 check_assist_not_applicable(extract_struct_from_enum_variant, r#"enum A { $0One }"#);
880 fn test_extract_enum_not_applicable_if_struct_exists() {
881 cov_mark::check!(test_extract_enum_not_applicable_if_struct_exists);
882 check_assist_not_applicable(
883 extract_struct_from_enum_variant,
886 enum A { $0One(u8, u32) }
892 fn test_extract_not_applicable_one_field() {
893 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0One(u32) }");
897 fn test_extract_not_applicable_no_field_tuple() {
898 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None() }");
902 fn test_extract_not_applicable_no_field_named() {
903 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None {} }");