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 starts_with_name_ref = !matches!(
58 path.first_segment().and_then(|it| it.kind()),
60 ast::PathSegmentKind::CrateKw
61 | ast::PathSegmentKind::SuperKw
62 | ast::PathSegmentKind::SelfKw
65 let path_to_qualifier = starts_with_name_ref
67 ctx.sema.scope(path.syntax()).module().and_then(|m| {
68 m.find_use_path_prefixed(ctx.sema.db, module, ctx.config.insert_use.prefix_kind)
73 let scope = ImportScope::find_insert_use_container(path.syntax(), &ctx.sema)?;
74 let target = path.syntax().text_range();
76 AssistId("replace_qualified_name_with_use", AssistKind::RefactorRewrite),
77 "Replace qualified path with use",
80 // Now that we've brought the name into scope, re-qualify all paths that could be
81 // affected (that is, all paths inside the node we added the `use` to).
82 let scope = match scope {
83 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
84 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
85 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
87 // stick the found import in front of the to be replaced path
88 let path = match path_to_qualifier.and_then(|it| mod_path_to_ast(&it).qualifier()) {
89 Some(qualifier) => make::path_concat(qualifier, path),
92 shorten_paths(scope.as_syntax_node(), &path.clone_for_update());
93 insert_use(&scope, path, &ctx.config.insert_use);
98 /// Adds replacements to `re` that shorten `path` in all descendants of `node`.
99 fn shorten_paths(node: &SyntaxNode, path: &ast::Path) {
100 for child in node.children() {
103 // Don't modify `use` items, as this can break the `use` item when injecting a new
104 // import into the use tree.
105 ast::Use(_) => continue,
106 // Don't descend into submodules, they don't have the same `use` items in scope.
107 // FIXME: This isn't true due to `super::*` imports?
108 ast::Module(_) => continue,
109 ast::Path(p) => if maybe_replace_path(p.clone(), path.clone()).is_none() {
110 shorten_paths(p.syntax(), path);
112 _ => shorten_paths(&child, path),
118 fn maybe_replace_path(path: ast::Path, target: ast::Path) -> Option<()> {
119 if !path_eq_no_generics(path.clone(), target) {
123 // Shorten `path`, leaving only its last segment.
124 if let Some(parent) = path.qualifier() {
125 ted::remove(parent.syntax());
127 if let Some(double_colon) = path.coloncolon_token() {
128 ted::remove(&double_colon);
134 fn path_eq_no_generics(lhs: ast::Path, rhs: ast::Path) -> bool {
135 let mut lhs_curr = lhs;
136 let mut rhs_curr = rhs;
138 match lhs_curr.segment().zip(rhs_curr.segment()) {
140 if lhs.coloncolon_token().is_some() == rhs.coloncolon_token().is_some()
144 .map_or(false, |(lhs, rhs)| lhs.text() == rhs.text()) => {}
148 match (lhs_curr.qualifier(), rhs_curr.qualifier()) {
149 (Some(lhs), Some(rhs)) => {
153 (None, None) => return true,
161 use crate::tests::{check_assist, check_assist_not_applicable};
166 fn test_replace_already_imported() {
168 replace_qualified_name_with_use,
170 mod std { pub mod fs { pub struct Path; } }
177 mod std { pub mod fs { pub struct Path; } }
187 fn test_replace_add_use_no_anchor() {
189 replace_qualified_name_with_use,
191 mod std { pub mod fs { pub struct Path; } }
197 mod std { pub mod fs { pub struct Path; } }
204 fn test_replace_add_use_no_anchor_middle_segment() {
206 replace_qualified_name_with_use,
208 mod std { pub mod fs { pub struct Path; } }
214 mod std { pub mod fs { pub struct Path; } }
221 fn dont_import_trivial_paths() {
222 cov_mark::check!(dont_import_trivial_paths);
223 check_assist_not_applicable(replace_qualified_name_with_use, r"impl foo$0 for () {}");
227 fn test_replace_not_applicable_in_use() {
228 cov_mark::check!(not_applicable_in_use);
229 check_assist_not_applicable(replace_qualified_name_with_use, r"use std::fmt$0;");
233 fn replaces_all_affected_paths() {
235 replace_qualified_name_with_use,
237 mod std { pub mod fmt { pub trait Debug {} } }
240 let x: std::fmt::Debug = std::fmt::Debug;
246 mod std { pub mod fmt { pub trait Debug {} } }
249 let x: Debug = Debug;
256 fn does_not_replace_in_submodules() {
258 replace_qualified_name_with_use,
260 mod std { pub mod fmt { pub trait Debug {} } }
274 mod std { pub mod fmt { pub trait Debug {} } }
289 fn does_not_replace_in_use() {
291 replace_qualified_name_with_use,
293 mod std { pub mod fmt { pub trait Display {} } }
294 use std::fmt::Display;
301 mod std { pub mod fmt { pub trait Display {} } }
302 use std::fmt::{Display, self};
312 fn does_not_replace_assoc_item_path() {
313 check_assist_not_applicable(
314 replace_qualified_name_with_use,
329 fn replace_reuses_path_qualifier() {
331 replace_qualified_name_with_use,
338 pub use super::foo::Foo as Bar;
353 pub use super::foo::Foo as Bar;