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