2 use ide_db::{base_db::FileId, helpers::SnippetCap};
3 use rustc_hash::{FxHashMap, FxHashSet};
7 edit::{AstNodeEdit, IndentLevel},
8 make, ArgListOwner, AstNode, ModuleItemOwner,
10 SyntaxKind, SyntaxNode, TextSize,
14 utils::{render_snippet, Cursor},
15 AssistContext, AssistId, AssistKind, Assists,
18 // Assist: generate_function
20 // Adds a stub function with a signature matching the function under the cursor.
24 // fn baz() -> Baz { Baz }
33 // fn baz() -> Baz { Baz }
38 // fn bar(arg: &str, baz: Baz) ${0:-> ()} {
43 pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
44 let path_expr: ast::PathExpr = ctx.find_node_at_offset()?;
45 let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?;
46 let path = path_expr.path()?;
48 if ctx.sema.resolve_path(&path).is_some() {
49 // The function call already resolves, no need to add a function
53 let target_module = match path.qualifier() {
54 Some(qualifier) => match ctx.sema.resolve_path(&qualifier) {
55 Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => Some(module),
61 let function_builder = FunctionBuilder::from_call(&ctx, &call, &path, target_module)?;
63 let target = call.syntax().text_range();
65 AssistId("generate_function", AssistKind::Generate),
66 format!("Generate `{}` function", function_builder.fn_name),
69 let function_template = function_builder.render();
70 builder.edit_file(function_template.file);
71 let new_fn = function_template.to_string(ctx.config.snippet_cap);
72 match ctx.config.snippet_cap {
73 Some(cap) => builder.insert_snippet(cap, function_template.insert_offset, new_fn),
74 None => builder.insert(function_template.insert_offset, new_fn),
80 struct FunctionTemplate {
81 insert_offset: TextSize,
84 ret_type: ast::RetType,
89 impl FunctionTemplate {
90 fn to_string(&self, cap: Option<SnippetCap>) -> String {
93 render_snippet(cap, self.fn_def.syntax(), Cursor::Replace(self.ret_type.syntax()))
95 None => self.fn_def.to_string(),
97 format!("{}{}{}", self.leading_ws, f, self.trailing_ws)
101 struct FunctionBuilder {
102 target: GeneratedFunctionTarget,
104 type_params: Option<ast::GenericParamList>,
105 params: ast::ParamList,
110 impl FunctionBuilder {
111 /// Prepares a generated function that matches `call`.
112 /// The function is generated in `target_module` or next to `call`
115 call: &ast::CallExpr,
117 target_module: Option<hir::Module>,
119 let mut file = ctx.frange.file_id;
120 let target = match &target_module {
121 Some(target_module) => {
122 let module_source = target_module.definition_source(ctx.db());
123 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?;
127 None => next_space_for_fn_after_call_site(&call)?,
129 let needs_pub = target_module.is_some();
130 let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?;
131 let fn_name = fn_name(&path)?;
132 let (type_params, params) = fn_args(ctx, target_module, &call)?;
134 Some(Self { target, fn_name, type_params, params, file, needs_pub })
137 fn render(self) -> FunctionTemplate {
138 let placeholder_expr = make::expr_todo();
139 let fn_body = make::block_expr(vec![], Some(placeholder_expr));
140 let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None };
141 let mut fn_def = make::fn_(
147 Some(make::ret_type(make::ty_unit())),
152 let insert_offset = match self.target {
153 GeneratedFunctionTarget::BehindItem(it) => {
154 let indent = IndentLevel::from_node(&it);
155 leading_ws = format!("\n\n{}", indent);
156 fn_def = fn_def.indent(indent);
157 trailing_ws = String::new();
158 it.text_range().end()
160 GeneratedFunctionTarget::InEmptyItemList(it) => {
161 let indent = IndentLevel::from_node(it.syntax());
162 leading_ws = format!("\n{}", indent + 1);
163 fn_def = fn_def.indent(indent + 1);
164 trailing_ws = format!("\n{}", indent);
165 it.syntax().text_range().start() + TextSize::of('{')
172 ret_type: fn_def.ret_type().unwrap(),
180 enum GeneratedFunctionTarget {
181 BehindItem(SyntaxNode),
182 InEmptyItemList(ast::ItemList),
185 impl GeneratedFunctionTarget {
186 fn syntax(&self) -> &SyntaxNode {
188 GeneratedFunctionTarget::BehindItem(it) => it,
189 GeneratedFunctionTarget::InEmptyItemList(it) => it.syntax(),
194 fn fn_name(call: &ast::Path) -> Option<ast::Name> {
195 let name = call.segment()?.syntax().to_string();
196 Some(make::name(&name))
199 /// Computes the type variables and arguments required for the generated function
202 target_module: hir::Module,
203 call: &ast::CallExpr,
204 ) -> Option<(Option<ast::GenericParamList>, ast::ParamList)> {
205 let mut arg_names = Vec::new();
206 let mut arg_types = Vec::new();
207 for arg in call.arg_list()?.args() {
208 arg_names.push(match fn_arg_name(&arg) {
210 None => String::from("arg"),
212 arg_types.push(match fn_arg_type(ctx, target_module, &arg) {
214 None => String::from("()"),
217 deduplicate_arg_names(&mut arg_names);
218 let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| make::param(name, ty));
219 Some((None, make::param_list(params)))
222 /// Makes duplicate argument names unique by appending incrementing numbers.
225 /// let mut names: Vec<String> =
226 /// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
227 /// deduplicate_arg_names(&mut names);
228 /// let expected: Vec<String> =
229 /// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
230 /// assert_eq!(names, expected);
232 fn deduplicate_arg_names(arg_names: &mut Vec<String>) {
233 let arg_name_counts = arg_names.iter().fold(FxHashMap::default(), |mut m, name| {
234 *m.entry(name).or_insert(0) += 1;
237 let duplicate_arg_names: FxHashSet<String> = arg_name_counts
239 .filter(|(_, count)| *count >= 2)
240 .map(|(name, _)| name.clone())
243 let mut counter_per_name = FxHashMap::default();
244 for arg_name in arg_names.iter_mut() {
245 if duplicate_arg_names.contains(arg_name) {
246 let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
248 arg_name.push_str(&counter.to_string());
254 fn fn_arg_name(fn_arg: &ast::Expr) -> Option<String> {
256 ast::Expr::CastExpr(cast_expr) => fn_arg_name(&cast_expr.expr()?),
261 .filter(|d| ast::NameRef::can_cast(d.kind()))
270 target_module: hir::Module,
272 ) -> Option<String> {
273 let ty = ctx.sema.type_of_expr(fn_arg)?;
278 if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) {
285 /// Returns the position inside the current mod or file
286 /// directly after the current block
287 /// We want to write the generated function directly after
288 /// fns, impls or macro calls, but inside mods
289 fn next_space_for_fn_after_call_site(expr: &ast::CallExpr) -> Option<GeneratedFunctionTarget> {
290 let mut ancestors = expr.syntax().ancestors().peekable();
291 let mut last_ancestor: Option<SyntaxNode> = None;
292 while let Some(next_ancestor) = ancestors.next() {
293 match next_ancestor.kind() {
294 SyntaxKind::SOURCE_FILE => {
297 SyntaxKind::ITEM_LIST => {
298 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
304 last_ancestor = Some(next_ancestor);
306 last_ancestor.map(GeneratedFunctionTarget::BehindItem)
309 fn next_space_for_fn_in_module(
310 db: &dyn hir::db::AstDatabase,
311 module_source: &hir::InFile<hir::ModuleSource>,
312 ) -> Option<(FileId, GeneratedFunctionTarget)> {
313 let file = module_source.file_id.original_file(db);
314 let assist_item = match &module_source.value {
315 hir::ModuleSource::SourceFile(it) => {
316 if let Some(last_item) = it.items().last() {
317 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
319 GeneratedFunctionTarget::BehindItem(it.syntax().clone())
322 hir::ModuleSource::Module(it) => {
323 if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
324 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
326 GeneratedFunctionTarget::InEmptyItemList(it.item_list()?)
330 Some((file, assist_item))
335 use crate::tests::{check_assist, check_assist_not_applicable};
340 fn add_function_with_no_args() {
353 fn bar() ${0:-> ()} {
361 fn add_function_from_method() {
362 // This ensures that the function is correctly generated
363 // in the next outer mod or file
380 fn bar() ${0:-> ()} {
388 fn add_function_directly_after_current_block() {
389 // The new fn should not be created at the end of the file or module
404 fn bar() ${0:-> ()} {
414 fn add_function_with_no_args_in_same_module() {
430 fn bar() ${0:-> ()} {
439 fn add_function_with_function_call_arg() {
444 fn baz() -> Baz { todo!() }
451 fn baz() -> Baz { todo!() }
456 fn bar(baz: Baz) ${0:-> ()} {
464 fn add_function_with_method_call_arg() {
470 fn foo(&self) -> Baz {
473 fn baz(&self) -> Baz {
481 fn foo(&self) -> Baz {
484 fn baz(&self) -> Baz {
489 fn bar(baz: Baz) ${0:-> ()} {
497 fn add_function_with_string_literal_arg() {
510 fn bar(arg: &str) ${0:-> ()} {
518 fn add_function_with_char_literal_arg() {
531 fn bar(arg: char) ${0:-> ()} {
539 fn add_function_with_int_literal_arg() {
552 fn bar(arg: i32) ${0:-> ()} {
560 fn add_function_with_cast_int_literal_arg() {
573 fn bar(arg: u8) ${0:-> ()} {
581 fn name_of_cast_variable_is_used() {
582 // Ensures that the name of the cast type isn't used
583 // in the generated function signature.
598 fn bar(x: u8) ${0:-> ()} {
606 fn add_function_with_variable_arg() {
621 fn bar(worble: ()) ${0:-> ()} {
629 fn add_function_with_impl_trait_arg() {
634 fn foo() -> impl Foo {
643 fn foo() -> impl Foo {
650 fn bar(foo: impl Foo) ${0:-> ()} {
663 fn baz() -> Baz { todo!() }
671 fn baz() -> Baz { todo!() }
677 fn bar(baz: &Baz) ${0:-> ()} {
685 fn add_function_with_qualified_path_arg() {
691 pub fn baz() -> Bof { Bof }
700 pub fn baz() -> Bof { Bof }
706 fn bar(baz: Baz::Bof) ${0:-> ()} {
715 // FIXME fix printing the generics of a `Ty` to make this test pass
716 fn add_function_with_generic_arg() {
729 fn bar<T>(t: T) ${0:-> ()} {
738 // FIXME Fix function type printing to make this test pass
739 fn add_function_with_fn_arg() {
745 fn new() -> Self { Baz }
754 fn new() -> Self { Baz }
760 fn bar(arg: fn() -> Baz) ${0:-> ()} {
769 // FIXME Fix closure type printing to make this test pass
770 fn add_function_with_closure_arg() {
775 let closure = |x: i64| x - 1;
781 let closure = |x: i64| x - 1;
785 fn bar(closure: impl Fn(i64) -> i64) ${0:-> ()} {
793 fn unresolveable_types_default_to_unit() {
806 fn bar(baz: ()) ${0:-> ()} {
814 fn arg_names_dont_overlap() {
819 fn baz() -> Baz { Baz }
826 fn baz() -> Baz { Baz }
831 fn bar(baz_1: Baz, baz_2: Baz) ${0:-> ()} {
839 fn arg_name_counters_start_at_1_per_name() {
844 fn baz() -> Baz { Baz }
846 $0bar(baz(), baz(), "foo", "bar")
851 fn baz() -> Baz { Baz }
853 bar(baz(), baz(), "foo", "bar")
856 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) ${0:-> ()} {
864 fn add_function_in_module() {
876 pub(crate) fn my_fn() ${0:-> ()} {
890 // Ignored until local imports are supported.
891 // See https://github.com/rust-analyzer/rust-analyzer/issues/1165
892 fn qualified_path_uses_correct_scope() {
915 fn baz(foo: foo::Foo) ${0:-> ()} {
923 fn add_function_in_module_containing_other_items() {
928 fn something_else() {}
937 fn something_else() {}
939 pub(crate) fn my_fn() ${0:-> ()} {
952 fn add_function_in_nested_module() {
967 pub(crate) fn my_fn() ${0:-> ()} {
981 fn add_function_in_another_file() {
996 pub(crate) fn bar() ${0:-> ()} {
1003 fn add_function_not_applicable_if_function_already_exists() {
1004 check_assist_not_applicable(
1017 fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1018 check_assist_not_applicable(
1019 // bar is resolved, but baz isn't.
1020 // The assist is only active if the cursor is on an unresolved path,
1021 // but the assist should only be offered if the path is a function call.
1035 fn create_method_with_no_args() {