4 ast::{self, edit::IndentLevel, ArgListOwner, AstNode, ModuleItemOwner},
5 SyntaxKind, SyntaxNode, TextSize,
7 use rustc_hash::{FxHashMap, FxHashSet};
9 use crate::{AssistContext, AssistId, Assists};
11 // Assist: add_function
13 // Adds a stub function with a signature matching the function under the cursor.
17 // fn baz() -> Baz { Baz }
26 // fn baz() -> Baz { Baz }
31 // fn bar(arg: &str, baz: Baz) {
36 pub(crate) fn add_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
37 let path_expr: ast::PathExpr = ctx.find_node_at_offset()?;
38 let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?;
39 let path = path_expr.path()?;
41 if ctx.sema.resolve_path(&path).is_some() {
42 // The function call already resolves, no need to add a function
46 let target_module = if let Some(qualifier) = path.qualifier() {
47 if let Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) =
48 ctx.sema.resolve_path(&qualifier)
50 Some(module.definition_source(ctx.sema.db))
58 let function_builder = FunctionBuilder::from_call(&ctx, &call, &path, target_module)?;
60 let target = call.syntax().text_range();
61 acc.add(AssistId("add_function"), "Add function", target, |edit| {
62 let function_template = function_builder.render();
63 edit.set_file(function_template.file);
64 edit.set_cursor(function_template.cursor_offset);
65 edit.insert(function_template.insert_offset, function_template.fn_def.to_string());
69 struct FunctionTemplate {
70 insert_offset: TextSize,
71 cursor_offset: TextSize,
72 fn_def: ast::SourceFile,
76 struct FunctionBuilder {
77 target: GeneratedFunctionTarget,
79 type_params: Option<ast::TypeParamList>,
80 params: ast::ParamList,
85 impl FunctionBuilder {
86 /// Prepares a generated function that matches `call` in `generate_in`
87 /// (or as close to `call` as possible, if `generate_in` is `None`)
92 target_module: Option<hir::InFile<hir::ModuleSource>>,
94 let needs_pub = target_module.is_some();
95 let mut file = ctx.frange.file_id;
96 let target = if let Some(target_module) = target_module {
97 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, target_module)?;
101 next_space_for_fn_after_call_site(&call)?
103 let fn_name = fn_name(&path)?;
104 let (type_params, params) = fn_args(ctx, &call)?;
105 Some(Self { target, fn_name, type_params, params, file, needs_pub })
108 fn render(self) -> FunctionTemplate {
109 let placeholder_expr = ast::make::expr_todo();
110 let fn_body = ast::make::block_expr(vec![], Some(placeholder_expr));
111 let mut fn_def = ast::make::fn_def(self.fn_name, self.type_params, self.params, fn_body);
113 fn_def = ast::make::add_pub_crate_modifier(fn_def);
116 let (fn_def, insert_offset) = match self.target {
117 GeneratedFunctionTarget::BehindItem(it) => {
118 let with_leading_blank_line = ast::make::add_leading_newlines(2, fn_def);
119 let indented = IndentLevel::from_node(&it).increase_indent(with_leading_blank_line);
120 (indented, it.text_range().end())
122 GeneratedFunctionTarget::InEmptyItemList(it) => {
123 let indent_once = IndentLevel(1);
124 let indent = IndentLevel::from_node(it.syntax());
126 let fn_def = ast::make::add_leading_newlines(1, fn_def);
127 let fn_def = indent_once.increase_indent(fn_def);
128 let fn_def = ast::make::add_trailing_newlines(1, fn_def);
129 let fn_def = indent.increase_indent(fn_def);
130 (fn_def, it.syntax().text_range().start() + TextSize::of('{'))
134 let placeholder_expr =
135 fn_def.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
136 let cursor_offset_from_fn_start = placeholder_expr.syntax().text_range().start();
137 let cursor_offset = insert_offset + cursor_offset_from_fn_start;
138 FunctionTemplate { insert_offset, cursor_offset, fn_def, file: self.file }
142 enum GeneratedFunctionTarget {
143 BehindItem(SyntaxNode),
144 InEmptyItemList(ast::ItemList),
147 fn fn_name(call: &ast::Path) -> Option<ast::Name> {
148 let name = call.segment()?.syntax().to_string();
149 Some(ast::make::name(&name))
152 /// Computes the type variables and arguments required for the generated function
155 call: &ast::CallExpr,
156 ) -> Option<(Option<ast::TypeParamList>, ast::ParamList)> {
157 let mut arg_names = Vec::new();
158 let mut arg_types = Vec::new();
159 for arg in call.arg_list()?.args() {
160 let arg_name = match fn_arg_name(&arg) {
162 None => String::from("arg"),
164 arg_names.push(arg_name);
165 arg_types.push(match fn_arg_type(ctx, &arg) {
167 None => String::from("()"),
170 deduplicate_arg_names(&mut arg_names);
171 let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| ast::make::param(name, ty));
172 Some((None, ast::make::param_list(params)))
175 /// Makes duplicate argument names unique by appending incrementing numbers.
178 /// let mut names: Vec<String> =
179 /// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
180 /// deduplicate_arg_names(&mut names);
181 /// let expected: Vec<String> =
182 /// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
183 /// assert_eq!(names, expected);
185 fn deduplicate_arg_names(arg_names: &mut Vec<String>) {
186 let arg_name_counts = arg_names.iter().fold(FxHashMap::default(), |mut m, name| {
187 *m.entry(name).or_insert(0) += 1;
190 let duplicate_arg_names: FxHashSet<String> = arg_name_counts
192 .filter(|(_, count)| *count >= 2)
193 .map(|(name, _)| name.clone())
196 let mut counter_per_name = FxHashMap::default();
197 for arg_name in arg_names.iter_mut() {
198 if duplicate_arg_names.contains(arg_name) {
199 let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
201 arg_name.push_str(&counter.to_string());
207 fn fn_arg_name(fn_arg: &ast::Expr) -> Option<String> {
209 ast::Expr::CastExpr(cast_expr) => fn_arg_name(&cast_expr.expr()?),
214 .filter(|d| ast::NameRef::can_cast(d.kind()))
221 fn fn_arg_type(ctx: &AssistContext, fn_arg: &ast::Expr) -> Option<String> {
222 let ty = ctx.sema.type_of_expr(fn_arg)?;
226 Some(ty.display(ctx.sema.db).to_string())
229 /// Returns the position inside the current mod or file
230 /// directly after the current block
231 /// We want to write the generated function directly after
232 /// fns, impls or macro calls, but inside mods
233 fn next_space_for_fn_after_call_site(expr: &ast::CallExpr) -> Option<GeneratedFunctionTarget> {
234 let mut ancestors = expr.syntax().ancestors().peekable();
235 let mut last_ancestor: Option<SyntaxNode> = None;
236 while let Some(next_ancestor) = ancestors.next() {
237 match next_ancestor.kind() {
238 SyntaxKind::SOURCE_FILE => {
241 SyntaxKind::ITEM_LIST => {
242 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
248 last_ancestor = Some(next_ancestor);
250 last_ancestor.map(GeneratedFunctionTarget::BehindItem)
253 fn next_space_for_fn_in_module(
254 db: &dyn hir::db::AstDatabase,
255 module: hir::InFile<hir::ModuleSource>,
256 ) -> Option<(FileId, GeneratedFunctionTarget)> {
257 let file = module.file_id.original_file(db);
258 let assist_item = match module.value {
259 hir::ModuleSource::SourceFile(it) => {
260 if let Some(last_item) = it.items().last() {
261 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
263 GeneratedFunctionTarget::BehindItem(it.syntax().clone())
266 hir::ModuleSource::Module(it) => {
267 if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
268 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
270 GeneratedFunctionTarget::InEmptyItemList(it.item_list()?)
274 Some((file, assist_item))
279 use crate::tests::{check_assist, check_assist_not_applicable};
284 fn add_function_with_no_args() {
305 fn add_function_from_method() {
306 // This ensures that the function is correctly generated
307 // in the next outer mod or file
332 fn add_function_directly_after_current_block() {
333 // The new fn should not be created at the end of the file or module
358 fn add_function_with_no_args_in_same_module() {
383 fn add_function_with_function_call_arg() {
388 fn baz() -> Baz { todo!() }
395 fn baz() -> Baz { todo!() }
408 fn add_function_with_method_call_arg() {
414 fn foo(&self) -> Baz {
417 fn baz(&self) -> Baz {
425 fn foo(&self) -> Baz {
428 fn baz(&self) -> Baz {
441 fn add_function_with_string_literal_arg() {
462 fn add_function_with_char_literal_arg() {
483 fn add_function_with_int_literal_arg() {
504 fn add_function_with_cast_int_literal_arg() {
525 fn name_of_cast_variable_is_used() {
526 // Ensures that the name of the cast type isn't used
527 // in the generated function signature.
550 fn add_function_with_variable_arg() {
573 fn add_function_with_impl_trait_arg() {
578 fn foo() -> impl Foo {
587 fn foo() -> impl Foo {
594 fn bar(foo: impl Foo) {
603 // FIXME print paths properly to make this test pass
604 fn add_function_with_qualified_path_arg() {
610 pub fn baz() -> Bof { Bof }
614 <|>bar(super::Baz::baz())
621 pub fn baz() -> Bof { Bof }
625 bar(super::Baz::baz())
628 fn bar(baz: super::Baz::Bof) {
638 // FIXME fix printing the generics of a `Ty` to make this test pass
639 fn add_function_with_generic_arg() {
661 // FIXME Fix function type printing to make this test pass
662 fn add_function_with_fn_arg() {
668 fn new() -> Self { Baz }
677 fn new() -> Self { Baz }
683 fn bar(arg: fn() -> Baz) {
692 // FIXME Fix closure type printing to make this test pass
693 fn add_function_with_closure_arg() {
698 let closure = |x: i64| x - 1;
704 let closure = |x: i64| x - 1;
708 fn bar(closure: impl Fn(i64) -> i64) {
716 fn unresolveable_types_default_to_unit() {
737 fn arg_names_dont_overlap() {
742 fn baz() -> Baz { Baz }
749 fn baz() -> Baz { Baz }
754 fn bar(baz_1: Baz, baz_2: Baz) {
762 fn arg_name_counters_start_at_1_per_name() {
767 fn baz() -> Baz { Baz }
769 <|>bar(baz(), baz(), "foo", "bar")
774 fn baz() -> Baz { Baz }
776 bar(baz(), baz(), "foo", "bar")
779 fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) {
787 fn add_function_in_module() {
799 pub(crate) fn my_fn() {
812 fn add_function_in_module_containing_other_items() {
817 fn something_else() {}
826 fn something_else() {}
828 pub(crate) fn my_fn() {
841 fn add_function_in_nested_module() {
856 pub(crate) fn my_fn() {
870 fn add_function_in_another_file() {
885 pub(crate) fn bar() {
892 fn add_function_not_applicable_if_function_already_exists() {
893 check_assist_not_applicable(
906 fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
907 check_assist_not_applicable(
908 // bar is resolved, but baz isn't.
909 // The assist is only active if the cursor is on an unresolved path,
910 // but the assist should only be offered if the path is a function call.
923 fn add_function_not_applicable_if_function_path_not_singleton() {
924 // In the future this assist could be extended to generate functions
925 // if the path is in the same crate (or even the same workspace).
926 // For the beginning, I think this is fine.
927 check_assist_not_applicable(
931 other_crate::bar<|>();
939 fn create_method_with_no_args() {