1 use hir::{HasSource, HirDisplay, Module, TypeInfo};
2 use ide_db::{base_db::FileId, helpers::SnippetCap};
3 use rustc_hash::{FxHashMap, FxHashSet};
4 use stdx::to_lower_snake_case;
8 edit::{AstNodeEdit, IndentLevel},
9 make, ArgListOwner, AstNode, ModuleItemOwner,
11 SyntaxKind, SyntaxNode, TextRange, TextSize,
15 utils::useless_type_special_case,
16 utils::{find_struct_impl, render_snippet, Cursor},
17 AssistContext, AssistId, AssistKind, Assists,
20 // Assist: generate_function
22 // Adds a stub function with a signature matching the function under the cursor.
26 // fn baz() -> Baz { Baz }
35 // fn baz() -> Baz { Baz }
40 // fn bar(arg: &str, baz: Baz) ${0:-> ()} {
45 pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
46 gen_fn(acc, ctx).or_else(|| gen_method(acc, ctx))
51 Method(ast::MethodCallExpr),
55 fn arg_list(&self) -> Option<ast::ArgList> {
57 FuncExpr::Func(fn_call) => fn_call.arg_list(),
58 FuncExpr::Method(m_call) => m_call.arg_list(),
62 fn syntax(&self) -> &SyntaxNode {
64 FuncExpr::Func(fn_call) => fn_call.syntax(),
65 FuncExpr::Method(m_call) => m_call.syntax(),
70 fn gen_fn(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
71 let path_expr: ast::PathExpr = ctx.find_node_at_offset()?;
72 let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?;
74 let path = path_expr.path()?;
75 if ctx.sema.resolve_path(&path).is_some() {
76 // The function call already resolves, no need to add a function
80 let target_module = match path.qualifier() {
81 Some(qualifier) => match ctx.sema.resolve_path(&qualifier) {
82 Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => Some(module),
88 let (function_builder, inserting_offset, file) =
89 FunctionBuilder::from_call(ctx, &call, &path, target_module)?;
90 let target = call.syntax().text_range();
91 add_func_to_accumulator(acc, ctx, target, function_builder, inserting_offset, file, None)
94 fn gen_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
95 let call: ast::MethodCallExpr = ctx.find_node_at_offset()?;
96 let fn_name = call.name_ref()?;
97 let adt = ctx.sema.type_of_expr(&call.receiver()?)?.original().strip_references().as_adt()?;
99 let current_module = current_module(call.syntax(), ctx)?;
100 let target_module = adt.module(ctx.sema.db);
102 if current_module.krate() != target_module.krate() {
106 let range = adt.source(ctx.sema.db)?.syntax().original_file_range(ctx.sema.db);
107 let file = ctx.sema.parse(range.file_id);
109 ctx.sema.find_node_at_offset_with_macros(file.syntax(), range.range.start())?;
110 let impl_ = find_struct_impl(ctx, &adt_source, fn_name.text().as_str())?;
112 let (function_builder, inserting_offset, file) = FunctionBuilder::from_method_call(
121 let target = call.syntax().text_range();
122 let adt_name = if impl_.is_none() { Some(adt.name(ctx.sema.db)) } else { None };
123 add_func_to_accumulator(acc, ctx, target, function_builder, inserting_offset, file, adt_name)
126 fn add_func_to_accumulator(
130 function_builder: FunctionBuilder,
131 insert_offset: TextSize,
133 adt_name: Option<hir::Name>,
136 AssistId("generate_function", AssistKind::Generate),
137 format!("Generate `{}` method", function_builder.fn_name),
140 let function_template = function_builder.render();
141 let mut func = function_template.to_string(ctx.config.snippet_cap);
142 if let Some(name) = adt_name {
143 func = format!("\nimpl {} {{\n{}\n}}", name, func);
145 builder.edit_file(file);
146 match ctx.config.snippet_cap {
147 Some(cap) => builder.insert_snippet(cap, insert_offset, func),
148 None => builder.insert(insert_offset, func),
154 fn current_module(current_node: &SyntaxNode, ctx: &AssistContext) -> Option<Module> {
155 ctx.sema.scope(current_node).module()
158 struct FunctionTemplate {
161 ret_type: Option<ast::RetType>,
162 should_focus_return_type: bool,
164 tail_expr: ast::Expr,
167 impl FunctionTemplate {
168 fn to_string(&self, cap: Option<SnippetCap>) -> String {
171 let cursor = if self.should_focus_return_type {
172 // Focus the return type if there is one
173 if let Some(ref ret_type) = self.ret_type {
176 self.tail_expr.syntax()
179 self.tail_expr.syntax()
181 render_snippet(cap, self.fn_def.syntax(), Cursor::Replace(cursor))
183 None => self.fn_def.to_string(),
186 format!("{}{}{}", self.leading_ws, f, self.trailing_ws)
190 struct FunctionBuilder {
191 target: GeneratedFunctionTarget,
193 type_params: Option<ast::GenericParamList>,
194 params: ast::ParamList,
195 ret_type: Option<ast::RetType>,
196 should_focus_return_type: bool,
202 impl FunctionBuilder {
203 /// Prepares a generated function that matches `call`.
204 /// The function is generated in `target_module` or next to `call`
207 call: &ast::CallExpr,
209 target_module: Option<hir::Module>,
210 ) -> Option<(Self, TextSize, FileId)> {
211 let mut file = ctx.frange.file_id;
212 let target = match &target_module {
213 Some(target_module) => {
214 let module_source = target_module.definition_source(ctx.db());
215 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?;
219 None => next_space_for_fn_after_call_site(FuncExpr::Func(call.clone()))?,
221 let needs_pub = target_module.is_some();
222 let target_module = target_module.or_else(|| current_module(target.syntax(), ctx))?;
223 let fn_name = fn_name(path)?;
224 let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Func(call.clone()))?;
226 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
227 let is_async = await_expr.is_some();
229 let (ret_type, should_focus_return_type) =
230 make_return_type(ctx, &ast::Expr::CallExpr(call.clone()), target_module);
232 let insert_offset = match &target {
233 GeneratedFunctionTarget::BehindItem(it) => it.text_range().end(),
234 GeneratedFunctionTarget::InEmptyItemList(it) => {
235 it.text_range().start() + TextSize::of('{')
246 should_focus_return_type,
258 call: &ast::MethodCallExpr,
260 impl_: &Option<ast::Impl>,
262 target_module: Module,
263 current_module: Module,
264 ) -> Option<(Self, TextSize, FileId)> {
265 let target = match impl_ {
266 Some(impl_) => next_space_for_fn_in_impl(&impl_)?,
268 next_space_for_fn_in_module(
270 &target_module.definition_source(ctx.sema.db),
275 let needs_pub = !module_is_descendant(¤t_module, &target_module, ctx);
277 let fn_name = make::name(&name.text());
278 let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Method(call.clone()))?;
280 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
281 let is_async = await_expr.is_some();
283 let (ret_type, should_focus_return_type) =
284 make_return_type(ctx, &ast::Expr::MethodCallExpr(call.clone()), target_module);
286 let insert_offset = match &target {
287 GeneratedFunctionTarget::BehindItem(it) => it.text_range().end(),
288 GeneratedFunctionTarget::InEmptyItemList(it) => {
289 it.text_range().start() + TextSize::of('{')
300 should_focus_return_type,
310 fn render(self) -> FunctionTemplate {
311 let placeholder_expr = make::ext::expr_todo();
312 let fn_body = make::block_expr(vec![], Some(placeholder_expr));
313 let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None };
314 let mut fn_def = make::fn_(
327 GeneratedFunctionTarget::BehindItem(it) => {
328 let indent = IndentLevel::from_node(&it);
329 leading_ws = format!("\n\n{}", indent);
330 fn_def = fn_def.indent(indent);
331 trailing_ws = String::new();
333 GeneratedFunctionTarget::InEmptyItemList(it) => {
334 let indent = IndentLevel::from_node(&it);
335 leading_ws = format!("\n{}", indent + 1);
336 fn_def = fn_def.indent(indent + 1);
337 trailing_ws = format!("\n{}", indent);
343 ret_type: fn_def.ret_type(),
344 // PANIC: we guarantee we always create a function body with a tail expr
345 tail_expr: fn_def.body().unwrap().tail_expr().unwrap(),
346 should_focus_return_type: self.should_focus_return_type,
353 /// Makes an optional return type along with whether the return type should be focused by the cursor.
354 /// If we cannot infer what the return type should be, we create unit as a placeholder.
356 /// The rule for whether we focus a return type or not (and thus focus the function body),
357 /// is rather simple:
358 /// * If we could *not* infer what the return type should be, focus it (so the user can fill-in
359 /// the correct return type).
360 /// * If we could infer the return type, don't focus it (and thus focus the function body) so the
361 /// user can change the `todo!` function body.
365 target_module: Module,
366 ) -> (Option<ast::RetType>, bool) {
367 let (ret_ty, should_focus_return_type) = {
368 match ctx.sema.type_of_expr(call).map(TypeInfo::original) {
369 Some(ty) if ty.is_unknown() => (Some(make::ty_unit()), true),
370 None => (Some(make::ty_unit()), true),
371 Some(ty) if ty.is_unit() => (None, false),
373 let rendered = ty.display_source_code(ctx.db(), target_module.into());
375 Ok(rendered) => (Some(make::ty(&rendered)), false),
376 Err(_) => (Some(make::ty_unit()), true),
381 let ret_type = ret_ty.map(|rt| make::ret_type(rt));
382 (ret_type, should_focus_return_type)
385 enum GeneratedFunctionTarget {
386 BehindItem(SyntaxNode),
387 InEmptyItemList(SyntaxNode),
390 impl GeneratedFunctionTarget {
391 fn syntax(&self) -> &SyntaxNode {
393 GeneratedFunctionTarget::BehindItem(it) => it,
394 GeneratedFunctionTarget::InEmptyItemList(it) => it,
399 fn fn_name(call: &ast::Path) -> Option<ast::Name> {
400 let name = call.segment()?.syntax().to_string();
401 Some(make::name(&name))
404 /// Computes the type variables and arguments required for the generated function
407 target_module: hir::Module,
409 ) -> Option<(Option<ast::GenericParamList>, ast::ParamList)> {
410 let mut arg_names = Vec::new();
411 let mut arg_types = Vec::new();
412 for arg in call.arg_list()?.args() {
413 arg_names.push(match fn_arg_name(&arg) {
415 None => String::from("arg"),
417 arg_types.push(match fn_arg_type(ctx, target_module, &arg) {
419 if ty.len() > 0 && ty.starts_with('&') {
420 if let Some((new_ty, _)) = useless_type_special_case("", &ty[1..].to_owned()) {
429 None => String::from("()"),
432 deduplicate_arg_names(&mut arg_names);
433 let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| {
434 make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty))
441 FuncExpr::Func(_) => None,
442 FuncExpr::Method(_) => Some(make::self_param()),
449 /// Makes duplicate argument names unique by appending incrementing numbers.
452 /// let mut names: Vec<String> =
453 /// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
454 /// deduplicate_arg_names(&mut names);
455 /// let expected: Vec<String> =
456 /// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
457 /// assert_eq!(names, expected);
459 fn deduplicate_arg_names(arg_names: &mut Vec<String>) {
460 let arg_name_counts = arg_names.iter().fold(FxHashMap::default(), |mut m, name| {
461 *m.entry(name).or_insert(0) += 1;
464 let duplicate_arg_names: FxHashSet<String> = arg_name_counts
466 .filter(|(_, count)| *count >= 2)
467 .map(|(name, _)| name.clone())
470 let mut counter_per_name = FxHashMap::default();
471 for arg_name in arg_names.iter_mut() {
472 if duplicate_arg_names.contains(arg_name) {
473 let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
475 arg_name.push_str(&counter.to_string());
481 fn fn_arg_name(fn_arg: &ast::Expr) -> Option<String> {
483 ast::Expr::CastExpr(cast_expr) => fn_arg_name(&cast_expr.expr()?),
488 .filter(|d| ast::NameRef::can_cast(d.kind()))
491 Some(to_lower_snake_case(&s))
498 target_module: hir::Module,
500 ) -> Option<String> {
501 let ty = ctx.sema.type_of_expr(fn_arg)?.adjusted();
506 if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) {
513 /// Returns the position inside the current mod or file
514 /// directly after the current block
515 /// We want to write the generated function directly after
516 /// fns, impls or macro calls, but inside mods
517 fn next_space_for_fn_after_call_site(expr: FuncExpr) -> Option<GeneratedFunctionTarget> {
518 let mut ancestors = expr.syntax().ancestors().peekable();
519 let mut last_ancestor: Option<SyntaxNode> = None;
520 while let Some(next_ancestor) = ancestors.next() {
521 match next_ancestor.kind() {
522 SyntaxKind::SOURCE_FILE => {
525 SyntaxKind::ITEM_LIST => {
526 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
532 last_ancestor = Some(next_ancestor);
534 last_ancestor.map(GeneratedFunctionTarget::BehindItem)
537 fn next_space_for_fn_in_module(
538 db: &dyn hir::db::AstDatabase,
539 module_source: &hir::InFile<hir::ModuleSource>,
540 ) -> Option<(FileId, GeneratedFunctionTarget)> {
541 let file = module_source.file_id.original_file(db);
542 let assist_item = match &module_source.value {
543 hir::ModuleSource::SourceFile(it) => {
544 if let Some(last_item) = it.items().last() {
545 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
547 GeneratedFunctionTarget::BehindItem(it.syntax().clone())
550 hir::ModuleSource::Module(it) => {
551 if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
552 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
554 GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone())
557 hir::ModuleSource::BlockExpr(it) => {
558 if let Some(last_item) =
559 it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
561 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
563 GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone())
567 Some((file, assist_item))
570 fn next_space_for_fn_in_impl(impl_: &ast::Impl) -> Option<GeneratedFunctionTarget> {
571 if let Some(last_item) = impl_.assoc_item_list().and_then(|it| it.assoc_items().last()) {
572 Some(GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()))
574 Some(GeneratedFunctionTarget::InEmptyItemList(impl_.assoc_item_list()?.syntax().clone()))
578 fn module_is_descendant(module: &hir::Module, ans: &hir::Module, ctx: &AssistContext) -> bool {
582 for c in ans.children(ctx.sema.db) {
583 if module_is_descendant(module, &c, ctx) {
592 use crate::tests::{check_assist, check_assist_not_applicable};
597 fn add_function_with_no_args() {
610 fn bar() ${0:-> ()} {
618 fn add_function_from_method() {
619 // This ensures that the function is correctly generated
620 // in the next outer mod or file
637 fn bar() ${0:-> ()} {
645 fn add_function_directly_after_current_block() {
646 // The new fn should not be created at the end of the file or module
661 fn bar() ${0:-> ()} {
671 fn add_function_with_no_args_in_same_module() {
687 fn bar() ${0:-> ()} {
696 fn add_function_with_upper_camel_case_arg() {
711 fn bar(baz_baz: BazBaz) ${0:-> ()} {
719 fn add_function_with_upper_camel_case_arg_as_cast() {
725 bar$0(&BazBaz as *const BazBaz);
731 bar(&BazBaz as *const BazBaz);
734 fn bar(baz_baz: *const BazBaz) ${0:-> ()} {
742 fn add_function_with_function_call_arg() {
747 fn baz() -> Baz { todo!() }
754 fn baz() -> Baz { todo!() }
759 fn bar(baz: Baz) ${0:-> ()} {
767 fn add_function_with_method_call_arg() {
773 fn foo(&self) -> Baz {
776 fn baz(&self) -> Baz {
784 fn foo(&self) -> Baz {
787 fn baz(&self) -> Baz {
792 fn bar(baz: Baz) -> Baz {
800 fn add_function_with_string_literal_arg() {
821 fn add_function_with_char_literal_arg() {
842 fn add_function_with_int_literal_arg() {
863 fn add_function_with_cast_int_literal_arg() {
884 fn name_of_cast_variable_is_used() {
885 // Ensures that the name of the cast type isn't used
886 // in the generated function signature.
909 fn add_function_with_variable_arg() {
932 fn add_function_with_impl_trait_arg() {
938 fn foo() -> impl Foo {
947 fn foo() -> impl Foo {
954 fn bar(foo: impl Foo) {
967 fn baz() -> Baz { todo!() }
975 fn baz() -> Baz { todo!() }
989 fn add_function_with_qualified_path_arg() {
995 pub fn baz() -> Bof { Bof }
1004 pub fn baz() -> Bof { Bof }
1010 fn bar(baz: Baz::Bof) {
1018 fn add_function_with_generic_arg() {
1019 // FIXME: This is wrong, generated `bar` should include generic parameter.
1040 fn add_function_with_fn_arg() {
1041 // FIXME: The argument in `bar` is wrong.
1047 fn new() -> Self { Baz }
1056 fn new() -> Self { Baz }
1062 fn bar(new: fn) ${0:-> ()} {
1070 fn add_function_with_closure_arg() {
1071 // FIXME: The argument in `bar` is wrong.
1076 let closure = |x: i64| x - 1;
1082 let closure = |x: i64| x - 1;
1086 fn bar(closure: ()) {
1094 fn unresolveable_types_default_to_unit() {
1115 fn arg_names_dont_overlap() {
1120 fn baz() -> Baz { Baz }
1127 fn baz() -> Baz { Baz }
1132 fn bar(baz_1: Baz, baz_2: Baz) {
1140 fn arg_name_counters_start_at_1_per_name() {
1145 fn baz() -> Baz { Baz }
1147 $0bar(baz(), baz(), "foo", "bar")
1152 fn baz() -> Baz { Baz }
1154 bar(baz(), baz(), "foo", "bar")
1157 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) {
1165 fn add_function_in_module() {
1177 pub(crate) fn my_fn() {
1190 fn qualified_path_uses_correct_scope() {
1213 fn baz(foo: foo::Foo) {
1221 fn add_function_in_module_containing_other_items() {
1226 fn something_else() {}
1235 fn something_else() {}
1237 pub(crate) fn my_fn() {
1250 fn add_function_in_nested_module() {
1265 pub(crate) fn my_fn() {
1279 fn add_function_in_another_file() {
1294 pub(crate) fn bar() {
1301 fn add_function_with_return_type() {
1306 let x: u32 = foo$0();
1322 fn add_function_not_applicable_if_function_already_exists() {
1323 check_assist_not_applicable(
1336 fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1337 check_assist_not_applicable(
1338 // bar is resolved, but baz isn't.
1339 // The assist is only active if the cursor is on an unresolved path,
1340 // but the assist should only be offered if the path is a function call.
1353 fn create_method_with_no_args() {
1371 fn bar(&self) ${0:-> ()} {
1380 fn create_function_with_async() {
1393 async fn bar(arg: i32) ${0:-> ()} {
1401 fn create_method() {
1406 fn foo() {S.bar$0();}
1414 fn bar(&self) ${0:-> ()} {
1423 fn create_method_within_an_impl() {
1428 fn foo() {S.bar$0();}
1436 fn bar(&self) ${0:-> ()} {
1446 fn create_method_from_different_module() {
1453 fn foo() {s::S.bar$0();}
1461 pub(crate) fn bar(&self) ${0:-> ()} {
1466 fn foo() {s::S.bar();}
1472 fn create_method_from_descendant_module() {
1494 fn bar(&self) ${0:-> ()} {
1504 fn create_method_with_cursor_anywhere_on_call_expresion() {
1509 fn foo() {$0S.bar();}
1517 fn bar(&self) ${0:-> ()} {