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 fn_name = fn_name(&path)?;
75 if ctx.sema.resolve_path(&path).is_some() {
76 // The function call already resolves, no need to add a function
81 let mut adt_name = None;
83 let (target, file, insert_offset) = match path.qualifier() {
84 Some(qualifier) => match ctx.sema.resolve_path(&qualifier) {
85 Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => {
86 target_module = Some(module);
87 get_fn_target(ctx, &target_module, call.clone())?
89 Some(hir::PathResolution::Def(hir::ModuleDef::Adt(adt))) => {
90 let current_module = current_module(call.syntax(), ctx)?;
91 let module = adt.module(ctx.sema.db);
92 target_module = if current_module == module { None } else { Some(module) };
93 if current_module.krate() != module.krate() {
96 let (impl_, file) = get_adt_source(ctx, &adt, fn_name.text().as_str())?;
97 let (target, insert_offset) = get_method_target(ctx, &module, &impl_)?;
98 adt_name = if impl_.is_none() { Some(adt.name(ctx.sema.db)) } else { None };
99 (target, file, insert_offset)
106 target_module = None;
107 get_fn_target(ctx, &target_module, call.clone())?
110 let function_builder = FunctionBuilder::from_call(ctx, &call, &path, target_module, target)?;
111 let text_range = call.syntax().text_range();
112 let label = format!("Generate {} function", function_builder.fn_name.clone());
113 add_func_to_accumulator(
125 fn gen_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
126 let call: ast::MethodCallExpr = ctx.find_node_at_offset()?;
127 let fn_name = call.name_ref()?;
128 let adt = ctx.sema.type_of_expr(&call.receiver()?)?.original().strip_references().as_adt()?;
130 let current_module = current_module(call.syntax(), ctx)?;
131 let target_module = adt.module(ctx.sema.db);
133 if current_module.krate() != target_module.krate() {
136 let (impl_, file) = get_adt_source(ctx, &adt, fn_name.text().as_str())?;
137 let (target, insert_offset) = get_method_target(ctx, &target_module, &impl_)?;
138 let function_builder =
139 FunctionBuilder::from_method_call(ctx, &call, &fn_name, target_module, target)?;
140 let text_range = call.syntax().text_range();
141 let adt_name = if impl_.is_none() { Some(adt.name(ctx.sema.db)) } else { None };
142 let label = format!("Generate {} method", function_builder.fn_name.clone());
143 add_func_to_accumulator(
155 fn add_func_to_accumulator(
158 text_range: TextRange,
159 function_builder: FunctionBuilder,
160 insert_offset: TextSize,
162 adt_name: Option<hir::Name>,
165 acc.add(AssistId("generate_function", AssistKind::Generate), label, text_range, |builder| {
166 let function_template = function_builder.render();
167 let mut func = function_template.to_string(ctx.config.snippet_cap);
168 if let Some(name) = adt_name {
169 func = format!("\nimpl {} {{\n{}\n}}", name, func);
171 builder.edit_file(file);
172 match ctx.config.snippet_cap {
173 Some(cap) => builder.insert_snippet(cap, insert_offset, func),
174 None => builder.insert(insert_offset, func),
179 fn current_module(current_node: &SyntaxNode, ctx: &AssistContext) -> Option<Module> {
180 ctx.sema.scope(current_node).module()
187 ) -> Option<(Option<ast::Impl>, FileId)> {
188 let range = adt.source(ctx.sema.db)?.syntax().original_file_range(ctx.sema.db);
189 let file = ctx.sema.parse(range.file_id);
191 ctx.sema.find_node_at_offset_with_macros(file.syntax(), range.range.start())?;
192 find_struct_impl(ctx, &adt_source, fn_name).map(|impl_| (impl_, range.file_id))
195 struct FunctionTemplate {
198 ret_type: Option<ast::RetType>,
199 should_focus_return_type: bool,
201 tail_expr: ast::Expr,
204 impl FunctionTemplate {
205 fn to_string(&self, cap: Option<SnippetCap>) -> String {
208 let cursor = if self.should_focus_return_type {
209 // Focus the return type if there is one
210 if let Some(ref ret_type) = self.ret_type {
213 self.tail_expr.syntax()
216 self.tail_expr.syntax()
218 render_snippet(cap, self.fn_def.syntax(), Cursor::Replace(cursor))
220 None => self.fn_def.to_string(),
223 format!("{}{}{}", self.leading_ws, f, self.trailing_ws)
227 struct FunctionBuilder {
228 target: GeneratedFunctionTarget,
230 type_params: Option<ast::GenericParamList>,
231 params: ast::ParamList,
232 ret_type: Option<ast::RetType>,
233 should_focus_return_type: bool,
238 impl FunctionBuilder {
239 /// Prepares a generated function that matches `call`.
240 /// The function is generated in `target_module` or next to `call`
243 call: &ast::CallExpr,
245 target_module: Option<hir::Module>,
246 target: GeneratedFunctionTarget,
248 let needs_pub = target_module.is_some();
249 let target_module = target_module.or_else(|| current_module(target.syntax(), ctx))?;
250 let fn_name = fn_name(path)?;
251 let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Func(call.clone()))?;
253 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
254 let is_async = await_expr.is_some();
256 let (ret_type, should_focus_return_type) =
257 make_return_type(ctx, &ast::Expr::CallExpr(call.clone()), target_module);
265 should_focus_return_type,
273 call: &ast::MethodCallExpr,
275 target_module: Module,
276 target: GeneratedFunctionTarget,
279 !module_is_descendant(¤t_module(call.syntax(), ctx)?, &target_module, ctx);
280 let fn_name = make::name(&name.text());
281 let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Method(call.clone()))?;
283 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
284 let is_async = await_expr.is_some();
286 let (ret_type, should_focus_return_type) =
287 make_return_type(ctx, &ast::Expr::MethodCallExpr(call.clone()), target_module);
295 should_focus_return_type,
301 fn render(self) -> FunctionTemplate {
302 let placeholder_expr = make::ext::expr_todo();
303 let fn_body = make::block_expr(vec![], Some(placeholder_expr));
304 let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None };
305 let mut fn_def = make::fn_(
318 GeneratedFunctionTarget::BehindItem(it) => {
319 let indent = IndentLevel::from_node(&it);
320 leading_ws = format!("\n\n{}", indent);
321 fn_def = fn_def.indent(indent);
322 trailing_ws = String::new();
324 GeneratedFunctionTarget::InEmptyItemList(it) => {
325 let indent = IndentLevel::from_node(&it);
326 leading_ws = format!("\n{}", indent + 1);
327 fn_def = fn_def.indent(indent + 1);
328 trailing_ws = format!("\n{}", indent);
334 ret_type: fn_def.ret_type(),
335 // PANIC: we guarantee we always create a function body with a tail expr
336 tail_expr: fn_def.body().unwrap().tail_expr().unwrap(),
337 should_focus_return_type: self.should_focus_return_type,
344 /// Makes an optional return type along with whether the return type should be focused by the cursor.
345 /// If we cannot infer what the return type should be, we create unit as a placeholder.
347 /// The rule for whether we focus a return type or not (and thus focus the function body),
348 /// is rather simple:
349 /// * If we could *not* infer what the return type should be, focus it (so the user can fill-in
350 /// the correct return type).
351 /// * If we could infer the return type, don't focus it (and thus focus the function body) so the
352 /// user can change the `todo!` function body.
356 target_module: Module,
357 ) -> (Option<ast::RetType>, bool) {
358 let (ret_ty, should_focus_return_type) = {
359 match ctx.sema.type_of_expr(call).map(TypeInfo::original) {
360 Some(ty) if ty.is_unknown() => (Some(make::ty_unit()), true),
361 None => (Some(make::ty_unit()), true),
362 Some(ty) if ty.is_unit() => (None, false),
364 let rendered = ty.display_source_code(ctx.db(), target_module.into());
366 Ok(rendered) => (Some(make::ty(&rendered)), false),
367 Err(_) => (Some(make::ty_unit()), true),
372 let ret_type = ret_ty.map(|rt| make::ret_type(rt));
373 (ret_type, should_focus_return_type)
378 target_module: &Option<Module>,
380 ) -> Option<(GeneratedFunctionTarget, FileId, TextSize)> {
381 let mut file = ctx.frange.file_id;
382 let target = match target_module {
383 Some(target_module) => {
384 let module_source = target_module.definition_source(ctx.db());
385 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?;
389 None => next_space_for_fn_after_call_site(FuncExpr::Func(call.clone()))?,
391 Some((target.clone(), file, get_insert_offset(&target)))
394 fn get_method_target(
396 target_module: &Module,
397 impl_: &Option<ast::Impl>,
398 ) -> Option<(GeneratedFunctionTarget, TextSize)> {
399 let target = match impl_ {
400 Some(impl_) => next_space_for_fn_in_impl(&impl_)?,
402 next_space_for_fn_in_module(ctx.sema.db, &target_module.definition_source(ctx.sema.db))?
406 Some((target.clone(), get_insert_offset(&target)))
409 fn get_insert_offset(target: &GeneratedFunctionTarget) -> TextSize {
411 GeneratedFunctionTarget::BehindItem(it) => it.text_range().end(),
412 GeneratedFunctionTarget::InEmptyItemList(it) => it.text_range().start() + TextSize::of('{'),
417 enum GeneratedFunctionTarget {
418 BehindItem(SyntaxNode),
419 InEmptyItemList(SyntaxNode),
422 impl GeneratedFunctionTarget {
423 fn syntax(&self) -> &SyntaxNode {
425 GeneratedFunctionTarget::BehindItem(it) => it,
426 GeneratedFunctionTarget::InEmptyItemList(it) => it,
431 fn fn_name(call: &ast::Path) -> Option<ast::Name> {
432 let name = call.segment()?.syntax().to_string();
433 Some(make::name(&name))
436 /// Computes the type variables and arguments required for the generated function
439 target_module: hir::Module,
441 ) -> Option<(Option<ast::GenericParamList>, ast::ParamList)> {
442 let mut arg_names = Vec::new();
443 let mut arg_types = Vec::new();
444 for arg in call.arg_list()?.args() {
445 arg_names.push(match fn_arg_name(&arg) {
447 None => String::from("arg"),
449 arg_types.push(match fn_arg_type(ctx, target_module, &arg) {
451 if ty.len() > 0 && ty.starts_with('&') {
452 if let Some((new_ty, _)) = useless_type_special_case("", &ty[1..].to_owned()) {
461 None => String::from("()"),
464 deduplicate_arg_names(&mut arg_names);
465 let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| {
466 make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty))
473 FuncExpr::Func(_) => None,
474 FuncExpr::Method(_) => Some(make::self_param()),
481 /// Makes duplicate argument names unique by appending incrementing numbers.
484 /// let mut names: Vec<String> =
485 /// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
486 /// deduplicate_arg_names(&mut names);
487 /// let expected: Vec<String> =
488 /// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
489 /// assert_eq!(names, expected);
491 fn deduplicate_arg_names(arg_names: &mut Vec<String>) {
492 let arg_name_counts = arg_names.iter().fold(FxHashMap::default(), |mut m, name| {
493 *m.entry(name).or_insert(0) += 1;
496 let duplicate_arg_names: FxHashSet<String> = arg_name_counts
498 .filter(|(_, count)| *count >= 2)
499 .map(|(name, _)| name.clone())
502 let mut counter_per_name = FxHashMap::default();
503 for arg_name in arg_names.iter_mut() {
504 if duplicate_arg_names.contains(arg_name) {
505 let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
507 arg_name.push_str(&counter.to_string());
513 fn fn_arg_name(fn_arg: &ast::Expr) -> Option<String> {
515 ast::Expr::CastExpr(cast_expr) => fn_arg_name(&cast_expr.expr()?),
520 .filter(|d| ast::NameRef::can_cast(d.kind()))
523 Some(to_lower_snake_case(&s))
530 target_module: hir::Module,
532 ) -> Option<String> {
533 let ty = ctx.sema.type_of_expr(fn_arg)?.adjusted();
538 if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) {
545 /// Returns the position inside the current mod or file
546 /// directly after the current block
547 /// We want to write the generated function directly after
548 /// fns, impls or macro calls, but inside mods
549 fn next_space_for_fn_after_call_site(expr: FuncExpr) -> Option<GeneratedFunctionTarget> {
550 let mut ancestors = expr.syntax().ancestors().peekable();
551 let mut last_ancestor: Option<SyntaxNode> = None;
552 while let Some(next_ancestor) = ancestors.next() {
553 match next_ancestor.kind() {
554 SyntaxKind::SOURCE_FILE => {
557 SyntaxKind::ITEM_LIST => {
558 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
564 last_ancestor = Some(next_ancestor);
566 last_ancestor.map(GeneratedFunctionTarget::BehindItem)
569 fn next_space_for_fn_in_module(
570 db: &dyn hir::db::AstDatabase,
571 module_source: &hir::InFile<hir::ModuleSource>,
572 ) -> Option<(FileId, GeneratedFunctionTarget)> {
573 let file = module_source.file_id.original_file(db);
574 let assist_item = match &module_source.value {
575 hir::ModuleSource::SourceFile(it) => {
576 if let Some(last_item) = it.items().last() {
577 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
579 GeneratedFunctionTarget::BehindItem(it.syntax().clone())
582 hir::ModuleSource::Module(it) => {
583 if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
584 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
586 GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone())
589 hir::ModuleSource::BlockExpr(it) => {
590 if let Some(last_item) =
591 it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
593 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
595 GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone())
599 Some((file, assist_item))
602 fn next_space_for_fn_in_impl(impl_: &ast::Impl) -> Option<GeneratedFunctionTarget> {
603 if let Some(last_item) = impl_.assoc_item_list().and_then(|it| it.assoc_items().last()) {
604 Some(GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()))
606 Some(GeneratedFunctionTarget::InEmptyItemList(impl_.assoc_item_list()?.syntax().clone()))
610 fn module_is_descendant(module: &hir::Module, ans: &hir::Module, ctx: &AssistContext) -> bool {
614 for c in ans.children(ctx.sema.db) {
615 if module_is_descendant(module, &c, ctx) {
624 use crate::tests::{check_assist, check_assist_not_applicable};
629 fn add_function_with_no_args() {
642 fn bar() ${0:-> ()} {
650 fn add_function_from_method() {
651 // This ensures that the function is correctly generated
652 // in the next outer mod or file
669 fn bar() ${0:-> ()} {
677 fn add_function_directly_after_current_block() {
678 // The new fn should not be created at the end of the file or module
693 fn bar() ${0:-> ()} {
703 fn add_function_with_no_args_in_same_module() {
719 fn bar() ${0:-> ()} {
728 fn add_function_with_upper_camel_case_arg() {
743 fn bar(baz_baz: BazBaz) ${0:-> ()} {
751 fn add_function_with_upper_camel_case_arg_as_cast() {
757 bar$0(&BazBaz as *const BazBaz);
763 bar(&BazBaz as *const BazBaz);
766 fn bar(baz_baz: *const BazBaz) ${0:-> ()} {
774 fn add_function_with_function_call_arg() {
779 fn baz() -> Baz { todo!() }
786 fn baz() -> Baz { todo!() }
791 fn bar(baz: Baz) ${0:-> ()} {
799 fn add_function_with_method_call_arg() {
805 fn foo(&self) -> Baz {
808 fn baz(&self) -> Baz {
816 fn foo(&self) -> Baz {
819 fn baz(&self) -> Baz {
824 fn bar(baz: Baz) -> Baz {
832 fn add_function_with_string_literal_arg() {
853 fn add_function_with_char_literal_arg() {
874 fn add_function_with_int_literal_arg() {
895 fn add_function_with_cast_int_literal_arg() {
916 fn name_of_cast_variable_is_used() {
917 // Ensures that the name of the cast type isn't used
918 // in the generated function signature.
941 fn add_function_with_variable_arg() {
964 fn add_function_with_impl_trait_arg() {
970 fn foo() -> impl Foo {
979 fn foo() -> impl Foo {
986 fn bar(foo: impl Foo) {
999 fn baz() -> Baz { todo!() }
1007 fn baz() -> Baz { todo!() }
1021 fn add_function_with_qualified_path_arg() {
1027 pub fn baz() -> Bof { Bof }
1036 pub fn baz() -> Bof { Bof }
1042 fn bar(baz: Baz::Bof) {
1050 fn add_function_with_generic_arg() {
1051 // FIXME: This is wrong, generated `bar` should include generic parameter.
1072 fn add_function_with_fn_arg() {
1073 // FIXME: The argument in `bar` is wrong.
1079 fn new() -> Self { Baz }
1088 fn new() -> Self { Baz }
1094 fn bar(new: fn) ${0:-> ()} {
1102 fn add_function_with_closure_arg() {
1103 // FIXME: The argument in `bar` is wrong.
1108 let closure = |x: i64| x - 1;
1114 let closure = |x: i64| x - 1;
1118 fn bar(closure: ()) {
1126 fn unresolveable_types_default_to_unit() {
1147 fn arg_names_dont_overlap() {
1152 fn baz() -> Baz { Baz }
1159 fn baz() -> Baz { Baz }
1164 fn bar(baz_1: Baz, baz_2: Baz) {
1172 fn arg_name_counters_start_at_1_per_name() {
1177 fn baz() -> Baz { Baz }
1179 $0bar(baz(), baz(), "foo", "bar")
1184 fn baz() -> Baz { Baz }
1186 bar(baz(), baz(), "foo", "bar")
1189 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) {
1197 fn add_function_in_module() {
1209 pub(crate) fn my_fn() {
1222 fn qualified_path_uses_correct_scope() {
1245 fn baz(foo: foo::Foo) {
1253 fn add_function_in_module_containing_other_items() {
1258 fn something_else() {}
1267 fn something_else() {}
1269 pub(crate) fn my_fn() {
1282 fn add_function_in_nested_module() {
1297 pub(crate) fn my_fn() {
1311 fn add_function_in_another_file() {
1326 pub(crate) fn bar() {
1333 fn add_function_with_return_type() {
1338 let x: u32 = foo$0();
1354 fn add_function_not_applicable_if_function_already_exists() {
1355 check_assist_not_applicable(
1368 fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1369 check_assist_not_applicable(
1370 // bar is resolved, but baz isn't.
1371 // The assist is only active if the cursor is on an unresolved path,
1372 // but the assist should only be offered if the path is a function call.
1385 fn create_method_with_no_args() {
1403 fn bar(&self) ${0:-> ()} {
1412 fn create_function_with_async() {
1425 async fn bar(arg: i32) ${0:-> ()} {
1433 fn create_method() {
1438 fn foo() {S.bar$0();}
1446 fn bar(&self) ${0:-> ()} {
1455 fn create_method_within_an_impl() {
1460 fn foo() {S.bar$0();}
1468 fn bar(&self) ${0:-> ()} {
1478 fn create_method_from_different_module() {
1485 fn foo() {s::S.bar$0();}
1493 pub(crate) fn bar(&self) ${0:-> ()} {
1498 fn foo() {s::S.bar();}
1504 fn create_method_from_descendant_module() {
1526 fn bar(&self) ${0:-> ()} {
1536 fn create_method_with_cursor_anywhere_on_call_expresion() {
1541 fn foo() {$0S.bar();}
1549 fn bar(&self) ${0:-> ()} {
1558 fn create_static_method() {
1563 fn foo() {S::bar$0();}
1567 fn foo() {S::bar();}
1571 fn bar() ${0:-> ()} {
1580 fn create_static_method_within_an_impl() {
1585 fn foo() {S::bar$0();}
1591 fn foo() {S::bar();}
1593 fn bar() ${0:-> ()} {
1603 fn create_static_method_from_different_module() {
1610 fn foo() {s::S::bar$0();}
1618 pub(crate) fn bar() ${0:-> ()} {
1623 fn foo() {s::S::bar();}
1629 fn create_static_method_with_cursor_anywhere_on_call_expresion() {
1634 fn foo() {$0S::bar();}
1638 fn foo() {S::bar();}
1642 fn bar() ${0:-> ()} {