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