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
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
//! Tree-sitter based Rust parser.
//!
//! Extracts symbols and relationships from a single Rust source file.
//!
//! ## What is extracted
//!
//! Symbols:
//! - `fn` items (top-level) -> SymbolType::Function
//! - `struct` items         -> SymbolType::Class
//! - `enum` items           -> SymbolType::Class
//! - `trait` items          -> SymbolType::Class
//! - methods inside `impl`  -> SymbolType::Method
//! - the file itself        -> SymbolType::File
//!
//! Relationships:
//! - `use` declarations          -> RelationType::Imports
//! - `call_expression`           -> RelationType::Calls
//! - `impl Trait for Type`       -> RelationType::Inherits (type implements trait)
//! - enclosing scope -> symbol   -> RelationType::Defines

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

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

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

/// Parse a Rust 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_rust_file(
    file_path: &str,
    source: &str,
    project: &str,
    file_mtime: DateTime<Utc>,
) -> FileParseResult {
    let mut parser = Parser::new();
    parser
        .set_language(&tree_sitter_rust::LANGUAGE.into())
        .expect("failed to load Rust 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(),
        struct_fields: HashMap::new(),
    };

    // File-level symbol (always index 0 - other code depends on this).
    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: "rust".to_string(),
        project: project.to_string(),
        signature: None,
        file_mtime,
        layer: None,
        parent_symbol_id: None,
        moniker: None,
    });

    // Pass 1: collect `use` declarations (imports).
    let mut cursor = root.walk();
    collect_imports(&root, source_bytes, &mut ctx, &mut cursor);

    // Pass 2: collect type/function definitions and impl blocks.
    let mut cursor2 = root.walk();
    collect_definitions(&root, file_symbol_id, None, source_bytes, &mut ctx, &mut cursor2);

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

    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>,
    /// Names brought into scope via `use` statements.
    imported_names: HashSet<String>,
    /// (struct_id, field_name) -> field symbol UUID for struct fields defined in
    /// this file. Used to resolve `self.<field>` reads inside `impl` blocks to the
    /// struct's field. Keyed by struct id (not impl id) since methods live in a
    /// separate `impl` block from the struct definition.
    struct_fields: HashMap<(Uuid, String), Uuid>,
}

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

/// Recursively walk the AST looking for `use_declaration` nodes at any depth.
///
/// Rust allows `use` declarations inside function bodies (item-scoped imports),
/// so we must scan beyond the top level to capture all imports.  The imported
/// names are recorded on the file symbol regardless of nesting depth.
fn collect_imports<'a>(
    node: &Node<'a>,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
    cursor: &mut TreeCursor<'a>,
) {
    for child in node.children(cursor) {
        if child.kind() == "use_declaration" {
            process_use_declaration(&child, source, ctx);
        }
        // Recurse into blocks (function bodies, impl blocks, mod items) so that
        // inner `use` declarations are also captured.
        let mut inner = child.walk();
        collect_imports(&child, source, ctx, &mut inner);
    }
}

/// Emit an Imports relationship and a RawImport for a single `use` declaration.
///
/// Rust `use` paths use `::` as separators and may start with:
/// - `crate::` - absolute from the current crate root
/// - `super::` - parent module
/// - `self::` - current module
/// - an external crate name
///
/// We convert `::` to `/` for the module_path so the walker can do suffix
/// matching the same way it does for Python absolute imports.
fn process_use_declaration(node: &Node<'_>, source: &[u8], ctx: &mut ParseContext<'_>) {
    // The `use_declaration` node structure:
    //   use_declaration -> "use" argument=use_tree ";"
    //
    // use_tree can be:
    //   - scoped_identifier (e.g., `crate::foo::Bar`)
    //   - identifier (e.g., `std`)
    //   - use_wildcard (e.g., `crate::foo::*`)
    //   - use_list (e.g., `{ Foo, Bar }` - nested under a parent path)
    //
    // We extract a flat string from the argument and normalise it.

    let Some(arg) = node.child_by_field_name("argument") else {
        return;
    };

    // Collect all leaf paths from (potentially nested) use trees.
    let mut paths: Vec<String> = Vec::new();
    collect_use_tree_paths(&arg, source, &mut paths);

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

    for raw_path in paths {
        if raw_path.is_empty() {
            continue;
        }

        // Record the last segment as an imported name for call scoring.
        if let Some(last) = raw_path.split("::").last() {
            let name = last.trim_end_matches('*');
            if !name.is_empty() && name != "{" {
                ctx.imported_names.insert(name.to_string());
            }
        }

        // Classify relative vs absolute.
        let is_relative = raw_path.starts_with("crate::")
            || raw_path.starts_with("super::")
            || raw_path.starts_with("self::");

        // Convert `crate::foo::bar` -> `foo/bar` for suffix matching.
        // `super::foo` -> `foo`
        // `external_crate::foo` -> `external_crate/foo`
        let module_path = use_path_to_module_path(&raw_path);

        ctx.result.raw_imports.push(RawImport {
            source_id: file_id,
            module_raw: raw_path.clone(),
            is_relative,
            dot_count: 0, // Rust uses :: not dots
            module_path: module_path.clone(),
        });

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

/// Recursively collect all terminal paths from a use_tree node.
///
/// Handles:
/// - Simple identifier: `use foo` -> ["foo"]
/// - Scoped: `use foo::bar` -> ["foo::bar"]
/// - Glob: `use foo::*` -> ["foo::*"]
/// - List: `use foo::{Bar, Baz}` -> ["foo::Bar", "foo::Baz"]
fn collect_use_tree_paths(node: &Node<'_>, source: &[u8], paths: &mut Vec<String>) {
    match node.kind() {
        "identifier" | "self" | "crate" | "super" => {
            paths.push(node_text(node, source));
        }
        "scoped_identifier" => {
            // path::name
            paths.push(node_text(node, source));
        }
        "scoped_use_list" => {
            // `foo::{Bar, Baz}` - tree-sitter-rust: path + list
            let prefix = node
                .child_by_field_name("path")
                .map(|n| node_text(&n, source))
                .unwrap_or_default();
            if let Some(list) = node.child_by_field_name("list") {
                let mut sub_paths: Vec<String> = Vec::new();
                let mut c = list.walk();
                for child in list.named_children(&mut c) {
                    collect_use_tree_paths(&child, source, &mut sub_paths);
                }
                for sub in sub_paths {
                    if prefix.is_empty() {
                        paths.push(sub);
                    } else {
                        paths.push(format!("{prefix}::{sub}"));
                    }
                }
            }
        }
        "use_list" => {
            // `{ Foo, Bar }` as a standalone use_list (top of the tree).
            let mut c = node.walk();
            for child in node.named_children(&mut c) {
                collect_use_tree_paths(&child, source, paths);
            }
        }
        "use_wildcard" => {
            // `foo::*` - the wildcard node contains path + "*"
            paths.push(node_text(node, source));
        }
        "use_as_clause" => {
            // `foo::Bar as Baz` - record original path
            let path = node
                .child_by_field_name("path")
                .map(|n| node_text(&n, source))
                .unwrap_or_else(|| node_text(node, source));
            paths.push(path);
        }
        _ => {
            // Fallback: just grab the text.
            let text = node_text(node, source);
            if !text.is_empty() {
                paths.push(text);
            }
        }
    }
}

/// Convert a Rust use path to a filesystem-style module path for suffix matching.
///
/// - `crate::foo::bar`  -> `foo/bar`   (crate root relative)
/// - `super::foo`       -> `foo`        (parent module)
/// - `self::foo`        -> `foo`
/// - `std::collections` -> `std/collections` (external)
/// - `some::path::*`    -> `some/path`  (strip wildcard)
fn use_path_to_module_path(use_path: &str) -> String {
    let stripped = use_path
        .trim_end_matches("::*")
        .trim_end_matches("::{}")
        .trim_end_matches("::self");

    let without_prefix = if let Some(rest) = stripped.strip_prefix("crate::") {
        rest
    } else if let Some(rest) = stripped.strip_prefix("super::") {
        rest
    } else if let Some(rest) = stripped.strip_prefix("self::") {
        rest
    } else {
        stripped
    };

    without_prefix.replace("::", "/")
}

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

/// Recursively walk the AST collecting definitions.
///
/// Top-level items: fn_item, struct_item, enum_item, trait_item, impl_item.
/// Inside impl blocks: fn_item -> Method.
fn collect_definitions<'a>(
    node: &Node<'a>,
    parent_id: Uuid,
    enclosing_impl: Option<ImplContext>,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
    cursor: &mut TreeCursor<'a>,
) {
    for child in node.children(cursor) {
        match child.kind() {
            "function_item" => {
                let sym_id =
                    process_function(&child, parent_id, enclosing_impl.as_ref(), source, ctx);
                // Recurse into function body.
                if let Some(body) = child.child_by_field_name("body") {
                    let mut inner = body.walk();
                    collect_definitions(&body, sym_id, None, source, ctx, &mut inner);
                }
            }
            "struct_item" => {
                process_adt(&child, parent_id, source, ctx, "struct");
            }
            "enum_item" => {
                process_adt(&child, parent_id, source, ctx, "enum");
            }
            "trait_item" => {
                let trait_id = process_adt(&child, parent_id, source, ctx, "trait");
                // Also extract method signatures defined in the trait body.
                process_trait_body(&child, trait_id, source, ctx);
            }
            "impl_item" => {
                process_impl(&child, parent_id, source, ctx);
            }
            _ => {
                // Descend into mod items, if/match blocks, etc.
                let mut inner = child.walk();
                collect_definitions(
                    &child,
                    parent_id,
                    enclosing_impl.clone(),
                    source,
                    ctx,
                    &mut inner,
                );
            }
        }
    }
}

/// Context carried when we are inside an `impl` block.
///
/// Signals to `process_function` that the function being defined is a method
/// and provides the type name so the method can be stored as `TypeName::method`.
#[derive(Debug, Clone)]
struct ImplContext {
    /// The base type name (e.g. "Controller" for `impl Controller<'_>`).
    type_name: String,
}

/// Process `struct Foo`, `enum Bar`, `trait Baz` items -> SymbolType::Class.
fn process_adt(
    node: &Node<'_>,
    parent_id: Uuid,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
    keyword: &str,
) -> Uuid {
    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();

    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: "rust".to_string(),
        project: ctx.project.to_string(),
        signature: Some(format!("{keyword} {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,
    });

    // USES_TYPE: struct field types.
    if keyword == "struct" {
        collect_type_annotations(node, id, source, ctx);
        // Capture named struct fields as Field symbols with a Defines edge from
        // the struct. Tuple-struct fields have no name and are skipped.
        collect_struct_fields(node, id, source, ctx);
    }

    id
}

/// Walk a `struct_item` body and emit a `Field` symbol + `Defines` edge for each
/// named `field_declaration`. Tuple-struct fields (no name) are skipped.
fn collect_struct_fields(
    node: &Node<'_>,
    struct_id: Uuid,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) {
    let Some(body) = node.child_by_field_name("body") else {
        return;
    };
    let mut cursor = body.walk();
    for field in body.named_children(&mut cursor) {
        if field.kind() != "field_declaration" {
            continue;
        }
        let Some(name_node) = field.child_by_field_name("name") else {
            continue; // tuple field, no name
        };
        let name = node_text(&name_node, source);
        if name.is_empty() {
            continue;
        }
        let start_line = field.start_position().row as i32 + 1;
        let end_line = field.end_position().row as i32 + 1;
        let field_id = Uuid::new_v4();
        ctx.struct_fields.insert((struct_id, name.clone()), field_id);

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

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

/// Extract method signatures from a `trait_item` body.
///
/// Trait method definitions (with or without a default body) are collected as
/// Method symbols so that cross-file call resolution can find them via
/// `synthetic_to_real` in the walker.
fn process_trait_body(node: &Node<'_>, trait_id: Uuid, source: &[u8], ctx: &mut ParseContext<'_>) {
    // Retrieve the trait name (already registered in name_to_id by process_adt).
    let trait_name = node
        .child_by_field_name("name")
        .map(|n| node_text(&n, source))
        .unwrap_or_default();

    if trait_name.is_empty() {
        return;
    }

    let impl_ctx = ImplContext {
        type_name: trait_name,
    };

    if let Some(body) = node.child_by_field_name("body") {
        let mut c = body.walk();
        for child in body.named_children(&mut c) {
            // `function_signature_item` = signature without body (required methods)
            // `function_item` = function with default body
            if child.kind() == "function_item" || child.kind() == "function_signature_item" {
                let method_id =
                    process_function(&child, trait_id, Some(&impl_ctx), source, ctx);

                // DEFINES: the trait defines this method.
                ctx.result.relationships.push(Relationship {
                    source_id: trait_id,
                    target_id: method_id,
                    rel_type: RelationType::Defines,
                    confidence: 1.0,
                });
            }
        }
    }
}

/// Process an `impl` block.
///
/// Two forms:
/// - `impl Foo { ... }`         -> methods are defined on Foo
/// - `impl Trait for Foo { ... }` -> Foo Inherits Trait + methods on Foo
fn process_impl(node: &Node<'_>, parent_id: Uuid, source: &[u8], ctx: &mut ParseContext<'_>) {
    // In tree-sitter-rust, impl_item has:
    //   trait (optional) = the trait name
    //   type = the type being implemented
    let type_node = node.child_by_field_name("type");
    let trait_node = node.child_by_field_name("trait");

    let type_name = type_node
        .as_ref()
        .map(|n| extract_type_name(n, source))
        .unwrap_or_else(|| "<unknown>".to_string());

    // Resolve the type UUID (may already be known if defined in this file).
    let type_id = ctx
        .name_to_id
        .get(&type_name)
        .copied()
        .unwrap_or_else(|| Uuid::new_v5(&Uuid::NAMESPACE_OID, type_name.as_bytes()));

    // `impl Trait for Type` -> emit Inherits(Type, Trait).
    if let Some(trait_node) = trait_node {
        let trait_name = extract_type_name(&trait_node, source);
        if !trait_name.is_empty() {
            // If the trait is defined in this file, use its real UUID.
            // If it's a stdlib or external trait (e.g. Default, Drop, FromStr),
            // create a synthetic symbol in this file so the comparator can find
            // it via a "file::TraitName" reference.
            let trait_id = if let Some(&id) = ctx.name_to_id.get(&trait_name) {
                id
            } else {
                // Create a synthetic Class symbol representing the external trait.
                // Use a deterministic UUID so multiple impl blocks for the same
                // trait in the same file share the same node.
                let synthetic_key = format!("{}::{}", ctx.file_path, trait_name);
                let id = Uuid::new_v5(&Uuid::NAMESPACE_OID, synthetic_key.as_bytes());
                // Only push if we haven't already emitted this synthetic trait.
                if !ctx.result.symbols.iter().any(|s| s.id == id) {
                    ctx.result.symbols.push(Symbol {
                        id,
                        name: trait_name.clone(),
                        symbol_type: SymbolType::Class,
                        file_path: ctx.file_path.to_string(),
                        start_line: None,
                        end_line: None,
                        language: "rust".to_string(),
                        project: ctx.project.to_string(),
                        signature: Some(format!("trait {trait_name}")),
                        file_mtime: ctx.file_mtime,
                        layer: None,
                        parent_symbol_id: None,
                        moniker: None,
                    });
                    ctx.name_to_id.insert(trait_name.clone(), id);
                }
                id
            };

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

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

    let impl_ctx = ImplContext {
        type_name: type_name.clone(),
    };

    // Walk the impl body collecting methods.
    if let Some(body) = node.child_by_field_name("body") {
        let mut c = body.walk();
        for child in body.named_children(&mut c) {
            if child.kind() == "function_item" {
                let method_id =
                    process_function(&child, parent_id, Some(&impl_ctx), source, ctx);

                // DEFINES: the type defines this method.
                ctx.result.relationships.push(Relationship {
                    source_id: type_id,
                    target_id: method_id,
                    rel_type: RelationType::Defines,
                    confidence: 1.0,
                });

                // Recurse into method body.
                if let Some(fn_body) = child.child_by_field_name("body") {
                    let mut inner = fn_body.walk();
                    collect_definitions(&fn_body, method_id, None, source, ctx, &mut inner);
                }
            }
        }
    }

    // Suppress the "unused parent_id" lint.
    let _ = parent_id;
}

/// Process a `fn` item inside any scope.
///
/// Returns the UUID of the newly created symbol.
fn process_function(
    node: &Node<'_>,
    parent_id: Uuid,
    impl_ctx: Option<&ImplContext>,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) -> Uuid {
    let bare_name = node
        .child_by_field_name("name")
        .map(|n| node_text(&n, source))
        .unwrap_or_else(|| "<anonymous>".to_string());

    // Methods are stored as "TypeName::method_name" so that the test harness
    // and call-resolution logic can find them by their qualified name.
    let name = if let Some(ic) = impl_ctx {
        format!("{}::{}", ic.type_name, bare_name)
    } else {
        bare_name.clone()
    };

    let symbol_type = if impl_ctx.is_some() {
        SymbolType::Method
    } else {
        SymbolType::Function
    };

    let signature = build_fn_signature(node, &bare_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();

    // Register both the qualified name and the bare name for call resolution.
    // The qualified name is the canonical key; the bare name is a fallback so
    // that calls written as `new(...)` inside the same file can still resolve.
    ctx.name_to_id.insert(name.clone(), id);
    if impl_ctx.is_some() {
        ctx.name_to_id.entry(bare_name.clone()).or_insert(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: "rust".to_string(),
        project: ctx.project.to_string(),
        signature: Some(signature),
        file_mtime: ctx.file_mtime,
        layer: None,
        parent_symbol_id: None,
        moniker: None,
    });

    // DEFINES: parent scope (file or outer function) defines this function.
    // For methods, the parent_id passed here is the file; process_impl also
    // emits a second DEFINES from the type. We emit the file-level DEFINES only
    // for top-level functions (when impl_ctx is None) to avoid duplicating.
    if impl_ctx.is_none() {
        ctx.result.relationships.push(Relationship {
            source_id: parent_id,
            target_id: id,
            rel_type: RelationType::Defines,
            confidence: 1.0,
        });
    }

    // USES_TYPE: relationships from type annotations on parameters and return type.
    collect_type_annotations(node, id, source, ctx);

    id
}

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

fn collect_calls<'a>(
    node: &Node<'a>,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
    cursor: &mut TreeCursor<'a>,
) {
    // Build a local variable-to-type map to enable field_expression resolution.
    // Example: `let controller = Controller::new(...)` -> controller: Controller
    // Example: `let mut printer: Box<dyn Printer> = ...` -> printer: Printer
    let mut local_var_types: HashMap<String, String> = HashMap::new();
    collect_local_var_types(node, source, &mut local_var_types);

    collect_calls_inner(node, source, ctx, cursor, &local_var_types);
}

fn collect_calls_inner<'a>(
    node: &Node<'a>,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
    cursor: &mut TreeCursor<'a>,
    local_var_types: &HashMap<String, String>,
) {
    for child in node.children(cursor) {
        if child.kind() == "call_expression" {
            process_call(&child, source, ctx, local_var_types);
        }
        // `self.<field>` reads - emit a References edge to the struct's field.
        // Method calls (`self.method()`) and writes (`self.x = ...`) are filtered
        // inside process_self_field_read.
        if child.kind() == "field_expression" {
            process_self_field_read(&child, source, ctx);
        }
        let mut inner = child.walk();
        collect_calls_inner(&child, source, ctx, &mut inner, local_var_types);
    }
}

/// Scan `let_declaration` and `parameter` nodes to build a variable-to-type map.
///
/// Handles:
/// 1. `let x = TypeName::new(...)` -> x: TypeName (infer from constructor call)
/// 2. `let x: Box<dyn TypeName> = ...` or `let x: TypeName = ...` -> x: TypeName (from annotation)
/// 3. Function parameters `fn f(x: &mut TypeName, ...)` -> x: TypeName
fn collect_local_var_types<'a>(
    node: &Node<'a>,
    source: &[u8],
    var_types: &mut HashMap<String, String>,
) {
    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        match child.kind() {
            "let_declaration" => {
                if let Some(type_name) = extract_let_type(&child, source) {
                    if let Some(pat) = child.child_by_field_name("pattern") {
                        let var_name = extract_pattern_name(&pat, source);
                        if !var_name.is_empty() && !type_name.is_empty() {
                            var_types.insert(var_name, type_name);
                        }
                    }
                }
            }
            "parameter" => {
                // Function parameters: `name: TypeExpr`
                // The pattern is the first named child, type is via "type" field.
                if let Some(pat) = child.child_by_field_name("pattern") {
                    if let Some(type_node) = child.child_by_field_name("type") {
                        let var_name = extract_pattern_name(&pat, source);
                        let type_name = extract_leaf_type_name(&type_node, source);
                        if !var_name.is_empty() && !type_name.is_empty()
                            && var_name != "self"
                        {
                            var_types.insert(var_name, type_name);
                        }
                    }
                }
            }
            _ => {}
        }
        collect_local_var_types(&child, source, var_types);
    }
}

/// Extract the type name from a `let_declaration` node.
///
/// Tries:
/// 1. Explicit type annotation: `let x: SomeType = ...` -> "SomeType"
/// 2. Constructor inference: `let x = SomeType::new(...)` -> "SomeType"
fn extract_let_type(node: &Node<'_>, source: &[u8]) -> Option<String> {
    // Try explicit type annotation first.
    if let Some(type_node) = node.child_by_field_name("type") {
        let type_name = extract_leaf_type_name(&type_node, source);
        if !type_name.is_empty() {
            return Some(type_name);
        }
    }

    // Infer from initializer: `SomeType::new(...)` or `SomeType { ... }`
    if let Some(value_node) = node.child_by_field_name("value") {
        return infer_type_from_expr(&value_node, source);
    }

    None
}

/// Extract the leaf type name from a type annotation node.
///
/// Handles:
/// - `type_identifier` -> "Foo"
/// - `generic_type` -> strips generics
/// - `dynamic_type` (`dyn Trait`) -> extracts trait name
/// - `reference_type` -> recurse
/// - `scoped_type_identifier` -> last segment
fn extract_leaf_type_name(node: &Node<'_>, source: &[u8]) -> String {
    match node.kind() {
        "type_identifier" => node_text(node, source),
        "generic_type" => {
            // `Box<dyn Printer>` - get the outer type or recurse into type args.
            // For `Box<dyn Trait>` we want "Trait" not "Box".
            // Check if the type argument is a dyn type.
            if let Some(args) = node.child_by_field_name("type_arguments") {
                let mut c = args.walk();
                for arg in args.named_children(&mut c) {
                    let inner = extract_leaf_type_name(&arg, source);
                    if !inner.is_empty() && inner != "Box" && inner != "Vec" && inner != "Option" {
                        return inner;
                    }
                }
            }
            // Fall back to the base type name.
            node.child_by_field_name("type")
                .map(|n| extract_leaf_type_name(&n, source))
                .unwrap_or_default()
        }
        "dynamic_type" => {
            // `dyn Trait` - use the `trait` field.
            node.child_by_field_name("trait")
                .map(|n| extract_leaf_type_name(&n, source))
                .unwrap_or_default()
        }
        "reference_type" => {
            // `&mut Type` or `&Type` - use the `type` field.
            node.child_by_field_name("type")
                .map(|n| extract_leaf_type_name(&n, source))
                .unwrap_or_default()
        }
        "scoped_type_identifier" => {
            node.child_by_field_name("name")
                .map(|n| node_text(&n, source))
                .unwrap_or_default()
        }
        _ => String::new(),
    }
}

/// Infer the type name from an expression node (for constructor-style inference).
fn infer_type_from_expr(node: &Node<'_>, source: &[u8]) -> Option<String> {
    match node.kind() {
        "call_expression" => {
            // `SomeType::new(...)` or `SomeType::method(...)`
            let func = node.child_by_field_name("function")?;
            match func.kind() {
                "scoped_identifier" => {
                    // Take the path (left side of `::`).
                    if let Some(path) = func.child_by_field_name("path") {
                        let path_text = node_text(&path, source);
                        // Use only the last segment of a multi-segment path.
                        let last = path_text.split("::").last().unwrap_or("").to_string();
                        if !last.is_empty() {
                            return Some(last);
                        }
                    }
                    None
                }
                _ => None,
            }
        }
        // `Box::new(inner_expr)` - try to unwrap by looking at the argument.
        // If argument is also a call like `InteractivePrinter::new(...)`, use that.
        _ => None,
    }
}

/// Extract the variable name from a pattern node.
fn extract_pattern_name(node: &Node<'_>, source: &[u8]) -> String {
    match node.kind() {
        "identifier" => node_text(node, source),
        "mut_pattern" | "ref_pattern" => {
            let mut c = node.walk();
            for child in node.named_children(&mut c) {
                let name = extract_pattern_name(&child, source);
                if !name.is_empty() {
                    return name;
                }
            }
            String::new()
        }
        _ => String::new(),
    }
}

fn process_call(
    node: &Node<'_>,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
    local_var_types: &HashMap<String, String>,
) {
    // call_expression: function field is the callee.
    let Some(function_node) = node.child_by_field_name("function") else {
        return;
    };

    let (mut callee_name, callee_kind) = extract_callee_name(&function_node, source, local_var_types);
    if callee_name.is_empty() {
        return;
    }

    // For field_expression calls resolved to a type prefix via local var types,
    // the callee_name is already `Type::method`.  For other field expressions
    // without type info, the bare method name is used.
    // Strip the `::` qualifier from any crate:: or module:: prefixes so we
    // match the name as stored by the parser (e.g. "crate::foo::bar" -> "bar").
    if callee_kind == CalleeKind::PathOrField && callee_name.contains("::") {
        // If it's a scoped identifier with a crate/module prefix, strip it.
        // But preserve `Type::method` form for cross-file resolution.
        let segments: Vec<&str> = callee_name.split("::").collect();
        // Only strip crate/super/self prefixes; keep Type::method as-is.
        if segments[0] == "crate" || segments[0] == "super" || segments[0] == "self" {
            callee_name = segments[1..].join("::");
        }
    }

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

    // Confidence scoring mirrors the Python/TS parsers:
    //   1.0 - callee defined in this file
    //   0.8 - callee type (first segment) was imported, or it's a self-chain
    //   0.6 - self/Self method call (type not statically resolved)
    //   0.5 - unknown
    //
    // For scoped identifiers like `Controller::new`, callee_name is the full
    // path.  We check both the full name and the type prefix against
    // imported_names so that cross-file calls resolve correctly.
    let callee_type_prefix = callee_name
        .split("::")
        .next()
        .unwrap_or("")
        .to_string();
    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)
        || (!callee_type_prefix.is_empty() && ctx.imported_names.contains(&callee_type_prefix))
    {
        (
            Uuid::new_v5(&Uuid::NAMESPACE_OID, callee_name.as_bytes()),
            0.8,
        )
    } else if callee_kind == CalleeKind::SelfChain {
        (
            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,
    });
}

#[derive(Debug, PartialEq)]
enum CalleeKind {
    /// Plain function call: `foo()`
    Bare,
    /// `self.method()` call
    SelfChain,
    /// Any other path-based call: `Foo::bar()`, `obj.method()`
    PathOrField,
}

/// Extract the leaf function name from a Rust callee expression.
///
/// Rust callee forms:
/// - `identifier` -> bare call `foo()`
/// - `field_expression` -> method call on a receiver `obj.method()`
/// - `scoped_identifier` -> `Foo::new()`, `crate::util::helper()`
///
/// For `field_expression`, if `local_var_types` contains the receiver variable's
/// type, the returned name is qualified as `Type::method`, enabling cross-file
/// call resolution.
fn extract_callee_name(
    node: &Node<'_>,
    source: &[u8],
    local_var_types: &HashMap<String, String>,
) -> (String, CalleeKind) {
    match node.kind() {
        "identifier" => (node_text(node, source), CalleeKind::Bare),
        "field_expression" => {
            // obj.field - take the field name as callee.
            let field = node
                .child_by_field_name("field")
                .map(|n| node_text(&n, source))
                .unwrap_or_default();

            if field_expr_starts_with_self(node, source) {
                return (field, CalleeKind::SelfChain);
            }

            // Try to qualify the method call using local variable type info.
            // Only look at simple receiver identifiers (not chained expressions).
            if let Some(value_node) = node.child_by_field_name("value") {
                if value_node.kind() == "identifier" {
                    let var_name = node_text(&value_node, source);
                    if let Some(type_name) = local_var_types.get(&var_name) {
                        let qualified = format!("{type_name}::{field}");
                        return (qualified, CalleeKind::PathOrField);
                    }
                }
            }

            (field, CalleeKind::PathOrField)
        }
        "scoped_identifier" => {
            // `Foo::new` - return the full qualified path so that cross-file
            // resolution can match the symbol by its qualified name (e.g.
            // `Controller::new`).  The full text is used as the callee name;
            // `process_call` handles splitting for imported-name lookup.
            let full = node_text(node, source);
            (full, CalleeKind::PathOrField)
        }
        _ => (String::new(), CalleeKind::Bare),
    }
}

/// Walk up a field_expression chain to check if it starts with `self`.
fn field_expr_starts_with_self(node: &Node<'_>, source: &[u8]) -> bool {
    let mut current = node.clone();
    loop {
        match current.kind() {
            "field_expression" => {
                if let Some(obj) = current.child_by_field_name("value") {
                    current = obj;
                } else {
                    return false;
                }
            }
            "self" => return true,
            "identifier" => {
                return node_text(&current, source) == "self";
            }
            _ => return false,
        }
    }
}

/// Find the innermost function/method symbol containing `call_node` by line number.
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)> = None; // (id, range)

    for sym in &ctx.result.symbols {
        if !matches!(sym.symbol_type, SymbolType::Function | SymbolType::Method) {
            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 = best.map(|(_, r)| r).unwrap_or(i32::MAX);
            if range < current_best {
                best = Some((sym.id, range));
            }
        }
    }

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

/// Walk up the AST from `node` to find the enclosing `impl_item` and return the
/// name of the type being implemented. Returns None outside any impl block.
fn find_enclosing_impl_type(node: &Node<'_>, source: &[u8]) -> Option<String> {
    let mut current = node.parent()?;
    loop {
        if current.kind() == "impl_item" {
            if let Some(type_node) = current.child_by_field_name("type") {
                let name = extract_type_name(&type_node, source);
                if !name.is_empty() {
                    return Some(name);
                }
            }
            return None;
        }
        current = current.parent()?;
    }
}

/// Emit a `References` edge for a `self.<field>` read inside an `impl` method.
///
/// Only direct `self.<name>` field expressions (value is `self`). Intermediate
/// reads in `self.foo.bar()` (i.e. `self.foo`) are still caught. Method calls
/// (`self.method()`) and writes (`self.x = ...`) are skipped. The field is
/// resolved against the struct named by the enclosing `impl` block via the
/// per-file `struct_fields` map.
fn process_self_field_read(node: &Node<'_>, source: &[u8], ctx: &mut ParseContext<'_>) {
    let Some(value) = node.child_by_field_name("value") else {
        return;
    };
    // `self.x` -> value is `self` node or identifier "self". `&self.x` wraps the
    // field_expression in a reference_expression; the field_expression's value is
    // still `self`.
    let is_self = match value.kind() {
        "self" => true,
        "identifier" => node_text(&value, source) == "self",
        _ => false,
    };
    if !is_self {
        return;
    }
    let Some(field_node) = node.child_by_field_name("field") else {
        return;
    };
    let field_name = node_text(&field_node, source);
    if field_name.is_empty() {
        return;
    }

    if let Some(parent) = node.parent() {
        // Skip method invocations: `self.method()`.
        if parent.kind() == "call_expression"
            && parent.child_by_field_name("function").map(|f| f.id()) == Some(node.id())
        {
            return;
        }
        // Skip writes: `self.x = ...`.
        if parent.kind() == "assignment_expression"
            && parent.child_by_field_name("left").map(|l| l.id()) == Some(node.id())
        {
            return;
        }
    }

    let Some(type_name) = find_enclosing_impl_type(node, source) else {
        return;
    };
    let Some(&struct_id) = ctx.name_to_id.get(&type_name) else {
        return;
    };
    let Some(&field_id) = ctx.struct_fields.get(&(struct_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 extraction
// ---------------------------------------------------------------------------

/// Walk a function node's parameter list and return-type annotation, collecting
/// `UsesType` relationships for every non-builtin type name found.
///
/// Also handles struct field types when `func_node` is a `struct_item`.
fn collect_type_annotations(
    func_node: &Node<'_>,
    func_id: Uuid,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) {
    let mut type_names: Vec<String> = Vec::new();

    // 1. Parameter type annotations.
    if let Some(params) = func_node.child_by_field_name("parameters") {
        let mut cursor = params.walk();
        for param in params.named_children(&mut cursor) {
            // Skip `self` and `&self` / `&mut self` parameters.
            if param.kind() == "self_parameter" {
                continue;
            }
            if let Some(type_node) = param.child_by_field_name("type") {
                extract_type_identifiers(&type_node, source, &mut type_names);
            }
        }
    }

    // 2. Return type annotation.
    if let Some(return_type) = func_node.child_by_field_name("return_type") {
        extract_type_identifiers(&return_type, source, &mut type_names);
    }

    // 3. Struct field types (when the node is a struct_item).
    if func_node.kind() == "struct_item" {
        if let Some(body) = func_node.child_by_field_name("body") {
            let mut cursor = body.walk();
            for field in body.named_children(&mut cursor) {
                if field.kind() == "field_declaration" {
                    if let Some(type_node) = field.child_by_field_name("type") {
                        extract_type_identifiers(&type_node, source, &mut type_names);
                    }
                }
            }
        }
    }

    // 4. Emit UsesType relationships for all collected non-builtin types.
    // Deduplicate before emitting.
    let mut seen: HashSet<String> = HashSet::new();
    for type_name in type_names {
        if is_builtin_rust_type(&type_name) {
            continue;
        }
        if !seen.insert(type_name.clone()) {
            continue;
        }
        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: func_id,
            target_id,
            rel_type: RelationType::UsesType,
            confidence,
        });
    }
}

/// Recursively collect all type identifier names from a type node.
///
/// Handles:
/// - `type_identifier`          -> push the name directly
/// - `generic_type`             -> push the outer name, recurse into type arguments
/// - `reference_type`           -> recurse into the inner `type` field
/// - `scoped_type_identifier`   -> push the last segment (`name` field)
/// - `dynamic_type`             -> recurse into the `trait` field
/// - everything else            -> recurse into named children
fn extract_type_identifiers(node: &Node<'_>, source: &[u8], out: &mut Vec<String>) {
    match node.kind() {
        "type_identifier" => {
            let name = node_text(node, source);
            if !name.is_empty() {
                out.push(name);
            }
        }
        "scoped_type_identifier" => {
            // `module::Type` - only record the last segment.
            let name = node
                .child_by_field_name("name")
                .map(|n| node_text(&n, source))
                .unwrap_or_else(|| {
                    let text = node_text(node, source);
                    text.split("::").last().unwrap_or("").to_string()
                });
            if !name.is_empty() {
                out.push(name);
            }
        }
        "generic_type" => {
            // `Vec<SomeType>` - push the outer name and recurse into arguments.
            if let Some(base) = node.child_by_field_name("type") {
                extract_type_identifiers(&base, source, out);
            }
            if let Some(args) = node.child_by_field_name("type_arguments") {
                let mut cursor = args.walk();
                for arg in args.named_children(&mut cursor) {
                    extract_type_identifiers(&arg, source, out);
                }
            }
        }
        "reference_type" => {
            // `&SomeType` or `&mut SomeType`
            if let Some(inner) = node.child_by_field_name("type") {
                extract_type_identifiers(&inner, source, out);
            }
        }
        "dynamic_type" => {
            // `dyn Trait`
            if let Some(trait_node) = node.child_by_field_name("trait") {
                extract_type_identifiers(&trait_node, source, out);
            }
        }
        "tuple_type" | "array_type" | "slice_type" | "pointer_type"
        | "abstract_type" | "bounded_type" => {
            // Recurse into all named children.
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                extract_type_identifiers(&child, source, out);
            }
        }
        _ => {
            // Fallback: recurse.
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                extract_type_identifiers(&child, source, out);
            }
        }
    }
}

/// Returns `true` for Rust primitive types, standard library containers,
/// and other pervasive types that should not generate `UsesType` relationships.
fn is_builtin_rust_type(name: &str) -> bool {
    matches!(
        name,
        "str"
            | "String"
            | "i8"
            | "i16"
            | "i32"
            | "i64"
            | "i128"
            | "u8"
            | "u16"
            | "u32"
            | "u64"
            | "u128"
            | "f32"
            | "f64"
            | "bool"
            | "char"
            | "usize"
            | "isize"
            | "Vec"
            | "Option"
            | "Result"
            | "Box"
            | "Rc"
            | "Arc"
            | "Cell"
            | "RefCell"
            | "Pin"
            | "HashMap"
            | "HashSet"
            | "BTreeMap"
            | "BTreeSet"
            | "VecDeque"
            | "LinkedList"
            | "BinaryHeap"
            | "Cow"
            | "PhantomData"
            | "Self"
    )
}

// ---------------------------------------------------------------------------
// Signature building
// ---------------------------------------------------------------------------

/// Build a human-readable signature string: `fn foo(a: A, b: B) -> C`.
///
/// Includes `async`, `pub`, and generic parameters.
fn build_fn_signature(node: &Node<'_>, name: &str, source: &[u8]) -> String {
    // Collect leading visibility and qualifiers.
    let mut qualifiers: Vec<&str> = Vec::new();
    let mut c = node.walk();
    for child in node.children(&mut c) {
        match child.kind() {
            "visibility_modifier" => qualifiers.push("pub"),
            "async" => qualifiers.push("async"),
            "unsafe" => qualifiers.push("unsafe"),
            "extern" => qualifiers.push("extern"),
            _ => {}
        }
    }

    let type_params = node
        .child_by_field_name("type_parameters")
        .map(|n| node_text(&n, source))
        .unwrap_or_default();

    let params = node
        .child_by_field_name("parameters")
        .map(|n| node_text(&n, source))
        .unwrap_or_else(|| "()".to_string());

    let return_type = node
        .child_by_field_name("return_type")
        .map(|n| format!(" -> {}", node_text(&n, source)));

    let prefix = if qualifiers.is_empty() {
        String::new()
    } else {
        format!("{} ", qualifiers.join(" "))
    };

    format!(
        "{prefix}fn {name}{type_params}{params}{}",
        return_type.as_deref().unwrap_or("")
    )
}

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

/// Extract a clean type name from a type-position node.
///
/// Handles:
/// - `type_identifier` -> "Foo"
/// - `generic_type`    -> "Foo" (strips generics like `Foo<T>`)
/// - `scoped_type_identifier` -> last segment of `crate::foo::Bar`
fn extract_type_name(node: &Node<'_>, source: &[u8]) -> String {
    match node.kind() {
        "type_identifier" => node_text(node, source),
        "generic_type" => {
            // `Foo<T>` - take just the name, not the type args.
            node.child_by_field_name("type")
                .map(|n| node_text(&n, source))
                .unwrap_or_else(|| node_text(node, source))
        }
        "scoped_type_identifier" => {
            // `crate::foo::Bar` - take the last segment.
            node.child_by_field_name("name")
                .map(|n| node_text(&n, source))
                .unwrap_or_else(|| {
                    let full = node_text(node, source);
                    full.split("::").last().unwrap_or("").to_string()
                })
        }
        _ => {
            // Fallback: use the last `::` segment of the raw text.
            let text = node_text(node, source);
            text.split("::").last().unwrap_or("").to_string()
        }
    }
}

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

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;

    fn parse(source: &str) -> FileParseResult {
        parse_rust_file("test.rs", source, "proj", Utc::now())
    }

    fn uses_type_rels(result: &FileParseResult) -> Vec<&Relationship> {
        result
            .relationships
            .iter()
            .filter(|r| r.rel_type == RelationType::UsesType)
            .collect()
    }

    #[test]
    fn test_no_uses_type_for_builtins() {
        // Primitive and standard-library types should produce no UsesType rels.
        let source = r#"
fn process(x: i32, name: String, flag: bool) -> Vec<u8> {
    Vec::new()
}
"#;
        let result = parse(source);
        let rels = uses_type_rels(&result);
        assert!(
            rels.is_empty(),
            "Expected no UsesType rels for builtins, got: {rels:?}"
        );
    }

    #[test]
    fn test_uses_type_param_annotation() {
        // Custom types in parameter position should emit UsesType.
        let source = r#"
fn handle(req: HttpRequest, db: Database) {}
"#;
        let result = parse(source);
        let rels = uses_type_rels(&result);
        assert_eq!(
            rels.len(),
            2,
            "Expected 2 UsesType rels (HttpRequest, Database), got: {rels:?}"
        );
    }

    #[test]
    fn test_uses_type_return_annotation() {
        // Custom return type should emit a UsesType rel.
        let source = r#"
fn make_controller() -> Controller {
    Controller::new()
}
"#;
        let result = parse(source);
        let rels = uses_type_rels(&result);
        assert_eq!(
            rels.len(),
            1,
            "Expected 1 UsesType rel (Controller), got: {rels:?}"
        );
    }

    #[test]
    fn test_uses_type_reference_param() {
        // `&SomeType` should unwrap the reference and emit UsesType for the inner type.
        let source = r#"
fn render(view: &View) -> Html {}
"#;
        let result = parse(source);
        let type_names: Vec<_> = uses_type_rels(&result)
            .iter()
            .map(|r| r.target_id)
            .collect();
        assert_eq!(
            type_names.len(),
            2,
            "Expected 2 UsesType rels (&View, Html), got: {type_names:?}"
        );
    }

    #[test]
    fn test_uses_type_generic_param() {
        // Types nested inside generics (e.g. `Option<Controller>`) should be extracted.
        let source = r#"
fn find(id: u32) -> Option<Controller> {
    None
}
"#;
        let result = parse(source);
        let rels = uses_type_rels(&result);
        // Option is a builtin and should be skipped; Controller should be extracted.
        assert_eq!(
            rels.len(),
            1,
            "Expected 1 UsesType rel (Controller, not Option), got: {rels:?}"
        );
    }

    #[test]
    fn test_uses_type_confidence_same_file() {
        // When the target type is defined in the same file, confidence should be 1.0.
        let source = r#"
struct Controller {}

fn make() -> Controller {
    Controller {}
}
"#;
        let result = parse(source);
        let rels = uses_type_rels(&result);
        assert_eq!(rels.len(), 1, "Expected 1 UsesType rel, got: {rels:?}");
        assert!(
            (rels[0].confidence - 1.0).abs() < f32::EPSILON,
            "Same-file type should have confidence 1.0, got {}",
            rels[0].confidence
        );
    }

    #[test]
    fn test_uses_type_confidence_imported() {
        // When the target type is imported, confidence should be 0.8.
        let source = r#"
use some_crate::ExternalType;

fn process(val: ExternalType) {}
"#;
        let result = parse(source);
        let rels = uses_type_rels(&result);
        assert_eq!(rels.len(), 1, "Expected 1 UsesType rel, got: {rels:?}");
        assert!(
            (rels[0].confidence - 0.8).abs() < f32::EPSILON,
            "Imported type should have confidence 0.8, got {}",
            rels[0].confidence
        );
    }

    #[test]
    fn test_uses_type_confidence_external() {
        // An unknown (neither defined nor imported) type gets confidence 0.5.
        let source = r#"
fn process(val: UnknownType) -> AnotherUnknown {}
"#;
        let result = parse(source);
        let rels = uses_type_rels(&result);
        assert_eq!(rels.len(), 2, "Expected 2 UsesType rels, got: {rels:?}");
        for rel in &rels {
            assert!(
                (rel.confidence - 0.5).abs() < f32::EPSILON,
                "Unknown type should have confidence 0.5, got {}",
                rel.confidence
            );
        }
    }

    #[test]
    fn test_uses_type_method() {
        // Methods should also emit UsesType for annotated parameter and return types.
        let source = r#"
struct Server {}

impl Server {
    fn handle(&self, req: HttpRequest) -> HttpResponse {
        HttpResponse::ok()
    }
}
"#;
        let result = parse(source);
        let rels = uses_type_rels(&result);
        // `&self` is skipped; HttpRequest and HttpResponse should be extracted.
        assert_eq!(
            rels.len(),
            2,
            "Expected 2 UsesType rels (HttpRequest, HttpResponse), got: {rels:?}"
        );
    }

    #[test]
    fn test_uses_type_struct_fields() {
        // Struct field types should emit UsesType from the struct symbol.
        let source = r#"
struct App {
    db: Database,
    config: AppConfig,
    count: u32,
}
"#;
        let result = parse(source);
        let rels = uses_type_rels(&result);
        // u32 is a builtin - only Database and AppConfig should be extracted.
        assert_eq!(
            rels.len(),
            2,
            "Expected 2 UsesType rels (Database, AppConfig), got: {rels:?}"
        );
    }

    #[test]
    fn test_no_duplicate_uses_type() {
        // The same type referenced multiple times should only produce one UsesType rel.
        let source = r#"
fn process(a: Controller, b: Controller) {}
"#;
        let result = parse(source);
        let rels = uses_type_rels(&result);
        assert_eq!(
            rels.len(),
            1,
            "Duplicate UsesType for same type should be deduplicated, got: {rels:?}"
        );
    }

    fn field_symbols(result: &FileParseResult) -> Vec<&Symbol> {
        result
            .symbols
            .iter()
            .filter(|s| s.symbol_type == SymbolType::Field)
            .collect()
    }

    fn defines_rels(result: &FileParseResult) -> Vec<&Relationship> {
        result
            .relationships
            .iter()
            .filter(|r| r.rel_type == RelationType::Defines)
            .collect()
    }

    fn references_rels(result: &FileParseResult) -> Vec<&Relationship> {
        result
            .relationships
            .iter()
            .filter(|r| r.rel_type == RelationType::References)
            .collect()
    }

    #[test]
    fn test_struct_fields_captured() {
        // Named struct fields become Field symbols scoped under the struct.
        let source = r#"
struct Invoice {
    amount: u32,
    currency: String,
}
"#;
        let result = parse(source);
        let fields = field_symbols(&result);
        let names: Vec<_> = fields.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(names, vec!["amount", "currency"], "fields: {fields:?}");
        let struct_id = result
            .symbols
            .iter()
            .find(|s| s.symbol_type == SymbolType::Class && s.name == "Invoice")
            .map(|s| s.id)
            .unwrap();
        for f in &fields {
            assert_eq!(
                f.parent_symbol_id,
                Some(struct_id),
                "field {} should be parented under the struct",
                f.name
            );
        }
        // Each field has a Defines edge from the struct.
        let defines = defines_rels(&result);
        for f in &fields {
            assert!(
                defines
                    .iter()
                    .any(|r| r.source_id == struct_id && r.target_id == f.id),
                "missing Defines(struct -> field {})",
                f.name
            );
        }
    }

    #[test]
    fn test_tuple_struct_fields_skipped() {
        // Tuple-struct fields have no name and must not be emitted as Field symbols.
        let source = r#"
struct Point(u32, u32);
"#;
        let result = parse(source);
        let fields = field_symbols(&result);
        assert!(fields.is_empty(), "tuple fields should be skipped: {fields:?}");
    }

    #[test]
    fn test_self_field_read_emits_references() {
        // `self.amount` read inside an impl method emits a References edge from
        // the method to the struct's `amount` field.
        let source = r#"
struct Invoice {
    amount: u32,
}

impl Invoice {
    fn total(&self) -> u32 {
        self.amount
    }
}
"#;
        let result = parse(source);
        let amount = result
            .symbols
            .iter()
            .find(|s| s.symbol_type == SymbolType::Field && s.name == "amount")
            .map(|s| s.id)
            .expect("amount field should exist");
        let total = result
            .symbols
            .iter()
            .find(|s| s.name == "Invoice::total")
            .map(|s| s.id)
            .expect("Invoice::total method should exist");
        let refs = references_rels(&result);
        assert!(
            refs.iter()
                .any(|r| r.source_id == total && r.target_id == amount),
            "expected References(Invoice::total -> amount), refs: {refs:?}"
        );
    }

    #[test]
    fn test_self_method_call_not_a_field_reference() {
        // `self.compute()` is a method call, not a field read - it must not
        // produce a References edge to a field.
        let source = r#"
struct Calc {
    factor: u32,
}

impl Calc {
    fn compute(&self) -> u32 {
        self.factor
    }
    fn run(&self) -> u32 {
        self.compute()
    }
}
"#;
        let result = parse(source);
        let refs = references_rels(&result);
        // Only `self.factor` in compute() should produce a References edge.
        // `self.compute()` in run() is a Calls edge, not References.
        assert_eq!(
            refs.len(),
            1,
            "expected exactly 1 References edge (self.factor), got: {refs:?}"
        );
    }
}