]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide_api/src/completion/presentation.rs
move function rendering to presentation
[rust.git] / crates / ra_ide_api / src / completion / presentation.rs
1 //! This modules takes care of rendering various defenitions as completion items.
2 use test_utils::tested_by;
3 use hir::Docs;
4
5 use crate::completion::{
6     Completions, CompletionKind, CompletionItemKind, CompletionContext, CompletionItem,
7     function_label,
8 };
9
10 impl Completions {
11     pub(crate) fn add_field(
12         &mut self,
13         kind: CompletionKind,
14         ctx: &CompletionContext,
15         field: hir::StructField,
16         substs: &hir::Substs,
17     ) {
18         CompletionItem::new(kind, ctx.source_range(), field.name(ctx.db).to_string())
19             .kind(CompletionItemKind::Field)
20             .detail(field.ty(ctx.db).subst(substs).to_string())
21             .set_documentation(field.docs(ctx.db))
22             .add_to(self);
23     }
24
25     pub(crate) fn add_pos_field(
26         &mut self,
27         kind: CompletionKind,
28         ctx: &CompletionContext,
29         field: usize,
30         ty: &hir::Ty,
31     ) {
32         CompletionItem::new(kind, ctx.source_range(), field.to_string())
33             .kind(CompletionItemKind::Field)
34             .detail(ty.to_string())
35             .add_to(self);
36     }
37
38     pub(crate) fn add_function(
39         &mut self,
40         kind: CompletionKind,
41         ctx: &CompletionContext,
42         func: hir::Function,
43     ) {
44         let sig = func.signature(ctx.db);
45
46         let mut builder = CompletionItem::new(kind, ctx.source_range(), sig.name().to_string())
47             .kind(if sig.has_self_param() {
48                 CompletionItemKind::Method
49             } else {
50                 CompletionItemKind::Function
51             })
52             .set_documentation(func.docs(ctx.db))
53             .set_detail(function_item_label(ctx, func));
54         // If not an import, add parenthesis automatically.
55         if ctx.use_item_syntax.is_none() && !ctx.is_call {
56             tested_by!(inserts_parens_for_function_calls);
57             let snippet =
58                 if sig.params().is_empty() || sig.has_self_param() && sig.params().len() == 1 {
59                     format!("{}()$0", sig.name())
60                 } else {
61                     format!("{}($0)", sig.name())
62                 };
63             builder = builder.insert_snippet(snippet);
64         }
65         self.add(builder)
66     }
67 }
68
69 fn function_item_label(ctx: &CompletionContext, function: hir::Function) -> Option<String> {
70     let node = function.source(ctx.db).1;
71     function_label(&node)
72 }