]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/render/function.rs
eliminate find_use_path and show 'as' and 'use'
[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::Fn;
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<'a>(
17     ctx: RenderContext<'a>,
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<'a>(
27     ctx: RenderContext<'a>,
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     ast_node: Fn,
44     is_method: bool,
45 }
46
47 impl<'a> FunctionRender<'a> {
48     fn new(
49         ctx: RenderContext<'a>,
50         receiver: Option<hir::Name>,
51         local_name: Option<hir::Name>,
52         fn_: hir::Function,
53         is_method: bool,
54     ) -> Option<FunctionRender<'a>> {
55         let name = local_name.unwrap_or_else(|| fn_.name(ctx.db())).to_string();
56         let ast_node = fn_.source(ctx.db())?.value;
57
58         Some(FunctionRender { ctx, name, receiver, func: fn_, ast_node, is_method })
59     }
60
61     fn render(self, import_to_add: Option<ImportEdit>) -> CompletionItem {
62         let params = self.params();
63         let call = if let Some(receiver) = &self.receiver {
64             format!("{}.{}", receiver, &self.name)
65         } else {
66             self.name.clone()
67         };
68         let mut item =
69             CompletionItem::new(CompletionKind::Reference, self.ctx.source_range(), call.clone());
70         item.kind(self.kind())
71             .set_documentation(self.ctx.docs(self.func))
72             .set_deprecated(
73                 self.ctx.is_deprecated(self.func) || self.ctx.is_deprecated_assoc_item(self.func),
74             )
75             .detail(self.detail())
76             .add_call_parens(self.ctx.completion, call.clone(), params);
77
78         if import_to_add.is_none() {
79             let db = self.ctx.db();
80             if let Some(actm) = self.func.as_assoc_item(db) {
81                 if let Some(trt) = actm.containing_trait_or_trait_impl(db) {
82                     item.trait_name(trt.name(db).to_string());
83                 }
84             }
85         }
86
87         item.add_import(import_to_add).lookup_by(self.name);
88
89         let ret_type = self.func.ret_type(self.ctx.db());
90         item.set_relevance(CompletionRelevance {
91             type_match: compute_type_match(self.ctx.completion, &ret_type),
92             exact_name_match: compute_exact_name_match(self.ctx.completion, &call),
93             ..CompletionRelevance::default()
94         });
95
96         if let Some(ref_match) = compute_ref_match(self.ctx.completion, &ret_type) {
97             // FIXME
98             // For now we don't properly calculate the edits for ref match
99             // completions on methods, so we've disabled them. See #8058.
100             if !self.is_method {
101                 item.ref_match(ref_match);
102             }
103         }
104
105         item.build()
106     }
107
108     fn detail(&self) -> String {
109         let ret_ty = self.func.ret_type(self.ctx.db());
110         let ret = if ret_ty.is_unit() {
111             // Omit the return type if it is the unit type
112             String::new()
113         } else {
114             format!(" {}", self.ty_display())
115         };
116
117         format!("fn({}){}", self.params_display(), ret)
118     }
119
120     fn params_display(&self) -> String {
121         if let Some(self_param) = self.func.self_param(self.ctx.db()) {
122             let params = self
123                 .func
124                 .assoc_fn_params(self.ctx.db())
125                 .into_iter()
126                 .skip(1) // skip the self param because we are manually handling that
127                 .map(|p| p.ty().display(self.ctx.db()).to_string());
128
129             std::iter::once(self_param.display(self.ctx.db()).to_owned()).chain(params).join(", ")
130         } else {
131             let params = self
132                 .func
133                 .assoc_fn_params(self.ctx.db())
134                 .into_iter()
135                 .map(|p| p.ty().display(self.ctx.db()).to_string())
136                 .join(", ");
137             params
138         }
139     }
140
141     fn ty_display(&self) -> String {
142         let ret_ty = self.func.ret_type(self.ctx.db());
143
144         format!("-> {}", ret_ty.display(self.ctx.db()))
145     }
146
147     fn add_arg(&self, arg: &str, ty: &hir::Type) -> String {
148         if let Some(derefed_ty) = ty.remove_ref() {
149             for (name, local) in self.ctx.completion.locals.iter() {
150                 if name == arg && local.ty(self.ctx.db()) == derefed_ty {
151                     let mutability = if ty.is_mutable_reference() { "&mut " } else { "&" };
152                     return format!("{}{}", mutability, arg);
153                 }
154             }
155         }
156         arg.to_string()
157     }
158
159     fn params(&self) -> Params {
160         let ast_params = match self.ast_node.param_list() {
161             Some(it) => it,
162             None => return Params::Named(Vec::new()),
163         };
164
165         let mut params_pats = Vec::new();
166         let params_ty = if self.ctx.completion.has_dot_receiver() || self.receiver.is_some() {
167             self.func.method_params(self.ctx.db()).unwrap_or_default()
168         } else {
169             if let Some(s) = ast_params.self_param() {
170                 cov_mark::hit!(parens_for_method_call_as_assoc_fn);
171                 params_pats.push(Some(s.to_string()));
172             }
173             self.func.assoc_fn_params(self.ctx.db())
174         };
175         params_pats
176             .extend(ast_params.params().into_iter().map(|it| it.pat().map(|it| it.to_string())));
177
178         let params = params_pats
179             .into_iter()
180             .zip(params_ty)
181             .flat_map(|(pat, param_ty)| {
182                 let pat = pat?;
183                 let name = pat;
184                 let arg = name.trim_start_matches("mut ").trim_start_matches('_');
185                 Some(self.add_arg(arg, param_ty.ty()))
186             })
187             .collect();
188         Params::Named(params)
189     }
190
191     fn kind(&self) -> CompletionItemKind {
192         if self.func.self_param(self.ctx.db()).is_some() {
193             CompletionItemKind::Method
194         } else {
195             SymbolKind::Function.into()
196         }
197     }
198 }
199
200 #[cfg(test)]
201 mod tests {
202     use crate::{
203         tests::{check_edit, check_edit_with_config, TEST_CONFIG},
204         CompletionConfig,
205     };
206
207     #[test]
208     fn inserts_parens_for_function_calls() {
209         cov_mark::check!(inserts_parens_for_function_calls);
210         check_edit(
211             "no_args",
212             r#"
213 fn no_args() {}
214 fn main() { no_$0 }
215 "#,
216             r#"
217 fn no_args() {}
218 fn main() { no_args()$0 }
219 "#,
220         );
221
222         check_edit(
223             "with_args",
224             r#"
225 fn with_args(x: i32, y: String) {}
226 fn main() { with_$0 }
227 "#,
228             r#"
229 fn with_args(x: i32, y: String) {}
230 fn main() { with_args(${1:x}, ${2:y})$0 }
231 "#,
232         );
233
234         check_edit(
235             "foo",
236             r#"
237 struct S;
238 impl S {
239     fn foo(&self) {}
240 }
241 fn bar(s: &S) { s.f$0 }
242 "#,
243             r#"
244 struct S;
245 impl S {
246     fn foo(&self) {}
247 }
248 fn bar(s: &S) { s.foo()$0 }
249 "#,
250         );
251
252         check_edit(
253             "foo",
254             r#"
255 struct S {}
256 impl S {
257     fn foo(&self, x: i32) {}
258 }
259 fn bar(s: &S) {
260     s.f$0
261 }
262 "#,
263             r#"
264 struct S {}
265 impl S {
266     fn foo(&self, x: i32) {}
267 }
268 fn bar(s: &S) {
269     s.foo(${1:x})$0
270 }
271 "#,
272         );
273
274         check_edit(
275             "foo",
276             r#"
277 struct S {}
278 impl S {
279     fn foo(&self, x: i32) {
280         $0
281     }
282 }
283 "#,
284             r#"
285 struct S {}
286 impl S {
287     fn foo(&self, x: i32) {
288         self.foo(${1:x})$0
289     }
290 }
291 "#,
292         );
293     }
294
295     #[test]
296     fn parens_for_method_call_as_assoc_fn() {
297         cov_mark::check!(parens_for_method_call_as_assoc_fn);
298         check_edit(
299             "foo",
300             r#"
301 struct S;
302 impl S {
303     fn foo(&self) {}
304 }
305 fn main() { S::f$0 }
306 "#,
307             r#"
308 struct S;
309 impl S {
310     fn foo(&self) {}
311 }
312 fn main() { S::foo(${1:&self})$0 }
313 "#,
314         );
315     }
316
317     #[test]
318     fn suppress_arg_snippets() {
319         cov_mark::check!(suppress_arg_snippets);
320         check_edit_with_config(
321             CompletionConfig { add_call_argument_snippets: false, ..TEST_CONFIG },
322             "with_args",
323             r#"
324 fn with_args(x: i32, y: String) {}
325 fn main() { with_$0 }
326 "#,
327             r#"
328 fn with_args(x: i32, y: String) {}
329 fn main() { with_args($0) }
330 "#,
331         );
332     }
333
334     #[test]
335     fn strips_underscores_from_args() {
336         check_edit(
337             "foo",
338             r#"
339 fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
340 fn main() { f$0 }
341 "#,
342             r#"
343 fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
344 fn main() { foo(${1:foo}, ${2:bar}, ${3:ho_ge_})$0 }
345 "#,
346         );
347     }
348
349     #[test]
350     fn insert_ref_when_matching_local_in_scope() {
351         check_edit(
352             "ref_arg",
353             r#"
354 struct Foo {}
355 fn ref_arg(x: &Foo) {}
356 fn main() {
357     let x = Foo {};
358     ref_ar$0
359 }
360 "#,
361             r#"
362 struct Foo {}
363 fn ref_arg(x: &Foo) {}
364 fn main() {
365     let x = Foo {};
366     ref_arg(${1:&x})$0
367 }
368 "#,
369         );
370     }
371
372     #[test]
373     fn insert_mut_ref_when_matching_local_in_scope() {
374         check_edit(
375             "ref_arg",
376             r#"
377 struct Foo {}
378 fn ref_arg(x: &mut Foo) {}
379 fn main() {
380     let x = Foo {};
381     ref_ar$0
382 }
383 "#,
384             r#"
385 struct Foo {}
386 fn ref_arg(x: &mut Foo) {}
387 fn main() {
388     let x = Foo {};
389     ref_arg(${1:&mut x})$0
390 }
391 "#,
392         );
393     }
394
395     #[test]
396     fn insert_ref_when_matching_local_in_scope_for_method() {
397         check_edit(
398             "apply_foo",
399             r#"
400 struct Foo {}
401 struct Bar {}
402 impl Bar {
403     fn apply_foo(&self, x: &Foo) {}
404 }
405
406 fn main() {
407     let x = Foo {};
408     let y = Bar {};
409     y.$0
410 }
411 "#,
412             r#"
413 struct Foo {}
414 struct Bar {}
415 impl Bar {
416     fn apply_foo(&self, x: &Foo) {}
417 }
418
419 fn main() {
420     let x = Foo {};
421     let y = Bar {};
422     y.apply_foo(${1:&x})$0
423 }
424 "#,
425         );
426     }
427
428     #[test]
429     fn trim_mut_keyword_in_func_completion() {
430         check_edit(
431             "take_mutably",
432             r#"
433 fn take_mutably(mut x: &i32) {}
434
435 fn main() {
436     take_m$0
437 }
438 "#,
439             r#"
440 fn take_mutably(mut x: &i32) {}
441
442 fn main() {
443     take_mutably(${1:x})$0
444 }
445 "#,
446         );
447     }
448 }