Rerail split_import API onto AST

The code is more verbose and less efficient now, but should be
reusable in add_import context as well
This commit is contained in:
Aleksey Kladov 2020-03-05 19:03:14 +01:00
parent d75577fcee
commit ea0c124219
3 changed files with 72 additions and 19 deletions

View file

@ -1,6 +1,9 @@
use std::iter::successors; use std::iter::{once, successors};
use ra_syntax::{ast, AstNode, TextUnit, T}; use ra_syntax::{
ast::{self, make},
AstNode, T,
};
use crate::{Assist, AssistCtx, AssistId}; use crate::{Assist, AssistCtx, AssistId};
@ -17,39 +20,50 @@ use crate::{Assist, AssistCtx, AssistId};
// ``` // ```
pub(crate) fn split_import(ctx: AssistCtx) -> Option<Assist> { pub(crate) fn split_import(ctx: AssistCtx) -> Option<Assist> {
let colon_colon = ctx.find_token_at_offset(T![::])?; let colon_colon = ctx.find_token_at_offset(T![::])?;
let path = ast::Path::cast(colon_colon.parent())?; let path = ast::Path::cast(colon_colon.parent())?.qualifier()?;
let top_path = successors(Some(path), |it| it.parent_path()).last()?; let top_path = successors(Some(path.clone()), |it| it.parent_path()).last()?;
let use_tree = top_path.syntax().ancestors().find_map(ast::UseTree::cast); let use_tree = top_path.syntax().ancestors().find_map(ast::UseTree::cast)?;
if use_tree.is_none() {
return None;
}
let l_curly = colon_colon.text_range().end(); let new_tree = split_use_tree_prefix(&use_tree, &path)?;
let r_curly = match top_path.syntax().parent().and_then(ast::UseTree::cast) { let cursor = ctx.frange.range.start();
Some(tree) => tree.syntax().text_range().end(),
None => top_path.syntax().text_range().end(),
};
ctx.add_assist(AssistId("split_import"), "Split import", |edit| { ctx.add_assist(AssistId("split_import"), "Split import", |edit| {
edit.target(colon_colon.text_range()); edit.target(colon_colon.text_range());
edit.insert(l_curly, "{"); edit.replace_ast(use_tree, new_tree);
edit.insert(r_curly, "}"); edit.set_cursor(cursor);
edit.set_cursor(l_curly + TextUnit::of_str("{"));
}) })
} }
fn split_use_tree_prefix(use_tree: &ast::UseTree, prefix: &ast::Path) -> Option<ast::UseTree> {
let suffix = split_path_prefix(&prefix)?;
let use_tree = make::use_tree(suffix.clone(), use_tree.use_tree_list(), use_tree.alias());
let nested = make::use_tree_list(once(use_tree));
let res = make::use_tree(prefix.clone(), Some(nested), None);
Some(res)
}
fn split_path_prefix(prefix: &ast::Path) -> Option<ast::Path> {
let parent = prefix.parent_path()?;
let mut res = make::path_unqualified(parent.segment()?);
for p in successors(parent.parent_path(), |it| it.parent_path()) {
res = make::path_qualified(res, p.segment()?);
}
Some(res)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use crate::helpers::{check_assist, check_assist_target}; use crate::helpers::{check_assist, check_assist_target};
use super::*;
#[test] #[test]
fn test_split_import() { fn test_split_import() {
check_assist( check_assist(
split_import, split_import,
"use crate::<|>db::RootDatabase;", "use crate::<|>db::RootDatabase;",
"use crate::{<|>db::RootDatabase};", "use crate::<|>{db::RootDatabase};",
) )
} }
@ -58,7 +72,7 @@ mod tests {
check_assist( check_assist(
split_import, split_import,
"use crate:<|>:db::{RootDatabase, FileSymbol}", "use crate:<|>:db::{RootDatabase, FileSymbol}",
"use crate::{<|>db::{RootDatabase, FileSymbol}}", "use crate:<|>:{db::{RootDatabase, FileSymbol}}",
) )
} }

View file

@ -259,6 +259,24 @@ impl ast::UseItem {
} }
} }
impl ast::UseTree {
#[must_use]
pub fn with_path(&self, path: ast::Path) -> ast::UseTree {
if let Some(old) = self.path() {
return replace_descendants(self, iter::once((old, path)));
}
self.clone()
}
#[must_use]
pub fn with_use_tree_list(&self, use_tree_list: ast::UseTreeList) -> ast::UseTree {
if let Some(old) = self.use_tree_list() {
return replace_descendants(self, iter::once((old, use_tree_list)));
}
self.clone()
}
}
#[must_use] #[must_use]
pub fn strip_attrs_and_docs<N: ast::AttrsOwner>(node: &N) -> N { pub fn strip_attrs_and_docs<N: ast::AttrsOwner>(node: &N) -> N {
N::cast(strip_attrs_and_docs_inner(node.syntax().clone())).unwrap() N::cast(strip_attrs_and_docs_inner(node.syntax().clone())).unwrap()

View file

@ -25,6 +25,27 @@ fn path_from_text(text: &str) -> ast::Path {
ast_from_text(text) ast_from_text(text)
} }
pub fn use_tree(
path: ast::Path,
use_tree_list: Option<ast::UseTreeList>,
alias: Option<ast::Alias>,
) -> ast::UseTree {
let mut buf = "use ".to_string();
buf += &path.syntax().to_string();
if let Some(use_tree_list) = use_tree_list {
buf += &format!("::{}", use_tree_list.syntax());
}
if let Some(alias) = alias {
buf += &format!(" {}", alias.syntax());
}
ast_from_text(&buf)
}
pub fn use_tree_list(use_trees: impl IntoIterator<Item = ast::UseTree>) -> ast::UseTreeList {
let use_trees = use_trees.into_iter().map(|it| it.syntax().clone()).join(", ");
ast_from_text(&format!("use {{{}}};", use_trees))
}
pub fn record_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordField { pub fn record_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordField {
return match expr { return match expr {
Some(expr) => from_text(&format!("{}: {}", name.syntax(), expr.syntax())), Some(expr) => from_text(&format!("{}: {}", name.syntax(), expr.syntax())),