1 use hir::db::HirDatabase;
3 ast::{self, AstNode, AttrsOwner},
4 SyntaxKind::{WHITESPACE, COMMENT},
8 use crate::{AssistCtx, Assist};
10 pub(crate) fn add_derive(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
11 let nominal = ctx.node_at_offset::<ast::NominalDef>()?;
12 let node_start = derive_insertion_offset(nominal)?;
13 ctx.build("add `#[derive]`", |edit| {
14 let derive_attr = nominal
16 .filter_map(|x| x.as_call())
17 .filter(|(name, _arg)| name == "derive")
18 .map(|(_name, arg)| arg)
20 let offset = match derive_attr {
22 edit.insert(node_start, "#[derive()]\n");
23 node_start + TextUnit::of_str("#[derive(")
25 Some(tt) => tt.syntax().range().end() - TextUnit::of_char(')'),
27 edit.target(nominal.syntax().range());
28 edit.set_cursor(offset)
32 // Insert `derive` after doc comments.
33 fn derive_insertion_offset(nominal: &ast::NominalDef) -> Option<TextUnit> {
35 nominal.syntax().children().find(|it| it.kind() != COMMENT && it.kind() != WHITESPACE)?;
36 Some(non_ws_child.range().start())
42 use crate::helpers::{check_assist, check_assist_target};
48 "struct Foo { a: i32, <|>}",
49 "#[derive(<|>)]\nstruct Foo { a: i32, }",
53 "struct Foo { <|> a: i32, }",
54 "#[derive(<|>)]\nstruct Foo { a: i32, }",
59 fn add_derive_existing() {
62 "#[derive(Clone)]\nstruct Foo { a: i32<|>, }",
63 "#[derive(Clone<|>)]\nstruct Foo { a: i32, }",
68 fn add_derive_new_with_doc_comment() {
72 /// `Foo` is a pretty important struct.
74 struct Foo { a: i32<|>, }
77 /// `Foo` is a pretty important struct.
80 struct Foo { a: i32, }
86 fn add_derive_target() {
90 struct SomeThingIrrelevant;
91 /// `Foo` is a pretty important struct.
93 struct Foo { a: i32<|>, }
94 struct EvenMoreIrrelevant;
96 "/// `Foo` is a pretty important struct.
98 struct Foo { a: i32, }",