sem-core 0.3.22

Entity-level semantic diff engine. Extracts functions, classes, and methods from 20 languages via tree-sitter and diffs at the entity level.
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
mod entity_extractor;
pub mod languages;

use std::cell::RefCell;
use std::collections::HashMap;

use crate::model::entity::SemanticEntity;
use crate::parser::plugin::SemanticParserPlugin;
use languages::{get_all_code_extensions, get_language_config};
use entity_extractor::extract_entities;

pub struct CodeParserPlugin;

// Thread-local parser cache: one Parser per language per thread.
// Avoids creating a new Parser for every file during parallel graph builds.
thread_local! {
    static PARSER_CACHE: RefCell<HashMap<&'static str, tree_sitter::Parser>> = RefCell::new(HashMap::new());
}

impl SemanticParserPlugin for CodeParserPlugin {
    fn id(&self) -> &str {
        "code"
    }

    fn extensions(&self) -> &[&str] {
        get_all_code_extensions()
    }

    fn extract_entities(&self, content: &str, file_path: &str) -> Vec<SemanticEntity> {
        let ext = std::path::Path::new(file_path)
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| format!(".{}", e.to_lowercase()))
            .unwrap_or_default();

        let config = match get_language_config(&ext) {
            Some(c) => c,
            None => {
                // Try shebang detection for extensionless files
                match detect_ext_from_content(content)
                    .and_then(|se| get_language_config(&se))
                {
                    Some(c) => c,
                    None => return Vec::new(),
                }
            }
        };

        let language = match (config.get_language)() {
            Some(lang) => lang,
            None => return Vec::new(),
        };

        PARSER_CACHE.with(|cache| {
            let mut cache = cache.borrow_mut();
            let parser = cache.entry(config.id).or_insert_with(|| {
                let mut p = tree_sitter::Parser::new();
                let _ = p.set_language(&language);
                p
            });

            let tree = match parser.parse(content.as_bytes(), None) {
                Some(t) => t,
                None => return Vec::new(),
            };

            extract_entities(&tree, file_path, config, content)
        })
    }
}

use crate::parser::registry::detect_ext_from_content;

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

    #[test]
    fn test_java_entity_extraction() {
        let code = r#"
package com.example;

import java.util.List;

public class UserService {
    private String name;

    public UserService(String name) {
        this.name = name;
    }

    public List<User> getUsers() {
        return db.findAll();
    }

    public void createUser(User user) {
        db.save(user);
    }
}

interface Repository<T> {
    T findById(String id);
    List<T> findAll();
}

enum Status {
    ACTIVE,
    INACTIVE,
    DELETED
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "UserService.java");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        let types: Vec<&str> = entities.iter().map(|e| e.entity_type.as_str()).collect();
        eprintln!("Java entities: {:?}", names.iter().zip(types.iter()).collect::<Vec<_>>());

        assert!(names.contains(&"UserService"), "Should find class UserService, got: {:?}", names);
        assert!(names.contains(&"Repository"), "Should find interface Repository, got: {:?}", names);
        assert!(names.contains(&"Status"), "Should find enum Status, got: {:?}", names);
    }

    #[test]
    fn test_java_nested_methods() {
        let code = r#"
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "Calculator.java");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!("Java nested: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type, &e.parent_id)).collect::<Vec<_>>());

        assert!(names.contains(&"Calculator"), "Should find Calculator class");
        assert!(names.contains(&"add"), "Should find add method, got: {:?}", names);
        assert!(names.contains(&"subtract"), "Should find subtract method, got: {:?}", names);

        // Methods should have Calculator as parent
        let add = entities.iter().find(|e| e.name == "add").unwrap();
        assert!(add.parent_id.is_some(), "add should have parent_id");
    }

    #[test]
    fn test_c_entity_extraction() {
        let code = r#"
#include <stdio.h>

struct Point {
    int x;
    int y;
};

enum Color {
    RED,
    GREEN,
    BLUE
};

typedef struct {
    char name[50];
    int age;
} Person;

void greet(const char* name) {
    printf("Hello, %s!\n", name);
}

int add(int a, int b) {
    return a + b;
}

int main() {
    greet("world");
    return 0;
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "main.c");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        let types: Vec<&str> = entities.iter().map(|e| e.entity_type.as_str()).collect();
        eprintln!("C entities: {:?}", names.iter().zip(types.iter()).collect::<Vec<_>>());

        assert!(names.contains(&"greet"), "Should find greet function, got: {:?}", names);
        assert!(names.contains(&"add"), "Should find add function, got: {:?}", names);
        assert!(names.contains(&"main"), "Should find main function, got: {:?}", names);
        assert!(names.contains(&"Point"), "Should find Point struct, got: {:?}", names);
        assert!(names.contains(&"Color"), "Should find Color enum, got: {:?}", names);
    }

    #[test]
    fn test_cpp_entity_extraction() {
        let code = "namespace math {\nclass Vector3 {\npublic:\n    float length() const { return 0; }\n};\n}\nvoid greet() {}\n";
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "main.cpp");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"math"), "got: {:?}", names);
        assert!(names.contains(&"Vector3"), "got: {:?}", names);
        assert!(names.contains(&"greet"), "got: {:?}", names);
    }

    #[test]
    fn test_ruby_entity_extraction() {
        let code = "module Auth\n  class User\n    def greet\n      \"hi\"\n    end\n  end\nend\ndef helper(x)\n  x * 2\nend\n";
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "auth.rb");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"Auth"), "got: {:?}", names);
        assert!(names.contains(&"User"), "got: {:?}", names);
        assert!(names.contains(&"helper"), "got: {:?}", names);
    }

    #[test]
    fn test_csharp_entity_extraction() {
        let code = "namespace MyApp {\npublic class User {\n    public string GetName() { return \"\"; }\n}\npublic enum Role { Admin, User }\n}\n";
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "Models.cs");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"MyApp"), "got: {:?}", names);
        assert!(names.contains(&"User"), "got: {:?}", names);
        assert!(names.contains(&"Role"), "got: {:?}", names);
    }

    #[test]
    fn test_swift_entity_extraction() {
        let code = r#"
import Foundation

class UserService {
    var name: String

    init(name: String) {
        self.name = name
    }

    func getUsers() -> [User] {
        return db.findAll()
    }
}

struct Point {
    var x: Double
    var y: Double
}

enum Status {
    case active
    case inactive
    case deleted
}

protocol Repository {
    associatedtype Item
    func findById(id: String) -> Item?
    func findAll() -> [Item]
}

func helper(x: Int) -> Int {
    return x * 2
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "UserService.swift");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!("Swift entities: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());

        assert!(names.contains(&"UserService"), "Should find class UserService, got: {:?}", names);
        assert!(names.contains(&"Point"), "Should find struct Point, got: {:?}", names);
        assert!(names.contains(&"Status"), "Should find enum Status, got: {:?}", names);
        assert!(names.contains(&"Repository"), "Should find protocol Repository, got: {:?}", names);
        assert!(names.contains(&"helper"), "Should find function helper, got: {:?}", names);
    }

    #[test]
    fn test_elixir_entity_extraction() {
        let code = r#"
defmodule MyApp.Accounts do
  def create_user(attrs) do
    %User{}
    |> User.changeset(attrs)
    |> Repo.insert()
  end

  defp validate(attrs) do
    # private helper
    :ok
  end

  defmacro is_admin(user) do
    quote do
      unquote(user).role == :admin
    end
  end

  defguard is_positive(x) when is_integer(x) and x > 0
end

defprotocol Printable do
  def to_string(data)
end

defimpl Printable, for: Integer do
  def to_string(i), do: Integer.to_string(i)
end
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "accounts.ex");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        let types: Vec<&str> = entities.iter().map(|e| e.entity_type.as_str()).collect();
        eprintln!("Elixir entities: {:?}", names.iter().zip(types.iter()).collect::<Vec<_>>());

        assert!(names.contains(&"MyApp.Accounts"), "Should find module, got: {:?}", names);
        assert!(names.contains(&"create_user"), "Should find def, got: {:?}", names);
        assert!(names.contains(&"validate"), "Should find defp, got: {:?}", names);
        assert!(names.contains(&"is_admin"), "Should find defmacro, got: {:?}", names);
        assert!(names.contains(&"Printable"), "Should find defprotocol, got: {:?}", names);

        // Verify nesting: create_user should have MyApp.Accounts as parent
        let create_user = entities.iter().find(|e| e.name == "create_user").unwrap();
        assert!(create_user.parent_id.is_some(), "create_user should be nested under module");
    }

    #[test]
    fn test_bash_entity_extraction() {
        let code = r#"#!/bin/bash

greet() {
    echo "Hello, $1!"
}

function deploy {
    echo "deploying..."
}

# not a function
echo "main script"
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "deploy.sh");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        let types: Vec<&str> = entities.iter().map(|e| e.entity_type.as_str()).collect();
        eprintln!("Bash entities: {:?}", names.iter().zip(types.iter()).collect::<Vec<_>>());

        assert!(names.contains(&"greet"), "Should find greet(), got: {:?}", names);
        assert!(names.contains(&"deploy"), "Should find function deploy, got: {:?}", names);
        assert_eq!(entities.len(), 2, "Should only find functions, got: {:?}", names);
    }

    #[test]
    fn test_typescript_entity_extraction() {
        // Existing language should still work
        let code = r#"
export function hello(): string {
    return "hello";
}

export class Greeter {
    greet(name: string): string {
        return `Hello, ${name}!`;
    }
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "test.ts");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"hello"), "Should find hello function");
        assert!(names.contains(&"Greeter"), "Should find Greeter class");
    }

    #[test]
    fn test_module_typescript_entity_extraction() {
        let code = r#"
export function hello(): string {
    return "hello";
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "test.mts");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();

        assert!(names.contains(&"hello"), "Should find hello function");
    }

    #[test]
    fn test_commonjs_typescript_entity_extraction() {
        let code = r#"
export class Greeter {
    greet(name: string): string {
        return `Hello, ${name}!`;
    }
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "test.cts");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();

        assert!(names.contains(&"Greeter"), "Should find Greeter class");
        assert!(names.contains(&"greet"), "Should find greet method");
    }

    #[test]
    fn test_typescript_generator_function_entity_extraction() {
        let code = r#"
export async function* streamUsers(): AsyncGenerator<string> {
    yield "alice";
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "stream.ts");
        let stream = entities.iter().find(|e| e.name == "streamUsers");

        assert!(stream.is_some(), "Should find generator function, got: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());
        assert_eq!(stream.unwrap().entity_type, "function");
    }

    #[test]
    fn test_javascript_generator_function_entity_extraction() {
        let code = r#"
export function* ids() {
    yield 1;
    yield 2;
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "ids.js");
        let ids = entities.iter().find(|e| e.name == "ids");

        assert!(ids.is_some(), "Should find generator function, got: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());
        assert_eq!(ids.unwrap().entity_type, "function");
    }

    #[test]
    fn test_nested_functions_typescript() {
        let code = r#"
function outer() {
    function inner() {
        return 42;
    }
    return inner();
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "nested.ts");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!("Nested TS: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type, &e.parent_id)).collect::<Vec<_>>());

        assert!(names.contains(&"outer"), "Should find outer, got: {:?}", names);
        assert!(names.contains(&"inner"), "Should find inner, got: {:?}", names);

        let inner = entities.iter().find(|e| e.name == "inner").unwrap();
        assert!(inner.parent_id.is_some(), "inner should have parent_id");
    }

    #[test]
    fn test_nested_functions_python() {
        let code = "def outer():\n    def inner():\n        return 42\n    return inner()\n";
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "nested.py");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();

        assert!(names.contains(&"outer"), "got: {:?}", names);
        assert!(names.contains(&"inner"), "got: {:?}", names);

        let inner = entities.iter().find(|e| e.name == "inner").unwrap();
        assert!(inner.parent_id.is_some(), "inner should have parent_id");
    }

    #[test]
    fn test_nested_functions_rust() {
        let code = "fn outer() {\n    fn inner() -> i32 {\n        42\n    }\n    inner();\n}\n";
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "nested.rs");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();

        assert!(names.contains(&"outer"), "got: {:?}", names);
        assert!(names.contains(&"inner"), "got: {:?}", names);

        let inner = entities.iter().find(|e| e.name == "inner").unwrap();
        assert!(inner.parent_id.is_some(), "inner should have parent_id");
    }

    #[test]
    fn test_rust_impl_blocks_unique_names() {
        let code = r#"
trait Greeting {
    fn greet(&self) -> String;
}

struct Person;
struct Robot;
struct Cat;

impl Greeting for Person {
    fn greet(&self) -> String { "Hello".to_string() }
}

impl Greeting for Robot {
    fn greet(&self) -> String { "Beep".to_string() }
}

impl Greeting for Cat {
    fn greet(&self) -> String { "Meow".to_string() }
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "impls.rs");
        let impl_entities: Vec<&_> = entities.iter()
            .filter(|e| e.entity_type == "impl")
            .collect();
        let names: Vec<&str> = impl_entities.iter().map(|e| e.name.as_str()).collect();

        assert_eq!(impl_entities.len(), 3, "Should find 3 impl blocks, got: {:?}", names);
        assert!(names.contains(&"Greeting for Person"), "got: {:?}", names);
        assert!(names.contains(&"Greeting for Robot"), "got: {:?}", names);
        assert!(names.contains(&"Greeting for Cat"), "got: {:?}", names);
    }

    #[test]
    fn test_nested_functions_go() {
        // Go doesn't have named nested functions, but has nested type/var declarations
        let code = "package main\n\nfunc outer() {\n    var x int = 42\n    _ = x\n}\n";
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "nested.go");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();

        assert!(names.contains(&"outer"), "got: {:?}", names);
    }

    #[test]
    fn test_renamed_function_same_structural_hash() {
        let code_a = "def get_card():\n    return db.query('cards')\n";
        let code_b = "def get_card_1():\n    return db.query('cards')\n";

        let plugin = CodeParserPlugin;
        let entities_a = plugin.extract_entities(code_a, "a.py");
        let entities_b = plugin.extract_entities(code_b, "b.py");

        assert_eq!(entities_a.len(), 1, "Should find one entity in a");
        assert_eq!(entities_b.len(), 1, "Should find one entity in b");
        assert_eq!(entities_a[0].name, "get_card");
        assert_eq!(entities_b[0].name, "get_card_1");

        // Structural hash should match since only the name differs
        assert_eq!(
            entities_a[0].structural_hash, entities_b[0].structural_hash,
            "Renamed function with identical body should have same structural_hash"
        );

        // Content hash should differ (it includes the name)
        assert_ne!(
            entities_a[0].content_hash, entities_b[0].content_hash,
            "Content hash should differ since raw content includes the name"
        );
    }

    #[test]
    fn test_hcl_entity_extraction() {
        let code = r#"
region = "eu-west-1"

variable "image_id" {
  type = string
}

resource "aws_instance" "web" {
  ami = var.image_id

  lifecycle {
    create_before_destroy = true
  }
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "main.tf");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        let types: Vec<&str> = entities.iter().map(|e| e.entity_type.as_str()).collect();
        eprintln!("HCL entities: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type, &e.parent_id)).collect::<Vec<_>>());

        assert!(names.contains(&"region"), "Should find top-level attribute, got: {:?}", names);
        assert!(names.contains(&"variable.image_id"), "Should find variable block, got: {:?}", names);
        assert!(names.contains(&"resource.aws_instance.web"), "Should find resource block, got: {:?}", names);
        assert!(
            names.contains(&"resource.aws_instance.web.lifecycle"),
            "Should find nested lifecycle block with qualified name, got: {:?}",
            names
        );
        assert!(!names.contains(&"ami"), "Should skip nested attributes inside blocks, got: {:?}", names);
        assert!(
            !names.contains(&"create_before_destroy"),
            "Should skip nested attributes inside nested blocks, got: {:?}",
            names
        );

        let lifecycle = entities
            .iter()
            .find(|e| e.name == "resource.aws_instance.web.lifecycle")
            .unwrap();
        assert!(lifecycle.parent_id.is_some(), "lifecycle should be nested under resource");
        assert!(types.contains(&"attribute"), "Should preserve attribute entity type for top-level attributes");
    }

    #[test]
    fn test_kotlin_entity_extraction() {
        let code = r#"
class UserService {
    val name: String = ""

    fun greet(): String {
        return "Hello, $name"
    }

    companion object {
        fun create(): UserService = UserService()
    }
}

interface Repository {
    fun findById(id: Int): Any?
}

object AppConfig {
    val version = "1.0"
}

fun topLevel(x: Int): Int = x * 2
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "App.kt");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!("Kotlin entities: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());
        assert!(names.contains(&"UserService"), "got: {:?}", names);
        assert!(names.contains(&"greet"), "got: {:?}", names);
        assert!(names.contains(&"Repository"), "got: {:?}", names);
        assert!(names.contains(&"findById"), "got: {:?}", names);
        assert!(names.contains(&"AppConfig"), "got: {:?}", names);
        assert!(names.contains(&"topLevel"), "got: {:?}", names);
    }

    #[test]
    fn test_xml_entity_extraction() {
        let code = r#"<?xml version="1.0" encoding="UTF-8"?>
<project>
    <groupId>com.example</groupId>
    <artifactId>my-app</artifactId>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven</groupId>
            </plugin>
        </plugins>
    </build>
</project>
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "pom.xml");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!("XML entities: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());
        assert!(names.contains(&"project"), "got: {:?}", names);
        assert!(names.contains(&"dependencies"), "got: {:?}", names);
        assert!(names.contains(&"build"), "got: {:?}", names);
    }

    #[test]
    fn test_arrow_callback_scope_boundary_typescript() {
        // Arrow function callbacks: locals are suppressed, but inner
        // class/function declarations are still extracted. Nested callbacks
        // also suppress their locals.
        let code = r#"
const activeQueues = [
  { queue: queues.fooQueue, processor: foo.process },
];

activeQueues.forEach((handler: any) => {
  const queue = handler.queue;
  let retries = 0;

  class QueueHandler {
    handle() { return queue; }
  }

  function createHandler() {
    return new QueueHandler();
  }

  queue.process((job) => {
    const orderId = job.data.orderId;
    return orderId;
  });
});

function handleFailure(job: any, err: any) {
  console.error('failed', err);
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "process.ts");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        let top_level: Vec<&str> = entities
            .iter()
            .filter(|e| e.parent_id.is_none())
            .map(|e| e.name.as_str())
            .collect();

        // Top-level entities preserved
        assert!(top_level.contains(&"activeQueues"), "got: {:?}", top_level);
        assert!(top_level.contains(&"handleFailure"), "got: {:?}", top_level);

        // Declarations inside callback extracted
        assert!(names.contains(&"QueueHandler"), "got: {:?}", names);
        assert!(names.contains(&"handle"), "got: {:?}", names);
        assert!(names.contains(&"createHandler"), "got: {:?}", names);

        // Locals inside callbacks suppressed
        assert!(!names.contains(&"queue"), "got: {:?}", names);
        assert!(!names.contains(&"retries"), "got: {:?}", names);
        assert!(!names.contains(&"orderId"), "got: {:?}", names);
    }

    #[test]
    fn test_top_level_iife_wrapper_still_extracts_typescript_entities() {
        let code = r#"
function factory() {
  class Foo {
    method(): number {
      return 1;
    }
  }

  function bar(): Foo {
    return new Foo();
  }
}

factory();
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "wrapped.ts");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        assert!(
            names.contains(&"factory"),
            "Should find top-level wrapper function, got: {:?}",
            names
        );
        assert!(
            names.contains(&"Foo"),
            "Should find class inside top-level wrapper, got: {:?}",
            names
        );
        assert!(
            names.contains(&"bar"),
            "Should find function inside top-level wrapper, got: {:?}",
            names
        );
    }

    #[test]
    fn test_top_level_iife_still_extracts_typescript_entities() {
        let code = r#"
(() => {
  class Foo {
    method(): number {
      return 1;
    }
  }

  function bar(): Foo {
    return new Foo();
  }
})();
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "iife.ts");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        assert!(
            names.contains(&"Foo"),
            "Should find class inside top-level IIFE, got: {:?}",
            names
        );
        assert!(
            names.contains(&"bar"),
            "Should find function inside top-level IIFE, got: {:?}",
            names
        );
    }

    #[test]
    fn test_function_locals_not_extracted_as_nested_entities_typescript() {
        let code = r#"
export default function foo() {
  const x = 1;
  return x;
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "default-export.ts");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        assert!(
            names.contains(&"foo"),
            "Should find exported function, got: {:?}",
            names
        );
        assert!(
            !names.contains(&"x"),
            "Local inside function should not be extracted as an entity, got: {:?}",
            names
        );
    }

    #[test]
    fn test_function_expression_scope_boundary_typescript() {
        // Function expressions: assigned to variables, or used as callback
        // arguments. Locals are suppressed in all cases.
        let code = r#"
const foo = function namedExpr(x: number) {
  const inner = x + 1;
  return inner;
};

const bar = function(y: number) {
  const local = y * 2;
  return local;
};

const items = [1, 2, 3];

items.forEach(function process(item) {
  const doubled = item * 2;
  console.log(doubled);
});
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "funexpr.ts");
        let top_level: Vec<&str> = entities
            .iter()
            .filter(|e| e.parent_id.is_none())
            .map(|e| e.name.as_str())
            .collect();
        let find = |name: &str| entities.iter().find(|e| e.name == name).unwrap();
        let all_names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();

        // Top-level declarations preserved, and const-assigned function
        // expressions are promoted from variable to function.
        assert!(top_level.contains(&"foo"), "got: {:?}", top_level);
        assert!(top_level.contains(&"bar"), "got: {:?}", top_level);
        assert!(top_level.contains(&"items"), "got: {:?}", top_level);
        assert_eq!(find("foo").entity_type, "function");
        assert_eq!(find("bar").entity_type, "function");
        assert_eq!(find("items").entity_type, "variable");

        // Locals inside function expressions suppressed
        assert!(!all_names.contains(&"inner"), "got: {:?}", all_names);
        assert!(!all_names.contains(&"local"), "got: {:?}", all_names);
        assert!(!all_names.contains(&"doubled"), "got: {:?}", all_names);

        // Named function expression used as callback argument not extracted
        assert!(!top_level.contains(&"process"), "got: {:?}", top_level);
    }

    #[test]
    fn test_variable_assigned_arrow_extracts_inner_entities() {
        // Arrow function assigned to a variable: inner class/function
        // declarations should be extracted, locals should be suppressed.
        let code = r#"
const handler = () => {
  class Inner {
    run() { return 1; }
  }

  function make() {
    return new Inner();
  }

  const local = 42;
};
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "assigned.ts");
        let handler = entities.iter().find(|e| e.name == "handler").unwrap();
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();

        assert_eq!(handler.entity_type, "function");
        assert!(names.contains(&"handler"), "got: {:?}", names);
        assert!(names.contains(&"Inner"), "got: {:?}", names);
        assert!(names.contains(&"run"), "got: {:?}", names);
        assert!(names.contains(&"make"), "got: {:?}", names);
        assert!(!names.contains(&"local"), "got: {:?}", names);
    }

    #[test]
    fn test_variable_assigned_function_expression_extracts_inner_entities() {
        // Function expression assigned to a variable: same behavior.
        let code = r#"
const handler = function() {
  class Inner {}
  function make() { return new Inner(); }
  const local = 42;
};
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "funexpr-inner.ts");
        let handler = entities.iter().find(|e| e.name == "handler").unwrap();
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();

        assert_eq!(handler.entity_type, "function");
        assert!(names.contains(&"handler"), "got: {:?}", names);
        assert!(names.contains(&"Inner"), "got: {:?}", names);
        assert!(names.contains(&"make"), "got: {:?}", names);
        assert!(!names.contains(&"local"), "got: {:?}", names);
    }

    #[test]
    fn test_let_assigned_arrow_stays_variable_typescript() {
        let code = r#"
let handler = () => {
  return 42;
};
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "let-assigned.ts");
        let handler = entities.iter().find(|e| e.name == "handler").unwrap();

        assert_eq!(handler.entity_type, "variable");
    }

    #[test]
    fn test_const_assigned_arrow_promoted_to_function_javascript() {
        let code = r#"
const handler = () => {
  return 42;
};
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "handler.js");
        let handler = entities.iter().find(|e| e.name == "handler").unwrap();

        assert_eq!(handler.entity_type, "function");
    }

    #[test]
    fn test_go_var_declaration() {
        let code = r#"package featuremgmt

type FeatureFlag struct {
	Name        string
	Description string
	Stage       string
}

var standardFeatureFlags = []FeatureFlag{
	{
		Name:        "panelTitleSearch",
		Description: "Search for dashboards using panel title",
		Stage:       "PublicPreview",
	},
}

func GetFlags() []FeatureFlag {
	return standardFeatureFlags
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "flags.go");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        let types: Vec<&str> = entities.iter().map(|e| e.entity_type.as_str()).collect();
        eprintln!("Go entities: {:?}", names.iter().zip(types.iter()).collect::<Vec<_>>());

        assert!(names.contains(&"FeatureFlag"), "Should find type FeatureFlag, got: {:?}", names);
        assert!(names.contains(&"standardFeatureFlags"), "Should find var standardFeatureFlags, got: {:?}", names);
        assert!(names.contains(&"GetFlags"), "Should find func GetFlags, got: {:?}", names);
    }

    #[test]
    fn test_go_grouped_var_declaration() {
        let code = r#"package test

var (
	simple = 42
	flags = []string{"a", "b"}
)

const (
	x = 1
	y = 2
)

func main() {}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "test.go");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        let types: Vec<&str> = entities.iter().map(|e| e.entity_type.as_str()).collect();
        eprintln!("Go grouped entities: {:?}", names.iter().zip(types.iter()).collect::<Vec<_>>());

        assert!(names.contains(&"flags") || names.contains(&"simple"), "Should find grouped var, got: {:?}", names);
        assert!(names.contains(&"x"), "Should find grouped const x, got: {:?}", names);
        assert!(names.contains(&"main"), "Should find func main, got: {:?}", names);
    }

    #[test]
    fn test_dart_entity_extraction() {
        let code = r#"
import 'dart:math';

class Calculator {
  final String name;

  Calculator(this.name);

  Calculator.withDefault() : name = 'default';

  factory Calculator.create(String name) {
    return Calculator(name);
  }

  int add(int a, int b) {
    return a + b;
  }

  int get doubleAdd => add(1, 1) * 2;

  set label(String value) {
    // no-op
  }

  int operator +(Calculator other) {
    return 0;
  }
}

mixin Loggable {
  void log(String message) {
    print(message);
  }
}

extension StringExt on String {
  bool get isBlank => trim().isEmpty;
}

enum Status {
  active,
  inactive;

  String display() => name.toUpperCase();
}

typedef Callback = void Function(int);

int add(int a, int b) {
  return a + b;
}

extension type Wrapper(int value) implements int {}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "calculator.dart");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!(
            "Dart entities: {:?}",
            entities
                .iter()
                .map(|e| (&e.name, &e.entity_type, &e.parent_id))
                .collect::<Vec<_>>()
        );

        // Top-level declarations
        assert!(names.contains(&"Calculator"), "Should find class, got: {:?}", names);
        assert!(names.contains(&"Loggable"), "Should find mixin, got: {:?}", names);
        assert!(names.contains(&"StringExt"), "Should find extension, got: {:?}", names);
        assert!(names.contains(&"Status"), "Should find enum, got: {:?}", names);
        assert!(names.contains(&"Callback"), "Should find typedef, got: {:?}", names);
        assert!(names.contains(&"add"), "Should find top-level function, got: {:?}", names);
        assert!(names.contains(&"Wrapper"), "Should find extension type, got: {:?}", names);

        // Class members with correct types
        let add_method = entities.iter().find(|e| e.name == "add" && e.parent_id.is_some());
        assert!(add_method.is_some(), "Should find add method inside Calculator");
        assert_eq!(add_method.unwrap().entity_type, "method");

        // Named constructor gets distinct name from unnamed constructor
        let unnamed_ctor = entities.iter().find(|e| e.name == "Calculator" && e.entity_type == "constructor");
        assert!(unnamed_ctor.is_some(), "Should find unnamed constructor");
        let named_ctor = entities.iter().find(|e| e.name == "Calculator.withDefault");
        assert!(named_ctor.is_some(), "Should find named constructor Calculator.withDefault, got: {:?}", names);
        assert_eq!(named_ctor.unwrap().entity_type, "constructor");
        assert_ne!(unnamed_ctor.unwrap().id, named_ctor.unwrap().id, "Named and unnamed constructors must have different entity IDs");

        // Factory constructor
        let factory_ctor = entities.iter().find(|e| e.name == "Calculator.create");
        assert!(factory_ctor.is_some(), "Should find factory constructor Calculator.create, got: {:?}", names);
        assert_eq!(factory_ctor.unwrap().entity_type, "constructor");

        // Getter, setter, operator
        let getter = entities.iter().find(|e| e.name == "doubleAdd");
        assert!(getter.is_some(), "Should find getter doubleAdd");
        assert_eq!(getter.unwrap().entity_type, "getter");

        let setter = entities.iter().find(|e| e.name == "label");
        assert!(setter.is_some(), "Should find setter label");
        assert_eq!(setter.unwrap().entity_type, "setter");

        let operator = entities.iter().find(|e| e.name == "operator +");
        assert!(operator.is_some(), "Should find operator +");
        assert_eq!(operator.unwrap().entity_type, "method");

        // Mixin members have parent
        let log_method = entities.iter().find(|e| e.name == "log");
        assert!(log_method.is_some(), "Should find log in Loggable");
        assert!(log_method.unwrap().parent_id.is_some(), "log should have parent_id");

        // Entity type mapping
        let callback = entities.iter().find(|e| e.name == "Callback").unwrap();
        assert_eq!(callback.entity_type, "type", "typedef should map to 'type'");

        let loggable = entities.iter().find(|e| e.name == "Loggable").unwrap();
        assert_eq!(loggable.entity_type, "mixin");

        let ext = entities.iter().find(|e| e.name == "StringExt").unwrap();
        assert_eq!(ext.entity_type, "extension");

        let wrapper = entities.iter().find(|e| e.name == "Wrapper").unwrap();
        assert_eq!(wrapper.entity_type, "extension");
    }

    #[test]
    fn test_dart_top_level_function_includes_body() {
        let code = r#"
int add(int a, int b) {
  return a + b;
}

String greet(String name) => 'Hello, $name!';
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "funcs.dart");
        eprintln!(
            "Dart top-level: {:?}",
            entities
                .iter()
                .map(|e| (&e.name, &e.entity_type, &e.content))
                .collect::<Vec<_>>()
        );

        let add_fn = entities.iter().find(|e| e.name == "add").unwrap();
        assert!(
            add_fn.content.contains("return a + b"),
            "Top-level function content should include the body, got: {:?}",
            add_fn.content
        );

        let greet_fn = entities.iter().find(|e| e.name == "greet").unwrap();
        assert!(
            greet_fn.content.contains("Hello"),
            "Expression body should be included, got: {:?}",
            greet_fn.content
        );

        // Body changes should produce different content_hash
        let code_v2 = r#"
int add(int a, int b) {
  return a * b;
}

String greet(String name) => 'Hello, $name!';
"#;
        let entities_v2 = plugin.extract_entities(code_v2, "funcs.dart");
        let add_v2 = entities_v2.iter().find(|e| e.name == "add").unwrap();
        assert_ne!(
            add_fn.content_hash, add_v2.content_hash,
            "Body change should produce different content_hash"
        );

        // Unchanged function should keep the same hash
        let greet_v2 = entities_v2.iter().find(|e| e.name == "greet").unwrap();
        assert_eq!(
            greet_fn.content_hash, greet_v2.content_hash,
            "Unchanged function should keep the same content_hash"
        );
    }

    #[test]
    fn test_dart_renamed_named_constructor_same_structural_hash() {
        let code_a = r#"
class Foo {
  Foo.fromJson(Map<String, dynamic> json) {
    print(json);
  }
}
"#;
        let code_b = r#"
class Foo {
  Foo.fromMap(Map<String, dynamic> json) {
    print(json);
  }
}
"#;
        let plugin = CodeParserPlugin;
        let entities_a = plugin.extract_entities(code_a, "a.dart");
        let entities_b = plugin.extract_entities(code_b, "b.dart");

        let ctor_a = entities_a.iter().find(|e| e.name == "Foo.fromJson").unwrap();
        let ctor_b = entities_b.iter().find(|e| e.name == "Foo.fromMap").unwrap();

        assert_eq!(
            ctor_a.structural_hash, ctor_b.structural_hash,
            "Renamed named constructor with identical body should have same structural_hash"
        );
        assert_ne!(
            ctor_a.content_hash, ctor_b.content_hash,
            "Content hash should differ since raw content includes the name"
        );
    }

    #[test]
    fn test_dart_top_level_getter_setter() {
        let code = r#"
int _value = 0;

int get currentValue {
  return _value;
}

set currentValue(int v) {
  _value = v;
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "accessors.dart");
        eprintln!(
            "Dart top-level accessors: {:?}",
            entities
                .iter()
                .map(|e| (&e.name, &e.entity_type, &e.content))
                .collect::<Vec<_>>()
        );

        let getter = entities.iter().find(|e| e.name == "currentValue" && e.entity_type == "getter");
        assert!(getter.is_some(), "Should find top-level getter, got: {:?}",
            entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());
        assert!(
            getter.unwrap().content.contains("return _value"),
            "Top-level getter content should include the body"
        );
        assert!(getter.unwrap().parent_id.is_none(), "Top-level getter should have no parent");

        // tree-sitter-dart 0.1.0 parses top-level setters as function_signature
        // (treating `set` as a type_identifier). setter_signature is only
        // produced inside class_member → method_signature.
        let setter = entities.iter().find(|e| e.name == "currentValue" && e.entity_type == "function");
        assert!(setter.is_some(), "Should find top-level setter as function, got: {:?}",
            entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());
        assert!(
            setter.unwrap().content.contains("_value = v"),
            "Top-level setter content should include the body"
        );
    }

    #[test]
    fn test_dart_field_entity_type() {
        let code = r#"
class Config {
  final String name;
  static const int maxRetries = 3;
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "config.dart");
        eprintln!(
            "Dart fields: {:?}",
            entities
                .iter()
                .map(|e| (&e.name, &e.entity_type, &e.parent_id))
                .collect::<Vec<_>>()
        );

        let name_field = entities.iter().find(|e| e.name == "name" && e.parent_id.is_some());
        assert!(name_field.is_some(), "Should find field 'name', got: {:?}",
            entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());
        assert_eq!(name_field.unwrap().entity_type, "field");

        let max_retries = entities.iter().find(|e| e.name == "maxRetries");
        assert!(max_retries.is_some(), "Should find field 'maxRetries', got: {:?}",
            entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());
        assert_eq!(max_retries.unwrap().entity_type, "field");
    }

    #[test]
    fn test_dart_identifier_list_fields() {
        // identifier_list produces bare identifier children (no "name" field),
        // unlike initialized_identifier_list which wraps each in an
        // initialized_identifier node with a "name" field.
        let code = r#"
abstract class Shape {
  abstract double x, y;
  abstract String label;
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "shape.dart");
        eprintln!(
            "Dart identifier_list fields: {:?}",
            entities
                .iter()
                .map(|e| (&e.name, &e.entity_type, &e.parent_id))
                .collect::<Vec<_>>()
        );

        let x_field = entities.iter().find(|e| e.name == "x");
        assert!(x_field.is_some(), "Should find field 'x' from identifier_list, got: {:?}",
            entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());
        assert_eq!(x_field.unwrap().entity_type, "field");
        assert!(x_field.unwrap().parent_id.is_some(), "field 'x' should be nested under Shape");

        let label_field = entities.iter().find(|e| e.name == "label");
        assert!(label_field.is_some(), "Should find field 'label' from single-element identifier_list, got: {:?}",
            entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());
        assert_eq!(label_field.unwrap().entity_type, "field");
    }

    #[test]
    fn test_ocaml_entity_extraction() {
        let code = r#"
type color = Red | Green | Blue

type point = {
  x : float;
  y : float;
}

exception Not_found of string

let greet name =
  Printf.printf "Hello, %s!\n" name

let add a b = a + b

let version = "1.0"

let color_to_string = function
  | Red -> "red"
  | Blue -> "blue"

let inc = fun x -> x + 1

module MyModule = struct
  let helper x = x * 2
end

module type Printable = sig
  val to_string : 'a -> string
end

external caml_input : in_channel -> bytes -> int -> int -> int = "caml_input"

class point_class x_init = object
  val mutable x = x_init
  method get_x = x
end

class type measurable = object
  method measure : float
end
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "example.ml");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!("OCaml entities: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());

        let find = |name: &str| entities.iter().find(|e| e.name == name)
            .unwrap_or_else(|| panic!("Should find {}, got: {:?}", name, names));

        assert_eq!(find("color").entity_type, "type");
        assert_eq!(find("point").entity_type, "type");
        assert_eq!(find("Not_found").entity_type, "exception");
        assert_eq!(find("greet").entity_type, "function");
        assert_eq!(find("add").entity_type, "function");
        assert_eq!(find("version").entity_type, "value");
        assert_eq!(find("color_to_string").entity_type, "function");
        assert_eq!(find("inc").entity_type, "function");
        assert_eq!(find("MyModule").entity_type, "module");
        assert_eq!(find("Printable").entity_type, "module_type");
        assert_eq!(find("caml_input").entity_type, "external");
        assert_eq!(find("point_class").entity_type, "class");
        assert_eq!(find("measurable").entity_type, "class_type");
    }

    #[test]
    fn test_ocaml_nested_module_entities() {
        let code = r#"
module Outer = struct
  let x = 42

  module Inner = struct
    let y = 0
  end
end
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "nested.ml");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!("OCaml nested: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type, &e.parent_id)).collect::<Vec<_>>());

        let find = |name: &str| entities.iter().find(|e| e.name == name)
            .unwrap_or_else(|| panic!("Should find {}, got: {:?}", name, names));

        let outer = find("Outer");
        let x = find("x");
        let inner = find("Inner");
        let y = find("y");

        assert_eq!(outer.entity_type, "module");
        assert_eq!(x.entity_type, "value");
        assert_eq!(inner.entity_type, "module");
        assert_eq!(y.entity_type, "value");

        assert!(x.parent_id.as_ref().is_some_and(|p| p == &outer.id), "x should be nested under Outer");
        assert!(inner.parent_id.as_ref().is_some_and(|p| p == &outer.id), "Inner should be nested under Outer");
        assert!(y.parent_id.as_ref().is_some_and(|p| p == &inner.id), "y should be nested under Inner");
    }

    #[test]
    fn test_ocaml_interface_entity_extraction() {
        let code = r#"
type t

val create : string -> t
val to_string : t -> string

exception Invalid_input of string

module type Serializable = sig
  val serialize : t -> string
end
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "example.mli");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!("OCaml interface entities: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());

        let find = |name: &str| entities.iter().find(|e| e.name == name)
            .unwrap_or_else(|| panic!("Should find {}, got: {:?}", name, names));

        assert_eq!(find("t").entity_type, "type");
        assert_eq!(find("create").entity_type, "val");
        assert_eq!(find("to_string").entity_type, "val");
        assert_eq!(find("Invalid_input").entity_type, "exception");
        assert_eq!(find("Serializable").entity_type, "module_type");
    }

    #[test]
    fn test_ocaml_mutual_recursion_let() {
        let code = r#"
let rec even n = (n = 0) || odd (n - 1)
and odd n = (n <> 0) && even (n - 1)

let rec ping x = pong (x - 1)
and pong x = if x <= 0 then 0 else ping (x - 1)
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "mutual.ml");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!("OCaml mutual let: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());

        let find = |name: &str| entities.iter().find(|e| e.name == name)
            .unwrap_or_else(|| panic!("Should find {}, got: {:?}", name, names));

        assert_eq!(find("even").entity_type, "function");
        assert_eq!(find("odd").entity_type, "function");
        assert_eq!(find("ping").entity_type, "function");
        assert_eq!(find("pong").entity_type, "function");
    }

    #[test]
    fn test_ocaml_mutual_recursion_module() {
        let code = r#"
module rec A : sig val x : int end = struct
  let x = B.y + 1
end
and B : sig val y : int end = struct
  let y = 0
end
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "mutual_mod.ml");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!("OCaml mutual module: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type, &e.parent_id)).collect::<Vec<_>>());

        let find = |name: &str| entities.iter().find(|e| e.name == name)
            .unwrap_or_else(|| panic!("Should find {}, got: {:?}", name, names));

        let a = find("A");
        let b = find("B");
        assert_eq!(a.entity_type, "module");
        assert_eq!(b.entity_type, "module");

        let x = find("x");
        let y = find("y");
        assert!(x.parent_id.as_ref().is_some_and(|p| p == &a.id), "x should be nested under A");
        assert!(y.parent_id.as_ref().is_some_and(|p| p == &b.id), "y should be nested under B");
    }

    #[test]
    fn test_ocaml_destructured_let() {
        let code = r#"
let (a, b) = (1, 2)

let { x; y } = point

let simple = 42
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "destruct.ml");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!("OCaml destructured: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());

        let find = |name: &str| entities.iter().find(|e| e.name == name)
            .unwrap_or_else(|| panic!("Should find {}, got: {:?}", name, names));

        assert_eq!(find("a").entity_type, "value");
        assert_eq!(find("b").entity_type, "value");
        assert_eq!(find("x").entity_type, "value");
        assert_eq!(find("y").entity_type, "value");
        assert_eq!(find("simple").entity_type, "value");
    }

    #[test]
    fn test_ocaml_mutual_recursion_class() {
        let code = r#"
class foo = object
  method x = 1
end
and bar = object
  method y = 2
end
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "classes.ml");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!("OCaml mutual class: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());

        let find = |name: &str| entities.iter().find(|e| e.name == name)
            .unwrap_or_else(|| panic!("Should find {}, got: {:?}", name, names));

        assert_eq!(find("foo").entity_type, "class");
        assert_eq!(find("bar").entity_type, "class");
    }

    #[test]
    fn test_perl_entity_extraction() {
        let code = r#"package Foo::Bar;

use strict;
use warnings;

sub hello {
    my ($self, $name) = @_;
    print "Hello, $name!\n";
}

sub _private_helper {
    return 42;
}

1;
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "Foo/Bar.pm");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();

        assert!(names.contains(&"Foo::Bar"), "got: {:?}", names);
        assert!(names.contains(&"hello"), "got: {:?}", names);
        assert!(names.contains(&"_private_helper"), "got: {:?}", names);

        let find = |name: &str| entities.iter().find(|e| e.name == name)
            .unwrap_or_else(|| panic!("Should find {}, got: {:?}", name, names));

        assert_eq!(find("Foo::Bar").entity_type, "package");
        assert_eq!(find("hello").entity_type, "function");
        assert_eq!(find("_private_helper").entity_type, "function");
    }

    #[test]
    fn test_fortran_entity_extraction() {
        let code = r#"module math_utils
  implicit none
contains
  function add(a, b) result(c)
    integer, intent(in) :: a, b
    integer :: c
    c = a + b
  end function add

  subroutine greet()
    print *, "hello"
  end subroutine greet
end module math_utils

program main
  implicit none
  print *, "hello"
end program main
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "test.f90");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();

        assert!(names.contains(&"math_utils"), "got: {:?}", names);
        assert!(names.contains(&"add"), "got: {:?}", names);
        assert!(names.contains(&"greet"), "got: {:?}", names);
        assert!(names.contains(&"main"), "got: {:?}", names);

        let find = |name: &str| entities.iter().find(|e| e.name == name)
            .unwrap_or_else(|| panic!("Should find {}, got: {:?}", name, names));

        assert_eq!(find("math_utils").entity_type, "module");
        assert_eq!(find("add").entity_type, "function");
        assert_eq!(find("greet").entity_type, "subroutine");
        assert_eq!(find("main").entity_type, "program");

        // Nested entities have parent
        assert!(find("add").parent_id.is_some());
        assert!(find("greet").parent_id.is_some());
    }

    #[test]
    fn test_scala_entity_extraction() {
        let code = r#"
package com.example

import scala.collection.mutable

class UserService(val name: String) {
  def getUsers(): List[User] = db.findAll()

  def createUser(user: User): Unit = db.save(user)

  private def validate(user: User): Boolean = true
}

object UserService {
  def apply(name: String): UserService = new UserService(name)

  val DefaultName: String = "default"
}

trait Repository[T] {
  def findById(id: String): Option[T]
  def findAll(): List[T]
}

case class User(id: String, name: String)

type UserId = String
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "UserService.scala");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!("Scala entities: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());

        assert!(names.contains(&"UserService"), "Should find class UserService, got: {:?}", names);
        assert!(names.contains(&"Repository"), "Should find trait Repository, got: {:?}", names);
        assert!(names.contains(&"getUsers"), "Should find method getUsers, got: {:?}", names);
        assert!(names.contains(&"createUser"), "Should find method createUser, got: {:?}", names);

        // Methods should be nested under class
        let get_users = entities.iter().find(|e| e.name == "getUsers").unwrap();
        assert!(get_users.parent_id.is_some(), "getUsers should have parent_id");
    }

    #[test]
    fn test_scala3_entity_extraction() {
        let code = r#"
package com.example

enum Color:
  case Red, Green, Blue

enum Planet(mass: Double, radius: Double):
  case Mercury extends Planet(3.303e+23, 2.4397e6)
  case Venus   extends Planet(4.869e+24, 6.0518e6)

object Main:
  def main(args: Array[String]): Unit =
    println("Hello, World!")

trait Greeter:
  def greet(name: String): String

given Greeter with
  def greet(name: String): String = s"Hello, $name!"

extension (s: String)
  def shout: String = s.toUpperCase + "!"

type Predicate[A] = A => Boolean
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "Main.scala");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        eprintln!("Scala 3 entities: {:?}", entities.iter().map(|e| (&e.name, &e.entity_type)).collect::<Vec<_>>());

        assert!(names.contains(&"Color"), "Should find enum Color, got: {:?}", names);
        assert!(names.contains(&"Planet"), "Should find enum Planet, got: {:?}", names);
        assert!(names.contains(&"Main"), "Should find object Main, got: {:?}", names);
        assert!(names.contains(&"Greeter"), "Should find trait Greeter, got: {:?}", names);
        assert!(names.contains(&"Predicate"), "Should find type alias Predicate, got: {:?}", names);
    }

    #[test]
    fn test_zig_entity_extraction() {
        let code = r#"
const std = @import("std");

pub const Point = struct {
    x: i32,
    y: i32,
};

pub const Color = enum {
    red,
    green,
    blue,
};

const Person = struct {
    name: []const u8,
    age: u32,
};

pub fn greet(name: []const u8) void {
    std.debug.print("Hello, {s}!\n", .{name});
}

fn add(a: i32, b: i32) i32 {
    return a + b;
}

pub fn main() !void {
    greet("world");
}

test "basic addition" {
    const result = add(2, 3);
    _ = result;
}
"#;
        let plugin = CodeParserPlugin;
        let entities = plugin.extract_entities(code, "main.zig");
        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        let types: std::collections::HashMap<&str, &str> = entities
            .iter()
            .map(|e| (e.name.as_str(), e.entity_type.as_str()))
            .collect();

        assert!(names.contains(&"greet"), "Should find greet, got: {:?}", names);
        assert!(names.contains(&"add"), "Should find add, got: {:?}", names);
        assert!(names.contains(&"main"), "Should find main, got: {:?}", names);
        assert!(names.contains(&"Point"), "Should find Point, got: {:?}", names);
        assert!(names.contains(&"Color"), "Should find Color, got: {:?}", names);
        assert!(names.contains(&"Person"), "Should find Person, got: {:?}", names);

        assert_eq!(types["greet"], "function");
        assert_eq!(types["add"], "function");
        assert_eq!(types["Point"], "struct");
        assert_eq!(types["Color"], "enum");
        assert_eq!(types["Person"], "struct");
    }
}