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, CallExpr, 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)?;
73 let path = path_expr.path()?;
74 let name_ref = path.segment()?.name_ref()?;
75 if ctx.sema.resolve_path(&path).is_some() {
76 // The function call already resolves, no need to add a function
80 let fn_name = &*name_ref.text();
82 let mut adt_name = None;
84 let (target, file, insert_offset) = match path.qualifier() {
85 Some(qualifier) => match ctx.sema.resolve_path(&qualifier) {
86 Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => {
87 target_module = Some(module);
88 get_fn_target(ctx, &target_module, call.clone())?
90 Some(hir::PathResolution::Def(hir::ModuleDef::Adt(adt))) => {
91 let current_module = current_module(call.syntax(), ctx)?;
92 let module = adt.module(ctx.sema.db);
93 target_module = if current_module == module { None } else { Some(module) };
94 if current_module.krate() != module.krate() {
97 let (impl_, file) = get_adt_source(ctx, &adt, fn_name)?;
98 let (target, insert_offset) = get_method_target(ctx, &module, &impl_)?;
99 adt_name = if impl_.is_none() { Some(adt.name(ctx.sema.db)) } else { None };
100 (target, file, insert_offset)
107 target_module = None;
108 get_fn_target(ctx, &target_module, call.clone())?
111 let function_builder = FunctionBuilder::from_call(ctx, &call, fn_name, target_module, target)?;
112 let text_range = call.syntax().text_range();
113 let label = format!("Generate {} function", function_builder.fn_name);
114 add_func_to_accumulator(
126 fn gen_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
127 let call: ast::MethodCallExpr = ctx.find_node_at_offset()?;
128 let fn_name = call.name_ref()?;
129 let adt = ctx.sema.type_of_expr(&call.receiver()?)?.original().strip_references().as_adt()?;
131 let current_module = current_module(call.syntax(), ctx)?;
132 let target_module = adt.module(ctx.sema.db);
134 if current_module.krate() != target_module.krate() {
137 let (impl_, file) = get_adt_source(ctx, &adt, fn_name.text().as_str())?;
138 let (target, insert_offset) = get_method_target(ctx, &target_module, &impl_)?;
139 let function_builder =
140 FunctionBuilder::from_method_call(ctx, &call, &fn_name, target_module, target)?;
141 let text_range = call.syntax().text_range();
142 let adt_name = if impl_.is_none() { Some(adt.name(ctx.sema.db)) } else { None };
143 let label = format!("Generate {} method", function_builder.fn_name);
144 add_func_to_accumulator(
156 fn add_func_to_accumulator(
159 text_range: TextRange,
160 function_builder: FunctionBuilder,
161 insert_offset: TextSize,
163 adt_name: Option<hir::Name>,
166 acc.add(AssistId("generate_function", AssistKind::Generate), label, text_range, |builder| {
167 let function_template = function_builder.render();
168 let mut func = function_template.to_string(ctx.config.snippet_cap);
169 if let Some(name) = adt_name {
170 func = format!("\nimpl {} {{\n{}\n}}", name, func);
172 builder.edit_file(file);
173 match ctx.config.snippet_cap {
174 Some(cap) => builder.insert_snippet(cap, insert_offset, func),
175 None => builder.insert(insert_offset, func),
180 fn current_module(current_node: &SyntaxNode, ctx: &AssistContext) -> Option<Module> {
181 ctx.sema.scope(current_node).module()
188 ) -> Option<(Option<ast::Impl>, FileId)> {
189 let range = adt.source(ctx.sema.db)?.syntax().original_file_range(ctx.sema.db);
190 let file = ctx.sema.parse(range.file_id);
192 ctx.sema.find_node_at_offset_with_macros(file.syntax(), range.range.start())?;
193 find_struct_impl(ctx, &adt_source, fn_name).map(|impl_| (impl_, range.file_id))
196 struct FunctionTemplate {
199 ret_type: Option<ast::RetType>,
200 should_focus_return_type: bool,
202 tail_expr: ast::Expr,
205 impl FunctionTemplate {
206 fn to_string(&self, cap: Option<SnippetCap>) -> String {
209 let cursor = if self.should_focus_return_type {
210 // Focus the return type if there is one
211 if let Some(ref ret_type) = self.ret_type {
214 self.tail_expr.syntax()
217 self.tail_expr.syntax()
219 render_snippet(cap, self.fn_def.syntax(), Cursor::Replace(cursor))
221 None => self.fn_def.to_string(),
224 format!("{}{}{}", self.leading_ws, f, self.trailing_ws)
228 struct FunctionBuilder {
229 target: GeneratedFunctionTarget,
231 type_params: Option<ast::GenericParamList>,
232 params: ast::ParamList,
233 ret_type: Option<ast::RetType>,
234 should_focus_return_type: bool,
239 impl FunctionBuilder {
240 /// Prepares a generated function that matches `call`.
241 /// The function is generated in `target_module` or next to `call`
244 call: &ast::CallExpr,
246 target_module: Option<hir::Module>,
247 target: GeneratedFunctionTarget,
249 let needs_pub = target_module.is_some();
250 let target_module = target_module.or_else(|| current_module(target.syntax(), ctx))?;
251 let fn_name = make::name(fn_name);
252 let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Func(call.clone()))?;
254 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
255 let is_async = await_expr.is_some();
257 let (ret_type, should_focus_return_type) =
258 make_return_type(ctx, &ast::Expr::CallExpr(call.clone()), target_module);
266 should_focus_return_type,
274 call: &ast::MethodCallExpr,
276 target_module: Module,
277 target: GeneratedFunctionTarget,
280 !module_is_descendant(¤t_module(call.syntax(), ctx)?, &target_module, ctx);
281 let fn_name = make::name(&name.text());
282 let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Method(call.clone()))?;
284 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
285 let is_async = await_expr.is_some();
287 let (ret_type, should_focus_return_type) =
288 make_return_type(ctx, &ast::Expr::MethodCallExpr(call.clone()), target_module);
296 should_focus_return_type,
302 fn render(self) -> FunctionTemplate {
303 let placeholder_expr = make::ext::expr_todo();
304 let fn_body = make::block_expr(vec![], Some(placeholder_expr));
305 let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None };
306 let mut fn_def = make::fn_(
319 GeneratedFunctionTarget::BehindItem(it) => {
320 let indent = IndentLevel::from_node(&it);
321 leading_ws = format!("\n\n{}", indent);
322 fn_def = fn_def.indent(indent);
323 trailing_ws = String::new();
325 GeneratedFunctionTarget::InEmptyItemList(it) => {
326 let indent = IndentLevel::from_node(&it);
327 leading_ws = format!("\n{}", indent + 1);
328 fn_def = fn_def.indent(indent + 1);
329 trailing_ws = format!("\n{}", indent);
335 ret_type: fn_def.ret_type(),
336 // PANIC: we guarantee we always create a function body with a tail expr
337 tail_expr: fn_def.body().unwrap().tail_expr().unwrap(),
338 should_focus_return_type: self.should_focus_return_type,
345 /// Makes an optional return type along with whether the return type should be focused by the cursor.
346 /// If we cannot infer what the return type should be, we create a placeholder type.
348 /// The rule for whether we focus a return type or not (and thus focus the function body),
349 /// is rather simple:
350 /// * If we could *not* infer what the return type should be, focus it (so the user can fill-in
351 /// the correct return type).
352 /// * If we could infer the return type, don't focus it (and thus focus the function body) so the
353 /// user can change the `todo!` function body.
357 target_module: Module,
358 ) -> (Option<ast::RetType>, bool) {
359 let (ret_ty, should_focus_return_type) = {
360 match ctx.sema.type_of_expr(call).map(TypeInfo::original) {
361 Some(ty) if ty.is_unknown() => (Some(make::ty_placeholder()), true),
362 None => (Some(make::ty_placeholder()), true),
363 Some(ty) if ty.is_unit() => (None, false),
365 let rendered = ty.display_source_code(ctx.db(), target_module.into());
367 Ok(rendered) => (Some(make::ty(&rendered)), false),
368 Err(_) => (Some(make::ty_placeholder()), true),
373 let ret_type = ret_ty.map(make::ret_type);
374 (ret_type, should_focus_return_type)
379 target_module: &Option<Module>,
381 ) -> Option<(GeneratedFunctionTarget, FileId, TextSize)> {
382 let mut file = ctx.frange.file_id;
383 let target = match target_module {
384 Some(target_module) => {
385 let module_source = target_module.definition_source(ctx.db());
386 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?;
390 None => next_space_for_fn_after_call_site(FuncExpr::Func(call))?,
392 Some((target.clone(), file, get_insert_offset(&target)))
395 fn get_method_target(
397 target_module: &Module,
398 impl_: &Option<ast::Impl>,
399 ) -> Option<(GeneratedFunctionTarget, TextSize)> {
400 let target = match impl_ {
401 Some(impl_) => next_space_for_fn_in_impl(impl_)?,
403 next_space_for_fn_in_module(ctx.sema.db, &target_module.definition_source(ctx.sema.db))?
407 Some((target.clone(), get_insert_offset(&target)))
410 fn get_insert_offset(target: &GeneratedFunctionTarget) -> TextSize {
412 GeneratedFunctionTarget::BehindItem(it) => it.text_range().end(),
413 GeneratedFunctionTarget::InEmptyItemList(it) => it.text_range().start() + TextSize::of('{'),
418 enum GeneratedFunctionTarget {
419 BehindItem(SyntaxNode),
420 InEmptyItemList(SyntaxNode),
423 impl GeneratedFunctionTarget {
424 fn syntax(&self) -> &SyntaxNode {
426 GeneratedFunctionTarget::BehindItem(it) => it,
427 GeneratedFunctionTarget::InEmptyItemList(it) => it,
432 /// Computes the type variables and arguments required for the generated function
435 target_module: hir::Module,
437 ) -> Option<(Option<ast::GenericParamList>, ast::ParamList)> {
438 let mut arg_names = Vec::new();
439 let mut arg_types = Vec::new();
440 for arg in call.arg_list()?.args() {
441 arg_names.push(fn_arg_name(&arg));
442 arg_types.push(match fn_arg_type(ctx, target_module, &arg) {
444 if !ty.is_empty() && ty.starts_with('&') {
445 if let Some((new_ty, _)) = useless_type_special_case("", &ty[1..].to_owned()) {
454 None => String::from("_"),
457 deduplicate_arg_names(&mut arg_names);
458 let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| {
459 make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty))
466 FuncExpr::Func(_) => None,
467 FuncExpr::Method(_) => Some(make::self_param()),
474 /// Makes duplicate argument names unique by appending incrementing numbers.
477 /// let mut names: Vec<String> =
478 /// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
479 /// deduplicate_arg_names(&mut names);
480 /// let expected: Vec<String> =
481 /// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
482 /// assert_eq!(names, expected);
484 fn deduplicate_arg_names(arg_names: &mut Vec<String>) {
485 let arg_name_counts = arg_names.iter().fold(FxHashMap::default(), |mut m, name| {
486 *m.entry(name).or_insert(0) += 1;
489 let duplicate_arg_names: FxHashSet<String> = arg_name_counts
491 .filter(|(_, count)| *count >= 2)
492 .map(|(name, _)| name.clone())
495 let mut counter_per_name = FxHashMap::default();
496 for arg_name in arg_names.iter_mut() {
497 if duplicate_arg_names.contains(arg_name) {
498 let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
500 arg_name.push_str(&counter.to_string());
506 fn fn_arg_name(arg_expr: &ast::Expr) -> String {
507 let name = (|| match arg_expr {
508 ast::Expr::CastExpr(cast_expr) => Some(fn_arg_name(&cast_expr.expr()?)),
510 let s = expr.syntax().descendants().filter_map(ast::NameRef::cast).last()?.to_string();
511 Some(to_lower_snake_case(&s))
515 Some(mut name) if name.starts_with(|c: char| c.is_ascii_digit()) => {
516 name.insert_str(0, "arg");
520 None => "arg".to_string(),
526 target_module: hir::Module,
528 ) -> Option<String> {
529 let ty = ctx.sema.type_of_expr(fn_arg)?.adjusted();
534 if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) {
541 /// Returns the position inside the current mod or file
542 /// directly after the current block
543 /// We want to write the generated function directly after
544 /// fns, impls or macro calls, but inside mods
545 fn next_space_for_fn_after_call_site(expr: FuncExpr) -> Option<GeneratedFunctionTarget> {
546 let mut ancestors = expr.syntax().ancestors().peekable();
547 let mut last_ancestor: Option<SyntaxNode> = None;
548 while let Some(next_ancestor) = ancestors.next() {
549 match next_ancestor.kind() {
550 SyntaxKind::SOURCE_FILE => {
553 SyntaxKind::ITEM_LIST => {
554 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
560 last_ancestor = Some(next_ancestor);
562 last_ancestor.map(GeneratedFunctionTarget::BehindItem)
565 fn next_space_for_fn_in_module(
566 db: &dyn hir::db::AstDatabase,
567 module_source: &hir::InFile<hir::ModuleSource>,
568 ) -> Option<(FileId, GeneratedFunctionTarget)> {
569 let file = module_source.file_id.original_file(db);
570 let assist_item = match &module_source.value {
571 hir::ModuleSource::SourceFile(it) => {
572 if let Some(last_item) = it.items().last() {
573 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
575 GeneratedFunctionTarget::BehindItem(it.syntax().clone())
578 hir::ModuleSource::Module(it) => {
579 if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
580 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
582 GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone())
585 hir::ModuleSource::BlockExpr(it) => {
586 if let Some(last_item) =
587 it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
589 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
591 GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone())
595 Some((file, assist_item))
598 fn next_space_for_fn_in_impl(impl_: &ast::Impl) -> Option<GeneratedFunctionTarget> {
599 if let Some(last_item) = impl_.assoc_item_list().and_then(|it| it.assoc_items().last()) {
600 Some(GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()))
602 Some(GeneratedFunctionTarget::InEmptyItemList(impl_.assoc_item_list()?.syntax().clone()))
606 fn module_is_descendant(module: &hir::Module, ans: &hir::Module, ctx: &AssistContext) -> bool {
610 for c in ans.children(ctx.sema.db) {
611 if module_is_descendant(module, &c, ctx) {
620 use crate::tests::{check_assist, check_assist_not_applicable};
625 fn add_function_with_no_args() {
646 fn add_function_from_method() {
647 // This ensures that the function is correctly generated
648 // in the next outer mod or file
673 fn add_function_directly_after_current_block() {
674 // The new fn should not be created at the end of the file or module
699 fn add_function_with_no_args_in_same_module() {
724 fn add_function_with_upper_camel_case_arg() {
739 fn bar(baz_baz: BazBaz) ${0:-> _} {
747 fn add_function_with_upper_camel_case_arg_as_cast() {
753 bar$0(&BazBaz as *const BazBaz);
759 bar(&BazBaz as *const BazBaz);
762 fn bar(baz_baz: *const BazBaz) ${0:-> _} {
770 fn add_function_with_function_call_arg() {
775 fn baz() -> Baz { todo!() }
782 fn baz() -> Baz { todo!() }
787 fn bar(baz: Baz) ${0:-> _} {
795 fn add_function_with_method_call_arg() {
801 fn foo(&self) -> Baz {
804 fn baz(&self) -> Baz {
812 fn foo(&self) -> Baz {
815 fn baz(&self) -> Baz {
820 fn bar(baz: Baz) -> Baz {
828 fn add_function_with_string_literal_arg() {
849 fn add_function_with_char_literal_arg() {
870 fn add_function_with_int_literal_arg() {
891 fn add_function_with_cast_int_literal_arg() {
912 fn name_of_cast_variable_is_used() {
913 // Ensures that the name of the cast type isn't used
914 // in the generated function signature.
937 fn add_function_with_variable_arg() {
960 fn add_function_with_impl_trait_arg() {
966 fn foo() -> impl Foo {
975 fn foo() -> impl Foo {
982 fn bar(foo: impl Foo) {
995 fn baz() -> Baz { todo!() }
1003 fn baz() -> Baz { todo!() }
1017 fn add_function_with_qualified_path_arg() {
1023 pub fn baz() -> Bof { Bof }
1032 pub fn baz() -> Bof { Bof }
1038 fn bar(baz: Baz::Bof) {
1046 fn add_function_with_generic_arg() {
1047 // FIXME: This is wrong, generated `bar` should include generic parameter.
1068 fn add_function_with_fn_arg() {
1069 // FIXME: The argument in `bar` is wrong.
1075 fn new() -> Self { Baz }
1084 fn new() -> Self { Baz }
1090 fn bar(new: fn) ${0:-> _} {
1098 fn add_function_with_closure_arg() {
1099 // FIXME: The argument in `bar` is wrong.
1104 let closure = |x: i64| x - 1;
1110 let closure = |x: i64| x - 1;
1114 fn bar(closure: _) {
1122 fn unresolveable_types_default_to_placeholder() {
1143 fn arg_names_dont_overlap() {
1148 fn baz() -> Baz { Baz }
1155 fn baz() -> Baz { Baz }
1160 fn bar(baz_1: Baz, baz_2: Baz) {
1168 fn arg_name_counters_start_at_1_per_name() {
1173 fn baz() -> Baz { Baz }
1175 $0bar(baz(), baz(), "foo", "bar")
1180 fn baz() -> Baz { Baz }
1182 bar(baz(), baz(), "foo", "bar")
1185 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) {
1193 fn add_function_in_module() {
1205 pub(crate) fn my_fn() {
1218 fn qualified_path_uses_correct_scope() {
1241 fn baz(foo: foo::Foo) {
1249 fn add_function_in_module_containing_other_items() {
1254 fn something_else() {}
1263 fn something_else() {}
1265 pub(crate) fn my_fn() {
1278 fn add_function_in_nested_module() {
1293 pub(crate) fn my_fn() {
1307 fn add_function_in_another_file() {
1322 pub(crate) fn bar() {
1329 fn add_function_with_return_type() {
1334 let x: u32 = foo$0();
1350 fn add_function_not_applicable_if_function_already_exists() {
1351 check_assist_not_applicable(
1364 fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1365 check_assist_not_applicable(
1366 // bar is resolved, but baz isn't.
1367 // The assist is only active if the cursor is on an unresolved path,
1368 // but the assist should only be offered if the path is a function call.
1381 fn create_method_with_no_args() {
1399 fn bar(&self) ${0:-> _} {
1408 fn create_function_with_async() {
1421 async fn bar(arg: i32) ${0:-> _} {
1429 fn create_method() {
1434 fn foo() {S.bar$0();}
1442 fn bar(&self) ${0:-> _} {
1451 fn create_method_within_an_impl() {
1456 fn foo() {S.bar$0();}
1464 fn bar(&self) ${0:-> _} {
1474 fn create_method_from_different_module() {
1481 fn foo() {s::S.bar$0();}
1489 pub(crate) fn bar(&self) ${0:-> _} {
1494 fn foo() {s::S.bar();}
1500 fn create_method_from_descendant_module() {
1522 fn bar(&self) ${0:-> _} {
1532 fn create_method_with_cursor_anywhere_on_call_expresion() {
1537 fn foo() {$0S.bar();}
1545 fn bar(&self) ${0:-> _} {
1554 fn create_static_method() {
1559 fn foo() {S::bar$0();}
1563 fn foo() {S::bar();}
1567 fn bar() ${0:-> _} {
1576 fn create_static_method_within_an_impl() {
1581 fn foo() {S::bar$0();}
1587 fn foo() {S::bar();}
1589 fn bar() ${0:-> _} {
1599 fn create_static_method_from_different_module() {
1606 fn foo() {s::S::bar$0();}
1614 pub(crate) fn bar() ${0:-> _} {
1619 fn foo() {s::S::bar();}
1625 fn create_static_method_with_cursor_anywhere_on_call_expresion() {
1630 fn foo() {$0S::bar();}
1634 fn foo() {S::bar();}
1638 fn bar() ${0:-> _} {
1647 fn no_panic_on_invalid_global_path() {
1660 fn foo() ${0:-> _} {
1668 fn handle_tuple_indexing() {
1683 fn foo(arg0: ()) ${0:-> _} {