aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide_api/src/completion/complete_struct_pattern.rs
blob: d0dde593055985924f907c8222e229d056767c07 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use hir::Substs;

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

pub(super) fn complete_struct_pattern(acc: &mut Completions, ctx: &CompletionContext) {
    let (ty, variant) = match ctx.struct_lit_pat.as_ref().and_then(|it| {
        Some((
            ctx.analyzer.type_of_pat(ctx.db, &it.clone().into())?,
            ctx.analyzer.resolve_struct_pattern(it)?,
        ))
    }) {
        Some(it) => it,
        _ => return,
    };
    let substs = &ty.substs().unwrap_or_else(Substs::empty);

    for field in variant.fields(ctx.db) {
        acc.add_field(ctx, field, substs);
    }
}

#[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_pattern_field() {
        let completions = complete(
            r"
            struct S { foo: u32 }

            fn process(f: S) {
                match f {
                    S { f<|>: 92 } => (),
                }
            }
            ",
        );
        assert_debug_snapshot_matches!(completions, @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "foo",
       ⋮        source_range: [117; 118),
       ⋮        delete: [117; 118),
       ⋮        insert: "foo",
       ⋮        kind: Field,
       ⋮        detail: "u32",
       ⋮    },
       ⋮]
        "###);
    }

    #[test]
    fn test_struct_pattern_enum_variant() {
        let completions = complete(
            r"
            enum E {
                S { foo: u32, bar: () }
            }

            fn process(e: E) {
                match e {
                    E::S { <|> } => (),
                }
            }
            ",
        );
        assert_debug_snapshot_matches!(completions, @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "bar",
       ⋮        source_range: [161; 161),
       ⋮        delete: [161; 161),
       ⋮        insert: "bar",
       ⋮        kind: Field,
       ⋮        detail: "()",
       ⋮    },
       ⋮    CompletionItem {
       ⋮        label: "foo",
       ⋮        source_range: [161; 161),
       ⋮        delete: [161; 161),
       ⋮        insert: "foo",
       ⋮        kind: Field,
       ⋮        detail: "u32",
       ⋮    },
       ⋮]
        "###);
    }
}