1 use hir::{HirDisplay, 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, ArgListOwner, AstNode, ModuleItemOwner,
11 SyntaxKind, SyntaxNode, TextSize,
15 utils::useless_type_special_case,
16 utils::{render_snippet, Cursor},
17 AssistContext, AssistId, AssistKind, Assists,
20 // Assist: generate_function
22 // Adds a stub function with a signature matching the function under the cursor.
26 // fn baz() -> Baz { Baz }
35 // fn baz() -> Baz { Baz }
40 // fn bar(arg: &str, baz: Baz) ${0:-> ()} {
45 pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
46 let path_expr: ast::PathExpr = ctx.find_node_at_offset()?;
47 let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?;
49 let path = path_expr.path()?;
50 if ctx.sema.resolve_path(&path).is_some() {
51 // The function call already resolves, no need to add a function
55 let target_module = match path.qualifier() {
56 Some(qualifier) => match ctx.sema.resolve_path(&qualifier) {
57 Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => Some(module),
63 let function_builder = FunctionBuilder::from_call(ctx, &call, &path, target_module)?;
64 let target = call.syntax().text_range();
67 AssistId("generate_function", AssistKind::Generate),
68 format!("Generate `{}` function", function_builder.fn_name),
71 let function_template = function_builder.render();
72 builder.edit_file(function_template.file);
73 let new_fn = function_template.to_string(ctx.config.snippet_cap);
74 match ctx.config.snippet_cap {
75 Some(cap) => builder.insert_snippet(cap, function_template.insert_offset, new_fn),
76 None => builder.insert(function_template.insert_offset, new_fn),
82 struct FunctionTemplate {
83 insert_offset: TextSize,
86 ret_type: ast::RetType,
87 should_render_snippet: bool,
92 impl FunctionTemplate {
93 fn to_string(&self, cap: Option<SnippetCap>) -> String {
94 let f = match (cap, self.should_render_snippet) {
95 (Some(cap), true) => {
96 render_snippet(cap, self.fn_def.syntax(), Cursor::Replace(self.ret_type.syntax()))
98 _ => self.fn_def.to_string(),
100 format!("{}{}{}", self.leading_ws, f, self.trailing_ws)
104 struct FunctionBuilder {
105 target: GeneratedFunctionTarget,
107 type_params: Option<ast::GenericParamList>,
108 params: ast::ParamList,
109 ret_type: ast::RetType,
110 should_render_snippet: bool,
116 impl FunctionBuilder {
117 /// Prepares a generated function that matches `call`.
118 /// The function is generated in `target_module` or next to `call`
121 call: &ast::CallExpr,
123 target_module: Option<hir::Module>,
125 let mut file = ctx.frange.file_id;
126 let target = match &target_module {
127 Some(target_module) => {
128 let module_source = target_module.definition_source(ctx.db());
129 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?;
133 None => next_space_for_fn_after_call_site(call)?,
135 let needs_pub = target_module.is_some();
136 let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?;
137 let fn_name = fn_name(path)?;
138 let (type_params, params) = fn_args(ctx, target_module, call)?;
140 let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
141 let is_async = await_expr.is_some();
143 // should_render_snippet intends to express a rough level of confidence about
144 // the correctness of the return type.
146 // If we are able to infer some return type, and that return type is not unit, we
147 // don't want to render the snippet. The assumption here is in this situation the
148 // return type is just as likely to be correct as any other part of the generated
151 // In the case where the return type is inferred as unit it is likely that the
152 // user does in fact intend for this generated function to return some non unit
153 // type, but that the current state of their code doesn't allow that return type
154 // to be accurately inferred.
155 let (ret_ty, should_render_snippet) = {
156 match ctx.sema.type_of_expr(&ast::Expr::CallExpr(call.clone())).map(TypeInfo::original)
158 Some(ty) if ty.is_unknown() || ty.is_unit() => (make::ty_unit(), true),
160 let rendered = ty.display_source_code(ctx.db(), target_module.into());
162 Ok(rendered) => (make::ty(&rendered), false),
163 Err(_) => (make::ty_unit(), true),
166 None => (make::ty_unit(), true),
169 let ret_type = make::ret_type(ret_ty);
177 should_render_snippet,
184 fn render(self) -> FunctionTemplate {
185 let placeholder_expr = make::ext::expr_todo();
186 let fn_body = make::block_expr(vec![], Some(placeholder_expr));
187 let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None };
188 let mut fn_def = make::fn_(
200 let insert_offset = match self.target {
201 GeneratedFunctionTarget::BehindItem(it) => {
202 let indent = IndentLevel::from_node(&it);
203 leading_ws = format!("\n\n{}", indent);
204 fn_def = fn_def.indent(indent);
205 trailing_ws = String::new();
206 it.text_range().end()
208 GeneratedFunctionTarget::InEmptyItemList(it) => {
209 let indent = IndentLevel::from_node(&it);
210 leading_ws = format!("\n{}", indent + 1);
211 fn_def = fn_def.indent(indent + 1);
212 trailing_ws = format!("\n{}", indent);
213 it.text_range().start() + TextSize::of('{')
220 ret_type: fn_def.ret_type().unwrap(),
221 should_render_snippet: self.should_render_snippet,
229 enum GeneratedFunctionTarget {
230 BehindItem(SyntaxNode),
231 InEmptyItemList(SyntaxNode),
234 impl GeneratedFunctionTarget {
235 fn syntax(&self) -> &SyntaxNode {
237 GeneratedFunctionTarget::BehindItem(it) => it,
238 GeneratedFunctionTarget::InEmptyItemList(it) => it,
243 fn fn_name(call: &ast::Path) -> Option<ast::Name> {
244 let name = call.segment()?.syntax().to_string();
245 Some(make::name(&name))
248 /// Computes the type variables and arguments required for the generated function
251 target_module: hir::Module,
252 call: &ast::CallExpr,
253 ) -> Option<(Option<ast::GenericParamList>, ast::ParamList)> {
254 let mut arg_names = Vec::new();
255 let mut arg_types = Vec::new();
256 for arg in call.arg_list()?.args() {
257 arg_names.push(match fn_arg_name(&arg) {
259 None => String::from("arg"),
261 arg_types.push(match fn_arg_type(ctx, target_module, &arg) {
263 if ty.len() > 0 && ty.starts_with('&') {
264 if let Some((new_ty, _)) = useless_type_special_case("", &ty[1..].to_owned()) {
273 None => String::from("()"),
276 deduplicate_arg_names(&mut arg_names);
277 let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| {
278 make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty))
280 Some((None, make::param_list(None, params)))
283 /// Makes duplicate argument names unique by appending incrementing numbers.
286 /// let mut names: Vec<String> =
287 /// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
288 /// deduplicate_arg_names(&mut names);
289 /// let expected: Vec<String> =
290 /// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
291 /// assert_eq!(names, expected);
293 fn deduplicate_arg_names(arg_names: &mut Vec<String>) {
294 let arg_name_counts = arg_names.iter().fold(FxHashMap::default(), |mut m, name| {
295 *m.entry(name).or_insert(0) += 1;
298 let duplicate_arg_names: FxHashSet<String> = arg_name_counts
300 .filter(|(_, count)| *count >= 2)
301 .map(|(name, _)| name.clone())
304 let mut counter_per_name = FxHashMap::default();
305 for arg_name in arg_names.iter_mut() {
306 if duplicate_arg_names.contains(arg_name) {
307 let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
309 arg_name.push_str(&counter.to_string());
315 fn fn_arg_name(fn_arg: &ast::Expr) -> Option<String> {
317 ast::Expr::CastExpr(cast_expr) => fn_arg_name(&cast_expr.expr()?),
322 .filter(|d| ast::NameRef::can_cast(d.kind()))
325 Some(to_lower_snake_case(&s))
332 target_module: hir::Module,
334 ) -> Option<String> {
335 let ty = ctx.sema.type_of_expr(fn_arg)?.adjusted();
340 if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) {
347 /// Returns the position inside the current mod or file
348 /// directly after the current block
349 /// We want to write the generated function directly after
350 /// fns, impls or macro calls, but inside mods
351 fn next_space_for_fn_after_call_site(expr: &ast::CallExpr) -> Option<GeneratedFunctionTarget> {
352 let mut ancestors = expr.syntax().ancestors().peekable();
353 let mut last_ancestor: Option<SyntaxNode> = None;
354 while let Some(next_ancestor) = ancestors.next() {
355 match next_ancestor.kind() {
356 SyntaxKind::SOURCE_FILE => {
359 SyntaxKind::ITEM_LIST => {
360 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
366 last_ancestor = Some(next_ancestor);
368 last_ancestor.map(GeneratedFunctionTarget::BehindItem)
371 fn next_space_for_fn_in_module(
372 db: &dyn hir::db::AstDatabase,
373 module_source: &hir::InFile<hir::ModuleSource>,
374 ) -> Option<(FileId, GeneratedFunctionTarget)> {
375 let file = module_source.file_id.original_file(db);
376 let assist_item = match &module_source.value {
377 hir::ModuleSource::SourceFile(it) => {
378 if let Some(last_item) = it.items().last() {
379 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
381 GeneratedFunctionTarget::BehindItem(it.syntax().clone())
384 hir::ModuleSource::Module(it) => {
385 if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
386 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
388 GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone())
391 hir::ModuleSource::BlockExpr(it) => {
392 if let Some(last_item) =
393 it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
395 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
397 GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone())
401 Some((file, assist_item))
406 use crate::tests::{check_assist, check_assist_not_applicable};
411 fn add_function_with_no_args() {
424 fn bar() ${0:-> ()} {
432 fn add_function_from_method() {
433 // This ensures that the function is correctly generated
434 // in the next outer mod or file
451 fn bar() ${0:-> ()} {
459 fn add_function_directly_after_current_block() {
460 // The new fn should not be created at the end of the file or module
475 fn bar() ${0:-> ()} {
485 fn add_function_with_no_args_in_same_module() {
501 fn bar() ${0:-> ()} {
510 fn add_function_with_upper_camel_case_arg() {
525 fn bar(baz_baz: BazBaz) ${0:-> ()} {
533 fn add_function_with_upper_camel_case_arg_as_cast() {
539 bar$0(&BazBaz as *const BazBaz);
545 bar(&BazBaz as *const BazBaz);
548 fn bar(baz_baz: *const BazBaz) ${0:-> ()} {
556 fn add_function_with_function_call_arg() {
561 fn baz() -> Baz { todo!() }
568 fn baz() -> Baz { todo!() }
573 fn bar(baz: Baz) ${0:-> ()} {
581 fn add_function_with_method_call_arg() {
587 fn foo(&self) -> Baz {
590 fn baz(&self) -> Baz {
598 fn foo(&self) -> Baz {
601 fn baz(&self) -> Baz {
606 fn bar(baz: Baz) -> Baz {
614 fn add_function_with_string_literal_arg() {
627 fn bar(arg: &str) ${0:-> ()} {
635 fn add_function_with_char_literal_arg() {
648 fn bar(arg: char) ${0:-> ()} {
656 fn add_function_with_int_literal_arg() {
669 fn bar(arg: i32) ${0:-> ()} {
677 fn add_function_with_cast_int_literal_arg() {
690 fn bar(arg: u8) ${0:-> ()} {
698 fn name_of_cast_variable_is_used() {
699 // Ensures that the name of the cast type isn't used
700 // in the generated function signature.
715 fn bar(x: u8) ${0:-> ()} {
723 fn add_function_with_variable_arg() {
738 fn bar(worble: ()) ${0:-> ()} {
746 fn add_function_with_impl_trait_arg() {
752 fn foo() -> impl Foo {
761 fn foo() -> impl Foo {
768 fn bar(foo: impl Foo) ${0:-> ()} {
781 fn baz() -> Baz { todo!() }
789 fn baz() -> Baz { todo!() }
795 fn bar(baz: &Baz) ${0:-> ()} {
803 fn add_function_with_qualified_path_arg() {
809 pub fn baz() -> Bof { Bof }
818 pub fn baz() -> Bof { Bof }
824 fn bar(baz: Baz::Bof) ${0:-> ()} {
832 fn add_function_with_generic_arg() {
833 // FIXME: This is wrong, generated `bar` should include generic parameter.
846 fn bar(t: T) ${0:-> ()} {
854 fn add_function_with_fn_arg() {
855 // FIXME: The argument in `bar` is wrong.
861 fn new() -> Self { Baz }
870 fn new() -> Self { Baz }
876 fn bar(new: fn) ${0:-> ()} {
884 fn add_function_with_closure_arg() {
885 // FIXME: The argument in `bar` is wrong.
890 let closure = |x: i64| x - 1;
896 let closure = |x: i64| x - 1;
900 fn bar(closure: ()) ${0:-> ()} {
908 fn unresolveable_types_default_to_unit() {
921 fn bar(baz: ()) ${0:-> ()} {
929 fn arg_names_dont_overlap() {
934 fn baz() -> Baz { Baz }
941 fn baz() -> Baz { Baz }
946 fn bar(baz_1: Baz, baz_2: Baz) ${0:-> ()} {
954 fn arg_name_counters_start_at_1_per_name() {
959 fn baz() -> Baz { Baz }
961 $0bar(baz(), baz(), "foo", "bar")
966 fn baz() -> Baz { Baz }
968 bar(baz(), baz(), "foo", "bar")
971 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) ${0:-> ()} {
979 fn add_function_in_module() {
991 pub(crate) fn my_fn() ${0:-> ()} {
1004 fn qualified_path_uses_correct_scope() {
1027 fn baz(foo: foo::Foo) ${0:-> ()} {
1035 fn add_function_in_module_containing_other_items() {
1040 fn something_else() {}
1049 fn something_else() {}
1051 pub(crate) fn my_fn() ${0:-> ()} {
1064 fn add_function_in_nested_module() {
1079 pub(crate) fn my_fn() ${0:-> ()} {
1093 fn add_function_in_another_file() {
1108 pub(crate) fn bar() ${0:-> ()} {
1115 fn add_function_with_return_type() {
1120 let x: u32 = foo$0();
1136 fn add_function_not_applicable_if_function_already_exists() {
1137 check_assist_not_applicable(
1150 fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1151 check_assist_not_applicable(
1152 // bar is resolved, but baz isn't.
1153 // The assist is only active if the cursor is on an unresolved path,
1154 // but the assist should only be offered if the path is a function call.
1167 fn create_method_with_no_args() {
1168 // FIXME: This is wrong, this should just work.
1169 check_assist_not_applicable(
1183 fn create_function_with_async() {
1196 async fn bar(arg: i32) ${0:-> ()} {