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