rustcodegraph 1.2.10

Local-first code intelligence graph and CLI for AI agents
Documentation
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! Rust translation of `src/extraction/languages/kotlin.ts`.

use crate::extraction::tree_sitter_helpers::{get_child_by_field, get_node_text};
use crate::extraction::tree_sitter_types::{
    ClassClassification, ExtractorContext, ImportInfo, LanguageExtractor, NodeExtra, Visibility,
};
use crate::types::NodeKind;
use crate::web_tree_sitter::SyntaxNode;

pub struct KotlinExtractor;

pub const KOTLIN_EXTRACTOR: KotlinExtractor = KotlinExtractor;

pub fn kotlin_extractor() -> &'static KotlinExtractor {
    &KOTLIN_EXTRACTOR
}

const KOTLIN_NON_CLASS_RETURN: &[&str] = &["Unit", "Nothing"];

fn extract_kotlin_return_type(node: &SyntaxNode, source: &str) -> Option<String> {
    // Kotlin 返回类型出现在参数列表之后;遇到函数体/约束说明没有显式可用的类返回值。
    let mut seen_params = false;
    for i in 0..node.named_child_count() {
        let Some(child) = node.named_child(i) else {
            continue;
        };
        if child.type_name() == "function_value_parameters" {
            seen_params = true;
            continue;
        }
        if !seen_params {
            continue;
        }
        if child.type_name() == "function_body" || child.type_name() == "type_constraints" {
            return None;
        }
        if child.type_name() == "user_type" || child.type_name() == "nullable_type" {
            let user_type = if child.type_name() == "nullable_type" {
                child
                    .named_children()
                    .into_iter()
                    .find(|c| c.type_name() == "user_type")
                    .unwrap_or_else(|| child.clone())
            } else {
                child.clone()
            };
            let type_id = user_type
                .named_children()
                .into_iter()
                .find(|c| c.type_name() == "type_identifier")
                .unwrap_or(user_type);
            let name = get_node_text(&type_id, source).trim().to_string();
            if !is_identifier(&name) || KOTLIN_NON_CLASS_RETURN.contains(&name.as_str()) {
                return None;
            }
            return Some(name);
        }
    }
    None
}

fn is_fun_interface_node(node: &SyntaxNode) -> bool {
    // tree-sitter-kotlin 对 `fun interface` 有时会恢复成 ERROR 节点,
    // 这里按 token 组合识别,保住接口节点和内部 lambda 访问。
    let mut has_fun = false;
    let mut has_interface_type = false;
    for i in 0..node.child_count() {
        let Some(child) = node.child(i) else {
            continue;
        };
        if child.type_name() == "fun" && !child.is_named() {
            has_fun = true;
        }
        if child.type_name() == "user_type"
            && child
                .named_children()
                .into_iter()
                .any(|c| c.type_name() == "type_identifier" && c.text() == "interface")
        {
            has_interface_type = true;
        }
        if child.type_name() == "ERROR" {
            for j in 0..child.child_count() {
                if child.child(j).is_some_and(|gc| {
                    gc.type_name() == "user_type"
                        && gc.named_children().into_iter().any(|id| {
                            id.type_name() == "type_identifier" && id.text() == "interface"
                        })
                }) {
                    has_interface_type = true;
                }
            }
        }
    }
    has_fun && has_interface_type
}

fn is_identifier(value: &str) -> bool {
    let mut chars = value.chars();
    matches!(chars.next(), Some('_') | Some('A'..='Z') | Some('a'..='z'))
        && chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
}

fn kotlin_import_name(import_text: &str) -> Option<String> {
    // import alias 和 wildcard 都不应进入最终模块名,否则解析器会拿到不可定位的名字。
    let rest = import_text.trim().strip_prefix("import")?.trim();
    let without_alias = rest.split(" as ").next().unwrap_or(rest).trim();
    let without_wildcard = without_alias.trim_end_matches(".*").trim();
    (!without_wildcard.is_empty()).then(|| without_wildcard.to_string())
}

impl LanguageExtractor for KotlinExtractor {
    fn function_types(&self) -> &'static [&'static str] {
        &["function_declaration"]
    }

    fn class_types(&self) -> &'static [&'static str] {
        &["class_declaration"]
    }

    fn method_types(&self) -> &'static [&'static str] {
        &["function_declaration"]
    }

    fn interface_types(&self) -> &'static [&'static str] {
        &[]
    }

    fn struct_types(&self) -> &'static [&'static str] {
        &[]
    }

    fn enum_types(&self) -> &'static [&'static str] {
        &[]
    }

    fn enum_member_types(&self) -> &'static [&'static str] {
        &["enum_entry"]
    }

    fn type_alias_types(&self) -> &'static [&'static str] {
        &["type_alias"]
    }

    fn import_types(&self) -> &'static [&'static str] {
        &["import_header", "import"]
    }

    fn call_types(&self) -> &'static [&'static str] {
        &["call_expression"]
    }

    fn variable_types(&self) -> &'static [&'static str] {
        &["property_declaration"]
    }

    fn field_types(&self) -> &'static [&'static str] {
        &["property_declaration"]
    }

    fn extra_class_node_types(&self) -> &'static [&'static str] {
        &["object_declaration"]
    }

    fn name_field(&self) -> &'static str {
        "simple_identifier"
    }

    fn body_field(&self) -> &'static str {
        "function_body"
    }

    fn visit_node(&self, node: &SyntaxNode, ctx: &mut dyn ExtractorContext) -> bool {
        if node.type_name() == "property_declaration" {
            return visit_kotlin_property(node, ctx);
        }

        if node.type_name() == "lambda_literal" {
            // ERROR 形式的 fun interface 会把实现体放到相邻 lambda;前一个分支创建 scope 后再访问。
            return node
                .previous_sibling()
                .is_some_and(|prev| prev.type_name() == "ERROR" && is_fun_interface_node(&prev));
        }

        if node.type_name() != "ERROR" && node.type_name() != "function_declaration" {
            return false;
        }
        if node.type_name() == "ERROR"
            && node.child(0).is_some_and(|first| first.type_name() == "{")
        {
            return false;
        }
        if !is_fun_interface_node(node) {
            return false;
        }

        let name_text = kotlin_fun_interface_name(node);
        let Some(name_text) = name_text else {
            return false;
        };
        let Some(iface_node) =
            ctx.create_node(NodeKind::Interface, &name_text, node, NodeExtra::default())
        else {
            return false;
        };
        ctx.push_scope(iface_node.id.clone());
        if node.type_name() == "ERROR"
            && let Some(next) = node
                .next_sibling()
                .filter(|n| n.type_name() == "lambda_literal")
        {
            for child in next.named_children() {
                if child.type_name() == "statements" {
                    for stmt in child.named_children() {
                        ctx.visit_node(&stmt);
                    }
                }
            }
        }
        ctx.pop_scope();
        true
    }

    fn params_field(&self) -> &'static str {
        "function_value_parameters"
    }

    fn return_field(&self) -> Option<&'static str> {
        Some("type")
    }

    fn get_return_type(&self, node: &SyntaxNode, source: &str) -> Option<String> {
        extract_kotlin_return_type(node, source)
    }

    fn resolve_body(&self, node: &SyntaxNode, _body_field: &str) -> Option<SyntaxNode> {
        // Kotlin 的函数体、类体、枚举体节点名不同;错误恢复出的 `{...}` 也要当 body。
        for i in 0..node.named_child_count() {
            let Some(child) = node.named_child(i) else {
                continue;
            };
            if child.type_name() == "ERROR"
                && child.child(0).is_some_and(|first| first.type_name() == "{")
            {
                return Some(child.clone());
            }
            if matches!(
                child.type_name().as_str(),
                "function_body" | "class_body" | "enum_class_body"
            ) {
                return Some(child.clone());
            }
        }
        None
    }

    fn classify_class_node(&self, node: &SyntaxNode) -> ClassClassification {
        for i in 0..node.child_count() {
            let Some(child) = node.child(i) else {
                continue;
            };
            if child.type_name() == "interface" {
                return ClassClassification::Interface;
            }
            if child.type_name() == "enum" {
                return ClassClassification::Enum;
            }
        }
        ClassClassification::Class
    }

    fn get_receiver_type(&self, node: &SyntaxNode, source: &str) -> Option<String> {
        // 扩展函数 `fun Receiver.name(...)` 的 receiver 在函数名前的 user_type + `.`。
        let mut found_user_type = None;
        for i in 0..node.child_count() {
            let Some(child) = node.child(i) else {
                continue;
            };
            if child.type_name() == "user_type" {
                found_user_type = Some(child);
            } else if child.type_name() == "." {
                let found = found_user_type?;
                let type_id = found
                    .named_children()
                    .into_iter()
                    .find(|c| c.type_name() == "type_identifier");
                return Some(
                    type_id
                        .map(|id| get_node_text(&id, source))
                        .unwrap_or_else(|| get_node_text(found, source)),
                );
            } else if child.type_name() == "simple_identifier"
                || child.type_name() == "function_value_parameters"
            {
                break;
            }
        }
        None
    }

    fn get_signature(&self, node: &SyntaxNode, source: &str) -> Option<String> {
        let params = get_child_by_field(node, "function_value_parameters")?;
        let mut sig = get_node_text(params, source);
        if let Some(return_type) = get_child_by_field(node, "type") {
            sig.push_str(": ");
            sig.push_str(&get_node_text(return_type, source));
        }
        Some(sig)
    }

    fn get_visibility(&self, node: &SyntaxNode) -> Option<Visibility> {
        for i in 0..node.child_count() {
            let Some(child) = node.child(i) else {
                continue;
            };
            if child.type_name() == "modifiers" {
                let text = child.text();
                if text.contains("public") {
                    return Some(Visibility::Public);
                }
                if text.contains("private") {
                    return Some(Visibility::Private);
                }
                if text.contains("protected") {
                    return Some(Visibility::Protected);
                }
                if text.contains("internal") {
                    return Some(Visibility::Internal);
                }
            }
        }
        Some(Visibility::Public)
    }

    fn is_static(&self, _node: &SyntaxNode) -> bool {
        false
    }

    fn is_async(&self, node: &SyntaxNode) -> bool {
        (0..node.child_count()).any(|i| {
            node.child(i)
                .is_some_and(|c| c.type_name() == "modifiers" && c.text().contains("suspend"))
        })
    }

    fn extract_modifiers(&self, node: &SyntaxNode) -> Option<Vec<String>> {
        let mut mods = Vec::new();
        for child in node
            .children()
            .into_iter()
            .filter(|child| child.type_name() == "modifiers")
        {
            for platform_modifier in child
                .children()
                .into_iter()
                .filter(|pm| pm.type_name() == "platform_modifier")
            {
                for keyword in platform_modifier.children() {
                    if keyword.type_name() == "expect" || keyword.type_name() == "actual" {
                        mods.push(keyword.type_name());
                    }
                }
            }
        }
        (!mods.is_empty()).then_some(mods)
    }

    fn extract_import(&self, node: &SyntaxNode, source: &str) -> Option<ImportInfo> {
        let import_text = get_node_text(node, source).trim().to_string();
        let module_name = kotlin_import_name(&import_text).or_else(|| {
            node.named_children()
                .into_iter()
                .find(|c| c.type_name() == "identifier")
                .map(|identifier| get_node_text(&identifier, source))
        })?;
        Some(ImportInfo {
            module_name,
            signature: import_text,
            handled_refs: false,
        })
    }

    fn package_types(&self) -> &'static [&'static str] {
        &["package_header"]
    }

    fn extract_package(&self, node: &SyntaxNode, source: &str) -> Option<String> {
        node.named_children()
            .into_iter()
            .find(|c| c.type_name() == "identifier" || c.type_name() == "qualified_identifier")
            .map(|id| get_node_text(&id, source).trim().to_string())
    }
}

fn visit_kotlin_property(node: &SyntaxNode, ctx: &mut dyn ExtractorContext) -> bool {
    let var_decl = node
        .named_children()
        .into_iter()
        .find(|c| c.type_name() == "variable_declaration");
    let name_node = var_decl.and_then(|decl| {
        decl.named_children()
            .into_iter()
            .find(|c| c.type_name() == "simple_identifier")
    });
    let Some(name_node) = name_node else {
        return false;
    };
    let name = get_node_text(&name_node, ctx.source());
    if name.is_empty() {
        return false;
    }

    let mut scope = "const";
    // Kotlin property 的图 kind 取决于出现位置:类体是字段,对象/companion 常量化,函数内跳过。
    let mut parent = node.parent();
    while let Some(p) = parent {
        let pt = p.type_name();
        if matches!(
            pt.as_str(),
            "function_body"
                | "function_declaration"
                | "lambda_literal"
                | "anonymous_initializer"
                | "control_structure_body"
                | "getter"
                | "setter"
        ) {
            scope = "local";
            break;
        }
        if pt == "companion_object" || pt == "object_declaration" {
            scope = "const";
            break;
        }
        if pt == "class_declaration" {
            scope = "instance";
            break;
        }
        parent = p.parent();
    }
    if scope == "local" {
        return true;
    }

    let binding = node
        .named_children()
        .into_iter()
        .find(|c| c.type_name() == "binding_pattern_kind");
    let is_val = binding
        .as_ref()
        .is_some_and(|binding| get_node_text(binding, ctx.source()) == "val");
    let kind = if scope == "instance" {
        NodeKind::Field
    } else if is_val {
        NodeKind::Constant
    } else {
        NodeKind::Variable
    };

    let type_node = node.child_for_field_name("type");
    let extra = NodeExtra {
        signature: type_node.map(|ty| {
            format!(
                "{} {}: {}",
                if is_val { "val" } else { "var" },
                name,
                get_node_text(ty, ctx.source())
            )
        }),
        ..Default::default()
    };
    ctx.create_node(kind, &name, node, extra);
    true
}

fn kotlin_fun_interface_name(node: &SyntaxNode) -> Option<String> {
    if node.type_name() == "function_declaration" {
        for child in node.children() {
            if child.type_name() == "ERROR"
                && let Some(id) = child
                    .children()
                    .into_iter()
                    .find(|gc| gc.type_name() == "simple_identifier")
            {
                return Some(id.text());
            }
        }
    }
    node.children()
        .into_iter()
        .find(|child| child.type_name() == "simple_identifier")
        .map(|child| child.text())
}