]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/handlers/generate_function.rs
One assist for function and method generation
[rust.git] / crates / ide_assists / src / handlers / generate_function.rs
1 use hir::{HasSource, HirDisplay, InFile, Module, TypeInfo};
2 use ide_db::{base_db::FileId, helpers::SnippetCap};
3 use rustc_hash::{FxHashMap, FxHashSet};
4 use stdx::to_lower_snake_case;
5 use syntax::{
6     ast::{
7         self,
8         edit::{AstNodeEdit, IndentLevel},
9         make, ArgList, ArgListOwner, AstNode, ModuleItemOwner,
10     },
11     SyntaxKind, SyntaxNode, TextSize,
12 };
13
14 use crate::{
15     utils::useless_type_special_case,
16     utils::{find_struct_impl, render_snippet, Cursor},
17     AssistContext, AssistId, AssistKind, Assists,
18 };
19
20 enum FuncExpr {
21     Func(ast::CallExpr),
22     Method(ast::MethodCallExpr),
23 }
24
25 impl FuncExpr {
26     fn arg_list(&self) -> Option<ArgList> {
27         match self {
28             FuncExpr::Func(fn_call) => fn_call.arg_list(),
29             FuncExpr::Method(m_call) => m_call.arg_list(),
30         }
31     }
32
33     fn syntax(&self) -> &SyntaxNode {
34         match self {
35             FuncExpr::Func(fn_call) => fn_call.syntax(),
36             FuncExpr::Method(m_call) => m_call.syntax(),
37         }
38     }
39 }
40
41 // Assist: generate_function
42 //
43 // Adds a stub function with a signature matching the function under the cursor.
44 //
45 // ```
46 // struct Baz;
47 // fn baz() -> Baz { Baz }
48 // fn foo() {
49 //     bar$0("", baz());
50 // }
51 //
52 // ```
53 // ->
54 // ```
55 // struct Baz;
56 // fn baz() -> Baz { Baz }
57 // fn foo() {
58 //     bar("", baz());
59 // }
60 //
61 // fn bar(arg: &str, baz: Baz) ${0:-> ()} {
62 //     todo!()
63 // }
64 //
65 // ```
66 pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
67     let path_expr: ast::PathExpr = ctx.find_node_at_offset()?;
68     let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?;
69
70     let path = path_expr.path()?;
71     if ctx.sema.resolve_path(&path).is_some() {
72         // The function call already resolves, no need to add a function
73         return None;
74     }
75
76     let target_module = match path.qualifier() {
77         Some(qualifier) => match ctx.sema.resolve_path(&qualifier) {
78             Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => Some(module),
79             _ => return None,
80         },
81         None => None,
82     };
83
84     let function_builder = FunctionBuilder::from_call(ctx, &call, &path, target_module)?;
85     let target = call.syntax().text_range();
86
87     acc.add(
88         AssistId("generate_function", AssistKind::Generate),
89         format!("Generate `{}` function", function_builder.fn_name),
90         target,
91         |builder| {
92             let function_template = function_builder.render();
93             builder.edit_file(function_template.file);
94             let new_fn = function_template.to_string(ctx.config.snippet_cap);
95             match ctx.config.snippet_cap {
96                 Some(cap) => builder.insert_snippet(cap, function_template.insert_offset, new_fn),
97                 None => builder.insert(function_template.insert_offset, new_fn),
98             }
99         },
100     )
101 }
102
103 pub(crate) fn generate_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
104     let fn_name: ast::NameRef = ctx.find_node_at_offset()?;
105     let call: ast::MethodCallExpr = ctx.find_node_at_offset()?;
106     let ty = ctx.sema.type_of_expr(&call.receiver()?)?.original().strip_references().as_adt()?;
107
108     let current_module =
109         ctx.sema.scope(ctx.find_node_at_offset::<ast::MethodCallExpr>()?.syntax()).module()?;
110     let target_module = ty.module(ctx.sema.db);
111
112     if current_module.krate() != target_module.krate() {
113         return None;
114     }
115
116     let (impl_, file) = match ty {
117         hir::Adt::Struct(strukt) => get_impl(strukt.source(ctx.sema.db)?.syntax(), &fn_name, ctx),
118         hir::Adt::Enum(en) => get_impl(en.source(ctx.sema.db)?.syntax(), &fn_name, ctx),
119         hir::Adt::Union(union) => get_impl(union.source(ctx.sema.db)?.syntax(), &fn_name, ctx),
120     }?;
121
122     let function_builder = FunctionBuilder::from_method_call(
123         ctx,
124         &call,
125         &fn_name,
126         &impl_,
127         file,
128         target_module,
129         current_module,
130     )?;
131     let target = call.syntax().text_range();
132
133     acc.add(
134         AssistId("generate_function", AssistKind::Generate),
135         format!("Generate `{}` function", function_builder.fn_name),
136         target,
137         |builder| {
138             let function_template = function_builder.render();
139             builder.edit_file(function_template.file);
140             let mut new_fn = function_template.to_string(ctx.config.snippet_cap);
141             if impl_.is_none() {
142                 new_fn = format!("\nimpl {} {{\n   {}\n}}", ty.name(ctx.sema.db), new_fn,);
143             }
144             match ctx.config.snippet_cap {
145                 Some(cap) => builder.insert_snippet(cap, function_template.insert_offset, new_fn),
146                 None => builder.insert(function_template.insert_offset, new_fn),
147             }
148         },
149     )
150 }
151
152 fn get_impl(
153     adt: InFile<&SyntaxNode>,
154     fn_name: &ast::NameRef,
155     ctx: &AssistContext,
156 ) -> Option<(Option<ast::Impl>, FileId)> {
157     let file = adt.file_id.original_file(ctx.sema.db);
158     let adt = adt.value;
159     let adt = ast::Adt::cast(adt.clone())?;
160     let r = find_struct_impl(ctx, &adt, fn_name.text().as_str())?;
161     Some((r, file))
162 }
163
164 struct FunctionTemplate {
165     insert_offset: TextSize,
166     leading_ws: String,
167     fn_def: ast::Fn,
168     ret_type: ast::RetType,
169     should_render_snippet: bool,
170     trailing_ws: String,
171     file: FileId,
172 }
173
174 impl FunctionTemplate {
175     fn to_string(&self, cap: Option<SnippetCap>) -> String {
176         let f = match (cap, self.should_render_snippet) {
177             (Some(cap), true) => {
178                 render_snippet(cap, self.fn_def.syntax(), Cursor::Replace(self.ret_type.syntax()))
179             }
180             _ => self.fn_def.to_string(),
181         };
182         format!("{}{}{}", self.leading_ws, f, self.trailing_ws)
183     }
184 }
185
186 struct FunctionBuilder {
187     target: GeneratedFunctionTarget,
188     fn_name: ast::Name,
189     type_params: Option<ast::GenericParamList>,
190     params: ast::ParamList,
191     ret_type: ast::RetType,
192     should_render_snippet: bool,
193     file: FileId,
194     needs_pub: bool,
195     is_async: bool,
196 }
197
198 impl FunctionBuilder {
199     /// Prepares a generated function that matches `call`.
200     /// The function is generated in `target_module` or next to `call`
201     fn from_call(
202         ctx: &AssistContext,
203         call: &ast::CallExpr,
204         path: &ast::Path,
205         target_module: Option<hir::Module>,
206     ) -> Option<Self> {
207         let mut file = ctx.frange.file_id;
208         let target = match &target_module {
209             Some(target_module) => {
210                 let module_source = target_module.definition_source(ctx.db());
211                 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?;
212                 file = in_file;
213                 target
214             }
215             None => next_space_for_fn_after_call_site(FuncExpr::Func(call.clone()))?,
216         };
217         let needs_pub = target_module.is_some();
218         let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?;
219         let fn_name = fn_name(path)?;
220         let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Func(call.clone()))?;
221
222         let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
223         let is_async = await_expr.is_some();
224
225         // should_render_snippet intends to express a rough level of confidence about
226         // the correctness of the return type.
227         //
228         // If we are able to infer some return type, and that return type is not unit, we
229         // don't want to render the snippet. The assumption here is in this situation the
230         // return type is just as likely to be correct as any other part of the generated
231         // function.
232         //
233         // In the case where the return type is inferred as unit it is likely that the
234         // user does in fact intend for this generated function to return some non unit
235         // type, but that the current state of their code doesn't allow that return type
236         // to be accurately inferred.
237         let (ret_ty, should_render_snippet) = {
238             match ctx.sema.type_of_expr(&ast::Expr::CallExpr(call.clone())).map(TypeInfo::original)
239             {
240                 Some(ty) if ty.is_unknown() || ty.is_unit() => (make::ty_unit(), true),
241                 Some(ty) => {
242                     let rendered = ty.display_source_code(ctx.db(), target_module.into());
243                     match rendered {
244                         Ok(rendered) => (make::ty(&rendered), false),
245                         Err(_) => (make::ty_unit(), true),
246                     }
247                 }
248                 None => (make::ty_unit(), true),
249             }
250         };
251         let ret_type = make::ret_type(ret_ty);
252
253         Some(Self {
254             target,
255             fn_name,
256             type_params,
257             params,
258             ret_type,
259             should_render_snippet,
260             file,
261             needs_pub,
262             is_async,
263         })
264     }
265
266     fn from_method_call(
267         ctx: &AssistContext,
268         call: &ast::MethodCallExpr,
269         name: &ast::NameRef,
270         impl_: &Option<ast::Impl>,
271         file: FileId,
272         target_module: Module,
273         current_module: Module,
274     ) -> Option<Self> {
275         // let mut file = ctx.frange.file_id;
276         // let target_module = ctx.sema.scope(call.syntax()).module()?;
277         let target = match impl_ {
278             Some(impl_) => next_space_for_fn_in_impl(&impl_)?,
279             None => {
280                 next_space_for_fn_in_module(
281                     ctx.sema.db,
282                     &target_module.definition_source(ctx.sema.db),
283                 )?
284                 .1
285             }
286         };
287         let needs_pub = !module_is_descendant(&current_module, &target_module, ctx);
288
289         let fn_name = make::name(&name.text());
290         let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Method(call.clone()))?;
291
292         let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
293         let is_async = await_expr.is_some();
294
295         // should_render_snippet intends to express a rough level of confidence about
296         // the correctness of the return type.
297         //
298         // If we are able to infer some return type, and that return type is not unit, we
299         // don't want to render the snippet. The assumption here is in this situation the
300         // return type is just as likely to be correct as any other part of the generated
301         // function.
302         //
303         // In the case where the return type is inferred as unit it is likely that the
304         // user does in fact intend for this generated function to return some non unit
305         // type, but that the current state of their code doesn't allow that return type
306         // to be accurately inferred.
307         let (ret_ty, should_render_snippet) = {
308             match ctx
309                 .sema
310                 .type_of_expr(&ast::Expr::MethodCallExpr(call.clone()))
311                 .map(TypeInfo::original)
312             {
313                 Some(ty) if ty.is_unknown() || ty.is_unit() => (make::ty_unit(), true),
314                 Some(ty) => {
315                     let rendered = ty.display_source_code(ctx.db(), target_module.into());
316                     match rendered {
317                         Ok(rendered) => (make::ty(&rendered), false),
318                         Err(_) => (make::ty_unit(), true),
319                     }
320                 }
321                 None => (make::ty_unit(), true),
322             }
323         };
324         let ret_type = make::ret_type(ret_ty);
325
326         Some(Self {
327             target,
328             fn_name,
329             type_params,
330             params,
331             ret_type,
332             should_render_snippet,
333             file,
334             needs_pub,
335             is_async,
336         })
337     }
338
339     fn render(self) -> FunctionTemplate {
340         let placeholder_expr = make::ext::expr_todo();
341         let fn_body = make::block_expr(vec![], Some(placeholder_expr));
342         let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None };
343         let mut fn_def = make::fn_(
344             visibility,
345             self.fn_name,
346             self.type_params,
347             self.params,
348             fn_body,
349             Some(self.ret_type),
350             self.is_async,
351         );
352         let leading_ws;
353         let trailing_ws;
354
355         let insert_offset = match self.target {
356             GeneratedFunctionTarget::BehindItem(it) => {
357                 let indent = IndentLevel::from_node(&it);
358                 leading_ws = format!("\n\n{}", indent);
359                 fn_def = fn_def.indent(indent);
360                 trailing_ws = String::new();
361                 it.text_range().end()
362             }
363             GeneratedFunctionTarget::InEmptyItemList(it) => {
364                 let indent = IndentLevel::from_node(&it);
365                 leading_ws = format!("\n{}", indent + 1);
366                 fn_def = fn_def.indent(indent + 1);
367                 trailing_ws = format!("\n{}", indent);
368                 it.text_range().start() + TextSize::of('{')
369             }
370         };
371
372         FunctionTemplate {
373             insert_offset,
374             leading_ws,
375             ret_type: fn_def.ret_type().unwrap(),
376             should_render_snippet: self.should_render_snippet,
377             fn_def,
378             trailing_ws,
379             file: self.file,
380         }
381     }
382 }
383
384 enum GeneratedFunctionTarget {
385     BehindItem(SyntaxNode),
386     InEmptyItemList(SyntaxNode),
387 }
388
389 impl GeneratedFunctionTarget {
390     fn syntax(&self) -> &SyntaxNode {
391         match self {
392             GeneratedFunctionTarget::BehindItem(it) => it,
393             GeneratedFunctionTarget::InEmptyItemList(it) => it,
394         }
395     }
396 }
397
398 fn fn_name(call: &ast::Path) -> Option<ast::Name> {
399     let name = call.segment()?.syntax().to_string();
400     Some(make::name(&name))
401 }
402
403 /// Computes the type variables and arguments required for the generated function
404 fn fn_args(
405     ctx: &AssistContext,
406     target_module: hir::Module,
407     call: FuncExpr,
408 ) -> Option<(Option<ast::GenericParamList>, ast::ParamList)> {
409     let mut arg_names = Vec::new();
410     let mut arg_types = Vec::new();
411     for arg in call.arg_list()?.args() {
412         arg_names.push(match fn_arg_name(&arg) {
413             Some(name) => name,
414             None => String::from("arg"),
415         });
416         arg_types.push(match fn_arg_type(ctx, target_module, &arg) {
417             Some(ty) => {
418                 if ty.len() > 0 && ty.starts_with('&') {
419                     if let Some((new_ty, _)) = useless_type_special_case("", &ty[1..].to_owned()) {
420                         new_ty
421                     } else {
422                         ty
423                     }
424                 } else {
425                     ty
426                 }
427             }
428             None => String::from("()"),
429         });
430     }
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))
434     });
435
436     Some((
437         None,
438         make::param_list(
439             match call {
440                 FuncExpr::Func(_) => None,
441                 FuncExpr::Method(_) => Some(make::self_param()),
442             },
443             params,
444         ),
445     ))
446 }
447
448 /// Makes duplicate argument names unique by appending incrementing numbers.
449 ///
450 /// ```
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);
457 /// ```
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;
461         m
462     });
463     let duplicate_arg_names: FxHashSet<String> = arg_name_counts
464         .into_iter()
465         .filter(|(_, count)| *count >= 2)
466         .map(|(name, _)| name.clone())
467         .collect();
468
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);
473             arg_name.push('_');
474             arg_name.push_str(&counter.to_string());
475             *counter += 1;
476         }
477     }
478 }
479
480 fn fn_arg_name(fn_arg: &ast::Expr) -> Option<String> {
481     match fn_arg {
482         ast::Expr::CastExpr(cast_expr) => fn_arg_name(&cast_expr.expr()?),
483         _ => {
484             let s = fn_arg
485                 .syntax()
486                 .descendants()
487                 .filter(|d| ast::NameRef::can_cast(d.kind()))
488                 .last()?
489                 .to_string();
490             Some(to_lower_snake_case(&s))
491         }
492     }
493 }
494
495 fn fn_arg_type(
496     ctx: &AssistContext,
497     target_module: hir::Module,
498     fn_arg: &ast::Expr,
499 ) -> Option<String> {
500     let ty = ctx.sema.type_of_expr(fn_arg)?.adjusted();
501     if ty.is_unknown() {
502         return None;
503     }
504
505     if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) {
506         Some(rendered)
507     } else {
508         None
509     }
510 }
511
512 /// Returns the position inside the current mod or file
513 /// directly after the current block
514 /// We want to write the generated function directly after
515 /// fns, impls or macro calls, but inside mods
516 fn next_space_for_fn_after_call_site(expr: FuncExpr) -> Option<GeneratedFunctionTarget> {
517     let mut ancestors = expr.syntax().ancestors().peekable();
518     let mut last_ancestor: Option<SyntaxNode> = None;
519     while let Some(next_ancestor) = ancestors.next() {
520         match next_ancestor.kind() {
521             SyntaxKind::SOURCE_FILE => {
522                 break;
523             }
524             SyntaxKind::ITEM_LIST => {
525                 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
526                     break;
527                 }
528             }
529             _ => {}
530         }
531         last_ancestor = Some(next_ancestor);
532     }
533     last_ancestor.map(GeneratedFunctionTarget::BehindItem)
534 }
535
536 fn next_space_for_fn_in_module(
537     db: &dyn hir::db::AstDatabase,
538     module_source: &hir::InFile<hir::ModuleSource>,
539 ) -> Option<(FileId, GeneratedFunctionTarget)> {
540     let file = module_source.file_id.original_file(db);
541     let assist_item = match &module_source.value {
542         hir::ModuleSource::SourceFile(it) => {
543             if let Some(last_item) = it.items().last() {
544                 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
545             } else {
546                 GeneratedFunctionTarget::BehindItem(it.syntax().clone())
547             }
548         }
549         hir::ModuleSource::Module(it) => {
550             if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
551                 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
552             } else {
553                 GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone())
554             }
555         }
556         hir::ModuleSource::BlockExpr(it) => {
557             if let Some(last_item) =
558                 it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
559             {
560                 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
561             } else {
562                 GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone())
563             }
564         }
565     };
566     Some((file, assist_item))
567 }
568
569 fn next_space_for_fn_in_impl(impl_: &ast::Impl) -> Option<GeneratedFunctionTarget> {
570     if let Some(last_item) = impl_.assoc_item_list().and_then(|it| it.assoc_items().last()) {
571         Some(GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()))
572     } else {
573         Some(GeneratedFunctionTarget::InEmptyItemList(impl_.assoc_item_list()?.syntax().clone()))
574     }
575 }
576
577 fn module_is_descendant(module: &hir::Module, ans: &hir::Module, ctx: &AssistContext) -> bool {
578     if module == ans {
579         return true;
580     }
581     for c in ans.children(ctx.sema.db) {
582         if module_is_descendant(module, &c, ctx) {
583             return true;
584         }
585     }
586     false
587 }
588
589 #[cfg(test)]
590 mod tests {
591     use crate::tests::{check_assist, check_assist_not_applicable};
592
593     use super::*;
594
595     #[test]
596     fn add_function_with_no_args() {
597         check_assist(
598             generate_function,
599             r"
600 fn foo() {
601     bar$0();
602 }
603 ",
604             r"
605 fn foo() {
606     bar();
607 }
608
609 fn bar() ${0:-> ()} {
610     todo!()
611 }
612 ",
613         )
614     }
615
616     #[test]
617     fn add_function_from_method() {
618         // This ensures that the function is correctly generated
619         // in the next outer mod or file
620         check_assist(
621             generate_function,
622             r"
623 impl Foo {
624     fn foo() {
625         bar$0();
626     }
627 }
628 ",
629             r"
630 impl Foo {
631     fn foo() {
632         bar();
633     }
634 }
635
636 fn bar() ${0:-> ()} {
637     todo!()
638 }
639 ",
640         )
641     }
642
643     #[test]
644     fn add_function_directly_after_current_block() {
645         // The new fn should not be created at the end of the file or module
646         check_assist(
647             generate_function,
648             r"
649 fn foo1() {
650     bar$0();
651 }
652
653 fn foo2() {}
654 ",
655             r"
656 fn foo1() {
657     bar();
658 }
659
660 fn bar() ${0:-> ()} {
661     todo!()
662 }
663
664 fn foo2() {}
665 ",
666         )
667     }
668
669     #[test]
670     fn add_function_with_no_args_in_same_module() {
671         check_assist(
672             generate_function,
673             r"
674 mod baz {
675     fn foo() {
676         bar$0();
677     }
678 }
679 ",
680             r"
681 mod baz {
682     fn foo() {
683         bar();
684     }
685
686     fn bar() ${0:-> ()} {
687         todo!()
688     }
689 }
690 ",
691         )
692     }
693
694     #[test]
695     fn add_function_with_upper_camel_case_arg() {
696         check_assist(
697             generate_function,
698             r"
699 struct BazBaz;
700 fn foo() {
701     bar$0(BazBaz);
702 }
703 ",
704             r"
705 struct BazBaz;
706 fn foo() {
707     bar(BazBaz);
708 }
709
710 fn bar(baz_baz: BazBaz) ${0:-> ()} {
711     todo!()
712 }
713 ",
714         );
715     }
716
717     #[test]
718     fn add_function_with_upper_camel_case_arg_as_cast() {
719         check_assist(
720             generate_function,
721             r"
722 struct BazBaz;
723 fn foo() {
724     bar$0(&BazBaz as *const BazBaz);
725 }
726 ",
727             r"
728 struct BazBaz;
729 fn foo() {
730     bar(&BazBaz as *const BazBaz);
731 }
732
733 fn bar(baz_baz: *const BazBaz) ${0:-> ()} {
734     todo!()
735 }
736 ",
737         );
738     }
739
740     #[test]
741     fn add_function_with_function_call_arg() {
742         check_assist(
743             generate_function,
744             r"
745 struct Baz;
746 fn baz() -> Baz { todo!() }
747 fn foo() {
748     bar$0(baz());
749 }
750 ",
751             r"
752 struct Baz;
753 fn baz() -> Baz { todo!() }
754 fn foo() {
755     bar(baz());
756 }
757
758 fn bar(baz: Baz) ${0:-> ()} {
759     todo!()
760 }
761 ",
762         );
763     }
764
765     #[test]
766     fn add_function_with_method_call_arg() {
767         check_assist(
768             generate_function,
769             r"
770 struct Baz;
771 impl Baz {
772     fn foo(&self) -> Baz {
773         ba$0r(self.baz())
774     }
775     fn baz(&self) -> Baz {
776         Baz
777     }
778 }
779 ",
780             r"
781 struct Baz;
782 impl Baz {
783     fn foo(&self) -> Baz {
784         bar(self.baz())
785     }
786     fn baz(&self) -> Baz {
787         Baz
788     }
789 }
790
791 fn bar(baz: Baz) -> Baz {
792     todo!()
793 }
794 ",
795         )
796     }
797
798     #[test]
799     fn add_function_with_string_literal_arg() {
800         check_assist(
801             generate_function,
802             r#"
803 fn foo() {
804     $0bar("bar")
805 }
806 "#,
807             r#"
808 fn foo() {
809     bar("bar")
810 }
811
812 fn bar(arg: &str) ${0:-> ()} {
813     todo!()
814 }
815 "#,
816         )
817     }
818
819     #[test]
820     fn add_function_with_char_literal_arg() {
821         check_assist(
822             generate_function,
823             r#"
824 fn foo() {
825     $0bar('x')
826 }
827 "#,
828             r#"
829 fn foo() {
830     bar('x')
831 }
832
833 fn bar(arg: char) ${0:-> ()} {
834     todo!()
835 }
836 "#,
837         )
838     }
839
840     #[test]
841     fn add_function_with_int_literal_arg() {
842         check_assist(
843             generate_function,
844             r"
845 fn foo() {
846     $0bar(42)
847 }
848 ",
849             r"
850 fn foo() {
851     bar(42)
852 }
853
854 fn bar(arg: i32) ${0:-> ()} {
855     todo!()
856 }
857 ",
858         )
859     }
860
861     #[test]
862     fn add_function_with_cast_int_literal_arg() {
863         check_assist(
864             generate_function,
865             r"
866 fn foo() {
867     $0bar(42 as u8)
868 }
869 ",
870             r"
871 fn foo() {
872     bar(42 as u8)
873 }
874
875 fn bar(arg: u8) ${0:-> ()} {
876     todo!()
877 }
878 ",
879         )
880     }
881
882     #[test]
883     fn name_of_cast_variable_is_used() {
884         // Ensures that the name of the cast type isn't used
885         // in the generated function signature.
886         check_assist(
887             generate_function,
888             r"
889 fn foo() {
890     let x = 42;
891     bar$0(x as u8)
892 }
893 ",
894             r"
895 fn foo() {
896     let x = 42;
897     bar(x as u8)
898 }
899
900 fn bar(x: u8) ${0:-> ()} {
901     todo!()
902 }
903 ",
904         )
905     }
906
907     #[test]
908     fn add_function_with_variable_arg() {
909         check_assist(
910             generate_function,
911             r"
912 fn foo() {
913     let worble = ();
914     $0bar(worble)
915 }
916 ",
917             r"
918 fn foo() {
919     let worble = ();
920     bar(worble)
921 }
922
923 fn bar(worble: ()) ${0:-> ()} {
924     todo!()
925 }
926 ",
927         )
928     }
929
930     #[test]
931     fn add_function_with_impl_trait_arg() {
932         check_assist(
933             generate_function,
934             r"
935 trait Foo {}
936 fn foo() -> impl Foo {
937     todo!()
938 }
939 fn baz() {
940     $0bar(foo())
941 }
942 ",
943             r"
944 trait Foo {}
945 fn foo() -> impl Foo {
946     todo!()
947 }
948 fn baz() {
949     bar(foo())
950 }
951
952 fn bar(foo: impl Foo) ${0:-> ()} {
953     todo!()
954 }
955 ",
956         )
957     }
958
959     #[test]
960     fn borrowed_arg() {
961         check_assist(
962             generate_function,
963             r"
964 struct Baz;
965 fn baz() -> Baz { todo!() }
966
967 fn foo() {
968     bar$0(&baz())
969 }
970 ",
971             r"
972 struct Baz;
973 fn baz() -> Baz { todo!() }
974
975 fn foo() {
976     bar(&baz())
977 }
978
979 fn bar(baz: &Baz) ${0:-> ()} {
980     todo!()
981 }
982 ",
983         )
984     }
985
986     #[test]
987     fn add_function_with_qualified_path_arg() {
988         check_assist(
989             generate_function,
990             r"
991 mod Baz {
992     pub struct Bof;
993     pub fn baz() -> Bof { Bof }
994 }
995 fn foo() {
996     $0bar(Baz::baz())
997 }
998 ",
999             r"
1000 mod Baz {
1001     pub struct Bof;
1002     pub fn baz() -> Bof { Bof }
1003 }
1004 fn foo() {
1005     bar(Baz::baz())
1006 }
1007
1008 fn bar(baz: Baz::Bof) ${0:-> ()} {
1009     todo!()
1010 }
1011 ",
1012         )
1013     }
1014
1015     #[test]
1016     fn add_function_with_generic_arg() {
1017         // FIXME: This is wrong, generated `bar` should include generic parameter.
1018         check_assist(
1019             generate_function,
1020             r"
1021 fn foo<T>(t: T) {
1022     $0bar(t)
1023 }
1024 ",
1025             r"
1026 fn foo<T>(t: T) {
1027     bar(t)
1028 }
1029
1030 fn bar(t: T) ${0:-> ()} {
1031     todo!()
1032 }
1033 ",
1034         )
1035     }
1036
1037     #[test]
1038     fn add_function_with_fn_arg() {
1039         // FIXME: The argument in `bar` is wrong.
1040         check_assist(
1041             generate_function,
1042             r"
1043 struct Baz;
1044 impl Baz {
1045     fn new() -> Self { Baz }
1046 }
1047 fn foo() {
1048     $0bar(Baz::new);
1049 }
1050 ",
1051             r"
1052 struct Baz;
1053 impl Baz {
1054     fn new() -> Self { Baz }
1055 }
1056 fn foo() {
1057     bar(Baz::new);
1058 }
1059
1060 fn bar(new: fn) ${0:-> ()} {
1061     todo!()
1062 }
1063 ",
1064         )
1065     }
1066
1067     #[test]
1068     fn add_function_with_closure_arg() {
1069         // FIXME: The argument in `bar` is wrong.
1070         check_assist(
1071             generate_function,
1072             r"
1073 fn foo() {
1074     let closure = |x: i64| x - 1;
1075     $0bar(closure)
1076 }
1077 ",
1078             r"
1079 fn foo() {
1080     let closure = |x: i64| x - 1;
1081     bar(closure)
1082 }
1083
1084 fn bar(closure: ()) ${0:-> ()} {
1085     todo!()
1086 }
1087 ",
1088         )
1089     }
1090
1091     #[test]
1092     fn unresolveable_types_default_to_unit() {
1093         check_assist(
1094             generate_function,
1095             r"
1096 fn foo() {
1097     $0bar(baz)
1098 }
1099 ",
1100             r"
1101 fn foo() {
1102     bar(baz)
1103 }
1104
1105 fn bar(baz: ()) ${0:-> ()} {
1106     todo!()
1107 }
1108 ",
1109         )
1110     }
1111
1112     #[test]
1113     fn arg_names_dont_overlap() {
1114         check_assist(
1115             generate_function,
1116             r"
1117 struct Baz;
1118 fn baz() -> Baz { Baz }
1119 fn foo() {
1120     $0bar(baz(), baz())
1121 }
1122 ",
1123             r"
1124 struct Baz;
1125 fn baz() -> Baz { Baz }
1126 fn foo() {
1127     bar(baz(), baz())
1128 }
1129
1130 fn bar(baz_1: Baz, baz_2: Baz) ${0:-> ()} {
1131     todo!()
1132 }
1133 ",
1134         )
1135     }
1136
1137     #[test]
1138     fn arg_name_counters_start_at_1_per_name() {
1139         check_assist(
1140             generate_function,
1141             r#"
1142 struct Baz;
1143 fn baz() -> Baz { Baz }
1144 fn foo() {
1145     $0bar(baz(), baz(), "foo", "bar")
1146 }
1147 "#,
1148             r#"
1149 struct Baz;
1150 fn baz() -> Baz { Baz }
1151 fn foo() {
1152     bar(baz(), baz(), "foo", "bar")
1153 }
1154
1155 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) ${0:-> ()} {
1156     todo!()
1157 }
1158 "#,
1159         )
1160     }
1161
1162     #[test]
1163     fn add_function_in_module() {
1164         check_assist(
1165             generate_function,
1166             r"
1167 mod bar {}
1168
1169 fn foo() {
1170     bar::my_fn$0()
1171 }
1172 ",
1173             r"
1174 mod bar {
1175     pub(crate) fn my_fn() ${0:-> ()} {
1176         todo!()
1177     }
1178 }
1179
1180 fn foo() {
1181     bar::my_fn()
1182 }
1183 ",
1184         )
1185     }
1186
1187     #[test]
1188     fn qualified_path_uses_correct_scope() {
1189         check_assist(
1190             generate_function,
1191             r#"
1192 mod foo {
1193     pub struct Foo;
1194 }
1195 fn bar() {
1196     use foo::Foo;
1197     let foo = Foo;
1198     baz$0(foo)
1199 }
1200 "#,
1201             r#"
1202 mod foo {
1203     pub struct Foo;
1204 }
1205 fn bar() {
1206     use foo::Foo;
1207     let foo = Foo;
1208     baz(foo)
1209 }
1210
1211 fn baz(foo: foo::Foo) ${0:-> ()} {
1212     todo!()
1213 }
1214 "#,
1215         )
1216     }
1217
1218     #[test]
1219     fn add_function_in_module_containing_other_items() {
1220         check_assist(
1221             generate_function,
1222             r"
1223 mod bar {
1224     fn something_else() {}
1225 }
1226
1227 fn foo() {
1228     bar::my_fn$0()
1229 }
1230 ",
1231             r"
1232 mod bar {
1233     fn something_else() {}
1234
1235     pub(crate) fn my_fn() ${0:-> ()} {
1236         todo!()
1237     }
1238 }
1239
1240 fn foo() {
1241     bar::my_fn()
1242 }
1243 ",
1244         )
1245     }
1246
1247     #[test]
1248     fn add_function_in_nested_module() {
1249         check_assist(
1250             generate_function,
1251             r"
1252 mod bar {
1253     mod baz {}
1254 }
1255
1256 fn foo() {
1257     bar::baz::my_fn$0()
1258 }
1259 ",
1260             r"
1261 mod bar {
1262     mod baz {
1263         pub(crate) fn my_fn() ${0:-> ()} {
1264             todo!()
1265         }
1266     }
1267 }
1268
1269 fn foo() {
1270     bar::baz::my_fn()
1271 }
1272 ",
1273         )
1274     }
1275
1276     #[test]
1277     fn add_function_in_another_file() {
1278         check_assist(
1279             generate_function,
1280             r"
1281 //- /main.rs
1282 mod foo;
1283
1284 fn main() {
1285     foo::bar$0()
1286 }
1287 //- /foo.rs
1288 ",
1289             r"
1290
1291
1292 pub(crate) fn bar() ${0:-> ()} {
1293     todo!()
1294 }",
1295         )
1296     }
1297
1298     #[test]
1299     fn add_function_with_return_type() {
1300         check_assist(
1301             generate_function,
1302             r"
1303 fn main() {
1304     let x: u32 = foo$0();
1305 }
1306 ",
1307             r"
1308 fn main() {
1309     let x: u32 = foo();
1310 }
1311
1312 fn foo() -> u32 {
1313     todo!()
1314 }
1315 ",
1316         )
1317     }
1318
1319     #[test]
1320     fn add_function_not_applicable_if_function_already_exists() {
1321         check_assist_not_applicable(
1322             generate_function,
1323             r"
1324 fn foo() {
1325     bar$0();
1326 }
1327
1328 fn bar() {}
1329 ",
1330         )
1331     }
1332
1333     #[test]
1334     fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1335         check_assist_not_applicable(
1336             // bar is resolved, but baz isn't.
1337             // The assist is only active if the cursor is on an unresolved path,
1338             // but the assist should only be offered if the path is a function call.
1339             generate_function,
1340             r#"
1341 fn foo() {
1342     bar(b$0az);
1343 }
1344
1345 fn bar(baz: ()) {}
1346 "#,
1347         )
1348     }
1349
1350     #[test]
1351     fn create_method_with_no_args() {
1352         // FIXME: This is wrong, this should just work.
1353         check_assist_not_applicable(
1354             generate_function,
1355             r#"
1356 struct Foo;
1357 impl Foo {
1358     fn foo(&self) {
1359         self.bar()$0;
1360     }
1361 }
1362         "#,
1363         )
1364     }
1365
1366     #[test]
1367     fn create_function_with_async() {
1368         check_assist(
1369             generate_function,
1370             r"
1371 fn foo() {
1372     $0bar(42).await();
1373 }
1374 ",
1375             r"
1376 fn foo() {
1377     bar(42).await();
1378 }
1379
1380 async fn bar(arg: i32) ${0:-> ()} {
1381     todo!()
1382 }
1383 ",
1384         )
1385     }
1386 }