aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/utils/insert_use.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists/src/utils/insert_use.rs')
-rw-r--r--crates/ra_assists/src/utils/insert_use.rs526
1 files changed, 0 insertions, 526 deletions
diff --git a/crates/ra_assists/src/utils/insert_use.rs b/crates/ra_assists/src/utils/insert_use.rs
deleted file mode 100644
index 32780fceb..000000000
--- a/crates/ra_assists/src/utils/insert_use.rs
+++ /dev/null
@@ -1,526 +0,0 @@
1//! Handle syntactic aspects of inserting a new `use`.
2// FIXME: rewrite according to the plan, outlined in
3// https://github.com/rust-analyzer/rust-analyzer/issues/3301#issuecomment-592931553
4
5use hir::{self, ModPath};
6use ra_syntax::{
7 ast::{self, NameOwner, VisibilityOwner},
8 AstNode, Direction, SmolStr,
9 SyntaxKind::{PATH, PATH_SEGMENT},
10 SyntaxNode, T,
11};
12use ra_text_edit::TextEditBuilder;
13
14use crate::assist_context::AssistContext;
15use either::Either;
16
17/// Determines the containing syntax node in which to insert a `use` statement affecting `position`.
18pub(crate) fn find_insert_use_container(
19 position: &SyntaxNode,
20 ctx: &AssistContext,
21) -> Option<Either<ast::ItemList, ast::SourceFile>> {
22 ctx.sema.ancestors_with_macros(position.clone()).find_map(|n| {
23 if let Some(module) = ast::Module::cast(n.clone()) {
24 return module.item_list().map(|it| Either::Left(it));
25 }
26 Some(Either::Right(ast::SourceFile::cast(n)?))
27 })
28}
29
30/// Creates and inserts a use statement for the given path to import.
31/// The use statement is inserted in the scope most appropriate to the
32/// the cursor position given, additionally merged with the existing use imports.
33pub(crate) fn insert_use_statement(
34 // Ideally the position of the cursor, used to
35 position: &SyntaxNode,
36 path_to_import: &ModPath,
37 ctx: &AssistContext,
38 builder: &mut TextEditBuilder,
39) {
40 let target = path_to_import.to_string().split("::").map(SmolStr::new).collect::<Vec<_>>();
41 let container = find_insert_use_container(position, ctx);
42
43 if let Some(container) = container {
44 let syntax = container.either(|l| l.syntax().clone(), |r| r.syntax().clone());
45 let action = best_action_for_target(syntax, position.clone(), &target);
46 make_assist(&action, &target, builder);
47 }
48}
49
50fn collect_path_segments_raw(
51 segments: &mut Vec<ast::PathSegment>,
52 mut path: ast::Path,
53) -> Option<usize> {
54 let oldlen = segments.len();
55 loop {
56 let mut children = path.syntax().children_with_tokens();
57 let (first, second, third) = (
58 children.next().map(|n| (n.clone(), n.kind())),
59 children.next().map(|n| (n.clone(), n.kind())),
60 children.next().map(|n| (n.clone(), n.kind())),
61 );
62 match (first, second, third) {
63 (Some((subpath, PATH)), Some((_, T![::])), Some((segment, PATH_SEGMENT))) => {
64 path = ast::Path::cast(subpath.as_node()?.clone())?;
65 segments.push(ast::PathSegment::cast(segment.as_node()?.clone())?);
66 }
67 (Some((segment, PATH_SEGMENT)), _, _) => {
68 segments.push(ast::PathSegment::cast(segment.as_node()?.clone())?);
69 break;
70 }
71 (_, _, _) => return None,
72 }
73 }
74 // We need to reverse only the new added segments
75 let only_new_segments = segments.split_at_mut(oldlen).1;
76 only_new_segments.reverse();
77 Some(segments.len() - oldlen)
78}
79
80fn fmt_segments_raw(segments: &[SmolStr], buf: &mut String) {
81 let mut iter = segments.iter();
82 if let Some(s) = iter.next() {
83 buf.push_str(s);
84 }
85 for s in iter {
86 buf.push_str("::");
87 buf.push_str(s);
88 }
89}
90
91/// Returns the number of common segments.
92fn compare_path_segments(left: &[SmolStr], right: &[ast::PathSegment]) -> usize {
93 left.iter().zip(right).take_while(|(l, r)| compare_path_segment(l, r)).count()
94}
95
96fn compare_path_segment(a: &SmolStr, b: &ast::PathSegment) -> bool {
97 if let Some(kb) = b.kind() {
98 match kb {
99 ast::PathSegmentKind::Name(nameref_b) => a == nameref_b.text(),
100 ast::PathSegmentKind::SelfKw => a == "self",
101 ast::PathSegmentKind::SuperKw => a == "super",
102 ast::PathSegmentKind::CrateKw => a == "crate",
103 ast::PathSegmentKind::Type { .. } => false, // not allowed in imports
104 }
105 } else {
106 false
107 }
108}
109
110fn compare_path_segment_with_name(a: &SmolStr, b: &ast::Name) -> bool {
111 a == b.text()
112}
113
114#[derive(Clone, Debug)]
115enum ImportAction {
116 Nothing,
117 // Add a brand new use statement.
118 AddNewUse {
119 anchor: Option<SyntaxNode>, // anchor node
120 add_after_anchor: bool,
121 },
122
123 // To split an existing use statement creating a nested import.
124 AddNestedImport {
125 // how may segments matched with the target path
126 common_segments: usize,
127 path_to_split: ast::Path,
128 // the first segment of path_to_split we want to add into the new nested list
129 first_segment_to_split: Option<ast::PathSegment>,
130 // Wether to add 'self' in addition to the target path
131 add_self: bool,
132 },
133 // To add the target path to an existing nested import tree list.
134 AddInTreeList {
135 common_segments: usize,
136 // The UseTreeList where to add the target path
137 tree_list: ast::UseTreeList,
138 add_self: bool,
139 },
140}
141
142impl ImportAction {
143 fn add_new_use(anchor: Option<SyntaxNode>, add_after_anchor: bool) -> Self {
144 ImportAction::AddNewUse { anchor, add_after_anchor }
145 }
146
147 fn add_nested_import(
148 common_segments: usize,
149 path_to_split: ast::Path,
150 first_segment_to_split: Option<ast::PathSegment>,
151 add_self: bool,
152 ) -> Self {
153 ImportAction::AddNestedImport {
154 common_segments,
155 path_to_split,
156 first_segment_to_split,
157 add_self,
158 }
159 }
160
161 fn add_in_tree_list(
162 common_segments: usize,
163 tree_list: ast::UseTreeList,
164 add_self: bool,
165 ) -> Self {
166 ImportAction::AddInTreeList { common_segments, tree_list, add_self }
167 }
168
169 fn better(left: ImportAction, right: ImportAction) -> ImportAction {
170 if left.is_better(&right) {
171 left
172 } else {
173 right
174 }
175 }
176
177 fn is_better(&self, other: &ImportAction) -> bool {
178 match (self, other) {
179 (ImportAction::Nothing, _) => true,
180 (ImportAction::AddInTreeList { .. }, ImportAction::Nothing) => false,
181 (
182 ImportAction::AddNestedImport { common_segments: n, .. },
183 ImportAction::AddInTreeList { common_segments: m, .. },
184 )
185 | (
186 ImportAction::AddInTreeList { common_segments: n, .. },
187 ImportAction::AddNestedImport { common_segments: m, .. },
188 )
189 | (
190 ImportAction::AddInTreeList { common_segments: n, .. },
191 ImportAction::AddInTreeList { common_segments: m, .. },
192 )
193 | (
194 ImportAction::AddNestedImport { common_segments: n, .. },
195 ImportAction::AddNestedImport { common_segments: m, .. },
196 ) => n > m,
197 (ImportAction::AddInTreeList { .. }, _) => true,
198 (ImportAction::AddNestedImport { .. }, ImportAction::Nothing) => false,
199 (ImportAction::AddNestedImport { .. }, _) => true,
200 (ImportAction::AddNewUse { .. }, _) => false,
201 }
202 }
203}
204
205// Find out the best ImportAction to import target path against current_use_tree.
206// If current_use_tree has a nested import the function gets called recursively on every UseTree inside a UseTreeList.
207fn walk_use_tree_for_best_action(
208 current_path_segments: &mut Vec<ast::PathSegment>, // buffer containing path segments
209 current_parent_use_tree_list: Option<ast::UseTreeList>, // will be Some value if we are in a nested import
210 current_use_tree: ast::UseTree, // the use tree we are currently examinating
211 target: &[SmolStr], // the path we want to import
212) -> ImportAction {
213 // We save the number of segments in the buffer so we can restore the correct segments
214 // before returning. Recursive call will add segments so we need to delete them.
215 let prev_len = current_path_segments.len();
216
217 let tree_list = current_use_tree.use_tree_list();
218 let alias = current_use_tree.rename();
219
220 let path = match current_use_tree.path() {
221 Some(path) => path,
222 None => {
223 // If the use item don't have a path, it means it's broken (syntax error)
224 return ImportAction::add_new_use(
225 current_use_tree
226 .syntax()
227 .ancestors()
228 .find_map(ast::Use::cast)
229 .map(|it| it.syntax().clone()),
230 true,
231 );
232 }
233 };
234
235 // This can happen only if current_use_tree is a direct child of a UseItem
236 if let Some(name) = alias.and_then(|it| it.name()) {
237 if compare_path_segment_with_name(&target[0], &name) {
238 return ImportAction::Nothing;
239 }
240 }
241
242 collect_path_segments_raw(current_path_segments, path.clone());
243
244 // We compare only the new segments added in the line just above.
245 // The first prev_len segments were already compared in 'parent' recursive calls.
246 let left = target.split_at(prev_len).1;
247 let right = current_path_segments.split_at(prev_len).1;
248 let common = compare_path_segments(left, &right);
249 let mut action = match common {
250 0 => ImportAction::add_new_use(
251 // e.g: target is std::fmt and we can have
252 // use foo::bar
253 // We add a brand new use statement
254 current_use_tree
255 .syntax()
256 .ancestors()
257 .find_map(ast::Use::cast)
258 .map(|it| it.syntax().clone()),
259 true,
260 ),
261 common if common == left.len() && left.len() == right.len() => {
262 // e.g: target is std::fmt and we can have
263 // 1- use std::fmt;
264 // 2- use std::fmt::{ ... }
265 if let Some(list) = tree_list {
266 // In case 2 we need to add self to the nested list
267 // unless it's already there
268 let has_self = list.use_trees().map(|it| it.path()).any(|p| {
269 p.and_then(|it| it.segment())
270 .and_then(|it| it.kind())
271 .filter(|k| *k == ast::PathSegmentKind::SelfKw)
272 .is_some()
273 });
274
275 if has_self {
276 ImportAction::Nothing
277 } else {
278 ImportAction::add_in_tree_list(current_path_segments.len(), list, true)
279 }
280 } else {
281 // Case 1
282 ImportAction::Nothing
283 }
284 }
285 common if common != left.len() && left.len() == right.len() => {
286 // e.g: target is std::fmt and we have
287 // use std::io;
288 // We need to split.
289 let segments_to_split = current_path_segments.split_at(prev_len + common).1;
290 ImportAction::add_nested_import(
291 prev_len + common,
292 path,
293 Some(segments_to_split[0].clone()),
294 false,
295 )
296 }
297 common if common == right.len() && left.len() > right.len() => {
298 // e.g: target is std::fmt and we can have
299 // 1- use std;
300 // 2- use std::{ ... };
301
302 // fallback action
303 let mut better_action = ImportAction::add_new_use(
304 current_use_tree
305 .syntax()
306 .ancestors()
307 .find_map(ast::Use::cast)
308 .map(|it| it.syntax().clone()),
309 true,
310 );
311 if let Some(list) = tree_list {
312 // Case 2, check recursively if the path is already imported in the nested list
313 for u in list.use_trees() {
314 let child_action = walk_use_tree_for_best_action(
315 current_path_segments,
316 Some(list.clone()),
317 u,
318 target,
319 );
320 if child_action.is_better(&better_action) {
321 better_action = child_action;
322 if let ImportAction::Nothing = better_action {
323 return better_action;
324 }
325 }
326 }
327 } else {
328 // Case 1, split adding self
329 better_action = ImportAction::add_nested_import(prev_len + common, path, None, true)
330 }
331 better_action
332 }
333 common if common == left.len() && left.len() < right.len() => {
334 // e.g: target is std::fmt and we can have
335 // use std::fmt::Debug;
336 let segments_to_split = current_path_segments.split_at(prev_len + common).1;
337 ImportAction::add_nested_import(
338 prev_len + common,
339 path,
340 Some(segments_to_split[0].clone()),
341 true,
342 )
343 }
344 common if common < left.len() && common < right.len() => {
345 // e.g: target is std::fmt::nested::Debug
346 // use std::fmt::Display
347 let segments_to_split = current_path_segments.split_at(prev_len + common).1;
348 ImportAction::add_nested_import(
349 prev_len + common,
350 path,
351 Some(segments_to_split[0].clone()),
352 false,
353 )
354 }
355 _ => unreachable!(),
356 };
357
358 // If we are inside a UseTreeList adding a use statement become adding to the existing
359 // tree list.
360 action = match (current_parent_use_tree_list, action.clone()) {
361 (Some(use_tree_list), ImportAction::AddNewUse { .. }) => {
362 ImportAction::add_in_tree_list(prev_len, use_tree_list, false)
363 }
364 (_, _) => action,
365 };
366
367 // We remove the segments added
368 current_path_segments.truncate(prev_len);
369 action
370}
371
372fn best_action_for_target(
373 container: SyntaxNode,
374 anchor: SyntaxNode,
375 target: &[SmolStr],
376) -> ImportAction {
377 let mut storage = Vec::with_capacity(16); // this should be the only allocation
378 let best_action = container
379 .children()
380 .filter_map(ast::Use::cast)
381 .filter(|u| u.visibility().is_none())
382 .filter_map(|it| it.use_tree())
383 .map(|u| walk_use_tree_for_best_action(&mut storage, None, u, target))
384 .fold(None, |best, a| match best {
385 Some(best) => Some(ImportAction::better(best, a)),
386 None => Some(a),
387 });
388
389 match best_action {
390 Some(action) => action,
391 None => {
392 // We have no action and no UseItem was found in container so we find
393 // another item and we use it as anchor.
394 // If there are no items above, we choose the target path itself as anchor.
395 // todo: we should include even whitespace blocks as anchor candidates
396 let anchor = container.children().next().or_else(|| Some(anchor));
397
398 let add_after_anchor = anchor
399 .clone()
400 .and_then(ast::Attr::cast)
401 .map(|attr| attr.kind() == ast::AttrKind::Inner)
402 .unwrap_or(false);
403 ImportAction::add_new_use(anchor, add_after_anchor)
404 }
405 }
406}
407
408fn make_assist(action: &ImportAction, target: &[SmolStr], edit: &mut TextEditBuilder) {
409 match action {
410 ImportAction::AddNewUse { anchor, add_after_anchor } => {
411 make_assist_add_new_use(anchor, *add_after_anchor, target, edit)
412 }
413 ImportAction::AddInTreeList { common_segments, tree_list, add_self } => {
414 // We know that the fist n segments already exists in the use statement we want
415 // to modify, so we want to add only the last target.len() - n segments.
416 let segments_to_add = target.split_at(*common_segments).1;
417 make_assist_add_in_tree_list(tree_list, segments_to_add, *add_self, edit)
418 }
419 ImportAction::AddNestedImport {
420 common_segments,
421 path_to_split,
422 first_segment_to_split,
423 add_self,
424 } => {
425 let segments_to_add = target.split_at(*common_segments).1;
426 make_assist_add_nested_import(
427 path_to_split,
428 first_segment_to_split,
429 segments_to_add,
430 *add_self,
431 edit,
432 )
433 }
434 _ => {}
435 }
436}
437
438fn make_assist_add_new_use(
439 anchor: &Option<SyntaxNode>,
440 after: bool,
441 target: &[SmolStr],
442 edit: &mut TextEditBuilder,
443) {
444 if let Some(anchor) = anchor {
445 let indent = ra_fmt::leading_indent(anchor);
446 let mut buf = String::new();
447 if after {
448 buf.push_str("\n");
449 if let Some(spaces) = &indent {
450 buf.push_str(spaces);
451 }
452 }
453 buf.push_str("use ");
454 fmt_segments_raw(target, &mut buf);
455 buf.push_str(";");
456 if !after {
457 buf.push_str("\n\n");
458 if let Some(spaces) = &indent {
459 buf.push_str(&spaces);
460 }
461 }
462 let position = if after { anchor.text_range().end() } else { anchor.text_range().start() };
463 edit.insert(position, buf);
464 }
465}
466
467fn make_assist_add_in_tree_list(
468 tree_list: &ast::UseTreeList,
469 target: &[SmolStr],
470 add_self: bool,
471 edit: &mut TextEditBuilder,
472) {
473 let last = tree_list.use_trees().last();
474 if let Some(last) = last {
475 let mut buf = String::new();
476 let comma = last.syntax().siblings(Direction::Next).find(|n| n.kind() == T![,]);
477 let offset = if let Some(comma) = comma {
478 comma.text_range().end()
479 } else {
480 buf.push_str(",");
481 last.syntax().text_range().end()
482 };
483 if add_self {
484 buf.push_str(" self")
485 } else {
486 buf.push_str(" ");
487 }
488 fmt_segments_raw(target, &mut buf);
489 edit.insert(offset, buf);
490 } else {
491 }
492}
493
494fn make_assist_add_nested_import(
495 path: &ast::Path,
496 first_segment_to_split: &Option<ast::PathSegment>,
497 target: &[SmolStr],
498 add_self: bool,
499 edit: &mut TextEditBuilder,
500) {
501 let use_tree = path.syntax().ancestors().find_map(ast::UseTree::cast);
502 if let Some(use_tree) = use_tree {
503 let (start, add_colon_colon) = if let Some(first_segment_to_split) = first_segment_to_split
504 {
505 (first_segment_to_split.syntax().text_range().start(), false)
506 } else {
507 (use_tree.syntax().text_range().end(), true)
508 };
509 let end = use_tree.syntax().text_range().end();
510
511 let mut buf = String::new();
512 if add_colon_colon {
513 buf.push_str("::");
514 }
515 buf.push_str("{");
516 if add_self {
517 buf.push_str("self, ");
518 }
519 fmt_segments_raw(target, &mut buf);
520 if !target.is_empty() {
521 buf.push_str(", ");
522 }
523 edit.insert(start, buf);
524 edit.insert(end, "}".to_string());
525 }
526}