rust/crates/ra_assists/src/split_import.rs

58 lines
1.5 KiB
Rust
Raw Normal View History

2019-02-03 19:26:35 +01:00
use hir::db::HirDatabase;
2019-01-05 11:45:18 +01:00
use ra_syntax::{
TextUnit, AstNode, SyntaxKind::COLONCOLON,
ast,
algo::generate,
};
2019-02-03 19:26:35 +01:00
use crate::{AssistCtx, Assist};
2019-01-05 11:45:18 +01:00
2019-02-03 19:26:35 +01:00
pub(crate) fn split_import(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
2019-01-05 11:45:18 +01:00
let colon_colon = ctx
.leaf_at_offset()
.find(|leaf| leaf.kind() == COLONCOLON)?;
let path = colon_colon.parent().and_then(ast::Path::cast)?;
let top_path = generate(Some(path), |it| it.parent_path()).last()?;
let use_tree = top_path.syntax().ancestors().find_map(ast::UseTree::cast);
if use_tree.is_none() {
return None;
}
let l_curly = colon_colon.range().end();
let r_curly = match top_path.syntax().parent().and_then(ast::UseTree::cast) {
Some(tree) => tree.syntax().range().end(),
None => top_path.syntax().range().end(),
};
2019-01-05 11:45:18 +01:00
ctx.build("split import", |edit| {
edit.insert(l_curly, "{");
edit.insert(r_curly, "}");
edit.set_cursor(l_curly + TextUnit::of_str("{"));
})
}
#[cfg(test)]
mod tests {
use super::*;
2019-02-03 19:26:35 +01:00
use crate::helpers::check_assist;
2019-01-05 11:45:18 +01:00
#[test]
fn test_split_import() {
check_assist(
split_import,
"use crate::<|>db::RootDatabase;",
"use crate::{<|>db::RootDatabase};",
)
}
#[test]
fn split_import_works_with_trees() {
check_assist(
split_import,
"use algo:<|>:visitor::{Visitor, visit}",
"use algo::{<|>visitor::{Visitor, visit}}",
)
}
2019-01-05 11:45:18 +01:00
}