1 use rustc_hash::{FxHashMap, FxHashSet};
3 use hir::{HasSource, HirDisplay, Module, ModuleDef, 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 let fn_name = call.name_ref()?;
115 let adt = ctx.sema.type_of_expr(&call.receiver()?)?.original().strip_references().as_adt()?;
117 let current_module = current_module(call.syntax(), ctx)?;
118 let target_module = adt.module(ctx.sema.db);
120 if current_module.krate() != target_module.krate() {
123 let (impl_, file) = get_adt_source(ctx, &adt, fn_name.text().as_str())?;
124 let (target, insert_offset) = get_method_target(ctx, &target_module, &impl_)?;
125 let function_builder =
126 FunctionBuilder::from_method_call(ctx, &call, &fn_name, target_module, target)?;
127 let text_range = call.syntax().text_range();
128 let adt_name = if impl_.is_none() { Some(adt.name(ctx.sema.db)) } else { None };
129 let label = format!("Generate {} method", function_builder.fn_name);
130 add_func_to_accumulator(
142 fn add_func_to_accumulator(
145 text_range: TextRange,
146 function_builder: FunctionBuilder,
147 insert_offset: TextSize,
149 adt_name: Option<hir::Name>,
152 acc.add(AssistId("generate_function", AssistKind::Generate), label, text_range, |builder| {
153 let function_template = function_builder.render();
154 let mut func = function_template.to_string(ctx.config.snippet_cap);
155 if let Some(name) = adt_name {
156 func = format!("\nimpl {} {{\n{}\n}}", name, func);
158 builder.edit_file(file);
159 match ctx.config.snippet_cap {
160 Some(cap) => builder.insert_snippet(cap, insert_offset, func),
161 None => builder.insert(insert_offset, func),
166 fn current_module(current_node: &SyntaxNode, ctx: &AssistContext) -> Option<Module> {
167 ctx.sema.scope(current_node).module()
174 ) -> Option<(Option<ast::Impl>, FileId)> {
175 let range = adt.source(ctx.sema.db)?.syntax().original_file_range(ctx.sema.db);
176 let file = ctx.sema.parse(range.file_id);
178 ctx.sema.find_node_at_offset_with_macros(file.syntax(), range.range.start())?;
179 find_struct_impl(ctx, &adt_source, fn_name).map(|impl_| (impl_, range.file_id))
182 struct FunctionTemplate {
185 ret_type: Option<ast::RetType>,
186 should_focus_return_type: bool,
188 tail_expr: ast::Expr,
191 impl FunctionTemplate {
192 fn to_string(&self, cap: Option<SnippetCap>) -> String {
195 let cursor = if self.should_focus_return_type {
196 // Focus the return type if there is one
197 match self.ret_type {
198 Some(ref ret_type) => ret_type.syntax(),
199 None => self.tail_expr.syntax(),
202 self.tail_expr.syntax()
204 render_snippet(cap, self.fn_def.syntax(), Cursor::Replace(cursor))
206 None => self.fn_def.to_string(),
209 format!("{}{}{}", self.leading_ws, f, self.trailing_ws)
213 struct FunctionBuilder {
214 target: GeneratedFunctionTarget,
216 type_params: Option<ast::GenericParamList>,
217 params: ast::ParamList,
218 ret_type: Option<ast::RetType>,
219 should_focus_return_type: bool,
224 impl FunctionBuilder {
225 /// Prepares a generated function that matches `call`.
226 /// The function is generated in `target_module` or next to `call`
229 call: &ast::CallExpr,
231 target_module: Option<hir::Module>,
232 target: GeneratedFunctionTarget,
234 let needs_pub = target_module.is_some();
235 let target_module = target_module.or_else(|| current_module(target.syntax(), ctx))?;
236 let fn_name = make::name(fn_name);
237 let (type_params, params) =
238 fn_args(ctx, target_module, ast::CallableExpr::Call(call.clone()))?;
240 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
241 let is_async = await_expr.is_some();
243 let (ret_type, should_focus_return_type) =
244 make_return_type(ctx, &ast::Expr::CallExpr(call.clone()), target_module);
252 should_focus_return_type,
260 call: &ast::MethodCallExpr,
262 target_module: Module,
263 target: GeneratedFunctionTarget,
266 !module_is_descendant(¤t_module(call.syntax(), ctx)?, &target_module, ctx);
267 let fn_name = make::name(&name.text());
268 let (type_params, params) =
269 fn_args(ctx, target_module, ast::CallableExpr::MethodCall(call.clone()))?;
271 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
272 let is_async = await_expr.is_some();
274 let (ret_type, should_focus_return_type) =
275 make_return_type(ctx, &ast::Expr::MethodCallExpr(call.clone()), target_module);
283 should_focus_return_type,
289 fn render(self) -> FunctionTemplate {
290 let placeholder_expr = make::ext::expr_todo();
291 let fn_body = make::block_expr(vec![], Some(placeholder_expr));
292 let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None };
293 let mut fn_def = make::fn_(
306 GeneratedFunctionTarget::BehindItem(it) => {
307 let indent = IndentLevel::from_node(&it);
308 leading_ws = format!("\n\n{}", indent);
309 fn_def = fn_def.indent(indent);
310 trailing_ws = String::new();
312 GeneratedFunctionTarget::InEmptyItemList(it) => {
313 let indent = IndentLevel::from_node(&it);
314 leading_ws = format!("\n{}", indent + 1);
315 fn_def = fn_def.indent(indent + 1);
316 trailing_ws = format!("\n{}", indent);
322 ret_type: fn_def.ret_type(),
323 // PANIC: we guarantee we always create a function body with a tail expr
324 tail_expr: fn_def.body().unwrap().tail_expr().unwrap(),
325 should_focus_return_type: self.should_focus_return_type,
332 /// Makes an optional return type along with whether the return type should be focused by the cursor.
333 /// If we cannot infer what the return type should be, we create a placeholder type.
335 /// The rule for whether we focus a return type or not (and thus focus the function body),
336 /// is rather simple:
337 /// * If we could *not* infer what the return type should be, focus it (so the user can fill-in
338 /// the correct return type).
339 /// * If we could infer the return type, don't focus it (and thus focus the function body) so the
340 /// user can change the `todo!` function body.
344 target_module: Module,
345 ) -> (Option<ast::RetType>, bool) {
346 let (ret_ty, should_focus_return_type) = {
347 match ctx.sema.type_of_expr(call).map(TypeInfo::original) {
348 Some(ty) if ty.is_unknown() => (Some(make::ty_placeholder()), true),
349 None => (Some(make::ty_placeholder()), true),
350 Some(ty) if ty.is_unit() => (None, false),
352 let rendered = ty.display_source_code(ctx.db(), target_module.into());
354 Ok(rendered) => (Some(make::ty(&rendered)), false),
355 Err(_) => (Some(make::ty_placeholder()), true),
360 let ret_type = ret_ty.map(make::ret_type);
361 (ret_type, should_focus_return_type)
366 target_module: &Option<Module>,
368 ) -> Option<(GeneratedFunctionTarget, FileId, TextSize)> {
369 let mut file = ctx.file_id();
370 let target = match target_module {
371 Some(target_module) => {
372 let module_source = target_module.definition_source(ctx.db());
373 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?;
377 None => next_space_for_fn_after_call_site(ast::CallableExpr::Call(call))?,
379 Some((target.clone(), file, get_insert_offset(&target)))
382 fn get_method_target(
384 target_module: &Module,
385 impl_: &Option<ast::Impl>,
386 ) -> Option<(GeneratedFunctionTarget, TextSize)> {
387 let target = match impl_ {
388 Some(impl_) => next_space_for_fn_in_impl(impl_)?,
390 next_space_for_fn_in_module(ctx.sema.db, &target_module.definition_source(ctx.sema.db))?
394 Some((target.clone(), get_insert_offset(&target)))
397 fn get_insert_offset(target: &GeneratedFunctionTarget) -> TextSize {
399 GeneratedFunctionTarget::BehindItem(it) => it.text_range().end(),
400 GeneratedFunctionTarget::InEmptyItemList(it) => it.text_range().start() + TextSize::of('{'),
405 enum GeneratedFunctionTarget {
406 BehindItem(SyntaxNode),
407 InEmptyItemList(SyntaxNode),
410 impl GeneratedFunctionTarget {
411 fn syntax(&self) -> &SyntaxNode {
413 GeneratedFunctionTarget::BehindItem(it) => it,
414 GeneratedFunctionTarget::InEmptyItemList(it) => it,
419 /// Computes the type variables and arguments required for the generated function
422 target_module: hir::Module,
423 call: ast::CallableExpr,
424 ) -> Option<(Option<ast::GenericParamList>, ast::ParamList)> {
425 let mut arg_names = Vec::new();
426 let mut arg_types = Vec::new();
427 for arg in call.arg_list()?.args() {
428 arg_names.push(fn_arg_name(&ctx.sema, &arg));
429 arg_types.push(fn_arg_type(ctx, target_module, &arg));
431 deduplicate_arg_names(&mut arg_names);
432 let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| {
433 make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty))
440 ast::CallableExpr::Call(_) => None,
441 ast::CallableExpr::MethodCall(_) => Some(make::self_param()),
448 /// Makes duplicate argument names unique by appending incrementing numbers.
451 /// let mut names: Vec<String> =
452 /// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
453 /// deduplicate_arg_names(&mut names);
454 /// let expected: Vec<String> =
455 /// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
456 /// assert_eq!(names, expected);
458 fn deduplicate_arg_names(arg_names: &mut Vec<String>) {
459 let arg_name_counts = arg_names.iter().fold(FxHashMap::default(), |mut m, name| {
460 *m.entry(name).or_insert(0) += 1;
463 let duplicate_arg_names: FxHashSet<String> = arg_name_counts
465 .filter(|(_, count)| *count >= 2)
466 .map(|(name, _)| name.clone())
469 let mut counter_per_name = FxHashMap::default();
470 for arg_name in arg_names.iter_mut() {
471 if duplicate_arg_names.contains(arg_name) {
472 let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
474 arg_name.push_str(&counter.to_string());
480 fn fn_arg_name(sema: &Semantics<RootDatabase>, arg_expr: &ast::Expr) -> String {
481 let name = (|| match arg_expr {
482 ast::Expr::CastExpr(cast_expr) => Some(fn_arg_name(sema, &cast_expr.expr()?)),
484 let name_ref = expr.syntax().descendants().filter_map(ast::NameRef::cast).last()?;
485 if let Some(NameRefClass::Definition(Definition::ModuleDef(
486 ModuleDef::Const(_) | ModuleDef::Static(_),
487 ))) = NameRefClass::classify(sema, &name_ref)
489 return Some(name_ref.to_string().to_lowercase());
491 Some(to_lower_snake_case(&name_ref.to_string()))
495 Some(mut name) if name.starts_with(|c: char| c.is_ascii_digit()) => {
496 name.insert_str(0, "arg");
500 None => "arg".to_string(),
504 fn fn_arg_type(ctx: &AssistContext, target_module: hir::Module, fn_arg: &ast::Expr) -> String {
505 fn maybe_displayed_type(
507 target_module: hir::Module,
509 ) -> Option<String> {
510 let ty = ctx.sema.type_of_expr(fn_arg)?.adjusted();
515 if ty.is_reference() || ty.is_mutable_reference() {
516 let famous_defs = &FamousDefs(&ctx.sema, ctx.sema.scope(fn_arg.syntax()).krate());
517 convert_reference_type(ty.strip_references(), ctx.db(), famous_defs)
518 .map(|conversion| conversion.convert_type(ctx.db()))
519 .or_else(|| ty.display_source_code(ctx.db(), target_module.into()).ok())
521 ty.display_source_code(ctx.db(), target_module.into()).ok()
525 maybe_displayed_type(ctx, target_module, fn_arg).unwrap_or_else(|| String::from("_"))
528 /// Returns the position inside the current mod or file
529 /// directly after the current block
530 /// We want to write the generated function directly after
531 /// fns, impls or macro calls, but inside mods
532 fn next_space_for_fn_after_call_site(expr: ast::CallableExpr) -> Option<GeneratedFunctionTarget> {
533 let mut ancestors = expr.syntax().ancestors().peekable();
534 let mut last_ancestor: Option<SyntaxNode> = None;
535 while let Some(next_ancestor) = ancestors.next() {
536 match next_ancestor.kind() {
537 SyntaxKind::SOURCE_FILE => {
540 SyntaxKind::ITEM_LIST => {
541 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
547 last_ancestor = Some(next_ancestor);
549 last_ancestor.map(GeneratedFunctionTarget::BehindItem)
552 fn next_space_for_fn_in_module(
553 db: &dyn hir::db::AstDatabase,
554 module_source: &hir::InFile<hir::ModuleSource>,
555 ) -> Option<(FileId, GeneratedFunctionTarget)> {
556 let file = module_source.file_id.original_file(db);
557 let assist_item = match &module_source.value {
558 hir::ModuleSource::SourceFile(it) => match it.items().last() {
559 Some(last_item) => GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()),
560 None => GeneratedFunctionTarget::BehindItem(it.syntax().clone()),
562 hir::ModuleSource::Module(it) => match it.item_list().and_then(|it| it.items().last()) {
563 Some(last_item) => GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()),
564 None => GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone()),
566 hir::ModuleSource::BlockExpr(it) => {
567 if let Some(last_item) =
568 it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
570 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
572 GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone())
576 Some((file, assist_item))
579 fn next_space_for_fn_in_impl(impl_: &ast::Impl) -> Option<GeneratedFunctionTarget> {
580 if let Some(last_item) = impl_.assoc_item_list().and_then(|it| it.assoc_items().last()) {
581 Some(GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()))
583 Some(GeneratedFunctionTarget::InEmptyItemList(impl_.assoc_item_list()?.syntax().clone()))
587 fn module_is_descendant(module: &hir::Module, ans: &hir::Module, ctx: &AssistContext) -> bool {
591 for c in ans.children(ctx.sema.db) {
592 if module_is_descendant(module, &c, ctx) {
601 use crate::tests::{check_assist, check_assist_not_applicable};
606 fn add_function_with_no_args() {
627 fn add_function_from_method() {
628 // This ensures that the function is correctly generated
629 // in the next outer mod or file
654 fn add_function_directly_after_current_block() {
655 // The new fn should not be created at the end of the file or module
680 fn add_function_with_no_args_in_same_module() {
705 fn add_function_with_upper_camel_case_arg() {
720 fn bar(baz_baz: BazBaz) ${0:-> _} {
728 fn add_function_with_upper_camel_case_arg_as_cast() {
734 bar$0(&BazBaz as *const BazBaz);
740 bar(&BazBaz as *const BazBaz);
743 fn bar(baz_baz: *const BazBaz) ${0:-> _} {
751 fn add_function_with_function_call_arg() {
756 fn baz() -> Baz { todo!() }
763 fn baz() -> Baz { todo!() }
768 fn bar(baz: Baz) ${0:-> _} {
776 fn add_function_with_method_call_arg() {
782 fn foo(&self) -> Baz {
785 fn baz(&self) -> Baz {
793 fn foo(&self) -> Baz {
796 fn baz(&self) -> Baz {
801 fn bar(baz: Baz) -> Baz {
809 fn add_function_with_string_literal_arg() {
830 fn add_function_with_char_literal_arg() {
851 fn add_function_with_int_literal_arg() {
872 fn add_function_with_cast_int_literal_arg() {
893 fn name_of_cast_variable_is_used() {
894 // Ensures that the name of the cast type isn't used
895 // in the generated function signature.
918 fn add_function_with_variable_arg() {
941 fn add_function_with_impl_trait_arg() {
947 fn foo() -> impl Foo {
956 fn foo() -> impl Foo {
963 fn bar(foo: impl Foo) {
976 fn baz() -> Baz { todo!() }
984 fn baz() -> Baz { todo!() }
998 fn add_function_with_qualified_path_arg() {
1004 pub fn baz() -> Bof { Bof }
1013 pub fn baz() -> Bof { Bof }
1019 fn bar(baz: Baz::Bof) {
1027 fn add_function_with_generic_arg() {
1028 // FIXME: This is wrong, generated `bar` should include generic parameter.
1049 fn add_function_with_fn_arg() {
1050 // FIXME: The argument in `bar` is wrong.
1056 fn new() -> Self { Baz }
1065 fn new() -> Self { Baz }
1071 fn bar(new: fn) ${0:-> _} {
1079 fn add_function_with_closure_arg() {
1080 // FIXME: The argument in `bar` is wrong.
1085 let closure = |x: i64| x - 1;
1091 let closure = |x: i64| x - 1;
1095 fn bar(closure: _) {
1103 fn unresolveable_types_default_to_placeholder() {
1124 fn arg_names_dont_overlap() {
1129 fn baz() -> Baz { Baz }
1136 fn baz() -> Baz { Baz }
1141 fn bar(baz_1: Baz, baz_2: Baz) {
1149 fn arg_name_counters_start_at_1_per_name() {
1154 fn baz() -> Baz { Baz }
1156 $0bar(baz(), baz(), "foo", "bar")
1161 fn baz() -> Baz { Baz }
1163 bar(baz(), baz(), "foo", "bar")
1166 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) {
1174 fn add_function_in_module() {
1186 pub(crate) fn my_fn() {
1199 fn qualified_path_uses_correct_scope() {
1222 fn baz(foo: foo::Foo) {
1230 fn add_function_in_module_containing_other_items() {
1235 fn something_else() {}
1244 fn something_else() {}
1246 pub(crate) fn my_fn() {
1259 fn add_function_in_nested_module() {
1274 pub(crate) fn my_fn() {
1288 fn add_function_in_another_file() {
1303 pub(crate) fn bar() {
1310 fn add_function_with_return_type() {
1315 let x: u32 = foo$0();
1331 fn add_function_not_applicable_if_function_already_exists() {
1332 check_assist_not_applicable(
1345 fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1346 check_assist_not_applicable(
1347 // bar is resolved, but baz isn't.
1348 // The assist is only active if the cursor is on an unresolved path,
1349 // but the assist should only be offered if the path is a function call.
1362 fn create_method_with_no_args() {
1380 fn bar(&self) ${0:-> _} {
1389 fn create_function_with_async() {
1402 async fn bar(arg: i32) ${0:-> _} {
1410 fn create_method() {
1415 fn foo() {S.bar$0();}
1423 fn bar(&self) ${0:-> _} {
1432 fn create_method_within_an_impl() {
1437 fn foo() {S.bar$0();}
1445 fn bar(&self) ${0:-> _} {
1455 fn create_method_from_different_module() {
1462 fn foo() {s::S.bar$0();}
1470 pub(crate) fn bar(&self) ${0:-> _} {
1475 fn foo() {s::S.bar();}
1481 fn create_method_from_descendant_module() {
1503 fn bar(&self) ${0:-> _} {
1513 fn create_method_with_cursor_anywhere_on_call_expresion() {
1518 fn foo() {$0S.bar();}
1526 fn bar(&self) ${0:-> _} {
1535 fn create_static_method() {
1540 fn foo() {S::bar$0();}
1544 fn foo() {S::bar();}
1548 fn bar() ${0:-> _} {
1557 fn create_static_method_within_an_impl() {
1562 fn foo() {S::bar$0();}
1568 fn foo() {S::bar();}
1570 fn bar() ${0:-> _} {
1580 fn create_static_method_from_different_module() {
1587 fn foo() {s::S::bar$0();}
1595 pub(crate) fn bar() ${0:-> _} {
1600 fn foo() {s::S::bar();}
1606 fn create_static_method_with_cursor_anywhere_on_call_expresion() {
1611 fn foo() {$0S::bar();}
1615 fn foo() {S::bar();}
1619 fn bar() ${0:-> _} {
1628 fn no_panic_on_invalid_global_path() {
1641 fn foo() ${0:-> _} {
1649 fn handle_tuple_indexing() {
1664 fn foo(arg0: ()) ${0:-> _} {
1672 fn add_function_with_const_arg() {
1676 const VALUE: usize = 0;
1682 const VALUE: usize = 0;
1687 fn foo(value: usize) ${0:-> _} {
1695 fn add_function_with_static_arg() {
1699 static VALUE: usize = 0;
1705 static VALUE: usize = 0;
1710 fn foo(value: usize) ${0:-> _} {
1718 fn add_function_with_static_mut_arg() {
1722 static mut VALUE: usize = 0;
1728 static mut VALUE: usize = 0;
1733 fn foo(value: usize) ${0:-> _} {