rust/crates/ide_assists/src/handlers/generate_getter.rs

278 lines
5.8 KiB
Rust
Raw Normal View History

use stdx::{format_to, to_lower_snake_case};
2021-02-13 12:58:58 -06:00
use syntax::ast::{self, AstNode, NameOwner, VisibilityOwner};
use crate::{
utils::{find_impl_block_end, find_struct_impl, generate_impl_text},
2021-02-13 12:58:58 -06:00
AssistContext, AssistId, AssistKind, Assists, GroupLabel,
};
// Assist: generate_getter
//
// Generate a getter method.
//
// ```
// struct Person {
// nam$0e: String,
// }
// ```
// ->
// ```
// struct Person {
// name: String,
// }
//
// impl Person {
// /// Get a reference to the person's name.
// fn $0name(&self) -> &String {
// &self.name
// }
// }
// ```
pub(crate) fn generate_getter(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
2021-05-23 15:13:35 -05:00
generate_getter_impl(acc, ctx, false)
}
// Assist: generate_getter_mut
//
// Generate a mut getter method.
//
// ```
// struct Person {
// nam$0e: String,
// }
// ```
// ->
// ```
// struct Person {
// name: String,
// }
//
// impl Person {
// /// Get a mutable reference to the person's name.
// fn $0name_mut(&mut self) -> &mut String {
2021-05-23 15:13:35 -05:00
// &mut self.name
// }
// }
// ```
pub(crate) fn generate_getter_mut(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
generate_getter_impl(acc, ctx, true)
}
pub(crate) fn generate_getter_impl(
acc: &mut Assists,
ctx: &AssistContext,
mutable: bool,
) -> Option<()> {
let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
let field = ctx.find_node_at_offset::<ast::RecordField>()?;
let strukt_name = strukt.name()?;
let field_name = field.name()?;
let field_ty = field.ty()?;
// Return early if we've found an existing fn
2021-05-23 15:13:35 -05:00
let mut fn_name = to_lower_snake_case(&field_name.to_string());
if mutable {
format_to!(fn_name, "_mut");
}
let impl_def = find_struct_impl(&ctx, &ast::Adt::Struct(strukt.clone()), fn_name.as_str())?;
2021-05-23 15:13:35 -05:00
let (id, label) = if mutable {
("generate_getter_mut", "Generate a mut getter method")
} else {
("generate_getter", "Generate a getter method")
};
let target = field.syntax().text_range();
2021-02-13 12:58:58 -06:00
acc.add_group(
&GroupLabel("Generate getter/setter".to_owned()),
2021-05-23 15:13:35 -05:00
AssistId(id, AssistKind::Generate),
label,
target,
|builder| {
let mut buf = String::with_capacity(512);
if impl_def.is_some() {
buf.push('\n');
}
let vis = strukt.visibility().map_or(String::new(), |v| format!("{} ", v));
format_to!(
buf,
2021-05-23 15:13:35 -05:00
" /// Get a {}reference to the {}'s {}.
{}fn {}(&{mut_}self) -> &{mut_}{} {{
&{mut_}self.{}
}}",
2021-05-23 15:13:35 -05:00
mutable.then(|| "mutable ").unwrap_or_default(),
to_lower_snake_case(&strukt_name.to_string()).replace('_', " "),
fn_name.trim_end_matches("_mut").replace('_', " "),
vis,
fn_name,
field_ty,
2021-05-23 15:13:35 -05:00
field_name,
mut_ = mutable.then(|| "mut ").unwrap_or_default(),
);
let start_offset = impl_def
.and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
.unwrap_or_else(|| {
buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf);
strukt.syntax().text_range().end()
});
match ctx.config.snippet_cap {
Some(cap) => {
builder.insert_snippet(cap, start_offset, buf.replacen("fn ", "fn $0", 1))
}
None => builder.insert(start_offset, buf),
}
},
)
}
#[cfg(test)]
mod tests {
use crate::tests::{check_assist, check_assist_not_applicable};
use super::*;
#[test]
fn test_generate_getter_from_field() {
check_assist(
generate_getter,
r#"
2021-05-23 15:19:00 -05:00
struct Context {
dat$0a: Data,
}
"#,
r#"
2021-05-23 15:19:00 -05:00
struct Context {
data: Data,
}
2021-05-23 15:19:00 -05:00
impl Context {
/// Get a reference to the context's data.
fn $0data(&self) -> &Data {
&self.data
}
2021-05-23 15:19:00 -05:00
}
"#,
);
check_assist(
2021-05-23 15:15:54 -05:00
generate_getter_mut,
r#"
2021-05-23 15:19:00 -05:00
struct Context {
dat$0a: Data,
}
"#,
r#"
2021-05-23 15:19:00 -05:00
struct Context {
data: Data,
}
2021-05-23 15:19:00 -05:00
impl Context {
2021-05-23 15:15:54 -05:00
/// Get a mutable reference to the context's data.
fn $0data_mut(&mut self) -> &mut Data {
2021-05-23 15:15:54 -05:00
&mut self.data
}
2021-05-23 15:19:00 -05:00
}
"#,
);
}
#[test]
2021-05-23 15:15:54 -05:00
fn test_generate_getter_already_implemented() {
check_assist_not_applicable(
generate_getter,
r#"
2021-05-23 15:19:00 -05:00
struct Context {
dat$0a: Data,
}
2021-05-23 15:19:00 -05:00
impl Context {
fn data(&self) -> &Data {
&self.data
}
2021-05-23 15:19:00 -05:00
}
"#,
);
2021-05-23 15:13:35 -05:00
2021-05-23 15:15:54 -05:00
check_assist_not_applicable(
2021-05-23 15:13:35 -05:00
generate_getter_mut,
r#"
2021-05-23 15:19:00 -05:00
struct Context {
dat$0a: Data,
2021-05-23 15:13:35 -05:00
}
2021-05-23 15:19:00 -05:00
impl Context {
fn data_mut(&mut self) -> &mut Data {
2021-05-23 15:13:35 -05:00
&mut self.data
}
2021-05-23 15:19:00 -05:00
}
"#,
2021-05-23 15:13:35 -05:00
);
}
#[test]
2021-05-23 15:15:54 -05:00
fn test_generate_getter_from_field_with_visibility_marker() {
2021-05-23 15:13:35 -05:00
check_assist(
2021-05-23 15:15:54 -05:00
generate_getter,
2021-05-23 15:13:35 -05:00
r#"
2021-05-23 15:19:00 -05:00
pub(crate) struct Context {
dat$0a: Data,
}
"#,
2021-05-23 15:13:35 -05:00
r#"
2021-05-23 15:19:00 -05:00
pub(crate) struct Context {
data: Data,
2021-05-23 15:13:35 -05:00
}
2021-05-23 15:19:00 -05:00
impl Context {
2021-05-23 15:15:54 -05:00
/// Get a reference to the context's data.
pub(crate) fn $0data(&self) -> &Data {
2021-05-23 15:15:54 -05:00
&self.data
2021-05-23 15:13:35 -05:00
}
2021-05-23 15:19:00 -05:00
}
"#,
2021-05-23 15:13:35 -05:00
);
}
#[test]
2021-05-23 15:15:54 -05:00
fn test_multiple_generate_getter() {
2021-05-23 15:13:35 -05:00
check_assist(
2021-05-23 15:15:54 -05:00
generate_getter,
2021-05-23 15:13:35 -05:00
r#"
2021-05-23 15:19:00 -05:00
struct Context {
data: Data,
2021-05-23 15:13:35 -05:00
cou$0nt: usize,
}
2021-05-23 15:19:00 -05:00
impl Context {
2021-05-23 15:15:54 -05:00
/// Get a reference to the context's data.
2021-05-23 15:19:00 -05:00
fn data(&self) -> &Data {
2021-05-23 15:15:54 -05:00
&self.data
2021-05-23 15:13:35 -05:00
}
2021-05-23 15:19:00 -05:00
}
"#,
2021-05-23 15:13:35 -05:00
r#"
2021-05-23 15:19:00 -05:00
struct Context {
data: Data,
2021-05-23 15:13:35 -05:00
count: usize,
}
2021-05-23 15:19:00 -05:00
impl Context {
2021-05-23 15:15:54 -05:00
/// Get a reference to the context's data.
2021-05-23 15:19:00 -05:00
fn data(&self) -> &Data {
2021-05-23 15:15:54 -05:00
&self.data
2021-05-23 15:13:35 -05:00
}
2021-05-23 15:15:54 -05:00
/// Get a reference to the context's count.
fn $0count(&self) -> &usize {
2021-05-23 15:15:54 -05:00
&self.count
2021-05-23 15:13:35 -05:00
}
2021-05-23 15:19:00 -05:00
}
"#,
2021-05-23 15:13:35 -05:00
);
}
}