ide_assists/handlers/
generate_function.rs

1use hir::{
2    Adt, AsAssocItem, HasSource, HirDisplay, Module, PathResolution, Semantics, StructKind, Type,
3    TypeInfo,
4};
5use ide_db::{
6    FileId, FxHashMap, FxHashSet, RootDatabase, SnippetCap,
7    defs::{Definition, NameRefClass},
8    famous_defs::FamousDefs,
9    helpers::is_editable_crate,
10    path_transform::PathTransform,
11    source_change::SourceChangeBuilder,
12};
13use itertools::Itertools;
14use stdx::to_lower_snake_case;
15use syntax::{
16    Edition, SyntaxKind, SyntaxNode, T, TextRange,
17    ast::{
18        self, AstNode, BlockExpr, CallExpr, HasArgList, HasGenericParams, HasModuleItem,
19        HasTypeBounds, edit::IndentLevel, edit_in_place::Indent, make,
20    },
21    ted,
22};
23
24use crate::{
25    AssistContext, AssistId, Assists,
26    utils::{convert_reference_type, find_struct_impl},
27};
28
29// Assist: generate_function
30//
31// Adds a stub function with a signature matching the function under the cursor.
32//
33// ```
34// struct Baz;
35// fn baz() -> Baz { Baz }
36// fn foo() {
37//     bar$0("", baz());
38// }
39//
40// ```
41// ->
42// ```
43// struct Baz;
44// fn baz() -> Baz { Baz }
45// fn foo() {
46//     bar("", baz());
47// }
48//
49// fn bar(arg: &str, baz: Baz) ${0:-> _} {
50//     todo!()
51// }
52//
53// ```
54pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
55    gen_fn(acc, ctx).or_else(|| gen_method(acc, ctx))
56}
57
58fn gen_fn(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
59    let path_expr: ast::PathExpr = ctx.find_node_at_offset()?;
60    let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?;
61    let path = path_expr.path()?;
62    let name_ref = path.segment()?.name_ref()?;
63    if ctx.sema.resolve_path(&path).is_some() {
64        // The function call already resolves, no need to add a function
65        return None;
66    }
67
68    let fn_name = &*name_ref.text();
69    let TargetInfo { target_module, adt_info, target, file } =
70        fn_target_info(ctx, path, &call, fn_name)?;
71
72    if let Some(m) = target_module {
73        if !is_editable_crate(m.krate(), ctx.db()) {
74            return None;
75        }
76    }
77
78    let function_builder =
79        FunctionBuilder::from_call(ctx, &call, fn_name, target_module, target, &adt_info)?;
80    let text_range = call.syntax().text_range();
81    let label = format!("Generate {} function", function_builder.fn_name);
82    add_func_to_accumulator(acc, ctx, text_range, function_builder, file, adt_info, label)
83}
84
85struct TargetInfo {
86    target_module: Option<Module>,
87    adt_info: Option<AdtInfo>,
88    target: GeneratedFunctionTarget,
89    file: FileId,
90}
91
92impl TargetInfo {
93    fn new(
94        target_module: Option<Module>,
95        adt_info: Option<AdtInfo>,
96        target: GeneratedFunctionTarget,
97        file: FileId,
98    ) -> Self {
99        Self { target_module, adt_info, target, file }
100    }
101}
102
103fn fn_target_info(
104    ctx: &AssistContext<'_>,
105    path: ast::Path,
106    call: &CallExpr,
107    fn_name: &str,
108) -> Option<TargetInfo> {
109    match path.qualifier() {
110        Some(qualifier) => match ctx.sema.resolve_path(&qualifier) {
111            Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => {
112                get_fn_target_info(ctx, Some(module), call.clone())
113            }
114            Some(hir::PathResolution::Def(hir::ModuleDef::Adt(adt))) => {
115                if let hir::Adt::Enum(_) = adt {
116                    // Don't suggest generating function if the name starts with an uppercase letter
117                    if fn_name.starts_with(char::is_uppercase) {
118                        return None;
119                    }
120                }
121
122                assoc_fn_target_info(ctx, call, adt, fn_name)
123            }
124            Some(hir::PathResolution::SelfType(impl_)) => {
125                let adt = impl_.self_ty(ctx.db()).as_adt()?;
126                assoc_fn_target_info(ctx, call, adt, fn_name)
127            }
128            _ => None,
129        },
130        _ => get_fn_target_info(ctx, None, call.clone()),
131    }
132}
133
134fn gen_method(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
135    let call: ast::MethodCallExpr = ctx.find_node_at_offset()?;
136    if ctx.sema.resolve_method_call(&call).is_some() {
137        return None;
138    }
139
140    let fn_name = call.name_ref()?;
141    let receiver_ty = ctx.sema.type_of_expr(&call.receiver()?)?.original().strip_references();
142    let adt = receiver_ty.as_adt()?;
143
144    let target_module = adt.module(ctx.sema.db);
145    if !is_editable_crate(target_module.krate(), ctx.db()) {
146        return None;
147    }
148
149    let (impl_, file) = get_adt_source(ctx, &adt, fn_name.text().as_str())?;
150    let target = get_method_target(ctx, &impl_, &adt)?;
151
152    let function_builder = FunctionBuilder::from_method_call(
153        ctx,
154        &call,
155        &fn_name,
156        receiver_ty,
157        target_module,
158        target,
159    )?;
160    let text_range = call.syntax().text_range();
161    let adt_info = AdtInfo::new(adt, impl_.is_some());
162    let label = format!("Generate {} method", function_builder.fn_name);
163    add_func_to_accumulator(acc, ctx, text_range, function_builder, file, Some(adt_info), label)
164}
165
166fn add_func_to_accumulator(
167    acc: &mut Assists,
168    ctx: &AssistContext<'_>,
169    text_range: TextRange,
170    function_builder: FunctionBuilder,
171    file: FileId,
172    adt_info: Option<AdtInfo>,
173    label: String,
174) -> Option<()> {
175    acc.add(AssistId::generate("generate_function"), label, text_range, |edit| {
176        edit.edit_file(file);
177
178        let target = function_builder.target.clone();
179        let edition = function_builder.target_edition;
180        let func = function_builder.render(ctx.config.snippet_cap, edit);
181
182        if let Some(adt) = adt_info
183            .and_then(|adt_info| if adt_info.impl_exists { None } else { Some(adt_info.adt) })
184        {
185            let name = make::ty_path(make::ext::ident_path(&format!(
186                "{}",
187                adt.name(ctx.db()).display(ctx.db(), edition)
188            )));
189
190            // FIXME: adt may have generic params.
191            let impl_ = make::impl_(None, None, name, None, None).clone_for_update();
192
193            func.indent(IndentLevel(1));
194            impl_.get_or_create_assoc_item_list().add_item(func.into());
195            target.insert_impl_at(edit, impl_);
196        } else {
197            target.insert_fn_at(edit, func);
198        }
199    })
200}
201
202fn get_adt_source(
203    ctx: &AssistContext<'_>,
204    adt: &hir::Adt,
205    fn_name: &str,
206) -> Option<(Option<ast::Impl>, FileId)> {
207    let range = adt.source(ctx.sema.db)?.syntax().original_file_range_rooted(ctx.sema.db);
208
209    let file = ctx.sema.parse(range.file_id);
210    let adt_source =
211        ctx.sema.find_node_at_offset_with_macros(file.syntax(), range.range.start())?;
212    find_struct_impl(ctx, &adt_source, &[fn_name.to_owned()])
213        .map(|impl_| (impl_, range.file_id.file_id(ctx.db())))
214}
215
216struct FunctionBuilder {
217    target: GeneratedFunctionTarget,
218    fn_name: ast::Name,
219    generic_param_list: Option<ast::GenericParamList>,
220    where_clause: Option<ast::WhereClause>,
221    params: ast::ParamList,
222    fn_body: BlockExpr,
223    ret_type: Option<ast::RetType>,
224    should_focus_return_type: bool,
225    visibility: Visibility,
226    is_async: bool,
227    target_edition: Edition,
228}
229
230impl FunctionBuilder {
231    /// Prepares a generated function that matches `call`.
232    /// The function is generated in `target_module` or next to `call`
233    fn from_call(
234        ctx: &AssistContext<'_>,
235        call: &ast::CallExpr,
236        fn_name: &str,
237        target_module: Option<Module>,
238        target: GeneratedFunctionTarget,
239        adt_info: &Option<AdtInfo>,
240    ) -> Option<Self> {
241        let target_module =
242            target_module.or_else(|| ctx.sema.scope(target.syntax()).map(|it| it.module()))?;
243        let target_edition = target_module.krate().edition(ctx.db());
244
245        let current_module = ctx.sema.scope(call.syntax())?.module();
246        let visibility = calculate_necessary_visibility(current_module, target_module, ctx);
247        let fn_name = make::name(fn_name);
248        let mut necessary_generic_params = FxHashSet::default();
249        let params = fn_args(
250            ctx,
251            target_module,
252            ast::CallableExpr::Call(call.clone()),
253            &mut necessary_generic_params,
254        )?;
255
256        let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
257        let is_async = await_expr.is_some();
258
259        let ret_type;
260        let should_focus_return_type;
261        let fn_body;
262
263        // If generated function has the name "new" and is an associated function, we generate fn body
264        // as a constructor and assume a "Self" return type.
265        if let Some(body) =
266            make_fn_body_as_new_function(ctx, &fn_name.text(), adt_info, target_edition)
267        {
268            ret_type = Some(make::ret_type(make::ty_path(make::ext::ident_path("Self"))));
269            should_focus_return_type = false;
270            fn_body = body;
271        } else {
272            let expr_for_ret_ty = await_expr.map_or_else(|| call.clone().into(), |it| it.into());
273            (ret_type, should_focus_return_type) = make_return_type(
274                ctx,
275                &expr_for_ret_ty,
276                target_module,
277                &mut necessary_generic_params,
278            );
279            let placeholder_expr = make::ext::expr_todo();
280            fn_body = make::block_expr(vec![], Some(placeholder_expr));
281        };
282
283        let (generic_param_list, where_clause) =
284            fn_generic_params(ctx, necessary_generic_params, &target)?;
285
286        Some(Self {
287            target,
288            fn_name,
289            generic_param_list,
290            where_clause,
291            params,
292            fn_body,
293            ret_type,
294            should_focus_return_type,
295            visibility,
296            is_async,
297            target_edition,
298        })
299    }
300
301    fn from_method_call(
302        ctx: &AssistContext<'_>,
303        call: &ast::MethodCallExpr,
304        name: &ast::NameRef,
305        receiver_ty: Type,
306        target_module: Module,
307        target: GeneratedFunctionTarget,
308    ) -> Option<Self> {
309        let target_edition = target_module.krate().edition(ctx.db());
310
311        let current_module = ctx.sema.scope(call.syntax())?.module();
312        let visibility = calculate_necessary_visibility(current_module, target_module, ctx);
313
314        let fn_name = make::name(&name.text());
315        let mut necessary_generic_params = FxHashSet::default();
316        necessary_generic_params.extend(receiver_ty.generic_params(ctx.db()));
317        let params = fn_args(
318            ctx,
319            target_module,
320            ast::CallableExpr::MethodCall(call.clone()),
321            &mut necessary_generic_params,
322        )?;
323
324        let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
325        let is_async = await_expr.is_some();
326
327        let expr_for_ret_ty = await_expr.map_or_else(|| call.clone().into(), |it| it.into());
328        let (ret_type, should_focus_return_type) =
329            make_return_type(ctx, &expr_for_ret_ty, target_module, &mut necessary_generic_params);
330
331        let (generic_param_list, where_clause) =
332            fn_generic_params(ctx, necessary_generic_params, &target)?;
333
334        let placeholder_expr = make::ext::expr_todo();
335        let fn_body = make::block_expr(vec![], Some(placeholder_expr));
336
337        Some(Self {
338            target,
339            fn_name,
340            generic_param_list,
341            where_clause,
342            params,
343            fn_body,
344            ret_type,
345            should_focus_return_type,
346            visibility,
347            is_async,
348            target_edition,
349        })
350    }
351
352    fn render(self, cap: Option<SnippetCap>, edit: &mut SourceChangeBuilder) -> ast::Fn {
353        let visibility = match self.visibility {
354            Visibility::None => None,
355            Visibility::Crate => Some(make::visibility_pub_crate()),
356            Visibility::Pub => Some(make::visibility_pub()),
357        };
358        let fn_def = make::fn_(
359            visibility,
360            self.fn_name,
361            self.generic_param_list,
362            self.where_clause,
363            self.params,
364            self.fn_body,
365            self.ret_type,
366            self.is_async,
367            false, // FIXME : const and unsafe are not handled yet.
368            false,
369            false,
370        )
371        .clone_for_update();
372
373        let ret_type = fn_def.ret_type();
374        // PANIC: we guarantee we always create a function body with a tail expr
375        let tail_expr = fn_def
376            .body()
377            .expect("generated function should have a body")
378            .tail_expr()
379            .expect("function body should have a tail expression");
380
381        if let Some(cap) = cap {
382            if self.should_focus_return_type {
383                // Focus the return type if there is one
384                match ret_type {
385                    Some(ret_type) => {
386                        edit.add_placeholder_snippet(cap, ret_type.clone());
387                    }
388                    None => {
389                        edit.add_placeholder_snippet(cap, tail_expr.clone());
390                    }
391                }
392            } else {
393                edit.add_placeholder_snippet(cap, tail_expr.clone());
394            }
395        }
396
397        fn_def
398    }
399}
400
401/// Makes an optional return type along with whether the return type should be focused by the cursor.
402/// If we cannot infer what the return type should be, we create a placeholder type.
403///
404/// The rule for whether we focus a return type or not (and thus focus the function body),
405/// is rather simple:
406/// * If we could *not* infer what the return type should be, focus it (so the user can fill-in
407///   the correct return type).
408/// * If we could infer the return type, don't focus it (and thus focus the function body) so the
409///   user can change the `todo!` function body.
410fn make_return_type(
411    ctx: &AssistContext<'_>,
412    expr: &ast::Expr,
413    target_module: Module,
414    necessary_generic_params: &mut FxHashSet<hir::GenericParam>,
415) -> (Option<ast::RetType>, bool) {
416    let (ret_ty, should_focus_return_type) = {
417        match ctx.sema.type_of_expr(expr).map(TypeInfo::original) {
418            Some(ty) if ty.is_unknown() => (Some(make::ty_placeholder()), true),
419            None => (Some(make::ty_placeholder()), true),
420            Some(ty) if ty.is_unit() => (None, false),
421            Some(ty) => {
422                necessary_generic_params.extend(ty.generic_params(ctx.db()));
423                let rendered = ty.display_source_code(ctx.db(), target_module.into(), true);
424                match rendered {
425                    Ok(rendered) => (Some(make::ty(&rendered)), false),
426                    Err(_) => (Some(make::ty_placeholder()), true),
427                }
428            }
429        }
430    };
431    let ret_type = ret_ty.map(make::ret_type);
432    (ret_type, should_focus_return_type)
433}
434
435fn make_fn_body_as_new_function(
436    ctx: &AssistContext<'_>,
437    fn_name: &str,
438    adt_info: &Option<AdtInfo>,
439    edition: Edition,
440) -> Option<ast::BlockExpr> {
441    if fn_name != "new" {
442        return None;
443    };
444    let adt_info = adt_info.as_ref()?;
445
446    let path_self = make::ext::ident_path("Self");
447    let placeholder_expr = make::ext::expr_todo();
448    let tail_expr = if let Some(strukt) = adt_info.adt.as_struct() {
449        match strukt.kind(ctx.db()) {
450            StructKind::Record => {
451                let fields = strukt
452                    .fields(ctx.db())
453                    .iter()
454                    .map(|field| {
455                        make::record_expr_field(
456                            make::name_ref(&format!(
457                                "{}",
458                                field.name(ctx.db()).display(ctx.db(), edition)
459                            )),
460                            Some(placeholder_expr.clone()),
461                        )
462                    })
463                    .collect::<Vec<_>>();
464
465                make::record_expr(path_self, make::record_expr_field_list(fields)).into()
466            }
467            StructKind::Tuple => {
468                let args = strukt
469                    .fields(ctx.db())
470                    .iter()
471                    .map(|_| placeholder_expr.clone())
472                    .collect::<Vec<_>>();
473
474                make::expr_call(make::expr_path(path_self), make::arg_list(args)).into()
475            }
476            StructKind::Unit => make::expr_path(path_self),
477        }
478    } else {
479        placeholder_expr
480    };
481
482    let fn_body = make::block_expr(vec![], Some(tail_expr));
483    Some(fn_body)
484}
485
486fn get_fn_target_info(
487    ctx: &AssistContext<'_>,
488    target_module: Option<Module>,
489    call: CallExpr,
490) -> Option<TargetInfo> {
491    let (target, file) = get_fn_target(ctx, target_module, call)?;
492    Some(TargetInfo::new(target_module, None, target, file))
493}
494
495fn get_fn_target(
496    ctx: &AssistContext<'_>,
497    target_module: Option<Module>,
498    call: CallExpr,
499) -> Option<(GeneratedFunctionTarget, FileId)> {
500    let mut file = ctx.vfs_file_id();
501    let target = match target_module {
502        Some(target_module) => {
503            let (in_file, target) = next_space_for_fn_in_module(ctx.db(), target_module);
504            file = in_file;
505            target
506        }
507        None => next_space_for_fn_after_call_site(ast::CallableExpr::Call(call))?,
508    };
509    Some((target, file))
510}
511
512fn get_method_target(
513    ctx: &AssistContext<'_>,
514    impl_: &Option<ast::Impl>,
515    adt: &Adt,
516) -> Option<GeneratedFunctionTarget> {
517    let target = match impl_ {
518        Some(impl_) => GeneratedFunctionTarget::InImpl(impl_.clone()),
519        None => GeneratedFunctionTarget::AfterItem(adt.source(ctx.sema.db)?.syntax().value.clone()),
520    };
521    Some(target)
522}
523
524fn assoc_fn_target_info(
525    ctx: &AssistContext<'_>,
526    call: &CallExpr,
527    adt: hir::Adt,
528    fn_name: &str,
529) -> Option<TargetInfo> {
530    let current_module = ctx.sema.scope(call.syntax())?.module();
531    let module = adt.module(ctx.sema.db);
532    let target_module = if current_module == module { None } else { Some(module) };
533    if current_module.krate() != module.krate() {
534        return None;
535    }
536    let (impl_, file) = get_adt_source(ctx, &adt, fn_name)?;
537    let target = get_method_target(ctx, &impl_, &adt)?;
538    let adt_info = AdtInfo::new(adt, impl_.is_some());
539    Some(TargetInfo::new(target_module, Some(adt_info), target, file))
540}
541
542#[derive(Clone)]
543enum GeneratedFunctionTarget {
544    AfterItem(SyntaxNode),
545    InEmptyItemList(SyntaxNode),
546    InImpl(ast::Impl),
547}
548
549impl GeneratedFunctionTarget {
550    fn syntax(&self) -> &SyntaxNode {
551        match self {
552            GeneratedFunctionTarget::AfterItem(it) => it,
553            GeneratedFunctionTarget::InEmptyItemList(it) => it,
554            GeneratedFunctionTarget::InImpl(it) => it.syntax(),
555        }
556    }
557
558    fn parent(&self) -> SyntaxNode {
559        match self {
560            GeneratedFunctionTarget::AfterItem(it) => it.parent().expect("item without parent"),
561            GeneratedFunctionTarget::InEmptyItemList(it) => it.clone(),
562            GeneratedFunctionTarget::InImpl(it) => it.syntax().clone(),
563        }
564    }
565
566    fn insert_impl_at(&self, edit: &mut SourceChangeBuilder, impl_: ast::Impl) {
567        match self {
568            GeneratedFunctionTarget::AfterItem(item) => {
569                let item = edit.make_syntax_mut(item.clone());
570                let position = if item.parent().is_some() {
571                    ted::Position::after(&item)
572                } else {
573                    ted::Position::first_child_of(&item)
574                };
575
576                let indent = IndentLevel::from_node(&item);
577                let leading_ws = make::tokens::whitespace(&format!("\n{indent}"));
578                impl_.indent(indent);
579
580                ted::insert_all(position, vec![leading_ws.into(), impl_.syntax().clone().into()]);
581            }
582            GeneratedFunctionTarget::InEmptyItemList(item_list) => {
583                let item_list = edit.make_syntax_mut(item_list.clone());
584                let insert_after =
585                    item_list.children_with_tokens().find_or_first(|child| child.kind() == T!['{']);
586                let position = match insert_after {
587                    Some(child) => ted::Position::after(child),
588                    None => ted::Position::first_child_of(&item_list),
589                };
590
591                let indent = IndentLevel::from_node(&item_list);
592                let leading_indent = indent + 1;
593                let leading_ws = make::tokens::whitespace(&format!("\n{leading_indent}"));
594                impl_.indent(indent);
595
596                ted::insert_all(position, vec![leading_ws.into(), impl_.syntax().clone().into()]);
597            }
598            GeneratedFunctionTarget::InImpl(_) => {
599                unreachable!("can't insert an impl inside an impl")
600            }
601        }
602    }
603
604    fn insert_fn_at(&self, edit: &mut SourceChangeBuilder, func: ast::Fn) {
605        match self {
606            GeneratedFunctionTarget::AfterItem(item) => {
607                let item = edit.make_syntax_mut(item.clone());
608                let position = if item.parent().is_some() {
609                    ted::Position::after(&item)
610                } else {
611                    ted::Position::first_child_of(&item)
612                };
613
614                let indent = IndentLevel::from_node(&item);
615                let leading_ws = make::tokens::whitespace(&format!("\n\n{indent}"));
616                func.indent(indent);
617
618                ted::insert_all_raw(
619                    position,
620                    vec![leading_ws.into(), func.syntax().clone().into()],
621                );
622            }
623            GeneratedFunctionTarget::InEmptyItemList(item_list) => {
624                let item_list = edit.make_syntax_mut(item_list.clone());
625                let insert_after =
626                    item_list.children_with_tokens().find_or_first(|child| child.kind() == T!['{']);
627                let position = match insert_after {
628                    Some(child) => ted::Position::after(child),
629                    None => ted::Position::first_child_of(&item_list),
630                };
631
632                let indent = IndentLevel::from_node(&item_list);
633                let leading_indent = indent + 1;
634                let leading_ws = make::tokens::whitespace(&format!("\n{leading_indent}"));
635                let trailing_ws = make::tokens::whitespace(&format!("\n{indent}"));
636                func.indent(leading_indent);
637
638                ted::insert_all(
639                    position,
640                    vec![leading_ws.into(), func.syntax().clone().into(), trailing_ws.into()],
641                );
642            }
643            GeneratedFunctionTarget::InImpl(impl_) => {
644                let impl_ = edit.make_mut(impl_.clone());
645
646                let leading_indent = impl_.indent_level() + 1;
647                func.indent(leading_indent);
648
649                impl_.get_or_create_assoc_item_list().add_item(func.into());
650            }
651        }
652    }
653}
654
655struct AdtInfo {
656    adt: hir::Adt,
657    impl_exists: bool,
658}
659
660impl AdtInfo {
661    fn new(adt: Adt, impl_exists: bool) -> Self {
662        Self { adt, impl_exists }
663    }
664}
665
666/// Computes parameter list for the generated function.
667fn fn_args(
668    ctx: &AssistContext<'_>,
669    target_module: Module,
670    call: ast::CallableExpr,
671    necessary_generic_params: &mut FxHashSet<hir::GenericParam>,
672) -> Option<ast::ParamList> {
673    let mut arg_names = Vec::new();
674    let mut arg_types = Vec::new();
675    for arg in call.arg_list()?.args() {
676        arg_names.push(fn_arg_name(&ctx.sema, &arg));
677        arg_types.push(fn_arg_type(ctx, target_module, &arg, necessary_generic_params));
678    }
679    deduplicate_arg_names(&mut arg_names);
680    let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| {
681        make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty))
682    });
683
684    Some(make::param_list(
685        match call {
686            ast::CallableExpr::Call(_) => None,
687            ast::CallableExpr::MethodCall(_) => Some(make::self_param()),
688        },
689        params,
690    ))
691}
692
693/// Gets parameter bounds and where predicates in scope and filters out irrelevant ones. Returns
694/// `None` when it fails to get scope information.
695///
696/// See comment on `filter_unnecessary_bounds()` for what bounds we consider relevant.
697///
698/// NOTE: Generic parameters returned from this function may cause name clash at `target`. We don't
699/// currently do anything about it because it's actually easy to resolve it after the assist: just
700/// use the Rename functionality.
701fn fn_generic_params(
702    ctx: &AssistContext<'_>,
703    necessary_params: FxHashSet<hir::GenericParam>,
704    target: &GeneratedFunctionTarget,
705) -> Option<(Option<ast::GenericParamList>, Option<ast::WhereClause>)> {
706    if necessary_params.is_empty() {
707        // Not really needed but fast path.
708        return Some((None, None));
709    }
710
711    // 1. Get generic parameters (with bounds) and where predicates in scope.
712    let (generic_params, where_preds) = params_and_where_preds_in_scope(ctx);
713
714    // 2. Extract type parameters included in each bound.
715    let mut generic_params = generic_params
716        .into_iter()
717        .filter_map(|it| compute_contained_params_in_generic_param(ctx, it))
718        .collect();
719    let mut where_preds = where_preds
720        .into_iter()
721        .filter_map(|it| compute_contained_params_in_where_pred(ctx, it))
722        .collect();
723
724    // 3. Filter out unnecessary bounds.
725    filter_unnecessary_bounds(&mut generic_params, &mut where_preds, necessary_params);
726    filter_bounds_in_scope(&mut generic_params, &mut where_preds, ctx, target);
727
728    let generic_params: Vec<ast::GenericParam> =
729        generic_params.into_iter().map(|it| it.node.clone_for_update()).collect();
730    let where_preds: Vec<ast::WherePred> =
731        where_preds.into_iter().map(|it| it.node.clone_for_update()).collect();
732
733    // 4. Rewrite paths
734    if let Some(param) = generic_params.first() {
735        let source_scope = ctx.sema.scope(param.syntax())?;
736        let target_scope = ctx.sema.scope(&target.parent())?;
737        if source_scope.module() != target_scope.module() {
738            let transform = PathTransform::generic_transformation(&target_scope, &source_scope);
739            let generic_params = generic_params.iter().map(|it| it.syntax());
740            let where_preds = where_preds.iter().map(|it| it.syntax());
741            transform.apply_all(generic_params.chain(where_preds));
742        }
743    }
744
745    let generic_param_list = make::generic_param_list(generic_params);
746    let where_clause =
747        if where_preds.is_empty() { None } else { Some(make::where_clause(where_preds)) };
748
749    Some((Some(generic_param_list), where_clause))
750}
751
752fn params_and_where_preds_in_scope(
753    ctx: &AssistContext<'_>,
754) -> (Vec<ast::GenericParam>, Vec<ast::WherePred>) {
755    let Some(body) = containing_body(ctx) else {
756        return Default::default();
757    };
758
759    let mut generic_params = Vec::new();
760    let mut where_clauses = Vec::new();
761
762    // There are two items where generic parameters currently in scope may be declared: the item
763    // the cursor is at, and its parent (if any).
764    //
765    // We handle parent first so that their generic parameters appear first in the generic
766    // parameter list of the function we're generating.
767    let db = ctx.db();
768    if let Some(parent) = body.as_assoc_item(db).map(|it| it.container(db)) {
769        match parent {
770            hir::AssocItemContainer::Impl(it) => {
771                let (params, clauses) = get_bounds_in_scope(ctx, it);
772                generic_params.extend(params);
773                where_clauses.extend(clauses);
774            }
775            hir::AssocItemContainer::Trait(it) => {
776                let (params, clauses) = get_bounds_in_scope(ctx, it);
777                generic_params.extend(params);
778                where_clauses.extend(clauses);
779            }
780        }
781    }
782
783    // Other defs with body may inherit generic parameters from its parent, but never have their
784    // own generic parameters.
785    if let hir::DefWithBody::Function(it) = body {
786        let (params, clauses) = get_bounds_in_scope(ctx, it);
787        generic_params.extend(params);
788        where_clauses.extend(clauses);
789    }
790
791    (generic_params, where_clauses)
792}
793
794fn containing_body(ctx: &AssistContext<'_>) -> Option<hir::DefWithBody> {
795    let item: ast::Item = ctx.find_node_at_offset()?;
796    let def = match item {
797        ast::Item::Fn(it) => ctx.sema.to_def(&it)?.into(),
798        ast::Item::Const(it) => ctx.sema.to_def(&it)?.into(),
799        ast::Item::Static(it) => ctx.sema.to_def(&it)?.into(),
800        _ => return None,
801    };
802    Some(def)
803}
804
805fn get_bounds_in_scope<D>(
806    ctx: &AssistContext<'_>,
807    def: D,
808) -> (impl Iterator<Item = ast::GenericParam>, impl Iterator<Item = ast::WherePred>)
809where
810    D: HasSource,
811    D::Ast: HasGenericParams,
812{
813    // This function should be only called with `Impl`, `Trait`, or `Function`, for which it's
814    // infallible to get source ast.
815    let node = ctx.sema.source(def).expect("definition's source couldn't be found").value;
816    let generic_params = node.generic_param_list().into_iter().flat_map(|it| it.generic_params());
817    let where_clauses = node.where_clause().into_iter().flat_map(|it| it.predicates());
818    (generic_params, where_clauses)
819}
820
821#[derive(Debug)]
822struct ParamBoundWithParams {
823    node: ast::GenericParam,
824    /// Generic parameter `node` introduces.
825    ///
826    /// ```text
827    /// impl<T> S<T> {
828    ///     fn f<U: Trait<T>>() {}
829    ///          ^ this
830    /// }
831    /// ```
832    ///
833    /// `U` in this example.
834    self_ty_param: hir::GenericParam,
835    /// Generic parameters contained in the trait reference of this bound.
836    ///
837    /// ```text
838    /// impl<T> S<T> {
839    ///     fn f<U: Trait<T>>() {}
840    ///             ^^^^^^^^ params in this part
841    /// }
842    /// ```
843    ///
844    /// `T` in this example.
845    other_params: FxHashSet<hir::GenericParam>,
846}
847
848#[derive(Debug)]
849struct WherePredWithParams {
850    node: ast::WherePred,
851    /// Generic parameters contained in the "self type" of this where predicate.
852    ///
853    /// ```text
854    /// Struct<T, U>: Trait<T, Assoc = V>,
855    /// ^^^^^^^^^^^^ params in this part
856    /// ```
857    ///
858    /// `T` and `U` in this example.
859    self_ty_params: FxHashSet<hir::GenericParam>,
860    /// Generic parameters contained in the trait reference of this where predicate.
861    ///
862    /// ```text
863    /// Struct<T, U>: Trait<T, Assoc = V>,
864    ///               ^^^^^^^^^^^^^^^^^^^ params in this part
865    /// ```
866    ///
867    /// `T` and `V` in this example.
868    other_params: FxHashSet<hir::GenericParam>,
869}
870
871fn compute_contained_params_in_generic_param(
872    ctx: &AssistContext<'_>,
873    node: ast::GenericParam,
874) -> Option<ParamBoundWithParams> {
875    match &node {
876        ast::GenericParam::TypeParam(ty) => {
877            let self_ty_param = ctx.sema.to_def(ty)?.into();
878
879            let other_params = ty
880                .type_bound_list()
881                .into_iter()
882                .flat_map(|it| it.bounds())
883                .flat_map(|bound| bound.syntax().descendants())
884                .filter_map(|node| filter_generic_params(ctx, node))
885                .collect();
886
887            Some(ParamBoundWithParams { node, self_ty_param, other_params })
888        }
889        ast::GenericParam::ConstParam(ct) => {
890            let self_ty_param = ctx.sema.to_def(ct)?.into();
891            Some(ParamBoundWithParams { node, self_ty_param, other_params: FxHashSet::default() })
892        }
893        ast::GenericParam::LifetimeParam(_) => {
894            // FIXME: It might be a good idea to handle lifetime parameters too.
895            None
896        }
897    }
898}
899
900fn compute_contained_params_in_where_pred(
901    ctx: &AssistContext<'_>,
902    node: ast::WherePred,
903) -> Option<WherePredWithParams> {
904    let self_ty = node.ty()?;
905    let bound_list = node.type_bound_list()?;
906
907    let self_ty_params = self_ty
908        .syntax()
909        .descendants()
910        .filter_map(|node| filter_generic_params(ctx, node))
911        .collect();
912
913    let other_params = bound_list
914        .bounds()
915        .flat_map(|bound| bound.syntax().descendants())
916        .filter_map(|node| filter_generic_params(ctx, node))
917        .collect();
918
919    Some(WherePredWithParams { node, self_ty_params, other_params })
920}
921
922fn filter_generic_params(ctx: &AssistContext<'_>, node: SyntaxNode) -> Option<hir::GenericParam> {
923    let path = ast::Path::cast(node)?;
924    match ctx.sema.resolve_path(&path)? {
925        PathResolution::TypeParam(it) => Some(it.into()),
926        PathResolution::ConstParam(it) => Some(it.into()),
927        _ => None,
928    }
929}
930
931/// Filters out irrelevant bounds from `generic_params` and `where_preds`.
932///
933/// Say we have a trait bound `Struct<T>: Trait<U>`. Given `necessary_params`, when is it relevant
934/// and when not? Some observations:
935/// - When `necessary_params` contains `T`, it's likely that we want this bound, but now we have
936///   an extra param to consider: `U`.
937/// - On the other hand, when `necessary_params` contains `U` (but not `T`), then it's unlikely
938///   that we want this bound because it doesn't really constrain `U`.
939///
940/// (FIXME?: The latter clause might be overstating. We may want to include the bound if the self
941/// type does *not* include generic params at all - like `Option<i32>: From<U>`)
942///
943/// Can we make this a bit more formal? Let's define "dependency" between generic parameters and
944/// trait bounds:
945/// - A generic parameter `T` depends on a trait bound if `T` appears in the self type (i.e. left
946///   part) of the bound.
947/// - A trait bound depends on a generic parameter `T` if `T` appears in the bound.
948///
949/// Using the notion, what we want is all the bounds that params in `necessary_params`
950/// *transitively* depend on!
951///
952/// Now it's not hard to solve: we build a dependency graph and compute all reachable nodes from
953/// nodes that represent params in `necessary_params` by usual and boring DFS.
954///
955/// The time complexity is O(|generic_params| + |where_preds| + |necessary_params|).
956fn filter_unnecessary_bounds(
957    generic_params: &mut Vec<ParamBoundWithParams>,
958    where_preds: &mut Vec<WherePredWithParams>,
959    necessary_params: FxHashSet<hir::GenericParam>,
960) {
961    // All `self_ty_param` should be unique as they were collected from `ast::GenericParamList`s.
962    let param_map: FxHashMap<hir::GenericParam, usize> =
963        generic_params.iter().map(|it| it.self_ty_param).zip(0..).collect();
964    let param_count = param_map.len();
965    let generic_params_upper_bound = param_count + generic_params.len();
966    let node_count = generic_params_upper_bound + where_preds.len();
967
968    // | node index range                        | what the node represents |
969    // |-----------------------------------------|--------------------------|
970    // | 0..param_count                          | generic parameter        |
971    // | param_count..generic_params_upper_bound | `ast::GenericParam`      |
972    // | generic_params_upper_bound..node_count  | `ast::WherePred`         |
973    let mut graph = Graph::new(node_count);
974    for (pred, pred_idx) in generic_params.iter().zip(param_count..) {
975        let param_idx = param_map[&pred.self_ty_param];
976        graph.add_edge(param_idx, pred_idx);
977        graph.add_edge(pred_idx, param_idx);
978
979        for param in &pred.other_params {
980            let param_idx = param_map[param];
981            graph.add_edge(pred_idx, param_idx);
982        }
983    }
984    for (pred, pred_idx) in where_preds.iter().zip(generic_params_upper_bound..) {
985        for param in &pred.self_ty_params {
986            let param_idx = param_map[param];
987            graph.add_edge(param_idx, pred_idx);
988            graph.add_edge(pred_idx, param_idx);
989        }
990        for param in &pred.other_params {
991            let param_idx = param_map[param];
992            graph.add_edge(pred_idx, param_idx);
993        }
994    }
995
996    let starting_nodes = necessary_params.iter().flat_map(|param| param_map.get(param).copied());
997    let reachable = graph.compute_reachable_nodes(starting_nodes);
998
999    // Not pretty, but effective. If only there were `Vec::retain_index()`...
1000    let mut idx = param_count;
1001    generic_params.retain(|_| {
1002        idx += 1;
1003        reachable[idx - 1]
1004    });
1005    stdx::always!(idx == generic_params_upper_bound, "inconsistent index");
1006    where_preds.retain(|_| {
1007        idx += 1;
1008        reachable[idx - 1]
1009    });
1010}
1011
1012/// Filters out bounds from impl if we're generating the function into the same impl we're
1013/// generating from.
1014fn filter_bounds_in_scope(
1015    generic_params: &mut Vec<ParamBoundWithParams>,
1016    where_preds: &mut Vec<WherePredWithParams>,
1017    ctx: &AssistContext<'_>,
1018    target: &GeneratedFunctionTarget,
1019) -> Option<()> {
1020    let target_impl = target.parent().ancestors().find_map(ast::Impl::cast)?;
1021    let target_impl = ctx.sema.to_def(&target_impl)?;
1022    // It's sufficient to test only the first element of `generic_params` because of the order of
1023    // insertion (see `params_and_where_preds_in_scope()`).
1024    let def = generic_params.first()?.self_ty_param.parent();
1025    if def != hir::GenericDef::Impl(target_impl) {
1026        return None;
1027    }
1028
1029    // Now we know every element that belongs to an impl would be in scope at `target`, we can
1030    // filter them out just by looking at their parent.
1031    generic_params.retain(|it| !matches!(it.self_ty_param.parent(), hir::GenericDef::Impl(_)));
1032    where_preds.retain(|it| {
1033        it.node.syntax().parent().and_then(|it| it.parent()).and_then(ast::Impl::cast).is_none()
1034    });
1035
1036    Some(())
1037}
1038
1039/// Makes duplicate argument names unique by appending incrementing numbers.
1040///
1041/// ```ignore
1042/// let mut names: Vec<String> =
1043///     vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
1044/// deduplicate_arg_names(&mut names);
1045/// let expected: Vec<String> =
1046///     vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
1047/// assert_eq!(names, expected);
1048/// ```
1049fn deduplicate_arg_names(arg_names: &mut [String]) {
1050    let mut arg_name_counts = FxHashMap::default();
1051    for name in arg_names.iter() {
1052        *arg_name_counts.entry(name).or_insert(0) += 1;
1053    }
1054    let duplicate_arg_names: FxHashSet<String> = arg_name_counts
1055        .into_iter()
1056        .filter(|(_, count)| *count >= 2)
1057        .map(|(name, _)| name.clone())
1058        .collect();
1059
1060    let mut counter_per_name = FxHashMap::default();
1061    for arg_name in arg_names.iter_mut() {
1062        if duplicate_arg_names.contains(arg_name) {
1063            let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
1064            arg_name.push('_');
1065            arg_name.push_str(&counter.to_string());
1066            *counter += 1;
1067        }
1068    }
1069}
1070
1071fn fn_arg_name(sema: &Semantics<'_, RootDatabase>, arg_expr: &ast::Expr) -> String {
1072    let name = (|| match arg_expr {
1073        ast::Expr::CastExpr(cast_expr) => Some(fn_arg_name(sema, &cast_expr.expr()?)),
1074        expr => {
1075            let name_ref = expr
1076                .syntax()
1077                .descendants()
1078                .filter_map(ast::NameRef::cast)
1079                .filter(|name| name.ident_token().is_some())
1080                .last()?;
1081            if let Some(NameRefClass::Definition(Definition::Const(_) | Definition::Static(_), _)) =
1082                NameRefClass::classify(sema, &name_ref)
1083            {
1084                return Some(name_ref.to_string().to_lowercase());
1085            };
1086            Some(to_lower_snake_case(&name_ref.to_string()))
1087        }
1088    })();
1089    match name {
1090        Some(mut name) if name.starts_with(|c: char| c.is_ascii_digit()) => {
1091            name.insert_str(0, "arg");
1092            name
1093        }
1094        Some(name) => name,
1095        None => "arg".to_owned(),
1096    }
1097}
1098
1099fn fn_arg_type(
1100    ctx: &AssistContext<'_>,
1101    target_module: Module,
1102    fn_arg: &ast::Expr,
1103    generic_params: &mut FxHashSet<hir::GenericParam>,
1104) -> String {
1105    fn maybe_displayed_type(
1106        ctx: &AssistContext<'_>,
1107        target_module: Module,
1108        fn_arg: &ast::Expr,
1109        generic_params: &mut FxHashSet<hir::GenericParam>,
1110    ) -> Option<String> {
1111        let ty = ctx.sema.type_of_expr(fn_arg)?.adjusted();
1112        if ty.is_unknown() {
1113            return None;
1114        }
1115
1116        generic_params.extend(ty.generic_params(ctx.db()));
1117
1118        if ty.is_reference() || ty.is_mutable_reference() {
1119            let famous_defs = &FamousDefs(&ctx.sema, ctx.sema.scope(fn_arg.syntax())?.krate());
1120            convert_reference_type(ty.strip_references(), ctx.db(), famous_defs)
1121                .map(|conversion| {
1122                    conversion
1123                        .convert_type(ctx.db(), target_module.krate().to_display_target(ctx.db()))
1124                        .to_string()
1125                })
1126                .or_else(|| ty.display_source_code(ctx.db(), target_module.into(), true).ok())
1127        } else {
1128            ty.display_source_code(ctx.db(), target_module.into(), true).ok()
1129        }
1130    }
1131
1132    maybe_displayed_type(ctx, target_module, fn_arg, generic_params)
1133        .unwrap_or_else(|| String::from("_"))
1134}
1135
1136/// Returns the position inside the current mod or file
1137/// directly after the current block
1138/// We want to write the generated function directly after
1139/// fns, impls or macro calls, but inside mods
1140fn next_space_for_fn_after_call_site(expr: ast::CallableExpr) -> Option<GeneratedFunctionTarget> {
1141    let mut ancestors = expr.syntax().ancestors().peekable();
1142    let mut last_ancestor: Option<SyntaxNode> = None;
1143    while let Some(next_ancestor) = ancestors.next() {
1144        match next_ancestor.kind() {
1145            SyntaxKind::SOURCE_FILE => {
1146                break;
1147            }
1148            SyntaxKind::ITEM_LIST => {
1149                if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
1150                    break;
1151                }
1152            }
1153            _ => {}
1154        }
1155        last_ancestor = Some(next_ancestor);
1156    }
1157    last_ancestor.map(GeneratedFunctionTarget::AfterItem)
1158}
1159
1160fn next_space_for_fn_in_module(
1161    db: &dyn hir::db::HirDatabase,
1162    target_module: hir::Module,
1163) -> (FileId, GeneratedFunctionTarget) {
1164    let module_source = target_module.definition_source(db);
1165    let file = module_source.file_id.original_file(db);
1166    let assist_item = match &module_source.value {
1167        hir::ModuleSource::SourceFile(it) => match it.items().last() {
1168            Some(last_item) => GeneratedFunctionTarget::AfterItem(last_item.syntax().clone()),
1169            None => GeneratedFunctionTarget::AfterItem(it.syntax().clone()),
1170        },
1171        hir::ModuleSource::Module(it) => match it.item_list().and_then(|it| it.items().last()) {
1172            Some(last_item) => GeneratedFunctionTarget::AfterItem(last_item.syntax().clone()),
1173            None => {
1174                let item_list =
1175                    it.item_list().expect("module definition source should have an item list");
1176                GeneratedFunctionTarget::InEmptyItemList(item_list.syntax().clone())
1177            }
1178        },
1179        hir::ModuleSource::BlockExpr(it) => {
1180            if let Some(last_item) =
1181                it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
1182            {
1183                GeneratedFunctionTarget::AfterItem(last_item.syntax().clone())
1184            } else {
1185                GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone())
1186            }
1187        }
1188    };
1189
1190    (file.file_id(db), assist_item)
1191}
1192
1193#[derive(Clone, Copy)]
1194enum Visibility {
1195    None,
1196    Crate,
1197    Pub,
1198}
1199
1200fn calculate_necessary_visibility(
1201    current_module: Module,
1202    target_module: Module,
1203    ctx: &AssistContext<'_>,
1204) -> Visibility {
1205    let db = ctx.db();
1206    let current_module = current_module.nearest_non_block_module(db);
1207    let target_module = target_module.nearest_non_block_module(db);
1208
1209    if target_module.krate() != current_module.krate() {
1210        Visibility::Pub
1211    } else if current_module.path_to_root(db).contains(&target_module) {
1212        Visibility::None
1213    } else {
1214        Visibility::Crate
1215    }
1216}
1217
1218// This is never intended to be used as a generic graph structure. If there's ever another need of
1219// graph algorithm, consider adding a library for that (and replace the following).
1220/// Minimally implemented directed graph structure represented by adjacency list.
1221struct Graph {
1222    edges: Vec<Vec<usize>>,
1223}
1224
1225impl Graph {
1226    fn new(node_count: usize) -> Self {
1227        Self { edges: vec![Vec::new(); node_count] }
1228    }
1229
1230    fn add_edge(&mut self, from: usize, to: usize) {
1231        self.edges[from].push(to);
1232    }
1233
1234    fn edges_for(&self, node_idx: usize) -> &[usize] {
1235        &self.edges[node_idx]
1236    }
1237
1238    fn len(&self) -> usize {
1239        self.edges.len()
1240    }
1241
1242    fn compute_reachable_nodes(
1243        &self,
1244        starting_nodes: impl IntoIterator<Item = usize>,
1245    ) -> Vec<bool> {
1246        let mut visitor = Visitor::new(self);
1247        for idx in starting_nodes {
1248            visitor.mark_reachable(idx);
1249        }
1250        visitor.visited
1251    }
1252}
1253
1254struct Visitor<'g> {
1255    graph: &'g Graph,
1256    visited: Vec<bool>,
1257    // Stack is held in this struct so we can reuse its buffer.
1258    stack: Vec<usize>,
1259}
1260
1261impl<'g> Visitor<'g> {
1262    fn new(graph: &'g Graph) -> Self {
1263        let visited = vec![false; graph.len()];
1264        Self { graph, visited, stack: Vec::new() }
1265    }
1266
1267    fn mark_reachable(&mut self, start_idx: usize) {
1268        // non-recursive DFS
1269        stdx::always!(self.stack.is_empty());
1270
1271        self.stack.push(start_idx);
1272        while let Some(idx) = self.stack.pop() {
1273            if !self.visited[idx] {
1274                self.visited[idx] = true;
1275                for &neighbor in self.graph.edges_for(idx) {
1276                    if !self.visited[neighbor] {
1277                        self.stack.push(neighbor);
1278                    }
1279                }
1280            }
1281        }
1282    }
1283}
1284
1285#[cfg(test)]
1286mod tests {
1287    use crate::tests::{check_assist, check_assist_not_applicable};
1288
1289    use super::*;
1290
1291    #[test]
1292    fn add_function_with_no_args() {
1293        check_assist(
1294            generate_function,
1295            r"
1296fn foo() {
1297    bar$0();
1298}
1299",
1300            r"
1301fn foo() {
1302    bar();
1303}
1304
1305fn bar() ${0:-> _} {
1306    todo!()
1307}
1308",
1309        )
1310    }
1311
1312    #[test]
1313    fn add_function_from_method() {
1314        // This ensures that the function is correctly generated
1315        // in the next outer mod or file
1316        check_assist(
1317            generate_function,
1318            r"
1319impl Foo {
1320    fn foo() {
1321        bar$0();
1322    }
1323}
1324",
1325            r"
1326impl Foo {
1327    fn foo() {
1328        bar();
1329    }
1330}
1331
1332fn bar() ${0:-> _} {
1333    todo!()
1334}
1335",
1336        )
1337    }
1338
1339    #[test]
1340    fn add_function_directly_after_current_block() {
1341        // The new fn should not be created at the end of the file or module
1342        check_assist(
1343            generate_function,
1344            r"
1345fn foo1() {
1346    bar$0();
1347}
1348
1349fn foo2() {}
1350",
1351            r"
1352fn foo1() {
1353    bar();
1354}
1355
1356fn bar() ${0:-> _} {
1357    todo!()
1358}
1359
1360fn foo2() {}
1361",
1362        )
1363    }
1364
1365    #[test]
1366    fn add_function_with_no_args_in_same_module() {
1367        check_assist(
1368            generate_function,
1369            r"
1370mod baz {
1371    fn foo() {
1372        bar$0();
1373    }
1374}
1375",
1376            r"
1377mod baz {
1378    fn foo() {
1379        bar();
1380    }
1381
1382    fn bar() ${0:-> _} {
1383        todo!()
1384    }
1385}
1386",
1387        )
1388    }
1389
1390    #[test]
1391    fn add_function_with_upper_camel_case_arg() {
1392        check_assist(
1393            generate_function,
1394            r"
1395struct BazBaz;
1396fn foo() {
1397    bar$0(BazBaz);
1398}
1399",
1400            r"
1401struct BazBaz;
1402fn foo() {
1403    bar(BazBaz);
1404}
1405
1406fn bar(baz_baz: BazBaz) ${0:-> _} {
1407    todo!()
1408}
1409",
1410        );
1411    }
1412
1413    #[test]
1414    fn add_function_with_upper_camel_case_arg_as_cast() {
1415        check_assist(
1416            generate_function,
1417            r"
1418struct BazBaz;
1419fn foo() {
1420    bar$0(&BazBaz as *const BazBaz);
1421}
1422",
1423            r"
1424struct BazBaz;
1425fn foo() {
1426    bar(&BazBaz as *const BazBaz);
1427}
1428
1429fn bar(baz_baz: *const BazBaz) ${0:-> _} {
1430    todo!()
1431}
1432",
1433        );
1434    }
1435
1436    #[test]
1437    fn add_function_with_function_call_arg() {
1438        check_assist(
1439            generate_function,
1440            r"
1441struct Baz;
1442fn baz() -> Baz { todo!() }
1443fn foo() {
1444    bar$0(baz());
1445}
1446",
1447            r"
1448struct Baz;
1449fn baz() -> Baz { todo!() }
1450fn foo() {
1451    bar(baz());
1452}
1453
1454fn bar(baz: Baz) ${0:-> _} {
1455    todo!()
1456}
1457",
1458        );
1459    }
1460
1461    #[test]
1462    fn add_function_with_method_call_arg() {
1463        check_assist(
1464            generate_function,
1465            r"
1466struct Baz;
1467impl Baz {
1468    fn foo(&self) -> Baz {
1469        ba$0r(self.baz())
1470    }
1471    fn baz(&self) -> Baz {
1472        Baz
1473    }
1474}
1475",
1476            r"
1477struct Baz;
1478impl Baz {
1479    fn foo(&self) -> Baz {
1480        bar(self.baz())
1481    }
1482    fn baz(&self) -> Baz {
1483        Baz
1484    }
1485}
1486
1487fn bar(baz: Baz) -> Baz {
1488    ${0:todo!()}
1489}
1490",
1491        )
1492    }
1493
1494    #[test]
1495    fn add_function_with_string_literal_arg() {
1496        check_assist(
1497            generate_function,
1498            r#"
1499fn foo() {
1500    $0bar("bar")
1501}
1502"#,
1503            r#"
1504fn foo() {
1505    bar("bar")
1506}
1507
1508fn bar(arg: &str) {
1509    ${0:todo!()}
1510}
1511"#,
1512        )
1513    }
1514
1515    #[test]
1516    fn add_function_with_char_literal_arg() {
1517        check_assist(
1518            generate_function,
1519            r#"
1520fn foo() {
1521    $0bar('x')
1522}
1523"#,
1524            r#"
1525fn foo() {
1526    bar('x')
1527}
1528
1529fn bar(arg: char) {
1530    ${0:todo!()}
1531}
1532"#,
1533        )
1534    }
1535
1536    #[test]
1537    fn add_function_with_int_literal_arg() {
1538        check_assist(
1539            generate_function,
1540            r"
1541fn foo() {
1542    $0bar(42)
1543}
1544",
1545            r"
1546fn foo() {
1547    bar(42)
1548}
1549
1550fn bar(arg: i32) {
1551    ${0:todo!()}
1552}
1553",
1554        )
1555    }
1556
1557    #[test]
1558    fn add_function_with_cast_int_literal_arg() {
1559        check_assist(
1560            generate_function,
1561            r"
1562fn foo() {
1563    $0bar(42 as u8)
1564}
1565",
1566            r"
1567fn foo() {
1568    bar(42 as u8)
1569}
1570
1571fn bar(arg: u8) {
1572    ${0:todo!()}
1573}
1574",
1575        )
1576    }
1577
1578    #[test]
1579    fn name_of_cast_variable_is_used() {
1580        // Ensures that the name of the cast type isn't used
1581        // in the generated function signature.
1582        check_assist(
1583            generate_function,
1584            r"
1585fn foo() {
1586    let x = 42;
1587    bar$0(x as u8)
1588}
1589",
1590            r"
1591fn foo() {
1592    let x = 42;
1593    bar(x as u8)
1594}
1595
1596fn bar(x: u8) {
1597    ${0:todo!()}
1598}
1599",
1600        )
1601    }
1602
1603    #[test]
1604    fn add_function_with_variable_arg() {
1605        check_assist(
1606            generate_function,
1607            r"
1608fn foo() {
1609    let worble = ();
1610    $0bar(worble)
1611}
1612",
1613            r"
1614fn foo() {
1615    let worble = ();
1616    bar(worble)
1617}
1618
1619fn bar(worble: ()) {
1620    ${0:todo!()}
1621}
1622",
1623        )
1624    }
1625
1626    #[test]
1627    fn add_function_with_impl_trait_arg() {
1628        check_assist(
1629            generate_function,
1630            r#"
1631//- minicore: sized
1632trait Foo {}
1633fn foo() -> impl Foo {
1634    todo!()
1635}
1636fn baz() {
1637    $0bar(foo())
1638}
1639"#,
1640            r#"
1641trait Foo {}
1642fn foo() -> impl Foo {
1643    todo!()
1644}
1645fn baz() {
1646    bar(foo())
1647}
1648
1649fn bar(foo: impl Foo) {
1650    ${0:todo!()}
1651}
1652"#,
1653        )
1654    }
1655
1656    #[test]
1657    fn borrowed_arg() {
1658        check_assist(
1659            generate_function,
1660            r"
1661struct Baz;
1662fn baz() -> Baz { todo!() }
1663
1664fn foo() {
1665    bar$0(&baz())
1666}
1667",
1668            r"
1669struct Baz;
1670fn baz() -> Baz { todo!() }
1671
1672fn foo() {
1673    bar(&baz())
1674}
1675
1676fn bar(baz: &Baz) {
1677    ${0:todo!()}
1678}
1679",
1680        )
1681    }
1682
1683    #[test]
1684    fn add_function_with_qualified_path_arg() {
1685        check_assist(
1686            generate_function,
1687            r"
1688mod Baz {
1689    pub struct Bof;
1690    pub fn baz() -> Bof { Bof }
1691}
1692fn foo() {
1693    $0bar(Baz::baz())
1694}
1695",
1696            r"
1697mod Baz {
1698    pub struct Bof;
1699    pub fn baz() -> Bof { Bof }
1700}
1701fn foo() {
1702    bar(Baz::baz())
1703}
1704
1705fn bar(baz: Baz::Bof) {
1706    ${0:todo!()}
1707}
1708",
1709        )
1710    }
1711
1712    #[test]
1713    fn generate_function_with_generic_param() {
1714        check_assist(
1715            generate_function,
1716            r"
1717fn foo<T, const N: usize>(t: [T; N]) { $0bar(t) }
1718",
1719            r"
1720fn foo<T, const N: usize>(t: [T; N]) { bar(t) }
1721
1722fn bar<T, const N: usize>(t: [T; N]) {
1723    ${0:todo!()}
1724}
1725",
1726        )
1727    }
1728
1729    #[test]
1730    fn generate_function_with_parent_generic_param() {
1731        check_assist(
1732            generate_function,
1733            r"
1734struct S<T>(T);
1735impl<T> S<T> {
1736    fn foo<U>(t: T, u: U) { $0bar(t, u) }
1737}
1738",
1739            r"
1740struct S<T>(T);
1741impl<T> S<T> {
1742    fn foo<U>(t: T, u: U) { bar(t, u) }
1743}
1744
1745fn bar<T, U>(t: T, u: U) {
1746    ${0:todo!()}
1747}
1748",
1749        )
1750    }
1751
1752    #[test]
1753    fn generic_param_in_receiver_type() {
1754        // FIXME: Generic parameter `T` should be part of impl, not method.
1755        check_assist(
1756            generate_function,
1757            r"
1758struct S<T>(T);
1759fn foo<T, U>(s: S<T>, u: U) { s.$0foo(u) }
1760",
1761            r"
1762struct S<T>(T);
1763impl S {
1764    fn foo<T, U>(&self, u: U) {
1765        ${0:todo!()}
1766    }
1767}
1768fn foo<T, U>(s: S<T>, u: U) { s.foo(u) }
1769",
1770        )
1771    }
1772
1773    #[test]
1774    fn generic_param_in_return_type() {
1775        check_assist(
1776            generate_function,
1777            r"
1778fn foo<T, const N: usize>() -> [T; N] { $0bar() }
1779",
1780            r"
1781fn foo<T, const N: usize>() -> [T; N] { bar() }
1782
1783fn bar<T, const N: usize>() -> [T; N] {
1784    ${0:todo!()}
1785}
1786",
1787        )
1788    }
1789
1790    #[test]
1791    fn generate_fn_with_bounds() {
1792        // FIXME: where predicates should be on next lines.
1793        check_assist(
1794            generate_function,
1795            r"
1796trait A<T> {}
1797struct S<T>(T);
1798impl<T: A<i32>> S<T>
1799where
1800    T: A<i64>,
1801{
1802    fn foo<U>(t: T, u: U)
1803    where
1804        T: A<()>,
1805        U: A<i32> + A<i64>,
1806    {
1807        $0bar(t, u)
1808    }
1809}
1810",
1811            r"
1812trait A<T> {}
1813struct S<T>(T);
1814impl<T: A<i32>> S<T>
1815where
1816    T: A<i64>,
1817{
1818    fn foo<U>(t: T, u: U)
1819    where
1820        T: A<()>,
1821        U: A<i32> + A<i64>,
1822    {
1823        bar(t, u)
1824    }
1825}
1826
1827fn bar<T: A<i32>, U>(t: T, u: U) where T: A<i64>, T: A<()>, U: A<i32> + A<i64> {
1828    ${0:todo!()}
1829}
1830",
1831        )
1832    }
1833
1834    #[test]
1835    fn include_transitive_param_dependency() {
1836        // FIXME: where predicates should be on next lines.
1837        check_assist(
1838            generate_function,
1839            r"
1840trait A<T> { type Assoc; }
1841trait B { type Item; }
1842struct S<T>(T);
1843impl<T, U, V: B, W> S<(T, U, V, W)>
1844where
1845    T: A<U, Assoc = V>,
1846    S<V::Item>: A<U, Assoc = W>,
1847{
1848    fn foo<I>(t: T, u: U)
1849    where
1850        U: A<T, Assoc = I>,
1851    {
1852        $0bar(u)
1853    }
1854}
1855",
1856            r"
1857trait A<T> { type Assoc; }
1858trait B { type Item; }
1859struct S<T>(T);
1860impl<T, U, V: B, W> S<(T, U, V, W)>
1861where
1862    T: A<U, Assoc = V>,
1863    S<V::Item>: A<U, Assoc = W>,
1864{
1865    fn foo<I>(t: T, u: U)
1866    where
1867        U: A<T, Assoc = I>,
1868    {
1869        bar(u)
1870    }
1871}
1872
1873fn bar<T, U, V: B, W, I>(u: U) where T: A<U, Assoc = V>, S<V::Item>: A<U, Assoc = W>, U: A<T, Assoc = I> {
1874    ${0:todo!()}
1875}
1876",
1877        )
1878    }
1879
1880    #[test]
1881    fn irrelevant_bounds_are_filtered_out() {
1882        check_assist(
1883            generate_function,
1884            r"
1885trait A<T> {}
1886struct S<T>(T);
1887impl<T, U, V, W> S<(T, U, V, W)>
1888where
1889    T: A<U>,
1890    V: A<W>,
1891{
1892    fn foo<I>(t: T, u: U)
1893    where
1894        U: A<T> + A<I>,
1895    {
1896        $0bar(u)
1897    }
1898}
1899",
1900            r"
1901trait A<T> {}
1902struct S<T>(T);
1903impl<T, U, V, W> S<(T, U, V, W)>
1904where
1905    T: A<U>,
1906    V: A<W>,
1907{
1908    fn foo<I>(t: T, u: U)
1909    where
1910        U: A<T> + A<I>,
1911    {
1912        bar(u)
1913    }
1914}
1915
1916fn bar<T, U, I>(u: U) where T: A<U>, U: A<T> + A<I> {
1917    ${0:todo!()}
1918}
1919",
1920        )
1921    }
1922
1923    #[test]
1924    fn params_in_trait_arg_are_not_dependency() {
1925        // Even though `bar` depends on `U` and `I`, we don't have to copy these bounds:
1926        // `T: A<I>` and `T: A<U>`.
1927        check_assist(
1928            generate_function,
1929            r"
1930trait A<T> {}
1931struct S<T>(T);
1932impl<T, U> S<(T, U)>
1933where
1934    T: A<U>,
1935{
1936    fn foo<I>(t: T, u: U)
1937    where
1938        T: A<I>,
1939        U: A<I>,
1940    {
1941        $0bar(u)
1942    }
1943}
1944",
1945            r"
1946trait A<T> {}
1947struct S<T>(T);
1948impl<T, U> S<(T, U)>
1949where
1950    T: A<U>,
1951{
1952    fn foo<I>(t: T, u: U)
1953    where
1954        T: A<I>,
1955        U: A<I>,
1956    {
1957        bar(u)
1958    }
1959}
1960
1961fn bar<U, I>(u: U) where U: A<I> {
1962    ${0:todo!()}
1963}
1964",
1965        )
1966    }
1967
1968    #[test]
1969    fn dont_copy_bounds_already_in_scope() {
1970        check_assist(
1971            generate_function,
1972            r"
1973trait A<T> {}
1974struct S<T>(T);
1975impl<T: A<i32>> S<T>
1976where
1977    T: A<usize>,
1978{
1979    fn foo<U: A<()>>(t: T, u: U)
1980    where
1981        T: A<S<i32>>,
1982    {
1983        Self::$0bar(t, u);
1984    }
1985}
1986",
1987            r"
1988trait A<T> {}
1989struct S<T>(T);
1990impl<T: A<i32>> S<T>
1991where
1992    T: A<usize>,
1993{
1994    fn foo<U: A<()>>(t: T, u: U)
1995    where
1996        T: A<S<i32>>,
1997    {
1998        Self::bar(t, u);
1999    }
2000
2001    fn bar<U: A<()>>(t: T, u: U) ${0:-> _} where T: A<S<i32>> {
2002        todo!()
2003    }
2004}
2005",
2006        )
2007    }
2008
2009    #[test]
2010    fn add_function_with_fn_arg() {
2011        check_assist(
2012            generate_function,
2013            r"
2014struct Baz;
2015impl Baz {
2016    fn new() -> Self { Baz }
2017}
2018fn foo() {
2019    $0bar(Baz::new);
2020}
2021",
2022            r"
2023struct Baz;
2024impl Baz {
2025    fn new() -> Self { Baz }
2026}
2027fn foo() {
2028    bar(Baz::new);
2029}
2030
2031fn bar(new: fn() -> Baz) ${0:-> _} {
2032    todo!()
2033}
2034",
2035        )
2036    }
2037
2038    #[test]
2039    fn add_function_with_closure_arg() {
2040        check_assist(
2041            generate_function,
2042            r"
2043fn foo() {
2044    let closure = |x: i64| x - 1;
2045    $0bar(closure)
2046}
2047",
2048            r"
2049fn foo() {
2050    let closure = |x: i64| x - 1;
2051    bar(closure)
2052}
2053
2054fn bar(closure: impl Fn(i64) -> i64) {
2055    ${0:todo!()}
2056}
2057",
2058        )
2059    }
2060
2061    #[test]
2062    fn unresolvable_types_default_to_placeholder() {
2063        check_assist(
2064            generate_function,
2065            r"
2066fn foo() {
2067    $0bar(baz)
2068}
2069",
2070            r"
2071fn foo() {
2072    bar(baz)
2073}
2074
2075fn bar(baz: _) {
2076    ${0:todo!()}
2077}
2078",
2079        )
2080    }
2081
2082    #[test]
2083    fn arg_names_dont_overlap() {
2084        check_assist(
2085            generate_function,
2086            r"
2087struct Baz;
2088fn baz() -> Baz { Baz }
2089fn foo() {
2090    $0bar(baz(), baz())
2091}
2092",
2093            r"
2094struct Baz;
2095fn baz() -> Baz { Baz }
2096fn foo() {
2097    bar(baz(), baz())
2098}
2099
2100fn bar(baz_1: Baz, baz_2: Baz) {
2101    ${0:todo!()}
2102}
2103",
2104        )
2105    }
2106
2107    #[test]
2108    fn arg_name_counters_start_at_1_per_name() {
2109        check_assist(
2110            generate_function,
2111            r#"
2112struct Baz;
2113fn baz() -> Baz { Baz }
2114fn foo() {
2115    $0bar(baz(), baz(), "foo", "bar")
2116}
2117"#,
2118            r#"
2119struct Baz;
2120fn baz() -> Baz { Baz }
2121fn foo() {
2122    bar(baz(), baz(), "foo", "bar")
2123}
2124
2125fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) {
2126    ${0:todo!()}
2127}
2128"#,
2129        )
2130    }
2131
2132    #[test]
2133    fn add_function_in_module() {
2134        check_assist(
2135            generate_function,
2136            r"
2137mod bar {}
2138
2139fn foo() {
2140    bar::my_fn$0()
2141}
2142",
2143            r"
2144mod bar {
2145    pub(crate) fn my_fn() {
2146        ${0:todo!()}
2147    }
2148}
2149
2150fn foo() {
2151    bar::my_fn()
2152}
2153",
2154        )
2155    }
2156
2157    #[test]
2158    fn qualified_path_uses_correct_scope() {
2159        check_assist(
2160            generate_function,
2161            r#"
2162mod foo {
2163    pub struct Foo;
2164}
2165fn bar() {
2166    use foo::Foo;
2167    let foo = Foo;
2168    baz$0(foo)
2169}
2170"#,
2171            r#"
2172mod foo {
2173    pub struct Foo;
2174}
2175fn bar() {
2176    use foo::Foo;
2177    let foo = Foo;
2178    baz(foo)
2179}
2180
2181fn baz(foo: foo::Foo) {
2182    ${0:todo!()}
2183}
2184"#,
2185        )
2186    }
2187
2188    #[test]
2189    fn qualified_path_in_generic_bounds_uses_correct_scope() {
2190        check_assist(
2191            generate_function,
2192            r"
2193mod a {
2194    pub trait A {};
2195}
2196pub mod b {
2197    pub struct S<T>(T);
2198}
2199struct S<T>(T);
2200impl<T> S<T>
2201where
2202    T: a::A,
2203{
2204    fn foo<U: a::A>(t: b::S<T>, u: S<U>) {
2205        a::$0bar(t, u);
2206    }
2207}
2208",
2209            r"
2210mod a {
2211    pub trait A {}
2212
2213    pub(crate) fn bar<T, U: self::A>(t: crate::b::S<T>, u: crate::S<U>) ${0:-> _} where T: self::A {
2214        todo!()
2215    };
2216}
2217pub mod b {
2218    pub struct S<T>(T);
2219}
2220struct S<T>(T);
2221impl<T> S<T>
2222where
2223    T: a::A,
2224{
2225    fn foo<U: a::A>(t: b::S<T>, u: S<U>) {
2226        a::bar(t, u);
2227    }
2228}
2229",
2230        )
2231    }
2232    #[test]
2233    fn add_function_in_module_containing_other_items() {
2234        check_assist(
2235            generate_function,
2236            r"
2237mod bar {
2238    fn something_else() {}
2239}
2240
2241fn foo() {
2242    bar::my_fn$0()
2243}
2244",
2245            r"
2246mod bar {
2247    fn something_else() {}
2248
2249    pub(crate) fn my_fn() {
2250        ${0:todo!()}
2251    }
2252}
2253
2254fn foo() {
2255    bar::my_fn()
2256}
2257",
2258        )
2259    }
2260
2261    #[test]
2262    fn add_function_in_nested_module() {
2263        check_assist(
2264            generate_function,
2265            r"
2266mod bar {
2267    pub mod baz {}
2268}
2269
2270fn foo() {
2271    bar::baz::my_fn$0()
2272}
2273",
2274            r"
2275mod bar {
2276    pub mod baz {
2277        pub(crate) fn my_fn() {
2278            ${0:todo!()}
2279        }
2280    }
2281}
2282
2283fn foo() {
2284    bar::baz::my_fn()
2285}
2286",
2287        )
2288    }
2289
2290    #[test]
2291    fn add_function_in_another_file() {
2292        check_assist(
2293            generate_function,
2294            r"
2295//- /main.rs
2296mod foo;
2297
2298fn main() {
2299    foo::bar$0()
2300}
2301//- /foo.rs
2302",
2303            r"
2304
2305
2306pub(crate) fn bar() {
2307    ${0:todo!()}
2308}",
2309        )
2310    }
2311
2312    #[test]
2313    fn add_function_with_return_type() {
2314        check_assist(
2315            generate_function,
2316            r"
2317fn main() {
2318    let x: u32 = foo$0();
2319}
2320",
2321            r"
2322fn main() {
2323    let x: u32 = foo();
2324}
2325
2326fn foo() -> u32 {
2327    ${0:todo!()}
2328}
2329",
2330        )
2331    }
2332
2333    #[test]
2334    fn add_function_not_applicable_if_function_already_exists() {
2335        check_assist_not_applicable(
2336            generate_function,
2337            r"
2338fn foo() {
2339    bar$0();
2340}
2341
2342fn bar() {}
2343",
2344        )
2345    }
2346
2347    #[test]
2348    fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
2349        check_assist_not_applicable(
2350            // bar is resolved, but baz isn't.
2351            // The assist is only active if the cursor is on an unresolved path,
2352            // but the assist should only be offered if the path is a function call.
2353            generate_function,
2354            r#"
2355fn foo() {
2356    bar(b$0az);
2357}
2358
2359fn bar(baz: ()) {}
2360"#,
2361        )
2362    }
2363
2364    #[test]
2365    fn create_method_with_no_args() {
2366        check_assist(
2367            generate_function,
2368            r#"
2369struct Foo;
2370impl Foo {
2371    fn foo(&self) {
2372        self.bar()$0;
2373    }
2374}
2375"#,
2376            r#"
2377struct Foo;
2378impl Foo {
2379    fn foo(&self) {
2380        self.bar();
2381    }
2382
2383    fn bar(&self) ${0:-> _} {
2384        todo!()
2385    }
2386}
2387"#,
2388        )
2389    }
2390
2391    #[test]
2392    fn create_function_with_async() {
2393        check_assist(
2394            generate_function,
2395            r"
2396async fn foo() {
2397    $0bar(42).await;
2398}
2399",
2400            r"
2401async fn foo() {
2402    bar(42).await;
2403}
2404
2405async fn bar(arg: i32) ${0:-> _} {
2406    todo!()
2407}
2408",
2409        )
2410    }
2411
2412    #[test]
2413    fn return_type_for_async_fn() {
2414        check_assist(
2415            generate_function,
2416            r"
2417//- minicore: result
2418async fn foo() {
2419    if Err(()) = $0bar(42).await {}
2420}
2421",
2422            r"
2423async fn foo() {
2424    if Err(()) = bar(42).await {}
2425}
2426
2427async fn bar(arg: i32) -> Result<_, ()> {
2428    ${0:todo!()}
2429}
2430",
2431        );
2432    }
2433
2434    #[test]
2435    fn create_method() {
2436        check_assist(
2437            generate_function,
2438            r"
2439struct S;
2440fn foo() {S.bar$0();}
2441",
2442            r"
2443struct S;
2444impl S {
2445    fn bar(&self) ${0:-> _} {
2446        todo!()
2447    }
2448}
2449fn foo() {S.bar();}
2450",
2451        )
2452    }
2453
2454    #[test]
2455    fn create_method_within_an_impl() {
2456        check_assist(
2457            generate_function,
2458            r"
2459struct S;
2460fn foo() {S.bar$0();}
2461impl S {}
2462
2463",
2464            r"
2465struct S;
2466fn foo() {S.bar();}
2467impl S {
2468    fn bar(&self) ${0:-> _} {
2469        todo!()
2470    }
2471}
2472
2473",
2474        )
2475    }
2476
2477    #[test]
2478    fn create_method_from_different_module() {
2479        check_assist(
2480            generate_function,
2481            r"
2482mod s {
2483    pub struct S;
2484}
2485fn foo() {s::S.bar$0();}
2486",
2487            r"
2488mod s {
2489    pub struct S;
2490    impl S {
2491        pub(crate) fn bar(&self) ${0:-> _} {
2492            todo!()
2493        }
2494    }
2495}
2496fn foo() {s::S.bar();}
2497",
2498        )
2499    }
2500
2501    #[test]
2502    fn create_method_from_descendant_module() {
2503        check_assist(
2504            generate_function,
2505            r"
2506struct S;
2507mod s {
2508    fn foo() {
2509        super::S.bar$0();
2510    }
2511}
2512
2513",
2514            r"
2515struct S;
2516impl S {
2517    fn bar(&self) ${0:-> _} {
2518        todo!()
2519    }
2520}
2521mod s {
2522    fn foo() {
2523        super::S.bar();
2524    }
2525}
2526
2527",
2528        )
2529    }
2530
2531    #[test]
2532    fn create_method_with_cursor_anywhere_on_call_expression() {
2533        check_assist(
2534            generate_function,
2535            r"
2536struct S;
2537fn foo() {$0S.bar();}
2538",
2539            r"
2540struct S;
2541impl S {
2542    fn bar(&self) ${0:-> _} {
2543        todo!()
2544    }
2545}
2546fn foo() {S.bar();}
2547",
2548        )
2549    }
2550
2551    #[test]
2552    fn create_async_method() {
2553        check_assist(
2554            generate_function,
2555            r"
2556//- minicore: result
2557struct S;
2558async fn foo() {
2559    if let Err(()) = S.$0bar(42).await {}
2560}
2561",
2562            r"
2563struct S;
2564impl S {
2565    async fn bar(&self, arg: i32) -> Result<_, ()> {
2566        ${0:todo!()}
2567    }
2568}
2569async fn foo() {
2570    if let Err(()) = S.bar(42).await {}
2571}
2572",
2573        )
2574    }
2575
2576    #[test]
2577    fn create_static_method() {
2578        check_assist(
2579            generate_function,
2580            r"
2581struct S;
2582fn foo() {S::bar$0();}
2583",
2584            r"
2585struct S;
2586impl S {
2587    fn bar() ${0:-> _} {
2588        todo!()
2589    }
2590}
2591fn foo() {S::bar();}
2592",
2593        )
2594    }
2595
2596    #[test]
2597    fn create_async_static_method() {
2598        check_assist(
2599            generate_function,
2600            r"
2601//- minicore: result
2602struct S;
2603async fn foo() {
2604    if let Err(()) = S::$0bar(42).await {}
2605}
2606",
2607            r"
2608struct S;
2609impl S {
2610    async fn bar(arg: i32) -> Result<_, ()> {
2611        ${0:todo!()}
2612    }
2613}
2614async fn foo() {
2615    if let Err(()) = S::bar(42).await {}
2616}
2617",
2618        )
2619    }
2620
2621    #[test]
2622    fn create_generic_static_method() {
2623        check_assist(
2624            generate_function,
2625            r"
2626struct S;
2627fn foo<T, const N: usize>(t: [T; N]) { S::bar$0(t); }
2628",
2629            r"
2630struct S;
2631impl S {
2632    fn bar<T, const N: usize>(t: [T; N]) ${0:-> _} {
2633        todo!()
2634    }
2635}
2636fn foo<T, const N: usize>(t: [T; N]) { S::bar(t); }
2637",
2638        )
2639    }
2640
2641    #[test]
2642    fn create_static_method_within_an_impl() {
2643        check_assist(
2644            generate_function,
2645            r"
2646struct S;
2647fn foo() {S::bar$0();}
2648impl S {}
2649
2650",
2651            r"
2652struct S;
2653fn foo() {S::bar();}
2654impl S {
2655    fn bar() ${0:-> _} {
2656        todo!()
2657    }
2658}
2659
2660",
2661        )
2662    }
2663
2664    #[test]
2665    fn create_static_method_from_different_module() {
2666        check_assist(
2667            generate_function,
2668            r"
2669mod s {
2670    pub struct S;
2671}
2672fn foo() {s::S::bar$0();}
2673",
2674            r"
2675mod s {
2676    pub struct S;
2677    impl S {
2678        pub(crate) fn bar() ${0:-> _} {
2679            todo!()
2680        }
2681    }
2682}
2683fn foo() {s::S::bar();}
2684",
2685        )
2686    }
2687
2688    #[test]
2689    fn create_static_method_with_cursor_anywhere_on_call_expression() {
2690        check_assist(
2691            generate_function,
2692            r"
2693struct S;
2694fn foo() {$0S::bar();}
2695",
2696            r"
2697struct S;
2698impl S {
2699    fn bar() ${0:-> _} {
2700        todo!()
2701    }
2702}
2703fn foo() {S::bar();}
2704",
2705        )
2706    }
2707
2708    #[test]
2709    fn create_static_method_within_an_impl_with_self_syntax() {
2710        check_assist(
2711            generate_function,
2712            r"
2713struct S;
2714impl S {
2715    fn foo(&self) {
2716        Self::bar$0();
2717    }
2718}
2719",
2720            r"
2721struct S;
2722impl S {
2723    fn foo(&self) {
2724        Self::bar();
2725    }
2726
2727    fn bar() ${0:-> _} {
2728        todo!()
2729    }
2730}
2731",
2732        )
2733    }
2734
2735    #[test]
2736    fn no_panic_on_invalid_global_path() {
2737        check_assist(
2738            generate_function,
2739            r"
2740fn main() {
2741    ::foo$0();
2742}
2743",
2744            r"
2745fn main() {
2746    ::foo();
2747}
2748
2749fn foo() ${0:-> _} {
2750    todo!()
2751}
2752",
2753        )
2754    }
2755
2756    #[test]
2757    fn handle_tuple_indexing() {
2758        check_assist(
2759            generate_function,
2760            r"
2761fn main() {
2762    let a = ((),);
2763    foo$0(a.0);
2764}
2765",
2766            r"
2767fn main() {
2768    let a = ((),);
2769    foo(a.0);
2770}
2771
2772fn foo(a: ()) ${0:-> _} {
2773    todo!()
2774}
2775",
2776        )
2777    }
2778
2779    #[test]
2780    fn add_function_with_const_arg() {
2781        check_assist(
2782            generate_function,
2783            r"
2784const VALUE: usize = 0;
2785fn main() {
2786    foo$0(VALUE);
2787}
2788",
2789            r"
2790const VALUE: usize = 0;
2791fn main() {
2792    foo(VALUE);
2793}
2794
2795fn foo(value: usize) ${0:-> _} {
2796    todo!()
2797}
2798",
2799        )
2800    }
2801
2802    #[test]
2803    fn add_function_with_static_arg() {
2804        check_assist(
2805            generate_function,
2806            r"
2807static VALUE: usize = 0;
2808fn main() {
2809    foo$0(VALUE);
2810}
2811",
2812            r"
2813static VALUE: usize = 0;
2814fn main() {
2815    foo(VALUE);
2816}
2817
2818fn foo(value: usize) ${0:-> _} {
2819    todo!()
2820}
2821",
2822        )
2823    }
2824
2825    #[test]
2826    fn add_function_with_static_mut_arg() {
2827        check_assist(
2828            generate_function,
2829            r"
2830static mut VALUE: usize = 0;
2831fn main() {
2832    foo$0(VALUE);
2833}
2834",
2835            r"
2836static mut VALUE: usize = 0;
2837fn main() {
2838    foo(VALUE);
2839}
2840
2841fn foo(value: usize) ${0:-> _} {
2842    todo!()
2843}
2844",
2845        )
2846    }
2847
2848    #[test]
2849    fn not_applicable_for_enum_variant() {
2850        check_assist_not_applicable(
2851            generate_function,
2852            r"
2853enum Foo {}
2854fn main() {
2855    Foo::Bar$0(true)
2856}
2857",
2858        );
2859    }
2860
2861    #[test]
2862    fn applicable_for_enum_method() {
2863        check_assist(
2864            generate_function,
2865            r"
2866enum Foo {}
2867fn main() {
2868    Foo::bar$0();
2869}
2870",
2871            r"
2872enum Foo {}
2873impl Foo {
2874    fn bar() ${0:-> _} {
2875        todo!()
2876    }
2877}
2878fn main() {
2879    Foo::bar();
2880}
2881",
2882        )
2883    }
2884
2885    #[test]
2886    fn applicable_in_different_local_crate() {
2887        check_assist(
2888            generate_function,
2889            r"
2890//- /lib.rs crate:lib new_source_root:local
2891fn dummy() {}
2892//- /main.rs crate:main deps:lib new_source_root:local
2893fn main() {
2894    lib::foo$0();
2895}
2896",
2897            r"
2898fn dummy() {}
2899
2900pub fn foo() ${0:-> _} {
2901    todo!()
2902}
2903",
2904        );
2905    }
2906
2907    #[test]
2908    fn applicable_in_different_local_crate_method() {
2909        check_assist(
2910            generate_function,
2911            r"
2912//- /lib.rs crate:lib new_source_root:local
2913pub struct S;
2914//- /main.rs crate:main deps:lib new_source_root:local
2915fn main() {
2916    lib::S.foo$0();
2917}
2918",
2919            r"
2920pub struct S;
2921impl S {
2922    pub fn foo(&self) ${0:-> _} {
2923        todo!()
2924    }
2925}
2926",
2927        );
2928    }
2929
2930    #[test]
2931    fn not_applicable_in_different_library_crate() {
2932        check_assist_not_applicable(
2933            generate_function,
2934            r"
2935//- /lib.rs crate:lib new_source_root:library
2936fn dummy() {}
2937//- /main.rs crate:main deps:lib new_source_root:local
2938fn main() {
2939    lib::foo$0();
2940}
2941",
2942        );
2943    }
2944
2945    #[test]
2946    fn not_applicable_in_different_library_crate_method() {
2947        check_assist_not_applicable(
2948            generate_function,
2949            r"
2950//- /lib.rs crate:lib new_source_root:library
2951pub struct S;
2952//- /main.rs crate:main deps:lib new_source_root:local
2953fn main() {
2954    lib::S.foo$0();
2955}
2956",
2957        );
2958    }
2959
2960    #[test]
2961    fn new_function_assume_self_type() {
2962        check_assist(
2963            generate_function,
2964            r"
2965pub struct Foo {
2966    field_1: usize,
2967    field_2: String,
2968}
2969
2970fn main() {
2971    let foo = Foo::new$0();
2972}
2973        ",
2974            r"
2975pub struct Foo {
2976    field_1: usize,
2977    field_2: String,
2978}
2979impl Foo {
2980    fn new() -> Self {
2981        ${0:Self { field_1: todo!(), field_2: todo!() }}
2982    }
2983}
2984
2985fn main() {
2986    let foo = Foo::new();
2987}
2988        ",
2989        )
2990    }
2991
2992    #[test]
2993    fn new_function_assume_self_type_for_tuple_struct() {
2994        check_assist(
2995            generate_function,
2996            r"
2997pub struct Foo (usize, String);
2998
2999fn main() {
3000    let foo = Foo::new$0();
3001}
3002        ",
3003            r"
3004pub struct Foo (usize, String);
3005impl Foo {
3006    fn new() -> Self {
3007        ${0:Self(todo!(), todo!())}
3008    }
3009}
3010
3011fn main() {
3012    let foo = Foo::new();
3013}
3014        ",
3015        )
3016    }
3017
3018    #[test]
3019    fn new_function_assume_self_type_for_unit_struct() {
3020        check_assist(
3021            generate_function,
3022            r"
3023pub struct Foo;
3024
3025fn main() {
3026    let foo = Foo::new$0();
3027}
3028        ",
3029            r"
3030pub struct Foo;
3031impl Foo {
3032    fn new() -> Self {
3033        ${0:Self}
3034    }
3035}
3036
3037fn main() {
3038    let foo = Foo::new();
3039}
3040        ",
3041        )
3042    }
3043
3044    #[test]
3045    fn new_function_assume_self_type_for_enum() {
3046        check_assist(
3047            generate_function,
3048            r"
3049pub enum Foo {}
3050
3051fn main() {
3052    let foo = Foo::new$0();
3053}
3054        ",
3055            r"
3056pub enum Foo {}
3057impl Foo {
3058    fn new() -> Self {
3059        ${0:todo!()}
3060    }
3061}
3062
3063fn main() {
3064    let foo = Foo::new();
3065}
3066        ",
3067        )
3068    }
3069
3070    #[test]
3071    fn new_function_assume_self_type_with_args() {
3072        check_assist(
3073            generate_function,
3074            r#"
3075pub struct Foo {
3076    field_1: usize,
3077    field_2: String,
3078}
3079
3080struct Baz;
3081fn baz() -> Baz { Baz }
3082
3083fn main() {
3084    let foo = Foo::new$0(baz(), baz(), "foo", "bar");
3085}
3086        "#,
3087            r#"
3088pub struct Foo {
3089    field_1: usize,
3090    field_2: String,
3091}
3092impl Foo {
3093    fn new(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) -> Self {
3094        ${0:Self { field_1: todo!(), field_2: todo!() }}
3095    }
3096}
3097
3098struct Baz;
3099fn baz() -> Baz { Baz }
3100
3101fn main() {
3102    let foo = Foo::new(baz(), baz(), "foo", "bar");
3103}
3104        "#,
3105        )
3106    }
3107}