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