]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/handlers/extract_struct_from_enum_variant.rs
feat: Use enum's visibility for extracted struct fields
[rust.git] / crates / ide_assists / src / handlers / extract_struct_from_enum_variant.rs
1 use std::iter;
2
3 use either::Either;
4 use hir::{Module, ModuleDef, Name, Variant};
5 use ide_db::{
6     defs::Definition,
7     helpers::{
8         insert_use::{insert_use, ImportScope, InsertUseConfig},
9         mod_path_to_ast,
10     },
11     search::FileReference,
12     RootDatabase,
13 };
14 use itertools::Itertools;
15 use rustc_hash::FxHashSet;
16 use syntax::{
17     ast::{
18         self, edit::IndentLevel, edit_in_place::Indent, make, AstNode, AttrsOwner,
19         GenericParamsOwner, NameOwner, TypeBoundsOwner, VisibilityOwner,
20     },
21     match_ast,
22     ted::{self, Position},
23     SyntaxKind::*,
24     SyntaxNode, T,
25 };
26
27 use crate::{assist_context::AssistBuilder, AssistContext, AssistId, AssistKind, Assists};
28
29 // Assist: extract_struct_from_enum_variant
30 //
31 // Extracts a struct from enum variant.
32 //
33 // ```
34 // enum A { $0One(u32, u32) }
35 // ```
36 // ->
37 // ```
38 // struct One(u32, u32);
39 //
40 // enum A { One(One) }
41 // ```
42 pub(crate) fn extract_struct_from_enum_variant(
43     acc: &mut Assists,
44     ctx: &AssistContext,
45 ) -> Option<()> {
46     let variant = ctx.find_node_at_offset::<ast::Variant>()?;
47     let field_list = extract_field_list_if_applicable(&variant)?;
48
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);
53         return None;
54     }
55
56     let enum_ast = variant.parent_enum();
57     let enum_hir = ctx.sema.to_def(&enum_ast)?;
58     let target = variant.syntax().text_range();
59     acc.add(
60         AssistId("extract_struct_from_enum_variant", AssistKind::RefactorRewrite),
61         "Extract struct from enum variant",
62         target,
63         |builder| {
64             let variant_hir_name = variant_hir.name(ctx.db());
65             let enum_module_def = ModuleDef::from(enum_hir);
66             let usages =
67                 Definition::ModuleDef(ModuleDef::Variant(variant_hir)).usages(&ctx.sema).all();
68
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);
77                     continue;
78                 }
79                 builder.edit_file(file_id);
80                 let processed = process_references(
81                     ctx,
82                     builder,
83                     &mut visited_modules_set,
84                     &enum_module_def,
85                     &variant_hir_name,
86                     references,
87                 );
88                 processed.into_iter().for_each(|(path, node, import)| {
89                     apply_references(ctx.config.insert_use, path, node, import)
90                 });
91             }
92             builder.edit_file(ctx.frange.file_id);
93
94             let variant = builder.make_mut(variant.clone());
95             if let Some(references) = def_file_references {
96                 let processed = process_references(
97                     ctx,
98                     builder,
99                     &mut visited_modules_set,
100                     &enum_module_def,
101                     &variant_hir_name,
102                     references,
103                 );
104                 processed.into_iter().for_each(|(path, node, import)| {
105                     apply_references(ctx.config.insert_use, path, node, import)
106                 });
107             }
108
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);
112
113             let start_offset = &variant.parent_enum().syntax().clone();
114             ted::insert_all_raw(
115                 ted::Position::before(start_offset),
116                 vec![
117                     def.syntax().clone().into(),
118                     make::tokens::whitespace(&format!("\n\n{}", indent)).into(),
119                 ],
120             );
121
122             update_variant(&variant, enum_ast.generic_param_list());
123         },
124     )
125 }
126
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))
133         }
134         ast::StructKind::Tuple(field_list) if field_list.fields().count() > 1 => {
135             Some(Either::Right(field_list))
136         }
137         _ => None,
138     }
139 }
140
141 fn existing_definition(db: &RootDatabase, variant_name: &ast::Name, variant: &Variant) -> bool {
142     variant
143         .parent_enum(db)
144         .module(db)
145         .scope(db, None)
146         .into_iter()
147         .filter(|(_, def)| match def {
148             // only check type-namespace
149             hir::ScopeDef::ModuleDef(def) => matches!(
150                 def,
151                 ModuleDef::Module(_)
152                     | ModuleDef::Adt(_)
153                     | ModuleDef::Variant(_)
154                     | ModuleDef::Trait(_)
155                     | ModuleDef::TypeAlias(_)
156                     | ModuleDef::BuiltinType(_)
157             ),
158             _ => false,
159         })
160         .any(|(name, _)| name.to_string() == variant_name.to_string())
161 }
162
163 fn create_struct_def(
164     variant_name: ast::Name,
165     variant: &ast::Variant,
166     field_list: &Either<ast::RecordFieldList, ast::TupleFieldList>,
167     enum_: &ast::Enum,
168 ) -> ast::Struct {
169     let enum_vis = enum_.visibility();
170
171     let insert_vis = |node: &'_ SyntaxNode, vis: &'_ SyntaxNode| {
172         let vis = vis.clone_for_update();
173         ted::insert(ted::Position::before(node), vis);
174     };
175
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();
180
181             if let Some(vis) = &enum_vis {
182                 field_list
183                     .fields()
184                     .filter(|field| field.visibility().is_none())
185                     .filter_map(|field| field.name())
186                     .for_each(|it| insert_vis(it.syntax(), vis.syntax()));
187             }
188
189             field_list.into()
190         }
191         Either::Right(field_list) => {
192             let field_list = field_list.clone_for_update();
193
194             if let Some(vis) = &enum_vis {
195                 field_list
196                     .fields()
197                     .filter(|field| field.visibility().is_none())
198                     .filter_map(|field| field.ty())
199                     .for_each(|it| insert_vis(it.syntax(), vis.syntax()));
200             }
201
202             field_list.into()
203         }
204     };
205
206     field_list.reindent_to(IndentLevel::single());
207
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)
210         .clone_for_update();
211
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() {
217                 ATTR | COMMENT => {
218                     select_next_ws = true;
219                     return true;
220                 }
221                 WHITESPACE if select_next_ws => true,
222                 _ => false,
223             };
224             select_next_ws = false;
225
226             accept
227         })
228     };
229
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(),
234             _ => tok.into(),
235         })
236         .collect();
237     ted::insert_all(Position::first_child_of(strukt.syntax()), variant_attrs);
238
239     // copy attributes from enum
240     ted::insert_all(
241         Position::first_child_of(strukt.syntax()),
242         enum_.attrs().map(|it| it.syntax().clone_for_update().into()).collect(),
243     );
244     strukt
245 }
246
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.
251         Some(gpl) => {
252             let gpl = gpl.clone_for_update();
253             gpl.generic_params().for_each(|gp| {
254                 match gp {
255                     ast::GenericParam::LifetimeParam(it) => it.type_bound_list(),
256                     ast::GenericParam::TypeParam(it) => it.type_bound_list(),
257                     ast::GenericParam::ConstParam(_) => return,
258                 }
259                 .map(|it| it.remove());
260             });
261             make::ty(&format!("{}<{}>", name.text(), gpl.generic_params().join(", ")))
262         }
263         None => make::ty(&name.text()),
264     };
265     let tuple_field = make::tuple_field(None, ty);
266     let replacement = make::variant(
267         name,
268         Some(ast::FieldList::TupleFieldList(make::tuple_field_list(iter::once(tuple_field)))),
269     )
270     .clone_for_update();
271     ted::replace(variant.syntax(), replacement.syntax());
272     Some(())
273 }
274
275 fn apply_references(
276     insert_use_cfg: InsertUseConfig,
277     segment: ast::PathSegment,
278     node: SyntaxNode,
279     import: Option<(ImportScope, hir::ModPath)>,
280 ) {
281     if let Some((scope, path)) = import {
282         insert_use(&scope, mod_path_to_ast(&path), &insert_use_cfg);
283     }
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![')']));
289 }
290
291 fn process_references(
292     ctx: &AssistContext,
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
301     refs.into_iter()
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(
308                     ctx.sema.db,
309                     *enum_module_def,
310                     ctx.config.insert_use.prefix_kind,
311                 );
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))));
318                 }
319             }
320             Some((segment, scope_node, None))
321         })
322         .collect()
323 }
324
325 fn reference_to_node(
326     sema: &hir::Semantics<RootDatabase>,
327     reference: FileReference,
328 ) -> Option<(ast::PathSegment, SyntaxNode, hir::Module)> {
329     let segment =
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! {
333         match parent {
334             ast::PathExpr(_it) => parent.parent()?,
335             ast::RecordExpr(_it) => parent,
336             ast::TupleStructPat(_it) => parent,
337             ast::RecordPat(_it) => parent,
338             _ => return None,
339         }
340     };
341     let module = sema.scope(&expr_or_pat).module()?;
342     Some((segment, expr_or_pat, module))
343 }
344
345 #[cfg(test)]
346 mod tests {
347     use crate::tests::{check_assist, check_assist_not_applicable};
348
349     use super::*;
350
351     #[test]
352     fn test_extract_struct_several_fields_tuple() {
353         check_assist(
354             extract_struct_from_enum_variant,
355             "enum A { $0One(u32, u32) }",
356             r#"struct One(u32, u32);
357
358 enum A { One(One) }"#,
359         );
360     }
361
362     #[test]
363     fn test_extract_struct_several_fields_named() {
364         check_assist(
365             extract_struct_from_enum_variant,
366             "enum A { $0One { foo: u32, bar: u32 } }",
367             r#"struct One{ foo: u32, bar: u32 }
368
369 enum A { One(One) }"#,
370         );
371     }
372
373     #[test]
374     fn test_extract_struct_one_field_named() {
375         check_assist(
376             extract_struct_from_enum_variant,
377             "enum A { $0One { foo: u32 } }",
378             r#"struct One{ foo: u32 }
379
380 enum A { One(One) }"#,
381         );
382     }
383
384     #[test]
385     fn test_extract_struct_carries_over_generics() {
386         check_assist(
387             extract_struct_from_enum_variant,
388             r"enum En<T> { Var { a: T$0 } }",
389             r#"struct Var<T>{ a: T }
390
391 enum En<T> { Var(Var<T>) }"#,
392         );
393     }
394
395     #[test]
396     fn test_extract_struct_carries_over_attributes() {
397         check_assist(
398             extract_struct_from_enum_variant,
399             r#"#[derive(Debug)]
400 #[derive(Clone)]
401 enum Enum { Variant{ field: u32$0 } }"#,
402             r#"#[derive(Debug)]#[derive(Clone)] struct Variant{ field: u32 }
403
404 #[derive(Debug)]
405 #[derive(Clone)]
406 enum Enum { Variant(Variant) }"#,
407         );
408     }
409
410     #[test]
411     fn test_extract_struct_indent_to_parent_enum() {
412         check_assist(
413             extract_struct_from_enum_variant,
414             r#"
415 enum Enum {
416     Variant {
417         field: u32$0
418     }
419 }"#,
420             r#"
421 struct Variant{
422     field: u32
423 }
424
425 enum Enum {
426     Variant(Variant)
427 }"#,
428         );
429     }
430
431     #[test]
432     fn test_extract_struct_indent_to_parent_enum_in_mod() {
433         check_assist(
434             extract_struct_from_enum_variant,
435             r#"
436 mod indenting {
437     enum Enum {
438         Variant {
439             field: u32$0
440         }
441     }
442 }"#,
443             r#"
444 mod indenting {
445     struct Variant{
446         field: u32
447     }
448
449     enum Enum {
450         Variant(Variant)
451     }
452 }"#,
453         );
454     }
455
456     #[test]
457     fn test_extract_struct_keep_comments_and_attrs_one_field_named() {
458         check_assist(
459             extract_struct_from_enum_variant,
460             r#"
461 enum A {
462     $0One {
463         // leading comment
464         /// doc comment
465         #[an_attr]
466         foo: u32
467         // trailing comment
468     }
469 }"#,
470             r#"
471 struct One{
472     // leading comment
473     /// doc comment
474     #[an_attr]
475     foo: u32
476     // trailing comment
477 }
478
479 enum A {
480     One(One)
481 }"#,
482         );
483     }
484
485     #[test]
486     fn test_extract_struct_keep_comments_and_attrs_several_fields_named() {
487         check_assist(
488             extract_struct_from_enum_variant,
489             r#"
490 enum A {
491     $0One {
492         // comment
493         /// doc
494         #[attr]
495         foo: u32,
496         // comment
497         #[attr]
498         /// doc
499         bar: u32
500     }
501 }"#,
502             r#"
503 struct One{
504     // comment
505     /// doc
506     #[attr]
507     foo: u32,
508     // comment
509     #[attr]
510     /// doc
511     bar: u32
512 }
513
514 enum A {
515     One(One)
516 }"#,
517         );
518     }
519
520     #[test]
521     fn test_extract_struct_keep_comments_and_attrs_several_fields_tuple() {
522         check_assist(
523             extract_struct_from_enum_variant,
524             "enum A { $0One(/* comment */ #[attr] u32, /* another */ u32 /* tail */) }",
525             r#"
526 struct One(/* comment */ #[attr] u32, /* another */ u32 /* tail */);
527
528 enum A { One(One) }"#,
529         );
530     }
531
532     #[test]
533     fn test_extract_struct_keep_comments_and_attrs_on_variant_struct() {
534         check_assist(
535             extract_struct_from_enum_variant,
536             r#"
537 enum A {
538     /* comment */
539     // other
540     /// comment
541     #[attr]
542     $0One {
543         a: u32
544     }
545 }"#,
546             r#"
547 /* comment */
548 // other
549 /// comment
550 #[attr]
551 struct One{
552     a: u32
553 }
554
555 enum A {
556     One(One)
557 }"#,
558         );
559     }
560
561     #[test]
562     fn test_extract_struct_keep_comments_and_attrs_on_variant_tuple() {
563         check_assist(
564             extract_struct_from_enum_variant,
565             r#"
566 enum A {
567     /* comment */
568     // other
569     /// comment
570     #[attr]
571     $0One(u32, u32)
572 }"#,
573             r#"
574 /* comment */
575 // other
576 /// comment
577 #[attr]
578 struct One(u32, u32);
579
580 enum A {
581     One(One)
582 }"#,
583         );
584     }
585
586     #[test]
587     fn test_extract_struct_keep_existing_visibility_named() {
588         check_assist(
589             extract_struct_from_enum_variant,
590             "enum A { $0One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 } }",
591             r#"
592 struct One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 }
593
594 enum A { One(One) }"#,
595         );
596     }
597
598     #[test]
599     fn test_extract_struct_keep_existing_visibility_tuple() {
600         check_assist(
601             extract_struct_from_enum_variant,
602             "enum A { $0One(u32, pub(crate) u32, pub(super) u32, u32) }",
603             r#"
604 struct One(u32, pub(crate) u32, pub(super) u32, u32);
605
606 enum A { One(One) }"#,
607         );
608     }
609
610     #[test]
611     fn test_extract_enum_variant_name_value_namespace() {
612         check_assist(
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);
618
619 enum A { One(One) }"#,
620         );
621     }
622
623     #[test]
624     fn test_extract_struct_no_visibility() {
625         check_assist(
626             extract_struct_from_enum_variant,
627             "enum A { $0One(u32, u32) }",
628             r#"
629 struct One(u32, u32);
630
631 enum A { One(One) }"#,
632         );
633     }
634
635     #[test]
636     fn test_extract_struct_pub_visibility() {
637         check_assist(
638             extract_struct_from_enum_variant,
639             "pub enum A { $0One(u32, u32) }",
640             r#"
641 pub struct One(pub u32, pub u32);
642
643 pub enum A { One(One) }"#,
644         );
645     }
646
647     #[test]
648     fn test_extract_struct_pub_in_mod_visibility() {
649         check_assist(
650             extract_struct_from_enum_variant,
651             "pub(in something) enum A { $0One{ a: u32, b: u32 } }",
652             r#"
653 pub(in something) struct One{ pub(in something) a: u32, pub(in something) b: u32 }
654
655 pub(in something) enum A { One(One) }"#,
656         );
657     }
658
659     #[test]
660     fn test_extract_struct_pub_crate_visibility() {
661         check_assist(
662             extract_struct_from_enum_variant,
663             "pub(crate) enum A { $0One{ a: u32, b: u32, c: u32 } }",
664             r#"
665 pub(crate) struct One{ pub(crate) a: u32, pub(crate) b: u32, pub(crate) c: u32 }
666
667 pub(crate) enum A { One(One) }"#,
668         );
669     }
670
671     #[test]
672     fn test_extract_struct_with_complex_imports() {
673         check_assist(
674             extract_struct_from_enum_variant,
675             r#"mod my_mod {
676     fn another_fn() {
677         let m = my_other_mod::MyEnum::MyField(1, 1);
678     }
679
680     pub mod my_other_mod {
681         fn another_fn() {
682             let m = MyEnum::MyField(1, 1);
683         }
684
685         pub enum MyEnum {
686             $0MyField(u8, u8),
687         }
688     }
689 }
690
691 fn another_fn() {
692     let m = my_mod::my_other_mod::MyEnum::MyField(1, 1);
693 }"#,
694             r#"use my_mod::my_other_mod::MyField;
695
696 mod my_mod {
697     use self::my_other_mod::MyField;
698
699     fn another_fn() {
700         let m = my_other_mod::MyEnum::MyField(MyField(1, 1));
701     }
702
703     pub mod my_other_mod {
704         fn another_fn() {
705             let m = MyEnum::MyField(MyField(1, 1));
706         }
707
708         pub struct MyField(pub u8, pub u8);
709
710         pub enum MyEnum {
711             MyField(MyField),
712         }
713     }
714 }
715
716 fn another_fn() {
717     let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1));
718 }"#,
719         );
720     }
721
722     #[test]
723     fn extract_record_fix_references() {
724         check_assist(
725             extract_struct_from_enum_variant,
726             r#"
727 enum E {
728     $0V { i: i32, j: i32 }
729 }
730
731 fn f() {
732     let E::V { i, j } = E::V { i: 9, j: 2 };
733 }
734 "#,
735             r#"
736 struct V{ i: i32, j: i32 }
737
738 enum E {
739     V(V)
740 }
741
742 fn f() {
743     let E::V(V { i, j }) = E::V(V { i: 9, j: 2 });
744 }
745 "#,
746         )
747     }
748
749     #[test]
750     fn extract_record_fix_references2() {
751         check_assist(
752             extract_struct_from_enum_variant,
753             r#"
754 enum E {
755     $0V(i32, i32)
756 }
757
758 fn f() {
759     let E::V(i, j) = E::V(9, 2);
760 }
761 "#,
762             r#"
763 struct V(i32, i32);
764
765 enum E {
766     V(V)
767 }
768
769 fn f() {
770     let E::V(V(i, j)) = E::V(V(9, 2));
771 }
772 "#,
773         )
774     }
775
776     #[test]
777     fn test_several_files() {
778         check_assist(
779             extract_struct_from_enum_variant,
780             r#"
781 //- /main.rs
782 enum E {
783     $0V(i32, i32)
784 }
785 mod foo;
786
787 //- /foo.rs
788 use crate::E;
789 fn f() {
790     let e = E::V(9, 2);
791 }
792 "#,
793             r#"
794 //- /main.rs
795 struct V(i32, i32);
796
797 enum E {
798     V(V)
799 }
800 mod foo;
801
802 //- /foo.rs
803 use crate::{E, V};
804 fn f() {
805     let e = E::V(V(9, 2));
806 }
807 "#,
808         )
809     }
810
811     #[test]
812     fn test_several_files_record() {
813         check_assist(
814             extract_struct_from_enum_variant,
815             r#"
816 //- /main.rs
817 enum E {
818     $0V { i: i32, j: i32 }
819 }
820 mod foo;
821
822 //- /foo.rs
823 use crate::E;
824 fn f() {
825     let e = E::V { i: 9, j: 2 };
826 }
827 "#,
828             r#"
829 //- /main.rs
830 struct V{ i: i32, j: i32 }
831
832 enum E {
833     V(V)
834 }
835 mod foo;
836
837 //- /foo.rs
838 use crate::{E, V};
839 fn f() {
840     let e = E::V(V { i: 9, j: 2 });
841 }
842 "#,
843         )
844     }
845
846     #[test]
847     fn test_extract_struct_record_nested_call_exp() {
848         check_assist(
849             extract_struct_from_enum_variant,
850             r#"
851 enum A { $0One { a: u32, b: u32 } }
852
853 struct B(A);
854
855 fn foo() {
856     let _ = B(A::One { a: 1, b: 2 });
857 }
858 "#,
859             r#"
860 struct One{ a: u32, b: u32 }
861
862 enum A { One(One) }
863
864 struct B(A);
865
866 fn foo() {
867     let _ = B(A::One(One { a: 1, b: 2 }));
868 }
869 "#,
870         );
871     }
872
873     #[test]
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 }"#);
876     }
877
878     #[test]
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,
883             r#"
884 struct One;
885 enum A { $0One(u8, u32) }
886 "#,
887         );
888     }
889
890     #[test]
891     fn test_extract_not_applicable_one_field() {
892         check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0One(u32) }");
893     }
894
895     #[test]
896     fn test_extract_not_applicable_no_field_tuple() {
897         check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None() }");
898     }
899
900     #[test]
901     fn test_extract_not_applicable_no_field_named() {
902         check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None {} }");
903     }
904 }