1 use stdx::{format_to, to_lower_snake_case};
2 use syntax::ast::{self, AstNode, NameOwner, VisibilityOwner};
5 utils::{find_impl_block_end, find_struct_impl, generate_impl_text},
6 AssistContext, AssistId, AssistKind, Assists, GroupLabel,
9 // Assist: generate_setter
11 // Generate a setter method.
25 // /// Set the person's name.
26 // fn set_name(&mut self, name: String) {
31 pub(crate) fn generate_setter(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
32 let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
33 let field = ctx.find_node_at_offset::<ast::RecordField>()?;
35 let strukt_name = strukt.name()?;
36 let field_name = field.name()?;
37 let field_ty = field.ty()?;
39 // Return early if we've found an existing fn
40 let fn_name = to_lower_snake_case(&field_name.to_string());
41 let impl_def = find_struct_impl(
43 &ast::Adt::Struct(strukt.clone()),
44 format!("set_{}", fn_name).as_str(),
47 let target = field.syntax().text_range();
49 &GroupLabel("Generate getter/setter".to_owned()),
50 AssistId("generate_setter", AssistKind::Generate),
51 "Generate a setter method",
54 let mut buf = String::with_capacity(512);
56 let fn_name_spaced = fn_name.replace('_', " ");
57 let strukt_name_spaced =
58 to_lower_snake_case(&strukt_name.to_string()).replace('_', " ");
60 if impl_def.is_some() {
64 let vis = strukt.visibility().map_or(String::new(), |v| format!("{} ", v));
67 " /// Set the {}'s {}.
68 {}fn set_{}(&mut self, {}: {}) {{
81 let start_offset = impl_def
82 .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
84 buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf);
85 strukt.syntax().text_range().end()
88 builder.insert(start_offset, buf);
95 use crate::tests::{check_assist, check_assist_not_applicable};
99 fn check_not_applicable(ra_fixture: &str) {
100 check_assist_not_applicable(generate_setter, ra_fixture)
104 fn test_generate_setter_from_field() {
108 struct Person<T: Clone> {
112 struct Person<T: Clone> {
116 impl<T: Clone> Person<T> {
117 /// Set the person's data.
118 fn set_data(&mut self, data: T) {
126 fn test_generate_setter_already_implemented() {
127 check_not_applicable(
129 struct Person<T: Clone> {
133 impl<T: Clone> Person<T> {
134 fn set_data(&mut self, data: T) {
142 fn test_generate_setter_from_field_with_visibility_marker() {
146 pub(crate) struct Person<T: Clone> {
150 pub(crate) struct Person<T: Clone> {
154 impl<T: Clone> Person<T> {
155 /// Set the person's data.
156 pub(crate) fn set_data(&mut self, data: T) {
164 fn test_multiple_generate_setter() {
168 struct Context<T: Clone> {
173 impl<T: Clone> Context<T> {
174 /// Set the context's data.
175 fn set_data(&mut self, data: T) {
180 struct Context<T: Clone> {
185 impl<T: Clone> Context<T> {
186 /// Set the context's data.
187 fn set_data(&mut self, data: T) {
191 /// Set the context's count.
192 fn set_count(&mut self, count: usize) {