rust/crates/ra_assists/src/handlers/split_import.rs

72 lines
1.8 KiB
Rust
Raw Normal View History

use std::iter::successors;
use ra_syntax::{ast, AstNode, T};
2019-01-05 04:45:18 -06:00
use crate::{AssistContext, AssistId, Assists};
2019-01-05 04:45:18 -06:00
2019-10-27 04:22:53 -05:00
// Assist: split_import
//
// Wraps the tail of import into braces.
//
// ```
// use std::<|>collections::HashMap;
// ```
// ->
// ```
// use std::{collections::HashMap};
// ```
pub(crate) fn split_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
let colon_colon = ctx.find_token_at_offset(T![::])?;
let path = ast::Path::cast(colon_colon.parent())?.qualifier()?;
let top_path = successors(Some(path.clone()), |it| it.parent_path()).last()?;
2019-01-05 04:45:18 -06:00
let use_tree = top_path.syntax().ancestors().find_map(ast::UseTree::cast)?;
2019-01-05 04:45:18 -06:00
let new_tree = use_tree.split_prefix(&path);
if new_tree == use_tree {
return None;
}
2020-05-07 10:32:01 -05:00
let cursor = ctx.offset();
2019-01-05 04:45:18 -06:00
let target = colon_colon.text_range();
acc.add(AssistId("split_import"), "Split import", target, |edit| {
edit.replace_ast(use_tree, new_tree);
edit.set_cursor(cursor);
})
2019-01-05 04:45:18 -06:00
}
#[cfg(test)]
mod tests {
2020-05-06 03:16:55 -05:00
use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
2019-01-05 04:45:18 -06:00
use super::*;
2019-01-05 04:45:18 -06:00
#[test]
fn test_split_import() {
check_assist(
split_import,
"use crate::<|>db::RootDatabase;",
"use crate::<|>{db::RootDatabase};",
2019-01-05 04:45:18 -06:00
)
}
#[test]
fn split_import_works_with_trees() {
check_assist(
split_import,
2019-10-05 09:48:31 -05:00
"use crate:<|>:db::{RootDatabase, FileSymbol}",
"use crate:<|>:{db::{RootDatabase, FileSymbol}}",
)
}
2019-02-08 17:34:05 -06:00
#[test]
fn split_import_target() {
2019-10-05 09:48:31 -05:00
check_assist_target(split_import, "use crate::<|>db::{RootDatabase, FileSymbol}", "::");
2019-02-08 17:34:05 -06:00
}
#[test]
fn issue4044() {
check_assist_not_applicable(split_import, "use crate::<|>:::self;")
}
2019-01-05 04:45:18 -06:00
}