diff options
author | Kevin DeLorey <[email protected]> | 2020-02-09 16:25:47 +0000 |
---|---|---|
committer | Kevin DeLorey <[email protected]> | 2020-02-09 16:37:43 +0000 |
commit | a957c473fdb79880c39b73dc9e0c923093cf16ac (patch) | |
tree | f998b548f530ce604651e0e6af314ed2ec74b3b5 /crates/ra_assists/src/handlers/replace_qualified_name_with_use.rs | |
parent | 22caf982b99c54058e2e9200aeea0e61cada284a (diff) | |
parent | 1b9b13b4b4a75b5531c3f046ce6bf72d681f2732 (diff) |
Merge branch 'master' into kdelorey/complete-trait-impl
Diffstat (limited to 'crates/ra_assists/src/handlers/replace_qualified_name_with_use.rs')
-rw-r--r-- | crates/ra_assists/src/handlers/replace_qualified_name_with_use.rs | 965 |
1 files changed, 965 insertions, 0 deletions
diff --git a/crates/ra_assists/src/handlers/replace_qualified_name_with_use.rs b/crates/ra_assists/src/handlers/replace_qualified_name_with_use.rs new file mode 100644 index 000000000..b70c88ec2 --- /dev/null +++ b/crates/ra_assists/src/handlers/replace_qualified_name_with_use.rs | |||
@@ -0,0 +1,965 @@ | |||
1 | use hir::{self, ModPath}; | ||
2 | use ra_syntax::{ | ||
3 | ast::{self, NameOwner}, | ||
4 | AstNode, Direction, SmolStr, | ||
5 | SyntaxKind::{PATH, PATH_SEGMENT}, | ||
6 | SyntaxNode, TextRange, T, | ||
7 | }; | ||
8 | use ra_text_edit::TextEditBuilder; | ||
9 | |||
10 | use crate::{ | ||
11 | assist_ctx::{Assist, AssistCtx}, | ||
12 | AssistId, | ||
13 | }; | ||
14 | |||
15 | /// Creates and inserts a use statement for the given path to import. | ||
16 | /// The use statement is inserted in the scope most appropriate to the | ||
17 | /// the cursor position given, additionally merged with the existing use imports. | ||
18 | pub fn insert_use_statement( | ||
19 | // Ideally the position of the cursor, used to | ||
20 | position: &SyntaxNode, | ||
21 | // The statement to use as anchor (last resort) | ||
22 | anchor: &SyntaxNode, | ||
23 | path_to_import: &ModPath, | ||
24 | edit: &mut TextEditBuilder, | ||
25 | ) { | ||
26 | let target = path_to_import.to_string().split("::").map(SmolStr::new).collect::<Vec<_>>(); | ||
27 | let container = position.ancestors().find_map(|n| { | ||
28 | if let Some(module) = ast::Module::cast(n.clone()) { | ||
29 | return module.item_list().map(|it| it.syntax().clone()); | ||
30 | } | ||
31 | ast::SourceFile::cast(n).map(|it| it.syntax().clone()) | ||
32 | }); | ||
33 | |||
34 | if let Some(container) = container { | ||
35 | let action = best_action_for_target(container, anchor.clone(), &target); | ||
36 | make_assist(&action, &target, edit); | ||
37 | } | ||
38 | } | ||
39 | |||
40 | // Assist: replace_qualified_name_with_use | ||
41 | // | ||
42 | // Adds a use statement for a given fully-qualified name. | ||
43 | // | ||
44 | // ``` | ||
45 | // fn process(map: std::collections::<|>HashMap<String, String>) {} | ||
46 | // ``` | ||
47 | // -> | ||
48 | // ``` | ||
49 | // use std::collections::HashMap; | ||
50 | // | ||
51 | // fn process(map: HashMap<String, String>) {} | ||
52 | // ``` | ||
53 | pub(crate) fn replace_qualified_name_with_use(ctx: AssistCtx) -> Option<Assist> { | ||
54 | let path: ast::Path = ctx.find_node_at_offset()?; | ||
55 | // We don't want to mess with use statements | ||
56 | if path.syntax().ancestors().find_map(ast::UseItem::cast).is_some() { | ||
57 | return None; | ||
58 | } | ||
59 | |||
60 | let hir_path = hir::Path::from_ast(path.clone())?; | ||
61 | let segments = collect_hir_path_segments(&hir_path)?; | ||
62 | if segments.len() < 2 { | ||
63 | return None; | ||
64 | } | ||
65 | |||
66 | let module = path.syntax().ancestors().find_map(ast::Module::cast); | ||
67 | let position = match module.and_then(|it| it.item_list()) { | ||
68 | Some(item_list) => item_list.syntax().clone(), | ||
69 | None => { | ||
70 | let current_file = path.syntax().ancestors().find_map(ast::SourceFile::cast)?; | ||
71 | current_file.syntax().clone() | ||
72 | } | ||
73 | }; | ||
74 | |||
75 | ctx.add_assist( | ||
76 | AssistId("replace_qualified_name_with_use"), | ||
77 | "Replace qualified path with use", | ||
78 | |edit| { | ||
79 | replace_with_use(&position, &path, &segments, edit.text_edit_builder()); | ||
80 | }, | ||
81 | ) | ||
82 | } | ||
83 | |||
84 | fn collect_path_segments_raw( | ||
85 | segments: &mut Vec<ast::PathSegment>, | ||
86 | mut path: ast::Path, | ||
87 | ) -> Option<usize> { | ||
88 | let oldlen = segments.len(); | ||
89 | loop { | ||
90 | let mut children = path.syntax().children_with_tokens(); | ||
91 | let (first, second, third) = ( | ||
92 | children.next().map(|n| (n.clone(), n.kind())), | ||
93 | children.next().map(|n| (n.clone(), n.kind())), | ||
94 | children.next().map(|n| (n.clone(), n.kind())), | ||
95 | ); | ||
96 | match (first, second, third) { | ||
97 | (Some((subpath, PATH)), Some((_, T![::])), Some((segment, PATH_SEGMENT))) => { | ||
98 | path = ast::Path::cast(subpath.as_node()?.clone())?; | ||
99 | segments.push(ast::PathSegment::cast(segment.as_node()?.clone())?); | ||
100 | } | ||
101 | (Some((segment, PATH_SEGMENT)), _, _) => { | ||
102 | segments.push(ast::PathSegment::cast(segment.as_node()?.clone())?); | ||
103 | break; | ||
104 | } | ||
105 | (_, _, _) => return None, | ||
106 | } | ||
107 | } | ||
108 | // We need to reverse only the new added segments | ||
109 | let only_new_segments = segments.split_at_mut(oldlen).1; | ||
110 | only_new_segments.reverse(); | ||
111 | Some(segments.len() - oldlen) | ||
112 | } | ||
113 | |||
114 | fn fmt_segments_raw(segments: &[SmolStr], buf: &mut String) { | ||
115 | let mut iter = segments.iter(); | ||
116 | if let Some(s) = iter.next() { | ||
117 | buf.push_str(s); | ||
118 | } | ||
119 | for s in iter { | ||
120 | buf.push_str("::"); | ||
121 | buf.push_str(s); | ||
122 | } | ||
123 | } | ||
124 | |||
125 | /// Returns the number of common segments. | ||
126 | fn compare_path_segments(left: &[SmolStr], right: &[ast::PathSegment]) -> usize { | ||
127 | left.iter().zip(right).take_while(|(l, r)| compare_path_segment(l, r)).count() | ||
128 | } | ||
129 | |||
130 | fn compare_path_segment(a: &SmolStr, b: &ast::PathSegment) -> bool { | ||
131 | if let Some(kb) = b.kind() { | ||
132 | match kb { | ||
133 | ast::PathSegmentKind::Name(nameref_b) => a == nameref_b.text(), | ||
134 | ast::PathSegmentKind::SelfKw => a == "self", | ||
135 | ast::PathSegmentKind::SuperKw => a == "super", | ||
136 | ast::PathSegmentKind::CrateKw => a == "crate", | ||
137 | ast::PathSegmentKind::Type { .. } => false, // not allowed in imports | ||
138 | } | ||
139 | } else { | ||
140 | false | ||
141 | } | ||
142 | } | ||
143 | |||
144 | fn compare_path_segment_with_name(a: &SmolStr, b: &ast::Name) -> bool { | ||
145 | a == b.text() | ||
146 | } | ||
147 | |||
148 | #[derive(Clone, Debug)] | ||
149 | enum ImportAction { | ||
150 | Nothing, | ||
151 | // Add a brand new use statement. | ||
152 | AddNewUse { | ||
153 | anchor: Option<SyntaxNode>, // anchor node | ||
154 | add_after_anchor: bool, | ||
155 | }, | ||
156 | |||
157 | // To split an existing use statement creating a nested import. | ||
158 | AddNestedImport { | ||
159 | // how may segments matched with the target path | ||
160 | common_segments: usize, | ||
161 | path_to_split: ast::Path, | ||
162 | // the first segment of path_to_split we want to add into the new nested list | ||
163 | first_segment_to_split: Option<ast::PathSegment>, | ||
164 | // Wether to add 'self' in addition to the target path | ||
165 | add_self: bool, | ||
166 | }, | ||
167 | // To add the target path to an existing nested import tree list. | ||
168 | AddInTreeList { | ||
169 | common_segments: usize, | ||
170 | // The UseTreeList where to add the target path | ||
171 | tree_list: ast::UseTreeList, | ||
172 | add_self: bool, | ||
173 | }, | ||
174 | } | ||
175 | |||
176 | impl ImportAction { | ||
177 | fn add_new_use(anchor: Option<SyntaxNode>, add_after_anchor: bool) -> Self { | ||
178 | ImportAction::AddNewUse { anchor, add_after_anchor } | ||
179 | } | ||
180 | |||
181 | fn add_nested_import( | ||
182 | common_segments: usize, | ||
183 | path_to_split: ast::Path, | ||
184 | first_segment_to_split: Option<ast::PathSegment>, | ||
185 | add_self: bool, | ||
186 | ) -> Self { | ||
187 | ImportAction::AddNestedImport { | ||
188 | common_segments, | ||
189 | path_to_split, | ||
190 | first_segment_to_split, | ||
191 | add_self, | ||
192 | } | ||
193 | } | ||
194 | |||
195 | fn add_in_tree_list( | ||
196 | common_segments: usize, | ||
197 | tree_list: ast::UseTreeList, | ||
198 | add_self: bool, | ||
199 | ) -> Self { | ||
200 | ImportAction::AddInTreeList { common_segments, tree_list, add_self } | ||
201 | } | ||
202 | |||
203 | fn better(left: ImportAction, right: ImportAction) -> ImportAction { | ||
204 | if left.is_better(&right) { | ||
205 | left | ||
206 | } else { | ||
207 | right | ||
208 | } | ||
209 | } | ||
210 | |||
211 | fn is_better(&self, other: &ImportAction) -> bool { | ||
212 | match (self, other) { | ||
213 | (ImportAction::Nothing, _) => true, | ||
214 | (ImportAction::AddInTreeList { .. }, ImportAction::Nothing) => false, | ||
215 | ( | ||
216 | ImportAction::AddNestedImport { common_segments: n, .. }, | ||
217 | ImportAction::AddInTreeList { common_segments: m, .. }, | ||
218 | ) | ||
219 | | ( | ||
220 | ImportAction::AddInTreeList { common_segments: n, .. }, | ||
221 | ImportAction::AddNestedImport { common_segments: m, .. }, | ||
222 | ) | ||
223 | | ( | ||
224 | ImportAction::AddInTreeList { common_segments: n, .. }, | ||
225 | ImportAction::AddInTreeList { common_segments: m, .. }, | ||
226 | ) | ||
227 | | ( | ||
228 | ImportAction::AddNestedImport { common_segments: n, .. }, | ||
229 | ImportAction::AddNestedImport { common_segments: m, .. }, | ||
230 | ) => n > m, | ||
231 | (ImportAction::AddInTreeList { .. }, _) => true, | ||
232 | (ImportAction::AddNestedImport { .. }, ImportAction::Nothing) => false, | ||
233 | (ImportAction::AddNestedImport { .. }, _) => true, | ||
234 | (ImportAction::AddNewUse { .. }, _) => false, | ||
235 | } | ||
236 | } | ||
237 | } | ||
238 | |||
239 | // Find out the best ImportAction to import target path against current_use_tree. | ||
240 | // If current_use_tree has a nested import the function gets called recursively on every UseTree inside a UseTreeList. | ||
241 | fn walk_use_tree_for_best_action( | ||
242 | current_path_segments: &mut Vec<ast::PathSegment>, // buffer containing path segments | ||
243 | current_parent_use_tree_list: Option<ast::UseTreeList>, // will be Some value if we are in a nested import | ||
244 | current_use_tree: ast::UseTree, // the use tree we are currently examinating | ||
245 | target: &[SmolStr], // the path we want to import | ||
246 | ) -> ImportAction { | ||
247 | // We save the number of segments in the buffer so we can restore the correct segments | ||
248 | // before returning. Recursive call will add segments so we need to delete them. | ||
249 | let prev_len = current_path_segments.len(); | ||
250 | |||
251 | let tree_list = current_use_tree.use_tree_list(); | ||
252 | let alias = current_use_tree.alias(); | ||
253 | |||
254 | let path = match current_use_tree.path() { | ||
255 | Some(path) => path, | ||
256 | None => { | ||
257 | // If the use item don't have a path, it means it's broken (syntax error) | ||
258 | return ImportAction::add_new_use( | ||
259 | current_use_tree | ||
260 | .syntax() | ||
261 | .ancestors() | ||
262 | .find_map(ast::UseItem::cast) | ||
263 | .map(|it| it.syntax().clone()), | ||
264 | true, | ||
265 | ); | ||
266 | } | ||
267 | }; | ||
268 | |||
269 | // This can happen only if current_use_tree is a direct child of a UseItem | ||
270 | if let Some(name) = alias.and_then(|it| it.name()) { | ||
271 | if compare_path_segment_with_name(&target[0], &name) { | ||
272 | return ImportAction::Nothing; | ||
273 | } | ||
274 | } | ||
275 | |||
276 | collect_path_segments_raw(current_path_segments, path.clone()); | ||
277 | |||
278 | // We compare only the new segments added in the line just above. | ||
279 | // The first prev_len segments were already compared in 'parent' recursive calls. | ||
280 | let left = target.split_at(prev_len).1; | ||
281 | let right = current_path_segments.split_at(prev_len).1; | ||
282 | let common = compare_path_segments(left, &right); | ||
283 | let mut action = match common { | ||
284 | 0 => ImportAction::add_new_use( | ||
285 | // e.g: target is std::fmt and we can have | ||
286 | // use foo::bar | ||
287 | // We add a brand new use statement | ||
288 | current_use_tree | ||
289 | .syntax() | ||
290 | .ancestors() | ||
291 | .find_map(ast::UseItem::cast) | ||
292 | .map(|it| it.syntax().clone()), | ||
293 | true, | ||
294 | ), | ||
295 | common if common == left.len() && left.len() == right.len() => { | ||
296 | // e.g: target is std::fmt and we can have | ||
297 | // 1- use std::fmt; | ||
298 | // 2- use std::fmt::{ ... } | ||
299 | if let Some(list) = tree_list { | ||
300 | // In case 2 we need to add self to the nested list | ||
301 | // unless it's already there | ||
302 | let has_self = list.use_trees().map(|it| it.path()).any(|p| { | ||
303 | p.and_then(|it| it.segment()) | ||
304 | .and_then(|it| it.kind()) | ||
305 | .filter(|k| *k == ast::PathSegmentKind::SelfKw) | ||
306 | .is_some() | ||
307 | }); | ||
308 | |||
309 | if has_self { | ||
310 | ImportAction::Nothing | ||
311 | } else { | ||
312 | ImportAction::add_in_tree_list(current_path_segments.len(), list, true) | ||
313 | } | ||
314 | } else { | ||
315 | // Case 1 | ||
316 | ImportAction::Nothing | ||
317 | } | ||
318 | } | ||
319 | common if common != left.len() && left.len() == right.len() => { | ||
320 | // e.g: target is std::fmt and we have | ||
321 | // use std::io; | ||
322 | // We need to split. | ||
323 | let segments_to_split = current_path_segments.split_at(prev_len + common).1; | ||
324 | ImportAction::add_nested_import( | ||
325 | prev_len + common, | ||
326 | path, | ||
327 | Some(segments_to_split[0].clone()), | ||
328 | false, | ||
329 | ) | ||
330 | } | ||
331 | common if common == right.len() && left.len() > right.len() => { | ||
332 | // e.g: target is std::fmt and we can have | ||
333 | // 1- use std; | ||
334 | // 2- use std::{ ... }; | ||
335 | |||
336 | // fallback action | ||
337 | let mut better_action = ImportAction::add_new_use( | ||
338 | current_use_tree | ||
339 | .syntax() | ||
340 | .ancestors() | ||
341 | .find_map(ast::UseItem::cast) | ||
342 | .map(|it| it.syntax().clone()), | ||
343 | true, | ||
344 | ); | ||
345 | if let Some(list) = tree_list { | ||
346 | // Case 2, check recursively if the path is already imported in the nested list | ||
347 | for u in list.use_trees() { | ||
348 | let child_action = walk_use_tree_for_best_action( | ||
349 | current_path_segments, | ||
350 | Some(list.clone()), | ||
351 | u, | ||
352 | target, | ||
353 | ); | ||
354 | if child_action.is_better(&better_action) { | ||
355 | better_action = child_action; | ||
356 | if let ImportAction::Nothing = better_action { | ||
357 | return better_action; | ||
358 | } | ||
359 | } | ||
360 | } | ||
361 | } else { | ||
362 | // Case 1, split adding self | ||
363 | better_action = ImportAction::add_nested_import(prev_len + common, path, None, true) | ||
364 | } | ||
365 | better_action | ||
366 | } | ||
367 | common if common == left.len() && left.len() < right.len() => { | ||
368 | // e.g: target is std::fmt and we can have | ||
369 | // use std::fmt::Debug; | ||
370 | let segments_to_split = current_path_segments.split_at(prev_len + common).1; | ||
371 | ImportAction::add_nested_import( | ||
372 | prev_len + common, | ||
373 | path, | ||
374 | Some(segments_to_split[0].clone()), | ||
375 | true, | ||
376 | ) | ||
377 | } | ||
378 | common if common < left.len() && common < right.len() => { | ||
379 | // e.g: target is std::fmt::nested::Debug | ||
380 | // use std::fmt::Display | ||
381 | let segments_to_split = current_path_segments.split_at(prev_len + common).1; | ||
382 | ImportAction::add_nested_import( | ||
383 | prev_len + common, | ||
384 | path, | ||
385 | Some(segments_to_split[0].clone()), | ||
386 | false, | ||
387 | ) | ||
388 | } | ||
389 | _ => unreachable!(), | ||
390 | }; | ||
391 | |||
392 | // If we are inside a UseTreeList adding a use statement become adding to the existing | ||
393 | // tree list. | ||
394 | action = match (current_parent_use_tree_list, action.clone()) { | ||
395 | (Some(use_tree_list), ImportAction::AddNewUse { .. }) => { | ||
396 | ImportAction::add_in_tree_list(prev_len, use_tree_list, false) | ||
397 | } | ||
398 | (_, _) => action, | ||
399 | }; | ||
400 | |||
401 | // We remove the segments added | ||
402 | current_path_segments.truncate(prev_len); | ||
403 | action | ||
404 | } | ||
405 | |||
406 | fn best_action_for_target( | ||
407 | container: SyntaxNode, | ||
408 | anchor: SyntaxNode, | ||
409 | target: &[SmolStr], | ||
410 | ) -> ImportAction { | ||
411 | let mut storage = Vec::with_capacity(16); // this should be the only allocation | ||
412 | let best_action = container | ||
413 | .children() | ||
414 | .filter_map(ast::UseItem::cast) | ||
415 | .filter_map(|it| it.use_tree()) | ||
416 | .map(|u| walk_use_tree_for_best_action(&mut storage, None, u, target)) | ||
417 | .fold(None, |best, a| match best { | ||
418 | Some(best) => Some(ImportAction::better(best, a)), | ||
419 | None => Some(a), | ||
420 | }); | ||
421 | |||
422 | match best_action { | ||
423 | Some(action) => action, | ||
424 | None => { | ||
425 | // We have no action and no UseItem was found in container so we find | ||
426 | // another item and we use it as anchor. | ||
427 | // If there are no items above, we choose the target path itself as anchor. | ||
428 | // todo: we should include even whitespace blocks as anchor candidates | ||
429 | let anchor = container | ||
430 | .children() | ||
431 | .find(|n| n.text_range().start() < anchor.text_range().start()) | ||
432 | .or_else(|| Some(anchor)); | ||
433 | |||
434 | ImportAction::add_new_use(anchor, false) | ||
435 | } | ||
436 | } | ||
437 | } | ||
438 | |||
439 | fn make_assist(action: &ImportAction, target: &[SmolStr], edit: &mut TextEditBuilder) { | ||
440 | match action { | ||
441 | ImportAction::AddNewUse { anchor, add_after_anchor } => { | ||
442 | make_assist_add_new_use(anchor, *add_after_anchor, target, edit) | ||
443 | } | ||
444 | ImportAction::AddInTreeList { common_segments, tree_list, add_self } => { | ||
445 | // We know that the fist n segments already exists in the use statement we want | ||
446 | // to modify, so we want to add only the last target.len() - n segments. | ||
447 | let segments_to_add = target.split_at(*common_segments).1; | ||
448 | make_assist_add_in_tree_list(tree_list, segments_to_add, *add_self, edit) | ||
449 | } | ||
450 | ImportAction::AddNestedImport { | ||
451 | common_segments, | ||
452 | path_to_split, | ||
453 | first_segment_to_split, | ||
454 | add_self, | ||
455 | } => { | ||
456 | let segments_to_add = target.split_at(*common_segments).1; | ||
457 | make_assist_add_nested_import( | ||
458 | path_to_split, | ||
459 | first_segment_to_split, | ||
460 | segments_to_add, | ||
461 | *add_self, | ||
462 | edit, | ||
463 | ) | ||
464 | } | ||
465 | _ => {} | ||
466 | } | ||
467 | } | ||
468 | |||
469 | fn make_assist_add_new_use( | ||
470 | anchor: &Option<SyntaxNode>, | ||
471 | after: bool, | ||
472 | target: &[SmolStr], | ||
473 | edit: &mut TextEditBuilder, | ||
474 | ) { | ||
475 | if let Some(anchor) = anchor { | ||
476 | let indent = ra_fmt::leading_indent(anchor); | ||
477 | let mut buf = String::new(); | ||
478 | if after { | ||
479 | buf.push_str("\n"); | ||
480 | if let Some(spaces) = &indent { | ||
481 | buf.push_str(spaces); | ||
482 | } | ||
483 | } | ||
484 | buf.push_str("use "); | ||
485 | fmt_segments_raw(target, &mut buf); | ||
486 | buf.push_str(";"); | ||
487 | if !after { | ||
488 | buf.push_str("\n\n"); | ||
489 | if let Some(spaces) = &indent { | ||
490 | buf.push_str(&spaces); | ||
491 | } | ||
492 | } | ||
493 | let position = if after { anchor.text_range().end() } else { anchor.text_range().start() }; | ||
494 | edit.insert(position, buf); | ||
495 | } | ||
496 | } | ||
497 | |||
498 | fn make_assist_add_in_tree_list( | ||
499 | tree_list: &ast::UseTreeList, | ||
500 | target: &[SmolStr], | ||
501 | add_self: bool, | ||
502 | edit: &mut TextEditBuilder, | ||
503 | ) { | ||
504 | let last = tree_list.use_trees().last(); | ||
505 | if let Some(last) = last { | ||
506 | let mut buf = String::new(); | ||
507 | let comma = last.syntax().siblings(Direction::Next).find(|n| n.kind() == T![,]); | ||
508 | let offset = if let Some(comma) = comma { | ||
509 | comma.text_range().end() | ||
510 | } else { | ||
511 | buf.push_str(","); | ||
512 | last.syntax().text_range().end() | ||
513 | }; | ||
514 | if add_self { | ||
515 | buf.push_str(" self") | ||
516 | } else { | ||
517 | buf.push_str(" "); | ||
518 | } | ||
519 | fmt_segments_raw(target, &mut buf); | ||
520 | edit.insert(offset, buf); | ||
521 | } else { | ||
522 | } | ||
523 | } | ||
524 | |||
525 | fn make_assist_add_nested_import( | ||
526 | path: &ast::Path, | ||
527 | first_segment_to_split: &Option<ast::PathSegment>, | ||
528 | target: &[SmolStr], | ||
529 | add_self: bool, | ||
530 | edit: &mut TextEditBuilder, | ||
531 | ) { | ||
532 | let use_tree = path.syntax().ancestors().find_map(ast::UseTree::cast); | ||
533 | if let Some(use_tree) = use_tree { | ||
534 | let (start, add_colon_colon) = if let Some(first_segment_to_split) = first_segment_to_split | ||
535 | { | ||
536 | (first_segment_to_split.syntax().text_range().start(), false) | ||
537 | } else { | ||
538 | (use_tree.syntax().text_range().end(), true) | ||
539 | }; | ||
540 | let end = use_tree.syntax().text_range().end(); | ||
541 | |||
542 | let mut buf = String::new(); | ||
543 | if add_colon_colon { | ||
544 | buf.push_str("::"); | ||
545 | } | ||
546 | buf.push_str("{"); | ||
547 | if add_self { | ||
548 | buf.push_str("self, "); | ||
549 | } | ||
550 | fmt_segments_raw(target, &mut buf); | ||
551 | if !target.is_empty() { | ||
552 | buf.push_str(", "); | ||
553 | } | ||
554 | edit.insert(start, buf); | ||
555 | edit.insert(end, "}".to_string()); | ||
556 | } | ||
557 | } | ||
558 | |||
559 | fn replace_with_use( | ||
560 | container: &SyntaxNode, | ||
561 | path: &ast::Path, | ||
562 | target: &[SmolStr], | ||
563 | edit: &mut TextEditBuilder, | ||
564 | ) { | ||
565 | let action = best_action_for_target(container.clone(), path.syntax().clone(), target); | ||
566 | make_assist(&action, target, edit); | ||
567 | if let Some(last) = path.segment() { | ||
568 | // Here we are assuming the assist will provide a correct use statement | ||
569 | // so we can delete the path qualifier | ||
570 | edit.delete(TextRange::from_to( | ||
571 | path.syntax().text_range().start(), | ||
572 | last.syntax().text_range().start(), | ||
573 | )); | ||
574 | } | ||
575 | } | ||
576 | |||
577 | fn collect_hir_path_segments(path: &hir::Path) -> Option<Vec<SmolStr>> { | ||
578 | let mut ps = Vec::<SmolStr>::with_capacity(10); | ||
579 | match path.kind() { | ||
580 | hir::PathKind::Abs => ps.push("".into()), | ||
581 | hir::PathKind::Crate => ps.push("crate".into()), | ||
582 | hir::PathKind::Plain => {} | ||
583 | hir::PathKind::Super(0) => ps.push("self".into()), | ||
584 | hir::PathKind::Super(lvl) => { | ||
585 | let mut chain = "super".to_string(); | ||
586 | for _ in 0..*lvl { | ||
587 | chain += "::super"; | ||
588 | } | ||
589 | ps.push(chain.into()); | ||
590 | } | ||
591 | hir::PathKind::DollarCrate(_) => return None, | ||
592 | } | ||
593 | ps.extend(path.segments().iter().map(|it| it.name.to_string().into())); | ||
594 | Some(ps) | ||
595 | } | ||
596 | |||
597 | #[cfg(test)] | ||
598 | mod tests { | ||
599 | use crate::helpers::{check_assist, check_assist_not_applicable}; | ||
600 | |||
601 | use super::*; | ||
602 | |||
603 | #[test] | ||
604 | fn test_replace_add_use_no_anchor() { | ||
605 | check_assist( | ||
606 | replace_qualified_name_with_use, | ||
607 | " | ||
608 | std::fmt::Debug<|> | ||
609 | ", | ||
610 | " | ||
611 | use std::fmt::Debug; | ||
612 | |||
613 | Debug<|> | ||
614 | ", | ||
615 | ); | ||
616 | } | ||
617 | #[test] | ||
618 | fn test_replace_add_use_no_anchor_with_item_below() { | ||
619 | check_assist( | ||
620 | replace_qualified_name_with_use, | ||
621 | " | ||
622 | std::fmt::Debug<|> | ||
623 | |||
624 | fn main() { | ||
625 | } | ||
626 | ", | ||
627 | " | ||
628 | use std::fmt::Debug; | ||
629 | |||
630 | Debug<|> | ||
631 | |||
632 | fn main() { | ||
633 | } | ||
634 | ", | ||
635 | ); | ||
636 | } | ||
637 | |||
638 | #[test] | ||
639 | fn test_replace_add_use_no_anchor_with_item_above() { | ||
640 | check_assist( | ||
641 | replace_qualified_name_with_use, | ||
642 | " | ||
643 | fn main() { | ||
644 | } | ||
645 | |||
646 | std::fmt::Debug<|> | ||
647 | ", | ||
648 | " | ||
649 | use std::fmt::Debug; | ||
650 | |||
651 | fn main() { | ||
652 | } | ||
653 | |||
654 | Debug<|> | ||
655 | ", | ||
656 | ); | ||
657 | } | ||
658 | |||
659 | #[test] | ||
660 | fn test_replace_add_use_no_anchor_2seg() { | ||
661 | check_assist( | ||
662 | replace_qualified_name_with_use, | ||
663 | " | ||
664 | std::fmt<|>::Debug | ||
665 | ", | ||
666 | " | ||
667 | use std::fmt; | ||
668 | |||
669 | fmt<|>::Debug | ||
670 | ", | ||
671 | ); | ||
672 | } | ||
673 | |||
674 | #[test] | ||
675 | fn test_replace_add_use() { | ||
676 | check_assist( | ||
677 | replace_qualified_name_with_use, | ||
678 | " | ||
679 | use stdx; | ||
680 | |||
681 | impl std::fmt::Debug<|> for Foo { | ||
682 | } | ||
683 | ", | ||
684 | " | ||
685 | use stdx; | ||
686 | use std::fmt::Debug; | ||
687 | |||
688 | impl Debug<|> for Foo { | ||
689 | } | ||
690 | ", | ||
691 | ); | ||
692 | } | ||
693 | |||
694 | #[test] | ||
695 | fn test_replace_file_use_other_anchor() { | ||
696 | check_assist( | ||
697 | replace_qualified_name_with_use, | ||
698 | " | ||
699 | impl std::fmt::Debug<|> for Foo { | ||
700 | } | ||
701 | ", | ||
702 | " | ||
703 | use std::fmt::Debug; | ||
704 | |||
705 | impl Debug<|> for Foo { | ||
706 | } | ||
707 | ", | ||
708 | ); | ||
709 | } | ||
710 | |||
711 | #[test] | ||
712 | fn test_replace_add_use_other_anchor_indent() { | ||
713 | check_assist( | ||
714 | replace_qualified_name_with_use, | ||
715 | " | ||
716 | impl std::fmt::Debug<|> for Foo { | ||
717 | } | ||
718 | ", | ||
719 | " | ||
720 | use std::fmt::Debug; | ||
721 | |||
722 | impl Debug<|> for Foo { | ||
723 | } | ||
724 | ", | ||
725 | ); | ||
726 | } | ||
727 | |||
728 | #[test] | ||
729 | fn test_replace_split_different() { | ||
730 | check_assist( | ||
731 | replace_qualified_name_with_use, | ||
732 | " | ||
733 | use std::fmt; | ||
734 | |||
735 | impl std::io<|> for Foo { | ||
736 | } | ||
737 | ", | ||
738 | " | ||
739 | use std::{io, fmt}; | ||
740 | |||
741 | impl io<|> for Foo { | ||
742 | } | ||
743 | ", | ||
744 | ); | ||
745 | } | ||
746 | |||
747 | #[test] | ||
748 | fn test_replace_split_self_for_use() { | ||
749 | check_assist( | ||
750 | replace_qualified_name_with_use, | ||
751 | " | ||
752 | use std::fmt; | ||
753 | |||
754 | impl std::fmt::Debug<|> for Foo { | ||
755 | } | ||
756 | ", | ||
757 | " | ||
758 | use std::fmt::{self, Debug, }; | ||
759 | |||
760 | impl Debug<|> for Foo { | ||
761 | } | ||
762 | ", | ||
763 | ); | ||
764 | } | ||
765 | |||
766 | #[test] | ||
767 | fn test_replace_split_self_for_target() { | ||
768 | check_assist( | ||
769 | replace_qualified_name_with_use, | ||
770 | " | ||
771 | use std::fmt::Debug; | ||
772 | |||
773 | impl std::fmt<|> for Foo { | ||
774 | } | ||
775 | ", | ||
776 | " | ||
777 | use std::fmt::{self, Debug}; | ||
778 | |||
779 | impl fmt<|> for Foo { | ||
780 | } | ||
781 | ", | ||
782 | ); | ||
783 | } | ||
784 | |||
785 | #[test] | ||
786 | fn test_replace_add_to_nested_self_nested() { | ||
787 | check_assist( | ||
788 | replace_qualified_name_with_use, | ||
789 | " | ||
790 | use std::fmt::{Debug, nested::{Display}}; | ||
791 | |||
792 | impl std::fmt::nested<|> for Foo { | ||
793 | } | ||
794 | ", | ||
795 | " | ||
796 | use std::fmt::{Debug, nested::{Display, self}}; | ||
797 | |||
798 | impl nested<|> for Foo { | ||
799 | } | ||
800 | ", | ||
801 | ); | ||
802 | } | ||
803 | |||
804 | #[test] | ||
805 | fn test_replace_add_to_nested_self_already_included() { | ||
806 | check_assist( | ||
807 | replace_qualified_name_with_use, | ||
808 | " | ||
809 | use std::fmt::{Debug, nested::{self, Display}}; | ||
810 | |||
811 | impl std::fmt::nested<|> for Foo { | ||
812 | } | ||
813 | ", | ||
814 | " | ||
815 | use std::fmt::{Debug, nested::{self, Display}}; | ||
816 | |||
817 | impl nested<|> for Foo { | ||
818 | } | ||
819 | ", | ||
820 | ); | ||
821 | } | ||
822 | |||
823 | #[test] | ||
824 | fn test_replace_add_to_nested_nested() { | ||
825 | check_assist( | ||
826 | replace_qualified_name_with_use, | ||
827 | " | ||
828 | use std::fmt::{Debug, nested::{Display}}; | ||
829 | |||
830 | impl std::fmt::nested::Debug<|> for Foo { | ||
831 | } | ||
832 | ", | ||
833 | " | ||
834 | use std::fmt::{Debug, nested::{Display, Debug}}; | ||
835 | |||
836 | impl Debug<|> for Foo { | ||
837 | } | ||
838 | ", | ||
839 | ); | ||
840 | } | ||
841 | |||
842 | #[test] | ||
843 | fn test_replace_split_common_target_longer() { | ||
844 | check_assist( | ||
845 | replace_qualified_name_with_use, | ||
846 | " | ||
847 | use std::fmt::Debug; | ||
848 | |||
849 | impl std::fmt::nested::Display<|> for Foo { | ||
850 | } | ||
851 | ", | ||
852 | " | ||
853 | use std::fmt::{nested::Display, Debug}; | ||
854 | |||
855 | impl Display<|> for Foo { | ||
856 | } | ||
857 | ", | ||
858 | ); | ||
859 | } | ||
860 | |||
861 | #[test] | ||
862 | fn test_replace_split_common_use_longer() { | ||
863 | check_assist( | ||
864 | replace_qualified_name_with_use, | ||
865 | " | ||
866 | use std::fmt::nested::Debug; | ||
867 | |||
868 | impl std::fmt::Display<|> for Foo { | ||
869 | } | ||
870 | ", | ||
871 | " | ||
872 | use std::fmt::{Display, nested::Debug}; | ||
873 | |||
874 | impl Display<|> for Foo { | ||
875 | } | ||
876 | ", | ||
877 | ); | ||
878 | } | ||
879 | |||
880 | #[test] | ||
881 | fn test_replace_use_nested_import() { | ||
882 | check_assist( | ||
883 | replace_qualified_name_with_use, | ||
884 | " | ||
885 | use crate::{ | ||
886 | ty::{Substs, Ty}, | ||
887 | AssocItem, | ||
888 | }; | ||
889 | |||
890 | fn foo() { crate::ty::lower<|>::trait_env() } | ||
891 | ", | ||
892 | " | ||
893 | use crate::{ | ||
894 | ty::{Substs, Ty, lower}, | ||
895 | AssocItem, | ||
896 | }; | ||
897 | |||
898 | fn foo() { lower<|>::trait_env() } | ||
899 | ", | ||
900 | ); | ||
901 | } | ||
902 | |||
903 | #[test] | ||
904 | fn test_replace_alias() { | ||
905 | check_assist( | ||
906 | replace_qualified_name_with_use, | ||
907 | " | ||
908 | use std::fmt as foo; | ||
909 | |||
910 | impl foo::Debug<|> for Foo { | ||
911 | } | ||
912 | ", | ||
913 | " | ||
914 | use std::fmt as foo; | ||
915 | |||
916 | impl Debug<|> for Foo { | ||
917 | } | ||
918 | ", | ||
919 | ); | ||
920 | } | ||
921 | |||
922 | #[test] | ||
923 | fn test_replace_not_applicable_one_segment() { | ||
924 | check_assist_not_applicable( | ||
925 | replace_qualified_name_with_use, | ||
926 | " | ||
927 | impl foo<|> for Foo { | ||
928 | } | ||
929 | ", | ||
930 | ); | ||
931 | } | ||
932 | |||
933 | #[test] | ||
934 | fn test_replace_not_applicable_in_use() { | ||
935 | check_assist_not_applicable( | ||
936 | replace_qualified_name_with_use, | ||
937 | " | ||
938 | use std::fmt<|>; | ||
939 | ", | ||
940 | ); | ||
941 | } | ||
942 | |||
943 | #[test] | ||
944 | fn test_replace_add_use_no_anchor_in_mod_mod() { | ||
945 | check_assist( | ||
946 | replace_qualified_name_with_use, | ||
947 | " | ||
948 | mod foo { | ||
949 | mod bar { | ||
950 | std::fmt::Debug<|> | ||
951 | } | ||
952 | } | ||
953 | ", | ||
954 | " | ||
955 | mod foo { | ||
956 | mod bar { | ||
957 | use std::fmt::Debug; | ||
958 | |||
959 | Debug<|> | ||
960 | } | ||
961 | } | ||
962 | ", | ||
963 | ); | ||
964 | } | ||
965 | } | ||