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_getter
11 // Generate a getter method.
25 // /// Get a reference to the person's name.
26 // fn name(&self) -> &String {
31 pub(crate) fn generate_getter(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(&ctx, &ast::Adt::Struct(strukt.clone()), fn_name.as_str())?;
43 let target = field.syntax().text_range();
45 &GroupLabel("Generate getter/setter".to_owned()),
46 AssistId("generate_getter", AssistKind::Generate),
47 "Generate a getter method",
50 let mut buf = String::with_capacity(512);
52 let fn_name_spaced = fn_name.replace('_', " ");
53 let strukt_name_spaced =
54 to_lower_snake_case(&strukt_name.to_string()).replace('_', " ");
56 if impl_def.is_some() {
60 let vis = strukt.visibility().map_or(String::new(), |v| format!("{} ", v));
63 " /// Get a reference to the {}'s {}.
64 {}fn {}(&self) -> &{} {{
75 let start_offset = impl_def
76 .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
78 buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf);
79 strukt.syntax().text_range().end()
82 builder.insert(start_offset, buf);
89 use crate::tests::{check_assist, check_assist_not_applicable};
93 fn check_not_applicable(ra_fixture: &str) {
94 check_assist_not_applicable(generate_getter, ra_fixture)
98 fn test_generate_getter_from_field() {
102 struct Context<T: Clone> {
106 struct Context<T: Clone> {
110 impl<T: Clone> Context<T> {
111 /// Get a reference to the context's data.
112 fn data(&self) -> &T {
120 fn test_generate_getter_already_implemented() {
121 check_not_applicable(
123 struct Context<T: Clone> {
127 impl<T: Clone> Context<T> {
128 fn data(&self) -> &T {
136 fn test_generate_getter_from_field_with_visibility_marker() {
140 pub(crate) struct Context<T: Clone> {
144 pub(crate) struct Context<T: Clone> {
148 impl<T: Clone> Context<T> {
149 /// Get a reference to the context's data.
150 pub(crate) fn data(&self) -> &T {
158 fn test_multiple_generate_getter() {
162 struct Context<T: Clone> {
167 impl<T: Clone> Context<T> {
168 /// Get a reference to the context's data.
169 fn data(&self) -> &T {
174 struct Context<T: Clone> {
179 impl<T: Clone> Context<T> {
180 /// Get a reference to the context's data.
181 fn data(&self) -> &T {
185 /// Get a reference to the context's count.
186 fn count(&self) -> &usize {