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, AstNode, CallExpr, HasArgList, HasModuleItem,
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 ty.display_source_code(ctx.db(), target_module.into()).ok()
548 /// Returns the position inside the current mod or file
549 /// directly after the current block
550 /// We want to write the generated function directly after
551 /// fns, impls or macro calls, but inside mods
552 fn next_space_for_fn_after_call_site(expr: FuncExpr) -> Option<GeneratedFunctionTarget> {
553 let mut ancestors = expr.syntax().ancestors().peekable();
554 let mut last_ancestor: Option<SyntaxNode> = None;
555 while let Some(next_ancestor) = ancestors.next() {
556 match next_ancestor.kind() {
557 SyntaxKind::SOURCE_FILE => {
560 SyntaxKind::ITEM_LIST => {
561 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
567 last_ancestor = Some(next_ancestor);
569 last_ancestor.map(GeneratedFunctionTarget::BehindItem)
572 fn next_space_for_fn_in_module(
573 db: &dyn hir::db::AstDatabase,
574 module_source: &hir::InFile<hir::ModuleSource>,
575 ) -> Option<(FileId, GeneratedFunctionTarget)> {
576 let file = module_source.file_id.original_file(db);
577 let assist_item = match &module_source.value {
578 hir::ModuleSource::SourceFile(it) => {
579 if let Some(last_item) = it.items().last() {
580 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
582 GeneratedFunctionTarget::BehindItem(it.syntax().clone())
585 hir::ModuleSource::Module(it) => {
586 if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
587 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
589 GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone())
592 hir::ModuleSource::BlockExpr(it) => {
593 if let Some(last_item) =
594 it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
596 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
598 GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone())
602 Some((file, assist_item))
605 fn next_space_for_fn_in_impl(impl_: &ast::Impl) -> Option<GeneratedFunctionTarget> {
606 if let Some(last_item) = impl_.assoc_item_list().and_then(|it| it.assoc_items().last()) {
607 Some(GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()))
609 Some(GeneratedFunctionTarget::InEmptyItemList(impl_.assoc_item_list()?.syntax().clone()))
613 fn module_is_descendant(module: &hir::Module, ans: &hir::Module, ctx: &AssistContext) -> bool {
617 for c in ans.children(ctx.sema.db) {
618 if module_is_descendant(module, &c, ctx) {
627 use crate::tests::{check_assist, check_assist_not_applicable};
632 fn add_function_with_no_args() {
653 fn add_function_from_method() {
654 // This ensures that the function is correctly generated
655 // in the next outer mod or file
680 fn add_function_directly_after_current_block() {
681 // The new fn should not be created at the end of the file or module
706 fn add_function_with_no_args_in_same_module() {
731 fn add_function_with_upper_camel_case_arg() {
746 fn bar(baz_baz: BazBaz) ${0:-> _} {
754 fn add_function_with_upper_camel_case_arg_as_cast() {
760 bar$0(&BazBaz as *const BazBaz);
766 bar(&BazBaz as *const BazBaz);
769 fn bar(baz_baz: *const BazBaz) ${0:-> _} {
777 fn add_function_with_function_call_arg() {
782 fn baz() -> Baz { todo!() }
789 fn baz() -> Baz { todo!() }
794 fn bar(baz: Baz) ${0:-> _} {
802 fn add_function_with_method_call_arg() {
808 fn foo(&self) -> Baz {
811 fn baz(&self) -> Baz {
819 fn foo(&self) -> Baz {
822 fn baz(&self) -> Baz {
827 fn bar(baz: Baz) -> Baz {
835 fn add_function_with_string_literal_arg() {
856 fn add_function_with_char_literal_arg() {
877 fn add_function_with_int_literal_arg() {
898 fn add_function_with_cast_int_literal_arg() {
919 fn name_of_cast_variable_is_used() {
920 // Ensures that the name of the cast type isn't used
921 // in the generated function signature.
944 fn add_function_with_variable_arg() {
967 fn add_function_with_impl_trait_arg() {
973 fn foo() -> impl Foo {
982 fn foo() -> impl Foo {
989 fn bar(foo: impl Foo) {
1002 fn baz() -> Baz { todo!() }
1010 fn baz() -> Baz { todo!() }
1024 fn add_function_with_qualified_path_arg() {
1030 pub fn baz() -> Bof { Bof }
1039 pub fn baz() -> Bof { Bof }
1045 fn bar(baz: Baz::Bof) {
1053 fn add_function_with_generic_arg() {
1054 // FIXME: This is wrong, generated `bar` should include generic parameter.
1075 fn add_function_with_fn_arg() {
1076 // FIXME: The argument in `bar` is wrong.
1082 fn new() -> Self { Baz }
1091 fn new() -> Self { Baz }
1097 fn bar(new: fn) ${0:-> _} {
1105 fn add_function_with_closure_arg() {
1106 // FIXME: The argument in `bar` is wrong.
1111 let closure = |x: i64| x - 1;
1117 let closure = |x: i64| x - 1;
1121 fn bar(closure: _) {
1129 fn unresolveable_types_default_to_placeholder() {
1150 fn arg_names_dont_overlap() {
1155 fn baz() -> Baz { Baz }
1162 fn baz() -> Baz { Baz }
1167 fn bar(baz_1: Baz, baz_2: Baz) {
1175 fn arg_name_counters_start_at_1_per_name() {
1180 fn baz() -> Baz { Baz }
1182 $0bar(baz(), baz(), "foo", "bar")
1187 fn baz() -> Baz { Baz }
1189 bar(baz(), baz(), "foo", "bar")
1192 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) {
1200 fn add_function_in_module() {
1212 pub(crate) fn my_fn() {
1225 fn qualified_path_uses_correct_scope() {
1248 fn baz(foo: foo::Foo) {
1256 fn add_function_in_module_containing_other_items() {
1261 fn something_else() {}
1270 fn something_else() {}
1272 pub(crate) fn my_fn() {
1285 fn add_function_in_nested_module() {
1300 pub(crate) fn my_fn() {
1314 fn add_function_in_another_file() {
1329 pub(crate) fn bar() {
1336 fn add_function_with_return_type() {
1341 let x: u32 = foo$0();
1357 fn add_function_not_applicable_if_function_already_exists() {
1358 check_assist_not_applicable(
1371 fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1372 check_assist_not_applicable(
1373 // bar is resolved, but baz isn't.
1374 // The assist is only active if the cursor is on an unresolved path,
1375 // but the assist should only be offered if the path is a function call.
1388 fn create_method_with_no_args() {
1406 fn bar(&self) ${0:-> _} {
1415 fn create_function_with_async() {
1428 async fn bar(arg: i32) ${0:-> _} {
1436 fn create_method() {
1441 fn foo() {S.bar$0();}
1449 fn bar(&self) ${0:-> _} {
1458 fn create_method_within_an_impl() {
1463 fn foo() {S.bar$0();}
1471 fn bar(&self) ${0:-> _} {
1481 fn create_method_from_different_module() {
1488 fn foo() {s::S.bar$0();}
1496 pub(crate) fn bar(&self) ${0:-> _} {
1501 fn foo() {s::S.bar();}
1507 fn create_method_from_descendant_module() {
1529 fn bar(&self) ${0:-> _} {
1539 fn create_method_with_cursor_anywhere_on_call_expresion() {
1544 fn foo() {$0S.bar();}
1552 fn bar(&self) ${0:-> _} {
1561 fn create_static_method() {
1566 fn foo() {S::bar$0();}
1570 fn foo() {S::bar();}
1574 fn bar() ${0:-> _} {
1583 fn create_static_method_within_an_impl() {
1588 fn foo() {S::bar$0();}
1594 fn foo() {S::bar();}
1596 fn bar() ${0:-> _} {
1606 fn create_static_method_from_different_module() {
1613 fn foo() {s::S::bar$0();}
1621 pub(crate) fn bar() ${0:-> _} {
1626 fn foo() {s::S::bar();}
1632 fn create_static_method_with_cursor_anywhere_on_call_expresion() {
1637 fn foo() {$0S::bar();}
1641 fn foo() {S::bar();}
1645 fn bar() ${0:-> _} {
1654 fn no_panic_on_invalid_global_path() {
1667 fn foo() ${0:-> _} {
1675 fn handle_tuple_indexing() {
1690 fn foo(arg0: ()) ${0:-> _} {
1698 fn add_function_with_const_arg() {
1702 const VALUE: usize = 0;
1708 const VALUE: usize = 0;
1713 fn foo(value: usize) ${0:-> _} {
1721 fn add_function_with_static_arg() {
1725 static VALUE: usize = 0;
1731 static VALUE: usize = 0;
1736 fn foo(value: usize) ${0:-> _} {
1744 fn add_function_with_static_mut_arg() {
1748 static mut VALUE: usize = 0;
1754 static mut VALUE: usize = 0;
1759 fn foo(value: usize) ${0:-> _} {