1 use hir::{self, HasCrate, HasSource, HasVisibility};
2 use syntax::ast::{self, make, AstNode, HasGenericParams, HasName, HasVisibility as _};
5 utils::{convert_param_list_to_arg_list, find_struct_impl, render_snippet, Cursor},
6 AssistContext, AssistId, AssistKind, Assists, GroupLabel,
8 use syntax::ast::edit::AstNodeEdit;
10 // Assist: generate_delegate_methods
12 // Generate delegate methods.
17 // fn age(&self) -> u8 {
30 // fn age(&self) -> u8 {
40 // $0fn age(&self) -> u8 {
45 pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
46 let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
47 let strukt_name = strukt.name()?;
48 let current_module = ctx.sema.scope(strukt.syntax()).module()?;
50 let (field_name, field_ty, target) = match ctx.find_node_at_offset::<ast::RecordField>() {
52 let field_name = field.name()?;
53 let field_ty = field.ty()?;
54 (format!("{}", field_name), field_ty, field.syntax().text_range())
57 let field = ctx.find_node_at_offset::<ast::TupleField>()?;
58 let field_list = ctx.find_node_at_offset::<ast::TupleFieldList>()?;
59 let field_list_index = field_list.fields().position(|it| it == field)?;
60 let field_ty = field.ty()?;
61 (format!("{}", field_list_index), field_ty, field.syntax().text_range())
65 let sema_field_ty = ctx.sema.resolve_type(&field_ty)?;
66 let krate = sema_field_ty.krate(ctx.db());
67 let mut methods = vec![];
68 sema_field_ty.iterate_assoc_items(ctx.db(), krate, |item| {
69 if let hir::AssocItem::Function(f) = item {
70 if f.self_param(ctx.db()).is_some() && f.is_visible_from(ctx.db(), current_module) {
77 for method in methods {
78 let adt = ast::Adt::Struct(strukt.clone());
79 let name = method.name(ctx.db()).to_string();
80 let impl_def = find_struct_impl(ctx, &adt, &name).flatten();
82 &GroupLabel("Generate delegate methods…".to_owned()),
83 AssistId("generate_delegate_methods", AssistKind::Generate),
84 format!("Generate delegate for `{}.{}()`", field_name, method.name(ctx.db())),
87 // Create the function
88 let method_source = match method.source(ctx.db()) {
89 Some(source) => source.value,
92 let method_name = method.name(ctx.db());
93 let vis = method_source.visibility();
94 let name = make::name(&method.name(ctx.db()).to_string());
96 method_source.param_list().unwrap_or_else(|| make::param_list(None, []));
97 let type_params = method_source.generic_param_list();
98 let arg_list = match method_source.param_list() {
99 Some(list) => convert_param_list_to_arg_list(list),
100 None => make::arg_list([]),
102 let tail_expr = make::expr_method_call(
103 make::ext::field_from_idents(["self", &field_name]).unwrap(), // This unwrap is ok because we have at least 1 arg in the list
104 make::name_ref(&method_name.to_string()),
107 let body = make::block_expr([], Some(tail_expr));
108 let ret_type = method_source.ret_type();
109 let is_async = method_source.async_token().is_some();
110 let f = make::fn_(vis, name, type_params, params, body, ret_type, is_async)
111 .indent(ast::edit::IndentLevel(1))
114 let cursor = Cursor::Before(f.syntax());
116 // Create or update an impl block, attach the function to it,
117 // then insert into our code.
120 // Remember where in our source our `impl` block lives.
121 let impl_def = impl_def.clone_for_update();
122 let old_range = impl_def.syntax().text_range();
124 // Attach the function to the impl block
125 let assoc_items = impl_def.get_or_create_assoc_item_list();
126 assoc_items.add_item(f.clone().into());
128 // Update the impl block.
129 match ctx.config.snippet_cap {
131 let snippet = render_snippet(cap, impl_def.syntax(), cursor);
132 builder.replace_snippet(cap, old_range, snippet);
135 builder.replace(old_range, impl_def.syntax().to_string());
140 // Attach the function to the impl block
141 let name = &strukt_name.to_string();
142 let params = strukt.generic_param_list();
143 let ty_params = params.clone();
144 let impl_def = make::impl_(make::ext::ident_path(name), params, ty_params)
146 let assoc_items = impl_def.get_or_create_assoc_item_list();
147 assoc_items.add_item(f.clone().into());
149 // Insert the impl block.
150 match ctx.config.snippet_cap {
152 let offset = strukt.syntax().text_range().end();
153 let snippet = render_snippet(cap, impl_def.syntax(), cursor);
154 let snippet = format!("\n\n{}", snippet);
155 builder.insert_snippet(cap, offset, snippet);
158 let offset = strukt.syntax().text_range().end();
159 let snippet = format!("\n\n{}", impl_def.syntax().to_string());
160 builder.insert(offset, snippet);
173 use crate::tests::{check_assist, check_assist_not_applicable};
178 fn test_generate_delegate_create_impl_block() {
180 generate_delegate_methods,
184 fn age(&self) -> u8 {
195 fn age(&self) -> u8 {
205 $0fn age(&self) -> u8 {
213 fn test_generate_delegate_update_impl_block() {
215 generate_delegate_methods,
219 fn age(&self) -> u8 {
232 fn age(&self) -> u8 {
242 $0fn age(&self) -> u8 {
250 fn test_generate_delegate_tuple_struct() {
252 generate_delegate_methods,
256 fn age(&self) -> u8 {
261 struct Person(A$0ge);"#,
265 fn age(&self) -> u8 {
273 $0fn age(&self) -> u8 {
281 fn test_generate_delegate_enable_all_attributes() {
283 generate_delegate_methods,
287 pub(crate) async fn age<J, 'a>(&'a mut self, ty: T, arg: J) -> T {
298 pub(crate) async fn age<J, 'a>(&'a mut self, ty: T, arg: J) -> T {
308 $0pub(crate) async fn age<J, 'a>(&'a mut self, ty: T, arg: J) -> T {
309 self.age.age(ty, arg)
316 fn test_generate_delegate_visibility() {
317 check_assist_not_applicable(
318 generate_delegate_methods,
323 fn age(&self) -> u8 {