]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/handlers/generate_function.rs
Merge #10373
[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     if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) {
546         Some(rendered)
547     } else {
548         None
549     }
550 }
551
552 /// Returns the position inside the current mod or file
553 /// directly after the current block
554 /// We want to write the generated function directly after
555 /// fns, impls or macro calls, but inside mods
556 fn next_space_for_fn_after_call_site(expr: FuncExpr) -> Option<GeneratedFunctionTarget> {
557     let mut ancestors = expr.syntax().ancestors().peekable();
558     let mut last_ancestor: Option<SyntaxNode> = None;
559     while let Some(next_ancestor) = ancestors.next() {
560         match next_ancestor.kind() {
561             SyntaxKind::SOURCE_FILE => {
562                 break;
563             }
564             SyntaxKind::ITEM_LIST => {
565                 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
566                     break;
567                 }
568             }
569             _ => {}
570         }
571         last_ancestor = Some(next_ancestor);
572     }
573     last_ancestor.map(GeneratedFunctionTarget::BehindItem)
574 }
575
576 fn next_space_for_fn_in_module(
577     db: &dyn hir::db::AstDatabase,
578     module_source: &hir::InFile<hir::ModuleSource>,
579 ) -> Option<(FileId, GeneratedFunctionTarget)> {
580     let file = module_source.file_id.original_file(db);
581     let assist_item = match &module_source.value {
582         hir::ModuleSource::SourceFile(it) => {
583             if let Some(last_item) = it.items().last() {
584                 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
585             } else {
586                 GeneratedFunctionTarget::BehindItem(it.syntax().clone())
587             }
588         }
589         hir::ModuleSource::Module(it) => {
590             if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
591                 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
592             } else {
593                 GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone())
594             }
595         }
596         hir::ModuleSource::BlockExpr(it) => {
597             if let Some(last_item) =
598                 it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
599             {
600                 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
601             } else {
602                 GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone())
603             }
604         }
605     };
606     Some((file, assist_item))
607 }
608
609 fn next_space_for_fn_in_impl(impl_: &ast::Impl) -> Option<GeneratedFunctionTarget> {
610     if let Some(last_item) = impl_.assoc_item_list().and_then(|it| it.assoc_items().last()) {
611         Some(GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()))
612     } else {
613         Some(GeneratedFunctionTarget::InEmptyItemList(impl_.assoc_item_list()?.syntax().clone()))
614     }
615 }
616
617 fn module_is_descendant(module: &hir::Module, ans: &hir::Module, ctx: &AssistContext) -> bool {
618     if module == ans {
619         return true;
620     }
621     for c in ans.children(ctx.sema.db) {
622         if module_is_descendant(module, &c, ctx) {
623             return true;
624         }
625     }
626     false
627 }
628
629 #[cfg(test)]
630 mod tests {
631     use crate::tests::{check_assist, check_assist_not_applicable};
632
633     use super::*;
634
635     #[test]
636     fn add_function_with_no_args() {
637         check_assist(
638             generate_function,
639             r"
640 fn foo() {
641     bar$0();
642 }
643 ",
644             r"
645 fn foo() {
646     bar();
647 }
648
649 fn bar() ${0:-> _} {
650     todo!()
651 }
652 ",
653         )
654     }
655
656     #[test]
657     fn add_function_from_method() {
658         // This ensures that the function is correctly generated
659         // in the next outer mod or file
660         check_assist(
661             generate_function,
662             r"
663 impl Foo {
664     fn foo() {
665         bar$0();
666     }
667 }
668 ",
669             r"
670 impl Foo {
671     fn foo() {
672         bar();
673     }
674 }
675
676 fn bar() ${0:-> _} {
677     todo!()
678 }
679 ",
680         )
681     }
682
683     #[test]
684     fn add_function_directly_after_current_block() {
685         // The new fn should not be created at the end of the file or module
686         check_assist(
687             generate_function,
688             r"
689 fn foo1() {
690     bar$0();
691 }
692
693 fn foo2() {}
694 ",
695             r"
696 fn foo1() {
697     bar();
698 }
699
700 fn bar() ${0:-> _} {
701     todo!()
702 }
703
704 fn foo2() {}
705 ",
706         )
707     }
708
709     #[test]
710     fn add_function_with_no_args_in_same_module() {
711         check_assist(
712             generate_function,
713             r"
714 mod baz {
715     fn foo() {
716         bar$0();
717     }
718 }
719 ",
720             r"
721 mod baz {
722     fn foo() {
723         bar();
724     }
725
726     fn bar() ${0:-> _} {
727         todo!()
728     }
729 }
730 ",
731         )
732     }
733
734     #[test]
735     fn add_function_with_upper_camel_case_arg() {
736         check_assist(
737             generate_function,
738             r"
739 struct BazBaz;
740 fn foo() {
741     bar$0(BazBaz);
742 }
743 ",
744             r"
745 struct BazBaz;
746 fn foo() {
747     bar(BazBaz);
748 }
749
750 fn bar(baz_baz: BazBaz) ${0:-> _} {
751     todo!()
752 }
753 ",
754         );
755     }
756
757     #[test]
758     fn add_function_with_upper_camel_case_arg_as_cast() {
759         check_assist(
760             generate_function,
761             r"
762 struct BazBaz;
763 fn foo() {
764     bar$0(&BazBaz as *const BazBaz);
765 }
766 ",
767             r"
768 struct BazBaz;
769 fn foo() {
770     bar(&BazBaz as *const BazBaz);
771 }
772
773 fn bar(baz_baz: *const BazBaz) ${0:-> _} {
774     todo!()
775 }
776 ",
777         );
778     }
779
780     #[test]
781     fn add_function_with_function_call_arg() {
782         check_assist(
783             generate_function,
784             r"
785 struct Baz;
786 fn baz() -> Baz { todo!() }
787 fn foo() {
788     bar$0(baz());
789 }
790 ",
791             r"
792 struct Baz;
793 fn baz() -> Baz { todo!() }
794 fn foo() {
795     bar(baz());
796 }
797
798 fn bar(baz: Baz) ${0:-> _} {
799     todo!()
800 }
801 ",
802         );
803     }
804
805     #[test]
806     fn add_function_with_method_call_arg() {
807         check_assist(
808             generate_function,
809             r"
810 struct Baz;
811 impl Baz {
812     fn foo(&self) -> Baz {
813         ba$0r(self.baz())
814     }
815     fn baz(&self) -> Baz {
816         Baz
817     }
818 }
819 ",
820             r"
821 struct Baz;
822 impl Baz {
823     fn foo(&self) -> Baz {
824         bar(self.baz())
825     }
826     fn baz(&self) -> Baz {
827         Baz
828     }
829 }
830
831 fn bar(baz: Baz) -> Baz {
832     ${0:todo!()}
833 }
834 ",
835         )
836     }
837
838     #[test]
839     fn add_function_with_string_literal_arg() {
840         check_assist(
841             generate_function,
842             r#"
843 fn foo() {
844     $0bar("bar")
845 }
846 "#,
847             r#"
848 fn foo() {
849     bar("bar")
850 }
851
852 fn bar(arg: &str) {
853     ${0:todo!()}
854 }
855 "#,
856         )
857     }
858
859     #[test]
860     fn add_function_with_char_literal_arg() {
861         check_assist(
862             generate_function,
863             r#"
864 fn foo() {
865     $0bar('x')
866 }
867 "#,
868             r#"
869 fn foo() {
870     bar('x')
871 }
872
873 fn bar(arg: char) {
874     ${0:todo!()}
875 }
876 "#,
877         )
878     }
879
880     #[test]
881     fn add_function_with_int_literal_arg() {
882         check_assist(
883             generate_function,
884             r"
885 fn foo() {
886     $0bar(42)
887 }
888 ",
889             r"
890 fn foo() {
891     bar(42)
892 }
893
894 fn bar(arg: i32) {
895     ${0:todo!()}
896 }
897 ",
898         )
899     }
900
901     #[test]
902     fn add_function_with_cast_int_literal_arg() {
903         check_assist(
904             generate_function,
905             r"
906 fn foo() {
907     $0bar(42 as u8)
908 }
909 ",
910             r"
911 fn foo() {
912     bar(42 as u8)
913 }
914
915 fn bar(arg: u8) {
916     ${0:todo!()}
917 }
918 ",
919         )
920     }
921
922     #[test]
923     fn name_of_cast_variable_is_used() {
924         // Ensures that the name of the cast type isn't used
925         // in the generated function signature.
926         check_assist(
927             generate_function,
928             r"
929 fn foo() {
930     let x = 42;
931     bar$0(x as u8)
932 }
933 ",
934             r"
935 fn foo() {
936     let x = 42;
937     bar(x as u8)
938 }
939
940 fn bar(x: u8) {
941     ${0:todo!()}
942 }
943 ",
944         )
945     }
946
947     #[test]
948     fn add_function_with_variable_arg() {
949         check_assist(
950             generate_function,
951             r"
952 fn foo() {
953     let worble = ();
954     $0bar(worble)
955 }
956 ",
957             r"
958 fn foo() {
959     let worble = ();
960     bar(worble)
961 }
962
963 fn bar(worble: ()) {
964     ${0:todo!()}
965 }
966 ",
967         )
968     }
969
970     #[test]
971     fn add_function_with_impl_trait_arg() {
972         check_assist(
973             generate_function,
974             r#"
975 //- minicore: sized
976 trait Foo {}
977 fn foo() -> impl Foo {
978     todo!()
979 }
980 fn baz() {
981     $0bar(foo())
982 }
983 "#,
984             r#"
985 trait Foo {}
986 fn foo() -> impl Foo {
987     todo!()
988 }
989 fn baz() {
990     bar(foo())
991 }
992
993 fn bar(foo: impl Foo) {
994     ${0:todo!()}
995 }
996 "#,
997         )
998     }
999
1000     #[test]
1001     fn borrowed_arg() {
1002         check_assist(
1003             generate_function,
1004             r"
1005 struct Baz;
1006 fn baz() -> Baz { todo!() }
1007
1008 fn foo() {
1009     bar$0(&baz())
1010 }
1011 ",
1012             r"
1013 struct Baz;
1014 fn baz() -> Baz { todo!() }
1015
1016 fn foo() {
1017     bar(&baz())
1018 }
1019
1020 fn bar(baz: &Baz) {
1021     ${0:todo!()}
1022 }
1023 ",
1024         )
1025     }
1026
1027     #[test]
1028     fn add_function_with_qualified_path_arg() {
1029         check_assist(
1030             generate_function,
1031             r"
1032 mod Baz {
1033     pub struct Bof;
1034     pub fn baz() -> Bof { Bof }
1035 }
1036 fn foo() {
1037     $0bar(Baz::baz())
1038 }
1039 ",
1040             r"
1041 mod Baz {
1042     pub struct Bof;
1043     pub fn baz() -> Bof { Bof }
1044 }
1045 fn foo() {
1046     bar(Baz::baz())
1047 }
1048
1049 fn bar(baz: Baz::Bof) {
1050     ${0:todo!()}
1051 }
1052 ",
1053         )
1054     }
1055
1056     #[test]
1057     fn add_function_with_generic_arg() {
1058         // FIXME: This is wrong, generated `bar` should include generic parameter.
1059         check_assist(
1060             generate_function,
1061             r"
1062 fn foo<T>(t: T) {
1063     $0bar(t)
1064 }
1065 ",
1066             r"
1067 fn foo<T>(t: T) {
1068     bar(t)
1069 }
1070
1071 fn bar(t: T) {
1072     ${0:todo!()}
1073 }
1074 ",
1075         )
1076     }
1077
1078     #[test]
1079     fn add_function_with_fn_arg() {
1080         // FIXME: The argument in `bar` is wrong.
1081         check_assist(
1082             generate_function,
1083             r"
1084 struct Baz;
1085 impl Baz {
1086     fn new() -> Self { Baz }
1087 }
1088 fn foo() {
1089     $0bar(Baz::new);
1090 }
1091 ",
1092             r"
1093 struct Baz;
1094 impl Baz {
1095     fn new() -> Self { Baz }
1096 }
1097 fn foo() {
1098     bar(Baz::new);
1099 }
1100
1101 fn bar(new: fn) ${0:-> _} {
1102     todo!()
1103 }
1104 ",
1105         )
1106     }
1107
1108     #[test]
1109     fn add_function_with_closure_arg() {
1110         // FIXME: The argument in `bar` is wrong.
1111         check_assist(
1112             generate_function,
1113             r"
1114 fn foo() {
1115     let closure = |x: i64| x - 1;
1116     $0bar(closure)
1117 }
1118 ",
1119             r"
1120 fn foo() {
1121     let closure = |x: i64| x - 1;
1122     bar(closure)
1123 }
1124
1125 fn bar(closure: _) {
1126     ${0:todo!()}
1127 }
1128 ",
1129         )
1130     }
1131
1132     #[test]
1133     fn unresolveable_types_default_to_placeholder() {
1134         check_assist(
1135             generate_function,
1136             r"
1137 fn foo() {
1138     $0bar(baz)
1139 }
1140 ",
1141             r"
1142 fn foo() {
1143     bar(baz)
1144 }
1145
1146 fn bar(baz: _) {
1147     ${0:todo!()}
1148 }
1149 ",
1150         )
1151     }
1152
1153     #[test]
1154     fn arg_names_dont_overlap() {
1155         check_assist(
1156             generate_function,
1157             r"
1158 struct Baz;
1159 fn baz() -> Baz { Baz }
1160 fn foo() {
1161     $0bar(baz(), baz())
1162 }
1163 ",
1164             r"
1165 struct Baz;
1166 fn baz() -> Baz { Baz }
1167 fn foo() {
1168     bar(baz(), baz())
1169 }
1170
1171 fn bar(baz_1: Baz, baz_2: Baz) {
1172     ${0:todo!()}
1173 }
1174 ",
1175         )
1176     }
1177
1178     #[test]
1179     fn arg_name_counters_start_at_1_per_name() {
1180         check_assist(
1181             generate_function,
1182             r#"
1183 struct Baz;
1184 fn baz() -> Baz { Baz }
1185 fn foo() {
1186     $0bar(baz(), baz(), "foo", "bar")
1187 }
1188 "#,
1189             r#"
1190 struct Baz;
1191 fn baz() -> Baz { Baz }
1192 fn foo() {
1193     bar(baz(), baz(), "foo", "bar")
1194 }
1195
1196 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) {
1197     ${0:todo!()}
1198 }
1199 "#,
1200         )
1201     }
1202
1203     #[test]
1204     fn add_function_in_module() {
1205         check_assist(
1206             generate_function,
1207             r"
1208 mod bar {}
1209
1210 fn foo() {
1211     bar::my_fn$0()
1212 }
1213 ",
1214             r"
1215 mod bar {
1216     pub(crate) fn my_fn() {
1217         ${0:todo!()}
1218     }
1219 }
1220
1221 fn foo() {
1222     bar::my_fn()
1223 }
1224 ",
1225         )
1226     }
1227
1228     #[test]
1229     fn qualified_path_uses_correct_scope() {
1230         check_assist(
1231             generate_function,
1232             r#"
1233 mod foo {
1234     pub struct Foo;
1235 }
1236 fn bar() {
1237     use foo::Foo;
1238     let foo = Foo;
1239     baz$0(foo)
1240 }
1241 "#,
1242             r#"
1243 mod foo {
1244     pub struct Foo;
1245 }
1246 fn bar() {
1247     use foo::Foo;
1248     let foo = Foo;
1249     baz(foo)
1250 }
1251
1252 fn baz(foo: foo::Foo) {
1253     ${0:todo!()}
1254 }
1255 "#,
1256         )
1257     }
1258
1259     #[test]
1260     fn add_function_in_module_containing_other_items() {
1261         check_assist(
1262             generate_function,
1263             r"
1264 mod bar {
1265     fn something_else() {}
1266 }
1267
1268 fn foo() {
1269     bar::my_fn$0()
1270 }
1271 ",
1272             r"
1273 mod bar {
1274     fn something_else() {}
1275
1276     pub(crate) fn my_fn() {
1277         ${0:todo!()}
1278     }
1279 }
1280
1281 fn foo() {
1282     bar::my_fn()
1283 }
1284 ",
1285         )
1286     }
1287
1288     #[test]
1289     fn add_function_in_nested_module() {
1290         check_assist(
1291             generate_function,
1292             r"
1293 mod bar {
1294     mod baz {}
1295 }
1296
1297 fn foo() {
1298     bar::baz::my_fn$0()
1299 }
1300 ",
1301             r"
1302 mod bar {
1303     mod baz {
1304         pub(crate) fn my_fn() {
1305             ${0:todo!()}
1306         }
1307     }
1308 }
1309
1310 fn foo() {
1311     bar::baz::my_fn()
1312 }
1313 ",
1314         )
1315     }
1316
1317     #[test]
1318     fn add_function_in_another_file() {
1319         check_assist(
1320             generate_function,
1321             r"
1322 //- /main.rs
1323 mod foo;
1324
1325 fn main() {
1326     foo::bar$0()
1327 }
1328 //- /foo.rs
1329 ",
1330             r"
1331
1332
1333 pub(crate) fn bar() {
1334     ${0:todo!()}
1335 }",
1336         )
1337     }
1338
1339     #[test]
1340     fn add_function_with_return_type() {
1341         check_assist(
1342             generate_function,
1343             r"
1344 fn main() {
1345     let x: u32 = foo$0();
1346 }
1347 ",
1348             r"
1349 fn main() {
1350     let x: u32 = foo();
1351 }
1352
1353 fn foo() -> u32 {
1354     ${0:todo!()}
1355 }
1356 ",
1357         )
1358     }
1359
1360     #[test]
1361     fn add_function_not_applicable_if_function_already_exists() {
1362         check_assist_not_applicable(
1363             generate_function,
1364             r"
1365 fn foo() {
1366     bar$0();
1367 }
1368
1369 fn bar() {}
1370 ",
1371         )
1372     }
1373
1374     #[test]
1375     fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1376         check_assist_not_applicable(
1377             // bar is resolved, but baz isn't.
1378             // The assist is only active if the cursor is on an unresolved path,
1379             // but the assist should only be offered if the path is a function call.
1380             generate_function,
1381             r#"
1382 fn foo() {
1383     bar(b$0az);
1384 }
1385
1386 fn bar(baz: ()) {}
1387 "#,
1388         )
1389     }
1390
1391     #[test]
1392     fn create_method_with_no_args() {
1393         check_assist(
1394             generate_function,
1395             r#"
1396 struct Foo;
1397 impl Foo {
1398     fn foo(&self) {
1399         self.bar()$0;
1400     }
1401 }
1402 "#,
1403             r#"
1404 struct Foo;
1405 impl Foo {
1406     fn foo(&self) {
1407         self.bar();
1408     }
1409
1410     fn bar(&self) ${0:-> _} {
1411         todo!()
1412     }
1413 }
1414 "#,
1415         )
1416     }
1417
1418     #[test]
1419     fn create_function_with_async() {
1420         check_assist(
1421             generate_function,
1422             r"
1423 fn foo() {
1424     $0bar(42).await();
1425 }
1426 ",
1427             r"
1428 fn foo() {
1429     bar(42).await();
1430 }
1431
1432 async fn bar(arg: i32) ${0:-> _} {
1433     todo!()
1434 }
1435 ",
1436         )
1437     }
1438
1439     #[test]
1440     fn create_method() {
1441         check_assist(
1442             generate_function,
1443             r"
1444 struct S;
1445 fn foo() {S.bar$0();}
1446 ",
1447             r"
1448 struct S;
1449 fn foo() {S.bar();}
1450 impl S {
1451
1452
1453 fn bar(&self) ${0:-> _} {
1454     todo!()
1455 }
1456 }
1457 ",
1458         )
1459     }
1460
1461     #[test]
1462     fn create_method_within_an_impl() {
1463         check_assist(
1464             generate_function,
1465             r"
1466 struct S;
1467 fn foo() {S.bar$0();}
1468 impl S {}
1469
1470 ",
1471             r"
1472 struct S;
1473 fn foo() {S.bar();}
1474 impl S {
1475     fn bar(&self) ${0:-> _} {
1476         todo!()
1477     }
1478 }
1479
1480 ",
1481         )
1482     }
1483
1484     #[test]
1485     fn create_method_from_different_module() {
1486         check_assist(
1487             generate_function,
1488             r"
1489 mod s {
1490     pub struct S;
1491 }
1492 fn foo() {s::S.bar$0();}
1493 ",
1494             r"
1495 mod s {
1496     pub struct S;
1497 impl S {
1498
1499
1500     pub(crate) fn bar(&self) ${0:-> _} {
1501         todo!()
1502     }
1503 }
1504 }
1505 fn foo() {s::S.bar();}
1506 ",
1507         )
1508     }
1509
1510     #[test]
1511     fn create_method_from_descendant_module() {
1512         check_assist(
1513             generate_function,
1514             r"
1515 struct S;
1516 mod s {
1517     fn foo() {
1518         super::S.bar$0();
1519     }
1520 }
1521
1522 ",
1523             r"
1524 struct S;
1525 mod s {
1526     fn foo() {
1527         super::S.bar();
1528     }
1529 }
1530 impl S {
1531
1532
1533 fn bar(&self) ${0:-> _} {
1534     todo!()
1535 }
1536 }
1537
1538 ",
1539         )
1540     }
1541
1542     #[test]
1543     fn create_method_with_cursor_anywhere_on_call_expresion() {
1544         check_assist(
1545             generate_function,
1546             r"
1547 struct S;
1548 fn foo() {$0S.bar();}
1549 ",
1550             r"
1551 struct S;
1552 fn foo() {S.bar();}
1553 impl S {
1554
1555
1556 fn bar(&self) ${0:-> _} {
1557     todo!()
1558 }
1559 }
1560 ",
1561         )
1562     }
1563
1564     #[test]
1565     fn create_static_method() {
1566         check_assist(
1567             generate_function,
1568             r"
1569 struct S;
1570 fn foo() {S::bar$0();}
1571 ",
1572             r"
1573 struct S;
1574 fn foo() {S::bar();}
1575 impl S {
1576
1577
1578 fn bar() ${0:-> _} {
1579     todo!()
1580 }
1581 }
1582 ",
1583         )
1584     }
1585
1586     #[test]
1587     fn create_static_method_within_an_impl() {
1588         check_assist(
1589             generate_function,
1590             r"
1591 struct S;
1592 fn foo() {S::bar$0();}
1593 impl S {}
1594
1595 ",
1596             r"
1597 struct S;
1598 fn foo() {S::bar();}
1599 impl S {
1600     fn bar() ${0:-> _} {
1601         todo!()
1602     }
1603 }
1604
1605 ",
1606         )
1607     }
1608
1609     #[test]
1610     fn create_static_method_from_different_module() {
1611         check_assist(
1612             generate_function,
1613             r"
1614 mod s {
1615     pub struct S;
1616 }
1617 fn foo() {s::S::bar$0();}
1618 ",
1619             r"
1620 mod s {
1621     pub struct S;
1622 impl S {
1623
1624
1625     pub(crate) fn bar() ${0:-> _} {
1626         todo!()
1627     }
1628 }
1629 }
1630 fn foo() {s::S::bar();}
1631 ",
1632         )
1633     }
1634
1635     #[test]
1636     fn create_static_method_with_cursor_anywhere_on_call_expresion() {
1637         check_assist(
1638             generate_function,
1639             r"
1640 struct S;
1641 fn foo() {$0S::bar();}
1642 ",
1643             r"
1644 struct S;
1645 fn foo() {S::bar();}
1646 impl S {
1647
1648
1649 fn bar() ${0:-> _} {
1650     todo!()
1651 }
1652 }
1653 ",
1654         )
1655     }
1656
1657     #[test]
1658     fn no_panic_on_invalid_global_path() {
1659         check_assist(
1660             generate_function,
1661             r"
1662 fn main() {
1663     ::foo$0();
1664 }
1665 ",
1666             r"
1667 fn main() {
1668     ::foo();
1669 }
1670
1671 fn foo() ${0:-> _} {
1672     todo!()
1673 }
1674 ",
1675         )
1676     }
1677
1678     #[test]
1679     fn handle_tuple_indexing() {
1680         check_assist(
1681             generate_function,
1682             r"
1683 fn main() {
1684     let a = ((),);
1685     foo$0(a.0);
1686 }
1687 ",
1688             r"
1689 fn main() {
1690     let a = ((),);
1691     foo(a.0);
1692 }
1693
1694 fn foo(arg0: ()) ${0:-> _} {
1695     todo!()
1696 }
1697 ",
1698         )
1699     }
1700
1701     #[test]
1702     fn add_function_with_const_arg() {
1703         check_assist(
1704             generate_function,
1705             r"
1706 const VALUE: usize = 0;
1707 fn main() {
1708     foo$0(VALUE);
1709 }
1710 ",
1711             r"
1712 const VALUE: usize = 0;
1713 fn main() {
1714     foo(VALUE);
1715 }
1716
1717 fn foo(value: usize) ${0:-> _} {
1718     todo!()
1719 }
1720 ",
1721         )
1722     }
1723
1724     #[test]
1725     fn add_function_with_static_arg() {
1726         check_assist(
1727             generate_function,
1728             r"
1729 static VALUE: usize = 0;
1730 fn main() {
1731     foo$0(VALUE);
1732 }
1733 ",
1734             r"
1735 static VALUE: usize = 0;
1736 fn main() {
1737     foo(VALUE);
1738 }
1739
1740 fn foo(value: usize) ${0:-> _} {
1741     todo!()
1742 }
1743 ",
1744         )
1745     }
1746
1747     #[test]
1748     fn add_function_with_static_mut_arg() {
1749         check_assist(
1750             generate_function,
1751             r"
1752 static mut VALUE: usize = 0;
1753 fn main() {
1754     foo$0(VALUE);
1755 }
1756 ",
1757             r"
1758 static mut VALUE: usize = 0;
1759 fn main() {
1760     foo(VALUE);
1761 }
1762
1763 fn foo(value: usize) ${0:-> _} {
1764     todo!()
1765 }
1766 ",
1767         )
1768     }
1769 }