2 use hir::{AssocItem, HasVisibility, Module, ModuleDef, Name, PathResolution, ScopeDef};
4 defs::{Definition, NameRefClass},
10 ted, AstNode, Direction, SyntaxNode, SyntaxToken, T,
14 assist_context::{AssistContext, Assists},
18 // Assist: expand_glob_import
20 // Expands glob imports.
30 // fn qux(bar: Bar, baz: Baz) {}
39 // use foo::{Baz, Bar};
41 // fn qux(bar: Bar, baz: Baz) {}
43 pub(crate) fn expand_glob_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
44 let star = ctx.find_token_syntax_at_offset(T![*])?;
45 let use_tree = star.parent().and_then(ast::UseTree::cast)?;
46 let (parent, mod_path) = find_parent_and_path(&star)?;
47 let target_module = match ctx.sema.resolve_path(&mod_path)? {
48 PathResolution::Def(ModuleDef::Module(it)) => it,
52 let current_scope = ctx.sema.scope(&star.parent()?)?;
53 let current_module = current_scope.module();
55 let refs_in_target = find_refs_in_mod(ctx, target_module, current_module)?;
56 let imported_defs = find_imported_defs(ctx, star)?;
58 let target = parent.either(|n| n.syntax().clone(), |n| n.syntax().clone());
60 AssistId("expand_glob_import", AssistKind::RefactorRewrite),
64 let use_tree = builder.make_mut(use_tree);
66 let names_to_import = find_names_to_import(ctx, refs_in_target, imported_defs);
67 let expanded = make::use_tree_list(names_to_import.iter().map(|n| {
68 let path = make::ext::ident_path(&n.to_string());
69 make::use_tree(path, None, None, false)
73 match use_tree.star_token() {
75 let needs_braces = use_tree.path().is_some() && names_to_import.len() != 1;
77 ted::replace(star, expanded.syntax())
79 let without_braces = expanded
81 .children_with_tokens()
82 .filter(|child| !matches!(child.kind(), T!['{'] | T!['}']))
84 ted::replace_with_many(star, without_braces)
93 fn find_parent_and_path(
95 ) -> Option<(Either<ast::UseTree, ast::UseTreeList>, ast::Path)> {
96 return star.parent_ancestors().find_map(|n| {
97 find_use_tree_list(n.clone())
98 .map(|(u, p)| (Either::Right(u), p))
99 .or_else(|| find_use_tree(n).map(|(u, p)| (Either::Left(u), p)))
102 fn find_use_tree_list(n: SyntaxNode) -> Option<(ast::UseTreeList, ast::Path)> {
103 let use_tree_list = ast::UseTreeList::cast(n)?;
104 let path = use_tree_list.parent_use_tree().path()?;
105 Some((use_tree_list, path))
108 fn find_use_tree(n: SyntaxNode) -> Option<(ast::UseTree, ast::Path)> {
109 let use_tree = ast::UseTree::cast(n)?;
110 let path = use_tree.path()?;
111 Some((use_tree, path))
115 fn def_is_referenced_in(def: Definition, ctx: &AssistContext<'_>) -> bool {
116 let search_scope = SearchScope::single_file(ctx.file_id());
117 def.usages(&ctx.sema).in_scope(search_scope).at_least_one()
120 #[derive(Debug, Clone)]
128 fn from_scope_def(name: Name, scope_def: ScopeDef) -> Option<Self> {
130 ScopeDef::ModuleDef(def) => {
131 Some(Ref { visible_name: name, def: Definition::from(def) })
138 #[derive(Debug, Clone)]
139 struct Refs(Vec<Ref>);
142 fn used_refs(&self, ctx: &AssistContext<'_>) -> Refs {
148 if let Definition::Trait(tr) = r.def {
149 if tr.items(ctx.db()).into_iter().any(|ai| {
150 if let AssocItem::Function(f) = ai {
151 def_is_referenced_in(Definition::Function(f), ctx)
160 def_is_referenced_in(r.def, ctx)
166 fn filter_out_by_defs(&self, defs: Vec<Definition>) -> Refs {
167 Refs(self.0.clone().into_iter().filter(|r| !defs.contains(&r.def)).collect())
171 fn find_refs_in_mod(ctx: &AssistContext<'_>, module: Module, visible_from: Module) -> Option<Refs> {
172 if !is_mod_visible_from(ctx, module, visible_from) {
176 let module_scope = module.scope(ctx.db(), Some(visible_from));
177 let refs = module_scope.into_iter().filter_map(|(n, d)| Ref::from_scope_def(n, d)).collect();
181 fn is_mod_visible_from(ctx: &AssistContext<'_>, module: Module, from: Module) -> bool {
182 match module.parent(ctx.db()) {
184 module.visibility(ctx.db()).is_visible_from(ctx.db(), from.into())
185 && is_mod_visible_from(ctx, parent, from)
191 // looks for name refs in parent use block's siblings
205 fn find_imported_defs(ctx: &AssistContext<'_>, star: SyntaxToken) -> Option<Vec<Definition>> {
206 let parent_use_item_syntax = star.parent_ancestors().find_map(|n| {
207 if ast::Use::can_cast(n.kind()) {
215 [Direction::Prev, Direction::Next]
218 parent_use_item_syntax
219 .siblings(dir.to_owned())
220 .filter(|n| ast::Use::can_cast(n.kind()))
222 .flat_map(|n| n.descendants().filter_map(ast::NameRef::cast))
223 .filter_map(|r| match NameRefClass::classify(&ctx.sema, &r)? {
224 NameRefClass::Definition(
225 def @ (Definition::Macro(_)
226 | Definition::Module(_)
227 | Definition::Function(_)
229 | Definition::Variant(_)
230 | Definition::Const(_)
231 | Definition::Static(_)
232 | Definition::Trait(_)
233 | Definition::TypeAlias(_)),
241 fn find_names_to_import(
242 ctx: &AssistContext<'_>,
243 refs_in_target: Refs,
244 imported_defs: Vec<Definition>,
246 let used_refs = refs_in_target.used_refs(ctx).filter_out_by_defs(imported_defs);
247 used_refs.0.iter().map(|r| r.visible_name.clone()).collect()
252 use crate::tests::{check_assist, check_assist_not_applicable};
257 fn expanding_glob_import() {
271 fn qux(bar: Bar, baz: Baz) {
284 use foo::{Baz, Bar, f};
286 fn qux(bar: Bar, baz: Baz) {
294 fn expanding_glob_import_unused() {
327 fn expanding_glob_import_with_existing_explicit_names() {
341 fn qux(bar: Bar, baz: Baz) {
354 use foo::{Baz, Bar, f};
356 fn qux(bar: Bar, baz: Baz) {
364 fn expanding_glob_import_with_existing_uses_in_same_module() {
379 fn qux(bar: Bar, baz: Baz) {
395 fn qux(bar: Bar, baz: Baz) {
403 fn expanding_nested_glob_import() {
421 use foo::{bar::{*$0, f}, baz::*};
423 fn qux(bar: Bar, baz: Baz) {
443 use foo::{bar::{Baz, Bar, f}, baz::*};
445 fn qux(bar: Bar, baz: Baz) {
469 use foo::{bar::{Bar, Baz, f}, baz::*$0};
471 fn qux(bar: Bar, baz: Baz) {
491 use foo::{bar::{Bar, Baz, f}, baz::g};
493 fn qux(bar: Bar, baz: Baz) {
531 fn qux(bar: Bar, baz: Baz) {
564 baz::{g, qux::{q, h}}
567 fn qux(bar: Bar, baz: Baz) {
604 baz::{g, qux::{h, q::*$0}}
607 fn qux(bar: Bar, baz: Baz) {
640 baz::{g, qux::{h, q::j}}
643 fn qux(bar: Bar, baz: Baz) {
680 baz::{g, qux::{q::j, *$0}}
683 fn qux(bar: Bar, baz: Baz) {
716 baz::{g, qux::{q::j, h}}
719 fn qux(bar: Bar, baz: Baz) {
730 fn expanding_glob_import_with_macro_defs() {
734 //- /lib.rs crate:foo
742 //- /main.rs crate:main deps:foo
762 fn expanding_glob_import_with_trait_method_uses() {
766 //- /lib.rs crate:foo
772 //- /main.rs crate:main deps:foo
791 //- /lib.rs crate:foo
802 //- /main.rs crate:main deps:foo
820 fn expanding_is_not_applicable_if_target_module_is_not_accessible_from_current_scope() {
821 check_assist_not_applicable(
836 check_assist_not_applicable(
847 use foo::bar::baz::*$0;
855 fn expanding_is_not_applicable_if_cursor_is_not_in_star_token() {
856 check_assist_not_applicable(
867 fn qux(bar: Bar, baz: Baz) {}
873 fn expanding_glob_import_single_nested_glob_only() {