]> git.lizzy.rs Git - rust.git/blobdiff - crates/ide_assists/src/handlers/extract_module.rs
Merge #11481
[rust.git] / crates / ide_assists / src / handlers / extract_module.rs
index 79c5354f848a61a6a74f24a7514c69a658195f96..6cc311fd7585d3adbf9ea34acff318c91ed43692 100644 (file)
@@ -1,6 +1,6 @@
 use std::collections::{HashMap, HashSet};
 
-use hir::{HasSource, ModuleDef, ModuleSource};
+use hir::{HasSource, ModuleSource};
 use ide_db::{
     assists::{AssistId, AssistKind},
     base_db::FileId,
 // resolved.
 //
 // ```
-// $0
-// fn foo(name: i32) -> i32 {
+// $0fn foo(name: i32) -> i32 {
 //     name + 1
-// }
-// $0
+// }$0
 //
 // fn bar(name: i32) -> i32 {
 //     name + 2
@@ -51,7 +49,7 @@
 // }
 // ```
 pub(crate) fn extract_module(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
-    if ctx.frange.range.is_empty() {
+    if ctx.has_empty_selection() {
         return None;
     }
 
@@ -66,70 +64,78 @@ pub(crate) fn extract_module(acc: &mut Assists, ctx: &AssistContext) -> Option<(
         curr_parent_module = ast::Module::cast(mod_syn_opt);
     }
 
-    let mut module = extract_target(&node, ctx.frange.range)?;
+    let mut module = extract_target(&node, ctx.selection_trimmed())?;
     if module.body_items.len() == 0 {
         return None;
     }
 
     let old_item_indent = module.body_items[0].indent_level();
 
+    //This takes place in three steps:
+    //
+    //- Firstly, we will update the references(usages) e.g. converting a
+    //  function call bar() to modname::bar(), and similarly for other items
+    //
+    //- Secondly, changing the visibility of each item inside the newly selected module
+    //  i.e. making a fn a() {} to pub(crate) fn a() {}
+    //
+    //- Thirdly, resolving all the imports this includes removing paths from imports
+    //  outside the module, shifting/cloning them inside new module, or shifting the imports, or making
+    //  new import statemnts
+
+    //We are getting item usages and record_fields together, record_fields
+    //for change_visibility and usages for first point mentioned above in the process
+    let (usages_to_be_processed, record_fields) = module.get_usages_and_record_fields(ctx);
+
+    let import_paths_to_be_removed = module.resolve_imports(curr_parent_module, &ctx);
+    module.body_items = module.change_visibility(record_fields)?;
+    if module.body_items.len() == 0 {
+        return None;
+    }
+
     acc.add(
         AssistId("extract_module", AssistKind::RefactorExtract),
         "Extract Module",
         module.text_range,
         |builder| {
-            //This takes place in three steps:
-            //
-            //- Firstly, we will update the references(usages) e.g. converting a
-            //  function call bar() to modname::bar(), and similarly for other items
-            //
-            //- Secondly, changing the visibility of each item inside the newly selected module
-            //  i.e. making a fn a() {} to pub(crate) fn a() {}
-            //
-            //- Thirdly, resolving all the imports this includes removing paths from imports
-            //  outside the module, shifting/cloning them inside new module, or shifting the imports, or making
-            //  new import statemnts
-
-            //We are getting item usages and record_fields together, record_fields
-            //for change_visibility and usages for first point mentioned above in the process
-            let (usages_to_be_processed, record_fields) = module.get_usages_and_record_fields(ctx);
-
-            let import_paths_to_be_removed = module.resolve_imports(curr_parent_module, &ctx);
-
-            if let Some(block_items) = module.change_visibility(record_fields) {
-                module.body_items = block_items;
-                if module.body_items.len() == 0 {
-                    return;
-                }
+            let _ = &module;
 
-                let mut body_items = Vec::new();
-                let new_item_indent = old_item_indent + 1;
-                for item in module.body_items {
-                    let item = item.indent(IndentLevel(1));
-                    let mut indented_item = String::new();
-                    format_to!(indented_item, "{}{}", new_item_indent, item.to_string());
-                    body_items.push(indented_item);
-                }
+            let mut body_items = Vec::new();
+            let new_item_indent = old_item_indent + 1;
+            for item in module.body_items {
+                let item = item.indent(IndentLevel(1));
+                let mut indented_item = String::new();
+                format_to!(indented_item, "{}{}", new_item_indent, item.to_string());
+                body_items.push(indented_item);
+            }
 
-                let body = body_items.join("\n\n");
+            let body = body_items.join("\n\n");
 
-                let mut module_def = String::new();
+            let mut module_def = String::new();
 
-                format_to!(module_def, "mod {} {{\n{}\n{}}}", module.name, body, old_item_indent);
+            format_to!(module_def, "mod {} {{\n{}\n{}}}", module.name, body, old_item_indent);
 
-                for usages_to_be_updated_for_file in usages_to_be_processed {
-                    builder.edit_file(usages_to_be_updated_for_file.0);
-                    for usage_to_be_processed in usages_to_be_updated_for_file.1 {
-                        builder.replace(usage_to_be_processed.0, usage_to_be_processed.1)
-                    }
+            let mut usages_to_be_updated_for_curr_file = vec![];
+            for usages_to_be_updated_for_file in usages_to_be_processed {
+                if usages_to_be_updated_for_file.0 == ctx.file_id() {
+                    usages_to_be_updated_for_curr_file = usages_to_be_updated_for_file.1;
+                    continue;
                 }
-
-                builder.edit_file(ctx.frange.file_id);
-                for import_path_text_range in import_paths_to_be_removed {
-                    builder.delete(import_path_text_range);
+                builder.edit_file(usages_to_be_updated_for_file.0);
+                for usage_to_be_processed in usages_to_be_updated_for_file.1 {
+                    builder.replace(usage_to_be_processed.0, usage_to_be_processed.1)
                 }
-                builder.replace(module.text_range, module_def)
             }
+
+            builder.edit_file(ctx.file_id());
+            for usage_to_be_processed in usages_to_be_updated_for_curr_file {
+                builder.replace(usage_to_be_processed.0, usage_to_be_processed.1)
+            }
+
+            for import_path_text_range in import_paths_to_be_removed {
+                builder.delete(import_path_text_range);
+            }
+            builder.replace(module.text_range, module_def)
         },
     )
 }
@@ -142,10 +148,10 @@ struct Module {
 }
 
 fn extract_target(node: &SyntaxNode, selection_range: TextRange) -> Option<Module> {
-    let body_items: Vec<ast::Item> = node
+    let mut body_items: Vec<ast::Item> = node
         .children()
         .filter_map(|child| {
-            if let Some(item) = ast::Item::cast(child.clone()) {
+            if let Some(item) = ast::Item::cast(child) {
                 if selection_range.contains_range(item.syntax().text_range()) {
                     return Some(item);
                 }
@@ -155,6 +161,10 @@ fn extract_target(node: &SyntaxNode, selection_range: TextRange) -> Option<Modul
         })
         .collect();
 
+    if let Some(node_item) = ast::Item::cast(node.clone()) {
+        body_items.push(node_item);
+    }
+
     Some(Module { text_range: selection_range, name: "modname".to_string(), body_items })
 }
 
@@ -163,7 +173,7 @@ fn get_usages_and_record_fields(
         &self,
         ctx: &AssistContext,
     ) -> (HashMap<FileId, Vec<(TextRange, String)>>, Vec<SyntaxNode>) {
-        let mut record_fields = Vec::new();
+        let mut adt_fields = Vec::new();
         let mut refs: HashMap<FileId, Vec<(TextRange, String)>> = HashMap::new();
 
         //Here impl is not included as each item inside impl will be tied to the parent of
@@ -174,46 +184,59 @@ fn get_usages_and_record_fields(
                 match (item.syntax()) {
                     ast::Adt(it) => {
                         if let Some( nod ) = ctx.sema.to_def(&it) {
-                            let node_def = Definition::ModuleDef(nod.into());
+                            let node_def = Definition::Adt(nod.into());
                             self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
 
-                            let mut get_record_fields = |it: ast::Adt| {
-                                for desc in it.syntax().descendants() {
-                                    if let Some(record_field) = ast::RecordField::cast(desc) {
-                                        record_fields.push(record_field.syntax().clone());
-                                    }
-                                }
-                            };
-
                             //Enum Fields are not allowed to explicitly specify pub, it is implied
                             match it {
-                                ast::Adt::Struct(_) => get_record_fields(it),
-                                ast::Adt::Union(_) => get_record_fields(it),
+                                ast::Adt::Struct(x) => {
+                                    if let Some(field_list) = x.field_list() {
+                                        match field_list {
+                                            ast::FieldList::RecordFieldList(record_field_list) => {
+                                                record_field_list.fields().for_each(|record_field| {
+                                                    adt_fields.push(record_field.syntax().clone());
+                                                });
+                                            },
+                                            ast::FieldList::TupleFieldList(tuple_field_list) => {
+                                                tuple_field_list.fields().for_each(|tuple_field| {
+                                                    adt_fields.push(tuple_field.syntax().clone());
+                                                });
+                                            },
+                                        }
+                                    }
+                                },
+                                ast::Adt::Union(x) => {
+                                        if let Some(record_field_list) = x.record_field_list() {
+                                            record_field_list.fields().for_each(|record_field| {
+                                                    adt_fields.push(record_field.syntax().clone());
+                                            });
+                                        }
+                                },
                                 ast::Adt::Enum(_) => {},
                             }
                         }
                     },
                     ast::TypeAlias(it) => {
                         if let Some( nod ) = ctx.sema.to_def(&it) {
-                            let node_def = Definition::ModuleDef(nod.into());
+                            let node_def = Definition::TypeAlias(nod.into());
                             self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
                         }
                     },
                     ast::Const(it) => {
                         if let Some( nod ) = ctx.sema.to_def(&it) {
-                            let node_def = Definition::ModuleDef(nod.into());
+                            let node_def = Definition::Const(nod.into());
                             self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
                         }
                     },
                     ast::Static(it) => {
                         if let Some( nod ) = ctx.sema.to_def(&it) {
-                            let node_def = Definition::ModuleDef(nod.into());
+                            let node_def = Definition::Static(nod.into());
                             self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
                         }
                     },
                     ast::Fn(it) => {
                         if let Some( nod ) = ctx.sema.to_def(&it) {
-                            let node_def = Definition::ModuleDef(nod.into());
+                            let node_def = Definition::Function(nod.into());
                             self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
                         }
                     },
@@ -222,7 +245,7 @@ fn get_usages_and_record_fields(
             }
         });
 
-        return (refs, record_fields);
+        return (refs, adt_fields);
     }
 
     fn expand_and_group_usages_file_wise(
@@ -275,7 +298,7 @@ fn get_usage_to_be_processed(
                 if let Some(name_ref) = ast::NameRef::cast(desc) {
                     return Some((
                         name_ref.syntax().text_range(),
-                        format!("{}::{}", self.name, name_ref.to_string()),
+                        format!("{}::{}", self.name, name_ref),
                     ));
                 }
             }
@@ -288,21 +311,20 @@ fn change_visibility(&self, record_fields: Vec<SyntaxNode>) -> Option<Vec<ast::I
         let (body_items, mut replacements, record_field_parents, impls) =
             get_replacements_for_visibilty_change(self.body_items.clone(), false);
 
-        let impl_items = impls.into_iter().fold(Vec::new(), |mut impl_items, x| {
-            let this_impl_items =
-                x.syntax().descendants().fold(Vec::new(), |mut this_impl_items, x| {
-                    if let Some(item) = ast::Item::cast(x.clone()) {
-                        this_impl_items.push(item);
-                    }
-                    return this_impl_items;
-                });
+        let mut impl_items = Vec::new();
+        for impl_ in impls {
+            let mut this_impl_items = Vec::new();
+            for node in impl_.syntax().descendants() {
+                if let Some(item) = ast::Item::cast(node) {
+                    this_impl_items.push(item);
+                }
+            }
 
-            impl_items.append(&mut this_impl_items.clone());
-            return impl_items;
-        });
+            impl_items.append(&mut this_impl_items);
+        }
 
         let (_, mut impl_item_replacements, _, _) =
-            get_replacements_for_visibilty_change(impl_items.clone(), true);
+            get_replacements_for_visibilty_change(impl_items, true);
 
         replacements.append(&mut impl_item_replacements);
 
@@ -314,7 +336,7 @@ fn change_visibility(&self, record_fields: Vec<SyntaxNode>) -> Option<Vec<ast::I
                     .find(|x| x.to_string() == desc.to_string())
                     .is_some();
                 if is_record_field_present {
-                    replacements.push((desc.visibility().clone(), desc.syntax().clone()));
+                    replacements.push((desc.visibility(), desc.syntax().clone()));
                 }
             });
         });
@@ -401,11 +423,11 @@ fn process_names_and_namerefs_for_import_resolve(
         ctx: &AssistContext,
     ) -> Option<TextRange> {
         //We only need to find in the current file
-        let selection_range = ctx.frange.range;
-        let search_scope = SearchScope::single_file(ctx.frange.file_id);
+        let selection_range = ctx.selection_trimmed();
+        let curr_file_id = ctx.file_id();
+        let search_scope = SearchScope::single_file(curr_file_id);
         let usage_res = def.usages(&ctx.sema).in_scope(search_scope).all();
-        let curr_file_id = ctx.frange.file_id;
-        let file = ctx.sema.parse(ctx.frange.file_id);
+        let file = ctx.sema.parse(curr_file_id);
 
         let mut exists_inside_sel = false;
         let mut exists_outside_sel = false;
@@ -445,11 +467,11 @@ fn process_names_and_namerefs_for_import_resolve(
         let use_stmt_opt: Option<ast::Use> = usage_res.into_iter().find_map(|x| {
             let file_id = x.0;
             let mut use_opt: Option<ast::Use> = None;
-            if file_id == ctx.frange.file_id {
+            if file_id == curr_file_id {
                 (&x.1).into_iter().for_each(|x| {
                     let node_opt: Option<ast::Use> = find_node_at_range(file.syntax(), x.range);
                     if let Some(node) = node_opt {
-                        use_opt = Some(node.clone());
+                        use_opt = Some(node);
                     }
                 });
             }
@@ -506,7 +528,7 @@ fn process_names_and_namerefs_for_import_resolve(
         }
 
         if let Some(use_tree_str) = use_tree_str_opt {
-            let mut use_tree_str = use_tree_str.clone();
+            let mut use_tree_str = use_tree_str;
             use_tree_str.reverse();
             if use_tree_str[0].to_string().contains("super") {
                 let super_path = make::ext::ident_path("super");
@@ -580,161 +602,151 @@ fn does_source_exists_outside_sel_in_same_mod(
 ) -> bool {
     let mut source_exists_outside_sel_in_same_mod = false;
     match def {
-        Definition::ModuleDef(it) => match it {
-            ModuleDef::Module(x) => {
-                let source = x.definition_source(ctx.db());
-                let have_same_parent;
-                if let Some(ast_module) = &curr_parent_module {
-                    if let Some(hir_module) = x.parent(ctx.db()) {
-                        have_same_parent =
-                            compare_hir_and_ast_module(&ast_module, hir_module, ctx).is_some();
-                    } else {
-                        let source_file_id = source.file_id.original_file(ctx.db());
-                        have_same_parent = source_file_id == curr_file_id;
-                    }
+        Definition::Module(x) => {
+            let source = x.definition_source(ctx.db());
+            let have_same_parent;
+            if let Some(ast_module) = &curr_parent_module {
+                if let Some(hir_module) = x.parent(ctx.db()) {
+                    have_same_parent =
+                        compare_hir_and_ast_module(&ast_module, hir_module, ctx).is_some();
                 } else {
                     let source_file_id = source.file_id.original_file(ctx.db());
                     have_same_parent = source_file_id == curr_file_id;
                 }
+            } else {
+                let source_file_id = source.file_id.original_file(ctx.db());
+                have_same_parent = source_file_id == curr_file_id;
+            }
 
-                if have_same_parent {
-                    match source.value {
-                        ModuleSource::Module(module_) => {
-                            source_exists_outside_sel_in_same_mod =
-                                !selection_range.contains_range(module_.syntax().text_range());
-                        }
-                        _ => {}
+            if have_same_parent {
+                match source.value {
+                    ModuleSource::Module(module_) => {
+                        source_exists_outside_sel_in_same_mod =
+                            !selection_range.contains_range(module_.syntax().text_range());
                     }
+                    _ => {}
                 }
             }
-            ModuleDef::Function(x) => {
-                if let Some(source) = x.source(ctx.db()) {
-                    let have_same_parent;
-                    if let Some(ast_module) = &curr_parent_module {
-                        have_same_parent =
-                            compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx)
-                                .is_some();
-                    } else {
-                        let source_file_id = source.file_id.original_file(ctx.db());
-                        have_same_parent = source_file_id == curr_file_id;
-                    }
+        }
+        Definition::Function(x) => {
+            if let Some(source) = x.source(ctx.db()) {
+                let have_same_parent;
+                if let Some(ast_module) = &curr_parent_module {
+                    have_same_parent =
+                        compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx).is_some();
+                } else {
+                    let source_file_id = source.file_id.original_file(ctx.db());
+                    have_same_parent = source_file_id == curr_file_id;
+                }
 
-                    if have_same_parent {
-                        source_exists_outside_sel_in_same_mod =
-                            !selection_range.contains_range(source.value.syntax().text_range());
-                    }
+                if have_same_parent {
+                    source_exists_outside_sel_in_same_mod =
+                        !selection_range.contains_range(source.value.syntax().text_range());
                 }
             }
-            ModuleDef::Adt(x) => {
-                if let Some(source) = x.source(ctx.db()) {
-                    let have_same_parent;
-                    if let Some(ast_module) = &curr_parent_module {
-                        have_same_parent =
-                            compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx)
-                                .is_some();
-                    } else {
-                        let source_file_id = source.file_id.original_file(ctx.db());
-                        have_same_parent = source_file_id == curr_file_id;
-                    }
+        }
+        Definition::Adt(x) => {
+            if let Some(source) = x.source(ctx.db()) {
+                let have_same_parent;
+                if let Some(ast_module) = &curr_parent_module {
+                    have_same_parent =
+                        compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx).is_some();
+                } else {
+                    let source_file_id = source.file_id.original_file(ctx.db());
+                    have_same_parent = source_file_id == curr_file_id;
+                }
 
-                    if have_same_parent {
-                        source_exists_outside_sel_in_same_mod =
-                            !selection_range.contains_range(source.value.syntax().text_range());
-                    }
+                if have_same_parent {
+                    source_exists_outside_sel_in_same_mod =
+                        !selection_range.contains_range(source.value.syntax().text_range());
                 }
             }
-            ModuleDef::Variant(x) => {
-                if let Some(source) = x.source(ctx.db()) {
-                    let have_same_parent;
-                    if let Some(ast_module) = &curr_parent_module {
-                        have_same_parent =
-                            compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx)
-                                .is_some();
-                    } else {
-                        let source_file_id = source.file_id.original_file(ctx.db());
-                        have_same_parent = source_file_id == curr_file_id;
-                    }
+        }
+        Definition::Variant(x) => {
+            if let Some(source) = x.source(ctx.db()) {
+                let have_same_parent;
+                if let Some(ast_module) = &curr_parent_module {
+                    have_same_parent =
+                        compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx).is_some();
+                } else {
+                    let source_file_id = source.file_id.original_file(ctx.db());
+                    have_same_parent = source_file_id == curr_file_id;
+                }
 
-                    if have_same_parent {
-                        source_exists_outside_sel_in_same_mod =
-                            !selection_range.contains_range(source.value.syntax().text_range());
-                    }
+                if have_same_parent {
+                    source_exists_outside_sel_in_same_mod =
+                        !selection_range.contains_range(source.value.syntax().text_range());
                 }
             }
-            ModuleDef::Const(x) => {
-                if let Some(source) = x.source(ctx.db()) {
-                    let have_same_parent;
-                    if let Some(ast_module) = &curr_parent_module {
-                        have_same_parent =
-                            compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx)
-                                .is_some();
-                    } else {
-                        let source_file_id = source.file_id.original_file(ctx.db());
-                        have_same_parent = source_file_id == curr_file_id;
-                    }
+        }
+        Definition::Const(x) => {
+            if let Some(source) = x.source(ctx.db()) {
+                let have_same_parent;
+                if let Some(ast_module) = &curr_parent_module {
+                    have_same_parent =
+                        compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx).is_some();
+                } else {
+                    let source_file_id = source.file_id.original_file(ctx.db());
+                    have_same_parent = source_file_id == curr_file_id;
+                }
 
-                    if have_same_parent {
-                        source_exists_outside_sel_in_same_mod =
-                            !selection_range.contains_range(source.value.syntax().text_range());
-                    }
+                if have_same_parent {
+                    source_exists_outside_sel_in_same_mod =
+                        !selection_range.contains_range(source.value.syntax().text_range());
                 }
             }
-            ModuleDef::Static(x) => {
-                if let Some(source) = x.source(ctx.db()) {
-                    let have_same_parent;
-                    if let Some(ast_module) = &curr_parent_module {
-                        have_same_parent =
-                            compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx)
-                                .is_some();
-                    } else {
-                        let source_file_id = source.file_id.original_file(ctx.db());
-                        have_same_parent = source_file_id == curr_file_id;
-                    }
+        }
+        Definition::Static(x) => {
+            if let Some(source) = x.source(ctx.db()) {
+                let have_same_parent;
+                if let Some(ast_module) = &curr_parent_module {
+                    have_same_parent =
+                        compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx).is_some();
+                } else {
+                    let source_file_id = source.file_id.original_file(ctx.db());
+                    have_same_parent = source_file_id == curr_file_id;
+                }
 
-                    if have_same_parent {
-                        source_exists_outside_sel_in_same_mod =
-                            !selection_range.contains_range(source.value.syntax().text_range());
-                    }
+                if have_same_parent {
+                    source_exists_outside_sel_in_same_mod =
+                        !selection_range.contains_range(source.value.syntax().text_range());
                 }
             }
-            ModuleDef::Trait(x) => {
-                if let Some(source) = x.source(ctx.db()) {
-                    let have_same_parent;
-                    if let Some(ast_module) = &curr_parent_module {
-                        have_same_parent =
-                            compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx)
-                                .is_some();
-                    } else {
-                        let source_file_id = source.file_id.original_file(ctx.db());
-                        have_same_parent = source_file_id == curr_file_id;
-                    }
+        }
+        Definition::Trait(x) => {
+            if let Some(source) = x.source(ctx.db()) {
+                let have_same_parent;
+                if let Some(ast_module) = &curr_parent_module {
+                    have_same_parent =
+                        compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx).is_some();
+                } else {
+                    let source_file_id = source.file_id.original_file(ctx.db());
+                    have_same_parent = source_file_id == curr_file_id;
+                }
 
-                    if have_same_parent {
-                        source_exists_outside_sel_in_same_mod =
-                            !selection_range.contains_range(source.value.syntax().text_range());
-                    }
+                if have_same_parent {
+                    source_exists_outside_sel_in_same_mod =
+                        !selection_range.contains_range(source.value.syntax().text_range());
                 }
             }
-            ModuleDef::TypeAlias(x) => {
-                if let Some(source) = x.source(ctx.db()) {
-                    let have_same_parent;
-                    if let Some(ast_module) = &curr_parent_module {
-                        have_same_parent =
-                            compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx)
-                                .is_some();
-                    } else {
-                        let source_file_id = source.file_id.original_file(ctx.db());
-                        have_same_parent = source_file_id == curr_file_id;
-                    }
+        }
+        Definition::TypeAlias(x) => {
+            if let Some(source) = x.source(ctx.db()) {
+                let have_same_parent;
+                if let Some(ast_module) = &curr_parent_module {
+                    have_same_parent =
+                        compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx).is_some();
+                } else {
+                    let source_file_id = source.file_id.original_file(ctx.db());
+                    have_same_parent = source_file_id == curr_file_id;
+                }
 
-                    if have_same_parent {
-                        source_exists_outside_sel_in_same_mod =
-                            !selection_range.contains_range(source.value.syntax().text_range());
-                    }
+                if have_same_parent {
+                    source_exists_outside_sel_in_same_mod =
+                        !selection_range.contains_range(source.value.syntax().text_range());
                 }
             }
-            _ => {}
-        },
+        }
         _ => {}
     }
 
@@ -763,42 +775,24 @@ fn get_replacements_for_visibilty_change(
         body_items.push(item.clone());
         //Use stmts are ignored
         match item {
-            ast::Item::Const(it) => {
-                replacements.push((it.visibility().clone(), it.syntax().clone()))
-            }
-            ast::Item::Enum(it) => {
-                replacements.push((it.visibility().clone(), it.syntax().clone()))
-            }
-            ast::Item::ExternCrate(it) => {
-                replacements.push((it.visibility().clone(), it.syntax().clone()))
-            }
-            ast::Item::Fn(it) => replacements.push((it.visibility().clone(), it.syntax().clone())),
+            ast::Item::Const(it) => replacements.push((it.visibility(), it.syntax().clone())),
+            ast::Item::Enum(it) => replacements.push((it.visibility(), it.syntax().clone())),
+            ast::Item::ExternCrate(it) => replacements.push((it.visibility(), it.syntax().clone())),
+            ast::Item::Fn(it) => replacements.push((it.visibility(), it.syntax().clone())),
             ast::Item::Impl(it) => impls.push(it),
-            ast::Item::MacroRules(it) => {
-                replacements.push((it.visibility().clone(), it.syntax().clone()))
-            }
-            ast::Item::MacroDef(it) => {
-                replacements.push((it.visibility().clone(), it.syntax().clone()))
-            }
-            ast::Item::Module(it) => {
-                replacements.push((it.visibility().clone(), it.syntax().clone()))
-            }
-            ast::Item::Static(it) => {
-                replacements.push((it.visibility().clone(), it.syntax().clone()))
-            }
+            ast::Item::MacroRules(it) => replacements.push((it.visibility(), it.syntax().clone())),
+            ast::Item::MacroDef(it) => replacements.push((it.visibility(), it.syntax().clone())),
+            ast::Item::Module(it) => replacements.push((it.visibility(), it.syntax().clone())),
+            ast::Item::Static(it) => replacements.push((it.visibility(), it.syntax().clone())),
             ast::Item::Struct(it) => {
-                replacements.push((it.visibility().clone(), it.syntax().clone()));
-                record_field_parents.push((it.visibility().clone(), it.syntax().clone()));
-            }
-            ast::Item::Trait(it) => {
-                replacements.push((it.visibility().clone(), it.syntax().clone()))
-            }
-            ast::Item::TypeAlias(it) => {
-                replacements.push((it.visibility().clone(), it.syntax().clone()))
+                replacements.push((it.visibility(), it.syntax().clone()));
+                record_field_parents.push((it.visibility(), it.syntax().clone()));
             }
+            ast::Item::Trait(it) => replacements.push((it.visibility(), it.syntax().clone())),
+            ast::Item::TypeAlias(it) => replacements.push((it.visibility(), it.syntax().clone())),
             ast::Item::Union(it) => {
-                replacements.push((it.visibility().clone(), it.syntax().clone()));
-                record_field_parents.push((it.visibility().clone(), it.syntax().clone()));
+                replacements.push((it.visibility(), it.syntax().clone()));
+                record_field_parents.push((it.visibility(), it.syntax().clone()));
             }
             _ => (),
         }
@@ -812,7 +806,7 @@ fn get_use_tree_paths_from_path(
     use_tree_str: &mut Vec<ast::Path>,
 ) -> Option<&mut Vec<ast::Path>> {
     path.syntax().ancestors().filter(|x| x.to_string() != path.to_string()).find_map(|x| {
-        if let Some(use_tree) = ast::UseTree::cast(x.clone()) {
+        if let Some(use_tree) = ast::UseTree::cast(x) {
             if let Some(upper_tree_path) = use_tree.path() {
                 if upper_tree_path.to_string() != path.to_string() {
                     use_tree_str.push(upper_tree_path.clone());
@@ -875,9 +869,9 @@ fn test_not_applicable_without_selection() {
         check_assist_not_applicable(
             extract_module,
             r"
-                $0pub struct PublicStruct {
-                    field: i32,
-                }
+$0pub struct PublicStruct {
+    field: i32,
+}
             ",
         )
     }
@@ -914,25 +908,23 @@ fn foo() {
                     let _a = bar();
                 }
 
-                $0
-                struct PrivateStruct {
-                    inner: SomeType,
-                }
+$0struct PrivateStruct {
+    inner: SomeType,
+}
 
-                pub struct PrivateStruct1 {
-                    pub inner: i32,
-                }
+pub struct PrivateStruct1 {
+    pub inner: i32,
+}
 
-                impl PrivateStruct {
-                    fn new() -> Self {
-                         PrivateStruct { inner: SomeType }
-                    }
-                }
+impl PrivateStruct {
+    fn new() -> Self {
+         PrivateStruct { inner: SomeType }
+    }
+}
 
-                fn bar() -> i32 {
-                    2
-                }
-                $0
+fn bar() -> i32 {
+    2
+}$0
             }
             ",
             r"
@@ -963,27 +955,27 @@ fn foo() {
                     let _a = modname::bar();
                 }
 
-                mod modname {
-                    use crate::thirdpartycrate::nest::SomeType;
+mod modname {
+    use crate::thirdpartycrate::nest::SomeType;
 
-                    pub(crate) struct PrivateStruct {
-                        pub(crate) inner: SomeType,
-                    }
+    pub(crate) struct PrivateStruct {
+        pub(crate) inner: SomeType,
+    }
 
-                    pub(crate) struct PrivateStruct1 {
-                        pub(crate) inner: i32,
-                    }
+    pub(crate) struct PrivateStruct1 {
+        pub(crate) inner: i32,
+    }
 
-                    impl PrivateStruct {
-                        pub(crate) fn new() -> Self {
-                             PrivateStruct { inner: SomeType }
-                        }
-                    }
+    impl PrivateStruct {
+        pub(crate) fn new() -> Self {
+             PrivateStruct { inner: SomeType }
+        }
+    }
 
-                    pub(crate) fn bar() -> i32 {
-                        2
-                    }
-                }
+    pub(crate) fn bar() -> i32 {
+        2
+    }
+}
             }
             ",
         );
@@ -994,22 +986,20 @@ fn test_extract_module_for_function_only() {
         check_assist(
             extract_module,
             r"
-                $0
-                fn foo(name: i32) -> i32 {
-                    name + 1
-                }
-                $0
+$0fn foo(name: i32) -> i32 {
+    name + 1
+}$0
 
                 fn bar(name: i32) -> i32 {
                     name + 2
                 }
             ",
             r"
-                mod modname {
-                    pub(crate) fn foo(name: i32) -> i32 {
-                        name + 1
-                    }
-                }
+mod modname {
+    pub(crate) fn foo(name: i32) -> i32 {
+        name + 1
+    }
+}
 
                 fn bar(name: i32) -> i32 {
                     name + 2
@@ -1024,15 +1014,13 @@ fn test_extract_module_for_impl_having_corresponding_adt_in_selection() {
             extract_module,
             r"
             mod impl_play {
-                $0
-                struct A {}
+$0struct A {}
 
-                impl A {
-                    pub fn new_a() -> i32 {
-                        2
-                    }
-                }
-                $0
+impl A {
+    pub fn new_a() -> i32 {
+        2
+    }
+}$0
 
                 fn a() {
                     let _a = A::new_a();
@@ -1041,15 +1029,15 @@ fn a() {
             ",
             r"
             mod impl_play {
-                mod modname {
-                    pub(crate) struct A {}
+mod modname {
+    pub(crate) struct A {}
 
-                    impl A {
-                        pub(crate) fn new_a() -> i32 {
-                            2
-                        }
-                    }
-                }
+    impl A {
+        pub(crate) fn new_a() -> i32 {
+            2
+        }
+    }
+}
 
                 fn a() {
                     let _a = modname::A::new_a();
@@ -1072,11 +1060,9 @@ mod foo {
             mod bar {
                 use super::foo::{PrivateStruct, PrivateStruct1};
 
-                $0
-                struct Strukt {
-                    field: PrivateStruct,
-                }
-                $0
+$0struct Strukt {
+    field: PrivateStruct,
+}$0
 
                 struct Strukt1 {
                     field: PrivateStruct1,
@@ -1092,13 +1078,13 @@ mod foo {
             mod bar {
                 use super::foo::{PrivateStruct1};
 
-                mod modname {
-                    use super::super::foo::PrivateStruct;
+mod modname {
+    use super::super::foo::PrivateStruct;
 
-                    pub(crate) struct Strukt {
-                        pub(crate) field: PrivateStruct,
-                    }
-                }
+    pub(crate) struct Strukt {
+        pub(crate) field: PrivateStruct,
+    }
+}
 
                 struct Strukt1 {
                     field: PrivateStruct1,
@@ -1120,11 +1106,9 @@ mod foo {
             mod bar {
                 use super::foo::PrivateStruct;
 
-                $0
-                struct Strukt {
-                    field: PrivateStruct,
-                }
-                $0
+$0struct Strukt {
+    field: PrivateStruct,
+}$0
 
                 struct Strukt1 {
                     field: PrivateStruct,
@@ -1139,13 +1123,13 @@ mod foo {
             mod bar {
                 use super::foo::PrivateStruct;
 
-                mod modname {
-                    use super::super::foo::PrivateStruct;
+mod modname {
+    use super::super::foo::PrivateStruct;
 
-                    pub(crate) struct Strukt {
-                        pub(crate) field: PrivateStruct,
-                    }
-                }
+    pub(crate) struct Strukt {
+        pub(crate) field: PrivateStruct,
+    }
+}
 
                 struct Strukt1 {
                     field: PrivateStruct,
@@ -1163,11 +1147,9 @@ fn test_import_resolve_when_its_inside_and_outside_selection_and_source_is_in_sa
             mod bar {
                 pub struct PrivateStruct;
 
-                $0
-                struct Strukt {
-                    field: PrivateStruct,
-                }
-                $0
+$0struct Strukt {
+    field: PrivateStruct,
+}$0
 
                 struct Strukt1 {
                     field: PrivateStruct,
@@ -1178,13 +1160,13 @@ struct Strukt1 {
             mod bar {
                 pub struct PrivateStruct;
 
-                mod modname {
-                    use super::PrivateStruct;
+mod modname {
+    use super::PrivateStruct;
 
-                    pub(crate) struct Strukt {
-                        pub(crate) field: PrivateStruct,
-                    }
-                }
+    pub(crate) struct Strukt {
+        pub(crate) field: PrivateStruct,
+    }
+}
 
                 struct Strukt1 {
                     field: PrivateStruct,
@@ -1202,13 +1184,11 @@ fn test_extract_module_for_correspoding_adt_of_impl_present_in_same_mod_but_not_
             mod impl_play {
                 struct A {}
 
-                $0
-                impl A {
-                    pub fn new_a() -> i32 {
-                        2
-                    }
-                }
-                $0
+$0impl A {
+    pub fn new_a() -> i32 {
+        2
+    }
+}$0
 
                 fn a() {
                     let _a = A::new_a();
@@ -1219,15 +1199,15 @@ fn a() {
             mod impl_play {
                 struct A {}
 
-                mod modname {
-                    use super::A;
+mod modname {
+    use super::A;
 
-                    impl A {
-                        pub(crate) fn new_a() -> i32 {
-                            2
-                        }
-                    }
-                }
+    impl A {
+        pub(crate) fn new_a() -> i32 {
+            2
+        }
+    }
+}
 
                 fn a() {
                     let _a = A::new_a();
@@ -1249,13 +1229,11 @@ pub struct A {}
             mod impl_play {
                 use super::foo::A;
 
-                $0
-                impl A {
-                    pub fn new_a() -> i32 {
-                        2
-                    }
-                }
-                $0
+$0impl A {
+    pub fn new_a() -> i32 {
+        2
+    }
+}$0
 
                 fn a() {
                     let _a = A::new_a();
@@ -1269,15 +1247,15 @@ pub struct A {}
             mod impl_play {
                 use super::foo::A;
 
-                mod modname {
-                    use super::super::foo::A;
+mod modname {
+    use super::super::foo::A;
 
-                    impl A {
-                        pub(crate) fn new_a() -> i32 {
-                            2
-                        }
-                    }
-                }
+    impl A {
+        pub(crate) fn new_a() -> i32 {
+            2
+        }
+    }
+}
 
                 fn a() {
                     let _a = A::new_a();
@@ -1295,42 +1273,40 @@ fn test_import_resolve_for_trait_bounds_on_function() {
             mod impl_play2 {
                 trait JustATrait {}
 
-                $0
-                struct A {}
+$0struct A {}
 
-                fn foo<T: JustATrait>(arg: T) -> T {
-                    arg
-                }
+fn foo<T: JustATrait>(arg: T) -> T {
+    arg
+}
 
-                impl JustATrait for A {}
+impl JustATrait for A {}
 
-                fn bar() {
-                    let a = A {};
-                    foo(a);
-                }
-                $0
+fn bar() {
+    let a = A {};
+    foo(a);
+}$0
             }
             ",
             r"
             mod impl_play2 {
                 trait JustATrait {}
 
-                mod modname {
-                    use super::JustATrait;
+mod modname {
+    use super::JustATrait;
 
-                    pub(crate) struct A {}
+    pub(crate) struct A {}
 
-                    pub(crate) fn foo<T: JustATrait>(arg: T) -> T {
-                        arg
-                    }
+    pub(crate) fn foo<T: JustATrait>(arg: T) -> T {
+        arg
+    }
 
-                    impl JustATrait for A {}
+    impl JustATrait for A {}
 
-                    pub(crate) fn bar() {
-                        let a = A {};
-                        foo(a);
-                    }
-                }
+    pub(crate) fn bar() {
+        let a = A {};
+        foo(a);
+    }
+}
             }
             ",
         )
@@ -1342,20 +1318,18 @@ fn test_extract_module_for_module() {
             extract_module,
             r"
             mod impl_play2 {
-                $0
-                mod impl_play {
-                    pub struct A {}
-                }
-                $0
+$0mod impl_play {
+    pub struct A {}
+}$0
             }
             ",
             r"
             mod impl_play2 {
-                mod modname {
-                    pub(crate) mod impl_play {
-                        pub struct A {}
-                    }
-                }
+mod modname {
+    pub(crate) mod impl_play {
+        pub struct A {}
+    }
+}
             }
             ",
         )
@@ -1376,11 +1350,9 @@ pub struct Strukt {
             }
 
             fn main() {
-                $0
-                struct Strukt1 {
+                $0struct Strukt1 {
                     field: Strukt,
-                }
-                $0
+                }$0
             }
             //- /foo.rs
             pub struct PrivateStruct;