From 9c8a57ed08a4341f881302c81633bf33ac99a6ed Mon Sep 17 00:00:00 2001 From: roife Date: Thu, 14 Mar 2024 02:00:39 +0800 Subject: [PATCH] fix: simplify extract_module --- .../src/handlers/extract_module.rs | 490 +++++++----------- 1 file changed, 182 insertions(+), 308 deletions(-) diff --git a/crates/ide-assists/src/handlers/extract_module.rs b/crates/ide-assists/src/handlers/extract_module.rs index af834c8a53d..95bb4e174be 100644 --- a/crates/ide-assists/src/handlers/extract_module.rs +++ b/crates/ide-assists/src/handlers/extract_module.rs @@ -16,7 +16,7 @@ ast::{ self, edit::{AstNodeEdit, IndentLevel}, - make, HasName, HasVisibility, + make, HasVisibility, }, match_ast, ted, AstNode, SourceFile, SyntaxKind::{self, WHITESPACE}, @@ -134,16 +134,13 @@ pub(crate) fn extract_module(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti let mut body = body_items.join("\n\n"); if let Some(impl_) = &impl_parent { - let mut impl_body_def = String::new(); - if let Some(self_ty) = impl_.self_ty() { - { - let impl_indent = old_item_indent + 1; - format_to!( - impl_body_def, - "{impl_indent}impl {self_ty} {{\n{body}\n{impl_indent}}}", - ); - } + let impl_indent = old_item_indent + 1; + let mut impl_body_def = String::new(); + format_to!( + impl_body_def, + "{impl_indent}impl {self_ty} {{\n{body}\n{impl_indent}}}", + ); body = impl_body_def; // Add the import for enum/struct corresponding to given impl block @@ -156,7 +153,6 @@ pub(crate) fn extract_module(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti } let mut module_def = String::new(); - let module_name = module.name; format_to!(module_def, "mod {module_name} {{\n{body}\n{old_item_indent}}}"); @@ -177,10 +173,6 @@ pub(crate) fn extract_module(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti 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); - } - if let Some(impl_) = impl_parent { // Remove complete impl block if it has only one child (as such it will be empty // after deleting that child) @@ -199,6 +191,14 @@ pub(crate) fn extract_module(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti builder.insert(impl_.syntax().text_range().end(), format!("\n\n{module_def}")); } else { + for import_path_text_range in import_paths_to_be_removed { + if module.text_range.intersect(import_path_text_range).is_some() { + module.text_range = module.text_range.cover(import_path_text_range); + } else { + builder.delete(import_path_text_range); + } + } + builder.replace(module.text_range, module_def) } }, @@ -394,78 +394,43 @@ fn change_visibility(&mut self, record_fields: Vec) { fn resolve_imports( &mut self, - curr_parent_module: Option, + module: Option, ctx: &AssistContext<'_>, ) -> Vec { - let mut import_paths_to_be_removed: Vec = vec![]; - let mut node_set: FxHashSet = FxHashSet::default(); + let mut imports_to_remove = vec![]; + let mut node_set = FxHashSet::default(); for item in self.body_items.clone() { - for x in item.syntax().descendants() { - if let Some(name) = ast::Name::cast(x.clone()) { - if let Some(name_classify) = NameClass::classify(&ctx.sema, &name) { - //Necessary to avoid two same names going through - if !node_set.contains(&name.syntax().to_string()) { - node_set.insert(name.syntax().to_string()); - let def_opt: Option = match name_classify { - NameClass::Definition(def) => Some(def), - _ => None, - }; - - if let Some(def) = def_opt { - if let Some(import_path) = self - .process_names_and_namerefs_for_import_resolve( - def, - name.syntax(), - &curr_parent_module, - ctx, - ) - { - check_intersection_and_push( - &mut import_paths_to_be_removed, - import_path, - ); - } - } + item.syntax() + .descendants() + .filter_map(|x| { + if let Some(name) = ast::Name::cast(x.clone()) { + NameClass::classify(&ctx.sema, &name).and_then(|nc| match nc { + NameClass::Definition(def) => Some((name.syntax().clone(), def)), + _ => None, + }) + } else if let Some(name_ref) = ast::NameRef::cast(x) { + NameRefClass::classify(&ctx.sema, &name_ref).and_then(|nc| match nc { + NameRefClass::Definition(def) => Some((name_ref.syntax().clone(), def)), + _ => None, + }) + } else { + None + } + }) + .for_each(|(node, def)| { + if node_set.insert(node.to_string()) { + if let Some(import) = self.process_def_in_sel(def, &node, &module, ctx) { + check_intersection_and_push(&mut imports_to_remove, import); } } - } - - if let Some(name_ref) = ast::NameRef::cast(x) { - if let Some(name_classify) = NameRefClass::classify(&ctx.sema, &name_ref) { - //Necessary to avoid two same names going through - if !node_set.contains(&name_ref.syntax().to_string()) { - node_set.insert(name_ref.syntax().to_string()); - let def_opt: Option = match name_classify { - NameRefClass::Definition(def) => Some(def), - _ => None, - }; - - if let Some(def) = def_opt { - if let Some(import_path) = self - .process_names_and_namerefs_for_import_resolve( - def, - name_ref.syntax(), - &curr_parent_module, - ctx, - ) - { - check_intersection_and_push( - &mut import_paths_to_be_removed, - import_path, - ); - } - } - } - } - } - } + }) } - import_paths_to_be_removed + imports_to_remove } - fn process_names_and_namerefs_for_import_resolve( + fn process_def_in_sel( &mut self, def: Definition, node_syntax: &SyntaxNode, @@ -474,51 +439,38 @@ fn process_names_and_namerefs_for_import_resolve( ) -> Option { //We only need to find in the current file 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 file = ctx.sema.parse(curr_file_id); + let file_id = ctx.file_id(); + let usage_res = def.usages(&ctx.sema).in_scope(&SearchScope::single_file(file_id)).all(); + let file = ctx.sema.parse(file_id); + // track uses which does not exists in `Use` let mut exists_inside_sel = false; let mut exists_outside_sel = false; - for (_, refs) in usage_res.iter() { - let mut non_use_nodes_itr = refs.iter().filter_map(|x| { - if find_node_at_range::(file.syntax(), x.range).is_none() { - let path_opt = find_node_at_range::(file.syntax(), x.range); - return path_opt; - } - - None - }); - - if non_use_nodes_itr - .clone() - .any(|x| !selection_range.contains_range(x.syntax().text_range())) + 'outside: for (_, refs) in usage_res.iter() { + for x in refs + .iter() + .filter(|x| find_node_at_range::(file.syntax(), x.range).is_none()) + .filter_map(|x| find_node_at_range::(file.syntax(), x.range)) { - exists_outside_sel = true; - } - if non_use_nodes_itr.any(|x| selection_range.contains_range(x.syntax().text_range())) { - exists_inside_sel = true; + let in_selectin = selection_range.contains_range(x.syntax().text_range()); + exists_inside_sel |= in_selectin; + exists_outside_sel |= !in_selectin; + + if exists_inside_sel && exists_outside_sel { + break 'outside; + } } } - let source_exists_outside_sel_in_same_mod = does_source_exists_outside_sel_in_same_mod( - def, - ctx, - curr_parent_module, - selection_range, - curr_file_id, - ); + let def_in_mod_and_out_sel = + check_def_in_mod_and_out_sel(def, ctx, curr_parent_module, selection_range, file_id); - let use_stmt_opt: Option = usage_res.into_iter().find_map(|(file_id, refs)| { - if file_id == curr_file_id { - refs.into_iter() - .rev() - .find_map(|fref| find_node_at_range(file.syntax(), fref.range)) - } else { - None - } - }); + // Find use stmt that use def in current file + let use_stmt: Option = usage_res + .into_iter() + .filter(|(use_file_id, _)| *use_file_id == file_id) + .flat_map(|(_, refs)| refs.into_iter().rev()) + .find_map(|fref| find_node_at_range(file.syntax(), fref.range)); let mut use_tree_str_opt: Option> = None; //Exists inside and outside selection @@ -539,32 +491,32 @@ fn process_names_and_namerefs_for_import_resolve( //If use_stmt exists, find the use_tree_str, reconstruct it inside new module //If not, insert a use stmt with super and the given nameref - if let Some((use_tree_str, _)) = - self.process_use_stmt_for_import_resolve(use_stmt_opt, node_syntax) - { - use_tree_str_opt = Some(use_tree_str); - } else if source_exists_outside_sel_in_same_mod { - //Considered only after use_stmt is not present - //source_exists_outside_sel_in_same_mod | exists_outside_sel(exists_inside_sel = - //true for all cases) - // false | false -> Do nothing - // false | true -> If source is in selection -> nothing to do, If source is outside - // mod -> ust_stmt transversal - // true | false -> super import insertion - // true | true -> super import insertion - self.make_use_stmt_of_node_with_super(node_syntax); + match self.process_use_stmt_for_import_resolve(use_stmt, node_syntax) { + Some((use_tree_str, _)) => use_tree_str_opt = Some(use_tree_str), + None if def_in_mod_and_out_sel => { + //Considered only after use_stmt is not present + //def_in_mod_and_out_sel | exists_outside_sel(exists_inside_sel = + //true for all cases) + // false | false -> Do nothing + // false | true -> If source is in selection -> nothing to do, If source is outside + // mod -> ust_stmt transversal + // true | false -> super import insertion + // true | true -> super import insertion + self.make_use_stmt_of_node_with_super(node_syntax); + } + None => {} } } else if exists_inside_sel && !exists_outside_sel { //Changes to be made inside new module, and remove import from outside if let Some((mut use_tree_str, text_range_opt)) = - self.process_use_stmt_for_import_resolve(use_stmt_opt, node_syntax) + self.process_use_stmt_for_import_resolve(use_stmt, node_syntax) { if let Some(text_range) = text_range_opt { import_path_to_be_removed = Some(text_range); } - if source_exists_outside_sel_in_same_mod { + if def_in_mod_and_out_sel { if let Some(first_path_in_use_tree) = use_tree_str.last() { let first_path_in_use_tree_str = first_path_in_use_tree.to_string(); if !first_path_in_use_tree_str.contains("super") @@ -577,7 +529,7 @@ fn process_names_and_namerefs_for_import_resolve( } use_tree_str_opt = Some(use_tree_str); - } else if source_exists_outside_sel_in_same_mod { + } else if def_in_mod_and_out_sel { self.make_use_stmt_of_node_with_super(node_syntax); } } @@ -586,13 +538,10 @@ fn process_names_and_namerefs_for_import_resolve( let mut use_tree_str = use_tree_str; use_tree_str.reverse(); - if !(!exists_outside_sel && exists_inside_sel && source_exists_outside_sel_in_same_mod) - { + if exists_outside_sel || !exists_inside_sel || !def_in_mod_and_out_sel { if let Some(first_path_in_use_tree) = use_tree_str.first() { - let first_path_in_use_tree_str = first_path_in_use_tree.to_string(); - if first_path_in_use_tree_str.contains("super") { - let super_path = make::ext::ident_path("super"); - use_tree_str.insert(0, super_path) + if first_path_in_use_tree.to_string().contains("super") { + use_tree_str.insert(0, make::ext::ident_path("super")); } } } @@ -621,33 +570,26 @@ fn make_use_stmt_of_node_with_super(&mut self, node_syntax: &SyntaxNode) -> ast: fn process_use_stmt_for_import_resolve( &self, - use_stmt_opt: Option, + use_stmt: Option, node_syntax: &SyntaxNode, ) -> Option<(Vec, Option)> { - if let Some(use_stmt) = use_stmt_opt { - for desc in use_stmt.syntax().descendants() { - if let Some(path_seg) = ast::PathSegment::cast(desc) { - if path_seg.syntax().to_string() == node_syntax.to_string() { - let mut use_tree_str = vec![path_seg.parent_path()]; - get_use_tree_paths_from_path(path_seg.parent_path(), &mut use_tree_str); - for ancs in path_seg.syntax().ancestors() { - //Here we are looking for use_tree with same string value as node - //passed above as the range_to_remove function looks for a comma and - //then includes it in the text range to remove it. But the comma only - //appears at the use_tree level - if let Some(use_tree) = ast::UseTree::cast(ancs) { - if use_tree.syntax().to_string() == node_syntax.to_string() { - return Some(( - use_tree_str, - Some(range_to_remove(use_tree.syntax())), - )); - } - } - } + let use_stmt = use_stmt?; + for path_seg in use_stmt.syntax().descendants().filter_map(ast::PathSegment::cast) { + if path_seg.syntax().to_string() == node_syntax.to_string() { + let mut use_tree_str = vec![path_seg.parent_path()]; + get_use_tree_paths_from_path(path_seg.parent_path(), &mut use_tree_str); - return Some((use_tree_str, None)); + //Here we are looking for use_tree with same string value as node + //passed above as the range_to_remove function looks for a comma and + //then includes it in the text range to remove it. But the comma only + //appears at the use_tree level + for use_tree in path_seg.syntax().ancestors().filter_map(ast::UseTree::cast) { + if use_tree.syntax().to_string() == node_syntax.to_string() { + return Some((use_tree_str, Some(range_to_remove(use_tree.syntax())))); } } + + return Some((use_tree_str, None)); } } @@ -676,145 +618,56 @@ fn check_intersection_and_push( import_paths_to_be_removed.push(import_path); } -fn does_source_exists_outside_sel_in_same_mod( +fn check_def_in_mod_and_out_sel( def: Definition, ctx: &AssistContext<'_>, curr_parent_module: &Option, selection_range: TextRange, curr_file_id: FileId, ) -> bool { - let mut source_exists_outside_sel_in_same_mod = false; + macro_rules! check_item { + ($x:ident) => { + if let Some(source) = $x.source(ctx.db()) { + let have_same_parent = if let Some(ast_module) = &curr_parent_module { + ctx.sema.to_module_def(ast_module).is_some_and(|it| it == $x.module(ctx.db())) + } else { + source.file_id.original_file(ctx.db()) == curr_file_id + }; + + if have_same_parent { + return !selection_range.contains_range(source.value.syntax().text_range()); + } + } + }; + } + match def { 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()) { - compare_hir_and_ast_module(ast_module, hir_module, ctx).is_some() - } else { - let source_file_id = source.file_id.original_file(ctx.db()); - source_file_id == curr_file_id + let have_same_parent = match (&curr_parent_module, x.parent(ctx.db())) { + (Some(ast_module), Some(hir_module)) => { + ctx.sema.to_module_def(ast_module).is_some_and(|it| it == hir_module) } - } else { - let source_file_id = source.file_id.original_file(ctx.db()); - source_file_id == curr_file_id + _ => source.file_id.original_file(ctx.db()) == curr_file_id, }; if have_same_parent { if let ModuleSource::Module(module_) = source.value { - source_exists_outside_sel_in_same_mod = - !selection_range.contains_range(module_.syntax().text_range()); - } - } - } - Definition::Function(x) => { - if let Some(source) = x.source(ctx.db()) { - let have_same_parent = if let Some(ast_module) = &curr_parent_module { - 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()); - 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()); - } - } - } - Definition::Adt(x) => { - if let Some(source) = x.source(ctx.db()) { - let have_same_parent = if let Some(ast_module) = &curr_parent_module { - 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()); - 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()); - } - } - } - Definition::Variant(x) => { - if let Some(source) = x.source(ctx.db()) { - let have_same_parent = if let Some(ast_module) = &curr_parent_module { - 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()); - 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()); - } - } - } - Definition::Const(x) => { - if let Some(source) = x.source(ctx.db()) { - let have_same_parent = if let Some(ast_module) = &curr_parent_module { - 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()); - 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()); - } - } - } - Definition::Static(x) => { - if let Some(source) = x.source(ctx.db()) { - let have_same_parent = if let Some(ast_module) = &curr_parent_module { - 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()); - 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()); - } - } - } - Definition::Trait(x) => { - if let Some(source) = x.source(ctx.db()) { - let have_same_parent = if let Some(ast_module) = &curr_parent_module { - 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()); - 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()); - } - } - } - Definition::TypeAlias(x) => { - if let Some(source) = x.source(ctx.db()) { - let have_same_parent = if let Some(ast_module) = &curr_parent_module { - 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()); - 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()); + return !selection_range.contains_range(module_.syntax().text_range()); } } } + Definition::Function(x) => check_item!(x), + Definition::Adt(x) => check_item!(x), + Definition::Variant(x) => check_item!(x), + Definition::Const(x) => check_item!(x), + Definition::Static(x) => check_item!(x), + Definition::Trait(x) => check_item!(x), + Definition::TypeAlias(x) => check_item!(x), _ => {} } - source_exists_outside_sel_in_same_mod + false } fn get_replacements_for_visibility_change( @@ -834,24 +687,30 @@ fn get_replacements_for_visibility_change( *item = item.clone_for_update(); } //Use stmts are ignored + macro_rules! push_to_replacement { + ($it:ident) => { + replacements.push(($it.visibility(), $it.syntax().clone())) + }; + } + match item { - 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::Const(it) => push_to_replacement!(it), + ast::Item::Enum(it) => push_to_replacement!(it), + ast::Item::ExternCrate(it) => push_to_replacement!(it), + ast::Item::Fn(it) => push_to_replacement!(it), //Associated item's visibility should not be changed ast::Item::Impl(it) if it.for_token().is_none() => impls.push(it.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::MacroDef(it) => push_to_replacement!(it), + ast::Item::Module(it) => push_to_replacement!(it), + ast::Item::Static(it) => push_to_replacement!(it), ast::Item::Struct(it) => { - replacements.push((it.visibility(), it.syntax().clone())); + push_to_replacement!(it); 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::Trait(it) => push_to_replacement!(it), + ast::Item::TypeAlias(it) => push_to_replacement!(it), ast::Item::Union(it) => { - replacements.push((it.visibility(), it.syntax().clone())); + push_to_replacement!(it); record_field_parents.push((it.visibility(), it.syntax().clone())); } _ => (), @@ -865,8 +724,11 @@ fn get_use_tree_paths_from_path( path: ast::Path, use_tree_str: &mut Vec, ) -> Option<&mut Vec> { - path.syntax().ancestors().filter(|x| x.to_string() != path.to_string()).find_map(|x| { - if let Some(use_tree) = ast::UseTree::cast(x) { + path.syntax() + .ancestors() + .filter(|x| x.to_string() != path.to_string()) + .filter_map(ast::UseTree::cast) + .find_map(|use_tree| { 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()); @@ -874,9 +736,8 @@ fn get_use_tree_paths_from_path( return Some(use_tree); } } - } - None - })?; + None + })?; Some(use_tree_str) } @@ -890,20 +751,6 @@ fn add_change_vis(vis: Option, node_or_token_opt: Option, -) -> Option<()> { - let hir_mod_name = hir_module.name(ctx.db())?; - let ast_mod_name = ast_module.name()?; - if hir_mod_name.display(ctx.db()).to_string() != ast_mod_name.to_string() { - return None; - } - - Some(()) -} - fn indent_range_before_given_node(node: &SyntaxNode) -> Option { node.siblings_with_tokens(syntax::Direction::Prev) .find(|x| x.kind() == WHITESPACE) @@ -1799,6 +1646,33 @@ pub(crate) struct S { pub(crate) condvar: B, } } +"#, + ); + } + + #[test] + fn test_remove_import_path_inside_selection() { + check_assist( + extract_module, + r#" +$0struct Point; +impl Point { + pub const fn direction(self, other: Self) -> Option { + Some(Vertical) + } +} + +pub enum Direction { + Horizontal, + Vertical, +} +use Direction::{Horizontal, Vertical};$0 + +fn main() { + let x = Vertical; +} +"#, + r#" "#, ); }