Skip to content

Commit 1a4faaf

Browse files
committed
auto_import: use ra_fmt
1 parent ee9b0c8 commit 1a4faaf

File tree

1 file changed

+29
-109
lines changed

1 file changed

+29
-109
lines changed

crates/ra_assists/src/auto_import.rs

+29-109
Original file line numberDiff line numberDiff line change
@@ -5,42 +5,6 @@ use ra_syntax::{
55
};
66
use crate::assist_ctx::{AssistCtx, Assist, AssistBuilder};
77

8-
// TODO: refactor this before merge
9-
mod formatting {
10-
use ra_syntax::{
11-
AstNode, SyntaxNode,
12-
ast::{self, AstToken},
13-
algo::generate,
14-
};
15-
16-
/// If the node is on the beginning of the line, calculate indent.
17-
pub fn leading_indent(node: &SyntaxNode) -> Option<&str> {
18-
for leaf in prev_leaves(node) {
19-
if let Some(ws) = ast::Whitespace::cast(leaf) {
20-
let ws_text = ws.text();
21-
if let Some(pos) = ws_text.rfind('\n') {
22-
return Some(&ws_text[pos + 1..]);
23-
}
24-
}
25-
if leaf.leaf_text().unwrap().contains('\n') {
26-
break;
27-
}
28-
}
29-
None
30-
}
31-
32-
fn prev_leaves(node: &SyntaxNode) -> impl Iterator<Item = &SyntaxNode> {
33-
generate(prev_leaf(node), |&node| prev_leaf(node))
34-
}
35-
36-
fn prev_leaf(node: &SyntaxNode) -> Option<&SyntaxNode> {
37-
generate(node.ancestors().find_map(SyntaxNode::prev_sibling), |it| {
38-
it.last_child()
39-
})
40-
.last()
41-
}
42-
}
43-
448
fn collect_path_segments(path: &ast::Path) -> Option<Vec<&ast::PathSegment>> {
459
let mut v = Vec::new();
4610
collect_path_segments_raw(&mut v, path)?;
@@ -102,11 +66,7 @@ fn fmt_segments_raw(segments: &[&ast::PathSegment], buf: &mut String) {
10266

10367
// Returns the numeber of common segments.
10468
fn compare_path_segments(left: &[&ast::PathSegment], right: &[&ast::PathSegment]) -> usize {
105-
return left
106-
.iter()
107-
.zip(right)
108-
.filter(|(l, r)| compare_path_segment(l, r))
109-
.count();
69+
return left.iter().zip(right).filter(|(l, r)| compare_path_segment(l, r)).count();
11070
}
11171

11272
fn compare_path_segment(a: &ast::PathSegment, b: &ast::PathSegment) -> bool {
@@ -166,10 +126,7 @@ enum ImportAction<'a> {
166126

167127
impl<'a> ImportAction<'a> {
168128
fn add_new_use(anchor: Option<&'a SyntaxNode>, add_after_anchor: bool) -> Self {
169-
ImportAction::AddNewUse {
170-
anchor,
171-
add_after_anchor,
172-
}
129+
ImportAction::AddNewUse { anchor, add_after_anchor }
173130
}
174131

175132
fn add_nested_import(
@@ -191,11 +148,7 @@ impl<'a> ImportAction<'a> {
191148
tree_list: &'a ast::UseTreeList,
192149
add_self: bool,
193150
) -> Self {
194-
ImportAction::AddInTreeList {
195-
common_segments,
196-
tree_list,
197-
add_self,
198-
}
151+
ImportAction::AddInTreeList { common_segments, tree_list, add_self }
199152
}
200153

201154
fn better<'b>(left: &'b ImportAction<'a>, right: &'b ImportAction<'a>) -> &'b ImportAction<'a> {
@@ -211,20 +164,12 @@ impl<'a> ImportAction<'a> {
211164
(ImportAction::Nothing, _) => true,
212165
(ImportAction::AddInTreeList { .. }, ImportAction::Nothing) => false,
213166
(
214-
ImportAction::AddNestedImport {
215-
common_segments: n, ..
216-
},
217-
ImportAction::AddInTreeList {
218-
common_segments: m, ..
219-
},
167+
ImportAction::AddNestedImport { common_segments: n, .. },
168+
ImportAction::AddInTreeList { common_segments: m, .. },
220169
) => n > m,
221170
(
222-
ImportAction::AddInTreeList {
223-
common_segments: n, ..
224-
},
225-
ImportAction::AddNestedImport {
226-
common_segments: m, ..
227-
},
171+
ImportAction::AddInTreeList { common_segments: n, .. },
172+
ImportAction::AddNestedImport { common_segments: m, .. },
228173
) => n > m,
229174
(ImportAction::AddInTreeList { .. }, _) => true,
230175
(ImportAction::AddNestedImport { .. }, ImportAction::Nothing) => false,
@@ -283,11 +228,7 @@ fn walk_use_tree_for_best_action<'a>(
283228
// e.g: target is std::fmt and we can have
284229
// use foo::bar
285230
// We add a brand new use statement
286-
current_use_tree
287-
.syntax()
288-
.ancestors()
289-
.find_map(ast::UseItem::cast)
290-
.map(AstNode::syntax),
231+
current_use_tree.syntax().ancestors().find_map(ast::UseItem::cast).map(AstNode::syntax),
291232
true,
292233
),
293234
common if common == left.len() && left.len() == right.len() => {
@@ -398,8 +339,7 @@ fn best_action_for_target<'b, 'a: 'b>(
398339
.filter_map(ast::UseItem::use_tree)
399340
.map(|u| walk_use_tree_for_best_action(&mut storage, None, u, target))
400341
.fold(None, |best, a| {
401-
best.and_then(|best| Some(*ImportAction::better(&best, &a)))
402-
.or(Some(a))
342+
best.and_then(|best| Some(*ImportAction::better(&best, &a))).or(Some(a))
403343
});
404344

405345
match best_action {
@@ -421,15 +361,10 @@ fn best_action_for_target<'b, 'a: 'b>(
421361

422362
fn make_assist(action: &ImportAction, target: &[&ast::PathSegment], edit: &mut AssistBuilder) {
423363
match action {
424-
ImportAction::AddNewUse {
425-
anchor,
426-
add_after_anchor,
427-
} => make_assist_add_new_use(anchor, *add_after_anchor, target, edit),
428-
ImportAction::AddInTreeList {
429-
common_segments,
430-
tree_list,
431-
add_self,
432-
} => {
364+
ImportAction::AddNewUse { anchor, add_after_anchor } => {
365+
make_assist_add_new_use(anchor, *add_after_anchor, target, edit)
366+
}
367+
ImportAction::AddInTreeList { common_segments, tree_list, add_self } => {
433368
// We know that the fist n segments already exists in the use statement we want
434369
// to modify, so we want to add only the last target.len() - n segments.
435370
let segments_to_add = target.split_at(*common_segments).1;
@@ -461,7 +396,7 @@ fn make_assist_add_new_use(
461396
edit: &mut AssistBuilder,
462397
) {
463398
if let Some(anchor) = anchor {
464-
let indent = formatting::leading_indent(anchor);
399+
let indent = ra_fmt::leading_indent(anchor);
465400
let mut buf = String::new();
466401
if after {
467402
buf.push_str("\n");
@@ -478,11 +413,7 @@ fn make_assist_add_new_use(
478413
buf.push_str(spaces);
479414
}
480415
}
481-
let position = if after {
482-
anchor.range().end()
483-
} else {
484-
anchor.range().start()
485-
};
416+
let position = if after { anchor.range().end() } else { anchor.range().start() };
486417
edit.insert(position, buf);
487418
}
488419
}
@@ -496,10 +427,7 @@ fn make_assist_add_in_tree_list(
496427
let last = tree_list.use_trees().last();
497428
if let Some(last) = last {
498429
let mut buf = String::new();
499-
let comma = last
500-
.syntax()
501-
.siblings(Direction::Next)
502-
.find(|n| n.kind() == COMMA);
430+
let comma = last.syntax().siblings(Direction::Next).find(|n| n.kind() == COMMA);
503431
let offset = if let Some(comma) = comma {
504432
comma.range().end()
505433
} else {
@@ -558,12 +486,7 @@ pub(crate) fn auto_import(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
558486

559487
let path = node.ancestors().find_map(ast::Path::cast)?;
560488
// We don't want to mess with use statements
561-
if path
562-
.syntax()
563-
.ancestors()
564-
.find_map(ast::UseItem::cast)
565-
.is_some()
566-
{
489+
if path.syntax().ancestors().find_map(ast::UseItem::cast).is_some() {
567490
return None;
568491
}
569492

@@ -572,21 +495,18 @@ pub(crate) fn auto_import(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
572495
return None;
573496
}
574497

575-
ctx.build(
576-
format!("import {} in the current file", fmt_segments(&segments)),
577-
|edit| {
578-
let action = best_action_for_target(current_file.syntax(), path, &segments);
579-
make_assist(&action, segments.as_slice(), edit);
580-
if let Some(last_segment) = path.segment() {
581-
// Here we are assuming the assist will provide a correct use statement
582-
// so we can delete the path qualifier
583-
edit.delete(TextRange::from_to(
584-
path.syntax().range().start(),
585-
last_segment.syntax().range().start(),
586-
));
587-
}
588-
},
589-
)
498+
ctx.build(format!("import {} in the current file", fmt_segments(&segments)), |edit| {
499+
let action = best_action_for_target(current_file.syntax(), path, &segments);
500+
make_assist(&action, segments.as_slice(), edit);
501+
if let Some(last_segment) = path.segment() {
502+
// Here we are assuming the assist will provide a correct use statement
503+
// so we can delete the path qualifier
504+
edit.delete(TextRange::from_to(
505+
path.syntax().range().start(),
506+
last_segment.syntax().range().start(),
507+
));
508+
}
509+
})
590510
}
591511

592512
#[cfg(test)]

0 commit comments

Comments
 (0)