]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/render/function.rs
Merge #10459
[rust.git] / crates / ide_completion / src / render / function.rs
1 //! Renderer for function calls.
2
3 use hir::{AsAssocItem, HasSource, HirDisplay};
4 use ide_db::SymbolKind;
5 use itertools::Itertools;
6 use syntax::ast;
7
8 use crate::{
9     item::{CompletionItem, CompletionItemKind, CompletionKind, CompletionRelevance, ImportEdit},
10     render::{
11         builder_ext::Params, compute_exact_name_match, compute_ref_match, compute_type_match,
12         RenderContext,
13     },
14 };
15
16 pub(crate) fn render_fn(
17     ctx: RenderContext<'_>,
18     import_to_add: Option<ImportEdit>,
19     local_name: Option<hir::Name>,
20     fn_: hir::Function,
21 ) -> Option<CompletionItem> {
22     let _p = profile::span("render_fn");
23     Some(FunctionRender::new(ctx, None, local_name, fn_, false)?.render(import_to_add))
24 }
25
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>,
31     fn_: hir::Function,
32 ) -> Option<CompletionItem> {
33     let _p = profile::span("render_method");
34     Some(FunctionRender::new(ctx, receiver, local_name, fn_, true)?.render(import_to_add))
35 }
36
37 #[derive(Debug)]
38 struct FunctionRender<'a> {
39     ctx: RenderContext<'a>,
40     name: String,
41     receiver: Option<hir::Name>,
42     func: hir::Function,
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.
47     ///
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.
51     ///
52     /// Alternatively we can reconstruct params from the function body, but that
53     /// would require parsing anyway.
54     ///
55     /// It seems that just using `ast` is the best choice -- most of parses
56     /// should be cached anyway.
57     ast_node: ast::Fn,
58     is_method: bool,
59 }
60
61 impl<'a> FunctionRender<'a> {
62     fn new(
63         ctx: RenderContext<'a>,
64         receiver: Option<hir::Name>,
65         local_name: Option<hir::Name>,
66         fn_: hir::Function,
67         is_method: bool,
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;
71
72         Some(FunctionRender { ctx, name, receiver, func: fn_, ast_node, is_method })
73     }
74
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(),
80         };
81         let mut item =
82             CompletionItem::new(CompletionKind::Reference, self.ctx.source_range(), call.clone());
83         item.kind(self.kind())
84             .set_documentation(self.ctx.docs(self.func))
85             .set_deprecated(
86                 self.ctx.is_deprecated(self.func) || self.ctx.is_deprecated_assoc_item(self.func),
87             )
88             .detail(self.detail())
89             .add_call_parens(self.ctx.completion, call.clone(), params);
90
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());
96                 }
97             }
98         }
99
100         if let Some(import_to_add) = import_to_add {
101             item.add_import(import_to_add);
102         }
103         item.lookup_by(self.name);
104
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()
110         });
111
112         if let Some(ref_match) = compute_ref_match(self.ctx.completion, &ret_type) {
113             // FIXME
114             // For now we don't properly calculate the edits for ref match
115             // completions on methods, so we've disabled them. See #8058.
116             if !self.is_method {
117                 item.ref_match(ref_match);
118             }
119         }
120
121         item.build()
122     }
123
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
128             String::new()
129         } else {
130             format!(" {}", self.ty_display())
131         };
132
133         format!("fn({}){}", self.params_display(), ret)
134     }
135
136     fn params_display(&self) -> String {
137         if let Some(self_param) = self.func.self_param(self.ctx.db()) {
138             let params = self
139                 .func
140                 .assoc_fn_params(self.ctx.db())
141                 .into_iter()
142                 .skip(1) // skip the self param because we are manually handling that
143                 .map(|p| p.ty().display(self.ctx.db()).to_string());
144
145             std::iter::once(self_param.display(self.ctx.db()).to_owned()).chain(params).join(", ")
146         } else {
147             let params = self
148                 .func
149                 .assoc_fn_params(self.ctx.db())
150                 .into_iter()
151                 .map(|p| p.ty().display(self.ctx.db()).to_string())
152                 .join(", ");
153             params
154         }
155     }
156
157     fn ty_display(&self) -> String {
158         let ret_ty = self.func.ret_type(self.ctx.db());
159
160         format!("-> {}", ret_ty.display(self.ctx.db()))
161     }
162
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);
169                 }
170             }
171         }
172         arg.to_string()
173     }
174
175     fn params(&self) -> Params {
176         let ast_params = match self.ast_node.param_list() {
177             Some(it) => it,
178             None => return Params::Named(Vec::new()),
179         };
180
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()
184         } else {
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()));
188             }
189             self.func.assoc_fn_params(self.ctx.db())
190         };
191         params_pats
192             .extend(ast_params.params().into_iter().map(|it| it.pat().map(|it| it.to_string())));
193
194         let params = params_pats
195             .into_iter()
196             .zip(params_ty)
197             .flat_map(|(pat, param_ty)| {
198                 let pat = pat?;
199                 let name = pat;
200                 let arg = name.trim_start_matches("mut ").trim_start_matches('_');
201                 Some(self.add_arg(arg, param_ty.ty()))
202             })
203             .collect();
204         Params::Named(params)
205     }
206
207     fn kind(&self) -> CompletionItemKind {
208         if self.func.self_param(self.ctx.db()).is_some() {
209             CompletionItemKind::Method
210         } else {
211             SymbolKind::Function.into()
212         }
213     }
214 }
215
216 #[cfg(test)]
217 mod tests {
218     use crate::{
219         tests::{check_edit, check_edit_with_config, TEST_CONFIG},
220         CompletionConfig,
221     };
222
223     #[test]
224     fn inserts_parens_for_function_calls() {
225         cov_mark::check!(inserts_parens_for_function_calls);
226         check_edit(
227             "no_args",
228             r#"
229 fn no_args() {}
230 fn main() { no_$0 }
231 "#,
232             r#"
233 fn no_args() {}
234 fn main() { no_args()$0 }
235 "#,
236         );
237
238         check_edit(
239             "with_args",
240             r#"
241 fn with_args(x: i32, y: String) {}
242 fn main() { with_$0 }
243 "#,
244             r#"
245 fn with_args(x: i32, y: String) {}
246 fn main() { with_args(${1:x}, ${2:y})$0 }
247 "#,
248         );
249
250         check_edit(
251             "foo",
252             r#"
253 struct S;
254 impl S {
255     fn foo(&self) {}
256 }
257 fn bar(s: &S) { s.f$0 }
258 "#,
259             r#"
260 struct S;
261 impl S {
262     fn foo(&self) {}
263 }
264 fn bar(s: &S) { s.foo()$0 }
265 "#,
266         );
267
268         check_edit(
269             "foo",
270             r#"
271 struct S {}
272 impl S {
273     fn foo(&self, x: i32) {}
274 }
275 fn bar(s: &S) {
276     s.f$0
277 }
278 "#,
279             r#"
280 struct S {}
281 impl S {
282     fn foo(&self, x: i32) {}
283 }
284 fn bar(s: &S) {
285     s.foo(${1:x})$0
286 }
287 "#,
288         );
289
290         check_edit(
291             "foo",
292             r#"
293 struct S {}
294 impl S {
295     fn foo(&self, x: i32) {
296         $0
297     }
298 }
299 "#,
300             r#"
301 struct S {}
302 impl S {
303     fn foo(&self, x: i32) {
304         self.foo(${1:x})$0
305     }
306 }
307 "#,
308         );
309     }
310
311     #[test]
312     fn parens_for_method_call_as_assoc_fn() {
313         cov_mark::check!(parens_for_method_call_as_assoc_fn);
314         check_edit(
315             "foo",
316             r#"
317 struct S;
318 impl S {
319     fn foo(&self) {}
320 }
321 fn main() { S::f$0 }
322 "#,
323             r#"
324 struct S;
325 impl S {
326     fn foo(&self) {}
327 }
328 fn main() { S::foo(${1:&self})$0 }
329 "#,
330         );
331     }
332
333     #[test]
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 },
338             "with_args",
339             r#"
340 fn with_args(x: i32, y: String) {}
341 fn main() { with_$0 }
342 "#,
343             r#"
344 fn with_args(x: i32, y: String) {}
345 fn main() { with_args($0) }
346 "#,
347         );
348     }
349
350     #[test]
351     fn strips_underscores_from_args() {
352         check_edit(
353             "foo",
354             r#"
355 fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
356 fn main() { f$0 }
357 "#,
358             r#"
359 fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
360 fn main() { foo(${1:foo}, ${2:bar}, ${3:ho_ge_})$0 }
361 "#,
362         );
363     }
364
365     #[test]
366     fn insert_ref_when_matching_local_in_scope() {
367         check_edit(
368             "ref_arg",
369             r#"
370 struct Foo {}
371 fn ref_arg(x: &Foo) {}
372 fn main() {
373     let x = Foo {};
374     ref_ar$0
375 }
376 "#,
377             r#"
378 struct Foo {}
379 fn ref_arg(x: &Foo) {}
380 fn main() {
381     let x = Foo {};
382     ref_arg(${1:&x})$0
383 }
384 "#,
385         );
386     }
387
388     #[test]
389     fn insert_mut_ref_when_matching_local_in_scope() {
390         check_edit(
391             "ref_arg",
392             r#"
393 struct Foo {}
394 fn ref_arg(x: &mut Foo) {}
395 fn main() {
396     let x = Foo {};
397     ref_ar$0
398 }
399 "#,
400             r#"
401 struct Foo {}
402 fn ref_arg(x: &mut Foo) {}
403 fn main() {
404     let x = Foo {};
405     ref_arg(${1:&mut x})$0
406 }
407 "#,
408         );
409     }
410
411     #[test]
412     fn insert_ref_when_matching_local_in_scope_for_method() {
413         check_edit(
414             "apply_foo",
415             r#"
416 struct Foo {}
417 struct Bar {}
418 impl Bar {
419     fn apply_foo(&self, x: &Foo) {}
420 }
421
422 fn main() {
423     let x = Foo {};
424     let y = Bar {};
425     y.$0
426 }
427 "#,
428             r#"
429 struct Foo {}
430 struct Bar {}
431 impl Bar {
432     fn apply_foo(&self, x: &Foo) {}
433 }
434
435 fn main() {
436     let x = Foo {};
437     let y = Bar {};
438     y.apply_foo(${1:&x})$0
439 }
440 "#,
441         );
442     }
443
444     #[test]
445     fn trim_mut_keyword_in_func_completion() {
446         check_edit(
447             "take_mutably",
448             r#"
449 fn take_mutably(mut x: &i32) {}
450
451 fn main() {
452     take_m$0
453 }
454 "#,
455             r#"
456 fn take_mutably(mut x: &i32) {}
457
458 fn main() {
459     take_mutably(${1:x})$0
460 }
461 "#,
462         );
463     }
464 }