]> git.lizzy.rs Git - rust.git/blob - crates/ide_db/src/helpers/insert_use.rs
Merge #7353
[rust.git] / crates / ide_db / src / helpers / insert_use.rs
1 //! Handle syntactic aspects of inserting a new `use`.
2 use std::{cmp::Ordering, iter::successors};
3
4 use crate::RootDatabase;
5 use hir::Semantics;
6 use itertools::{EitherOrBoth, Itertools};
7 use syntax::{
8     algo::SyntaxRewriter,
9     ast::{
10         self,
11         edit::{AstNodeEdit, IndentLevel},
12         make, AstNode, AttrsOwner, PathSegmentKind, VisibilityOwner,
13     },
14     AstToken, InsertPosition, NodeOrToken, SyntaxElement, SyntaxNode, SyntaxToken,
15 };
16 use test_utils::mark;
17
18 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
19 pub struct InsertUseConfig {
20     pub merge: Option<MergeBehavior>,
21     pub prefix_kind: hir::PrefixKind,
22 }
23
24 #[derive(Debug, Clone)]
25 pub enum ImportScope {
26     File(ast::SourceFile),
27     Module(ast::ItemList),
28 }
29
30 impl ImportScope {
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)
36         } else {
37             ast::ItemList::cast(syntax).map(ImportScope::Module)
38         }
39     }
40
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>,
45     ) -> Option<Self> {
46         sema.ancestors_with_macros(position.clone()).find_map(Self::from)
47     }
48
49     pub fn as_syntax_node(&self) -> &SyntaxNode {
50         match self {
51             ImportScope::File(file) => file.syntax(),
52             ImportScope::Module(item_list) => item_list.syntax(),
53         }
54     }
55
56     fn indent_level(&self) -> IndentLevel {
57         match self {
58             ImportScope::File(file) => file.indent_level(),
59             ImportScope::Module(item_list) => item_list.indent_level() + 1,
60         }
61     }
62
63     fn first_insert_pos(&self) -> (InsertPosition<SyntaxElement>, AddBlankLine) {
64         match self {
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
68                 .l_curly_token()
69                 .map(|b| (InsertPosition::After(b.into()), AddBlankLine::Around))
70                 .unwrap_or((InsertPosition::First, AddBlankLine::AfterTwice)),
71         }
72     }
73
74     fn insert_pos_after_last_inner_element(&self) -> (InsertPosition<SyntaxElement>, AddBlankLine) {
75         self.as_syntax_node()
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()),
80             })
81             .last()
82             .map(|last_inner_element| {
83                 (InsertPosition::After(last_inner_element.into()), AddBlankLine::BeforeTwice)
84             })
85             .unwrap_or_else(|| self.first_insert_pos())
86     }
87 }
88
89 fn is_inner_attribute(node: SyntaxNode) -> bool {
90     ast::Attr::cast(node).map(|attr| attr.kind()) == Some(ast::AttrKind::Inner)
91 }
92
93 fn is_inner_comment(token: SyntaxToken) -> bool {
94     ast::Comment::cast(token).and_then(|comment| comment.kind().doc)
95         == Some(ast::CommentPlacement::Inner)
96 }
97
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>(
100     scope: &ImportScope,
101     path: ast::Path,
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());
112                 return rewriter;
113             }
114         }
115     }
116
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);
120
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())
123     } else {
124         None
125     };
126
127     let to_insert: Vec<SyntaxElement> = {
128         let mut buf = Vec::new();
129
130         match add_blank {
131             AddBlankLine::Before | AddBlankLine::Around => {
132                 buf.push(make::tokens::single_newline().into())
133             }
134             AddBlankLine::BeforeTwice => buf.push(make::tokens::blank_line().into()),
135             _ => (),
136         }
137
138         if add_blank.has_before() {
139             if let Some(indent) = indent.clone() {
140                 mark::hit!(insert_use_indent_before);
141                 buf.push(indent);
142             }
143         }
144
145         buf.push(use_item.syntax().clone().into());
146
147         match add_blank {
148             AddBlankLine::After | AddBlankLine::Around => {
149                 buf.push(make::tokens::single_newline().into())
150             }
151             AddBlankLine::AfterTwice => buf.push(make::tokens::blank_line().into()),
152             _ => (),
153         }
154
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);
159                 buf.push(indent);
160             }
161         } else if add_blank.has_after() && matches!(insert_position, InsertPosition::After(_)) {
162             mark::hit!(insert_use_no_indent_after);
163         }
164
165         buf
166     };
167
168     match insert_position {
169         InsertPosition::First => {
170             rewriter.insert_many_as_first_children(scope.as_syntax_node(), to_insert)
171         }
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),
175     }
176     rewriter
177 }
178
179 fn eq_visibility(vis0: Option<ast::Visibility>, vis1: Option<ast::Visibility>) -> bool {
180     match (vis0, vis1) {
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(),
185         _ => false,
186     }
187 }
188
189 fn eq_attrs(
190     attrs0: impl Iterator<Item = ast::Attr>,
191     attrs1: impl Iterator<Item = ast::Attr>,
192 ) -> bool {
193     let attrs0 = attrs0.map(|attr| attr.to_string());
194     let attrs1 = attrs1.map(|attr| attr.to_string());
195     attrs0.eq(attrs1)
196 }
197
198 pub fn try_merge_imports(
199     lhs: &ast::Use,
200     rhs: &ast::Use,
201     merge_behavior: MergeBehavior,
202 ) -> Option<ast::Use> {
203     // don't merge imports with different visibilities
204     if !eq_visibility(lhs.visibility(), rhs.visibility()) {
205         return None;
206     }
207     if !eq_attrs(lhs.attrs(), rhs.attrs()) {
208         return None;
209     }
210
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))
215 }
216
217 pub fn try_merge_trees(
218     lhs: &ast::UseTree,
219     rhs: &ast::UseTree,
220     merge: MergeBehavior,
221 ) -> Option<ast::UseTree> {
222     let lhs_path = lhs.path()?;
223     let rhs_path = rhs.path()?;
224
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
230     {
231         (lhs.clone(), rhs.clone())
232     } else {
233         (lhs.split_prefix(&lhs_prefix), rhs.split_prefix(&rhs_prefix))
234     };
235     recursive_merge(&lhs, &rhs, merge)
236 }
237
238 /// Recursively "zips" together lhs and rhs.
239 fn recursive_merge(
240     lhs: &ast::UseTree,
241     rhs: &ast::UseTree,
242     merge: MergeBehavior,
243 ) -> Option<ast::UseTree> {
244     let mut use_trees = lhs
245         .use_tree_list()
246         .into_iter()
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) {
250             true => Some(tree),
251             false => None,
252         })
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) {
257             return None;
258         }
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
262                 .path()
263                 .zip(rhs_path.clone())
264                 .and_then(|(lhs, rhs)| common_prefix(&lhs, &rhs))
265             {
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()),
268             };
269
270             path_cmp_bin_search(lhs_t.path(), rhs_t.path())
271         }) {
272             Ok(idx) => {
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)
280                     };
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| {
284                         tree.use_tree_list()
285                             .map(|tree_list| tree_list.use_trees().any(tree_is_self))
286                             .unwrap_or(false)
287                     };
288                     match (tree_contains_self(&lhs_t), tree_contains_self(&rhs_t)) {
289                         (true, false) => continue,
290                         (false, true) => {
291                             *lhs_t = rhs_t;
292                             continue;
293                         }
294                         _ => (),
295                     }
296
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()),
303                             None,
304                             None,
305                             false,
306                         );
307                         use_trees.insert(idx, make::glob_use_tree());
308                         continue;
309                     }
310
311                     if lhs_t.use_tree_list().is_none() && rhs_t.use_tree_list().is_none() {
312                         continue;
313                     }
314                 }
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,
319                     None => return None,
320                 }
321             }
322             Err(_)
323                 if merge == MergeBehavior::Last
324                     && use_trees.len() > 0
325                     && rhs_t.use_tree_list().is_some() =>
326             {
327                 return None
328             }
329             Err(idx) => {
330                 use_trees.insert(idx, rhs_t);
331             }
332         }
333     }
334     Some(lhs.with_use_tree_list(make::use_tree_list(use_trees)))
335 }
336
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)> {
339     let mut res = None;
340     let mut lhs_curr = first_path(&lhs);
341     let mut rhs_curr = first_path(&rhs);
342     loop {
343         match (lhs_curr.segment(), rhs_curr.segment()) {
344             (Some(lhs), Some(rhs)) if lhs.syntax().text() == rhs.syntax().text() => (),
345             _ => break res,
346         }
347         res = Some((lhs_curr.clone(), rhs_curr.clone()));
348
349         match lhs_curr.parent_path().zip(rhs_curr.parent_path()) {
350             Some((lhs, rhs)) => {
351                 lhs_curr = lhs;
352                 rhs_curr = rhs;
353             }
354             _ => break res,
355         }
356     }
357 }
358
359 fn is_simple_path(use_tree: &ast::UseTree) -> bool {
360     use_tree.use_tree_list().is_none() && use_tree.star_token().is_none()
361 }
362
363 fn path_is_self(path: &ast::Path) -> bool {
364     path.segment().and_then(|seg| seg.self_token()).is_some() && path.qualifier().is_none()
365 }
366
367 #[inline]
368 fn first_segment(path: &ast::Path) -> Option<ast::PathSegment> {
369     first_path(path).segment()
370 }
371
372 fn first_path(path: &ast::Path) -> ast::Path {
373     successors(Some(path.clone()), ast::Path::qualifier).last().unwrap()
374 }
375
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()))
379 }
380
381 fn path_len(path: ast::Path) -> usize {
382     segment_iter(&path).count()
383 }
384
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 {
391     match (a, b) {
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),
400         },
401     }
402 }
403
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),
411     }
412 }
413
414 /// Short circuiting comparison, if both paths are equal until one of them ends they are considered
415 /// equal
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
421     a.zip(b)
422         .find_map(|(a, b)| match path_segment_cmp(&a, &b) {
423             Ordering::Equal => None,
424             ord => Some(ord),
425         })
426         .unwrap_or(Ordering::Equal)
427 }
428
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
437     a_segments
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,
442                 ord => Some(ord),
443             },
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),
448         })
449         .unwrap_or(Ordering::Equal)
450 }
451
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),
455         _ => None,
456     });
457     let b = b.kind().and_then(|kind| match kind {
458         PathSegmentKind::Name(name_ref) => Some(name_ref),
459         _ => None,
460     });
461     a.as_ref().map(ast::NameRef::text).cmp(&b.as_ref().map(ast::NameRef::text))
462 }
463
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.
468     Full,
469     /// Only merge the last import level, doesn't allow import nesting.
470     Last,
471 }
472
473 impl MergeBehavior {
474     #[inline]
475     fn is_tree_allowed(&self, tree: &ast::UseTree) -> bool {
476         match self {
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)
481             }
482         }
483     }
484 }
485
486 #[derive(Eq, PartialEq, PartialOrd, Ord)]
487 enum ImportGroup {
488     // the order here defines the order of new group inserts
489     Std,
490     ExternCrate,
491     ThisCrate,
492     ThisModule,
493     SuperModule,
494 }
495
496 impl ImportGroup {
497     fn new(path: &ast::Path) -> ImportGroup {
498         let default = ImportGroup::ExternCrate;
499
500         let first_segment = match first_segment(path) {
501             Some(it) => it,
502             None => return default,
503         };
504
505         let kind = first_segment.kind().unwrap_or(PathSegmentKind::SelfKw);
506         match kind {
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,
514             },
515             PathSegmentKind::Type { .. } => unreachable!(),
516         }
517     }
518 }
519
520 #[derive(PartialEq, Eq)]
521 enum AddBlankLine {
522     Before,
523     BeforeTwice,
524     Around,
525     After,
526     AfterTwice,
527 }
528
529 impl AddBlankLine {
530     fn has_before(&self) -> bool {
531         matches!(self, AddBlankLine::Before | AddBlankLine::BeforeTwice | AddBlankLine::Around)
532     }
533     fn has_after(&self) -> bool {
534         matches!(self, AddBlankLine::After | AddBlankLine::AfterTwice | AddBlankLine::Around)
535     }
536 }
537
538 fn find_insert_position(
539     scope: &ImportScope,
540     insert_path: ast::Path,
541 ) -> (InsertPosition<SyntaxElement>, AddBlankLine) {
542     let group = ImportGroup::new(&insert_path);
543     let path_node_iter = scope
544         .as_syntax_node()
545         .children()
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))
552         });
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
556         .clone()
557         .skip_while(|(path, ..)| ImportGroup::new(path) != group)
558         .take_while(|(path, ..)| ImportGroup::new(path) == group);
559
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
561     let mut last = None;
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
566         },
567     );
568     match post_insert {
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
572         None => match last {
573             Some(node) => (InsertPosition::After(node.into()), AddBlankLine::Before),
574             // the group we were looking for actually doesnt exist, so insert
575             None => {
576                 // similar concept here to the `last` from above
577                 let mut last = None;
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);
582                 match post_group {
583                     Some((.., node)) => {
584                         (InsertPosition::Before(node.into()), AddBlankLine::AfterTwice)
585                     }
586                     // there is no such group, so append after the last one
587                     None => match last {
588                         Some(node) => {
589                             (InsertPosition::After(node.into()), AddBlankLine::BeforeTwice)
590                         }
591                         // there are no imports in this file at all
592                         None => scope.insert_pos_after_last_inner_element(),
593                     },
594                 }
595             }
596         },
597     }
598 }
599
600 #[cfg(test)]
601 mod tests;