aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide_api/src/completion/complete_struct_literal.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_ide_api/src/completion/complete_struct_literal.rs')
-rw-r--r--crates/ra_ide_api/src/completion/complete_struct_literal.rs73
1 files changed, 73 insertions, 0 deletions
diff --git a/crates/ra_ide_api/src/completion/complete_struct_literal.rs b/crates/ra_ide_api/src/completion/complete_struct_literal.rs
new file mode 100644
index 000000000..f8dd2baad
--- /dev/null
+++ b/crates/ra_ide_api/src/completion/complete_struct_literal.rs
@@ -0,0 +1,73 @@
1use hir::{Ty, AdtDef, Docs};
2
3use crate::completion::{CompletionContext, Completions, CompletionItem, CompletionItemKind};
4use crate::completion::completion_item::CompletionKind;
5
6/// Complete fields in fields literals.
7pub(super) fn complete_struct_literal(acc: &mut Completions, ctx: &CompletionContext) {
8 let (function, struct_lit) = match (&ctx.function, ctx.struct_lit_syntax) {
9 (Some(function), Some(struct_lit)) => (function, struct_lit),
10 _ => return,
11 };
12 let infer_result = function.infer(ctx.db);
13 let syntax_mapping = function.body_syntax_mapping(ctx.db);
14 let expr = match syntax_mapping.node_expr(struct_lit.into()) {
15 Some(expr) => expr,
16 None => return,
17 };
18 let ty = infer_result[expr].clone();
19 let (adt, substs) = match ty {
20 Ty::Adt { def_id, ref substs, .. } => (def_id, substs),
21 _ => return,
22 };
23 match adt {
24 AdtDef::Struct(s) => {
25 for field in s.fields(ctx.db) {
26 CompletionItem::new(
27 CompletionKind::Reference,
28 ctx.source_range(),
29 field.name(ctx.db).to_string(),
30 )
31 .kind(CompletionItemKind::Field)
32 .detail(field.ty(ctx.db).subst(substs).to_string())
33 .set_documentation(field.docs(ctx.db))
34 .add_to(acc);
35 }
36 }
37
38 // TODO unions
39 AdtDef::Enum(_) => (),
40 };
41}
42
43#[cfg(test)]
44mod tests {
45 use insta::assert_debug_snapshot_matches;
46 use crate::completion::{CompletionItem, CompletionKind};
47
48 fn complete(code: &str) -> Vec<CompletionItem> {
49 crate::completion::completion_item::do_completion(code, CompletionKind::Reference)
50 }
51
52 #[test]
53 fn test_struct_literal_field() {
54 let completions = complete(
55 r"
56 struct A { the_field: u32 }
57 fn foo() {
58 A { the<|> }
59 }
60 ",
61 );
62 assert_debug_snapshot_matches!(completions, @r###"[
63 CompletionItem {
64 label: "the_field",
65 source_range: [83; 86),
66 delete: [83; 86),
67 insert: "the_field",
68 kind: Field,
69 detail: "u32"
70 }
71]"###);
72 }
73}