1 use rustc_hash::{FxHashMap, FxHashSet};
3 use hir::{HasSource, HirDisplay, Module, Semantics, TypeInfo};
4 use ide_db::helpers::FamousDefs;
7 defs::{Definition, NameRefClass},
11 use stdx::to_lower_snake_case;
15 edit::{AstNodeEdit, IndentLevel},
16 make, AstNode, CallExpr, HasArgList, HasModuleItem,
18 SyntaxKind, SyntaxNode, TextRange, TextSize,
22 utils::convert_reference_type,
23 utils::{find_struct_impl, render_snippet, Cursor},
24 AssistContext, AssistId, AssistKind, Assists,
27 // Assist: generate_function
29 // Adds a stub function with a signature matching the function under the cursor.
33 // fn baz() -> Baz { Baz }
42 // fn baz() -> Baz { Baz }
47 // fn bar(arg: &str, baz: Baz) ${0:-> _} {
52 pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
53 gen_fn(acc, ctx).or_else(|| gen_method(acc, ctx))
56 fn gen_fn(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
57 let path_expr: ast::PathExpr = ctx.find_node_at_offset()?;
58 let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?;
59 let path = path_expr.path()?;
60 let name_ref = path.segment()?.name_ref()?;
61 if ctx.sema.resolve_path(&path).is_some() {
62 // The function call already resolves, no need to add a function
66 let fn_name = &*name_ref.text();
68 let mut adt_name = None;
70 let (target, file, insert_offset) = match path.qualifier() {
71 Some(qualifier) => match ctx.sema.resolve_path(&qualifier) {
72 Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => {
73 target_module = Some(module);
74 get_fn_target(ctx, &target_module, call.clone())?
76 Some(hir::PathResolution::Def(hir::ModuleDef::Adt(adt))) => {
77 let current_module = current_module(call.syntax(), ctx)?;
78 let module = adt.module(ctx.sema.db);
79 target_module = if current_module == module { None } else { Some(module) };
80 if current_module.krate() != module.krate() {
83 let (impl_, file) = get_adt_source(ctx, &adt, fn_name)?;
84 let (target, insert_offset) = get_method_target(ctx, &module, &impl_)?;
85 adt_name = if impl_.is_none() { Some(adt.name(ctx.sema.db)) } else { None };
86 (target, file, insert_offset)
94 get_fn_target(ctx, &target_module, call.clone())?
97 let function_builder = FunctionBuilder::from_call(ctx, &call, fn_name, target_module, target)?;
98 let text_range = call.syntax().text_range();
99 let label = format!("Generate {} function", function_builder.fn_name);
100 add_func_to_accumulator(
112 fn gen_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
113 let call: ast::MethodCallExpr = ctx.find_node_at_offset()?;
114 if ctx.sema.resolve_method_call(&call).is_some() {
118 let fn_name = call.name_ref()?;
119 let adt = ctx.sema.type_of_expr(&call.receiver()?)?.original().strip_references().as_adt()?;
121 let current_module = current_module(call.syntax(), ctx)?;
122 let target_module = adt.module(ctx.sema.db);
124 if current_module.krate() != target_module.krate() {
127 let (impl_, file) = get_adt_source(ctx, &adt, fn_name.text().as_str())?;
128 let (target, insert_offset) = get_method_target(ctx, &target_module, &impl_)?;
129 let function_builder =
130 FunctionBuilder::from_method_call(ctx, &call, &fn_name, target_module, target)?;
131 let text_range = call.syntax().text_range();
132 let adt_name = if impl_.is_none() { Some(adt.name(ctx.sema.db)) } else { None };
133 let label = format!("Generate {} method", function_builder.fn_name);
134 add_func_to_accumulator(
146 fn add_func_to_accumulator(
149 text_range: TextRange,
150 function_builder: FunctionBuilder,
151 insert_offset: TextSize,
153 adt_name: Option<hir::Name>,
156 acc.add(AssistId("generate_function", AssistKind::Generate), label, text_range, |builder| {
157 let function_template = function_builder.render();
158 let mut func = function_template.to_string(ctx.config.snippet_cap);
159 if let Some(name) = adt_name {
160 func = format!("\nimpl {} {{\n{}\n}}", name, func);
162 builder.edit_file(file);
163 match ctx.config.snippet_cap {
164 Some(cap) => builder.insert_snippet(cap, insert_offset, func),
165 None => builder.insert(insert_offset, func),
170 fn current_module(current_node: &SyntaxNode, ctx: &AssistContext) -> Option<Module> {
171 ctx.sema.scope(current_node).module()
178 ) -> Option<(Option<ast::Impl>, FileId)> {
179 let range = adt.source(ctx.sema.db)?.syntax().original_file_range(ctx.sema.db);
180 let file = ctx.sema.parse(range.file_id);
182 ctx.sema.find_node_at_offset_with_macros(file.syntax(), range.range.start())?;
183 find_struct_impl(ctx, &adt_source, fn_name).map(|impl_| (impl_, range.file_id))
186 struct FunctionTemplate {
189 ret_type: Option<ast::RetType>,
190 should_focus_return_type: bool,
192 tail_expr: ast::Expr,
195 impl FunctionTemplate {
196 fn to_string(&self, cap: Option<SnippetCap>) -> String {
199 let cursor = if self.should_focus_return_type {
200 // Focus the return type if there is one
201 match self.ret_type {
202 Some(ref ret_type) => ret_type.syntax(),
203 None => self.tail_expr.syntax(),
206 self.tail_expr.syntax()
208 render_snippet(cap, self.fn_def.syntax(), Cursor::Replace(cursor))
210 None => self.fn_def.to_string(),
213 format!("{}{}{}", self.leading_ws, f, self.trailing_ws)
217 struct FunctionBuilder {
218 target: GeneratedFunctionTarget,
220 type_params: Option<ast::GenericParamList>,
221 params: ast::ParamList,
222 ret_type: Option<ast::RetType>,
223 should_focus_return_type: bool,
228 impl FunctionBuilder {
229 /// Prepares a generated function that matches `call`.
230 /// The function is generated in `target_module` or next to `call`
233 call: &ast::CallExpr,
235 target_module: Option<hir::Module>,
236 target: GeneratedFunctionTarget,
238 let needs_pub = target_module.is_some();
239 let target_module = target_module.or_else(|| current_module(target.syntax(), ctx))?;
240 let fn_name = make::name(fn_name);
241 let (type_params, params) =
242 fn_args(ctx, target_module, ast::CallableExpr::Call(call.clone()))?;
244 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
245 let is_async = await_expr.is_some();
247 let (ret_type, should_focus_return_type) =
248 make_return_type(ctx, &ast::Expr::CallExpr(call.clone()), target_module);
256 should_focus_return_type,
264 call: &ast::MethodCallExpr,
266 target_module: Module,
267 target: GeneratedFunctionTarget,
270 !module_is_descendant(¤t_module(call.syntax(), ctx)?, &target_module, ctx);
271 let fn_name = make::name(&name.text());
272 let (type_params, params) =
273 fn_args(ctx, target_module, ast::CallableExpr::MethodCall(call.clone()))?;
275 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
276 let is_async = await_expr.is_some();
278 let (ret_type, should_focus_return_type) =
279 make_return_type(ctx, &ast::Expr::MethodCallExpr(call.clone()), target_module);
287 should_focus_return_type,
293 fn render(self) -> FunctionTemplate {
294 let placeholder_expr = make::ext::expr_todo();
295 let fn_body = make::block_expr(vec![], Some(placeholder_expr));
296 let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None };
297 let mut fn_def = make::fn_(
310 GeneratedFunctionTarget::BehindItem(it) => {
311 let indent = IndentLevel::from_node(&it);
312 leading_ws = format!("\n\n{}", indent);
313 fn_def = fn_def.indent(indent);
314 trailing_ws = String::new();
316 GeneratedFunctionTarget::InEmptyItemList(it) => {
317 let indent = IndentLevel::from_node(&it);
318 leading_ws = format!("\n{}", indent + 1);
319 fn_def = fn_def.indent(indent + 1);
320 trailing_ws = format!("\n{}", indent);
326 ret_type: fn_def.ret_type(),
327 // PANIC: we guarantee we always create a function body with a tail expr
328 tail_expr: fn_def.body().unwrap().tail_expr().unwrap(),
329 should_focus_return_type: self.should_focus_return_type,
336 /// Makes an optional return type along with whether the return type should be focused by the cursor.
337 /// If we cannot infer what the return type should be, we create a placeholder type.
339 /// The rule for whether we focus a return type or not (and thus focus the function body),
340 /// is rather simple:
341 /// * If we could *not* infer what the return type should be, focus it (so the user can fill-in
342 /// the correct return type).
343 /// * If we could infer the return type, don't focus it (and thus focus the function body) so the
344 /// user can change the `todo!` function body.
348 target_module: Module,
349 ) -> (Option<ast::RetType>, bool) {
350 let (ret_ty, should_focus_return_type) = {
351 match ctx.sema.type_of_expr(call).map(TypeInfo::original) {
352 Some(ty) if ty.is_unknown() => (Some(make::ty_placeholder()), true),
353 None => (Some(make::ty_placeholder()), true),
354 Some(ty) if ty.is_unit() => (None, false),
356 let rendered = ty.display_source_code(ctx.db(), target_module.into());
358 Ok(rendered) => (Some(make::ty(&rendered)), false),
359 Err(_) => (Some(make::ty_placeholder()), true),
364 let ret_type = ret_ty.map(make::ret_type);
365 (ret_type, should_focus_return_type)
370 target_module: &Option<Module>,
372 ) -> Option<(GeneratedFunctionTarget, FileId, TextSize)> {
373 let mut file = ctx.file_id();
374 let target = match target_module {
375 Some(target_module) => {
376 let module_source = target_module.definition_source(ctx.db());
377 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?;
381 None => next_space_for_fn_after_call_site(ast::CallableExpr::Call(call))?,
383 Some((target.clone(), file, get_insert_offset(&target)))
386 fn get_method_target(
388 target_module: &Module,
389 impl_: &Option<ast::Impl>,
390 ) -> Option<(GeneratedFunctionTarget, TextSize)> {
391 let target = match impl_ {
392 Some(impl_) => next_space_for_fn_in_impl(impl_)?,
394 next_space_for_fn_in_module(ctx.sema.db, &target_module.definition_source(ctx.sema.db))?
398 Some((target.clone(), get_insert_offset(&target)))
401 fn get_insert_offset(target: &GeneratedFunctionTarget) -> TextSize {
403 GeneratedFunctionTarget::BehindItem(it) => it.text_range().end(),
404 GeneratedFunctionTarget::InEmptyItemList(it) => it.text_range().start() + TextSize::of('{'),
409 enum GeneratedFunctionTarget {
410 BehindItem(SyntaxNode),
411 InEmptyItemList(SyntaxNode),
414 impl GeneratedFunctionTarget {
415 fn syntax(&self) -> &SyntaxNode {
417 GeneratedFunctionTarget::BehindItem(it) => it,
418 GeneratedFunctionTarget::InEmptyItemList(it) => it,
423 /// Computes the type variables and arguments required for the generated function
426 target_module: hir::Module,
427 call: ast::CallableExpr,
428 ) -> Option<(Option<ast::GenericParamList>, ast::ParamList)> {
429 let mut arg_names = Vec::new();
430 let mut arg_types = Vec::new();
431 for arg in call.arg_list()?.args() {
432 arg_names.push(fn_arg_name(&ctx.sema, &arg));
433 arg_types.push(fn_arg_type(ctx, target_module, &arg));
435 deduplicate_arg_names(&mut arg_names);
436 let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| {
437 make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty))
444 ast::CallableExpr::Call(_) => None,
445 ast::CallableExpr::MethodCall(_) => Some(make::self_param()),
452 /// Makes duplicate argument names unique by appending incrementing numbers.
455 /// let mut names: Vec<String> =
456 /// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
457 /// deduplicate_arg_names(&mut names);
458 /// let expected: Vec<String> =
459 /// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
460 /// assert_eq!(names, expected);
462 fn deduplicate_arg_names(arg_names: &mut Vec<String>) {
463 let mut arg_name_counts = FxHashMap::default();
464 for name in arg_names.iter() {
465 *arg_name_counts.entry(name).or_insert(0) += 1;
467 let duplicate_arg_names: FxHashSet<String> = arg_name_counts
469 .filter(|(_, count)| *count >= 2)
470 .map(|(name, _)| name.clone())
473 let mut counter_per_name = FxHashMap::default();
474 for arg_name in arg_names.iter_mut() {
475 if duplicate_arg_names.contains(arg_name) {
476 let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
478 arg_name.push_str(&counter.to_string());
484 fn fn_arg_name(sema: &Semantics<RootDatabase>, arg_expr: &ast::Expr) -> String {
485 let name = (|| match arg_expr {
486 ast::Expr::CastExpr(cast_expr) => Some(fn_arg_name(sema, &cast_expr.expr()?)),
491 .filter_map(ast::NameRef::cast)
492 .filter(|name| name.ident_token().is_some())
494 if let Some(NameRefClass::Definition(Definition::Const(_) | Definition::Static(_))) =
495 NameRefClass::classify(sema, &name_ref)
497 return Some(name_ref.to_string().to_lowercase());
499 Some(to_lower_snake_case(&name_ref.to_string()))
503 Some(mut name) if name.starts_with(|c: char| c.is_ascii_digit()) => {
504 name.insert_str(0, "arg");
508 None => "arg".to_string(),
512 fn fn_arg_type(ctx: &AssistContext, target_module: hir::Module, fn_arg: &ast::Expr) -> String {
513 fn maybe_displayed_type(
515 target_module: hir::Module,
517 ) -> Option<String> {
518 let ty = ctx.sema.type_of_expr(fn_arg)?.adjusted();
523 if ty.is_reference() || ty.is_mutable_reference() {
524 let famous_defs = &FamousDefs(&ctx.sema, ctx.sema.scope(fn_arg.syntax()).krate());
525 convert_reference_type(ty.strip_references(), ctx.db(), famous_defs)
526 .map(|conversion| conversion.convert_type(ctx.db()))
527 .or_else(|| ty.display_source_code(ctx.db(), target_module.into()).ok())
529 ty.display_source_code(ctx.db(), target_module.into()).ok()
533 maybe_displayed_type(ctx, target_module, fn_arg).unwrap_or_else(|| String::from("_"))
536 /// Returns the position inside the current mod or file
537 /// directly after the current block
538 /// We want to write the generated function directly after
539 /// fns, impls or macro calls, but inside mods
540 fn next_space_for_fn_after_call_site(expr: ast::CallableExpr) -> Option<GeneratedFunctionTarget> {
541 let mut ancestors = expr.syntax().ancestors().peekable();
542 let mut last_ancestor: Option<SyntaxNode> = None;
543 while let Some(next_ancestor) = ancestors.next() {
544 match next_ancestor.kind() {
545 SyntaxKind::SOURCE_FILE => {
548 SyntaxKind::ITEM_LIST => {
549 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
555 last_ancestor = Some(next_ancestor);
557 last_ancestor.map(GeneratedFunctionTarget::BehindItem)
560 fn next_space_for_fn_in_module(
561 db: &dyn hir::db::AstDatabase,
562 module_source: &hir::InFile<hir::ModuleSource>,
563 ) -> Option<(FileId, GeneratedFunctionTarget)> {
564 let file = module_source.file_id.original_file(db);
565 let assist_item = match &module_source.value {
566 hir::ModuleSource::SourceFile(it) => match it.items().last() {
567 Some(last_item) => GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()),
568 None => GeneratedFunctionTarget::BehindItem(it.syntax().clone()),
570 hir::ModuleSource::Module(it) => match it.item_list().and_then(|it| it.items().last()) {
571 Some(last_item) => GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()),
572 None => GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone()),
574 hir::ModuleSource::BlockExpr(it) => {
575 if let Some(last_item) =
576 it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
578 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
580 GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone())
584 Some((file, assist_item))
587 fn next_space_for_fn_in_impl(impl_: &ast::Impl) -> Option<GeneratedFunctionTarget> {
588 if let Some(last_item) = impl_.assoc_item_list().and_then(|it| it.assoc_items().last()) {
589 Some(GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()))
591 Some(GeneratedFunctionTarget::InEmptyItemList(impl_.assoc_item_list()?.syntax().clone()))
595 fn module_is_descendant(module: &hir::Module, ans: &hir::Module, ctx: &AssistContext) -> bool {
599 for c in ans.children(ctx.sema.db) {
600 if module_is_descendant(module, &c, ctx) {
609 use crate::tests::{check_assist, check_assist_not_applicable};
614 fn add_function_with_no_args() {
635 fn add_function_from_method() {
636 // This ensures that the function is correctly generated
637 // in the next outer mod or file
662 fn add_function_directly_after_current_block() {
663 // The new fn should not be created at the end of the file or module
688 fn add_function_with_no_args_in_same_module() {
713 fn add_function_with_upper_camel_case_arg() {
728 fn bar(baz_baz: BazBaz) ${0:-> _} {
736 fn add_function_with_upper_camel_case_arg_as_cast() {
742 bar$0(&BazBaz as *const BazBaz);
748 bar(&BazBaz as *const BazBaz);
751 fn bar(baz_baz: *const BazBaz) ${0:-> _} {
759 fn add_function_with_function_call_arg() {
764 fn baz() -> Baz { todo!() }
771 fn baz() -> Baz { todo!() }
776 fn bar(baz: Baz) ${0:-> _} {
784 fn add_function_with_method_call_arg() {
790 fn foo(&self) -> Baz {
793 fn baz(&self) -> Baz {
801 fn foo(&self) -> Baz {
804 fn baz(&self) -> Baz {
809 fn bar(baz: Baz) -> Baz {
817 fn add_function_with_string_literal_arg() {
838 fn add_function_with_char_literal_arg() {
859 fn add_function_with_int_literal_arg() {
880 fn add_function_with_cast_int_literal_arg() {
901 fn name_of_cast_variable_is_used() {
902 // Ensures that the name of the cast type isn't used
903 // in the generated function signature.
926 fn add_function_with_variable_arg() {
949 fn add_function_with_impl_trait_arg() {
955 fn foo() -> impl Foo {
964 fn foo() -> impl Foo {
971 fn bar(foo: impl Foo) {
984 fn baz() -> Baz { todo!() }
992 fn baz() -> Baz { todo!() }
1006 fn add_function_with_qualified_path_arg() {
1012 pub fn baz() -> Bof { Bof }
1021 pub fn baz() -> Bof { Bof }
1027 fn bar(baz: Baz::Bof) {
1035 fn add_function_with_generic_arg() {
1036 // FIXME: This is wrong, generated `bar` should include generic parameter.
1057 fn add_function_with_fn_arg() {
1058 // FIXME: The argument in `bar` is wrong.
1064 fn new() -> Self { Baz }
1073 fn new() -> Self { Baz }
1079 fn bar(new: fn) ${0:-> _} {
1087 fn add_function_with_closure_arg() {
1088 // FIXME: The argument in `bar` is wrong.
1093 let closure = |x: i64| x - 1;
1099 let closure = |x: i64| x - 1;
1103 fn bar(closure: _) {
1111 fn unresolveable_types_default_to_placeholder() {
1132 fn arg_names_dont_overlap() {
1137 fn baz() -> Baz { Baz }
1144 fn baz() -> Baz { Baz }
1149 fn bar(baz_1: Baz, baz_2: Baz) {
1157 fn arg_name_counters_start_at_1_per_name() {
1162 fn baz() -> Baz { Baz }
1164 $0bar(baz(), baz(), "foo", "bar")
1169 fn baz() -> Baz { Baz }
1171 bar(baz(), baz(), "foo", "bar")
1174 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) {
1182 fn add_function_in_module() {
1194 pub(crate) fn my_fn() {
1207 fn qualified_path_uses_correct_scope() {
1230 fn baz(foo: foo::Foo) {
1238 fn add_function_in_module_containing_other_items() {
1243 fn something_else() {}
1252 fn something_else() {}
1254 pub(crate) fn my_fn() {
1267 fn add_function_in_nested_module() {
1282 pub(crate) fn my_fn() {
1296 fn add_function_in_another_file() {
1311 pub(crate) fn bar() {
1318 fn add_function_with_return_type() {
1323 let x: u32 = foo$0();
1339 fn add_function_not_applicable_if_function_already_exists() {
1340 check_assist_not_applicable(
1353 fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1354 check_assist_not_applicable(
1355 // bar is resolved, but baz isn't.
1356 // The assist is only active if the cursor is on an unresolved path,
1357 // but the assist should only be offered if the path is a function call.
1370 fn create_method_with_no_args() {
1388 fn bar(&self) ${0:-> _} {
1397 fn create_function_with_async() {
1410 async fn bar(arg: i32) ${0:-> _} {
1418 fn create_method() {
1423 fn foo() {S.bar$0();}
1431 fn bar(&self) ${0:-> _} {
1440 fn create_method_within_an_impl() {
1445 fn foo() {S.bar$0();}
1453 fn bar(&self) ${0:-> _} {
1463 fn create_method_from_different_module() {
1470 fn foo() {s::S.bar$0();}
1478 pub(crate) fn bar(&self) ${0:-> _} {
1483 fn foo() {s::S.bar();}
1489 fn create_method_from_descendant_module() {
1511 fn bar(&self) ${0:-> _} {
1521 fn create_method_with_cursor_anywhere_on_call_expresion() {
1526 fn foo() {$0S.bar();}
1534 fn bar(&self) ${0:-> _} {
1543 fn create_static_method() {
1548 fn foo() {S::bar$0();}
1552 fn foo() {S::bar();}
1556 fn bar() ${0:-> _} {
1565 fn create_static_method_within_an_impl() {
1570 fn foo() {S::bar$0();}
1576 fn foo() {S::bar();}
1578 fn bar() ${0:-> _} {
1588 fn create_static_method_from_different_module() {
1595 fn foo() {s::S::bar$0();}
1603 pub(crate) fn bar() ${0:-> _} {
1608 fn foo() {s::S::bar();}
1614 fn create_static_method_with_cursor_anywhere_on_call_expresion() {
1619 fn foo() {$0S::bar();}
1623 fn foo() {S::bar();}
1627 fn bar() ${0:-> _} {
1636 fn no_panic_on_invalid_global_path() {
1649 fn foo() ${0:-> _} {
1657 fn handle_tuple_indexing() {
1672 fn foo(a: ()) ${0:-> _} {
1680 fn add_function_with_const_arg() {
1684 const VALUE: usize = 0;
1690 const VALUE: usize = 0;
1695 fn foo(value: usize) ${0:-> _} {
1703 fn add_function_with_static_arg() {
1707 static VALUE: usize = 0;
1713 static VALUE: usize = 0;
1718 fn foo(value: usize) ${0:-> _} {
1726 fn add_function_with_static_mut_arg() {
1730 static mut VALUE: usize = 0;
1736 static mut VALUE: usize = 0;
1741 fn foo(value: usize) ${0:-> _} {