2 ast::{self, AstNode, HasAttrs},
3 SyntaxKind::{COMMENT, WHITESPACE},
7 use crate::{AssistContext, AssistId, AssistKind, Assists};
9 // Assist: generate_derive
11 // Adds a new `#[derive()]` clause to a struct or enum.
27 pub(crate) fn generate_derive(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
28 let cap = ctx.config.snippet_cap?;
29 let nominal = ctx.find_node_at_offset::<ast::Adt>()?;
30 let node_start = derive_insertion_offset(&nominal)?;
31 let target = nominal.syntax().text_range();
33 AssistId("generate_derive", AssistKind::Generate),
37 let derive_attr = nominal
39 .filter_map(|x| x.as_simple_call())
40 .filter(|(name, _arg)| name == "derive")
41 .map(|(_name, arg)| arg)
45 builder.insert_snippet(cap, node_start, "#[derive($0)]\n");
48 // Just move the cursor.
49 builder.insert_snippet(
51 tt.syntax().text_range().end() - TextSize::of(')'),
60 // Insert `derive` after doc comments.
61 fn derive_insertion_offset(nominal: &ast::Adt) -> Option<TextSize> {
62 let non_ws_child = nominal
64 .children_with_tokens()
65 .find(|it| it.kind() != COMMENT && it.kind() != WHITESPACE)?;
66 Some(non_ws_child.text_range().start())
71 use crate::tests::{check_assist, check_assist_target};
79 "struct Foo { a: i32, $0}",
80 "#[derive($0)]\nstruct Foo { a: i32, }",
84 "struct Foo { $0 a: i32, }",
85 "#[derive($0)]\nstruct Foo { a: i32, }",
90 fn add_derive_existing() {
93 "#[derive(Clone)]\nstruct Foo { a: i32$0, }",
94 "#[derive(Clone$0)]\nstruct Foo { a: i32, }",
99 fn add_derive_new_with_doc_comment() {
103 /// `Foo` is a pretty important struct.
105 struct Foo { a: i32$0, }
108 /// `Foo` is a pretty important struct.
111 struct Foo { a: i32, }
117 fn add_derive_target() {
121 struct SomeThingIrrelevant;
122 /// `Foo` is a pretty important struct.
124 struct Foo { a: i32$0, }
125 struct EvenMoreIrrelevant;
127 "/// `Foo` is a pretty important struct.
129 struct Foo { a: i32, }",