]> git.lizzy.rs Git - rust.git/blob - crates/ra_assists/src/assists/add_import.rs
c522d6a5a71cc58292a06f18fde0b3423c925a4a
[rust.git] / crates / ra_assists / src / assists / add_import.rs
1 //! FIXME: write short doc here
2
3 use hir::{self, db::HirDatabase};
4 use ra_syntax::{
5     ast::{self, NameOwner},
6     AstNode, Direction, SmolStr,
7     SyntaxKind::{PATH, PATH_SEGMENT},
8     SyntaxNode, TextRange, T,
9 };
10 use ra_text_edit::TextEditBuilder;
11
12 use crate::{
13     assist_ctx::{Assist, AssistCtx},
14     AssistId,
15 };
16
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)
24     anchor: &SyntaxNode,
25     // The path to import as a sequence of strings
26     target: &[SmolStr],
27     edit: &mut TextEditBuilder,
28 ) {
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());
32         }
33         ast::SourceFile::cast(n).map(|it| it.syntax().clone())
34     });
35
36     if let Some(container) = container {
37         let action = best_action_for_target(container, anchor.clone(), target);
38         make_assist(&action, target, edit);
39     }
40 }
41
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() {
46         return None;
47     }
48
49     let hir_path = hir::Path::from_ast(path.clone())?;
50     let segments = collect_hir_path_segments(&hir_path)?;
51     if segments.len() < 2 {
52         return None;
53     }
54
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(),
58         None => {
59             let current_file = path.syntax().ancestors().find_map(ast::SourceFile::cast)?;
60             current_file.syntax().clone()
61         }
62     };
63
64     ctx.add_assist(AssistId("add_import"), format!("import {}", fmt_segments(&segments)), |edit| {
65         apply_auto_import(&position, &path, &segments, edit.text_edit_builder());
66     })
67 }
68
69 fn collect_path_segments_raw(
70     segments: &mut Vec<ast::PathSegment>,
71     mut path: ast::Path,
72 ) -> Option<usize> {
73     let oldlen = segments.len();
74     loop {
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())),
80         );
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())?);
85             }
86             (Some((segment, PATH_SEGMENT)), _, _) => {
87                 segments.push(ast::PathSegment::cast(segment.as_node()?.clone())?);
88                 break;
89             }
90             (_, _, _) => return None,
91         }
92     }
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)
97 }
98
99 fn fmt_segments(segments: &[SmolStr]) -> String {
100     let mut buf = String::new();
101     fmt_segments_raw(segments, &mut buf);
102     buf
103 }
104
105 fn fmt_segments_raw(segments: &[SmolStr], buf: &mut String) {
106     let mut iter = segments.iter();
107     if let Some(s) = iter.next() {
108         buf.push_str(s);
109     }
110     for s in iter {
111         buf.push_str("::");
112         buf.push_str(s);
113     }
114 }
115
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()
119 }
120
121 fn compare_path_segment(a: &SmolStr, b: &ast::PathSegment) -> bool {
122     if let Some(kb) = b.kind() {
123         match kb {
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
129         }
130     } else {
131         false
132     }
133 }
134
135 fn compare_path_segment_with_name(a: &SmolStr, b: &ast::Name) -> bool {
136     a == b.text()
137 }
138
139 #[derive(Clone)]
140 enum ImportAction {
141     Nothing,
142     // Add a brand new use statement.
143     AddNewUse {
144         anchor: Option<SyntaxNode>, // anchor node
145         add_after_anchor: bool,
146     },
147
148     // To split an existing use statement creating a nested import.
149     AddNestedImport {
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
156         add_self: bool,
157     },
158     // To add the target path to an existing nested import tree list.
159     AddInTreeList {
160         common_segments: usize,
161         // The UseTreeList where to add the target path
162         tree_list: ast::UseTreeList,
163         add_self: bool,
164     },
165 }
166
167 impl ImportAction {
168     fn add_new_use(anchor: Option<SyntaxNode>, add_after_anchor: bool) -> Self {
169         ImportAction::AddNewUse { anchor, add_after_anchor }
170     }
171
172     fn add_nested_import(
173         common_segments: usize,
174         path_to_split: ast::Path,
175         first_segment_to_split: Option<ast::PathSegment>,
176         add_self: bool,
177     ) -> Self {
178         ImportAction::AddNestedImport {
179             common_segments,
180             path_to_split,
181             first_segment_to_split,
182             add_self,
183         }
184     }
185
186     fn add_in_tree_list(
187         common_segments: usize,
188         tree_list: ast::UseTreeList,
189         add_self: bool,
190     ) -> Self {
191         ImportAction::AddInTreeList { common_segments, tree_list, add_self }
192     }
193
194     fn better(left: ImportAction, right: ImportAction) -> ImportAction {
195         if left.is_better(&right) {
196             left
197         } else {
198             right
199         }
200     }
201
202     fn is_better(&self, other: &ImportAction) -> bool {
203         match (self, other) {
204             (ImportAction::Nothing, _) => true,
205             (ImportAction::AddInTreeList { .. }, ImportAction::Nothing) => false,
206             (
207                 ImportAction::AddNestedImport { common_segments: n, .. },
208                 ImportAction::AddInTreeList { common_segments: m, .. },
209             ) => n > m,
210             (
211                 ImportAction::AddInTreeList { common_segments: n, .. },
212                 ImportAction::AddNestedImport { common_segments: m, .. },
213             ) => n > m,
214             (ImportAction::AddInTreeList { .. }, _) => true,
215             (ImportAction::AddNestedImport { .. }, ImportAction::Nothing) => false,
216             (ImportAction::AddNestedImport { .. }, _) => true,
217             (ImportAction::AddNewUse { .. }, _) => false,
218         }
219     }
220 }
221
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
229 ) -> ImportAction {
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();
233
234     let tree_list = current_use_tree.use_tree_list();
235     let alias = current_use_tree.alias();
236
237     let path = match current_use_tree.path() {
238         Some(path) => path,
239         None => {
240             // If the use item don't have a path, it means it's broken (syntax error)
241             return ImportAction::add_new_use(
242                 current_use_tree
243                     .syntax()
244                     .ancestors()
245                     .find_map(ast::UseItem::cast)
246                     .map(|it| it.syntax().clone()),
247                 true,
248             );
249         }
250     };
251
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;
256         }
257     }
258
259     collect_path_segments_raw(current_path_segments, path.clone());
260
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
269             // use foo::bar
270             // We add a brand new use statement
271             current_use_tree
272                 .syntax()
273                 .ancestors()
274                 .find_map(ast::UseItem::cast)
275                 .map(|it| it.syntax().clone()),
276             true,
277         ),
278         common if common == left.len() && left.len() == right.len() => {
279             // e.g: target is std::fmt and we can have
280             // 1- use std::fmt;
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)
289                         .is_some()
290                 });
291
292                 if has_self {
293                     ImportAction::Nothing
294                 } else {
295                     ImportAction::add_in_tree_list(current_path_segments.len(), list, true)
296                 }
297             } else {
298                 // Case 1
299                 ImportAction::Nothing
300             }
301         }
302         common if common != left.len() && left.len() == right.len() => {
303             // e.g: target is std::fmt and we have
304             // use std::io;
305             // We need to split.
306             let segments_to_split = current_path_segments.split_at(prev_len + common).1;
307             ImportAction::add_nested_import(
308                 prev_len + common,
309                 path,
310                 Some(segments_to_split[0].clone()),
311                 false,
312             )
313         }
314         common if common == right.len() && left.len() > right.len() => {
315             // e.g: target is std::fmt and we can have
316             // 1- use std;
317             // 2- use std::{ ... };
318
319             // fallback action
320             let mut better_action = ImportAction::add_new_use(
321                 current_use_tree
322                     .syntax()
323                     .ancestors()
324                     .find_map(ast::UseItem::cast)
325                     .map(|it| it.syntax().clone()),
326                 true,
327             );
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,
333                         Some(list.clone()),
334                         u,
335                         target,
336                     );
337                     if child_action.is_better(&better_action) {
338                         better_action = child_action;
339                         if let ImportAction::Nothing = better_action {
340                             return better_action;
341                         }
342                     }
343                 }
344             } else {
345                 // Case 1, split adding self
346                 better_action = ImportAction::add_nested_import(prev_len + common, path, None, true)
347             }
348             better_action
349         }
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(
355                 prev_len + common,
356                 path,
357                 Some(segments_to_split[0].clone()),
358                 true,
359             )
360         }
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(
366                 prev_len + common,
367                 path,
368                 Some(segments_to_split[0].clone()),
369                 false,
370             )
371         }
372         _ => unreachable!(),
373     };
374
375     // If we are inside a UseTreeList adding a use statement become adding to the existing
376     // tree list.
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)
380         }
381         (_, _) => action,
382     };
383
384     // We remove the segments added
385     current_path_segments.truncate(prev_len);
386     action
387 }
388
389 fn best_action_for_target(
390     container: SyntaxNode,
391     anchor: SyntaxNode,
392     target: &[SmolStr],
393 ) -> ImportAction {
394     let mut storage = Vec::with_capacity(16); // this should be the only allocation
395     let best_action = container
396         .children()
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)),
402             None => Some(a),
403         });
404
405     match best_action {
406         Some(action) => action,
407         None => {
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
413                 .children()
414                 .find(|n| n.text_range().start() < anchor.text_range().start())
415                 .or_else(|| Some(anchor));
416
417             ImportAction::add_new_use(anchor, false)
418         }
419     }
420 }
421
422 fn make_assist(action: &ImportAction, target: &[SmolStr], edit: &mut TextEditBuilder) {
423     match action {
424         ImportAction::AddNewUse { anchor, add_after_anchor } => {
425             make_assist_add_new_use(anchor, *add_after_anchor, target, edit)
426         }
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)
432         }
433         ImportAction::AddNestedImport {
434             common_segments,
435             path_to_split,
436             first_segment_to_split,
437             add_self,
438         } => {
439             let segments_to_add = target.split_at(*common_segments).1;
440             make_assist_add_nested_import(
441                 path_to_split,
442                 first_segment_to_split,
443                 segments_to_add,
444                 *add_self,
445                 edit,
446             )
447         }
448         _ => {}
449     }
450 }
451
452 fn make_assist_add_new_use(
453     anchor: &Option<SyntaxNode>,
454     after: bool,
455     target: &[SmolStr],
456     edit: &mut TextEditBuilder,
457 ) {
458     if let Some(anchor) = anchor {
459         let indent = ra_fmt::leading_indent(anchor);
460         let mut buf = String::new();
461         if after {
462             buf.push_str("\n");
463             if let Some(spaces) = &indent {
464                 buf.push_str(spaces);
465             }
466         }
467         buf.push_str("use ");
468         fmt_segments_raw(target, &mut buf);
469         buf.push_str(";");
470         if !after {
471             buf.push_str("\n\n");
472             if let Some(spaces) = &indent {
473                 buf.push_str(&spaces);
474             }
475         }
476         let position = if after { anchor.text_range().end() } else { anchor.text_range().start() };
477         edit.insert(position, buf);
478     }
479 }
480
481 fn make_assist_add_in_tree_list(
482     tree_list: &ast::UseTreeList,
483     target: &[SmolStr],
484     add_self: bool,
485     edit: &mut TextEditBuilder,
486 ) {
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()
493         } else {
494             buf.push_str(",");
495             last.syntax().text_range().end()
496         };
497         if add_self {
498             buf.push_str(" self")
499         } else {
500             buf.push_str(" ");
501         }
502         fmt_segments_raw(target, &mut buf);
503         edit.insert(offset, buf);
504     } else {
505     }
506 }
507
508 fn make_assist_add_nested_import(
509     path: &ast::Path,
510     first_segment_to_split: &Option<ast::PathSegment>,
511     target: &[SmolStr],
512     add_self: bool,
513     edit: &mut TextEditBuilder,
514 ) {
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
518         {
519             (first_segment_to_split.syntax().text_range().start(), false)
520         } else {
521             (use_tree.syntax().text_range().end(), true)
522         };
523         let end = use_tree.syntax().text_range().end();
524
525         let mut buf = String::new();
526         if add_colon_colon {
527             buf.push_str("::");
528         }
529         buf.push_str("{ ");
530         if add_self {
531             buf.push_str("self, ");
532         }
533         fmt_segments_raw(target, &mut buf);
534         if !target.is_empty() {
535             buf.push_str(", ");
536         }
537         edit.insert(start, buf);
538         edit.insert(end, "}".to_string());
539     }
540 }
541
542 fn apply_auto_import(
543     container: &SyntaxNode,
544     path: &ast::Path,
545     target: &[SmolStr],
546     edit: &mut TextEditBuilder,
547 ) {
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(),
556         ));
557     }
558 }
559
560 fn collect_hir_path_segments(path: &hir::Path) -> Option<Vec<SmolStr>> {
561     let mut ps = Vec::<SmolStr>::with_capacity(10);
562     match path.kind {
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,
569     }
570     for s in path.segments.iter() {
571         ps.push(s.name.to_string().into());
572     }
573     Some(ps)
574 }
575
576 #[cfg(test)]
577 mod tests {
578     use crate::helpers::{check_assist, check_assist_not_applicable};
579
580     use super::*;
581
582     #[test]
583     fn test_auto_import_add_use_no_anchor() {
584         check_assist(
585             add_import,
586             "
587 std::fmt::Debug<|>
588     ",
589             "
590 use std::fmt::Debug;
591
592 Debug<|>
593     ",
594         );
595     }
596     #[test]
597     fn test_auto_import_add_use_no_anchor_with_item_below() {
598         check_assist(
599             add_import,
600             "
601 std::fmt::Debug<|>
602
603 fn main() {
604 }
605     ",
606             "
607 use std::fmt::Debug;
608
609 Debug<|>
610
611 fn main() {
612 }
613     ",
614         );
615     }
616
617     #[test]
618     fn test_auto_import_add_use_no_anchor_with_item_above() {
619         check_assist(
620             add_import,
621             "
622 fn main() {
623 }
624
625 std::fmt::Debug<|>
626     ",
627             "
628 use std::fmt::Debug;
629
630 fn main() {
631 }
632
633 Debug<|>
634     ",
635         );
636     }
637
638     #[test]
639     fn test_auto_import_add_use_no_anchor_2seg() {
640         check_assist(
641             add_import,
642             "
643 std::fmt<|>::Debug
644     ",
645             "
646 use std::fmt;
647
648 fmt<|>::Debug
649     ",
650         );
651     }
652
653     #[test]
654     fn test_auto_import_add_use() {
655         check_assist(
656             add_import,
657             "
658 use stdx;
659
660 impl std::fmt::Debug<|> for Foo {
661 }
662     ",
663             "
664 use stdx;
665 use std::fmt::Debug;
666
667 impl Debug<|> for Foo {
668 }
669     ",
670         );
671     }
672
673     #[test]
674     fn test_auto_import_file_use_other_anchor() {
675         check_assist(
676             add_import,
677             "
678 impl std::fmt::Debug<|> for Foo {
679 }
680     ",
681             "
682 use std::fmt::Debug;
683
684 impl Debug<|> for Foo {
685 }
686     ",
687         );
688     }
689
690     #[test]
691     fn test_auto_import_add_use_other_anchor_indent() {
692         check_assist(
693             add_import,
694             "
695     impl std::fmt::Debug<|> for Foo {
696     }
697     ",
698             "
699     use std::fmt::Debug;
700
701     impl Debug<|> for Foo {
702     }
703     ",
704         );
705     }
706
707     #[test]
708     fn test_auto_import_split_different() {
709         check_assist(
710             add_import,
711             "
712 use std::fmt;
713
714 impl std::io<|> for Foo {
715 }
716     ",
717             "
718 use std::{ io, fmt};
719
720 impl io<|> for Foo {
721 }
722     ",
723         );
724     }
725
726     #[test]
727     fn test_auto_import_split_self_for_use() {
728         check_assist(
729             add_import,
730             "
731 use std::fmt;
732
733 impl std::fmt::Debug<|> for Foo {
734 }
735     ",
736             "
737 use std::fmt::{ self, Debug, };
738
739 impl Debug<|> for Foo {
740 }
741     ",
742         );
743     }
744
745     #[test]
746     fn test_auto_import_split_self_for_target() {
747         check_assist(
748             add_import,
749             "
750 use std::fmt::Debug;
751
752 impl std::fmt<|> for Foo {
753 }
754     ",
755             "
756 use std::fmt::{ self, Debug};
757
758 impl fmt<|> for Foo {
759 }
760     ",
761         );
762     }
763
764     #[test]
765     fn test_auto_import_add_to_nested_self_nested() {
766         check_assist(
767             add_import,
768             "
769 use std::fmt::{Debug, nested::{Display}};
770
771 impl std::fmt::nested<|> for Foo {
772 }
773 ",
774             "
775 use std::fmt::{Debug, nested::{Display, self}};
776
777 impl nested<|> for Foo {
778 }
779 ",
780         );
781     }
782
783     #[test]
784     fn test_auto_import_add_to_nested_self_already_included() {
785         check_assist(
786             add_import,
787             "
788 use std::fmt::{Debug, nested::{self, Display}};
789
790 impl std::fmt::nested<|> for Foo {
791 }
792 ",
793             "
794 use std::fmt::{Debug, nested::{self, Display}};
795
796 impl nested<|> for Foo {
797 }
798 ",
799         );
800     }
801
802     #[test]
803     fn test_auto_import_add_to_nested_nested() {
804         check_assist(
805             add_import,
806             "
807 use std::fmt::{Debug, nested::{Display}};
808
809 impl std::fmt::nested::Debug<|> for Foo {
810 }
811 ",
812             "
813 use std::fmt::{Debug, nested::{Display, Debug}};
814
815 impl Debug<|> for Foo {
816 }
817 ",
818         );
819     }
820
821     #[test]
822     fn test_auto_import_split_common_target_longer() {
823         check_assist(
824             add_import,
825             "
826 use std::fmt::Debug;
827
828 impl std::fmt::nested::Display<|> for Foo {
829 }
830 ",
831             "
832 use std::fmt::{ nested::Display, Debug};
833
834 impl Display<|> for Foo {
835 }
836 ",
837         );
838     }
839
840     #[test]
841     fn test_auto_import_split_common_use_longer() {
842         check_assist(
843             add_import,
844             "
845 use std::fmt::nested::Debug;
846
847 impl std::fmt::Display<|> for Foo {
848 }
849 ",
850             "
851 use std::fmt::{ Display, nested::Debug};
852
853 impl Display<|> for Foo {
854 }
855 ",
856         );
857     }
858
859     #[test]
860     fn test_auto_import_alias() {
861         check_assist(
862             add_import,
863             "
864 use std::fmt as foo;
865
866 impl foo::Debug<|> for Foo {
867 }
868 ",
869             "
870 use std::fmt as foo;
871
872 impl Debug<|> for Foo {
873 }
874 ",
875         );
876     }
877
878     #[test]
879     fn test_auto_import_not_applicable_one_segment() {
880         check_assist_not_applicable(
881             add_import,
882             "
883 impl foo<|> for Foo {
884 }
885 ",
886         );
887     }
888
889     #[test]
890     fn test_auto_import_not_applicable_in_use() {
891         check_assist_not_applicable(
892             add_import,
893             "
894 use std::fmt<|>;
895 ",
896         );
897     }
898
899     #[test]
900     fn test_auto_import_add_use_no_anchor_in_mod_mod() {
901         check_assist(
902             add_import,
903             "
904 mod foo {
905     mod bar {
906         std::fmt::Debug<|>
907     }
908 }
909     ",
910             "
911 mod foo {
912     mod bar {
913         use std::fmt::Debug;
914
915         Debug<|>
916     }
917 }
918     ",
919         );
920     }
921 }