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, make, AstNode, AttrsOwner, GenericParamsOwner, NameOwner, TypeBoundsOwner,
22 ted::{self, Position},
26 use crate::{assist_context::AssistBuilder, AssistContext, AssistId, AssistKind, Assists};
28 // Assist: extract_struct_from_enum_variant
30 // Extracts a struct from enum variant.
33 // enum A { $0One(u32, u32) }
37 // struct One(pub u32, pub u32);
39 // enum A { One(One) }
41 pub(crate) fn extract_struct_from_enum_variant(
45 let variant = ctx.find_node_at_offset::<ast::Variant>()?;
46 let field_list = extract_field_list_if_applicable(&variant)?;
48 let variant_name = variant.name()?;
49 let variant_hir = ctx.sema.to_def(&variant)?;
50 if existing_definition(ctx.db(), &variant_name, &variant_hir) {
54 let enum_ast = variant.parent_enum();
55 let enum_hir = ctx.sema.to_def(&enum_ast)?;
56 let target = variant.syntax().text_range();
58 AssistId("extract_struct_from_enum_variant", AssistKind::RefactorRewrite),
59 "Extract struct from enum variant",
62 let variant_hir_name = variant_hir.name(ctx.db());
63 let enum_module_def = ModuleDef::from(enum_hir);
65 Definition::ModuleDef(ModuleDef::Variant(variant_hir)).usages(&ctx.sema).all();
67 let mut visited_modules_set = FxHashSet::default();
68 let current_module = enum_hir.module(ctx.db());
69 visited_modules_set.insert(current_module);
70 // record file references of the file the def resides in, we only want to swap to the edited file in the builder once
71 let mut def_file_references = None;
72 for (file_id, references) in usages {
73 if file_id == ctx.frange.file_id {
74 def_file_references = Some(references);
77 builder.edit_file(file_id);
78 let processed = process_references(
81 &mut visited_modules_set,
86 processed.into_iter().for_each(|(path, node, import)| {
87 apply_references(ctx.config.insert_use, path, node, import)
90 builder.edit_file(ctx.frange.file_id);
91 let variant = builder.make_mut(variant.clone());
92 if let Some(references) = def_file_references {
93 let processed = process_references(
96 &mut visited_modules_set,
101 processed.into_iter().for_each(|(path, node, import)| {
102 apply_references(ctx.config.insert_use, path, node, import)
106 let def = create_struct_def(variant_name.clone(), &field_list, &enum_ast);
107 let start_offset = &variant.parent_enum().syntax().clone();
108 ted::insert_raw(ted::Position::before(start_offset), def.syntax());
109 ted::insert_raw(ted::Position::before(start_offset), &make::tokens::blank_line());
111 update_variant(&variant, enum_ast.generic_param_list());
116 fn extract_field_list_if_applicable(
117 variant: &ast::Variant,
118 ) -> Option<Either<ast::RecordFieldList, ast::TupleFieldList>> {
119 match variant.kind() {
120 ast::StructKind::Record(field_list) if field_list.fields().next().is_some() => {
121 Some(Either::Left(field_list))
123 ast::StructKind::Tuple(field_list) if field_list.fields().count() > 1 => {
124 Some(Either::Right(field_list))
130 fn existing_definition(db: &RootDatabase, variant_name: &ast::Name, variant: &Variant) -> bool {
136 .filter(|(_, def)| match def {
137 // only check type-namespace
138 hir::ScopeDef::ModuleDef(def) => matches!(
142 | ModuleDef::Variant(_)
143 | ModuleDef::Trait(_)
144 | ModuleDef::TypeAlias(_)
145 | ModuleDef::BuiltinType(_)
149 .any(|(name, _)| name.to_string() == variant_name.to_string())
152 fn create_struct_def(
153 variant_name: ast::Name,
154 field_list: &Either<ast::RecordFieldList, ast::TupleFieldList>,
157 let pub_vis = make::visibility_pub();
159 let insert_pub = |node: &'_ SyntaxNode| {
160 let pub_vis = pub_vis.clone_for_update();
161 ted::insert(ted::Position::before(node), pub_vis.syntax());
164 // for fields without any existing visibility, use pub visibility
165 let field_list = match field_list {
166 Either::Left(field_list) => {
167 let field_list = field_list.clone_for_update();
171 .filter(|field| field.visibility().is_none())
172 .filter_map(|field| field.name())
173 .for_each(|it| insert_pub(it.syntax()));
177 Either::Right(field_list) => {
178 let field_list = field_list.clone_for_update();
182 .filter(|field| field.visibility().is_none())
183 .filter_map(|field| field.ty())
184 .for_each(|it| insert_pub(it.syntax()));
190 // FIXME: This uses all the generic params of the enum, but the variant might not use all of them.
192 make::struct_(enum_.visibility(), variant_name, enum_.generic_param_list(), field_list)
197 Position::first_child_of(strukt.syntax()),
198 enum_.attrs().map(|it| it.syntax().clone_for_update().into()).collect(),
203 fn update_variant(variant: &ast::Variant, generic: Option<ast::GenericParamList>) -> Option<()> {
204 let name = variant.name()?;
205 let ty = match generic {
206 // FIXME: This uses all the generic params of the enum, but the variant might not use all of them.
208 let gpl = gpl.clone_for_update();
209 gpl.generic_params().for_each(|gp| {
211 ast::GenericParam::LifetimeParam(it) => it.type_bound_list(),
212 ast::GenericParam::TypeParam(it) => it.type_bound_list(),
213 ast::GenericParam::ConstParam(_) => return,
215 .map(|it| it.remove());
217 make::ty(&format!("{}<{}>", name.text(), gpl.generic_params().join(", ")))
219 None => make::ty(&name.text()),
221 let tuple_field = make::tuple_field(None, ty);
222 let replacement = make::variant(
224 Some(ast::FieldList::TupleFieldList(make::tuple_field_list(iter::once(tuple_field)))),
227 ted::replace(variant.syntax(), replacement.syntax());
232 insert_use_cfg: InsertUseConfig,
233 segment: ast::PathSegment,
235 import: Option<(ImportScope, hir::ModPath)>,
237 if let Some((scope, path)) = import {
238 insert_use(&scope, mod_path_to_ast(&path), &insert_use_cfg);
240 // deep clone to prevent cycle
241 let path = make::path_from_segments(iter::once(segment.clone_subtree()), false);
242 ted::insert_raw(ted::Position::before(segment.syntax()), path.clone_for_update().syntax());
243 ted::insert_raw(ted::Position::before(segment.syntax()), make::token(T!['(']));
244 ted::insert_raw(ted::Position::after(&node), make::token(T![')']));
247 fn process_references(
249 builder: &mut AssistBuilder,
250 visited_modules: &mut FxHashSet<Module>,
251 enum_module_def: &ModuleDef,
252 variant_hir_name: &Name,
253 refs: Vec<FileReference>,
254 ) -> Vec<(ast::PathSegment, SyntaxNode, Option<(ImportScope, hir::ModPath)>)> {
255 // we have to recollect here eagerly as we are about to edit the tree we need to calculate the changes
256 // and corresponding nodes up front
258 .flat_map(|reference| {
259 let (segment, scope_node, module) = reference_to_node(&ctx.sema, reference)?;
260 let segment = builder.make_mut(segment);
261 let scope_node = builder.make_syntax_mut(scope_node);
262 if !visited_modules.contains(&module) {
263 let mod_path = module.find_use_path_prefixed(
266 ctx.config.insert_use.prefix_kind,
268 if let Some(mut mod_path) = mod_path {
269 mod_path.pop_segment();
270 mod_path.push_segment(variant_hir_name.clone());
271 let scope = ImportScope::find_insert_use_container(&scope_node)?;
272 visited_modules.insert(module);
273 return Some((segment, scope_node, Some((scope, mod_path))));
276 Some((segment, scope_node, None))
281 fn reference_to_node(
282 sema: &hir::Semantics<RootDatabase>,
283 reference: FileReference,
284 ) -> Option<(ast::PathSegment, SyntaxNode, hir::Module)> {
286 reference.name.as_name_ref()?.syntax().parent().and_then(ast::PathSegment::cast)?;
287 let parent = segment.parent_path().syntax().parent()?;
288 let expr_or_pat = match_ast! {
290 ast::PathExpr(_it) => parent.parent()?,
291 ast::RecordExpr(_it) => parent,
292 ast::TupleStructPat(_it) => parent,
293 ast::RecordPat(_it) => parent,
297 let module = sema.scope(&expr_or_pat).module()?;
298 Some((segment, expr_or_pat, module))
303 use ide_db::helpers::FamousDefs;
305 use crate::tests::{check_assist, check_assist_not_applicable};
309 fn check_not_applicable(ra_fixture: &str) {
311 format!("//- /main.rs crate:main deps:core\n{}\n{}", ra_fixture, FamousDefs::FIXTURE);
312 check_assist_not_applicable(extract_struct_from_enum_variant, &fixture)
316 fn test_extract_struct_several_fields_tuple() {
318 extract_struct_from_enum_variant,
319 "enum A { $0One(u32, u32) }",
320 r#"struct One(pub u32, pub u32);
322 enum A { One(One) }"#,
327 fn test_extract_struct_several_fields_named() {
329 extract_struct_from_enum_variant,
330 "enum A { $0One { foo: u32, bar: u32 } }",
331 r#"struct One{ pub foo: u32, pub bar: u32 }
333 enum A { One(One) }"#,
338 fn test_extract_struct_one_field_named() {
340 extract_struct_from_enum_variant,
341 "enum A { $0One { foo: u32 } }",
342 r#"struct One{ pub foo: u32 }
344 enum A { One(One) }"#,
349 fn test_extract_struct_carries_over_generics() {
351 extract_struct_from_enum_variant,
352 r"enum En<T> { Var { a: T$0 } }",
353 r#"struct Var<T>{ pub a: T }
355 enum En<T> { Var(Var<T>) }"#,
360 fn test_extract_struct_carries_over_attributes() {
362 extract_struct_from_enum_variant,
365 enum Enum { Variant{ field: u32$0 } }"#,
366 r#"#[derive(Debug)]#[derive(Clone)] struct Variant{ pub field: u32 }
370 enum Enum { Variant(Variant) }"#,
375 fn test_extract_struct_keep_comments_and_attrs_one_field_named() {
377 extract_struct_from_enum_variant,
404 fn test_extract_struct_keep_comments_and_attrs_several_fields_named() {
406 extract_struct_from_enum_variant,
439 fn test_extract_struct_keep_comments_and_attrs_several_fields_tuple() {
441 extract_struct_from_enum_variant,
442 "enum A { $0One(/* comment */ #[attr] u32, /* another */ u32 /* tail */) }",
444 struct One(/* comment */ #[attr] pub u32, /* another */ pub u32 /* tail */);
446 enum A { One(One) }"#,
451 fn test_extract_struct_keep_existing_visibility_named() {
453 extract_struct_from_enum_variant,
454 "enum A { $0One{ pub a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 } }",
456 struct One{ pub a: u32, pub(crate) b: u32, pub(super) c: u32, pub d: u32 }
458 enum A { One(One) }"#,
463 fn test_extract_struct_keep_existing_visibility_tuple() {
465 extract_struct_from_enum_variant,
466 "enum A { $0One(pub u32, pub(crate) u32, pub(super) u32, u32) }",
468 struct One(pub u32, pub(crate) u32, pub(super) u32, pub u32);
470 enum A { One(One) }"#,
475 fn test_extract_enum_variant_name_value_namespace() {
477 extract_struct_from_enum_variant,
478 r#"const One: () = ();
479 enum A { $0One(u32, u32) }"#,
480 r#"const One: () = ();
481 struct One(pub u32, pub u32);
483 enum A { One(One) }"#,
488 fn test_extract_struct_pub_visibility() {
490 extract_struct_from_enum_variant,
491 "pub enum A { $0One(u32, u32) }",
492 r#"pub struct One(pub u32, pub u32);
494 pub enum A { One(One) }"#,
499 fn test_extract_struct_with_complex_imports() {
501 extract_struct_from_enum_variant,
504 let m = my_other_mod::MyEnum::MyField(1, 1);
507 pub mod my_other_mod {
509 let m = MyEnum::MyField(1, 1);
519 let m = my_mod::my_other_mod::MyEnum::MyField(1, 1);
521 r#"use my_mod::my_other_mod::MyField;
524 use self::my_other_mod::MyField;
527 let m = my_other_mod::MyEnum::MyField(MyField(1, 1));
530 pub mod my_other_mod {
532 let m = MyEnum::MyField(MyField(1, 1));
535 pub struct MyField(pub u8, pub u8);
544 let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1));
550 fn extract_record_fix_references() {
552 extract_struct_from_enum_variant,
555 $0V { i: i32, j: i32 }
559 let E::V { i, j } = E::V { i: 9, j: 2 };
563 struct V{ pub i: i32, pub j: i32 }
570 let E::V(V { i, j }) = E::V(V { i: 9, j: 2 });
577 fn extract_record_fix_references2() {
579 extract_struct_from_enum_variant,
586 let E::V(i, j) = E::V(9, 2);
590 struct V(pub i32, pub i32);
597 let E::V(V(i, j)) = E::V(V(9, 2));
604 fn test_several_files() {
606 extract_struct_from_enum_variant,
622 struct V(pub i32, pub i32);
632 let e = E::V(V(9, 2));
639 fn test_several_files_record() {
641 extract_struct_from_enum_variant,
645 $0V { i: i32, j: i32 }
652 let e = E::V { i: 9, j: 2 };
657 struct V{ pub i: i32, pub j: i32 }
667 let e = E::V(V { i: 9, j: 2 });
674 fn test_extract_struct_record_nested_call_exp() {
676 extract_struct_from_enum_variant,
678 enum A { $0One { a: u32, b: u32 } }
683 let _ = B(A::One { a: 1, b: 2 });
687 struct One{ pub a: u32, pub b: u32 }
694 let _ = B(A::One(One { a: 1, b: 2 }));
701 fn test_extract_enum_not_applicable_for_element_with_no_fields() {
702 check_not_applicable("enum A { $0One }");
706 fn test_extract_enum_not_applicable_if_struct_exists() {
707 check_not_applicable(
709 enum A { $0One(u8, u32) }"#,
714 fn test_extract_not_applicable_one_field() {
715 check_not_applicable(r"enum A { $0One(u32) }");
719 fn test_extract_not_applicable_no_field_tuple() {
720 check_not_applicable(r"enum A { $0None() }");
724 fn test_extract_not_applicable_no_field_named() {
725 check_not_applicable(r"enum A { $0None {} }");