3 helpers::mod_path_to_ast,
4 imports::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(
30 ctx: &AssistContext<'_>,
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() => (),
49 // then search for an import for the first path segment of what we want to replace
50 // that way it is less likely that we import the item from a different location due re-exports
51 let module = match ctx.sema.resolve_path(&path.first_qualifier_or_self())? {
52 hir::PathResolution::Def(module @ hir::ModuleDef::Module(_)) => module,
56 let starts_with_name_ref = !matches!(
57 path.first_segment().and_then(|it| it.kind()),
59 ast::PathSegmentKind::CrateKw
60 | ast::PathSegmentKind::SuperKw
61 | ast::PathSegmentKind::SelfKw
64 let path_to_qualifier = starts_with_name_ref
66 ctx.sema.scope(path.syntax())?.module().find_use_path_prefixed(
69 ctx.config.insert_use.prefix_kind,
74 let scope = ImportScope::find_insert_use_container(path.syntax(), &ctx.sema)?;
75 let target = path.syntax().text_range();
77 AssistId("replace_qualified_name_with_use", AssistKind::RefactorRewrite),
78 "Replace qualified path with use",
81 // Now that we've brought the name into scope, re-qualify all paths that could be
82 // affected (that is, all paths inside the node we added the `use` to).
83 let scope = match scope {
84 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
85 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
86 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
88 shorten_paths(scope.as_syntax_node(), &path);
89 let path = drop_generic_args(&path);
90 // stick the found import in front of the to be replaced path
91 let path = match path_to_qualifier.and_then(|it| mod_path_to_ast(&it).qualifier()) {
92 Some(qualifier) => make::path_concat(qualifier, path),
95 insert_use(&scope, path, &ctx.config.insert_use);
100 fn drop_generic_args(path: &ast::Path) -> ast::Path {
101 let path = path.clone_for_update();
102 if let Some(segment) = path.segment() {
103 if let Some(generic_args) = segment.generic_arg_list() {
104 ted::remove(generic_args.syntax());
110 /// Mutates `node` to shorten `path` in all descendants of `node`.
111 fn shorten_paths(node: &SyntaxNode, path: &ast::Path) {
112 for child in node.children() {
115 // Don't modify `use` items, as this can break the `use` item when injecting a new
116 // import into the use tree.
117 ast::Use(_) => continue,
118 // Don't descend into submodules, they don't have the same `use` items in scope.
119 // FIXME: This isn't true due to `super::*` imports?
120 ast::Module(_) => continue,
121 ast::Path(p) => if maybe_replace_path(p.clone(), path.clone()).is_none() {
122 shorten_paths(p.syntax(), path);
124 _ => shorten_paths(&child, path),
130 fn maybe_replace_path(path: ast::Path, target: ast::Path) -> Option<()> {
131 if !path_eq_no_generics(path.clone(), target) {
135 // Shorten `path`, leaving only its last segment.
136 if let Some(parent) = path.qualifier() {
137 ted::remove(parent.syntax());
139 if let Some(double_colon) = path.coloncolon_token() {
140 ted::remove(&double_colon);
146 fn path_eq_no_generics(lhs: ast::Path, rhs: ast::Path) -> bool {
147 let mut lhs_curr = lhs;
148 let mut rhs_curr = rhs;
150 match lhs_curr.segment().zip(rhs_curr.segment()) {
152 if lhs.coloncolon_token().is_some() == rhs.coloncolon_token().is_some()
156 .map_or(false, |(lhs, rhs)| lhs.text() == rhs.text()) => {}
160 match (lhs_curr.qualifier(), rhs_curr.qualifier()) {
161 (Some(lhs), Some(rhs)) => {
165 (None, None) => return true,
173 use crate::tests::{check_assist, check_assist_not_applicable};
178 fn test_replace_already_imported() {
180 replace_qualified_name_with_use,
182 mod std { pub mod fs { pub struct Path; } }
189 mod std { pub mod fs { pub struct Path; } }
199 fn test_replace_add_use_no_anchor() {
201 replace_qualified_name_with_use,
203 mod std { pub mod fs { pub struct Path; } }
209 mod std { pub mod fs { pub struct Path; } }
216 fn test_replace_add_use_no_anchor_middle_segment() {
218 replace_qualified_name_with_use,
220 mod std { pub mod fs { pub struct Path; } }
226 mod std { pub mod fs { pub struct Path; } }
233 fn dont_import_trivial_paths() {
234 cov_mark::check!(dont_import_trivial_paths);
235 check_assist_not_applicable(replace_qualified_name_with_use, r"impl foo$0 for () {}");
239 fn test_replace_not_applicable_in_use() {
240 cov_mark::check!(not_applicable_in_use);
241 check_assist_not_applicable(replace_qualified_name_with_use, r"use std::fmt$0;");
245 fn replaces_all_affected_paths() {
247 replace_qualified_name_with_use,
249 mod std { pub mod fmt { pub trait Debug {} } }
252 let x: std::fmt::Debug = std::fmt::Debug;
258 mod std { pub mod fmt { pub trait Debug {} } }
261 let x: Debug = Debug;
268 fn does_not_replace_in_submodules() {
270 replace_qualified_name_with_use,
272 mod std { pub mod fmt { pub trait Debug {} } }
286 mod std { pub mod fmt { pub trait Debug {} } }
301 fn does_not_replace_in_use() {
303 replace_qualified_name_with_use,
305 mod std { pub mod fmt { pub trait Display {} } }
306 use std::fmt::Display;
313 mod std { pub mod fmt { pub trait Display {} } }
314 use std::fmt::{Display, self};
324 fn does_not_replace_assoc_item_path() {
325 check_assist_not_applicable(
326 replace_qualified_name_with_use,
341 fn replace_reuses_path_qualifier() {
343 replace_qualified_name_with_use,
350 pub use super::foo::Foo as Bar;
365 pub use super::foo::Foo as Bar;
376 fn replace_does_not_always_try_to_replace_by_full_item_path() {
378 replace_qualified_name_with_use,
384 pub fn drop<T>(_: T) {}
393 use std::mem::{self, drop};
397 pub fn drop<T>(_: T) {}
409 fn replace_should_drop_generic_args_in_use() {
411 replace_qualified_name_with_use,
415 pub fn drop<T>(_: T) {}
420 std::mem::drop::<usize>$0(0);
428 pub fn drop<T>(_: T) {}