2 ast::{self, AstNode, AttrsOwner},
3 SyntaxKind::{COMMENT, WHITESPACE},
7 use crate::{AssistContext, AssistId, Assists};
11 // Adds a new `#[derive()]` clause to a struct or enum.
27 pub(crate) fn add_derive(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
28 let cap = ctx.config.snippet_cap?;
29 let nominal = ctx.find_node_at_offset::<ast::NominalDef>()?;
30 let node_start = derive_insertion_offset(&nominal)?;
31 let target = nominal.syntax().text_range();
32 acc.add(AssistId("add_derive"), "Add `#[derive]`", target, |builder| {
33 let derive_attr = nominal
35 .filter_map(|x| x.as_simple_call())
36 .filter(|(name, _arg)| name == "derive")
37 .map(|(_name, arg)| arg)
41 builder.insert_snippet(cap, node_start, "#[derive($0)]\n");
44 // Just move the cursor.
45 builder.insert_snippet(
47 tt.syntax().text_range().end() - TextSize::of(')'),
55 // Insert `derive` after doc comments.
56 fn derive_insertion_offset(nominal: &ast::NominalDef) -> Option<TextSize> {
57 let non_ws_child = nominal
59 .children_with_tokens()
60 .find(|it| it.kind() != COMMENT && it.kind() != WHITESPACE)?;
61 Some(non_ws_child.text_range().start())
66 use crate::tests::{check_assist, check_assist_target};
74 "struct Foo { a: i32, <|>}",
75 "#[derive($0)]\nstruct Foo { a: i32, }",
79 "struct Foo { <|> a: i32, }",
80 "#[derive($0)]\nstruct Foo { a: i32, }",
85 fn add_derive_existing() {
88 "#[derive(Clone)]\nstruct Foo { a: i32<|>, }",
89 "#[derive(Clone$0)]\nstruct Foo { a: i32, }",
94 fn add_derive_new_with_doc_comment() {
98 /// `Foo` is a pretty important struct.
100 struct Foo { a: i32<|>, }
103 /// `Foo` is a pretty important struct.
106 struct Foo { a: i32, }
112 fn add_derive_target() {
116 struct SomeThingIrrelevant;
117 /// `Foo` is a pretty important struct.
119 struct Foo { a: i32<|>, }
120 struct EvenMoreIrrelevant;
122 "/// `Foo` is a pretty important struct.
124 struct Foo { a: i32, }",