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