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)?;
74 let path = path_expr.path()?;
75 if ctx.sema.resolve_path(&path).is_some() {
76 // The function call already resolves, no need to add a function
80 let target_module = match path.qualifier() {
81 Some(qualifier) => match ctx.sema.resolve_path(&qualifier) {
82 Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => Some(module),
88 let (target, file, insert_offset) = get_fn_target(ctx, &target_module, call.clone())?;
89 let function_builder = FunctionBuilder::from_call(ctx, &call, &path, target_module, target)?;
90 let target = call.syntax().text_range();
91 let label = format!("Generate {} function", function_builder.fn_name.clone());
92 add_func_to_accumulator(acc, ctx, target, function_builder, insert_offset, file, None, label)
95 fn gen_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
96 let call: ast::MethodCallExpr = ctx.find_node_at_offset()?;
97 let fn_name = call.name_ref()?;
98 let adt = ctx.sema.type_of_expr(&call.receiver()?)?.original().strip_references().as_adt()?;
100 let current_module = current_module(call.syntax(), ctx)?;
101 let target_module = adt.module(ctx.sema.db);
103 if current_module.krate() != target_module.krate() {
107 let range = adt.source(ctx.sema.db)?.syntax().original_file_range(ctx.sema.db);
108 let file = ctx.sema.parse(range.file_id);
110 ctx.sema.find_node_at_offset_with_macros(file.syntax(), range.range.start())?;
111 let impl_ = find_struct_impl(ctx, &adt_source, fn_name.text().as_str())?;
113 let (target, insert_offset) = get_method_target(ctx, &target_module, &impl_)?;
114 let function_builder =
115 FunctionBuilder::from_method_call(ctx, &call, &fn_name, target_module, target)?;
116 let text_range = call.syntax().text_range();
117 let adt_name = if impl_.is_none() { Some(adt.name(ctx.sema.db)) } else { None };
118 let label = format!("Generate {} method", function_builder.fn_name.clone());
119 add_func_to_accumulator(
131 fn add_func_to_accumulator(
134 text_range: TextRange,
135 function_builder: FunctionBuilder,
136 insert_offset: TextSize,
138 adt_name: Option<hir::Name>,
141 acc.add(AssistId("generate_function", AssistKind::Generate), label, text_range, |builder| {
142 let function_template = function_builder.render();
143 let mut func = function_template.to_string(ctx.config.snippet_cap);
144 if let Some(name) = adt_name {
145 func = format!("\nimpl {} {{\n{}\n}}", name, func);
147 builder.edit_file(file);
148 match ctx.config.snippet_cap {
149 Some(cap) => builder.insert_snippet(cap, insert_offset, func),
150 None => builder.insert(insert_offset, func),
155 fn current_module(current_node: &SyntaxNode, ctx: &AssistContext) -> Option<Module> {
156 ctx.sema.scope(current_node).module()
159 struct FunctionTemplate {
162 ret_type: Option<ast::RetType>,
163 should_focus_return_type: bool,
165 tail_expr: ast::Expr,
168 impl FunctionTemplate {
169 fn to_string(&self, cap: Option<SnippetCap>) -> String {
172 let cursor = if self.should_focus_return_type {
173 // Focus the return type if there is one
174 if let Some(ref ret_type) = self.ret_type {
177 self.tail_expr.syntax()
180 self.tail_expr.syntax()
182 render_snippet(cap, self.fn_def.syntax(), Cursor::Replace(cursor))
184 None => self.fn_def.to_string(),
187 format!("{}{}{}", self.leading_ws, f, self.trailing_ws)
191 struct FunctionBuilder {
192 target: GeneratedFunctionTarget,
194 type_params: Option<ast::GenericParamList>,
195 params: ast::ParamList,
196 ret_type: Option<ast::RetType>,
197 should_focus_return_type: bool,
202 impl FunctionBuilder {
203 /// Prepares a generated function that matches `call`.
204 /// The function is generated in `target_module` or next to `call`
207 call: &ast::CallExpr,
209 target_module: Option<hir::Module>,
210 target: GeneratedFunctionTarget,
212 let needs_pub = target_module.is_some();
213 let target_module = target_module.or_else(|| current_module(target.syntax(), ctx))?;
214 let fn_name = fn_name(path)?;
215 let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Func(call.clone()))?;
217 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
218 let is_async = await_expr.is_some();
220 let (ret_type, should_focus_return_type) =
221 make_return_type(ctx, &ast::Expr::CallExpr(call.clone()), target_module);
229 should_focus_return_type,
237 call: &ast::MethodCallExpr,
239 target_module: Module,
240 target: GeneratedFunctionTarget,
243 !module_is_descendant(¤t_module(call.syntax(), ctx)?, &target_module, ctx);
244 let fn_name = make::name(&name.text());
245 let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Method(call.clone()))?;
247 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
248 let is_async = await_expr.is_some();
250 let (ret_type, should_focus_return_type) =
251 make_return_type(ctx, &ast::Expr::MethodCallExpr(call.clone()), target_module);
259 should_focus_return_type,
265 fn render(self) -> FunctionTemplate {
266 let placeholder_expr = make::ext::expr_todo();
267 let fn_body = make::block_expr(vec![], Some(placeholder_expr));
268 let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None };
269 let mut fn_def = make::fn_(
282 GeneratedFunctionTarget::BehindItem(it) => {
283 let indent = IndentLevel::from_node(&it);
284 leading_ws = format!("\n\n{}", indent);
285 fn_def = fn_def.indent(indent);
286 trailing_ws = String::new();
288 GeneratedFunctionTarget::InEmptyItemList(it) => {
289 let indent = IndentLevel::from_node(&it);
290 leading_ws = format!("\n{}", indent + 1);
291 fn_def = fn_def.indent(indent + 1);
292 trailing_ws = format!("\n{}", indent);
298 ret_type: fn_def.ret_type(),
299 // PANIC: we guarantee we always create a function body with a tail expr
300 tail_expr: fn_def.body().unwrap().tail_expr().unwrap(),
301 should_focus_return_type: self.should_focus_return_type,
308 /// Makes an optional return type along with whether the return type should be focused by the cursor.
309 /// If we cannot infer what the return type should be, we create unit as a placeholder.
311 /// The rule for whether we focus a return type or not (and thus focus the function body),
312 /// is rather simple:
313 /// * If we could *not* infer what the return type should be, focus it (so the user can fill-in
314 /// the correct return type).
315 /// * If we could infer the return type, don't focus it (and thus focus the function body) so the
316 /// user can change the `todo!` function body.
320 target_module: Module,
321 ) -> (Option<ast::RetType>, bool) {
322 let (ret_ty, should_focus_return_type) = {
323 match ctx.sema.type_of_expr(call).map(TypeInfo::original) {
324 Some(ty) if ty.is_unknown() => (Some(make::ty_unit()), true),
325 None => (Some(make::ty_unit()), true),
326 Some(ty) if ty.is_unit() => (None, false),
328 let rendered = ty.display_source_code(ctx.db(), target_module.into());
330 Ok(rendered) => (Some(make::ty(&rendered)), false),
331 Err(_) => (Some(make::ty_unit()), true),
336 let ret_type = ret_ty.map(|rt| make::ret_type(rt));
337 (ret_type, should_focus_return_type)
342 target_module: &Option<Module>,
344 ) -> Option<(GeneratedFunctionTarget, FileId, TextSize)> {
345 let mut file = ctx.frange.file_id;
346 let target = match target_module {
347 Some(target_module) => {
348 let module_source = target_module.definition_source(ctx.db());
349 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?;
353 None => next_space_for_fn_after_call_site(FuncExpr::Func(call.clone()))?,
355 Some((target.clone(), file, get_insert_offset(&target)))
358 fn get_method_target(
360 target_module: &Module,
361 impl_: &Option<ast::Impl>,
362 ) -> Option<(GeneratedFunctionTarget, TextSize)> {
363 let target = match impl_ {
364 Some(impl_) => next_space_for_fn_in_impl(&impl_)?,
366 next_space_for_fn_in_module(ctx.sema.db, &target_module.definition_source(ctx.sema.db))?
370 Some((target.clone(), get_insert_offset(&target)))
373 fn get_insert_offset(target: &GeneratedFunctionTarget) -> TextSize {
375 GeneratedFunctionTarget::BehindItem(it) => it.text_range().end(),
376 GeneratedFunctionTarget::InEmptyItemList(it) => it.text_range().start() + TextSize::of('{'),
381 enum GeneratedFunctionTarget {
382 BehindItem(SyntaxNode),
383 InEmptyItemList(SyntaxNode),
386 impl GeneratedFunctionTarget {
387 fn syntax(&self) -> &SyntaxNode {
389 GeneratedFunctionTarget::BehindItem(it) => it,
390 GeneratedFunctionTarget::InEmptyItemList(it) => it,
395 fn fn_name(call: &ast::Path) -> Option<ast::Name> {
396 let name = call.segment()?.syntax().to_string();
397 Some(make::name(&name))
400 /// Computes the type variables and arguments required for the generated function
403 target_module: hir::Module,
405 ) -> Option<(Option<ast::GenericParamList>, ast::ParamList)> {
406 let mut arg_names = Vec::new();
407 let mut arg_types = Vec::new();
408 for arg in call.arg_list()?.args() {
409 arg_names.push(match fn_arg_name(&arg) {
411 None => String::from("arg"),
413 arg_types.push(match fn_arg_type(ctx, target_module, &arg) {
415 if ty.len() > 0 && ty.starts_with('&') {
416 if let Some((new_ty, _)) = useless_type_special_case("", &ty[1..].to_owned()) {
425 None => String::from("()"),
428 deduplicate_arg_names(&mut arg_names);
429 let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| {
430 make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty))
437 FuncExpr::Func(_) => None,
438 FuncExpr::Method(_) => Some(make::self_param()),
445 /// Makes duplicate argument names unique by appending incrementing numbers.
448 /// let mut names: Vec<String> =
449 /// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
450 /// deduplicate_arg_names(&mut names);
451 /// let expected: Vec<String> =
452 /// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
453 /// assert_eq!(names, expected);
455 fn deduplicate_arg_names(arg_names: &mut Vec<String>) {
456 let arg_name_counts = arg_names.iter().fold(FxHashMap::default(), |mut m, name| {
457 *m.entry(name).or_insert(0) += 1;
460 let duplicate_arg_names: FxHashSet<String> = arg_name_counts
462 .filter(|(_, count)| *count >= 2)
463 .map(|(name, _)| name.clone())
466 let mut counter_per_name = FxHashMap::default();
467 for arg_name in arg_names.iter_mut() {
468 if duplicate_arg_names.contains(arg_name) {
469 let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
471 arg_name.push_str(&counter.to_string());
477 fn fn_arg_name(fn_arg: &ast::Expr) -> Option<String> {
479 ast::Expr::CastExpr(cast_expr) => fn_arg_name(&cast_expr.expr()?),
484 .filter(|d| ast::NameRef::can_cast(d.kind()))
487 Some(to_lower_snake_case(&s))
494 target_module: hir::Module,
496 ) -> Option<String> {
497 let ty = ctx.sema.type_of_expr(fn_arg)?.adjusted();
502 if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) {
509 /// Returns the position inside the current mod or file
510 /// directly after the current block
511 /// We want to write the generated function directly after
512 /// fns, impls or macro calls, but inside mods
513 fn next_space_for_fn_after_call_site(expr: FuncExpr) -> Option<GeneratedFunctionTarget> {
514 let mut ancestors = expr.syntax().ancestors().peekable();
515 let mut last_ancestor: Option<SyntaxNode> = None;
516 while let Some(next_ancestor) = ancestors.next() {
517 match next_ancestor.kind() {
518 SyntaxKind::SOURCE_FILE => {
521 SyntaxKind::ITEM_LIST => {
522 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
528 last_ancestor = Some(next_ancestor);
530 last_ancestor.map(GeneratedFunctionTarget::BehindItem)
533 fn next_space_for_fn_in_module(
534 db: &dyn hir::db::AstDatabase,
535 module_source: &hir::InFile<hir::ModuleSource>,
536 ) -> Option<(FileId, GeneratedFunctionTarget)> {
537 let file = module_source.file_id.original_file(db);
538 let assist_item = match &module_source.value {
539 hir::ModuleSource::SourceFile(it) => {
540 if let Some(last_item) = it.items().last() {
541 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
543 GeneratedFunctionTarget::BehindItem(it.syntax().clone())
546 hir::ModuleSource::Module(it) => {
547 if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
548 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
550 GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone())
553 hir::ModuleSource::BlockExpr(it) => {
554 if let Some(last_item) =
555 it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
557 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
559 GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone())
563 Some((file, assist_item))
566 fn next_space_for_fn_in_impl(impl_: &ast::Impl) -> Option<GeneratedFunctionTarget> {
567 if let Some(last_item) = impl_.assoc_item_list().and_then(|it| it.assoc_items().last()) {
568 Some(GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()))
570 Some(GeneratedFunctionTarget::InEmptyItemList(impl_.assoc_item_list()?.syntax().clone()))
574 fn module_is_descendant(module: &hir::Module, ans: &hir::Module, ctx: &AssistContext) -> bool {
578 for c in ans.children(ctx.sema.db) {
579 if module_is_descendant(module, &c, ctx) {
588 use crate::tests::{check_assist, check_assist_not_applicable};
593 fn add_function_with_no_args() {
606 fn bar() ${0:-> ()} {
614 fn add_function_from_method() {
615 // This ensures that the function is correctly generated
616 // in the next outer mod or file
633 fn bar() ${0:-> ()} {
641 fn add_function_directly_after_current_block() {
642 // The new fn should not be created at the end of the file or module
657 fn bar() ${0:-> ()} {
667 fn add_function_with_no_args_in_same_module() {
683 fn bar() ${0:-> ()} {
692 fn add_function_with_upper_camel_case_arg() {
707 fn bar(baz_baz: BazBaz) ${0:-> ()} {
715 fn add_function_with_upper_camel_case_arg_as_cast() {
721 bar$0(&BazBaz as *const BazBaz);
727 bar(&BazBaz as *const BazBaz);
730 fn bar(baz_baz: *const BazBaz) ${0:-> ()} {
738 fn add_function_with_function_call_arg() {
743 fn baz() -> Baz { todo!() }
750 fn baz() -> Baz { todo!() }
755 fn bar(baz: Baz) ${0:-> ()} {
763 fn add_function_with_method_call_arg() {
769 fn foo(&self) -> Baz {
772 fn baz(&self) -> Baz {
780 fn foo(&self) -> Baz {
783 fn baz(&self) -> Baz {
788 fn bar(baz: Baz) -> Baz {
796 fn add_function_with_string_literal_arg() {
817 fn add_function_with_char_literal_arg() {
838 fn add_function_with_int_literal_arg() {
859 fn add_function_with_cast_int_literal_arg() {
880 fn name_of_cast_variable_is_used() {
881 // Ensures that the name of the cast type isn't used
882 // in the generated function signature.
905 fn add_function_with_variable_arg() {
928 fn add_function_with_impl_trait_arg() {
934 fn foo() -> impl Foo {
943 fn foo() -> impl Foo {
950 fn bar(foo: impl Foo) {
963 fn baz() -> Baz { todo!() }
971 fn baz() -> Baz { todo!() }
985 fn add_function_with_qualified_path_arg() {
991 pub fn baz() -> Bof { Bof }
1000 pub fn baz() -> Bof { Bof }
1006 fn bar(baz: Baz::Bof) {
1014 fn add_function_with_generic_arg() {
1015 // FIXME: This is wrong, generated `bar` should include generic parameter.
1036 fn add_function_with_fn_arg() {
1037 // FIXME: The argument in `bar` is wrong.
1043 fn new() -> Self { Baz }
1052 fn new() -> Self { Baz }
1058 fn bar(new: fn) ${0:-> ()} {
1066 fn add_function_with_closure_arg() {
1067 // FIXME: The argument in `bar` is wrong.
1072 let closure = |x: i64| x - 1;
1078 let closure = |x: i64| x - 1;
1082 fn bar(closure: ()) {
1090 fn unresolveable_types_default_to_unit() {
1111 fn arg_names_dont_overlap() {
1116 fn baz() -> Baz { Baz }
1123 fn baz() -> Baz { Baz }
1128 fn bar(baz_1: Baz, baz_2: Baz) {
1136 fn arg_name_counters_start_at_1_per_name() {
1141 fn baz() -> Baz { Baz }
1143 $0bar(baz(), baz(), "foo", "bar")
1148 fn baz() -> Baz { Baz }
1150 bar(baz(), baz(), "foo", "bar")
1153 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) {
1161 fn add_function_in_module() {
1173 pub(crate) fn my_fn() {
1186 fn qualified_path_uses_correct_scope() {
1209 fn baz(foo: foo::Foo) {
1217 fn add_function_in_module_containing_other_items() {
1222 fn something_else() {}
1231 fn something_else() {}
1233 pub(crate) fn my_fn() {
1246 fn add_function_in_nested_module() {
1261 pub(crate) fn my_fn() {
1275 fn add_function_in_another_file() {
1290 pub(crate) fn bar() {
1297 fn add_function_with_return_type() {
1302 let x: u32 = foo$0();
1318 fn add_function_not_applicable_if_function_already_exists() {
1319 check_assist_not_applicable(
1332 fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1333 check_assist_not_applicable(
1334 // bar is resolved, but baz isn't.
1335 // The assist is only active if the cursor is on an unresolved path,
1336 // but the assist should only be offered if the path is a function call.
1349 fn create_method_with_no_args() {
1367 fn bar(&self) ${0:-> ()} {
1376 fn create_function_with_async() {
1389 async fn bar(arg: i32) ${0:-> ()} {
1397 fn create_method() {
1402 fn foo() {S.bar$0();}
1410 fn bar(&self) ${0:-> ()} {
1419 fn create_method_within_an_impl() {
1424 fn foo() {S.bar$0();}
1432 fn bar(&self) ${0:-> ()} {
1442 fn create_method_from_different_module() {
1449 fn foo() {s::S.bar$0();}
1457 pub(crate) fn bar(&self) ${0:-> ()} {
1462 fn foo() {s::S.bar();}
1468 fn create_method_from_descendant_module() {
1490 fn bar(&self) ${0:-> ()} {
1500 fn create_method_with_cursor_anywhere_on_call_expresion() {
1505 fn foo() {$0S.bar();}
1513 fn bar(&self) ${0:-> ()} {