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