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