2019-01-03 06:08:32 -06:00
|
|
|
use join_to_string::join;
|
|
|
|
use ra_syntax::{
|
2019-01-08 03:23:10 -06:00
|
|
|
ast::{self, AstNode, AstToken, NameOwner, TypeParamsOwner},
|
2019-01-03 06:08:32 -06:00
|
|
|
TextUnit,
|
|
|
|
};
|
|
|
|
|
2019-01-03 09:59:17 -06:00
|
|
|
use crate::assists::{AssistCtx, Assist};
|
2019-01-03 06:08:32 -06:00
|
|
|
|
2019-01-03 09:59:17 -06:00
|
|
|
pub fn add_impl(ctx: AssistCtx) -> Option<Assist> {
|
|
|
|
let nominal = ctx.node_at_offset::<ast::NominalDef>()?;
|
2019-01-03 06:08:32 -06:00
|
|
|
let name = nominal.name()?;
|
2019-01-03 09:59:17 -06:00
|
|
|
ctx.build("add impl", |edit| {
|
2019-01-03 06:08:32 -06:00
|
|
|
let type_params = nominal.type_param_list();
|
|
|
|
let start_offset = nominal.syntax().range().end();
|
|
|
|
let mut buf = String::new();
|
|
|
|
buf.push_str("\n\nimpl");
|
|
|
|
if let Some(type_params) = type_params {
|
|
|
|
type_params.syntax().text().push_to(&mut buf);
|
|
|
|
}
|
|
|
|
buf.push_str(" ");
|
|
|
|
buf.push_str(name.text().as_str());
|
|
|
|
if let Some(type_params) = type_params {
|
|
|
|
let lifetime_params = type_params
|
|
|
|
.lifetime_params()
|
|
|
|
.filter_map(|it| it.lifetime())
|
|
|
|
.map(|it| it.text());
|
|
|
|
let type_params = type_params
|
|
|
|
.type_params()
|
|
|
|
.filter_map(|it| it.name())
|
|
|
|
.map(|it| it.text());
|
|
|
|
join(lifetime_params.chain(type_params))
|
|
|
|
.surround_with("<", ">")
|
|
|
|
.to_buf(&mut buf);
|
|
|
|
}
|
|
|
|
buf.push_str(" {\n");
|
2019-01-03 09:59:17 -06:00
|
|
|
edit.set_cursor(start_offset + TextUnit::of_str(&buf));
|
2019-01-03 06:08:32 -06:00
|
|
|
buf.push_str("\n}");
|
|
|
|
edit.insert(start_offset, buf);
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2019-01-03 09:59:17 -06:00
|
|
|
use crate::assists::check_assist;
|
2019-01-03 06:08:32 -06:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_add_impl() {
|
2019-01-03 09:59:17 -06:00
|
|
|
check_assist(
|
|
|
|
add_impl,
|
2019-01-03 06:08:32 -06:00
|
|
|
"struct Foo {<|>}\n",
|
|
|
|
"struct Foo {}\n\nimpl Foo {\n<|>\n}\n",
|
|
|
|
);
|
2019-01-03 09:59:17 -06:00
|
|
|
check_assist(
|
|
|
|
add_impl,
|
2019-01-03 06:08:32 -06:00
|
|
|
"struct Foo<T: Clone> {<|>}",
|
|
|
|
"struct Foo<T: Clone> {}\n\nimpl<T: Clone> Foo<T> {\n<|>\n}",
|
|
|
|
);
|
2019-01-03 09:59:17 -06:00
|
|
|
check_assist(
|
|
|
|
add_impl,
|
2019-01-03 06:08:32 -06:00
|
|
|
"struct Foo<'a, T: Foo<'a>> {<|>}",
|
|
|
|
"struct Foo<'a, T: Foo<'a>> {}\n\nimpl<'a, T: Foo<'a>> Foo<'a, T> {\n<|>\n}",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|