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