aptu-coder-core 0.13.5

Multi-language AST analysis library using tree-sitter
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
// SPDX-FileCopyrightText: 2026 aptu-coder contributors
// SPDX-License-Identifier: Apache-2.0

/// Tree-sitter query for extracting Kotlin elements (functions and classes).
pub const ELEMENT_QUERY: &str = r"
(function_declaration
  name: (identifier) @function_name) @function
(class_declaration
  name: (identifier) @class_name) @class
(object_declaration
  name: (identifier) @object_name) @class
";

/// Tree-sitter query for extracting function calls.
pub const CALL_QUERY: &str = r"
(call_expression
  (identifier) @call)
";

/// Tree-sitter query for extracting type references.
pub const REFERENCE_QUERY: &str = r"
(identifier) @type_ref
";

/// Tree-sitter query for extracting Kotlin imports.
pub const IMPORT_QUERY: &str = r"
(import) @import_path
";

/// Tree-sitter query for extracting definition and use sites.
pub const DEFUSE_QUERY: &str = r"
(property_declaration
  name: (simple_identifier) @write.property)
(simple_identifier) @read.usage
";

use tree_sitter::Node;

use crate::languages::get_node_text;

/// Extract inheritance information from a Kotlin class node.
#[must_use]
pub fn extract_inheritance(node: &Node, source: &str) -> Vec<String> {
    let mut inherits = Vec::new();

    // Find the delegation_specifiers child of the class node.
    // Grammar: optional(seq(':', $.delegation_specifiers))
    let Some(delegation) = (0..node.child_count())
        .filter_map(|i| node.child(u32::try_from(i).ok()?))
        .find(|n| n.kind() == "delegation_specifiers")
    else {
        return inherits;
    };

    // Each delegation_specifier holds either a constructor_invocation (superclass)
    // or a user_type (interface).
    for spec in (0..delegation.child_count())
        .filter_map(|j| delegation.child(u32::try_from(j).ok()?))
        .filter(|n| n.kind() == "delegation_specifier")
    {
        for spec_child in (0..spec.child_count()).filter_map(|k| spec.child(u32::try_from(k).ok()?))
        {
            match spec_child.kind() {
                "constructor_invocation" => {
                    // Superclass: constructor_invocation = type + value_arguments.
                    // The first child is the type node.
                    if let Some(type_node) = spec_child.child(0)
                        && let Some(text) = get_node_text(&type_node, source)
                    {
                        inherits.push(format!("extends {text}"));
                    }
                }
                "type" | "user_type" => {
                    // Interface: direct type without constructor call.
                    if let Some(text) = get_node_text(&spec_child, source) {
                        inherits.push(format!("implements {text}"));
                    }
                }
                _ => {}
            }
        }
    }

    inherits
}

/// Extract the function name from a Kotlin `function_declaration` node.
#[must_use]
pub fn extract_function_name(node: &Node, source: &str, _lang: &str) -> Option<String> {
    if node.kind() != "function_declaration" {
        return None;
    }
    node.child_by_field_name("name")
        .and_then(|n| get_node_text(&n, source))
}

/// Find the receiver type (enclosing class or object) for a Kotlin function.
///
/// Returns `None` for top-level functions (including extension functions) and
/// functions whose only enclosing type is a `companion_object`.
#[must_use]
pub fn find_receiver_type(node: &Node, source: &str) -> Option<String> {
    if node.kind() != "function_declaration" {
        return None;
    }
    let mut current = *node;
    while let Some(parent) = current.parent() {
        match parent.kind() {
            "class_declaration" | "object_declaration" => {
                return parent
                    .child_by_field_name("name")
                    .and_then(|n| get_node_text(&n, source));
            }
            _ => {
                current = parent;
            }
        }
    }
    None
}

/// Find the method name when a function lives inside a named type body.
///
/// Returns `None` for top-level functions and functions inside `companion_object`
/// that have no enclosing `class_declaration` or `object_declaration`.
#[must_use]
pub fn find_method_for_receiver(
    node: &Node,
    source: &str,
    _depth: Option<usize>,
) -> Option<String> {
    if node.kind() != "function_declaration" {
        return None;
    }
    let mut current = *node;
    let mut in_type_body = false;
    while let Some(parent) = current.parent() {
        match parent.kind() {
            "class_declaration" | "object_declaration" => {
                in_type_body = true;
                break;
            }
            _ => {
                current = parent;
            }
        }
    }
    if !in_type_body {
        return None;
    }
    node.child_by_field_name("name")
        .and_then(|n| get_node_text(&n, source))
}

#[cfg(all(test, feature = "lang-kotlin"))]
mod tests {
    use super::*;
    use tree_sitter::{Parser, StreamingIterator};

    fn find_node<'a>(root: tree_sitter::Node<'a>, kind: &str) -> Option<tree_sitter::Node<'a>> {
        if root.kind() == kind {
            return Some(root);
        }
        let mut cursor = root.walk();
        for child in root.children(&mut cursor) {
            if let Some(n) = find_node(child, kind) {
                return Some(n);
            }
        }
        None
    }

    fn parse_kotlin(src: &str) -> tree_sitter::Tree {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_kotlin_ng::LANGUAGE.into())
            .expect("Error loading Kotlin language");
        parser.parse(src, None).expect("Failed to parse Kotlin")
    }

    #[test]
    fn test_element_query_free_function() {
        // Arrange: free function at top level
        let src = "fun greet(name: String): String { return \"Hello, $name\" }";
        let tree = parse_kotlin(src);
        let root = tree.root_node();

        // Act -- verify ELEMENT_QUERY compiles and matches function
        let query = tree_sitter::Query::new(&tree_sitter_kotlin_ng::LANGUAGE.into(), ELEMENT_QUERY)
            .expect("ELEMENT_QUERY must be valid");
        let mut cursor = tree_sitter::QueryCursor::new();
        let mut matches = cursor.matches(&query, root, src.as_bytes());

        let mut captured_functions: Vec<String> = Vec::new();
        while let Some(mat) = matches.next() {
            for capture in mat.captures {
                let name = query.capture_names()[capture.index as usize];
                let node = capture.node;
                if name == "function" {
                    if let Some(n) = node.child_by_field_name("name") {
                        captured_functions.push(src[n.start_byte()..n.end_byte()].to_string());
                    }
                }
            }
        }

        // Assert
        assert!(
            captured_functions.contains(&"greet".to_string()),
            "expected greet function, got {:?}",
            captured_functions
        );
    }

    #[test]
    fn test_element_query_method_in_class() {
        // Arrange: method inside a class
        let src = "class Animal { fun eat() {} }";
        let tree = parse_kotlin(src);
        let root = tree.root_node();

        // Act -- verify ELEMENT_QUERY compiles and matches class + method
        let query = tree_sitter::Query::new(&tree_sitter_kotlin_ng::LANGUAGE.into(), ELEMENT_QUERY)
            .expect("ELEMENT_QUERY must be valid");
        let mut cursor = tree_sitter::QueryCursor::new();
        let mut matches = cursor.matches(&query, root, src.as_bytes());

        let mut captured_classes: Vec<String> = Vec::new();
        let mut captured_functions: Vec<String> = Vec::new();
        while let Some(mat) = matches.next() {
            for capture in mat.captures {
                let name = query.capture_names()[capture.index as usize];
                let node = capture.node;
                match name {
                    "class" => {
                        if let Some(n) = node.child_by_field_name("name") {
                            captured_classes.push(src[n.start_byte()..n.end_byte()].to_string());
                        }
                    }
                    "function" => {
                        if let Some(n) = node.child_by_field_name("name") {
                            captured_functions.push(src[n.start_byte()..n.end_byte()].to_string());
                        }
                    }
                    _ => {}
                }
            }
        }

        // Assert
        assert!(
            captured_classes.contains(&"Animal".to_string()),
            "expected Animal class, got {:?}",
            captured_classes
        );
        assert!(
            captured_functions.contains(&"eat".to_string()),
            "expected eat function, got {:?}",
            captured_functions
        );
    }

    #[test]
    fn test_call_query() {
        // Arrange: function call
        let src = "fun main() { println(\"hello\") }";
        let tree = parse_kotlin(src);
        let root = tree.root_node();

        // Act -- verify CALL_QUERY compiles and matches call
        let query = tree_sitter::Query::new(&tree_sitter_kotlin_ng::LANGUAGE.into(), CALL_QUERY)
            .expect("CALL_QUERY must be valid");
        let mut cursor = tree_sitter::QueryCursor::new();
        let mut matches = cursor.matches(&query, root, src.as_bytes());

        let mut captured_calls: Vec<String> = Vec::new();
        while let Some(mat) = matches.next() {
            for capture in mat.captures {
                let name = query.capture_names()[capture.index as usize];
                if name == "call" {
                    let node = capture.node;
                    captured_calls.push(src[node.start_byte()..node.end_byte()].to_string());
                }
            }
        }

        // Assert
        assert!(
            captured_calls.contains(&"println".to_string()),
            "expected println call, got {:?}",
            captured_calls
        );
    }

    #[test]
    fn test_element_query_class_declarations() {
        // Arrange: various class types (data class is just a class with data modifier)
        let src = "class Dog {} object Singleton {}";
        let tree = parse_kotlin(src);
        let root = tree.root_node();

        // Act -- verify ELEMENT_QUERY matches all declaration types
        let query = tree_sitter::Query::new(&tree_sitter_kotlin_ng::LANGUAGE.into(), ELEMENT_QUERY)
            .expect("ELEMENT_QUERY must be valid");
        let mut cursor = tree_sitter::QueryCursor::new();
        let mut matches = cursor.matches(&query, root, src.as_bytes());

        let mut captured_classes: Vec<String> = Vec::new();
        while let Some(mat) = matches.next() {
            for capture in mat.captures {
                let name = query.capture_names()[capture.index as usize];
                let node = capture.node;
                if name == "class" {
                    if let Some(n) = node.child_by_field_name("name") {
                        captured_classes.push(src[n.start_byte()..n.end_byte()].to_string());
                    }
                }
            }
        }

        // Assert
        assert!(
            captured_classes.contains(&"Dog".to_string()),
            "expected Dog class, got {:?}",
            captured_classes
        );
        assert!(
            captured_classes.contains(&"Singleton".to_string()),
            "expected Singleton object, got {:?}",
            captured_classes
        );
    }

    #[test]
    fn test_import_query() {
        // Arrange: import statements
        let src = "import java.util.List\nimport kotlin.io.println";
        let tree = parse_kotlin(src);
        let root = tree.root_node();

        // Act -- verify IMPORT_QUERY compiles and matches imports
        let query = tree_sitter::Query::new(&tree_sitter_kotlin_ng::LANGUAGE.into(), IMPORT_QUERY)
            .expect("IMPORT_QUERY must be valid");
        let mut cursor = tree_sitter::QueryCursor::new();
        let matches = cursor.matches(&query, root, src.as_bytes());

        let import_count = matches.count();

        // Assert
        assert!(
            import_count >= 2,
            "expected at least 2 imports, got {}",
            import_count
        );
    }

    #[test]
    fn test_extract_inheritance_single_superclass() {
        // Arrange: class with single superclass (constructor invocation with parens)
        let src = "class Dog : Animal() {}";
        let tree = parse_kotlin(src);
        let root = tree.root_node();

        // Act -- find the class_declaration node and call extract_inheritance
        let mut class_node: Option<tree_sitter::Node> = None;
        let mut stack = vec![root];
        while let Some(node) = stack.pop() {
            if node.kind() == "class_declaration" {
                class_node = Some(node);
                break;
            }
            for i in 0..node.child_count() {
                if let Some(child) = node.child(u32::try_from(i).unwrap_or(u32::MAX)) {
                    stack.push(child);
                }
            }
        }
        let class = class_node.expect("class_declaration not found");
        let bases = extract_inheritance(&class, src);

        // Assert
        assert!(
            bases.iter().any(|b| b.contains("Animal")),
            "expected extends Animal, got {:?}",
            bases
        );
    }

    #[test]
    fn test_extract_inheritance_multiple_interfaces() {
        // Arrange: class with multiple interfaces (no parens)
        let src = "class Dog : Runnable, Comparable<Dog> {}";
        let tree = parse_kotlin(src);
        let root = tree.root_node();

        // Act -- find the class_declaration node and call extract_inheritance
        let mut class_node: Option<tree_sitter::Node> = None;
        let mut stack = vec![root];
        while let Some(node) = stack.pop() {
            if node.kind() == "class_declaration" {
                class_node = Some(node);
                break;
            }
            for i in 0..node.child_count() {
                if let Some(child) = node.child(u32::try_from(i).unwrap_or(u32::MAX)) {
                    stack.push(child);
                }
            }
        }
        let class = class_node.expect("class_declaration not found");
        let bases = extract_inheritance(&class, src);

        // Assert
        assert!(
            bases.iter().any(|b| b.contains("Runnable")),
            "expected implements Runnable, got {:?}",
            bases
        );
        assert!(
            bases.iter().any(|b| b.contains("Comparable")),
            "expected implements Comparable, got {:?}",
            bases
        );
    }

    #[test]
    fn test_extract_inheritance_mixed() {
        // Arrange: class with superclass and interfaces
        let src = "class Dog : Animal(), Runnable, Comparable<Dog> {}";
        let tree = parse_kotlin(src);
        let root = tree.root_node();

        // Act -- find the class_declaration node and call extract_inheritance
        let mut class_node: Option<tree_sitter::Node> = None;
        let mut stack = vec![root];
        while let Some(node) = stack.pop() {
            if node.kind() == "class_declaration" {
                class_node = Some(node);
                break;
            }
            for i in 0..node.child_count() {
                if let Some(child) = node.child(u32::try_from(i).unwrap_or(u32::MAX)) {
                    stack.push(child);
                }
            }
        }
        let class = class_node.expect("class_declaration not found");
        let bases = extract_inheritance(&class, src);

        // Assert
        assert!(
            bases.iter().any(|b| b.contains("Animal")),
            "expected extends Animal, got {:?}",
            bases
        );
        assert!(
            bases.iter().any(|b| b.contains("Runnable")),
            "expected implements Runnable, got {:?}",
            bases
        );
        assert!(
            bases.iter().any(|b| b.contains("Comparable")),
            "expected implements Comparable, got {:?}",
            bases
        );
    }

    #[test]
    fn test_extract_function_name_free_function() {
        let src = "fun greet() {}";
        let tree = parse_kotlin(src);
        let root = tree.root_node();
        let node = find_node(root, "function_declaration").expect("function_declaration not found");
        let result = extract_function_name(&node, src, "kotlin");
        assert_eq!(result, Some("greet".to_string()));
    }

    #[test]
    fn test_extract_function_name_method_in_class() {
        let src = "class Foo { fun bar() {} }";
        let tree = parse_kotlin(src);
        let root = tree.root_node();
        // find the inner function_declaration (bar), not the class
        let class_node = find_node(root, "class_declaration").expect("class_declaration not found");
        let node =
            find_node(class_node, "function_declaration").expect("function_declaration not found");
        let result = extract_function_name(&node, src, "kotlin");
        assert_eq!(result, Some("bar".to_string()));
    }

    #[test]
    fn test_find_receiver_type_top_level_returns_none() {
        let src = "fun greet() {}";
        let tree = parse_kotlin(src);
        let root = tree.root_node();
        let node = find_node(root, "function_declaration").expect("function_declaration not found");
        let result = find_receiver_type(&node, src);
        assert_eq!(result, None);
    }

    #[test]
    fn test_find_receiver_type_method_in_class() {
        let src = "class Foo { fun bar() {} }";
        let tree = parse_kotlin(src);
        let root = tree.root_node();
        let class_node = find_node(root, "class_declaration").expect("class_declaration not found");
        let node =
            find_node(class_node, "function_declaration").expect("function_declaration not found");
        let result = find_receiver_type(&node, src);
        assert_eq!(result, Some("Foo".to_string()));
    }

    #[test]
    fn test_find_receiver_type_extension_function_returns_none() {
        let src = "fun String.greet() {}";
        let tree = parse_kotlin(src);
        let root = tree.root_node();
        let node = find_node(root, "function_declaration").expect("function_declaration not found");
        let result = find_receiver_type(&node, src);
        assert_eq!(result, None);
    }

    #[test]
    fn test_find_method_for_receiver_top_level_returns_none() {
        let src = "fun greet() {}";
        let tree = parse_kotlin(src);
        let root = tree.root_node();
        let node = find_node(root, "function_declaration").expect("function_declaration not found");
        let result = find_method_for_receiver(&node, src, None);
        assert_eq!(result, None);
    }

    #[test]
    fn test_find_method_for_receiver_method_in_class() {
        let src = "class Foo { fun bar() {} }";
        let tree = parse_kotlin(src);
        let root = tree.root_node();
        let class_node = find_node(root, "class_declaration").expect("class_declaration not found");
        let node =
            find_node(class_node, "function_declaration").expect("function_declaration not found");
        let result = find_method_for_receiver(&node, src, None);
        assert_eq!(result, Some("bar".to_string()));
    }
}