aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide_api/src/completion/complete_struct_literal.rs
blob: 35fb2111336a8ccfe044fb857a1cc3fabad3ff45 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use hir::AdtDef;

use crate::completion::{CompletionContext, Completions};

/// Complete fields in fields literals.
pub(super) fn complete_struct_literal(acc: &mut Completions, ctx: &CompletionContext) {
    let ty = match ctx.struct_lit_syntax.and_then(|it| ctx.analyzer.type_of(ctx.db, it.into())) {
        Some(it) => it,
        None => return,
    };
    let (adt, substs) = match ty.as_adt() {
        Some(res) => res,
        _ => return,
    };
    match adt {
        AdtDef::Struct(s) => {
            for field in s.fields(ctx.db) {
                acc.add_field(ctx, field, substs);
            }
        }

        // FIXME unions
        AdtDef::Union(_) => (),
        AdtDef::Enum(_) => (),
    };
}

#[cfg(test)]
mod tests {
    use crate::completion::{do_completion, CompletionItem, CompletionKind};
    use insta::assert_debug_snapshot_matches;

    fn complete(code: &str) -> Vec<CompletionItem> {
        do_completion(code, CompletionKind::Reference)
    }

    #[test]
    fn test_struct_literal_field() {
        let completions = complete(
            r"
            struct A { the_field: u32 }
            fn foo() {
               A { the<|> }
            }
            ",
        );
        assert_debug_snapshot_matches!(completions, @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "the_field",
       ⋮        source_range: [83; 86),
       ⋮        delete: [83; 86),
       ⋮        insert: "the_field",
       ⋮        kind: Field,
       ⋮        detail: "u32",
       ⋮    },
       ⋮]
        "###);
    }
}