sway_lsp/capabilities/
completion.rs

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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
use crate::core::token::TokenIdent;
use lsp_types::{
    CompletionItem, CompletionItemKind, CompletionItemLabelDetails, CompletionTextEdit, Position,
    Range, TextEdit,
};
use sway_core::{
    language::ty::{TyAstNodeContent, TyDecl, TyFunctionDecl, TyFunctionParameter},
    namespace::Items,
    Engines, TypeId, TypeInfo,
};

pub(crate) fn to_completion_items(
    namespace: &Items,
    engines: &Engines,
    ident_to_complete: &TokenIdent,
    fn_decl: &TyFunctionDecl,
    position: Position,
) -> Vec<CompletionItem> {
    type_id_of_raw_ident(engines, namespace, &ident_to_complete.name, fn_decl)
        .map(|type_id| completion_items_for_type_id(engines, namespace, type_id, position))
        .unwrap_or_default()
}

/// Gathers the given [`TypeId`] struct's fields and methods and builds completion items.
fn completion_items_for_type_id(
    engines: &Engines,
    namespace: &Items,
    type_id: TypeId,
    position: Position,
) -> Vec<CompletionItem> {
    let mut completion_items = vec![];
    let type_info = engines.te().get(type_id);
    if let TypeInfo::Struct(decl_id) = &*type_info {
        let struct_decl = engines.de().get_struct(&decl_id.clone());
        for field in &struct_decl.fields {
            let item = CompletionItem {
                kind: Some(CompletionItemKind::FIELD),
                label: field.name.as_str().to_string(),
                label_details: Some(CompletionItemLabelDetails {
                    description: Some(field.type_argument.span.clone().str()),
                    detail: None,
                }),
                ..Default::default()
            };
            completion_items.push(item);
        }
    }

    for method in namespace.get_methods_for_type(engines, type_id) {
        let method = method.expect_typed();
        let fn_decl = engines.de().get_function(&method.id().clone());
        let params = &fn_decl.parameters;

        // Only show methods that take `self` as the first parameter.
        if params.first().is_some_and(TyFunctionParameter::is_self) {
            let params_short = if params.is_empty() {
                "()".to_string()
            } else {
                "(…)".to_string()
            };
            let params_edit_str = params
                .iter()
                .filter_map(|p| {
                    if p.is_self() {
                        return None;
                    }
                    Some(p.name.as_str())
                })
                .collect::<Vec<&str>>()
                .join(", ");
            let item = CompletionItem {
                kind: Some(CompletionItemKind::METHOD),
                label: format!("{}{}", method.name().clone().as_str(), params_short),
                text_edit: Some(CompletionTextEdit::Edit(TextEdit {
                    range: Range {
                        start: position,
                        end: position,
                    },
                    new_text: format!("{}({})", method.name().clone().as_str(), params_edit_str),
                })),
                label_details: Some(CompletionItemLabelDetails {
                    description: Some(fn_signature_string(engines, &fn_decl, &type_id)),
                    detail: None,
                }),
                ..Default::default()
            };
            completion_items.push(item);
        }
    }

    completion_items
}

/// Returns the [String] of the shortened function signature to display in the completion item's label details.
fn fn_signature_string(
    engines: &Engines,
    fn_decl: &TyFunctionDecl,
    parent_type_id: &TypeId,
) -> String {
    let params_str = fn_decl
        .parameters
        .iter()
        .map(|p| {
            replace_self_with_type_str(engines, p.type_argument.clone().span.str(), parent_type_id)
        })
        .collect::<Vec<String>>()
        .join(", ");
    format!(
        "fn({}) -> {}",
        params_str,
        replace_self_with_type_str(
            engines,
            fn_decl.return_type.clone().span.str(),
            parent_type_id
        )
    )
}

/// Given a [String] representing a type, replaces `Self` with the display name of the type.
fn replace_self_with_type_str(
    engines: &Engines,
    type_str: String,
    parent_type_id: &TypeId,
) -> String {
    if type_str == "Self" {
        return engines.help_out(parent_type_id).to_string();
    }
    type_str
}

/// Returns the [TypeId] of an ident that may include field accesses and may be incomplete.
/// For the first part of the ident, it looks for instantiation in the scope of the given
/// [`TyFunctionDecl`]. For example, given `a.b.c`, it will return the type ID of `c`
/// if it can resolve `a` in the given function.
fn type_id_of_raw_ident(
    engines: &Engines,
    namespace: &Items,
    ident_name: &str,
    fn_decl: &TyFunctionDecl,
) -> Option<TypeId> {
    // If this ident has no field accesses or chained methods, look for it in the local function scope.
    if !ident_name.contains('.') {
        return type_id_of_local_ident(ident_name, fn_decl);
    }

    // Otherwise, start with the first part of the ident and follow the subsequent types.
    let parts = ident_name.split('.').collect::<Vec<&str>>();
    let mut curr_type_id = type_id_of_local_ident(parts[0], fn_decl);
    let mut i = 1;

    while (i < parts.len()) && curr_type_id.is_some() {
        if parts[i].ends_with(')') {
            let method_name = parts[i].split_at(parts[i].find('(').unwrap_or(0)).0;
            curr_type_id = namespace
                .get_methods_for_type(engines, curr_type_id?)
                .into_iter()
                .find_map(|method| {
                    let method = method.expect_typed();
                    if method.name().clone().as_str() == method_name {
                        return Some(
                            engines
                                .de()
                                .get_function(&method.id().clone())
                                .return_type
                                .type_id,
                        );
                    }
                    None
                });
        } else if let TypeInfo::Struct(decl_id) = &*engines.te().get(curr_type_id.unwrap()) {
            let struct_decl = engines.de().get_struct(&decl_id.clone());
            curr_type_id = struct_decl
                .fields
                .iter()
                .find(|field| field.name.as_str() == parts[i])
                .map(|field| field.type_argument.type_id);
        }
        i += 1;
    }
    curr_type_id
}

/// Returns the [TypeId] of an ident by looking for its instantiation within the scope of the
/// given [TyFunctionDecl].
fn type_id_of_local_ident(ident_name: &str, fn_decl: &TyFunctionDecl) -> Option<TypeId> {
    fn_decl
        .parameters
        .iter()
        .find_map(|param| {
            // Check if this ident is a function parameter
            if param.name.as_str() == ident_name {
                return Some(param.type_argument.type_id);
            }
            None
        })
        .or_else(|| {
            // Check if there is a variable declaration for this ident
            fn_decl.body.contents.iter().find_map(|node| {
                if let TyAstNodeContent::Declaration(TyDecl::VariableDecl(variable_decl)) =
                    node.content.clone()
                {
                    if variable_decl.name.as_str() == ident_name {
                        return Some(variable_decl.return_type);
                    }
                }
                None
            })
        })
}