]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs
Rollup merge of #98391 - joboet:sgx_parker, r=m-ou-se
[rust.git] / src / tools / rust-analyzer / 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::mod_path_to_ast,
8     imports::insert_use::{insert_use, ImportScope, InsertUseConfig},
9     search::FileReference,
10     FxHashSet, RootDatabase,
11 };
12 use itertools::Itertools;
13 use syntax::{
14     ast::{
15         self, edit::IndentLevel, edit_in_place::Indent, make, AstNode, HasAttrs, HasGenericParams,
16         HasName, HasVisibility,
17     },
18     match_ast, ted, SyntaxElement,
19     SyntaxKind::*,
20     SyntaxNode, T,
21 };
22
23 use crate::{assist_context::SourceChangeBuilder, AssistContext, AssistId, AssistKind, Assists};
24
25 // Assist: extract_struct_from_enum_variant
26 //
27 // Extracts a struct from enum variant.
28 //
29 // ```
30 // enum A { $0One(u32, u32) }
31 // ```
32 // ->
33 // ```
34 // struct One(u32, u32);
35 //
36 // enum A { One(One) }
37 // ```
38 pub(crate) fn extract_struct_from_enum_variant(
39     acc: &mut Assists,
40     ctx: &AssistContext<'_>,
41 ) -> Option<()> {
42     let variant = ctx.find_node_at_offset::<ast::Variant>()?;
43     let field_list = extract_field_list_if_applicable(&variant)?;
44
45     let variant_name = variant.name()?;
46     let variant_hir = ctx.sema.to_def(&variant)?;
47     if existing_definition(ctx.db(), &variant_name, &variant_hir) {
48         cov_mark::hit!(test_extract_enum_not_applicable_if_struct_exists);
49         return None;
50     }
51
52     let enum_ast = variant.parent_enum();
53     let enum_hir = ctx.sema.to_def(&enum_ast)?;
54     let target = variant.syntax().text_range();
55     acc.add(
56         AssistId("extract_struct_from_enum_variant", AssistKind::RefactorRewrite),
57         "Extract struct from enum variant",
58         target,
59         |builder| {
60             let variant_hir_name = variant_hir.name(ctx.db());
61             let enum_module_def = ModuleDef::from(enum_hir);
62             let usages = Definition::Variant(variant_hir).usages(&ctx.sema).all();
63
64             let mut visited_modules_set = FxHashSet::default();
65             let current_module = enum_hir.module(ctx.db());
66             visited_modules_set.insert(current_module);
67             // record file references of the file the def resides in, we only want to swap to the edited file in the builder once
68             let mut def_file_references = None;
69             for (file_id, references) in usages {
70                 if file_id == ctx.file_id() {
71                     def_file_references = Some(references);
72                     continue;
73                 }
74                 builder.edit_file(file_id);
75                 let processed = process_references(
76                     ctx,
77                     builder,
78                     &mut visited_modules_set,
79                     &enum_module_def,
80                     &variant_hir_name,
81                     references,
82                 );
83                 processed.into_iter().for_each(|(path, node, import)| {
84                     apply_references(ctx.config.insert_use, path, node, import)
85                 });
86             }
87             builder.edit_file(ctx.file_id());
88
89             let variant = builder.make_mut(variant.clone());
90             if let Some(references) = def_file_references {
91                 let processed = process_references(
92                     ctx,
93                     builder,
94                     &mut visited_modules_set,
95                     &enum_module_def,
96                     &variant_hir_name,
97                     references,
98                 );
99                 processed.into_iter().for_each(|(path, node, import)| {
100                     apply_references(ctx.config.insert_use, path, node, import)
101                 });
102             }
103
104             let generic_params = enum_ast
105                 .generic_param_list()
106                 .and_then(|known_generics| extract_generic_params(&known_generics, &field_list));
107             let generics = generic_params.as_ref().map(|generics| generics.clone_for_update());
108             let def =
109                 create_struct_def(variant_name.clone(), &variant, &field_list, generics, &enum_ast);
110
111             let enum_ast = variant.parent_enum();
112             let indent = enum_ast.indent_level();
113             def.reindent_to(indent);
114
115             ted::insert_all(
116                 ted::Position::before(enum_ast.syntax()),
117                 vec![
118                     def.syntax().clone().into(),
119                     make::tokens::whitespace(&format!("\n\n{indent}")).into(),
120                 ],
121             );
122
123             update_variant(&variant, generic_params.map(|g| g.clone_for_update()));
124         },
125     )
126 }
127
128 fn extract_field_list_if_applicable(
129     variant: &ast::Variant,
130 ) -> Option<Either<ast::RecordFieldList, ast::TupleFieldList>> {
131     match variant.kind() {
132         ast::StructKind::Record(field_list) if field_list.fields().next().is_some() => {
133             Some(Either::Left(field_list))
134         }
135         ast::StructKind::Tuple(field_list) if field_list.fields().count() > 1 => {
136             Some(Either::Right(field_list))
137         }
138         _ => None,
139     }
140 }
141
142 fn existing_definition(db: &RootDatabase, variant_name: &ast::Name, variant: &Variant) -> bool {
143     variant
144         .parent_enum(db)
145         .module(db)
146         .scope(db, None)
147         .into_iter()
148         .filter(|(_, def)| match def {
149             // only check type-namespace
150             hir::ScopeDef::ModuleDef(def) => matches!(
151                 def,
152                 ModuleDef::Module(_)
153                     | ModuleDef::Adt(_)
154                     | ModuleDef::Variant(_)
155                     | ModuleDef::Trait(_)
156                     | ModuleDef::TypeAlias(_)
157                     | ModuleDef::BuiltinType(_)
158             ),
159             _ => false,
160         })
161         .any(|(name, _)| name.to_string() == variant_name.to_string())
162 }
163
164 fn extract_generic_params(
165     known_generics: &ast::GenericParamList,
166     field_list: &Either<ast::RecordFieldList, ast::TupleFieldList>,
167 ) -> Option<ast::GenericParamList> {
168     let mut generics = known_generics.generic_params().map(|param| (param, false)).collect_vec();
169
170     let tagged_one = match field_list {
171         Either::Left(field_list) => field_list
172             .fields()
173             .filter_map(|f| f.ty())
174             .fold(false, |tagged, ty| tag_generics_in_variant(&ty, &mut generics) || tagged),
175         Either::Right(field_list) => field_list
176             .fields()
177             .filter_map(|f| f.ty())
178             .fold(false, |tagged, ty| tag_generics_in_variant(&ty, &mut generics) || tagged),
179     };
180
181     let generics = generics.into_iter().filter_map(|(param, tag)| tag.then(|| param));
182     tagged_one.then(|| make::generic_param_list(generics))
183 }
184
185 fn tag_generics_in_variant(ty: &ast::Type, generics: &mut [(ast::GenericParam, bool)]) -> bool {
186     let mut tagged_one = false;
187
188     for token in ty.syntax().descendants_with_tokens().filter_map(SyntaxElement::into_token) {
189         for (param, tag) in generics.iter_mut().filter(|(_, tag)| !tag) {
190             match param {
191                 ast::GenericParam::LifetimeParam(lt)
192                     if matches!(token.kind(), T![lifetime_ident]) =>
193                 {
194                     if let Some(lt) = lt.lifetime() {
195                         if lt.text().as_str() == token.text() {
196                             *tag = true;
197                             tagged_one = true;
198                             break;
199                         }
200                     }
201                 }
202                 param if matches!(token.kind(), T![ident]) => {
203                     if match param {
204                         ast::GenericParam::ConstParam(konst) => konst
205                             .name()
206                             .map(|name| name.text().as_str() == token.text())
207                             .unwrap_or_default(),
208                         ast::GenericParam::TypeParam(ty) => ty
209                             .name()
210                             .map(|name| name.text().as_str() == token.text())
211                             .unwrap_or_default(),
212                         ast::GenericParam::LifetimeParam(lt) => lt
213                             .lifetime()
214                             .map(|lt| lt.text().as_str() == token.text())
215                             .unwrap_or_default(),
216                     } {
217                         *tag = true;
218                         tagged_one = true;
219                         break;
220                     }
221                 }
222                 _ => (),
223             }
224         }
225     }
226
227     tagged_one
228 }
229
230 fn create_struct_def(
231     name: ast::Name,
232     variant: &ast::Variant,
233     field_list: &Either<ast::RecordFieldList, ast::TupleFieldList>,
234     generics: Option<ast::GenericParamList>,
235     enum_: &ast::Enum,
236 ) -> ast::Struct {
237     let enum_vis = enum_.visibility();
238
239     let insert_vis = |node: &'_ SyntaxNode, vis: &'_ SyntaxNode| {
240         let vis = vis.clone_for_update();
241         ted::insert(ted::Position::before(node), vis);
242     };
243
244     // for fields without any existing visibility, use visibility of enum
245     let field_list: ast::FieldList = match field_list {
246         Either::Left(field_list) => {
247             let field_list = field_list.clone_for_update();
248
249             if let Some(vis) = &enum_vis {
250                 field_list
251                     .fields()
252                     .filter(|field| field.visibility().is_none())
253                     .filter_map(|field| field.name())
254                     .for_each(|it| insert_vis(it.syntax(), vis.syntax()));
255             }
256
257             field_list.into()
258         }
259         Either::Right(field_list) => {
260             let field_list = field_list.clone_for_update();
261
262             if let Some(vis) = &enum_vis {
263                 field_list
264                     .fields()
265                     .filter(|field| field.visibility().is_none())
266                     .filter_map(|field| field.ty())
267                     .for_each(|it| insert_vis(it.syntax(), vis.syntax()));
268             }
269
270             field_list.into()
271         }
272     };
273     field_list.reindent_to(IndentLevel::single());
274
275     let strukt = make::struct_(enum_vis, name, generics, field_list).clone_for_update();
276
277     // take comments from variant
278     ted::insert_all(
279         ted::Position::first_child_of(strukt.syntax()),
280         take_all_comments(variant.syntax()),
281     );
282
283     // copy attributes from enum
284     ted::insert_all(
285         ted::Position::first_child_of(strukt.syntax()),
286         enum_
287             .attrs()
288             .flat_map(|it| {
289                 vec![it.syntax().clone_for_update().into(), make::tokens::single_newline().into()]
290             })
291             .collect(),
292     );
293
294     strukt
295 }
296
297 fn update_variant(variant: &ast::Variant, generics: Option<ast::GenericParamList>) -> Option<()> {
298     let name = variant.name()?;
299     let generic_args = generics
300         .filter(|generics| generics.generic_params().count() > 0)
301         .map(|generics| generics.to_generic_args());
302     // FIXME: replace with a `ast::make` constructor
303     let ty = match generic_args {
304         Some(generic_args) => make::ty(&format!("{name}{generic_args}")),
305         None => make::ty(&name.text()),
306     };
307
308     // change from a record to a tuple field list
309     let tuple_field = make::tuple_field(None, ty);
310     let field_list = make::tuple_field_list(iter::once(tuple_field)).clone_for_update();
311     ted::replace(variant.field_list()?.syntax(), field_list.syntax());
312
313     // remove any ws after the name
314     if let Some(ws) = name
315         .syntax()
316         .siblings_with_tokens(syntax::Direction::Next)
317         .find_map(|tok| tok.into_token().filter(|tok| tok.kind() == WHITESPACE))
318     {
319         ted::remove(SyntaxElement::Token(ws));
320     }
321
322     Some(())
323 }
324
325 // Note: this also detaches whitespace after comments,
326 // since `SyntaxNode::splice_children` (and by extension `ted::insert_all_raw`)
327 // detaches nodes. If we only took the comments, we'd leave behind the old whitespace.
328 fn take_all_comments(node: &SyntaxNode) -> Vec<SyntaxElement> {
329     let mut remove_next_ws = false;
330     node.children_with_tokens()
331         .filter_map(move |child| match child.kind() {
332             COMMENT => {
333                 remove_next_ws = true;
334                 child.detach();
335                 Some(child)
336             }
337             WHITESPACE if remove_next_ws => {
338                 remove_next_ws = false;
339                 child.detach();
340                 Some(make::tokens::single_newline().into())
341             }
342             _ => {
343                 remove_next_ws = false;
344                 None
345             }
346         })
347         .collect()
348 }
349
350 fn apply_references(
351     insert_use_cfg: InsertUseConfig,
352     segment: ast::PathSegment,
353     node: SyntaxNode,
354     import: Option<(ImportScope, hir::ModPath)>,
355 ) {
356     if let Some((scope, path)) = import {
357         insert_use(&scope, mod_path_to_ast(&path), &insert_use_cfg);
358     }
359     // deep clone to prevent cycle
360     let path = make::path_from_segments(iter::once(segment.clone_subtree()), false);
361     ted::insert_raw(ted::Position::before(segment.syntax()), path.clone_for_update().syntax());
362     ted::insert_raw(ted::Position::before(segment.syntax()), make::token(T!['(']));
363     ted::insert_raw(ted::Position::after(&node), make::token(T![')']));
364 }
365
366 fn process_references(
367     ctx: &AssistContext<'_>,
368     builder: &mut SourceChangeBuilder,
369     visited_modules: &mut FxHashSet<Module>,
370     enum_module_def: &ModuleDef,
371     variant_hir_name: &Name,
372     refs: Vec<FileReference>,
373 ) -> Vec<(ast::PathSegment, SyntaxNode, Option<(ImportScope, hir::ModPath)>)> {
374     // we have to recollect here eagerly as we are about to edit the tree we need to calculate the changes
375     // and corresponding nodes up front
376     refs.into_iter()
377         .flat_map(|reference| {
378             let (segment, scope_node, module) = reference_to_node(&ctx.sema, reference)?;
379             let segment = builder.make_mut(segment);
380             let scope_node = builder.make_syntax_mut(scope_node);
381             if !visited_modules.contains(&module) {
382                 let mod_path = module.find_use_path_prefixed(
383                     ctx.sema.db,
384                     *enum_module_def,
385                     ctx.config.insert_use.prefix_kind,
386                     ctx.config.prefer_no_std,
387                 );
388                 if let Some(mut mod_path) = mod_path {
389                     mod_path.pop_segment();
390                     mod_path.push_segment(variant_hir_name.clone());
391                     let scope = ImportScope::find_insert_use_container(&scope_node, &ctx.sema)?;
392                     visited_modules.insert(module);
393                     return Some((segment, scope_node, Some((scope, mod_path))));
394                 }
395             }
396             Some((segment, scope_node, None))
397         })
398         .collect()
399 }
400
401 fn reference_to_node(
402     sema: &hir::Semantics<'_, RootDatabase>,
403     reference: FileReference,
404 ) -> Option<(ast::PathSegment, SyntaxNode, hir::Module)> {
405     let segment =
406         reference.name.as_name_ref()?.syntax().parent().and_then(ast::PathSegment::cast)?;
407     let parent = segment.parent_path().syntax().parent()?;
408     let expr_or_pat = match_ast! {
409         match parent {
410             ast::PathExpr(_it) => parent.parent()?,
411             ast::RecordExpr(_it) => parent,
412             ast::TupleStructPat(_it) => parent,
413             ast::RecordPat(_it) => parent,
414             _ => return None,
415         }
416     };
417     let module = sema.scope(&expr_or_pat)?.module();
418     Some((segment, expr_or_pat, module))
419 }
420
421 #[cfg(test)]
422 mod tests {
423     use crate::tests::{check_assist, check_assist_not_applicable};
424
425     use super::*;
426
427     #[test]
428     fn test_extract_struct_several_fields_tuple() {
429         check_assist(
430             extract_struct_from_enum_variant,
431             "enum A { $0One(u32, u32) }",
432             r#"struct One(u32, u32);
433
434 enum A { One(One) }"#,
435         );
436     }
437
438     #[test]
439     fn test_extract_struct_several_fields_named() {
440         check_assist(
441             extract_struct_from_enum_variant,
442             "enum A { $0One { foo: u32, bar: u32 } }",
443             r#"struct One{ foo: u32, bar: u32 }
444
445 enum A { One(One) }"#,
446         );
447     }
448
449     #[test]
450     fn test_extract_struct_one_field_named() {
451         check_assist(
452             extract_struct_from_enum_variant,
453             "enum A { $0One { foo: u32 } }",
454             r#"struct One{ foo: u32 }
455
456 enum A { One(One) }"#,
457         );
458     }
459
460     #[test]
461     fn test_extract_struct_carries_over_generics() {
462         check_assist(
463             extract_struct_from_enum_variant,
464             r"enum En<T> { Var { a: T$0 } }",
465             r#"struct Var<T>{ a: T }
466
467 enum En<T> { Var(Var<T>) }"#,
468         );
469     }
470
471     #[test]
472     fn test_extract_struct_carries_over_attributes() {
473         check_assist(
474             extract_struct_from_enum_variant,
475             r#"
476 #[derive(Debug)]
477 #[derive(Clone)]
478 enum Enum { Variant{ field: u32$0 } }"#,
479             r#"
480 #[derive(Debug)]
481 #[derive(Clone)]
482 struct Variant{ field: u32 }
483
484 #[derive(Debug)]
485 #[derive(Clone)]
486 enum Enum { Variant(Variant) }"#,
487         );
488     }
489
490     #[test]
491     fn test_extract_struct_indent_to_parent_enum() {
492         check_assist(
493             extract_struct_from_enum_variant,
494             r#"
495 enum Enum {
496     Variant {
497         field: u32$0
498     }
499 }"#,
500             r#"
501 struct Variant{
502     field: u32
503 }
504
505 enum Enum {
506     Variant(Variant)
507 }"#,
508         );
509     }
510
511     #[test]
512     fn test_extract_struct_indent_to_parent_enum_in_mod() {
513         check_assist(
514             extract_struct_from_enum_variant,
515             r#"
516 mod indenting {
517     enum Enum {
518         Variant {
519             field: u32$0
520         }
521     }
522 }"#,
523             r#"
524 mod indenting {
525     struct Variant{
526         field: u32
527     }
528
529     enum Enum {
530         Variant(Variant)
531     }
532 }"#,
533         );
534     }
535
536     #[test]
537     fn test_extract_struct_keep_comments_and_attrs_one_field_named() {
538         check_assist(
539             extract_struct_from_enum_variant,
540             r#"
541 enum A {
542     $0One {
543         // leading comment
544         /// doc comment
545         #[an_attr]
546         foo: u32
547         // trailing comment
548     }
549 }"#,
550             r#"
551 struct One{
552     // leading comment
553     /// doc comment
554     #[an_attr]
555     foo: u32
556     // trailing comment
557 }
558
559 enum A {
560     One(One)
561 }"#,
562         );
563     }
564
565     #[test]
566     fn test_extract_struct_keep_comments_and_attrs_several_fields_named() {
567         check_assist(
568             extract_struct_from_enum_variant,
569             r#"
570 enum A {
571     $0One {
572         // comment
573         /// doc
574         #[attr]
575         foo: u32,
576         // comment
577         #[attr]
578         /// doc
579         bar: u32
580     }
581 }"#,
582             r#"
583 struct One{
584     // comment
585     /// doc
586     #[attr]
587     foo: u32,
588     // comment
589     #[attr]
590     /// doc
591     bar: u32
592 }
593
594 enum A {
595     One(One)
596 }"#,
597         );
598     }
599
600     #[test]
601     fn test_extract_struct_keep_comments_and_attrs_several_fields_tuple() {
602         check_assist(
603             extract_struct_from_enum_variant,
604             "enum A { $0One(/* comment */ #[attr] u32, /* another */ u32 /* tail */) }",
605             r#"
606 struct One(/* comment */ #[attr] u32, /* another */ u32 /* tail */);
607
608 enum A { One(One) }"#,
609         );
610     }
611
612     #[test]
613     fn test_extract_struct_move_struct_variant_comments() {
614         check_assist(
615             extract_struct_from_enum_variant,
616             r#"
617 enum A {
618     /* comment */
619     // other
620     /// comment
621     #[attr]
622     $0One {
623         a: u32
624     }
625 }"#,
626             r#"
627 /* comment */
628 // other
629 /// comment
630 struct One{
631     a: u32
632 }
633
634 enum A {
635     #[attr]
636     One(One)
637 }"#,
638         );
639     }
640
641     #[test]
642     fn test_extract_struct_move_tuple_variant_comments() {
643         check_assist(
644             extract_struct_from_enum_variant,
645             r#"
646 enum A {
647     /* comment */
648     // other
649     /// comment
650     #[attr]
651     $0One(u32, u32)
652 }"#,
653             r#"
654 /* comment */
655 // other
656 /// comment
657 struct One(u32, u32);
658
659 enum A {
660     #[attr]
661     One(One)
662 }"#,
663         );
664     }
665
666     #[test]
667     fn test_extract_struct_keep_existing_visibility_named() {
668         check_assist(
669             extract_struct_from_enum_variant,
670             "enum A { $0One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 } }",
671             r#"
672 struct One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 }
673
674 enum A { One(One) }"#,
675         );
676     }
677
678     #[test]
679     fn test_extract_struct_keep_existing_visibility_tuple() {
680         check_assist(
681             extract_struct_from_enum_variant,
682             "enum A { $0One(u32, pub(crate) u32, pub(super) u32, u32) }",
683             r#"
684 struct One(u32, pub(crate) u32, pub(super) u32, u32);
685
686 enum A { One(One) }"#,
687         );
688     }
689
690     #[test]
691     fn test_extract_enum_variant_name_value_namespace() {
692         check_assist(
693             extract_struct_from_enum_variant,
694             r#"const One: () = ();
695 enum A { $0One(u32, u32) }"#,
696             r#"const One: () = ();
697 struct One(u32, u32);
698
699 enum A { One(One) }"#,
700         );
701     }
702
703     #[test]
704     fn test_extract_struct_no_visibility() {
705         check_assist(
706             extract_struct_from_enum_variant,
707             "enum A { $0One(u32, u32) }",
708             r#"
709 struct One(u32, u32);
710
711 enum A { One(One) }"#,
712         );
713     }
714
715     #[test]
716     fn test_extract_struct_pub_visibility() {
717         check_assist(
718             extract_struct_from_enum_variant,
719             "pub enum A { $0One(u32, u32) }",
720             r#"
721 pub struct One(pub u32, pub u32);
722
723 pub enum A { One(One) }"#,
724         );
725     }
726
727     #[test]
728     fn test_extract_struct_pub_in_mod_visibility() {
729         check_assist(
730             extract_struct_from_enum_variant,
731             "pub(in something) enum A { $0One{ a: u32, b: u32 } }",
732             r#"
733 pub(in something) struct One{ pub(in something) a: u32, pub(in something) b: u32 }
734
735 pub(in something) enum A { One(One) }"#,
736         );
737     }
738
739     #[test]
740     fn test_extract_struct_pub_crate_visibility() {
741         check_assist(
742             extract_struct_from_enum_variant,
743             "pub(crate) enum A { $0One{ a: u32, b: u32, c: u32 } }",
744             r#"
745 pub(crate) struct One{ pub(crate) a: u32, pub(crate) b: u32, pub(crate) c: u32 }
746
747 pub(crate) enum A { One(One) }"#,
748         );
749     }
750
751     #[test]
752     fn test_extract_struct_with_complex_imports() {
753         check_assist(
754             extract_struct_from_enum_variant,
755             r#"mod my_mod {
756     fn another_fn() {
757         let m = my_other_mod::MyEnum::MyField(1, 1);
758     }
759
760     pub mod my_other_mod {
761         fn another_fn() {
762             let m = MyEnum::MyField(1, 1);
763         }
764
765         pub enum MyEnum {
766             $0MyField(u8, u8),
767         }
768     }
769 }
770
771 fn another_fn() {
772     let m = my_mod::my_other_mod::MyEnum::MyField(1, 1);
773 }"#,
774             r#"use my_mod::my_other_mod::MyField;
775
776 mod my_mod {
777     use self::my_other_mod::MyField;
778
779     fn another_fn() {
780         let m = my_other_mod::MyEnum::MyField(MyField(1, 1));
781     }
782
783     pub mod my_other_mod {
784         fn another_fn() {
785             let m = MyEnum::MyField(MyField(1, 1));
786         }
787
788         pub struct MyField(pub u8, pub u8);
789
790         pub enum MyEnum {
791             MyField(MyField),
792         }
793     }
794 }
795
796 fn another_fn() {
797     let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1));
798 }"#,
799         );
800     }
801
802     #[test]
803     fn extract_record_fix_references() {
804         check_assist(
805             extract_struct_from_enum_variant,
806             r#"
807 enum E {
808     $0V { i: i32, j: i32 }
809 }
810
811 fn f() {
812     let E::V { i, j } = E::V { i: 9, j: 2 };
813 }
814 "#,
815             r#"
816 struct V{ i: i32, j: i32 }
817
818 enum E {
819     V(V)
820 }
821
822 fn f() {
823     let E::V(V { i, j }) = E::V(V { i: 9, j: 2 });
824 }
825 "#,
826         )
827     }
828
829     #[test]
830     fn extract_record_fix_references2() {
831         check_assist(
832             extract_struct_from_enum_variant,
833             r#"
834 enum E {
835     $0V(i32, i32)
836 }
837
838 fn f() {
839     let E::V(i, j) = E::V(9, 2);
840 }
841 "#,
842             r#"
843 struct V(i32, i32);
844
845 enum E {
846     V(V)
847 }
848
849 fn f() {
850     let E::V(V(i, j)) = E::V(V(9, 2));
851 }
852 "#,
853         )
854     }
855
856     #[test]
857     fn test_several_files() {
858         check_assist(
859             extract_struct_from_enum_variant,
860             r#"
861 //- /main.rs
862 enum E {
863     $0V(i32, i32)
864 }
865 mod foo;
866
867 //- /foo.rs
868 use crate::E;
869 fn f() {
870     let e = E::V(9, 2);
871 }
872 "#,
873             r#"
874 //- /main.rs
875 struct V(i32, i32);
876
877 enum E {
878     V(V)
879 }
880 mod foo;
881
882 //- /foo.rs
883 use crate::{E, V};
884 fn f() {
885     let e = E::V(V(9, 2));
886 }
887 "#,
888         )
889     }
890
891     #[test]
892     fn test_several_files_record() {
893         check_assist(
894             extract_struct_from_enum_variant,
895             r#"
896 //- /main.rs
897 enum E {
898     $0V { i: i32, j: i32 }
899 }
900 mod foo;
901
902 //- /foo.rs
903 use crate::E;
904 fn f() {
905     let e = E::V { i: 9, j: 2 };
906 }
907 "#,
908             r#"
909 //- /main.rs
910 struct V{ i: i32, j: i32 }
911
912 enum E {
913     V(V)
914 }
915 mod foo;
916
917 //- /foo.rs
918 use crate::{E, V};
919 fn f() {
920     let e = E::V(V { i: 9, j: 2 });
921 }
922 "#,
923         )
924     }
925
926     #[test]
927     fn test_extract_struct_record_nested_call_exp() {
928         check_assist(
929             extract_struct_from_enum_variant,
930             r#"
931 enum A { $0One { a: u32, b: u32 } }
932
933 struct B(A);
934
935 fn foo() {
936     let _ = B(A::One { a: 1, b: 2 });
937 }
938 "#,
939             r#"
940 struct One{ a: u32, b: u32 }
941
942 enum A { One(One) }
943
944 struct B(A);
945
946 fn foo() {
947     let _ = B(A::One(One { a: 1, b: 2 }));
948 }
949 "#,
950         );
951     }
952
953     #[test]
954     fn test_extract_enum_not_applicable_for_element_with_no_fields() {
955         check_assist_not_applicable(extract_struct_from_enum_variant, r#"enum A { $0One }"#);
956     }
957
958     #[test]
959     fn test_extract_enum_not_applicable_if_struct_exists() {
960         cov_mark::check!(test_extract_enum_not_applicable_if_struct_exists);
961         check_assist_not_applicable(
962             extract_struct_from_enum_variant,
963             r#"
964 struct One;
965 enum A { $0One(u8, u32) }
966 "#,
967         );
968     }
969
970     #[test]
971     fn test_extract_not_applicable_one_field() {
972         check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0One(u32) }");
973     }
974
975     #[test]
976     fn test_extract_not_applicable_no_field_tuple() {
977         check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None() }");
978     }
979
980     #[test]
981     fn test_extract_not_applicable_no_field_named() {
982         check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None {} }");
983     }
984
985     #[test]
986     fn test_extract_struct_only_copies_needed_generics() {
987         check_assist(
988             extract_struct_from_enum_variant,
989             r#"
990 enum X<'a, 'b, 'x> {
991     $0A { a: &'a &'x mut () },
992     B { b: &'b () },
993     C { c: () },
994 }
995 "#,
996             r#"
997 struct A<'a, 'x>{ a: &'a &'x mut () }
998
999 enum X<'a, 'b, 'x> {
1000     A(A<'a, 'x>),
1001     B { b: &'b () },
1002     C { c: () },
1003 }
1004 "#,
1005         );
1006     }
1007
1008     #[test]
1009     fn test_extract_struct_with_liftime_type_const() {
1010         check_assist(
1011             extract_struct_from_enum_variant,
1012             r#"
1013 enum X<'b, T, V, const C: usize> {
1014     $0A { a: T, b: X<'b>, c: [u8; C] },
1015     D { d: V },
1016 }
1017 "#,
1018             r#"
1019 struct A<'b, T, const C: usize>{ a: T, b: X<'b>, c: [u8; C] }
1020
1021 enum X<'b, T, V, const C: usize> {
1022     A(A<'b, T, C>),
1023     D { d: V },
1024 }
1025 "#,
1026         );
1027     }
1028
1029     #[test]
1030     fn test_extract_struct_without_generics() {
1031         check_assist(
1032             extract_struct_from_enum_variant,
1033             r#"
1034 enum X<'a, 'b> {
1035     A { a: &'a () },
1036     B { b: &'b () },
1037     $0C { c: () },
1038 }
1039 "#,
1040             r#"
1041 struct C{ c: () }
1042
1043 enum X<'a, 'b> {
1044     A { a: &'a () },
1045     B { b: &'b () },
1046     C(C),
1047 }
1048 "#,
1049         );
1050     }
1051
1052     #[test]
1053     fn test_extract_struct_keeps_trait_bounds() {
1054         check_assist(
1055             extract_struct_from_enum_variant,
1056             r#"
1057 enum En<T: TraitT, V: TraitV> {
1058     $0A { a: T },
1059     B { b: V },
1060 }
1061 "#,
1062             r#"
1063 struct A<T: TraitT>{ a: T }
1064
1065 enum En<T: TraitT, V: TraitV> {
1066     A(A<T>),
1067     B { b: V },
1068 }
1069 "#,
1070         );
1071     }
1072 }