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 item.add_import(import_to_add).lookup_by(self.name);
102 let ret_type = self.func.ret_type(self.ctx.db());
103 item.set_relevance(CompletionRelevance {
104 type_match: compute_type_match(self.ctx.completion, &ret_type),
105 exact_name_match: compute_exact_name_match(self.ctx.completion, &call),
106 ..CompletionRelevance::default()
109 if let Some(ref_match) = compute_ref_match(self.ctx.completion, &ret_type) {
111 // For now we don't properly calculate the edits for ref match
112 // completions on methods, so we've disabled them. See #8058.
114 item.ref_match(ref_match);
121 fn detail(&self) -> String {
122 let ret_ty = self.func.ret_type(self.ctx.db());
123 let ret = if ret_ty.is_unit() {
124 // Omit the return type if it is the unit type
127 format!(" {}", self.ty_display())
130 format!("fn({}){}", self.params_display(), ret)
133 fn params_display(&self) -> String {
134 if let Some(self_param) = self.func.self_param(self.ctx.db()) {
137 .assoc_fn_params(self.ctx.db())
139 .skip(1) // skip the self param because we are manually handling that
140 .map(|p| p.ty().display(self.ctx.db()).to_string());
142 std::iter::once(self_param.display(self.ctx.db()).to_owned()).chain(params).join(", ")
146 .assoc_fn_params(self.ctx.db())
148 .map(|p| p.ty().display(self.ctx.db()).to_string())
154 fn ty_display(&self) -> String {
155 let ret_ty = self.func.ret_type(self.ctx.db());
157 format!("-> {}", ret_ty.display(self.ctx.db()))
160 fn add_arg(&self, arg: &str, ty: &hir::Type) -> String {
161 if let Some(derefed_ty) = ty.remove_ref() {
162 for (name, local) in self.ctx.completion.locals.iter() {
163 if name == arg && local.ty(self.ctx.db()) == derefed_ty {
164 let mutability = if ty.is_mutable_reference() { "&mut " } else { "&" };
165 return format!("{}{}", mutability, arg);
172 fn params(&self) -> Params {
173 let ast_params = match self.ast_node.param_list() {
175 None => return Params::Named(Vec::new()),
178 let mut params_pats = Vec::new();
179 let params_ty = if self.ctx.completion.has_dot_receiver() || self.receiver.is_some() {
180 self.func.method_params(self.ctx.db()).unwrap_or_default()
182 if let Some(s) = ast_params.self_param() {
183 cov_mark::hit!(parens_for_method_call_as_assoc_fn);
184 params_pats.push(Some(s.to_string()));
186 self.func.assoc_fn_params(self.ctx.db())
189 .extend(ast_params.params().into_iter().map(|it| it.pat().map(|it| it.to_string())));
191 let params = params_pats
194 .flat_map(|(pat, param_ty)| {
197 let arg = name.trim_start_matches("mut ").trim_start_matches('_');
198 Some(self.add_arg(arg, param_ty.ty()))
201 Params::Named(params)
204 fn kind(&self) -> CompletionItemKind {
205 if self.func.self_param(self.ctx.db()).is_some() {
206 CompletionItemKind::Method
208 SymbolKind::Function.into()
216 tests::{check_edit, check_edit_with_config, TEST_CONFIG},
221 fn inserts_parens_for_function_calls() {
222 cov_mark::check!(inserts_parens_for_function_calls);
231 fn main() { no_args()$0 }
238 fn with_args(x: i32, y: String) {}
239 fn main() { with_$0 }
242 fn with_args(x: i32, y: String) {}
243 fn main() { with_args(${1:x}, ${2:y})$0 }
254 fn bar(s: &S) { s.f$0 }
261 fn bar(s: &S) { s.foo()$0 }
270 fn foo(&self, x: i32) {}
279 fn foo(&self, x: i32) {}
292 fn foo(&self, x: i32) {
300 fn foo(&self, x: i32) {
309 fn parens_for_method_call_as_assoc_fn() {
310 cov_mark::check!(parens_for_method_call_as_assoc_fn);
325 fn main() { S::foo(${1:&self})$0 }
331 fn suppress_arg_snippets() {
332 cov_mark::check!(suppress_arg_snippets);
333 check_edit_with_config(
334 CompletionConfig { add_call_argument_snippets: false, ..TEST_CONFIG },
337 fn with_args(x: i32, y: String) {}
338 fn main() { with_$0 }
341 fn with_args(x: i32, y: String) {}
342 fn main() { with_args($0) }
348 fn strips_underscores_from_args() {
352 fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
356 fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
357 fn main() { foo(${1:foo}, ${2:bar}, ${3:ho_ge_})$0 }
363 fn insert_ref_when_matching_local_in_scope() {
368 fn ref_arg(x: &Foo) {}
376 fn ref_arg(x: &Foo) {}
386 fn insert_mut_ref_when_matching_local_in_scope() {
391 fn ref_arg(x: &mut Foo) {}
399 fn ref_arg(x: &mut Foo) {}
402 ref_arg(${1:&mut x})$0
409 fn insert_ref_when_matching_local_in_scope_for_method() {
416 fn apply_foo(&self, x: &Foo) {}
429 fn apply_foo(&self, x: &Foo) {}
435 y.apply_foo(${1:&x})$0
442 fn trim_mut_keyword_in_func_completion() {
446 fn take_mutably(mut x: &i32) {}
453 fn take_mutably(mut x: &i32) {}
456 take_mutably(${1:x})$0