]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/handlers/extract_struct_from_enum_variant.rs
Merge #10373
[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, HasAttrs, HasGenericParams,
19         HasName, HasTypeBounds, HasVisibility,
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,
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                 let tbl = 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                 if let Some(tbl) = tbl {
260                     tbl.remove();
261                 }
262             });
263             make::ty(&format!("{}<{}>", name.text(), gpl.generic_params().join(", ")))
264         }
265         None => make::ty(&name.text()),
266     };
267     let tuple_field = make::tuple_field(None, ty);
268     let replacement = make::variant(
269         name,
270         Some(ast::FieldList::TupleFieldList(make::tuple_field_list(iter::once(tuple_field)))),
271     )
272     .clone_for_update();
273     ted::replace(variant.syntax(), replacement.syntax());
274     Some(())
275 }
276
277 fn apply_references(
278     insert_use_cfg: InsertUseConfig,
279     segment: ast::PathSegment,
280     node: SyntaxNode,
281     import: Option<(ImportScope, hir::ModPath)>,
282 ) {
283     if let Some((scope, path)) = import {
284         insert_use(&scope, mod_path_to_ast(&path), &insert_use_cfg);
285     }
286     // deep clone to prevent cycle
287     let path = make::path_from_segments(iter::once(segment.clone_subtree()), false);
288     ted::insert_raw(ted::Position::before(segment.syntax()), path.clone_for_update().syntax());
289     ted::insert_raw(ted::Position::before(segment.syntax()), make::token(T!['(']));
290     ted::insert_raw(ted::Position::after(&node), make::token(T![')']));
291 }
292
293 fn process_references(
294     ctx: &AssistContext,
295     builder: &mut AssistBuilder,
296     visited_modules: &mut FxHashSet<Module>,
297     enum_module_def: &ModuleDef,
298     variant_hir_name: &Name,
299     refs: Vec<FileReference>,
300 ) -> Vec<(ast::PathSegment, SyntaxNode, Option<(ImportScope, hir::ModPath)>)> {
301     // we have to recollect here eagerly as we are about to edit the tree we need to calculate the changes
302     // and corresponding nodes up front
303     refs.into_iter()
304         .flat_map(|reference| {
305             let (segment, scope_node, module) = reference_to_node(&ctx.sema, reference)?;
306             let segment = builder.make_mut(segment);
307             let scope_node = builder.make_syntax_mut(scope_node);
308             if !visited_modules.contains(&module) {
309                 let mod_path = module.find_use_path_prefixed(
310                     ctx.sema.db,
311                     *enum_module_def,
312                     ctx.config.insert_use.prefix_kind,
313                 );
314                 if let Some(mut mod_path) = mod_path {
315                     mod_path.pop_segment();
316                     mod_path.push_segment(variant_hir_name.clone());
317                     let scope = ImportScope::find_insert_use_container(&scope_node)?;
318                     visited_modules.insert(module);
319                     return Some((segment, scope_node, Some((scope, mod_path))));
320                 }
321             }
322             Some((segment, scope_node, None))
323         })
324         .collect()
325 }
326
327 fn reference_to_node(
328     sema: &hir::Semantics<RootDatabase>,
329     reference: FileReference,
330 ) -> Option<(ast::PathSegment, SyntaxNode, hir::Module)> {
331     let segment =
332         reference.name.as_name_ref()?.syntax().parent().and_then(ast::PathSegment::cast)?;
333     let parent = segment.parent_path().syntax().parent()?;
334     let expr_or_pat = match_ast! {
335         match parent {
336             ast::PathExpr(_it) => parent.parent()?,
337             ast::RecordExpr(_it) => parent,
338             ast::TupleStructPat(_it) => parent,
339             ast::RecordPat(_it) => parent,
340             _ => return None,
341         }
342     };
343     let module = sema.scope(&expr_or_pat).module()?;
344     Some((segment, expr_or_pat, module))
345 }
346
347 #[cfg(test)]
348 mod tests {
349     use crate::tests::{check_assist, check_assist_not_applicable};
350
351     use super::*;
352
353     #[test]
354     fn test_extract_struct_several_fields_tuple() {
355         check_assist(
356             extract_struct_from_enum_variant,
357             "enum A { $0One(u32, u32) }",
358             r#"struct One(u32, u32);
359
360 enum A { One(One) }"#,
361         );
362     }
363
364     #[test]
365     fn test_extract_struct_several_fields_named() {
366         check_assist(
367             extract_struct_from_enum_variant,
368             "enum A { $0One { foo: u32, bar: u32 } }",
369             r#"struct One{ foo: u32, bar: u32 }
370
371 enum A { One(One) }"#,
372         );
373     }
374
375     #[test]
376     fn test_extract_struct_one_field_named() {
377         check_assist(
378             extract_struct_from_enum_variant,
379             "enum A { $0One { foo: u32 } }",
380             r#"struct One{ foo: u32 }
381
382 enum A { One(One) }"#,
383         );
384     }
385
386     #[test]
387     fn test_extract_struct_carries_over_generics() {
388         check_assist(
389             extract_struct_from_enum_variant,
390             r"enum En<T> { Var { a: T$0 } }",
391             r#"struct Var<T>{ a: T }
392
393 enum En<T> { Var(Var<T>) }"#,
394         );
395     }
396
397     #[test]
398     fn test_extract_struct_carries_over_attributes() {
399         check_assist(
400             extract_struct_from_enum_variant,
401             r#"#[derive(Debug)]
402 #[derive(Clone)]
403 enum Enum { Variant{ field: u32$0 } }"#,
404             r#"#[derive(Debug)]#[derive(Clone)] struct Variant{ field: u32 }
405
406 #[derive(Debug)]
407 #[derive(Clone)]
408 enum Enum { Variant(Variant) }"#,
409         );
410     }
411
412     #[test]
413     fn test_extract_struct_indent_to_parent_enum() {
414         check_assist(
415             extract_struct_from_enum_variant,
416             r#"
417 enum Enum {
418     Variant {
419         field: u32$0
420     }
421 }"#,
422             r#"
423 struct Variant{
424     field: u32
425 }
426
427 enum Enum {
428     Variant(Variant)
429 }"#,
430         );
431     }
432
433     #[test]
434     fn test_extract_struct_indent_to_parent_enum_in_mod() {
435         check_assist(
436             extract_struct_from_enum_variant,
437             r#"
438 mod indenting {
439     enum Enum {
440         Variant {
441             field: u32$0
442         }
443     }
444 }"#,
445             r#"
446 mod indenting {
447     struct Variant{
448         field: u32
449     }
450
451     enum Enum {
452         Variant(Variant)
453     }
454 }"#,
455         );
456     }
457
458     #[test]
459     fn test_extract_struct_keep_comments_and_attrs_one_field_named() {
460         check_assist(
461             extract_struct_from_enum_variant,
462             r#"
463 enum A {
464     $0One {
465         // leading comment
466         /// doc comment
467         #[an_attr]
468         foo: u32
469         // trailing comment
470     }
471 }"#,
472             r#"
473 struct One{
474     // leading comment
475     /// doc comment
476     #[an_attr]
477     foo: u32
478     // trailing comment
479 }
480
481 enum A {
482     One(One)
483 }"#,
484         );
485     }
486
487     #[test]
488     fn test_extract_struct_keep_comments_and_attrs_several_fields_named() {
489         check_assist(
490             extract_struct_from_enum_variant,
491             r#"
492 enum A {
493     $0One {
494         // comment
495         /// doc
496         #[attr]
497         foo: u32,
498         // comment
499         #[attr]
500         /// doc
501         bar: u32
502     }
503 }"#,
504             r#"
505 struct One{
506     // comment
507     /// doc
508     #[attr]
509     foo: u32,
510     // comment
511     #[attr]
512     /// doc
513     bar: u32
514 }
515
516 enum A {
517     One(One)
518 }"#,
519         );
520     }
521
522     #[test]
523     fn test_extract_struct_keep_comments_and_attrs_several_fields_tuple() {
524         check_assist(
525             extract_struct_from_enum_variant,
526             "enum A { $0One(/* comment */ #[attr] u32, /* another */ u32 /* tail */) }",
527             r#"
528 struct One(/* comment */ #[attr] u32, /* another */ u32 /* tail */);
529
530 enum A { One(One) }"#,
531         );
532     }
533
534     #[test]
535     fn test_extract_struct_keep_comments_and_attrs_on_variant_struct() {
536         check_assist(
537             extract_struct_from_enum_variant,
538             r#"
539 enum A {
540     /* comment */
541     // other
542     /// comment
543     #[attr]
544     $0One {
545         a: u32
546     }
547 }"#,
548             r#"
549 /* comment */
550 // other
551 /// comment
552 #[attr]
553 struct One{
554     a: u32
555 }
556
557 enum A {
558     One(One)
559 }"#,
560         );
561     }
562
563     #[test]
564     fn test_extract_struct_keep_comments_and_attrs_on_variant_tuple() {
565         check_assist(
566             extract_struct_from_enum_variant,
567             r#"
568 enum A {
569     /* comment */
570     // other
571     /// comment
572     #[attr]
573     $0One(u32, u32)
574 }"#,
575             r#"
576 /* comment */
577 // other
578 /// comment
579 #[attr]
580 struct One(u32, u32);
581
582 enum A {
583     One(One)
584 }"#,
585         );
586     }
587
588     #[test]
589     fn test_extract_struct_keep_existing_visibility_named() {
590         check_assist(
591             extract_struct_from_enum_variant,
592             "enum A { $0One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 } }",
593             r#"
594 struct One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 }
595
596 enum A { One(One) }"#,
597         );
598     }
599
600     #[test]
601     fn test_extract_struct_keep_existing_visibility_tuple() {
602         check_assist(
603             extract_struct_from_enum_variant,
604             "enum A { $0One(u32, pub(crate) u32, pub(super) u32, u32) }",
605             r#"
606 struct One(u32, pub(crate) u32, pub(super) u32, u32);
607
608 enum A { One(One) }"#,
609         );
610     }
611
612     #[test]
613     fn test_extract_enum_variant_name_value_namespace() {
614         check_assist(
615             extract_struct_from_enum_variant,
616             r#"const One: () = ();
617 enum A { $0One(u32, u32) }"#,
618             r#"const One: () = ();
619 struct One(u32, u32);
620
621 enum A { One(One) }"#,
622         );
623     }
624
625     #[test]
626     fn test_extract_struct_no_visibility() {
627         check_assist(
628             extract_struct_from_enum_variant,
629             "enum A { $0One(u32, u32) }",
630             r#"
631 struct One(u32, u32);
632
633 enum A { One(One) }"#,
634         );
635     }
636
637     #[test]
638     fn test_extract_struct_pub_visibility() {
639         check_assist(
640             extract_struct_from_enum_variant,
641             "pub enum A { $0One(u32, u32) }",
642             r#"
643 pub struct One(pub u32, pub u32);
644
645 pub enum A { One(One) }"#,
646         );
647     }
648
649     #[test]
650     fn test_extract_struct_pub_in_mod_visibility() {
651         check_assist(
652             extract_struct_from_enum_variant,
653             "pub(in something) enum A { $0One{ a: u32, b: u32 } }",
654             r#"
655 pub(in something) struct One{ pub(in something) a: u32, pub(in something) b: u32 }
656
657 pub(in something) enum A { One(One) }"#,
658         );
659     }
660
661     #[test]
662     fn test_extract_struct_pub_crate_visibility() {
663         check_assist(
664             extract_struct_from_enum_variant,
665             "pub(crate) enum A { $0One{ a: u32, b: u32, c: u32 } }",
666             r#"
667 pub(crate) struct One{ pub(crate) a: u32, pub(crate) b: u32, pub(crate) c: u32 }
668
669 pub(crate) enum A { One(One) }"#,
670         );
671     }
672
673     #[test]
674     fn test_extract_struct_with_complex_imports() {
675         check_assist(
676             extract_struct_from_enum_variant,
677             r#"mod my_mod {
678     fn another_fn() {
679         let m = my_other_mod::MyEnum::MyField(1, 1);
680     }
681
682     pub mod my_other_mod {
683         fn another_fn() {
684             let m = MyEnum::MyField(1, 1);
685         }
686
687         pub enum MyEnum {
688             $0MyField(u8, u8),
689         }
690     }
691 }
692
693 fn another_fn() {
694     let m = my_mod::my_other_mod::MyEnum::MyField(1, 1);
695 }"#,
696             r#"use my_mod::my_other_mod::MyField;
697
698 mod my_mod {
699     use self::my_other_mod::MyField;
700
701     fn another_fn() {
702         let m = my_other_mod::MyEnum::MyField(MyField(1, 1));
703     }
704
705     pub mod my_other_mod {
706         fn another_fn() {
707             let m = MyEnum::MyField(MyField(1, 1));
708         }
709
710         pub struct MyField(pub u8, pub u8);
711
712         pub enum MyEnum {
713             MyField(MyField),
714         }
715     }
716 }
717
718 fn another_fn() {
719     let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1));
720 }"#,
721         );
722     }
723
724     #[test]
725     fn extract_record_fix_references() {
726         check_assist(
727             extract_struct_from_enum_variant,
728             r#"
729 enum E {
730     $0V { i: i32, j: i32 }
731 }
732
733 fn f() {
734     let E::V { i, j } = E::V { i: 9, j: 2 };
735 }
736 "#,
737             r#"
738 struct V{ i: i32, j: i32 }
739
740 enum E {
741     V(V)
742 }
743
744 fn f() {
745     let E::V(V { i, j }) = E::V(V { i: 9, j: 2 });
746 }
747 "#,
748         )
749     }
750
751     #[test]
752     fn extract_record_fix_references2() {
753         check_assist(
754             extract_struct_from_enum_variant,
755             r#"
756 enum E {
757     $0V(i32, i32)
758 }
759
760 fn f() {
761     let E::V(i, j) = E::V(9, 2);
762 }
763 "#,
764             r#"
765 struct V(i32, i32);
766
767 enum E {
768     V(V)
769 }
770
771 fn f() {
772     let E::V(V(i, j)) = E::V(V(9, 2));
773 }
774 "#,
775         )
776     }
777
778     #[test]
779     fn test_several_files() {
780         check_assist(
781             extract_struct_from_enum_variant,
782             r#"
783 //- /main.rs
784 enum E {
785     $0V(i32, i32)
786 }
787 mod foo;
788
789 //- /foo.rs
790 use crate::E;
791 fn f() {
792     let e = E::V(9, 2);
793 }
794 "#,
795             r#"
796 //- /main.rs
797 struct V(i32, i32);
798
799 enum E {
800     V(V)
801 }
802 mod foo;
803
804 //- /foo.rs
805 use crate::{E, V};
806 fn f() {
807     let e = E::V(V(9, 2));
808 }
809 "#,
810         )
811     }
812
813     #[test]
814     fn test_several_files_record() {
815         check_assist(
816             extract_struct_from_enum_variant,
817             r#"
818 //- /main.rs
819 enum E {
820     $0V { i: i32, j: i32 }
821 }
822 mod foo;
823
824 //- /foo.rs
825 use crate::E;
826 fn f() {
827     let e = E::V { i: 9, j: 2 };
828 }
829 "#,
830             r#"
831 //- /main.rs
832 struct V{ i: i32, j: i32 }
833
834 enum E {
835     V(V)
836 }
837 mod foo;
838
839 //- /foo.rs
840 use crate::{E, V};
841 fn f() {
842     let e = E::V(V { i: 9, j: 2 });
843 }
844 "#,
845         )
846     }
847
848     #[test]
849     fn test_extract_struct_record_nested_call_exp() {
850         check_assist(
851             extract_struct_from_enum_variant,
852             r#"
853 enum A { $0One { a: u32, b: u32 } }
854
855 struct B(A);
856
857 fn foo() {
858     let _ = B(A::One { a: 1, b: 2 });
859 }
860 "#,
861             r#"
862 struct One{ a: u32, b: u32 }
863
864 enum A { One(One) }
865
866 struct B(A);
867
868 fn foo() {
869     let _ = B(A::One(One { a: 1, b: 2 }));
870 }
871 "#,
872         );
873     }
874
875     #[test]
876     fn test_extract_enum_not_applicable_for_element_with_no_fields() {
877         check_assist_not_applicable(extract_struct_from_enum_variant, r#"enum A { $0One }"#);
878     }
879
880     #[test]
881     fn test_extract_enum_not_applicable_if_struct_exists() {
882         cov_mark::check!(test_extract_enum_not_applicable_if_struct_exists);
883         check_assist_not_applicable(
884             extract_struct_from_enum_variant,
885             r#"
886 struct One;
887 enum A { $0One(u8, u32) }
888 "#,
889         );
890     }
891
892     #[test]
893     fn test_extract_not_applicable_one_field() {
894         check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0One(u32) }");
895     }
896
897     #[test]
898     fn test_extract_not_applicable_no_field_tuple() {
899         check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None() }");
900     }
901
902     #[test]
903     fn test_extract_not_applicable_no_field_named() {
904         check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None {} }");
905     }
906 }