1 //! FIXME: write short doc here
3 use hir::{self, db::HirDatabase};
5 ast::{self, NameOwner},
6 AstNode, Direction, SmolStr,
7 SyntaxKind::{PATH, PATH_SEGMENT},
8 SyntaxNode, TextRange, T,
10 use ra_text_edit::TextEditBuilder;
13 assist_ctx::{Assist, AssistCtx},
17 // This function produces sequence of text edits into edit
18 // to import the target path in the most appropriate scope given
19 // the cursor position
20 pub fn auto_import_text_edit(
21 // Ideally the position of the cursor, used to
22 position: &SyntaxNode,
23 // The statement to use as anchor (last resort)
25 // The path to import as a sequence of strings
27 edit: &mut TextEditBuilder,
29 let container = position.ancestors().find_map(|n| {
30 if let Some(module) = ast::Module::cast(n.clone()) {
31 return module.item_list().map(|it| it.syntax().clone());
33 ast::SourceFile::cast(n).map(|it| it.syntax().clone())
36 if let Some(container) = container {
37 let action = best_action_for_target(container, anchor.clone(), target);
38 make_assist(&action, target, edit);
42 pub(crate) fn add_import(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
43 let path: ast::Path = ctx.find_node_at_offset()?;
44 // We don't want to mess with use statements
45 if path.syntax().ancestors().find_map(ast::UseItem::cast).is_some() {
49 let hir_path = hir::Path::from_ast(path.clone())?;
50 let segments = collect_hir_path_segments(&hir_path)?;
51 if segments.len() < 2 {
55 let module = path.syntax().ancestors().find_map(ast::Module::cast);
56 let position = match module.and_then(|it| it.item_list()) {
57 Some(item_list) => item_list.syntax().clone(),
59 let current_file = path.syntax().ancestors().find_map(ast::SourceFile::cast)?;
60 current_file.syntax().clone()
64 ctx.add_assist(AssistId("add_import"), format!("import {}", fmt_segments(&segments)), |edit| {
65 apply_auto_import(&position, &path, &segments, edit.text_edit_builder());
69 fn collect_path_segments_raw(
70 segments: &mut Vec<ast::PathSegment>,
73 let oldlen = segments.len();
75 let mut children = path.syntax().children_with_tokens();
76 let (first, second, third) = (
77 children.next().map(|n| (n.clone(), n.kind())),
78 children.next().map(|n| (n.clone(), n.kind())),
79 children.next().map(|n| (n.clone(), n.kind())),
81 match (first, second, third) {
82 (Some((subpath, PATH)), Some((_, T![::])), Some((segment, PATH_SEGMENT))) => {
83 path = ast::Path::cast(subpath.as_node()?.clone())?;
84 segments.push(ast::PathSegment::cast(segment.as_node()?.clone())?);
86 (Some((segment, PATH_SEGMENT)), _, _) => {
87 segments.push(ast::PathSegment::cast(segment.as_node()?.clone())?);
90 (_, _, _) => return None,
93 // We need to reverse only the new added segments
94 let only_new_segments = segments.split_at_mut(oldlen).1;
95 only_new_segments.reverse();
96 Some(segments.len() - oldlen)
99 fn fmt_segments(segments: &[SmolStr]) -> String {
100 let mut buf = String::new();
101 fmt_segments_raw(segments, &mut buf);
105 fn fmt_segments_raw(segments: &[SmolStr], buf: &mut String) {
106 let mut iter = segments.iter();
107 if let Some(s) = iter.next() {
116 // Returns the numeber of common segments.
117 fn compare_path_segments(left: &[SmolStr], right: &[ast::PathSegment]) -> usize {
118 left.iter().zip(right).filter(|(l, r)| compare_path_segment(l, r)).count()
121 fn compare_path_segment(a: &SmolStr, b: &ast::PathSegment) -> bool {
122 if let Some(kb) = b.kind() {
124 ast::PathSegmentKind::Name(nameref_b) => a == nameref_b.text(),
125 ast::PathSegmentKind::SelfKw => a == "self",
126 ast::PathSegmentKind::SuperKw => a == "super",
127 ast::PathSegmentKind::CrateKw => a == "crate",
128 ast::PathSegmentKind::Type { .. } => false, // not allowed in imports
135 fn compare_path_segment_with_name(a: &SmolStr, b: &ast::Name) -> bool {
142 // Add a brand new use statement.
144 anchor: Option<SyntaxNode>, // anchor node
145 add_after_anchor: bool,
148 // To split an existing use statement creating a nested import.
150 // how may segments matched with the target path
151 common_segments: usize,
152 path_to_split: ast::Path,
153 // the first segment of path_to_split we want to add into the new nested list
154 first_segment_to_split: Option<ast::PathSegment>,
155 // Wether to add 'self' in addition to the target path
158 // To add the target path to an existing nested import tree list.
160 common_segments: usize,
161 // The UseTreeList where to add the target path
162 tree_list: ast::UseTreeList,
168 fn add_new_use(anchor: Option<SyntaxNode>, add_after_anchor: bool) -> Self {
169 ImportAction::AddNewUse { anchor, add_after_anchor }
172 fn add_nested_import(
173 common_segments: usize,
174 path_to_split: ast::Path,
175 first_segment_to_split: Option<ast::PathSegment>,
178 ImportAction::AddNestedImport {
181 first_segment_to_split,
187 common_segments: usize,
188 tree_list: ast::UseTreeList,
191 ImportAction::AddInTreeList { common_segments, tree_list, add_self }
194 fn better(left: ImportAction, right: ImportAction) -> ImportAction {
195 if left.is_better(&right) {
202 fn is_better(&self, other: &ImportAction) -> bool {
203 match (self, other) {
204 (ImportAction::Nothing, _) => true,
205 (ImportAction::AddInTreeList { .. }, ImportAction::Nothing) => false,
207 ImportAction::AddNestedImport { common_segments: n, .. },
208 ImportAction::AddInTreeList { common_segments: m, .. },
211 ImportAction::AddInTreeList { common_segments: n, .. },
212 ImportAction::AddNestedImport { common_segments: m, .. },
214 (ImportAction::AddInTreeList { .. }, _) => true,
215 (ImportAction::AddNestedImport { .. }, ImportAction::Nothing) => false,
216 (ImportAction::AddNestedImport { .. }, _) => true,
217 (ImportAction::AddNewUse { .. }, _) => false,
222 // Find out the best ImportAction to import target path against current_use_tree.
223 // If current_use_tree has a nested import the function gets called recursively on every UseTree inside a UseTreeList.
224 fn walk_use_tree_for_best_action(
225 current_path_segments: &mut Vec<ast::PathSegment>, // buffer containing path segments
226 current_parent_use_tree_list: Option<ast::UseTreeList>, // will be Some value if we are in a nested import
227 current_use_tree: ast::UseTree, // the use tree we are currently examinating
228 target: &[SmolStr], // the path we want to import
230 // We save the number of segments in the buffer so we can restore the correct segments
231 // before returning. Recursive call will add segments so we need to delete them.
232 let prev_len = current_path_segments.len();
234 let tree_list = current_use_tree.use_tree_list();
235 let alias = current_use_tree.alias();
237 let path = match current_use_tree.path() {
240 // If the use item don't have a path, it means it's broken (syntax error)
241 return ImportAction::add_new_use(
245 .find_map(ast::UseItem::cast)
246 .map(|it| it.syntax().clone()),
252 // This can happen only if current_use_tree is a direct child of a UseItem
253 if let Some(name) = alias.and_then(|it| it.name()) {
254 if compare_path_segment_with_name(&target[0], &name) {
255 return ImportAction::Nothing;
259 collect_path_segments_raw(current_path_segments, path.clone());
261 // We compare only the new segments added in the line just above.
262 // The first prev_len segments were already compared in 'parent' recursive calls.
263 let left = target.split_at(prev_len).1;
264 let right = current_path_segments.split_at(prev_len).1;
265 let common = compare_path_segments(left, &right);
266 let mut action = match common {
267 0 => ImportAction::add_new_use(
268 // e.g: target is std::fmt and we can have
270 // We add a brand new use statement
274 .find_map(ast::UseItem::cast)
275 .map(|it| it.syntax().clone()),
278 common if common == left.len() && left.len() == right.len() => {
279 // e.g: target is std::fmt and we can have
281 // 2- use std::fmt:{ ... }
282 if let Some(list) = tree_list {
283 // In case 2 we need to add self to the nested list
284 // unless it's already there
285 let has_self = list.use_trees().map(|it| it.path()).any(|p| {
286 p.and_then(|it| it.segment())
287 .and_then(|it| it.kind())
288 .filter(|k| *k == ast::PathSegmentKind::SelfKw)
293 ImportAction::Nothing
295 ImportAction::add_in_tree_list(current_path_segments.len(), list, true)
299 ImportAction::Nothing
302 common if common != left.len() && left.len() == right.len() => {
303 // e.g: target is std::fmt and we have
306 let segments_to_split = current_path_segments.split_at(prev_len + common).1;
307 ImportAction::add_nested_import(
310 Some(segments_to_split[0].clone()),
314 common if common == right.len() && left.len() > right.len() => {
315 // e.g: target is std::fmt and we can have
317 // 2- use std::{ ... };
320 let mut better_action = ImportAction::add_new_use(
324 .find_map(ast::UseItem::cast)
325 .map(|it| it.syntax().clone()),
328 if let Some(list) = tree_list {
329 // Case 2, check recursively if the path is already imported in the nested list
330 for u in list.use_trees() {
331 let child_action = walk_use_tree_for_best_action(
332 current_path_segments,
337 if child_action.is_better(&better_action) {
338 better_action = child_action;
339 if let ImportAction::Nothing = better_action {
340 return better_action;
345 // Case 1, split adding self
346 better_action = ImportAction::add_nested_import(prev_len + common, path, None, true)
350 common if common == left.len() && left.len() < right.len() => {
351 // e.g: target is std::fmt and we can have
352 // use std::fmt::Debug;
353 let segments_to_split = current_path_segments.split_at(prev_len + common).1;
354 ImportAction::add_nested_import(
357 Some(segments_to_split[0].clone()),
361 common if common < left.len() && common < right.len() => {
362 // e.g: target is std::fmt::nested::Debug
363 // use std::fmt::Display
364 let segments_to_split = current_path_segments.split_at(prev_len + common).1;
365 ImportAction::add_nested_import(
368 Some(segments_to_split[0].clone()),
375 // If we are inside a UseTreeList adding a use statement become adding to the existing
377 action = match (current_parent_use_tree_list, action.clone()) {
378 (Some(use_tree_list), ImportAction::AddNewUse { .. }) => {
379 ImportAction::add_in_tree_list(prev_len, use_tree_list, false)
384 // We remove the segments added
385 current_path_segments.truncate(prev_len);
389 fn best_action_for_target(
390 container: SyntaxNode,
394 let mut storage = Vec::with_capacity(16); // this should be the only allocation
395 let best_action = container
397 .filter_map(ast::UseItem::cast)
398 .filter_map(|it| it.use_tree())
399 .map(|u| walk_use_tree_for_best_action(&mut storage, None, u, target))
400 .fold(None, |best, a| match best {
401 Some(best) => Some(ImportAction::better(best, a)),
406 Some(action) => action,
408 // We have no action and no UseItem was found in container so we find
409 // another item and we use it as anchor.
410 // If there are no items above, we choose the target path itself as anchor.
411 // todo: we should include even whitespace blocks as anchor candidates
412 let anchor = container
414 .find(|n| n.text_range().start() < anchor.text_range().start())
415 .or_else(|| Some(anchor));
417 ImportAction::add_new_use(anchor, false)
422 fn make_assist(action: &ImportAction, target: &[SmolStr], edit: &mut TextEditBuilder) {
424 ImportAction::AddNewUse { anchor, add_after_anchor } => {
425 make_assist_add_new_use(anchor, *add_after_anchor, target, edit)
427 ImportAction::AddInTreeList { common_segments, tree_list, add_self } => {
428 // We know that the fist n segments already exists in the use statement we want
429 // to modify, so we want to add only the last target.len() - n segments.
430 let segments_to_add = target.split_at(*common_segments).1;
431 make_assist_add_in_tree_list(tree_list, segments_to_add, *add_self, edit)
433 ImportAction::AddNestedImport {
436 first_segment_to_split,
439 let segments_to_add = target.split_at(*common_segments).1;
440 make_assist_add_nested_import(
442 first_segment_to_split,
452 fn make_assist_add_new_use(
453 anchor: &Option<SyntaxNode>,
456 edit: &mut TextEditBuilder,
458 if let Some(anchor) = anchor {
459 let indent = ra_fmt::leading_indent(anchor);
460 let mut buf = String::new();
463 if let Some(spaces) = &indent {
464 buf.push_str(spaces);
467 buf.push_str("use ");
468 fmt_segments_raw(target, &mut buf);
471 buf.push_str("\n\n");
472 if let Some(spaces) = &indent {
473 buf.push_str(&spaces);
476 let position = if after { anchor.text_range().end() } else { anchor.text_range().start() };
477 edit.insert(position, buf);
481 fn make_assist_add_in_tree_list(
482 tree_list: &ast::UseTreeList,
485 edit: &mut TextEditBuilder,
487 let last = tree_list.use_trees().last();
488 if let Some(last) = last {
489 let mut buf = String::new();
490 let comma = last.syntax().siblings(Direction::Next).find(|n| n.kind() == T![,]);
491 let offset = if let Some(comma) = comma {
492 comma.text_range().end()
495 last.syntax().text_range().end()
498 buf.push_str(" self")
502 fmt_segments_raw(target, &mut buf);
503 edit.insert(offset, buf);
508 fn make_assist_add_nested_import(
510 first_segment_to_split: &Option<ast::PathSegment>,
513 edit: &mut TextEditBuilder,
515 let use_tree = path.syntax().ancestors().find_map(ast::UseTree::cast);
516 if let Some(use_tree) = use_tree {
517 let (start, add_colon_colon) = if let Some(first_segment_to_split) = first_segment_to_split
519 (first_segment_to_split.syntax().text_range().start(), false)
521 (use_tree.syntax().text_range().end(), true)
523 let end = use_tree.syntax().text_range().end();
525 let mut buf = String::new();
531 buf.push_str("self, ");
533 fmt_segments_raw(target, &mut buf);
534 if !target.is_empty() {
537 edit.insert(start, buf);
538 edit.insert(end, "}".to_string());
542 fn apply_auto_import(
543 container: &SyntaxNode,
546 edit: &mut TextEditBuilder,
548 let action = best_action_for_target(container.clone(), path.syntax().clone(), target);
549 make_assist(&action, target, edit);
550 if let Some(last) = path.segment() {
551 // Here we are assuming the assist will provide a correct use statement
552 // so we can delete the path qualifier
553 edit.delete(TextRange::from_to(
554 path.syntax().text_range().start(),
555 last.syntax().text_range().start(),
560 fn collect_hir_path_segments(path: &hir::Path) -> Option<Vec<SmolStr>> {
561 let mut ps = Vec::<SmolStr>::with_capacity(10);
563 hir::PathKind::Abs => ps.push("".into()),
564 hir::PathKind::Crate => ps.push("crate".into()),
565 hir::PathKind::Plain => {}
566 hir::PathKind::Self_ => ps.push("self".into()),
567 hir::PathKind::Super => ps.push("super".into()),
568 hir::PathKind::Type(_) | hir::PathKind::DollarCrate(_) => return None,
570 for s in path.segments.iter() {
571 ps.push(s.name.to_string().into());
578 use crate::helpers::{check_assist, check_assist_not_applicable};
583 fn test_auto_import_add_use_no_anchor() {
597 fn test_auto_import_add_use_no_anchor_with_item_below() {
618 fn test_auto_import_add_use_no_anchor_with_item_above() {
639 fn test_auto_import_add_use_no_anchor_2seg() {
654 fn test_auto_import_add_use() {
660 impl std::fmt::Debug<|> for Foo {
667 impl Debug<|> for Foo {
674 fn test_auto_import_file_use_other_anchor() {
678 impl std::fmt::Debug<|> for Foo {
684 impl Debug<|> for Foo {
691 fn test_auto_import_add_use_other_anchor_indent() {
695 impl std::fmt::Debug<|> for Foo {
701 impl Debug<|> for Foo {
708 fn test_auto_import_split_different() {
714 impl std::io<|> for Foo {
727 fn test_auto_import_split_self_for_use() {
733 impl std::fmt::Debug<|> for Foo {
737 use std::fmt::{ self, Debug, };
739 impl Debug<|> for Foo {
746 fn test_auto_import_split_self_for_target() {
752 impl std::fmt<|> for Foo {
756 use std::fmt::{ self, Debug};
758 impl fmt<|> for Foo {
765 fn test_auto_import_add_to_nested_self_nested() {
769 use std::fmt::{Debug, nested::{Display}};
771 impl std::fmt::nested<|> for Foo {
775 use std::fmt::{Debug, nested::{Display, self}};
777 impl nested<|> for Foo {
784 fn test_auto_import_add_to_nested_self_already_included() {
788 use std::fmt::{Debug, nested::{self, Display}};
790 impl std::fmt::nested<|> for Foo {
794 use std::fmt::{Debug, nested::{self, Display}};
796 impl nested<|> for Foo {
803 fn test_auto_import_add_to_nested_nested() {
807 use std::fmt::{Debug, nested::{Display}};
809 impl std::fmt::nested::Debug<|> for Foo {
813 use std::fmt::{Debug, nested::{Display, Debug}};
815 impl Debug<|> for Foo {
822 fn test_auto_import_split_common_target_longer() {
828 impl std::fmt::nested::Display<|> for Foo {
832 use std::fmt::{ nested::Display, Debug};
834 impl Display<|> for Foo {
841 fn test_auto_import_split_common_use_longer() {
845 use std::fmt::nested::Debug;
847 impl std::fmt::Display<|> for Foo {
851 use std::fmt::{ Display, nested::Debug};
853 impl Display<|> for Foo {
860 fn test_auto_import_alias() {
866 impl foo::Debug<|> for Foo {
872 impl Debug<|> for Foo {
879 fn test_auto_import_not_applicable_one_segment() {
880 check_assist_not_applicable(
883 impl foo<|> for Foo {
890 fn test_auto_import_not_applicable_in_use() {
891 check_assist_not_applicable(
900 fn test_auto_import_add_use_no_anchor_in_mod_mod() {