big-code-analysis 1.1.0

Tool to compute and export code metrics
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
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
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
// 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::doc_markdown,
    clippy::enum_glob_use,
    clippy::match_wildcard_for_single_variants,
    clippy::similar_names,
    clippy::unused_self,
    clippy::wildcard_imports
)]
// Metric counts (token, function, branch, argument, etc.) are stored as
// `usize` and crossed with `f64` averages, ratios, and Halstead scores
// across the cyclomatic / MI / Halstead computations. The `usize as f64`
// and `f64 as usize` casts are intentional and snapshot-anchored — every
// site is bounded by the count it came from. Allowing the lints at the
// module level keeps the metric arithmetic legible.
#![allow(
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss
)]

use std::collections::HashMap;

use serde::Serialize;
use serde::ser::{SerializeStruct, Serializer};
use std::fmt;

use crate::checker::Checker;
use crate::getter::Getter;
use crate::macros::implement_metric_trait;

use crate::*;

/// The `Halstead` metric suite.
#[derive(Default, Clone, Debug)]
pub struct Stats {
    u_operators: u64,
    operators: u64,
    u_operands: u64,
    operands: u64,
}

/// Specifies the type of nodes accepted by the `Halstead` metric.
pub enum HalsteadType {
    /// The node is an `Halstead` operator
    Operator,
    /// The node is an `Halstead` operand
    Operand,
    /// The node is unknown to the `Halstead` metric
    Unknown,
}

/// Per-space operator / operand occurrence maps used to compute the
/// Halstead `Stats` struct. One map per distinct operator (`kind_id`)
/// and one per distinct operand (`text`); merged across nested spaces.
#[derive(Debug, Default, Clone)]
pub struct HalsteadMaps<'a> {
    pub(crate) operators: HashMap<u16, u64>,
    /// Primitive-type operators stored by text so each distinct primitive
    /// (e.g. `int` vs `double`) counts as a separate distinct operator,
    /// even when the grammar maps them all to a single kind_id.
    pub(crate) primitive_operators: HashMap<&'a [u8], u64>,
    pub(crate) operands: HashMap<&'a [u8], u64>,
}

impl<'a> HalsteadMaps<'a> {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    pub(crate) fn merge(&mut self, other: &HalsteadMaps<'a>) {
        for (k, v) in &other.operators {
            *self.operators.entry(*k).or_insert(0) += v;
        }
        for (k, v) in &other.primitive_operators {
            *self.primitive_operators.entry(*k).or_insert(0) += v;
        }
        for (k, v) in &other.operands {
            *self.operands.entry(*k).or_insert(0) += v;
        }
    }

    pub(crate) fn finalize(&self, stats: &mut Stats) {
        stats.u_operators = (self.operators.len() + self.primitive_operators.len()) as u64;
        stats.operators =
            self.operators.values().sum::<u64>() + self.primitive_operators.values().sum::<u64>();
        stats.u_operands = self.operands.len() as u64;
        stats.operands = self.operands.values().sum::<u64>();
    }
}

impl Serialize for Stats {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut st = serializer.serialize_struct("halstead", 14)?;
        st.serialize_field("n1", &self.u_operators())?;
        st.serialize_field("N1", &self.operators())?;
        st.serialize_field("n2", &self.u_operands())?;
        st.serialize_field("N2", &self.operands())?;
        st.serialize_field("length", &self.length())?;
        st.serialize_field("estimated_program_length", &self.estimated_program_length())?;
        st.serialize_field("purity_ratio", &self.purity_ratio())?;
        st.serialize_field("vocabulary", &self.vocabulary())?;
        st.serialize_field("volume", &self.volume())?;
        st.serialize_field("difficulty", &self.difficulty())?;
        st.serialize_field("level", &self.level())?;
        st.serialize_field("effort", &self.effort())?;
        st.serialize_field("time", &self.time())?;
        st.serialize_field("bugs", &self.bugs())?;
        st.end()
    }
}

impl fmt::Display for Stats {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "n1: {}, \
             N1: {}, \
             n2: {}, \
             N2: {}, \
             length: {}, \
             estimated program length: {}, \
             purity ratio: {}, \
             size: {}, \
             volume: {}, \
             difficulty: {}, \
             level: {}, \
             effort: {}, \
             time: {}, \
             bugs: {}",
            self.u_operators(),
            self.operators(),
            self.u_operands(),
            self.operands(),
            self.length(),
            self.estimated_program_length(),
            self.purity_ratio(),
            self.vocabulary(),
            self.volume(),
            self.difficulty(),
            self.level(),
            self.effort(),
            self.time(),
            self.bugs(),
        )
    }
}

impl Stats {
    pub(crate) fn merge(&mut self, _other: &Stats) {}

    /// Returns `η1`, the number of distinct operators
    #[inline]
    #[must_use]
    pub fn u_operators(&self) -> f64 {
        self.u_operators as f64
    }

    /// Returns `N1`, the number of total operators
    #[inline]
    #[must_use]
    pub fn operators(&self) -> f64 {
        self.operators as f64
    }

    /// Returns `η2`, the number of distinct operands
    #[inline]
    #[must_use]
    pub fn u_operands(&self) -> f64 {
        self.u_operands as f64
    }

    /// Returns `N2`, the number of total operands
    #[inline]
    #[must_use]
    pub fn operands(&self) -> f64 {
        self.operands as f64
    }

    /// Returns the program length
    #[inline]
    #[must_use]
    pub fn length(&self) -> f64 {
        self.operands() + self.operators()
    }

    /// Returns the calculated estimated program length
    #[inline]
    #[must_use]
    pub fn estimated_program_length(&self) -> f64 {
        let uo = self.u_operators();
        let ud = self.u_operands();
        let uo_term = if uo == 0.0 { 0.0 } else { uo * uo.log2() };
        let ud_term = if ud == 0.0 { 0.0 } else { ud * ud.log2() };
        uo_term + ud_term
    }

    /// Returns the purity ratio
    #[inline]
    #[must_use]
    pub fn purity_ratio(&self) -> f64 {
        let len = self.length();
        if len == 0.0 {
            0.0
        } else {
            self.estimated_program_length() / len
        }
    }

    /// Returns the program vocabulary
    #[inline]
    #[must_use]
    pub fn vocabulary(&self) -> f64 {
        self.u_operands() + self.u_operators()
    }

    /// Returns the program volume.
    ///
    /// Unit of measurement: bits
    #[inline]
    #[must_use]
    pub fn volume(&self) -> f64 {
        // Assumes a uniform binary encoding for the vocabulary is used.
        let vocab = self.vocabulary();
        if vocab <= 1.0 {
            0.0
        } else {
            self.length() * vocab.log2()
        }
    }

    /// Returns the estimated difficulty required to program
    #[inline]
    #[must_use]
    pub fn difficulty(&self) -> f64 {
        let ud = self.u_operands();
        if ud == 0.0 {
            0.0
        } else {
            self.u_operators() / 2. * self.operands() / ud
        }
    }

    /// Returns the estimated level of difficulty required to program
    #[inline]
    #[must_use]
    pub fn level(&self) -> f64 {
        let d = self.difficulty();
        if d == 0.0 { 0.0 } else { 1. / d }
    }

    /// Returns the estimated effort required to program
    #[inline]
    #[must_use]
    pub fn effort(&self) -> f64 {
        self.difficulty() * self.volume()
    }

    /// Returns the estimated time required to program.
    ///
    /// Unit of measurement: seconds
    #[inline]
    #[must_use]
    pub fn time(&self) -> f64 {
        // The floating point `18.` aims to describe the processing rate of the
        // human brain. It is called Stoud number, S, and its
        // unit of measurement is moments/seconds.
        // A moment is the time required by the human brain to carry out the
        // most elementary decision.
        // 5 <= S <= 20. Halstead uses 18.
        // The value of S has been empirically developed from psychological
        // reasoning, and its recommended value for
        // programming applications is 18.
        //
        // Source: https://www.geeksforgeeks.org/software-engineering-halsteads-software-metrics/
        self.effort() / 18.
    }

    /// Returns the estimated number of delivered bugs.
    ///
    /// This metric represents the average amount of work a programmer can do
    /// without introducing an error.
    #[inline]
    #[must_use]
    pub fn bugs(&self) -> f64 {
        // The floating point `3000.` represents the number of elementary
        // mental discriminations.
        // A mental discrimination, in psychology, is the ability to perceive
        // and respond to differences among stimuli.
        //
        // The value above is obtained starting from a constant that
        // is different for every language and assumes that natural language is
        // the language of the brain.
        // For programming languages, the English language constant
        // has been considered.
        //
        // After every 3000 mental discriminations a result is produced.
        // This result, whether correct or incorrect, is more than likely
        // either used as an input for the next operation or is output to the
        // environment.
        // If incorrect the error should become apparent.
        // Thus, an opportunity for error occurs every 3000
        // mental discriminations.
        //
        // Source: https://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=1145&context=cstech
        self.effort().powf(2. / 3.) / 3000.
    }
}

#[doc(hidden)]
/// Per-language extraction of Halstead operator/operand maps.
pub trait Halstead
where
    Self: Checker + Getter,
{
    /// Walk `node` and update `stats` with this metric for the language
    /// implementing the trait.
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>);
}

#[inline]
fn get_id<'a>(node: &Node<'a>, code: &'a [u8]) -> &'a [u8] {
    &code[node.start_byte()..node.end_byte()]
}

#[inline]
fn compute_halstead<'a, T: Getter + Checker>(
    node: &Node<'a>,
    code: &'a [u8],
    halstead_maps: &mut HalsteadMaps<'a>,
) {
    match T::get_op_type(node) {
        HalsteadType::Operator => {
            if T::is_primitive(node.kind_id()) {
                // Store primitive-type operators by text so distinct
                // primitives (e.g. `int` vs `double`) that share a
                // single kind_id are counted separately in n1/N1.
                *halstead_maps
                    .primitive_operators
                    .entry(get_id(node, code))
                    .or_insert(0) += 1;
            } else {
                *halstead_maps.operators.entry(node.kind_id()).or_insert(0) += 1;
            }
        }
        HalsteadType::Operand => {
            *halstead_maps
                .operands
                .entry(get_id(node, code))
                .or_insert(0) += 1;
        }
        _ => {}
    }
}

impl Halstead for PythonCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for MozjsCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for JavascriptCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for TypescriptCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for TsxCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for RustCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for CppCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for JavaCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for GroovyCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for CsharpCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for GoCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for PerlCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for KotlinCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for LuaCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for PhpCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

// Real defaults — no operators / operands to count. Audited in #188.
implement_metric_trait!(Halstead, PreprocCode, CcommentCode);

impl Halstead for RubyCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for ElixirCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for BashCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

impl Halstead for TclCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], halstead_maps: &mut HalsteadMaps<'a>) {
        compute_halstead::<Self>(node, code, halstead_maps);
    }
}

#[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 crate::tools::check_metrics;

    use super::*;

    #[test]
    fn python_operators_and_operands() {
        check_metrics::<PythonParser>(
            "def foo():
                 def bar():
                     def toto():
                        a = 1 + 1
                     b = 2 + a
                 c = 3 + 3",
            "foo.py",
            |metric| {
                // unique operators: def, =, +
                // operators: def, def, def, =, =, =, +, +, +
                // unique operands: foo, bar, toto, a, b, c, 1, 2, 3
                // operands: foo, bar, toto, a, b, c, 1, 1, 2, a, 3, 3
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r###"
                    {
                      "n1": 3.0,
                      "N1": 9.0,
                      "n2": 9.0,
                      "N2": 12.0,
                      "length": 21.0,
                      "estimated_program_length": 33.284212515144276,
                      "purity_ratio": 1.584962500721156,
                      "vocabulary": 12.0,
                      "volume": 75.28421251514428,
                      "difficulty": 2.0,
                      "level": 0.5,
                      "effort": 150.56842503028855,
                      "time": 8.364912501682698,
                      "bugs": 0.0094341190071077
                    }"###
                );
            },
        );
    }

    /// Pointer-arithmetic operators: `*` (dereference), `&` (address-of),
    /// `->` (member-of-pointer), `+` (pointer + offset). Each is counted
    /// once in `n1`; multiple uses bump `N1`. The headline integer values
    /// (`u_operators`, `u_operands`) anchor the snapshot per the
    /// snapshot-anchor policy.
    #[test]
    fn c_pointer_arithmetic_operators() {
        check_metrics::<CppParser>(
            "int g(int* p, int* q) {
                 return *(p + 1) + *q;
             }",
            "foo.c",
            |metric| {
                // Unique operators: int, *, (), {, }, +, ;, return  (= 8)
                //   `*` covers both pointer-type and dereference; the grammar
                //   does NOT split them.  `,` does not appear (only one
                //   parameter on each side of the body).
                // Unique operands: g, p, q, 1                       (= 4)
                assert_eq!(metric.halstead.u_operators(), 8.0);
                assert_eq!(metric.halstead.u_operands(), 4.0);
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    /// Bitwise (`&`, `|`, `^`, `~`, `<<`, `>>`) and logical (`&&`, `||`,
    /// `!`) operators are distinct kind_ids and count as separate unique
    /// operators in Halstead.  `&` (bitwise-and) and `&&` (logical-and)
    /// must NOT collapse, even though both render as ampersands.
    #[test]
    fn c_bitwise_and_logical_operators() {
        check_metrics::<CppParser>(
            "int f(int a, int b) {
                 int x = (a & b) | (a ^ b);
                 int y = ~a;
                 int z = (a << 1) >> 2;
                 return (a && b) || !x;
             }",
            "foo.c",
            |metric| {
                // Expect: 6 bitwise op kinds (& | ^ ~ << >>), 3 logical (&& || !).
                // Plus int, (), {, }, =, ;, return, , — 8 syntactic / arithmetic
                // operator kinds.  Six bitwise + three logical + eight = 17 unique
                // operators is the upper bound; actuals depend on grammar collapse,
                // so we assert a lower-bound and anchor via snapshot below.
                let s = &metric.halstead;
                assert!(
                    s.u_operators() >= 14.0,
                    "expected >= 14 unique operators (bitwise + logical + syntax), got {}",
                    s.u_operators(),
                );
                assert_eq!(s.u_operands(), 8.0); // f, a, b, x, y, z, 1, 2
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    /// Increment / decrement (`++`, `--`) and `sizeof` / cast operators
    /// each contribute distinct unique operators.  C-style casts in the
    /// tree-sitter grammar surface as `cast_expression` with the type
    /// token classified as a primitive_type operator.
    #[test]
    fn c_increment_decrement_and_sizeof() {
        check_metrics::<CppParser>(
            "void f(int* p) {
                 int n = sizeof(int);
                 ++p;
                 --n;
                 long w = (long) n;
             }",
            "foo.c",
            |metric| {
                // Unique operators include: void, int, long, *, =, sizeof, ++, --, (), {, }, ;
                // Unique operands: f, p, n, w
                let s = &metric.halstead;
                assert!(
                    s.u_operators() >= 10.0,
                    "expected >= 10 unique operators including ++ / -- / sizeof / cast, got {}",
                    s.u_operators(),
                );
                assert_eq!(s.u_operands(), 4.0);
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn cpp_operators_and_operands() {
        // Define operators and operands for C/C++ grammar according to this specification:
        // https://www.verifysoft.com/en_halstead_metrics.html
        // The only difference with the specification above is that
        // primitive types are treated as operators, since the definition of a
        // primitive type can be seen as the creation of a slot of a certain size.
        // i.e. The `int a;` definition creates a n-bytes slot.
        check_metrics::<CppParser>(
            "main()
            {
              int a, b, c, avg;
              scanf(\"%d %d %d\", &a, &b, &c);
              avg = (a + b + c) / 3;
              printf(\"avg = %d\", avg);
            }",
            "foo.c",
            |metric| {
                // unique operators: (), {}, int, &, =, +, /, ,, ;
                // unique operands: main, a, b, c, avg, scanf, "%d %d %d", 3, printf, "avg = %d"
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r###"
                    {
                      "n1": 9.0,
                      "N1": 24.0,
                      "n2": 10.0,
                      "N2": 18.0,
                      "length": 42.0,
                      "estimated_program_length": 61.74860596185444,
                      "purity_ratio": 1.470204903853677,
                      "vocabulary": 19.0,
                      "volume": 178.41295556463058,
                      "difficulty": 8.1,
                      "level": 0.1234567901234568,
                      "effort": 1445.1449400735075,
                      "time": 80.28583000408375,
                      "bugs": 0.04260752914034329
                    }"###
                );
            },
        );
    }

    /// C++20 spaceship operator `<=>` (`Cpp::LTEQGT`) is a comparison
    /// operator and must be counted in Halstead, like its sibling
    /// comparison operators `<`, `>`, `<=`, `>=`, `==`, `!=`. Prior to
    /// this fix it fell through to the `Unknown` arm and was silently
    /// dropped from `n1` / `N1`, under-reporting volume / effort on any
    /// C++20+ codebase that defines `operator<=>`. Regression test for
    /// issue #197.
    #[test]
    fn cpp_spaceship_operator_is_halstead_operator() {
        check_metrics::<CppParser>(
            "int f(int a, int b) {
                 return (a <=> b) != 0;
             }",
            "foo.cpp",
            |metric| {
                // Unique operators (grammar collapses matched delimiters
                // to a single kind_id): int, (), {}, <=>, !=, return, ;, ,
                //   `<=>` is the regression target — without the fix it
                //   would be Unknown and `u_operators` would be 7.
                // Unique operands: f, a, b, 0
                let s = &metric.halstead;
                assert_eq!(s.u_operators(), 8.0);
                assert_eq!(s.u_operands(), 4.0);
                insta::assert_json_snapshot!(
                    s,
                    @r###"
                    {
                      "n1": 8.0,
                      "N1": 11.0,
                      "n2": 4.0,
                      "N2": 6.0,
                      "length": 17.0,
                      "estimated_program_length": 32.0,
                      "purity_ratio": 1.8823529411764706,
                      "vocabulary": 12.0,
                      "volume": 60.94436251225965,
                      "difficulty": 6.0,
                      "level": 0.16666666666666666,
                      "effort": 365.6661750735579,
                      "time": 20.31478750408655,
                      "bugs": 0.01704519358507665
                    }"###
                );
            },
        );
    }

    /// C++ compound subtract-assign `-=` (`Cpp::DASHEQ`) must be counted
    /// in Halstead like every other compound assignment (`+=`, `*=`,
    /// `/=`, etc.). Prior to the fix it fell through to the `Unknown`
    /// arm and was silently dropped from `n1` / `N1` — under-reporting
    /// volume / effort wherever C++ code subtracts in place. Regression
    /// test for issue #198.
    #[test]
    fn cpp_dash_eq_is_halstead_operator() {
        check_metrics::<CppParser>("void f(int a, int b) { a -= b; }", "foo.cpp", |metric| {
            // Unique operators: void, (), {}, int, ,, -=, ;
            //   `-=` is the regression target — without the fix it
            //   would be Unknown and `u_operators` would be 6.
            // Unique operands: f, a, b
            let s = &metric.halstead;
            assert_eq!(s.u_operators(), 7.0);
            assert_eq!(s.u_operands(), 3.0);
        });
    }

    /// C++ pointer-to-member access `.*` (`Cpp::DOTSTAR`) must be
    /// counted in Halstead. Prior to the fix it fell through to the
    /// `Unknown` arm and was silently dropped from `n1` / `N1`.
    /// Regression test for issue #198.
    ///
    /// The snippet uses an `operator.*` declaration because that is
    /// where the C++ tree-sitter grammar reliably emits a single
    /// `DOTSTAR` leaf; in expression position (`a.*b`) some grammar
    /// versions split the token into `DOT` + `STAR` and the regression
    /// would be masked.
    #[test]
    fn cpp_dot_star_is_halstead_operator() {
        check_metrics::<CppParser>("struct S { void operator.*(int); };", "foo.cpp", |metric| {
            // Unique operators with fix: {}, ;, (), int, void, .*
            //   `.*` is the regression target — without the fix it
            //   falls through to `Unknown` and `u_operators` is 5.
            // Unique operands: S
            let s = &metric.halstead;
            assert_eq!(s.u_operators(), 6.0);
            assert_eq!(s.u_operands(), 1.0);
        });
    }

    /// C++ pointer-to-member access through pointer `->*`
    /// (`Cpp::DASHGTSTAR`) must be counted in Halstead. Prior to the
    /// fix it fell through to the `Unknown` arm and was silently
    /// dropped from `n1` / `N1`. Regression test for issue #198.
    ///
    /// The snippet uses an `operator->*` declaration because that is
    /// where the C++ tree-sitter grammar reliably emits a single
    /// `DASHGTSTAR` leaf; in expression position (`a->*b`) the grammar
    /// splits the token into `DASHGT` + `STAR` and the regression would
    /// be masked.
    #[test]
    fn cpp_dash_gt_star_is_halstead_operator() {
        check_metrics::<CppParser>(
            "struct S { void operator->*(int); };",
            "foo.cpp",
            |metric| {
                // Unique operators with fix: {}, ;, (), int, void, ->*
                //   `->*` is the regression target — without the fix it
                //   falls through to `Unknown` and `u_operators` is 5.
                // Unique operands: S
                let s = &metric.halstead;
                assert_eq!(s.u_operators(), 6.0);
                assert_eq!(s.u_operands(), 1.0);
            },
        );
    }

    #[test]
    fn rust_operators_and_operands() {
        check_metrics::<RustParser>(
            "fn main() {
              let a = 5; let b = 5; let c = 5;
              let avg = (a + b + c) / 3;
              println!(\"{}\", avg);
            }",
            "foo.rs",
            |metric| {
                // unique operators: fn, (), {}, let, =, +, /, ;, !, ,
                // unique operands: main, a, b, c, avg, 5, 3, println, "{}"
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r###"
                    {
                      "n1": 10.0,
                      "N1": 23.0,
                      "n2": 9.0,
                      "N2": 15.0,
                      "length": 38.0,
                      "estimated_program_length": 61.74860596185444,
                      "purity_ratio": 1.624963314785643,
                      "vocabulary": 19.0,
                      "volume": 161.42124551085624,
                      "difficulty": 8.333333333333334,
                      "level": 0.12,
                      "effort": 1345.177045923802,
                      "time": 74.7320581068779,
                      "bugs": 0.040619232256751396
                    }"###
                );
            },
        );
    }

    #[test]
    fn rust_aliased_primitive_type_classification() {
        // Regression for issue #95 (lesson #2): the Rust grammar emits 17
        // distinct `kind_id`s for `primitive_type` (one base plus 16
        // numeric-suffixed alias variants). `RustCode::is_primitive` in
        // `src/checker.rs` must list every variant; if a future regression
        // omits one, primitive type names emitted in that aliased position
        // silently drop into the kind_id-keyed operators bucket instead of
        // the text-keyed primitive_operators map, miscounting Halstead n1.
        //
        // The snippet exercises every primitive scalar type across many
        // syntactic positions (function parameter types, return types,
        // let-binding annotations, `as` casts, const items, type aliases,
        // struct fields, function pointer types, tuple types, array types,
        // reference types, generic type arguments). Empirically, ordinary
        // Rust source emits the base `Rust::PrimitiveType` variant from
        // all of these positions; the 16 suffixed alias variants are
        // produced by specific grammar productions not reachable from
        // user-written code. Mutation-verified: dropping
        // `Rust::PrimitiveType` from `is_primitive` fails this test
        // (u_operators 30→15). Dropping any single suffixed variant
        // currently leaves the test passing; if a future grammar bump
        // makes any suffixed variant reachable from idiomatic source,
        // extend the snippet so the test fires for that variant too.
        check_metrics::<RustParser>(
            "const C: u8 = 0;
            type T = i64;
            struct S { x: u32, y: u64 }
            fn g(p: fn(u8) -> u16) -> bool { let _ = p(0); true }
            fn f(a: u8, b: u16, c: u32, d: u64) -> u128 {
                let _x: i8 = 0;
                let _y: i16 = 0;
                let _z: i32 = 0;
                let _w: i64 = 0;
                let _v: i128 = 0;
                let _p: f32 = 1.0;
                let _q: f64 = 2.0;
                let _r: bool = true;
                let _s: char = 'x';
                let _t: usize = 0;
                let _u: isize = 0;
                let _arr: [u32; 4] = [0; 4];
                let _ref: &u8 = &0;
                let _tup: (u32, u64) = (0, 0);
                let _opt: Option<u32> = None;
                a as u128 + b as u128 + c as u128 + d
            }",
            "foo.rs",
            |metric| {
                // Headline: u_operators is the load-bearing assertion —
                // the 16 distinct primitive type names dedupe by text in
                // the primitive_operators map. Total operators (N1) and
                // operand counts pin the rest of the Halstead state.
                assert_eq!(metric.halstead.u_operators(), 30.0);
                assert_eq!(metric.halstead.operators(), 118.0);
                assert_eq!(metric.halstead.u_operands(), 31.0);
                assert_eq!(metric.halstead.operands(), 50.0);
            },
        );
    }

    #[test]
    fn javascript_operators_and_operands() {
        check_metrics::<JavascriptParser>(
            "function main() {
              var a, b, c, avg;
              a = 5; b = 5; c = 5;
              avg = (a + b + c) / 3;
              console.log(\"{}\", avg);
            }",
            "foo.js",
            |metric| {
                // unique operators: function, (), {}, var, =, +, /, ,, ., ;
                // unique operands: main, a, b, c, avg, 3, 5, console.log, console, log, "{}"
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r###"
                    {
                      "n1": 10.0,
                      "N1": 24.0,
                      "n2": 11.0,
                      "N2": 21.0,
                      "length": 45.0,
                      "estimated_program_length": 71.27302875388389,
                      "purity_ratio": 1.583845083419642,
                      "vocabulary": 21.0,
                      "volume": 197.65428402504423,
                      "difficulty": 9.545454545454545,
                      "level": 0.10476190476190476,
                      "effort": 1886.699983875422,
                      "time": 104.81666577085679,
                      "bugs": 0.05089564733125986
                    }"###
                );
            },
        );
    }

    #[test]
    fn mozjs_operators_and_operands() {
        check_metrics::<MozjsParser>(
            "function main() {
              var a, b, c, avg;
              a = 5; b = 5; c = 5;
              avg = (a + b + c) / 3;
              console.log(\"{}\", avg);
            }",
            "foo.js",
            |metric| {
                // unique operators: function, (), {}, var, =, +, /, ,, ., ;
                // unique operands: main, a, b, c, avg, 3, 5, console.log, console, log, "{}"
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r###"
                    {
                      "n1": 10.0,
                      "N1": 24.0,
                      "n2": 11.0,
                      "N2": 21.0,
                      "length": 45.0,
                      "estimated_program_length": 71.27302875388389,
                      "purity_ratio": 1.583845083419642,
                      "vocabulary": 21.0,
                      "volume": 197.65428402504423,
                      "difficulty": 9.545454545454545,
                      "level": 0.10476190476190476,
                      "effort": 1886.699983875422,
                      "time": 104.81666577085679,
                      "bugs": 0.05089564733125986
                    }"###
                );
            },
        );
    }

    #[test]
    fn typescript_operators_and_operands() {
        check_metrics::<TypescriptParser>(
            "function main() {
              var a, b, c, avg;
              a = 5; b = 5; c = 5;
              avg = (a + b + c) / 3;
              console.log(\"{}\", avg);
            }",
            "foo.ts",
            |metric| {
                // unique operators: function, (), {}, var, =, +, /, ,, ., ;
                // unique operands: main, a, b, c, avg, 3, 5, console.log, console, log, "{}"
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r###"
                    {
                      "n1": 10.0,
                      "N1": 24.0,
                      "n2": 11.0,
                      "N2": 21.0,
                      "length": 45.0,
                      "estimated_program_length": 71.27302875388389,
                      "purity_ratio": 1.583845083419642,
                      "vocabulary": 21.0,
                      "volume": 197.65428402504423,
                      "difficulty": 9.545454545454545,
                      "level": 0.10476190476190476,
                      "effort": 1886.699983875422,
                      "time": 104.81666577085679,
                      "bugs": 0.05089564733125986
                    }"###
                );
            },
        );
    }

    #[test]
    fn tsx_operators_and_operands() {
        check_metrics::<TsxParser>(
            "function main() {
              var a, b, c, avg;
              a = 5; b = 5; c = 5;
              avg = (a + b + c) / 3;
              console.log(\"{}\", avg);
            }",
            "foo.ts",
            |metric| {
                // unique operators: function, (), {}, var, =, +, /, ,, ., ;
                // unique operands: main, a, b, c, avg, 3, 5, console.log, console, log, "{}"
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r###"
                    {
                      "n1": 10.0,
                      "N1": 24.0,
                      "n2": 11.0,
                      "N2": 21.0,
                      "length": 45.0,
                      "estimated_program_length": 71.27302875388389,
                      "purity_ratio": 1.583845083419642,
                      "vocabulary": 21.0,
                      "volume": 197.65428402504423,
                      "difficulty": 9.545454545454545,
                      "level": 0.10476190476190476,
                      "effort": 1886.699983875422,
                      "time": 104.81666577085679,
                      "bugs": 0.05089564733125986
                    }"###
                );
            },
        );
    }

    #[test]
    fn javascript_template_string_plain_is_operand() {
        // Regression: issue #192. A backtick-delimited `` `hello` ``
        // without `${...}` is semantically identical to `"hello"` /
        // `'hello'` and must contribute exactly one operand — before
        // the fix `TemplateString` fell through to `HalsteadType::Unknown`
        // and contributed zero. expected: operands are `f` (function
        // name) and the wrapping `` `hello` `` template literal →
        // u_operands = 2, N2 = 2 (matches the equivalent
        // `function f() { return "hello"; }` baseline).
        check_metrics::<JavascriptParser>("function f() { return `hello`; }", "foo.js", |metric| {
            assert_eq!(metric.halstead.u_operands(), 2.0);
            assert_eq!(metric.halstead.operands(), 2.0);
        });
    }

    #[test]
    fn javascript_template_string_interpolation_no_double_count() {
        // Regression: issue #192. An interpolated template literal
        // `` `Hi ${name}!` `` used to fall through to `Unknown`,
        // dropping the wrapper from the count entirely; the inner
        // `name` was still walked and counted via the
        // `TemplateSubstitution` child. Mirrors #183 (C#), #191
        // (Kotlin), #199 (Perl): the wrapper is skipped when a
        // `TemplateSubstitution` child is present so the inner
        // expression is not double-counted.
        //
        // expected: for `function f(name) { return ` + "`Hi ${name}!`"
        // + `; }`, operands are `f` and `name` (twice — `name` as the
        // parameter, then again inside the interpolation), so
        // u_operands = 2 and N2 = 3. Without the wrapper-skip guard
        // the wrapping literal would also be counted, lifting
        // u_operands to 3 and N2 to 4.
        check_metrics::<JavascriptParser>(
            "function f(name) { return `Hi ${name}!`; }",
            "foo.js",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 2.0);
                assert_eq!(metric.halstead.operands(), 3.0);
            },
        );
    }

    #[test]
    fn mozjs_template_string_plain_is_operand() {
        // Regression: issue #192. Mirrors
        // `javascript_template_string_plain_is_operand` for the
        // Firefox-mode dialect — the four JS-family `get_op_type`
        // impls share the same template-literal handling.
        check_metrics::<MozjsParser>("function f() { return `hello`; }", "foo.js", |metric| {
            assert_eq!(metric.halstead.u_operands(), 2.0);
            assert_eq!(metric.halstead.operands(), 2.0);
        });
    }

    #[test]
    fn mozjs_template_string_interpolation_no_double_count() {
        // Regression: issue #192. Mirrors
        // `javascript_template_string_interpolation_no_double_count`
        // for the Firefox-mode dialect.
        check_metrics::<MozjsParser>(
            "function f(name) { return `Hi ${name}!`; }",
            "foo.js",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 2.0);
                assert_eq!(metric.halstead.operands(), 3.0);
            },
        );
    }

    #[test]
    fn typescript_template_string_plain_is_operand() {
        // Regression: issue #192. Mirrors
        // `javascript_template_string_plain_is_operand` for
        // TypeScript — the four JS-family `get_op_type` impls share
        // the same template-literal handling.
        //
        // After #313 the `: string` annotation's `String2` child also
        // counts as an operand (text `"string"`), so unique operands
        // are `f`, `` `hello` ``, `string` (3 each). The headline of
        // this test — that the plain template literal contributes one
        // operand — is unaffected.
        check_metrics::<TypescriptParser>(
            "function f(): string { return `hello`; }",
            "foo.ts",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 3.0);
                assert_eq!(metric.halstead.operands(), 3.0);
            },
        );
    }

    #[test]
    fn typescript_template_string_interpolation_no_double_count() {
        // Regression: issue #192. Mirrors
        // `javascript_template_string_interpolation_no_double_count`
        // for TypeScript.
        //
        // After #313 each `: string` annotation contributes one
        // `"string"` operand. Unique operands: `f`, `name`, `string`
        // (3). Total operands: `f`, `name` (param), `name` (in the
        // interpolation), `string`, `string` (5). The interpolation
        // guard from #192 still holds — the wrapping `` `Hi ${name}!` ``
        // is `Unknown`, not double-counted.
        check_metrics::<TypescriptParser>(
            "function f(name: string): string { return `Hi ${name}!`; }",
            "foo.ts",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 3.0);
                assert_eq!(metric.halstead.operands(), 5.0);
            },
        );
    }

    #[test]
    fn tsx_template_string_plain_is_operand() {
        // Regression: issue #192. Mirrors
        // `javascript_template_string_plain_is_operand` for the
        // TSX (TypeScript + JSX) variant.
        //
        // After #313 TSX's type-keyword `string` (`String3`) also
        // counts as an operand, mirroring TS::String2.
        check_metrics::<TsxParser>(
            "function f(): string { return `hello`; }",
            "foo.tsx",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 3.0);
                assert_eq!(metric.halstead.operands(), 3.0);
            },
        );
    }

    #[test]
    fn tsx_template_string_interpolation_no_double_count() {
        // Regression: issue #192. Mirrors
        // `javascript_template_string_interpolation_no_double_count`
        // for the TSX (TypeScript + JSX) variant.
        //
        // After #313 each `: string` annotation contributes one
        // `String3` operand; see `typescript_template_string_…` for
        // the count derivation.
        check_metrics::<TsxParser>(
            "function f(name: string): string { return `Hi ${name}!`; }",
            "foo.tsx",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 3.0);
                assert_eq!(metric.halstead.operands(), 5.0);
            },
        );
    }

    // Issue #281: optional chaining (`?.`) was double-counted as a
    // Halstead operator in TypeScript and TSX because the grammar
    // exposes both an `optional_chain` named wrapper AND a child
    // `?.` token, and both were classified as `Operator`. The fix
    // counts only the bare `?.` token (`QMARKDOT`) in TS/TSX so each
    // textual `?.` contributes exactly once, matching JS / MozJS
    // (whose grammars expose only `OptionalChain` — the `?.` token
    // itself).
    //
    // The four assertions below all compare against the same totals:
    // for `function f(a) { return a?.b?.c; }` the operator stream is
    // `function`, `(`, `{`, `return`, `?.`, `?.`, `;` (7 total, 6
    // unique — `LPAREN`/`LBRACE` count once, closing tokens are not
    // in the operator set). Before the fix, TS/TSX reported 9/7
    // instead of 7/6.
    #[test]
    fn javascript_optional_chain_not_double_counted_in_halstead_281() {
        check_metrics::<JavascriptParser>("function f(a) { return a?.b?.c; }", "foo.js", |m| {
            assert_eq!(m.halstead.u_operators(), 6.0);
            assert_eq!(m.halstead.operators(), 7.0);
        });
    }

    #[test]
    fn mozjs_optional_chain_not_double_counted_in_halstead_281() {
        check_metrics::<MozjsParser>("function f(a) { return a?.b?.c; }", "foo.js", |m| {
            assert_eq!(m.halstead.u_operators(), 6.0);
            assert_eq!(m.halstead.operators(), 7.0);
        });
    }

    #[test]
    fn typescript_optional_chain_not_double_counted_in_halstead_281() {
        // The TS grammar wraps member-expression `?.` in an
        // `optional_chain` named node containing the bare `?.`
        // token; classifying both as `Operator` double-counted the
        // chain. We now count only the bare token, so TS matches JS.
        check_metrics::<TypescriptParser>("function f(a) { return a?.b?.c; }", "foo.ts", |m| {
            assert_eq!(m.halstead.u_operators(), 6.0);
            assert_eq!(m.halstead.operators(), 7.0);
        });
    }

    #[test]
    fn tsx_optional_chain_not_double_counted_in_halstead_281() {
        check_metrics::<TsxParser>("function f(a) { return a?.b?.c; }", "foo.tsx", |m| {
            assert_eq!(m.halstead.u_operators(), 6.0);
            assert_eq!(m.halstead.operators(), 7.0);
        });
    }

    // Issue #299: parity guard for the JS-family `get_op_type` macro
    // on the optional-chain operator token (#281's prior regression
    // surface). All four languages must classify the bare `?.` token
    // identically — `OptionalChain` in JS/MozJS, `QMARKDOT` in
    // TS/TSX — and emit the same totals for
    // `function f(a) { return a?.b?.c; }`:
    //
    // * Operators: `function`, `(`, `{`, `return`, `?.`, `?.`, `;`
    //   (7 total, 6 unique).
    // * Operands: `f`, `a`, `a`, `b`, `c`, plus the two wrapping
    //   member expressions (`a?.b`, `a?.b?.c`) classified as
    //   `MemberExpression*` (7 total, 6 unique).
    //
    // Verified by test-via-revert: dropping `OptionalChain` from
    // JS/MozJS, or `QMARKDOT` from TS/TSX, trips the test
    // (u_operators 6→5). This input does NOT exercise every operand
    // alias in the per-language `operand_extras` (`Identifier2`,
    // `String2`, `NestedIdentifier`, `MemberExpression4`) or the TS
    // `PredefinedType` operator; drift in those is out of scope for
    // this regression guard and would need a separate fixture.
    #[test]
    fn js_family_get_op_type_parity_optional_chain_member_299() {
        // Non-capturing closure (coerced to the `fn` pointer that
        // `check_metrics` accepts) avoids the
        // `clippy::needless_pass_by_value` warning that a free `fn`
        // taking `CodeMetrics` by value would trigger.
        const SRC: &str = "function f(a) { return a?.b?.c; }";
        let check = |m: crate::CodeMetrics| {
            assert_eq!(m.halstead.u_operators(), 6.0);
            assert_eq!(m.halstead.operators(), 7.0);
            assert_eq!(m.halstead.u_operands(), 6.0);
            assert_eq!(m.halstead.operands(), 7.0);
        };

        check_metrics::<JavascriptParser>(SRC, "foo.js", check);
        check_metrics::<MozjsParser>(SRC, "foo.js", check);
        check_metrics::<TypescriptParser>(SRC, "foo.ts", check);
        check_metrics::<TsxParser>(SRC, "foo.tsx", check);
    }

    // Issue #313: parity guard for the `"string"` type-keyword aliases
    // that the TS / TSX grammars expose. `Checker::is_string` matches
    // these aliases (#283), so `Getter::get_op_type` must also classify
    // them — otherwise the same node disagrees between the two
    // predicates and Halstead silently undercounts every `: string`
    // annotation by one operand.
    //
    // For the input `let x: string = "y";`:
    //
    // * TypeScript emits `Typescript::String2` for the `string` type
    //   keyword (kind_id 135, in the type-keyword block of the enum).
    // * TSX emits `Tsx::String3` for the same role (kind_id 141).
    //
    // After #313 both kinds are in `operand_extras` and contribute one
    // `"string"` operand. Verified by test-via-revert: dropping
    // `String2` from TS's `operand_extras` (or `String3` from TSX's)
    // trips this test on `u_operands` / `operands` for the affected
    // language.
    #[test]
    fn ts_family_string2_string3_type_keyword_parity_313() {
        const SRC: &str = "let x: string = \"y\";";
        // Operators (n1 = 5, N1 = 5):
        //   `let`, `:`, `=`, `;`, plus `string` (PredefinedType wrapper,
        //   routed through `is_primitive` so it's keyed by its lexeme
        //   `"string"` in `primitive_operators`).
        // Operands (n2 = 3, N2 = 3):
        //   `x`, the `"y"` literal, and `string` (the type-keyword
        //   child of `predefined_type`, classified via the operand
        //   extras added by #313). Pre-fix the TS column reported
        //   n2 = 2 / N2 = 2 because String2 fell through to `Unknown`;
        //   the TSX column had the same gap for String3.
        let check = |m: crate::CodeMetrics| {
            assert_eq!(m.halstead.u_operators(), 5.0);
            assert_eq!(m.halstead.operators(), 5.0);
            assert_eq!(m.halstead.u_operands(), 3.0);
            assert_eq!(m.halstead.operands(), 3.0);
        };

        check_metrics::<TypescriptParser>(SRC, "foo.ts", check);
        check_metrics::<TsxParser>(SRC, "foo.tsx", check);
    }

    #[test]
    fn python_wrong_operators() {
        check_metrics::<PythonParser>("()[]{}", "foo.py", |metric| {
            insta::assert_json_snapshot!(
                metric.halstead,
                @r###"
                    {
                      "n1": 0.0,
                      "N1": 0.0,
                      "n2": 0.0,
                      "N2": 0.0,
                      "length": 0.0,
                      "estimated_program_length": 0.0,
                      "purity_ratio": 0.0,
                      "vocabulary": 0.0,
                      "volume": 0.0,
                      "difficulty": 0.0,
                      "level": 0.0,
                      "effort": 0.0,
                      "time": 0.0,
                      "bugs": 0.0
                    }"###
            );
        });
    }

    #[test]
    fn python_check_metrics() {
        check_metrics::<PythonParser>(
            "def f():
                 pass",
            "foo.py",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r###"
                    {
                      "n1": 2.0,
                      "N1": 2.0,
                      "n2": 1.0,
                      "N2": 1.0,
                      "length": 3.0,
                      "estimated_program_length": 2.0,
                      "purity_ratio": 0.6666666666666666,
                      "vocabulary": 3.0,
                      "volume": 4.754887502163468,
                      "difficulty": 1.0,
                      "level": 1.0,
                      "effort": 4.754887502163468,
                      "time": 0.26416041678685936,
                      "bugs": 0.0009425525573729414
                    }"###
                );
            },
        );
    }

    #[test]
    fn java_operators_and_operands() {
        check_metrics::<JavaParser>(
            "public class Main {
            public static void main(string args[]) {
                  int a, b, c, avg;
                  a = 5; b = 5; c = 5;
                  avg = (a + b + c) / 3;
                  MessageFormat.format(\"{0}\", avg);
                }
            }",
            "foo.java",
            |metric| {
                // Operators (n1=11): {} void () [] , . ; int = + /
                // Operands (n2=12): Main main args a b c avg 5 3 MessageFormat format "{0}"
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r#"
                {
                  "n1": 11.0,
                  "N1": 26.0,
                  "n2": 12.0,
                  "N2": 22.0,
                  "length": 48.0,
                  "estimated_program_length": 81.07329781366414,
                  "purity_ratio": 1.6890270377846697,
                  "vocabulary": 23.0,
                  "volume": 217.13097389073664,
                  "difficulty": 10.083333333333334,
                  "level": 0.09917355371900825,
                  "effort": 2189.4039867315946,
                  "time": 121.63355481842193,
                  "bugs": 0.05620341201461669
                }
                "#
                );
            },
        );
    }

    #[test]
    fn java_primitive_types_and_booleans() {
        check_metrics::<JavaParser>(
            "public class Prims {
                byte a = 1;
                short b = 2;
                int c = 3;
                long d = 4;
                char e = 'x';
                float f = 1.0f;
                double g = 2.0;
                boolean h = true;
                boolean i = false;
            }",
            "foo.java",
            |metric| {
                // Verifies all 8 Java primitive-type keywords (byte, short, int, long,
                // char, float, double, boolean) are counted as distinct operators, and
                // that true/false are counted as operands.
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r#"
                {
                  "n1": 11.0,
                  "N1": 28.0,
                  "n2": 19.0,
                  "N2": 19.0,
                  "length": 47.0,
                  "estimated_program_length": 118.76437056043838,
                  "purity_ratio": 2.526901501285923,
                  "vocabulary": 30.0,
                  "volume": 230.62385799360038,
                  "difficulty": 5.5,
                  "level": 0.18181818181818182,
                  "effort": 1268.4312189648022,
                  "time": 70.46840105360012,
                  "bugs": 0.03905920146699976
                }
                "#
                );
            },
        );
    }

    #[test]
    fn groovy_operators_and_operands() {
        check_metrics::<GroovyParser>(
            "class Main {
                static void main(String[] args) {
                    int a, b, c, avg;
                    a = 5; b = 5; c = 5;
                    avg = (a + b + c) / 3;
                    println(avg);
                }
            }",
            "foo.groovy",
            |metric| {
                // Groovy mirror of `java_operators_and_operands`. The juxt
                // call `println avg` exercises `juxt_function_call` in
                // place of Java's `MessageFormat.format(...)`. amaanq's
                // grammar inherits Java's tokenisation, so n1/N1/n2/N2
                // shapes match Java up to those substitutions.
                // The dekobon grammar parses primitive type names
                // (`void`, `int`, `String`) as `type_identifier`
                // rather than as distinct keyword tokens, so they
                // count as operands here — the prior amaanq grammar
                // treated them as operators. Net shift: −2 unique
                // operators (`void`, `int`), +2 unique operands
                // (`void`, `int` were the only two type_identifiers
                // not already counted as operands, since `String`
                // was already an identifier in the prior grammar's
                // counting).
                assert_eq!(metric.halstead.u_operators(), 8.0);
                assert_eq!(metric.halstead.u_operands(), 13.0);
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r#"
                {
                  "n1": 8.0,
                  "N1": 22.0,
                  "n2": 13.0,
                  "N2": 23.0,
                  "length": 45.0,
                  "estimated_program_length": 72.10571633583419,
                  "purity_ratio": 1.6023492519074265,
                  "vocabulary": 21.0,
                  "volume": 197.65428402504423,
                  "difficulty": 7.076923076923077,
                  "level": 0.14130434782608697,
                  "effort": 1398.7841638695438,
                  "time": 77.71023132608576,
                  "bugs": 0.04169134280255714
                }
                "#
                );
            },
        );
    }

    #[test]
    fn groovy_primitive_types_and_booleans() {
        check_metrics::<GroovyParser>(
            "class Prims {
                byte a = 1
                short b = 2
                int c = 3
                long d = 4
                char e = 'x'
                float f = 1.0f
                double g = 2.0
                boolean h = true
                boolean i = false
            }",
            "foo.groovy",
            |metric| {
                // The dekobon grammar consolidates the 8 primitive
                // type names (`byte`, `short`, `int`, `long`, `char`,
                // `float`, `double`, `boolean`) under `type_identifier`
                // — so they count as operands, not as distinct
                // operators. Likewise numeric literals collapse to one
                // `NumberLiteral` shape (no Hex/Octal/Binary/Decimal
                // split), and `'x'` parses as `StringLiteral` (Groovy
                // single-quoted strings) rather than as
                // `CharacterLiteral`. Operators remaining in this
                // fixture: `=` and `class`-body braces (only `{` is in
                // the operator set). True/false collapse under one
                // `BooleanLiteral`.
                assert_eq!(metric.halstead.u_operators(), 2.0);
                assert_eq!(metric.halstead.u_operands(), 27.0);
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r#"
                {
                  "n1": 2.0,
                  "N1": 10.0,
                  "n2": 27.0,
                  "N2": 28.0,
                  "length": 38.0,
                  "estimated_program_length": 130.38196255841365,
                  "purity_ratio": 3.4311042778529908,
                  "vocabulary": 29.0,
                  "volume": 184.60327781484773,
                  "difficulty": 1.037037037037037,
                  "level": 0.9642857142857143,
                  "effort": 191.44043625243467,
                  "time": 10.635579791801925,
                  "bugs": 0.01107221547116606
                }
                "#
                );
            },
        );
    }

    #[test]
    fn groovy_closure_operators_and_operands() {
        check_metrics::<GroovyParser>("def double = { x -> x * 2 }", "foo.groovy", |metric| {
            // Closure with arrow-style parameter list.
            // Distinct operators: def, =, {}, ->, * = 5.
            // Distinct operands: double, x, 2 = 3.
            assert_eq!(metric.halstead.u_operators(), 5.0);
            assert_eq!(metric.halstead.u_operands(), 3.0);
        });
    }

    /// Regression for issue #247: every Groovy-specific operator the
    /// prior amaanq grammar dropped to ERROR or mis-shaped as a Java
    /// node now parses as a distinct lexer token in the dekobon
    /// grammar, so Halstead counts each one. The fixture below
    /// exercises Elvis `?:`, safe-nav `?.`, safe-chain `??.`,
    /// spread-dot `*.`, method-pointer `.&`, direct-field `.@`,
    /// identity `===` / `!==`, spaceship `<=>`, regex `=~` / `==~`,
    /// exclusive ranges `..<` / `<..` / `<..<`, `as` coercion, and
    /// `?[` safe index — every distinct operator kind must appear in
    /// `u_operators` (the count grows by exactly the number of new
    /// distinct operator tokens introduced).
    #[test]
    fn groovy_dekobon_operator_coverage_247() {
        check_metrics::<GroovyParser>(
            "def f(a, b, list, s) {
                def x = a ?: b
                def y = a?.field
                def z = a??.field
                def items = list*.size()
                def ptr = a.&size
                def fld = a.@field
                def id1 = a === b
                def id2 = a !== b
                def ship = a <=> b
                def find = s =~ /pat/
                def match = s ==~ /^pat\\$/
                def r1 = 0..<10
                def r2 = 0<..10
                def r3 = 0<..<10
                def cast = a as String
                def safe = list?[0]
                return x
            }",
            "foo.groovy",
            |metric| {
                // Each Groovy-specific operator kind contributes one
                // distinct entry to the operator set. The 20-operator
                // floor breaks down as: 16 Groovy-specific tokens
                // exercised by the fixture (`?:`, `?.`, `??.`, `*.`,
                // `.&`, `.@`, `===`, `!==`, `<=>`, `=~`, `==~`, `..<`,
                // `<..`, `<..<`, `as`, `?[`) plus a handful of
                // ambient Java-shaped operators the fixture also
                // uses (`def`, `=`, `{`, `(`, `,`, `return`). A
                // grammar regression that drops one of the 16
                // Groovy-specific tokens would push the count below
                // this floor.
                // Exact pin: with the dekobon Groovy grammar this
                // fixture exercises 16 Groovy-specific tokens (`?:`,
                // `?.`, `??.`, `*.`, `.&`, `.@`, `===`, `!==`, `<=>`,
                // `=~`, `==~`, `..<`, `<..`, `<..<`, `as`, `?[`) plus
                // 7 ambient Java-shaped operators the fixture also
                // uses (`def`, `=`, `,`, `{`, `(`, `[`, `return`),
                // for a total of 23 distinct operator kinds. A
                // regression that drops any one of the 16 #247
                // operators would push the count below 23 and fail
                // this assertion. The complementary AST walk below
                // pins each #247 operator's identity individually so
                // a grammar change that adds an unrelated operator
                // (lifting `u_operators` to 24) still flags the loss
                // of a #247 operator at the per-token level.
                assert_eq!(
                    metric.halstead.u_operators(),
                    23.0,
                    "u_operators changed; check whether a #247 operator was dropped or an unrelated operator added (and update the comment / token list above accordingly)",
                );
            },
        );
    }

    #[test]
    fn csharp_operators_and_operands() {
        // After issue #286, `void`, `string`, and `int` count as three
        // distinct Halstead operators rather than collapsing into one
        // `PredefinedType` kind_id entry, lifting u_operators from 13
        // to 15. Total operators (N1) is unchanged because the same
        // nodes are still counted, just keyed by lexeme.
        check_metrics::<CsharpParser>(
            "public class Main {
                public static void Run(string[] args) {
                    int a, b, c, avg;
                    a = 5; b = 5; c = 5;
                    avg = (a + b + c) / 3;
                    System.Console.WriteLine(\"{0}\", avg);
                }
            }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.halstead.u_operators(), 15.0);
                assert_eq!(metric.halstead.operators(), 32.0);
                assert_eq!(metric.halstead.u_operands(), 13.0);
                assert_eq!(metric.halstead.operands(), 23.0);
                // Pin every Halstead field; values are whatever the
                // classifier produces and become the regression spec.
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn csharp_primitive_types_and_booleans() {
        // After issue #286: each of `byte`, `short`, `int`, `long`,
        // `char`, `float`, `double`, `bool`, `object` is now a distinct
        // Halstead operator (9 primitives) rather than collapsing into
        // one `PredefinedType` kind_id entry. u_operators rises from 6
        // to 14 (5 non-primitive operators + 9 distinct primitives);
        // total operators (N1) is unchanged because the same nodes are
        // still counted, just keyed by lexeme.
        check_metrics::<CsharpParser>(
            "public class Prims {
                byte a = 1;
                short b = 2;
                int c = 3;
                long d = 4;
                char e = 'x';
                float f = 1.0f;
                double g = 2.0;
                bool h = true;
                bool i = false;
                object j = null;
            }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.halstead.u_operators(), 14.0);
                assert_eq!(metric.halstead.operators(), 33.0);
                assert_eq!(metric.halstead.u_operands(), 21.0);
                assert_eq!(metric.halstead.operands(), 23.0);
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn csharp_predefined_types_keyed_by_lexeme() {
        // Regression: issue #286. The C# grammar emits one `PredefinedType`
        // kind_id for every keyword type (`int`, `string`, `bool`, …).
        // Without keying by source text the entire family collapses into
        // a single Halstead operator (n1 += 1) instead of one per distinct
        // keyword. This test pins the post-fix behaviour using four
        // distinct primitives — `int`, `string`, `bool`, `object` —
        // appearing as parameter types so no other operators interact
        // with the count.
        //
        // expected: operators are `class`, `void`, `M`, `{}`, `()`, `,`
        // (×3 between 4 params), plus the four distinct predefined types
        // → u_operators = 5 + 4 = 9. Without the fix the four primitives
        // collapse to one entry, giving u_operators = 6.
        check_metrics::<CsharpParser>(
            "class C { void M(int a, string b, bool c, object d) {} }",
            "foo.cs",
            |metric| {
                // The headline assertion: four distinct primitive
                // keywords contribute four distinct operators, not one.
                assert_eq!(metric.halstead.u_operators(), 9.0);
            },
        );
    }

    #[test]
    fn csharp_interpolated_string_no_double_count() {
        // Regression: issue #183. A C# `$"Hi {name}!"` used to be
        // classified as a Halstead operand (the wrapping
        // `InterpolatedStringExpression`) AND have its inner
        // `Interpolation`'s identifier classified as an operand too.
        // The fix routes `InterpolatedStringExpression` through a
        // conditional: when it has an `Interpolation` child, the inner
        // identifier already carries the operand contribution and the
        // wrapper is treated as `Unknown`; when it does not (static
        // `$"hello"`), the wrapper still counts as one operand.
        //
        // expected: operand contributions for
        //   `class C { void M(string name) { string s = $"Hi {name}!"; } }`
        // — `C` (class), `M` (method), `name` (param), `s` (local),
        // and the inner `name` (inside `{...}`). With the fix,
        // u_operands = 4 (C, M, name, s); N2 = 5 (`name` twice).
        // Without the fix, the wrapping `$"Hi {name}!"` would also
        // count → u_operands = 5, N2 = 6.
        check_metrics::<CsharpParser>(
            "class C { void M(string name) { string s = $\"Hi {name}!\"; } }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 4.0);
                assert_eq!(metric.halstead.operands(), 5.0);
            },
        );
    }

    #[test]
    fn csharp_static_interpolated_string_is_operand() {
        // Regression: issue #183. A `$"..."` with no `{...}` is
        // semantically identical to `"..."` and must still contribute
        // exactly one operand — the conditional `is_child(Interpolation)`
        // check distinguishes it from a true interpolation. expected:
        // operands are `C`, `M`, `s`, `$"hello"` → u_operands = 4, N2 = 4.
        // A naive "always Unknown" fix would yield u_operands = 3, N2 = 3,
        // diverging from the plain-string equivalent below.
        check_metrics::<CsharpParser>(
            "class C { void M() { string s = $\"hello\"; } }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 4.0);
                assert_eq!(metric.halstead.operands(), 4.0);
            },
        );
    }

    #[test]
    fn csharp_plain_string_still_operand() {
        // The fix for #183 only changes how `InterpolatedStringExpression`
        // is classified; plain `StringLiteral` (and `VerbatimStringLiteral`
        // / `RawStringLiteral`) must still contribute exactly one operand
        // each. expected: operands are `C`, `M`, `s`, `"hi"` →
        // u_operands = 4, N2 = 4.
        check_metrics::<CsharpParser>(
            "class C { void M() { string s = \"hi\"; } }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 4.0);
                assert_eq!(metric.halstead.operands(), 4.0);
            },
        );
    }

    #[test]
    fn go_operators_and_operands() {
        check_metrics::<GoParser>(
            "package main
            func sum(a, b int) int {
                return a + b
            }",
            "foo.go",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r###"
                    {
                      "n1": 7.0,
                      "N1": 7.0,
                      "n2": 5.0,
                      "N2": 8.0,
                      "length": 15.0,
                      "estimated_program_length": 31.26112492884004,
                      "purity_ratio": 2.0840749952560027,
                      "vocabulary": 12.0,
                      "volume": 53.77443751081734,
                      "difficulty": 5.6,
                      "level": 0.17857142857142858,
                      "effort": 301.1368500605771,
                      "time": 16.729825003365395,
                      "bugs": 0.014975730436275946
                    }"###
                );
            },
        );
    }

    #[test]
    fn perl_operators_and_operands() {
        check_metrics::<PerlParser>(
            "sub sum {
                my ($a, $b) = @_;
                return $a + $b;
            }",
            "foo.pl",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r#"
                {
                  "n1": 10.0,
                  "N1": 14.0,
                  "n2": 4.0,
                  "N2": 6.0,
                  "length": 20.0,
                  "estimated_program_length": 41.219280948873624,
                  "purity_ratio": 2.0609640474436812,
                  "vocabulary": 14.0,
                  "volume": 76.14709844115208,
                  "difficulty": 7.5,
                  "level": 0.13333333333333333,
                  "effort": 571.1032383086406,
                  "time": 31.727957683813365,
                  "bugs": 0.02294502281013948
                }
                "#
                );
            },
        );
    }

    #[test]
    fn perl_interpolated_string_no_double_count() {
        // Regression: issue #199. A `string_double_quoted` (and
        // `string_qq_quoted` / `backtick_quoted` / `command_qx_quoted`)
        // wrapping an `interpolation` child used to be counted as a
        // Halstead operand while the inner scalar/array/hash variable
        // was also walked and counted — double-counting the inner
        // variable's contribution to `N2`. Mirrors #180 (Bash/Elixir),
        // #183 (C#), #184 (PHP), #191 (Kotlin).
        //
        // expected: for
        //   sub greet { my $name = shift; my $msg = "Hi $name"; return $msg; }
        // — operands are `greet`, `$name`, `shift`, `$msg`. With the
        // fix the wrapping `"Hi $name"` is skipped (has `Interpolation`
        // child), so u_operands = 4 and N2 = 6 (`$name` x2 from the
        // `my` binding and the interpolation; `$msg` x2 from the `my`
        // binding and `return`; `greet`, `shift` once each). Without
        // the fix the wrapping literal would also be counted, lifting
        // u_operands to 5 and N2 to 7.
        check_metrics::<PerlParser>(
            "sub greet { my $name = shift; my $msg = \"Hi $name\"; return $msg; }",
            "foo.pl",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 4.0);
                assert_eq!(metric.halstead.operands(), 6.0);
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn perl_plain_string_still_operand() {
        // The fix for #199 only skips wrapping literals that carry an
        // `Interpolation` child; a plain `"hello"` (no `$…` inside)
        // must still contribute exactly one operand. expected: operands
        // `greet`, `$msg`, `"hello"` → u_operands = 3, N2 = 4 (`$msg`
        // appears in the `my` binding and the `return`).
        check_metrics::<PerlParser>(
            "sub greet { my $msg = \"hello\"; return $msg; }",
            "foo.pl",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 3.0);
                assert_eq!(metric.halstead.operands(), 4.0);
            },
        );
    }

    #[test]
    fn perl_single_quoted_string_never_interpolates() {
        // Single-quoted (`'…'`) and `q{…}` literals are not subject to
        // interpolation in Perl, so even when their text contains a
        // `$name`-shaped sequence the wrapper is still counted as one
        // operand and the inner text is not parsed as a variable.
        // expected: operands `greet`, `$msg`, `'Hi $name'` →
        // u_operands = 3, N2 = 4 (`$msg` x2).
        check_metrics::<PerlParser>(
            "sub greet { my $msg = 'Hi $name'; return $msg; }",
            "foo.pl",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 3.0);
                assert_eq!(metric.halstead.operands(), 4.0);
            },
        );
    }

    #[test]
    fn perl_plain_heredoc_counts_as_one_operand() {
        // Regression: issue #287. A plain (non-interpolating) Perl
        // heredoc body used to be classified `HalsteadType::Unknown`,
        // so its visible `HeredocBodyStatement` node contributed
        // nothing to N2 even though it is a string literal. The fix
        // adds `HeredocBodyStatement` to the interpolation-aware
        // operand arm, so an inert heredoc counts as one operand.
        //
        // Source (heredoc body lives at the source_file level, not
        // inside any sub):
        //   my $msg = <<END;
        //   hello world
        //   END
        //
        // Operands traversed:
        //   * `$msg` (`scalar_variable`)                    × 1
        //   * heredoc body (`heredoc_body_statement`)       × 1
        // expected: u_operands = 2, N2 = 2.
        check_metrics::<PerlParser>("my $msg = <<END;\nhello world\nEND\n", "foo.pl", |metric| {
            assert_eq!(metric.halstead.u_operands(), 2.0);
            assert_eq!(metric.halstead.operands(), 2.0);
        });
    }

    #[test]
    fn perl_interpolated_heredoc_no_double_count() {
        // Regression: issue #287. An interpolating Perl heredoc
        // (`<<"TAG"` or bare `<<TAG`) carries an `Interpolation` child
        // when its body contains a `$var`. The wrapper must drop to
        // `Unknown` so the inner scalar variable carries the operand
        // count — same dispatch as the existing double-quoted /
        // backtick / qx wrappers (issue #199) and the PHP heredoc fix
        // (issue #184).
        //
        // Source:
        //   my $name = "x";
        //   my $msg = <<"END";
        //   hi $name
        //   END
        //
        // Operands by text key:
        //   * `$name` × 2 (my-binding + interpolation inside heredoc)
        //   * `"x"`  × 1 (inert double-quoted string)
        //   * `$msg` × 1
        // expected: u_operands = 3, N2 = 4. Without the
        // interpolation-aware drop the wrapping heredoc body would
        // also count, lifting u_operands to 4 and N2 to 5.
        check_metrics::<PerlParser>(
            "my $name = \"x\";\nmy $msg = <<\"END\";\nhi $name\nEND\n",
            "foo.pl",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 3.0);
                assert_eq!(metric.halstead.operands(), 4.0);
            },
        );
    }

    #[test]
    fn lua_operators_and_operands() {
        check_metrics::<LuaParser>(
            "local function add(a, b)
  local result = a + b
  if result > 0 then
    return result
  end
  return 0
end",
            "foo.lua",
            |metric| {
                // n1=12: local,function,(,,,),=,+,if,>,then,return,end
                // n2=5: add,a,b,result,0
                insta::assert_json_snapshot!(metric.halstead, @r###"
                    {
                      "n1": 12.0,
                      "N1": 15.0,
                      "n2": 5.0,
                      "N2": 10.0,
                      "length": 25.0,
                      "estimated_program_length": 54.62919048309068,
                      "purity_ratio": 2.1851676193236274,
                      "vocabulary": 17.0,
                      "volume": 102.18657103125848,
                      "difficulty": 12.0,
                      "level": 0.08333333333333333,
                      "effort": 1226.2388523751017,
                      "time": 68.12438068750565,
                      "bugs": 0.03818816527310305
                    }
                    "###);
            },
        );
    }

    #[test]
    fn kotlin_halstead_basic() {
        check_metrics::<KotlinParser>(
            "fun add(a: Int, b: Int): Int {
                val result = a + b
                return result
            }",
            "foo.kt",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r###"
                    {
                      "n1": 9.0,
                      "N1": 11.0,
                      "n2": 5.0,
                      "N2": 10.0,
                      "length": 21.0,
                      "estimated_program_length": 40.13896548741762,
                      "purity_ratio": 1.9113793089246487,
                      "vocabulary": 14.0,
                      "volume": 79.9544533632097,
                      "difficulty": 9.0,
                      "level": 0.1111111111111111,
                      "effort": 719.5900802688873,
                      "time": 39.97722668160485,
                      "bugs": 0.026767153565498338
                    }
                    "###
                );
            },
        );
    }

    #[test]
    fn kotlin_string_template_no_double_count() {
        // Regression: issue #191. A Kotlin string template (`"Hi $name!"`)
        // wraps an `Interpolation` child whose inner expression is
        // walked and counted separately. Without the
        // `is_child(Interpolation)` guard the wrapping `StringLiteral`
        // would also count as an operand, inflating N2. Same pattern as
        // #180 (Bash/Elixir) and #184 (PHP).
        //
        // Source: `fun greet(name: String): String {\n    return "Hi $name!"\n}\n`
        // Operands (by source-byte key):
        //   Function signature (no body): `greet` × 1, `name` × 1,
        //   `String` × 2 (param type + return type) = 3 unique, 4 total.
        //   Body adds the short-form interpolation `$name`: tree-sitter
        //   kotlin-ng 1.1.0 produces an `identifier` node whose source
        //   range includes the leading `$`, so its bytes are `$name` —
        //   distinct from the bare `name` operand in the signature.
        //   The wrapping `StringLiteral` is skipped (fix working) →
        //   u_operands = 4 (`greet`, `name`, `String`, `$name`), N2 = 5.
        //   Without the fix the `StringLiteral` text (`"Hi $name!"`)
        //   would also be counted → N2 = 6, u_operands = 5.
        check_metrics::<KotlinParser>(
            "fun greet(name: String): String {\n    return \"Hi $name!\"\n}\n",
            "foo.kt",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 4.0);
                assert_eq!(metric.halstead.operands(), 5.0);
            },
        );
    }

    #[test]
    fn kotlin_string_template_long_form_no_double_count() {
        // The `${expr}` long form of a Kotlin string template also
        // produces an `Interpolation` child. The fix must apply to it
        // identically.
        //
        // Source: `fun f(x: Int): String { return "v=${x}" }\n`
        // Operands by source-byte key:
        //   `f` × 1, `x` × 2 (param + inside `${x}`),
        //   `Int` × 1, `String` × 1.
        // With the fix u_operands = 4 (`f`, `x`, `Int`, `String`),
        // N2 = 5. Without the fix the wrapping `"v=${x}"` would also
        // count → u_operands = 5, N2 = 6.
        check_metrics::<KotlinParser>(
            "fun f(x: Int): String { return \"v=${x}\" }\n",
            "foo.kt",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 4.0);
                assert_eq!(metric.halstead.operands(), 5.0);
            },
        );
    }

    #[test]
    fn kotlin_plain_string_still_operand() {
        // The fix for #191 only skips wrapping templates that contain
        // an `Interpolation` child; a plain `"hello"` (no `$` interp)
        // must still contribute exactly one operand.
        //
        // Source: `fun f(): String { return "hello" }\n`
        // Operands: `f` × 1, `String` × 1, `"hello"` × 1 →
        // u_operands = 3, N2 = 3.
        check_metrics::<KotlinParser>(
            "fun f(): String { return \"hello\" }\n",
            "foo.kt",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 3.0);
                assert_eq!(metric.halstead.operands(), 3.0);
            },
        );
    }

    #[test]
    fn python_fstring_no_double_count() {
        // Regression: issue #191. A Python f-string (`f"Hi {name}!"`)
        // wraps an `Interpolation` child whose inner identifier
        // `name` is walked and counted as its own operand. Without
        // the `is_child(Interpolation)` guard the wrapping `String`
        // would also count, double-counting `name`'s contribution to
        // `N2`. Same pattern as #180 (Bash/Elixir) and #184 (PHP).
        //
        // Source: `def greet(name):\n    return f"Hi {name}!"\n`
        // Operands by source-byte key:
        //   `greet` × 1, `name` × 2 (param + inside `{name}`).
        // With the fix the wrapping `f"Hi {name}!"` is skipped →
        // u_operands = 2 (`greet`, `name`), N2 = 3. Without the fix
        // the wrapping literal would also count → u_operands = 3,
        // N2 = 4.
        check_metrics::<PythonParser>(
            "def greet(name):\n    return f\"Hi {name}!\"\n",
            "foo.py",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 2.0);
                assert_eq!(metric.halstead.operands(), 3.0);
            },
        );
    }

    #[test]
    fn python_plain_string_still_operand() {
        // The fix for #191 only skips wrapping `String` nodes that
        // contain an `Interpolation` child; a plain `"hi"` must still
        // contribute exactly one operand.
        //
        // Source: `def f():\n    return "hi"\n`
        // Operands: `f` × 1, `"hi"` × 1 → u_operands = 2, N2 = 2.
        // (The previous documentation-string filter is preserved:
        // a bare `"hi"` as a top-level `expression_statement` would
        // be skipped, but here it appears as `return "hi"`.)
        check_metrics::<PythonParser>("def f():\n    return \"hi\"\n", "foo.py", |metric| {
            assert_eq!(metric.halstead.u_operands(), 2.0);
            assert_eq!(metric.halstead.operands(), 2.0);
        });
    }

    #[test]
    fn python_empty_file_halstead() {
        check_metrics::<PythonParser>("", "empty.py", |metric| {
            let h = &metric.halstead;
            assert_eq!(h.u_operators(), 0.0);
            assert_eq!(h.operands(), 0.0);
            assert_eq!(h.estimated_program_length(), 0.0);
            assert_eq!(h.purity_ratio(), 0.0);
            assert_eq!(h.volume(), 0.0);
            assert_eq!(h.difficulty(), 0.0);
            assert_eq!(h.level(), 0.0);
            assert_eq!(h.effort(), 0.0);
            assert_eq!(h.time(), 0.0);
            assert_eq!(h.bugs(), 0.0);
        });
    }

    #[test]
    fn bash_operators_and_operands() {
        check_metrics::<BashParser>(
            "#!/bin/bash
f() {
    local x=1
    if [ $x -eq 1 ]; then
        echo 'one'
    fi
}",
            "foo.sh",
            |metric| {
                // `x` (assignment LHS and inside `$x`) is a `variable_name`
                // with aliased kind_id 160 — all three aliases must be in
                // the operand list (see lesson 2).
                assert_eq!(metric.halstead.u_operators(), 12.0);
                assert_eq!(metric.halstead.operators(), 12.0);
                assert_eq!(metric.halstead.u_operands(), 6.0);
                assert_eq!(metric.halstead.operands(), 9.0);
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn bash_interpolated_string_no_double_count() {
        // Regression: issue #180. A double-quoted Bash string containing
        // `$name`, `${name[…]}`, or `$(cmd)` used to be classified as a
        // Halstead operand AND have its inner `simple_expansion` /
        // `expansion` / `command_substitution` children classified as
        // operands too. We now skip the wrapping literal when it has an
        // expansion child so only the inner expansion contributes.
        //
        // expected: operands across `a="plain"\nb="$x"\n` —
        //   line 1: variable_name `a`, plain string `"plain"` (no
        //     expansion, still operand) → 2.
        //   line 2: variable_name `b`, wrapping `"$x"` skipped (has
        //     expansion), `simple_expansion` `$x`, inner variable_name
        //     `x` → 3.
        // Total unique operands: 5 (`a`, `b`, `"plain"`, `$x`, `x`),
        // each appearing once → N2 = 5. Without the #180 fix, the
        // wrapping `"$x"` literal would also be counted, making
        // u_operands = 6 and N2 = 6. The `=` is the only operator;
        // appears twice (N1 = 2, n1 = 1).
        check_metrics::<BashParser>("a=\"plain\"\nb=\"$x\"\n", "foo.sh", |metric| {
            assert_eq!(metric.halstead.u_operators(), 1.0);
            assert_eq!(metric.halstead.operators(), 2.0);
            assert_eq!(metric.halstead.u_operands(), 5.0);
            assert_eq!(metric.halstead.operands(), 5.0);
            insta::assert_json_snapshot!(metric.halstead);
        });
    }

    #[test]
    fn elixir_interpolated_string_no_double_count() {
        // Regression: issue #180. Without the fix, an interpolated
        // Elixir `String` was classified as a single operand while its
        // inner `interpolation` identifier was also walked and
        // classified as its own operand — double-counting the
        // interpolated identifier's contribution to `N2`.
        //
        // expected: operand contributions for
        //   `def greet(name) do\n  msg = "Hi #{name}"\nend\n` —
        // `def`, `greet`, `name` (param), `msg`, and the inner `name`
        // (inside `#{...}`). With the fix, the wrapping
        // `"Hi #{name}"` literal is skipped (has `Interpolation`
        // child), so `name` is the only repeated operand:
        // u_operands = 4 (def, greet, name, msg), N2 = 5. Without the
        // fix, the wrapping literal would also count → u_operands = 5,
        // N2 = 6. Operators (`do`, `end`, `(`, `)`, `=`, `#{`, `}`)
        // are unchanged: u = N = 7 (the `#{`/`}` interpolation
        // markers stay classified as operators).
        check_metrics::<ElixirParser>(
            "def greet(name) do\n  msg = \"Hi #{name}\"\nend\n",
            "foo.ex",
            |metric| {
                assert_eq!(metric.halstead.u_operators(), 7.0);
                assert_eq!(metric.halstead.operators(), 7.0);
                assert_eq!(metric.halstead.u_operands(), 4.0);
                assert_eq!(metric.halstead.operands(), 5.0);
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn elixir_plain_string_still_operand() {
        // The fix for #180 only skips wrapping literals that contain
        // interpolation; a plain `"hello"` must still contribute exactly
        // one operand. expected: `def`, `f`, `"hello"` → 3 unique
        // operands (n2 = 3), each appearing once (N2 = 3).
        check_metrics::<ElixirParser>("def f do\n  \"hello\"\nend\n", "foo.ex", |metric| {
            assert_eq!(metric.halstead.u_operands(), 3.0);
            assert_eq!(metric.halstead.operands(), 3.0);
        });
    }

    #[test]
    fn elixir_interpolated_sigil_no_double_count() {
        // Sigils mirror strings under #180. For `~r/foo#{name}/`, the
        // wrapping `Sigil` is skipped, but `SigilName` (`r`) and the
        // inner `name` identifier each contribute one operand.
        // expected: `def`, `f`, `name` (param), `re`, `r` (sigil name),
        // `name` (inside `#{...}`) → u_operands = 5, N2 = 6 (`name`
        // twice).
        check_metrics::<ElixirParser>(
            "def f(name) do\n  re = ~r/foo#{name}/\nend\n",
            "foo.ex",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 5.0);
                assert_eq!(metric.halstead.operands(), 6.0);
            },
        );
    }

    #[test]
    fn elixir_interpolated_charlist_no_double_count() {
        // Charlists mirror strings and sigils under #180. The
        // `E::String | E::Charlist | E::Sigil` arm in `get_op_type`
        // skips any wrapping literal that has an `Interpolation`
        // child; this test exercises the `Charlist` branch
        // specifically.
        //
        // expected: for `def f(name) do\n  cl = 'Hi #{name}'\nend\n` —
        // `def`, `f`, `name` (param), `cl`, and the inner `name`
        // (inside `#{...}`). With the fix, the wrapping
        // `'Hi #{name}'` is skipped → u_operands = 4 (def, f, name,
        // cl), N2 = 5 (`name` twice).
        check_metrics::<ElixirParser>(
            "def f(name) do\n  cl = 'Hi #{name}'\nend\n",
            "foo.ex",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 4.0);
                assert_eq!(metric.halstead.operands(), 5.0);
            },
        );
    }

    #[test]
    fn bash_all_expansion_kinds_skip_wrapper() {
        // Exercises every node kind tested by
        // `bash_string_has_expansion`: `simple_expansion` (`$v`),
        // `expansion` (`${v[0]}`), `command_substitution` (`$(date)`),
        // and `arithmetic_expansion` (`$((1+2))`). A typo replacing
        // one kind with an aliased neighbour in `language_bash.rs`
        // (e.g., `ExpansionBody` instead of `Expansion`) would leave
        // the corresponding wrapping string counted as an operand and
        // shift the totals.
        //
        // expected: operands across the four lines —
        //   line 1 `a="$v"`: var_name `a`, simple_expansion `$v`,
        //     inner var_name `v` (wrapper skipped) → 3
        //   line 2 `b="${v[0]}"`: var_name `b`, var_name `v` (inside
        //     subscript), number `0` (wrapper skipped, `expansion`
        //     itself is not in the operand list) → 3
        //   line 3 `c="$(date)"`: var_name `c`, command_name `date`
        //     (wrapper skipped, `command_substitution` not in operand
        //     list) → 2
        //   line 4 `d="$((1+2))"`: var_name `d`, numbers `1` and `2`
        //     (wrapper skipped, `arithmetic_expansion` not in operand
        //     list) → 3
        // Unique operands (`v` shared across lines 1 and 2): a, b, c,
        // d, $v, v, 0, date, 1, 2 → 10. Total occurrences: 12 (`v`
        // appears twice). Operators include `=` four times plus the
        // `${`, `}`, `$(`, `)`, `$((`, `))`, `[`, `]`, `+` punctuation.
        check_metrics::<BashParser>(
            "a=\"$v\"\nb=\"${v[0]}\"\nc=\"$(date)\"\nd=\"$((1+2))\"\n",
            "foo.sh",
            |metric| {
                assert_eq!(metric.halstead.u_operators(), 6.0);
                assert_eq!(metric.halstead.operators(), 9.0);
                assert_eq!(metric.halstead.u_operands(), 10.0);
                assert_eq!(metric.halstead.operands(), 12.0);
            },
        );
    }

    #[test]
    fn tcl_operators_and_operands() {
        check_metrics::<TclParser>(
            "proc f {a b} {
    set x [expr {$a + $b}]
    if {$x > 0 && $x != 0} {
        return $x
    }
    return 0
}",
            "foo.tcl",
            |metric| {
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn tcl_bitwise_ternary_string_ops() {
        // Exercises operator families not covered by tcl_operators_and_operands:
        // bitwise (&, |, ^, ~, <<, >>), ternary (?), and string-comparison (eq, ne, in, ni).
        check_metrics::<TclParser>(
            "proc f {a b} {
    set bits [expr {$a & $b | $a ^ ~$b}]
    set sh [expr {$a << 1 | $b >> 1}]
    set t [expr {$a > 0 ? $a : $b}]
    if {$a eq {x} || $a ne {y}} {
        return $a
    }
    return $b
}",
            "foo.tcl",
            |metric| {
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn tcl_bare_variable_operand() {
        // Bare `$varname` produces a VariableSubstitution node (already an operand).
        // Its anonymous Id2 child must NOT be counted separately; each reference is 1 operand.
        check_metrics::<TclParser>(
            "proc f {x} {
    return $x
}",
            "foo.tcl",
            |metric| {
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn tcl_inert_quoted_word_counts_as_operand() {
        // Regression for #277. A `"..."` literal with no `$var` / `[cmd]`
        // interpolation must contribute exactly one operand (the wrapping
        // `QuotedWord`). The string content `hello world` is exposed as a
        // single `_quoted_word_content` token (not itself classified by
        // `get_op_type`), so the only operands here are `f`, `s`, and the
        // quoted string. `set` is the anonymous `Set2` keyword and is
        // classified as an operator, not an operand.
        check_metrics::<TclParser>(
            "proc f {} {
    set s \"hello world\"
}",
            "foo.tcl",
            |metric| {
                // Operands: `f`, `s`, `"hello world"` — 3 unique, 3 total.
                // The wrapping `QuotedWord` must still contribute exactly
                // one operand when it carries no interpolation children;
                // dropping to 2 would mean the inert case was over-guarded.
                assert_eq!(metric.halstead.u_operands(), 3.0);
                assert_eq!(metric.halstead.operands(), 3.0);
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn tcl_interpolated_quoted_word_no_double_count() {
        // Regression for #277. Before the fix, `"$x is $y"` produced an
        // extra operand for the wrapping `QuotedWord` on top of the two
        // inner `VariableSubstitution` operands (`$x`, `$y`), giving 7.
        // After the fix, the wrapper is `HalsteadType::Unknown` whenever
        // it carries an interpolation child, so operand attribution
        // belongs solely to the inner substitutions.
        check_metrics::<TclParser>(
            "proc f {x y} {
    set s \"$x is $y\"
}",
            "foo.tcl",
            |metric| {
                // Operands: `f`, `x`, `y` (proc args), `s`, `$x`, `$y` — 6
                // unique, 6 total. The wrapping `QuotedWord` contributes
                // nothing. Pre-fix this read 7/7 (double-counted wrapper).
                assert_eq!(metric.halstead.u_operands(), 6.0);
                assert_eq!(metric.halstead.operands(), 6.0);
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn tcl_command_substitution_quoted_word_no_double_count() {
        // Regression for #277. A `"...[cmd]..."` literal exposes the
        // bracketed command as a `command_substitution` child whose inner
        // identifiers/literals contribute their own operands. The wrapping
        // `QuotedWord` must not also be classified as an operand, or the
        // command's identifier would be counted alongside a phantom
        // wrapper operand.
        check_metrics::<TclParser>(
            "proc f {} {
    set s \"result: [foo]\"
}",
            "foo.tcl",
            |metric| {
                // Operands: `f`, `s`, `foo` — 3 unique, 3 total. The
                // wrapping `QuotedWord` and the inert text `result: ` do
                // not contribute extra operands. Pre-fix this read 4/4
                // (double-counted wrapper).
                assert_eq!(metric.halstead.u_operands(), 3.0);
                assert_eq!(metric.halstead.operands(), 3.0);
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn php_operators_and_operands() {
        check_metrics::<PhpParser>(
            "<?php
            function avg(int $a, int $b, int $c): int {
                return ($a + $b + $c) / 3;
            }",
            "foo.php",
            |metric| {
                assert_eq!(metric.halstead.u_operators(), 11.0);
                assert_eq!(metric.halstead.operators(), 15.0);
                assert_eq!(metric.halstead.u_operands(), 9.0);
                assert_eq!(metric.halstead.operands(), 22.0);
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn php_simple_function() {
        check_metrics::<PhpParser>(
            "<?php
            function inc(int $x): int { return $x + 1; }",
            "foo.php",
            |metric| {
                assert_eq!(metric.halstead.u_operators(), 9.0);
                assert_eq!(metric.halstead.operators(), 9.0);
                assert_eq!(metric.halstead.u_operands(), 5.0);
                assert_eq!(metric.halstead.operands(), 10.0);
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn php_encapsed_string_interpolation_no_double_count() {
        // Regression: issue #184. A PHP `"Hello $name!"` used to be
        // classified as a Halstead operand (the wrapping
        // `encapsed_string`) AND have its inner `variable_name`
        // (`$name`) plus the inner `name` token classified as
        // operands too. With the fix, the wrapping literal drops to
        // `Unknown` when it carries any `$var` / `${name}` / `{$expr}`
        // child, so `$name` is counted exactly once at each text
        // occurrence.
        //
        // Source:
        //   <?php $name = "world"; echo "Hello $name!";
        //
        // Inert operand: `"world"` (no interpolation, still operand).
        // Operands by text key (`get_id` keys by source bytes):
        //   `$name` × 2 (assignment LHS and `$name` inside the
        //   interpolated string), `name` × 2 (the `name` token inside
        //   each `variable_name`), `"world"` × 1.
        // u_operands = 3, N2 = 5.
        // Without the fix the wrapping `"Hello $name!"` would also
        // count → u_operands = 4, N2 = 6.
        check_metrics::<PhpParser>(
            "<?php $name = \"world\"; echo \"Hello $name!\";",
            "foo.php",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 3.0);
                assert_eq!(metric.halstead.operands(), 5.0);
            },
        );
    }

    #[test]
    fn php_encapsed_string_no_interpolation_still_operand() {
        // The fix for #184 only drops `EncapsedString`/`Heredoc` from
        // the operand arm when interpolation is present. An inert
        // double-quoted string must still count as exactly one
        // operand, identical to the single-quoted equivalent.
        //
        // Source: `<?php echo "Hello world!";`
        // Operands: `"Hello world!"` × 1 → u_operands = 1, N2 = 1.
        check_metrics::<PhpParser>("<?php echo \"Hello world!\";", "foo.php", |metric| {
            assert_eq!(metric.halstead.u_operands(), 1.0);
            assert_eq!(metric.halstead.operands(), 1.0);
        });
    }

    #[test]
    fn php_heredoc_interpolation_no_double_count() {
        // Regression: issue #184. A PHP heredoc whose body
        // interpolates `$name` previously counted both the wrapping
        // `heredoc` node and the inner `$name` as operands; the fix
        // drops the wrapper when its `heredoc_body` carries any
        // interpolation child.
        //
        // Source:
        //   <?php $name = "x"; echo <<<EOT
        //   hi $name
        //   EOT;
        //
        // Operands by text key: `$name` × 2, `name` × 2, `"x"` × 1
        // (inert single-interp encapsed string also operand). With
        // the fix u_operands = 3, N2 = 5. Without the fix the
        // wrapping heredoc text would add one more unique operand.
        check_metrics::<PhpParser>(
            "<?php $name = \"x\"; echo <<<EOT\nhi $name\nEOT;\n",
            "foo.php",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 3.0);
                assert_eq!(metric.halstead.operands(), 5.0);
            },
        );
    }

    #[test]
    fn php_nowdoc_unaffected() {
        // `Nowdoc` (single-quoted heredoc) never interpolates and is
        // never matched by `php_string_has_interpolation`. It must
        // continue counting as exactly one operand regardless of the
        // text inside, mirroring single-quoted `String`.
        //
        // Source:
        //   <?php echo <<<'EOT'
        //   plain $name not interpolated
        //   EOT;
        //
        // Operands: the nowdoc literal × 1 → u_operands = 1, N2 = 1.
        check_metrics::<PhpParser>(
            "<?php echo <<<'EOT'\nplain $name not interpolated\nEOT;\n",
            "foo.php",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 1.0);
                assert_eq!(metric.halstead.operands(), 1.0);
            },
        );
    }

    #[test]
    fn php_encapsed_string_bare_member_access_no_double_count() {
        // Regression: issue #184 follow-up. The PHP grammar allows
        // bare `$obj->prop` interpolation inside `"…"` without
        // surrounding `{ … }`; tree-sitter-php emits this as a
        // direct `member_access_expression` child of
        // `encapsed_string` (kind_id 329 in the current grammar).
        // The wrapper must drop to `Unknown` for that form too —
        // otherwise the inner `$obj` and `prop` `name` tokens are
        // walked as operands while the wrapper also counts,
        // double-counting `N2`.
        //
        // Source:
        //   <?php $obj = new stdClass; $obj->prop = "x"; echo "Hi $obj->prop!";
        //
        // Operands tallied by `get_id` (keyed on source bytes):
        //   `$obj`        × 3 (LHS assignment, member-access target,
        //                      inside the interpolated string)
        //   `obj`  (name) × 3 (one per `variable_name`)
        //   `prop` (name) × 2 (member-access RHS twice)
        //   `stdClass`    × 1
        //   `"x"`         × 1
        // ⇒ u_operands = 5, N2 = 10.
        // With the bug the wrapping `"Hi $obj->prop!"` text adds one
        // more unique operand and one more occurrence ⇒ 6 / 11.
        check_metrics::<PhpParser>(
            "<?php $obj = new stdClass; $obj->prop = \"x\"; echo \"Hi $obj->prop!\";",
            "foo.php",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 5.0);
                assert_eq!(metric.halstead.operands(), 10.0);
            },
        );
    }

    #[test]
    fn php_encapsed_string_bare_subscript_no_double_count() {
        // Regression: issue #184 follow-up. Bare `$arr[0]` inside
        // `"…"` produces a `subscript_expression` child of
        // `encapsed_string` (kind_id 351). The wrapper must drop to
        // `Unknown` for that form.
        //
        // Source:
        //   <?php $arr = [1]; echo "Hi $arr[0]!";
        //
        // Operands tallied by `get_id`:
        //   `$arr` × 2, `arr` × 2 (inner `name`), `1` × 1, `0` × 1.
        // ⇒ u_operands = 4, N2 = 6.
        // With the bug the wrapping `"Hi $arr[0]!"` text adds 1 / 1.
        check_metrics::<PhpParser>(
            "<?php $arr = [1]; echo \"Hi $arr[0]!\";",
            "foo.php",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 4.0);
                assert_eq!(metric.halstead.operands(), 6.0);
            },
        );
    }

    #[test]
    fn php_shell_command_expression_inert_is_operand() {
        // Regression: issue #288. Backtick command literals (PHP's
        // `shell_command_expression`) were filtered as strings by
        // `Checker::is_string` and `Alterator::alterate`, but never
        // classified as Halstead operands — so they contributed
        // nothing to N2 / eta2. An inert backtick literal must now
        // count as exactly one operand, matching `EncapsedString`
        // and `Heredoc`.
        //
        // Source: `<?php $out = ` + backtick `ls` + backtick + `;`
        // Operands tallied by `get_id`:
        //   `$out` × 1, `out` × 1 (inner `name`), backtick literal × 1.
        // ⇒ u_operands = 3, N2 = 3.
        // Before the fix the backtick literal vanished from the count
        // ⇒ u_operands = 2, N2 = 2.
        check_metrics::<PhpParser>("<?php $out = `ls`;", "foo.php", |metric| {
            assert_eq!(metric.halstead.u_operands(), 3.0);
            assert_eq!(metric.halstead.operands(), 3.0);
        });
    }

    #[test]
    fn php_shell_command_expression_interpolation_no_double_count() {
        // Regression: issue #288. PHP backtick literals DO support
        // `$var` interpolation (see tree-sitter-php node-types.json:
        // `shell_command_expression` children include `variable_name`,
        // `dynamic_variable_name`, `member_access_expression`,
        // `subscript_expression`). With the fix the wrapper drops to
        // `Unknown` when it carries any interpolation child, exactly
        // as `EncapsedString` does.
        //
        // Source: `<?php $dir = "/tmp"; $out = ` + backtick `ls $dir` +
        //   backtick + `;`
        //
        // Operands tallied by `get_id`:
        //   `$dir` × 2 (assignment LHS, inside backticks),
        //   `dir`  × 2 (inner `name`),
        //   `$out` × 1, `out` × 1, `"/tmp"` × 1.
        // ⇒ u_operands = 5, N2 = 7.
        // Without the interpolation guard the wrapping backtick literal
        // would also count ⇒ u_operands = 6, N2 = 8.
        check_metrics::<PhpParser>(
            "<?php $dir = \"/tmp\"; $out = `ls $dir`;",
            "foo.php",
            |metric| {
                assert_eq!(metric.halstead.u_operands(), 5.0);
                assert_eq!(metric.halstead.operands(), 7.0);
            },
        );
    }

    #[test]
    fn elixir_operators_and_operands() {
        // Exercises every Halstead family classified in Elixir's
        // `get_op_type`: control-flow keywords (`do`, `end`, `fn`),
        // structural punctuation (`(`, `)`, `[`, `]`, `,`, `.`, `@`),
        // arithmetic (`+`, `-`, `*`, `/`), comparison (`==`, `>`),
        // logical (`&&`, `||`, `and`, `or`, `!`), pipe (`|>`), capture
        // (`&`), assignment/match (`=`), and the stab arrow (`->`).
        // The body mixes identifiers, integers, atoms, and a string.
        check_metrics::<ElixirParser>(
            "defmodule Foo do\n  @doc \"add\"\n  def calc(a, b) do\n    result = a + b * 2\n    flag = result > 0 && a == b\n    out = if flag, do: result, else: -result\n    [out, a, b]\n  end\nend\n",
            "foo.ex",
            |metric| {
                // Positive headline assertions on integer counts.
                assert_eq!(metric.halstead.u_operators(), 15.0);
                assert_eq!(metric.halstead.operators(), 23.0);
                assert_eq!(metric.halstead.u_operands(), 16.0);
                assert_eq!(metric.halstead.operands(), 27.0);
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r###"
                {
                  "n1": 15.0,
                  "N1": 23.0,
                  "n2": 16.0,
                  "N2": 27.0,
                  "length": 50.0,
                  "estimated_program_length": 122.60335893412778,
                  "purity_ratio": 2.452067178682556,
                  "vocabulary": 31.0,
                  "volume": 247.70981551934375,
                  "difficulty": 12.65625,
                  "level": 0.07901234567901234,
                  "effort": 3135.0773526666944,
                  "time": 174.17096403703857,
                  "bugs": 0.07140208917738183
                }"###
                );
            },
        );
    }

    #[test]
    fn ruby_operators_and_operands() {
        // A small Ruby method exercising operators (def/if/end keyword
        // tokens, `+`, `==`, `<=`, structural punctuation) and operands
        // (`n`, `1`, `factorial`). Anchors the unique/total counts on
        // both sides and snapshots the full Halstead derivation.
        //
        // Lesson 4 invariants: u_operators / u_operands here equal the
        // dedupe lengths the `--ops` accessor would emit on the same
        // source. Any future grammar bump that adds an aliased kind_id
        // to either side will trip this without snapshot drift.
        check_metrics::<RubyParser>(
            "def factorial(n)\n  return 1 if n <= 1\n  n * factorial(n - 1)\nend\n",
            "foo.rb",
            |metric| {
                assert_eq!(metric.halstead.u_operators(), 9.0);
                assert_eq!(metric.halstead.operators(), 11.0);
                assert_eq!(metric.halstead.u_operands(), 3.0);
                assert_eq!(metric.halstead.operands(), 9.0);
                insta::assert_json_snapshot!(metric.halstead);
            },
        );
    }

    #[test]
    fn ruby_halstead_plain_string_operand() {
        // A bare string literal contributes exactly one operand. The
        // counterpart to `ruby_halstead_interpolated_string_no_double_count`
        // — verifies the "no interpolation" branch of the same arm
        // (see `src/getter.rs::get_op_type`'s `R::String | …` case).
        // expected: operators = {def, end} = 2; operands = {f, "hello"} = 2.
        check_metrics::<RubyParser>("def f\n  \"hello\"\nend\n", "foo.rb", |metric| {
            assert_eq!(metric.halstead.u_operators(), 2.0);
            assert_eq!(metric.halstead.operators(), 2.0);
            assert_eq!(metric.halstead.u_operands(), 2.0);
            assert_eq!(metric.halstead.operands(), 2.0);
        });
    }

    #[test]
    fn ruby_halstead_interpolated_string_no_double_count() {
        // Regression mirror for #180 (Bash) / #183 (C#): when a Ruby
        // string literal carries an `Interpolation` child, the
        // wrapping `String` node is intentionally classified as
        // `Unknown` so the inner expression's identifiers are not
        // double-counted as operands.
        //
        // expected: for `def f(name)\n  "Hi #{name}"\nend\n` —
        //   operators: def, (, ), #{, }, end → u_operators = 6.
        //   operands: f, name (param), name (inside `#{name}`). The
        //   wrapping `"…#{name}"` literal is skipped by the
        //   `is_child(R::Interpolation)` guard; the operand store
        //   keys by token text so the two `name` occurrences dedupe
        //   into one distinct entry → u_operands = 2, operands = 3
        //   (`f` once, `name` twice).
        // Without the guard, the wrapping literal would also count,
        // inflating u_operands to 3 and operands to 4.
        check_metrics::<RubyParser>("def f(name)\n  \"Hi #{name}\"\nend\n", "foo.rb", |metric| {
            assert_eq!(metric.halstead.u_operands(), 2.0);
            assert_eq!(metric.halstead.operands(), 3.0);
        });
    }

    #[test]
    fn ruby_halstead_symbol_literal_operand() {
        // `:foo` is a `SimpleSymbol` leaf — counts as a single
        // operand, no interpolation guard needed (only
        // `DelimitedSymbol` (`:"…#{x}…"`) can interpolate).
        // expected: operators = {def, end} = 2; operands = {f, :ok} = 2.
        check_metrics::<RubyParser>("def f\n  :ok\nend\n", "foo.rb", |metric| {
            assert_eq!(metric.halstead.u_operators(), 2.0);
            assert_eq!(metric.halstead.u_operands(), 2.0);
        });
    }

    #[test]
    fn ruby_halstead_regex_operand() {
        // `/foo/` parses as a `Regex` node — one operand. The slash
        // delimiters around it are emitted as `SLASH` tokens and
        // classified as arithmetic-or-divide operators by the shared
        // arm; they count once toward the distinct-operator set.
        // expected: u_operators = {def, (, ), =~, /, end} = 6;
        // u_operands = {f, s, /foo/} = 3.
        check_metrics::<RubyParser>("def f(s)\n  s =~ /foo/\nend\n", "foo.rb", |metric| {
            assert_eq!(metric.halstead.u_operators(), 6.0);
            assert_eq!(metric.halstead.u_operands(), 3.0);
        });
    }
}