rust-analyzer/crates/ide-assists/src/handlers/generate_delegate_methods.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

428 lines
11 KiB
Rust
Raw Normal View History

2023-04-04 06:57:02 +00:00
use std::collections::HashSet;
use hir::{self, HasCrate, HasSource, HasVisibility};
use syntax::ast::{self, make, AstNode, HasGenericParams, HasName, HasVisibility as _};
2021-10-13 13:08:40 +00:00
use crate::{
2021-10-14 16:19:20 +00:00
utils::{convert_param_list_to_arg_list, find_struct_impl, render_snippet, Cursor},
2021-10-13 13:08:40 +00:00
AssistContext, AssistId, AssistKind, Assists, GroupLabel,
};
2021-10-14 10:34:31 +00:00
use syntax::ast::edit::AstNodeEdit;
2021-10-13 13:08:40 +00:00
2021-10-14 11:52:31 +00:00
// Assist: generate_delegate_methods
2021-10-13 13:08:40 +00:00
//
2021-10-14 11:52:31 +00:00
// Generate delegate methods.
2021-10-13 13:08:40 +00:00
//
// ```
// struct Age(u8);
// impl Age {
// fn age(&self) -> u8 {
// self.0
// }
// }
//
2021-10-13 13:08:40 +00:00
// struct Person {
// ag$0e: Age,
2021-10-13 13:08:40 +00:00
// }
// ```
// ->
// ```
// struct Age(u8);
// impl Age {
// fn age(&self) -> u8 {
// self.0
// }
// }
//
2021-10-13 13:08:40 +00:00
// struct Person {
// age: Age,
2021-10-13 13:08:40 +00:00
// }
//
// impl Person {
// $0fn age(&self) -> u8 {
// self.age.age()
2021-10-13 13:08:40 +00:00
// }
// }
// ```
2022-07-20 13:02:08 +00:00
pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
2021-10-13 13:08:40 +00:00
let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
2021-10-13 21:59:23 +00:00
let strukt_name = strukt.name()?;
let current_module = ctx.sema.scope(strukt.syntax())?.module();
2021-10-13 13:08:40 +00:00
let (field_name, field_ty, target) = match ctx.find_node_at_offset::<ast::RecordField>() {
2021-10-14 12:18:12 +00:00
Some(field) => {
let field_name = field.name()?;
let field_ty = field.ty()?;
(field_name.to_string(), field_ty, field.syntax().text_range())
2021-10-14 12:18:12 +00:00
}
None => {
let field = ctx.find_node_at_offset::<ast::TupleField>()?;
let field_list = ctx.find_node_at_offset::<ast::TupleFieldList>()?;
2021-10-14 16:19:20 +00:00
let field_list_index = field_list.fields().position(|it| it == field)?;
2021-10-14 12:18:12 +00:00
let field_ty = field.ty()?;
(field_list_index.to_string(), field_ty, field.syntax().text_range())
2021-10-14 12:18:12 +00:00
}
};
2021-10-13 13:08:40 +00:00
let sema_field_ty = ctx.sema.resolve_type(&field_ty)?;
let mut methods = vec![];
2023-04-04 06:57:02 +00:00
let mut seen_names = HashSet::new();
for ty in sema_field_ty.autoderef(ctx.db()) {
2023-04-04 06:54:26 +00:00
let krate = ty.krate(ctx.db());
ty.iterate_assoc_items(ctx.db(), krate, |item| {
if let hir::AssocItem::Function(f) = item {
let name = f.name(ctx.db());
2023-04-04 06:57:02 +00:00
if f.self_param(ctx.db()).is_some()
&& f.is_visible_from(ctx.db(), current_module)
&& seen_names.insert(name.clone())
2023-04-04 06:57:02 +00:00
{
methods.push((name, f))
}
2021-10-13 13:08:40 +00:00
}
Option::<()>::None
});
}
methods.sort_by(|(a, _), (b, _)| a.cmp(b));
for (name, method) in methods {
2021-10-14 16:19:20 +00:00
let adt = ast::Adt::Struct(strukt.clone());
let name = name.display(ctx.db()).to_string();
// if `find_struct_impl` returns None, that means that a function named `name` already exists.
let Some(impl_def) = find_struct_impl(ctx, &adt, std::slice::from_ref(&name)) else { continue; };
2021-10-13 13:08:40 +00:00
acc.add_group(
2021-10-14 11:52:31 +00:00
&GroupLabel("Generate delegate methods…".to_owned()),
AssistId("generate_delegate_methods", AssistKind::Generate),
format!("Generate delegate for `{field_name}.{name}()`",),
2021-10-13 13:08:40 +00:00
target,
|builder| {
// Create the function
2021-10-14 10:34:31 +00:00
let method_source = match method.source(ctx.db()) {
Some(source) => source.value,
None => return,
};
let vis = method_source.visibility();
let fn_name = make::name(&name);
let params =
method_source.param_list().unwrap_or_else(|| make::param_list(None, []));
2021-10-14 16:19:20 +00: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 10:34:31 +00:00
let tail_expr = make::expr_method_call(
2021-10-14 12:18:12 +00:00
make::ext::field_from_idents(["self", &field_name]).unwrap(), // This unwrap is ok because we have at least 1 arg in the list
make::name_ref(&name),
2021-10-14 16:19:20 +00:00
arg_list,
2021-10-14 10:34:31 +00:00
);
2021-10-14 16:33:29 +00:00
let ret_type = method_source.ret_type();
let is_async = method_source.async_token().is_some();
let is_const = method_source.const_token().is_some();
let is_unsafe = method_source.unsafe_token().is_some();
2022-12-25 00:47:16 +00:00
let tail_expr_finished =
if is_async { make::expr_await(tail_expr) } else { tail_expr };
let body = make::block_expr([], Some(tail_expr_finished));
let f = make::fn_(
vis,
fn_name,
type_params,
None,
params,
body,
ret_type,
is_async,
is_const,
is_unsafe,
)
.indent(ast::edit::IndentLevel(1))
.clone_for_update();
2021-10-13 13:08:40 +00:00
2021-10-13 18:13:36 +00: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 21:59:23 +00:00
match impl_def {
Some(impl_def) => {
2021-10-14 10:34:31 +00:00
// Remember where in our source our `impl` block lives.
2021-10-13 21:59:23 +00:00
let impl_def = impl_def.clone_for_update();
let old_range = impl_def.syntax().text_range();
2021-10-14 10:34:31 +00:00
// Attach the function to the impl block
2021-10-13 21:59:23 +00:00
let assoc_items = impl_def.get_or_create_assoc_item_list();
assoc_items.add_item(f.clone().into());
2021-10-14 10:34:31 +00:00
// Update the impl block.
2021-10-14 16:19:20 +00: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 21:59:23 +00:00
}
None => {
2021-10-14 10:34:31 +00:00
// Attach the function to the impl block
2021-10-13 21:59:23 +00:00
let name = &strukt_name.to_string();
let params = strukt.generic_param_list();
let ty_params = params.clone();
let where_clause = strukt.where_clause();
let impl_def = make::impl_(
ty_params,
None,
make::ty_path(make::ext::ident_path(name)),
where_clause,
None,
)
.clone_for_update();
2021-10-13 21:59:23 +00:00
let assoc_items = impl_def.get_or_create_assoc_item_list();
assoc_items.add_item(f.clone().into());
2021-10-14 10:34:31 +00:00
// Insert the impl block.
2021-10-14 16:19:20 +00: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}");
2021-10-14 16:19:20 +00:00
builder.insert_snippet(cap, offset, snippet);
}
None => {
let offset = strukt.syntax().text_range().end();
let snippet = format!("\n\n{}", impl_def.syntax());
2021-10-14 16:19:20 +00:00
builder.insert(offset, snippet);
}
}
2021-10-13 21:59:23 +00:00
}
}
2021-10-13 13:08:40 +00:00
},
)?;
}
Some(())
}
#[cfg(test)]
mod tests {
use crate::tests::{check_assist, check_assist_not_applicable};
2021-10-13 13:08:40 +00:00
use super::*;
#[test]
2021-10-14 10:34:31 +00:00
fn test_generate_delegate_create_impl_block() {
check_assist(
2021-10-14 11:52:31 +00:00
generate_delegate_methods,
2021-10-14 10:34:31 +00: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 13:08:40 +00:00
check_assist(
2021-10-14 11:52:31 +00:00
generate_delegate_methods,
2021-10-13 13:08:40 +00:00
r#"
struct Age(u8);
impl Age {
fn age(&self) -> u8 {
self.0
}
}
struct Person {
ag$0e: Age,
}
2021-10-13 21:59:23 +00:00
2021-10-14 10:34:31 +00:00
impl Person {}"#,
2021-10-13 13:08:40 +00:00
r#"
struct Age(u8);
impl Age {
2021-10-14 10:34:31 +00:00
fn age(&self) -> u8 {
2021-10-13 13:08:40 +00:00
self.0
}
}
struct Person {
age: Age,
}
impl Person {
2021-10-14 10:34:31 +00:00
$0fn age(&self) -> u8 {
self.age.age()
}
}"#,
);
}
2021-10-14 12:18:12 +00: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 11:52:31 +00: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 16:33:29 +00:00
$0pub(crate) async fn age<J, 'a>(&'a mut self, ty: T, arg: J) -> T {
2022-12-25 00:47:16 +00:00
self.age.age(ty, arg).await
2021-10-13 13:08:40 +00:00
}
}"#,
);
}
#[test]
fn test_generates_delegate_autoderef() {
check_assist(
generate_delegate_methods,
r#"
//- minicore: deref
struct Age(u8);
impl Age {
fn age(&self) -> u8 {
self.0
}
}
struct AgeDeref(Age);
impl core::ops::Deref for AgeDeref { type Target = Age; }
struct Person {
ag$0e: AgeDeref,
}
impl Person {}"#,
r#"
struct Age(u8);
impl Age {
fn age(&self) -> u8 {
self.0
}
}
struct AgeDeref(Age);
impl core::ops::Deref for AgeDeref { type Target = Age; }
struct Person {
age: AgeDeref,
}
impl Person {
$0fn age(&self) -> u8 {
self.age.age()
}
}"#,
);
}
#[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,
}"#,
)
}
#[test]
fn test_generate_not_eligible_if_fn_exists() {
check_assist_not_applicable(
generate_delegate_methods,
r#"
struct Age(u8);
impl Age {
fn age(&self) -> u8 {
self.0
}
}
struct Person {
ag$0e: Age,
}
impl Person {
fn age(&self) -> u8 { 0 }
}
"#,
);
}
2021-10-13 13:08:40 +00:00
}