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,
22 Method(ast::MethodCallExpr),
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()?;
109 ctx.sema.scope(ctx.find_node_at_offset::<ast::MethodCallExpr>()?.syntax()).module()?;
110 let target_module = ty.module(ctx.sema.db);
112 if current_module.krate() != target_module.krate() {
116 let (impl_, file) = match ty {
117 hir::Adt::Struct(strukt) => get_impl(strukt.source(ctx.sema.db)?.syntax(), &fn_name, ctx),
118 hir::Adt::Enum(en) => get_impl(en.source(ctx.sema.db)?.syntax(), &fn_name, ctx),
119 hir::Adt::Union(union) => get_impl(union.source(ctx.sema.db)?.syntax(), &fn_name, ctx),
122 let function_builder = FunctionBuilder::from_method_call(
131 let target = call.syntax().text_range();
134 AssistId("generate_function", AssistKind::Generate),
135 format!("Generate `{}` function", function_builder.fn_name),
138 let function_template = function_builder.render();
139 builder.edit_file(function_template.file);
140 let mut new_fn = function_template.to_string(ctx.config.snippet_cap);
142 new_fn = format!("\nimpl {} {{\n {}\n}}", ty.name(ctx.sema.db), new_fn,);
144 match ctx.config.snippet_cap {
145 Some(cap) => builder.insert_snippet(cap, function_template.insert_offset, new_fn),
146 None => builder.insert(function_template.insert_offset, new_fn),
153 adt: InFile<&SyntaxNode>,
154 fn_name: &ast::NameRef,
156 ) -> Option<(Option<ast::Impl>, FileId)> {
157 let file = adt.file_id.original_file(ctx.sema.db);
159 let adt = ast::Adt::cast(adt.clone())?;
160 let r = find_struct_impl(ctx, &adt, fn_name.text().as_str())?;
164 struct FunctionTemplate {
165 insert_offset: TextSize,
168 ret_type: ast::RetType,
169 should_render_snippet: bool,
174 impl FunctionTemplate {
175 fn to_string(&self, cap: Option<SnippetCap>) -> String {
176 let f = match (cap, self.should_render_snippet) {
177 (Some(cap), true) => {
178 render_snippet(cap, self.fn_def.syntax(), Cursor::Replace(self.ret_type.syntax()))
180 _ => self.fn_def.to_string(),
182 format!("{}{}{}", self.leading_ws, f, self.trailing_ws)
186 struct FunctionBuilder {
187 target: GeneratedFunctionTarget,
189 type_params: Option<ast::GenericParamList>,
190 params: ast::ParamList,
191 ret_type: ast::RetType,
192 should_render_snippet: bool,
198 impl FunctionBuilder {
199 /// Prepares a generated function that matches `call`.
200 /// The function is generated in `target_module` or next to `call`
203 call: &ast::CallExpr,
205 target_module: Option<hir::Module>,
207 let mut file = ctx.frange.file_id;
208 let target = match &target_module {
209 Some(target_module) => {
210 let module_source = target_module.definition_source(ctx.db());
211 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?;
215 None => next_space_for_fn_after_call_site(FuncExpr::Func(call.clone()))?,
217 let needs_pub = target_module.is_some();
218 let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?;
219 let fn_name = fn_name(path)?;
220 let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Func(call.clone()))?;
222 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
223 let is_async = await_expr.is_some();
225 // should_render_snippet intends to express a rough level of confidence about
226 // the correctness of the return type.
228 // If we are able to infer some return type, and that return type is not unit, we
229 // don't want to render the snippet. The assumption here is in this situation the
230 // return type is just as likely to be correct as any other part of the generated
233 // In the case where the return type is inferred as unit it is likely that the
234 // user does in fact intend for this generated function to return some non unit
235 // type, but that the current state of their code doesn't allow that return type
236 // to be accurately inferred.
237 let (ret_ty, should_render_snippet) = {
238 match ctx.sema.type_of_expr(&ast::Expr::CallExpr(call.clone())).map(TypeInfo::original)
240 Some(ty) if ty.is_unknown() || ty.is_unit() => (make::ty_unit(), true),
242 let rendered = ty.display_source_code(ctx.db(), target_module.into());
244 Ok(rendered) => (make::ty(&rendered), false),
245 Err(_) => (make::ty_unit(), true),
248 None => (make::ty_unit(), true),
251 let ret_type = make::ret_type(ret_ty);
259 should_render_snippet,
268 call: &ast::MethodCallExpr,
270 impl_: &Option<ast::Impl>,
272 target_module: Module,
273 current_module: Module,
275 // let mut file = ctx.frange.file_id;
276 // let target_module = ctx.sema.scope(call.syntax()).module()?;
277 let target = match impl_ {
278 Some(impl_) => next_space_for_fn_in_impl(&impl_)?,
280 next_space_for_fn_in_module(
282 &target_module.definition_source(ctx.sema.db),
287 let needs_pub = !module_is_descendant(¤t_module, &target_module, ctx);
289 let fn_name = make::name(&name.text());
290 let (type_params, params) = fn_args(ctx, target_module, FuncExpr::Method(call.clone()))?;
292 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
293 let is_async = await_expr.is_some();
295 // should_render_snippet intends to express a rough level of confidence about
296 // the correctness of the return type.
298 // If we are able to infer some return type, and that return type is not unit, we
299 // don't want to render the snippet. The assumption here is in this situation the
300 // return type is just as likely to be correct as any other part of the generated
303 // In the case where the return type is inferred as unit it is likely that the
304 // user does in fact intend for this generated function to return some non unit
305 // type, but that the current state of their code doesn't allow that return type
306 // to be accurately inferred.
307 let (ret_ty, should_render_snippet) = {
310 .type_of_expr(&ast::Expr::MethodCallExpr(call.clone()))
311 .map(TypeInfo::original)
313 Some(ty) if ty.is_unknown() || ty.is_unit() => (make::ty_unit(), true),
315 let rendered = ty.display_source_code(ctx.db(), target_module.into());
317 Ok(rendered) => (make::ty(&rendered), false),
318 Err(_) => (make::ty_unit(), true),
321 None => (make::ty_unit(), true),
324 let ret_type = make::ret_type(ret_ty);
332 should_render_snippet,
339 fn render(self) -> FunctionTemplate {
340 let placeholder_expr = make::ext::expr_todo();
341 let fn_body = make::block_expr(vec![], Some(placeholder_expr));
342 let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None };
343 let mut fn_def = make::fn_(
355 let insert_offset = match self.target {
356 GeneratedFunctionTarget::BehindItem(it) => {
357 let indent = IndentLevel::from_node(&it);
358 leading_ws = format!("\n\n{}", indent);
359 fn_def = fn_def.indent(indent);
360 trailing_ws = String::new();
361 it.text_range().end()
363 GeneratedFunctionTarget::InEmptyItemList(it) => {
364 let indent = IndentLevel::from_node(&it);
365 leading_ws = format!("\n{}", indent + 1);
366 fn_def = fn_def.indent(indent + 1);
367 trailing_ws = format!("\n{}", indent);
368 it.text_range().start() + TextSize::of('{')
375 ret_type: fn_def.ret_type().unwrap(),
376 should_render_snippet: self.should_render_snippet,
384 enum GeneratedFunctionTarget {
385 BehindItem(SyntaxNode),
386 InEmptyItemList(SyntaxNode),
389 impl GeneratedFunctionTarget {
390 fn syntax(&self) -> &SyntaxNode {
392 GeneratedFunctionTarget::BehindItem(it) => it,
393 GeneratedFunctionTarget::InEmptyItemList(it) => it,
398 fn fn_name(call: &ast::Path) -> Option<ast::Name> {
399 let name = call.segment()?.syntax().to_string();
400 Some(make::name(&name))
403 /// Computes the type variables and arguments required for the generated function
406 target_module: hir::Module,
408 ) -> Option<(Option<ast::GenericParamList>, ast::ParamList)> {
409 let mut arg_names = Vec::new();
410 let mut arg_types = Vec::new();
411 for arg in call.arg_list()?.args() {
412 arg_names.push(match fn_arg_name(&arg) {
414 None => String::from("arg"),
416 arg_types.push(match fn_arg_type(ctx, target_module, &arg) {
418 if ty.len() > 0 && ty.starts_with('&') {
419 if let Some((new_ty, _)) = useless_type_special_case("", &ty[1..].to_owned()) {
428 None => String::from("()"),
431 deduplicate_arg_names(&mut arg_names);
432 let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| {
433 make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty))
440 FuncExpr::Func(_) => None,
441 FuncExpr::Method(_) => Some(make::self_param()),
448 /// Makes duplicate argument names unique by appending incrementing numbers.
451 /// let mut names: Vec<String> =
452 /// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
453 /// deduplicate_arg_names(&mut names);
454 /// let expected: Vec<String> =
455 /// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
456 /// assert_eq!(names, expected);
458 fn deduplicate_arg_names(arg_names: &mut Vec<String>) {
459 let arg_name_counts = arg_names.iter().fold(FxHashMap::default(), |mut m, name| {
460 *m.entry(name).or_insert(0) += 1;
463 let duplicate_arg_names: FxHashSet<String> = arg_name_counts
465 .filter(|(_, count)| *count >= 2)
466 .map(|(name, _)| name.clone())
469 let mut counter_per_name = FxHashMap::default();
470 for arg_name in arg_names.iter_mut() {
471 if duplicate_arg_names.contains(arg_name) {
472 let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
474 arg_name.push_str(&counter.to_string());
480 fn fn_arg_name(fn_arg: &ast::Expr) -> Option<String> {
482 ast::Expr::CastExpr(cast_expr) => fn_arg_name(&cast_expr.expr()?),
487 .filter(|d| ast::NameRef::can_cast(d.kind()))
490 Some(to_lower_snake_case(&s))
497 target_module: hir::Module,
499 ) -> Option<String> {
500 let ty = ctx.sema.type_of_expr(fn_arg)?.adjusted();
505 if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) {
512 /// Returns the position inside the current mod or file
513 /// directly after the current block
514 /// We want to write the generated function directly after
515 /// fns, impls or macro calls, but inside mods
516 fn next_space_for_fn_after_call_site(expr: FuncExpr) -> Option<GeneratedFunctionTarget> {
517 let mut ancestors = expr.syntax().ancestors().peekable();
518 let mut last_ancestor: Option<SyntaxNode> = None;
519 while let Some(next_ancestor) = ancestors.next() {
520 match next_ancestor.kind() {
521 SyntaxKind::SOURCE_FILE => {
524 SyntaxKind::ITEM_LIST => {
525 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
531 last_ancestor = Some(next_ancestor);
533 last_ancestor.map(GeneratedFunctionTarget::BehindItem)
536 fn next_space_for_fn_in_module(
537 db: &dyn hir::db::AstDatabase,
538 module_source: &hir::InFile<hir::ModuleSource>,
539 ) -> Option<(FileId, GeneratedFunctionTarget)> {
540 let file = module_source.file_id.original_file(db);
541 let assist_item = match &module_source.value {
542 hir::ModuleSource::SourceFile(it) => {
543 if let Some(last_item) = it.items().last() {
544 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
546 GeneratedFunctionTarget::BehindItem(it.syntax().clone())
549 hir::ModuleSource::Module(it) => {
550 if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
551 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
553 GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone())
556 hir::ModuleSource::BlockExpr(it) => {
557 if let Some(last_item) =
558 it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
560 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
562 GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone())
566 Some((file, assist_item))
569 fn next_space_for_fn_in_impl(impl_: &ast::Impl) -> Option<GeneratedFunctionTarget> {
570 if let Some(last_item) = impl_.assoc_item_list().and_then(|it| it.assoc_items().last()) {
571 Some(GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()))
573 Some(GeneratedFunctionTarget::InEmptyItemList(impl_.assoc_item_list()?.syntax().clone()))
577 fn module_is_descendant(module: &hir::Module, ans: &hir::Module, ctx: &AssistContext) -> bool {
581 for c in ans.children(ctx.sema.db) {
582 if module_is_descendant(module, &c, ctx) {
591 use crate::tests::{check_assist, check_assist_not_applicable};
596 fn add_function_with_no_args() {
609 fn bar() ${0:-> ()} {
617 fn add_function_from_method() {
618 // This ensures that the function is correctly generated
619 // in the next outer mod or file
636 fn bar() ${0:-> ()} {
644 fn add_function_directly_after_current_block() {
645 // The new fn should not be created at the end of the file or module
660 fn bar() ${0:-> ()} {
670 fn add_function_with_no_args_in_same_module() {
686 fn bar() ${0:-> ()} {
695 fn add_function_with_upper_camel_case_arg() {
710 fn bar(baz_baz: BazBaz) ${0:-> ()} {
718 fn add_function_with_upper_camel_case_arg_as_cast() {
724 bar$0(&BazBaz as *const BazBaz);
730 bar(&BazBaz as *const BazBaz);
733 fn bar(baz_baz: *const BazBaz) ${0:-> ()} {
741 fn add_function_with_function_call_arg() {
746 fn baz() -> Baz { todo!() }
753 fn baz() -> Baz { todo!() }
758 fn bar(baz: Baz) ${0:-> ()} {
766 fn add_function_with_method_call_arg() {
772 fn foo(&self) -> Baz {
775 fn baz(&self) -> Baz {
783 fn foo(&self) -> Baz {
786 fn baz(&self) -> Baz {
791 fn bar(baz: Baz) -> Baz {
799 fn add_function_with_string_literal_arg() {
812 fn bar(arg: &str) ${0:-> ()} {
820 fn add_function_with_char_literal_arg() {
833 fn bar(arg: char) ${0:-> ()} {
841 fn add_function_with_int_literal_arg() {
854 fn bar(arg: i32) ${0:-> ()} {
862 fn add_function_with_cast_int_literal_arg() {
875 fn bar(arg: u8) ${0:-> ()} {
883 fn name_of_cast_variable_is_used() {
884 // Ensures that the name of the cast type isn't used
885 // in the generated function signature.
900 fn bar(x: u8) ${0:-> ()} {
908 fn add_function_with_variable_arg() {
923 fn bar(worble: ()) ${0:-> ()} {
931 fn add_function_with_impl_trait_arg() {
936 fn foo() -> impl Foo {
945 fn foo() -> impl Foo {
952 fn bar(foo: impl Foo) ${0:-> ()} {
965 fn baz() -> Baz { todo!() }
973 fn baz() -> Baz { todo!() }
979 fn bar(baz: &Baz) ${0:-> ()} {
987 fn add_function_with_qualified_path_arg() {
993 pub fn baz() -> Bof { Bof }
1002 pub fn baz() -> Bof { Bof }
1008 fn bar(baz: Baz::Bof) ${0:-> ()} {
1016 fn add_function_with_generic_arg() {
1017 // FIXME: This is wrong, generated `bar` should include generic parameter.
1030 fn bar(t: T) ${0:-> ()} {
1038 fn add_function_with_fn_arg() {
1039 // FIXME: The argument in `bar` is wrong.
1045 fn new() -> Self { Baz }
1054 fn new() -> Self { Baz }
1060 fn bar(new: fn) ${0:-> ()} {
1068 fn add_function_with_closure_arg() {
1069 // FIXME: The argument in `bar` is wrong.
1074 let closure = |x: i64| x - 1;
1080 let closure = |x: i64| x - 1;
1084 fn bar(closure: ()) ${0:-> ()} {
1092 fn unresolveable_types_default_to_unit() {
1105 fn bar(baz: ()) ${0:-> ()} {
1113 fn arg_names_dont_overlap() {
1118 fn baz() -> Baz { Baz }
1125 fn baz() -> Baz { Baz }
1130 fn bar(baz_1: Baz, baz_2: Baz) ${0:-> ()} {
1138 fn arg_name_counters_start_at_1_per_name() {
1143 fn baz() -> Baz { Baz }
1145 $0bar(baz(), baz(), "foo", "bar")
1150 fn baz() -> Baz { Baz }
1152 bar(baz(), baz(), "foo", "bar")
1155 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) ${0:-> ()} {
1163 fn add_function_in_module() {
1175 pub(crate) fn my_fn() ${0:-> ()} {
1188 fn qualified_path_uses_correct_scope() {
1211 fn baz(foo: foo::Foo) ${0:-> ()} {
1219 fn add_function_in_module_containing_other_items() {
1224 fn something_else() {}
1233 fn something_else() {}
1235 pub(crate) fn my_fn() ${0:-> ()} {
1248 fn add_function_in_nested_module() {
1263 pub(crate) fn my_fn() ${0:-> ()} {
1277 fn add_function_in_another_file() {
1292 pub(crate) fn bar() ${0:-> ()} {
1299 fn add_function_with_return_type() {
1304 let x: u32 = foo$0();
1320 fn add_function_not_applicable_if_function_already_exists() {
1321 check_assist_not_applicable(
1334 fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1335 check_assist_not_applicable(
1336 // bar is resolved, but baz isn't.
1337 // The assist is only active if the cursor is on an unresolved path,
1338 // but the assist should only be offered if the path is a function call.
1351 fn create_method_with_no_args() {
1352 // FIXME: This is wrong, this should just work.
1353 check_assist_not_applicable(
1367 fn create_function_with_async() {
1380 async fn bar(arg: i32) ${0:-> ()} {