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) {
51 cov_mark::hit!(test_extract_enum_not_applicable_if_struct_exists);
55 let enum_ast = variant.parent_enum();
56 let enum_hir = ctx.sema.to_def(&enum_ast)?;
57 let target = variant.syntax().text_range();
59 AssistId("extract_struct_from_enum_variant", AssistKind::RefactorRewrite),
60 "Extract struct from enum variant",
63 let variant_hir_name = variant_hir.name(ctx.db());
64 let enum_module_def = ModuleDef::from(enum_hir);
66 Definition::ModuleDef(ModuleDef::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.frange.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.frange.file_id);
92 let variant = builder.make_mut(variant.clone());
93 if let Some(references) = def_file_references {
94 let processed = process_references(
97 &mut visited_modules_set,
102 processed.into_iter().for_each(|(path, node, import)| {
103 apply_references(ctx.config.insert_use, path, node, import)
107 let def = create_struct_def(variant_name.clone(), &field_list, &enum_ast);
108 let start_offset = &variant.parent_enum().syntax().clone();
109 ted::insert_raw(ted::Position::before(start_offset), def.syntax());
110 ted::insert_raw(ted::Position::before(start_offset), &make::tokens::blank_line());
112 update_variant(&variant, enum_ast.generic_param_list());
117 fn extract_field_list_if_applicable(
118 variant: &ast::Variant,
119 ) -> Option<Either<ast::RecordFieldList, ast::TupleFieldList>> {
120 match variant.kind() {
121 ast::StructKind::Record(field_list) if field_list.fields().next().is_some() => {
122 Some(Either::Left(field_list))
124 ast::StructKind::Tuple(field_list) if field_list.fields().count() > 1 => {
125 Some(Either::Right(field_list))
131 fn existing_definition(db: &RootDatabase, variant_name: &ast::Name, variant: &Variant) -> bool {
137 .filter(|(_, def)| match def {
138 // only check type-namespace
139 hir::ScopeDef::ModuleDef(def) => matches!(
143 | ModuleDef::Variant(_)
144 | ModuleDef::Trait(_)
145 | ModuleDef::TypeAlias(_)
146 | ModuleDef::BuiltinType(_)
150 .any(|(name, _)| name.to_string() == variant_name.to_string())
153 fn create_struct_def(
154 variant_name: ast::Name,
155 field_list: &Either<ast::RecordFieldList, ast::TupleFieldList>,
158 let pub_vis = make::visibility_pub();
160 let insert_pub = |node: &'_ SyntaxNode| {
161 let pub_vis = pub_vis.clone_for_update();
162 ted::insert(ted::Position::before(node), pub_vis.syntax());
165 // for fields without any existing visibility, use pub visibility
166 let field_list = match field_list {
167 Either::Left(field_list) => {
168 let field_list = field_list.clone_for_update();
172 .filter(|field| field.visibility().is_none())
173 .filter_map(|field| field.name())
174 .for_each(|it| insert_pub(it.syntax()));
178 Either::Right(field_list) => {
179 let field_list = field_list.clone_for_update();
183 .filter(|field| field.visibility().is_none())
184 .filter_map(|field| field.ty())
185 .for_each(|it| insert_pub(it.syntax()));
191 // FIXME: This uses all the generic params of the enum, but the variant might not use all of them.
193 make::struct_(enum_.visibility(), variant_name, enum_.generic_param_list(), field_list)
198 Position::first_child_of(strukt.syntax()),
199 enum_.attrs().map(|it| it.syntax().clone_for_update().into()).collect(),
204 fn update_variant(variant: &ast::Variant, generic: Option<ast::GenericParamList>) -> Option<()> {
205 let name = variant.name()?;
206 let ty = match generic {
207 // FIXME: This uses all the generic params of the enum, but the variant might not use all of them.
209 let gpl = gpl.clone_for_update();
210 gpl.generic_params().for_each(|gp| {
212 ast::GenericParam::LifetimeParam(it) => it.type_bound_list(),
213 ast::GenericParam::TypeParam(it) => it.type_bound_list(),
214 ast::GenericParam::ConstParam(_) => return,
216 .map(|it| it.remove());
218 make::ty(&format!("{}<{}>", name.text(), gpl.generic_params().join(", ")))
220 None => make::ty(&name.text()),
222 let tuple_field = make::tuple_field(None, ty);
223 let replacement = make::variant(
225 Some(ast::FieldList::TupleFieldList(make::tuple_field_list(iter::once(tuple_field)))),
228 ted::replace(variant.syntax(), replacement.syntax());
233 insert_use_cfg: InsertUseConfig,
234 segment: ast::PathSegment,
236 import: Option<(ImportScope, hir::ModPath)>,
238 if let Some((scope, path)) = import {
239 insert_use(&scope, mod_path_to_ast(&path), &insert_use_cfg);
241 // deep clone to prevent cycle
242 let path = make::path_from_segments(iter::once(segment.clone_subtree()), false);
243 ted::insert_raw(ted::Position::before(segment.syntax()), path.clone_for_update().syntax());
244 ted::insert_raw(ted::Position::before(segment.syntax()), make::token(T!['(']));
245 ted::insert_raw(ted::Position::after(&node), make::token(T![')']));
248 fn process_references(
250 builder: &mut AssistBuilder,
251 visited_modules: &mut FxHashSet<Module>,
252 enum_module_def: &ModuleDef,
253 variant_hir_name: &Name,
254 refs: Vec<FileReference>,
255 ) -> Vec<(ast::PathSegment, SyntaxNode, Option<(ImportScope, hir::ModPath)>)> {
256 // we have to recollect here eagerly as we are about to edit the tree we need to calculate the changes
257 // and corresponding nodes up front
259 .flat_map(|reference| {
260 let (segment, scope_node, module) = reference_to_node(&ctx.sema, reference)?;
261 let segment = builder.make_mut(segment);
262 let scope_node = builder.make_syntax_mut(scope_node);
263 if !visited_modules.contains(&module) {
264 let mod_path = module.find_use_path_prefixed(
267 ctx.config.insert_use.prefix_kind,
269 if let Some(mut mod_path) = mod_path {
270 mod_path.pop_segment();
271 mod_path.push_segment(variant_hir_name.clone());
272 let scope = ImportScope::find_insert_use_container(&scope_node)?;
273 visited_modules.insert(module);
274 return Some((segment, scope_node, Some((scope, mod_path))));
277 Some((segment, scope_node, None))
282 fn reference_to_node(
283 sema: &hir::Semantics<RootDatabase>,
284 reference: FileReference,
285 ) -> Option<(ast::PathSegment, SyntaxNode, hir::Module)> {
287 reference.name.as_name_ref()?.syntax().parent().and_then(ast::PathSegment::cast)?;
288 let parent = segment.parent_path().syntax().parent()?;
289 let expr_or_pat = match_ast! {
291 ast::PathExpr(_it) => parent.parent()?,
292 ast::RecordExpr(_it) => parent,
293 ast::TupleStructPat(_it) => parent,
294 ast::RecordPat(_it) => parent,
298 let module = sema.scope(&expr_or_pat).module()?;
299 Some((segment, expr_or_pat, module))
304 use crate::tests::{check_assist, check_assist_not_applicable};
309 fn test_extract_struct_several_fields_tuple() {
311 extract_struct_from_enum_variant,
312 "enum A { $0One(u32, u32) }",
313 r#"struct One(pub u32, pub u32);
315 enum A { One(One) }"#,
320 fn test_extract_struct_several_fields_named() {
322 extract_struct_from_enum_variant,
323 "enum A { $0One { foo: u32, bar: u32 } }",
324 r#"struct One{ pub foo: u32, pub bar: u32 }
326 enum A { One(One) }"#,
331 fn test_extract_struct_one_field_named() {
333 extract_struct_from_enum_variant,
334 "enum A { $0One { foo: u32 } }",
335 r#"struct One{ pub foo: u32 }
337 enum A { One(One) }"#,
342 fn test_extract_struct_carries_over_generics() {
344 extract_struct_from_enum_variant,
345 r"enum En<T> { Var { a: T$0 } }",
346 r#"struct Var<T>{ pub a: T }
348 enum En<T> { Var(Var<T>) }"#,
353 fn test_extract_struct_carries_over_attributes() {
355 extract_struct_from_enum_variant,
358 enum Enum { Variant{ field: u32$0 } }"#,
359 r#"#[derive(Debug)]#[derive(Clone)] struct Variant{ pub field: u32 }
363 enum Enum { Variant(Variant) }"#,
368 fn test_extract_struct_keep_comments_and_attrs_one_field_named() {
370 extract_struct_from_enum_variant,
397 fn test_extract_struct_keep_comments_and_attrs_several_fields_named() {
399 extract_struct_from_enum_variant,
432 fn test_extract_struct_keep_comments_and_attrs_several_fields_tuple() {
434 extract_struct_from_enum_variant,
435 "enum A { $0One(/* comment */ #[attr] u32, /* another */ u32 /* tail */) }",
437 struct One(/* comment */ #[attr] pub u32, /* another */ pub u32 /* tail */);
439 enum A { One(One) }"#,
444 fn test_extract_struct_keep_existing_visibility_named() {
446 extract_struct_from_enum_variant,
447 "enum A { $0One{ pub a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 } }",
449 struct One{ pub a: u32, pub(crate) b: u32, pub(super) c: u32, pub d: u32 }
451 enum A { One(One) }"#,
456 fn test_extract_struct_keep_existing_visibility_tuple() {
458 extract_struct_from_enum_variant,
459 "enum A { $0One(pub u32, pub(crate) u32, pub(super) u32, u32) }",
461 struct One(pub u32, pub(crate) u32, pub(super) u32, pub u32);
463 enum A { One(One) }"#,
468 fn test_extract_enum_variant_name_value_namespace() {
470 extract_struct_from_enum_variant,
471 r#"const One: () = ();
472 enum A { $0One(u32, u32) }"#,
473 r#"const One: () = ();
474 struct One(pub u32, pub u32);
476 enum A { One(One) }"#,
481 fn test_extract_struct_pub_visibility() {
483 extract_struct_from_enum_variant,
484 "pub enum A { $0One(u32, u32) }",
485 r#"pub struct One(pub u32, pub u32);
487 pub enum A { One(One) }"#,
492 fn test_extract_struct_with_complex_imports() {
494 extract_struct_from_enum_variant,
497 let m = my_other_mod::MyEnum::MyField(1, 1);
500 pub mod my_other_mod {
502 let m = MyEnum::MyField(1, 1);
512 let m = my_mod::my_other_mod::MyEnum::MyField(1, 1);
514 r#"use my_mod::my_other_mod::MyField;
517 use self::my_other_mod::MyField;
520 let m = my_other_mod::MyEnum::MyField(MyField(1, 1));
523 pub mod my_other_mod {
525 let m = MyEnum::MyField(MyField(1, 1));
528 pub struct MyField(pub u8, pub u8);
537 let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1));
543 fn extract_record_fix_references() {
545 extract_struct_from_enum_variant,
548 $0V { i: i32, j: i32 }
552 let E::V { i, j } = E::V { i: 9, j: 2 };
556 struct V{ pub i: i32, pub j: i32 }
563 let E::V(V { i, j }) = E::V(V { i: 9, j: 2 });
570 fn extract_record_fix_references2() {
572 extract_struct_from_enum_variant,
579 let E::V(i, j) = E::V(9, 2);
583 struct V(pub i32, pub i32);
590 let E::V(V(i, j)) = E::V(V(9, 2));
597 fn test_several_files() {
599 extract_struct_from_enum_variant,
615 struct V(pub i32, pub i32);
625 let e = E::V(V(9, 2));
632 fn test_several_files_record() {
634 extract_struct_from_enum_variant,
638 $0V { i: i32, j: i32 }
645 let e = E::V { i: 9, j: 2 };
650 struct V{ pub i: i32, pub j: i32 }
660 let e = E::V(V { i: 9, j: 2 });
667 fn test_extract_struct_record_nested_call_exp() {
669 extract_struct_from_enum_variant,
671 enum A { $0One { a: u32, b: u32 } }
676 let _ = B(A::One { a: 1, b: 2 });
680 struct One{ pub a: u32, pub b: u32 }
687 let _ = B(A::One(One { a: 1, b: 2 }));
694 fn test_extract_enum_not_applicable_for_element_with_no_fields() {
695 check_assist_not_applicable(extract_struct_from_enum_variant, r#"enum A { $0One }"#);
699 fn test_extract_enum_not_applicable_if_struct_exists() {
700 cov_mark::check!(test_extract_enum_not_applicable_if_struct_exists);
701 check_assist_not_applicable(
702 extract_struct_from_enum_variant,
705 enum A { $0One(u8, u32) }
711 fn test_extract_not_applicable_one_field() {
712 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0One(u32) }");
716 fn test_extract_not_applicable_no_field_tuple() {
717 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None() }");
721 fn test_extract_not_applicable_no_field_named() {
722 check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None {} }");