2 ast::{self, AstNode, AttrsOwner},
3 SyntaxKind::{COMMENT, WHITESPACE},
7 use crate::{Assist, AssistCtx, AssistId};
11 // Adds a new `#[derive()]` clause to a struct or enum.
27 pub(crate) fn add_derive(ctx: AssistCtx) -> Option<Assist> {
28 let nominal = ctx.find_node_at_offset::<ast::NominalDef>()?;
29 let node_start = derive_insertion_offset(&nominal)?;
30 let target = nominal.syntax().text_range();
31 ctx.add_assist(AssistId("add_derive"), "Add `#[derive]`", target, |edit| {
32 let derive_attr = nominal
34 .filter_map(|x| x.as_simple_call())
35 .filter(|(name, _arg)| name == "derive")
36 .map(|(_name, arg)| arg)
38 let offset = match derive_attr {
40 edit.insert(node_start, "#[derive()]\n");
41 node_start + TextSize::of("#[derive(")
43 Some(tt) => tt.syntax().text_range().end() - TextSize::of(')'),
45 edit.set_cursor(offset)
49 // Insert `derive` after doc comments.
50 fn derive_insertion_offset(nominal: &ast::NominalDef) -> Option<TextSize> {
51 let non_ws_child = nominal
53 .children_with_tokens()
54 .find(|it| it.kind() != COMMENT && it.kind() != WHITESPACE)?;
55 Some(non_ws_child.text_range().start())
61 use crate::tests::{check_assist, check_assist_target};
67 "struct Foo { a: i32, <|>}",
68 "#[derive(<|>)]\nstruct Foo { a: i32, }",
72 "struct Foo { <|> a: i32, }",
73 "#[derive(<|>)]\nstruct Foo { a: i32, }",
78 fn add_derive_existing() {
81 "#[derive(Clone)]\nstruct Foo { a: i32<|>, }",
82 "#[derive(Clone<|>)]\nstruct Foo { a: i32, }",
87 fn add_derive_new_with_doc_comment() {
91 /// `Foo` is a pretty important struct.
93 struct Foo { a: i32<|>, }
96 /// `Foo` is a pretty important struct.
99 struct Foo { a: i32, }
105 fn add_derive_target() {
109 struct SomeThingIrrelevant;
110 /// `Foo` is a pretty important struct.
112 struct Foo { a: i32<|>, }
113 struct EvenMoreIrrelevant;
115 "/// `Foo` is a pretty important struct.
117 struct Foo { a: i32, }",