1 //! Renderer for function calls.
4 use hir::{AsAssocItem, HasSource, HirDisplay};
5 use ide_db::SymbolKind;
6 use itertools::Itertools;
10 item::{CompletionItem, CompletionItemKind, CompletionKind, CompletionRelevance, ImportEdit},
12 builder_ext::Params, compute_exact_name_match, compute_ref_match, compute_type_match,
17 pub(crate) fn render_fn(
18 ctx: RenderContext<'_>,
19 import_to_add: Option<ImportEdit>,
20 local_name: Option<hir::Name>,
22 ) -> Option<CompletionItem> {
23 let _p = profile::span("render_fn");
24 Some(FunctionRender::new(ctx, None, local_name, fn_, false)?.render(import_to_add))
27 pub(crate) fn render_method(
28 ctx: RenderContext<'_>,
29 import_to_add: Option<ImportEdit>,
30 receiver: Option<hir::Name>,
31 local_name: Option<hir::Name>,
33 ) -> Option<CompletionItem> {
34 let _p = profile::span("render_method");
35 Some(FunctionRender::new(ctx, receiver, local_name, fn_, true)?.render(import_to_add))
39 struct FunctionRender<'a> {
40 ctx: RenderContext<'a>,
42 receiver: Option<hir::Name>,
44 /// NB: having `ast::Fn` here might or might not be a good idea. The problem
45 /// with it is that, to get an `ast::`, you want to parse the corresponding
46 /// source file. So, when flyimport completions suggest a bunch of
47 /// functions, we spend quite some time parsing many files.
49 /// We need ast because we want to access parameter names (patterns). We can
50 /// add them to the hir of the function itself, but parameter names are not
51 /// something hir cares otherwise.
53 /// Alternatively we can reconstruct params from the function body, but that
54 /// would require parsing anyway.
56 /// It seems that just using `ast` is the best choice -- most of parses
57 /// should be cached anyway.
62 impl<'a> FunctionRender<'a> {
64 ctx: RenderContext<'a>,
65 receiver: Option<hir::Name>,
66 local_name: Option<hir::Name>,
69 ) -> Option<FunctionRender<'a>> {
70 let name = local_name.unwrap_or_else(|| fn_.name(ctx.db())).to_string();
71 let ast_node = fn_.source(ctx.db())?.value;
73 Some(FunctionRender { ctx, name, receiver, func: fn_, ast_node, is_method })
76 fn render(self, import_to_add: Option<ImportEdit>) -> CompletionItem {
77 let params = self.params();
78 let call = match &self.receiver {
79 Some(receiver) => format!("{}.{}", receiver, &self.name),
80 None => self.name.clone(),
83 CompletionItem::new(CompletionKind::Reference, self.ctx.source_range(), call.clone());
84 item.kind(self.kind())
85 .set_documentation(self.ctx.docs(self.func))
87 self.ctx.is_deprecated(self.func) || self.ctx.is_deprecated_assoc_item(self.func),
89 .detail(self.detail())
90 .add_call_parens(self.ctx.completion, call.clone(), params);
92 if import_to_add.is_none() {
93 let db = self.ctx.db();
94 if let Some(actm) = self.func.as_assoc_item(db) {
95 if let Some(trt) = actm.containing_trait_or_trait_impl(db) {
96 item.trait_name(trt.name(db).to_string());
101 if let Some(import_to_add) = import_to_add {
102 item.add_import(import_to_add);
104 item.lookup_by(self.name);
106 let ret_type = self.func.ret_type(self.ctx.db());
107 item.set_relevance(CompletionRelevance {
108 type_match: compute_type_match(self.ctx.completion, &ret_type),
109 exact_name_match: compute_exact_name_match(self.ctx.completion, &call),
110 ..CompletionRelevance::default()
113 if let Some(ref_match) = compute_ref_match(self.ctx.completion, &ret_type) {
115 // For now we don't properly calculate the edits for ref match
116 // completions on methods, so we've disabled them. See #8058.
118 item.ref_match(ref_match);
125 fn detail(&self) -> String {
126 let ret_ty = self.func.ret_type(self.ctx.db());
127 let ret = if ret_ty.is_unit() {
128 // Omit the return type if it is the unit type
131 format!(" {}", self.ty_display())
134 format!("fn({}){}", self.params_display(), ret)
137 fn params_display(&self) -> String {
138 if let Some(self_param) = self.func.self_param(self.ctx.db()) {
141 .assoc_fn_params(self.ctx.db())
143 .skip(1) // skip the self param because we are manually handling that
144 .map(|p| p.ty().display(self.ctx.db()).to_string());
146 std::iter::once(self_param.display(self.ctx.db()).to_owned()).chain(params).join(", ")
150 .assoc_fn_params(self.ctx.db())
152 .map(|p| p.ty().display(self.ctx.db()).to_string())
158 fn ty_display(&self) -> String {
159 let ret_ty = self.func.ret_type(self.ctx.db());
161 format!("-> {}", ret_ty.display(self.ctx.db()))
164 fn params(&self) -> Params {
165 let ast_params = match self.ast_node.param_list() {
167 None => return Params::Named(Vec::new()),
169 let params = ast_params.params().map(Either::Right);
171 let params = if self.ctx.completion.has_dot_receiver() || self.receiver.is_some() {
172 params.zip(self.func.method_params(self.ctx.db()).unwrap_or_default()).collect()
179 .zip(self.func.assoc_fn_params(self.ctx.db()))
183 Params::Named(params)
186 fn kind(&self) -> CompletionItemKind {
187 if self.func.self_param(self.ctx.db()).is_some() {
188 CompletionItemKind::Method
190 SymbolKind::Function.into()
198 tests::{check_edit, check_edit_with_config, TEST_CONFIG},
203 fn inserts_parens_for_function_calls() {
204 cov_mark::check!(inserts_parens_for_function_calls);
213 fn main() { no_args()$0 }
220 fn with_args(x: i32, y: String) {}
221 fn main() { with_$0 }
224 fn with_args(x: i32, y: String) {}
225 fn main() { with_args(${1:x}, ${2:y})$0 }
236 fn bar(s: &S) { s.f$0 }
243 fn bar(s: &S) { s.foo()$0 }
252 fn foo(&self, x: i32) {}
261 fn foo(&self, x: i32) {}
274 fn foo(&self, x: i32) {
282 fn foo(&self, x: i32) {
291 fn parens_for_method_call_as_assoc_fn() {
306 fn main() { S::foo(${1:&self})$0 }
312 fn suppress_arg_snippets() {
313 cov_mark::check!(suppress_arg_snippets);
314 check_edit_with_config(
315 CompletionConfig { add_call_argument_snippets: false, ..TEST_CONFIG },
318 fn with_args(x: i32, y: String) {}
319 fn main() { with_$0 }
322 fn with_args(x: i32, y: String) {}
323 fn main() { with_args($0) }
329 fn strips_underscores_from_args() {
333 fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
337 fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
338 fn main() { foo(${1:foo}, ${2:bar}, ${3:ho_ge_})$0 }
344 fn insert_ref_when_matching_local_in_scope() {
349 fn ref_arg(x: &Foo) {}
357 fn ref_arg(x: &Foo) {}
367 fn insert_mut_ref_when_matching_local_in_scope() {
372 fn ref_arg(x: &mut Foo) {}
380 fn ref_arg(x: &mut Foo) {}
383 ref_arg(${1:&mut x})$0
390 fn insert_ref_when_matching_local_in_scope_for_method() {
397 fn apply_foo(&self, x: &Foo) {}
410 fn apply_foo(&self, x: &Foo) {}
416 y.apply_foo(${1:&x})$0
423 fn trim_mut_keyword_in_func_completion() {
427 fn take_mutably(mut x: &i32) {}
434 fn take_mutably(mut x: &i32) {}
437 take_mutably(${1:x})$0