1 use hir::{HasSource, HirDisplay, Module, ModuleDef, Semantics, TypeInfo};
4 defs::{Definition, NameRefClass},
8 use rustc_hash::{FxHashMap, FxHashSet};
9 use stdx::to_lower_snake_case;
13 edit::{AstNodeEdit, IndentLevel},
14 make, ArgListOwner, AstNode, CallExpr, ModuleItemOwner,
16 SyntaxKind, SyntaxNode, TextRange, TextSize,
20 utils::useless_type_special_case,
21 utils::{find_struct_impl, render_snippet, Cursor},
22 AssistContext, AssistId, AssistKind, Assists,
25 // Assist: generate_function
27 // Adds a stub function with a signature matching the function under the cursor.
31 // fn baz() -> Baz { Baz }
40 // fn baz() -> Baz { Baz }
45 // fn bar(arg: &str, baz: Baz) ${0:-> _} {
50 pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
51 gen_fn(acc, ctx).or_else(|| gen_method(acc, ctx))
56 Method(ast::MethodCallExpr),
60 fn arg_list(&self) -> Option<ast::ArgList> {
62 FuncExpr::Func(fn_call) => fn_call.arg_list(),
63 FuncExpr::Method(m_call) => m_call.arg_list(),
67 fn syntax(&self) -> &SyntaxNode {
69 FuncExpr::Func(fn_call) => fn_call.syntax(),
70 FuncExpr::Method(m_call) => m_call.syntax(),
75 fn gen_fn(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
76 let path_expr: ast::PathExpr = ctx.find_node_at_offset()?;
77 let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?;
78 let path = path_expr.path()?;
79 let name_ref = path.segment()?.name_ref()?;
80 if ctx.sema.resolve_path(&path).is_some() {
81 // The function call already resolves, no need to add a function
85 let fn_name = &*name_ref.text();
87 let mut adt_name = None;
89 let (target, file, insert_offset) = match path.qualifier() {
90 Some(qualifier) => match ctx.sema.resolve_path(&qualifier) {
91 Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => {
92 target_module = Some(module);
93 get_fn_target(ctx, &target_module, call.clone())?
95 Some(hir::PathResolution::Def(hir::ModuleDef::Adt(adt))) => {
96 let current_module = current_module(call.syntax(), ctx)?;
97 let module = adt.module(ctx.sema.db);
98 target_module = if current_module == module { None } else { Some(module) };
99 if current_module.krate() != module.krate() {
102 let (impl_, file) = get_adt_source(ctx, &adt, fn_name)?;
103 let (target, insert_offset) = get_method_target(ctx, &module, &impl_)?;
104 adt_name = if impl_.is_none() { Some(adt.name(ctx.sema.db)) } else { None };
105 (target, file, insert_offset)
112 target_module = None;
113 get_fn_target(ctx, &target_module, call.clone())?
116 let function_builder = FunctionBuilder::from_call(ctx, &call, fn_name, target_module, target)?;
117 let text_range = call.syntax().text_range();
118 let label = format!("Generate {} function", function_builder.fn_name);
119 add_func_to_accumulator(
131 fn gen_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
132 let call: ast::MethodCallExpr = ctx.find_node_at_offset()?;
133 let fn_name = call.name_ref()?;
134 let adt = ctx.sema.type_of_expr(&call.receiver()?)?.original().strip_references().as_adt()?;
136 let current_module = current_module(call.syntax(), ctx)?;
137 let target_module = adt.module(ctx.sema.db);
139 if current_module.krate() != target_module.krate() {
142 let (impl_, file) = get_adt_source(ctx, &adt, fn_name.text().as_str())?;
143 let (target, insert_offset) = get_method_target(ctx, &target_module, &impl_)?;
144 let function_builder =
145 FunctionBuilder::from_method_call(ctx, &call, &fn_name, target_module, target)?;
146 let text_range = call.syntax().text_range();
147 let adt_name = if impl_.is_none() { Some(adt.name(ctx.sema.db)) } else { None };
148 let label = format!("Generate {} method", function_builder.fn_name);
149 add_func_to_accumulator(
161 fn add_func_to_accumulator(
164 text_range: TextRange,
165 function_builder: FunctionBuilder,
166 insert_offset: TextSize,
168 adt_name: Option<hir::Name>,
171 acc.add(AssistId("generate_function", AssistKind::Generate), label, text_range, |builder| {
172 let function_template = function_builder.render();
173 let mut func = function_template.to_string(ctx.config.snippet_cap);
174 if let Some(name) = adt_name {
175 func = format!("\nimpl {} {{\n{}\n}}", name, func);
177 builder.edit_file(file);
178 match ctx.config.snippet_cap {
179 Some(cap) => builder.insert_snippet(cap, insert_offset, func),
180 None => builder.insert(insert_offset, func),
185 fn current_module(current_node: &SyntaxNode, ctx: &AssistContext) -> Option<Module> {
186 ctx.sema.scope(current_node).module()
193 ) -> Option<(Option<ast::Impl>, FileId)> {
194 let range = adt.source(ctx.sema.db)?.syntax().original_file_range(ctx.sema.db);
195 let file = ctx.sema.parse(range.file_id);
197 ctx.sema.find_node_at_offset_with_macros(file.syntax(), range.range.start())?;
198 find_struct_impl(ctx, &adt_source, fn_name).map(|impl_| (impl_, range.file_id))
201 struct FunctionTemplate {
204 ret_type: Option<ast::RetType>,
205 should_focus_return_type: bool,
207 tail_expr: ast::Expr,
210 impl FunctionTemplate {
211 fn to_string(&self, cap: Option<SnippetCap>) -> String {
214 let cursor = if self.should_focus_return_type {
215 // Focus the return type if there is one
216 if let Some(ref ret_type) = self.ret_type {
219 self.tail_expr.syntax()
222 self.tail_expr.syntax()
224 render_snippet(cap, self.fn_def.syntax(), Cursor::Replace(cursor))
226 None => self.fn_def.to_string(),
229 format!("{}{}{}", self.leading_ws, f, self.trailing_ws)
233 struct FunctionBuilder {
234 target: GeneratedFunctionTarget,
236 type_params: Option<ast::GenericParamList>,
237 params: ast::ParamList,
238 ret_type: Option<ast::RetType>,
239 should_focus_return_type: bool,
244 impl FunctionBuilder {
245 /// Prepares a generated function that matches `call`.
246 /// The function is generated in `target_module` or next to `call`
249 call: &ast::CallExpr,
251 target_module: Option<hir::Module>,
252 target: GeneratedFunctionTarget,
254 let needs_pub = target_module.is_some();
255 let target_module = target_module.or_else(|| current_module(target.syntax(), ctx))?;
256 let fn_name = make::name(fn_name);
257 let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Func(call.clone()))?;
259 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
260 let is_async = await_expr.is_some();
262 let (ret_type, should_focus_return_type) =
263 make_return_type(ctx, &ast::Expr::CallExpr(call.clone()), target_module);
271 should_focus_return_type,
279 call: &ast::MethodCallExpr,
281 target_module: Module,
282 target: GeneratedFunctionTarget,
285 !module_is_descendant(¤t_module(call.syntax(), ctx)?, &target_module, ctx);
286 let fn_name = make::name(&name.text());
287 let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Method(call.clone()))?;
289 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
290 let is_async = await_expr.is_some();
292 let (ret_type, should_focus_return_type) =
293 make_return_type(ctx, &ast::Expr::MethodCallExpr(call.clone()), target_module);
301 should_focus_return_type,
307 fn render(self) -> FunctionTemplate {
308 let placeholder_expr = make::ext::expr_todo();
309 let fn_body = make::block_expr(vec![], Some(placeholder_expr));
310 let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None };
311 let mut fn_def = make::fn_(
324 GeneratedFunctionTarget::BehindItem(it) => {
325 let indent = IndentLevel::from_node(&it);
326 leading_ws = format!("\n\n{}", indent);
327 fn_def = fn_def.indent(indent);
328 trailing_ws = String::new();
330 GeneratedFunctionTarget::InEmptyItemList(it) => {
331 let indent = IndentLevel::from_node(&it);
332 leading_ws = format!("\n{}", indent + 1);
333 fn_def = fn_def.indent(indent + 1);
334 trailing_ws = format!("\n{}", indent);
340 ret_type: fn_def.ret_type(),
341 // PANIC: we guarantee we always create a function body with a tail expr
342 tail_expr: fn_def.body().unwrap().tail_expr().unwrap(),
343 should_focus_return_type: self.should_focus_return_type,
350 /// Makes an optional return type along with whether the return type should be focused by the cursor.
351 /// If we cannot infer what the return type should be, we create a placeholder type.
353 /// The rule for whether we focus a return type or not (and thus focus the function body),
354 /// is rather simple:
355 /// * If we could *not* infer what the return type should be, focus it (so the user can fill-in
356 /// the correct return type).
357 /// * If we could infer the return type, don't focus it (and thus focus the function body) so the
358 /// user can change the `todo!` function body.
362 target_module: Module,
363 ) -> (Option<ast::RetType>, bool) {
364 let (ret_ty, should_focus_return_type) = {
365 match ctx.sema.type_of_expr(call).map(TypeInfo::original) {
366 Some(ty) if ty.is_unknown() => (Some(make::ty_placeholder()), true),
367 None => (Some(make::ty_placeholder()), true),
368 Some(ty) if ty.is_unit() => (None, false),
370 let rendered = ty.display_source_code(ctx.db(), target_module.into());
372 Ok(rendered) => (Some(make::ty(&rendered)), false),
373 Err(_) => (Some(make::ty_placeholder()), true),
378 let ret_type = ret_ty.map(make::ret_type);
379 (ret_type, should_focus_return_type)
384 target_module: &Option<Module>,
386 ) -> Option<(GeneratedFunctionTarget, FileId, TextSize)> {
387 let mut file = ctx.frange.file_id;
388 let target = match target_module {
389 Some(target_module) => {
390 let module_source = target_module.definition_source(ctx.db());
391 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?;
395 None => next_space_for_fn_after_call_site(FuncExpr::Func(call))?,
397 Some((target.clone(), file, get_insert_offset(&target)))
400 fn get_method_target(
402 target_module: &Module,
403 impl_: &Option<ast::Impl>,
404 ) -> Option<(GeneratedFunctionTarget, TextSize)> {
405 let target = match impl_ {
406 Some(impl_) => next_space_for_fn_in_impl(impl_)?,
408 next_space_for_fn_in_module(ctx.sema.db, &target_module.definition_source(ctx.sema.db))?
412 Some((target.clone(), get_insert_offset(&target)))
415 fn get_insert_offset(target: &GeneratedFunctionTarget) -> TextSize {
417 GeneratedFunctionTarget::BehindItem(it) => it.text_range().end(),
418 GeneratedFunctionTarget::InEmptyItemList(it) => it.text_range().start() + TextSize::of('{'),
423 enum GeneratedFunctionTarget {
424 BehindItem(SyntaxNode),
425 InEmptyItemList(SyntaxNode),
428 impl GeneratedFunctionTarget {
429 fn syntax(&self) -> &SyntaxNode {
431 GeneratedFunctionTarget::BehindItem(it) => it,
432 GeneratedFunctionTarget::InEmptyItemList(it) => it,
437 /// Computes the type variables and arguments required for the generated function
440 target_module: hir::Module,
442 ) -> Option<(Option<ast::GenericParamList>, ast::ParamList)> {
443 let mut arg_names = Vec::new();
444 let mut arg_types = Vec::new();
445 for arg in call.arg_list()?.args() {
446 arg_names.push(fn_arg_name(&ctx.sema, &arg));
447 arg_types.push(match fn_arg_type(ctx, target_module, &arg) {
449 if !ty.is_empty() && ty.starts_with('&') {
450 if let Some((new_ty, _)) = useless_type_special_case("", &ty[1..].to_owned()) {
459 None => String::from("_"),
462 deduplicate_arg_names(&mut arg_names);
463 let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| {
464 make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty))
471 FuncExpr::Func(_) => None,
472 FuncExpr::Method(_) => Some(make::self_param()),
479 /// Makes duplicate argument names unique by appending incrementing numbers.
482 /// let mut names: Vec<String> =
483 /// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
484 /// deduplicate_arg_names(&mut names);
485 /// let expected: Vec<String> =
486 /// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
487 /// assert_eq!(names, expected);
489 fn deduplicate_arg_names(arg_names: &mut Vec<String>) {
490 let arg_name_counts = arg_names.iter().fold(FxHashMap::default(), |mut m, name| {
491 *m.entry(name).or_insert(0) += 1;
494 let duplicate_arg_names: FxHashSet<String> = arg_name_counts
496 .filter(|(_, count)| *count >= 2)
497 .map(|(name, _)| name.clone())
500 let mut counter_per_name = FxHashMap::default();
501 for arg_name in arg_names.iter_mut() {
502 if duplicate_arg_names.contains(arg_name) {
503 let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
505 arg_name.push_str(&counter.to_string());
511 fn fn_arg_name(sema: &Semantics<RootDatabase>, arg_expr: &ast::Expr) -> String {
512 let name = (|| match arg_expr {
513 ast::Expr::CastExpr(cast_expr) => Some(fn_arg_name(sema, &cast_expr.expr()?)),
515 let name_ref = expr.syntax().descendants().filter_map(ast::NameRef::cast).last()?;
516 if let Some(NameRefClass::Definition(Definition::ModuleDef(
517 ModuleDef::Const(_) | ModuleDef::Static(_),
518 ))) = NameRefClass::classify(sema, &name_ref)
520 return Some(name_ref.to_string().to_lowercase());
522 Some(to_lower_snake_case(&name_ref.to_string()))
526 Some(mut name) if name.starts_with(|c: char| c.is_ascii_digit()) => {
527 name.insert_str(0, "arg");
531 None => "arg".to_string(),
537 target_module: hir::Module,
539 ) -> Option<String> {
540 let ty = ctx.sema.type_of_expr(fn_arg)?.adjusted();
545 if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) {
552 /// Returns the position inside the current mod or file
553 /// directly after the current block
554 /// We want to write the generated function directly after
555 /// fns, impls or macro calls, but inside mods
556 fn next_space_for_fn_after_call_site(expr: FuncExpr) -> Option<GeneratedFunctionTarget> {
557 let mut ancestors = expr.syntax().ancestors().peekable();
558 let mut last_ancestor: Option<SyntaxNode> = None;
559 while let Some(next_ancestor) = ancestors.next() {
560 match next_ancestor.kind() {
561 SyntaxKind::SOURCE_FILE => {
564 SyntaxKind::ITEM_LIST => {
565 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
571 last_ancestor = Some(next_ancestor);
573 last_ancestor.map(GeneratedFunctionTarget::BehindItem)
576 fn next_space_for_fn_in_module(
577 db: &dyn hir::db::AstDatabase,
578 module_source: &hir::InFile<hir::ModuleSource>,
579 ) -> Option<(FileId, GeneratedFunctionTarget)> {
580 let file = module_source.file_id.original_file(db);
581 let assist_item = match &module_source.value {
582 hir::ModuleSource::SourceFile(it) => {
583 if let Some(last_item) = it.items().last() {
584 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
586 GeneratedFunctionTarget::BehindItem(it.syntax().clone())
589 hir::ModuleSource::Module(it) => {
590 if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
591 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
593 GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone())
596 hir::ModuleSource::BlockExpr(it) => {
597 if let Some(last_item) =
598 it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
600 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
602 GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone())
606 Some((file, assist_item))
609 fn next_space_for_fn_in_impl(impl_: &ast::Impl) -> Option<GeneratedFunctionTarget> {
610 if let Some(last_item) = impl_.assoc_item_list().and_then(|it| it.assoc_items().last()) {
611 Some(GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()))
613 Some(GeneratedFunctionTarget::InEmptyItemList(impl_.assoc_item_list()?.syntax().clone()))
617 fn module_is_descendant(module: &hir::Module, ans: &hir::Module, ctx: &AssistContext) -> bool {
621 for c in ans.children(ctx.sema.db) {
622 if module_is_descendant(module, &c, ctx) {
631 use crate::tests::{check_assist, check_assist_not_applicable};
636 fn add_function_with_no_args() {
657 fn add_function_from_method() {
658 // This ensures that the function is correctly generated
659 // in the next outer mod or file
684 fn add_function_directly_after_current_block() {
685 // The new fn should not be created at the end of the file or module
710 fn add_function_with_no_args_in_same_module() {
735 fn add_function_with_upper_camel_case_arg() {
750 fn bar(baz_baz: BazBaz) ${0:-> _} {
758 fn add_function_with_upper_camel_case_arg_as_cast() {
764 bar$0(&BazBaz as *const BazBaz);
770 bar(&BazBaz as *const BazBaz);
773 fn bar(baz_baz: *const BazBaz) ${0:-> _} {
781 fn add_function_with_function_call_arg() {
786 fn baz() -> Baz { todo!() }
793 fn baz() -> Baz { todo!() }
798 fn bar(baz: Baz) ${0:-> _} {
806 fn add_function_with_method_call_arg() {
812 fn foo(&self) -> Baz {
815 fn baz(&self) -> Baz {
823 fn foo(&self) -> Baz {
826 fn baz(&self) -> Baz {
831 fn bar(baz: Baz) -> Baz {
839 fn add_function_with_string_literal_arg() {
860 fn add_function_with_char_literal_arg() {
881 fn add_function_with_int_literal_arg() {
902 fn add_function_with_cast_int_literal_arg() {
923 fn name_of_cast_variable_is_used() {
924 // Ensures that the name of the cast type isn't used
925 // in the generated function signature.
948 fn add_function_with_variable_arg() {
971 fn add_function_with_impl_trait_arg() {
977 fn foo() -> impl Foo {
986 fn foo() -> impl Foo {
993 fn bar(foo: impl Foo) {
1006 fn baz() -> Baz { todo!() }
1014 fn baz() -> Baz { todo!() }
1028 fn add_function_with_qualified_path_arg() {
1034 pub fn baz() -> Bof { Bof }
1043 pub fn baz() -> Bof { Bof }
1049 fn bar(baz: Baz::Bof) {
1057 fn add_function_with_generic_arg() {
1058 // FIXME: This is wrong, generated `bar` should include generic parameter.
1079 fn add_function_with_fn_arg() {
1080 // FIXME: The argument in `bar` is wrong.
1086 fn new() -> Self { Baz }
1095 fn new() -> Self { Baz }
1101 fn bar(new: fn) ${0:-> _} {
1109 fn add_function_with_closure_arg() {
1110 // FIXME: The argument in `bar` is wrong.
1115 let closure = |x: i64| x - 1;
1121 let closure = |x: i64| x - 1;
1125 fn bar(closure: _) {
1133 fn unresolveable_types_default_to_placeholder() {
1154 fn arg_names_dont_overlap() {
1159 fn baz() -> Baz { Baz }
1166 fn baz() -> Baz { Baz }
1171 fn bar(baz_1: Baz, baz_2: Baz) {
1179 fn arg_name_counters_start_at_1_per_name() {
1184 fn baz() -> Baz { Baz }
1186 $0bar(baz(), baz(), "foo", "bar")
1191 fn baz() -> Baz { Baz }
1193 bar(baz(), baz(), "foo", "bar")
1196 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) {
1204 fn add_function_in_module() {
1216 pub(crate) fn my_fn() {
1229 fn qualified_path_uses_correct_scope() {
1252 fn baz(foo: foo::Foo) {
1260 fn add_function_in_module_containing_other_items() {
1265 fn something_else() {}
1274 fn something_else() {}
1276 pub(crate) fn my_fn() {
1289 fn add_function_in_nested_module() {
1304 pub(crate) fn my_fn() {
1318 fn add_function_in_another_file() {
1333 pub(crate) fn bar() {
1340 fn add_function_with_return_type() {
1345 let x: u32 = foo$0();
1361 fn add_function_not_applicable_if_function_already_exists() {
1362 check_assist_not_applicable(
1375 fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1376 check_assist_not_applicable(
1377 // bar is resolved, but baz isn't.
1378 // The assist is only active if the cursor is on an unresolved path,
1379 // but the assist should only be offered if the path is a function call.
1392 fn create_method_with_no_args() {
1410 fn bar(&self) ${0:-> _} {
1419 fn create_function_with_async() {
1432 async fn bar(arg: i32) ${0:-> _} {
1440 fn create_method() {
1445 fn foo() {S.bar$0();}
1453 fn bar(&self) ${0:-> _} {
1462 fn create_method_within_an_impl() {
1467 fn foo() {S.bar$0();}
1475 fn bar(&self) ${0:-> _} {
1485 fn create_method_from_different_module() {
1492 fn foo() {s::S.bar$0();}
1500 pub(crate) fn bar(&self) ${0:-> _} {
1505 fn foo() {s::S.bar();}
1511 fn create_method_from_descendant_module() {
1533 fn bar(&self) ${0:-> _} {
1543 fn create_method_with_cursor_anywhere_on_call_expresion() {
1548 fn foo() {$0S.bar();}
1556 fn bar(&self) ${0:-> _} {
1565 fn create_static_method() {
1570 fn foo() {S::bar$0();}
1574 fn foo() {S::bar();}
1578 fn bar() ${0:-> _} {
1587 fn create_static_method_within_an_impl() {
1592 fn foo() {S::bar$0();}
1598 fn foo() {S::bar();}
1600 fn bar() ${0:-> _} {
1610 fn create_static_method_from_different_module() {
1617 fn foo() {s::S::bar$0();}
1625 pub(crate) fn bar() ${0:-> _} {
1630 fn foo() {s::S::bar();}
1636 fn create_static_method_with_cursor_anywhere_on_call_expresion() {
1641 fn foo() {$0S::bar();}
1645 fn foo() {S::bar();}
1649 fn bar() ${0:-> _} {
1658 fn no_panic_on_invalid_global_path() {
1671 fn foo() ${0:-> _} {
1679 fn handle_tuple_indexing() {
1694 fn foo(arg0: ()) ${0:-> _} {
1702 fn add_function_with_const_arg() {
1706 const VALUE: usize = 0;
1712 const VALUE: usize = 0;
1717 fn foo(value: usize) ${0:-> _} {
1725 fn add_function_with_static_arg() {
1729 static VALUE: usize = 0;
1735 static VALUE: usize = 0;
1740 fn foo(value: usize) ${0:-> _} {
1748 fn add_function_with_static_mut_arg() {
1752 static mut VALUE: usize = 0;
1758 static mut VALUE: usize = 0;
1763 fn foo(value: usize) ${0:-> _} {