1 //! Renderer for function calls.
4 use hir::{AsAssocItem, HasSource, HirDisplay};
5 use ide_db::SymbolKind;
6 use itertools::Itertools;
10 item::{CompletionItem, CompletionItemKind, 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()));
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.to_string(),
82 let mut item = CompletionItem::new(self.kind(), self.ctx.source_range(), call.clone());
83 item.set_documentation(self.ctx.docs(self.func))
85 self.ctx.is_deprecated(self.func) || self.ctx.is_deprecated_assoc_item(self.func),
87 .detail(self.detail())
88 .add_call_parens(self.ctx.completion, call.clone(), params);
90 if import_to_add.is_none() {
91 let db = self.ctx.db();
92 if let Some(actm) = self.func.as_assoc_item(db) {
93 if let Some(trt) = actm.containing_trait_or_trait_impl(db) {
94 item.trait_name(trt.name(db).to_smol_str());
99 if let Some(import_to_add) = import_to_add {
100 item.add_import(import_to_add);
102 item.lookup_by(self.name.to_smol_str());
104 let ret_type = self.func.ret_type(self.ctx.db());
105 item.set_relevance(CompletionRelevance {
106 type_match: compute_type_match(self.ctx.completion, &ret_type),
107 exact_name_match: compute_exact_name_match(self.ctx.completion, &call),
108 ..CompletionRelevance::default()
111 if let Some(ref_match) = compute_ref_match(self.ctx.completion, &ret_type) {
113 // For now we don't properly calculate the edits for ref match
114 // completions on methods, so we've disabled them. See #8058.
116 item.ref_match(ref_match);
123 fn detail(&self) -> String {
124 let ret_ty = self.func.ret_type(self.ctx.db());
125 let ret = if ret_ty.is_unit() {
126 // Omit the return type if it is the unit type
129 format!(" {}", self.ty_display())
132 format!("fn({}){}", self.params_display(), ret)
135 fn params_display(&self) -> String {
136 if let Some(self_param) = self.func.self_param(self.ctx.db()) {
139 .assoc_fn_params(self.ctx.db())
141 .skip(1) // skip the self param because we are manually handling that
142 .map(|p| p.ty().display(self.ctx.db()).to_string());
144 std::iter::once(self_param.display(self.ctx.db()).to_owned()).chain(params).join(", ")
148 .assoc_fn_params(self.ctx.db())
150 .map(|p| p.ty().display(self.ctx.db()).to_string())
156 fn ty_display(&self) -> String {
157 let ret_ty = self.func.ret_type(self.ctx.db());
159 format!("-> {}", ret_ty.display(self.ctx.db()))
162 fn params(&self) -> Params {
163 let ast_params = match self.ast_node.param_list() {
165 None => return Params::Named(Vec::new()),
167 let params = ast_params.params().map(Either::Right);
169 let params = if self.ctx.completion.has_dot_receiver() || self.receiver.is_some() {
170 params.zip(self.func.method_params(self.ctx.db()).unwrap_or_default()).collect()
177 .zip(self.func.assoc_fn_params(self.ctx.db()))
181 Params::Named(params)
184 fn kind(&self) -> CompletionItemKind {
185 if self.func.self_param(self.ctx.db()).is_some() {
186 CompletionItemKind::Method
188 SymbolKind::Function.into()
196 tests::{check_edit, check_edit_with_config, TEST_CONFIG},
201 fn inserts_parens_for_function_calls() {
202 cov_mark::check!(inserts_parens_for_function_calls);
211 fn main() { no_args()$0 }
218 fn with_args(x: i32, y: String) {}
219 fn main() { with_$0 }
222 fn with_args(x: i32, y: String) {}
223 fn main() { with_args(${1:x}, ${2:y})$0 }
234 fn bar(s: &S) { s.f$0 }
241 fn bar(s: &S) { s.foo()$0 }
250 fn foo(&self, x: i32) {}
259 fn foo(&self, x: i32) {}
272 fn foo(&self, x: i32) {
280 fn foo(&self, x: i32) {
289 fn parens_for_method_call_as_assoc_fn() {
304 fn main() { S::foo(${1:&self})$0 }
310 fn suppress_arg_snippets() {
311 cov_mark::check!(suppress_arg_snippets);
312 check_edit_with_config(
313 CompletionConfig { add_call_argument_snippets: false, ..TEST_CONFIG },
316 fn with_args(x: i32, y: String) {}
317 fn main() { with_$0 }
320 fn with_args(x: i32, y: String) {}
321 fn main() { with_args($0) }
327 fn strips_underscores_from_args() {
331 fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
335 fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
336 fn main() { foo(${1:foo}, ${2:bar}, ${3:ho_ge_})$0 }
342 fn insert_ref_when_matching_local_in_scope() {
347 fn ref_arg(x: &Foo) {}
355 fn ref_arg(x: &Foo) {}
365 fn insert_mut_ref_when_matching_local_in_scope() {
370 fn ref_arg(x: &mut Foo) {}
378 fn ref_arg(x: &mut Foo) {}
381 ref_arg(${1:&mut x})$0
388 fn insert_ref_when_matching_local_in_scope_for_method() {
395 fn apply_foo(&self, x: &Foo) {}
408 fn apply_foo(&self, x: &Foo) {}
414 y.apply_foo(${1:&x})$0
421 fn trim_mut_keyword_in_func_completion() {
425 fn take_mutably(mut x: &i32) {}
432 fn take_mutably(mut x: &i32) {}
435 take_mutably(${1:x})$0