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 = if let Some(receiver) = &self.receiver {
78 format!("{}.{}", receiver, &self.name)
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 item.add_import(import_to_add).lookup_by(self.name);
103 let ret_type = self.func.ret_type(self.ctx.db());
104 item.set_relevance(CompletionRelevance {
105 type_match: compute_type_match(self.ctx.completion, &ret_type),
106 exact_name_match: compute_exact_name_match(self.ctx.completion, &call),
107 ..CompletionRelevance::default()
110 if let Some(ref_match) = compute_ref_match(self.ctx.completion, &ret_type) {
112 // For now we don't properly calculate the edits for ref match
113 // completions on methods, so we've disabled them. See #8058.
115 item.ref_match(ref_match);
122 fn detail(&self) -> String {
123 let ret_ty = self.func.ret_type(self.ctx.db());
124 let ret = if ret_ty.is_unit() {
125 // Omit the return type if it is the unit type
128 format!(" {}", self.ty_display())
131 format!("fn({}){}", self.params_display(), ret)
134 fn params_display(&self) -> String {
135 if let Some(self_param) = self.func.self_param(self.ctx.db()) {
138 .assoc_fn_params(self.ctx.db())
140 .skip(1) // skip the self param because we are manually handling that
141 .map(|p| p.ty().display(self.ctx.db()).to_string());
143 std::iter::once(self_param.display(self.ctx.db()).to_owned()).chain(params).join(", ")
147 .assoc_fn_params(self.ctx.db())
149 .map(|p| p.ty().display(self.ctx.db()).to_string())
155 fn ty_display(&self) -> String {
156 let ret_ty = self.func.ret_type(self.ctx.db());
158 format!("-> {}", ret_ty.display(self.ctx.db()))
161 fn add_arg(&self, arg: &str, ty: &hir::Type) -> String {
162 if let Some(derefed_ty) = ty.remove_ref() {
163 for (name, local) in self.ctx.completion.locals.iter() {
164 if name == arg && local.ty(self.ctx.db()) == derefed_ty {
165 let mutability = if ty.is_mutable_reference() { "&mut " } else { "&" };
166 return format!("{}{}", mutability, arg);
173 fn params(&self) -> Params {
174 let ast_params = match self.ast_node.param_list() {
176 None => return Params::Named(Vec::new()),
179 let mut params_pats = Vec::new();
180 let params_ty = if self.ctx.completion.has_dot_receiver() || self.receiver.is_some() {
181 self.func.method_params(self.ctx.db()).unwrap_or_default()
183 if let Some(s) = ast_params.self_param() {
184 cov_mark::hit!(parens_for_method_call_as_assoc_fn);
185 params_pats.push(Some(s.to_string()));
187 self.func.assoc_fn_params(self.ctx.db())
190 .extend(ast_params.params().into_iter().map(|it| it.pat().map(|it| it.to_string())));
192 let params = params_pats
195 .flat_map(|(pat, param_ty)| {
198 let arg = name.trim_start_matches("mut ").trim_start_matches('_');
199 Some(self.add_arg(arg, param_ty.ty()))
202 Params::Named(params)
205 fn kind(&self) -> CompletionItemKind {
206 if self.func.self_param(self.ctx.db()).is_some() {
207 CompletionItemKind::Method
209 SymbolKind::Function.into()
217 tests::{check_edit, check_edit_with_config, TEST_CONFIG},
222 fn inserts_parens_for_function_calls() {
223 cov_mark::check!(inserts_parens_for_function_calls);
232 fn main() { no_args()$0 }
239 fn with_args(x: i32, y: String) {}
240 fn main() { with_$0 }
243 fn with_args(x: i32, y: String) {}
244 fn main() { with_args(${1:x}, ${2:y})$0 }
255 fn bar(s: &S) { s.f$0 }
262 fn bar(s: &S) { s.foo()$0 }
271 fn foo(&self, x: i32) {}
280 fn foo(&self, x: i32) {}
293 fn foo(&self, x: i32) {
301 fn foo(&self, x: i32) {
310 fn parens_for_method_call_as_assoc_fn() {
311 cov_mark::check!(parens_for_method_call_as_assoc_fn);
326 fn main() { S::foo(${1:&self})$0 }
332 fn suppress_arg_snippets() {
333 cov_mark::check!(suppress_arg_snippets);
334 check_edit_with_config(
335 CompletionConfig { add_call_argument_snippets: false, ..TEST_CONFIG },
338 fn with_args(x: i32, y: String) {}
339 fn main() { with_$0 }
342 fn with_args(x: i32, y: String) {}
343 fn main() { with_args($0) }
349 fn strips_underscores_from_args() {
353 fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
357 fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
358 fn main() { foo(${1:foo}, ${2:bar}, ${3:ho_ge_})$0 }
364 fn insert_ref_when_matching_local_in_scope() {
369 fn ref_arg(x: &Foo) {}
377 fn ref_arg(x: &Foo) {}
387 fn insert_mut_ref_when_matching_local_in_scope() {
392 fn ref_arg(x: &mut Foo) {}
400 fn ref_arg(x: &mut Foo) {}
403 ref_arg(${1:&mut x})$0
410 fn insert_ref_when_matching_local_in_scope_for_method() {
417 fn apply_foo(&self, x: &Foo) {}
430 fn apply_foo(&self, x: &Foo) {}
436 y.apply_foo(${1:&x})$0
443 fn trim_mut_keyword_in_func_completion() {
447 fn take_mutably(mut x: &i32) {}
454 fn take_mutably(mut x: &i32) {}
457 take_mutably(${1:x})$0