aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/assists/add_import.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists/src/assists/add_import.rs')
-rw-r--r--crates/ra_assists/src/assists/add_import.rs940
1 files changed, 940 insertions, 0 deletions
diff --git a/crates/ra_assists/src/assists/add_import.rs b/crates/ra_assists/src/assists/add_import.rs
new file mode 100644
index 000000000..048bc49c8
--- /dev/null
+++ b/crates/ra_assists/src/assists/add_import.rs
@@ -0,0 +1,940 @@
1//! FIXME: write short doc here
2
3use hir::{self, db::HirDatabase};
4use ra_syntax::{
5 ast::{self, NameOwner},
6 AstNode, Direction, SmolStr,
7 SyntaxKind::{PATH, PATH_SEGMENT},
8 SyntaxNode, TextRange, T,
9};
10use ra_text_edit::TextEditBuilder;
11
12use crate::{
13 assist_ctx::{Assist, AssistCtx},
14 AssistId,
15};
16
17pub(crate) fn add_import(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
18 let path: ast::Path = ctx.find_node_at_offset()?;
19 // We don't want to mess with use statements
20 if path.syntax().ancestors().find_map(ast::UseItem::cast).is_some() {
21 return None;
22 }
23
24 let hir_path = hir::Path::from_ast(path.clone())?;
25 let segments = collect_hir_path_segments(&hir_path)?;
26 if segments.len() < 2 {
27 return None;
28 }
29
30 if let Some(module) = path.syntax().ancestors().find_map(ast::Module::cast) {
31 if let (Some(item_list), Some(name)) = (module.item_list(), module.name()) {
32 ctx.add_action(
33 AssistId("add_import"),
34 format!("import {} in mod {}", fmt_segments(&segments), name.text()),
35 |edit| {
36 apply_auto_import(
37 item_list.syntax(),
38 &path,
39 &segments,
40 edit.text_edit_builder(),
41 );
42 },
43 );
44 }
45 } else {
46 let current_file = path.syntax().ancestors().find_map(ast::SourceFile::cast)?;
47 ctx.add_action(
48 AssistId("add_import"),
49 format!("import {} in the current file", fmt_segments(&segments)),
50 |edit| {
51 apply_auto_import(
52 current_file.syntax(),
53 &path,
54 &segments,
55 edit.text_edit_builder(),
56 );
57 },
58 );
59 }
60
61 ctx.build()
62}
63
64fn collect_path_segments_raw(
65 segments: &mut Vec<ast::PathSegment>,
66 mut path: ast::Path,
67) -> Option<usize> {
68 let oldlen = segments.len();
69 loop {
70 let mut children = path.syntax().children_with_tokens();
71 let (first, second, third) = (
72 children.next().map(|n| (n.clone(), n.kind())),
73 children.next().map(|n| (n.clone(), n.kind())),
74 children.next().map(|n| (n.clone(), n.kind())),
75 );
76 match (first, second, third) {
77 (Some((subpath, PATH)), Some((_, T![::])), Some((segment, PATH_SEGMENT))) => {
78 path = ast::Path::cast(subpath.as_node()?.clone())?;
79 segments.push(ast::PathSegment::cast(segment.as_node()?.clone())?);
80 }
81 (Some((segment, PATH_SEGMENT)), _, _) => {
82 segments.push(ast::PathSegment::cast(segment.as_node()?.clone())?);
83 break;
84 }
85 (_, _, _) => return None,
86 }
87 }
88 // We need to reverse only the new added segments
89 let only_new_segments = segments.split_at_mut(oldlen).1;
90 only_new_segments.reverse();
91 Some(segments.len() - oldlen)
92}
93
94fn fmt_segments(segments: &[SmolStr]) -> String {
95 let mut buf = String::new();
96 fmt_segments_raw(segments, &mut buf);
97 buf
98}
99
100fn fmt_segments_raw(segments: &[SmolStr], buf: &mut String) {
101 let mut iter = segments.iter();
102 if let Some(s) = iter.next() {
103 buf.push_str(s);
104 }
105 for s in iter {
106 buf.push_str("::");
107 buf.push_str(s);
108 }
109}
110
111// Returns the numeber of common segments.
112fn compare_path_segments(left: &[SmolStr], right: &[ast::PathSegment]) -> usize {
113 left.iter().zip(right).filter(|(l, r)| compare_path_segment(l, r)).count()
114}
115
116fn compare_path_segment(a: &SmolStr, b: &ast::PathSegment) -> bool {
117 if let Some(kb) = b.kind() {
118 match kb {
119 ast::PathSegmentKind::Name(nameref_b) => a == nameref_b.text(),
120 ast::PathSegmentKind::SelfKw => a == "self",
121 ast::PathSegmentKind::SuperKw => a == "super",
122 ast::PathSegmentKind::CrateKw => a == "crate",
123 ast::PathSegmentKind::Type { .. } => false, // not allowed in imports
124 }
125 } else {
126 false
127 }
128}
129
130fn compare_path_segment_with_name(a: &SmolStr, b: &ast::Name) -> bool {
131 a == b.text()
132}
133
134#[derive(Clone)]
135enum ImportAction {
136 Nothing,
137 // Add a brand new use statement.
138 AddNewUse {
139 anchor: Option<SyntaxNode>, // anchor node
140 add_after_anchor: bool,
141 },
142
143 // To split an existing use statement creating a nested import.
144 AddNestedImport {
145 // how may segments matched with the target path
146 common_segments: usize,
147 path_to_split: ast::Path,
148 // the first segment of path_to_split we want to add into the new nested list
149 first_segment_to_split: Option<ast::PathSegment>,
150 // Wether to add 'self' in addition to the target path
151 add_self: bool,
152 },
153 // To add the target path to an existing nested import tree list.
154 AddInTreeList {
155 common_segments: usize,
156 // The UseTreeList where to add the target path
157 tree_list: ast::UseTreeList,
158 add_self: bool,
159 },
160}
161
162impl ImportAction {
163 fn add_new_use(anchor: Option<SyntaxNode>, add_after_anchor: bool) -> Self {
164 ImportAction::AddNewUse { anchor, add_after_anchor }
165 }
166
167 fn add_nested_import(
168 common_segments: usize,
169 path_to_split: ast::Path,
170 first_segment_to_split: Option<ast::PathSegment>,
171 add_self: bool,
172 ) -> Self {
173 ImportAction::AddNestedImport {
174 common_segments,
175 path_to_split,
176 first_segment_to_split,
177 add_self,
178 }
179 }
180
181 fn add_in_tree_list(
182 common_segments: usize,
183 tree_list: ast::UseTreeList,
184 add_self: bool,
185 ) -> Self {
186 ImportAction::AddInTreeList { common_segments, tree_list, add_self }
187 }
188
189 fn better(left: ImportAction, right: ImportAction) -> ImportAction {
190 if left.is_better(&right) {
191 left
192 } else {
193 right
194 }
195 }
196
197 fn is_better(&self, other: &ImportAction) -> bool {
198 match (self, other) {
199 (ImportAction::Nothing, _) => true,
200 (ImportAction::AddInTreeList { .. }, ImportAction::Nothing) => false,
201 (
202 ImportAction::AddNestedImport { common_segments: n, .. },
203 ImportAction::AddInTreeList { common_segments: m, .. },
204 ) => n > m,
205 (
206 ImportAction::AddInTreeList { common_segments: n, .. },
207 ImportAction::AddNestedImport { common_segments: m, .. },
208 ) => n > m,
209 (ImportAction::AddInTreeList { .. }, _) => true,
210 (ImportAction::AddNestedImport { .. }, ImportAction::Nothing) => false,
211 (ImportAction::AddNestedImport { .. }, _) => true,
212 (ImportAction::AddNewUse { .. }, _) => false,
213 }
214 }
215}
216
217// Find out the best ImportAction to import target path against current_use_tree.
218// If current_use_tree has a nested import the function gets called recursively on every UseTree inside a UseTreeList.
219fn walk_use_tree_for_best_action(
220 current_path_segments: &mut Vec<ast::PathSegment>, // buffer containing path segments
221 current_parent_use_tree_list: Option<ast::UseTreeList>, // will be Some value if we are in a nested import
222 current_use_tree: ast::UseTree, // the use tree we are currently examinating
223 target: &[SmolStr], // the path we want to import
224) -> ImportAction {
225 // We save the number of segments in the buffer so we can restore the correct segments
226 // before returning. Recursive call will add segments so we need to delete them.
227 let prev_len = current_path_segments.len();
228
229 let tree_list = current_use_tree.use_tree_list();
230 let alias = current_use_tree.alias();
231
232 let path = match current_use_tree.path() {
233 Some(path) => path,
234 None => {
235 // If the use item don't have a path, it means it's broken (syntax error)
236 return ImportAction::add_new_use(
237 current_use_tree
238 .syntax()
239 .ancestors()
240 .find_map(ast::UseItem::cast)
241 .map(|it| it.syntax().clone()),
242 true,
243 );
244 }
245 };
246
247 // This can happen only if current_use_tree is a direct child of a UseItem
248 if let Some(name) = alias.and_then(|it| it.name()) {
249 if compare_path_segment_with_name(&target[0], &name) {
250 return ImportAction::Nothing;
251 }
252 }
253
254 collect_path_segments_raw(current_path_segments, path.clone());
255
256 // We compare only the new segments added in the line just above.
257 // The first prev_len segments were already compared in 'parent' recursive calls.
258 let left = target.split_at(prev_len).1;
259 let right = current_path_segments.split_at(prev_len).1;
260 let common = compare_path_segments(left, &right);
261 let mut action = match common {
262 0 => ImportAction::add_new_use(
263 // e.g: target is std::fmt and we can have
264 // use foo::bar
265 // We add a brand new use statement
266 current_use_tree
267 .syntax()
268 .ancestors()
269 .find_map(ast::UseItem::cast)
270 .map(|it| it.syntax().clone()),
271 true,
272 ),
273 common if common == left.len() && left.len() == right.len() => {
274 // e.g: target is std::fmt and we can have
275 // 1- use std::fmt;
276 // 2- use std::fmt:{ ... }
277 if let Some(list) = tree_list {
278 // In case 2 we need to add self to the nested list
279 // unless it's already there
280 let has_self = list.use_trees().map(|it| it.path()).any(|p| {
281 p.and_then(|it| it.segment())
282 .and_then(|it| it.kind())
283 .filter(|k| *k == ast::PathSegmentKind::SelfKw)
284 .is_some()
285 });
286
287 if has_self {
288 ImportAction::Nothing
289 } else {
290 ImportAction::add_in_tree_list(current_path_segments.len(), list, true)
291 }
292 } else {
293 // Case 1
294 ImportAction::Nothing
295 }
296 }
297 common if common != left.len() && left.len() == right.len() => {
298 // e.g: target is std::fmt and we have
299 // use std::io;
300 // We need to split.
301 let segments_to_split = current_path_segments.split_at(prev_len + common).1;
302 ImportAction::add_nested_import(
303 prev_len + common,
304 path,
305 Some(segments_to_split[0].clone()),
306 false,
307 )
308 }
309 common if common == right.len() && left.len() > right.len() => {
310 // e.g: target is std::fmt and we can have
311 // 1- use std;
312 // 2- use std::{ ... };
313
314 // fallback action
315 let mut better_action = ImportAction::add_new_use(
316 current_use_tree
317 .syntax()
318 .ancestors()
319 .find_map(ast::UseItem::cast)
320 .map(|it| it.syntax().clone()),
321 true,
322 );
323 if let Some(list) = tree_list {
324 // Case 2, check recursively if the path is already imported in the nested list
325 for u in list.use_trees() {
326 let child_action = walk_use_tree_for_best_action(
327 current_path_segments,
328 Some(list.clone()),
329 u,
330 target,
331 );
332 if child_action.is_better(&better_action) {
333 better_action = child_action;
334 if let ImportAction::Nothing = better_action {
335 return better_action;
336 }
337 }
338 }
339 } else {
340 // Case 1, split adding self
341 better_action = ImportAction::add_nested_import(prev_len + common, path, None, true)
342 }
343 better_action
344 }
345 common if common == left.len() && left.len() < right.len() => {
346 // e.g: target is std::fmt and we can have
347 // use std::fmt::Debug;
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 true,
354 )
355 }
356 common if common < left.len() && common < right.len() => {
357 // e.g: target is std::fmt::nested::Debug
358 // use std::fmt::Display
359 let segments_to_split = current_path_segments.split_at(prev_len + common).1;
360 ImportAction::add_nested_import(
361 prev_len + common,
362 path,
363 Some(segments_to_split[0].clone()),
364 false,
365 )
366 }
367 _ => unreachable!(),
368 };
369
370 // If we are inside a UseTreeList adding a use statement become adding to the existing
371 // tree list.
372 action = match (current_parent_use_tree_list, action.clone()) {
373 (Some(use_tree_list), ImportAction::AddNewUse { .. }) => {
374 ImportAction::add_in_tree_list(prev_len, use_tree_list, false)
375 }
376 (_, _) => action,
377 };
378
379 // We remove the segments added
380 current_path_segments.truncate(prev_len);
381 action
382}
383
384fn best_action_for_target(
385 container: SyntaxNode,
386 anchor: SyntaxNode,
387 target: &[SmolStr],
388) -> ImportAction {
389 let mut storage = Vec::with_capacity(16); // this should be the only allocation
390 let best_action = container
391 .children()
392 .filter_map(ast::UseItem::cast)
393 .filter_map(|it| it.use_tree())
394 .map(|u| walk_use_tree_for_best_action(&mut storage, None, u, target))
395 .fold(None, |best, a| match best {
396 Some(best) => Some(ImportAction::better(best, a)),
397 None => Some(a),
398 });
399
400 match best_action {
401 Some(action) => action,
402 None => {
403 // We have no action and no UseItem was found in container so we find
404 // another item and we use it as anchor.
405 // If there are no items above, we choose the target path itself as anchor.
406 // todo: we should include even whitespace blocks as anchor candidates
407 let anchor = container
408 .children()
409 .find(|n| n.text_range().start() < anchor.text_range().start())
410 .or_else(|| Some(anchor));
411
412 ImportAction::add_new_use(anchor, false)
413 }
414 }
415}
416
417fn make_assist(action: &ImportAction, target: &[SmolStr], edit: &mut TextEditBuilder) {
418 match action {
419 ImportAction::AddNewUse { anchor, add_after_anchor } => {
420 make_assist_add_new_use(anchor, *add_after_anchor, target, edit)
421 }
422 ImportAction::AddInTreeList { common_segments, tree_list, add_self } => {
423 // We know that the fist n segments already exists in the use statement we want
424 // to modify, so we want to add only the last target.len() - n segments.
425 let segments_to_add = target.split_at(*common_segments).1;
426 make_assist_add_in_tree_list(tree_list, segments_to_add, *add_self, edit)
427 }
428 ImportAction::AddNestedImport {
429 common_segments,
430 path_to_split,
431 first_segment_to_split,
432 add_self,
433 } => {
434 let segments_to_add = target.split_at(*common_segments).1;
435 make_assist_add_nested_import(
436 path_to_split,
437 first_segment_to_split,
438 segments_to_add,
439 *add_self,
440 edit,
441 )
442 }
443 _ => {}
444 }
445}
446
447fn make_assist_add_new_use(
448 anchor: &Option<SyntaxNode>,
449 after: bool,
450 target: &[SmolStr],
451 edit: &mut TextEditBuilder,
452) {
453 if let Some(anchor) = anchor {
454 let indent = ra_fmt::leading_indent(anchor);
455 let mut buf = String::new();
456 if after {
457 buf.push_str("\n");
458 if let Some(spaces) = &indent {
459 buf.push_str(spaces);
460 }
461 }
462 buf.push_str("use ");
463 fmt_segments_raw(target, &mut buf);
464 buf.push_str(";");
465 if !after {
466 buf.push_str("\n\n");
467 if let Some(spaces) = &indent {
468 buf.push_str(&spaces);
469 }
470 }
471 let position = if after { anchor.text_range().end() } else { anchor.text_range().start() };
472 edit.insert(position, buf);
473 }
474}
475
476fn make_assist_add_in_tree_list(
477 tree_list: &ast::UseTreeList,
478 target: &[SmolStr],
479 add_self: bool,
480 edit: &mut TextEditBuilder,
481) {
482 let last = tree_list.use_trees().last();
483 if let Some(last) = last {
484 let mut buf = String::new();
485 let comma = last.syntax().siblings(Direction::Next).find(|n| n.kind() == T![,]);
486 let offset = if let Some(comma) = comma {
487 comma.text_range().end()
488 } else {
489 buf.push_str(",");
490 last.syntax().text_range().end()
491 };
492 if add_self {
493 buf.push_str(" self")
494 } else {
495 buf.push_str(" ");
496 }
497 fmt_segments_raw(target, &mut buf);
498 edit.insert(offset, buf);
499 } else {
500 }
501}
502
503fn make_assist_add_nested_import(
504 path: &ast::Path,
505 first_segment_to_split: &Option<ast::PathSegment>,
506 target: &[SmolStr],
507 add_self: bool,
508 edit: &mut TextEditBuilder,
509) {
510 let use_tree = path.syntax().ancestors().find_map(ast::UseTree::cast);
511 if let Some(use_tree) = use_tree {
512 let (start, add_colon_colon) = if let Some(first_segment_to_split) = first_segment_to_split
513 {
514 (first_segment_to_split.syntax().text_range().start(), false)
515 } else {
516 (use_tree.syntax().text_range().end(), true)
517 };
518 let end = use_tree.syntax().text_range().end();
519
520 let mut buf = String::new();
521 if add_colon_colon {
522 buf.push_str("::");
523 }
524 buf.push_str("{ ");
525 if add_self {
526 buf.push_str("self, ");
527 }
528 fmt_segments_raw(target, &mut buf);
529 if !target.is_empty() {
530 buf.push_str(", ");
531 }
532 edit.insert(start, buf);
533 edit.insert(end, "}".to_string());
534 }
535}
536
537fn apply_auto_import(
538 container: &SyntaxNode,
539 path: &ast::Path,
540 target: &[SmolStr],
541 edit: &mut TextEditBuilder,
542) {
543 let action = best_action_for_target(container.clone(), path.syntax().clone(), target);
544 make_assist(&action, target, edit);
545 if let Some(last) = path.segment() {
546 // Here we are assuming the assist will provide a correct use statement
547 // so we can delete the path qualifier
548 edit.delete(TextRange::from_to(
549 path.syntax().text_range().start(),
550 last.syntax().text_range().start(),
551 ));
552 }
553}
554
555pub fn collect_hir_path_segments(path: &hir::Path) -> Option<Vec<SmolStr>> {
556 let mut ps = Vec::<SmolStr>::with_capacity(10);
557 match path.kind {
558 hir::PathKind::Abs => ps.push("".into()),
559 hir::PathKind::Crate => ps.push("crate".into()),
560 hir::PathKind::Plain => {}
561 hir::PathKind::Self_ => ps.push("self".into()),
562 hir::PathKind::Super => ps.push("super".into()),
563 hir::PathKind::Type(_) | hir::PathKind::DollarCrate(_) => return None,
564 }
565 for s in path.segments.iter() {
566 ps.push(s.name.to_string().into());
567 }
568 Some(ps)
569}
570
571// This function produces sequence of text edits into edit
572// to import the target path in the most appropriate scope given
573// the cursor position
574pub fn auto_import_text_edit(
575 // Ideally the position of the cursor, used to
576 position: &SyntaxNode,
577 // The statement to use as anchor (last resort)
578 anchor: &SyntaxNode,
579 // The path to import as a sequence of strings
580 target: &[SmolStr],
581 edit: &mut TextEditBuilder,
582) {
583 let container = position.ancestors().find_map(|n| {
584 if let Some(module) = ast::Module::cast(n.clone()) {
585 return module.item_list().map(|it| it.syntax().clone());
586 }
587 ast::SourceFile::cast(n).map(|it| it.syntax().clone())
588 });
589
590 if let Some(container) = container {
591 let action = best_action_for_target(container, anchor.clone(), target);
592 make_assist(&action, target, edit);
593 }
594}
595
596#[cfg(test)]
597mod tests {
598 use super::*;
599 use crate::helpers::{check_assist, check_assist_not_applicable};
600
601 #[test]
602 fn test_auto_import_add_use_no_anchor() {
603 check_assist(
604 add_import,
605 "
606std::fmt::Debug<|>
607 ",
608 "
609use std::fmt::Debug;
610
611Debug<|>
612 ",
613 );
614 }
615 #[test]
616 fn test_auto_import_add_use_no_anchor_with_item_below() {
617 check_assist(
618 add_import,
619 "
620std::fmt::Debug<|>
621
622fn main() {
623}
624 ",
625 "
626use std::fmt::Debug;
627
628Debug<|>
629
630fn main() {
631}
632 ",
633 );
634 }
635
636 #[test]
637 fn test_auto_import_add_use_no_anchor_with_item_above() {
638 check_assist(
639 add_import,
640 "
641fn main() {
642}
643
644std::fmt::Debug<|>
645 ",
646 "
647use std::fmt::Debug;
648
649fn main() {
650}
651
652Debug<|>
653 ",
654 );
655 }
656
657 #[test]
658 fn test_auto_import_add_use_no_anchor_2seg() {
659 check_assist(
660 add_import,
661 "
662std::fmt<|>::Debug
663 ",
664 "
665use std::fmt;
666
667fmt<|>::Debug
668 ",
669 );
670 }
671
672 #[test]
673 fn test_auto_import_add_use() {
674 check_assist(
675 add_import,
676 "
677use stdx;
678
679impl std::fmt::Debug<|> for Foo {
680}
681 ",
682 "
683use stdx;
684use std::fmt::Debug;
685
686impl Debug<|> for Foo {
687}
688 ",
689 );
690 }
691
692 #[test]
693 fn test_auto_import_file_use_other_anchor() {
694 check_assist(
695 add_import,
696 "
697impl std::fmt::Debug<|> for Foo {
698}
699 ",
700 "
701use std::fmt::Debug;
702
703impl Debug<|> for Foo {
704}
705 ",
706 );
707 }
708
709 #[test]
710 fn test_auto_import_add_use_other_anchor_indent() {
711 check_assist(
712 add_import,
713 "
714 impl std::fmt::Debug<|> for Foo {
715 }
716 ",
717 "
718 use std::fmt::Debug;
719
720 impl Debug<|> for Foo {
721 }
722 ",
723 );
724 }
725
726 #[test]
727 fn test_auto_import_split_different() {
728 check_assist(
729 add_import,
730 "
731use std::fmt;
732
733impl std::io<|> for Foo {
734}
735 ",
736 "
737use std::{ io, fmt};
738
739impl io<|> for Foo {
740}
741 ",
742 );
743 }
744
745 #[test]
746 fn test_auto_import_split_self_for_use() {
747 check_assist(
748 add_import,
749 "
750use std::fmt;
751
752impl std::fmt::Debug<|> for Foo {
753}
754 ",
755 "
756use std::fmt::{ self, Debug, };
757
758impl Debug<|> for Foo {
759}
760 ",
761 );
762 }
763
764 #[test]
765 fn test_auto_import_split_self_for_target() {
766 check_assist(
767 add_import,
768 "
769use std::fmt::Debug;
770
771impl std::fmt<|> for Foo {
772}
773 ",
774 "
775use std::fmt::{ self, Debug};
776
777impl fmt<|> for Foo {
778}
779 ",
780 );
781 }
782
783 #[test]
784 fn test_auto_import_add_to_nested_self_nested() {
785 check_assist(
786 add_import,
787 "
788use std::fmt::{Debug, nested::{Display}};
789
790impl std::fmt::nested<|> for Foo {
791}
792",
793 "
794use std::fmt::{Debug, nested::{Display, self}};
795
796impl nested<|> for Foo {
797}
798",
799 );
800 }
801
802 #[test]
803 fn test_auto_import_add_to_nested_self_already_included() {
804 check_assist(
805 add_import,
806 "
807use std::fmt::{Debug, nested::{self, Display}};
808
809impl std::fmt::nested<|> for Foo {
810}
811",
812 "
813use std::fmt::{Debug, nested::{self, Display}};
814
815impl nested<|> for Foo {
816}
817",
818 );
819 }
820
821 #[test]
822 fn test_auto_import_add_to_nested_nested() {
823 check_assist(
824 add_import,
825 "
826use std::fmt::{Debug, nested::{Display}};
827
828impl std::fmt::nested::Debug<|> for Foo {
829}
830",
831 "
832use std::fmt::{Debug, nested::{Display, Debug}};
833
834impl Debug<|> for Foo {
835}
836",
837 );
838 }
839
840 #[test]
841 fn test_auto_import_split_common_target_longer() {
842 check_assist(
843 add_import,
844 "
845use std::fmt::Debug;
846
847impl std::fmt::nested::Display<|> for Foo {
848}
849",
850 "
851use std::fmt::{ nested::Display, Debug};
852
853impl Display<|> for Foo {
854}
855",
856 );
857 }
858
859 #[test]
860 fn test_auto_import_split_common_use_longer() {
861 check_assist(
862 add_import,
863 "
864use std::fmt::nested::Debug;
865
866impl std::fmt::Display<|> for Foo {
867}
868",
869 "
870use std::fmt::{ Display, nested::Debug};
871
872impl Display<|> for Foo {
873}
874",
875 );
876 }
877
878 #[test]
879 fn test_auto_import_alias() {
880 check_assist(
881 add_import,
882 "
883use std::fmt as foo;
884
885impl foo::Debug<|> for Foo {
886}
887",
888 "
889use std::fmt as foo;
890
891impl Debug<|> for Foo {
892}
893",
894 );
895 }
896
897 #[test]
898 fn test_auto_import_not_applicable_one_segment() {
899 check_assist_not_applicable(
900 add_import,
901 "
902impl foo<|> for Foo {
903}
904",
905 );
906 }
907
908 #[test]
909 fn test_auto_import_not_applicable_in_use() {
910 check_assist_not_applicable(
911 add_import,
912 "
913use std::fmt<|>;
914",
915 );
916 }
917
918 #[test]
919 fn test_auto_import_add_use_no_anchor_in_mod_mod() {
920 check_assist(
921 add_import,
922 "
923mod foo {
924 mod bar {
925 std::fmt::Debug<|>
926 }
927}
928 ",
929 "
930mod foo {
931 mod bar {
932 use std::fmt::Debug;
933
934 Debug<|>
935 }
936}
937 ",
938 );
939 }
940}