aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/handlers
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists/src/handlers')
-rw-r--r--crates/ra_assists/src/handlers/auto_import.rs4
-rw-r--r--crates/ra_assists/src/handlers/replace_qualified_name_with_use.rs555
2 files changed, 16 insertions, 543 deletions
diff --git a/crates/ra_assists/src/handlers/auto_import.rs b/crates/ra_assists/src/handlers/auto_import.rs
index edf0cf6d0..c8bf181f9 100644
--- a/crates/ra_assists/src/handlers/auto_import.rs
+++ b/crates/ra_assists/src/handlers/auto_import.rs
@@ -1,6 +1,7 @@
1use crate::{ 1use crate::{
2 assist_ctx::{Assist, AssistCtx}, 2 assist_ctx::{Assist, AssistCtx},
3 insert_use_statement, AssistId, 3 utils::insert_use_statement,
4 AssistId,
4}; 5};
5use hir::{ 6use hir::{
6 AsAssocItem, AssocItemContainer, ModPath, Module, ModuleDef, PathResolution, Semantics, Trait, 7 AsAssocItem, AssocItemContainer, ModPath, Module, ModuleDef, PathResolution, Semantics, Trait,
@@ -52,7 +53,6 @@ pub(crate) fn auto_import(ctx: AssistCtx) -> Option<Assist> {
52 edit.target(auto_import_assets.syntax_under_caret.text_range()); 53 edit.target(auto_import_assets.syntax_under_caret.text_range());
53 insert_use_statement( 54 insert_use_statement(
54 &auto_import_assets.syntax_under_caret, 55 &auto_import_assets.syntax_under_caret,
55 &auto_import_assets.syntax_under_caret,
56 &import, 56 &import,
57 edit.text_edit_builder(), 57 edit.text_edit_builder(),
58 ); 58 );
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
index eac452413..94f5d6c50 100644
--- a/crates/ra_assists/src/handlers/replace_qualified_name_with_use.rs
+++ b/crates/ra_assists/src/handlers/replace_qualified_name_with_use.rs
@@ -1,42 +1,12 @@
1use hir::{self, ModPath}; 1use hir;
2use ra_syntax::{ 2use ra_syntax::{ast, AstNode, SmolStr, TextRange};
3 ast::{self, NameOwner},
4 AstNode, Direction, SmolStr,
5 SyntaxKind::{PATH, PATH_SEGMENT},
6 SyntaxNode, TextRange, T,
7};
8use ra_text_edit::TextEditBuilder;
9 3
10use crate::{ 4use crate::{
11 assist_ctx::{Assist, AssistCtx}, 5 assist_ctx::{Assist, AssistCtx},
6 utils::insert_use_statement,
12 AssistId, 7 AssistId,
13}; 8};
14 9
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.
18pub 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 10// Assist: replace_qualified_name_with_use
41// 11//
42// Adds a use statement for a given fully-qualified name. 12// Adds a use statement for a given fully-qualified name.
@@ -63,522 +33,25 @@ pub(crate) fn replace_qualified_name_with_use(ctx: AssistCtx) -> Option<Assist>
63 return None; 33 return None;
64 } 34 }
65 35
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( 36 ctx.add_assist(
76 AssistId("replace_qualified_name_with_use"), 37 AssistId("replace_qualified_name_with_use"),
77 "Replace qualified path with use", 38 "Replace qualified path with use",
78 |edit| { 39 |edit| {
79 replace_with_use(&position, &path, &segments, edit.text_edit_builder()); 40 let path_to_import = hir_path.mod_path().clone();
41 insert_use_statement(path.syntax(), &path_to_import, edit.text_edit_builder());
42
43 if let Some(last) = path.segment() {
44 // Here we are assuming the assist will provide a correct use statement
45 // so we can delete the path qualifier
46 edit.delete(TextRange::from_to(
47 path.syntax().text_range().start(),
48 last.syntax().text_range().start(),
49 ));
50 }
80 }, 51 },
81 ) 52 )
82} 53}
83 54
84fn 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
114fn 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.
126fn 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
130fn 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
144fn compare_path_segment_with_name(a: &SmolStr, b: &ast::Name) -> bool {
145 a == b.text()
146}
147
148#[derive(Clone, Debug)]
149enum 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
176impl 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.
241fn 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
406fn 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 let add_after_anchor = anchor
435 .clone()
436 .and_then(ast::Attr::cast)
437 .map(|attr| attr.kind() == ast::AttrKind::Inner)
438 .unwrap_or(false);
439 ImportAction::add_new_use(anchor, add_after_anchor)
440 }
441 }
442}
443
444fn make_assist(action: &ImportAction, target: &[SmolStr], edit: &mut TextEditBuilder) {
445 match action {
446 ImportAction::AddNewUse { anchor, add_after_anchor } => {
447 make_assist_add_new_use(anchor, *add_after_anchor, target, edit)
448 }
449 ImportAction::AddInTreeList { common_segments, tree_list, add_self } => {
450 // We know that the fist n segments already exists in the use statement we want
451 // to modify, so we want to add only the last target.len() - n segments.
452 let segments_to_add = target.split_at(*common_segments).1;
453 make_assist_add_in_tree_list(tree_list, segments_to_add, *add_self, edit)
454 }
455 ImportAction::AddNestedImport {
456 common_segments,
457 path_to_split,
458 first_segment_to_split,
459 add_self,
460 } => {
461 let segments_to_add = target.split_at(*common_segments).1;
462 make_assist_add_nested_import(
463 path_to_split,
464 first_segment_to_split,
465 segments_to_add,
466 *add_self,
467 edit,
468 )
469 }
470 _ => {}
471 }
472}
473
474fn make_assist_add_new_use(
475 anchor: &Option<SyntaxNode>,
476 after: bool,
477 target: &[SmolStr],
478 edit: &mut TextEditBuilder,
479) {
480 if let Some(anchor) = anchor {
481 let indent = ra_fmt::leading_indent(anchor);
482 let mut buf = String::new();
483 if after {
484 buf.push_str("\n");
485 if let Some(spaces) = &indent {
486 buf.push_str(spaces);
487 }
488 }
489 buf.push_str("use ");
490 fmt_segments_raw(target, &mut buf);
491 buf.push_str(";");
492 if !after {
493 buf.push_str("\n\n");
494 if let Some(spaces) = &indent {
495 buf.push_str(&spaces);
496 }
497 }
498 let position = if after { anchor.text_range().end() } else { anchor.text_range().start() };
499 edit.insert(position, buf);
500 }
501}
502
503fn make_assist_add_in_tree_list(
504 tree_list: &ast::UseTreeList,
505 target: &[SmolStr],
506 add_self: bool,
507 edit: &mut TextEditBuilder,
508) {
509 let last = tree_list.use_trees().last();
510 if let Some(last) = last {
511 let mut buf = String::new();
512 let comma = last.syntax().siblings(Direction::Next).find(|n| n.kind() == T![,]);
513 let offset = if let Some(comma) = comma {
514 comma.text_range().end()
515 } else {
516 buf.push_str(",");
517 last.syntax().text_range().end()
518 };
519 if add_self {
520 buf.push_str(" self")
521 } else {
522 buf.push_str(" ");
523 }
524 fmt_segments_raw(target, &mut buf);
525 edit.insert(offset, buf);
526 } else {
527 }
528}
529
530fn make_assist_add_nested_import(
531 path: &ast::Path,
532 first_segment_to_split: &Option<ast::PathSegment>,
533 target: &[SmolStr],
534 add_self: bool,
535 edit: &mut TextEditBuilder,
536) {
537 let use_tree = path.syntax().ancestors().find_map(ast::UseTree::cast);
538 if let Some(use_tree) = use_tree {
539 let (start, add_colon_colon) = if let Some(first_segment_to_split) = first_segment_to_split
540 {
541 (first_segment_to_split.syntax().text_range().start(), false)
542 } else {
543 (use_tree.syntax().text_range().end(), true)
544 };
545 let end = use_tree.syntax().text_range().end();
546
547 let mut buf = String::new();
548 if add_colon_colon {
549 buf.push_str("::");
550 }
551 buf.push_str("{");
552 if add_self {
553 buf.push_str("self, ");
554 }
555 fmt_segments_raw(target, &mut buf);
556 if !target.is_empty() {
557 buf.push_str(", ");
558 }
559 edit.insert(start, buf);
560 edit.insert(end, "}".to_string());
561 }
562}
563
564fn replace_with_use(
565 container: &SyntaxNode,
566 path: &ast::Path,
567 target: &[SmolStr],
568 edit: &mut TextEditBuilder,
569) {
570 let action = best_action_for_target(container.clone(), path.syntax().clone(), target);
571 make_assist(&action, target, edit);
572 if let Some(last) = path.segment() {
573 // Here we are assuming the assist will provide a correct use statement
574 // so we can delete the path qualifier
575 edit.delete(TextRange::from_to(
576 path.syntax().text_range().start(),
577 last.syntax().text_range().start(),
578 ));
579 }
580}
581
582fn collect_hir_path_segments(path: &hir::Path) -> Option<Vec<SmolStr>> { 55fn collect_hir_path_segments(path: &hir::Path) -> Option<Vec<SmolStr>> {
583 let mut ps = Vec::<SmolStr>::with_capacity(10); 56 let mut ps = Vec::<SmolStr>::with_capacity(10);
584 match path.kind() { 57 match path.kind() {