remembrall-core 0.4.2

Field-aware code graph plus persistent memory for AI agents - Rust, Postgres + pgvector
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
//! Tree-sitter based Kotlin parser.
//!
//! Extracts symbols and relationships from a single Kotlin source file.
//!
//! # Symbols extracted
//! - `class_declaration`, `object_declaration` -> SymbolType::Class
//! - `companion_object` -> SymbolType::Class
//! - `function_declaration` inside a class/object body -> SymbolType::Method
//! - Top-level `function_declaration` -> SymbolType::Function
//! - The file itself -> SymbolType::File
//!
//! # Relationships extracted
//! - `import` -> RelationType::Imports
//! - `call_expression` -> RelationType::Calls
//! - `delegation_specifiers` in class declarations -> RelationType::Inherits
//! - Classes/functions defined inside a scope -> RelationType::Defines
//! - Function/method parameter and return types -> RelationType::UsesType

use std::collections::{HashMap, HashSet};

use chrono::{DateTime, Utc};
use tree_sitter::{Node, Parser};
use uuid::Uuid;

use crate::graph::types::{RelationType, Relationship, Symbol, SymbolType};
use crate::parser::python::{FileParseResult, RawImport};

/// Parse a Kotlin file and extract symbols and relationships.
///
/// - `file_path`  - canonical path string stored on each symbol
/// - `source`     - raw UTF-8 source text
/// - `project`    - project name tag
/// - `file_mtime` - filesystem mtime; stored on symbols for incremental indexing
pub fn parse_kotlin_file(
    file_path: &str,
    source: &str,
    project: &str,
    file_mtime: DateTime<Utc>,
) -> FileParseResult {
    let mut parser = Parser::new();
    parser
        .set_language(&tree_sitter_kotlin_ng::LANGUAGE.into())
        .expect("failed to load Kotlin grammar");

    let Some(tree) = parser.parse(source, None) else {
        tracing::warn!("tree-sitter failed to parse {file_path}");
        return FileParseResult::default();
    };

    let source_bytes = source.as_bytes();
    let root = tree.root_node();

    let mut ctx = ParseContext {
        file_path,
        project,
        file_mtime,
        result: FileParseResult::default(),
        name_to_id: HashMap::new(),
        imported_names: HashSet::new(),
        class_fields: HashMap::new(),
    };

    // File-level symbol - always the first entry in symbols.
    let file_symbol_id = Uuid::new_v4();
    ctx.result.symbols.push(Symbol {
        id: file_symbol_id,
        name: file_path.to_string(),
        symbol_type: SymbolType::File,
        file_path: file_path.to_string(),
        start_line: Some(1),
        end_line: Some(source.lines().count() as i32),
        language: "kotlin".to_string(),
        project: project.to_string(),
        signature: None,
        file_mtime,
        layer: None,
        parent_symbol_id: None,
        moniker: None,
    });

    // Pass 1: collect imports from top-level `import` nodes.
    collect_imports(&root, source_bytes, &mut ctx);

    // Pass 2: collect class, object, and function declarations recursively.
    collect_definitions(&root, file_symbol_id, false, source_bytes, &mut ctx);

    // Pass 3: collect call expressions.
    collect_calls(&root, source_bytes, &mut ctx);

    // Pass 4: collect type annotations from function/method signatures.
    collect_type_annotations(&root, source_bytes, &mut ctx);

    ctx.result
}

// ---------------------------------------------------------------------------
// Internal state
// ---------------------------------------------------------------------------

struct ParseContext<'a> {
    file_path: &'a str,
    project: &'a str,
    file_mtime: DateTime<Utc>,
    result: FileParseResult,
    /// name -> symbol UUID for all symbols defined in this file.
    name_to_id: HashMap<String, Uuid>,
    /// Short names imported into this file (for confidence scoring).
    imported_names: HashSet<String>,
    /// (class_id, field_name) -> field symbol UUID for class properties defined
    /// in this file. Used to resolve `this.<field>` reads to the enclosing
    /// class's field.
    class_fields: HashMap<(Uuid, String), Uuid>,
}

// ---------------------------------------------------------------------------
// Import collection
// ---------------------------------------------------------------------------

/// Walk top-level children of `source_file` looking for `import` nodes.
///
/// Kotlin AST: the root `source_file` contains `import` nodes as direct
/// children. Each `import` node contains a `qualified_identifier` (and
/// optionally a wildcard `*`).
fn collect_imports(root: &Node<'_>, source: &[u8], ctx: &mut ParseContext<'_>) {
    let mut cursor = root.walk();
    for child in root.children(&mut cursor) {
        if child.kind() == "import" {
            process_import(&child, source, ctx);
        }
    }
}

fn process_import(node: &Node<'_>, source: &[u8], ctx: &mut ParseContext<'_>) {
    // The full text of this node is e.g. "import org.jetbrains.exposed.sql.Table"
    // or "import org.jetbrains.exposed.sql.transactions.*"
    // Strip the leading "import " keyword and trim.
    let full_text = node_text(node, source);
    let after_import = full_text
        .trim_start_matches("import")
        .trim_start();

    // Handle aliased imports: `import com.example.Foo as Bar`
    let (module_raw, alias_opt) = if let Some(idx) = after_import.find(" as ") {
        let module = after_import[..idx].trim();
        let alias = after_import[idx + 4..].trim();
        (module.to_string(), Some(alias.to_string()))
    } else {
        (after_import.trim().to_string(), None)
    };

    if module_raw.is_empty() {
        return;
    }

    // Record the short name (last segment or alias) for call confidence scoring.
    if let Some(alias) = &alias_opt {
        ctx.imported_names.insert(alias.clone());
    } else if !module_raw.ends_with('*') {
        if let Some(last) = module_raw.split('.').last() {
            ctx.imported_names.insert(last.to_string());
        }
    }

    let file_id = ctx.result.symbols[0].id;

    ctx.result.raw_imports.push(RawImport {
        source_id: file_id,
        module_raw: module_raw.clone(),
        is_relative: false,
        dot_count: 0,
        module_path: module_raw.clone(),
    });

    let target_id = Uuid::new_v5(&Uuid::NAMESPACE_OID, module_raw.as_bytes());
    ctx.result.relationships.push(Relationship {
        source_id: file_id,
        target_id,
        rel_type: RelationType::Imports,
        confidence: 0.3,
    });
}

// ---------------------------------------------------------------------------
// Definition collection
// ---------------------------------------------------------------------------

/// Recursively collect class, object, companion_object, and function declarations.
///
/// - `parent_id`     - UUID of the enclosing scope (file or class/object)
/// - `in_class_body` - true when we're inside a class/object body
fn collect_definitions(
    node: &Node<'_>,
    parent_id: Uuid,
    in_class_body: bool,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "class_declaration" | "object_declaration" => {
                let class_id = process_type_declaration(&child, parent_id, source, ctx);
                // Find and recurse into the class_body child.
                if let Some(body) = find_child_by_kind(&child, "class_body") {
                    collect_definitions(&body, class_id, true, source, ctx);
                }
                // Also handle enum_class_body (for enum classes).
                if let Some(body) = find_child_by_kind(&child, "enum_class_body") {
                    collect_definitions(&body, class_id, true, source, ctx);
                }
            }
            "companion_object" => {
                let comp_id = process_companion_object(&child, parent_id, source, ctx);
                if let Some(body) = find_child_by_kind(&child, "class_body") {
                    collect_definitions(&body, comp_id, true, source, ctx);
                }
            }
            "function_declaration" => {
                let sym_id = process_function(&child, parent_id, in_class_body, source, ctx);
                // Recurse into function body for nested lambdas/local classes.
                if let Some(body) = find_child_by_kind(&child, "function_body") {
                    collect_definitions(&body, sym_id, false, source, ctx);
                }
            }
            // Class-body property: `val amount: Int = 0` or `var amount = 0`.
            "property_declaration" if in_class_body => {
                process_property(&child, parent_id, source, ctx);
            }
            // Descend into other block constructs transparently.
            _ => {
                collect_definitions(&child, parent_id, in_class_body, source, ctx);
            }
        }
    }
}

/// Process a `class_declaration` or `object_declaration` node.
///
/// In this grammar, interfaces are also `class_declaration` nodes (the
/// keyword is `interface` instead of `class`).
fn process_type_declaration(
    node: &Node<'_>,
    parent_id: Uuid,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) -> Uuid {
    // The name is in an `identifier` field child.
    let name = node
        .child_by_field_name("name")
        .map(|n| node_text(&n, source))
        .unwrap_or_else(|| "<anonymous>".to_string());

    let start_line = node.start_position().row as i32 + 1;
    let end_line = node.end_position().row as i32 + 1;
    let id = Uuid::new_v4();

    let signature = build_type_signature(node, &name, source);

    ctx.name_to_id.insert(name.clone(), id);
    ctx.result.symbols.push(Symbol {
        id,
        name: name.clone(),
        symbol_type: SymbolType::Class,
        file_path: ctx.file_path.to_string(),
        start_line: Some(start_line),
        end_line: Some(end_line),
        language: "kotlin".to_string(),
        project: ctx.project.to_string(),
        signature: Some(signature),
        file_mtime: ctx.file_mtime,
        layer: None,
        parent_symbol_id: None,
        moniker: None,
    });

    ctx.result.relationships.push(Relationship {
        source_id: parent_id,
        target_id: id,
        rel_type: RelationType::Defines,
        confidence: 1.0,
    });

    // Emit INHERITS relationships from delegation_specifiers.
    collect_supertypes(node, id, source, ctx);

    id
}

/// Capture a class-body `property_declaration` (`val amount: Int = 0`) as a
/// `Field` symbol with a `Defines` edge from the enclosing class. The property
/// name is the `simple_identifier` inside the `variable_declaration` child.
fn process_property(
    node: &Node<'_>,
    class_id: Uuid,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) {
    let name = find_child_by_kind(node, "variable_declaration")
        .and_then(|vd| find_child_by_kind(&vd, "simple_identifier"))
        .map(|n| node_text(&n, source))
        .unwrap_or_default();
    if name.is_empty() {
        return;
    }

    let start_line = node.start_position().row as i32 + 1;
    let end_line = node.end_position().row as i32 + 1;
    let id = Uuid::new_v4();
    ctx.class_fields.insert((class_id, name.clone()), id);

    ctx.result.symbols.push(Symbol {
        id,
        name,
        symbol_type: SymbolType::Field,
        file_path: ctx.file_path.to_string(),
        start_line: Some(start_line),
        end_line: Some(end_line),
        language: "kotlin".to_string(),
        project: ctx.project.to_string(),
        signature: None,
        file_mtime: ctx.file_mtime,
        layer: None,
        parent_symbol_id: Some(class_id),
        moniker: None,
    });

    ctx.result.relationships.push(Relationship {
        source_id: class_id,
        target_id: id,
        rel_type: RelationType::Defines,
        confidence: 1.0,
    });
}

/// Process a `companion_object` node.
fn process_companion_object(
    node: &Node<'_>,
    parent_id: Uuid,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) -> Uuid {
    let name = node
        .child_by_field_name("name")
        .map(|n| node_text(&n, source))
        .unwrap_or_else(|| "Companion".to_string());

    let start_line = node.start_position().row as i32 + 1;
    let end_line = node.end_position().row as i32 + 1;
    let id = Uuid::new_v4();

    ctx.name_to_id.insert(name.clone(), id);
    ctx.result.symbols.push(Symbol {
        id,
        name: name.clone(),
        symbol_type: SymbolType::Class,
        file_path: ctx.file_path.to_string(),
        start_line: Some(start_line),
        end_line: Some(end_line),
        language: "kotlin".to_string(),
        project: ctx.project.to_string(),
        signature: Some(format!("companion object {name}")),
        file_mtime: ctx.file_mtime,
        layer: None,
        parent_symbol_id: None,
        moniker: None,
    });

    ctx.result.relationships.push(Relationship {
        source_id: parent_id,
        target_id: id,
        rel_type: RelationType::Defines,
        confidence: 1.0,
    });

    id
}

/// Process a `function_declaration` node.
fn process_function(
    node: &Node<'_>,
    parent_id: Uuid,
    in_class_body: bool,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) -> Uuid {
    let name = node
        .child_by_field_name("name")
        .map(|n| node_text(&n, source))
        .unwrap_or_else(|| "<anonymous>".to_string());

    let symbol_type = if in_class_body {
        SymbolType::Method
    } else {
        SymbolType::Function
    };

    let signature = build_function_signature(node, &name, source);
    let start_line = node.start_position().row as i32 + 1;
    let end_line = node.end_position().row as i32 + 1;
    let id = Uuid::new_v4();

    ctx.name_to_id.insert(name.clone(), id);
    ctx.result.symbols.push(Symbol {
        id,
        name: name.clone(),
        symbol_type,
        file_path: ctx.file_path.to_string(),
        start_line: Some(start_line),
        end_line: Some(end_line),
        language: "kotlin".to_string(),
        project: ctx.project.to_string(),
        signature: Some(signature),
        file_mtime: ctx.file_mtime,
        layer: None,
        parent_symbol_id: None,
        moniker: None,
    });

    ctx.result.relationships.push(Relationship {
        source_id: parent_id,
        target_id: id,
        rel_type: RelationType::Defines,
        confidence: 1.0,
    });

    id
}

/// Walk `delegation_specifiers` to emit INHERITS relationships.
///
/// Kotlin AST: `delegation_specifiers` contains `delegation_specifier` nodes,
/// each of which contains either a `constructor_invocation` or a `type` (user_type).
fn collect_supertypes(
    node: &Node<'_>,
    class_id: Uuid,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) {
    let Some(specs_node) = find_child_by_kind(node, "delegation_specifiers") else {
        return;
    };

    let mut specs_cursor = specs_node.walk();
    for spec in specs_node.children(&mut specs_cursor) {
        if spec.kind() != "delegation_specifier" {
            continue;
        }

        // A delegation_specifier contains one of:
        //   constructor_invocation -> Bar(...)
        //   type -> IFoo (a user_type directly)
        let mut sc = spec.walk();
        for inner in spec.children(&mut sc) {
            let base_name = match inner.kind() {
                "constructor_invocation" => {
                    // First child of constructor_invocation is the type (user_type).
                    find_child_by_kind(&inner, "user_type")
                        .map(|n| extract_simple_type_name(&n, source))
                        .unwrap_or_default()
                }
                "user_type" => extract_simple_type_name(&inner, source),
                _ => continue,
            };

            if base_name.is_empty() {
                continue;
            }

            let target_id = ctx
                .name_to_id
                .get(&base_name)
                .copied()
                .unwrap_or_else(|| Uuid::new_v5(&Uuid::NAMESPACE_OID, base_name.as_bytes()));

            let confidence = if ctx.name_to_id.contains_key(&base_name) {
                1.0
            } else if ctx.imported_names.contains(&base_name) {
                0.8
            } else {
                0.5
            };

            ctx.result.relationships.push(Relationship {
                source_id: class_id,
                target_id,
                rel_type: RelationType::Inherits,
                confidence,
            });
        }
    }
}

/// Extract the simple (unqualified) type name from a `user_type` node.
///
/// A `user_type` may look like `List<String>` or just `IFoo`.
/// We want the first identifier segment: `List` or `IFoo`.
fn extract_simple_type_name(node: &Node<'_>, source: &[u8]) -> String {
    // user_type contains identifier children (possibly multiple for qualified types).
    // Take the first one.
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "identifier" {
            return node_text(&child, source);
        }
    }
    // Fallback: strip generics from the full text.
    let full = node_text(node, source);
    full.split('<').next().unwrap_or(&full).trim().to_string()
}

// ---------------------------------------------------------------------------
// Signature builders
// ---------------------------------------------------------------------------

/// Build a human-readable signature for a class/object/interface.
fn build_type_signature(node: &Node<'_>, name: &str, source: &[u8]) -> String {
    let mut modifiers: Vec<String> = Vec::new();

    // Collect modifiers from the `modifiers` child node.
    if let Some(mods_node) = find_child_by_kind(node, "modifiers") {
        let mut mc = mods_node.walk();
        for modifier in mods_node.children(&mut mc) {
            // modifier children are things like class_modifier, visibility_modifier, etc.
            // Recurse one level to get the actual keyword text.
            let mut mc2 = modifier.walk();
            for kw in modifier.children(&mut mc2) {
                let text = node_text(&kw, source);
                if matches!(
                    text.as_str(),
                    "data"
                        | "sealed"
                        | "abstract"
                        | "open"
                        | "inner"
                        | "value"
                        | "enum"
                        | "annotation"
                ) {
                    modifiers.push(text);
                }
            }
        }
    }

    // Determine keyword: interface classes use "interface", objects use "object".
    let keyword = {
        let mut c = node.walk();
        let kw_text = node
            .children(&mut c)
            .find(|ch| matches!(ch.kind(), "interface" | "class" | "object"))
            .map(|ch| node_text(&ch, source))
            .unwrap_or_else(|| match node.kind() {
                "object_declaration" => "object".to_string(),
                _ => "class".to_string(),
            });
        kw_text
    };

    if modifiers.is_empty() {
        format!("{keyword} {name}")
    } else {
        format!("{} {keyword} {name}", modifiers.join(" "))
    }
}

/// Build a human-readable signature for a function.
fn build_function_signature(node: &Node<'_>, name: &str, source: &[u8]) -> String {
    let mut prefix_parts: Vec<String> = Vec::new();

    if let Some(mods_node) = find_child_by_kind(node, "modifiers") {
        let mut mc = mods_node.walk();
        for modifier in mods_node.children(&mut mc) {
            let mut mc2 = modifier.walk();
            for kw in modifier.children(&mut mc2) {
                let text = node_text(&kw, source);
                if matches!(
                    text.as_str(),
                    "suspend"
                        | "inline"
                        | "operator"
                        | "override"
                        | "private"
                        | "protected"
                        | "internal"
                        | "public"
                        | "abstract"
                        | "open"
                ) {
                    prefix_parts.push(text);
                }
            }
        }
    }

    // Parameters: look for `function_value_parameters` child.
    let params = find_child_by_kind(node, "function_value_parameters")
        .map(|n| node_text(&n, source))
        .unwrap_or_else(|| "()".to_string());

    // Return type: the `type` field child (after `:` and before `{`).
    // In the grammar this is a direct child with kind "user_type", "nullable_type", etc.
    // It appears after the function_value_parameters and before the function_body.
    let return_type = find_return_type(node, source);

    let fun_part = format!(
        "fun {name}{params}{}",
        return_type
            .as_deref()
            .map(|t| format!(": {t}"))
            .unwrap_or_default()
    );

    if prefix_parts.is_empty() {
        fun_part
    } else {
        format!("{} {fun_part}", prefix_parts.join(" "))
    }
}

/// Find the return type annotation of a function_declaration.
///
/// In the Kotlin grammar the return type appears as a direct child after
/// the `function_value_parameters`. It is a `type` field in the grammar spec,
/// but tree-sitter exposes it as a named child with kinds like `user_type`,
/// `nullable_type`, `function_type`, etc. We scan children positionally to
/// find it between the parameters and the function body.
fn find_return_type(node: &Node<'_>, source: &[u8]) -> Option<String> {
    let mut after_params = false;
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "function_value_parameters" {
            after_params = true;
            continue;
        }
        if !after_params {
            continue;
        }
        match child.kind() {
            "function_body" | "block" => break,
            "user_type" | "nullable_type" | "function_type" | "parenthesized_type"
            | "dynamic_type" => {
                return Some(node_text(&child, source));
            }
            _ => {}
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Call collection
// ---------------------------------------------------------------------------

/// Walk the entire tree collecting `call_expression` nodes.
fn collect_calls(node: &Node<'_>, source: &[u8], ctx: &mut ParseContext<'_>) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "call_expression" {
            process_call(&child, source, ctx);
        }
        // `this.<field>` reads - emit a References edge to the enclosing class's
        // field. Method calls (`this.method()`) are filtered inside
        // process_this_field_read.
        if child.kind() == "navigation_expression" {
            process_this_field_read(&child, source, ctx);
        }
        collect_calls(&child, source, ctx);
    }
}

fn process_call(node: &Node<'_>, source: &[u8], ctx: &mut ParseContext<'_>) {
    let Some(callee_node) = node.child(0) else {
        return;
    };

    let (callee_name, is_chained) = extract_callee_name(&callee_node, source);
    if callee_name.is_empty() {
        return;
    }

    let caller_id = find_enclosing_function(node, ctx);
    let source_id = caller_id.unwrap_or(ctx.result.symbols[0].id);

    let (target_id, confidence) = if let Some(&id) = ctx.name_to_id.get(&callee_name) {
        (id, 1.0_f32)
    } else if ctx.imported_names.contains(&callee_name) {
        (
            Uuid::new_v5(&Uuid::NAMESPACE_OID, callee_name.as_bytes()),
            0.8,
        )
    } else if is_chained {
        (
            Uuid::new_v5(&Uuid::NAMESPACE_OID, callee_name.as_bytes()),
            0.6,
        )
    } else {
        (
            Uuid::new_v5(&Uuid::NAMESPACE_OID, callee_name.as_bytes()),
            0.5,
        )
    };

    ctx.result.relationships.push(Relationship {
        source_id,
        target_id,
        rel_type: RelationType::Calls,
        confidence,
    });
}

/// Extract the leaf callee name and whether it was accessed via navigation.
fn extract_callee_name(node: &Node<'_>, source: &[u8]) -> (String, bool) {
    match node.kind() {
        "identifier" | "simple_identifier" => (node_text(node, source), false),
        "navigation_expression" => {
            // Last child is the right-hand identifier after the final `.`
            // AST: navigation_expression -> [expr, ".", identifier]
            let mut cursor = node.walk();
            let children: Vec<_> = node.children(&mut cursor).collect();
            // Walk backwards to find the last identifier.
            let name = children
                .iter()
                .rev()
                .find(|c| c.kind() == "identifier" || c.kind() == "simple_identifier")
                .map(|n| node_text(n, source))
                .unwrap_or_default();
            (name, true)
        }
        _ => {
            let text = node_text(node, source);
            let name = text.split('.').last().unwrap_or(&text).to_string();
            let is_chained = name != text;
            (name, is_chained)
        }
    }
}

/// Find the UUID of the innermost function/method that contains `call_node`.
fn find_enclosing_function(call_node: &Node<'_>, ctx: &ParseContext<'_>) -> Option<Uuid> {
    let call_start = call_node.start_position().row as i32 + 1;

    let mut best: Option<(Uuid, i32, i32)> = None;

    for sym in &ctx.result.symbols {
        if !matches!(sym.symbol_type, SymbolType::Function | SymbolType::Method) {
            continue;
        }
        if sym.file_path != ctx.file_path {
            continue;
        }
        let (start, end) = match (sym.start_line, sym.end_line) {
            (Some(s), Some(e)) => (s, e),
            _ => continue,
        };
        if call_start >= start && call_start <= end {
            let range = end - start;
            let current_best_range = best.map(|(_, s, e)| e - s).unwrap_or(i32::MAX);
            if range < current_best_range {
                best = Some((sym.id, start, end));
            }
        }
    }

    best.map(|(id, _, _)| id)
}

/// Find the UUID of the innermost class symbol that contains `node`.
fn find_enclosing_class(node: &Node<'_>, ctx: &ParseContext<'_>) -> Option<Uuid> {
    let target = node.start_position().row as i32 + 1;
    let mut best: Option<(Uuid, i32)> = None; // (id, span)

    for sym in &ctx.result.symbols {
        if sym.symbol_type != SymbolType::Class || sym.file_path != ctx.file_path {
            continue;
        }
        let (Some(s), Some(e)) = (sym.start_line, sym.end_line) else {
            continue;
        };
        if target >= s && target <= e {
            let range = e - s;
            if range < best.map(|(_, r)| r).unwrap_or(i32::MAX) {
                best = Some((sym.id, range));
            }
        }
    }

    best.map(|(id, _)| id)
}

/// Emit a `References` edge for a `this.<field>` read inside a method.
///
/// Only `navigation_expression` nodes whose receiver is `this`. Method calls
/// (`this.method()`, where the navigation_expression is the callee of a
/// `call_expression`) are skipped. Only resolves when the property names a
/// known class field of the enclosing class.
fn process_this_field_read(node: &Node<'_>, source: &[u8], ctx: &mut ParseContext<'_>) {
    let mut cursor = node.walk();
    let children: Vec<_> = node.children(&mut cursor).collect();

    // Receiver is the first named child.
    let is_this = children
        .iter()
        .find(|c| c.is_named())
        .map(|r| r.kind() == "this_expression" || node_text(r, source) == "this")
        .unwrap_or(false);
    if !is_this {
        return;
    }

    let field_name = children
        .iter()
        .rev()
        .find(|c| c.kind() == "identifier" || c.kind() == "simple_identifier")
        .map(|n| node_text(n, source))
        .unwrap_or_default();
    if field_name.is_empty() {
        return;
    }

    // Skip method invocations: `this.method()` - the navigation_expression is
    // the first child (callee) of a call_expression.
    if let Some(parent) = node.parent() {
        if parent.kind() == "call_expression"
            && parent.child(0).map(|c| c.id()) == Some(node.id())
        {
            return;
        }
    }

    let Some(class_id) = find_enclosing_class(node, ctx) else {
        return;
    };
    let Some(&field_id) = ctx.class_fields.get(&(class_id, field_name.clone())) else {
        return;
    };

    let source_id = find_enclosing_function(node, ctx)
        .unwrap_or_else(|| ctx.result.symbols[0].id);

    ctx.result.relationships.push(Relationship {
        source_id,
        target_id: field_id,
        rel_type: RelationType::References,
        confidence: 1.0,
    });
}

// ---------------------------------------------------------------------------
// Type annotation collection
// ---------------------------------------------------------------------------

/// Walk all `function_declaration` nodes anywhere in the tree and emit
/// UsesType relationships for each non-builtin type found in parameter and
/// return type positions.
fn collect_type_annotations(node: &Node<'_>, source: &[u8], ctx: &mut ParseContext<'_>) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "function_declaration" {
            process_func_type_annotations(&child, source, ctx);
        }
        collect_type_annotations(&child, source, ctx);
    }
}

/// Emit UsesType relationships for all non-builtin types in a
/// `function_declaration`'s parameters and return type.
fn process_func_type_annotations(node: &Node<'_>, source: &[u8], ctx: &mut ParseContext<'_>) {
    let name = node
        .child_by_field_name("name")
        .map(|n| node_text(&n, source))
        .unwrap_or_default();
    if name.is_empty() {
        return;
    }
    let func_id = match ctx.name_to_id.get(&name).copied() {
        Some(id) => id,
        None => return,
    };

    // Parameter types: walk function_value_parameters children.
    if let Some(params_node) = find_child_by_kind(node, "function_value_parameters") {
        for type_name in extract_kotlin_type_identifiers(&params_node, source) {
            emit_uses_type(func_id, &type_name, ctx);
        }
    }

    // Return type: appears directly after function_value_parameters.
    if let Some(ret_text) = find_return_type(node, source) {
        // find_return_type returns the full type text; extract identifiers from it.
        for type_name in extract_type_names_from_text(&ret_text) {
            if !is_kotlin_builtin(&type_name) {
                emit_uses_type(func_id, &type_name, ctx);
            }
        }
    }
}

/// Recursively collect non-builtin type identifier strings from a Kotlin
/// parameter list node subtree.
///
/// Handles:
/// - `user_type`       - `MyType` or `pkg.MyType` (first identifier segment)
/// - `nullable_type`   - `MyType?` (recurse into wrapped type)
/// - `type_identifier` - bare identifier used as a type
fn extract_kotlin_type_identifiers(node: &Node<'_>, source: &[u8]) -> Vec<String> {
    let mut result = Vec::new();
    collect_kotlin_type_ids(node, source, &mut result);
    result
}

fn collect_kotlin_type_ids(node: &Node<'_>, source: &[u8], out: &mut Vec<String>) {
    match node.kind() {
        "user_type" => {
            // Extract the first identifier segment (strips generics and qualifiers).
            let name = extract_simple_type_name(node, source);
            if !name.is_empty() && !is_kotlin_builtin(&name) {
                out.push(name);
            }
        }
        "nullable_type" => {
            // Recurse into the inner type.
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                collect_kotlin_type_ids(&child, source, out);
            }
        }
        "type_identifier" => {
            let name = node_text(node, source);
            if !name.is_empty() && !is_kotlin_builtin(&name) {
                out.push(name);
            }
        }
        _ => {
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                collect_kotlin_type_ids(&child, source, out);
            }
        }
    }
}

/// Extract simple identifier tokens from a raw type text string.
///
/// Used for return type text that has already been extracted as a string.
/// Splits on non-identifier characters and returns word-like tokens.
fn extract_type_names_from_text(text: &str) -> Vec<String> {
    let mut names = Vec::new();
    let mut current = String::new();
    for ch in text.chars() {
        if ch.is_alphanumeric() || ch == '_' {
            current.push(ch);
        } else {
            if !current.is_empty() {
                names.push(current.clone());
                current.clear();
            }
        }
    }
    if !current.is_empty() {
        names.push(current);
    }
    names
}

/// Returns true if `name` is a Kotlin stdlib/primitive type that should not
/// produce a UsesType relationship.
fn is_kotlin_builtin(name: &str) -> bool {
    matches!(
        name,
        "Int"
            | "Long"
            | "Short"
            | "Byte"
            | "Float"
            | "Double"
            | "Boolean"
            | "Char"
            | "String"
            | "Unit"
            | "Nothing"
            | "Any"
            | "Number"
            | "Comparable"
            | "List"
            | "Map"
            | "Set"
            | "MutableList"
            | "MutableMap"
            | "MutableSet"
            | "Array"
            | "Pair"
            | "Triple"
            | "Sequence"
            | "Iterable"
            | "Collection"
    )
}

/// Emit a single UsesType relationship from `source_id` to the resolved or
/// synthetic target UUID for `type_name`.
fn emit_uses_type(source_id: Uuid, type_name: &str, ctx: &mut ParseContext<'_>) {
    let (target_id, confidence) = if let Some(&id) = ctx.name_to_id.get(type_name) {
        (id, 1.0_f32)
    } else if ctx.imported_names.contains(type_name) {
        (Uuid::new_v5(&Uuid::NAMESPACE_OID, type_name.as_bytes()), 0.8)
    } else {
        (Uuid::new_v5(&Uuid::NAMESPACE_OID, type_name.as_bytes()), 0.5)
    };

    ctx.result.relationships.push(Relationship {
        source_id,
        target_id,
        rel_type: RelationType::UsesType,
        confidence,
    });
}

// ---------------------------------------------------------------------------
// Utility
// ---------------------------------------------------------------------------

/// Find the first direct child of `node` with the given `kind`.
fn find_child_by_kind<'a>(node: &Node<'a>, kind: &str) -> Option<Node<'a>> {
    let mut cursor = node.walk();
    node.children(&mut cursor).find(|c| c.kind() == kind)
}

fn node_text(node: &Node<'_>, source: &[u8]) -> String {
    node.utf8_text(source)
        .unwrap_or("")
        .trim()
        .to_string()
}