2 collections::{HashMap, HashSet},
6 use hir::{HasSource, ModuleSource};
8 assists::{AssistId, AssistKind},
10 defs::{Definition, NameClass, NameRefClass},
11 search::{FileReference, SearchScope},
15 algo::find_node_at_range,
18 edit::{AstNodeEdit, IndentLevel},
19 make, HasName, HasVisibility,
21 match_ast, ted, AstNode, SourceFile,
22 SyntaxKind::{self, WHITESPACE},
23 SyntaxNode, TextRange,
26 use crate::{AssistContext, Assists};
28 use super::remove_unused_param::range_to_remove;
30 // Assist: extract_module
32 // Extracts a selected region as separate module. All the references, visibility and imports are
36 // $0fn foo(name: i32) -> i32 {
40 // fn bar(name: i32) -> i32 {
47 // pub(crate) fn foo(name: i32) -> i32 {
52 // fn bar(name: i32) -> i32 {
56 pub(crate) fn extract_module(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
57 if ctx.has_empty_selection() {
61 let node = ctx.covering_element();
62 let node = match node {
63 syntax::NodeOrToken::Node(n) => n,
64 syntax::NodeOrToken::Token(t) => t.parent()?,
67 //If the selection is inside impl block, we need to place new module outside impl block,
68 //as impl blocks cannot contain modules
70 let mut impl_parent: Option<ast::Impl> = None;
71 let mut impl_child_count: usize = 0;
72 if let Some(parent_assoc_list) = node.parent() {
73 if let Some(parent_impl) = parent_assoc_list.parent() {
74 if let Some(impl_) = ast::Impl::cast(parent_impl) {
75 impl_child_count = parent_assoc_list.children().count();
76 impl_parent = Some(impl_);
81 let mut curr_parent_module: Option<ast::Module> = None;
82 if let Some(mod_syn_opt) = node.ancestors().find(|it| ast::Module::can_cast(it.kind())) {
83 curr_parent_module = ast::Module::cast(mod_syn_opt);
86 let mut module = extract_target(&node, ctx.selection_trimmed())?;
87 if module.body_items.is_empty() {
91 let old_item_indent = module.body_items[0].indent_level();
94 AssistId("extract_module", AssistKind::RefactorExtract),
98 //This takes place in three steps:
100 //- Firstly, we will update the references(usages) e.g. converting a
101 // function call bar() to modname::bar(), and similarly for other items
103 //- Secondly, changing the visibility of each item inside the newly selected module
104 // i.e. making a fn a() {} to pub(crate) fn a() {}
106 //- Thirdly, resolving all the imports this includes removing paths from imports
107 // outside the module, shifting/cloning them inside new module, or shifting the imports, or making
108 // new import statements
110 //We are getting item usages and record_fields together, record_fields
111 //for change_visibility and usages for first point mentioned above in the process
112 let (usages_to_be_processed, record_fields) = module.get_usages_and_record_fields(ctx);
114 let import_paths_to_be_removed = module.resolve_imports(curr_parent_module, ctx);
115 module.change_visibility(record_fields);
117 let mut body_items: Vec<String> = Vec::new();
118 let mut items_to_be_processed: Vec<ast::Item> = module.body_items.clone();
119 let mut new_item_indent = old_item_indent + 1;
121 if impl_parent.is_some() {
122 new_item_indent = old_item_indent + 2;
124 items_to_be_processed = [module.use_items.clone(), items_to_be_processed].concat();
127 for item in items_to_be_processed {
128 let item = item.indent(IndentLevel(1));
129 let mut indented_item = String::new();
130 format_to!(indented_item, "{}{}", new_item_indent, item.to_string());
131 body_items.push(indented_item);
134 let mut body = body_items.join("\n\n");
136 if let Some(impl_) = &impl_parent {
137 let mut impl_body_def = String::new();
139 if let Some(self_ty) = impl_.self_ty() {
142 "{}impl {} {{\n{}\n{}}}",
149 body = impl_body_def;
151 // Add the import for enum/struct corresponding to given impl block
152 module.make_use_stmt_of_node_with_super(self_ty.syntax());
153 for item in module.use_items {
154 let mut indented_item = String::new();
155 format_to!(indented_item, "{}{}", old_item_indent + 1, item.to_string());
156 body = format!("{}\n\n{}", indented_item, body);
161 let mut module_def = String::new();
163 format_to!(module_def, "mod {} {{\n{}\n{}}}", module.name, body, old_item_indent);
165 let mut usages_to_be_updated_for_curr_file = vec![];
166 for usages_to_be_updated_for_file in usages_to_be_processed {
167 if usages_to_be_updated_for_file.0 == ctx.file_id() {
168 usages_to_be_updated_for_curr_file = usages_to_be_updated_for_file.1;
171 builder.edit_file(usages_to_be_updated_for_file.0);
172 for usage_to_be_processed in usages_to_be_updated_for_file.1 {
173 builder.replace(usage_to_be_processed.0, usage_to_be_processed.1)
177 builder.edit_file(ctx.file_id());
178 for usage_to_be_processed in usages_to_be_updated_for_curr_file {
179 builder.replace(usage_to_be_processed.0, usage_to_be_processed.1)
182 for import_path_text_range in import_paths_to_be_removed {
183 builder.delete(import_path_text_range);
186 if let Some(impl_) = impl_parent {
187 // Remove complete impl block if it has only one child (as such it will be empty
188 // after deleting that child)
189 let node_to_be_removed = if impl_child_count == 1 {
192 //Remove selected node
196 builder.delete(node_to_be_removed.text_range());
197 // Remove preceding indentation from node
198 if let Some(range) = indent_range_before_given_node(node_to_be_removed) {
199 builder.delete(range);
202 builder.insert(impl_.syntax().text_range().end(), format!("\n\n{}", module_def));
204 builder.replace(module.text_range, module_def)
212 text_range: TextRange,
214 /// All items except use items.
215 body_items: Vec<ast::Item>,
216 /// Use items are kept separately as they help when the selection is inside an impl block,
217 /// we can directly take these items and keep them outside generated impl block inside
218 /// generated module.
219 use_items: Vec<ast::Item>,
222 fn extract_target(node: &SyntaxNode, selection_range: TextRange) -> Option<Module> {
223 let selected_nodes = node
225 .filter(|node| selection_range.contains_range(node.text_range()))
226 .chain(iter::once(node.clone()));
227 let (use_items, body_items) = selected_nodes
228 .filter_map(ast::Item::cast)
229 .partition(|item| matches!(item, ast::Item::Use(..)));
231 Some(Module { text_range: selection_range, name: "modname", body_items, use_items })
235 fn get_usages_and_record_fields(
237 ctx: &AssistContext<'_>,
238 ) -> (HashMap<FileId, Vec<(TextRange, String)>>, Vec<SyntaxNode>) {
239 let mut adt_fields = Vec::new();
240 let mut refs: HashMap<FileId, Vec<(TextRange, String)>> = HashMap::new();
242 //Here impl is not included as each item inside impl will be tied to the parent of
243 //implementing block(a struct, enum, etc), if the parent is in selected module, it will
244 //get updated by ADT section given below or if it is not, then we dont need to do any operation
245 for item in &self.body_items {
247 match (item.syntax()) {
249 if let Some( nod ) = ctx.sema.to_def(&it) {
250 let node_def = Definition::Adt(nod);
251 self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
253 //Enum Fields are not allowed to explicitly specify pub, it is implied
255 ast::Adt::Struct(x) => {
256 if let Some(field_list) = x.field_list() {
258 ast::FieldList::RecordFieldList(record_field_list) => {
259 record_field_list.fields().for_each(|record_field| {
260 adt_fields.push(record_field.syntax().clone());
263 ast::FieldList::TupleFieldList(tuple_field_list) => {
264 tuple_field_list.fields().for_each(|tuple_field| {
265 adt_fields.push(tuple_field.syntax().clone());
271 ast::Adt::Union(x) => {
272 if let Some(record_field_list) = x.record_field_list() {
273 record_field_list.fields().for_each(|record_field| {
274 adt_fields.push(record_field.syntax().clone());
278 ast::Adt::Enum(_) => {},
282 ast::TypeAlias(it) => {
283 if let Some( nod ) = ctx.sema.to_def(&it) {
284 let node_def = Definition::TypeAlias(nod);
285 self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
289 if let Some( nod ) = ctx.sema.to_def(&it) {
290 let node_def = Definition::Const(nod);
291 self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
295 if let Some( nod ) = ctx.sema.to_def(&it) {
296 let node_def = Definition::Static(nod);
297 self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
301 if let Some( nod ) = ctx.sema.to_def(&it) {
302 let node_def = Definition::Function(nod);
303 self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
307 if let Some(nod) = ctx.sema.to_def(&it) {
308 self.expand_and_group_usages_file_wise(ctx, Definition::Macro(nod), &mut refs);
319 fn expand_and_group_usages_file_wise(
321 ctx: &AssistContext<'_>,
322 node_def: Definition,
323 refs_in_files: &mut HashMap<FileId, Vec<(TextRange, String)>>,
325 for (file_id, references) in node_def.usages(&ctx.sema).all() {
326 let source_file = ctx.sema.parse(file_id);
327 let usages_in_file = references
329 .filter_map(|usage| self.get_usage_to_be_processed(&source_file, usage));
330 refs_in_files.entry(file_id).or_default().extend(usages_in_file);
334 fn get_usage_to_be_processed(
336 source_file: &SourceFile,
337 FileReference { range, name, .. }: FileReference,
338 ) -> Option<(TextRange, String)> {
339 let path: ast::Path = find_node_at_range(source_file.syntax(), range)?;
341 for desc in path.syntax().descendants() {
342 if desc.to_string() == name.syntax().to_string()
343 && !self.text_range.contains_range(desc.text_range())
345 if let Some(name_ref) = ast::NameRef::cast(desc) {
347 name_ref.syntax().text_range(),
348 format!("{}::{}", self.name, name_ref),
357 fn change_visibility(&mut self, record_fields: Vec<SyntaxNode>) {
358 let (mut replacements, record_field_parents, impls) =
359 get_replacements_for_visibilty_change(&mut self.body_items, false);
361 let mut impl_items: Vec<ast::Item> = impls
363 .flat_map(|impl_| impl_.syntax().descendants())
364 .filter_map(ast::Item::cast)
367 let (mut impl_item_replacements, _, _) =
368 get_replacements_for_visibilty_change(&mut impl_items, true);
370 replacements.append(&mut impl_item_replacements);
372 for (_, field_owner) in record_field_parents {
373 for desc in field_owner.descendants().filter_map(ast::RecordField::cast) {
374 let is_record_field_present =
375 record_fields.clone().into_iter().any(|x| x.to_string() == desc.to_string());
376 if is_record_field_present {
377 replacements.push((desc.visibility(), desc.syntax().clone()));
382 for (vis, syntax) in replacements {
383 let item = syntax.children_with_tokens().find(|node_or_token| {
384 match node_or_token.kind() {
385 // We're skipping comments, doc comments, and attribute macros that may precede the keyword
386 // that the visibility should be placed before.
387 SyntaxKind::COMMENT | SyntaxKind::ATTR | SyntaxKind::WHITESPACE => false,
392 add_change_vis(vis, item);
398 curr_parent_module: Option<ast::Module>,
399 ctx: &AssistContext<'_>,
400 ) -> Vec<TextRange> {
401 let mut import_paths_to_be_removed: Vec<TextRange> = vec![];
402 let mut node_set: HashSet<String> = HashSet::new();
404 for item in self.body_items.clone() {
405 for x in item.syntax().descendants() {
406 if let Some(name) = ast::Name::cast(x.clone()) {
407 if let Some(name_classify) = NameClass::classify(&ctx.sema, &name) {
408 //Necessary to avoid two same names going through
409 if !node_set.contains(&name.syntax().to_string()) {
410 node_set.insert(name.syntax().to_string());
411 let def_opt: Option<Definition> = match name_classify {
412 NameClass::Definition(def) => Some(def),
416 if let Some(def) = def_opt {
417 if let Some(import_path) = self
418 .process_names_and_namerefs_for_import_resolve(
425 check_intersection_and_push(
426 &mut import_paths_to_be_removed,
435 if let Some(name_ref) = ast::NameRef::cast(x) {
436 if let Some(name_classify) = NameRefClass::classify(&ctx.sema, &name_ref) {
437 //Necessary to avoid two same names going through
438 if !node_set.contains(&name_ref.syntax().to_string()) {
439 node_set.insert(name_ref.syntax().to_string());
440 let def_opt: Option<Definition> = match name_classify {
441 NameRefClass::Definition(def) => Some(def),
445 if let Some(def) = def_opt {
446 if let Some(import_path) = self
447 .process_names_and_namerefs_for_import_resolve(
454 check_intersection_and_push(
455 &mut import_paths_to_be_removed,
466 import_paths_to_be_removed
469 fn process_names_and_namerefs_for_import_resolve(
472 node_syntax: &SyntaxNode,
473 curr_parent_module: &Option<ast::Module>,
474 ctx: &AssistContext<'_>,
475 ) -> Option<TextRange> {
476 //We only need to find in the current file
477 let selection_range = ctx.selection_trimmed();
478 let curr_file_id = ctx.file_id();
479 let search_scope = SearchScope::single_file(curr_file_id);
480 let usage_res = def.usages(&ctx.sema).in_scope(search_scope).all();
481 let file = ctx.sema.parse(curr_file_id);
483 let mut exists_inside_sel = false;
484 let mut exists_outside_sel = false;
485 for (_, refs) in usage_res.iter() {
486 let mut non_use_nodes_itr = refs.iter().filter_map(|x| {
487 if find_node_at_range::<ast::Use>(file.syntax(), x.range).is_none() {
488 let path_opt = find_node_at_range::<ast::Path>(file.syntax(), x.range);
497 .any(|x| !selection_range.contains_range(x.syntax().text_range()))
499 exists_outside_sel = true;
501 if non_use_nodes_itr.any(|x| selection_range.contains_range(x.syntax().text_range())) {
502 exists_inside_sel = true;
506 let source_exists_outside_sel_in_same_mod = does_source_exists_outside_sel_in_same_mod(
514 let use_stmt_opt: Option<ast::Use> = usage_res.into_iter().find_map(|(file_id, refs)| {
515 if file_id == curr_file_id {
518 .find_map(|fref| find_node_at_range(file.syntax(), fref.range))
524 let mut use_tree_str_opt: Option<Vec<ast::Path>> = None;
525 //Exists inside and outside selection
526 // - Use stmt for item is present -> get the use_tree_str and reconstruct the path in new
528 // - Use stmt for item is not present ->
529 //If it is not found, the definition is either ported inside new module or it stays
531 //- Def is inside: Nothing to import
532 //- Def is outside: Import it inside with super
534 //Exists inside selection but not outside -> Check for the import of it in original module,
535 //get the use_tree_str, reconstruct the use stmt in new module
537 let mut import_path_to_be_removed: Option<TextRange> = None;
538 if exists_inside_sel && exists_outside_sel {
539 //Changes to be made only inside new module
541 //If use_stmt exists, find the use_tree_str, reconstruct it inside new module
542 //If not, insert a use stmt with super and the given nameref
543 if let Some((use_tree_str, _)) =
544 self.process_use_stmt_for_import_resolve(use_stmt_opt, node_syntax)
546 use_tree_str_opt = Some(use_tree_str);
547 } else if source_exists_outside_sel_in_same_mod {
548 //Considered only after use_stmt is not present
549 //source_exists_outside_sel_in_same_mod | exists_outside_sel(exists_inside_sel =
550 //true for all cases)
551 // false | false -> Do nothing
552 // false | true -> If source is in selection -> nothing to do, If source is outside
553 // mod -> ust_stmt transversal
554 // true | false -> super import insertion
555 // true | true -> super import insertion
556 self.make_use_stmt_of_node_with_super(node_syntax);
558 } else if exists_inside_sel && !exists_outside_sel {
559 //Changes to be made inside new module, and remove import from outside
561 if let Some((mut use_tree_str, text_range_opt)) =
562 self.process_use_stmt_for_import_resolve(use_stmt_opt, node_syntax)
564 if let Some(text_range) = text_range_opt {
565 import_path_to_be_removed = Some(text_range);
568 if source_exists_outside_sel_in_same_mod {
569 if let Some(first_path_in_use_tree) = use_tree_str.last() {
570 let first_path_in_use_tree_str = first_path_in_use_tree.to_string();
571 if !first_path_in_use_tree_str.contains("super")
572 && !first_path_in_use_tree_str.contains("crate")
574 let super_path = make::ext::ident_path("super");
575 use_tree_str.push(super_path);
580 use_tree_str_opt = Some(use_tree_str);
581 } else if source_exists_outside_sel_in_same_mod {
582 self.make_use_stmt_of_node_with_super(node_syntax);
586 if let Some(use_tree_str) = use_tree_str_opt {
587 let mut use_tree_str = use_tree_str;
588 use_tree_str.reverse();
590 if !(!exists_outside_sel && exists_inside_sel && source_exists_outside_sel_in_same_mod)
592 if let Some(first_path_in_use_tree) = use_tree_str.first() {
593 let first_path_in_use_tree_str = first_path_in_use_tree.to_string();
594 if first_path_in_use_tree_str.contains("super") {
595 let super_path = make::ext::ident_path("super");
596 use_tree_str.insert(0, super_path)
602 make::use_(None, make::use_tree(make::join_paths(use_tree_str), None, None, false));
603 let item = ast::Item::from(use_);
604 self.use_items.insert(0, item);
607 import_path_to_be_removed
610 fn make_use_stmt_of_node_with_super(&mut self, node_syntax: &SyntaxNode) -> ast::Item {
611 let super_path = make::ext::ident_path("super");
612 let node_path = make::ext::ident_path(&node_syntax.to_string());
613 let use_ = make::use_(
615 make::use_tree(make::join_paths(vec![super_path, node_path]), None, None, false),
618 let item = ast::Item::from(use_);
619 self.use_items.insert(0, item.clone());
623 fn process_use_stmt_for_import_resolve(
625 use_stmt_opt: Option<ast::Use>,
626 node_syntax: &SyntaxNode,
627 ) -> Option<(Vec<ast::Path>, Option<TextRange>)> {
628 if let Some(use_stmt) = use_stmt_opt {
629 for desc in use_stmt.syntax().descendants() {
630 if let Some(path_seg) = ast::PathSegment::cast(desc) {
631 if path_seg.syntax().to_string() == node_syntax.to_string() {
632 let mut use_tree_str = vec![path_seg.parent_path()];
633 get_use_tree_paths_from_path(path_seg.parent_path(), &mut use_tree_str);
634 for ancs in path_seg.syntax().ancestors() {
635 //Here we are looking for use_tree with same string value as node
636 //passed above as the range_to_remove function looks for a comma and
637 //then includes it in the text range to remove it. But the comma only
638 //appears at the use_tree level
639 if let Some(use_tree) = ast::UseTree::cast(ancs) {
640 if use_tree.syntax().to_string() == node_syntax.to_string() {
643 Some(range_to_remove(use_tree.syntax())),
649 return Some((use_tree_str, None));
659 fn check_intersection_and_push(
660 import_paths_to_be_removed: &mut Vec<TextRange>,
661 import_path: TextRange,
663 if import_paths_to_be_removed.len() > 0 {
664 // Text ranges received here for imports are extended to the
665 // next/previous comma which can cause intersections among them
666 // and later deletion of these can cause panics similar
667 // to reported in #11766. So to mitigate it, we
668 // check for intersection between all current members
669 // and if it exists we combine both text ranges into
671 let r = import_paths_to_be_removed
673 .position(|it| it.intersect(import_path).is_some());
676 import_paths_to_be_removed[it] = import_paths_to_be_removed[it].cover(import_path)
678 None => import_paths_to_be_removed.push(import_path),
681 import_paths_to_be_removed.push(import_path);
685 fn does_source_exists_outside_sel_in_same_mod(
687 ctx: &AssistContext<'_>,
688 curr_parent_module: &Option<ast::Module>,
689 selection_range: TextRange,
690 curr_file_id: FileId,
692 let mut source_exists_outside_sel_in_same_mod = false;
694 Definition::Module(x) => {
695 let source = x.definition_source(ctx.db());
696 let have_same_parent;
697 if let Some(ast_module) = &curr_parent_module {
698 if let Some(hir_module) = x.parent(ctx.db()) {
700 compare_hir_and_ast_module(ast_module, hir_module, ctx).is_some();
702 let source_file_id = source.file_id.original_file(ctx.db());
703 have_same_parent = source_file_id == curr_file_id;
706 let source_file_id = source.file_id.original_file(ctx.db());
707 have_same_parent = source_file_id == curr_file_id;
710 if have_same_parent {
712 ModuleSource::Module(module_) => {
713 source_exists_outside_sel_in_same_mod =
714 !selection_range.contains_range(module_.syntax().text_range());
720 Definition::Function(x) => {
721 if let Some(source) = x.source(ctx.db()) {
722 let have_same_parent = if let Some(ast_module) = &curr_parent_module {
723 compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
725 let source_file_id = source.file_id.original_file(ctx.db());
726 source_file_id == curr_file_id
729 if have_same_parent {
730 source_exists_outside_sel_in_same_mod =
731 !selection_range.contains_range(source.value.syntax().text_range());
735 Definition::Adt(x) => {
736 if let Some(source) = x.source(ctx.db()) {
737 let have_same_parent = if let Some(ast_module) = &curr_parent_module {
738 compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
740 let source_file_id = source.file_id.original_file(ctx.db());
741 source_file_id == curr_file_id
744 if have_same_parent {
745 source_exists_outside_sel_in_same_mod =
746 !selection_range.contains_range(source.value.syntax().text_range());
750 Definition::Variant(x) => {
751 if let Some(source) = x.source(ctx.db()) {
752 let have_same_parent = if let Some(ast_module) = &curr_parent_module {
753 compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
755 let source_file_id = source.file_id.original_file(ctx.db());
756 source_file_id == curr_file_id
759 if have_same_parent {
760 source_exists_outside_sel_in_same_mod =
761 !selection_range.contains_range(source.value.syntax().text_range());
765 Definition::Const(x) => {
766 if let Some(source) = x.source(ctx.db()) {
767 let have_same_parent = if let Some(ast_module) = &curr_parent_module {
768 compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
770 let source_file_id = source.file_id.original_file(ctx.db());
771 source_file_id == curr_file_id
774 if have_same_parent {
775 source_exists_outside_sel_in_same_mod =
776 !selection_range.contains_range(source.value.syntax().text_range());
780 Definition::Static(x) => {
781 if let Some(source) = x.source(ctx.db()) {
782 let have_same_parent = if let Some(ast_module) = &curr_parent_module {
783 compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
785 let source_file_id = source.file_id.original_file(ctx.db());
786 source_file_id == curr_file_id
789 if have_same_parent {
790 source_exists_outside_sel_in_same_mod =
791 !selection_range.contains_range(source.value.syntax().text_range());
795 Definition::Trait(x) => {
796 if let Some(source) = x.source(ctx.db()) {
797 let have_same_parent = if let Some(ast_module) = &curr_parent_module {
798 compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
800 let source_file_id = source.file_id.original_file(ctx.db());
801 source_file_id == curr_file_id
804 if have_same_parent {
805 source_exists_outside_sel_in_same_mod =
806 !selection_range.contains_range(source.value.syntax().text_range());
810 Definition::TypeAlias(x) => {
811 if let Some(source) = x.source(ctx.db()) {
812 let have_same_parent = if let Some(ast_module) = &curr_parent_module {
813 compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
815 let source_file_id = source.file_id.original_file(ctx.db());
816 source_file_id == curr_file_id
819 if have_same_parent {
820 source_exists_outside_sel_in_same_mod =
821 !selection_range.contains_range(source.value.syntax().text_range());
828 source_exists_outside_sel_in_same_mod
831 fn get_replacements_for_visibilty_change(
832 items: &mut [ast::Item],
833 is_clone_for_updated: bool,
835 Vec<(Option<ast::Visibility>, SyntaxNode)>,
836 Vec<(Option<ast::Visibility>, SyntaxNode)>,
839 let mut replacements = Vec::new();
840 let mut record_field_parents = Vec::new();
841 let mut impls = Vec::new();
844 if !is_clone_for_updated {
845 *item = item.clone_for_update();
847 //Use stmts are ignored
849 ast::Item::Const(it) => replacements.push((it.visibility(), it.syntax().clone())),
850 ast::Item::Enum(it) => replacements.push((it.visibility(), it.syntax().clone())),
851 ast::Item::ExternCrate(it) => replacements.push((it.visibility(), it.syntax().clone())),
852 ast::Item::Fn(it) => replacements.push((it.visibility(), it.syntax().clone())),
853 //Associated item's visibility should not be changed
854 ast::Item::Impl(it) if it.for_token().is_none() => impls.push(it.clone()),
855 ast::Item::MacroDef(it) => replacements.push((it.visibility(), it.syntax().clone())),
856 ast::Item::Module(it) => replacements.push((it.visibility(), it.syntax().clone())),
857 ast::Item::Static(it) => replacements.push((it.visibility(), it.syntax().clone())),
858 ast::Item::Struct(it) => {
859 replacements.push((it.visibility(), it.syntax().clone()));
860 record_field_parents.push((it.visibility(), it.syntax().clone()));
862 ast::Item::Trait(it) => replacements.push((it.visibility(), it.syntax().clone())),
863 ast::Item::TypeAlias(it) => replacements.push((it.visibility(), it.syntax().clone())),
864 ast::Item::Union(it) => {
865 replacements.push((it.visibility(), it.syntax().clone()));
866 record_field_parents.push((it.visibility(), it.syntax().clone()));
872 (replacements, record_field_parents, impls)
875 fn get_use_tree_paths_from_path(
877 use_tree_str: &mut Vec<ast::Path>,
878 ) -> Option<&mut Vec<ast::Path>> {
879 path.syntax().ancestors().filter(|x| x.to_string() != path.to_string()).find_map(|x| {
880 if let Some(use_tree) = ast::UseTree::cast(x) {
881 if let Some(upper_tree_path) = use_tree.path() {
882 if upper_tree_path.to_string() != path.to_string() {
883 use_tree_str.push(upper_tree_path.clone());
884 get_use_tree_paths_from_path(upper_tree_path, use_tree_str);
885 return Some(use_tree);
895 fn add_change_vis(vis: Option<ast::Visibility>, node_or_token_opt: Option<syntax::SyntaxElement>) {
897 if let Some(node_or_token) = node_or_token_opt {
898 let pub_crate_vis = make::visibility_pub_crate().clone_for_update();
899 ted::insert(ted::Position::before(node_or_token), pub_crate_vis.syntax());
904 fn compare_hir_and_ast_module(
905 ast_module: &ast::Module,
906 hir_module: hir::Module,
907 ctx: &AssistContext<'_>,
909 let hir_mod_name = hir_module.name(ctx.db())?;
910 let ast_mod_name = ast_module.name()?;
911 if hir_mod_name.to_string() != ast_mod_name.to_string() {
918 fn indent_range_before_given_node(node: &SyntaxNode) -> Option<TextRange> {
919 node.siblings_with_tokens(syntax::Direction::Prev)
920 .find(|x| x.kind() == WHITESPACE)
921 .map(|x| x.text_range())
926 use crate::tests::{check_assist, check_assist_not_applicable};
931 fn test_not_applicable_without_selection() {
932 check_assist_not_applicable(
935 $0pub struct PublicStruct {
943 fn test_extract_module() {
947 mod thirdpartycrate {
950 pub struct SomeType2;
952 pub struct SomeType1;
956 use crate::thirdpartycrate::{nest::{SomeType, SomeType2}, SomeType1};
958 pub struct PublicStruct {
959 field: PrivateStruct,
964 pub fn new() -> Self {
965 Self { field: PrivateStruct::new(), field1: SomeType1 }
970 let _s = PrivateStruct::new();
974 $0struct PrivateStruct {
978 pub struct PrivateStruct1 {
984 PrivateStruct { inner: SomeType }
994 mod thirdpartycrate {
997 pub struct SomeType2;
999 pub struct SomeType1;
1003 use crate::thirdpartycrate::{nest::{SomeType2}, SomeType1};
1005 pub struct PublicStruct {
1006 field: modname::PrivateStruct,
1011 pub fn new() -> Self {
1012 Self { field: modname::PrivateStruct::new(), field1: SomeType1 }
1017 let _s = modname::PrivateStruct::new();
1018 let _a = modname::bar();
1022 use crate::thirdpartycrate::nest::SomeType;
1024 pub(crate) struct PrivateStruct {
1025 pub(crate) inner: SomeType,
1028 pub struct PrivateStruct1 {
1032 impl PrivateStruct {
1033 pub(crate) fn new() -> Self {
1034 PrivateStruct { inner: SomeType }
1038 pub(crate) fn bar() -> i32 {
1048 fn test_extract_module_for_function_only() {
1052 $0fn foo(name: i32) -> i32 {
1056 fn bar(name: i32) -> i32 {
1062 pub(crate) fn foo(name: i32) -> i32 {
1067 fn bar(name: i32) -> i32 {
1075 fn test_extract_module_for_impl_having_corresponding_adt_in_selection() {
1083 pub fn new_a() -> i32 {
1089 let _a = A::new_a();
1096 pub(crate) struct A {}
1099 pub fn new_a() -> i32 {
1106 let _a = modname::A::new_a();
1114 fn test_import_resolve_when_its_only_inside_selection() {
1119 pub struct PrivateStruct;
1120 pub struct PrivateStruct1;
1124 use super::foo::{PrivateStruct, PrivateStruct1};
1127 field: PrivateStruct,
1131 field: PrivateStruct1,
1137 pub struct PrivateStruct;
1138 pub struct PrivateStruct1;
1142 use super::foo::{PrivateStruct1};
1145 use super::super::foo::PrivateStruct;
1147 pub(crate) struct Strukt {
1148 pub(crate) field: PrivateStruct,
1153 field: PrivateStruct1,
1161 fn test_import_resolve_when_its_inside_and_outside_selection_and_source_not_in_same_mod() {
1166 pub struct PrivateStruct;
1170 use super::foo::PrivateStruct;
1173 field: PrivateStruct,
1177 field: PrivateStruct,
1183 pub struct PrivateStruct;
1187 use super::foo::PrivateStruct;
1190 use super::super::foo::PrivateStruct;
1192 pub(crate) struct Strukt {
1193 pub(crate) field: PrivateStruct,
1198 field: PrivateStruct,
1206 fn test_import_resolve_when_its_inside_and_outside_selection_and_source_is_in_same_mod() {
1211 pub struct PrivateStruct;
1214 field: PrivateStruct,
1218 field: PrivateStruct,
1224 pub struct PrivateStruct;
1227 use super::PrivateStruct;
1229 pub(crate) struct Strukt {
1230 pub(crate) field: PrivateStruct,
1235 field: PrivateStruct,
1243 fn test_extract_module_for_correspoding_adt_of_impl_present_in_same_mod_but_not_in_selection() {
1251 pub fn new_a() -> i32 {
1257 let _a = A::new_a();
1269 pub fn new_a() -> i32 {
1276 let _a = A::new_a();
1284 fn test_extract_module_for_impl_not_having_corresponding_adt_in_selection_and_not_in_same_mod_but_with_super(
1296 pub fn new_a() -> i32 {
1302 let _a = A::new_a();
1314 use super::super::foo::A;
1317 pub fn new_a() -> i32 {
1324 let _a = A::new_a();
1332 fn test_import_resolve_for_trait_bounds_on_function() {
1341 fn foo<T: JustATrait>(arg: T) -> T {
1345 impl JustATrait for A {}
1358 use super::JustATrait;
1360 pub(crate) struct A {}
1362 pub(crate) fn foo<T: JustATrait>(arg: T) -> T {
1366 impl JustATrait for A {}
1368 pub(crate) fn bar() {
1379 fn test_extract_module_for_module() {
1392 pub(crate) mod impl_play {
1402 fn test_extract_module_with_multiple_files() {
1409 use foo::PrivateStruct;
1412 field: PrivateStruct,
1421 pub struct PrivateStruct;
1426 use foo::PrivateStruct;
1429 field: PrivateStruct,
1436 pub(crate) struct Strukt1 {
1437 pub(crate) field: Strukt,
1446 fn test_extract_module_macro_rules() {
1467 fn test_do_not_apply_visibility_modifier_to_trait_impl_items() {
1477 $0impl ATrait for A {
1502 fn test_if_inside_impl_block_generate_module_outside() {
1524 pub(crate) fn foo() {}
1532 fn test_if_inside_impl_block_generate_module_outside_but_impl_block_having_one_child() {
1553 pub(crate) fn foo(x: B) {}
1561 fn test_issue_11766() {
1562 //https://github.com/rust-lang/rust-analyzer/issues/11766
1573 $0type A = (Foo, Bar);$0
1588 pub(crate) type A = (Foo, Bar);
1595 fn test_issue_12790() {
1599 $0/// A documented function
1600 fn documented_fn() {}
1602 // A commented function with a #[] attribute macro
1604 fn attribute_fn() {}
1606 // A normally commented function
1609 /// A documented Struct
1610 struct DocumentedStruct {
1614 /// Documented field
1624 struct MacroedStruct {
1628 /// Documented field
1637 struct NormalStruct {
1641 /// Documented field
1649 /// A documented type
1650 type DocumentedType = i32;
1654 type MacroedType = i32;
1656 /// A module to move
1665 /// A documented trait
1672 enum DocumentedEnum {
1676 B { x: i32, y: i32 }
1679 /// Documented const
1680 const MY_CONST: i32 = 0;$0
1684 /// A documented function
1685 pub(crate) fn documented_fn() {}
1687 // A commented function with a #[] attribute macro
1689 pub(crate) fn attribute_fn() {}
1691 // A normally commented function
1692 pub(crate) fn normal_fn() {}
1694 /// A documented Struct
1695 pub(crate) struct DocumentedStruct {
1699 /// Documented field
1709 pub(crate) struct MacroedStruct {
1713 /// Documented field
1722 pub(crate) struct NormalStruct {
1726 /// Documented field
1734 /// A documented type
1735 pub(crate) type DocumentedType = i32;
1739 pub(crate) type MacroedType = i32;
1741 /// A module to move
1742 pub(crate) mod module {}
1747 pub(crate) fn new() {}
1750 /// A documented trait
1751 pub(crate) trait DocTrait {
1757 pub(crate) enum DocumentedEnum {
1761 B { x: i32, y: i32 }
1764 /// Documented const
1765 pub(crate) const MY_CONST: i32 = 0;