]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/handlers/replace_qualified_name_with_use.rs
Merge #9453
[rust.git] / crates / ide_assists / src / handlers / replace_qualified_name_with_use.rs
1 use hir::AsAssocItem;
2 use ide_db::helpers::{
3     insert_use::{insert_use, ImportScope},
4     mod_path_to_ast,
5 };
6 use syntax::{
7     ast::{self, make},
8     match_ast, ted, AstNode, SyntaxNode,
9 };
10
11 use crate::{AssistContext, AssistId, AssistKind, Assists};
12
13 // Assist: replace_qualified_name_with_use
14 //
15 // Adds a use statement for a given fully-qualified name.
16 //
17 // ```
18 // # mod std { pub mod collections { pub struct HashMap<T, U>(T, U); } }
19 // fn process(map: std::collections::$0HashMap<String, String>) {}
20 // ```
21 // ->
22 // ```
23 // use std::collections::HashMap;
24 //
25 // # mod std { pub mod collections { pub struct HashMap<T, U>(T, U); } }
26 // fn process(map: HashMap<String, String>) {}
27 // ```
28 pub(crate) fn replace_qualified_name_with_use(
29     acc: &mut Assists,
30     ctx: &AssistContext,
31 ) -> Option<()> {
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);
36         return None;
37     }
38
39     if path.qualifier().is_none() {
40         cov_mark::hit!(dont_import_trivial_paths);
41         return None;
42     }
43
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(_) => (),
48         _ => return None,
49     }
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,
54         _ => return None,
55     };
56
57     let starts_with_name_ref = !matches!(
58         path.first_segment().and_then(|it| it.kind()),
59         Some(
60             ast::PathSegmentKind::CrateKw
61                 | ast::PathSegmentKind::SuperKw
62                 | ast::PathSegmentKind::SelfKw
63         )
64     );
65     let path_to_qualifier = starts_with_name_ref
66         .then(|| {
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)
69             })
70         })
71         .flatten();
72
73     let scope = ImportScope::find_insert_use_container_with_macros(path.syntax(), &ctx.sema)?;
74     let target = path.syntax().text_range();
75     acc.add(
76         AssistId("replace_qualified_name_with_use", AssistKind::RefactorRewrite),
77         "Replace qualified path with use",
78         target,
79         |builder| {
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)),
86             };
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),
90                 None => path,
91             };
92             shorten_paths(scope.as_syntax_node(), &path.clone_for_update());
93             insert_use(&scope, path, &ctx.config.insert_use);
94         },
95     )
96 }
97
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() {
101         match_ast! {
102             match child {
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(_it) => 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(_it) => continue,
109                 ast::Path(p) => if maybe_replace_path(p.clone(), path.clone()).is_none() {
110                     shorten_paths(p.syntax(), path);
111                 },
112                 _ => shorten_paths(&child, path),
113             }
114         }
115     }
116 }
117
118 fn maybe_replace_path(path: ast::Path, target: ast::Path) -> Option<()> {
119     if !path_eq_no_generics(path.clone(), target) {
120         return None;
121     }
122
123     // Shorten `path`, leaving only its last segment.
124     if let Some(parent) = path.qualifier() {
125         ted::remove(parent.syntax());
126     }
127     if let Some(double_colon) = path.coloncolon_token() {
128         ted::remove(&double_colon);
129     }
130
131     Some(())
132 }
133
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;
137     loop {
138         match lhs_curr.segment().zip(rhs_curr.segment()) {
139             Some((lhs, rhs))
140                 if lhs.coloncolon_token().is_some() == rhs.coloncolon_token().is_some()
141                     && lhs
142                         .name_ref()
143                         .zip(rhs.name_ref())
144                         .map_or(false, |(lhs, rhs)| lhs.text() == rhs.text()) =>
145             {
146                 ()
147             }
148             _ => return false,
149         }
150
151         match (lhs_curr.qualifier(), rhs_curr.qualifier()) {
152             (Some(lhs), Some(rhs)) => {
153                 lhs_curr = lhs;
154                 rhs_curr = rhs;
155             }
156             (None, None) => return true,
157             _ => return false,
158         }
159     }
160 }
161
162 #[cfg(test)]
163 mod tests {
164     use crate::tests::{check_assist, check_assist_not_applicable};
165
166     use super::*;
167
168     #[test]
169     fn test_replace_already_imported() {
170         check_assist(
171             replace_qualified_name_with_use,
172             r"
173 mod std { pub mod fs { pub struct Path; } }
174 use std::fs;
175
176 fn main() {
177     std::f$0s::Path
178 }",
179             r"
180 mod std { pub mod fs { pub struct Path; } }
181 use std::fs;
182
183 fn main() {
184     fs::Path
185 }",
186         )
187     }
188
189     #[test]
190     fn test_replace_add_use_no_anchor() {
191         check_assist(
192             replace_qualified_name_with_use,
193             r"
194 mod std { pub mod fs { pub struct Path; } }
195 std::fs::Path$0
196     ",
197             r"
198 use std::fs::Path;
199
200 mod std { pub mod fs { pub struct Path; } }
201 Path
202     ",
203         );
204     }
205
206     #[test]
207     fn test_replace_add_use_no_anchor_middle_segment() {
208         check_assist(
209             replace_qualified_name_with_use,
210             r"
211 mod std { pub mod fs { pub struct Path; } }
212 std::fs$0::Path
213     ",
214             r"
215 use std::fs;
216
217 mod std { pub mod fs { pub struct Path; } }
218 fs::Path
219     ",
220         );
221     }
222     #[test]
223     #[test]
224     fn dont_import_trivial_paths() {
225         cov_mark::check!(dont_import_trivial_paths);
226         check_assist_not_applicable(replace_qualified_name_with_use, r"impl foo$0 for () {}");
227     }
228
229     #[test]
230     fn test_replace_not_applicable_in_use() {
231         cov_mark::check!(not_applicable_in_use);
232         check_assist_not_applicable(replace_qualified_name_with_use, r"use std::fmt$0;");
233     }
234
235     #[test]
236     fn replaces_all_affected_paths() {
237         check_assist(
238             replace_qualified_name_with_use,
239             r"
240 mod std { pub mod fmt { pub trait Debug {} } }
241 fn main() {
242     std::fmt::Debug$0;
243     let x: std::fmt::Debug = std::fmt::Debug;
244 }
245     ",
246             r"
247 use std::fmt::Debug;
248
249 mod std { pub mod fmt { pub trait Debug {} } }
250 fn main() {
251     Debug;
252     let x: Debug = Debug;
253 }
254     ",
255         );
256     }
257
258     #[test]
259     fn does_not_replace_in_submodules() {
260         check_assist(
261             replace_qualified_name_with_use,
262             r"
263 mod std { pub mod fmt { pub trait Debug {} } }
264 fn main() {
265     std::fmt::Debug$0;
266 }
267
268 mod sub {
269     fn f() {
270         std::fmt::Debug;
271     }
272 }
273     ",
274             r"
275 use std::fmt::Debug;
276
277 mod std { pub mod fmt { pub trait Debug {} } }
278 fn main() {
279     Debug;
280 }
281
282 mod sub {
283     fn f() {
284         std::fmt::Debug;
285     }
286 }
287     ",
288         );
289     }
290
291     #[test]
292     fn does_not_replace_in_use() {
293         check_assist(
294             replace_qualified_name_with_use,
295             r"
296 mod std { pub mod fmt { pub trait Display {} } }
297 use std::fmt::Display;
298
299 fn main() {
300     std::fmt$0;
301 }
302     ",
303             r"
304 mod std { pub mod fmt { pub trait Display {} } }
305 use std::fmt::{self, Display};
306
307 fn main() {
308     fmt;
309 }
310     ",
311         );
312     }
313
314     #[test]
315     fn does_not_replace_assoc_item_path() {
316         check_assist_not_applicable(
317             replace_qualified_name_with_use,
318             r"
319 pub struct Foo;
320 impl Foo {
321     pub fn foo() {}
322 }
323
324 fn main() {
325     Foo::foo$0();
326 }
327 ",
328         );
329     }
330
331     #[test]
332     fn replace_reuses_path_qualifier() {
333         check_assist(
334             replace_qualified_name_with_use,
335             r"
336 pub mod foo {
337     pub struct Foo;
338 }
339
340 mod bar {
341     pub use super::foo::Foo as Bar;
342 }
343
344 fn main() {
345     foo::Foo$0;
346 }
347 ",
348             r"
349 use foo::Foo;
350
351 pub mod foo {
352     pub struct Foo;
353 }
354
355 mod bar {
356     pub use super::foo::Foo as Bar;
357 }
358
359 fn main() {
360     Foo;
361 }
362 ",
363         );
364     }
365 }