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

336 lines
9.2 KiB
Rust
Raw Normal View History

use hir::{self, HasCrate, HasSource, HasVisibility};
use syntax::ast::{self, make, AstNode, HasGenericParams, HasName, HasVisibility as _};
2021-10-13 08:08:40 -05:00
use crate::{
2021-10-14 11:19:20 -05:00
utils::{convert_param_list_to_arg_list, find_struct_impl, render_snippet, Cursor},
2021-10-13 08:08:40 -05:00
AssistContext, AssistId, AssistKind, Assists, GroupLabel,
};
2021-10-14 05:34:31 -05:00
use syntax::ast::edit::AstNodeEdit;
2021-10-13 08:08:40 -05:00
2021-10-14 06:52:31 -05:00
// Assist: generate_delegate_methods
2021-10-13 08:08:40 -05:00
//
2021-10-14 06:52:31 -05:00
// Generate delegate methods.
2021-10-13 08:08:40 -05:00
//
// ```
// struct Age(u8);
// impl Age {
// fn age(&self) -> u8 {
// self.0
// }
// }
//
2021-10-13 08:08:40 -05:00
// struct Person {
// ag$0e: Age,
2021-10-13 08:08:40 -05:00
// }
// ```
// ->
// ```
// struct Age(u8);
// impl Age {
// fn age(&self) -> u8 {
// self.0
// }
// }
//
2021-10-13 08:08:40 -05:00
// struct Person {
// age: Age,
2021-10-13 08:08:40 -05:00
// }
//
// impl Person {
// $0fn age(&self) -> u8 {
// self.age.age()
2021-10-13 08:08:40 -05:00
// }
// }
// ```
2021-10-14 06:52:31 -05:00
pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
2021-10-13 08:08:40 -05:00
let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
2021-10-13 16:59:23 -05:00
let strukt_name = strukt.name()?;
let current_module = ctx.sema.scope(strukt.syntax()).module()?;
2021-10-13 08:08:40 -05:00
2021-10-14 07:18:12 -05:00
let (field_name, field_ty) = match ctx.find_node_at_offset::<ast::RecordField>() {
Some(field) => {
let field_name = field.name()?;
let field_ty = field.ty()?;
(format!("{}", field_name), field_ty)
}
None => {
let field = ctx.find_node_at_offset::<ast::TupleField>()?;
let field_list = ctx.find_node_at_offset::<ast::TupleFieldList>()?;
2021-10-14 11:19:20 -05:00
let field_list_index = field_list.fields().position(|it| it == field)?;
2021-10-14 07:18:12 -05:00
let field_ty = field.ty()?;
(format!("{}", field_list_index), field_ty)
}
};
2021-10-13 08:08:40 -05:00
let sema_field_ty = ctx.sema.resolve_type(&field_ty)?;
let krate = sema_field_ty.krate(ctx.db());
let mut methods = vec![];
sema_field_ty.iterate_assoc_items(ctx.db(), krate, |item| {
if let hir::AssocItem::Function(f) = item {
if f.self_param(ctx.db()).is_some() && f.is_visible_from(ctx.db(), current_module) {
2021-10-13 08:08:40 -05:00
methods.push(f)
}
}
2021-10-14 11:19:20 -05:00
Option::<()>::None
2021-10-13 08:08:40 -05:00
});
let target = field_ty.syntax().text_range();
for method in methods {
2021-10-14 11:19:20 -05:00
let adt = ast::Adt::Struct(strukt.clone());
let name = method.name(ctx.db()).to_string();
let impl_def = find_struct_impl(ctx, &adt, &name).flatten();
2021-10-13 08:08:40 -05:00
acc.add_group(
2021-10-14 06:52:31 -05:00
&GroupLabel("Generate delegate methods…".to_owned()),
AssistId("generate_delegate_methods", AssistKind::Generate),
format!("Generate delegate for `{}.{}()`", field_name, method.name(ctx.db())),
2021-10-13 08:08:40 -05:00
target,
|builder| {
// Create the function
2021-10-14 05:34:31 -05:00
let method_source = match method.source(ctx.db()) {
Some(source) => source.value,
None => return,
};
let method_name = method.name(ctx.db());
let vis = method_source.visibility();
2021-10-13 13:13:36 -05:00
let name = make::name(&method.name(ctx.db()).to_string());
let params =
method_source.param_list().unwrap_or_else(|| make::param_list(None, []));
2021-10-14 11:19:20 -05:00
let type_params = method_source.generic_param_list();
let arg_list = match method_source.param_list() {
Some(list) => convert_param_list_to_arg_list(list),
None => make::arg_list([]),
};
2021-10-14 05:34:31 -05:00
let tail_expr = make::expr_method_call(
2021-10-14 07:18:12 -05:00
make::ext::field_from_idents(["self", &field_name]).unwrap(), // This unwrap is ok because we have at least 1 arg in the list
2021-10-14 05:34:31 -05:00
make::name_ref(&method_name.to_string()),
2021-10-14 11:19:20 -05:00
arg_list,
2021-10-14 05:34:31 -05:00
);
let body = make::block_expr([], Some(tail_expr));
2021-10-14 11:33:29 -05:00
let ret_type = method_source.ret_type();
let is_async = method_source.async_token().is_some();
2021-10-14 05:34:31 -05:00
let f = make::fn_(vis, name, type_params, params, body, ret_type, is_async)
.indent(ast::edit::IndentLevel(1))
.clone_for_update();
2021-10-13 08:08:40 -05:00
2021-10-13 13:13:36 -05:00
let cursor = Cursor::Before(f.syntax());
// Create or update an impl block, attach the function to it,
// then insert into our code.
2021-10-13 16:59:23 -05:00
match impl_def {
Some(impl_def) => {
2021-10-14 05:34:31 -05:00
// Remember where in our source our `impl` block lives.
2021-10-13 16:59:23 -05:00
let impl_def = impl_def.clone_for_update();
let old_range = impl_def.syntax().text_range();
2021-10-14 05:34:31 -05:00
// Attach the function to the impl block
2021-10-13 16:59:23 -05:00
let assoc_items = impl_def.get_or_create_assoc_item_list();
assoc_items.add_item(f.clone().into());
2021-10-14 05:34:31 -05:00
// Update the impl block.
2021-10-14 11:19:20 -05:00
match ctx.config.snippet_cap {
Some(cap) => {
let snippet = render_snippet(cap, impl_def.syntax(), cursor);
builder.replace_snippet(cap, old_range, snippet);
}
None => {
builder.replace(old_range, impl_def.syntax().to_string());
}
}
2021-10-13 16:59:23 -05:00
}
None => {
2021-10-14 05:34:31 -05:00
// Attach the function to the impl block
2021-10-13 16:59:23 -05:00
let name = &strukt_name.to_string();
let params = strukt.generic_param_list();
let ty_params = params.clone();
let impl_def = make::impl_(make::ext::ident_path(name), params, ty_params)
.clone_for_update();
2021-10-13 16:59:23 -05:00
let assoc_items = impl_def.get_or_create_assoc_item_list();
assoc_items.add_item(f.clone().into());
2021-10-14 05:34:31 -05:00
// Insert the impl block.
2021-10-14 11:19:20 -05:00
match ctx.config.snippet_cap {
Some(cap) => {
let offset = strukt.syntax().text_range().end();
let snippet = render_snippet(cap, impl_def.syntax(), cursor);
let snippet = format!("\n\n{}", snippet);
builder.insert_snippet(cap, offset, snippet);
}
None => {
let offset = strukt.syntax().text_range().end();
let snippet = format!("\n\n{}", impl_def.syntax().to_string());
builder.insert(offset, snippet);
}
}
2021-10-13 16:59:23 -05:00
}
}
2021-10-13 08:08:40 -05:00
},
)?;
}
Some(())
}
#[cfg(test)]
mod tests {
use crate::tests::{check_assist, check_assist_not_applicable};
2021-10-13 08:08:40 -05:00
use super::*;
#[test]
2021-10-14 05:34:31 -05:00
fn test_generate_delegate_create_impl_block() {
check_assist(
2021-10-14 06:52:31 -05:00
generate_delegate_methods,
2021-10-14 05:34:31 -05:00
r#"
struct Age(u8);
impl Age {
fn age(&self) -> u8 {
self.0
}
}
struct Person {
ag$0e: Age,
}"#,
r#"
struct Age(u8);
impl Age {
fn age(&self) -> u8 {
self.0
}
}
struct Person {
age: Age,
}
impl Person {
$0fn age(&self) -> u8 {
self.age.age()
}
}"#,
);
}
#[test]
fn test_generate_delegate_update_impl_block() {
2021-10-13 08:08:40 -05:00
check_assist(
2021-10-14 06:52:31 -05:00
generate_delegate_methods,
2021-10-13 08:08:40 -05:00
r#"
struct Age(u8);
impl Age {
fn age(&self) -> u8 {
self.0
}
}
struct Person {
ag$0e: Age,
}
2021-10-13 16:59:23 -05:00
2021-10-14 05:34:31 -05:00
impl Person {}"#,
2021-10-13 08:08:40 -05:00
r#"
struct Age(u8);
impl Age {
2021-10-14 05:34:31 -05:00
fn age(&self) -> u8 {
2021-10-13 08:08:40 -05:00
self.0
}
}
struct Person {
age: Age,
}
impl Person {
2021-10-14 05:34:31 -05:00
$0fn age(&self) -> u8 {
self.age.age()
}
}"#,
);
}
2021-10-14 07:18:12 -05:00
#[test]
fn test_generate_delegate_tuple_struct() {
check_assist(
generate_delegate_methods,
r#"
struct Age(u8);
impl Age {
fn age(&self) -> u8 {
self.0
}
}
struct Person(A$0ge);"#,
r#"
struct Age(u8);
impl Age {
fn age(&self) -> u8 {
self.0
}
}
struct Person(Age);
impl Person {
$0fn age(&self) -> u8 {
self.0.age()
}
}"#,
);
}
#[test]
fn test_generate_delegate_enable_all_attributes() {
check_assist(
2021-10-14 06:52:31 -05:00
generate_delegate_methods,
r#"
struct Age<T>(T);
impl<T> Age<T> {
pub(crate) async fn age<J, 'a>(&'a mut self, ty: T, arg: J) -> T {
self.0
}
}
struct Person<T> {
ag$0e: Age<T>,
}"#,
r#"
struct Age<T>(T);
impl<T> Age<T> {
pub(crate) async fn age<J, 'a>(&'a mut self, ty: T, arg: J) -> T {
self.0
}
}
struct Person<T> {
age: Age<T>,
}
impl<T> Person<T> {
2021-10-14 11:33:29 -05:00
$0pub(crate) async fn age<J, 'a>(&'a mut self, ty: T, arg: J) -> T {
2021-10-14 11:19:20 -05:00
self.age.age(ty, arg)
2021-10-13 08:08:40 -05:00
}
}"#,
);
}
#[test]
fn test_generate_delegate_visibility() {
check_assist_not_applicable(
generate_delegate_methods,
r#"
mod m {
pub struct Age(u8);
impl Age {
fn age(&self) -> u8 {
self.0
}
}
}
struct Person {
ag$0e: m::Age,
}"#,
)
}
2021-10-13 08:08:40 -05:00
}