1 //! Handle syntactic aspects of inserting a new `use`.
2 use std::iter::{self, successors};
4 use algo::skip_trivia_token;
6 edit::{AstNodeEdit, IndentLevel},
7 PathSegmentKind, VisibilityOwner,
11 ast::{self, make, AstNode},
12 Direction, InsertPosition, SyntaxElement, SyntaxNode, T,
17 pub enum ImportScope {
18 File(ast::SourceFile),
19 Module(ast::ItemList),
23 pub fn from(syntax: SyntaxNode) -> Option<Self> {
24 if let Some(module) = ast::Module::cast(syntax.clone()) {
25 module.item_list().map(ImportScope::Module)
26 } else if let this @ Some(_) = ast::SourceFile::cast(syntax.clone()) {
27 this.map(ImportScope::File)
29 ast::ItemList::cast(syntax).map(ImportScope::Module)
33 /// Determines the containing syntax node in which to insert a `use` statement affecting `position`.
34 pub(crate) fn find_insert_use_container(
35 position: &SyntaxNode,
36 ctx: &crate::assist_context::AssistContext,
38 ctx.sema.ancestors_with_macros(position.clone()).find_map(Self::from)
41 pub(crate) fn as_syntax_node(&self) -> &SyntaxNode {
43 ImportScope::File(file) => file.syntax(),
44 ImportScope::Module(item_list) => item_list.syntax(),
48 fn indent_level(&self) -> IndentLevel {
50 ImportScope::File(file) => file.indent_level(),
51 ImportScope::Module(item_list) => item_list.indent_level() + 1,
55 fn first_insert_pos(&self) -> (InsertPosition<SyntaxElement>, AddBlankLine) {
57 ImportScope::File(_) => (InsertPosition::First, AddBlankLine::AfterTwice),
58 // don't insert the imports before the item list's opening curly brace
59 ImportScope::Module(item_list) => item_list
61 .map(|b| (InsertPosition::After(b.into()), AddBlankLine::Around))
62 .unwrap_or((InsertPosition::First, AddBlankLine::AfterTwice)),
66 fn insert_pos_after_inner_attribute(&self) -> (InsertPosition<SyntaxElement>, AddBlankLine) {
67 // check if the scope has inner attributes, we dont want to insert in front of them
71 // no flat_map here cause we want to short circuit the iterator
74 attr.as_ref().map(|attr| attr.kind() == ast::AttrKind::Inner).unwrap_or(false)
80 (InsertPosition::After(attr.syntax().clone().into()), AddBlankLine::BeforeTwice)
82 None => self.first_insert_pos(),
87 /// Insert an import path into the given file/node. A `merge` value of none indicates that no import merging is allowed to occur.
88 pub(crate) fn insert_use(
91 merge: Option<MergeBehaviour>,
93 let use_item = make::use_(make::use_tree(path.clone(), None, None, false));
94 // merge into existing imports if possible
95 if let Some(mb) = merge {
96 for existing_use in scope.as_syntax_node().children().filter_map(ast::Use::cast) {
97 if let Some(merged) = try_merge_imports(&existing_use, &use_item, mb) {
98 let to_delete: SyntaxElement = existing_use.syntax().clone().into();
99 let to_delete = to_delete.clone()..=to_delete;
100 let to_insert = iter::once(merged.syntax().clone().into());
101 return algo::replace_children(scope.as_syntax_node(), to_delete, to_insert);
106 // either we weren't allowed to merge or there is no import that fits the merge conditions
107 // so look for the place we have to insert to
108 let (insert_position, add_blank) = find_insert_position(scope, path);
110 let to_insert: Vec<SyntaxElement> = {
111 let mut buf = Vec::new();
114 AddBlankLine::Before | AddBlankLine::Around => {
115 buf.push(make::tokens::single_newline().into())
117 AddBlankLine::BeforeTwice => buf.push(make::tokens::blank_line().into()),
121 if let ident_level @ 1..=usize::MAX = scope.indent_level().0 as usize {
122 // FIXME: this alone doesnt properly re-align all cases
123 buf.push(make::tokens::whitespace(&" ".repeat(4 * ident_level)).into());
125 buf.push(use_item.syntax().clone().into());
128 AddBlankLine::After | AddBlankLine::Around => {
129 buf.push(make::tokens::single_newline().into())
131 AddBlankLine::AfterTwice => buf.push(make::tokens::blank_line().into()),
138 algo::insert_children(scope.as_syntax_node(), insert_position, to_insert)
141 fn eq_visibility(vis0: Option<ast::Visibility>, vis1: Option<ast::Visibility>) -> bool {
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(),
151 pub(crate) fn try_merge_imports(
154 merge_behaviour: MergeBehaviour,
155 ) -> Option<ast::Use> {
156 // don't merge imports with different visibilities
157 if !eq_visibility(old.visibility(), new.visibility()) {
160 let old_tree = old.use_tree()?;
161 let new_tree = new.use_tree()?;
162 let merged = try_merge_trees(&old_tree, &new_tree, merge_behaviour)?;
163 Some(old.with_use_tree(merged))
166 /// Simple function that checks if a UseTreeList is deeper than one level
167 fn use_tree_list_is_nested(tl: &ast::UseTreeList) -> bool {
168 tl.use_trees().any(|use_tree| {
169 use_tree.use_tree_list().is_some() || use_tree.path().and_then(|p| p.qualifier()).is_some()
173 // FIXME: currently this merely prepends the new tree into old, ideally it would insert the items in a sorted fashion
174 pub(crate) fn try_merge_trees(
177 merge_behaviour: MergeBehaviour,
178 ) -> Option<ast::UseTree> {
179 let lhs_path = old.path()?;
180 let rhs_path = new.path()?;
182 let (lhs_prefix, rhs_prefix) = common_prefix(&lhs_path, &rhs_path)?;
183 let lhs = old.split_prefix(&lhs_prefix);
184 let rhs = new.split_prefix(&rhs_prefix);
185 let lhs_tl = lhs.use_tree_list()?;
186 let rhs_tl = rhs.use_tree_list()?;
188 // if we are only allowed to merge the last level check if the split off paths are only one level deep
189 if merge_behaviour == MergeBehaviour::Last
190 && (use_tree_list_is_nested(&lhs_tl) || use_tree_list_is_nested(&rhs_tl))
192 mark::hit!(test_last_merge_too_long);
196 let should_insert_comma = lhs_tl
198 .and_then(|it| skip_trivia_token(it.prev_token()?, Direction::Prev))
201 let mut to_insert: Vec<SyntaxElement> = Vec::new();
202 if should_insert_comma {
203 to_insert.push(make::token(T![,]).into());
204 to_insert.push(make::tokens::single_space().into());
207 rhs_tl.syntax().children_with_tokens().filter(|it| !matches!(it.kind(), T!['{'] | T!['}'])),
209 let pos = InsertPosition::Before(lhs_tl.r_curly_token()?.into());
210 let use_tree_list = lhs_tl.insert_children(pos, to_insert);
211 Some(lhs.with_use_tree_list(use_tree_list))
214 /// Traverses both paths until they differ, returning the common prefix of both.
215 fn common_prefix(lhs: &ast::Path, rhs: &ast::Path) -> Option<(ast::Path, ast::Path)> {
217 let mut lhs_curr = first_path(&lhs);
218 let mut rhs_curr = first_path(&rhs);
220 match (lhs_curr.segment(), rhs_curr.segment()) {
221 (Some(lhs), Some(rhs)) if lhs.syntax().text() == rhs.syntax().text() => (),
224 res = Some((lhs_curr.clone(), rhs_curr.clone()));
226 match lhs_curr.parent_path().zip(rhs_curr.parent_path()) {
227 Some((lhs, rhs)) => {
238 /// What type of merges are allowed.
239 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
240 pub enum MergeBehaviour {
241 /// Merge everything together creating deeply nested imports.
243 /// Only merge the last import level, doesn't allow import nesting.
247 #[derive(Eq, PartialEq, PartialOrd, Ord)]
249 // the order here defines the order of new group inserts
258 fn new(path: &ast::Path) -> ImportGroup {
259 let default = ImportGroup::ExternCrate;
261 let first_segment = match first_segment(path) {
263 None => return default,
266 let kind = first_segment.kind().unwrap_or(PathSegmentKind::SelfKw);
268 PathSegmentKind::SelfKw => ImportGroup::ThisModule,
269 PathSegmentKind::SuperKw => ImportGroup::SuperModule,
270 PathSegmentKind::CrateKw => ImportGroup::ThisCrate,
271 PathSegmentKind::Name(name) => match name.text().as_str() {
272 "std" => ImportGroup::Std,
273 "core" => ImportGroup::Std,
274 // FIXME: can be ThisModule as well
275 _ => ImportGroup::ExternCrate,
277 PathSegmentKind::Type { .. } => unreachable!(),
282 fn first_segment(path: &ast::Path) -> Option<ast::PathSegment> {
283 first_path(path).segment()
286 fn first_path(path: &ast::Path) -> ast::Path {
287 successors(Some(path.clone()), ast::Path::qualifier).last().unwrap()
290 fn segment_iter(path: &ast::Path) -> impl Iterator<Item = ast::PathSegment> + Clone {
291 // cant make use of SyntaxNode::siblings, because the returned Iterator is not clone
292 successors(first_segment(path), |p| p.parent_path().parent_path().and_then(|p| p.segment()))
295 #[derive(PartialEq, Eq)]
304 fn find_insert_position(
306 insert_path: ast::Path,
307 ) -> (InsertPosition<SyntaxElement>, AddBlankLine) {
308 let group = ImportGroup::new(&insert_path);
309 let path_node_iter = scope
312 .filter_map(|node| ast::Use::cast(node.clone()).zip(Some(node)))
313 .flat_map(|(use_, node)| use_.use_tree().and_then(|tree| tree.path()).zip(Some(node)));
314 // Iterator that discards anything thats not in the required grouping
315 // This implementation allows the user to rearrange their import groups as this only takes the first group that fits
316 let group_iter = path_node_iter
318 .skip_while(|(path, _)| ImportGroup::new(path) != group)
319 .take_while(|(path, _)| ImportGroup::new(path) == group);
321 let segments = segment_iter(&insert_path);
322 // 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
324 // find the element that would come directly after our new import
326 group_iter.inspect(|(_, node)| last = Some(node.clone())).find(|(path, _)| {
327 let check_segments = segment_iter(&path);
331 .flat_map(|(seg, seg2)| seg.name_ref().zip(seg2.name_ref()))
332 .all(|(l, r)| l.text() <= r.text())
335 // insert our import before that element
336 Some((_, node)) => (InsertPosition::Before(node.into()), AddBlankLine::After),
337 // there is no element after our new import, so append it to the end of the group
339 Some(node) => (InsertPosition::After(node.into()), AddBlankLine::Before),
340 // the group we were looking for actually doesnt exist, so insert
342 // similar concept here to the `last` from above
344 // find the group that comes after where we want to insert
345 let post_group = path_node_iter
346 .inspect(|(_, node)| last = Some(node.clone()))
347 .find(|(p, _)| ImportGroup::new(p) > group);
350 (InsertPosition::Before(node.into()), AddBlankLine::AfterTwice)
352 // there is no such group, so append after the last one
355 (InsertPosition::After(node.into()), AddBlankLine::BeforeTwice)
357 // there are no imports in this file at all
358 None => scope.insert_pos_after_inner_attribute(),
370 use test_utils::assert_eq_text;
427 fn insert_middle_nested() {
432 use std::bar::{D, Z}; // example of weird imports due to user
438 use std::bar::{D, Z}; // example of weird imports due to user
445 fn insert_middle_groups() {
465 fn insert_first_matching_group() {
489 fn insert_missing_group_std() {
504 fn insert_missing_group_self() {
519 fn insert_no_imports() {
530 fn insert_empty_file() {
531 // empty files will get two trailing newlines
532 // this is due to the test case insert_no_imports above
543 fn insert_after_inner_attr() {
546 r"#![allow(unused_imports)]",
547 r"#![allow(unused_imports)]
554 fn insert_after_inner_attr2() {
557 r"#![allow(unused_imports)]
560 r"#![allow(unused_imports)]
570 check_last("std::io", r"use std::fmt;", r"use std::{fmt, io};")
574 fn merge_groups_last() {
577 r"use std::fmt::{Result, Display};",
578 r"use std::fmt::{Result, Display};
584 fn merge_groups_full() {
587 r"use std::fmt::{Result, Display};",
588 r"use std::{fmt::{Result, Display}, io};",
593 fn merge_groups_long_full() {
595 "std::foo::bar::Baz",
596 r"use std::foo::bar::Qux;",
597 r"use std::foo::bar::{Qux, Baz};",
602 fn merge_groups_long_last() {
604 "std::foo::bar::Baz",
605 r"use std::foo::bar::Qux;",
606 r"use std::foo::bar::{Qux, Baz};",
611 fn merge_groups_long_full_list() {
613 "std::foo::bar::Baz",
614 r"use std::foo::bar::{Qux, Quux};",
615 r"use std::foo::bar::{Qux, Quux, Baz};",
620 fn merge_groups_long_last_list() {
622 "std::foo::bar::Baz",
623 r"use std::foo::bar::{Qux, Quux};",
624 r"use std::foo::bar::{Qux, Quux, Baz};",
629 fn merge_groups_long_full_nested() {
631 "std::foo::bar::Baz",
632 r"use std::foo::bar::{Qux, quux::{Fez, Fizz}};",
633 r"use std::foo::bar::{Qux, quux::{Fez, Fizz}, Baz};",
638 fn merge_groups_long_last_nested() {
640 "std::foo::bar::Baz",
641 r"use std::foo::bar::{Qux, quux::{Fez, Fizz}};",
642 r"use std::foo::bar::Baz;
643 use std::foo::bar::{Qux, quux::{Fez, Fizz}};",
648 fn merge_groups_skip_pub() {
651 r"pub use std::fmt::{Result, Display};",
652 r"pub use std::fmt::{Result, Display};
658 fn merge_groups_skip_pub_crate() {
661 r"pub(crate) use std::fmt::{Result, Display};",
662 r"pub(crate) use std::fmt::{Result, Display};
668 #[ignore] // FIXME: Support this
669 fn split_out_merge() {
672 r"use std::{fmt, io};",
673 r"use std::{self, fmt::Result};
679 fn merge_groups_self() {
680 check_full("std::fmt::Debug", r"use std::fmt;", r"use std::fmt::{self, Debug};")
684 fn merge_self_glob() {
687 r"use token::TokenKind::*;",
688 r"use token::TokenKind::{self::*, self};",
693 fn merge_last_too_long() {
694 mark::check!(test_last_merge_too_long);
697 r"use foo::bar::baz::Qux;",
699 use foo::bar::baz::Qux;",
704 fn insert_short_before_long() {
707 r"use foo::bar::baz::Qux;",
709 use foo::bar::baz::Qux;",
715 ra_fixture_before: &str,
716 ra_fixture_after: &str,
717 mb: Option<MergeBehaviour>,
719 let file = super::ImportScope::from(
720 ast::SourceFile::parse(ra_fixture_before).tree().syntax().clone(),
723 let path = ast::SourceFile::parse(&format!("use {};", path))
727 .find_map(ast::Path::cast)
730 let result = insert_use(&file, path, mb).to_string();
731 assert_eq_text!(&result, ra_fixture_after);
734 fn check_full(path: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
735 check(path, ra_fixture_before, ra_fixture_after, Some(MergeBehaviour::Full))
738 fn check_last(path: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
739 check(path, ra_fixture_before, ra_fixture_after, Some(MergeBehaviour::Last))
742 fn check_none(path: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
743 check(path, ra_fixture_before, ra_fixture_after, None)