1 //! Renderer for function calls.
3 use hir::{AsAssocItem, HasSource, HirDisplay};
4 use ide_db::SymbolKind;
5 use itertools::Itertools;
9 item::{CompletionItem, CompletionItemKind, CompletionKind, CompletionRelevance, ImportEdit},
11 builder_ext::Params, compute_exact_name_match, compute_ref_match, compute_type_match,
16 pub(crate) fn render_fn(
17 ctx: RenderContext<'_>,
18 import_to_add: Option<ImportEdit>,
19 local_name: Option<hir::Name>,
21 ) -> Option<CompletionItem> {
22 let _p = profile::span("render_fn");
23 Some(FunctionRender::new(ctx, None, local_name, fn_, false)?.render(import_to_add))
26 pub(crate) fn render_method(
27 ctx: RenderContext<'_>,
28 import_to_add: Option<ImportEdit>,
29 receiver: Option<hir::Name>,
30 local_name: Option<hir::Name>,
32 ) -> Option<CompletionItem> {
33 let _p = profile::span("render_method");
34 Some(FunctionRender::new(ctx, receiver, local_name, fn_, true)?.render(import_to_add))
38 struct FunctionRender<'a> {
39 ctx: RenderContext<'a>,
41 receiver: Option<hir::Name>,
43 /// NB: having `ast::Fn` here might or might not be a good idea. The problem
44 /// with it is that, to get an `ast::`, you want to parse the corresponding
45 /// source file. So, when flyimport completions suggest a bunch of
46 /// functions, we spend quite some time parsing many files.
48 /// We need ast because we want to access parameter names (patterns). We can
49 /// add them to the hir of the function itself, but parameter names are not
50 /// something hir cares otherwise.
52 /// Alternatively we can reconstruct params from the function body, but that
53 /// would require parsing anyway.
55 /// It seems that just using `ast` is the best choice -- most of parses
56 /// should be cached anyway.
61 impl<'a> FunctionRender<'a> {
63 ctx: RenderContext<'a>,
64 receiver: Option<hir::Name>,
65 local_name: Option<hir::Name>,
68 ) -> Option<FunctionRender<'a>> {
69 let name = local_name.unwrap_or_else(|| fn_.name(ctx.db())).to_string();
70 let ast_node = fn_.source(ctx.db())?.value;
72 Some(FunctionRender { ctx, name, receiver, func: fn_, ast_node, is_method })
75 fn render(self, import_to_add: Option<ImportEdit>) -> CompletionItem {
76 let params = self.params();
77 let call = match &self.receiver {
78 Some(receiver) => format!("{}.{}", receiver, &self.name),
79 None => self.name.clone(),
82 CompletionItem::new(CompletionKind::Reference, self.ctx.source_range(), call.clone());
83 item.kind(self.kind())
84 .set_documentation(self.ctx.docs(self.func))
86 self.ctx.is_deprecated(self.func) || self.ctx.is_deprecated_assoc_item(self.func),
88 .detail(self.detail())
89 .add_call_parens(self.ctx.completion, call.clone(), params);
91 if import_to_add.is_none() {
92 let db = self.ctx.db();
93 if let Some(actm) = self.func.as_assoc_item(db) {
94 if let Some(trt) = actm.containing_trait_or_trait_impl(db) {
95 item.trait_name(trt.name(db).to_string());
100 if let Some(import_to_add) = import_to_add {
101 item.add_import(import_to_add);
103 item.lookup_by(self.name);
105 let ret_type = self.func.ret_type(self.ctx.db());
106 item.set_relevance(CompletionRelevance {
107 type_match: compute_type_match(self.ctx.completion, &ret_type),
108 exact_name_match: compute_exact_name_match(self.ctx.completion, &call),
109 ..CompletionRelevance::default()
112 if let Some(ref_match) = compute_ref_match(self.ctx.completion, &ret_type) {
114 // For now we don't properly calculate the edits for ref match
115 // completions on methods, so we've disabled them. See #8058.
117 item.ref_match(ref_match);
124 fn detail(&self) -> String {
125 let ret_ty = self.func.ret_type(self.ctx.db());
126 let ret = if ret_ty.is_unit() {
127 // Omit the return type if it is the unit type
130 format!(" {}", self.ty_display())
133 format!("fn({}){}", self.params_display(), ret)
136 fn params_display(&self) -> String {
137 if let Some(self_param) = self.func.self_param(self.ctx.db()) {
140 .assoc_fn_params(self.ctx.db())
142 .skip(1) // skip the self param because we are manually handling that
143 .map(|p| p.ty().display(self.ctx.db()).to_string());
145 std::iter::once(self_param.display(self.ctx.db()).to_owned()).chain(params).join(", ")
149 .assoc_fn_params(self.ctx.db())
151 .map(|p| p.ty().display(self.ctx.db()).to_string())
157 fn ty_display(&self) -> String {
158 let ret_ty = self.func.ret_type(self.ctx.db());
160 format!("-> {}", ret_ty.display(self.ctx.db()))
163 fn add_arg(&self, arg: &str, ty: &hir::Type) -> String {
164 if let Some(derefed_ty) = ty.remove_ref() {
165 for (name, local) in self.ctx.completion.locals.iter() {
166 if name == arg && local.ty(self.ctx.db()) == derefed_ty {
167 let mutability = if ty.is_mutable_reference() { "&mut " } else { "&" };
168 return format!("{}{}", mutability, arg);
175 fn params(&self) -> Params {
176 let ast_params = match self.ast_node.param_list() {
178 None => return Params::Named(Vec::new()),
181 let mut params_pats = Vec::new();
182 let params_ty = if self.ctx.completion.has_dot_receiver() || self.receiver.is_some() {
183 self.func.method_params(self.ctx.db()).unwrap_or_default()
185 if let Some(s) = ast_params.self_param() {
186 cov_mark::hit!(parens_for_method_call_as_assoc_fn);
187 params_pats.push(Some(s.to_string()));
189 self.func.assoc_fn_params(self.ctx.db())
192 .extend(ast_params.params().into_iter().map(|it| it.pat().map(|it| it.to_string())));
194 let params = params_pats
197 .flat_map(|(pat, param_ty)| {
200 let arg = name.trim_start_matches("mut ").trim_start_matches('_');
201 Some(self.add_arg(arg, param_ty.ty()))
204 Params::Named(params)
207 fn kind(&self) -> CompletionItemKind {
208 if self.func.self_param(self.ctx.db()).is_some() {
209 CompletionItemKind::Method
211 SymbolKind::Function.into()
219 tests::{check_edit, check_edit_with_config, TEST_CONFIG},
224 fn inserts_parens_for_function_calls() {
225 cov_mark::check!(inserts_parens_for_function_calls);
234 fn main() { no_args()$0 }
241 fn with_args(x: i32, y: String) {}
242 fn main() { with_$0 }
245 fn with_args(x: i32, y: String) {}
246 fn main() { with_args(${1:x}, ${2:y})$0 }
257 fn bar(s: &S) { s.f$0 }
264 fn bar(s: &S) { s.foo()$0 }
273 fn foo(&self, x: i32) {}
282 fn foo(&self, x: i32) {}
295 fn foo(&self, x: i32) {
303 fn foo(&self, x: i32) {
312 fn parens_for_method_call_as_assoc_fn() {
313 cov_mark::check!(parens_for_method_call_as_assoc_fn);
328 fn main() { S::foo(${1:&self})$0 }
334 fn suppress_arg_snippets() {
335 cov_mark::check!(suppress_arg_snippets);
336 check_edit_with_config(
337 CompletionConfig { add_call_argument_snippets: false, ..TEST_CONFIG },
340 fn with_args(x: i32, y: String) {}
341 fn main() { with_$0 }
344 fn with_args(x: i32, y: String) {}
345 fn main() { with_args($0) }
351 fn strips_underscores_from_args() {
355 fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
359 fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
360 fn main() { foo(${1:foo}, ${2:bar}, ${3:ho_ge_})$0 }
366 fn insert_ref_when_matching_local_in_scope() {
371 fn ref_arg(x: &Foo) {}
379 fn ref_arg(x: &Foo) {}
389 fn insert_mut_ref_when_matching_local_in_scope() {
394 fn ref_arg(x: &mut Foo) {}
402 fn ref_arg(x: &mut Foo) {}
405 ref_arg(${1:&mut x})$0
412 fn insert_ref_when_matching_local_in_scope_for_method() {
419 fn apply_foo(&self, x: &Foo) {}
432 fn apply_foo(&self, x: &Foo) {}
438 y.apply_foo(${1:&x})$0
445 fn trim_mut_keyword_in_func_completion() {
449 fn take_mutably(mut x: &i32) {}
456 fn take_mutably(mut x: &i32) {}
459 take_mutably(${1:x})$0