1 use hir::{HasSource, HirDisplay, InFile, Module, TypeInfo};
2 use ide_db::{base_db::FileId, helpers::SnippetCap};
3 use rustc_hash::{FxHashMap, FxHashSet};
4 use stdx::to_lower_snake_case;
8 edit::{AstNodeEdit, IndentLevel},
9 make, ArgList, ArgListOwner, AstNode, ModuleItemOwner,
11 SyntaxKind, SyntaxNode, TextSize,
15 utils::useless_type_special_case,
16 utils::{find_struct_impl, render_snippet, Cursor},
17 AssistContext, AssistId, AssistKind, Assists,
21 Func(&'a ast::CallExpr),
22 Method(&'a ast::MethodCallExpr),
25 impl<'a> FuncExpr<'a> {
26 fn arg_list(&self) -> Option<ArgList> {
28 FuncExpr::Func(fn_call) => fn_call.arg_list(),
29 FuncExpr::Method(m_call) => m_call.arg_list(),
33 fn syntax(&self) -> &SyntaxNode {
35 FuncExpr::Func(fn_call) => fn_call.syntax(),
36 FuncExpr::Method(m_call) => m_call.syntax(),
41 // Assist: generate_function
43 // Adds a stub function with a signature matching the function under the cursor.
47 // fn baz() -> Baz { Baz }
56 // fn baz() -> Baz { Baz }
61 // fn bar(arg: &str, baz: Baz) ${0:-> ()} {
66 pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
67 let path_expr: ast::PathExpr = ctx.find_node_at_offset()?;
68 let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?;
70 let path = path_expr.path()?;
71 if ctx.sema.resolve_path(&path).is_some() {
72 // The function call already resolves, no need to add a function
76 let target_module = match path.qualifier() {
77 Some(qualifier) => match ctx.sema.resolve_path(&qualifier) {
78 Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => Some(module),
84 let function_builder = FunctionBuilder::from_call(ctx, &call, &path, target_module)?;
85 let target = call.syntax().text_range();
88 AssistId("generate_function", AssistKind::Generate),
89 format!("Generate `{}` function", function_builder.fn_name),
92 let function_template = function_builder.render();
93 builder.edit_file(function_template.file);
94 let new_fn = function_template.to_string(ctx.config.snippet_cap);
95 match ctx.config.snippet_cap {
96 Some(cap) => builder.insert_snippet(cap, function_template.insert_offset, new_fn),
97 None => builder.insert(function_template.insert_offset, new_fn),
103 pub(crate) fn generate_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
104 let fn_name: ast::NameRef = ctx.find_node_at_offset()?;
105 let call: ast::MethodCallExpr = ctx.find_node_at_offset()?;
106 let ty = ctx.sema.type_of_expr(&call.receiver()?)?.original().strip_references().as_adt()?;
108 let (impl_, file) = match ty {
109 hir::Adt::Struct(strukt) => get_impl(strukt.source(ctx.sema.db)?.syntax(), &fn_name, ctx),
110 hir::Adt::Enum(en) => get_impl(en.source(ctx.sema.db)?.syntax(), &fn_name, ctx),
111 hir::Adt::Union(union) => get_impl(union.source(ctx.sema.db)?.syntax(), &fn_name, ctx),
114 let function_builder = FunctionBuilder::from_method_call(
120 ty.module(ctx.sema.db),
122 let target = call.syntax().text_range();
125 AssistId("generate_method", AssistKind::Generate),
126 format!("Generate `{}` method", function_builder.fn_name),
129 let function_template = function_builder.render();
130 builder.edit_file(function_template.file);
131 let mut new_fn = function_template.to_string(ctx.config.snippet_cap);
133 new_fn = format!("\nimpl {} {{\n {}\n}}", ty.name(ctx.sema.db), new_fn,);
135 match ctx.config.snippet_cap {
136 Some(cap) => builder.insert_snippet(cap, function_template.insert_offset, new_fn),
137 None => builder.insert(function_template.insert_offset, new_fn),
144 adt: InFile<&SyntaxNode>,
145 fn_name: &ast::NameRef,
147 ) -> Option<(Option<ast::Impl>, FileId)> {
148 let file = adt.file_id.original_file(ctx.sema.db);
150 let adt = ast::Adt::cast(adt.clone())?;
151 let r = find_struct_impl(ctx, &adt, fn_name.text().as_str())?;
155 struct FunctionTemplate {
156 insert_offset: TextSize,
159 ret_type: ast::RetType,
160 should_render_snippet: bool,
165 impl FunctionTemplate {
166 fn to_string(&self, cap: Option<SnippetCap>) -> String {
167 let f = match (cap, self.should_render_snippet) {
168 (Some(cap), true) => {
169 render_snippet(cap, self.fn_def.syntax(), Cursor::Replace(self.ret_type.syntax()))
171 _ => self.fn_def.to_string(),
173 format!("{}{}{}", self.leading_ws, f, self.trailing_ws)
177 struct FunctionBuilder {
178 target: GeneratedFunctionTarget,
180 type_params: Option<ast::GenericParamList>,
181 params: ast::ParamList,
182 ret_type: ast::RetType,
183 should_render_snippet: bool,
189 impl FunctionBuilder {
190 /// Prepares a generated function that matches `call`.
191 /// The function is generated in `target_module` or next to `call`
194 call: &ast::CallExpr,
196 target_module: Option<hir::Module>,
198 let mut file = ctx.frange.file_id;
199 let target = match &target_module {
200 Some(target_module) => {
201 let module_source = target_module.definition_source(ctx.db());
202 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?;
206 None => next_space_for_fn_after_call_site(FuncExpr::Func(call))?,
208 let needs_pub = target_module.is_some();
209 let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?;
210 let fn_name = fn_name(path)?;
211 let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Func(call))?;
213 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
214 let is_async = await_expr.is_some();
216 // should_render_snippet intends to express a rough level of confidence about
217 // the correctness of the return type.
219 // If we are able to infer some return type, and that return type is not unit, we
220 // don't want to render the snippet. The assumption here is in this situation the
221 // return type is just as likely to be correct as any other part of the generated
224 // In the case where the return type is inferred as unit it is likely that the
225 // user does in fact intend for this generated function to return some non unit
226 // type, but that the current state of their code doesn't allow that return type
227 // to be accurately inferred.
228 let (ret_ty, should_render_snippet) = {
229 match ctx.sema.type_of_expr(&ast::Expr::CallExpr(call.clone())).map(TypeInfo::original)
231 Some(ty) if ty.is_unknown() || ty.is_unit() => (make::ty_unit(), true),
233 let rendered = ty.display_source_code(ctx.db(), target_module.into());
235 Ok(rendered) => (make::ty(&rendered), false),
236 Err(_) => (make::ty_unit(), true),
239 None => (make::ty_unit(), true),
242 let ret_type = make::ret_type(ret_ty);
250 should_render_snippet,
259 call: &ast::MethodCallExpr,
261 impl_: &Option<ast::Impl>,
263 target_module: Module,
265 // let mut file = ctx.frange.file_id;
266 // let target_module = ctx.sema.scope(call.syntax()).module()?;
267 let target = match impl_ {
268 Some(impl_) => next_space_for_fn_in_impl(&impl_)?,
270 next_space_for_fn_in_module(
272 &target_module.definition_source(ctx.sema.db),
278 let needs_pub = false;
279 let fn_name = make::name(&name.text());
280 let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Method(call))?;
282 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
283 let is_async = await_expr.is_some();
285 // should_render_snippet intends to express a rough level of confidence about
286 // the correctness of the return type.
288 // If we are able to infer some return type, and that return type is not unit, we
289 // don't want to render the snippet. The assumption here is in this situation the
290 // return type is just as likely to be correct as any other part of the generated
293 // In the case where the return type is inferred as unit it is likely that the
294 // user does in fact intend for this generated function to return some non unit
295 // type, but that the current state of their code doesn't allow that return type
296 // to be accurately inferred.
297 let (ret_ty, should_render_snippet) = {
300 .type_of_expr(&ast::Expr::MethodCallExpr(call.clone()))
301 .map(TypeInfo::original)
303 Some(ty) if ty.is_unknown() || ty.is_unit() => (make::ty_unit(), true),
305 let rendered = ty.display_source_code(ctx.db(), target_module.into());
307 Ok(rendered) => (make::ty(&rendered), false),
308 Err(_) => (make::ty_unit(), true),
311 None => (make::ty_unit(), true),
314 let ret_type = make::ret_type(ret_ty);
322 should_render_snippet,
329 fn render(self) -> FunctionTemplate {
330 let placeholder_expr = make::ext::expr_todo();
331 let fn_body = make::block_expr(vec![], Some(placeholder_expr));
332 let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None };
333 let mut fn_def = make::fn_(
345 let insert_offset = match self.target {
346 GeneratedFunctionTarget::BehindItem(it) => {
347 let indent = IndentLevel::from_node(&it);
348 leading_ws = format!("\n\n{}", indent);
349 fn_def = fn_def.indent(indent);
350 trailing_ws = String::new();
351 it.text_range().end()
353 GeneratedFunctionTarget::InEmptyItemList(it) => {
354 let indent = IndentLevel::from_node(&it);
355 leading_ws = format!("\n{}", indent + 1);
356 fn_def = fn_def.indent(indent + 1);
357 trailing_ws = format!("\n{}", indent);
358 it.text_range().start() + TextSize::of('{')
365 ret_type: fn_def.ret_type().unwrap(),
366 should_render_snippet: self.should_render_snippet,
374 enum GeneratedFunctionTarget {
375 BehindItem(SyntaxNode),
376 InEmptyItemList(SyntaxNode),
379 impl GeneratedFunctionTarget {
380 fn syntax(&self) -> &SyntaxNode {
382 GeneratedFunctionTarget::BehindItem(it) => it,
383 GeneratedFunctionTarget::InEmptyItemList(it) => it,
388 fn fn_name(call: &ast::Path) -> Option<ast::Name> {
389 let name = call.segment()?.syntax().to_string();
390 Some(make::name(&name))
393 /// Computes the type variables and arguments required for the generated function
396 target_module: hir::Module,
398 ) -> Option<(Option<ast::GenericParamList>, ast::ParamList)> {
399 let mut arg_names = Vec::new();
400 let mut arg_types = Vec::new();
401 for arg in call.arg_list()?.args() {
402 arg_names.push(match fn_arg_name(&arg) {
404 None => String::from("arg"),
406 arg_types.push(match fn_arg_type(ctx, target_module, &arg) {
408 if ty.len() > 0 && ty.starts_with('&') {
409 if let Some((new_ty, _)) = useless_type_special_case("", &ty[1..].to_owned()) {
418 None => String::from("()"),
421 deduplicate_arg_names(&mut arg_names);
422 let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| {
423 make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty))
430 FuncExpr::Func(_) => None,
431 FuncExpr::Method(_) => Some(make::self_param()),
438 /// Makes duplicate argument names unique by appending incrementing numbers.
441 /// let mut names: Vec<String> =
442 /// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
443 /// deduplicate_arg_names(&mut names);
444 /// let expected: Vec<String> =
445 /// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
446 /// assert_eq!(names, expected);
448 fn deduplicate_arg_names(arg_names: &mut Vec<String>) {
449 let arg_name_counts = arg_names.iter().fold(FxHashMap::default(), |mut m, name| {
450 *m.entry(name).or_insert(0) += 1;
453 let duplicate_arg_names: FxHashSet<String> = arg_name_counts
455 .filter(|(_, count)| *count >= 2)
456 .map(|(name, _)| name.clone())
459 let mut counter_per_name = FxHashMap::default();
460 for arg_name in arg_names.iter_mut() {
461 if duplicate_arg_names.contains(arg_name) {
462 let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
464 arg_name.push_str(&counter.to_string());
470 fn fn_arg_name(fn_arg: &ast::Expr) -> Option<String> {
472 ast::Expr::CastExpr(cast_expr) => fn_arg_name(&cast_expr.expr()?),
477 .filter(|d| ast::NameRef::can_cast(d.kind()))
480 Some(to_lower_snake_case(&s))
487 target_module: hir::Module,
489 ) -> Option<String> {
490 let ty = ctx.sema.type_of_expr(fn_arg)?.adjusted();
495 if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) {
502 /// Returns the position inside the current mod or file
503 /// directly after the current block
504 /// We want to write the generated function directly after
505 /// fns, impls or macro calls, but inside mods
506 fn next_space_for_fn_after_call_site(expr: FuncExpr) -> Option<GeneratedFunctionTarget> {
507 let mut ancestors = expr.syntax().ancestors().peekable();
508 let mut last_ancestor: Option<SyntaxNode> = None;
509 while let Some(next_ancestor) = ancestors.next() {
510 match next_ancestor.kind() {
511 SyntaxKind::SOURCE_FILE => {
514 SyntaxKind::ITEM_LIST => {
515 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
521 last_ancestor = Some(next_ancestor);
523 last_ancestor.map(GeneratedFunctionTarget::BehindItem)
526 fn next_space_for_fn_in_module(
527 db: &dyn hir::db::AstDatabase,
528 module_source: &hir::InFile<hir::ModuleSource>,
529 ) -> Option<(FileId, GeneratedFunctionTarget)> {
530 let file = module_source.file_id.original_file(db);
531 let assist_item = match &module_source.value {
532 hir::ModuleSource::SourceFile(it) => {
533 if let Some(last_item) = it.items().last() {
534 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
536 GeneratedFunctionTarget::BehindItem(it.syntax().clone())
539 hir::ModuleSource::Module(it) => {
540 if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
541 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
543 GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone())
546 hir::ModuleSource::BlockExpr(it) => {
547 if let Some(last_item) =
548 it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
550 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
552 GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone())
556 Some((file, assist_item))
559 fn next_space_for_fn_in_impl(impl_: &ast::Impl) -> Option<GeneratedFunctionTarget> {
560 if let Some(last_item) = impl_.assoc_item_list().and_then(|it| it.assoc_items().last()) {
561 Some(GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()))
563 Some(GeneratedFunctionTarget::InEmptyItemList(impl_.assoc_item_list()?.syntax().clone()))
569 use crate::tests::{check_assist, check_assist_not_applicable};
574 fn add_function_with_no_args() {
587 fn bar() ${0:-> ()} {
595 fn add_function_from_method() {
596 // This ensures that the function is correctly generated
597 // in the next outer mod or file
614 fn bar() ${0:-> ()} {
622 fn add_function_directly_after_current_block() {
623 // The new fn should not be created at the end of the file or module
638 fn bar() ${0:-> ()} {
648 fn add_function_with_no_args_in_same_module() {
664 fn bar() ${0:-> ()} {
673 fn add_function_with_upper_camel_case_arg() {
688 fn bar(baz_baz: BazBaz) ${0:-> ()} {
696 fn add_function_with_upper_camel_case_arg_as_cast() {
702 bar$0(&BazBaz as *const BazBaz);
708 bar(&BazBaz as *const BazBaz);
711 fn bar(baz_baz: *const BazBaz) ${0:-> ()} {
719 fn add_function_with_function_call_arg() {
724 fn baz() -> Baz { todo!() }
731 fn baz() -> Baz { todo!() }
736 fn bar(baz: Baz) ${0:-> ()} {
744 fn add_function_with_method_call_arg() {
750 fn foo(&self) -> Baz {
753 fn baz(&self) -> Baz {
761 fn foo(&self) -> Baz {
764 fn baz(&self) -> Baz {
769 fn bar(baz: Baz) -> Baz {
777 fn add_function_with_string_literal_arg() {
790 fn bar(arg: &str) ${0:-> ()} {
798 fn add_function_with_char_literal_arg() {
811 fn bar(arg: char) ${0:-> ()} {
819 fn add_function_with_int_literal_arg() {
832 fn bar(arg: i32) ${0:-> ()} {
840 fn add_function_with_cast_int_literal_arg() {
853 fn bar(arg: u8) ${0:-> ()} {
861 fn name_of_cast_variable_is_used() {
862 // Ensures that the name of the cast type isn't used
863 // in the generated function signature.
878 fn bar(x: u8) ${0:-> ()} {
886 fn add_function_with_variable_arg() {
901 fn bar(worble: ()) ${0:-> ()} {
909 fn add_function_with_impl_trait_arg() {
914 fn foo() -> impl Foo {
923 fn foo() -> impl Foo {
930 fn bar(foo: impl Foo) ${0:-> ()} {
943 fn baz() -> Baz { todo!() }
951 fn baz() -> Baz { todo!() }
957 fn bar(baz: &Baz) ${0:-> ()} {
965 fn add_function_with_qualified_path_arg() {
971 pub fn baz() -> Bof { Bof }
980 pub fn baz() -> Bof { Bof }
986 fn bar(baz: Baz::Bof) ${0:-> ()} {
994 fn add_function_with_generic_arg() {
995 // FIXME: This is wrong, generated `bar` should include generic parameter.
1008 fn bar(t: T) ${0:-> ()} {
1016 fn add_function_with_fn_arg() {
1017 // FIXME: The argument in `bar` is wrong.
1023 fn new() -> Self { Baz }
1032 fn new() -> Self { Baz }
1038 fn bar(new: fn) ${0:-> ()} {
1046 fn add_function_with_closure_arg() {
1047 // FIXME: The argument in `bar` is wrong.
1052 let closure = |x: i64| x - 1;
1058 let closure = |x: i64| x - 1;
1062 fn bar(closure: ()) ${0:-> ()} {
1070 fn unresolveable_types_default_to_unit() {
1083 fn bar(baz: ()) ${0:-> ()} {
1091 fn arg_names_dont_overlap() {
1096 fn baz() -> Baz { Baz }
1103 fn baz() -> Baz { Baz }
1108 fn bar(baz_1: Baz, baz_2: Baz) ${0:-> ()} {
1116 fn arg_name_counters_start_at_1_per_name() {
1121 fn baz() -> Baz { Baz }
1123 $0bar(baz(), baz(), "foo", "bar")
1128 fn baz() -> Baz { Baz }
1130 bar(baz(), baz(), "foo", "bar")
1133 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) ${0:-> ()} {
1141 fn add_function_in_module() {
1153 pub(crate) fn my_fn() ${0:-> ()} {
1166 fn qualified_path_uses_correct_scope() {
1189 fn baz(foo: foo::Foo) ${0:-> ()} {
1197 fn add_function_in_module_containing_other_items() {
1202 fn something_else() {}
1211 fn something_else() {}
1213 pub(crate) fn my_fn() ${0:-> ()} {
1226 fn add_function_in_nested_module() {
1241 pub(crate) fn my_fn() ${0:-> ()} {
1255 fn add_function_in_another_file() {
1270 pub(crate) fn bar() ${0:-> ()} {
1277 fn add_function_with_return_type() {
1282 let x: u32 = foo$0();
1298 fn add_function_not_applicable_if_function_already_exists() {
1299 check_assist_not_applicable(
1312 fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1313 check_assist_not_applicable(
1314 // bar is resolved, but baz isn't.
1315 // The assist is only active if the cursor is on an unresolved path,
1316 // but the assist should only be offered if the path is a function call.
1329 fn create_method_with_no_args() {
1330 // FIXME: This is wrong, this should just work.
1331 check_assist_not_applicable(
1345 fn create_function_with_async() {
1358 async fn bar(arg: i32) ${0:-> ()} {