9119: fix: some minor "extract type alias" fixes r=jonas-schievink a=jonas-schievink

It now correctly works inside traits, and no longer messes up the indentation of the original node

bors r+

Co-authored-by: Jonas Schievink <jonasschievink@gmail.com>
This commit is contained in:
bors[bot] 2021-06-02 20:28:15 +00:00 committed by GitHub
commit 092396c65a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,4 +1,7 @@
use syntax::ast::{self, AstNode};
use syntax::{
ast::{self, edit::IndentLevel, AstNode},
match_ast,
};
use crate::{AssistContext, AssistId, AssistKind, Assists};
@ -25,12 +28,15 @@ pub(crate) fn extract_type_alias(acc: &mut Assists, ctx: &AssistContext) -> Opti
}
let node = ctx.find_node_at_range::<ast::Type>()?;
let insert = ctx
.find_node_at_offset::<ast::Impl>()
.map(|imp| imp.syntax().clone())
.or_else(|| ctx.find_node_at_offset::<ast::Item>().map(|item| item.syntax().clone()))?
.text_range()
.start();
let item = ctx.find_node_at_offset::<ast::Item>()?;
let insert = match_ast! {
match (item.syntax().parent()?) {
ast::AssocItemList(it) => it.syntax().parent()?.clone(),
_ => item.syntax().clone(),
}
};
let indent = IndentLevel::from_node(&insert);
let insert = insert.text_range().start();
let target = node.syntax().text_range();
acc.add(
@ -42,10 +48,14 @@ pub(crate) fn extract_type_alias(acc: &mut Assists, ctx: &AssistContext) -> Opti
builder.replace(target, "Type");
match ctx.config.snippet_cap {
Some(cap) => {
builder.insert_snippet(cap, insert, format!("type $0Type = {};\n\n", node));
builder.insert_snippet(
cap,
insert,
format!("type $0Type = {};\n\n{}", node, indent),
);
}
None => {
builder.insert(insert, format!("type Type = {};\n\n", node));
builder.insert(insert, format!("type Type = {};\n\n{}", node, indent));
}
}
},
@ -153,9 +163,9 @@ struct S {
}
#[test]
fn extract_from_impl() {
// When invoked in an impl, extracted type alias should be placed next to the impl, not
// inside.
fn extract_from_impl_or_trait() {
// When invoked in an impl/trait, extracted type alias should be placed next to the
// impl/trait, not inside.
check_assist(
extract_type_alias,
r#"
@ -167,6 +177,40 @@ fn f() -> $0(u8, u8)$0 {}
type $0Type = (u8, u8);
impl S {
fn f() -> Type {}
}
"#,
);
check_assist(
extract_type_alias,
r#"
trait Tr {
fn f() -> $0(u8, u8)$0 {}
}
"#,
r#"
type $0Type = (u8, u8);
trait Tr {
fn f() -> Type {}
}
"#,
);
}
#[test]
fn indentation() {
check_assist(
extract_type_alias,
r#"
mod m {
fn f() -> $0u8$0 {}
}
"#,
r#"
mod m {
type $0Type = u8;
fn f() -> Type {}
}
"#,