rust-analyzer/crates/ide-assists/src/handlers/split_import.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

83 lines
2.1 KiB
Rust
Raw Normal View History

2020-08-12 16:26:51 +00:00
use syntax::{ast, AstNode, T};
2019-01-05 10:45:18 +00:00
2020-06-28 22:36:05 +00:00
use crate::{AssistContext, AssistId, AssistKind, Assists};
2019-01-05 10:45:18 +00:00
2019-10-27 09:22:53 +00:00
// Assist: split_import
//
// Wraps the tail of import into braces.
//
// ```
2021-01-06 20:15:48 +00:00
// use std::$0collections::HashMap;
2019-10-27 09:22:53 +00:00
// ```
// ->
// ```
// use std::{collections::HashMap};
// ```
2022-07-20 13:02:08 +00:00
pub(crate) fn split_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
let colon_colon = ctx.find_token_syntax_at_offset(T![::])?;
let path = ast::Path::cast(colon_colon.parent()?)?.qualifier()?;
2019-01-05 10:45:18 +00:00
let use_tree = path.top_path().syntax().ancestors().find_map(ast::UseTree::cast)?;
2019-01-05 10:45:18 +00:00
let has_errors = use_tree
.syntax()
.descendants_with_tokens()
.any(|it| it.kind() == syntax::SyntaxKind::ERROR);
let last_segment = use_tree.path().and_then(|it| it.segment());
if has_errors || last_segment.is_none() {
return None;
}
2019-01-05 10:45:18 +00:00
let target = colon_colon.text_range();
2020-07-02 21:48:35 +00:00
acc.add(AssistId("split_import", AssistKind::RefactorRewrite), "Split import", target, |edit| {
let use_tree = edit.make_mut(use_tree.clone());
let path = edit.make_mut(path);
use_tree.split_prefix(&path);
})
2019-01-05 10:45:18 +00:00
}
#[cfg(test)]
mod tests {
2020-05-06 08:16:55 +00:00
use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
2019-01-05 10:45:18 +00:00
use super::*;
2019-01-05 10:45:18 +00:00
#[test]
fn test_split_import() {
check_assist(
split_import,
2021-01-06 20:15:48 +00:00
"use crate::$0db::RootDatabase;",
2020-05-20 21:50:29 +00:00
"use crate::{db::RootDatabase};",
2019-01-05 10:45:18 +00:00
)
}
#[test]
fn split_import_works_with_trees() {
check_assist(
split_import,
2021-01-06 20:15:48 +00:00
"use crate:$0:db::{RootDatabase, FileSymbol}",
2020-05-20 21:50:29 +00:00
"use crate::{db::{RootDatabase, FileSymbol}}",
)
}
2019-02-08 23:34:05 +00:00
#[test]
fn split_import_target() {
2021-01-06 20:15:48 +00:00
check_assist_target(split_import, "use crate::$0db::{RootDatabase, FileSymbol}", "::");
2019-02-08 23:34:05 +00:00
}
#[test]
fn issue4044() {
2021-01-06 20:15:48 +00:00
check_assist_not_applicable(split_import, "use crate::$0:::self;")
}
#[test]
fn test_empty_use() {
check_assist_not_applicable(
split_import,
r"
2021-01-06 20:15:48 +00:00
use std::$0
fn main() {}",
);
}
2019-01-05 10:45:18 +00:00
}