3 insert_use::{insert_use, ImportScope},
8 match_ast, ted, AstNode, SyntaxNode,
11 use crate::{AssistContext, AssistId, AssistKind, Assists};
13 // Assist: replace_qualified_name_with_use
15 // Adds a use statement for a given fully-qualified name.
18 // # mod std { pub mod collections { pub struct HashMap<T, U>(T, U); } }
19 // fn process(map: std::collections::$0HashMap<String, String>) {}
23 // use std::collections::HashMap;
25 // # mod std { pub mod collections { pub struct HashMap<T, U>(T, U); } }
26 // fn process(map: HashMap<String, String>) {}
28 pub(crate) fn replace_qualified_name_with_use(
32 let path: ast::Path = ctx.find_node_at_offset()?;
33 // We don't want to mess with use statements
34 if path.syntax().ancestors().find_map(ast::UseTree::cast).is_some() {
35 cov_mark::hit!(not_applicable_in_use);
39 if path.qualifier().is_none() {
40 cov_mark::hit!(dont_import_trivial_paths);
44 // only offer replacement for non assoc items
45 match ctx.sema.resolve_path(&path)? {
46 hir::PathResolution::Def(def) if def.as_assoc_item(ctx.sema.db).is_none() => (),
47 hir::PathResolution::Macro(_) => (),
50 // then search for an import for the first path segment of what we want to replace
51 // that way it is less likely that we import the item from a different location due re-exports
52 let module = match ctx.sema.resolve_path(&path.first_qualifier_or_self())? {
53 hir::PathResolution::Def(module @ hir::ModuleDef::Module(_)) => module,
57 let scope = ImportScope::find_insert_use_container_with_macros(path.syntax(), &ctx.sema)?;
58 let path_to_qualifier = ctx.sema.scope(path.syntax()).module()?.find_use_path_prefixed(
61 ctx.config.insert_use.prefix_kind,
63 let target = path.syntax().text_range();
65 AssistId("replace_qualified_name_with_use", AssistKind::RefactorRewrite),
66 "Replace qualified path with use",
69 // Now that we've brought the name into scope, re-qualify all paths that could be
70 // affected (that is, all paths inside the node we added the `use` to).
71 let scope = match scope {
72 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
73 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
74 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
76 // stick the found import in front of the to be replaced path
77 let path = match mod_path_to_ast(&path_to_qualifier).qualifier() {
78 Some(qualifier) => make::path_concat(qualifier, path),
81 shorten_paths(scope.as_syntax_node(), &path.clone_for_update());
82 insert_use(&scope, path, &ctx.config.insert_use);
87 /// Adds replacements to `re` that shorten `path` in all descendants of `node`.
88 fn shorten_paths(node: &SyntaxNode, path: &ast::Path) {
89 for child in node.children() {
92 // Don't modify `use` items, as this can break the `use` item when injecting a new
93 // import into the use tree.
94 ast::Use(_it) => continue,
95 // Don't descend into submodules, they don't have the same `use` items in scope.
96 // FIXME: This isn't true due to `super::*` imports?
97 ast::Module(_it) => continue,
98 ast::Path(p) => if maybe_replace_path(p.clone(), path.clone()).is_none() {
99 shorten_paths(p.syntax(), path);
101 _ => shorten_paths(&child, path),
107 fn maybe_replace_path(path: ast::Path, target: ast::Path) -> Option<()> {
108 if !path_eq_no_generics(path.clone(), target) {
112 // Shorten `path`, leaving only its last segment.
113 if let Some(parent) = path.qualifier() {
114 ted::remove(parent.syntax());
116 if let Some(double_colon) = path.coloncolon_token() {
117 ted::remove(&double_colon);
123 fn path_eq_no_generics(lhs: ast::Path, rhs: ast::Path) -> bool {
124 let mut lhs_curr = lhs;
125 let mut rhs_curr = rhs;
127 match lhs_curr.segment().zip(rhs_curr.segment()) {
129 if lhs.coloncolon_token().is_some() == rhs.coloncolon_token().is_some()
133 .map_or(false, |(lhs, rhs)| lhs.text() == rhs.text()) =>
140 match (lhs_curr.qualifier(), rhs_curr.qualifier()) {
141 (Some(lhs), Some(rhs)) => {
145 (None, None) => return true,
153 use crate::tests::{check_assist, check_assist_not_applicable};
158 fn test_replace_already_imported() {
160 replace_qualified_name_with_use,
162 mod std { pub mod fs { pub struct Path; } }
169 mod std { pub mod fs { pub struct Path; } }
179 fn test_replace_add_use_no_anchor() {
181 replace_qualified_name_with_use,
183 mod std { pub mod fs { pub struct Path; } }
189 mod std { pub mod fs { pub struct Path; } }
196 fn test_replace_add_use_no_anchor_middle_segment() {
198 replace_qualified_name_with_use,
200 mod std { pub mod fs { pub struct Path; } }
206 mod std { pub mod fs { pub struct Path; } }
213 fn dont_import_trivial_paths() {
214 cov_mark::check!(dont_import_trivial_paths);
215 check_assist_not_applicable(replace_qualified_name_with_use, r"impl foo$0 for () {}");
219 fn test_replace_not_applicable_in_use() {
220 cov_mark::check!(not_applicable_in_use);
221 check_assist_not_applicable(replace_qualified_name_with_use, r"use std::fmt$0;");
225 fn replaces_all_affected_paths() {
227 replace_qualified_name_with_use,
229 mod std { pub mod fmt { pub trait Debug {} } }
232 let x: std::fmt::Debug = std::fmt::Debug;
238 mod std { pub mod fmt { pub trait Debug {} } }
241 let x: Debug = Debug;
248 fn does_not_replace_in_submodules() {
250 replace_qualified_name_with_use,
252 mod std { pub mod fmt { pub trait Debug {} } }
266 mod std { pub mod fmt { pub trait Debug {} } }
281 fn does_not_replace_in_use() {
283 replace_qualified_name_with_use,
285 mod std { pub mod fmt { pub trait Display {} } }
286 use std::fmt::Display;
293 mod std { pub mod fmt { pub trait Display {} } }
294 use std::fmt::{self, Display};
304 fn does_not_replace_assoc_item_path() {
305 check_assist_not_applicable(
306 replace_qualified_name_with_use,
321 fn replace_reuses_path_qualifier() {
323 replace_qualified_name_with_use,
330 pub use super::foo::Foo as Bar;
345 pub use super::foo::Foo as Bar;