2 collections::{HashMap, HashSet},
6 use hir::{HasSource, ModuleSource};
8 assists::{AssistId, AssistKind},
10 defs::{Definition, NameClass, NameRefClass},
11 search::{FileReference, SearchScope},
13 use itertools::Itertools;
14 use smallvec::SmallVec;
17 algo::find_node_at_range,
20 edit::{AstNodeEdit, IndentLevel},
21 make, HasName, HasVisibility,
23 match_ast, ted, AstNode, SourceFile,
24 SyntaxKind::{self, WHITESPACE},
25 SyntaxNode, TextRange,
28 use crate::{AssistContext, Assists};
30 use super::remove_unused_param::range_to_remove;
32 // Assist: extract_module
34 // Extracts a selected region as separate module. All the references, visibility and imports are
38 // $0fn foo(name: i32) -> i32 {
42 // fn bar(name: i32) -> i32 {
49 // pub(crate) fn foo(name: i32) -> i32 {
54 // fn bar(name: i32) -> i32 {
58 pub(crate) fn extract_module(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
59 if ctx.has_empty_selection() {
63 let node = ctx.covering_element();
64 let node = match node {
65 syntax::NodeOrToken::Node(n) => n,
66 syntax::NodeOrToken::Token(t) => t.parent()?,
69 //If the selection is inside impl block, we need to place new module outside impl block,
70 //as impl blocks cannot contain modules
72 let mut impl_parent: Option<ast::Impl> = None;
73 let mut impl_child_count: usize = 0;
74 if let Some(parent_assoc_list) = node.parent() {
75 if let Some(parent_impl) = parent_assoc_list.parent() {
76 if let Some(impl_) = ast::Impl::cast(parent_impl) {
77 impl_child_count = parent_assoc_list.children().count();
78 impl_parent = Some(impl_);
83 let mut curr_parent_module: Option<ast::Module> = None;
84 if let Some(mod_syn_opt) = node.ancestors().find(|it| ast::Module::can_cast(it.kind())) {
85 curr_parent_module = ast::Module::cast(mod_syn_opt);
88 let mut module = extract_target(&node, ctx.selection_trimmed())?;
89 if module.body_items.is_empty() {
93 let old_item_indent = module.body_items[0].indent_level();
96 AssistId("extract_module", AssistKind::RefactorExtract),
100 //This takes place in three steps:
102 //- Firstly, we will update the references(usages) e.g. converting a
103 // function call bar() to modname::bar(), and similarly for other items
105 //- Secondly, changing the visibility of each item inside the newly selected module
106 // i.e. making a fn a() {} to pub(crate) fn a() {}
108 //- Thirdly, resolving all the imports this includes removing paths from imports
109 // outside the module, shifting/cloning them inside new module, or shifting the imports, or making
110 // new import statements
112 //We are getting item usages and record_fields together, record_fields
113 //for change_visibility and usages for first point mentioned above in the process
114 let (usages_to_be_processed, record_fields) = module.get_usages_and_record_fields(ctx);
116 let import_paths_to_be_removed = module.resolve_imports(curr_parent_module, ctx);
117 module.change_visibility(record_fields);
119 let mut body_items: Vec<String> = Vec::new();
120 let mut items_to_be_processed: Vec<ast::Item> = module.body_items.clone();
122 let new_item_indent = if impl_parent.is_some() {
125 items_to_be_processed = [module.use_items.clone(), items_to_be_processed].concat();
129 for item in items_to_be_processed {
130 let item = item.indent(IndentLevel(1));
131 let mut indented_item = String::new();
132 format_to!(indented_item, "{new_item_indent}{item}");
133 body_items.push(indented_item);
136 let mut body = body_items.join("\n\n");
138 if let Some(impl_) = &impl_parent {
139 let mut impl_body_def = String::new();
141 if let Some(self_ty) = impl_.self_ty() {
143 let impl_indent = old_item_indent + 1;
146 "{impl_indent}impl {self_ty} {{\n{body}\n{impl_indent}}}",
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 item_indent = old_item_indent + 1;
155 body = format!("{item_indent}{item}\n\n{body}");
160 let mut module_def = String::new();
162 let module_name = module.name;
163 format_to!(module_def, "mod {module_name} {{\n{body}\n{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) {
346 let mod_name = self.name;
348 name_ref.syntax().text_range(),
349 format!("{mod_name}::{name_ref}"),
358 fn change_visibility(&mut self, record_fields: Vec<SyntaxNode>) {
359 let (mut replacements, record_field_parents, impls) =
360 get_replacements_for_visibilty_change(&mut self.body_items, false);
362 let mut impl_items: Vec<ast::Item> = impls
364 .flat_map(|impl_| impl_.syntax().descendants())
365 .filter_map(ast::Item::cast)
368 let (mut impl_item_replacements, _, _) =
369 get_replacements_for_visibilty_change(&mut impl_items, true);
371 replacements.append(&mut impl_item_replacements);
373 for (_, field_owner) in record_field_parents {
374 for desc in field_owner.descendants().filter_map(ast::RecordField::cast) {
375 let is_record_field_present =
376 record_fields.clone().into_iter().any(|x| x.to_string() == desc.to_string());
377 if is_record_field_present {
378 replacements.push((desc.visibility(), desc.syntax().clone()));
383 for (vis, syntax) in replacements {
384 let item = syntax.children_with_tokens().find(|node_or_token| {
385 match node_or_token.kind() {
386 // We're skipping comments, doc comments, and attribute macros that may precede the keyword
387 // that the visibility should be placed before.
388 SyntaxKind::COMMENT | SyntaxKind::ATTR | SyntaxKind::WHITESPACE => false,
393 add_change_vis(vis, item);
399 curr_parent_module: Option<ast::Module>,
400 ctx: &AssistContext<'_>,
401 ) -> Vec<TextRange> {
402 let mut import_paths_to_be_removed: Vec<TextRange> = vec![];
403 let mut node_set: HashSet<String> = HashSet::new();
405 for item in self.body_items.clone() {
406 for x in item.syntax().descendants() {
407 if let Some(name) = ast::Name::cast(x.clone()) {
408 if let Some(name_classify) = NameClass::classify(&ctx.sema, &name) {
409 //Necessary to avoid two same names going through
410 if !node_set.contains(&name.syntax().to_string()) {
411 node_set.insert(name.syntax().to_string());
412 let def_opt: Option<Definition> = match name_classify {
413 NameClass::Definition(def) => Some(def),
417 if let Some(def) = def_opt {
418 if let Some(import_path) = self
419 .process_names_and_namerefs_for_import_resolve(
426 check_intersection_and_push(
427 &mut import_paths_to_be_removed,
436 if let Some(name_ref) = ast::NameRef::cast(x) {
437 if let Some(name_classify) = NameRefClass::classify(&ctx.sema, &name_ref) {
438 //Necessary to avoid two same names going through
439 if !node_set.contains(&name_ref.syntax().to_string()) {
440 node_set.insert(name_ref.syntax().to_string());
441 let def_opt: Option<Definition> = match name_classify {
442 NameRefClass::Definition(def) => Some(def),
446 if let Some(def) = def_opt {
447 if let Some(import_path) = self
448 .process_names_and_namerefs_for_import_resolve(
455 check_intersection_and_push(
456 &mut import_paths_to_be_removed,
467 import_paths_to_be_removed
470 fn process_names_and_namerefs_for_import_resolve(
473 node_syntax: &SyntaxNode,
474 curr_parent_module: &Option<ast::Module>,
475 ctx: &AssistContext<'_>,
476 ) -> Option<TextRange> {
477 //We only need to find in the current file
478 let selection_range = ctx.selection_trimmed();
479 let curr_file_id = ctx.file_id();
480 let search_scope = SearchScope::single_file(curr_file_id);
481 let usage_res = def.usages(&ctx.sema).in_scope(search_scope).all();
482 let file = ctx.sema.parse(curr_file_id);
484 let mut exists_inside_sel = false;
485 let mut exists_outside_sel = false;
486 for (_, refs) in usage_res.iter() {
487 let mut non_use_nodes_itr = refs.iter().filter_map(|x| {
488 if find_node_at_range::<ast::Use>(file.syntax(), x.range).is_none() {
489 let path_opt = find_node_at_range::<ast::Path>(file.syntax(), x.range);
498 .any(|x| !selection_range.contains_range(x.syntax().text_range()))
500 exists_outside_sel = true;
502 if non_use_nodes_itr.any(|x| selection_range.contains_range(x.syntax().text_range())) {
503 exists_inside_sel = true;
507 let source_exists_outside_sel_in_same_mod = does_source_exists_outside_sel_in_same_mod(
515 let use_stmt_opt: Option<ast::Use> = usage_res.into_iter().find_map(|(file_id, refs)| {
516 if file_id == curr_file_id {
519 .find_map(|fref| find_node_at_range(file.syntax(), fref.range))
525 let mut use_tree_str_opt: Option<Vec<ast::Path>> = None;
526 //Exists inside and outside selection
527 // - Use stmt for item is present -> get the use_tree_str and reconstruct the path in new
529 // - Use stmt for item is not present ->
530 //If it is not found, the definition is either ported inside new module or it stays
532 //- Def is inside: Nothing to import
533 //- Def is outside: Import it inside with super
535 //Exists inside selection but not outside -> Check for the import of it in original module,
536 //get the use_tree_str, reconstruct the use stmt in new module
538 let mut import_path_to_be_removed: Option<TextRange> = None;
539 if exists_inside_sel && exists_outside_sel {
540 //Changes to be made only inside new module
542 //If use_stmt exists, find the use_tree_str, reconstruct it inside new module
543 //If not, insert a use stmt with super and the given nameref
544 if let Some((use_tree_str, _)) =
545 self.process_use_stmt_for_import_resolve(use_stmt_opt, node_syntax)
547 use_tree_str_opt = Some(use_tree_str);
548 } else if source_exists_outside_sel_in_same_mod {
549 //Considered only after use_stmt is not present
550 //source_exists_outside_sel_in_same_mod | exists_outside_sel(exists_inside_sel =
551 //true for all cases)
552 // false | false -> Do nothing
553 // false | true -> If source is in selection -> nothing to do, If source is outside
554 // mod -> ust_stmt transversal
555 // true | false -> super import insertion
556 // true | true -> super import insertion
557 self.make_use_stmt_of_node_with_super(node_syntax);
559 } else if exists_inside_sel && !exists_outside_sel {
560 //Changes to be made inside new module, and remove import from outside
562 if let Some((mut use_tree_str, text_range_opt)) =
563 self.process_use_stmt_for_import_resolve(use_stmt_opt, node_syntax)
565 if let Some(text_range) = text_range_opt {
566 import_path_to_be_removed = Some(text_range);
569 if source_exists_outside_sel_in_same_mod {
570 if let Some(first_path_in_use_tree) = use_tree_str.last() {
571 let first_path_in_use_tree_str = first_path_in_use_tree.to_string();
572 if !first_path_in_use_tree_str.contains("super")
573 && !first_path_in_use_tree_str.contains("crate")
575 let super_path = make::ext::ident_path("super");
576 use_tree_str.push(super_path);
581 use_tree_str_opt = Some(use_tree_str);
582 } else if source_exists_outside_sel_in_same_mod {
583 self.make_use_stmt_of_node_with_super(node_syntax);
587 if let Some(use_tree_str) = use_tree_str_opt {
588 let mut use_tree_str = use_tree_str;
589 use_tree_str.reverse();
591 if !(!exists_outside_sel && exists_inside_sel && source_exists_outside_sel_in_same_mod)
593 if let Some(first_path_in_use_tree) = use_tree_str.first() {
594 let first_path_in_use_tree_str = first_path_in_use_tree.to_string();
595 if first_path_in_use_tree_str.contains("super") {
596 let super_path = make::ext::ident_path("super");
597 use_tree_str.insert(0, super_path)
603 make::use_(None, make::use_tree(make::join_paths(use_tree_str), None, None, false));
604 let item = ast::Item::from(use_);
605 self.use_items.insert(0, item);
608 import_path_to_be_removed
611 fn make_use_stmt_of_node_with_super(&mut self, node_syntax: &SyntaxNode) -> ast::Item {
612 let super_path = make::ext::ident_path("super");
613 let node_path = make::ext::ident_path(&node_syntax.to_string());
614 let use_ = make::use_(
616 make::use_tree(make::join_paths(vec![super_path, node_path]), None, None, false),
619 let item = ast::Item::from(use_);
620 self.use_items.insert(0, item.clone());
624 fn process_use_stmt_for_import_resolve(
626 use_stmt_opt: Option<ast::Use>,
627 node_syntax: &SyntaxNode,
628 ) -> Option<(Vec<ast::Path>, Option<TextRange>)> {
629 if let Some(use_stmt) = use_stmt_opt {
630 for desc in use_stmt.syntax().descendants() {
631 if let Some(path_seg) = ast::PathSegment::cast(desc) {
632 if path_seg.syntax().to_string() == node_syntax.to_string() {
633 let mut use_tree_str = vec![path_seg.parent_path()];
634 get_use_tree_paths_from_path(path_seg.parent_path(), &mut use_tree_str);
635 for ancs in path_seg.syntax().ancestors() {
636 //Here we are looking for use_tree with same string value as node
637 //passed above as the range_to_remove function looks for a comma and
638 //then includes it in the text range to remove it. But the comma only
639 //appears at the use_tree level
640 if let Some(use_tree) = ast::UseTree::cast(ancs) {
641 if use_tree.syntax().to_string() == node_syntax.to_string() {
644 Some(range_to_remove(use_tree.syntax())),
650 return Some((use_tree_str, None));
660 fn check_intersection_and_push(
661 import_paths_to_be_removed: &mut Vec<TextRange>,
662 mut import_path: TextRange,
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 combine all such ranges into one.
670 let s: SmallVec<[_; 2]> = import_paths_to_be_removed
672 .positions(|it| it.intersect(import_path).is_some())
674 for pos in s.into_iter().rev() {
675 let intersecting_path = import_paths_to_be_removed.swap_remove(pos);
676 import_path = import_path.cover(intersecting_path);
678 import_paths_to_be_removed.push(import_path);
681 fn does_source_exists_outside_sel_in_same_mod(
683 ctx: &AssistContext<'_>,
684 curr_parent_module: &Option<ast::Module>,
685 selection_range: TextRange,
686 curr_file_id: FileId,
688 let mut source_exists_outside_sel_in_same_mod = false;
690 Definition::Module(x) => {
691 let source = x.definition_source(ctx.db());
692 let have_same_parent;
693 if let Some(ast_module) = &curr_parent_module {
694 if let Some(hir_module) = x.parent(ctx.db()) {
696 compare_hir_and_ast_module(ast_module, hir_module, ctx).is_some();
698 let source_file_id = source.file_id.original_file(ctx.db());
699 have_same_parent = source_file_id == curr_file_id;
702 let source_file_id = source.file_id.original_file(ctx.db());
703 have_same_parent = source_file_id == curr_file_id;
706 if have_same_parent {
708 ModuleSource::Module(module_) => {
709 source_exists_outside_sel_in_same_mod =
710 !selection_range.contains_range(module_.syntax().text_range());
716 Definition::Function(x) => {
717 if let Some(source) = x.source(ctx.db()) {
718 let have_same_parent = if let Some(ast_module) = &curr_parent_module {
719 compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
721 let source_file_id = source.file_id.original_file(ctx.db());
722 source_file_id == curr_file_id
725 if have_same_parent {
726 source_exists_outside_sel_in_same_mod =
727 !selection_range.contains_range(source.value.syntax().text_range());
731 Definition::Adt(x) => {
732 if let Some(source) = x.source(ctx.db()) {
733 let have_same_parent = if let Some(ast_module) = &curr_parent_module {
734 compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
736 let source_file_id = source.file_id.original_file(ctx.db());
737 source_file_id == curr_file_id
740 if have_same_parent {
741 source_exists_outside_sel_in_same_mod =
742 !selection_range.contains_range(source.value.syntax().text_range());
746 Definition::Variant(x) => {
747 if let Some(source) = x.source(ctx.db()) {
748 let have_same_parent = if let Some(ast_module) = &curr_parent_module {
749 compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
751 let source_file_id = source.file_id.original_file(ctx.db());
752 source_file_id == curr_file_id
755 if have_same_parent {
756 source_exists_outside_sel_in_same_mod =
757 !selection_range.contains_range(source.value.syntax().text_range());
761 Definition::Const(x) => {
762 if let Some(source) = x.source(ctx.db()) {
763 let have_same_parent = if let Some(ast_module) = &curr_parent_module {
764 compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
766 let source_file_id = source.file_id.original_file(ctx.db());
767 source_file_id == curr_file_id
770 if have_same_parent {
771 source_exists_outside_sel_in_same_mod =
772 !selection_range.contains_range(source.value.syntax().text_range());
776 Definition::Static(x) => {
777 if let Some(source) = x.source(ctx.db()) {
778 let have_same_parent = if let Some(ast_module) = &curr_parent_module {
779 compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
781 let source_file_id = source.file_id.original_file(ctx.db());
782 source_file_id == curr_file_id
785 if have_same_parent {
786 source_exists_outside_sel_in_same_mod =
787 !selection_range.contains_range(source.value.syntax().text_range());
791 Definition::Trait(x) => {
792 if let Some(source) = x.source(ctx.db()) {
793 let have_same_parent = if let Some(ast_module) = &curr_parent_module {
794 compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
796 let source_file_id = source.file_id.original_file(ctx.db());
797 source_file_id == curr_file_id
800 if have_same_parent {
801 source_exists_outside_sel_in_same_mod =
802 !selection_range.contains_range(source.value.syntax().text_range());
806 Definition::TypeAlias(x) => {
807 if let Some(source) = x.source(ctx.db()) {
808 let have_same_parent = if let Some(ast_module) = &curr_parent_module {
809 compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
811 let source_file_id = source.file_id.original_file(ctx.db());
812 source_file_id == curr_file_id
815 if have_same_parent {
816 source_exists_outside_sel_in_same_mod =
817 !selection_range.contains_range(source.value.syntax().text_range());
824 source_exists_outside_sel_in_same_mod
827 fn get_replacements_for_visibilty_change(
828 items: &mut [ast::Item],
829 is_clone_for_updated: bool,
831 Vec<(Option<ast::Visibility>, SyntaxNode)>,
832 Vec<(Option<ast::Visibility>, SyntaxNode)>,
835 let mut replacements = Vec::new();
836 let mut record_field_parents = Vec::new();
837 let mut impls = Vec::new();
840 if !is_clone_for_updated {
841 *item = item.clone_for_update();
843 //Use stmts are ignored
845 ast::Item::Const(it) => replacements.push((it.visibility(), it.syntax().clone())),
846 ast::Item::Enum(it) => replacements.push((it.visibility(), it.syntax().clone())),
847 ast::Item::ExternCrate(it) => replacements.push((it.visibility(), it.syntax().clone())),
848 ast::Item::Fn(it) => replacements.push((it.visibility(), it.syntax().clone())),
849 //Associated item's visibility should not be changed
850 ast::Item::Impl(it) if it.for_token().is_none() => impls.push(it.clone()),
851 ast::Item::MacroDef(it) => replacements.push((it.visibility(), it.syntax().clone())),
852 ast::Item::Module(it) => replacements.push((it.visibility(), it.syntax().clone())),
853 ast::Item::Static(it) => replacements.push((it.visibility(), it.syntax().clone())),
854 ast::Item::Struct(it) => {
855 replacements.push((it.visibility(), it.syntax().clone()));
856 record_field_parents.push((it.visibility(), it.syntax().clone()));
858 ast::Item::Trait(it) => replacements.push((it.visibility(), it.syntax().clone())),
859 ast::Item::TypeAlias(it) => replacements.push((it.visibility(), it.syntax().clone())),
860 ast::Item::Union(it) => {
861 replacements.push((it.visibility(), it.syntax().clone()));
862 record_field_parents.push((it.visibility(), it.syntax().clone()));
868 (replacements, record_field_parents, impls)
871 fn get_use_tree_paths_from_path(
873 use_tree_str: &mut Vec<ast::Path>,
874 ) -> Option<&mut Vec<ast::Path>> {
875 path.syntax().ancestors().filter(|x| x.to_string() != path.to_string()).find_map(|x| {
876 if let Some(use_tree) = ast::UseTree::cast(x) {
877 if let Some(upper_tree_path) = use_tree.path() {
878 if upper_tree_path.to_string() != path.to_string() {
879 use_tree_str.push(upper_tree_path.clone());
880 get_use_tree_paths_from_path(upper_tree_path, use_tree_str);
881 return Some(use_tree);
891 fn add_change_vis(vis: Option<ast::Visibility>, node_or_token_opt: Option<syntax::SyntaxElement>) {
893 if let Some(node_or_token) = node_or_token_opt {
894 let pub_crate_vis = make::visibility_pub_crate().clone_for_update();
895 ted::insert(ted::Position::before(node_or_token), pub_crate_vis.syntax());
900 fn compare_hir_and_ast_module(
901 ast_module: &ast::Module,
902 hir_module: hir::Module,
903 ctx: &AssistContext<'_>,
905 let hir_mod_name = hir_module.name(ctx.db())?;
906 let ast_mod_name = ast_module.name()?;
907 if hir_mod_name.to_string() != ast_mod_name.to_string() {
914 fn indent_range_before_given_node(node: &SyntaxNode) -> Option<TextRange> {
915 node.siblings_with_tokens(syntax::Direction::Prev)
916 .find(|x| x.kind() == WHITESPACE)
917 .map(|x| x.text_range())
922 use crate::tests::{check_assist, check_assist_not_applicable};
927 fn test_not_applicable_without_selection() {
928 check_assist_not_applicable(
931 $0pub struct PublicStruct {
939 fn test_extract_module() {
943 mod thirdpartycrate {
946 pub struct SomeType2;
948 pub struct SomeType1;
952 use crate::thirdpartycrate::{nest::{SomeType, SomeType2}, SomeType1};
954 pub struct PublicStruct {
955 field: PrivateStruct,
960 pub fn new() -> Self {
961 Self { field: PrivateStruct::new(), field1: SomeType1 }
966 let _s = PrivateStruct::new();
970 $0struct PrivateStruct {
974 pub struct PrivateStruct1 {
980 PrivateStruct { inner: SomeType }
990 mod thirdpartycrate {
993 pub struct SomeType2;
995 pub struct SomeType1;
999 use crate::thirdpartycrate::{nest::{SomeType2}, SomeType1};
1001 pub struct PublicStruct {
1002 field: modname::PrivateStruct,
1007 pub fn new() -> Self {
1008 Self { field: modname::PrivateStruct::new(), field1: SomeType1 }
1013 let _s = modname::PrivateStruct::new();
1014 let _a = modname::bar();
1018 use crate::thirdpartycrate::nest::SomeType;
1020 pub(crate) struct PrivateStruct {
1021 pub(crate) inner: SomeType,
1024 pub struct PrivateStruct1 {
1028 impl PrivateStruct {
1029 pub(crate) fn new() -> Self {
1030 PrivateStruct { inner: SomeType }
1034 pub(crate) fn bar() -> i32 {
1044 fn test_extract_module_for_function_only() {
1048 $0fn foo(name: i32) -> i32 {
1052 fn bar(name: i32) -> i32 {
1058 pub(crate) fn foo(name: i32) -> i32 {
1063 fn bar(name: i32) -> i32 {
1071 fn test_extract_module_for_impl_having_corresponding_adt_in_selection() {
1079 pub fn new_a() -> i32 {
1085 let _a = A::new_a();
1092 pub(crate) struct A {}
1095 pub fn new_a() -> i32 {
1102 let _a = modname::A::new_a();
1110 fn test_import_resolve_when_its_only_inside_selection() {
1115 pub struct PrivateStruct;
1116 pub struct PrivateStruct1;
1120 use super::foo::{PrivateStruct, PrivateStruct1};
1123 field: PrivateStruct,
1127 field: PrivateStruct1,
1133 pub struct PrivateStruct;
1134 pub struct PrivateStruct1;
1138 use super::foo::{PrivateStruct1};
1141 use super::super::foo::PrivateStruct;
1143 pub(crate) struct Strukt {
1144 pub(crate) field: PrivateStruct,
1149 field: PrivateStruct1,
1157 fn test_import_resolve_when_its_inside_and_outside_selection_and_source_not_in_same_mod() {
1162 pub struct PrivateStruct;
1166 use super::foo::PrivateStruct;
1169 field: PrivateStruct,
1173 field: PrivateStruct,
1179 pub struct PrivateStruct;
1183 use super::foo::PrivateStruct;
1186 use super::super::foo::PrivateStruct;
1188 pub(crate) struct Strukt {
1189 pub(crate) field: PrivateStruct,
1194 field: PrivateStruct,
1202 fn test_import_resolve_when_its_inside_and_outside_selection_and_source_is_in_same_mod() {
1207 pub struct PrivateStruct;
1210 field: PrivateStruct,
1214 field: PrivateStruct,
1220 pub struct PrivateStruct;
1223 use super::PrivateStruct;
1225 pub(crate) struct Strukt {
1226 pub(crate) field: PrivateStruct,
1231 field: PrivateStruct,
1239 fn test_extract_module_for_correspoding_adt_of_impl_present_in_same_mod_but_not_in_selection() {
1247 pub fn new_a() -> i32 {
1253 let _a = A::new_a();
1265 pub fn new_a() -> i32 {
1272 let _a = A::new_a();
1280 fn test_extract_module_for_impl_not_having_corresponding_adt_in_selection_and_not_in_same_mod_but_with_super(
1292 pub fn new_a() -> i32 {
1298 let _a = A::new_a();
1310 use super::super::foo::A;
1313 pub fn new_a() -> i32 {
1320 let _a = A::new_a();
1328 fn test_import_resolve_for_trait_bounds_on_function() {
1337 fn foo<T: JustATrait>(arg: T) -> T {
1341 impl JustATrait for A {}
1354 use super::JustATrait;
1356 pub(crate) struct A {}
1358 pub(crate) fn foo<T: JustATrait>(arg: T) -> T {
1362 impl JustATrait for A {}
1364 pub(crate) fn bar() {
1375 fn test_extract_module_for_module() {
1388 pub(crate) mod impl_play {
1398 fn test_extract_module_with_multiple_files() {
1405 use foo::PrivateStruct;
1408 field: PrivateStruct,
1417 pub struct PrivateStruct;
1422 use foo::PrivateStruct;
1425 field: PrivateStruct,
1432 pub(crate) struct Strukt1 {
1433 pub(crate) field: Strukt,
1442 fn test_extract_module_macro_rules() {
1463 fn test_do_not_apply_visibility_modifier_to_trait_impl_items() {
1473 $0impl ATrait for A {
1498 fn test_if_inside_impl_block_generate_module_outside() {
1520 pub(crate) fn foo() {}
1528 fn test_if_inside_impl_block_generate_module_outside_but_impl_block_having_one_child() {
1549 pub(crate) fn foo(x: B) {}
1557 fn test_issue_11766() {
1558 //https://github.com/rust-lang/rust-analyzer/issues/11766
1569 $0type A = (Foo, Bar);$0
1584 pub(crate) type A = (Foo, Bar);
1591 fn test_issue_12790() {
1595 $0/// A documented function
1596 fn documented_fn() {}
1598 // A commented function with a #[] attribute macro
1600 fn attribute_fn() {}
1602 // A normally commented function
1605 /// A documented Struct
1606 struct DocumentedStruct {
1610 /// Documented field
1620 struct MacroedStruct {
1624 /// Documented field
1633 struct NormalStruct {
1637 /// Documented field
1645 /// A documented type
1646 type DocumentedType = i32;
1650 type MacroedType = i32;
1652 /// A module to move
1661 /// A documented trait
1668 enum DocumentedEnum {
1672 B { x: i32, y: i32 }
1675 /// Documented const
1676 const MY_CONST: i32 = 0;$0
1680 /// A documented function
1681 pub(crate) fn documented_fn() {}
1683 // A commented function with a #[] attribute macro
1685 pub(crate) fn attribute_fn() {}
1687 // A normally commented function
1688 pub(crate) fn normal_fn() {}
1690 /// A documented Struct
1691 pub(crate) struct DocumentedStruct {
1695 /// Documented field
1705 pub(crate) struct MacroedStruct {
1709 /// Documented field
1718 pub(crate) struct NormalStruct {
1722 /// Documented field
1730 /// A documented type
1731 pub(crate) type DocumentedType = i32;
1735 pub(crate) type MacroedType = i32;
1737 /// A module to move
1738 pub(crate) mod module {}
1743 pub(crate) fn new() {}
1746 /// A documented trait
1747 pub(crate) trait DocTrait {
1753 pub(crate) enum DocumentedEnum {
1757 B { x: i32, y: i32 }
1760 /// Documented const
1761 pub(crate) const MY_CONST: i32 = 0;
1768 fn test_merge_multiple_intersections() {
1802 pub(crate) struct S {
1803 pub(crate) inner: A,
1804 pub(crate) state: C,
1805 pub(crate) condvar: B,