Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
//! A "Parser" structure for token trees. We use this when parsing a declarative
//! macro definition into a list of patterns and templates.

use syntax::SyntaxKind;
use tt::buffer::TokenBuffer;

use crate::{to_parser_input::to_parser_input, ExpandError, ExpandResult};

#[derive(Debug, Clone)]
pub(crate) struct TtIter<'a> {
    pub(crate) inner: std::slice::Iter<'a, tt::TokenTree>,
}

impl<'a> TtIter<'a> {
    pub(crate) fn new(subtree: &'a tt::Subtree) -> TtIter<'a> {
        TtIter { inner: subtree.token_trees.iter() }
    }

    pub(crate) fn expect_char(&mut self, char: char) -> Result<(), ()> {
        match self.next() {
            Some(&tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct { char: c, .. }))) if c == char => {
                Ok(())
            }
            _ => Err(()),
        }
    }

    pub(crate) fn expect_any_char(&mut self, chars: &[char]) -> Result<(), ()> {
        match self.next() {
            Some(tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct { char: c, .. })))
                if chars.contains(c) =>
            {
                Ok(())
            }
            _ => Err(()),
        }
    }

    pub(crate) fn expect_subtree(&mut self) -> Result<&'a tt::Subtree, ()> {
        match self.next() {
            Some(tt::TokenTree::Subtree(it)) => Ok(it),
            _ => Err(()),
        }
    }

    pub(crate) fn expect_leaf(&mut self) -> Result<&'a tt::Leaf, ()> {
        match self.next() {
            Some(tt::TokenTree::Leaf(it)) => Ok(it),
            _ => Err(()),
        }
    }

    pub(crate) fn expect_ident(&mut self) -> Result<&'a tt::Ident, ()> {
        match self.expect_leaf()? {
            tt::Leaf::Ident(it) if it.text != "_" => Ok(it),
            _ => Err(()),
        }
    }

    pub(crate) fn expect_ident_or_underscore(&mut self) -> Result<&'a tt::Ident, ()> {
        match self.expect_leaf()? {
            tt::Leaf::Ident(it) => Ok(it),
            _ => Err(()),
        }
    }

    pub(crate) fn expect_literal(&mut self) -> Result<&'a tt::Leaf, ()> {
        let it = self.expect_leaf()?;
        match it {
            tt::Leaf::Literal(_) => Ok(it),
            tt::Leaf::Ident(ident) if ident.text == "true" || ident.text == "false" => Ok(it),
            _ => Err(()),
        }
    }

    pub(crate) fn expect_u32_literal(&mut self) -> Result<u32, ()> {
        match self.expect_literal()? {
            tt::Leaf::Literal(lit) => lit.text.parse().map_err(drop),
            _ => Err(()),
        }
    }

    pub(crate) fn expect_punct(&mut self) -> Result<&'a tt::Punct, ()> {
        match self.expect_leaf()? {
            tt::Leaf::Punct(it) => Ok(it),
            _ => Err(()),
        }
    }

    pub(crate) fn expect_fragment(
        &mut self,
        entry_point: parser::PrefixEntryPoint,
    ) -> ExpandResult<Option<tt::TokenTree>> {
        let buffer = TokenBuffer::from_tokens(self.inner.as_slice());
        let parser_input = to_parser_input(&buffer);
        let tree_traversal = entry_point.parse(&parser_input);

        let mut cursor = buffer.begin();
        let mut error = false;
        for step in tree_traversal.iter() {
            match step {
                parser::Step::Token { kind, mut n_input_tokens } => {
                    if kind == SyntaxKind::LIFETIME_IDENT {
                        n_input_tokens = 2;
                    }
                    for _ in 0..n_input_tokens {
                        cursor = cursor.bump_subtree();
                    }
                }
                parser::Step::Enter { .. } | parser::Step::Exit => (),
                parser::Step::Error { .. } => error = true,
            }
        }

        let err = if error || !cursor.is_root() {
            Some(ExpandError::binding_error(format!("expected {entry_point:?}")))
        } else {
            None
        };

        let mut curr = buffer.begin();
        let mut res = vec![];

        if cursor.is_root() {
            while curr != cursor {
                if let Some(token) = curr.token_tree() {
                    res.push(token);
                }
                curr = curr.bump();
            }
        }
        self.inner = self.inner.as_slice()[res.len()..].iter();
        let res = match res.len() {
            1 => Some(res[0].cloned()),
            0 => None,
            _ => Some(tt::TokenTree::Subtree(tt::Subtree {
                delimiter: None,
                token_trees: res.into_iter().map(|it| it.cloned()).collect(),
            })),
        };
        ExpandResult { value: res, err }
    }

    pub(crate) fn peek_n(&self, n: usize) -> Option<&tt::TokenTree> {
        self.inner.as_slice().get(n)
    }
}

impl<'a> Iterator for TtIter<'a> {
    type Item = &'a tt::TokenTree;
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<'a> std::iter::ExactSizeIterator for TtIter<'a> {}
id='n355' href='#n355'>355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
use std::iter;

use either::Either;
use hir::{EnumVariant, HasCrate, Module, ModuleDef, Name};
use ide_db::{
    FxHashSet, RootDatabase,
    defs::Definition,
    helpers::mod_path_to_ast_with_factory,
    imports::insert_use::{ImportScope, InsertUseConfig, insert_use_with_editor},
    path_transform::PathTransform,
    search::FileReference,
};
use itertools::Itertools;
use syntax::{
    Edition, SyntaxElement,
    SyntaxKind::*,
    SyntaxNode, T,
    ast::{
        self, AstNode, HasAttrs, HasGenericParams, HasName, HasVisibility, edit::AstNodeEdit,
        syntax_factory::SyntaxFactory,
    },
    match_ast,
    syntax_editor::{Position, SyntaxEditor},
};

use crate::{AssistContext, AssistId, Assists};

// Assist: extract_struct_from_enum_variant
//
// Extracts a struct from enum variant.
//
// ```
// enum A { $0One(u32, u32) }
// ```
// ->
// ```
// struct One(u32, u32);
//
// enum A { One(One) }
// ```
pub(crate) fn extract_struct_from_enum_variant(
    acc: &mut Assists,
    ctx: &AssistContext<'_, '_>,
) -> Option<()> {
    let variant = ctx.find_node_at_offset::<ast::Variant>()?;
    let field_list = extract_field_list_if_applicable(&variant)?;

    let variant_name = variant.name()?;
    let variant_hir = ctx.sema.to_def(&variant)?;
    if existing_definition(ctx.db(), &variant_name, &variant_hir) {
        cov_mark::hit!(test_extract_enum_not_applicable_if_struct_exists);
        return None;
    }

    let enum_ast = variant.parent_enum();
    let enum_hir = ctx.sema.to_def(&enum_ast)?;
    let target = variant.syntax().text_range();
    acc.add(
        AssistId::refactor_rewrite("extract_struct_from_enum_variant"),
        "Extract struct from enum variant",
        target,
        |builder| {
            let editor = builder.make_editor(variant.syntax());
            let make = editor.make();
            let edition = enum_hir.krate(ctx.db()).edition(ctx.db());
            let variant_hir_name = variant_hir.name(ctx.db());
            let enum_module_def = ModuleDef::from(enum_hir);
            let usages = Definition::EnumVariant(variant_hir).usages(&ctx.sema).all();

            let mut visited_modules_set = FxHashSet::default();
            let current_module = enum_hir.module(ctx.db());
            visited_modules_set.insert(current_module);
            // record file references of the file the def resides in, we only want to swap to the edited file in the builder once
            let mut def_file_references = None;
            for (file_id, references) in usages {
                if file_id == ctx.file_id() {
                    def_file_references = Some(references);
                    continue;
                }
                let processed = process_references(
                    ctx,
                    &mut visited_modules_set,
                    &enum_module_def,
                    &variant_hir_name,
                    references,
                );
                if processed.is_empty() {
                    continue;
                }
                let file_editor = builder.make_editor(processed[0].0.syntax());
                processed.into_iter().for_each(|(path, node, import)| {
                    apply_references(
                        ctx.config.insert_use,
                        path,
                        node,
                        import,
                        edition,
                        &file_editor,
                    )
                });
                builder.add_file_edits(file_id.file_id(ctx.db()), file_editor);
            }

            if let Some(references) = def_file_references {
                let processed = process_references(
                    ctx,
                    &mut visited_modules_set,
                    &enum_module_def,
                    &variant_hir_name,
                    references,
                );
                processed.into_iter().for_each(|(path, node, import)| {
                    apply_references(ctx.config.insert_use, path, node, import, edition, &editor)
                });
            }

            let generic_params = enum_ast.generic_param_list().and_then(|known_generics| {
                extract_generic_params(make, &known_generics, &field_list)
            });

            // resolve GenericArg in field_list to actual type
            let field_list = if let Some((target_scope, source_scope)) =
                ctx.sema.scope(enum_ast.syntax()).zip(ctx.sema.scope(field_list.syntax()))
            {
                let field_list = field_list.reset_indent();
                let field_list =
                    PathTransform::generic_transformation(&target_scope, &source_scope)
                        .apply(field_list.syntax());
                match_ast! {
                    match field_list {
                        ast::RecordFieldList(field_list) => Either::Left(field_list),
                        ast::TupleFieldList(field_list) => Either::Right(field_list),
                        _ => unreachable!(),
                    }
                }
            } else {
                field_list.clone()
            };

            let (comments_for_struct, comments_to_delete) =
                collect_variant_comments(make, variant.syntax());
            for element in &comments_to_delete {
                editor.delete(element.clone());
            }

            let def = create_struct_def(
                make,
                variant_name.clone(),
                &field_list,
                generic_params.clone(),
                &enum_ast,
            );

            let enum_ast = variant.parent_enum();
            let indent = enum_ast.indent_level();
            let def = def.indent(indent);

            let mut insert_items: Vec<SyntaxElement> = Vec::new();
            for attr in enum_ast.attrs() {
                insert_items.push(attr.syntax().clone().into());
                insert_items.push(make.whitespace("\n").into());
            }
            insert_items.extend(comments_for_struct);
            insert_items.push(def.syntax().clone().into());
            insert_items.push(make.whitespace(&format!("\n\n{indent}")).into());
            editor.insert_all_with_whitespace(Position::before(enum_ast.syntax()), insert_items);

            update_variant(&editor, &variant, generic_params);

            builder.add_file_edits(ctx.vfs_file_id(), editor);
        },
    )
}

fn extract_field_list_if_applicable(
    variant: &ast::Variant,
) -> Option<Either<ast::RecordFieldList, ast::TupleFieldList>> {
    match variant.kind() {
        ast::StructKind::Record(field_list) if field_list.fields().next().is_some() => {
            Some(Either::Left(field_list))
        }
        ast::StructKind::Tuple(field_list) if field_list.fields().count() > 1 => {
            Some(Either::Right(field_list))
        }
        _ => None,
    }
}

fn existing_definition(db: &RootDatabase, variant_name: &ast::Name, variant: &EnumVariant) -> bool {
    variant
        .parent_enum(db)
        .module(db)
        .scope(db, None)
        .into_iter()
        .filter(|(_, def)| match def {
            // only check type-namespace
            hir::ScopeDef::ModuleDef(def) => matches!(
                def,
                ModuleDef::Module(_)
                    | ModuleDef::Adt(_)
                    | ModuleDef::EnumVariant(_)
                    | ModuleDef::Trait(_)
                    | ModuleDef::TypeAlias(_)
                    | ModuleDef::BuiltinType(_)
            ),
            _ => false,
        })
        .any(|(name, _)| name.as_str() == variant_name.text().trim_start_matches("r#"))
}

fn extract_generic_params(
    make: &SyntaxFactory,
    known_generics: &ast::GenericParamList,
    field_list: &Either<ast::RecordFieldList, ast::TupleFieldList>,
) -> Option<ast::GenericParamList> {
    let mut generics = known_generics.generic_params().map(|param| (param, false)).collect_vec();

    #[expect(clippy::unnecessary_fold, reason = "this function has side effects")]
    let tagged_one = match field_list {
        Either::Left(field_list) => field_list
            .fields()
            .filter_map(|f| f.ty())
            .fold(false, |tagged, ty| tag_generics_in_variant(&ty, &mut generics) || tagged),
        Either::Right(field_list) => field_list
            .fields()
            .filter_map(|f| f.ty())
            .fold(false, |tagged, ty| tag_generics_in_variant(&ty, &mut generics) || tagged),
    };

    let generics = generics.into_iter().filter_map(|(param, tag)| tag.then_some(param));
    tagged_one.then(|| make.generic_param_list(generics))
}

fn tag_generics_in_variant(ty: &ast::Type, generics: &mut [(ast::GenericParam, bool)]) -> bool {
    let mut tagged_one = false;

    for token in ty.syntax().descendants_with_tokens().filter_map(SyntaxElement::into_token) {
        for (param, tag) in generics.iter_mut().filter(|(_, tag)| !tag) {
            match param {
                ast::GenericParam::LifetimeParam(lt)
                    if matches!(token.kind(), T![lifetime_ident]) =>
                {
                    if let Some(lt) = lt.lifetime()
                        && lt.text().as_str() == token.text()
                    {
                        *tag = true;
                        tagged_one = true;
                        break;
                    }
                }
                param if matches!(token.kind(), T![ident]) => {
                    #[expect(
                        clippy::collapsible_match,
                        reason = "it won't compile since in the guard, `param` is immutable"
                    )]
                    if match param {
                        ast::GenericParam::ConstParam(konst) => konst
                            .name()
                            .map(|name| name.text().as_str() == token.text())
                            .unwrap_or_default(),
                        ast::GenericParam::TypeParam(ty) => ty
                            .name()
                            .map(|name| name.text().as_str() == token.text())
                            .unwrap_or_default(),
                        ast::GenericParam::LifetimeParam(lt) => lt
                            .lifetime()
                            .map(|lt| lt.text().as_str() == token.text())
                            .unwrap_or_default(),
                    } {
                        *tag = true;
                        tagged_one = true;
                        break;
                    }
                }
                _ => (),
            }
        }
    }

    tagged_one
}

fn create_struct_def(
    make: &SyntaxFactory,
    name: ast::Name,
    field_list: &Either<ast::RecordFieldList, ast::TupleFieldList>,
    generics: Option<ast::GenericParamList>,
    enum_: &ast::Enum,
) -> ast::Struct {
    let enum_vis = enum_.visibility();

    // for fields without any existing visibility, use visibility of enum
    let field_list: ast::FieldList = match field_list {
        Either::Left(field_list) => {
            if let Some(vis) = &enum_vis {
                let new_fields = field_list.fields().map(|field| {
                    if field.visibility().is_none()
                        && let Some(name) = field.name()
                        && let Some(ty) = field.ty()
                    {
                        make.record_field(Some(vis.clone()), name, ty)
                    } else {
                        field
                    }
                });
                make.record_field_list(new_fields).into()
            } else {
                field_list.clone().into()
            }
        }
        Either::Right(field_list) => {
            if let Some(vis) = &enum_vis {
                let new_fields = field_list.fields().map(|field| {
                    if field.visibility().is_none()
                        && let Some(ty) = field.ty()
                    {
                        make.tuple_field(Some(vis.clone()), ty)
                    } else {
                        field
                    }
                });
                make.tuple_field_list(new_fields).into()
            } else {
                field_list.clone().into()
            }
        }
    };

    make.struct_(enum_vis, name, generics, field_list)
}

fn update_variant(
    editor: &SyntaxEditor,
    variant: &ast::Variant,
    generics: Option<ast::GenericParamList>,
) -> Option<()> {
    let make = editor.make();
    let name = variant.name()?;
    let generic_args = generics
        .filter(|generics| generics.generic_params().count() > 0)
        .map(|generics| generics.to_generic_args());
    // FIXME: replace with a `ast::make` constructor
    let ty = match generic_args {
        Some(generic_args) => make.ty(&format!("{name}{generic_args}")),
        None => make.ty(&name.text()),
    };

    // change from a record to a tuple field list
    let tuple_field = make.tuple_field(None, ty);
    let field_list = make.tuple_field_list(iter::once(tuple_field));
    editor.replace(variant.field_list()?.syntax(), field_list.syntax());

    // remove any ws after the name
    if let Some(ws) = name
        .syntax()
        .siblings_with_tokens(syntax::Direction::Next)
        .find_map(|tok| tok.into_token().filter(|tok| tok.kind() == WHITESPACE))
    {
        editor.delete(ws);
    }

    Some(())
}

fn collect_variant_comments(
    make: &SyntaxFactory,
    node: &SyntaxNode,
) -> (Vec<SyntaxElement>, Vec<SyntaxElement>) {
    let mut to_insert: Vec<SyntaxElement> = Vec::new();
    let mut to_delete: Vec<SyntaxElement> = Vec::new();
    let mut after_comment = false;

    for child in node.children_with_tokens() {
        match child.kind() {
            COMMENT => {
                after_comment = true;
                to_insert.push(child.clone());
                to_delete.push(child);
            }
            WHITESPACE if after_comment => {
                after_comment = false;
                to_insert.push(make.whitespace("\n").into());
                to_delete.push(child);
            }
            _ => {
                after_comment = false;
            }
        }
    }

    (to_insert, to_delete)
}

fn apply_references(
    insert_use_cfg: InsertUseConfig,
    segment: ast::PathSegment,
    node: SyntaxNode,
    import: Option<(ImportScope, hir::ModPath)>,
    edition: Edition,
    editor: &SyntaxEditor,
) {
    let make = editor.make();
    if let Some((scope, path)) = import {
        insert_use_with_editor(
            &scope,
            mod_path_to_ast_with_factory(make, &path, edition),
            &insert_use_cfg,
            editor,
        );
    }
    // deep clone to prevent cycle
    let path = make.path_from_segments(iter::once(segment.clone()), false);
    editor.insert(Position::before(segment.syntax()), make.token(T!['(']));
    editor.insert(Position::before(segment.syntax()), path.syntax());
    editor.insert(Position::after(&node), make.token(T![')']));
}

fn process_references(
    ctx: &AssistContext<'_, '_>,
    visited_modules: &mut FxHashSet<Module>,
    enum_module_def: &ModuleDef,
    variant_hir_name: &Name,
    refs: Vec<FileReference>,
) -> Vec<(ast::PathSegment, SyntaxNode, Option<(ImportScope, hir::ModPath)>)> {
    // we have to recollect here eagerly as we are about to edit the tree we need to calculate the changes
    // and corresponding nodes up front
    refs.into_iter()
        .flat_map(|reference| {
            let (segment, scope_node, module) = reference_to_node(&ctx.sema, reference)?;
            if !visited_modules.contains(&module) {
                let cfg =
                    ctx.config.find_path_config(ctx.sema.is_nightly(module.krate(ctx.sema.db)));
                let mod_path = module.find_use_path(
                    ctx.sema.db,
                    *enum_module_def,
                    ctx.config.insert_use.prefix_kind,
                    cfg,
                );
                if let Some(mut mod_path) = mod_path {
                    mod_path.pop_segment();
                    mod_path.push_segment(variant_hir_name.clone());
                    let scope = ImportScope::find_insert_use_container(&scope_node, &ctx.sema)?;
                    visited_modules.insert(module);
                    return Some((segment, scope_node, Some((scope, mod_path))));
                }
            }
            Some((segment, scope_node, None))
        })
        .collect()
}

fn reference_to_node(
    sema: &hir::Semantics<'_, RootDatabase>,
    reference: FileReference,
) -> Option<(ast::PathSegment, SyntaxNode, hir::Module)> {
    let segment =
        reference.name.as_name_ref()?.syntax().parent().and_then(ast::PathSegment::cast)?;

    // filter out the reference in marco
    let segment_range = segment.syntax().text_range();
    if segment_range != reference.range {
        return None;
    }

    let parent = segment.parent_path().syntax().parent()?;
    let expr_or_pat = match_ast! {
        match parent {
            ast::PathExpr(_it) => parent.parent()?,
            ast::RecordExpr(_it) => parent,
            ast::TupleStructPat(_it) => parent,
            ast::RecordPat(_it) => parent,
            _ => return None,
        }
    };
    let module = sema.scope(&expr_or_pat)?.module();
    Some((segment, expr_or_pat, module))
}

#[cfg(test)]
mod tests {
    use crate::tests::{check_assist, check_assist_not_applicable};

    use super::*;

    #[test]
    fn test_with_marco() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
macro_rules! foo {
    ($x:expr) => {
        $x
    };
}

enum TheEnum {
    TheVariant$0 { the_field: u8 },
}

fn main() {
    foo![TheEnum::TheVariant { the_field: 42 }];
}
"#,
            r#"
macro_rules! foo {
    ($x:expr) => {
        $x
    };
}

struct TheVariant { the_field: u8 }

enum TheEnum {
    TheVariant(TheVariant),
}

fn main() {
    foo![TheEnum::TheVariant { the_field: 42 }];
}
"#,
        );
    }

    #[test]
    fn issue_16197() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum Foo {
    Bar $0{ node: Box<Self> },
    Nil,
}
"#,
            r#"
struct Bar { node: Box<Foo> }

enum Foo {
    Bar(Bar),
    Nil,
}
"#,
        );
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum Foo {
    Bar $0{ node: Box<Self>, a: Arc<Box<Self>> },
    Nil,
}
"#,
            r#"
struct Bar { node: Box<Foo>, a: Arc<Box<Foo>> }

enum Foo {
    Bar(Bar),
    Nil,
}
"#,
        );
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum Foo {
    Nil(Box$0<Self>, Arc<Box<Self>>),
}
"#,
            r#"
struct Nil(Box<Foo>, Arc<Box<Foo>>);

enum Foo {
    Nil(Nil),
}
"#,
        );
    }

    #[test]
    fn test_extract_struct_several_fields_tuple() {
        check_assist(
            extract_struct_from_enum_variant,
            "enum A { $0One(u32, u32) }",
            r#"struct One(u32, u32);

enum A { One(One) }"#,
        );
    }

    #[test]
    fn test_extract_struct_several_fields_named() {
        check_assist(
            extract_struct_from_enum_variant,
            "enum A { $0One { foo: u32, bar: u32 } }",
            r#"struct One { foo: u32, bar: u32 }

enum A { One(One) }"#,
        );
    }

    #[test]
    fn test_extract_struct_one_field_named() {
        check_assist(
            extract_struct_from_enum_variant,
            "enum A { $0One { foo: u32 } }",
            r#"struct One { foo: u32 }

enum A { One(One) }"#,
        );
    }

    #[test]
    fn test_extract_struct_carries_over_generics() {
        check_assist(
            extract_struct_from_enum_variant,
            r"enum En<T> { Var { a: T$0 } }",
            r#"struct Var<T> { a: T }

enum En<T> { Var(Var<T>) }"#,
        );
    }

    #[test]
    fn test_extract_struct_carries_over_attributes() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
#[derive(Debug)]
#[derive(Clone)]
enum Enum { Variant{ field: u32$0 } }"#,
            r#"
#[derive(Debug)]
#[derive(Clone)]
struct Variant { field: u32 }

#[derive(Debug)]
#[derive(Clone)]
enum Enum { Variant(Variant) }"#,
        );
    }

    #[test]
    fn test_extract_struct_indent_to_parent_enum() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum Enum {
    Variant {
        field: u32$0
    }
}"#,
            r#"
struct Variant {
    field: u32
}

enum Enum {
    Variant(Variant)
}"#,
        );
    }

    #[test]
    fn test_extract_struct_indent_to_parent_enum_in_mod() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
mod indenting {
    enum Enum {
        Variant {
            field: u32$0
        }
    }
}"#,
            r#"
mod indenting {
    struct Variant {
        field: u32
    }

    enum Enum {
        Variant(Variant)
    }
}"#,
        );
    }

    #[test]
    fn test_extract_struct_keep_comments_and_attrs_one_field_named() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum A {
    $0One {
        // leading comment
        /// doc comment
        #[an_attr]
        foo: u32
        // trailing comment
    }
}"#,
            r#"
struct One {
    // leading comment
    /// doc comment
    #[an_attr]
    foo: u32
    // trailing comment
}

enum A {
    One(One)
}"#,
        );
    }

    #[test]
    fn test_extract_struct_keep_comments_and_attrs_several_fields_named() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum A {
    $0One {
        // comment
        /// doc
        #[attr]
        foo: u32,
        // comment
        #[attr]
        /// doc
        bar: u32
    }
}"#,
            r#"
struct One {
    // comment
    /// doc
    #[attr]
    foo: u32,
    // comment
    #[attr]
    /// doc
    bar: u32
}

enum A {
    One(One)
}"#,
        );
    }

    #[test]
    fn test_extract_struct_keep_comments_and_attrs_several_fields_tuple() {
        check_assist(
            extract_struct_from_enum_variant,
            "enum A { $0One(/* comment */ #[attr] u32, /* another */ u32 /* tail */) }",
            r#"
struct One(/* comment */ #[attr] u32, /* another */ u32 /* tail */);

enum A { One(One) }"#,
        );
    }

    #[test]
    fn test_extract_struct_move_struct_variant_comments() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum A {
    /* comment */
    // other
    /// comment
    #[attr]
    $0One {
        a: u32
    }
}"#,
            r#"
/* comment */
// other
/// comment
struct One {
    a: u32
}

enum A {
    #[attr]
    One(One)
}"#,
        );
    }

    #[test]
    fn test_extract_struct_move_tuple_variant_comments() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum A {
    /* comment */
    // other
    /// comment
    #[attr]
    $0One(u32, u32)
}"#,
            r#"
/* comment */
// other
/// comment
struct One(u32, u32);

enum A {
    #[attr]
    One(One)
}"#,
        );
    }

    #[test]
    fn test_extract_struct_keep_existing_visibility_named() {
        check_assist(
            extract_struct_from_enum_variant,
            "enum A { $0One{ a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 } }",
            r#"
struct One { a: u32, pub(crate) b: u32, pub(super) c: u32, d: u32 }

enum A { One(One) }"#,
        );
    }

    #[test]
    fn test_extract_struct_keep_existing_visibility_tuple() {
        check_assist(
            extract_struct_from_enum_variant,
            "enum A { $0One(u32, pub(crate) u32, pub(super) u32, u32) }",
            r#"
struct One(u32, pub(crate) u32, pub(super) u32, u32);

enum A { One(One) }"#,
        );
    }

    #[test]
    fn test_extract_enum_variant_name_value_namespace() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"const One: () = ();
enum A { $0One(u32, u32) }"#,
            r#"const One: () = ();
struct One(u32, u32);

enum A { One(One) }"#,
        );
    }

    #[test]
    fn test_extract_struct_no_visibility() {
        check_assist(
            extract_struct_from_enum_variant,
            "enum A { $0One(u32, u32) }",
            r#"
struct One(u32, u32);

enum A { One(One) }"#,
        );
    }

    #[test]
    fn test_extract_struct_pub_visibility() {
        check_assist(
            extract_struct_from_enum_variant,
            "pub enum A { $0One(u32, u32) }",
            r#"
pub struct One(pub u32, pub u32);

pub enum A { One(One) }"#,
        );
    }

    #[test]
    fn test_extract_struct_pub_in_mod_visibility() {
        check_assist(
            extract_struct_from_enum_variant,
            "pub(in something) enum A { $0One{ a: u32, b: u32 } }",
            r#"
pub(in something) struct One { pub(in something) a: u32, pub(in something) b: u32 }

pub(in something) enum A { One(One) }"#,
        );
    }

    #[test]
    fn test_extract_struct_pub_crate_visibility() {
        check_assist(
            extract_struct_from_enum_variant,
            "pub(crate) enum A { $0One{ a: u32, b: u32, c: u32 } }",
            r#"
pub(crate) struct One { pub(crate) a: u32, pub(crate) b: u32, pub(crate) c: u32 }

pub(crate) enum A { One(One) }"#,
        );
    }

    #[test]
    fn test_extract_struct_with_complex_imports() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"mod my_mod {
    fn another_fn() {
        let m = my_other_mod::MyEnum::MyField(1, 1);
    }

    pub mod my_other_mod {
        fn another_fn() {
            let m = MyEnum::MyField(1, 1);
        }

        pub enum MyEnum {
            $0MyField(u8, u8),
        }
    }
}

fn another_fn() {
    let m = my_mod::my_other_mod::MyEnum::MyField(1, 1);
}"#,
            r#"use my_mod::my_other_mod::MyField;

mod my_mod {
    use my_other_mod::MyField;

    fn another_fn() {
        let m = my_other_mod::MyEnum::MyField(MyField(1, 1));
    }

    pub mod my_other_mod {
        fn another_fn() {
            let m = MyEnum::MyField(MyField(1, 1));
        }

        pub struct MyField(pub u8, pub u8);

        pub enum MyEnum {
            MyField(MyField),
        }
    }
}

fn another_fn() {
    let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1));
}"#,
        );
    }

    #[test]
    fn extract_record_fix_references() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum E {
    $0V { i: i32, j: i32 }
}

fn f() {
    let E::V { i, j } = E::V { i: 9, j: 2 };
}
"#,
            r#"
struct V { i: i32, j: i32 }

enum E {
    V(V)
}

fn f() {
    let E::V(V { i, j }) = E::V(V { i: 9, j: 2 });
}
"#,
        )
    }

    #[test]
    fn extract_record_fix_references2() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum E {
    $0V(i32, i32)
}

fn f() {
    let E::V(i, j) = E::V(9, 2);
}
"#,
            r#"
struct V(i32, i32);

enum E {
    V(V)
}

fn f() {
    let E::V(V(i, j)) = E::V(V(9, 2));
}
"#,
        )
    }

    #[test]
    fn test_several_files() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
//- /main.rs
enum E {
    $0V(i32, i32)
}
mod foo;

//- /foo.rs
use crate::E;
fn f() {
    let e = E::V(9, 2);
}
"#,
            r#"
//- /main.rs
struct V(i32, i32);

enum E {
    V(V)
}
mod foo;

//- /foo.rs
use crate::{E, V};
fn f() {
    let e = E::V(V(9, 2));
}
"#,
        )
    }

    #[test]
    fn test_several_files_record() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
//- /main.rs
enum E {
    $0V { i: i32, j: i32 }
}
mod foo;

//- /foo.rs
use crate::E;
fn f() {
    let e = E::V { i: 9, j: 2 };
}
"#,
            r#"
//- /main.rs
struct V { i: i32, j: i32 }

enum E {
    V(V)
}
mod foo;

//- /foo.rs
use crate::{E, V};
fn f() {
    let e = E::V(V { i: 9, j: 2 });
}
"#,
        )
    }

    #[test]
    fn test_extract_struct_record_nested_call_exp() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum A { $0One { a: u32, b: u32 } }

struct B(A);

fn foo() {
    let _ = B(A::One { a: 1, b: 2 });
}
"#,
            r#"
struct One { a: u32, b: u32 }

enum A { One(One) }

struct B(A);

fn foo() {
    let _ = B(A::One(One { a: 1, b: 2 }));
}
"#,
        );
    }

    #[test]
    fn test_extract_enum_not_applicable_for_element_with_no_fields() {
        check_assist_not_applicable(extract_struct_from_enum_variant, r#"enum A { $0One }"#);
    }

    #[test]
    fn test_extract_enum_not_applicable_if_struct_exists() {
        cov_mark::check!(test_extract_enum_not_applicable_if_struct_exists);
        check_assist_not_applicable(
            extract_struct_from_enum_variant,
            r#"
struct One;
enum A { $0One(u8, u32) }
"#,
        );
    }

    #[test]
    fn test_extract_not_applicable_one_field() {
        check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0One(u32) }");
    }

    #[test]
    fn test_extract_not_applicable_no_field_tuple() {
        check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None() }");
    }

    #[test]
    fn test_extract_not_applicable_no_field_named() {
        check_assist_not_applicable(extract_struct_from_enum_variant, r"enum A { $0None {} }");
    }

    #[test]
    fn test_extract_struct_only_copies_needed_generics() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum X<'a, 'b, 'x> {
    $0A { a: &'a &'x mut () },
    B { b: &'b () },
    C { c: () },
}
"#,
            r#"
struct A<'a, 'x> { a: &'a &'x mut () }

enum X<'a, 'b, 'x> {
    A(A<'a, 'x>),
    B { b: &'b () },
    C { c: () },
}
"#,
        );
    }

    #[test]
    fn test_extract_struct_with_lifetime_type_const() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum X<'b, T, V, const C: usize> {
    $0A { a: T, b: X<'b>, c: [u8; C] },
    D { d: V },
}
"#,
            r#"
struct A<'b, T, const C: usize> { a: T, b: X<'b>, c: [u8; C] }

enum X<'b, T, V, const C: usize> {
    A(A<'b, T, C>),
    D { d: V },
}
"#,
        );
    }

    #[test]
    fn test_extract_struct_without_generics() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum X<'a, 'b> {
    A { a: &'a () },
    B { b: &'b () },
    $0C { c: () },
}
"#,
            r#"
struct C { c: () }

enum X<'a, 'b> {
    A { a: &'a () },
    B { b: &'b () },
    C(C),
}
"#,
        );
    }

    #[test]
    fn test_extract_struct_keeps_trait_bounds() {
        check_assist(
            extract_struct_from_enum_variant,
            r#"
enum En<T: TraitT, V: TraitV> {
    $0A { a: T },
    B { b: V },
}
"#,
            r#"
struct A<T: TraitT> { a: T }

enum En<T: TraitT, V: TraitV> {
    A(A<T>),
    B { b: V },
}
"#,
        );
    }
}