From 9ca73528ee3aef96cc7b1784ecb44e29fdc0c194 Mon Sep 17 00:00:00 2001 From: mahdi-frms Date: Thu, 5 Aug 2021 14:00:08 +0430 Subject: [PATCH 01/10] generate method assist --- .../src/handlers/generate_function.rs | 149 ++++++++++++++++++ crates/ide_assists/src/lib.rs | 1 + crates/syntax/src/ast/make.rs | 4 + 3 files changed, 154 insertions(+) diff --git a/crates/ide_assists/src/handlers/generate_function.rs b/crates/ide_assists/src/handlers/generate_function.rs index 255f9ae4ec..3012ccf2ba 100644 --- a/crates/ide_assists/src/handlers/generate_function.rs +++ b/crates/ide_assists/src/handlers/generate_function.rs @@ -79,6 +79,35 @@ pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Optio ) } +pub(crate) fn generate_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let fn_name: ast::NameRef = ctx.find_node_at_offset()?; + let call: ast::MethodCallExpr = ctx.find_node_at_offset()?; + let module = ctx.sema.scope(call.syntax()).module(); + let ty = ctx.sema.type_of_expr(&call.receiver()?)?.as_adt()?; + + let function_builder = FunctionBuilder::from_method_call(ctx, &call, &fn_name, module)?; + let target = call.syntax().text_range(); + + acc.add( + AssistId("generate_method", AssistKind::Generate), + format!("Generate `{}` method", function_builder.fn_name), + target, + |builder| { + let function_template = function_builder.render(); + builder.edit_file(function_template.file); + let new_fn = format!( + "impl {} {{{}}}", + ty.name(ctx.sema.db), + function_template.to_string(ctx.config.snippet_cap) + ); + match ctx.config.snippet_cap { + Some(cap) => builder.insert_snippet(cap, function_template.insert_offset, new_fn), + None => builder.insert(function_template.insert_offset, new_fn), + } + }, + ) +} + struct FunctionTemplate { insert_offset: TextSize, leading_ws: String, @@ -181,6 +210,70 @@ impl FunctionBuilder { }) } + fn from_method_call( + ctx: &AssistContext, + call: &ast::MethodCallExpr, + name: &ast::NameRef, + target_module: Option, + ) -> Option { + let mut file = ctx.frange.file_id; + let target = match &target_module { + Some(target_module) => { + let module_source = target_module.definition_source(ctx.db()); + let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?; + file = in_file; + target + } + None => next_space_for_fn_after_method_call_site(call)?, + }; + let needs_pub = false; + let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?; + let fn_name = make::name(&name.text()); + let (type_params, params) = method_args(ctx, target_module, call)?; + + let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast); + let is_async = await_expr.is_some(); + + // should_render_snippet intends to express a rough level of confidence about + // the correctness of the return type. + // + // If we are able to infer some return type, and that return type is not unit, we + // don't want to render the snippet. The assumption here is in this situation the + // return type is just as likely to be correct as any other part of the generated + // function. + // + // In the case where the return type is inferred as unit it is likely that the + // user does in fact intend for this generated function to return some non unit + // type, but that the current state of their code doesn't allow that return type + // to be accurately inferred. + let (ret_ty, should_render_snippet) = { + match ctx.sema.type_of_expr(&ast::Expr::MethodCallExpr(call.clone())) { + Some(ty) if ty.is_unknown() || ty.is_unit() => (make::ty_unit(), true), + Some(ty) => { + let rendered = ty.display_source_code(ctx.db(), target_module.into()); + match rendered { + Ok(rendered) => (make::ty(&rendered), false), + Err(_) => (make::ty_unit(), true), + } + } + None => (make::ty_unit(), true), + } + }; + let ret_type = make::ret_type(ret_ty); + + Some(Self { + target, + fn_name, + type_params, + params, + ret_type, + should_render_snippet, + file, + needs_pub, + is_async, + }) + } + fn render(self) -> FunctionTemplate { let placeholder_expr = make::ext::expr_todo(); let fn_body = make::block_expr(vec![], Some(placeholder_expr)); @@ -280,6 +373,40 @@ fn fn_args( Some((None, make::param_list(None, params))) } +fn method_args( + ctx: &AssistContext, + target_module: hir::Module, + call: &ast::MethodCallExpr, +) -> Option<(Option, ast::ParamList)> { + let mut arg_names = Vec::new(); + let mut arg_types = Vec::new(); + for arg in call.arg_list()?.args() { + arg_names.push(match fn_arg_name(&arg) { + Some(name) => name, + None => String::from("arg"), + }); + arg_types.push(match fn_arg_type(ctx, target_module, &arg) { + Some(ty) => { + if ty.len() > 0 && ty.starts_with('&') { + if let Some((new_ty, _)) = useless_type_special_case("", &ty[1..].to_owned()) { + new_ty + } else { + ty + } + } else { + ty + } + } + None => String::from("()"), + }); + } + deduplicate_arg_names(&mut arg_names); + let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| { + make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty)) + }); + Some((None, make::param_list(Some(make::self_param()), params))) +} + /// Makes duplicate argument names unique by appending incrementing numbers. /// /// ``` @@ -368,6 +495,28 @@ fn next_space_for_fn_after_call_site(expr: &ast::CallExpr) -> Option Option { + let mut ancestors = expr.syntax().ancestors().peekable(); + let mut last_ancestor: Option = None; + while let Some(next_ancestor) = ancestors.next() { + match next_ancestor.kind() { + SyntaxKind::SOURCE_FILE => { + break; + } + SyntaxKind::ITEM_LIST => { + if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) { + break; + } + } + _ => {} + } + last_ancestor = Some(next_ancestor); + } + last_ancestor.map(GeneratedFunctionTarget::BehindItem) +} + fn next_space_for_fn_in_module( db: &dyn hir::db::AstDatabase, module_source: &hir::InFile, diff --git a/crates/ide_assists/src/lib.rs b/crates/ide_assists/src/lib.rs index bb9d5dd991..30b57ade14 100644 --- a/crates/ide_assists/src/lib.rs +++ b/crates/ide_assists/src/lib.rs @@ -151,6 +151,7 @@ mod handlers { generate_enum_projection_method::generate_enum_try_into_method, generate_from_impl_for_enum::generate_from_impl_for_enum, generate_function::generate_function, + generate_function::generate_method, generate_getter::generate_getter, generate_getter::generate_getter_mut, generate_impl::generate_impl, diff --git a/crates/syntax/src/ast/make.rs b/crates/syntax/src/ast/make.rs index 87faac0aa3..ec90be35a6 100644 --- a/crates/syntax/src/ast/make.rs +++ b/crates/syntax/src/ast/make.rs @@ -531,6 +531,10 @@ pub fn param(pat: ast::Pat, ty: ast::Type) -> ast::Param { ast_from_text(&format!("fn f({}: {}) {{ }}", pat, ty)) } +pub fn self_param() -> ast::SelfParam { + ast_from_text(&format!("fn f(&self) {{ }}")) +} + pub fn ret_type(ty: ast::Type) -> ast::RetType { ast_from_text(&format!("fn f() -> {} {{ }}", ty)) } From b777e498fe4122fadd6091b1529a5cdb0b0cb0d6 Mon Sep 17 00:00:00 2001 From: mahdi-frms Date: Thu, 5 Aug 2021 16:37:00 +0430 Subject: [PATCH 02/10] refactor: use single fn_args --- .../src/handlers/generate_function.rs | 66 ++++++++----------- 1 file changed, 28 insertions(+), 38 deletions(-) diff --git a/crates/ide_assists/src/handlers/generate_function.rs b/crates/ide_assists/src/handlers/generate_function.rs index 3012ccf2ba..6791392c50 100644 --- a/crates/ide_assists/src/handlers/generate_function.rs +++ b/crates/ide_assists/src/handlers/generate_function.rs @@ -6,7 +6,7 @@ use syntax::{ ast::{ self, edit::{AstNodeEdit, IndentLevel}, - make, ArgListOwner, AstNode, ModuleItemOwner, + make, ArgList, ArgListOwner, AstNode, ModuleItemOwner, }, SyntaxKind, SyntaxNode, TextSize, }; @@ -17,6 +17,20 @@ use crate::{ AssistContext, AssistId, AssistKind, Assists, }; +enum FuncExpr<'a> { + Func(&'a ast::CallExpr), + Method(&'a ast::MethodCallExpr), +} + +impl<'a> FuncExpr<'a> { + fn arg_list(&self) -> Option { + match *self { + FuncExpr::Func(fn_call) => fn_call.arg_list(), + FuncExpr::Method(m_call) => m_call.arg_list(), + } + } +} + // Assist: generate_function // // Adds a stub function with a signature matching the function under the cursor. @@ -164,7 +178,7 @@ impl FunctionBuilder { let needs_pub = target_module.is_some(); let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?; let fn_name = fn_name(path)?; - let (type_params, params) = fn_args(ctx, target_module, call)?; + let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Func(call))?; let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast); let is_async = await_expr.is_some(); @@ -229,7 +243,7 @@ impl FunctionBuilder { let needs_pub = false; let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?; let fn_name = make::name(&name.text()); - let (type_params, params) = method_args(ctx, target_module, call)?; + let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Method(call))?; let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast); let is_async = await_expr.is_some(); @@ -342,7 +356,7 @@ fn fn_name(call: &ast::Path) -> Option { fn fn_args( ctx: &AssistContext, target_module: hir::Module, - call: &ast::CallExpr, + call: FuncExpr, ) -> Option<(Option, ast::ParamList)> { let mut arg_names = Vec::new(); let mut arg_types = Vec::new(); @@ -370,41 +384,17 @@ fn fn_args( let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| { make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty)) }); - Some((None, make::param_list(None, params))) -} -fn method_args( - ctx: &AssistContext, - target_module: hir::Module, - call: &ast::MethodCallExpr, -) -> Option<(Option, ast::ParamList)> { - let mut arg_names = Vec::new(); - let mut arg_types = Vec::new(); - for arg in call.arg_list()?.args() { - arg_names.push(match fn_arg_name(&arg) { - Some(name) => name, - None => String::from("arg"), - }); - arg_types.push(match fn_arg_type(ctx, target_module, &arg) { - Some(ty) => { - if ty.len() > 0 && ty.starts_with('&') { - if let Some((new_ty, _)) = useless_type_special_case("", &ty[1..].to_owned()) { - new_ty - } else { - ty - } - } else { - ty - } - } - None => String::from("()"), - }); - } - deduplicate_arg_names(&mut arg_names); - let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| { - make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty)) - }); - Some((None, make::param_list(Some(make::self_param()), params))) + Some(( + None, + make::param_list( + match call { + FuncExpr::Func(_) => None, + FuncExpr::Method(_) => Some(make::self_param()), + }, + params, + ), + )) } /// Makes duplicate argument names unique by appending incrementing numbers. From 99570f32d863504946bde3151eb02b7ca97f9399 Mon Sep 17 00:00:00 2001 From: mahdi-frms Date: Thu, 5 Aug 2021 16:48:51 +0430 Subject: [PATCH 03/10] refactor: use single next space --- .../src/handlers/generate_function.rs | 35 ++++++------------- 1 file changed, 10 insertions(+), 25 deletions(-) diff --git a/crates/ide_assists/src/handlers/generate_function.rs b/crates/ide_assists/src/handlers/generate_function.rs index 6791392c50..bd1be5f98d 100644 --- a/crates/ide_assists/src/handlers/generate_function.rs +++ b/crates/ide_assists/src/handlers/generate_function.rs @@ -29,6 +29,13 @@ impl<'a> FuncExpr<'a> { FuncExpr::Method(m_call) => m_call.arg_list(), } } + + fn syntax(&self) -> &SyntaxNode { + match *self { + FuncExpr::Func(fn_call) => fn_call.syntax(), + FuncExpr::Method(m_call) => m_call.syntax(), + } + } } // Assist: generate_function @@ -173,7 +180,7 @@ impl FunctionBuilder { file = in_file; target } - None => next_space_for_fn_after_call_site(call)?, + None => next_space_for_fn_after_call_site(FuncExpr::Func(call))?, }; let needs_pub = target_module.is_some(); let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?; @@ -238,7 +245,7 @@ impl FunctionBuilder { file = in_file; target } - None => next_space_for_fn_after_method_call_site(call)?, + None => next_space_for_fn_after_call_site(FuncExpr::Method(call))?, }; let needs_pub = false; let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?; @@ -465,29 +472,7 @@ fn fn_arg_type( /// directly after the current block /// We want to write the generated function directly after /// fns, impls or macro calls, but inside mods -fn next_space_for_fn_after_call_site(expr: &ast::CallExpr) -> Option { - let mut ancestors = expr.syntax().ancestors().peekable(); - let mut last_ancestor: Option = None; - while let Some(next_ancestor) = ancestors.next() { - match next_ancestor.kind() { - SyntaxKind::SOURCE_FILE => { - break; - } - SyntaxKind::ITEM_LIST => { - if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) { - break; - } - } - _ => {} - } - last_ancestor = Some(next_ancestor); - } - last_ancestor.map(GeneratedFunctionTarget::BehindItem) -} - -fn next_space_for_fn_after_method_call_site( - expr: &ast::MethodCallExpr, -) -> Option { +fn next_space_for_fn_after_call_site(expr: FuncExpr) -> Option { let mut ancestors = expr.syntax().ancestors().peekable(); let mut last_ancestor: Option = None; while let Some(next_ancestor) = ancestors.next() { From d38f36e5af9d58ba4b2d234bfad2f7ec8b444674 Mon Sep 17 00:00:00 2001 From: mahdi-frms Date: Sat, 7 Aug 2021 11:29:49 +0430 Subject: [PATCH 04/10] generate method assist uses existing impl blocks --- .../src/handlers/generate_function.rs | 81 ++++++++++++++----- 1 file changed, 60 insertions(+), 21 deletions(-) diff --git a/crates/ide_assists/src/handlers/generate_function.rs b/crates/ide_assists/src/handlers/generate_function.rs index bd1be5f98d..eb69808649 100644 --- a/crates/ide_assists/src/handlers/generate_function.rs +++ b/crates/ide_assists/src/handlers/generate_function.rs @@ -1,4 +1,4 @@ -use hir::{HirDisplay, TypeInfo}; +use hir::{HasSource, HirDisplay, InFile, Module, TypeInfo}; use ide_db::{base_db::FileId, helpers::SnippetCap}; use rustc_hash::{FxHashMap, FxHashSet}; use stdx::to_lower_snake_case; @@ -13,7 +13,7 @@ use syntax::{ use crate::{ utils::useless_type_special_case, - utils::{render_snippet, Cursor}, + utils::{find_struct_impl, render_snippet, Cursor}, AssistContext, AssistId, AssistKind, Assists, }; @@ -103,10 +103,22 @@ pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Optio pub(crate) fn generate_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { let fn_name: ast::NameRef = ctx.find_node_at_offset()?; let call: ast::MethodCallExpr = ctx.find_node_at_offset()?; - let module = ctx.sema.scope(call.syntax()).module(); - let ty = ctx.sema.type_of_expr(&call.receiver()?)?.as_adt()?; + let ty = ctx.sema.type_of_expr(&call.receiver()?)?.original().strip_references().as_adt()?; - let function_builder = FunctionBuilder::from_method_call(ctx, &call, &fn_name, module)?; + let (impl_, file) = match ty { + hir::Adt::Struct(strukt) => get_impl(strukt.source(ctx.sema.db)?.syntax(), &fn_name, ctx), + hir::Adt::Enum(en) => get_impl(en.source(ctx.sema.db)?.syntax(), &fn_name, ctx), + hir::Adt::Union(union) => get_impl(union.source(ctx.sema.db)?.syntax(), &fn_name, ctx), + }?; + + let function_builder = FunctionBuilder::from_method_call( + ctx, + &call, + &fn_name, + &impl_, + file, + ty.module(ctx.sema.db), + )?; let target = call.syntax().text_range(); acc.add( @@ -116,11 +128,10 @@ pub(crate) fn generate_method(acc: &mut Assists, ctx: &AssistContext) -> Option< |builder| { let function_template = function_builder.render(); builder.edit_file(function_template.file); - let new_fn = format!( - "impl {} {{{}}}", - ty.name(ctx.sema.db), - function_template.to_string(ctx.config.snippet_cap) - ); + let mut new_fn = function_template.to_string(ctx.config.snippet_cap); + if impl_.is_none() { + new_fn = format!("\nimpl {} {{\n {}\n}}", ty.name(ctx.sema.db), new_fn,); + } match ctx.config.snippet_cap { Some(cap) => builder.insert_snippet(cap, function_template.insert_offset, new_fn), None => builder.insert(function_template.insert_offset, new_fn), @@ -129,6 +140,18 @@ pub(crate) fn generate_method(acc: &mut Assists, ctx: &AssistContext) -> Option< ) } +fn get_impl( + adt: InFile<&SyntaxNode>, + fn_name: &ast::NameRef, + ctx: &AssistContext, +) -> Option<(Option, FileId)> { + let file = adt.file_id.original_file(ctx.sema.db); + let adt = adt.value; + let adt = ast::Adt::cast(adt.clone())?; + let r = find_struct_impl(ctx, &adt, fn_name.text().as_str())?; + Some((r, file)) +} + struct FunctionTemplate { insert_offset: TextSize, leading_ws: String, @@ -235,20 +258,24 @@ impl FunctionBuilder { ctx: &AssistContext, call: &ast::MethodCallExpr, name: &ast::NameRef, - target_module: Option, + impl_: &Option, + file: FileId, + target_module: Module, ) -> Option { - let mut file = ctx.frange.file_id; - let target = match &target_module { - Some(target_module) => { - let module_source = target_module.definition_source(ctx.db()); - let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?; - file = in_file; - target + // let mut file = ctx.frange.file_id; + // let target_module = ctx.sema.scope(call.syntax()).module()?; + let target = match impl_ { + Some(impl_) => next_space_for_fn_in_impl(&impl_)?, + None => { + next_space_for_fn_in_module( + ctx.sema.db, + &target_module.definition_source(ctx.sema.db), + )? + .1 } - None => next_space_for_fn_after_call_site(FuncExpr::Method(call))?, }; + let needs_pub = false; - let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?; let fn_name = make::name(&name.text()); let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Method(call))?; @@ -268,7 +295,11 @@ impl FunctionBuilder { // type, but that the current state of their code doesn't allow that return type // to be accurately inferred. let (ret_ty, should_render_snippet) = { - match ctx.sema.type_of_expr(&ast::Expr::MethodCallExpr(call.clone())) { + match ctx + .sema + .type_of_expr(&ast::Expr::MethodCallExpr(call.clone())) + .map(TypeInfo::original) + { Some(ty) if ty.is_unknown() || ty.is_unit() => (make::ty_unit(), true), Some(ty) => { let rendered = ty.display_source_code(ctx.db(), target_module.into()); @@ -525,6 +556,14 @@ fn next_space_for_fn_in_module( Some((file, assist_item)) } +fn next_space_for_fn_in_impl(impl_: &ast::Impl) -> Option { + if let Some(last_item) = impl_.assoc_item_list().and_then(|it| it.assoc_items().last()) { + Some(GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())) + } else { + Some(GeneratedFunctionTarget::InEmptyItemList(impl_.assoc_item_list()?.syntax().clone())) + } +} + #[cfg(test)] mod tests { use crate::tests::{check_assist, check_assist_not_applicable}; From 6240b2dae291a5999163cf8204bdc1597f4c30c1 Mon Sep 17 00:00:00 2001 From: mahdi-frms Date: Sat, 7 Aug 2021 13:59:33 +0430 Subject: [PATCH 05/10] generate method adds pub keyword --- .../src/handlers/generate_function.rs | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/ide_assists/src/handlers/generate_function.rs b/crates/ide_assists/src/handlers/generate_function.rs index eb69808649..8d0ac4ae7b 100644 --- a/crates/ide_assists/src/handlers/generate_function.rs +++ b/crates/ide_assists/src/handlers/generate_function.rs @@ -105,6 +105,14 @@ pub(crate) fn generate_method(acc: &mut Assists, ctx: &AssistContext) -> Option< let call: ast::MethodCallExpr = ctx.find_node_at_offset()?; let ty = ctx.sema.type_of_expr(&call.receiver()?)?.original().strip_references().as_adt()?; + let current_module = + ctx.sema.scope(ctx.find_node_at_offset::()?.syntax()).module()?; + let target_module = ty.module(ctx.sema.db); + + if current_module.krate() != target_module.krate() { + return None; + } + let (impl_, file) = match ty { hir::Adt::Struct(strukt) => get_impl(strukt.source(ctx.sema.db)?.syntax(), &fn_name, ctx), hir::Adt::Enum(en) => get_impl(en.source(ctx.sema.db)?.syntax(), &fn_name, ctx), @@ -117,7 +125,8 @@ pub(crate) fn generate_method(acc: &mut Assists, ctx: &AssistContext) -> Option< &fn_name, &impl_, file, - ty.module(ctx.sema.db), + target_module, + current_module, )?; let target = call.syntax().text_range(); @@ -261,6 +270,7 @@ impl FunctionBuilder { impl_: &Option, file: FileId, target_module: Module, + current_module: Module, ) -> Option { // let mut file = ctx.frange.file_id; // let target_module = ctx.sema.scope(call.syntax()).module()?; @@ -274,8 +284,8 @@ impl FunctionBuilder { .1 } }; + let needs_pub = !module_is_descendant(¤t_module, &target_module, ctx); - let needs_pub = false; let fn_name = make::name(&name.text()); let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Method(call))?; @@ -564,6 +574,18 @@ fn next_space_for_fn_in_impl(impl_: &ast::Impl) -> Option bool { + if module == ans { + return true; + } + for c in ans.children(ctx.sema.db) { + if module_is_descendant(module, &c, ctx) { + return true; + } + } + false +} + #[cfg(test)] mod tests { use crate::tests::{check_assist, check_assist_not_applicable}; From 02f5b5e0e253e61744e726ff3f190d2d1671f16e Mon Sep 17 00:00:00 2001 From: mahdi-frms Date: Sun, 8 Aug 2021 17:21:34 +0430 Subject: [PATCH 06/10] method generation assist: store owned ast nodes --- .../src/handlers/generate_function.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/ide_assists/src/handlers/generate_function.rs b/crates/ide_assists/src/handlers/generate_function.rs index 8d0ac4ae7b..426f20cd15 100644 --- a/crates/ide_assists/src/handlers/generate_function.rs +++ b/crates/ide_assists/src/handlers/generate_function.rs @@ -17,21 +17,21 @@ use crate::{ AssistContext, AssistId, AssistKind, Assists, }; -enum FuncExpr<'a> { - Func(&'a ast::CallExpr), - Method(&'a ast::MethodCallExpr), +enum FuncExpr { + Func(ast::CallExpr), + Method(ast::MethodCallExpr), } -impl<'a> FuncExpr<'a> { +impl FuncExpr { fn arg_list(&self) -> Option { - match *self { + match self { FuncExpr::Func(fn_call) => fn_call.arg_list(), FuncExpr::Method(m_call) => m_call.arg_list(), } } fn syntax(&self) -> &SyntaxNode { - match *self { + match self { FuncExpr::Func(fn_call) => fn_call.syntax(), FuncExpr::Method(m_call) => m_call.syntax(), } @@ -212,12 +212,12 @@ impl FunctionBuilder { file = in_file; target } - None => next_space_for_fn_after_call_site(FuncExpr::Func(call))?, + None => next_space_for_fn_after_call_site(FuncExpr::Func(call.clone()))?, }; let needs_pub = target_module.is_some(); let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?; let fn_name = fn_name(path)?; - let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Func(call))?; + let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Func(call.clone()))?; let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast); let is_async = await_expr.is_some(); @@ -287,7 +287,7 @@ impl FunctionBuilder { let needs_pub = !module_is_descendant(¤t_module, &target_module, ctx); let fn_name = make::name(&name.text()); - let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Method(call))?; + let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Method(call.clone()))?; let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast); let is_async = await_expr.is_some(); From 3c31f3831d86b599dc6cb5a9a2fa09a59731c4e0 Mon Sep 17 00:00:00 2001 From: mahdi-frms Date: Sun, 8 Aug 2021 17:44:05 +0430 Subject: [PATCH 07/10] One assist for function and method generation --- crates/ide_assists/src/handlers/generate_function.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ide_assists/src/handlers/generate_function.rs b/crates/ide_assists/src/handlers/generate_function.rs index 426f20cd15..50d3a74f27 100644 --- a/crates/ide_assists/src/handlers/generate_function.rs +++ b/crates/ide_assists/src/handlers/generate_function.rs @@ -131,8 +131,8 @@ pub(crate) fn generate_method(acc: &mut Assists, ctx: &AssistContext) -> Option< let target = call.syntax().text_range(); acc.add( - AssistId("generate_method", AssistKind::Generate), - format!("Generate `{}` method", function_builder.fn_name), + AssistId("generate_function", AssistKind::Generate), + format!("Generate `{}` function", function_builder.fn_name), target, |builder| { let function_template = function_builder.render(); From 311dc5b04f0c41358714a88e097bbf2735deeb99 Mon Sep 17 00:00:00 2001 From: mahdi-frms Date: Mon, 9 Aug 2021 18:55:10 +0430 Subject: [PATCH 08/10] add test for method generation assist --- .../src/handlers/generate_function.rs | 125 +++++++++++++++++- 1 file changed, 124 insertions(+), 1 deletion(-) diff --git a/crates/ide_assists/src/handlers/generate_function.rs b/crates/ide_assists/src/handlers/generate_function.rs index 50d3a74f27..7321c1f38e 100644 --- a/crates/ide_assists/src/handlers/generate_function.rs +++ b/crates/ide_assists/src/handlers/generate_function.rs @@ -139,7 +139,7 @@ pub(crate) fn generate_method(acc: &mut Assists, ctx: &AssistContext) -> Option< builder.edit_file(function_template.file); let mut new_fn = function_template.to_string(ctx.config.snippet_cap); if impl_.is_none() { - new_fn = format!("\nimpl {} {{\n {}\n}}", ty.name(ctx.sema.db), new_fn,); + new_fn = format!("\nimpl {} {{\n{}\n}}", ty.name(ctx.sema.db), new_fn,); } match ctx.config.snippet_cap { Some(cap) => builder.insert_snippet(cap, function_template.insert_offset, new_fn), @@ -1380,6 +1380,129 @@ fn foo() { async fn bar(arg: i32) ${0:-> ()} { todo!() } +", + ) + } + + #[test] + fn create_method() { + check_assist( + generate_method, + r" +struct S; + +fn foo() { + S.bar$0(); +} + +", + r" +struct S; + +fn foo() { + S.bar(); +} +impl S { + + +fn bar(&self) ${0:-> ()} { + todo!() +} +} + +", + ) + } + + #[test] + fn create_method_within_an_impl() { + check_assist( + generate_method, + r" +struct S; + +fn foo() { + S.bar$0(); +} +impl S {} + +", + r" +struct S; + +fn foo() { + S.bar(); +} +impl S { + fn bar(&self) ${0:-> ()} { + todo!() + } +} + +", + ) + } + + #[test] + fn create_method_from_different_module() { + check_assist( + generate_method, + r" +mod s { + pub struct S; +} +fn foo() { + s::S.bar$0(); +} + +", + r" +mod s { + pub struct S; +impl S { + + + pub(crate) fn bar(&self) ${0:-> ()} { + todo!() + } +} +} +fn foo() { + s::S.bar(); +} + +", + ) + } + + #[test] + fn create_method_from_descendant_module() { + check_assist( + generate_method, + r" +struct S; +mod s { + fn foo() { + super::S.bar$0(); + } +} + +", + r" +struct S; +mod s { + fn foo() { + super::S.bar(); + } +} +impl S { + + +fn bar(&self) ${0:-> ()} { + todo!() +} +} + ", ) } From 9217f6dcf73ee9dd9fae8888ed33ada96ec49110 Mon Sep 17 00:00:00 2001 From: mahdi-frms Date: Mon, 9 Aug 2021 19:21:15 +0430 Subject: [PATCH 09/10] method gen assist usable in all of expression --- .../src/handlers/generate_function.rs | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/ide_assists/src/handlers/generate_function.rs b/crates/ide_assists/src/handlers/generate_function.rs index 7321c1f38e..39756611dd 100644 --- a/crates/ide_assists/src/handlers/generate_function.rs +++ b/crates/ide_assists/src/handlers/generate_function.rs @@ -101,8 +101,10 @@ pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Optio } pub(crate) fn generate_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { - let fn_name: ast::NameRef = ctx.find_node_at_offset()?; let call: ast::MethodCallExpr = ctx.find_node_at_offset()?; + let fn_name: ast::NameRef = ast::NameRef::cast( + call.syntax().children().find(|child| child.kind() == SyntaxKind::NAME_REF)?, + )?; let ty = ctx.sema.type_of_expr(&call.receiver()?)?.original().strip_references().as_adt()?; let current_module = @@ -1498,6 +1500,36 @@ mod s { impl S { +fn bar(&self) ${0:-> ()} { + todo!() +} +} + +", + ) + } + + #[test] + fn create_method_with_cursor_anywhere_on_call_expresion() { + check_assist( + generate_method, + r" +struct S; + +fn foo() { + $0S.bar(); +} + +", + r" +struct S; + +fn foo() { + S.bar(); +} +impl S { + + fn bar(&self) ${0:-> ()} { todo!() } From 05a789c09dbe886c82eaece6b2af134de6d277de Mon Sep 17 00:00:00 2001 From: mahdi-frms Date: Mon, 9 Aug 2021 20:37:07 +0430 Subject: [PATCH 10/10] refactor method generation assist --- .../src/handlers/generate_function.rs | 121 ++++++++---------- crates/ide_assists/src/lib.rs | 1 - 2 files changed, 54 insertions(+), 68 deletions(-) diff --git a/crates/ide_assists/src/handlers/generate_function.rs b/crates/ide_assists/src/handlers/generate_function.rs index 39756611dd..cb281d5dcb 100644 --- a/crates/ide_assists/src/handlers/generate_function.rs +++ b/crates/ide_assists/src/handlers/generate_function.rs @@ -6,7 +6,7 @@ use syntax::{ ast::{ self, edit::{AstNodeEdit, IndentLevel}, - make, ArgList, ArgListOwner, AstNode, ModuleItemOwner, + make, ArgListOwner, AstNode, ModuleItemOwner, }, SyntaxKind, SyntaxNode, TextSize, }; @@ -17,27 +17,6 @@ use crate::{ AssistContext, AssistId, AssistKind, Assists, }; -enum FuncExpr { - Func(ast::CallExpr), - Method(ast::MethodCallExpr), -} - -impl FuncExpr { - fn arg_list(&self) -> Option { - match self { - FuncExpr::Func(fn_call) => fn_call.arg_list(), - FuncExpr::Method(m_call) => m_call.arg_list(), - } - } - - fn syntax(&self) -> &SyntaxNode { - match self { - FuncExpr::Func(fn_call) => fn_call.syntax(), - FuncExpr::Method(m_call) => m_call.syntax(), - } - } -} - // Assist: generate_function // // Adds a stub function with a signature matching the function under the cursor. @@ -64,6 +43,31 @@ impl FuncExpr { // // ``` pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + gen_fn(acc, ctx).or_else(|| gen_method(acc, ctx)) +} + +enum FuncExpr { + Func(ast::CallExpr), + Method(ast::MethodCallExpr), +} + +impl FuncExpr { + fn arg_list(&self) -> Option { + match self { + FuncExpr::Func(fn_call) => fn_call.arg_list(), + FuncExpr::Method(m_call) => m_call.arg_list(), + } + } + + fn syntax(&self) -> &SyntaxNode { + match self { + FuncExpr::Func(fn_call) => fn_call.syntax(), + FuncExpr::Method(m_call) => m_call.syntax(), + } + } +} + +fn gen_fn(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { let path_expr: ast::PathExpr = ctx.find_node_at_offset()?; let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?; @@ -100,7 +104,7 @@ pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Optio ) } -pub(crate) fn generate_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { +fn gen_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { let call: ast::MethodCallExpr = ctx.find_node_at_offset()?; let fn_name: ast::NameRef = ast::NameRef::cast( call.syntax().children().find(|child| child.kind() == SyntaxKind::NAME_REF)?, @@ -1351,8 +1355,7 @@ fn bar(baz: ()) {} #[test] fn create_method_with_no_args() { - // FIXME: This is wrong, this should just work. - check_assist_not_applicable( + check_assist( generate_function, r#" struct Foo; @@ -1361,7 +1364,19 @@ impl Foo { self.bar()$0; } } - "#, +"#, + r#" +struct Foo; +impl Foo { + fn foo(&self) { + self.bar(); + } + + fn bar(&self) ${0:-> ()} { + todo!() + } +} +"#, ) } @@ -1389,21 +1404,14 @@ async fn bar(arg: i32) ${0:-> ()} { #[test] fn create_method() { check_assist( - generate_method, + generate_function, r" struct S; - -fn foo() { - S.bar$0(); -} - +fn foo() {S.bar$0();} ", r" struct S; - -fn foo() { - S.bar(); -} +fn foo() {S.bar();} impl S { @@ -1411,7 +1419,6 @@ fn bar(&self) ${0:-> ()} { todo!() } } - ", ) } @@ -1419,22 +1426,16 @@ fn bar(&self) ${0:-> ()} { #[test] fn create_method_within_an_impl() { check_assist( - generate_method, + generate_function, r" struct S; - -fn foo() { - S.bar$0(); -} +fn foo() {S.bar$0();} impl S {} ", r" struct S; - -fn foo() { - S.bar(); -} +fn foo() {S.bar();} impl S { fn bar(&self) ${0:-> ()} { todo!() @@ -1448,15 +1449,12 @@ impl S { #[test] fn create_method_from_different_module() { check_assist( - generate_method, + generate_function, r" mod s { pub struct S; } -fn foo() { - s::S.bar$0(); -} - +fn foo() {s::S.bar$0();} ", r" mod s { @@ -1469,10 +1467,7 @@ impl S { } } } -fn foo() { - s::S.bar(); -} - +fn foo() {s::S.bar();} ", ) } @@ -1480,7 +1475,7 @@ fn foo() { #[test] fn create_method_from_descendant_module() { check_assist( - generate_method, + generate_function, r" struct S; mod s { @@ -1512,21 +1507,14 @@ fn bar(&self) ${0:-> ()} { #[test] fn create_method_with_cursor_anywhere_on_call_expresion() { check_assist( - generate_method, + generate_function, r" struct S; - -fn foo() { - $0S.bar(); -} - +fn foo() {$0S.bar();} ", r" struct S; - -fn foo() { - S.bar(); -} +fn foo() {S.bar();} impl S { @@ -1534,7 +1522,6 @@ fn bar(&self) ${0:-> ()} { todo!() } } - ", ) } diff --git a/crates/ide_assists/src/lib.rs b/crates/ide_assists/src/lib.rs index 30b57ade14..bb9d5dd991 100644 --- a/crates/ide_assists/src/lib.rs +++ b/crates/ide_assists/src/lib.rs @@ -151,7 +151,6 @@ mod handlers { generate_enum_projection_method::generate_enum_try_into_method, generate_from_impl_for_enum::generate_from_impl_for_enum, generate_function::generate_function, - generate_function::generate_method, generate_getter::generate_getter, generate_getter::generate_getter_mut, generate_impl::generate_impl,