1 //! Handle syntactic aspects of inserting a new `use`.
2 use std::{cmp::Ordering, iter::successors};
4 use crate::RootDatabase;
6 use itertools::{EitherOrBoth, Itertools};
11 edit::{AstNodeEdit, IndentLevel},
12 make, AstNode, AttrsOwner, PathSegmentKind, VisibilityOwner,
14 AstToken, InsertPosition, NodeOrToken, SyntaxElement, SyntaxNode, SyntaxToken,
18 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
19 pub struct InsertUseConfig {
20 pub merge: Option<MergeBehavior>,
21 pub prefix_kind: hir::PrefixKind,
24 #[derive(Debug, Clone)]
25 pub enum ImportScope {
26 File(ast::SourceFile),
27 Module(ast::ItemList),
31 pub fn from(syntax: SyntaxNode) -> Option<Self> {
32 if let Some(module) = ast::Module::cast(syntax.clone()) {
33 module.item_list().map(ImportScope::Module)
34 } else if let this @ Some(_) = ast::SourceFile::cast(syntax.clone()) {
35 this.map(ImportScope::File)
37 ast::ItemList::cast(syntax).map(ImportScope::Module)
41 /// Determines the containing syntax node in which to insert a `use` statement affecting `position`.
42 pub fn find_insert_use_container(
43 position: &SyntaxNode,
44 sema: &Semantics<'_, RootDatabase>,
46 sema.ancestors_with_macros(position.clone()).find_map(Self::from)
49 pub fn as_syntax_node(&self) -> &SyntaxNode {
51 ImportScope::File(file) => file.syntax(),
52 ImportScope::Module(item_list) => item_list.syntax(),
56 fn indent_level(&self) -> IndentLevel {
58 ImportScope::File(file) => file.indent_level(),
59 ImportScope::Module(item_list) => item_list.indent_level() + 1,
63 fn first_insert_pos(&self) -> (InsertPosition<SyntaxElement>, AddBlankLine) {
65 ImportScope::File(_) => (InsertPosition::First, AddBlankLine::AfterTwice),
66 // don't insert the imports before the item list's opening curly brace
67 ImportScope::Module(item_list) => item_list
69 .map(|b| (InsertPosition::After(b.into()), AddBlankLine::Around))
70 .unwrap_or((InsertPosition::First, AddBlankLine::AfterTwice)),
74 fn insert_pos_after_last_inner_element(&self) -> (InsertPosition<SyntaxElement>, AddBlankLine) {
76 .children_with_tokens()
77 .filter(|child| match child {
78 NodeOrToken::Node(node) => is_inner_attribute(node.clone()),
79 NodeOrToken::Token(token) => is_inner_comment(token.clone()),
82 .map(|last_inner_element| {
83 (InsertPosition::After(last_inner_element.into()), AddBlankLine::BeforeTwice)
85 .unwrap_or_else(|| self.first_insert_pos())
89 fn is_inner_attribute(node: SyntaxNode) -> bool {
90 ast::Attr::cast(node).map(|attr| attr.kind()) == Some(ast::AttrKind::Inner)
93 fn is_inner_comment(token: SyntaxToken) -> bool {
94 ast::Comment::cast(token).and_then(|comment| comment.kind().doc)
95 == Some(ast::CommentPlacement::Inner)
98 /// Insert an import path into the given file/node. A `merge` value of none indicates that no import merging is allowed to occur.
99 pub fn insert_use<'a>(
102 merge: Option<MergeBehavior>,
103 ) -> SyntaxRewriter<'a> {
104 let _p = profile::span("insert_use");
105 let mut rewriter = SyntaxRewriter::default();
106 let use_item = make::use_(None, make::use_tree(path.clone(), None, None, false));
107 // merge into existing imports if possible
108 if let Some(mb) = merge {
109 for existing_use in scope.as_syntax_node().children().filter_map(ast::Use::cast) {
110 if let Some(merged) = try_merge_imports(&existing_use, &use_item, mb) {
111 rewriter.replace(existing_use.syntax(), merged.syntax());
117 // either we weren't allowed to merge or there is no import that fits the merge conditions
118 // so look for the place we have to insert to
119 let (insert_position, add_blank) = find_insert_position(scope, path);
121 let indent = if let ident_level @ 1..=usize::MAX = scope.indent_level().0 as usize {
122 Some(make::tokens::whitespace(&" ".repeat(4 * ident_level)).into())
127 let to_insert: Vec<SyntaxElement> = {
128 let mut buf = Vec::new();
131 AddBlankLine::Before | AddBlankLine::Around => {
132 buf.push(make::tokens::single_newline().into())
134 AddBlankLine::BeforeTwice => buf.push(make::tokens::blank_line().into()),
138 if add_blank.has_before() {
139 if let Some(indent) = indent.clone() {
140 mark::hit!(insert_use_indent_before);
145 buf.push(use_item.syntax().clone().into());
148 AddBlankLine::After | AddBlankLine::Around => {
149 buf.push(make::tokens::single_newline().into())
151 AddBlankLine::AfterTwice => buf.push(make::tokens::blank_line().into()),
155 // only add indentation *after* our stuff if there's another node directly after it
156 if add_blank.has_after() && matches!(insert_position, InsertPosition::Before(_)) {
157 if let Some(indent) = indent {
158 mark::hit!(insert_use_indent_after);
161 } else if add_blank.has_after() && matches!(insert_position, InsertPosition::After(_)) {
162 mark::hit!(insert_use_no_indent_after);
168 match insert_position {
169 InsertPosition::First => {
170 rewriter.insert_many_as_first_children(scope.as_syntax_node(), to_insert)
172 InsertPosition::Last => return rewriter, // actually unreachable
173 InsertPosition::Before(anchor) => rewriter.insert_many_before(&anchor, to_insert),
174 InsertPosition::After(anchor) => rewriter.insert_many_after(&anchor, to_insert),
179 fn eq_visibility(vis0: Option<ast::Visibility>, vis1: Option<ast::Visibility>) -> bool {
181 (None, None) => true,
182 // FIXME: Don't use the string representation to check for equality
183 // spaces inside of the node would break this comparison
184 (Some(vis0), Some(vis1)) => vis0.to_string() == vis1.to_string(),
190 attrs0: impl Iterator<Item = ast::Attr>,
191 attrs1: impl Iterator<Item = ast::Attr>,
193 let attrs0 = attrs0.map(|attr| attr.to_string());
194 let attrs1 = attrs1.map(|attr| attr.to_string());
198 pub fn try_merge_imports(
201 merge_behavior: MergeBehavior,
202 ) -> Option<ast::Use> {
203 // don't merge imports with different visibilities
204 if !eq_visibility(lhs.visibility(), rhs.visibility()) {
207 if !eq_attrs(lhs.attrs(), rhs.attrs()) {
211 let lhs_tree = lhs.use_tree()?;
212 let rhs_tree = rhs.use_tree()?;
213 let merged = try_merge_trees(&lhs_tree, &rhs_tree, merge_behavior)?;
214 Some(lhs.with_use_tree(merged))
217 pub fn try_merge_trees(
220 merge: MergeBehavior,
221 ) -> Option<ast::UseTree> {
222 let lhs_path = lhs.path()?;
223 let rhs_path = rhs.path()?;
225 let (lhs_prefix, rhs_prefix) = common_prefix(&lhs_path, &rhs_path)?;
226 let (lhs, rhs) = if is_simple_path(lhs)
227 && is_simple_path(rhs)
228 && lhs_path == lhs_prefix
229 && rhs_path == rhs_prefix
231 (lhs.clone(), rhs.clone())
233 (lhs.split_prefix(&lhs_prefix), rhs.split_prefix(&rhs_prefix))
235 recursive_merge(&lhs, &rhs, merge)
238 /// Recursively "zips" together lhs and rhs.
242 merge: MergeBehavior,
243 ) -> Option<ast::UseTree> {
244 let mut use_trees = lhs
247 .flat_map(|list| list.use_trees())
248 // we use Option here to early return from this function(this is not the same as a `filter` op)
249 .map(|tree| match merge.is_tree_allowed(&tree) {
253 .collect::<Option<Vec<_>>>()?;
254 use_trees.sort_unstable_by(|a, b| path_cmp_for_sort(a.path(), b.path()));
255 for rhs_t in rhs.use_tree_list().into_iter().flat_map(|list| list.use_trees()) {
256 if !merge.is_tree_allowed(&rhs_t) {
259 let rhs_path = rhs_t.path();
260 match use_trees.binary_search_by(|lhs_t| {
261 let (lhs_t, rhs_t) = match lhs_t
263 .zip(rhs_path.clone())
264 .and_then(|(lhs, rhs)| common_prefix(&lhs, &rhs))
266 Some((lhs_p, rhs_p)) => (lhs_t.split_prefix(&lhs_p), rhs_t.split_prefix(&rhs_p)),
267 None => (lhs_t.clone(), rhs_t.clone()),
270 path_cmp_bin_search(lhs_t.path(), rhs_t.path())
273 let lhs_t = &mut use_trees[idx];
274 let lhs_path = lhs_t.path()?;
275 let rhs_path = rhs_path?;
276 let (lhs_prefix, rhs_prefix) = common_prefix(&lhs_path, &rhs_path)?;
277 if lhs_prefix == lhs_path && rhs_prefix == rhs_path {
278 let tree_is_self = |tree: ast::UseTree| {
279 tree.path().as_ref().map(path_is_self).unwrap_or(false)
281 // check if only one of the two trees has a tree list, and whether that then contains `self` or not.
282 // 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`
283 let tree_contains_self = |tree: &ast::UseTree| {
285 .map(|tree_list| tree_list.use_trees().any(tree_is_self))
288 match (tree_contains_self(&lhs_t), tree_contains_self(&rhs_t)) {
289 (true, false) => continue,
297 // glob imports arent part of the use-tree lists so we need to special handle them here as well
298 // this special handling is only required for when we merge a module import into a glob import of said module
299 // see the `merge_self_glob` or `merge_mod_into_glob` tests
300 if lhs_t.star_token().is_some() || rhs_t.star_token().is_some() {
301 *lhs_t = make::use_tree(
302 make::path_unqualified(make::path_segment_self()),
307 use_trees.insert(idx, make::glob_use_tree());
311 if lhs_t.use_tree_list().is_none() && rhs_t.use_tree_list().is_none() {
315 let lhs = lhs_t.split_prefix(&lhs_prefix);
316 let rhs = rhs_t.split_prefix(&rhs_prefix);
317 match recursive_merge(&lhs, &rhs, merge) {
318 Some(use_tree) => use_trees[idx] = use_tree,
323 if merge == MergeBehavior::Last
324 && use_trees.len() > 0
325 && rhs_t.use_tree_list().is_some() =>
330 use_trees.insert(idx, rhs_t);
334 Some(lhs.with_use_tree_list(make::use_tree_list(use_trees)))
337 /// Traverses both paths until they differ, returning the common prefix of both.
338 fn common_prefix(lhs: &ast::Path, rhs: &ast::Path) -> Option<(ast::Path, ast::Path)> {
340 let mut lhs_curr = first_path(&lhs);
341 let mut rhs_curr = first_path(&rhs);
343 match (lhs_curr.segment(), rhs_curr.segment()) {
344 (Some(lhs), Some(rhs)) if lhs.syntax().text() == rhs.syntax().text() => (),
347 res = Some((lhs_curr.clone(), rhs_curr.clone()));
349 match lhs_curr.parent_path().zip(rhs_curr.parent_path()) {
350 Some((lhs, rhs)) => {
359 fn is_simple_path(use_tree: &ast::UseTree) -> bool {
360 use_tree.use_tree_list().is_none() && use_tree.star_token().is_none()
363 fn path_is_self(path: &ast::Path) -> bool {
364 path.segment().and_then(|seg| seg.self_token()).is_some() && path.qualifier().is_none()
368 fn first_segment(path: &ast::Path) -> Option<ast::PathSegment> {
369 first_path(path).segment()
372 fn first_path(path: &ast::Path) -> ast::Path {
373 successors(Some(path.clone()), ast::Path::qualifier).last().unwrap()
376 fn segment_iter(path: &ast::Path) -> impl Iterator<Item = ast::PathSegment> + Clone {
377 // cant make use of SyntaxNode::siblings, because the returned Iterator is not clone
378 successors(first_segment(path), |p| p.parent_path().parent_path().and_then(|p| p.segment()))
381 fn path_len(path: ast::Path) -> usize {
382 segment_iter(&path).count()
385 /// Orders paths in the following way:
386 /// the sole self token comes first, after that come uppercase identifiers, then lowercase identifiers
387 // FIXME: rustfmt sorts lowercase idents before uppercase, in general we want to have the same ordering rustfmt has
388 // which is `self` and `super` first, then identifier imports with lowercase ones first, then glob imports and at last list imports.
389 // Example foo::{self, foo, baz, Baz, Qux, *, {Bar}}
390 fn path_cmp_for_sort(a: Option<ast::Path>, b: Option<ast::Path>) -> Ordering {
392 (None, None) => Ordering::Equal,
393 (None, Some(_)) => Ordering::Less,
394 (Some(_), None) => Ordering::Greater,
395 (Some(ref a), Some(ref b)) => match (path_is_self(a), path_is_self(b)) {
396 (true, true) => Ordering::Equal,
397 (true, false) => Ordering::Less,
398 (false, true) => Ordering::Greater,
399 (false, false) => path_cmp_short(a, b),
404 /// Path comparison func for binary searching for merging.
405 fn path_cmp_bin_search(lhs: Option<ast::Path>, rhs: Option<ast::Path>) -> Ordering {
406 match (lhs.as_ref().and_then(first_segment), rhs.as_ref().and_then(first_segment)) {
407 (None, None) => Ordering::Equal,
408 (None, Some(_)) => Ordering::Less,
409 (Some(_), None) => Ordering::Greater,
410 (Some(ref a), Some(ref b)) => path_segment_cmp(a, b),
414 /// Short circuiting comparison, if both paths are equal until one of them ends they are considered
416 fn path_cmp_short(a: &ast::Path, b: &ast::Path) -> Ordering {
417 let a = segment_iter(a);
418 let b = segment_iter(b);
419 // cmp_by would be useful for us here but that is currently unstable
420 // cmp doesnt work due the lifetimes on text's return type
422 .find_map(|(a, b)| match path_segment_cmp(&a, &b) {
423 Ordering::Equal => None,
426 .unwrap_or(Ordering::Equal)
429 /// Compares to paths, if one ends earlier than the other the has_tl parameters decide which is
430 /// greater as a a path that has a tree list should be greater, while one that just ends without
431 /// a tree list should be considered less.
432 fn use_tree_path_cmp(a: &ast::Path, a_has_tl: bool, b: &ast::Path, b_has_tl: bool) -> Ordering {
433 let a_segments = segment_iter(a);
434 let b_segments = segment_iter(b);
435 // cmp_by would be useful for us here but that is currently unstable
436 // cmp doesnt work due the lifetimes on text's return type
438 .zip_longest(b_segments)
439 .find_map(|zipped| match zipped {
440 EitherOrBoth::Both(ref a, ref b) => match path_segment_cmp(a, b) {
441 Ordering::Equal => None,
444 EitherOrBoth::Left(_) if !b_has_tl => Some(Ordering::Greater),
445 EitherOrBoth::Left(_) => Some(Ordering::Less),
446 EitherOrBoth::Right(_) if !a_has_tl => Some(Ordering::Less),
447 EitherOrBoth::Right(_) => Some(Ordering::Greater),
449 .unwrap_or(Ordering::Equal)
452 fn path_segment_cmp(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
453 let a = a.kind().and_then(|kind| match kind {
454 PathSegmentKind::Name(name_ref) => Some(name_ref),
457 let b = b.kind().and_then(|kind| match kind {
458 PathSegmentKind::Name(name_ref) => Some(name_ref),
461 a.as_ref().map(ast::NameRef::text).cmp(&b.as_ref().map(ast::NameRef::text))
464 /// What type of merges are allowed.
465 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
466 pub enum MergeBehavior {
467 /// Merge everything together creating deeply nested imports.
469 /// Only merge the last import level, doesn't allow import nesting.
475 fn is_tree_allowed(&self, tree: &ast::UseTree) -> bool {
477 MergeBehavior::Full => true,
478 // only simple single segment paths are allowed
479 MergeBehavior::Last => {
480 tree.use_tree_list().is_none() && tree.path().map(path_len) <= Some(1)
486 #[derive(Eq, PartialEq, PartialOrd, Ord)]
488 // the order here defines the order of new group inserts
497 fn new(path: &ast::Path) -> ImportGroup {
498 let default = ImportGroup::ExternCrate;
500 let first_segment = match first_segment(path) {
502 None => return default,
505 let kind = first_segment.kind().unwrap_or(PathSegmentKind::SelfKw);
507 PathSegmentKind::SelfKw => ImportGroup::ThisModule,
508 PathSegmentKind::SuperKw => ImportGroup::SuperModule,
509 PathSegmentKind::CrateKw => ImportGroup::ThisCrate,
510 PathSegmentKind::Name(name) => match name.text() {
511 "std" => ImportGroup::Std,
512 "core" => ImportGroup::Std,
513 _ => ImportGroup::ExternCrate,
515 PathSegmentKind::Type { .. } => unreachable!(),
520 #[derive(PartialEq, Eq)]
530 fn has_before(&self) -> bool {
531 matches!(self, AddBlankLine::Before | AddBlankLine::BeforeTwice | AddBlankLine::Around)
533 fn has_after(&self) -> bool {
534 matches!(self, AddBlankLine::After | AddBlankLine::AfterTwice | AddBlankLine::Around)
538 fn find_insert_position(
540 insert_path: ast::Path,
541 ) -> (InsertPosition<SyntaxElement>, AddBlankLine) {
542 let group = ImportGroup::new(&insert_path);
543 let path_node_iter = scope
546 .filter_map(|node| ast::Use::cast(node.clone()).zip(Some(node)))
547 .flat_map(|(use_, node)| {
548 let tree = use_.use_tree()?;
549 let path = tree.path()?;
550 let has_tl = tree.use_tree_list().is_some();
551 Some((path, has_tl, node))
553 // Iterator that discards anything thats not in the required grouping
554 // This implementation allows the user to rearrange their import groups as this only takes the first group that fits
555 let group_iter = path_node_iter
557 .skip_while(|(path, ..)| ImportGroup::new(path) != group)
558 .take_while(|(path, ..)| ImportGroup::new(path) == group);
560 // 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
562 // find the element that would come directly after our new import
563 let post_insert = group_iter.inspect(|(.., node)| last = Some(node.clone())).find(
564 |&(ref path, has_tl, _)| {
565 use_tree_path_cmp(&insert_path, false, path, has_tl) != Ordering::Greater
569 // insert our import before that element
570 Some((.., node)) => (InsertPosition::Before(node.into()), AddBlankLine::After),
571 // there is no element after our new import, so append it to the end of the group
573 Some(node) => (InsertPosition::After(node.into()), AddBlankLine::Before),
574 // the group we were looking for actually doesnt exist, so insert
576 // similar concept here to the `last` from above
578 // find the group that comes after where we want to insert
579 let post_group = path_node_iter
580 .inspect(|(.., node)| last = Some(node.clone()))
581 .find(|(p, ..)| ImportGroup::new(p) > group);
583 Some((.., node)) => {
584 (InsertPosition::Before(node.into()), AddBlankLine::AfterTwice)
586 // there is no such group, so append after the last one
589 (InsertPosition::After(node.into()), AddBlankLine::BeforeTwice)
591 // there are no imports in this file at all
592 None => scope.insert_pos_after_last_inner_element(),