1 use hir::db::HirDatabase;
3 ast, AstNode, SyntaxNode, Direction, TextRange,
4 SyntaxKind::{ PATH, PATH_SEGMENT, COLONCOLON, COMMA }
6 use crate::assist_ctx::{AssistCtx, Assist, AssistBuilder};
8 fn collect_path_segments(path: &ast::Path) -> Option<Vec<&ast::PathSegment>> {
9 let mut v = Vec::new();
10 collect_path_segments_raw(&mut v, path)?;
14 fn collect_path_segments_raw<'a>(
15 segments: &mut Vec<&'a ast::PathSegment>,
16 mut path: &'a ast::Path,
18 let oldlen = segments.len();
20 let mut children = path.syntax().children();
21 let (first, second, third) = (
22 children.next().map(|n| (n, n.kind())),
23 children.next().map(|n| (n, n.kind())),
24 children.next().map(|n| (n, n.kind())),
26 match (first, second, third) {
27 (Some((subpath, PATH)), Some((_, COLONCOLON)), Some((segment, PATH_SEGMENT))) => {
28 path = ast::Path::cast(subpath)?;
29 segments.push(ast::PathSegment::cast(segment)?);
31 (Some((segment, PATH_SEGMENT)), _, _) => {
32 segments.push(ast::PathSegment::cast(segment)?);
35 (_, _, _) => return None,
38 // We need to reverse only the new added segments
39 let only_new_segments = segments.split_at_mut(oldlen).1;
40 only_new_segments.reverse();
41 return Some(segments.len() - oldlen);
44 fn fmt_segments(segments: &[&ast::PathSegment]) -> String {
45 let mut buf = String::new();
46 fmt_segments_raw(segments, &mut buf);
50 fn fmt_segments_raw(segments: &[&ast::PathSegment], buf: &mut String) {
57 Some(ast::PathSegmentKind::Name(nameref)) => buf.push_str(nameref.text()),
58 Some(ast::PathSegmentKind::SelfKw) => buf.push_str("self"),
59 Some(ast::PathSegmentKind::SuperKw) => buf.push_str("super"),
60 Some(ast::PathSegmentKind::CrateKw) => buf.push_str("crate"),
67 // Returns the numeber of common segments.
68 fn compare_path_segments(left: &[&ast::PathSegment], right: &[&ast::PathSegment]) -> usize {
69 return left.iter().zip(right).filter(|(l, r)| compare_path_segment(l, r)).count();
72 fn compare_path_segment(a: &ast::PathSegment, b: &ast::PathSegment) -> bool {
73 if let (Some(ka), Some(kb)) = (a.kind(), b.kind()) {
75 (ast::PathSegmentKind::Name(nameref_a), ast::PathSegmentKind::Name(nameref_b)) => {
76 nameref_a.text() == nameref_b.text()
78 (ast::PathSegmentKind::SelfKw, ast::PathSegmentKind::SelfKw) => true,
79 (ast::PathSegmentKind::SuperKw, ast::PathSegmentKind::SuperKw) => true,
80 (ast::PathSegmentKind::CrateKw, ast::PathSegmentKind::CrateKw) => true,
88 fn compare_path_segment_with_name(a: &ast::PathSegment, b: &ast::Name) -> bool {
89 if let Some(ka) = a.kind() {
90 return match (ka, b) {
91 (ast::PathSegmentKind::Name(nameref_a), _) => nameref_a.text() == b.text(),
99 #[derive(Copy, Clone)]
100 enum ImportAction<'a> {
102 // Add a brand new use statement.
104 anchor: Option<&'a SyntaxNode>, // anchor node
105 add_after_anchor: bool,
108 // To split an existing use statement creating a nested import.
110 // how may segments matched with the target path
111 common_segments: usize,
112 path_to_split: &'a 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<&'a ast::PathSegment>,
115 // Wether to add 'self' in addition to the target path
118 // To add the target path to an existing nested import tree list.
120 common_segments: usize,
121 // The UseTreeList where to add the target path
122 tree_list: &'a ast::UseTreeList,
127 impl<'a> ImportAction<'a> {
128 fn add_new_use(anchor: Option<&'a SyntaxNode>, add_after_anchor: bool) -> Self {
129 ImportAction::AddNewUse { anchor, add_after_anchor }
132 fn add_nested_import(
133 common_segments: usize,
134 path_to_split: &'a ast::Path,
135 first_segment_to_split: Option<&'a ast::PathSegment>,
138 ImportAction::AddNestedImport {
141 first_segment_to_split,
147 common_segments: usize,
148 tree_list: &'a ast::UseTreeList,
151 ImportAction::AddInTreeList { common_segments, tree_list, add_self }
154 fn better<'b>(left: &'b ImportAction<'a>, right: &'b ImportAction<'a>) -> &'b ImportAction<'a> {
155 if left.is_better(right) {
162 fn is_better(&self, other: &ImportAction) -> bool {
163 match (self, other) {
164 (ImportAction::Nothing, _) => true,
165 (ImportAction::AddInTreeList { .. }, ImportAction::Nothing) => false,
167 ImportAction::AddNestedImport { common_segments: n, .. },
168 ImportAction::AddInTreeList { common_segments: m, .. },
171 ImportAction::AddInTreeList { common_segments: n, .. },
172 ImportAction::AddNestedImport { common_segments: m, .. },
174 (ImportAction::AddInTreeList { .. }, _) => true,
175 (ImportAction::AddNestedImport { .. }, ImportAction::Nothing) => false,
176 (ImportAction::AddNestedImport { .. }, _) => true,
177 (ImportAction::AddNewUse { .. }, _) => false,
182 // Find out the best ImportAction to import target path against current_use_tree.
183 // If current_use_tree has a nested import the function gets called recursively on every UseTree inside a UseTreeList.
184 fn walk_use_tree_for_best_action<'a>(
185 current_path_segments: &mut Vec<&'a ast::PathSegment>, // buffer containing path segments
186 current_parent_use_tree_list: Option<&'a ast::UseTreeList>, // will be Some value if we are in a nested import
187 current_use_tree: &'a ast::UseTree, // the use tree we are currently examinating
188 target: &[&'a ast::PathSegment], // the path we want to import
189 ) -> ImportAction<'a> {
190 // We save the number of segments in the buffer so we can restore the correct segments
191 // before returning. Recursive call will add segments so we need to delete them.
192 let prev_len = current_path_segments.len();
194 let tree_list = current_use_tree.use_tree_list();
195 let alias = current_use_tree.alias();
197 let path = match current_use_tree.path() {
200 // If the use item don't have a path, it means it's broken (syntax error)
201 return ImportAction::add_new_use(
205 .find_map(ast::UseItem::cast)
206 .map(AstNode::syntax),
212 // This can happen only if current_use_tree is a direct child of a UseItem
213 if let Some(name) = alias.and_then(ast::NameOwner::name) {
214 if compare_path_segment_with_name(target[0], name) {
215 return ImportAction::Nothing;
219 collect_path_segments_raw(current_path_segments, path);
221 // We compare only the new segments added in the line just above.
222 // The first prev_len segments were already compared in 'parent' recursive calls.
223 let left = target.split_at(prev_len).1;
224 let right = current_path_segments.split_at(prev_len).1;
225 let common = compare_path_segments(left, right);
226 let mut action = match common {
227 0 => ImportAction::add_new_use(
228 // e.g: target is std::fmt and we can have
230 // We add a brand new use statement
231 current_use_tree.syntax().ancestors().find_map(ast::UseItem::cast).map(AstNode::syntax),
234 common if common == left.len() && left.len() == right.len() => {
235 // e.g: target is std::fmt and we can have
237 // 2- use std::fmt:{ ... }
238 if let Some(list) = tree_list {
239 // In case 2 we need to add self to the nested list
240 // unless it's already there
241 let has_self = list.use_trees().map(ast::UseTree::path).any(|p| {
242 p.and_then(ast::Path::segment)
243 .and_then(ast::PathSegment::kind)
244 .filter(|k| *k == ast::PathSegmentKind::SelfKw)
249 ImportAction::Nothing
251 ImportAction::add_in_tree_list(current_path_segments.len(), list, true)
255 ImportAction::Nothing
258 common if common != left.len() && left.len() == right.len() => {
259 // e.g: target is std::fmt and we have
262 let segments_to_split = current_path_segments.split_at(prev_len + common).1;
263 ImportAction::add_nested_import(
266 Some(segments_to_split[0]),
270 common if left.len() > right.len() => {
271 // e.g: target is std::fmt and we can have
273 // 2- use std::{ ... };
276 let mut better_action = ImportAction::add_new_use(
280 .find_map(ast::UseItem::cast)
281 .map(AstNode::syntax),
284 if let Some(list) = tree_list {
285 // Case 2, check recursively if the path is already imported in the nested list
286 for u in list.use_trees() {
288 walk_use_tree_for_best_action(current_path_segments, Some(list), u, target);
289 if child_action.is_better(&better_action) {
290 better_action = child_action;
291 if let ImportAction::Nothing = better_action {
292 return better_action;
298 better_action = ImportAction::add_nested_import(prev_len + common, path, None, true)
302 common if left.len() < right.len() => {
303 // e.g: target is std::fmt and we can have
304 // use std::fmt::Debug;
305 let segments_to_split = current_path_segments.split_at(prev_len + common).1;
306 ImportAction::add_nested_import(
309 Some(segments_to_split[0]),
316 // If we are inside a UseTreeList adding a use statement become adding to the existing
318 action = match (current_parent_use_tree_list, action) {
319 (Some(use_tree_list), ImportAction::AddNewUse { .. }) => {
320 ImportAction::add_in_tree_list(prev_len, use_tree_list, false)
325 // We remove the segments added
326 current_path_segments.truncate(prev_len);
330 fn best_action_for_target<'b, 'a: 'b>(
331 container: &'a SyntaxNode,
333 target: &'b [&'a ast::PathSegment],
334 ) -> ImportAction<'a> {
335 let mut storage = Vec::with_capacity(16); // this should be the only allocation
336 let best_action = container
338 .filter_map(ast::UseItem::cast)
339 .filter_map(ast::UseItem::use_tree)
340 .map(|u| walk_use_tree_for_best_action(&mut storage, None, u, target))
341 .fold(None, |best, a| {
342 best.and_then(|best| Some(*ImportAction::better(&best, &a))).or(Some(a))
346 Some(action) => return action,
348 // We have no action we no use item was found in container so we find
349 // another item and we use it as anchor.
350 // If there are not items, we choose the target path itself as anchor.
351 let anchor = container
353 .find_map(ast::ModuleItem::cast)
354 .map(AstNode::syntax)
355 .or(Some(path.syntax()));
357 return ImportAction::add_new_use(anchor, false);
362 fn make_assist(action: &ImportAction, target: &[&ast::PathSegment], edit: &mut AssistBuilder) {
364 ImportAction::AddNewUse { anchor, add_after_anchor } => {
365 make_assist_add_new_use(anchor, *add_after_anchor, target, edit)
367 ImportAction::AddInTreeList { common_segments, tree_list, add_self } => {
368 // We know that the fist n segments already exists in the use statement we want
369 // to modify, so we want to add only the last target.len() - n segments.
370 let segments_to_add = target.split_at(*common_segments).1;
371 make_assist_add_in_tree_list(tree_list, segments_to_add, *add_self, edit)
373 ImportAction::AddNestedImport {
376 first_segment_to_split,
379 let segments_to_add = target.split_at(*common_segments).1;
380 make_assist_add_nested_import(
382 first_segment_to_split,
392 fn make_assist_add_new_use(
393 anchor: &Option<&SyntaxNode>,
395 target: &[&ast::PathSegment],
396 edit: &mut AssistBuilder,
398 if let Some(anchor) = anchor {
399 let indent = ra_fmt::leading_indent(anchor);
400 let mut buf = String::new();
403 if let Some(spaces) = indent {
404 buf.push_str(spaces);
407 buf.push_str("use ");
408 fmt_segments_raw(target, &mut buf);
411 buf.push_str("\n\n");
412 if let Some(spaces) = indent {
413 buf.push_str(spaces);
416 let position = if after { anchor.range().end() } else { anchor.range().start() };
417 edit.insert(position, buf);
421 fn make_assist_add_in_tree_list(
422 tree_list: &ast::UseTreeList,
423 target: &[&ast::PathSegment],
425 edit: &mut AssistBuilder,
427 let last = tree_list.use_trees().last();
428 if let Some(last) = last {
429 let mut buf = String::new();
430 let comma = last.syntax().siblings(Direction::Next).find(|n| n.kind() == COMMA);
431 let offset = if let Some(comma) = comma {
435 last.syntax().range().end()
438 buf.push_str(" self")
442 fmt_segments_raw(target, &mut buf);
443 edit.insert(offset, buf);
449 fn make_assist_add_nested_import(
451 first_segment_to_split: &Option<&ast::PathSegment>,
452 target: &[&ast::PathSegment],
454 edit: &mut AssistBuilder,
456 let use_tree = path.syntax().ancestors().find_map(ast::UseTree::cast);
457 if let Some(use_tree) = use_tree {
458 let (start, add_colon_colon) = if let Some(first_segment_to_split) = first_segment_to_split
460 (first_segment_to_split.syntax().range().start(), false)
462 (use_tree.syntax().range().end(), true)
464 let end = use_tree.syntax().range().end();
466 let mut buf = String::new();
472 buf.push_str("self, ");
474 fmt_segments_raw(target, &mut buf);
475 if !target.is_empty() {
478 edit.insert(start, buf);
479 edit.insert(end, "}");
483 pub(crate) fn auto_import(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
484 let node = ctx.covering_node();
485 let current_file = node.ancestors().find_map(ast::SourceFile::cast)?;
487 let path = node.ancestors().find_map(ast::Path::cast)?;
488 // We don't want to mess with use statements
489 if path.syntax().ancestors().find_map(ast::UseItem::cast).is_some() {
493 let segments = collect_path_segments(path)?;
494 if segments.len() < 2 {
498 ctx.build(format!("import {} in the current file", fmt_segments(&segments)), |edit| {
499 let action = best_action_for_target(current_file.syntax(), path, &segments);
500 make_assist(&action, segments.as_slice(), edit);
501 if let Some(last_segment) = path.segment() {
502 // Here we are assuming the assist will provide a correct use statement
503 // so we can delete the path qualifier
504 edit.delete(TextRange::from_to(
505 path.syntax().range().start(),
506 last_segment.syntax().range().start(),
515 use crate::helpers::{ check_assist, check_assist_not_applicable };
518 fn test_auto_import_file_add_use_no_anchor() {
533 fn test_auto_import_file_add_use() {
539 impl std::fmt::Debug<|> for Foo {
546 impl Debug<|> for Foo {
553 fn test_auto_import_file_add_use_other_anchor() {
557 impl std::fmt::Debug<|> for Foo {
563 impl Debug<|> for Foo {
570 fn test_auto_import_file_add_use_other_anchor_indent() {
574 impl std::fmt::Debug<|> for Foo {
580 impl Debug<|> for Foo {
587 fn test_auto_import_file_split_different() {
593 impl std::io<|> for Foo {
606 fn test_auto_import_file_split_self_for_use() {
612 impl std::fmt::Debug<|> for Foo {
616 use std::fmt::{ self, Debug, };
618 impl Debug<|> for Foo {
625 fn test_auto_import_file_split_self_for_target() {
631 impl std::fmt<|> for Foo {
635 use std::fmt::{ self, Debug};
637 impl fmt<|> for Foo {
644 fn test_auto_import_file_add_to_nested_self_nested() {
648 use std::fmt::{Debug, nested::{Display}};
650 impl std::fmt::nested<|> for Foo {
654 use std::fmt::{Debug, nested::{Display, self}};
656 impl nested<|> for Foo {
663 fn test_auto_import_file_add_to_nested_self_already_included() {
667 use std::fmt::{Debug, nested::{self, Display}};
669 impl std::fmt::nested<|> for Foo {
673 use std::fmt::{Debug, nested::{self, Display}};
675 impl nested<|> for Foo {
682 fn test_auto_import_file_add_to_nested_nested() {
686 use std::fmt::{Debug, nested::{Display}};
688 impl std::fmt::nested::Debug<|> for Foo {
692 use std::fmt::{Debug, nested::{Display, Debug}};
694 impl Debug<|> for Foo {
701 fn test_auto_import_file_alias() {
707 impl foo::Debug<|> for Foo {
713 impl Debug<|> for Foo {
720 fn test_auto_import_not_applicable_one_segment() {
721 check_assist_not_applicable(
724 impl foo<|> for Foo {