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
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
// Per-language metric and AST modules deliberately consume the macro-
// generated tree-sitter token enums via `use crate::*` and `use Foo::*`
// inside match expressions — explicit imports would list dozens of
// variants per arm and obscure the per-language token sets that are the
// point of these files. Allowed at the module level rather than per
// function so the per-language impl blocks stay readable.
#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
use std::sync::OnceLock;
use aho_corasick::AhoCorasick;
use regex::bytes::Regex;
use crate::cfg_predicate::attribute_marks_test as rust_attribute_marks_test;
use crate::macros::csharp_invocation_expr_kinds;
use crate::*;
static AHO_CORASICK: OnceLock<AhoCorasick> = OnceLock::new();
static RE: OnceLock<Regex> = OnceLock::new();
macro_rules! check_if_func {
($parser: ident, $node: ident) => {
$node.count_specific_ancestors::<$parser>(
|node| {
matches!(
node.kind_id().into(),
VariableDeclarator | AssignmentExpression | LabeledStatement | Pair
)
},
|node| {
matches!(
node.kind_id().into(),
StatementBlock | ReturnStatement | NewExpression | Arguments
)
},
) > 0
|| $node.is_child(Identifier as u16)
};
}
macro_rules! check_if_arrow_func {
($parser: ident, $node: ident) => {
$node.count_specific_ancestors::<$parser>(
|node| {
matches!(
node.kind_id().into(),
VariableDeclarator | AssignmentExpression | LabeledStatement
)
},
|node| {
matches!(
node.kind_id().into(),
StatementBlock | ReturnStatement | NewExpression | CallExpression
)
},
) > 0
|| $node.has_sibling(PropertyIdentifier as u16)
};
}
macro_rules! is_js_func {
($parser: ident, $node: ident) => {
match $node.kind_id().into() {
FunctionDeclaration | MethodDefinition => true,
FunctionExpression => check_if_func!($parser, $node),
ArrowFunction => check_if_arrow_func!($parser, $node),
_ => false,
}
};
}
macro_rules! is_js_closure {
($parser: ident, $node: ident) => {
match $node.kind_id().into() {
GeneratorFunction | GeneratorFunctionDeclaration => true,
FunctionExpression => !check_if_func!($parser, $node),
ArrowFunction => !check_if_arrow_func!($parser, $node),
_ => false,
}
};
}
macro_rules! is_js_func_and_closure_checker {
($parser: ident, $language: ident) => {
#[inline]
fn is_func(node: &Node) -> bool {
use $language::*;
is_js_func!($parser, node)
}
#[inline]
fn is_closure(node: &Node) -> bool {
use $language::*;
is_js_closure!($parser, node)
}
};
}
// Generate an `is_string` impl for a JS-family `Checker` block. The
// MozJS / JavaScript / TypeScript grammars expose `String2` as the
// anonymous `"string"` keyword alias for `String`; TSX additionally
// exposes `String3` (the JSX-attribute string production). The
// alterator flattens these aliases; the generic `string` filter must
// agree (issue #283).
macro_rules! impl_js_family_is_string {
($lang:ident $(, $extra:ident)* $(,)?) => {
fn is_string(node: &Node) -> bool {
matches!(
node.kind_id().into(),
$lang::String | $lang::String2 | $lang::TemplateString
$(| $lang::$extra)*
)
}
};
}
// Generate an `is_string` impl for languages whose `is_string`
// predicate is a flat `matches!` against one or more variant
// kinds. Reduces drift risk for new alias additions and gives a
// single table that answers "which kinds count as a string for
// `find string` / `count string`?" per language (issue #301).
//
// Languages whose `is_string` needs anything beyond a flat variant
// list (e.g. JS family's `String` + `String2` + `TemplateString`
// pattern) keep their own dedicated macros or impls.
macro_rules! impl_simple_is_string {
($lang:ident, $first:ident $(, $rest:ident)* $(,)?) => {
fn is_string(node: &Node) -> bool {
matches!(
node.kind_id().into(),
$lang::$first $(| $lang::$rest)*
)
}
};
}
#[inline]
fn get_aho_corasick_match(code: &[u8]) -> bool {
AHO_CORASICK
.get_or_init(|| AhoCorasick::new(vec![b"<div rustbindgen"]).unwrap())
.is_match(code)
}
#[doc(hidden)]
pub trait Checker {
fn is_comment(_: &Node) -> bool;
fn is_useful_comment(_: &Node, _: &[u8]) -> bool;
fn is_func_space(_: &Node) -> bool;
fn is_func(_: &Node) -> bool;
fn is_closure(_: &Node) -> bool;
fn is_call(_: &Node) -> bool;
fn is_non_arg(_: &Node) -> bool;
fn is_string(_: &Node) -> bool;
fn is_else_if(_: &Node) -> bool;
fn is_primitive(_id: u16) -> bool;
fn is_error(node: &Node) -> bool {
node.has_error()
}
/// Return `true` to elide this node and all its descendants from
/// every metric. Used by language modules to filter
/// test-only / generated / preprocessor-disabled subtrees.
///
/// The default returns `false` for every node, preserving the
/// pre-#182 behavior. Language overrides drive opt-in skips
/// (currently: `RustCode` filters `#[cfg(test)]` items, gated
/// by the runtime `MetricsOptions::exclude_tests` flag).
#[inline]
fn should_skip_subtree(_node: &Node, _code: &[u8]) -> bool {
false
}
/// Source-aware variant of [`is_func_space`]. The default forwards
/// to the byte-less predicate so languages whose function-space
/// classification is encoded in distinct grammar productions (Java,
/// Rust, Python, …) need no override. Languages whose function
/// boundaries are macro-shaped — Elixir's `def` / `defp` /
/// `defmacro` / `defmacrop` / `defmodule` — override this to
/// disambiguate `Call` nodes by their target identifier text
/// (#275).
#[inline]
fn is_func_space_with_code(node: &Node, _code: &[u8]) -> bool {
Self::is_func_space(node)
}
/// Source-aware variant of [`is_func`]. Same rationale as
/// [`is_func_space_with_code`] (#275).
#[inline]
fn is_func_with_code(node: &Node, _code: &[u8]) -> bool {
Self::is_func(node)
}
/// Combined predicate the walker uses to decide whether to promote
/// `node` to a new function-space frame. Default forwards to
/// `is_func_with_code || is_func_space_with_code` so existing
/// languages need no override — each kept the freedom to expose
/// `is_func` and `is_func_space` as disjoint sets (Rust includes
/// closures in `is_func_space`, Java keeps lambdas out, …) and
/// this method preserves that flexibility while letting Elixir
/// halve its per-`Call` source-text lookups: a single
/// `elixir_call_keyword` call answers both halves at once
/// (#310 follow-on perf).
#[inline]
fn promotes_to_func_space_with_code(node: &Node, code: &[u8]) -> bool {
Self::is_func_with_code(node, code) || Self::is_func_space_with_code(node, code)
}
}
impl Checker for PreprocCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Preproc::Comment
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
fn is_func_space(_: &Node) -> bool {
false
}
fn is_func(_: &Node) -> bool {
false
}
fn is_closure(_: &Node) -> bool {
false
}
fn is_call(_: &Node) -> bool {
false
}
fn is_non_arg(_: &Node) -> bool {
false
}
impl_simple_is_string!(Preproc, StringLiteral, RawStringLiteral);
fn is_else_if(_: &Node) -> bool {
false
}
fn is_primitive(_id: u16) -> bool {
false
}
}
impl Checker for CcommentCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Ccomment::Comment
}
fn is_useful_comment(node: &Node, code: &[u8]) -> bool {
get_aho_corasick_match(&code[node.start_byte()..node.end_byte()])
}
fn is_func_space(_: &Node) -> bool {
false
}
fn is_func(_: &Node) -> bool {
false
}
fn is_closure(_: &Node) -> bool {
false
}
fn is_call(_: &Node) -> bool {
false
}
fn is_non_arg(_: &Node) -> bool {
false
}
impl_simple_is_string!(Ccomment, StringLiteral, RawStringLiteral);
fn is_else_if(_: &Node) -> bool {
false
}
fn is_primitive(_id: u16) -> bool {
false
}
}
impl Checker for CppCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Cpp::Comment
}
fn is_useful_comment(node: &Node, code: &[u8]) -> bool {
get_aho_corasick_match(&code[node.start_byte()..node.end_byte()])
}
// Issue #285 contract: every `Cpp::FunctionDefinition*` alias must
// be enumerated here AND in `is_func`, `get_func_space_name`, and
// `get_space_kind` (see `src/getter.rs`). Aliased kind_ids
// 489/491/494 are not emitted by the currently pinned
// `tree-sitter-mozcpp` parse tables on any input we can construct,
// so a missing variant won't fail a parse-and-assert test — it
// will silently drop those nodes from FuncSpace creation the next
// time a grammar bump starts emitting them (see lesson 2 in
// `docs/development/lessons_learned.md`).
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Cpp::TranslationUnit
| Cpp::FunctionDefinition
| Cpp::FunctionDefinition2
| Cpp::FunctionDefinition3
| Cpp::FunctionDefinition4
| Cpp::StructSpecifier
| Cpp::ClassSpecifier
| Cpp::NamespaceDefinition
)
}
// Issue #285 contract: keep this in sync with `is_func_space` and
// the C++ getters — see comment above `is_func_space`.
fn is_func(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Cpp::FunctionDefinition
| Cpp::FunctionDefinition2
| Cpp::FunctionDefinition3
| Cpp::FunctionDefinition4
)
}
fn is_closure(node: &Node) -> bool {
node.kind_id() == Cpp::LambdaExpression
}
fn is_call(node: &Node) -> bool {
node.kind_id() == Cpp::CallExpression
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Cpp::LPAREN | Cpp::LPAREN2 | Cpp::COMMA | Cpp::RPAREN
)
}
impl_simple_is_string!(Cpp, StringLiteral, ConcatenatedString, RawStringLiteral);
fn is_else_if(node: &Node) -> bool {
if node.kind_id() != Cpp::IfStatement {
return false;
}
if let Some(parent) = node.parent() {
return parent.kind_id() == Cpp::ElseClause;
}
false
}
#[inline]
fn is_primitive(id: u16) -> bool {
id == Cpp::PrimitiveType
}
}
impl Checker for PythonCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Python::Comment
}
fn is_useful_comment(node: &Node, code: &[u8]) -> bool {
// comment containing coding info are useful
node.start_row() <= 1
&& RE
.get_or_init(|| {
Regex::new(r"^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)").unwrap()
})
.is_match(&code[node.start_byte()..node.end_byte()])
}
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Python::Module | Python::FunctionDefinition | Python::ClassDefinition
)
}
fn is_func(node: &Node) -> bool {
node.kind_id() == Python::FunctionDefinition
}
fn is_closure(node: &Node) -> bool {
node.kind_id() == Python::Lambda
}
fn is_call(node: &Node) -> bool {
node.kind_id() == Python::Call
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Python::LPAREN | Python::COMMA | Python::RPAREN
)
}
impl_simple_is_string!(Python, String, ConcatenatedString);
// Python models `elif` as a dedicated `elif_clause` node, which is
// handled directly by cognitive/cyclomatic dispatch as a branch
// extension — `is_else_if` is intentionally never invoked for
// `elif_clause` because it is not an `if_statement` and is not in
// any of the structural kind sets that `count_specific_ancestors`
// walks for nesting (issue #274).
//
// `else: if x: ...` chains also exist — semantically equivalent to
// `else if` — but the grammar wraps the inner `if_statement` in a
// `block` node, so the shape is `else_clause → block → if_statement`
// rather than the direct `else_clause → if_statement` used by
// C++/JS/TS/TSX/Rust. Match the chained shape by walking through
// the `block` and requiring the inner `if` to be the block's sole
// named child; sibling statements would mean a real nested-if, not
// a chain (issue #276).
//
// `block` has two aliased kind_ids in tree-sitter-python
// (`Block` = 135, `Block2` = 160 — both surface as `"block"`); we
// accept either per lesson 2 in `docs/development/lessons_learned.md`.
fn is_else_if(node: &Node) -> bool {
node.kind_id() == Python::IfStatement
&& node.parent().is_some_and(|parent| {
matches!(parent.kind_id().into(), Python::Block | Python::Block2)
&& parent.children().filter(Node::is_named).count() == 1
&& parent
.parent()
.is_some_and(|gp| gp.kind_id() == Python::ElseClause)
})
}
fn is_primitive(_id: u16) -> bool {
false
}
}
impl Checker for JavaCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Java::LineComment || node.kind_id() == Java::BlockComment
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
// `EnumDeclaration`, `RecordDeclaration`, and `AnnotationTypeDeclaration`
// are class-like declarations that can contain fields and methods,
// so they open a class space alongside `ClassDeclaration` /
// `InterfaceDeclaration` (issue #280). Without them, `Npa`/`Npm`/`Wmc`
// never see their bodies as class scopes and silently produce zero
// counts. Annotation types map to `Interface` in `get_space_kind`
// (their elements are abstract methods at the bytecode level);
// enums and records map to `Class`.
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Java::Program
| Java::ClassDeclaration
| Java::InterfaceDeclaration
| Java::EnumDeclaration
| Java::RecordDeclaration
| Java::AnnotationTypeDeclaration
)
}
fn is_func(node: &Node) -> bool {
node.kind_id() == Java::MethodDeclaration || node.kind_id() == Java::ConstructorDeclaration
}
fn is_closure(node: &Node) -> bool {
node.kind_id() == Java::LambdaExpression
}
fn is_call(node: &Node) -> bool {
node.kind_id() == Java::MethodInvocation
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Java::LPAREN | Java::COMMA | Java::RPAREN
)
}
impl_simple_is_string!(Java, StringLiteral, MultilineStringLiteral);
#[inline]
fn is_else_if(node: &Node) -> bool {
// tree-sitter-java models `else if` as an `Else` keyword token followed
// by a nested `if_statement` (no wrapping `else_clause` node).
node.kind_id() == Java::IfStatement
&& node
.previous_sibling()
.is_some_and(|prev| prev.kind_id() == Java::Else)
}
fn is_primitive(_id: u16) -> bool {
false
}
}
impl Checker for CsharpCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Csharp::Comment
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Csharp::CompilationUnit
| Csharp::ClassDeclaration
| Csharp::StructDeclaration
| Csharp::RecordDeclaration
| Csharp::InterfaceDeclaration
| Csharp::EnumDeclaration
| Csharp::MethodDeclaration
| Csharp::ConstructorDeclaration
| Csharp::DestructorDeclaration
| Csharp::LocalFunctionStatement
| Csharp::LambdaExpression
| Csharp::AnonymousMethodExpression
| Csharp::AccessorDeclaration
| Csharp::OperatorDeclaration
| Csharp::ConversionOperatorDeclaration
| Csharp::IndexerDeclaration
)
}
fn is_func(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Csharp::MethodDeclaration
| Csharp::ConstructorDeclaration
| Csharp::DestructorDeclaration
| Csharp::LocalFunctionStatement
| Csharp::AccessorDeclaration
| Csharp::OperatorDeclaration
| Csharp::ConversionOperatorDeclaration
| Csharp::IndexerDeclaration
)
}
fn is_closure(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Csharp::LambdaExpression | Csharp::AnonymousMethodExpression
)
}
fn is_call(node: &Node) -> bool {
// The C# grammar emits three aliased `kind_id`s for
// `invocation_expression`; matching only the unsuffixed variant
// silently drops the rest (lesson #2 in lessons_learned.md).
matches!(node.kind_id().into(), csharp_invocation_expr_kinds!())
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Csharp::LPAREN | Csharp::COMMA | Csharp::RPAREN
)
}
impl_simple_is_string!(
Csharp,
StringLiteral,
VerbatimStringLiteral,
RawStringLiteral,
InterpolatedStringExpression,
);
#[inline]
fn is_else_if(node: &Node) -> bool {
// tree-sitter-c-sharp models `else if` as an `Else` keyword token
// followed by a nested `if_statement` (no wrapping `else_clause` node).
node.kind_id() == Csharp::IfStatement
&& node
.previous_sibling()
.is_some_and(|prev| prev.kind_id() == Csharp::Else)
}
#[inline]
fn is_primitive(id: u16) -> bool {
// Without this, every `PredefinedType` keyword (`int`, `string`,
// `bool`, `object`, …) collapses into a single Halstead operator
// because they share one `kind_id`. Returning `true` here routes
// them through the lexeme-keyed `primitive_operators` map so
// distinct keywords count as distinct operators (issue #286).
id == Csharp::PredefinedType as u16
}
}
impl Checker for MozjsCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Mozjs::Comment
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Mozjs::Program
| Mozjs::FunctionExpression
| Mozjs::Class
| Mozjs::GeneratorFunction
| Mozjs::FunctionDeclaration
| Mozjs::MethodDefinition
| Mozjs::GeneratorFunctionDeclaration
| Mozjs::ClassDeclaration
| Mozjs::ArrowFunction
)
}
is_js_func_and_closure_checker!(MozjsParser, Mozjs);
fn is_call(node: &Node) -> bool {
node.kind_id() == Mozjs::CallExpression
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Mozjs::LPAREN | Mozjs::COMMA | Mozjs::RPAREN
)
}
impl_js_family_is_string!(Mozjs);
#[inline]
fn is_else_if(node: &Node) -> bool {
if node.kind_id() != Mozjs::IfStatement {
return false;
}
if let Some(parent) = node.parent() {
return parent.kind_id() == Mozjs::ElseClause;
}
false
}
fn is_primitive(_id: u16) -> bool {
false
}
}
impl Checker for JavascriptCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Javascript::Comment
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Javascript::Program
| Javascript::FunctionExpression
| Javascript::Class
| Javascript::GeneratorFunction
| Javascript::FunctionDeclaration
| Javascript::MethodDefinition
| Javascript::GeneratorFunctionDeclaration
| Javascript::ClassDeclaration
| Javascript::ArrowFunction
)
}
is_js_func_and_closure_checker!(JavascriptParser, Javascript);
fn is_call(node: &Node) -> bool {
node.kind_id() == Javascript::CallExpression
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Javascript::LPAREN | Javascript::COMMA | Javascript::RPAREN
)
}
impl_js_family_is_string!(Javascript);
#[inline]
fn is_else_if(node: &Node) -> bool {
node.kind_id() == Javascript::IfStatement
&& node
.parent()
.is_some_and(|p| p.kind_id() == Javascript::ElseClause)
}
fn is_primitive(_id: u16) -> bool {
false
}
}
impl Checker for TypescriptCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Typescript::Comment
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Typescript::Program
| Typescript::FunctionExpression
| Typescript::Class
| Typescript::GeneratorFunction
| Typescript::FunctionDeclaration
| Typescript::MethodDefinition
| Typescript::GeneratorFunctionDeclaration
| Typescript::ClassDeclaration
| Typescript::AbstractClassDeclaration
| Typescript::InterfaceDeclaration
| Typescript::ArrowFunction
)
}
is_js_func_and_closure_checker!(TypescriptParser, Typescript);
fn is_call(node: &Node) -> bool {
node.kind_id() == Typescript::CallExpression
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Typescript::LPAREN | Typescript::COMMA | Typescript::RPAREN
)
}
impl_js_family_is_string!(Typescript);
#[inline]
fn is_else_if(node: &Node) -> bool {
if node.kind_id() != Typescript::IfStatement {
return false;
}
if let Some(parent) = node.parent() {
return parent.kind_id() == Typescript::ElseClause;
}
false
}
#[inline]
fn is_primitive(id: u16) -> bool {
id == Typescript::PredefinedType
}
}
impl Checker for TsxCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Tsx::Comment
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Tsx::Program
| Tsx::FunctionExpression
| Tsx::Class
| Tsx::GeneratorFunction
| Tsx::FunctionDeclaration
| Tsx::MethodDefinition
| Tsx::GeneratorFunctionDeclaration
| Tsx::ClassDeclaration
| Tsx::AbstractClassDeclaration
| Tsx::InterfaceDeclaration
| Tsx::ArrowFunction
)
}
is_js_func_and_closure_checker!(TsxParser, Tsx);
fn is_call(node: &Node) -> bool {
node.kind_id() == Tsx::CallExpression
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Tsx::LPAREN | Tsx::COMMA | Tsx::RPAREN
)
}
impl_js_family_is_string!(Tsx, String3);
fn is_else_if(node: &Node) -> bool {
node.kind_id() == Tsx::IfStatement
&& node
.parent()
.is_some_and(|p| p.kind_id() == Tsx::ElseClause)
}
#[inline]
fn is_primitive(id: u16) -> bool {
id == Tsx::PredefinedType
}
}
/// Strip the `#` / `#!` marker plus the `[...]` brackets from a
/// Rust `AttributeItem` / `InnerAttributeItem` token's raw text,
/// returning the inner body. Returns `None` if the input shape is
/// unexpected — callers skip silently rather than feed the matcher
/// the literal `#[...]` form.
fn rust_attribute_body<'a>(text: &'a str, marker: &str) -> Option<&'a str> {
text.trim()
.strip_prefix(marker)
.and_then(|t| t.trim_start().strip_prefix('['))
.and_then(|t| t.trim().strip_suffix(']'))
}
fn rust_item_is_test_only(node: &Node, code: &[u8]) -> bool {
// The tree-sitter Rust grammar exposes outer attributes
// (`#[...]`) as `AttributeItem` siblings *before* the decorated
// item. Walk backward across consecutive attribute siblings; any
// match short-circuits.
let mut sibling = node.previous_sibling();
while let Some(s) = sibling {
if s.kind_id() != Rust::AttributeItem {
break;
}
if let Some(text) = s.utf8_text(code)
&& let Some(inner) = rust_attribute_body(text, "#")
&& rust_attribute_marks_test(inner)
{
return true;
}
sibling = s.previous_sibling();
}
// `mod_item` additionally accepts inner attributes
// (`#![cfg(test)]`). The grammar nests these inside the module's
// `declaration_list` body, not as direct `mod_item` children, so
// descend one level via the `body` field before scanning.
if node.kind_id() == Rust::ModItem
&& let Some(body) = node.child_by_field_name("body")
{
for child in body.children() {
if child.kind_id() != Rust::InnerAttributeItem {
continue;
}
if let Some(text) = child.utf8_text(code)
&& let Some(inner) = rust_attribute_body(text, "#!")
&& rust_attribute_marks_test(inner)
{
return true;
}
}
}
false
}
impl Checker for RustCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Rust::LineComment || node.kind_id() == Rust::BlockComment
}
fn is_useful_comment(node: &Node, code: &[u8]) -> bool {
if let Some(parent) = node.parent()
&& parent.kind_id() == Rust::TokenTree
{
// A comment could be a macro token
return true;
}
let code = &code[node.start_byte()..node.end_byte()];
code.starts_with(b"/// cbindgen:")
}
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Rust::SourceFile
| Rust::FunctionItem
| Rust::ImplItem
| Rust::TraitItem
| Rust::ClosureExpression
)
}
fn is_func(node: &Node) -> bool {
node.kind_id() == Rust::FunctionItem
}
fn is_closure(node: &Node) -> bool {
node.kind_id() == Rust::ClosureExpression
}
fn is_call(node: &Node) -> bool {
node.kind_id() == Rust::CallExpression
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Rust::LPAREN | Rust::COMMA | Rust::RPAREN | Rust::PIPE | Rust::AttributeItem
)
}
impl_simple_is_string!(Rust, StringLiteral, RawStringLiteral);
#[inline]
fn is_else_if(node: &Node) -> bool {
if node.kind_id() != Rust::IfExpression {
return false;
}
if let Some(parent) = node.parent() {
return parent.kind_id() == Rust::ElseClause;
}
false
}
#[inline]
fn is_primitive(id: u16) -> bool {
matches!(
id.into(),
Rust::PrimitiveType
| Rust::PrimitiveType2
| Rust::PrimitiveType3
| Rust::PrimitiveType4
| Rust::PrimitiveType5
| Rust::PrimitiveType6
| Rust::PrimitiveType7
| Rust::PrimitiveType8
| Rust::PrimitiveType9
| Rust::PrimitiveType10
| Rust::PrimitiveType11
| Rust::PrimitiveType12
| Rust::PrimitiveType13
| Rust::PrimitiveType14
| Rust::PrimitiveType15
| Rust::PrimitiveType16
| Rust::PrimitiveType17
)
}
/// Skip the subtree when `node` is a `mod`, `fn`, `impl`,
/// `trait`, `const`, or `static` item marked test-only by an
/// outer or inner attribute (`#[test]`, `#[cfg(test)]`,
/// `#[tokio::test]`, `#![cfg(test)]`, …). The runtime guard
/// in `spaces::metrics_with_options` only consults this hook
/// when the caller opts in via `MetricsOptions::exclude_tests`,
/// so the default `metrics()` entry point is unaffected.
fn should_skip_subtree(node: &Node, code: &[u8]) -> bool {
if !matches!(
node.kind_id().into(),
Rust::ModItem
| Rust::FunctionItem
| Rust::ImplItem
| Rust::TraitItem
| Rust::ConstItem
| Rust::StaticItem
) {
return false;
}
rust_item_is_test_only(node, code)
}
}
impl Checker for GoCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Go::Comment
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Go::SourceFile | Go::FunctionDeclaration | Go::MethodDeclaration | Go::FuncLiteral
)
}
fn is_func(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Go::FunctionDeclaration | Go::MethodDeclaration
)
}
fn is_closure(node: &Node) -> bool {
node.kind_id() == Go::FuncLiteral
}
fn is_call(node: &Node) -> bool {
node.kind_id() == Go::CallExpression
}
fn is_non_arg(node: &Node) -> bool {
matches!(node.kind_id().into(), Go::LPAREN | Go::COMMA | Go::RPAREN)
}
impl_simple_is_string!(Go, InterpretedStringLiteral, RawStringLiteral);
#[inline]
fn is_else_if(node: &Node) -> bool {
node.kind_id() == Go::IfStatement
&& node
.parent()
.is_some_and(|p| p.kind_id() == Go::IfStatement)
}
fn is_primitive(_id: u16) -> bool {
false
}
}
impl Checker for KotlinCode {
fn is_comment(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Kotlin::LineComment | Kotlin::BlockComment
)
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Kotlin::SourceFile | Kotlin::ClassDeclaration | Kotlin::ObjectDeclaration
)
}
fn is_func(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Kotlin::FunctionDeclaration | Kotlin::SecondaryConstructor
)
}
fn is_closure(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Kotlin::LambdaLiteral | Kotlin::AnonymousFunction
)
}
fn is_call(node: &Node) -> bool {
node.kind_id() == Kotlin::CallExpression
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Kotlin::LPAREN | Kotlin::COMMA | Kotlin::RPAREN
)
}
impl_simple_is_string!(Kotlin, StringLiteral, MultilineStringLiteral);
#[inline]
fn is_else_if(node: &Node) -> bool {
// tree-sitter-kotlin models `else if` as an `else` keyword sibling
// followed by an `if_expression`, not a wrapping clause node.
node.kind_id() == Kotlin::IfExpression
&& node
.previous_sibling()
.is_some_and(|prev| prev.kind_id() == Kotlin::Else)
}
fn is_primitive(_id: u16) -> bool {
false
}
}
impl Checker for PerlCode {
fn is_comment(node: &Node) -> bool {
matches!(node.kind_id().into(), Perl::Comments | Perl::PodStatement)
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Perl::SourceFile
| Perl::FunctionDefinition
| Perl::FunctionDefinitionWithoutSub
| Perl::AnonymousFunction
)
}
fn is_func(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Perl::FunctionDefinition | Perl::FunctionDefinitionWithoutSub
)
}
fn is_closure(node: &Node) -> bool {
node.kind_id() == Perl::AnonymousFunction
}
fn is_call(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Perl::CallExpressionWithSpacedArgs
| Perl::CallExpressionWithSub
| Perl::CallExpressionWithArgsWithBrackets
| Perl::CallExpressionWithVariable
| Perl::CallExpressionWithBareword
| Perl::CallExpressionRecursive
| Perl::MethodInvocation
)
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Perl::LPAREN | Perl::COMMA | Perl::RPAREN | Perl::FatComma
)
}
// `HeredocBodyStatement` wraps the heredoc body text (and any
// `Interpolation` children) that appears as a top-level
// statement after the heredoc-introducing `<<TAG`; it is the
// visible literal node and is treated as a string here, the
// same way Bash's `heredoc_body` is treated as a string.
impl_simple_is_string!(
Perl,
StringSingleQuoted,
StringDoubleQuoted,
StringQQuoted,
StringQqQuoted,
BacktickQuoted,
CommandQxQuoted,
HeredocBodyStatement,
);
#[inline]
fn is_else_if(node: &Node) -> bool {
// tree-sitter-perl emits `elsif_clause` as a direct child of the
// surrounding `if_statement` (not as a wrapper around a nested
// `if`), so the clause node itself is the else-if.
node.kind_id() == Perl::ElsifClause
}
fn is_primitive(_id: u16) -> bool {
false
}
}
impl Checker for LuaCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Lua::Comment
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Lua::Chunk
| Lua::FunctionDeclaration
| Lua::FunctionDeclaration2
| Lua::FunctionDeclaration3
| Lua::FunctionDefinition
)
}
fn is_func(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Lua::FunctionDeclaration | Lua::FunctionDeclaration2 | Lua::FunctionDeclaration3
)
}
fn is_closure(node: &Node) -> bool {
node.kind_id() == Lua::FunctionDefinition
}
fn is_call(node: &Node) -> bool {
node.kind_id() == Lua::FunctionCall
}
fn is_non_arg(node: &Node) -> bool {
// NOTE: `impl NArgs for LuaCode` overrides `compute` with a positive
// filter on `Identifier | VarargExpression` and never calls `is_non_arg`.
// This implementation satisfies the trait contract but is unused for NArgs.
matches!(
node.kind_id().into(),
Lua::LPAREN | Lua::COMMA | Lua::RPAREN
)
}
impl_simple_is_string!(Lua, String);
#[inline]
fn is_else_if(node: &Node) -> bool {
// Lua uses a dedicated elseif_statement node rather than nesting a
// second if_statement inside the outer one (as Go does).
node.kind_id() == Lua::ElseifStatement
}
fn is_primitive(_id: u16) -> bool {
false
}
}
impl Checker for BashCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Bash::Comment
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Bash::Program | Bash::FunctionDefinition
)
}
fn is_func(node: &Node) -> bool {
node.kind_id() == Bash::FunctionDefinition
}
fn is_closure(_node: &Node) -> bool {
false
}
fn is_call(node: &Node) -> bool {
node.kind_id() == Bash::Command
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Bash::LPAREN | Bash::RPAREN | Bash::COMMA | Bash::SEMI
)
}
// tree-sitter-bash 0.25.1 only emits the `heredoc_body`
// parser-node symbol (`HeredocBody2`) in observed parse trees;
// the duplicate `HeredocBody` entry plus the hidden
// `_heredoc_body` (`HeredocBody3`) and `_simple_heredoc_body`
// (`SimpleHeredocBody`) rules do not surface, so they are
// intentionally omitted here.
impl_simple_is_string!(
Bash,
String,
RawString,
AnsiCString,
TranslatedString,
HeredocBody2,
);
#[inline]
fn is_else_if(node: &Node) -> bool {
node.kind_id() == Bash::ElifClause
}
fn is_primitive(_id: u16) -> bool {
false
}
}
impl Checker for TclCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Tcl::Comment
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
fn is_func_space(node: &Node) -> bool {
matches!(node.kind_id().into(), Tcl::SourceFile | Tcl::Procedure)
}
fn is_func(node: &Node) -> bool {
node.kind_id() == Tcl::Procedure
}
// Tcl closures (`apply`) are ordinary commands; the grammar has no distinct closure node.
fn is_closure(_: &Node) -> bool {
false
}
fn is_call(node: &Node) -> bool {
node.kind_id() == Tcl::Command
}
// Tcl arguments are whitespace-separated; no punctuation to exclude.
fn is_non_arg(_: &Node) -> bool {
false
}
impl_simple_is_string!(Tcl, QuotedWord, BracedWord, BracedWordSimple);
#[inline]
fn is_else_if(node: &Node) -> bool {
// Tcl grammar has a dedicated `elseif` named node, not a nested `if`.
node.kind_id() == Tcl::Elseif
}
fn is_primitive(_: u16) -> bool {
false
}
}
impl Checker for PhpCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Php::Comment
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Php::Program
| Php::FunctionDefinition
| Php::MethodDeclaration
| Php::AnonymousFunction
| Php::ArrowFunction
| Php::ClassDeclaration
| Php::InterfaceDeclaration
| Php::TraitDeclaration
| Php::EnumDeclaration
| Php::AnonymousClass
)
}
fn is_func(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Php::FunctionDefinition | Php::MethodDeclaration
)
}
fn is_closure(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Php::AnonymousFunction | Php::ArrowFunction
)
}
// Intentionally narrower than ABC's `branches` set: ABC additionally
// counts `ObjectCreationExpression` (`new Foo()`) as a branch, but
// `is_call` drives the `--ops` CLI feature and should match the
// user's mental model of "function/method call sites" (mirrors
// Java's `is_call` = `MethodInvocation` while ABC counts
// `MethodInvocation | New`).
fn is_call(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Php::FunctionCallExpression
| Php::MemberCallExpression
| Php::ScopedCallExpression
| Php::NullsafeMemberCallExpression
)
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Php::LPAREN | Php::LPAREN2 | Php::COMMA | Php::RPAREN | Php::RPAREN2 | Php::DOTDOTDOT
)
}
// `String` is the named single-quoted literal; `String2` and
// `String3` are aliased kind_ids that the language enum also
// maps to `"string"` (`String2` is the `string` type keyword
// and `String3` is the hidden `_string` supertype that covers
// any string literal). Include all three so generic
// string-filtering stays consistent with `get_op_type` and the
// `Alterator` text-preservation arm (issue #288).
impl_simple_is_string!(
Php,
String,
String2,
String3,
EncapsedString,
Heredoc,
Nowdoc,
ShellCommandExpression,
);
#[inline]
fn is_else_if(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Php::ElseIfClause | Php::ElseIfClause2
)
}
fn is_primitive(_: u16) -> bool {
false
}
}
impl Checker for ElixirCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Elixir::Comment
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
// Elixir has no syntactic function-definition node: `def`/`defp` /
// `defmacro`/`defmacrop` / `defmodule` are ordinary `Call` nodes
// with the macro identifier in the `target` field. The byte-less
// [`is_func_space`] and [`is_func`] cannot distinguish them from
// any other `Call`, so they conservatively return zero (only the
// file root and explicit anonymous functions surface as func
// spaces). The text-aware [`is_func_space_with_code`] /
// [`is_func_with_code`] overrides below promote the macro-shaped
// declarations to first-class function / class spaces (#275). The
// walker passes the source bytes through, so the metrics
// attributed to a `def`'s body now correctly nest under a Function
// space and `Wmc` / `Npm` / `Npa` see a `defmodule` Class.
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Elixir::Source | Elixir::AnonymousFunction
)
}
fn is_func(_: &Node) -> bool {
false
}
fn is_func_space_with_code(node: &Node, code: &[u8]) -> bool {
use crate::metrics::cognitive::{
elixir_call_keyword, elixir_is_class_macro, elixir_is_inside_quote_block,
elixir_is_method_macro,
};
if Self::is_func_space(node) {
return true;
}
let Some(kw) = elixir_call_keyword(node, code) else {
return false;
};
if elixir_is_class_macro(kw) {
return true;
}
// A `def` / `defp` / `defmacro` / `defmacrop` nested inside a
// `quote do … end` template does NOT declare a method of any
// enclosing module — the syntax tree there is a code template
// emitted later, on macro expansion (#310).
elixir_is_method_macro(kw) && !elixir_is_inside_quote_block(node, code)
}
fn is_func_with_code(node: &Node, code: &[u8]) -> bool {
use crate::metrics::cognitive::{
elixir_call_keyword, elixir_is_inside_quote_block, elixir_is_method_macro,
};
let Some(kw) = elixir_call_keyword(node, code) else {
return false;
};
elixir_is_method_macro(kw) && !elixir_is_inside_quote_block(node, code)
}
fn promotes_to_func_space_with_code(node: &Node, code: &[u8]) -> bool {
use crate::metrics::cognitive::{
elixir_call_keyword, elixir_is_class_macro, elixir_is_inside_quote_block,
elixir_is_method_macro,
};
// Cheap path: byte-less `is_func_space` matches `Source` and
// `AnonymousFunction` without needing any text inspection.
if Self::is_func_space(node) {
return true;
}
// Otherwise one `elixir_call_keyword` lookup answers the
// combined question instead of the two the default impl would
// have made via `is_func_with_code || is_func_space_with_code`.
let Some(kw) = elixir_call_keyword(node, code) else {
return false;
};
if elixir_is_class_macro(kw) {
return true;
}
elixir_is_method_macro(kw) && !elixir_is_inside_quote_block(node, code)
}
fn is_closure(node: &Node) -> bool {
node.kind_id() == Elixir::AnonymousFunction
}
fn is_call(node: &Node) -> bool {
node.kind_id() == Elixir::Call
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Elixir::LPAREN | Elixir::LPAREN2 | Elixir::RPAREN | Elixir::COMMA
)
}
impl_simple_is_string!(Elixir, String, Charlist, Sigil);
// Elixir lacks an `else if` chain construct. Multi-way branching uses
// `cond do ... end` (a `Call` whose `do_block` holds many
// `stab_clause`s, each `+1` nesting in cognitive) or nested
// `if/else`. No tail-recursive chain to collapse here.
#[inline]
fn is_else_if(_: &Node) -> bool {
false
}
fn is_primitive(_: u16) -> bool {
false
}
}
impl Checker for RubyCode {
fn is_comment(node: &Node) -> bool {
node.kind_id() == Ruby::Comment
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Ruby::Program
| Ruby::Method
| Ruby::SingletonMethod
| Ruby::Lambda
| Ruby::Block
| Ruby::DoBlock
| Ruby::Class
| Ruby::SingletonClass
| Ruby::Module
)
}
fn is_func(node: &Node) -> bool {
matches!(node.kind_id().into(), Ruby::Method | Ruby::SingletonMethod)
}
fn is_closure(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Ruby::Lambda | Ruby::Block | Ruby::DoBlock
)
}
// tree-sitter-ruby 0.23.1 emits four aliased visible variants of the
// `call` rule (`Call`, `Call2`, `Call3`, `Call4`); `Call5` ("_call")
// is the hidden inner production and does not surface.
fn is_call(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Ruby::Call | Ruby::Call2 | Ruby::Call3 | Ruby::Call4
)
}
fn is_non_arg(node: &Node) -> bool {
// `PIPE` is included because block parameter lists are delimited
// by `|` rather than parentheses (e.g. `[1,2,3].each { |x| … }`).
matches!(
node.kind_id().into(),
Ruby::LPAREN
| Ruby::LPAREN2
| Ruby::RPAREN
| Ruby::RPAREN2
| Ruby::COMMA
| Ruby::SEMI
| Ruby::PIPE
)
}
impl_simple_is_string!(
Ruby,
String,
ChainedString,
BareString,
Subshell,
Regex,
HeredocBody,
DelimitedSymbol,
SimpleSymbol,
StringArray,
SymbolArray,
Character,
);
// tree-sitter-ruby exposes `elsif` as its own named clause node, so the
// dedicated-clause-node strategy applies here (same as Lua/Bash/PHP).
#[inline]
fn is_else_if(node: &Node) -> bool {
node.kind_id() == Ruby::Elsif
}
fn is_primitive(_: u16) -> bool {
false
}
}
impl Checker for GroovyCode {
fn is_comment(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Groovy::LineComment | Groovy::BlockComment
)
}
fn is_useful_comment(_: &Node, _: &[u8]) -> bool {
false
}
// Mirrors `impl Checker for JavaCode` exactly: `EnumDeclaration`,
// `RecordDeclaration`, and `AnnotationTypeDeclaration` open class
// spaces so `Npa`/`Npm`/`Wmc` walk their bodies. Cross-language parity
// with Java is the point — identical-shape sources must agree on
// class-shaped metrics (issue #280).
fn is_func_space(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Groovy::SourceFile
| Groovy::ClassDeclaration
| Groovy::TraitDeclaration
| Groovy::InterfaceDeclaration
| Groovy::EnumDeclaration
| Groovy::RecordDeclaration
| Groovy::AnnotationTypeDeclaration
)
}
fn is_func(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Groovy::MethodDeclaration | Groovy::ConstructorDeclaration
)
}
fn is_closure(node: &Node) -> bool {
matches!(node.kind_id().into(), Groovy::Closure)
}
// `command_chain` is the new grammar's distinct node for Groovy's
// command-style juxtaposed calls (`foo bar baz`) which the prior
// amaanq grammar mis-modelled as `juxt_function_call`.
fn is_call(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Groovy::MethodInvocation | Groovy::CommandChain | Groovy::ObjectCreationExpression
)
}
fn is_non_arg(node: &Node) -> bool {
matches!(
node.kind_id().into(),
Groovy::LPAREN | Groovy::COMMA | Groovy::RPAREN
)
}
impl_simple_is_string!(Groovy, StringLiteral);
// The dekobon Groovy grammar models `if_statement` with the `else`
// keyword token emitted inline followed by the inner `if_statement`
// sibling — same shape as the prior amaanq grammar and Java.
#[inline]
fn is_else_if(node: &Node) -> bool {
node.kind_id() == Groovy::IfStatement
&& node
.previous_sibling()
.is_some_and(|prev| prev.kind_id() == Groovy::Else)
}
fn is_primitive(_: u16) -> bool {
false
}
}
#[cfg(test)]
#[allow(
clippy::float_cmp,
clippy::cast_precision_loss,
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::similar_names,
clippy::doc_markdown,
clippy::needless_raw_string_hashes,
clippy::too_many_lines
)]
mod tests {
use super::*;
use crate::count::count;
use crate::langs::{
BashParser, JavascriptParser, MozjsParser, PhpParser, TsxParser, TypescriptParser,
};
use std::path::PathBuf;
fn parse(source: &str) -> BashParser {
BashParser::new(source.as_bytes().to_vec(), &PathBuf::from("test.sh"), None)
}
fn count_strings(source: &str) -> usize {
count(&parse(source), &["string".to_string()]).0
}
// `count`'s filter parser accepts a numeric string as a `kind_id` match
// (parser.rs `get_filters`), so `has_kind` reuses the same primitive.
fn has_kind(source: &str, kind_id: u16) -> bool {
count(&parse(source), &[kind_id.to_string()]).0 > 0
}
#[test]
fn bash_is_string_excludes_word_tokens() {
// `echo hello world` produces three Word nodes — none of them are
// string literals. Regression for #44 (Word must not match
// is_string).
assert_eq!(count_strings("echo hello world\n"), 0);
assert_eq!(
count_strings("if [ -f file.txt ]; then cat file.txt; fi\n"),
0
);
}
#[test]
fn bash_is_string_matches_quoted_literals() {
// Regular double-quoted string -> `string` (Bash::String).
assert_eq!(count_strings("echo \"double\"\n"), 1);
// Single-quoted string -> `raw_string` (Bash::RawString).
assert_eq!(count_strings("echo 'single'\n"), 1);
// ANSI-C quoting -> `ansi_c_string` (Bash::AnsiCString).
assert_eq!(count_strings("echo $'ansi-c'\n"), 1);
}
#[test]
fn bash_is_string_matches_translated_string() {
// tree-sitter-bash only emits a visible `translated_string` node
// in assignment-style contexts; in command arguments the `$"..."`
// tokenizes as `$` plus a regular `string`. Use an assignment so
// the wrapper actually appears in the AST.
let src = "x=$\"translated\"\n";
assert!(
has_kind(src, Bash::TranslatedString as u16),
"expected a translated_string node in {src:?}"
);
// The wrapper plus its inner `string` child both match is_string,
// so count is 2.
assert_eq!(count_strings(src), 2);
}
#[test]
fn bash_is_string_matches_heredoc_bodies() {
// Plain heredoc body.
assert_eq!(
count_strings("cat <<EOF\nhello world\nEOF\n"),
1,
"heredoc body should be counted as a string literal"
);
// Quoted-tag heredoc disables expansions but is still a string.
assert_eq!(
count_strings("cat <<'EOF'\nliteral $not_expanded\nEOF\n"),
1
);
// Heredoc with an embedded expansion still yields exactly one
// body node (parallel to a JS template string with `${x}`).
assert_eq!(count_strings("cat <<EOF\nhi $name\nEOF\n"), 1);
}
// ===== PHP `is_string` regression tests (issue #288) =====
fn parse_php(source: &str) -> PhpParser {
PhpParser::new(source.as_bytes().to_vec(), &PathBuf::from("test.php"), None)
}
fn count_php_strings(source: &str) -> usize {
count(&parse_php(source), &["string".to_string()]).0
}
#[test]
fn php_is_string_matches_single_quoted_literal() {
// `Php::String` is the named single-quoted literal. Inert
// single-quoted strings have always been matched; this anchors
// the baseline before exercising the alias kinds.
assert_eq!(count_php_strings("<?php $x = 'single';"), 1);
}
#[test]
fn php_is_string_matches_encapsed_heredoc_nowdoc_shell() {
// `EncapsedString` (double-quoted), `Heredoc`, `Nowdoc`, and
// `ShellCommandExpression` (backticks) must all match
// `is_string`. Pre-#288 the alterator/checker arms were almost
// aligned for these named literals — this test locks in the
// shape.
assert_eq!(count_php_strings("<?php $x = \"double\";"), 1);
assert_eq!(
count_php_strings("<?php $x = <<<EOT\nbody\nEOT;\n"),
1,
"heredoc should match is_string"
);
assert_eq!(
count_php_strings("<?php $x = <<<'EOT'\nbody\nEOT;\n"),
1,
"nowdoc should match is_string"
);
assert_eq!(
count_php_strings("<?php $x = `ls`;"),
1,
"shell command (backtick) should match is_string"
);
}
#[test]
fn php_is_string_matches_string_alias_kinds() {
// Regression for #288. Before the fix, only `Php::String`
// (kind_id 368, the named single-quoted literal) matched
// `is_string`. The `Php::String2` (anonymous `string` type
// keyword, kind_id 25) and `Php::String3` (the hidden `_string`
// supertype, kind_id 378) alias kinds — both of which the
// language enum maps to `"string"` — were missed. A function
// with a `: string` return type produces a `Php::String2`
// anonymous-keyword node, so we exercise it here. The named
// `Php::String` literal in the body matches too.
let src = "<?php function f(): string { return 'x'; }";
// Two string-matching nodes: the `string` return-type keyword
// (Php::String2) and the `'x'` literal (Php::String). Pre-fix
// only the literal matched (count would be 1).
assert_eq!(count_php_strings(src), 2);
}
// ===== JS-family `is_string` regression tests (issue #283) =====
// Walk the AST and return true iff any node has `kind_id == target`.
// Used to confirm an alias kind actually surfaces in a real parse
// before asserting it routes through `is_string`.
fn ast_has_kind_id<P: ParserTrait>(parser: &P, target: u16) -> bool {
let mut stack = vec![parser.get_root()];
while let Some(node) = stack.pop() {
if node.kind_id() == target {
return true;
}
for i in (0..node.child_count()).rev() {
if let Some(c) = node.child(i) {
stack.push(c);
}
}
}
false
}
// For each language, count nodes whose kind_id is exactly `target`
// *and* simultaneously match `is_string`. A non-zero result proves
// both that the alias appears in the parse and that the checker
// accepts it. Pre-fix this would be zero for the alias kinds.
fn count_string_matches_for_kind<P: ParserTrait, F: Fn(&Node) -> bool>(
parser: &P,
target: u16,
is_string: F,
) -> usize {
let mut stack = vec![parser.get_root()];
let mut hits = 0;
while let Some(node) = stack.pop() {
if node.kind_id() == target && is_string(&node) {
hits += 1;
}
for i in (0..node.child_count()).rev() {
if let Some(c) = node.child(i) {
stack.push(c);
}
}
}
hits
}
#[test]
fn javascript_is_string_matches_string2_alias() {
// `Javascript::String2` (kind_id 221) aliases to `"string"`
// (see `language_javascript.rs`). The alterator already
// flattens it (#119); the generic `string` filter must agree
// (#283). Use a source mix that exercises both the primary
// `String` and the anonymous `String2` productions.
let src = "const a = 'single';\nconst b = \"double\";\nimport \"m\";\n";
let parser = JavascriptParser::new(src.as_bytes().to_vec(), &PathBuf::from("t.js"), None);
// First confirm String2 actually surfaces in this parse —
// otherwise the assertion below would be vacuously true.
assert!(
ast_has_kind_id(&parser, Javascript::String2 as u16),
"expected Javascript::String2 to appear in the parse",
);
// Then assert every String2 node matches is_string.
assert!(
count_string_matches_for_kind(
&parser,
Javascript::String2 as u16,
JavascriptCode::is_string,
) > 0,
"Javascript::String2 nodes must match is_string",
);
}
#[test]
fn mozjs_is_string_matches_string2_alias() {
// Parallel coverage for the MozJS dialect; same `String2`
// alias as upstream JavaScript (kind_id 220 here).
let src = "const a = 'single';\nconst b = \"double\";\nimport \"m\";\n";
let parser = MozjsParser::new(src.as_bytes().to_vec(), &PathBuf::from("t.js"), None);
assert!(
ast_has_kind_id(&parser, Mozjs::String2 as u16),
"expected Mozjs::String2 to appear in the parse",
);
assert!(
count_string_matches_for_kind(&parser, Mozjs::String2 as u16, MozjsCode::is_string) > 0,
"Mozjs::String2 nodes must match is_string",
);
}
#[test]
fn typescript_is_string_matches_string2_alias() {
// TypeScript exposes both the primary `String` literal and
// a `String2` alias (kind_id 135). The latter sits among the
// type-keyword tokens in the enum, so a `: string` annotation
// is a reliable producer.
let src = "const a: string = 'x';\nfunction f(): string { return 'y'; }\n";
let parser = TypescriptParser::new(src.as_bytes().to_vec(), &PathBuf::from("t.ts"), None);
assert!(
ast_has_kind_id(&parser, Typescript::String2 as u16),
"expected Typescript::String2 to appear in the parse",
);
assert!(
count_string_matches_for_kind(
&parser,
Typescript::String2 as u16,
TypescriptCode::is_string,
) > 0,
"Typescript::String2 nodes must match is_string",
);
}
#[test]
fn tsx_is_string_matches_string2_and_string3_aliases() {
// TSX uniquely carries two anonymous `"string"` aliases:
// `String3` (kind_id 141, the type-annotation keyword) and
// `String2` (kind_id 261). Both must appear in this fixture:
// the `: string` annotation produces `String3`, and the
// `'x'` / `"y"` / `"m"` / `"c"` literals produce `String2`.
// Asserting presence of both *before* checking `is_string`
// ensures a future grammar bump that stops emitting either
// alias fails loudly here rather than silently dropping
// coverage (which would invalidate the regression for #283).
let src = "const a: string = 'x';\n\
const b = \"y\";\n\
import \"m\";\n\
const el = <div className=\"c\">{\"t\"}</div>;\n";
let parser = TsxParser::new(src.as_bytes().to_vec(), &PathBuf::from("t.tsx"), None);
assert!(
ast_has_kind_id(&parser, Tsx::String3 as u16),
"expected Tsx::String3 (type-keyword `string`) in the parse",
);
assert!(
ast_has_kind_id(&parser, Tsx::String2 as u16),
"expected Tsx::String2 (string-literal alias) in the parse",
);
assert!(
count_string_matches_for_kind(&parser, Tsx::String3 as u16, TsxCode::is_string) > 0,
"Tsx::String3 nodes must match is_string",
);
assert!(
count_string_matches_for_kind(&parser, Tsx::String2 as u16, TsxCode::is_string) > 0,
"Tsx::String2 nodes must match is_string",
);
}
// Walk the AST and return the first node whose `kind_id` equals
// `target`. Used by the `is_else_if` tests below to fish a
// specific node out of the parse tree without depending on the
// `count` helper above.
fn find_first_kind<P: ParserTrait>(parser: &P, target: u16) -> Option<Node<'_>> {
let mut stack = vec![parser.get_root()];
while let Some(node) = stack.pop() {
if node.kind_id() == target {
return Some(node);
}
for i in (0..node.child_count()).rev() {
if let Some(c) = node.child(i) {
stack.push(c);
}
}
}
None
}
#[test]
fn groovy_is_else_if_recognises_else_followed_by_if() {
// Direct assertion that `GroovyCode::is_else_if` returns true
// for an `if_statement` whose previous sibling is the `else`
// token. Defends the sibling-token strategy against accidental
// regression to a `false` stub (lesson 10, #115 / #239).
let src = "if (x) { } else if (y) { } else { }";
let parser =
GroovyParser::new(src.as_bytes().to_vec(), &PathBuf::from("test.groovy"), None);
let outer =
find_first_kind(&parser, Groovy::IfStatement as u16).expect("outer if_statement");
// Locate the inner if_statement (in the `alternative` slot of
// the outer if, after the `else` token).
let mut inner: Option<Node> = None;
for i in 0..outer.child_count() {
if let Some(c) = outer.child(i)
&& c.kind_id() == Groovy::IfStatement as u16
{
inner = Some(c);
break;
}
}
let inner = inner.expect("expected an inner if_statement");
assert!(
GroovyCode::is_else_if(&inner),
"inner if_statement after `else` must be recognised as else-if"
);
assert!(
!GroovyCode::is_else_if(&outer),
"outer if_statement must not be recognised as else-if"
);
}
#[test]
fn groovy_is_else_if_false_for_standalone_if() {
// A bare `if` (no `else` preceding it) must NOT register as
// an else-if.
let src = "if (x) { println(x) }";
let parser =
GroovyParser::new(src.as_bytes().to_vec(), &PathBuf::from("test.groovy"), None);
let node = find_first_kind(&parser, Groovy::IfStatement as u16).expect("if_statement");
assert!(!GroovyCode::is_else_if(&node));
}
fn parse_python(src: &str) -> PythonParser {
PythonParser::new(src.as_bytes().to_vec(), &PathBuf::from("test.py"), None)
}
// Walk the AST and return every node whose `kind_id` equals `target`,
// in DFS pre-order. Used by the Python `is_else_if` tests below to
// distinguish the outer if from the inner one in an `else: if` chain.
fn find_all_kinds<P: ParserTrait>(parser: &P, target: u16) -> Vec<Node<'_>> {
let mut out = Vec::new();
let mut stack = vec![parser.get_root()];
while let Some(node) = stack.pop() {
if node.kind_id() == target {
out.push(node);
}
for i in (0..node.child_count()).rev() {
if let Some(c) = node.child(i) {
stack.push(c);
}
}
}
out
}
#[test]
fn python_is_else_if_recognises_if_inside_else_clause() {
// `else: if b:` chains parse as `else_clause → block → if_statement`
// (the `block` wrapper is Python-specific). `is_else_if` must
// walk through that wrapper. Regression for #276 (the stub
// returned `false` unconditionally).
let src = "if a:\n pass\nelse:\n if b:\n pass\n";
let parser = parse_python(src);
let outer =
find_first_kind(&parser, Python::IfStatement as u16).expect("outer if_statement");
let inner =
find_python_if_inside_else_block(&parser).expect("inner if_statement under else");
assert!(
PythonCode::is_else_if(&inner),
"if_statement inside else_clause's block must be recognised as else-if"
);
assert!(
!PythonCode::is_else_if(&outer),
"outer if_statement must not be recognised as else-if"
);
}
#[test]
fn python_is_else_if_false_for_standalone_if() {
// A bare `if` whose parent is the module / function body must
// NOT register as an else-if.
let src = "if a:\n pass\n";
let parser = parse_python(src);
let node = find_first_kind(&parser, Python::IfStatement as u16).expect("if_statement");
assert!(!PythonCode::is_else_if(&node));
}
#[test]
fn python_is_else_if_false_for_outer_if_with_elif_alternative() {
// `elif` parses as an `ElifClause`, not an `IfStatement`, so the
// only `IfStatement` in `if … elif …` is the outer one. Its
// parent is the module / function body, not an `else_clause`.
// Pins that the presence of `elif` in the AST does not trip
// `is_else_if` for the outer `if`.
let src = "if a:\n pass\nelif b:\n pass\n";
let parser = parse_python(src);
let outer = find_first_kind(&parser, Python::IfStatement as u16).expect("if_statement");
assert!(!PythonCode::is_else_if(&outer));
}
// Return the inner `if_statement` that sits directly inside an
// `else_clause`'s `block` wrapper, or `None` if no such node exists.
// Used by tests below instead of relying on `find_all_kinds`'s DFS
// pre-order to land at `ifs[1]`.
fn find_python_if_inside_else_block(parser: &PythonParser) -> Option<Node<'_>> {
find_all_kinds(parser, Python::IfStatement as u16)
.into_iter()
.find(|n| {
n.parent().is_some_and(|p| {
matches!(p.kind_id().into(), Python::Block | Python::Block2)
&& p.parent()
.is_some_and(|gp| gp.kind_id() == Python::ElseClause)
})
})
}
#[test]
fn python_is_else_if_false_when_else_body_has_siblings() {
// `else: if b:` followed by another statement at the same indent
// is a real nested-if, not a chain. The block has 2 named
// children, so `is_else_if` must return false.
let src = "if a:\n pass\nelse:\n if b:\n pass\n pass\n";
let parser = parse_python(src);
let inner =
find_python_if_inside_else_block(&parser).expect("inner if_statement under else");
assert!(
!PythonCode::is_else_if(&inner),
"inner if must NOT be recognised as else-if when its block has siblings"
);
}
// Regression for #301: every language consolidated under
// `impl_simple_is_string!` must still recognise its canonical
// string literal via the `"string"` filter (which routes through
// `Checker::is_string`). The positive test now drills down to
// every individual variant of every multi-variant language so a
// future macro invocation that drops a variant (e.g. forgetting
// `Cpp::ConcatenatedString` after a grammar bump) fails loudly.
//
// JS-family languages (Mozjs/Javascript/Typescript/Tsx) keep
// their dedicated `impl_js_family_is_string!` macro and have
// their own alias-aware tests above; they are intentionally
// not duplicated here.
fn count_with_parser<P: ParserTrait>(parser: &P) -> usize {
count(parser, &["string".to_string()]).0
}
// Assert that `target` kind_id appears in the parse and every
// such node matches `is_string`. The two-step check makes test
// failures unambiguous: a presence failure means the fixture no
// longer produces the variant (likely grammar drift); a match
// failure means a macro invocation dropped the variant.
fn assert_variant_is_string<P: ParserTrait, F: Fn(&Node) -> bool>(
parser: &P,
target: u16,
is_string: F,
lang: &str,
variant: &str,
) {
assert!(
ast_has_kind_id(parser, target),
"{lang}::{variant} (kind_id {target}) did not appear in the parse — fixture broken",
);
assert!(
count_string_matches_for_kind(parser, target, is_string) > 0,
"{lang}::{variant} must route through is_string",
);
}
// Collapses the 6-line-per-variant `assert_variant_is_string`
// call into a single token per variant. `$lang` is the language
// enum (e.g. `Cpp`); `$code` is the `Checker`-implementing type
// (e.g. `CppCode`); the trailing list names the enum variants to
// exercise. The macro feeds `stringify!` for both the language
// and variant labels so test failures keep the same "Lang::Variant"
// wording the helper already emits.
macro_rules! assert_variants_is_string {
($parser:expr, $lang:ident, $code:ident, [$($variant:ident),+ $(,)?]) => {
$(
assert_variant_is_string(
$parser,
$lang::$variant as u16,
$code::is_string,
stringify!($lang),
stringify!($variant),
);
)+
};
}
// Parse `$src` with `$parser_ty` and assert the generic `"string"`
// filter yields zero matches. Used by the negative test, which
// walks 17 languages with identical per-language shape (parse →
// count → assert_eq! 0).
macro_rules! assert_no_string_matches {
($parser_ty:ident, $path:expr, $src:expr, $lang:literal $(,)?) => {{
let parser = $parser_ty::new($src.to_vec(), $path, None);
assert_eq!(count_with_parser(&parser), 0, $lang);
}};
}
#[test]
fn simple_is_string_macro_recognises_each_language() {
use crate::langs::{
CcommentParser, CppParser, CsharpParser, ElixirParser, GoParser, GroovyParser,
JavaParser, KotlinParser, LuaParser, PerlParser, PreprocParser, PythonParser,
RubyParser, RustParser, TclParser,
};
let path = PathBuf::from("test");
// ---- Preproc (2 variants): StringLiteral, RawStringLiteral ----
let src = b"#include \"foo.h\"\nR\"(raw)\"\n".to_vec();
let parser = PreprocParser::new(src, &path, None);
assert_variants_is_string!(
&parser,
Preproc,
PreprocCode,
[StringLiteral, RawStringLiteral]
);
// ---- Ccomment (2 variants): StringLiteral, RawStringLiteral ----
// The Ccomment grammar is a stub that only emits Comment /
// StringLiteral / RawStringLiteral; feed it both forms.
let src = b"\"hello\"\nR\"(raw)\"\n".to_vec();
let parser = CcommentParser::new(src, &path, None);
assert_variants_is_string!(
&parser,
Ccomment,
CcommentCode,
[StringLiteral, RawStringLiteral]
);
// ---- Cpp (3 variants): StringLiteral, ConcatenatedString, RawStringLiteral ----
// C++ string concatenation (`"a" "b"`) produces a
// `concatenated_string` node wrapping the literals.
let src =
b"const char* a = \"hi\";\nconst char* b = \"a\" \"b\";\nconst char* c = R\"(raw)\";\n"
.to_vec();
let parser = CppParser::new(src, &path, None);
assert_variants_is_string!(
&parser,
Cpp,
CppCode,
[StringLiteral, ConcatenatedString, RawStringLiteral]
);
// ---- Python (2 variants): String, ConcatenatedString ----
// Python concatenates adjacent string literals into a
// `concatenated_string` node.
let src = b"a = \"hi\"\nb = \"a\" \"b\"\n".to_vec();
let parser = PythonParser::new(src, &path, None);
assert_variants_is_string!(&parser, Python, PythonCode, [String, ConcatenatedString]);
// ---- Java (2 variants): StringLiteral, MultilineStringLiteral ----
// `Java::MultilineStringLiteral` maps to `_multiline_string_literal`
// (leading-underscore hidden supertype) and does NOT surface as a
// concrete kind_id in observed parses. Triple-quoted text blocks
// instead produce regular `StringLiteral` nodes. The variant is
// intentionally listed in the macro so a future grammar revision
// that promotes it can't bypass `is_string`; presence is asserted
// below to flag drift.
let src = b"class C { String a = \"hi\"; String b = \"\"\"\nmulti\n\"\"\"; }\n".to_vec();
let parser = JavaParser::new(src, &path, None);
assert_variants_is_string!(&parser, Java, JavaCode, [StringLiteral]);
assert!(
!ast_has_kind_id(&parser, Java::MultilineStringLiteral as u16),
"Java::MultilineStringLiteral is documented as the hidden _multiline_string_literal supertype; if it now appears in parses, replace this with a positive variant assertion",
);
// ---- Csharp (4 variants): StringLiteral, VerbatimStringLiteral,
// RawStringLiteral, InterpolatedStringExpression ----
// Verbatim: `@"..."`; raw: triple-double-quote; interpolated: `$"..."`.
let src = b"class C { string a = \"hi\"; string b = @\"verb\"; string c = \"\"\"raw\"\"\"; string d = $\"int{1}\"; }\n".to_vec();
let parser = CsharpParser::new(src, &path, None);
assert_variants_is_string!(
&parser,
Csharp,
CsharpCode,
[
StringLiteral,
VerbatimStringLiteral,
RawStringLiteral,
InterpolatedStringExpression,
]
);
// ---- Rust (2 variants): StringLiteral, RawStringLiteral ----
let src = b"fn main() { let a = \"hi\"; let b = r\"raw\"; }\n".to_vec();
let parser = RustParser::new(src, &path, None);
assert_variants_is_string!(&parser, Rust, RustCode, [StringLiteral, RawStringLiteral]);
// ---- Go (2 variants): InterpretedStringLiteral, RawStringLiteral ----
// Backtick-delimited string is the raw form.
let src = b"package main\nfunc main() { _ = \"hi\"; _ = `raw` }\n".to_vec();
let parser = GoParser::new(src, &path, None);
assert_variants_is_string!(
&parser,
Go,
GoCode,
[InterpretedStringLiteral, RawStringLiteral]
);
// ---- Kotlin (2 variants): StringLiteral, MultilineStringLiteral ----
let src = b"fun main() { val a = \"hi\"; val b = \"\"\"multi\"\"\" }\n".to_vec();
let parser = KotlinParser::new(src, &path, None);
assert_variants_is_string!(
&parser,
Kotlin,
KotlinCode,
[StringLiteral, MultilineStringLiteral]
);
// ---- Lua (1 variant): String ----
let src = b"local a = \"hi\"\nlocal b = [[long]]\n".to_vec();
let parser = LuaParser::new(src, &path, None);
assert_variants_is_string!(&parser, Lua, LuaCode, [String]);
// ---- Perl (7 variants): StringSingleQuoted, StringDoubleQuoted,
// StringQQuoted, StringQqQuoted, BacktickQuoted, CommandQxQuoted,
// HeredocBodyStatement ----
let src = b"my $a = 'single';\nmy $b = \"double\";\nmy $c = q(qquoted);\nmy $d = qq(qqquoted);\nmy $e = `cmd`;\nmy $f = qx(qxcmd);\nmy $g = <<EOT;\nbody\nEOT\n".to_vec();
let parser = PerlParser::new(src, &path, None);
assert_variants_is_string!(
&parser,
Perl,
PerlCode,
[
StringSingleQuoted,
StringDoubleQuoted,
StringQQuoted,
StringQqQuoted,
BacktickQuoted,
CommandQxQuoted,
HeredocBodyStatement,
]
);
// ---- Bash (5 variants): String, RawString, AnsiCString,
// TranslatedString, HeredocBody2 ----
// TranslatedString surfaces as a wrapper node only in
// assignment-style contexts (see `bash_is_string_matches_translated_string`).
let src = b"a=\"d\"\nb='r'\nc=$'ansi'\nd=$\"t\"\ncat <<EOF\nbody\nEOF\n".to_vec();
let parser = crate::langs::BashParser::new(src, &path, None);
assert_variants_is_string!(
&parser,
Bash,
BashCode,
[
String,
RawString,
AnsiCString,
TranslatedString,
HeredocBody2
]
);
// ---- Tcl (3 variants): QuotedWord, BracedWord, BracedWordSimple ----
// Tcl uses two `braced_word` rules: the named rule `braced_word`
// (an argument-position braced expression that admits commands
// and substitutions, e.g. `proc ... { body }`'s `body` arg) and
// `braced_word_simple` (a plain inert braced word like
// `{braced}` in `set v {braced}`). The fixture below mixes a
// `proc ... {body}` (BracedWord), a simple `set` assignment
// (BracedWordSimple), and a `set` to a quoted literal
// (QuotedWord).
let src = b"set a \"quoted\"\nset b {braced}\nproc p {x y} { return $x }\n".to_vec();
let parser = TclParser::new(src, &path, None);
assert_variants_is_string!(
&parser,
Tcl,
TclCode,
[QuotedWord, BracedWordSimple, BracedWord]
);
// ---- Php (7 variants): String, String2, String3,
// EncapsedString, Heredoc, Nowdoc, ShellCommandExpression ----
// String2 is the `string` type-keyword (`: string` return
// type, exercised here). String3 is the hidden `_string`
// supertype (kind_id => "_string" — name starts with `_`),
// which tree-sitter does NOT emit as a concrete node — see
// its empirical absence asserted below.
let src = b"<?php function f(): string { $a = 'single'; $b = \"double\"; $c = <<<EOT\nbody\nEOT;\n$d = <<<'EOT'\nnow\nEOT;\n$e = `ls`; return $a; }\n".to_vec();
let parser = PhpParser::new(src, &path, None);
assert_variants_is_string!(&parser, Php, PhpCode, [String, String2]);
// `Php::String3` is the hidden `_string` supertype — never
// surfaces as a concrete kind_id in observed parses; the
// checker still lists it so future grammar revisions that
// promote it cannot silently bypass `is_string`. Verified
// unreachable empirically (assertion below proves the
// fixture does not produce it; the variant is intentionally
// unverifiable through a positive test until then).
assert!(
!ast_has_kind_id(&parser, Php::String3 as u16),
"Php::String3 is documented as the hidden _string supertype; if it now appears in parses, add a positive variant assertion",
);
assert_variants_is_string!(
&parser,
Php,
PhpCode,
[EncapsedString, Heredoc, Nowdoc, ShellCommandExpression]
);
// ---- Elixir (3 variants): String, Charlist, Sigil ----
// Charlists use single quotes; sigils use `~s(...)` etc.
let src = b"a = \"hi\"\nb = 'charlist'\nc = ~s(sigil)\n".to_vec();
let parser = ElixirParser::new(src, &path, None);
assert_variants_is_string!(&parser, Elixir, ElixirCode, [String, Charlist, Sigil]);
// ---- Ruby (11 variants): String, ChainedString, BareString,
// Subshell, Regex, HeredocBody, DelimitedSymbol, SimpleSymbol,
// StringArray, SymbolArray, Character ----
// ChainedString: two adjacent string literals (`"a" "b"`).
// BareString: an unquoted element inside `%w[...]` / inside
// a string array context. `%w[bare1 bare2]` emits a
// StringArray whose children are BareString nodes — both
// surface in the parse. Use a script that produces every
// form so the per-variant assertion can hit each.
let src = b"a = \"hi\"\nb = \"x\" \"y\"\nc = `cmd`\nd = /re/\ne = <<EOT\nbody\nEOT\nf = :sym\ng = :\"dsym\"\nh = %w[bare1 bare2]\ni = %i[s1 s2]\nj = ?A\n".to_vec();
let parser = RubyParser::new(src, &path, None);
assert_variants_is_string!(
&parser,
Ruby,
RubyCode,
[
String,
ChainedString,
BareString,
Subshell,
Regex,
HeredocBody,
DelimitedSymbol,
SimpleSymbol,
StringArray,
SymbolArray,
Character,
]
);
// ---- Groovy (1 variant): StringLiteral ----
// The dekobon Groovy grammar consolidates every string shape
// (single / double / triple-quoted, slashy `/.../`, dollar-
// slashy `$/.../$`, GString-interpolated) under one
// `string_literal` rule, so a single variant suffices —
// unlike Java, character literals are not a separate node.
let src =
b"def m() { def a = \"hi\"; def b = \"\"\"multi\"\"\"; def c = /pat/ }\n".to_vec();
let parser = GroovyParser::new(src, &path, None);
assert_variants_is_string!(&parser, Groovy, GroovyCode, [StringLiteral]);
}
#[test]
fn simple_is_string_macro_rejects_non_string_nodes() {
// Pure-identifier source must produce zero string matches.
// Catches a regression where a macro invocation accidentally
// included a too-broad variant (e.g. `Identifier`). Covers
// every language consolidated under `impl_simple_is_string!`.
use crate::langs::{
BashParser, CcommentParser, CppParser, CsharpParser, ElixirParser, GoParser,
GroovyParser, JavaParser, KotlinParser, LuaParser, PerlParser, PreprocParser,
PythonParser, RubyParser, RustParser, TclParser,
};
let path = PathBuf::from("test");
// Each fixture is the most minimal identifier-only input that
// still parses for the target language. Per-language comments
// below flag the few cases where the input choice is load-
// bearing (Bash `s=$y` to avoid `string`-kind expansion nodes,
// Tcl `set x $y` to keep the bareword as `Word`, etc.).
assert_no_string_matches!(PreprocParser, &path, b"#define FOO 1\n", "Preproc");
// Ccomment: input that lexes as a single line comment only.
assert_no_string_matches!(CcommentParser, &path, b"// just a comment\n", "Ccomment");
assert_no_string_matches!(CppParser, &path, b"int main() { return x; }\n", "Cpp");
assert_no_string_matches!(PythonParser, &path, b"x = y\n", "Python");
assert_no_string_matches!(JavaParser, &path, b"class C { int x = y; }\n", "Java");
// Csharp: identifier-only field initializer.
assert_no_string_matches!(CsharpParser, &path, b"class C { int x = y; }\n", "Csharp");
assert_no_string_matches!(RustParser, &path, b"fn main() { let x = y; }\n", "Rust");
assert_no_string_matches!(
GoParser,
&path,
b"package main\nfunc main() { _ = x }\n",
"Go"
);
assert_no_string_matches!(KotlinParser, &path, b"fun main() { val x = y }\n", "Kotlin");
// Perl: identifier-only assignment with no quoted forms.
assert_no_string_matches!(PerlParser, &path, b"my $x = $y;\n", "Perl");
assert_no_string_matches!(LuaParser, &path, b"local x = y\n", "Lua");
// Bash: assignment of one variable to another, no literals.
// `s=$y` produces only Variable/SimpleExpansion nodes; no
// string-kind node should appear.
assert_no_string_matches!(BashParser, &path, b"s=$y\n", "Bash");
// Tcl: `set` of an unquoted identifier word. The unquoted
// bareword surfaces as `Word`, not any of the three string
// kinds.
assert_no_string_matches!(TclParser, &path, b"set x $y\n", "Tcl");
// Php: identifier-only assignment.
assert_no_string_matches!(PhpParser, &path, b"<?php $x = $y;\n", "Php");
// Elixir: integer assignment, no string/charlist/sigil.
assert_no_string_matches!(ElixirParser, &path, b"x = 1\n", "Elixir");
assert_no_string_matches!(RubyParser, &path, b"x = y\n", "Ruby");
// Groovy: identifier-only method body.
assert_no_string_matches!(GroovyParser, &path, b"def m() { def x = y }\n", "Groovy");
}
}