]> git.lizzy.rs Git - rust.git/blob - crates/assists/src/utils/insert_use.rs
Merge #5989
[rust.git] / crates / assists / src / utils / insert_use.rs
1 //! Handle syntactic aspects of inserting a new `use`.
2 use std::{
3     cmp::Ordering,
4     iter::{self, successors},
5 };
6
7 use ast::{
8     edit::{AstNodeEdit, IndentLevel},
9     PathSegmentKind, VisibilityOwner,
10 };
11 use syntax::{
12     algo,
13     ast::{self, make, AstNode},
14     InsertPosition, SyntaxElement, SyntaxNode,
15 };
16
17 #[derive(Debug)]
18 pub enum ImportScope {
19     File(ast::SourceFile),
20     Module(ast::ItemList),
21 }
22
23 impl ImportScope {
24     pub fn from(syntax: SyntaxNode) -> Option<Self> {
25         if let Some(module) = ast::Module::cast(syntax.clone()) {
26             module.item_list().map(ImportScope::Module)
27         } else if let this @ Some(_) = ast::SourceFile::cast(syntax.clone()) {
28             this.map(ImportScope::File)
29         } else {
30             ast::ItemList::cast(syntax).map(ImportScope::Module)
31         }
32     }
33
34     /// Determines the containing syntax node in which to insert a `use` statement affecting `position`.
35     pub(crate) fn find_insert_use_container(
36         position: &SyntaxNode,
37         ctx: &crate::assist_context::AssistContext,
38     ) -> Option<Self> {
39         ctx.sema.ancestors_with_macros(position.clone()).find_map(Self::from)
40     }
41
42     pub(crate) fn as_syntax_node(&self) -> &SyntaxNode {
43         match self {
44             ImportScope::File(file) => file.syntax(),
45             ImportScope::Module(item_list) => item_list.syntax(),
46         }
47     }
48
49     fn indent_level(&self) -> IndentLevel {
50         match self {
51             ImportScope::File(file) => file.indent_level(),
52             ImportScope::Module(item_list) => item_list.indent_level() + 1,
53         }
54     }
55
56     fn first_insert_pos(&self) -> (InsertPosition<SyntaxElement>, AddBlankLine) {
57         match self {
58             ImportScope::File(_) => (InsertPosition::First, AddBlankLine::AfterTwice),
59             // don't insert the imports before the item list's opening curly brace
60             ImportScope::Module(item_list) => item_list
61                 .l_curly_token()
62                 .map(|b| (InsertPosition::After(b.into()), AddBlankLine::Around))
63                 .unwrap_or((InsertPosition::First, AddBlankLine::AfterTwice)),
64         }
65     }
66
67     fn insert_pos_after_inner_attribute(&self) -> (InsertPosition<SyntaxElement>, AddBlankLine) {
68         // check if the scope has inner attributes, we dont want to insert in front of them
69         match self
70             .as_syntax_node()
71             .children()
72             // no flat_map here cause we want to short circuit the iterator
73             .map(ast::Attr::cast)
74             .take_while(|attr| {
75                 attr.as_ref().map(|attr| attr.kind() == ast::AttrKind::Inner).unwrap_or(false)
76             })
77             .last()
78             .flatten()
79         {
80             Some(attr) => {
81                 (InsertPosition::After(attr.syntax().clone().into()), AddBlankLine::BeforeTwice)
82             }
83             None => self.first_insert_pos(),
84         }
85     }
86 }
87
88 /// Insert an import path into the given file/node. A `merge` value of none indicates that no import merging is allowed to occur.
89 pub(crate) fn insert_use(
90     scope: &ImportScope,
91     path: ast::Path,
92     merge: Option<MergeBehaviour>,
93 ) -> SyntaxNode {
94     let use_item = make::use_(make::use_tree(path.clone(), None, None, false));
95     // merge into existing imports if possible
96     if let Some(mb) = merge {
97         for existing_use in scope.as_syntax_node().children().filter_map(ast::Use::cast) {
98             if let Some(merged) = try_merge_imports(&existing_use, &use_item, mb) {
99                 let to_delete: SyntaxElement = existing_use.syntax().clone().into();
100                 let to_delete = to_delete.clone()..=to_delete;
101                 let to_insert = iter::once(merged.syntax().clone().into());
102                 return algo::replace_children(scope.as_syntax_node(), to_delete, to_insert);
103             }
104         }
105     }
106
107     // either we weren't allowed to merge or there is no import that fits the merge conditions
108     // so look for the place we have to insert to
109     let (insert_position, add_blank) = find_insert_position(scope, path);
110
111     let to_insert: Vec<SyntaxElement> = {
112         let mut buf = Vec::new();
113
114         match add_blank {
115             AddBlankLine::Before | AddBlankLine::Around => {
116                 buf.push(make::tokens::single_newline().into())
117             }
118             AddBlankLine::BeforeTwice => buf.push(make::tokens::blank_line().into()),
119             _ => (),
120         }
121
122         if let ident_level @ 1..=usize::MAX = scope.indent_level().0 as usize {
123             buf.push(make::tokens::whitespace(&" ".repeat(4 * ident_level)).into());
124         }
125         buf.push(use_item.syntax().clone().into());
126
127         match add_blank {
128             AddBlankLine::After | AddBlankLine::Around => {
129                 buf.push(make::tokens::single_newline().into())
130             }
131             AddBlankLine::AfterTwice => buf.push(make::tokens::blank_line().into()),
132             _ => (),
133         }
134
135         buf
136     };
137
138     algo::insert_children(scope.as_syntax_node(), insert_position, to_insert)
139 }
140
141 fn eq_visibility(vis0: Option<ast::Visibility>, vis1: Option<ast::Visibility>) -> bool {
142     match (vis0, vis1) {
143         (None, None) => true,
144         // FIXME: Don't use the string representation to check for equality
145         // spaces inside of the node would break this comparison
146         (Some(vis0), Some(vis1)) => vis0.to_string() == vis1.to_string(),
147         _ => false,
148     }
149 }
150
151 pub(crate) fn try_merge_imports(
152     lhs: &ast::Use,
153     rhs: &ast::Use,
154     merge_behaviour: MergeBehaviour,
155 ) -> Option<ast::Use> {
156     // don't merge imports with different visibilities
157     if !eq_visibility(lhs.visibility(), rhs.visibility()) {
158         return None;
159     }
160     let lhs_tree = lhs.use_tree()?;
161     let rhs_tree = rhs.use_tree()?;
162     let merged = try_merge_trees(&lhs_tree, &rhs_tree, merge_behaviour)?;
163     Some(lhs.with_use_tree(merged))
164 }
165
166 pub(crate) fn try_merge_trees(
167     lhs: &ast::UseTree,
168     rhs: &ast::UseTree,
169     merge: MergeBehaviour,
170 ) -> Option<ast::UseTree> {
171     let lhs_path = lhs.path()?;
172     let rhs_path = rhs.path()?;
173
174     let (lhs_prefix, rhs_prefix) = common_prefix(&lhs_path, &rhs_path)?;
175     let lhs = lhs.split_prefix(&lhs_prefix);
176     let rhs = rhs.split_prefix(&rhs_prefix);
177     recursive_merge(&lhs, &rhs, merge).map(|(merged, _)| merged)
178 }
179
180 /// Recursively "zips" together lhs and rhs.
181 fn recursive_merge(
182     lhs: &ast::UseTree,
183     rhs: &ast::UseTree,
184     merge: MergeBehaviour,
185 ) -> Option<(ast::UseTree, bool)> {
186     let mut use_trees = lhs
187         .use_tree_list()
188         .into_iter()
189         .flat_map(|list| list.use_trees())
190         // check if any of the use trees are nested, if they are and the behaviour is `last` we are not allowed to merge this
191         // so early exit the iterator by using Option's Intoiterator impl
192         .map(|tree| match merge == MergeBehaviour::Last && tree.use_tree_list().is_some() {
193             true => None,
194             false => Some(tree),
195         })
196         .collect::<Option<Vec<_>>>()?;
197     use_trees.sort_unstable_by(|a, b| path_cmp_opt(a.path(), b.path()));
198     for rhs_t in rhs.use_tree_list().into_iter().flat_map(|list| list.use_trees()) {
199         let rhs_path = rhs_t.path();
200         match use_trees.binary_search_by(|p| path_cmp_opt(p.path(), rhs_path.clone())) {
201             Ok(idx) => {
202                 let lhs_t = &mut use_trees[idx];
203                 let lhs_path = lhs_t.path()?;
204                 let rhs_path = rhs_path?;
205                 let (lhs_prefix, rhs_prefix) = common_prefix(&lhs_path, &rhs_path)?;
206                 if lhs_prefix == lhs_path && rhs_prefix == rhs_path {
207                     let tree_is_self = |tree: ast::UseTree| {
208                         tree.path().as_ref().map(path_is_self).unwrap_or(false)
209                     };
210                     // check if only one of the two trees has a tree list, and whether that then contains `self` or not.
211                     // If this is the case we can skip this iteration since the path without the list is already included in the other one via `self`
212                     let tree_contains_self = |tree: &ast::UseTree| {
213                         tree.use_tree_list()
214                             .map(|tree_list| tree_list.use_trees().any(tree_is_self))
215                             .unwrap_or(false)
216                     };
217                     match (tree_contains_self(&lhs_t), tree_contains_self(&rhs_t)) {
218                         (true, false) => continue,
219                         (false, true) => {
220                             *lhs_t = rhs_t;
221                             continue;
222                         }
223                         _ => (),
224                     }
225
226                     // glob imports arent part of the use-tree lists so we need to special handle them here as well
227                     // this special handling is only required for when we merge a module import into a glob import of said module
228                     // see the `merge_self_glob` or `merge_mod_into_glob` tests
229                     if lhs_t.star_token().is_some() || rhs_t.star_token().is_some() {
230                         *lhs_t = make::use_tree(
231                             make::path_unqualified(make::path_segment_self()),
232                             None,
233                             None,
234                             false,
235                         );
236                         use_trees.insert(idx, make::glob_use_tree());
237                         continue;
238                     }
239                 }
240                 let lhs = lhs_t.split_prefix(&lhs_prefix);
241                 let rhs = rhs_t.split_prefix(&rhs_prefix);
242                 let this_has_children = use_trees.len() > 0;
243                 match recursive_merge(&lhs, &rhs, merge) {
244                     Some((_, has_multiple_children))
245                         if merge == MergeBehaviour::Last
246                             && this_has_children
247                             && has_multiple_children =>
248                     {
249                         return None
250                     }
251                     Some((use_tree, _)) => use_trees[idx] = use_tree,
252                     None => use_trees.insert(idx, rhs_t),
253                 }
254             }
255             Err(_)
256                 if merge == MergeBehaviour::Last
257                     && use_trees.len() > 0
258                     && rhs_t.use_tree_list().is_some() =>
259             {
260                 return None
261             }
262             Err(idx) => {
263                 use_trees.insert(idx, rhs_t);
264             }
265         }
266     }
267     let has_multiple_children = use_trees.len() > 1;
268     Some((lhs.with_use_tree_list(make::use_tree_list(use_trees)), has_multiple_children))
269 }
270
271 /// Traverses both paths until they differ, returning the common prefix of both.
272 fn common_prefix(lhs: &ast::Path, rhs: &ast::Path) -> Option<(ast::Path, ast::Path)> {
273     let mut res = None;
274     let mut lhs_curr = first_path(&lhs);
275     let mut rhs_curr = first_path(&rhs);
276     loop {
277         match (lhs_curr.segment(), rhs_curr.segment()) {
278             (Some(lhs), Some(rhs)) if lhs.syntax().text() == rhs.syntax().text() => (),
279             _ => break res,
280         }
281         res = Some((lhs_curr.clone(), rhs_curr.clone()));
282
283         match lhs_curr.parent_path().zip(rhs_curr.parent_path()) {
284             Some((lhs, rhs)) => {
285                 lhs_curr = lhs;
286                 rhs_curr = rhs;
287             }
288             _ => break res,
289         }
290     }
291 }
292
293 fn path_is_self(path: &ast::Path) -> bool {
294     path.segment().and_then(|seg| seg.self_token()).is_some() && path.qualifier().is_none()
295 }
296
297 #[inline]
298 fn first_segment(path: &ast::Path) -> Option<ast::PathSegment> {
299     first_path(path).segment()
300 }
301
302 fn first_path(path: &ast::Path) -> ast::Path {
303     successors(Some(path.clone()), ast::Path::qualifier).last().unwrap()
304 }
305
306 fn segment_iter(path: &ast::Path) -> impl Iterator<Item = ast::PathSegment> + Clone {
307     // cant make use of SyntaxNode::siblings, because the returned Iterator is not clone
308     successors(first_segment(path), |p| p.parent_path().parent_path().and_then(|p| p.segment()))
309 }
310
311 /// Orders paths in the following way:
312 /// the sole self token comes first, after that come uppercase identifiers, then lowercase identifiers
313 // FIXME: rustfmt sort lowercase idents before uppercase, in general we want to have the same ordering rustfmt has
314 // which is `self` and `super` first, then identifier imports with lowercase ones first, then glob imports and at last list imports.
315 // Example foo::{self, foo, baz, Baz, Qux, *, {Bar}}
316 fn path_cmp(a: &ast::Path, b: &ast::Path) -> Ordering {
317     match (path_is_self(a), path_is_self(b)) {
318         (true, true) => Ordering::Equal,
319         (true, false) => Ordering::Less,
320         (false, true) => Ordering::Greater,
321         (false, false) => {
322             let a = segment_iter(a);
323             let b = segment_iter(b);
324             // cmp_by would be useful for us here but that is currently unstable
325             // cmp doesnt work due the lifetimes on text's return type
326             a.zip(b)
327                 .flat_map(|(seg, seg2)| seg.name_ref().zip(seg2.name_ref()))
328                 .find_map(|(a, b)| match a.text().cmp(b.text()) {
329                     ord @ Ordering::Greater | ord @ Ordering::Less => Some(ord),
330                     Ordering::Equal => None,
331                 })
332                 .unwrap_or(Ordering::Equal)
333         }
334     }
335 }
336
337 fn path_cmp_opt(a: Option<ast::Path>, b: Option<ast::Path>) -> Ordering {
338     match (a, b) {
339         (None, None) => Ordering::Equal,
340         (None, Some(_)) => Ordering::Less,
341         (Some(_), None) => Ordering::Greater,
342         (Some(a), Some(b)) => path_cmp(&a, &b),
343     }
344 }
345
346 /// What type of merges are allowed.
347 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
348 pub enum MergeBehaviour {
349     /// Merge everything together creating deeply nested imports.
350     Full,
351     /// Only merge the last import level, doesn't allow import nesting.
352     Last,
353 }
354
355 #[derive(Eq, PartialEq, PartialOrd, Ord)]
356 enum ImportGroup {
357     // the order here defines the order of new group inserts
358     Std,
359     ExternCrate,
360     ThisCrate,
361     ThisModule,
362     SuperModule,
363 }
364
365 impl ImportGroup {
366     fn new(path: &ast::Path) -> ImportGroup {
367         let default = ImportGroup::ExternCrate;
368
369         let first_segment = match first_segment(path) {
370             Some(it) => it,
371             None => return default,
372         };
373
374         let kind = first_segment.kind().unwrap_or(PathSegmentKind::SelfKw);
375         match kind {
376             PathSegmentKind::SelfKw => ImportGroup::ThisModule,
377             PathSegmentKind::SuperKw => ImportGroup::SuperModule,
378             PathSegmentKind::CrateKw => ImportGroup::ThisCrate,
379             PathSegmentKind::Name(name) => match name.text().as_str() {
380                 "std" => ImportGroup::Std,
381                 "core" => ImportGroup::Std,
382                 // FIXME: can be ThisModule as well
383                 _ => ImportGroup::ExternCrate,
384             },
385             PathSegmentKind::Type { .. } => unreachable!(),
386         }
387     }
388 }
389
390 #[derive(PartialEq, Eq)]
391 enum AddBlankLine {
392     Before,
393     BeforeTwice,
394     Around,
395     After,
396     AfterTwice,
397 }
398
399 fn find_insert_position(
400     scope: &ImportScope,
401     insert_path: ast::Path,
402 ) -> (InsertPosition<SyntaxElement>, AddBlankLine) {
403     let group = ImportGroup::new(&insert_path);
404     let path_node_iter = scope
405         .as_syntax_node()
406         .children()
407         .filter_map(|node| ast::Use::cast(node.clone()).zip(Some(node)))
408         .flat_map(|(use_, node)| use_.use_tree().and_then(|tree| tree.path()).zip(Some(node)));
409     // Iterator that discards anything thats not in the required grouping
410     // This implementation allows the user to rearrange their import groups as this only takes the first group that fits
411     let group_iter = path_node_iter
412         .clone()
413         .skip_while(|(path, _)| ImportGroup::new(path) != group)
414         .take_while(|(path, _)| ImportGroup::new(path) == group);
415
416     let segments = segment_iter(&insert_path);
417     // track the last element we iterated over, if this is still None after the iteration then that means we never iterated in the first place
418     let mut last = None;
419     // find the element that would come directly after our new import
420     let post_insert =
421         group_iter.inspect(|(_, node)| last = Some(node.clone())).find(|(path, _)| {
422             let check_segments = segment_iter(&path);
423             segments
424                 .clone()
425                 .zip(check_segments)
426                 .flat_map(|(seg, seg2)| seg.name_ref().zip(seg2.name_ref()))
427                 .all(|(l, r)| l.text() <= r.text())
428         });
429     match post_insert {
430         // insert our import before that element
431         Some((_, node)) => (InsertPosition::Before(node.into()), AddBlankLine::After),
432         // there is no element after our new import, so append it to the end of the group
433         None => match last {
434             Some(node) => (InsertPosition::After(node.into()), AddBlankLine::Before),
435             // the group we were looking for actually doesnt exist, so insert
436             None => {
437                 // similar concept here to the `last` from above
438                 let mut last = None;
439                 // find the group that comes after where we want to insert
440                 let post_group = path_node_iter
441                     .inspect(|(_, node)| last = Some(node.clone()))
442                     .find(|(p, _)| ImportGroup::new(p) > group);
443                 match post_group {
444                     Some((_, node)) => {
445                         (InsertPosition::Before(node.into()), AddBlankLine::AfterTwice)
446                     }
447                     // there is no such group, so append after the last one
448                     None => match last {
449                         Some(node) => {
450                             (InsertPosition::After(node.into()), AddBlankLine::BeforeTwice)
451                         }
452                         // there are no imports in this file at all
453                         None => scope.insert_pos_after_inner_attribute(),
454                     },
455                 }
456             }
457         },
458     }
459 }
460
461 #[cfg(test)]
462 mod tests {
463     use super::*;
464
465     use test_utils::assert_eq_text;
466
467     #[test]
468     fn insert_start() {
469         check_none(
470             "std::bar::AA",
471             r"
472 use std::bar::B;
473 use std::bar::D;
474 use std::bar::F;
475 use std::bar::G;",
476             r"
477 use std::bar::AA;
478 use std::bar::B;
479 use std::bar::D;
480 use std::bar::F;
481 use std::bar::G;",
482         )
483     }
484
485     #[test]
486     fn insert_middle() {
487         check_none(
488             "std::bar::EE",
489             r"
490 use std::bar::A;
491 use std::bar::D;
492 use std::bar::F;
493 use std::bar::G;",
494             r"
495 use std::bar::A;
496 use std::bar::D;
497 use std::bar::EE;
498 use std::bar::F;
499 use std::bar::G;",
500         )
501     }
502
503     #[test]
504     fn insert_end() {
505         check_none(
506             "std::bar::ZZ",
507             r"
508 use std::bar::A;
509 use std::bar::D;
510 use std::bar::F;
511 use std::bar::G;",
512             r"
513 use std::bar::A;
514 use std::bar::D;
515 use std::bar::F;
516 use std::bar::G;
517 use std::bar::ZZ;",
518         )
519     }
520
521     #[test]
522     fn insert_middle_nested() {
523         check_none(
524             "std::bar::EE",
525             r"
526 use std::bar::A;
527 use std::bar::{D, Z}; // example of weird imports due to user
528 use std::bar::F;
529 use std::bar::G;",
530             r"
531 use std::bar::A;
532 use std::bar::EE;
533 use std::bar::{D, Z}; // example of weird imports due to user
534 use std::bar::F;
535 use std::bar::G;",
536         )
537     }
538
539     #[test]
540     fn insert_middle_groups() {
541         check_none(
542             "foo::bar::GG",
543             r"
544 use std::bar::A;
545 use std::bar::D;
546
547 use foo::bar::F;
548 use foo::bar::H;",
549             r"
550 use std::bar::A;
551 use std::bar::D;
552
553 use foo::bar::F;
554 use foo::bar::GG;
555 use foo::bar::H;",
556         )
557     }
558
559     #[test]
560     fn insert_first_matching_group() {
561         check_none(
562             "foo::bar::GG",
563             r"
564 use foo::bar::A;
565 use foo::bar::D;
566
567 use std;
568
569 use foo::bar::F;
570 use foo::bar::H;",
571             r"
572 use foo::bar::A;
573 use foo::bar::D;
574 use foo::bar::GG;
575
576 use std;
577
578 use foo::bar::F;
579 use foo::bar::H;",
580         )
581     }
582
583     #[test]
584     fn insert_missing_group_std() {
585         check_none(
586             "std::fmt",
587             r"
588 use foo::bar::A;
589 use foo::bar::D;",
590             r"
591 use std::fmt;
592
593 use foo::bar::A;
594 use foo::bar::D;",
595         )
596     }
597
598     #[test]
599     fn insert_missing_group_self() {
600         check_none(
601             "self::fmt",
602             r"
603 use foo::bar::A;
604 use foo::bar::D;",
605             r"
606 use foo::bar::A;
607 use foo::bar::D;
608
609 use self::fmt;",
610         )
611     }
612
613     #[test]
614     fn insert_no_imports() {
615         check_full(
616             "foo::bar",
617             "fn main() {}",
618             r"use foo::bar;
619
620 fn main() {}",
621         )
622     }
623
624     #[test]
625     fn insert_empty_file() {
626         // empty files will get two trailing newlines
627         // this is due to the test case insert_no_imports above
628         check_full(
629             "foo::bar",
630             "",
631             r"use foo::bar;
632
633 ",
634         )
635     }
636
637     #[test]
638     fn insert_after_inner_attr() {
639         check_full(
640             "foo::bar",
641             r"#![allow(unused_imports)]",
642             r"#![allow(unused_imports)]
643
644 use foo::bar;",
645         )
646     }
647
648     #[test]
649     fn insert_after_inner_attr2() {
650         check_full(
651             "foo::bar",
652             r"#![allow(unused_imports)]
653
654 fn main() {}",
655             r"#![allow(unused_imports)]
656
657 use foo::bar;
658
659 fn main() {}",
660         )
661     }
662
663     #[test]
664     fn merge_groups() {
665         check_last("std::io", r"use std::fmt;", r"use std::{fmt, io};")
666     }
667
668     #[test]
669     fn merge_groups_last() {
670         check_last(
671             "std::io",
672             r"use std::fmt::{Result, Display};",
673             r"use std::fmt::{Result, Display};
674 use std::io;",
675         )
676     }
677
678     #[test]
679     fn merge_groups_full() {
680         check_full(
681             "std::io",
682             r"use std::fmt::{Result, Display};",
683             r"use std::{fmt::{Result, Display}, io};",
684         )
685     }
686
687     #[test]
688     fn merge_groups_long_full() {
689         check_full(
690             "std::foo::bar::Baz",
691             r"use std::foo::bar::Qux;",
692             r"use std::foo::bar::{Baz, Qux};",
693         )
694     }
695
696     #[test]
697     fn merge_groups_long_last() {
698         check_last(
699             "std::foo::bar::Baz",
700             r"use std::foo::bar::Qux;",
701             r"use std::foo::bar::{Baz, Qux};",
702         )
703     }
704
705     #[test]
706     fn merge_groups_long_full_list() {
707         check_full(
708             "std::foo::bar::Baz",
709             r"use std::foo::bar::{Qux, Quux};",
710             r"use std::foo::bar::{Baz, Quux, Qux};",
711         )
712     }
713
714     #[test]
715     fn merge_groups_long_last_list() {
716         check_last(
717             "std::foo::bar::Baz",
718             r"use std::foo::bar::{Qux, Quux};",
719             r"use std::foo::bar::{Baz, Quux, Qux};",
720         )
721     }
722
723     #[test]
724     fn merge_groups_long_full_nested() {
725         check_full(
726             "std::foo::bar::Baz",
727             r"use std::foo::bar::{Qux, quux::{Fez, Fizz}};",
728             r"use std::foo::bar::{Baz, Qux, quux::{Fez, Fizz}};",
729         )
730     }
731
732     #[test]
733     fn merge_groups_long_last_nested() {
734         check_last(
735             "std::foo::bar::Baz",
736             r"use std::foo::bar::{Qux, quux::{Fez, Fizz}};",
737             r"use std::foo::bar::Baz;
738 use std::foo::bar::{Qux, quux::{Fez, Fizz}};",
739         )
740     }
741
742     #[test]
743     fn merge_groups_full_nested_deep() {
744         check_full(
745             "std::foo::bar::quux::Baz",
746             r"use std::foo::bar::{Qux, quux::{Fez, Fizz}};",
747             r"use std::foo::bar::{Qux, quux::{Baz, Fez, Fizz}};",
748         )
749     }
750
751     #[test]
752     fn merge_groups_skip_pub() {
753         check_full(
754             "std::io",
755             r"pub use std::fmt::{Result, Display};",
756             r"pub use std::fmt::{Result, Display};
757 use std::io;",
758         )
759     }
760
761     #[test]
762     fn merge_groups_skip_pub_crate() {
763         check_full(
764             "std::io",
765             r"pub(crate) use std::fmt::{Result, Display};",
766             r"pub(crate) use std::fmt::{Result, Display};
767 use std::io;",
768         )
769     }
770
771     #[test]
772     #[ignore] // FIXME: Support this
773     fn split_out_merge() {
774         check_last(
775             "std::fmt::Result",
776             r"use std::{fmt, io};",
777             r"use std::fmt::{self, Result};
778 use std::io;",
779         )
780     }
781
782     #[test]
783     fn merge_into_module_import() {
784         check_full(
785             "std::fmt::Result",
786             r"use std::{fmt, io};",
787             r"use std::{fmt::{self, Result}, io};",
788         )
789     }
790
791     #[test]
792     fn merge_groups_self() {
793         check_full("std::fmt::Debug", r"use std::fmt;", r"use std::fmt::{self, Debug};")
794     }
795
796     #[test]
797     fn merge_mod_into_glob() {
798         check_full(
799             "token::TokenKind",
800             r"use token::TokenKind::*;",
801             r"use token::TokenKind::{*, self};",
802         )
803         // FIXME: have it emit `use token::TokenKind::{self, *}`?
804     }
805
806     #[test]
807     fn merge_self_glob() {
808         check_full("self", r"use self::*;", r"use self::{*, self};")
809         // FIXME: have it emit `use {self, *}`?
810     }
811
812     #[test]
813     #[ignore] // FIXME: Support this
814     fn merge_partial_path() {
815         check_full(
816             "ast::Foo",
817             r"use syntax::{ast, algo};",
818             r"use syntax::{ast::{self, Foo}, algo};",
819         )
820     }
821
822     #[test]
823     fn merge_glob_nested() {
824         check_full(
825             "foo::bar::quux::Fez",
826             r"use foo::bar::{Baz, quux::*};",
827             r"use foo::bar::{Baz, quux::{self::*, Fez}};",
828         )
829     }
830
831     #[test]
832     fn merge_last_too_long() {
833         check_last("foo::bar", r"use foo::bar::baz::Qux;", r"use foo::bar::{self, baz::Qux};");
834     }
835
836     #[test]
837     fn insert_short_before_long() {
838         check_none(
839             "foo::bar",
840             r"use foo::bar::baz::Qux;",
841             r"use foo::bar;
842 use foo::bar::baz::Qux;",
843         );
844     }
845
846     #[test]
847     fn merge_last_fail() {
848         check_merge_only_fail(
849             r"use foo::bar::{baz::{Qux, Fez}};",
850             r"use foo::bar::{baaz::{Quux, Feez}};",
851             MergeBehaviour::Last,
852         );
853     }
854
855     #[test]
856     fn merge_last_fail1() {
857         check_merge_only_fail(
858             r"use foo::bar::{baz::{Qux, Fez}};",
859             r"use foo::bar::baaz::{Quux, Feez};",
860             MergeBehaviour::Last,
861         );
862     }
863
864     #[test]
865     fn merge_last_fail2() {
866         check_merge_only_fail(
867             r"use foo::bar::baz::{Qux, Fez};",
868             r"use foo::bar::{baaz::{Quux, Feez}};",
869             MergeBehaviour::Last,
870         );
871     }
872
873     #[test]
874     fn merge_last_fail3() {
875         check_merge_only_fail(
876             r"use foo::bar::baz::{Qux, Fez};",
877             r"use foo::bar::baaz::{Quux, Feez};",
878             MergeBehaviour::Last,
879         );
880     }
881
882     fn check(
883         path: &str,
884         ra_fixture_before: &str,
885         ra_fixture_after: &str,
886         mb: Option<MergeBehaviour>,
887     ) {
888         let file = super::ImportScope::from(
889             ast::SourceFile::parse(ra_fixture_before).tree().syntax().clone(),
890         )
891         .unwrap();
892         let path = ast::SourceFile::parse(&format!("use {};", path))
893             .tree()
894             .syntax()
895             .descendants()
896             .find_map(ast::Path::cast)
897             .unwrap();
898
899         let result = insert_use(&file, path, mb).to_string();
900         assert_eq_text!(&result, ra_fixture_after);
901     }
902
903     fn check_full(path: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
904         check(path, ra_fixture_before, ra_fixture_after, Some(MergeBehaviour::Full))
905     }
906
907     fn check_last(path: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
908         check(path, ra_fixture_before, ra_fixture_after, Some(MergeBehaviour::Last))
909     }
910
911     fn check_none(path: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
912         check(path, ra_fixture_before, ra_fixture_after, None)
913     }
914
915     fn check_merge_only_fail(ra_fixture0: &str, ra_fixture1: &str, mb: MergeBehaviour) {
916         let use0 = ast::SourceFile::parse(ra_fixture0)
917             .tree()
918             .syntax()
919             .descendants()
920             .find_map(ast::Use::cast)
921             .unwrap();
922
923         let use1 = ast::SourceFile::parse(ra_fixture1)
924             .tree()
925             .syntax()
926             .descendants()
927             .find_map(ast::Use::cast)
928             .unwrap();
929
930         let result = try_merge_imports(&use0, &use1, mb);
931         assert_eq!(result.map(|u| u.to_string()), None);
932     }
933 }