aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_analysis/src/completion/complete_dot.rs
blob: f24835d17779cacfea67ea7570a719e1ecc1be7f (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
use ra_syntax::ast::AstNode;
use hir::{Ty, Def};

use crate::Cancelable;
use crate::completion::{CompletionContext, Completions, CompletionKind, CompletionItem, CompletionItemKind};

/// Complete dot accesses, i.e. fields or methods (currently only fields).
pub(super) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) -> Cancelable<()> {
    let (function, receiver) = match (&ctx.function, ctx.dot_receiver) {
        (Some(function), Some(receiver)) => (function, receiver),
        _ => return Ok(()),
    };
    let infer_result = function.infer(ctx.db)?;
    let receiver_ty = if let Some(ty) = infer_result.type_of_node(receiver.syntax()) {
        ty
    } else {
        return Ok(());
    };
    if !ctx.is_method_call {
        complete_fields(acc, ctx, receiver_ty)?;
    }
    Ok(())
}

fn complete_fields(acc: &mut Completions, ctx: &CompletionContext, receiver: Ty) -> Cancelable<()> {
    // TODO: autoderef etc.
    match receiver {
        Ty::Adt { def_id, .. } => {
            match def_id.resolve(ctx.db)? {
                Def::Struct(s) => {
                    let variant_data = s.variant_data(ctx.db)?;
                    for field in variant_data.fields() {
                        CompletionItem::new(CompletionKind::Reference, field.name().to_string())
                            .kind(CompletionItemKind::Field)
                            .add_to(acc);
                    }
                }
                // TODO unions
                _ => {}
            }
        }
        Ty::Tuple(fields) => {
            for (i, _ty) in fields.iter().enumerate() {
                CompletionItem::new(CompletionKind::Reference, i.to_string())
                    .kind(CompletionItemKind::Field)
                    .add_to(acc);
            }
        }
        _ => {}
    };
    Ok(())
}

#[cfg(test)]
mod tests {
    use crate::completion::*;

    fn check_ref_completion(code: &str, expected_completions: &str) {
        check_completion(code, expected_completions, CompletionKind::Reference);
    }

    #[test]
    fn test_struct_field_completion() {
        check_ref_completion(
            r"
            struct A { the_field: u32 }
            fn foo(a: A) {
               a.<|>
            }
            ",
            r#"the_field"#,
        );
    }

    #[test]
    fn test_no_struct_field_completion_for_method_call() {
        check_ref_completion(
            r"
            struct A { the_field: u32 }
            fn foo(a: A) {
               a.<|>()
            }
            ",
            r#""#,
        );
    }
}