infigraph-core 1.5.5

AST-powered code analysis framework — parser, graph, diff, and analysis engine
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
use sha2::{Digest, Sha256};
use tree_sitter::{Node, Query, QueryCursor, StreamingIterator};

use crate::analysis::cyclomatic_complexity;
use crate::model::{Span, Symbol, SymbolKind};

/// Extract symbols from a parsed AST using a Tree-sitter query.
///
/// The query must use these capture names:
///   @func.def / @func.name / @func.docstring / @func.decorator
///   @method.def / @method.name / @method.docstring / @method.decorator
///   @class.def / @class.name / @class.docstring / @class.decorator
///   @module.def / @module.name
///   @test.def / @test.name / @test.docstring
///   @var.def / @var.name
///   @route.def / @route.method / @route.path / @route.handler
pub fn extract_entities(
    file: &str,
    source: &[u8],
    root: Node,
    query: &Query,
    language: &str,
) -> Vec<Symbol> {
    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(query, root, source);

    let capture_names = query.capture_names();

    let mut symbols = Vec::new();

    while let Some(m) = matches.next() {
        let mut name_text = None;
        let mut def_node = None;
        let mut kind = None;
        let mut docstring = None;
        let mut decorator = None;
        let mut route_method: Option<String> = None;
        let mut route_path: Option<String> = None;
        let mut route_handler: Option<String> = None;
        let mut route_def_node: Option<Node> = None;

        for capture in m.captures {
            let idx = capture.index as usize;
            let cap_name = capture_names[idx];
            let node = capture.node;

            match cap_name {
                "func.name" => {
                    name_text = Some(node_text(node, source));
                    if kind.is_none() {
                        kind = Some(SymbolKind::Function);
                    }
                }
                "func.def" => {
                    def_node = Some(node);
                    if kind.is_none() {
                        kind = Some(SymbolKind::Function);
                    }
                }
                "func.docstring" => {
                    docstring = Some(strip_docstring(&node_text(node, source)));
                }
                "func.decorator" => {
                    decorator = Some(node_text(node, source));
                }
                "method.name" => {
                    name_text = Some(node_text(node, source));
                    kind = Some(SymbolKind::Method);
                }
                "method.def" => {
                    def_node = Some(node);
                    if kind.is_none() {
                        kind = Some(SymbolKind::Method);
                    }
                }
                "method.docstring" => {
                    docstring = Some(strip_docstring(&node_text(node, source)));
                }
                "method.decorator" => {
                    decorator = Some(node_text(node, source));
                }
                "class.name" => {
                    name_text = Some(node_text(node, source));
                    if kind.is_none() {
                        kind = Some(SymbolKind::Class);
                    }
                }
                "class.def" => {
                    def_node = Some(node);
                    if kind.is_none() {
                        kind = Some(SymbolKind::Class);
                    }
                }
                "class.docstring" => {
                    docstring = Some(strip_docstring(&node_text(node, source)));
                }
                "class.decorator" => {
                    decorator = Some(node_text(node, source));
                }
                "module.name" => {
                    let raw = node_text(node, source);
                    name_text = Some(strip_string_delimiters(&raw));
                    if kind.is_none() {
                        kind = Some(SymbolKind::Module);
                    }
                }
                "module.def" => {
                    def_node = Some(node);
                    if kind.is_none() {
                        kind = Some(SymbolKind::Module);
                    }
                }
                "test.name" => {
                    name_text = Some(node_text(node, source));
                    kind = Some(SymbolKind::Test);
                }
                "test.def" => {
                    def_node = Some(node);
                    if kind.is_none() {
                        kind = Some(SymbolKind::Test);
                    }
                }
                "test.docstring" => {
                    docstring = Some(strip_docstring(&node_text(node, source)));
                }
                "var.name" => {
                    name_text = Some(node_text(node, source));
                    if kind.is_none() {
                        kind = Some(SymbolKind::Variable);
                    }
                }
                "var.def" => {
                    def_node = Some(node);
                    if kind.is_none() {
                        kind = Some(SymbolKind::Variable);
                    }
                }
                "section.name" => {
                    name_text = Some(node_text(node, source));
                    if kind.is_none() {
                        kind = Some(SymbolKind::Section);
                    }
                }
                "section.def" => {
                    def_node = Some(node);
                    if kind.is_none() {
                        kind = Some(SymbolKind::Section);
                    }
                }
                "route.method" => {
                    route_method = Some(node_text(node, source));
                }
                "route.path" => {
                    route_path = Some(strip_string_delimiters(&node_text(node, source)));
                }
                "route.handler" => {
                    route_handler = Some(node_text(node, source));
                }
                "route.def" => {
                    route_def_node = Some(node);
                }
                _ => {}
            }
        }

        // Prepend decorator/attribute text to docstring for searchability
        // If no decorator from query capture, try AST-based extraction (Rust attrs, Go comments, C# attrs)
        if decorator.is_none() {
            if let Some(node) = def_node {
                decorator = find_preceding_attributes(node, source);
            }
        }
        if let Some(dec) = decorator {
            let dec_clean = dec.trim().to_string();
            docstring = Some(match docstring {
                Some(doc) => format!("{} {}", dec_clean, doc),
                None => dec_clean,
            });
        }

        if let (Some(name), Some(node), Some(sym_kind)) = (name_text, def_node, kind) {
            let span = Span {
                file: file.to_string(),
                start_line: node.start_position().row as u32 + 1,
                start_col: node.start_position().column as u32,
                end_line: node.end_position().row as u32 + 1,
                end_col: node.end_position().column as u32,
            };

            let signature_hash = match sym_kind {
                SymbolKind::Function | SymbolKind::Method | SymbolKind::Test => {
                    hash_body(node, source)
                }
                _ => hash_node(node, source),
            };

            // Find parent class for methods by walking up the AST
            let parent_class = find_parent_class(node, source);
            let id = if let Some(ref cls) = parent_class {
                format!("{}::{}::{}", file, cls, name)
            } else {
                format!("{}::{}", file, name)
            };
            let parent = parent_class.map(|cls| format!("{}::{}", file, cls));

            let complexity = match sym_kind {
                SymbolKind::Function | SymbolKind::Method | SymbolKind::Test => {
                    cyclomatic_complexity(node)
                }
                _ => 1,
            };

            let parameters = extract_child_text(node, "parameters", source);
            let return_type = extract_child_text(node, "return_type", source)
                .or_else(|| extract_child_text(node, "result", source));

            let visibility = extract_visibility(node, source);

            symbols.push(Symbol {
                id,
                name,
                kind: sym_kind,
                span,
                signature_hash,
                parent,
                language: language.to_string(),
                visibility,
                docstring,
                complexity,
                parameters,
                return_type,
            });
        }

        // Create Route symbol from @route.* captures
        if let Some(path) = route_path {
            let method = route_method.unwrap_or_default().to_uppercase();
            let handler = route_handler.clone().unwrap_or_default();
            let route_name = if method.is_empty() {
                format!("ROUTE {}", path)
            } else {
                format!("{} {}", method, path)
            };
            let node = route_def_node.unwrap_or(def_node.unwrap_or(root));
            let span = Span {
                file: file.to_string(),
                start_line: node.start_position().row as u32 + 1,
                start_col: node.start_position().column as u32,
                end_line: node.end_position().row as u32 + 1,
                end_col: node.end_position().column as u32,
            };
            let id = format!("{}::{}", file, route_name.replace([' ', '/'], "_"));
            let docstring = if handler.is_empty() {
                Some(format!("route {} {}", method, path))
            } else {
                Some(format!("route {} {} handler={}", method, path, handler))
            };
            symbols.push(Symbol {
                id,
                name: route_name,
                kind: SymbolKind::Route,
                span,
                signature_hash: hash_node(node, source),
                parameters: None,
                return_type: None,
                parent: None,
                language: language.to_string(),
                visibility: None,
                docstring,
                complexity: 1,
            });
        }
    }

    for sym in &mut symbols {
        if matches!(sym.kind, SymbolKind::Function | SymbolKind::Method)
            && (is_test_by_docstring(&sym.docstring)
                || is_test_by_name_and_path(&sym.name, file, &sym.language))
        {
            sym.kind = SymbolKind::Test;
        }
    }

    // Deduplicate by ID — prefer more specific kind (Test > Function)
    let mut seen = std::collections::HashMap::new();
    for sym in symbols {
        seen.entry(sym.id.clone())
            .and_modify(|existing: &mut Symbol| {
                // Test is more specific than Function
                if sym.kind == SymbolKind::Test && existing.kind == SymbolKind::Function {
                    *existing = sym.clone();
                }
            })
            .or_insert(sym);
    }
    seen.into_values().collect()
}

/// Walk up the AST to find the enclosing class_definition and return its name.
fn find_parent_class(node: Node, source: &[u8]) -> Option<String> {
    let mut current = node.parent();
    while let Some(n) = current {
        if n.kind() == "class_definition" {
            // The name child of a class_definition is the class name
            return n
                .child_by_field_name("name")
                .map(|name_node| node_text(name_node, source));
        }
        current = n.parent();
    }
    None
}

/// Look at preceding siblings for attribute/decorator nodes.
/// Handles: Rust `attribute_item` (#[get("/path")]), C# `attribute_list` ([HttpGet]),
/// Go preceding line comments (// @router /api/users [get]), and similar patterns.
fn find_preceding_attributes(node: Node, source: &[u8]) -> Option<String> {
    // Node kinds that represent decorators/attributes across languages
    const ATTR_KINDS: &[&str] = &[
        "attribute_item",    // Rust: #[get("/path")]
        "attribute_list",    // C#: [HttpGet], PHP 8: #[Route("/path")]
        "attribute",         // C# inner, PHP inner
        "annotation",        // Kotlin, Scala, Java (fallback)
        "decorator",         // TypeScript/JS (NestJS @Controller, @Get)
        "marker_annotation", // Java @Override, @GetMapping
    ];

    // Comment kinds that may contain route annotations (Go swagger, JSDoc)
    const COMMENT_KINDS: &[&str] = &["comment", "line_comment", "block_comment"];

    let mut attrs = Vec::new();

    // Collect from preceding siblings
    collect_attrs(node, source, ATTR_KINDS, COMMENT_KINDS, &mut attrs);

    // Also check parent's preceding siblings (for attributes at different nesting)
    if attrs.is_empty() {
        if let Some(parent) = node.parent() {
            collect_attrs(parent, source, ATTR_KINDS, COMMENT_KINDS, &mut attrs);
        }
    }

    if attrs.is_empty() {
        None
    } else {
        attrs.reverse();
        Some(attrs.join(" "))
    }
}

/// Collect attribute/decorator nodes from preceding siblings.
fn collect_attrs(
    node: Node,
    source: &[u8],
    attr_kinds: &[&str],
    comment_kinds: &[&str],
    attrs: &mut Vec<String>,
) {
    let mut sibling = node.prev_sibling();
    while let Some(sib) = sibling {
        if attr_kinds.contains(&sib.kind()) {
            attrs.push(node_text(sib, source));
            sibling = sib.prev_sibling();
        } else if comment_kinds.contains(&sib.kind()) {
            // Only capture annotation-like comments: // @Router, /// @route, # @app.route
            let text = node_text(sib, source);
            if text.contains("@")
                || text.contains("route")
                || text.contains("endpoint")
                || text.contains("handler")
                || text.contains("API")
            {
                attrs.push(text);
            }
            sibling = sib.prev_sibling();
        } else {
            break;
        }
    }
}

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

fn extract_child_text(node: Node, field_name: &str, source: &[u8]) -> Option<String> {
    let child = node.child_by_field_name(field_name)?;
    let text = child.utf8_text(source).ok()?.trim().to_string();
    if text.is_empty() {
        None
    } else {
        Some(text)
    }
}

/// Extract visibility from AST node. Works across languages by checking for
/// common visibility-related child node kinds.
fn extract_visibility(node: Node, source: &[u8]) -> Option<String> {
    // Check named children for visibility-related node kinds
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            // Rust: pub, pub(crate), pub(super)
            "visibility_modifier" => {
                let text = child.utf8_text(source).ok()?.trim().to_string();
                return Some(text);
            }
            // Java/C#/Kotlin/Groovy: modifiers node containing access keywords
            "modifiers" | "modifier_list" => {
                let mut mod_cursor = child.walk();
                for modifier in child.children(&mut mod_cursor) {
                    let kind = modifier.kind();
                    if kind == "public"
                        || kind == "private"
                        || kind == "protected"
                        || kind == "internal"
                    {
                        return Some(kind.to_string());
                    }
                    // C#/Java text-based modifier check
                    if let Ok(text) = modifier.utf8_text(source) {
                        let t = text.trim();
                        if t == "public" || t == "private" || t == "protected" || t == "internal" {
                            return Some(t.to_string());
                        }
                    }
                }
            }
            // Swift: modifier with visibility_modifier child
            "modifier" => {
                if let Ok(text) = child.utf8_text(source) {
                    let t = text.trim();
                    if t == "public"
                        || t == "private"
                        || t == "internal"
                        || t == "fileprivate"
                        || t == "open"
                    {
                        return Some(t.to_string());
                    }
                }
            }
            // Direct keyword children (some grammars)
            "public" | "private" | "protected" | "internal" => {
                return Some(child.kind().to_string());
            }
            _ => {}
        }
    }
    None
}

const TEST_ATTR_PATTERNS: &[&str] = &[
    "#[test]",
    "#[tokio::test]",
    "#[rstest]",
    "#[test_case",
    "@Test",
    "@ParameterizedTest",
    "@RepeatedTest",
    "[Test]",
    "[Fact]",
    "[Theory]",
    "[TestMethod]",
    "@pytest.mark",
    "@unittest",
];

fn is_test_by_docstring(docstring: &Option<String>) -> bool {
    match docstring {
        Some(doc) => TEST_ATTR_PATTERNS.iter().any(|pat| doc.contains(pat)),
        None => false,
    }
}

fn is_test_by_name_and_path(name: &str, file: &str, language: &str) -> bool {
    let file_lower = file.to_lowercase();
    let in_test_dir = file_lower.contains("/test/")
        || file_lower.contains("/tests/")
        || file_lower.contains("/__tests__/")
        || file_lower.contains("/spec/")
        || file_lower.starts_with("test/")
        || file_lower.starts_with("tests/")
        || file_lower.starts_with("spec/")
        || file_lower.starts_with("__tests__/");

    match language {
        // JS/TS: *.test.ts, *.spec.js, __tests__/ with describe/it/test
        "typescript" | "javascript" => {
            file_lower.ends_with(".test.ts")
                || file_lower.ends_with(".test.tsx")
                || file_lower.ends_with(".test.js")
                || file_lower.ends_with(".test.jsx")
                || file_lower.ends_with(".test.mjs")
                || file_lower.ends_with(".spec.ts")
                || file_lower.ends_with(".spec.tsx")
                || file_lower.ends_with(".spec.js")
                || file_lower.ends_with(".spec.jsx")
                || (in_test_dir && (name == "it" || name == "test" || name == "describe"))
        }
        // Go: func TestXxx in _test.go
        "go" => {
            file_lower.ends_with("_test.go")
                && (name.starts_with("Test")
                    || name.starts_with("Benchmark")
                    || name.starts_with("Fuzz"))
        }
        // Python: test_ prefix in test files/dirs, or pytest/unittest via docstring (handled separately)
        "python" => {
            name.starts_with("test_")
                && (file_lower.contains("test_") || file_lower.ends_with("_test.py") || in_test_dir)
        }
        // Ruby: RSpec it/describe in _spec.rb, Minitest test_ in _test.rb
        "ruby" => {
            (name.starts_with("test_") && in_test_dir)
                || (file_lower.ends_with("_spec.rb")
                    && (name == "it"
                        || name == "specify"
                        || name == "describe"
                        || name == "context"))
                || (file_lower.ends_with("_test.rb") && name.starts_with("test_"))
        }
        // PHP: PHPUnit test* methods in *Test.php
        "php" => name.starts_with("test") && (file_lower.ends_with("test.php") || in_test_dir),
        // Swift: XCTest func testXxx in *Tests.swift
        "swift" => {
            name.starts_with("test")
                && (file_lower.ends_with("tests.swift")
                    || file_lower.ends_with("test.swift")
                    || in_test_dir)
        }
        // Scala: ScalaTest it/test/describe in spec/test dirs or files
        "scala" => {
            (in_test_dir || file_lower.contains("src/test/"))
                && (name == "test"
                    || name == "it"
                    || name == "describe"
                    || file_lower.ends_with("spec.scala")
                    || file_lower.ends_with("test.scala"))
        }
        // Dart: *_test.dart files, test()/testWidgets()/group() in test/
        "dart" => {
            file_lower.ends_with("_test.dart")
                || (in_test_dir && (name == "test" || name == "testWidgets" || name == "group"))
        }
        // Elixir: test macro in *_test.exs
        "elixir" => {
            file_lower.ends_with("_test.exs")
                && (name == "test" || name.starts_with("test ") || name == "describe")
        }
        // Lua: busted describe/it/spec, or in spec/ or test/ dirs
        "lua" => {
            in_test_dir
                && (name == "describe" || name == "it" || name == "spec" || name == "pending")
        }
        // Perl: Test::More/Test2 — functions in .t files
        "perl" => file_lower.ends_with(".t"),
        // R: testthat test_that() in test/ dirs
        "r" => in_test_dir && (name == "test_that" || name.starts_with("test_")),
        // Julia: @test macro in test/ dir or runtests.jl
        "julia" => in_test_dir || file_lower.ends_with("runtests.jl"),
        // Haskell: HSpec describe/it, or HUnit test* in test/ or spec/
        "haskell" => {
            (in_test_dir || file_lower.contains("/spec/"))
                && (name == "describe"
                    || name == "it"
                    || name == "spec"
                    || name.starts_with("test"))
        }
        // Erlang: EUnit test_/0, Common Test *_SUITE in test/
        "erlang" => {
            (file_lower.ends_with("_test.erl")
                || file_lower.ends_with("_tests.erl")
                || file_lower.ends_with("_suite.erl"))
                || (in_test_dir && name.starts_with("test_"))
        }
        // Zig: test blocks — zig names them "test" or "test \"description\""
        "zig" => name == "test" || name.starts_with("test "),
        // F#: NUnit/xUnit [Test]/[Fact] via docstring (retag handles), Expecto testCase in test dirs
        "fsharp" => {
            in_test_dir && (name == "testCase" || name == "testList" || name.starts_with("test"))
        }
        // Groovy: Spock where/then in *Spec.groovy, JUnit via docstring retag
        "groovy" => {
            file_lower.ends_with("spec.groovy")
                || file_lower.ends_with("test.groovy")
                || (in_test_dir && name.starts_with("test"))
        }
        // Kotlin: JUnit @Test via docstring retag, kotest describe/it in test dirs
        "kotlin" => {
            in_test_dir
                && (name == "describe"
                    || name == "it"
                    || name == "test"
                    || name.starts_with("test"))
        }
        // C#: NUnit/xUnit/MSTest via docstring retag, this catches test dir heuristic
        "csharp" => {
            (file_lower.ends_with("test.cs") || file_lower.ends_with("tests.cs"))
                && name.starts_with("Test")
        }
        // Objective-C: XCTest testXxx in *Tests.m
        "objc" => {
            name.starts_with("test")
                && (file_lower.ends_with("tests.m")
                    || file_lower.ends_with("test.m")
                    || in_test_dir)
        }
        // OCaml: Alcotest/OUnit test_ in test/ dir
        "ocaml" => in_test_dir && name.starts_with("test"),
        // Fortran: pFUnit test_ in test/ dir
        "fortran" => in_test_dir && name.starts_with("test"),
        // PowerShell: Pester Describe/It/Context in *.Tests.ps1
        "powershell" => {
            file_lower.ends_with(".tests.ps1")
                && (name == "Describe" || name == "It" || name == "Context")
        }
        // Bash: bats @test in .bats files, or test_ functions in test/ dir
        "bash" => file_lower.ends_with(".bats") || (in_test_dir && name.starts_with("test_")),
        // Svelte: same as JS/TS — *.test.ts patterns
        "svelte" => {
            file_lower.ends_with(".test.ts") || file_lower.ends_with(".spec.ts") || in_test_dir
        }
        // C++: GTest TEST/TEST_F/TEST_P, Catch2 TEST_CASE/SCENARIO, Boost test*
        "cpp" => {
            (name == "TEST"
                || name == "TEST_F"
                || name == "TEST_P"
                || name == "TEST_CASE"
                || name == "SCENARIO"
                || name == "SECTION"
                || name == "BOOST_AUTO_TEST_CASE"
                || name == "BOOST_FIXTURE_TEST_CASE")
                || (in_test_dir && name.starts_with("test"))
                || file_lower.ends_with("_test.cpp")
                || file_lower.ends_with("_test.cc")
                || file_lower.ends_with("_tests.cpp")
                || file_lower.ends_with("_tests.cc")
        }
        // C: CUnit, Unity, Check — test_ prefix in test files/dirs
        "c" => {
            (in_test_dir && name.starts_with("test"))
                || file_lower.ends_with("_test.c")
                || file_lower.ends_with("_tests.c")
        }
        // CUDA: same as C++ patterns
        "cuda" => {
            (name == "TEST" || name == "TEST_F" || name == "TEST_P")
                || (in_test_dir && name.starts_with("test"))
                || file_lower.ends_with("_test.cu")
        }
        // Clojure: deftest macro — name is the test function name, file in test/ dir
        "clojure" => {
            in_test_dir || file_lower.ends_with("_test.clj") || file_lower.ends_with("_test.cljc")
        }
        // Elm: Test.describe/Test.test in tests/ dir
        "elm" => {
            in_test_dir
                || (name == "describe" || name == "test" || name == "fuzz")
                    && file_lower.contains("test")
        }
        // Common Lisp: FiveAM def-test, in test/ dirs
        "commonlisp" => in_test_dir && (name.starts_with("test") || name == "def-test"),
        // Pascal: DUnit/FPCUnit test* methods in *Test.pas
        "pascal" => {
            name.starts_with("Test")
                && (file_lower.ends_with("test.pas")
                    || file_lower.ends_with("tests.pas")
                    || in_test_dir)
        }
        // Rust/Java/C#/Kotlin: handled by docstring retag
        _ => false,
    }
}

fn hash_node(node: Node, source: &[u8]) -> String {
    let mut hasher = Sha256::new();
    let text = &source[node.byte_range()];
    hasher.update(text);
    format!("{:x}", hasher.finalize())[..16].to_string()
}

/// Hash only the body of a function/method node, excluding the signature line.
/// This allows rename detection: two functions with different names but identical
/// bodies will produce the same hash.
fn hash_body(node: Node, source: &[u8]) -> String {
    if let Some(body) = node.child_by_field_name("body") {
        hash_node(body, source)
    } else {
        // Fallback: try "block" field (used by some grammars like Java/C#)
        if let Some(block) = node.child_by_field_name("block") {
            hash_node(block, source)
        } else {
            hash_node(node, source)
        }
    }
}

/// Strip string delimiters (quotes) from a captured path string.
fn strip_string_delimiters(s: &str) -> String {
    let s = s.trim();
    let s = s.strip_prefix('"').unwrap_or(s);
    let s = s.strip_suffix('"').unwrap_or(s);
    let s = s.strip_prefix('\'').unwrap_or(s);
    let s = s.strip_suffix('\'').unwrap_or(s);
    let s = s.strip_prefix('`').unwrap_or(s);
    let s = s.strip_suffix('`').unwrap_or(s);
    s.to_string()
}

/// Strip triple-quote delimiters and leading whitespace from a docstring.
fn strip_docstring(raw: &str) -> String {
    let s = raw.trim();
    let s = s
        .strip_prefix("\"\"\"")
        .or_else(|| s.strip_prefix("'''"))
        .unwrap_or(s);
    let s = s
        .strip_suffix("\"\"\"")
        .or_else(|| s.strip_suffix("'''"))
        .unwrap_or(s);
    // Dedent: find minimum indentation and strip it
    let lines: Vec<&str> = s.lines().collect();
    if lines.len() <= 1 {
        return s.trim().to_string();
    }
    let min_indent = lines[1..]
        .iter()
        .filter(|l| !l.trim().is_empty())
        .map(|l| l.len() - l.trim_start().len())
        .min()
        .unwrap_or(0);
    let mut result = String::new();
    for (i, line) in lines.iter().enumerate() {
        if i == 0 {
            result.push_str(line.trim());
        } else if line.len() >= min_indent {
            if !result.is_empty() {
                result.push('\n');
            }
            result.push_str(&line[min_indent..]);
        } else {
            if !result.is_empty() {
                result.push('\n');
            }
            result.push_str(line.trim());
        }
    }
    result.trim().to_string()
}

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

    #[test]
    fn test_module_capture_produces_module_symbol() {
        // Use Python grammar: capture identifier as @module.name and enclosing
        // assignment as @module.def — two distinct nodes, proving arm independence.
        let grammar = tree_sitter_python::LANGUAGE.into();
        let src = b"MyModule = 1";
        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();
        let tree = parser.parse(src, None).unwrap();
        let root = tree.root_node();

        // identifier node (name) and assignment node (def) are distinct
        let query = tree_sitter::Query::new(
            &grammar,
            r#"(assignment left: (identifier) @module.name) @module.def"#,
        )
        .unwrap();

        let symbols = extract_entities("test.bas", src, root, &query, "vb6");
        assert_eq!(symbols.len(), 1);
        assert_eq!(symbols[0].kind, crate::model::SymbolKind::Module);
        assert_eq!(symbols[0].name, "MyModule");
    }

    #[test]
    fn test_python_function_extracts_parameters_and_return_type() {
        let grammar = tree_sitter_python::LANGUAGE.into();
        let src = b"def greet(name: str, age: int) -> str:\n    return f'hello {name}'\n";
        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();
        let tree = parser.parse(src, None).unwrap();
        let root = tree.root_node();

        let query = tree_sitter::Query::new(
            &grammar,
            "(function_definition name: (identifier) @func.name) @func.def",
        )
        .unwrap();

        let symbols = extract_entities("greet.py", src, root, &query, "python");
        assert_eq!(symbols.len(), 1);
        assert_eq!(symbols[0].name, "greet");
        assert!(
            symbols[0].parameters.is_some(),
            "parameters should be extracted"
        );
        assert!(
            symbols[0].parameters.as_deref().unwrap().contains("name"),
            "parameters should contain param names: {:?}",
            symbols[0].parameters
        );
        assert!(
            symbols[0].return_type.is_some(),
            "return_type should be extracted for typed Python"
        );
        assert_eq!(symbols[0].return_type.as_deref(), Some("str"));
    }

    #[test]
    fn test_python_function_no_return_type() {
        let grammar = tree_sitter_python::LANGUAGE.into();
        let src = b"def hello(x):\n    pass\n";
        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();
        let tree = parser.parse(src, None).unwrap();
        let root = tree.root_node();

        let query = tree_sitter::Query::new(
            &grammar,
            "(function_definition name: (identifier) @func.name) @func.def",
        )
        .unwrap();

        let symbols = extract_entities("hello.py", src, root, &query, "python");
        assert_eq!(symbols.len(), 1);
        assert!(symbols[0].parameters.is_some());
        assert!(
            symbols[0].return_type.is_none(),
            "no return type annotation"
        );
    }

    #[test]
    fn test_is_test_by_name_and_path_go() {
        assert!(is_test_by_name_and_path(
            "TestFoo",
            "pkg/auth/auth_test.go",
            "go"
        ));
        assert!(is_test_by_name_and_path(
            "BenchmarkHash",
            "hash_test.go",
            "go"
        ));
        assert!(is_test_by_name_and_path("FuzzParse", "parse_test.go", "go"));
        assert!(!is_test_by_name_and_path(
            "TestFoo",
            "pkg/auth/auth.go",
            "go"
        ));
        assert!(!is_test_by_name_and_path("helper", "auth_test.go", "go"));
    }

    #[test]
    fn test_is_test_by_name_and_path_typescript() {
        assert!(is_test_by_name_and_path(
            "it",
            "src/auth.test.ts",
            "typescript"
        ));
        assert!(is_test_by_name_and_path(
            "describe",
            "src/auth.spec.tsx",
            "typescript"
        ));
        assert!(is_test_by_name_and_path(
            "test",
            "src/__tests__/auth.ts",
            "typescript"
        ));
        assert!(!is_test_by_name_and_path("it", "src/auth.ts", "typescript"));
    }

    #[test]
    fn test_is_test_by_name_and_path_javascript() {
        assert!(is_test_by_name_and_path(
            "it",
            "src/utils.test.js",
            "javascript"
        ));
        assert!(is_test_by_name_and_path(
            "test",
            "src/utils.spec.jsx",
            "javascript"
        ));
        assert!(is_test_by_name_and_path(
            "describe",
            "src/utils.test.mjs",
            "javascript"
        ));
        assert!(!is_test_by_name_and_path(
            "render",
            "src/utils.js",
            "javascript"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_python() {
        assert!(is_test_by_name_and_path(
            "test_login",
            "tests/test_auth.py",
            "python"
        ));
        assert!(is_test_by_name_and_path(
            "test_foo",
            "test/test_foo.py",
            "python"
        ));
        assert!(is_test_by_name_and_path(
            "test_bar",
            "src/bar_test.py",
            "python"
        ));
        assert!(!is_test_by_name_and_path(
            "helper",
            "tests/test_auth.py",
            "python"
        ));
        assert!(!is_test_by_name_and_path(
            "test_login",
            "src/auth.py",
            "python"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_ruby() {
        assert!(is_test_by_name_and_path(
            "it",
            "spec/models/user_spec.rb",
            "ruby"
        ));
        assert!(is_test_by_name_and_path(
            "describe",
            "spec/auth_spec.rb",
            "ruby"
        ));
        assert!(is_test_by_name_and_path(
            "test_login",
            "test/auth_test.rb",
            "ruby"
        ));
        assert!(!is_test_by_name_and_path(
            "helper",
            "spec/user_spec.rb",
            "ruby"
        ));
        assert!(!is_test_by_name_and_path(
            "it",
            "app/models/user.rb",
            "ruby"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_php() {
        assert!(is_test_by_name_and_path(
            "testLogin",
            "tests/AuthTest.php",
            "php"
        ));
        assert!(is_test_by_name_and_path(
            "testCreate",
            "test/UserTest.php",
            "php"
        ));
        assert!(!is_test_by_name_and_path(
            "helper",
            "tests/AuthTest.php",
            "php"
        ));
        assert!(!is_test_by_name_and_path(
            "testLogin",
            "src/Auth.php",
            "php"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_swift() {
        assert!(is_test_by_name_and_path(
            "testLogin",
            "AuthTests.swift",
            "swift"
        ));
        assert!(is_test_by_name_and_path(
            "testFoo",
            "Tests/FooTest.swift",
            "swift"
        ));
        assert!(!is_test_by_name_and_path(
            "helper",
            "AuthTests.swift",
            "swift"
        ));
        assert!(!is_test_by_name_and_path(
            "testLogin",
            "Sources/Auth.swift",
            "swift"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_elixir() {
        assert!(is_test_by_name_and_path(
            "test",
            "test/auth_test.exs",
            "elixir"
        ));
        assert!(is_test_by_name_and_path(
            "describe",
            "test/user_test.exs",
            "elixir"
        ));
        assert!(!is_test_by_name_and_path("test", "lib/auth.ex", "elixir"));
        assert!(!is_test_by_name_and_path(
            "helper",
            "test/auth_test.exs",
            "elixir"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_lua() {
        assert!(is_test_by_name_and_path(
            "describe",
            "spec/auth_spec.lua",
            "lua"
        ));
        assert!(is_test_by_name_and_path("it", "test/utils_test.lua", "lua"));
        assert!(!is_test_by_name_and_path("describe", "src/auth.lua", "lua"));
    }

    #[test]
    fn test_is_test_by_name_and_path_perl() {
        assert!(is_test_by_name_and_path("subtest", "t/auth.t", "perl"));
        assert!(is_test_by_name_and_path("ok", "t/01-basic.t", "perl"));
        assert!(!is_test_by_name_and_path("ok", "lib/Auth.pm", "perl"));
    }

    #[test]
    fn test_is_test_by_name_and_path_r() {
        assert!(is_test_by_name_and_path(
            "test_that",
            "tests/test-auth.R",
            "r"
        ));
        assert!(is_test_by_name_and_path(
            "test_login",
            "tests/testthat/test-login.R",
            "r"
        ));
        assert!(!is_test_by_name_and_path("test_that", "R/auth.R", "r"));
    }

    #[test]
    fn test_is_test_by_name_and_path_julia() {
        assert!(is_test_by_name_and_path("foo", "test/runtests.jl", "julia"));
        assert!(is_test_by_name_and_path(
            "bar",
            "test/auth_tests.jl",
            "julia"
        ));
        assert!(!is_test_by_name_and_path("foo", "src/Auth.jl", "julia"));
    }

    #[test]
    fn test_is_test_by_name_and_path_haskell() {
        assert!(is_test_by_name_and_path(
            "describe",
            "test/AuthSpec.hs",
            "haskell"
        ));
        assert!(is_test_by_name_and_path(
            "it",
            "spec/AuthSpec.hs",
            "haskell"
        ));
        assert!(is_test_by_name_and_path(
            "testLogin",
            "test/Auth.hs",
            "haskell"
        ));
        assert!(!is_test_by_name_and_path(
            "describe",
            "src/Auth.hs",
            "haskell"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_erlang() {
        assert!(is_test_by_name_and_path(
            "test_login",
            "test/auth_test.erl",
            "erlang"
        ));
        assert!(is_test_by_name_and_path(
            "init",
            "test/auth_SUITE.erl",
            "erlang"
        ));
        assert!(is_test_by_name_and_path(
            "test_foo",
            "test/bar_tests.erl",
            "erlang"
        ));
        assert!(!is_test_by_name_and_path(
            "handle_call",
            "src/auth.erl",
            "erlang"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_zig() {
        assert!(is_test_by_name_and_path("test", "src/auth.zig", "zig"));
        assert!(is_test_by_name_and_path(
            "test allocator",
            "src/mem.zig",
            "zig"
        ));
        assert!(!is_test_by_name_and_path("init", "src/auth.zig", "zig"));
    }

    #[test]
    fn test_is_test_by_name_and_path_fsharp() {
        assert!(is_test_by_name_and_path(
            "testCase",
            "tests/AuthTests.fs",
            "fsharp"
        ));
        assert!(is_test_by_name_and_path(
            "testLogin",
            "test/Auth.fs",
            "fsharp"
        ));
        assert!(!is_test_by_name_and_path(
            "testCase",
            "src/Auth.fs",
            "fsharp"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_groovy() {
        assert!(is_test_by_name_and_path(
            "testLogin",
            "src/test/AuthSpec.groovy",
            "groovy"
        ));
        assert!(is_test_by_name_and_path("foo", "AuthTest.groovy", "groovy"));
        assert!(!is_test_by_name_and_path(
            "handle",
            "src/Auth.groovy",
            "groovy"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_kotlin() {
        assert!(is_test_by_name_and_path(
            "testLogin",
            "src/test/AuthTest.kt",
            "kotlin"
        ));
        assert!(is_test_by_name_and_path(
            "describe",
            "test/AuthSpec.kt",
            "kotlin"
        ));
        assert!(!is_test_by_name_and_path("handle", "src/Auth.kt", "kotlin"));
    }

    #[test]
    fn test_is_test_by_name_and_path_csharp() {
        assert!(is_test_by_name_and_path(
            "TestLogin",
            "AuthTest.cs",
            "csharp"
        ));
        assert!(is_test_by_name_and_path(
            "TestCreate",
            "UserTests.cs",
            "csharp"
        ));
        assert!(!is_test_by_name_and_path("TestLogin", "Auth.cs", "csharp"));
        assert!(!is_test_by_name_and_path("Handle", "AuthTest.cs", "csharp"));
    }

    #[test]
    fn test_is_test_by_name_and_path_objc() {
        assert!(is_test_by_name_and_path("testLogin", "AuthTests.m", "objc"));
        assert!(is_test_by_name_and_path(
            "testFoo",
            "tests/FooTest.m",
            "objc"
        ));
        assert!(!is_test_by_name_and_path("viewDidLoad", "Auth.m", "objc"));
    }

    #[test]
    fn test_is_test_by_name_and_path_ocaml() {
        assert!(is_test_by_name_and_path(
            "test_login",
            "test/auth_test.ml",
            "ocaml"
        ));
        assert!(!is_test_by_name_and_path(
            "test_login",
            "lib/auth.ml",
            "ocaml"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_powershell() {
        assert!(is_test_by_name_and_path(
            "Describe",
            "Auth.Tests.ps1",
            "powershell"
        ));
        assert!(is_test_by_name_and_path(
            "It",
            "Auth.Tests.ps1",
            "powershell"
        ));
        assert!(!is_test_by_name_and_path(
            "Describe",
            "Auth.ps1",
            "powershell"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_bash() {
        assert!(is_test_by_name_and_path("run", "test/auth.bats", "bash"));
        assert!(is_test_by_name_and_path(
            "test_login",
            "test/auth_test.sh",
            "bash"
        ));
        assert!(!is_test_by_name_and_path("main", "src/auth.sh", "bash"));
    }

    #[test]
    fn test_is_test_by_name_and_path_dart() {
        assert!(is_test_by_name_and_path(
            "test",
            "test/auth_test.dart",
            "dart"
        ));
        assert!(is_test_by_name_and_path(
            "testWidgets",
            "test/widget_test.dart",
            "dart"
        ));
        assert!(!is_test_by_name_and_path("build", "lib/auth.dart", "dart"));
    }

    #[test]
    fn test_is_test_by_name_and_path_scala() {
        assert!(is_test_by_name_and_path(
            "test",
            "src/test/AuthSpec.scala",
            "scala"
        ));
        assert!(is_test_by_name_and_path(
            "it",
            "src/test/AuthTest.scala",
            "scala"
        ));
        assert!(!is_test_by_name_and_path(
            "handle",
            "src/main/Auth.scala",
            "scala"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_fortran() {
        assert!(is_test_by_name_and_path(
            "test_solve",
            "test/test_solver.f90",
            "fortran"
        ));
        assert!(!is_test_by_name_and_path(
            "solve",
            "src/solver.f90",
            "fortran"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_cpp() {
        assert!(is_test_by_name_and_path(
            "TEST",
            "test/auth_test.cpp",
            "cpp"
        ));
        assert!(is_test_by_name_and_path(
            "TEST_F",
            "test/auth_test.cc",
            "cpp"
        ));
        assert!(is_test_by_name_and_path(
            "TEST_CASE",
            "test/auth.cpp",
            "cpp"
        ));
        assert!(is_test_by_name_and_path("SCENARIO", "test/auth.cpp", "cpp"));
        assert!(is_test_by_name_and_path(
            "testAuth",
            "src/auth_test.cpp",
            "cpp"
        ));
        assert!(!is_test_by_name_and_path("main", "src/auth.cpp", "cpp"));
    }

    #[test]
    fn test_is_test_by_name_and_path_c() {
        assert!(is_test_by_name_and_path(
            "test_auth",
            "test/test_auth.c",
            "c"
        ));
        assert!(is_test_by_name_and_path(
            "test_parse",
            "src/parse_test.c",
            "c"
        ));
        assert!(!is_test_by_name_and_path("main", "src/auth.c", "c"));
    }

    #[test]
    fn test_is_test_by_name_and_path_cuda() {
        assert!(is_test_by_name_and_path(
            "TEST",
            "test/kernel_test.cu",
            "cuda"
        ));
        assert!(is_test_by_name_and_path("TEST_F", "test/kernel.cu", "cuda"));
        assert!(!is_test_by_name_and_path(
            "launch_kernel",
            "src/kernel.cu",
            "cuda"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_clojure() {
        assert!(is_test_by_name_and_path(
            "deftest",
            "test/auth_test.clj",
            "clojure"
        ));
        assert!(is_test_by_name_and_path(
            "my-test",
            "test/core_test.cljc",
            "clojure"
        ));
        assert!(!is_test_by_name_and_path(
            "handler",
            "src/auth.clj",
            "clojure"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_elm() {
        assert!(is_test_by_name_and_path(
            "describe",
            "tests/AuthTest.elm",
            "elm"
        ));
        assert!(is_test_by_name_and_path("test", "tests/Suite.elm", "elm"));
        assert!(!is_test_by_name_and_path("view", "src/Auth.elm", "elm"));
    }

    #[test]
    fn test_is_test_by_name_and_path_commonlisp() {
        assert!(is_test_by_name_and_path(
            "test-auth",
            "test/auth-test.lisp",
            "commonlisp"
        ));
        assert!(is_test_by_name_and_path(
            "def-test",
            "tests/suite.lisp",
            "commonlisp"
        ));
        assert!(!is_test_by_name_and_path(
            "handle",
            "src/auth.lisp",
            "commonlisp"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_pascal() {
        assert!(is_test_by_name_and_path(
            "TestLogin",
            "tests/AuthTest.pas",
            "pascal"
        ));
        assert!(is_test_by_name_and_path(
            "TestCreate",
            "test/UserTests.pas",
            "pascal"
        ));
        assert!(!is_test_by_name_and_path(
            "HandleClick",
            "src/Auth.pas",
            "pascal"
        ));
    }

    #[test]
    fn test_is_test_by_name_and_path_unknown_language() {
        assert!(!is_test_by_name_and_path(
            "test",
            "test/foo.xxx",
            "unknown_lang"
        ));
    }

    #[test]
    fn test_renamed_function_produces_same_sig_hash() {
        let grammar = tree_sitter_python::LANGUAGE.into();
        let src_old = b"def calculate_order_total(items: list) -> float:\n    return sum(i[\"price\"] * i[\"quantity\"] for i in items)\n";
        let src_new = b"def compute_order_sum(items: list) -> float:\n    return sum(i[\"price\"] * i[\"quantity\"] for i in items)\n";

        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();

        let query = tree_sitter::Query::new(
            &grammar,
            "(function_definition name: (identifier) @func.name) @func.def",
        )
        .unwrap();

        let tree_old = parser.parse(src_old, None).unwrap();
        let syms_old = extract_entities("calc.py", src_old, tree_old.root_node(), &query, "python");
        assert_eq!(syms_old.len(), 1);

        let tree_new = parser.parse(src_new, None).unwrap();
        let syms_new = extract_entities("calc.py", src_new, tree_new.root_node(), &query, "python");
        assert_eq!(syms_new.len(), 1);

        assert_eq!(
            syms_old[0].signature_hash, syms_new[0].signature_hash,
            "Renamed function with identical body should produce same sig_hash.\n  old: {} ({})\n  new: {} ({})",
            syms_old[0].name, syms_old[0].signature_hash,
            syms_new[0].name, syms_new[0].signature_hash,
        );
        assert_ne!(syms_old[0].name, syms_new[0].name);
    }

    #[test]
    fn test_different_body_produces_different_sig_hash() {
        let grammar = tree_sitter_python::LANGUAGE.into();
        let src_a = b"def foo(x):\n    return x + 1\n";
        let src_b = b"def foo(x):\n    return x * 2\n";

        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();

        let query = tree_sitter::Query::new(
            &grammar,
            "(function_definition name: (identifier) @func.name) @func.def",
        )
        .unwrap();

        let tree_a = parser.parse(src_a, None).unwrap();
        let syms_a = extract_entities("a.py", src_a, tree_a.root_node(), &query, "python");

        let tree_b = parser.parse(src_b, None).unwrap();
        let syms_b = extract_entities("a.py", src_b, tree_b.root_node(), &query, "python");

        assert_ne!(
            syms_a[0].signature_hash, syms_b[0].signature_hash,
            "Functions with different bodies should have different sig_hash"
        );
    }
}