]> 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 #99460 - JanBeh:PR_asref_asmut_docs, r=joshtriplett
[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, Position};
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 ty = generics
300         .filter(|generics| generics.generic_params().count() > 0)
301         .map(|generics| {
302             let mut generic_str = String::with_capacity(8);
303
304             for (p, more) in generics.generic_params().with_position().map(|p| match p {
305                 Position::First(p) | Position::Middle(p) => (p, true),
306                 Position::Last(p) | Position::Only(p) => (p, false),
307             }) {
308                 match p {
309                     ast::GenericParam::ConstParam(konst) => {
310                         if let Some(name) = konst.name() {
311                             generic_str.push_str(name.text().as_str());
312                         }
313                     }
314                     ast::GenericParam::LifetimeParam(lt) => {
315                         if let Some(lt) = lt.lifetime() {
316                             generic_str.push_str(lt.text().as_str());
317                         }
318                     }
319                     ast::GenericParam::TypeParam(ty) => {
320                         if let Some(name) = ty.name() {
321                             generic_str.push_str(name.text().as_str());
322                         }
323                     }
324                 }
325                 if more {
326                     generic_str.push_str(", ");
327                 }
328             }
329
330             make::ty(&format!("{}<{}>", &name.text(), &generic_str))
331         })
332         .unwrap_or_else(|| make::ty(&name.text()));
333
334     // change from a record to a tuple field list
335     let tuple_field = make::tuple_field(None, ty);
336     let field_list = make::tuple_field_list(iter::once(tuple_field)).clone_for_update();
337     ted::replace(variant.field_list()?.syntax(), field_list.syntax());
338
339     // remove any ws after the name
340     if let Some(ws) = name
341         .syntax()
342         .siblings_with_tokens(syntax::Direction::Next)
343         .find_map(|tok| tok.into_token().filter(|tok| tok.kind() == WHITESPACE))
344     {
345         ted::remove(SyntaxElement::Token(ws));
346     }
347
348     Some(())
349 }
350
351 // Note: this also detaches whitespace after comments,
352 // since `SyntaxNode::splice_children` (and by extension `ted::insert_all_raw`)
353 // detaches nodes. If we only took the comments, we'd leave behind the old whitespace.
354 fn take_all_comments(node: &SyntaxNode) -> Vec<SyntaxElement> {
355     let mut remove_next_ws = false;
356     node.children_with_tokens()
357         .filter_map(move |child| match child.kind() {
358             COMMENT => {
359                 remove_next_ws = true;
360                 child.detach();
361                 Some(child)
362             }
363             WHITESPACE if remove_next_ws => {
364                 remove_next_ws = false;
365                 child.detach();
366                 Some(make::tokens::single_newline().into())
367             }
368             _ => {
369                 remove_next_ws = false;
370                 None
371             }
372         })
373         .collect()
374 }
375
376 fn apply_references(
377     insert_use_cfg: InsertUseConfig,
378     segment: ast::PathSegment,
379     node: SyntaxNode,
380     import: Option<(ImportScope, hir::ModPath)>,
381 ) {
382     if let Some((scope, path)) = import {
383         insert_use(&scope, mod_path_to_ast(&path), &insert_use_cfg);
384     }
385     // deep clone to prevent cycle
386     let path = make::path_from_segments(iter::once(segment.clone_subtree()), false);
387     ted::insert_raw(ted::Position::before(segment.syntax()), path.clone_for_update().syntax());
388     ted::insert_raw(ted::Position::before(segment.syntax()), make::token(T!['(']));
389     ted::insert_raw(ted::Position::after(&node), make::token(T![')']));
390 }
391
392 fn process_references(
393     ctx: &AssistContext<'_>,
394     builder: &mut SourceChangeBuilder,
395     visited_modules: &mut FxHashSet<Module>,
396     enum_module_def: &ModuleDef,
397     variant_hir_name: &Name,
398     refs: Vec<FileReference>,
399 ) -> Vec<(ast::PathSegment, SyntaxNode, Option<(ImportScope, hir::ModPath)>)> {
400     // we have to recollect here eagerly as we are about to edit the tree we need to calculate the changes
401     // and corresponding nodes up front
402     refs.into_iter()
403         .flat_map(|reference| {
404             let (segment, scope_node, module) = reference_to_node(&ctx.sema, reference)?;
405             let segment = builder.make_mut(segment);
406             let scope_node = builder.make_syntax_mut(scope_node);
407             if !visited_modules.contains(&module) {
408                 let mod_path = module.find_use_path_prefixed(
409                     ctx.sema.db,
410                     *enum_module_def,
411                     ctx.config.insert_use.prefix_kind,
412                     ctx.config.prefer_no_std,
413                 );
414                 if let Some(mut mod_path) = mod_path {
415                     mod_path.pop_segment();
416                     mod_path.push_segment(variant_hir_name.clone());
417                     let scope = ImportScope::find_insert_use_container(&scope_node, &ctx.sema)?;
418                     visited_modules.insert(module);
419                     return Some((segment, scope_node, Some((scope, mod_path))));
420                 }
421             }
422             Some((segment, scope_node, None))
423         })
424         .collect()
425 }
426
427 fn reference_to_node(
428     sema: &hir::Semantics<'_, RootDatabase>,
429     reference: FileReference,
430 ) -> Option<(ast::PathSegment, SyntaxNode, hir::Module)> {
431     let segment =
432         reference.name.as_name_ref()?.syntax().parent().and_then(ast::PathSegment::cast)?;
433     let parent = segment.parent_path().syntax().parent()?;
434     let expr_or_pat = match_ast! {
435         match parent {
436             ast::PathExpr(_it) => parent.parent()?,
437             ast::RecordExpr(_it) => parent,
438             ast::TupleStructPat(_it) => parent,
439             ast::RecordPat(_it) => parent,
440             _ => return None,
441         }
442     };
443     let module = sema.scope(&expr_or_pat)?.module();
444     Some((segment, expr_or_pat, module))
445 }
446
447 #[cfg(test)]
448 mod tests {
449     use crate::tests::{check_assist, check_assist_not_applicable};
450
451     use super::*;
452
453     #[test]
454     fn test_extract_struct_several_fields_tuple() {
455         check_assist(
456             extract_struct_from_enum_variant,
457             "enum A { $0One(u32, u32) }",
458             r#"struct One(u32, u32);
459
460 enum A { One(One) }"#,
461         );
462     }
463
464     #[test]
465     fn test_extract_struct_several_fields_named() {
466         check_assist(
467             extract_struct_from_enum_variant,
468             "enum A { $0One { foo: u32, bar: u32 } }",
469             r#"struct One{ foo: u32, bar: u32 }
470
471 enum A { One(One) }"#,
472         );
473     }
474
475     #[test]
476     fn test_extract_struct_one_field_named() {
477         check_assist(
478             extract_struct_from_enum_variant,
479             "enum A { $0One { foo: u32 } }",
480             r#"struct One{ foo: u32 }
481
482 enum A { One(One) }"#,
483         );
484     }
485
486     #[test]
487     fn test_extract_struct_carries_over_generics() {
488         check_assist(
489             extract_struct_from_enum_variant,
490             r"enum En<T> { Var { a: T$0 } }",
491             r#"struct Var<T>{ a: T }
492
493 enum En<T> { Var(Var<T>) }"#,
494         );
495     }
496
497     #[test]
498     fn test_extract_struct_carries_over_attributes() {
499         check_assist(
500             extract_struct_from_enum_variant,
501             r#"
502 #[derive(Debug)]
503 #[derive(Clone)]
504 enum Enum { Variant{ field: u32$0 } }"#,
505             r#"
506 #[derive(Debug)]
507 #[derive(Clone)]
508 struct Variant{ field: u32 }
509
510 #[derive(Debug)]
511 #[derive(Clone)]
512 enum Enum { Variant(Variant) }"#,
513         );
514     }
515
516     #[test]
517     fn test_extract_struct_indent_to_parent_enum() {
518         check_assist(
519             extract_struct_from_enum_variant,
520             r#"
521 enum Enum {
522     Variant {
523         field: u32$0
524     }
525 }"#,
526             r#"
527 struct Variant{
528     field: u32
529 }
530
531 enum Enum {
532     Variant(Variant)
533 }"#,
534         );
535     }
536
537     #[test]
538     fn test_extract_struct_indent_to_parent_enum_in_mod() {
539         check_assist(
540             extract_struct_from_enum_variant,
541             r#"
542 mod indenting {
543     enum Enum {
544         Variant {
545             field: u32$0
546         }
547     }
548 }"#,
549             r#"
550 mod indenting {
551     struct Variant{
552         field: u32
553     }
554
555     enum Enum {
556         Variant(Variant)
557     }
558 }"#,
559         );
560     }
561
562     #[test]
563     fn test_extract_struct_keep_comments_and_attrs_one_field_named() {
564         check_assist(
565             extract_struct_from_enum_variant,
566             r#"
567 enum A {
568     $0One {
569         // leading comment
570         /// doc comment
571         #[an_attr]
572         foo: u32
573         // trailing comment
574     }
575 }"#,
576             r#"
577 struct One{
578     // leading comment
579     /// doc comment
580     #[an_attr]
581     foo: u32
582     // trailing comment
583 }
584
585 enum A {
586     One(One)
587 }"#,
588         );
589     }
590
591     #[test]
592     fn test_extract_struct_keep_comments_and_attrs_several_fields_named() {
593         check_assist(
594             extract_struct_from_enum_variant,
595             r#"
596 enum A {
597     $0One {
598         // comment
599         /// doc
600         #[attr]
601         foo: u32,
602         // comment
603         #[attr]
604         /// doc
605         bar: u32
606     }
607 }"#,
608             r#"
609 struct One{
610     // comment
611     /// doc
612     #[attr]
613     foo: u32,
614     // comment
615     #[attr]
616     /// doc
617     bar: u32
618 }
619
620 enum A {
621     One(One)
622 }"#,
623         );
624     }
625
626     #[test]
627     fn test_extract_struct_keep_comments_and_attrs_several_fields_tuple() {
628         check_assist(
629             extract_struct_from_enum_variant,
630             "enum A { $0One(/* comment */ #[attr] u32, /* another */ u32 /* tail */) }",
631             r#"
632 struct One(/* comment */ #[attr] u32, /* another */ u32 /* tail */);
633
634 enum A { One(One) }"#,
635         );
636     }
637
638     #[test]
639     fn test_extract_struct_move_struct_variant_comments() {
640         check_assist(
641             extract_struct_from_enum_variant,
642             r#"
643 enum A {
644     /* comment */
645     // other
646     /// comment
647     #[attr]
648     $0One {
649         a: u32
650     }
651 }"#,
652             r#"
653 /* comment */
654 // other
655 /// comment
656 struct One{
657     a: u32
658 }
659
660 enum A {
661     #[attr]
662     One(One)
663 }"#,
664         );
665     }
666
667     #[test]
668     fn test_extract_struct_move_tuple_variant_comments() {
669         check_assist(
670             extract_struct_from_enum_variant,
671             r#"
672 enum A {
673     /* comment */
674     // other
675     /// comment
676     #[attr]
677     $0One(u32, u32)
678 }"#,
679             r#"
680 /* comment */
681 // other
682 /// comment
683 struct One(u32, u32);
684
685 enum A {
686     #[attr]
687     One(One)
688 }"#,
689         );
690     }
691
692     #[test]
693     fn test_extract_struct_keep_existing_visibility_named() {
694         check_assist(
695             extract_struct_from_enum_variant,
696             "enum A { $0One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 } }",
697             r#"
698 struct One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 }
699
700 enum A { One(One) }"#,
701         );
702     }
703
704     #[test]
705     fn test_extract_struct_keep_existing_visibility_tuple() {
706         check_assist(
707             extract_struct_from_enum_variant,
708             "enum A { $0One(u32, pub(crate) u32, pub(super) u32, u32) }",
709             r#"
710 struct One(u32, pub(crate) u32, pub(super) u32, u32);
711
712 enum A { One(One) }"#,
713         );
714     }
715
716     #[test]
717     fn test_extract_enum_variant_name_value_namespace() {
718         check_assist(
719             extract_struct_from_enum_variant,
720             r#"const One: () = ();
721 enum A { $0One(u32, u32) }"#,
722             r#"const One: () = ();
723 struct One(u32, u32);
724
725 enum A { One(One) }"#,
726         );
727     }
728
729     #[test]
730     fn test_extract_struct_no_visibility() {
731         check_assist(
732             extract_struct_from_enum_variant,
733             "enum A { $0One(u32, u32) }",
734             r#"
735 struct One(u32, u32);
736
737 enum A { One(One) }"#,
738         );
739     }
740
741     #[test]
742     fn test_extract_struct_pub_visibility() {
743         check_assist(
744             extract_struct_from_enum_variant,
745             "pub enum A { $0One(u32, u32) }",
746             r#"
747 pub struct One(pub u32, pub u32);
748
749 pub enum A { One(One) }"#,
750         );
751     }
752
753     #[test]
754     fn test_extract_struct_pub_in_mod_visibility() {
755         check_assist(
756             extract_struct_from_enum_variant,
757             "pub(in something) enum A { $0One{ a: u32, b: u32 } }",
758             r#"
759 pub(in something) struct One{ pub(in something) a: u32, pub(in something) b: u32 }
760
761 pub(in something) enum A { One(One) }"#,
762         );
763     }
764
765     #[test]
766     fn test_extract_struct_pub_crate_visibility() {
767         check_assist(
768             extract_struct_from_enum_variant,
769             "pub(crate) enum A { $0One{ a: u32, b: u32, c: u32 } }",
770             r#"
771 pub(crate) struct One{ pub(crate) a: u32, pub(crate) b: u32, pub(crate) c: u32 }
772
773 pub(crate) enum A { One(One) }"#,
774         );
775     }
776
777     #[test]
778     fn test_extract_struct_with_complex_imports() {
779         check_assist(
780             extract_struct_from_enum_variant,
781             r#"mod my_mod {
782     fn another_fn() {
783         let m = my_other_mod::MyEnum::MyField(1, 1);
784     }
785
786     pub mod my_other_mod {
787         fn another_fn() {
788             let m = MyEnum::MyField(1, 1);
789         }
790
791         pub enum MyEnum {
792             $0MyField(u8, u8),
793         }
794     }
795 }
796
797 fn another_fn() {
798     let m = my_mod::my_other_mod::MyEnum::MyField(1, 1);
799 }"#,
800             r#"use my_mod::my_other_mod::MyField;
801
802 mod my_mod {
803     use self::my_other_mod::MyField;
804
805     fn another_fn() {
806         let m = my_other_mod::MyEnum::MyField(MyField(1, 1));
807     }
808
809     pub mod my_other_mod {
810         fn another_fn() {
811             let m = MyEnum::MyField(MyField(1, 1));
812         }
813
814         pub struct MyField(pub u8, pub u8);
815
816         pub enum MyEnum {
817             MyField(MyField),
818         }
819     }
820 }
821
822 fn another_fn() {
823     let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1));
824 }"#,
825         );
826     }
827
828     #[test]
829     fn extract_record_fix_references() {
830         check_assist(
831             extract_struct_from_enum_variant,
832             r#"
833 enum E {
834     $0V { i: i32, j: i32 }
835 }
836
837 fn f() {
838     let E::V { i, j } = E::V { i: 9, j: 2 };
839 }
840 "#,
841             r#"
842 struct V{ i: i32, j: i32 }
843
844 enum E {
845     V(V)
846 }
847
848 fn f() {
849     let E::V(V { i, j }) = E::V(V { i: 9, j: 2 });
850 }
851 "#,
852         )
853     }
854
855     #[test]
856     fn extract_record_fix_references2() {
857         check_assist(
858             extract_struct_from_enum_variant,
859             r#"
860 enum E {
861     $0V(i32, i32)
862 }
863
864 fn f() {
865     let E::V(i, j) = E::V(9, 2);
866 }
867 "#,
868             r#"
869 struct V(i32, i32);
870
871 enum E {
872     V(V)
873 }
874
875 fn f() {
876     let E::V(V(i, j)) = E::V(V(9, 2));
877 }
878 "#,
879         )
880     }
881
882     #[test]
883     fn test_several_files() {
884         check_assist(
885             extract_struct_from_enum_variant,
886             r#"
887 //- /main.rs
888 enum E {
889     $0V(i32, i32)
890 }
891 mod foo;
892
893 //- /foo.rs
894 use crate::E;
895 fn f() {
896     let e = E::V(9, 2);
897 }
898 "#,
899             r#"
900 //- /main.rs
901 struct V(i32, i32);
902
903 enum E {
904     V(V)
905 }
906 mod foo;
907
908 //- /foo.rs
909 use crate::{E, V};
910 fn f() {
911     let e = E::V(V(9, 2));
912 }
913 "#,
914         )
915     }
916
917     #[test]
918     fn test_several_files_record() {
919         check_assist(
920             extract_struct_from_enum_variant,
921             r#"
922 //- /main.rs
923 enum E {
924     $0V { i: i32, j: i32 }
925 }
926 mod foo;
927
928 //- /foo.rs
929 use crate::E;
930 fn f() {
931     let e = E::V { i: 9, j: 2 };
932 }
933 "#,
934             r#"
935 //- /main.rs
936 struct V{ i: i32, j: i32 }
937
938 enum E {
939     V(V)
940 }
941 mod foo;
942
943 //- /foo.rs
944 use crate::{E, V};
945 fn f() {
946     let e = E::V(V { i: 9, j: 2 });
947 }
948 "#,
949         )
950     }
951
952     #[test]
953     fn test_extract_struct_record_nested_call_exp() {
954         check_assist(
955             extract_struct_from_enum_variant,
956             r#"
957 enum A { $0One { a: u32, b: u32 } }
958
959 struct B(A);
960
961 fn foo() {
962     let _ = B(A::One { a: 1, b: 2 });
963 }
964 "#,
965             r#"
966 struct One{ a: u32, b: u32 }
967
968 enum A { One(One) }
969
970 struct B(A);
971
972 fn foo() {
973     let _ = B(A::One(One { a: 1, b: 2 }));
974 }
975 "#,
976         );
977     }
978
979     #[test]
980     fn test_extract_enum_not_applicable_for_element_with_no_fields() {
981         check_assist_not_applicable(extract_struct_from_enum_variant, r#"enum A { $0One }"#);
982     }
983
984     #[test]
985     fn test_extract_enum_not_applicable_if_struct_exists() {
986         cov_mark::check!(test_extract_enum_not_applicable_if_struct_exists);
987         check_assist_not_applicable(
988             extract_struct_from_enum_variant,
989             r#"
990 struct One;
991 enum A { $0One(u8, u32) }
992 "#,
993         );
994     }
995
996     #[test]
997     fn test_extract_not_applicable_one_field() {
998         check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0One(u32) }");
999     }
1000
1001     #[test]
1002     fn test_extract_not_applicable_no_field_tuple() {
1003         check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None() }");
1004     }
1005
1006     #[test]
1007     fn test_extract_not_applicable_no_field_named() {
1008         check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None {} }");
1009     }
1010
1011     #[test]
1012     fn test_extract_struct_only_copies_needed_generics() {
1013         check_assist(
1014             extract_struct_from_enum_variant,
1015             r#"
1016 enum X<'a, 'b, 'x> {
1017     $0A { a: &'a &'x mut () },
1018     B { b: &'b () },
1019     C { c: () },
1020 }
1021 "#,
1022             r#"
1023 struct A<'a, 'x>{ a: &'a &'x mut () }
1024
1025 enum X<'a, 'b, 'x> {
1026     A(A<'a, 'x>),
1027     B { b: &'b () },
1028     C { c: () },
1029 }
1030 "#,
1031         );
1032     }
1033
1034     #[test]
1035     fn test_extract_struct_with_liftime_type_const() {
1036         check_assist(
1037             extract_struct_from_enum_variant,
1038             r#"
1039 enum X<'b, T, V, const C: usize> {
1040     $0A { a: T, b: X<'b>, c: [u8; C] },
1041     D { d: V },
1042 }
1043 "#,
1044             r#"
1045 struct A<'b, T, const C: usize>{ a: T, b: X<'b>, c: [u8; C] }
1046
1047 enum X<'b, T, V, const C: usize> {
1048     A(A<'b, T, C>),
1049     D { d: V },
1050 }
1051 "#,
1052         );
1053     }
1054
1055     #[test]
1056     fn test_extract_struct_without_generics() {
1057         check_assist(
1058             extract_struct_from_enum_variant,
1059             r#"
1060 enum X<'a, 'b> {
1061     A { a: &'a () },
1062     B { b: &'b () },
1063     $0C { c: () },
1064 }
1065 "#,
1066             r#"
1067 struct C{ c: () }
1068
1069 enum X<'a, 'b> {
1070     A { a: &'a () },
1071     B { b: &'b () },
1072     C(C),
1073 }
1074 "#,
1075         );
1076     }
1077
1078     #[test]
1079     fn test_extract_struct_keeps_trait_bounds() {
1080         check_assist(
1081             extract_struct_from_enum_variant,
1082             r#"
1083 enum En<T: TraitT, V: TraitV> {
1084     $0A { a: T },
1085     B { b: V },
1086 }
1087 "#,
1088             r#"
1089 struct A<T: TraitT>{ a: T }
1090
1091 enum En<T: TraitT, V: TraitV> {
1092     A(A<T>),
1093     B { b: V },
1094 }
1095 "#,
1096         );
1097     }
1098 }