]> git.lizzy.rs Git - rust.git/blob - crates/ra_assists/src/add_impl.rs
ra_assists: assist "providers" can produce multiple assists
[rust.git] / crates / ra_assists / src / add_impl.rs
1 use join_to_string::join;
2 use hir::db::HirDatabase;
3 use ra_syntax::{
4     ast::{self, AstNode, AstToken, NameOwner, TypeParamsOwner},
5     TextUnit,
6 };
7
8 use crate::{AssistCtx, Assist};
9
10 pub(crate) fn add_impl(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
11     let nominal = ctx.node_at_offset::<ast::NominalDef>()?;
12     let name = nominal.name()?;
13     ctx.add_action("add impl", |edit| {
14         edit.target(nominal.syntax().range());
15         let type_params = nominal.type_param_list();
16         let start_offset = nominal.syntax().range().end();
17         let mut buf = String::new();
18         buf.push_str("\n\nimpl");
19         if let Some(type_params) = type_params {
20             type_params.syntax().text().push_to(&mut buf);
21         }
22         buf.push_str(" ");
23         buf.push_str(name.text().as_str());
24         if let Some(type_params) = type_params {
25             let lifetime_params =
26                 type_params.lifetime_params().filter_map(|it| it.lifetime()).map(|it| it.text());
27             let type_params =
28                 type_params.type_params().filter_map(|it| it.name()).map(|it| it.text());
29             join(lifetime_params.chain(type_params)).surround_with("<", ">").to_buf(&mut buf);
30         }
31         buf.push_str(" {\n");
32         edit.set_cursor(start_offset + TextUnit::of_str(&buf));
33         buf.push_str("\n}");
34         edit.insert(start_offset, buf);
35     });
36
37     ctx.build()
38 }
39
40 #[cfg(test)]
41 mod tests {
42     use super::*;
43     use crate::helpers::{check_assist, check_assist_target};
44
45     #[test]
46     fn test_add_impl() {
47         check_assist(add_impl, "struct Foo {<|>}\n", "struct Foo {}\n\nimpl Foo {\n<|>\n}\n");
48         check_assist(
49             add_impl,
50             "struct Foo<T: Clone> {<|>}",
51             "struct Foo<T: Clone> {}\n\nimpl<T: Clone> Foo<T> {\n<|>\n}",
52         );
53         check_assist(
54             add_impl,
55             "struct Foo<'a, T: Foo<'a>> {<|>}",
56             "struct Foo<'a, T: Foo<'a>> {}\n\nimpl<'a, T: Foo<'a>> Foo<'a, T> {\n<|>\n}",
57         );
58     }
59
60     #[test]
61     fn add_impl_target() {
62         check_assist_target(
63             add_impl,
64             "
65 struct SomeThingIrrelevant;
66 /// Has a lifetime parameter
67 struct Foo<'a, T: Foo<'a>> {<|>}
68 struct EvenMoreIrrelevant;
69 ",
70             "/// Has a lifetime parameter
71 struct Foo<'a, T: Foo<'a>> {}",
72         );
73     }
74 }