tldr-core 0.4.0

Core analysis engine for TLDR code analysis tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
//! Shared function finder utilities for locating functions in tree-sitter ASTs.
//!
//! This module provides the canonical implementations of function-finding logic
//! used across CFG, DFG, metrics, and quality modules. All languages supported
//! by tree-sitter grammars are handled here.

use crate::types::Language;
use tree_sitter::Node;

/// Helper to recursively search for function_definition inside a node (e.g., wrapped in function_call).
/// Searches up to `max_depth` levels deep to handle patterns like `socket.protect(function() end)`.
fn find_function_in_node<'a>(node: Node<'a>, max_depth: usize) -> Option<Node<'a>> {
    if max_depth == 0 {
        return None;
    }

    // Direct function_definition
    if node.kind() == "function_definition" {
        return Some(node);
    }

    // Recurse into children (especially for function_call -> arguments -> function_definition)
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if let Some(func) = find_function_in_node(child, max_depth - 1) {
            return Some(func);
        }
    }

    None
}

/// Find a function node by name in the AST.
///
/// Accepts either a bare function name (`run`) or a qualified
/// `Class.method` form (`Flask.run`). When a qualified name is supplied:
///
/// 1. The class is located first via [`find_class_node`].
/// 2. The method is searched within the class body.
/// 3. If the class is not found, the search falls back to the bare
///    method name (the segment after the final `.`). This preserves
///    backward compatibility when the user passes a dotted name that
///    does not actually correspond to a class scope (for example, the
///    Lua/Luau dot-indexed pattern `M.request` is handled directly by
///    the bare-name branch via the existing `dot_index_expression`
///    matching below).
///
/// For overloaded methods (rare in Python but common in Java, C++,
/// Kotlin, and Scala), the FIRST match wins. To disambiguate, callers
/// should resolve ambiguity by line range or signature at a higher
/// level — this function does not attempt overload resolution.
pub fn find_function_node<'a>(
    root: Node<'a>,
    function_name: &str,
    language: Language,
    source: &str,
) -> Option<Node<'a>> {
    // Qualified `Class.method` lookup — try class-scoped resolution first.
    // We deliberately skip this for Lua/Luau because their dot-indexed
    // function form (`function Kong.init() ... end`) is matched directly
    // by the bare-name branch below using `dot_index_expression`, and
    // there is no class node to descend into.
    if function_name.contains('.') && !matches!(language, Language::Lua | Language::Luau) {
        let parts: Vec<&str> = function_name.split('.').collect();
        // Multi-component: at least one class segment + final method name.
        // Take the FIRST segment as the class to scope into; the LAST
        // segment is the method name to look up inside the class body.
        // This handles both `Class.method` and deeper nestings like
        // `Outer.Inner.method` (we descend into the leftmost class and
        // recursively re-resolve `Inner.method` inside it).
        if parts.len() >= 2 {
            let class_name = parts[0];
            let remainder = parts[1..].join(".");
            if let Some(class_node) = find_class_node(root, class_name, language, source) {
                // Search inside the class body (or the class node itself if
                // the body field isn't present for this language).
                let scope = class_node
                    .child_by_field_name("body")
                    .unwrap_or(class_node);
                if let Some(found) =
                    find_function_node_in_subtree(scope, &remainder, language, source)
                {
                    return Some(found);
                }
            }
            // Fallback: class not found, or method not found inside class —
            // try resolving the LAST component as a bare name. This is the
            // documented graceful degradation behavior.
            let last = *parts.last().unwrap();
            return find_function_node_in_subtree(root, last, language, source);
        }
    }

    // context-file-func-cross-lang-and-cpp-qualified-v1 (P14.AGG14-3):
    // Accept C++ `Class::method` qualified names so that the 8 per-function
    // commands (`reaching-defs`, `available`, `dead-stores`, `slice`,
    // `taint`, `complexity`, `contracts`, `explain`) can resolve a function
    // by its fully-qualified out-of-class definition. The C++ extractor
    // stores the bare last segment (`Parse`) for both inline class methods
    // and out-of-class definitions, so first try a direct match on the
    // qualified form (in case the extractor returned a qualified name —
    // see `find_function_node_in_subtree` C/C++ branch below), then
    // descend into the class scope (covers inline definitions inside the
    // class body), and finally fall back to the bare last segment so a
    // call like `XMLDocument::Parse` still resolves to the out-of-class
    // `void XMLDocument::Parse(...)` definition.
    if function_name.contains("::")
        && matches!(language, Language::C | Language::Cpp)
    {
        // Try the full qualified form first — handles the (rare) case
        // where the extractor returned the qualified text verbatim.
        if let Some(found) = find_function_node_in_subtree(root, function_name, language, source)
        {
            return Some(found);
        }

        // p19-secondary-fixes-v1 (BUG-P19-04): cpp `XMLClass::ParseDeep`
        // overloads were previously all routed to the first `ParseDeep`
        // function in the file (XMLNode's). For out-of-class
        // definitions like `char* XMLText::ParseDeep(...)` the
        // declarator is a `qualified_identifier` whose full text is
        // `XMLText::ParseDeep`. Walk the file's `function_definition`
        // nodes and match by full qualified-identifier text BEFORE
        // falling back to the bare-name search. This disambiguates the
        // 7 ParseDeep overloads in tinyxml2.cpp.
        if let Some(found) =
            find_cpp_qualified_function_definition(root, function_name, source)
        {
            return Some(found);
        }

        let parts: Vec<&str> = function_name.split("::").collect();
        if parts.len() >= 2 {
            // class scope resolution: e.g. XMLDocument::Parse
            let class_name = parts[0];
            let remainder = parts[1..].join("::");
            if let Some(class_node) = find_class_node(root, class_name, language, source) {
                let scope = class_node
                    .child_by_field_name("body")
                    .unwrap_or(class_node);
                if let Some(found) =
                    find_function_node_in_subtree(scope, &remainder, language, source)
                {
                    return Some(found);
                }
            }
            // Graceful fallback: bare last segment (e.g. `Parse`).
            // This is what tinyxml2.cpp's out-of-class definitions are
            // stored as in the AST — `void XMLDocument::Parse() {...}`
            // appears as `function_definition` with declarator
            // `qualified_identifier`, and our extractor returns the
            // rightmost identifier (`Parse`) for both lookup and storage.
            let last = *parts.last().unwrap();
            return find_function_node_in_subtree(root, last, language, source);
        }
    }

    find_function_node_in_subtree(root, function_name, language, source)
}

/// p19-secondary-fixes-v1 (BUG-P19-04): find a C/C++ `function_definition`
/// whose `declarator` carries the exact qualified name `Class::method`
/// (e.g. `XMLText::ParseDeep`). The 7 `ParseDeep` overloads in
/// tinyxml2.cpp all share the same bare name, so the bare-name search
/// can only return the first; this resolver matches the full qualified
/// text to disambiguate.
fn find_cpp_qualified_function_definition<'a>(
    root: Node<'a>,
    qualified_name: &str,
    source: &str,
) -> Option<Node<'a>> {
    // BFS / pre-order traversal so that the FIRST matching definition in
    // source order is returned (matters when a name has multiple
    // overloads like `XMLDocument::Parse(xml, nBytes)` followed by
    // `XMLDocument::Parse()` — bare-name fallback historically returned
    // the first overload, and we preserve that behavior for callers
    // whose `Class::method` is not arity-specific).
    let mut queue: std::collections::VecDeque<Node> =
        std::collections::VecDeque::new();
    queue.push_back(root);
    while let Some(node) = queue.pop_front() {
        if node.kind() == "function_definition" {
            if let Some(declarator) = node.child_by_field_name("declarator") {
                if let Some(inner) = peel_to_function_declarator(declarator) {
                    if let Some(decl_name) = inner.child_by_field_name("declarator") {
                        if decl_name.kind() == "qualified_identifier" {
                            let text = decl_name
                                .utf8_text(source.as_bytes())
                                .unwrap_or("")
                                .trim();
                            if text == qualified_name {
                                return Some(node);
                            }
                        }
                    }
                }
            }
        }
        let mut cursor = node.walk();
        if cursor.goto_first_child() {
            loop {
                queue.push_back(cursor.node());
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
        }
    }
    None
}

/// Peel through pointer / reference / parenthesized declarator wrappers
/// to expose the inner `function_declarator`. Returns None if no
/// `function_declarator` is reachable.
fn peel_to_function_declarator(node: Node) -> Option<Node> {
    match node.kind() {
        "function_declarator" => Some(node),
        "pointer_declarator" | "reference_declarator" | "parenthesized_declarator" => {
            let inner = node.child_by_field_name("declarator")?;
            peel_to_function_declarator(inner)
        }
        _ => None,
    }
}

/// Internal: original bare-name function lookup. Splitting this out lets
/// `find_function_node` first try `Class.method` resolution and then
/// delegate the per-name search either to the full AST (bare-name) or
/// to a class body subtree (qualified).
fn find_function_node_in_subtree<'a>(
    root: Node<'a>,
    function_name: &str,
    language: Language,
    source: &str,
) -> Option<Node<'a>> {
    let func_kinds = get_function_node_kinds(language);

    let mut stack = vec![root];

    while let Some(node) = stack.pop() {
        // Check direct function nodes
        if func_kinds.contains(&node.kind()) {
            if let Some(name) = get_function_name(node, language, source) {
                if name == function_name
                    || name
                        .strip_prefix('#')
                        .is_some_and(|stripped| stripped == function_name)
                    // Lua/Luau: match short name for dot-indexed functions
                    // e.g. "Kong.init" matches search for "init"
                    || (matches!(language, Language::Lua | Language::Luau)
                        && name.contains('.')
                        && name
                            .rsplit('.')
                            .next()
                            .is_some_and(|short| short == function_name))
                {
                    return Some(node);
                }
            }
        }

        // Check for variable declarations with arrow functions (TypeScript/JavaScript pattern)
        // Pattern: const foo = () => {}  or  const foo = function() {}
        if matches!(language, Language::TypeScript | Language::JavaScript)
            && matches!(node.kind(), "lexical_declaration" | "variable_declaration")
        {
            let mut child_cursor = node.walk();
            for child in node.children(&mut child_cursor) {
                if child.kind() == "variable_declarator" {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        let var_name = name_node.utf8_text(source.as_bytes()).unwrap_or("");
                        if var_name == function_name {
                            // Check if the value is a function
                            if let Some(value_node) = child.child_by_field_name("value") {
                                if matches!(
                                    value_node.kind(),
                                    "arrow_function"
                                        | "function"
                                        | "function_expression"
                                        | "generator_function"
                                ) {
                                    return Some(value_node);
                                }
                            }
                        }
                    }
                }
            }
        }

        // (js-extract-function-expressions-v1) JS/TS assignment-based functions:
        //   app.use = function() {}
        //   Foo.prototype.bar = function() {}
        //   handler = () => {}
        //   { foo: function() {} } / { foo: () => {} } / { foo() {} }
        if matches!(language, Language::TypeScript | Language::JavaScript) {
            // Pattern A: assignment_expression — handle directly here. Look at
            // the LHS to extract the target name and the RHS to find the
            // function-like value.
            if node.kind() == "assignment_expression" {
                let left = node.child_by_field_name("left");
                let right = node.child_by_field_name("right");
                if let (Some(left), Some(right)) = (left, right) {
                    let matches_name = match left.kind() {
                        "identifier" => {
                            left.utf8_text(source.as_bytes()).unwrap_or("") == function_name
                        }
                        "member_expression" => {
                            // app.use → match "use"; Foo.prototype.bar → match "bar"
                            match left.child_by_field_name("property") {
                                Some(p) => {
                                    p.utf8_text(source.as_bytes()).unwrap_or("") == function_name
                                }
                                None => false,
                            }
                        }
                        _ => false,
                    };
                    if matches_name
                        && matches!(
                            right.kind(),
                            "arrow_function"
                                | "function_expression"
                                | "function"
                                | "generator_function"
                        )
                    {
                        return Some(right);
                    }
                }
            }

            // Pattern B: object literal pair — `{ foo: function() {} }`
            if node.kind() == "pair" {
                if let (Some(key), Some(value)) = (
                    node.child_by_field_name("key"),
                    node.child_by_field_name("value"),
                ) {
                    let key_name = match key.kind() {
                        "property_identifier" | "identifier" => {
                            key.utf8_text(source.as_bytes()).unwrap_or("").to_string()
                        }
                        "string" => key
                            .utf8_text(source.as_bytes())
                            .unwrap_or("")
                            .trim_matches(|c| c == '"' || c == '\'' || c == '`')
                            .to_string(),
                        _ => String::new(),
                    };
                    if key_name == function_name
                        && matches!(
                            value.kind(),
                            "arrow_function"
                                | "function_expression"
                                | "function"
                                | "generator_function"
                        )
                    {
                        return Some(value);
                    }
                }
            }

            // Pattern C: object literal method shorthand — `{ foo() {} }`.
            // tree-sitter emits `method_definition` even outside class bodies;
            // it's handled by the generic kind-match above only when
            // method_definition is in `func_kinds`. JS/TS already includes it,
            // so the existing match covers this case.
        }

        // Check for Lua/Luau assignment-based functions: M.request = function() end
        if matches!(language, Language::Lua | Language::Luau)
            && matches!(node.kind(), "assignment_statement" | "variable_assignment")
        {
            let mut child_cursor = node.walk();
            let children: Vec<_> = node.children(&mut child_cursor).collect();
            // Look for field_expression or dot_index_expression on LHS, function on RHS
            for child in &children {
                if matches!(child.kind(), "variable_list" | "assignment_variable_list") {
                    let mut inner_cursor = child.walk();
                    for inner in child.children(&mut inner_cursor) {
                        if matches!(inner.kind(), "field_expression" | "dot_index_expression") {
                            let lhs_text = inner.utf8_text(source.as_bytes()).unwrap_or("");
                            // Check if the field name matches (e.g. "M.request" -> "request")
                            if let Some(field_name) = lhs_text.rsplit('.').next() {
                                if field_name == function_name || lhs_text == function_name {
                                    // Find function_definition in RHS (handles both direct and wrapped)
                                    for rhs in &children {
                                        if matches!(
                                            rhs.kind(),
                                            "expression_list" | "assignment_expression_list"
                                        ) {
                                            let mut rhs_cursor = rhs.walk();
                                            for rhs_child in rhs.children(&mut rhs_cursor) {
                                                if let Some(func) =
                                                    find_function_in_node(rhs_child, 3)
                                                {
                                                    return Some(func);
                                                }
                                            }
                                        }
                                        if let Some(func) = find_function_in_node(*rhs, 3) {
                                            return Some(func);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // Add children to stack (reverse order for depth-first)
        let mut cursor = node.walk();
        let children: Vec<_> = node.children(&mut cursor).collect();
        for child in children.into_iter().rev() {
            stack.push(child);
        }
    }

    None
}

/// Get the node kinds that represent functions in each language
pub fn get_function_node_kinds(language: Language) -> &'static [&'static str] {
    match language {
        Language::Python => &["function_definition"],
        Language::TypeScript | Language::JavaScript => &[
            "function_declaration",
            "arrow_function",
            "method_definition",
            "function",
            "generator_function_declaration",
            "generator_function",
        ],
        Language::Go => &["function_declaration", "method_declaration"],
        Language::Rust => &["function_item"],
        Language::Java => &["method_declaration", "constructor_declaration"],
        Language::C | Language::Cpp => &["function_definition"],
        Language::Ruby => &["method", "singleton_method"],
        Language::Php => &["function_definition", "method_declaration"],
        Language::CSharp => &["method_declaration", "constructor_declaration"],
        Language::Kotlin => &["function_declaration"],
        Language::Scala => &["function_definition", "function_declaration"],
        Language::Elixir => &["call"], // Elixir uses def/defp which are calls
        Language::Lua | Language::Luau => &[
            "function_declaration",
            "function_definition",
            "local_function",
        ],
        Language::Swift => &["function_declaration", "init_declaration"],
        Language::Ocaml => &["let_binding", "value_definition"],
    }
}

/// Get the node kinds that represent classes/structs/objects/traits in
/// each language. Used by [`find_class_node`] to scope qualified
/// `Class.method` lookups.
///
/// The selection is intentionally broad: anything that can act as a
/// container of methods is included (classes, structs with methods,
/// interfaces, traits, impls, enums with methods, objects, modules with
/// member functions). Languages where there is no dedicated class node
/// (C, OCaml, Elixir, Lua/Luau) return an empty slice — qualified
/// lookups for those languages will fall back to the bare-name search.
pub fn get_class_node_kinds(language: Language) -> &'static [&'static str] {
    match language {
        Language::Python => &["class_definition"],
        Language::TypeScript | Language::JavaScript => {
            &["class_declaration", "class", "interface_declaration"]
        }
        Language::Go => &["type_declaration"],
        Language::Rust => &[
            "struct_item",
            "enum_item",
            "trait_item",
            "impl_item",
            "union_item",
        ],
        Language::Java => &[
            "class_declaration",
            "interface_declaration",
            "enum_declaration",
            "record_declaration",
        ],
        Language::Cpp => &[
            "class_specifier",
            "struct_specifier",
            "union_specifier",
        ],
        Language::C => &[],
        Language::Ruby => &["class", "module"],
        Language::Php => &[
            "class_declaration",
            "interface_declaration",
            "trait_declaration",
            "enum_declaration",
        ],
        Language::CSharp => &[
            "class_declaration",
            "struct_declaration",
            "interface_declaration",
            "record_declaration",
            "enum_declaration",
        ],
        Language::Kotlin => &["class_declaration", "object_declaration"],
        Language::Scala => &[
            "class_definition",
            "object_definition",
            "trait_definition",
        ],
        // No class container in these languages (Elixir uses defmodule but
        // the resolver here doesn't model it; Lua/Luau dotted names are
        // handled directly in the bare-name branch).
        Language::Elixir | Language::Lua | Language::Luau | Language::Ocaml => &[],
        Language::Swift => &[
            "class_declaration",
            "protocol_declaration",
            "extension_declaration",
        ],
    }
}

/// Find a class/struct/trait node by name in the AST.
///
/// Walks the tree depth-first and returns the FIRST node whose kind is
/// in [`get_class_node_kinds`] and whose name matches `class_name`. If
/// the language has no class node kinds (e.g. C, Lua), returns `None`
/// immediately.
pub fn find_class_node<'a>(
    root: Node<'a>,
    class_name: &str,
    language: Language,
    source: &str,
) -> Option<Node<'a>> {
    let class_kinds = get_class_node_kinds(language);
    if class_kinds.is_empty() {
        return None;
    }

    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if class_kinds.contains(&node.kind()) {
            // Try the standard "name" field (Python, TS/JS, Java, Kotlin,
            // Scala, Swift, Ruby, PHP, C#).
            if let Some(name_node) = node.child_by_field_name("name") {
                let name = name_node.utf8_text(source.as_bytes()).unwrap_or("");
                if name == class_name {
                    return Some(node);
                }
            } else {
                // Fallback: scan named children for an identifier-shaped
                // name node (covers grammars where the name isn't
                // exposed as a field, e.g. Rust struct/enum/trait/impl
                // and C++ class/struct specifiers).
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    if matches!(
                        child.kind(),
                        "identifier"
                            | "type_identifier"
                            | "constant"
                            | "scoped_type_identifier"
                    ) {
                        let name = child.utf8_text(source.as_bytes()).unwrap_or("");
                        // For Rust impl_item the type_identifier IS the
                        // class-equivalent name. For scoped names, only
                        // exact match counts.
                        if name == class_name {
                            return Some(node);
                        }
                        break;
                    }
                }
            }
        }

        let mut cursor = node.walk();
        let children: Vec<_> = node.children(&mut cursor).collect();
        for child in children.into_iter().rev() {
            stack.push(child);
        }
    }

    None
}

/// Recursively extract the function name from a C/C++ declarator chain.
/// Handles: function_declarator, pointer_declarator, parenthesized_declarator,
/// identifier, field_identifier, qualified_identifier, destructor_name,
/// template_function.
fn extract_c_declarator_name(declarator: Node, source: &str) -> Option<String> {
    match declarator.kind() {
        "identifier" | "field_identifier" => {
            // field_identifier is used for methods defined inline in class bodies
            Some(
                declarator
                    .utf8_text(source.as_bytes())
                    .unwrap_or("")
                    .to_string(),
            )
        }
        "destructor_name" => {
            // ~ClassName - return as-is
            Some(
                declarator
                    .utf8_text(source.as_bytes())
                    .unwrap_or("")
                    .to_string(),
            )
        }
        "qualified_identifier" => {
            // C++ qualified name: Namespace::Class::method
            // Tree-sitter nests these recursively:
            //   qualified_identifier(Luau::Analysis::Normalizer::normalize)
            //     -> namespace_identifier(Luau), qualified_identifier(Analysis::...)
            //       -> ... -> identifier(normalize)
            // We need to find the deepest rightmost identifier.
            let mut cursor = declarator.walk();
            for child in declarator.children(&mut cursor) {
                // If there's a nested qualified_identifier, recurse into it
                if child.kind() == "qualified_identifier" {
                    return extract_c_declarator_name(child, source);
                }
            }
            // No nested qualified_identifier: look for terminal name nodes
            let mut cursor2 = declarator.walk();
            for child in declarator.children(&mut cursor2) {
                if matches!(child.kind(), "identifier" | "destructor_name") {
                    return Some(child.utf8_text(source.as_bytes()).unwrap_or("").to_string());
                }
                if child.kind() == "template_function" {
                    return child
                        .child_by_field_name("name")
                        .or_else(|| child.named_child(0))
                        .map(|n| n.utf8_text(source.as_bytes()).unwrap_or("").to_string());
                }
            }
            None
        }
        "template_function" => {
            // template<T> void foo() - extract identifier from template_function
            declarator
                .child_by_field_name("name")
                .or_else(|| declarator.named_child(0))
                .map(|n| n.utf8_text(source.as_bytes()).unwrap_or("").to_string())
        }
        "function_declarator" => {
            // function_declarator has a "declarator" field which is the name (identifier)
            if let Some(inner) = declarator.child_by_field_name("declarator") {
                return extract_c_declarator_name(inner, source);
            }
            None
        }
        "pointer_declarator" | "reference_declarator" => {
            // pointer_declarator wraps: * <inner_declarator>
            // reference_declarator wraps: & <inner_declarator>
            if let Some(inner) = declarator.child_by_field_name("declarator") {
                return extract_c_declarator_name(inner, source);
            }
            // Fallback: search children for function_declarator or identifier
            let mut cursor = declarator.walk();
            for child in declarator.children(&mut cursor) {
                if matches!(
                    child.kind(),
                    "function_declarator" | "identifier" | "field_identifier"
                ) {
                    return extract_c_declarator_name(child, source);
                }
            }
            None
        }
        "parenthesized_declarator" => {
            // parenthesized_declarator wraps: ( <inner_declarator> )
            let mut cursor = declarator.walk();
            for child in declarator.children(&mut cursor) {
                if child.is_named() {
                    if let Some(name) = extract_c_declarator_name(child, source) {
                        return Some(name);
                    }
                }
            }
            None
        }
        _ => None,
    }
}

/// Extract function name from a function node
pub fn get_function_name(node: Node, language: Language, source: &str) -> Option<String> {
    match language {
        Language::C | Language::Cpp => {
            // C/C++: function_definition -> declarator -> ... -> identifier
            // The declarator chain can be:
            //   function_declarator -> identifier (simple: int foo())
            //   pointer_declarator -> function_declarator -> identifier (pointer return: int *foo())
            //   identifier (rare, no parens)
            if let Some(declarator) = node.child_by_field_name("declarator") {
                return extract_c_declarator_name(declarator, source);
            }
            None
        }
        Language::Ruby => {
            // Ruby: method node has "name" field
            node.child_by_field_name("name")
                .map(|n| n.utf8_text(source.as_bytes()).unwrap_or("").to_string())
        }
        Language::Php => {
            // PHP function_definition has "name" field
            node.child_by_field_name("name")
                .map(|n| n.utf8_text(source.as_bytes()).unwrap_or("").to_string())
        }
        Language::Elixir => {
            // Elixir: def/defp are calls. The first argument after "def" is the function clause.
            //
            // Structure (no guard):
            //   (call (identifier "def") (arguments (call (identifier "func_name") ...)))
            //
            // Structure (with guard):
            //   (call (identifier "def")
            //         (arguments (binary_operator
            //                        left:  (call (identifier "func_name") ...)
            //                        op:    "when"
            //                        right: (guard expr))
            //                    (do_block ...)))
            //
            // The DFG used to miss the guarded form because it only looked
            // for `call`/`identifier` immediately under `arguments`. When the
            // function clause is wrapped in a `binary_operator` for a `when`
            // guard, the function-name `call` is the left child of the
            // binary_operator, not a direct child of `arguments`.
            // (P11.BUG-AGG-16)
            if node.kind() == "call" {
                // First child should be "def" or "defp"
                let first_child = node.child(0)?;
                let first_text = first_child.utf8_text(source.as_bytes()).unwrap_or("");
                if first_text == "def" || first_text == "defp" {
                    // Second child: arguments containing the function name
                    if let Some(args) = node.child(1) {
                        // Could be directly an identifier or a call node
                        if args.kind() == "identifier" {
                            return Some(
                                args.utf8_text(source.as_bytes()).unwrap_or("").to_string(),
                            );
                        }
                        if args.kind() == "arguments" || args.kind() == "call" {
                            // Find the first identifier or descend through
                            // `binary_operator` for guard clauses.
                            let mut cursor = args.walk();
                            for child in args.children(&mut cursor) {
                                if child.kind() == "identifier" {
                                    return Some(
                                        child
                                            .utf8_text(source.as_bytes())
                                            .unwrap_or("")
                                            .to_string(),
                                    );
                                }
                                if child.kind() == "call" {
                                    if let Some(name) = child.child(0) {
                                        if name.kind() == "identifier" {
                                            return Some(
                                                name.utf8_text(source.as_bytes())
                                                    .unwrap_or("")
                                                    .to_string(),
                                            );
                                        }
                                    }
                                }
                                // Guard clause: descend into binary_operator's
                                // left child to recover the function name.
                                if child.kind() == "binary_operator" {
                                    let mut bin_cursor = child.walk();
                                    for bin_child in child.children(&mut bin_cursor) {
                                        if bin_child.kind() == "call" {
                                            if let Some(name) = bin_child.child(0) {
                                                if name.kind() == "identifier" {
                                                    return Some(
                                                        name.utf8_text(source.as_bytes())
                                                            .unwrap_or("")
                                                            .to_string(),
                                                    );
                                                }
                                            }
                                        }
                                        if bin_child.kind() == "identifier" {
                                            // `def func_name when guard` (no args)
                                            // is rare but the LHS may be a bare
                                            // identifier.
                                            return Some(
                                                bin_child
                                                    .utf8_text(source.as_bytes())
                                                    .unwrap_or("")
                                                    .to_string(),
                                            );
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                None
            } else {
                None
            }
        }
        Language::Ocaml => {
            // OCaml: let_binding has "pattern" field (not "name")
            // Structure: (let_binding pattern: (value_name) body: ...)
            // For value_definition, it wraps let_binding(s)
            if node.kind() == "value_definition" {
                // Find the first let_binding child and recurse
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    if child.kind() == "let_binding" {
                        return get_function_name(child, language, source);
                    }
                }
                None
            } else {
                // let_binding: pattern field contains the name
                node.child_by_field_name("pattern")
                    .map(|n| n.utf8_text(source.as_bytes()).unwrap_or("").to_string())
            }
        }
        Language::Swift => {
            // Swift: function_declaration has "name" field, but init_declaration does not --
            // the keyword "init" IS the name.
            if node.kind() == "init_declaration" {
                return Some("init".to_string());
            }
            node.child_by_field_name("name")
                .map(|n| n.utf8_text(source.as_bytes()).unwrap_or("").to_string())
        }
        Language::Lua | Language::Luau => {
            // Lua/Luau: function_declaration may have a dot_index_expression as name
            // e.g. function Kong.init() -> name is dot_index_expression "Kong.init"
            if let Some(name_node) = node.child_by_field_name("name") {
                let name_text = name_node
                    .utf8_text(source.as_bytes())
                    .unwrap_or("")
                    .to_string();
                return Some(name_text);
            }
            // Fallback for local_function or other variants: search named children
            // for identifier or dot_index_expression
            if node.kind() == "local_function" || node.kind() == "function_declaration" {
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    if matches!(child.kind(), "identifier" | "dot_index_expression") {
                        return Some(child.utf8_text(source.as_bytes()).unwrap_or("").to_string());
                    }
                }
            }
            // For function_definition (anonymous), no name
            None
        }
        _ => {
            // Most languages use "name" field
            node.child_by_field_name("name")
                .map(|n| n.utf8_text(source.as_bytes()).unwrap_or("").to_string())
        }
    }
}

/// Get the body node of a function
pub fn get_function_body(func_node: Node, language: Language) -> Option<Node> {
    match language {
        Language::Python => func_node.child_by_field_name("body"),
        Language::TypeScript | Language::JavaScript => func_node.child_by_field_name("body"),
        Language::Go => func_node.child_by_field_name("body"),
        Language::Rust => func_node.child_by_field_name("body"),
        Language::Java => func_node.child_by_field_name("body"),
        Language::C | Language::Cpp => func_node.child_by_field_name("body"),
        Language::Ruby => func_node.child_by_field_name("body"),
        Language::Php => func_node.child_by_field_name("body"),
        Language::CSharp => func_node.child_by_field_name("body"),
        Language::Kotlin => {
            // Kotlin: function_declaration has function_body as a named child (not a field).
            // function_body contains a block with the actual statements.
            func_node.child_by_field_name("body").or_else(|| {
                let mut cursor = func_node.walk();
                for child in func_node.children(&mut cursor) {
                    if child.kind() == "function_body" {
                        // function_body may contain a block or a direct expression
                        let mut inner = child.walk();
                        for inner_child in child.children(&mut inner) {
                            if inner_child.kind() == "block" {
                                return Some(inner_child);
                            }
                        }
                        return Some(child);
                    }
                }
                None
            })
        }
        Language::Scala => func_node.child_by_field_name("body"),
        Language::Elixir => {
            // Elixir def body is inside a "do" block
            // Structure: (call "def" (arguments ...) (do_block (body)))
            let mut cursor = func_node.walk();
            for child in func_node.children(&mut cursor) {
                if child.kind() == "do_block" {
                    return Some(child);
                }
            }
            func_node.child_by_field_name("body")
        }
        Language::Lua | Language::Luau => func_node.child_by_field_name("body"),
        Language::Ocaml => {
            // OCaml: func_node may be value_definition or let_binding.
            // For value_definition, drill down to let_binding first.
            // For let_binding, the body field contains the expression.
            if func_node.kind() == "value_definition" {
                // Find let_binding child, then get its body
                let child_count = func_node.child_count();
                let mut binding_body = None;
                for i in 0..child_count {
                    if let Some(child) = func_node.child(i) {
                        if child.kind() == "let_binding" {
                            binding_body = child.child_by_field_name("body");
                            break;
                        }
                    }
                }
                binding_body.or(Some(func_node))
            } else {
                // Already a let_binding
                func_node.child_by_field_name("body").or(Some(func_node))
            }
        }
        _ => func_node.child_by_field_name("body"),
    }
}

/// Convenience: get function node kinds as a Vec (for callers that need Vec<&'static str>)
pub fn get_function_node_kinds_vec(language: Language) -> Vec<&'static str> {
    get_function_node_kinds(language).to_vec()
}

/// Resolve the (start_line, end_line) bounds of a function in a parsed source.
///
/// Used by chop/slice to surface a meaningful range in `LineOutsideFunction`
/// errors instead of leaking the `u32::MAX` sentinel that previously rendered
/// as `lines 1-4294967295` in user-facing messages
/// (pdg-bounds-and-stdout-hygiene-v1, P11.BUG-AGG-5).
///
/// Returns:
/// - `Some((start, end))` if the function is found in the parsed tree. Both
///   line numbers are 1-indexed and inclusive of the function's first and
///   last source lines (signature through closing brace / `end` keyword).
/// - `None` if the function cannot be located. Callers MUST treat this as a
///   distinct case from "found but line is outside" — emit a clear "could not
///   determine function bounds" message rather than a fabricated range.
pub fn find_function_bounds(
    source: &str,
    function_name: &str,
    language: Language,
) -> Option<(u32, u32)> {
    let tree = crate::ast::parser::parse(source, language).ok()?;
    let root = tree.root_node();
    let node = find_function_node(root, function_name, language, source)?;
    let start = node.start_position().row as u32 + 1;
    let end = node.end_position().row as u32 + 1;
    if end < start {
        return None;
    }
    Some((start, end))
}

/// File-aware variant of [`find_function_bounds`] that accepts either a
/// path to a source file or a raw source string. Mirrors the
/// `source_or_path` convention used by `get_cfg_context`/`get_pdg_context`.
pub fn find_function_bounds_from_path_or_source(
    source_or_path: &str,
    function_name: &str,
    language: Language,
) -> Option<(u32, u32)> {
    let source = if std::path::Path::new(source_or_path).exists() {
        std::fs::read_to_string(source_or_path).ok()?
    } else {
        source_or_path.to_string()
    };
    find_function_bounds(&source, function_name, language)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::parser::parse;

    // -- TypeScript generator function tests --

    #[test]
    fn test_ts_generator_function_declaration() {
        let source = r#"
function* genNumbers(): Generator<number> {
    yield 1;
    yield 2;
    yield 3;
}
"#;
        let tree = parse(source, Language::TypeScript).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "genNumbers", Language::TypeScript, source);
        assert!(node.is_some(), "Should find generator function declaration");
        let node = node.unwrap();
        assert_eq!(node.kind(), "generator_function_declaration");
        let name = get_function_name(node, Language::TypeScript, source);
        assert_eq!(name.as_deref(), Some("genNumbers"));
        let body = get_function_body(node, Language::TypeScript);
        assert!(body.is_some(), "Should find body of generator function");
    }

    #[test]
    fn test_ts_async_generator_function() {
        let source = r#"
async function* asyncGen(): AsyncGenerator<string> {
    yield "hello";
    yield "world";
}
"#;
        let tree = parse(source, Language::TypeScript).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "asyncGen", Language::TypeScript, source);
        assert!(
            node.is_some(),
            "Should find async generator function declaration"
        );
        let node = node.unwrap();
        assert_eq!(node.kind(), "generator_function_declaration");
        let name = get_function_name(node, Language::TypeScript, source);
        assert_eq!(name.as_deref(), Some("asyncGen"));
    }

    #[test]
    fn test_ts_generator_function_expression() {
        let source = r#"
const genArrow = function*(x: number): Generator<number> {
    yield x;
};
"#;
        let tree = parse(source, Language::TypeScript).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "genArrow", Language::TypeScript, source);
        assert!(
            node.is_some(),
            "Should find generator function expression via const assignment"
        );
        let node = node.unwrap();
        assert_eq!(node.kind(), "generator_function");
        let body = get_function_body(node, Language::TypeScript);
        assert!(
            body.is_some(),
            "Should find body of generator function expression"
        );
    }

    // -- JavaScript generator function tests --

    #[test]
    fn test_js_generator_function_declaration() {
        let source = r#"
function* genNumbers() {
    yield 1;
    yield 2;
}
"#;
        let tree = parse(source, Language::JavaScript).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "genNumbers", Language::JavaScript, source);
        assert!(
            node.is_some(),
            "Should find JS generator function declaration"
        );
        let node = node.unwrap();
        assert_eq!(node.kind(), "generator_function_declaration");
    }

    #[test]
    fn test_js_async_generator_function() {
        let source = r#"
async function* asyncIter() {
    yield "a";
    yield "b";
}
"#;
        let tree = parse(source, Language::JavaScript).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "asyncIter", Language::JavaScript, source);
        assert!(node.is_some(), "Should find JS async generator function");
    }

    // -- TypeScript regular function tests (regression) --

    #[test]
    fn test_ts_regular_function() {
        let source = r#"
function greet(name: string): string {
    const greeting = "Hello, " + name;
    return greeting;
}
"#;
        let tree = parse(source, Language::TypeScript).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "greet", Language::TypeScript, source);
        assert!(node.is_some(), "Should find regular function declaration");
        assert_eq!(node.unwrap().kind(), "function_declaration");
    }

    #[test]
    fn test_ts_arrow_function() {
        let source = r#"
const add = (a: number, b: number): number => {
    return a + b;
};
"#;
        let tree = parse(source, Language::TypeScript).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "add", Language::TypeScript, source);
        assert!(node.is_some(), "Should find arrow function via const");
        assert_eq!(node.unwrap().kind(), "arrow_function");
    }

    #[test]
    fn test_ts_class_method() {
        let source = r#"
class MyClass {
    myMethod(x: number): number {
        return x * 2;
    }
}
"#;
        let tree = parse(source, Language::TypeScript).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "myMethod", Language::TypeScript, source);
        assert!(node.is_some(), "Should find class method");
        assert_eq!(node.unwrap().kind(), "method_definition");
    }

    #[test]
    fn test_ts_exported_function() {
        let source = r#"
export function fetchData(url: string): Promise<string> {
    return fetch(url).then(r => r.text());
}
"#;
        let tree = parse(source, Language::TypeScript).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "fetchData", Language::TypeScript, source);
        assert!(node.is_some(), "Should find exported function");
    }

    #[test]
    fn test_ts_exported_generator() {
        let source = r#"
export function* items(): Generator<number> {
    yield 1;
    yield 2;
}
"#;
        let tree = parse(source, Language::TypeScript).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "items", Language::TypeScript, source);
        assert!(node.is_some(), "Should find exported generator function");
    }

    // -- DFG integration tests for generator functions --

    #[test]
    fn test_ts_generator_dfg() {
        use crate::dfg::get_dfg_context;
        let source = r#"
function* genNumbers(): Generator<number> {
    const x = 1;
    yield x;
    const y = 2;
    yield y;
}
"#;
        let result = get_dfg_context(source, "genNumbers", Language::TypeScript);
        assert!(
            result.is_ok(),
            "DFG should succeed for generator functions, got: {:?}",
            result.err()
        );
        let dfg = result.unwrap();
        assert_eq!(dfg.function, "genNumbers");
        assert!(
            !dfg.variables.is_empty(),
            "Should find variables in generator function"
        );
    }

    #[test]
    fn test_ts_async_generator_dfg() {
        use crate::dfg::get_dfg_context;
        let source = r#"
async function* asyncGen(): AsyncGenerator<string> {
    const msg = "hello";
    yield msg;
}
"#;
        let result = get_dfg_context(source, "asyncGen", Language::TypeScript);
        assert!(
            result.is_ok(),
            "DFG should succeed for async generator functions, got: {:?}",
            result.err()
        );
    }

    // -- CFG integration tests for generator functions --

    #[test]
    fn test_ts_generator_cfg() {
        use crate::cfg::get_cfg_context;
        let source = r#"
function* genNumbers(): Generator<number> {
    const x = 1;
    yield x;
}
"#;
        let result = get_cfg_context(source, "genNumbers", Language::TypeScript);
        assert!(result.is_ok());
        let cfg = result.unwrap();
        assert_eq!(cfg.function, "genNumbers");
        assert!(
            !cfg.blocks.is_empty(),
            "CFG should have blocks for generator function"
        );
    }

    // -- get_function_node_kinds tests --

    #[test]
    fn test_ts_node_kinds_include_generators() {
        let kinds = get_function_node_kinds(Language::TypeScript);
        assert!(
            kinds.contains(&"generator_function_declaration"),
            "TypeScript node kinds should include generator_function_declaration"
        );
        assert!(
            kinds.contains(&"generator_function"),
            "TypeScript node kinds should include generator_function"
        );
    }

    #[test]
    fn test_js_node_kinds_include_generators() {
        let kinds = get_function_node_kinds(Language::JavaScript);
        assert!(
            kinds.contains(&"generator_function_declaration"),
            "JavaScript node kinds should include generator_function_declaration"
        );
        assert!(
            kinds.contains(&"generator_function"),
            "JavaScript node kinds should include generator_function"
        );
    }

    // -- C pointer-returning function tests --

    #[test]
    fn test_c_pointer_returning_function() {
        let source = r#"
typedef struct { int x; } MyStruct;

MyStruct *createStruct(void) {
    int y = 1;
    return (MyStruct*)0;
}
"#;
        let tree = parse(source, Language::C).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "createStruct", Language::C, source);
        assert!(
            node.is_some(),
            "Should find C function with pointer return type"
        );
        let node = node.unwrap();
        assert_eq!(node.kind(), "function_definition");
        let name = get_function_name(node, Language::C, source);
        assert_eq!(name.as_deref(), Some("createStruct"));
    }

    #[test]
    fn test_c_pointer_returning_function_dfg() {
        use crate::dfg::get_dfg_context;
        let source = r#"
typedef struct { int x; } MyStruct;

MyStruct *createStruct(int val) {
    int y = val + 1;
    return (MyStruct*)0;
}
"#;
        let result = get_dfg_context(source, "createStruct", Language::C);
        assert!(
            result.is_ok(),
            "DFG should succeed for C pointer-returning function, got: {:?}",
            result.err()
        );
        let dfg = result.unwrap();
        assert_eq!(dfg.function, "createStruct");
    }

    #[test]
    fn test_cpp_pointer_returning_function() {
        let source = r#"
struct Node { int val; };

Node *createNode(int x) {
    int temp = x * 2;
    return nullptr;
}
"#;
        let tree = parse(source, Language::Cpp).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "createNode", Language::Cpp, source);
        assert!(
            node.is_some(),
            "Should find C++ function with pointer return type"
        );
        let name = get_function_name(node.unwrap(), Language::Cpp, source);
        assert_eq!(name.as_deref(), Some("createNode"));
    }

    // -- Swift init_declaration tests --

    #[test]
    fn test_swift_init_declaration() {
        let source = r#"
class App {
    init(port: Int) {
        let x = port + 1
    }
}
"#;
        let tree = parse(source, Language::Swift).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "init", Language::Swift, source);
        assert!(node.is_some(), "Should find Swift init declaration");
    }

    #[test]
    fn test_swift_init_dfg() {
        use crate::dfg::get_dfg_context;
        let source = r#"
class Server {
    init(port: Int) {
        let addr = port + 1000
    }
}
"#;
        let result = get_dfg_context(source, "init", Language::Swift);
        assert!(
            result.is_ok(),
            "DFG should succeed for Swift init, got: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_swift_node_kinds_include_init() {
        let kinds = get_function_node_kinds(Language::Swift);
        assert!(
            kinds.contains(&"init_declaration"),
            "Swift node kinds should include init_declaration"
        );
    }

    // -- Lua dot-indexed function name tests --

    #[test]
    fn test_lua_dot_indexed_function_short_name() {
        let source = r#"
function Kong.init()
    local x = 1
    return x
end
"#;
        let tree = parse(source, Language::Lua).unwrap();
        let root = tree.root_node();
        // Should find "init" when searching by short name
        let node = find_function_node(root, "init", Language::Lua, source);
        assert!(
            node.is_some(),
            "Should find Lua dot-indexed function by short name 'init'"
        );
    }

    #[test]
    fn test_lua_dot_indexed_function_full_name() {
        let source = r#"
function Kong.init()
    local x = 1
    return x
end
"#;
        let tree = parse(source, Language::Lua).unwrap();
        let root = tree.root_node();
        // Should also find by full qualified name
        let node = find_function_node(root, "Kong.init", Language::Lua, source);
        assert!(
            node.is_some(),
            "Should find Lua dot-indexed function by full name 'Kong.init'"
        );
    }

    #[test]
    fn test_lua_dot_indexed_function_dfg() {
        use crate::dfg::get_dfg_context;
        let source = r#"
function M.request(url)
    local result = url .. "/api"
    return result
end
"#;
        let result = get_dfg_context(source, "request", Language::Lua);
        assert!(
            result.is_ok(),
            "DFG should succeed for Lua dot-indexed function by short name, got: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_luau_dot_indexed_function_short_name() {
        let source = r#"
function Module.process(data)
    local x = data + 1
    return x
end
"#;
        let tree = parse(source, Language::Luau).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "process", Language::Luau, source);
        assert!(
            node.is_some(),
            "Should find Luau dot-indexed function by short name 'process'"
        );
    }

    // =========================================================================
    // C++ qualified method definition tests
    // =========================================================================

    #[test]
    fn test_cpp_qualified_method_definition() {
        // C++ method defined outside class body with ClassName::method syntax
        let source = r#"
class MyClass {
public:
    void externalMethod();
};

void MyClass::externalMethod() {
    int x = 1;
}
"#;
        let tree = parse(source, Language::Cpp).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "externalMethod", Language::Cpp, source);
        assert!(
            node.is_some(),
            "Should find C++ qualified method definition (ClassName::method)"
        );
        let node = node.unwrap();
        assert_eq!(node.kind(), "function_definition");
        let name = get_function_name(node, Language::Cpp, source);
        assert_eq!(
            name.as_deref(),
            Some("externalMethod"),
            "get_function_name should extract bare name from qualified C++ method"
        );
    }

    #[test]
    fn test_cpp_qualified_method_dfg() {
        use crate::dfg::get_dfg_context;
        let source = r#"
void MyClass::compute(int a) {
    int b = a + 1;
    int c = b * 2;
}
"#;
        let result = get_dfg_context(source, "compute", Language::Cpp);
        assert!(
            result.is_ok(),
            "DFG should succeed for C++ qualified method, got: {:?}",
            result.err()
        );
        let dfg = result.unwrap();
        assert_eq!(dfg.function, "compute");
    }

    #[test]
    fn test_cpp_inline_class_method() {
        // C++ method defined inline inside class body
        let source = r#"
class MyClass {
public:
    void myMethod() {
        int x = 1;
    }
};
"#;
        let tree = parse(source, Language::Cpp).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "myMethod", Language::Cpp, source);
        assert!(
            node.is_some(),
            "Should find C++ inline class method (field_identifier)"
        );
        let node = node.unwrap();
        assert_eq!(node.kind(), "function_definition");
        let name = get_function_name(node, Language::Cpp, source);
        assert_eq!(
            name.as_deref(),
            Some("myMethod"),
            "get_function_name should extract name from inline C++ class method"
        );
    }

    #[test]
    fn test_cpp_inline_class_method_dfg() {
        use crate::dfg::get_dfg_context;
        let source = r#"
class Widget {
public:
    int calculate(int a, int b) {
        int sum = a + b;
        int product = a * b;
        return sum;
    }
};
"#;
        let result = get_dfg_context(source, "calculate", Language::Cpp);
        assert!(
            result.is_ok(),
            "DFG should succeed for C++ inline class method, got: {:?}",
            result.err()
        );
        let dfg = result.unwrap();
        assert_eq!(dfg.function, "calculate");
        assert!(
            !dfg.variables.is_empty(),
            "Should find variables in inline class method"
        );
    }

    #[test]
    fn test_cpp_namespace_function() {
        // C++ function inside a namespace
        let source = r#"
namespace Foo {
    void bar() {
        int x = 1;
    }
}
"#;
        let tree = parse(source, Language::Cpp).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "bar", Language::Cpp, source);
        assert!(node.is_some(), "Should find C++ function inside namespace");
    }

    #[test]
    fn test_cpp_const_qualified_method() {
        // C++ const method defined outside class
        let source = r#"
bool NormalizedStringType::isNever() const {
    return !isCofinite && singletons.empty();
}
"#;
        let tree = parse(source, Language::Cpp).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "isNever", Language::Cpp, source);
        assert!(node.is_some(), "Should find C++ const qualified method");
        let name = get_function_name(node.unwrap(), Language::Cpp, source);
        assert_eq!(name.as_deref(), Some("isNever"));
    }

    #[test]
    fn test_cpp_nested_namespace_qualified_method() {
        // C++ method with deeply nested namespace::class::method
        let source = r#"
void Luau::Analysis::Normalizer::normalize() {
    int x = 1;
}
"#;
        let tree = parse(source, Language::Cpp).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "normalize", Language::Cpp, source);
        assert!(node.is_some(), "Should find deeply qualified C++ method");
        let name = get_function_name(node.unwrap(), Language::Cpp, source);
        assert_eq!(name.as_deref(), Some("normalize"));
    }

    // =========================================================================
    // C qualified function tests (same issues apply to C with qualified names)
    // =========================================================================

    #[test]
    fn test_c_inline_struct_method_like() {
        // C doesn't have classes but let's ensure function_definition inside
        // struct declarations or other nesting still works
        let source = r#"
void process(int x) {
    int y = x + 1;
}
"#;
        let tree = parse(source, Language::C).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "process", Language::C, source);
        assert!(node.is_some(), "Should find simple C function");
    }

    // =========================================================================
    // Lua/Luau local_function tests
    // =========================================================================

    #[test]
    fn test_lua_local_function_node_kinds() {
        // Verify that local_function is included in node kinds for Lua
        // This ensures consistency with ast_utils::function_node_kinds
        let kinds = get_function_node_kinds(Language::Lua);
        // Lua tree-sitter may or may not use "local_function" - but if ast_utils
        // includes it, function_finder should too for consistency
        let ast_kinds = crate::security::ast_utils::function_node_kinds(Language::Lua);
        for kind in ast_kinds {
            assert!(
                kinds.contains(kind),
                "function_finder should include '{}' which ast_utils includes for Lua",
                kind
            );
        }
    }

    #[test]
    fn test_luau_local_function_node_kinds() {
        let kinds = get_function_node_kinds(Language::Luau);
        let ast_kinds = crate::security::ast_utils::function_node_kinds(Language::Luau);
        for kind in ast_kinds {
            assert!(
                kinds.contains(kind),
                "function_finder should include '{}' which ast_utils includes for Luau",
                kind
            );
        }
    }

    // =========================================================================
    // Class.method qualified-name lookup tests (complexity-class-method-qualified-v1)
    // =========================================================================

    #[test]
    fn test_qualified_class_method_python() {
        // Python: Flask.run-style qualified lookup must find the method
        // INSIDE the class (not the bare-name fallback).
        let source = r#"
class Flask:
    def run(self):
        x = 1
        return x

def run():
    pass
"#;
        let tree = parse(source, Language::Python).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "Flask.run", Language::Python, source);
        assert!(node.is_some(), "Should resolve Flask.run to class method");
        let node = node.unwrap();
        // The matched node should be inside the class body — its parent
        // chain must include a class_definition with name "Flask".
        let mut p = node.parent();
        let mut found_class = false;
        while let Some(parent) = p {
            if parent.kind() == "class_definition" {
                if let Some(name_node) = parent.child_by_field_name("name") {
                    if name_node.utf8_text(source.as_bytes()).unwrap_or("") == "Flask" {
                        found_class = true;
                        break;
                    }
                }
            }
            p = parent.parent();
        }
        assert!(
            found_class,
            "Resolved method must be lexically inside class Flask (not the bare top-level run)"
        );
    }

    #[test]
    fn test_complexity_unqualified_still_works() {
        // Regression: bare-name lookup must continue to work.
        let source = r#"
class Flask:
    def run(self):
        if True:
            pass
"#;
        let tree = parse(source, Language::Python).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "run", Language::Python, source);
        assert!(node.is_some(), "Bare-name 'run' must still resolve");
    }

    #[test]
    fn test_qualified_class_not_found_falls_back_to_method() {
        // When the class part doesn't exist, we should fall back to the
        // last component as a bare name.
        let source = r#"
def standalone():
    return 42
"#;
        let tree = parse(source, Language::Python).unwrap();
        let root = tree.root_node();
        let node = find_function_node(
            root,
            "NonexistentClass.standalone",
            Language::Python,
            source,
        );
        assert!(
            node.is_some(),
            "Should fall back to bare 'standalone' when class doesn't exist"
        );
    }

    #[test]
    fn test_qualified_class_method_typescript() {
        let source = r#"
class Server {
    start(): void {
        const port = 8080;
    }
}

class Logger {
    start(): void {}
}
"#;
        let tree = parse(source, Language::TypeScript).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "Server.start", Language::TypeScript, source);
        assert!(node.is_some(), "Should resolve Server.start in TS");
        // Verify lexical scope: parent class should be Server.
        let node = node.unwrap();
        let mut p = node.parent();
        let mut found = false;
        while let Some(parent) = p {
            if parent.kind() == "class_declaration" {
                if let Some(name_node) = parent.child_by_field_name("name") {
                    if name_node.utf8_text(source.as_bytes()).unwrap_or("") == "Server" {
                        found = true;
                        break;
                    }
                }
            }
            p = parent.parent();
        }
        assert!(found, "Resolved method must be inside class Server");
    }

    #[test]
    fn test_qualified_class_method_rust_impl() {
        let source = r#"
struct Foo;

impl Foo {
    fn process(&self) -> i32 {
        let x = 1;
        x
    }
}
"#;
        let tree = parse(source, Language::Rust).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "Foo.process", Language::Rust, source);
        assert!(node.is_some(), "Should resolve Foo.process via impl block");
    }

    #[test]
    fn test_qualified_class_method_java() {
        let source = r#"
class Calculator {
    int add(int a, int b) {
        return a + b;
    }
}
"#;
        let tree = parse(source, Language::Java).unwrap();
        let root = tree.root_node();
        let node = find_function_node(root, "Calculator.add", Language::Java, source);
        assert!(node.is_some(), "Should resolve Calculator.add in Java");
    }

    #[test]
    fn test_qualified_lookup_via_complexity_python() {
        // Integration: complexity calculation through qualified name.
        use crate::metrics::calculate_complexity;
        let source = r#"
class Flask:
    def run(self, debug=False):
        if debug:
            print("debug")
        else:
            print("normal")
        return 0
"#;
        let metrics = calculate_complexity(source, "Flask.run", Language::Python).unwrap();
        // if/else => cyclomatic >= 2
        assert!(
            metrics.cyclomatic >= 2,
            "Flask.run cyclomatic should be >= 2, got {}",
            metrics.cyclomatic
        );
    }

    #[test]
    fn test_qualified_lookup_via_dfg_python() {
        // Integration: DFG (used by taint, slice, available, dead-stores,
        // reaching-defs) through qualified name.
        use crate::dfg::get_dfg_context;
        let source = r#"
class Service:
    def handler(self, req):
        x = req.data
        y = x + 1
        return y
"#;
        let result = get_dfg_context(source, "Service.handler", Language::Python);
        assert!(
            result.is_ok(),
            "DFG should succeed for Service.handler, got: {:?}",
            result.err()
        );
        let dfg = result.unwrap();
        assert_eq!(dfg.function, "Service.handler");
    }

    #[test]
    fn test_qualified_lookup_via_cfg_python() {
        // Integration: CFG (used by taint, slice, chop) through qualified name.
        use crate::cfg::get_cfg_context;
        let source = r#"
class Worker:
    def run(self):
        if True:
            return 1
        return 0
"#;
        let result = get_cfg_context(source, "Worker.run", Language::Python);
        assert!(
            result.is_ok(),
            "CFG should succeed for Worker.run, got: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_qualified_class_method_disambiguates_overloaded() {
        // Two classes with the same method name. Qualified lookup must
        // pick the one in the named class, not the first one in source order.
        let source = r#"
class Alpha:
    def shared(self):
        a = 1
        return a

class Beta:
    def shared(self):
        b = 2
        c = b + 1
        return c
"#;
        let tree = parse(source, Language::Python).unwrap();
        let root = tree.root_node();
        let beta_method =
            find_function_node(root, "Beta.shared", Language::Python, source).unwrap();
        // Verify it is the Beta version: walk up to enclosing class.
        let mut p = beta_method.parent();
        let mut enclosing = None;
        while let Some(parent) = p {
            if parent.kind() == "class_definition" {
                enclosing = parent
                    .child_by_field_name("name")
                    .map(|n| n.utf8_text(source.as_bytes()).unwrap_or("").to_string());
                break;
            }
            p = parent.parent();
        }
        assert_eq!(
            enclosing.as_deref(),
            Some("Beta"),
            "Beta.shared must resolve to the method inside class Beta"
        );
    }

    #[test]
    fn test_find_class_node_python() {
        let source = r#"
class Outer:
    pass

class Inner:
    pass
"#;
        let tree = parse(source, Language::Python).unwrap();
        let root = tree.root_node();
        let inner = find_class_node(root, "Inner", Language::Python, source);
        assert!(inner.is_some(), "Should find class Inner");
        let nonexistent = find_class_node(root, "DoesNotExist", Language::Python, source);
        assert!(
            nonexistent.is_none(),
            "Nonexistent class should return None"
        );
    }

    #[test]
    fn test_find_class_node_languages_without_classes() {
        // C, OCaml, Elixir, Lua, Luau have no class container — must
        // return None unconditionally.
        let source = "int foo() { return 0; }";
        let tree = parse(source, Language::C).unwrap();
        let root = tree.root_node();
        let result = find_class_node(root, "Anything", Language::C, source);
        assert!(result.is_none(), "C has no class kinds — must return None");
    }
}