]> git.lizzy.rs Git - rust.git/blob - crates/ra_assists/src/add_impl.rs
32fc074a6207750e41ad42129eb46f0f47689aa8
[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(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
11     let nominal = ctx.node_at_offset::<ast::NominalDef>()?;
12     let name = nominal.name()?;
13     ctx.build("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
38 #[cfg(test)]
39 mod tests {
40     use super::*;
41     use crate::helpers::{check_assist, check_assist_target};
42
43     #[test]
44     fn test_add_impl() {
45         check_assist(add_impl, "struct Foo {<|>}\n", "struct Foo {}\n\nimpl Foo {\n<|>\n}\n");
46         check_assist(
47             add_impl,
48             "struct Foo<T: Clone> {<|>}",
49             "struct Foo<T: Clone> {}\n\nimpl<T: Clone> Foo<T> {\n<|>\n}",
50         );
51         check_assist(
52             add_impl,
53             "struct Foo<'a, T: Foo<'a>> {<|>}",
54             "struct Foo<'a, T: Foo<'a>> {}\n\nimpl<'a, T: Foo<'a>> Foo<'a, T> {\n<|>\n}",
55         );
56     }
57
58     #[test]
59     fn add_impl_target() {
60         check_assist_target(
61             add_impl,
62             "
63 struct SomeThingIrrelevant;
64 /// Has a lifetime parameter
65 struct Foo<'a, T: Foo<'a>> {<|>}
66 struct EvenMoreIrrelevant;
67 ",
68             "/// Has a lifetime parameter
69 struct Foo<'a, T: Foo<'a>> {}",
70         );
71     }
72 }