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(mut 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.add_action("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)
34 // Insert `derive` after doc comments.
35 fn derive_insertion_offset(nominal: &ast::NominalDef) -> Option<TextUnit> {
37 nominal.syntax().children().find(|it| it.kind() != COMMENT && it.kind() != WHITESPACE)?;
38 Some(non_ws_child.range().start())
44 use crate::helpers::{check_assist, check_assist_target};
50 "struct Foo { a: i32, <|>}",
51 "#[derive(<|>)]\nstruct Foo { a: i32, }",
55 "struct Foo { <|> a: i32, }",
56 "#[derive(<|>)]\nstruct Foo { a: i32, }",
61 fn add_derive_existing() {
64 "#[derive(Clone)]\nstruct Foo { a: i32<|>, }",
65 "#[derive(Clone<|>)]\nstruct Foo { a: i32, }",
70 fn add_derive_new_with_doc_comment() {
74 /// `Foo` is a pretty important struct.
76 struct Foo { a: i32<|>, }
79 /// `Foo` is a pretty important struct.
82 struct Foo { a: i32, }
88 fn add_derive_target() {
92 struct SomeThingIrrelevant;
93 /// `Foo` is a pretty important struct.
95 struct Foo { a: i32<|>, }
96 struct EvenMoreIrrelevant;
98 "/// `Foo` is a pretty important struct.
100 struct Foo { a: i32, }",