aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/handlers/add_function.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists/src/handlers/add_function.rs')
-rw-r--r--crates/ra_assists/src/handlers/add_function.rs204
1 files changed, 132 insertions, 72 deletions
diff --git a/crates/ra_assists/src/handlers/add_function.rs b/crates/ra_assists/src/handlers/add_function.rs
index 278079665..de016ae4e 100644
--- a/crates/ra_assists/src/handlers/add_function.rs
+++ b/crates/ra_assists/src/handlers/add_function.rs
@@ -1,14 +1,17 @@
1use hir::HirDisplay;
2use ra_db::FileId;
1use ra_syntax::{ 3use ra_syntax::{
2 ast::{self, AstNode}, 4 ast::{
5 self,
6 edit::{AstNodeEdit, IndentLevel},
7 ArgListOwner, AstNode, ModuleItemOwner,
8 },
3 SyntaxKind, SyntaxNode, TextSize, 9 SyntaxKind, SyntaxNode, TextSize,
4}; 10};
5
6use crate::{Assist, AssistCtx, AssistId};
7use ast::{edit::IndentLevel, ArgListOwner, ModuleItemOwner};
8use hir::HirDisplay;
9use ra_db::FileId;
10use rustc_hash::{FxHashMap, FxHashSet}; 11use rustc_hash::{FxHashMap, FxHashSet};
11 12
13use crate::{AssistContext, AssistId, Assists};
14
12// Assist: add_function 15// Assist: add_function
13// 16//
14// Adds a stub function with a signature matching the function under the cursor. 17// Adds a stub function with a signature matching the function under the cursor.
@@ -34,7 +37,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
34// } 37// }
35// 38//
36// ``` 39// ```
37pub(crate) fn add_function(ctx: AssistCtx) -> Option<Assist> { 40pub(crate) fn add_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
38 let path_expr: ast::PathExpr = ctx.find_node_at_offset()?; 41 let path_expr: ast::PathExpr = ctx.find_node_at_offset()?;
39 let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?; 42 let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?;
40 let path = path_expr.path()?; 43 let path = path_expr.path()?;
@@ -44,22 +47,18 @@ pub(crate) fn add_function(ctx: AssistCtx) -> Option<Assist> {
44 return None; 47 return None;
45 } 48 }
46 49
47 let target_module = if let Some(qualifier) = path.qualifier() { 50 let target_module = match path.qualifier() {
48 if let Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) = 51 Some(qualifier) => match ctx.sema.resolve_path(&qualifier) {
49 ctx.sema.resolve_path(&qualifier) 52 Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => Some(module),
50 { 53 _ => return None,
51 Some(module.definition_source(ctx.sema.db)) 54 },
52 } else { 55 None => None,
53 return None;
54 }
55 } else {
56 None
57 }; 56 };
58 57
59 let function_builder = FunctionBuilder::from_call(&ctx, &call, &path, target_module)?; 58 let function_builder = FunctionBuilder::from_call(&ctx, &call, &path, target_module)?;
60 59
61 let target = call.syntax().text_range(); 60 let target = call.syntax().text_range();
62 ctx.add_assist(AssistId("add_function"), "Add function", target, |edit| { 61 acc.add(AssistId("add_function"), "Add function", target, |edit| {
63 let function_template = function_builder.render(); 62 let function_template = function_builder.render();
64 edit.set_file(function_template.file); 63 edit.set_file(function_template.file);
65 edit.set_cursor(function_template.cursor_offset); 64 edit.set_cursor(function_template.cursor_offset);
@@ -84,25 +83,29 @@ struct FunctionBuilder {
84} 83}
85 84
86impl FunctionBuilder { 85impl FunctionBuilder {
87 /// Prepares a generated function that matches `call` in `generate_in` 86 /// Prepares a generated function that matches `call`.
88 /// (or as close to `call` as possible, if `generate_in` is `None`) 87 /// The function is generated in `target_module` or next to `call`
89 fn from_call( 88 fn from_call(
90 ctx: &AssistCtx, 89 ctx: &AssistContext,
91 call: &ast::CallExpr, 90 call: &ast::CallExpr,
92 path: &ast::Path, 91 path: &ast::Path,
93 target_module: Option<hir::InFile<hir::ModuleSource>>, 92 target_module: Option<hir::Module>,
94 ) -> Option<Self> { 93 ) -> Option<Self> {
95 let needs_pub = target_module.is_some();
96 let mut file = ctx.frange.file_id; 94 let mut file = ctx.frange.file_id;
97 let target = if let Some(target_module) = target_module { 95 let target = match &target_module {
98 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, target_module)?; 96 Some(target_module) => {
99 file = in_file; 97 let module_source = target_module.definition_source(ctx.db);
100 target 98 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?;
101 } else { 99 file = in_file;
102 next_space_for_fn_after_call_site(&call)? 100 target
101 }
102 None => next_space_for_fn_after_call_site(&call)?,
103 }; 103 };
104 let needs_pub = target_module.is_some();
105 let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?;
104 let fn_name = fn_name(&path)?; 106 let fn_name = fn_name(&path)?;
105 let (type_params, params) = fn_args(ctx, &call)?; 107 let (type_params, params) = fn_args(ctx, target_module, &call)?;
108
106 Some(Self { target, fn_name, type_params, params, file, needs_pub }) 109 Some(Self { target, fn_name, type_params, params, file, needs_pub })
107 } 110 }
108 111
@@ -117,17 +120,16 @@ impl FunctionBuilder {
117 let (fn_def, insert_offset) = match self.target { 120 let (fn_def, insert_offset) = match self.target {
118 GeneratedFunctionTarget::BehindItem(it) => { 121 GeneratedFunctionTarget::BehindItem(it) => {
119 let with_leading_blank_line = ast::make::add_leading_newlines(2, fn_def); 122 let with_leading_blank_line = ast::make::add_leading_newlines(2, fn_def);
120 let indented = IndentLevel::from_node(&it).increase_indent(with_leading_blank_line); 123 let indented = with_leading_blank_line.indent(IndentLevel::from_node(&it));
121 (indented, it.text_range().end()) 124 (indented, it.text_range().end())
122 } 125 }
123 GeneratedFunctionTarget::InEmptyItemList(it) => { 126 GeneratedFunctionTarget::InEmptyItemList(it) => {
124 let indent_once = IndentLevel(1); 127 let indent_once = IndentLevel(1);
125 let indent = IndentLevel::from_node(it.syntax()); 128 let indent = IndentLevel::from_node(it.syntax());
126
127 let fn_def = ast::make::add_leading_newlines(1, fn_def); 129 let fn_def = ast::make::add_leading_newlines(1, fn_def);
128 let fn_def = indent_once.increase_indent(fn_def); 130 let fn_def = fn_def.indent(indent_once);
129 let fn_def = ast::make::add_trailing_newlines(1, fn_def); 131 let fn_def = ast::make::add_trailing_newlines(1, fn_def);
130 let fn_def = indent.increase_indent(fn_def); 132 let fn_def = fn_def.indent(indent);
131 (fn_def, it.syntax().text_range().start() + TextSize::of('{')) 133 (fn_def, it.syntax().text_range().start() + TextSize::of('{'))
132 } 134 }
133 }; 135 };
@@ -145,6 +147,15 @@ enum GeneratedFunctionTarget {
145 InEmptyItemList(ast::ItemList), 147 InEmptyItemList(ast::ItemList),
146} 148}
147 149
150impl GeneratedFunctionTarget {
151 fn syntax(&self) -> &SyntaxNode {
152 match self {
153 GeneratedFunctionTarget::BehindItem(it) => it,
154 GeneratedFunctionTarget::InEmptyItemList(it) => it.syntax(),
155 }
156 }
157}
158
148fn fn_name(call: &ast::Path) -> Option<ast::Name> { 159fn fn_name(call: &ast::Path) -> Option<ast::Name> {
149 let name = call.segment()?.syntax().to_string(); 160 let name = call.segment()?.syntax().to_string();
150 Some(ast::make::name(&name)) 161 Some(ast::make::name(&name))
@@ -152,18 +163,18 @@ fn fn_name(call: &ast::Path) -> Option<ast::Name> {
152 163
153/// Computes the type variables and arguments required for the generated function 164/// Computes the type variables and arguments required for the generated function
154fn fn_args( 165fn fn_args(
155 ctx: &AssistCtx, 166 ctx: &AssistContext,
167 target_module: hir::Module,
156 call: &ast::CallExpr, 168 call: &ast::CallExpr,
157) -> Option<(Option<ast::TypeParamList>, ast::ParamList)> { 169) -> Option<(Option<ast::TypeParamList>, ast::ParamList)> {
158 let mut arg_names = Vec::new(); 170 let mut arg_names = Vec::new();
159 let mut arg_types = Vec::new(); 171 let mut arg_types = Vec::new();
160 for arg in call.arg_list()?.args() { 172 for arg in call.arg_list()?.args() {
161 let arg_name = match fn_arg_name(&arg) { 173 arg_names.push(match fn_arg_name(&arg) {
162 Some(name) => name, 174 Some(name) => name,
163 None => String::from("arg"), 175 None => String::from("arg"),
164 }; 176 });
165 arg_names.push(arg_name); 177 arg_types.push(match fn_arg_type(ctx, target_module, &arg) {
166 arg_types.push(match fn_arg_type(ctx, &arg) {
167 Some(ty) => ty, 178 Some(ty) => ty,
168 None => String::from("()"), 179 None => String::from("()"),
169 }); 180 });
@@ -219,12 +230,21 @@ fn fn_arg_name(fn_arg: &ast::Expr) -> Option<String> {
219 } 230 }
220} 231}
221 232
222fn fn_arg_type(ctx: &AssistCtx, fn_arg: &ast::Expr) -> Option<String> { 233fn fn_arg_type(
234 ctx: &AssistContext,
235 target_module: hir::Module,
236 fn_arg: &ast::Expr,
237) -> Option<String> {
223 let ty = ctx.sema.type_of_expr(fn_arg)?; 238 let ty = ctx.sema.type_of_expr(fn_arg)?;
224 if ty.is_unknown() { 239 if ty.is_unknown() {
225 return None; 240 return None;
226 } 241 }
227 Some(ty.display(ctx.sema.db).to_string()) 242
243 if let Ok(rendered) = ty.display_source_code(ctx.db, target_module.into()) {
244 Some(rendered)
245 } else {
246 None
247 }
228} 248}
229 249
230/// Returns the position inside the current mod or file 250/// Returns the position inside the current mod or file
@@ -253,10 +273,10 @@ fn next_space_for_fn_after_call_site(expr: &ast::CallExpr) -> Option<GeneratedFu
253 273
254fn next_space_for_fn_in_module( 274fn next_space_for_fn_in_module(
255 db: &dyn hir::db::AstDatabase, 275 db: &dyn hir::db::AstDatabase,
256 module: hir::InFile<hir::ModuleSource>, 276 module_source: &hir::InFile<hir::ModuleSource>,
257) -> Option<(FileId, GeneratedFunctionTarget)> { 277) -> Option<(FileId, GeneratedFunctionTarget)> {
258 let file = module.file_id.original_file(db); 278 let file = module_source.file_id.original_file(db);
259 let assist_item = match module.value { 279 let assist_item = match &module_source.value {
260 hir::ModuleSource::SourceFile(it) => { 280 hir::ModuleSource::SourceFile(it) => {
261 if let Some(last_item) = it.items().last() { 281 if let Some(last_item) = it.items().last() {
262 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()) 282 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
@@ -600,8 +620,33 @@ fn bar(foo: impl Foo) {
600 } 620 }
601 621
602 #[test] 622 #[test]
603 #[ignore] 623 fn borrowed_arg() {
604 // FIXME print paths properly to make this test pass 624 check_assist(
625 add_function,
626 r"
627struct Baz;
628fn baz() -> Baz { todo!() }
629
630fn foo() {
631 bar<|>(&baz())
632}
633",
634 r"
635struct Baz;
636fn baz() -> Baz { todo!() }
637
638fn foo() {
639 bar(&baz())
640}
641
642fn bar(baz: &Baz) {
643 <|>todo!()
644}
645",
646 )
647 }
648
649 #[test]
605 fn add_function_with_qualified_path_arg() { 650 fn add_function_with_qualified_path_arg() {
606 check_assist( 651 check_assist(
607 add_function, 652 add_function,
@@ -610,10 +655,8 @@ mod Baz {
610 pub struct Bof; 655 pub struct Bof;
611 pub fn baz() -> Bof { Bof } 656 pub fn baz() -> Bof { Bof }
612} 657}
613mod Foo { 658fn foo() {
614 fn foo() { 659 <|>bar(Baz::baz())
615 <|>bar(super::Baz::baz())
616 }
617} 660}
618", 661",
619 r" 662 r"
@@ -621,14 +664,12 @@ mod Baz {
621 pub struct Bof; 664 pub struct Bof;
622 pub fn baz() -> Bof { Bof } 665 pub fn baz() -> Bof { Bof }
623} 666}
624mod Foo { 667fn foo() {
625 fn foo() { 668 bar(Baz::baz())
626 bar(super::Baz::baz()) 669}
627 }
628 670
629 fn bar(baz: super::Baz::Bof) { 671fn bar(baz: Baz::Bof) {
630 <|>todo!() 672 <|>todo!()
631 }
632} 673}
633", 674",
634 ) 675 )
@@ -810,6 +851,40 @@ fn foo() {
810 } 851 }
811 852
812 #[test] 853 #[test]
854 #[ignore]
855 // Ignored until local imports are supported.
856 // See https://github.com/rust-analyzer/rust-analyzer/issues/1165
857 fn qualified_path_uses_correct_scope() {
858 check_assist(
859 add_function,
860 "
861mod foo {
862 pub struct Foo;
863}
864fn bar() {
865 use foo::Foo;
866 let foo = Foo;
867 baz<|>(foo)
868}
869",
870 "
871mod foo {
872 pub struct Foo;
873}
874fn bar() {
875 use foo::Foo;
876 let foo = Foo;
877 baz(foo)
878}
879
880fn baz(foo: foo::Foo) {
881 <|>todo!()
882}
883",
884 )
885 }
886
887 #[test]
813 fn add_function_in_module_containing_other_items() { 888 fn add_function_in_module_containing_other_items() {
814 check_assist( 889 check_assist(
815 add_function, 890 add_function,
@@ -921,21 +996,6 @@ fn bar(baz: ()) {}
921 } 996 }
922 997
923 #[test] 998 #[test]
924 fn add_function_not_applicable_if_function_path_not_singleton() {
925 // In the future this assist could be extended to generate functions
926 // if the path is in the same crate (or even the same workspace).
927 // For the beginning, I think this is fine.
928 check_assist_not_applicable(
929 add_function,
930 r"
931fn foo() {
932 other_crate::bar<|>();
933}
934 ",
935 )
936 }
937
938 #[test]
939 #[ignore] 999 #[ignore]
940 fn create_method_with_no_args() { 1000 fn create_method_with_no_args() {
941 check_assist( 1001 check_assist(