1 use hir::db::HirDatabase;
3 ast::{self, AstNode, AttrsOwner},
4 SyntaxKind::{COMMENT, WHITESPACE},
8 use crate::{Assist, AssistCtx, AssistId};
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(AssistId("add_derive"), "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().text_range().end() - TextUnit::of_char(')'),
27 edit.target(nominal.syntax().text_range());
28 edit.set_cursor(offset)
34 // Insert `derive` after doc comments.
35 fn derive_insertion_offset(nominal: &ast::NominalDef) -> Option<TextUnit> {
36 let non_ws_child = nominal
38 .children_with_tokens()
39 .find(|it| it.kind() != COMMENT && it.kind() != WHITESPACE)?;
40 Some(non_ws_child.text_range().start())
46 use crate::helpers::{check_assist, check_assist_target};
52 "struct Foo { a: i32, <|>}",
53 "#[derive(<|>)]\nstruct Foo { a: i32, }",
57 "struct Foo { <|> a: i32, }",
58 "#[derive(<|>)]\nstruct Foo { a: i32, }",
63 fn add_derive_existing() {
66 "#[derive(Clone)]\nstruct Foo { a: i32<|>, }",
67 "#[derive(Clone<|>)]\nstruct Foo { a: i32, }",
72 fn add_derive_new_with_doc_comment() {
76 /// `Foo` is a pretty important struct.
78 struct Foo { a: i32<|>, }
81 /// `Foo` is a pretty important struct.
84 struct Foo { a: i32, }
90 fn add_derive_target() {
94 struct SomeThingIrrelevant;
95 /// `Foo` is a pretty important struct.
97 struct Foo { a: i32<|>, }
98 struct EvenMoreIrrelevant;
100 "/// `Foo` is a pretty important struct.
102 struct Foo { a: i32, }",