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
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
// 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 std::fmt;
use crate::checker::Checker;
use crate::getter::Getter;
use crate::int_hash::IntKeyHashMap;
use crate::macros::implement_metric_trait;
use crate::*;
/// The `Halstead` metric suite.
#[derive(Default, Clone, Debug, PartialEq)]
#[non_exhaustive]
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, PartialEq)]
pub struct HalsteadMaps<'a> {
/// Keyed by `kind_id`, so it is hashed with [`crate::int_hash`]'s
/// integer hasher rather than SipHash: the key is a grammar symbol
/// this crate generated, drawn from an alphabet of at most a few
/// hundred values, so there is nothing for a keyed hash to defend.
pub(crate) operators: IntKeyHashMap<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.
///
/// Text-keyed, so it keeps SipHash — see the module doc on
/// [`crate::int_hash`] for why analysed source text does not qualify
/// for the fast hasher.
pub(crate) primitive_operators: HashMap<&'a [u8], u64>,
/// Text-keyed, and on SipHash for the same reason as
/// `primitive_operators`.
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 fmt::Display for Stats {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"unique_operators: {}, \
total_operators: {}, \
unique_operands: {}, \
total_operands: {}, \
length: {}, \
estimated_program_length: {}, \
purity_ratio: {}, \
size: {}, \
volume: {}, \
difficulty: {}, \
level: {}, \
effort: {}, \
time: {}, \
bugs: {}",
self.unique_operators(),
self.total_operators(),
self.unique_operands(),
self.total_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 {
// Intentionally a no-op. Halstead distinct-counts (`u_operators` /
// `u_operands`) cannot be summed across sibling spaces without
// double-counting operators/operands they share. Cross-space
// aggregation is instead done by unioning the occurrence maps
// (`HalsteadMaps::merge`) and re-running `finalize` on the parent
// (see `spaces/compute.rs`). Summing the finalized fields here —
// mirroring the sibling metrics' `merge` — would silently inflate
// every parent space's n1/n2/N1/N2.
pub(crate) fn merge(&mut self, _other: &Stats) {}
/// Returns `η1`, the number of distinct operators
#[inline]
#[must_use]
pub fn unique_operators(&self) -> u64 {
self.u_operators
}
/// Returns `N1`, the number of total operators
#[inline]
#[must_use]
pub fn total_operators(&self) -> u64 {
self.operators
}
/// Returns `η2`, the number of distinct operands
#[inline]
#[must_use]
pub fn unique_operands(&self) -> u64 {
self.u_operands
}
/// Returns `N2`, the number of total operands
#[inline]
#[must_use]
pub fn total_operands(&self) -> u64 {
self.operands
}
/// Returns the program length
///
/// Computed as `N = N1 + N2`, the sum of [`Self::total_operators`] and
/// [`Self::total_operands`].
#[inline]
#[must_use]
pub fn length(&self) -> u64 {
self.total_operands() + self.total_operators()
}
/// Returns the calculated estimated program length
///
/// Computed as `N^ = n1 * log2(n1) + n2 * log2(n2)`, where `n1` is
/// [`Self::unique_operators`] and `n2` is [`Self::unique_operands`]. Each term is
/// treated as `0` when its unique count is `0`.
#[inline]
#[must_use]
pub fn estimated_program_length(&self) -> f64 {
let uo = self.unique_operators() as f64;
let ud = self.unique_operands() as f64;
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
///
/// Computed as `PR = N^ / N`, the ratio of
/// [`Self::estimated_program_length`] to [`Self::length`].
#[inline]
#[must_use]
pub fn purity_ratio(&self) -> f64 {
let len = self.length() as f64;
if len == 0.0 {
0.0
} else {
self.estimated_program_length() / len
}
}
/// Returns the program vocabulary
///
/// Computed as `n = n1 + n2`, the sum of [`Self::unique_operators`] and
/// [`Self::unique_operands`].
#[inline]
#[must_use]
pub fn vocabulary(&self) -> u64 {
self.unique_operands() + self.unique_operators()
}
/// Returns the program volume.
///
/// Computed as `V = N * log2(n)`, where `N` is [`Self::length`] and `n`
/// is [`Self::vocabulary`]. Returns `0` when the vocabulary is `<= 1`,
/// since `log2` would be non-positive.
///
/// 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() as f64;
if vocab <= 1.0 {
0.0
} else {
self.length() as f64 * vocab.log2()
}
}
/// Returns the estimated difficulty required to program
///
/// Computed as `D = (n1 / 2) * (N2 / n2)`, where `n1` is
/// [`Self::unique_operators`], `N2` is [`Self::total_operands`], and `n2` is
/// [`Self::unique_operands`].
#[inline]
#[must_use]
pub fn difficulty(&self) -> f64 {
let ud = self.unique_operands() as f64;
if ud == 0.0 {
0.0
} else {
self.unique_operators() as f64 / 2. * self.total_operands() as f64 / ud
}
}
/// Returns the estimated level of difficulty required to program
///
/// Computed as `L = 1 / D`, the reciprocal of [`Self::difficulty`].
#[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
///
/// Computed as `E = D * V`, the product of [`Self::difficulty`] and
/// [`Self::volume`].
#[inline]
#[must_use]
pub fn effort(&self) -> f64 {
self.difficulty() * self.volume()
}
/// Returns the estimated time required to program.
///
/// Computed as `T = E / 18`, where `E` is [`Self::effort`] and `18` is
/// the Stroud number (see the divisor rationale below).
///
/// 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.
///
/// Computed as `B = E^(2/3) / 3000`, where `E` is [`Self::effort`]. This
/// is the effort-based variant of Halstead's delivered-bugs estimate
/// rather than the more commonly cited volume-based form `B = V / 3000`;
/// it matches the formula used by upstream `rust-code-analysis`.
#[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(crate) trait Halstead
where
Self: Checker + Getter,
{
/// Walk `node` and update `stats` with this metric for the language
/// implementing the trait.
///
/// `ancestors` is the chain the walker descended through; it is
/// handed to [`Getter::get_op_type`], six of whose impls classify a
/// token by what encloses it (#1096).
fn compute<'a>(
node: &Node<'a>,
code: &'a [u8],
ancestors: Ancestors<'a, '_>,
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],
ancestors: Ancestors<'a, '_>,
halstead_maps: &mut HalsteadMaps<'a>,
) {
match T::get_op_type_with_code(node, code, ancestors) {
HalsteadType::Operator => {
if T::is_primitive(node) {
// 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(T::get_operand_id(node, code, ancestors))
.or_insert(0) += 1;
}
_ => {}
}
}
// Every language's `Halstead::compute` is the same forward to
// `compute_halstead`, which classifies each node through the language's
// own `Getter` / `Checker`. Nothing per-language lives here — it lives
// in `src/getter/<lang>.rs` — so writing the impls out was 23 copies of
// one signature. (This is the only metric whose per-language impls are
// all identical; every other trait has real per-language bodies.)
macro_rules! impl_halstead_forwarding {
($($code:ty),+ $(,)?) => {
$(
impl Halstead for $code {
fn compute<'a>(
node: &Node<'a>,
code: &'a [u8],
ancestors: Ancestors<'a, '_>,
halstead_maps: &mut HalsteadMaps<'a>,
) {
compute_halstead::<Self>(node, code, ancestors, halstead_maps);
}
}
)+
};
}
impl_halstead_forwarding!(
PythonCode,
MozjsCode,
JavascriptCode,
TypescriptCode,
TsxCode,
RustCode,
CppCode,
CCode,
ObjcCode,
MozcppCode,
JavaCode,
GroovyCode,
CsharpCode,
GoCode,
PerlCode,
KotlinCode,
LuaCode,
PhpCode,
RubyCode,
ElixirCode,
BashCode,
TclCode,
IrulesCode,
);
// Real defaults — no operators / operands to count. Audited in #188.
implement_metric_trait!(Halstead, PreprocCode, CcommentCode);
#[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 std::collections::HashSet;
use std::path::PathBuf;
use crate::test_support::{ast_has_kind_id, check_metrics_only_shim, for_each_node_with_chain};
use super::*;
check_metrics_only_shim!(check_metrics, Halstead);
// Pins the lesson-4 invariant `n2 == len(dedupe(ops.operands))` by
// running `operands_and_operators` (the text-keyed `--ops` store)
// on the same source and comparing its deduplicated operand count
// to the expected `n2`. The metrics store and the ops store are
// independent (lesson 4); this catches a classification change that
// moves one without the other.
// `#[track_caller]` so a failure reports the *caller's* line rather
// than this helper's. Callers that wrap it in a per-language helper
// (`assert_char_literal_operands`, #1316) are tracked too, so the
// reported location names the language row instead of a shared line
// no assertion message distinguishes.
#[track_caller]
fn assert_ops_operands<T: crate::ParserTrait>(
source: &str,
file: &str,
expected_n2: usize,
mut expected_operands: Vec<&str>,
) {
let path = PathBuf::from(file);
let parser = T::new(source.as_bytes().to_vec(), &path, None);
let ops = crate::ops::ops_inner(&parser, None).expect("ops walk succeeds");
let unique: HashSet<&str> = ops.operands.iter().map(String::as_str).collect();
assert_eq!(
unique.len(),
expected_n2,
"dedupe(ops.operands) must equal n2; operands were {:?}",
ops.operands
);
let mut got: Vec<&str> = unique.into_iter().collect();
got.sort_unstable();
expected_operands.sort_unstable();
assert_eq!(got, expected_operands, "operand vocabulary for {file}");
}
/// Asserts the root space's `[n1, N1, n2, N2]`, naming `label` when
/// it does not hold.
///
/// The delimiter-invariance tests (#1256 Elixir, #1312 Ruby and
/// Perl) each loop over spellings of one literal and need the
/// spelling in the failure message; `check_metrics` expands to a
/// plain `fn` that cannot capture a loop variable, so they reach
/// for the closure-taking helper it wraps. Three copies of that
/// dance is two too many.
fn assert_halstead_counts<T: crate::ParserTrait>(
source: &str,
file: &str,
expected: [u64; 4],
label: &str,
) {
crate::test_support::check_func_space_only::<T, _>(
source,
file,
&[crate::Metric::Halstead],
|space| {
let halstead = &space.metrics.halstead;
assert_eq!(
[
halstead.unique_operators(),
halstead.total_operators(),
halstead.unique_operands(),
halstead.total_operands(),
],
expected,
"{label}"
);
},
);
}
#[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#"
{
"unique_operators": 3,
"total_operators": 9,
"unique_operands": 9,
"total_operands": 12,
"length": 21,
"estimated_program_length": 33.284212515144276,
"purity_ratio": 1.584962500721156,
"vocabulary": 12,
"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::<CParser>(
"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.unique_operators(), 8);
assert_eq!(metric.halstead.unique_operands(), 4);
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::<CParser>(
"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.unique_operators() >= 14,
"expected >= 14 unique operators (bitwise + logical + syntax), got {}",
s.unique_operators(),
);
assert_eq!(s.unique_operands(), 8); // 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::<CParser>(
"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.unique_operators() >= 10,
"expected >= 10 unique operators including ++ / -- / sizeof / cast, got {}",
s.unique_operators(),
);
assert_eq!(s.unique_operands(), 4);
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#"
{
"unique_operators": 9,
"total_operators": 24,
"unique_operands": 10,
"total_operands": 18,
"length": 42,
"estimated_program_length": 61.74860596185444,
"purity_ratio": 1.470204903853677,
"vocabulary": 19,
"volume": 178.41295556463058,
"difficulty": 8.1,
"level": 0.1234567901234568,
"effort": 1445.1449400735075,
"time": 80.28583000408375,
"bugs": 0.04260752914034329
}
"#
);
},
);
}
/// A `sized_type_specifier` carries its `unsigned`/`signed`/`long`/
/// `short` modifiers as bare keyword tokens (distinct kind_ids), not
/// as `primitive_type` children. Prior to issue #466 those tokens
/// fell through to the `Unknown` arm and were dropped from `n1`/`N1`,
/// so `unsigned int` collapsed to just `int` and `signed long`
/// contributed nothing. They must each count as a distinct operator,
/// while `long long`'s two `long` tokens fold to one `n1` entry but
/// two `N1` hits. Regression test for issue #466.
#[test]
fn cpp_sized_type_specifier_operators() {
let source = "unsigned int u = 3; signed long b = 4; long long c = 5;";
check_metrics::<CppParser>(source, "foo.cpp", |metric| {
// Distinct operators (n1): unsigned, signed, long, int, =, ; = 6
// Total operators (N1):
// unsigned(1) + int(1) + =(3) + ;(3) + signed(1) + long(3) = 12
// (`long` appears once in `signed long` and twice in `long long`)
// Distinct/total operands: u, b, c, 3, 4, 5 = 6 / 6
assert_eq!(metric.halstead.unique_operators(), 6);
assert_eq!(metric.halstead.total_operators(), 12);
assert_eq!(metric.halstead.unique_operands(), 6);
assert_eq!(metric.halstead.total_operands(), 6);
});
// Pin the lesson-4 `n1 == dedupe(ops.operators)` invariant: the
// kind_id-keyed metrics store and the text-keyed `--ops` store are
// independent, so a modifier classified in one but not the other
// would diverge here.
let path = PathBuf::from("foo.cpp");
let parser = CppParser::new(source.as_bytes().to_vec(), &path, None);
let ops = crate::ops::ops_inner(&parser, None).expect("ops walk succeeds");
let unique_operators: HashSet<&str> = ops.operators.iter().map(String::as_str).collect();
assert_eq!(
unique_operators.len(),
6,
"dedupe(ops.operators) must equal n1; operators were {:?}",
ops.operators
);
for modifier in ["unsigned", "signed", "long"] {
assert!(
unique_operators.contains(modifier),
"sized_type_specifier modifier {modifier:?} missing from ops.operators: {:?}",
ops.operators
);
}
}
/// 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.unique_operators(), 8);
assert_eq!(s.unique_operands(), 4);
insta::assert_json_snapshot!(
s,
@r#"
{
"unique_operators": 8,
"total_operators": 11,
"unique_operands": 4,
"total_operands": 6,
"length": 17,
"estimated_program_length": 32.0,
"purity_ratio": 1.8823529411764706,
"vocabulary": 12,
"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.unique_operators(), 7);
assert_eq!(s.unique_operands(), 3);
});
}
/// 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.unique_operators(), 6);
assert_eq!(s.unique_operands(), 1);
});
}
/// 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.unique_operators(), 6);
assert_eq!(s.unique_operands(), 1);
},
);
}
#[test]
fn cpp_raw_string_delimiter_is_not_an_operator() {
// Regression: issue #1314, the C++ sibling of Elixir #1256 and
// Ruby/Perl #1312. A `raw_string_literal` carries its `R"(`
// opener as a bare `LPAREN` child — the kind id a call uses —
// so `auto a = R"(raw)";` reported a `()` operator with no call
// in the source.
//
// The fixture holds both sides at once: two raw strings and one
// real call. A guard widened past the literal would drop
// `f(a)`'s parenthesis and fail here rather than silently
// passing.
//
// The second literal uses the custom-delimiter form to pin that
// shape too — it adds a `raw_string_delimiter` child but keeps
// the same `(` — and its distinct text makes n2 differ from N2.
//
// expected: operators `;` × 3, `=` × 3, `int`, `()` × 1 →
// n1 = 4, N1 = 8. Operands the two literals, `a` × 2, `b`, `c`,
// `f` → n2 = 6, N2 = 7. Before the guard the two openers added
// two more `()` → N1 = 10.
check_metrics::<CppParser>(
"auto a = R\"(raw)\";\nauto b = R\"tag(raw)tag\";\nint c = f(a);\n",
"foo.cpp",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 4);
assert_eq!(metric.halstead.total_operators(), 8);
assert_eq!(metric.halstead.unique_operands(), 6);
assert_eq!(metric.halstead.total_operands(), 7);
},
);
}
#[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#"
{
"unique_operators": 10,
"total_operators": 23,
"unique_operands": 9,
"total_operands": 15,
"length": 38,
"estimated_program_length": 61.74860596185444,
"purity_ratio": 1.624963314785643,
"vocabulary": 19,
"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.
// Grew from 30 → 33 with the issue #394 fix: `const`,
// `type`, and `struct` keywords are now classified as
// operators (one occurrence each).
assert_eq!(metric.halstead.unique_operators(), 33);
assert_eq!(metric.halstead.total_operators(), 121);
// u_operands / operands grew (was 31/50 before #390): the
// fix now classifies TypeIdentifier (`T`, `S`, `Option`)
// and FieldIdentifier (struct fields `x`, `y`) as operands
// alongside the existing primitive type names.
assert_eq!(metric.halstead.unique_operands(), 36);
assert_eq!(metric.halstead.total_operands(), 55);
},
);
}
#[test]
fn rust_field_identifier_is_operand() {
// Regression for issue #390: prior to the fix, `FieldIdentifier`
// (e.g. the `x` / `y` in `p.x`, `p.y`) fell through to
// `HalsteadType::Unknown`, so the field names were not counted
// as operands. Both C++ and Go already classify FieldIdentifier
// as an operand. After the fix:
// unique operators: fn, (), {}, let, =, +, ;, .
// unique operands : main, p, Point, x, y, sum, 0, 1
// Field names `x` and `y` each appear twice (`p.x + p.y` and
// the struct literal `Point { x: 0, y: 1 }`).
check_metrics::<RustParser>(
"fn main() {
let p = Point { x: 0, y: 1 };
let sum = p.x + p.y;
}",
"foo.rs",
|metric| {
// Headline: pre-fix, FieldIdentifier (`x`, `y`) and
// TypeIdentifier (`Point`) fell through to Unknown, so
// u_operands was 5 (main, p, sum, 0, 1). After the
// fix, +Point, +x, +y → 8 distinct names.
assert_eq!(metric.halstead.unique_operands(), 8);
assert_eq!(metric.halstead.total_operands(), 12);
insta::assert_json_snapshot!(
metric.halstead,
@r#"
{
"unique_operators": 9,
"total_operators": 14,
"unique_operands": 8,
"total_operands": 12,
"length": 26,
"estimated_program_length": 52.529325012980806,
"purity_ratio": 2.0203586543454155,
"vocabulary": 17,
"volume": 106.27403387250882,
"difficulty": 6.75,
"level": 0.14814814814814814,
"effort": 717.3497286394346,
"time": 39.85276270219081,
"bugs": 0.026711567292222575
}
"#
);
},
);
}
#[test]
fn rust_type_identifier_is_operand() {
// Regression for issue #390: `TypeIdentifier` (e.g. `Vec`,
// `HashMap`, `String` when used as a path name) was dropped to
// `HalsteadType::Unknown` for Rust. C++ and Go classify them as
// operands. After the fix, u_operands = 8:
// main, v, m, Vec, HashMap, new, K, V
// (`i32` is a primitive type, classified as an operator.)
//
// Also covers issue #394: `::` is now an operator. The snippet
// has two `::` tokens (`Vec::new`, `HashMap::new`), so n1 grew
// from 10 → 11 and N1 from 17 → 19.
check_metrics::<RustParser>(
"fn main() {
let v: Vec<i32> = Vec::new();
let m: HashMap<K, V> = HashMap::new();
}",
"foo.rs",
|metric| {
// Headline: u_operands includes `Vec`, `HashMap`, `K`,
// `V` (and `i32` as a primitive operator). Without the
// fix, Vec/HashMap/K/V silently dropped to Unknown.
assert_eq!(metric.halstead.unique_operands(), 8);
assert_eq!(metric.halstead.total_operands(), 11);
// `::` appears twice (Vec::new, HashMap::new); without
// the #394 fix u_operators was 10 and operators 17.
assert_eq!(metric.halstead.unique_operators(), 11);
assert_eq!(metric.halstead.total_operators(), 19);
insta::assert_json_snapshot!(
metric.halstead,
@r#"
{
"unique_operators": 11,
"total_operators": 19,
"unique_operands": 8,
"total_operands": 11,
"length": 30,
"estimated_program_length": 62.05374780501027,
"purity_ratio": 2.068458260167009,
"vocabulary": 19,
"volume": 127.43782540330756,
"difficulty": 7.5625,
"level": 0.1322314049586777,
"effort": 963.7485546125134,
"time": 53.54158636736186,
"bugs": 0.03252279825177962
}
"#
);
},
);
}
#[test]
fn rust_path_separator_is_operator() {
// Regression for issue #394: `::` (`COLONCOLON`) was missing
// from the Rust `get_op_type` operator arm even though C++,
// Java, C#, and Kotlin all classify it as an operator. Path-
// heavy code (`std::collections::HashMap`, `Vec::new`,
// `T::method`) had every `::` silently dropped into
// HalsteadType::Unknown.
//
// Snippet has three `::` tokens (`std::collections::HashMap`,
// counted as two `::` separators, plus `HashMap::new`).
check_metrics::<RustParser>(
"fn main() {
let m = std::collections::HashMap::new();
}",
"foo.rs",
|metric| {
// `::` appears 3 times across the two path expressions
// (`std::collections::HashMap` contributes two; the
// `HashMap::new` contributes one). Pre-fix all three
// dropped to Unknown: u_operators would be 6 (no `::`
// distinct) and total_operators() would be 7 (minus 3 `::`
// occurrences). With the fix u_operators=7 and
// operators=10.
//
// unique operators (post-fix): fn, LPAREN, LBRACE,
// let, =, ::, ;. unique operands: main, m, std,
// collections, HashMap, new.
assert_eq!(metric.halstead.unique_operators(), 7);
assert_eq!(metric.halstead.total_operators(), 10);
assert_eq!(metric.halstead.unique_operands(), 6);
assert_eq!(metric.halstead.total_operands(), 6);
},
);
}
#[test]
fn rust_declaration_keywords_are_operators() {
// Regression for issue #394: the Rust impl already accepted 17
// keywords as operators (As, Async, Await, …, Fn) but omitted
// 14 declaration / visibility keywords. The fix adds `Const`,
// `Static`, `Enum`, `Struct`, `Trait`, `Impl`, `Use`, `Mod`,
// `Pub`, `Type`, `Union`, `Where`, `Extern`, `Dyn`.
//
// Snippet exercises `use`, `pub`, `struct`, and `impl` (one of
// each); together they account for 4 new operator occurrences
// and 4 new unique operators.
check_metrics::<RustParser>(
"use std::fmt;
pub struct S;
impl S { fn n() -> u8 { 0 } }",
"foo.rs",
|metric| {
// expected: unique operators (11) = use, ::, ;, pub,
// struct, impl, LBRACE, fn, LPAREN, DASHGT, u8. Without
// the #394 fix, `use`, `pub`, `struct`, and `impl`
// would each drop to Unknown and u_operators would be
// 7. unique operands (5): std, fmt, S, n, 0.
assert_eq!(metric.halstead.unique_operators(), 11);
assert_eq!(metric.halstead.total_operators(), 13);
assert_eq!(metric.halstead.unique_operands(), 5);
assert_eq!(metric.halstead.total_operands(), 6);
},
);
}
#[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` is the `.` operator applied to the two
// identifier leaves; the composite `member_expression`
// text is deliberately not a third operand (#1263), so
// n2/N2 are 10/20 rather than the pre-#1263 11/21.
insta::assert_json_snapshot!(
metric.halstead,
@r#"
{
"unique_operators": 10,
"total_operators": 24,
"unique_operands": 10,
"total_operands": 20,
"length": 44,
"estimated_program_length": 66.43856189774725,
"purity_ratio": 1.5099673158578921,
"vocabulary": 20,
"volume": 190.16483617504394,
"difficulty": 10.0,
"level": 0.1,
"effort": 1901.6483617504396,
"time": 105.64713120835775,
"bugs": 0.05116412536051621
}
"#
);
},
);
}
#[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` is the `.` operator applied to the two
// identifier leaves; the composite `member_expression`
// text is deliberately not a third operand (#1263), so
// n2/N2 are 10/20 rather than the pre-#1263 11/21.
insta::assert_json_snapshot!(
metric.halstead,
@r#"
{
"unique_operators": 10,
"total_operators": 24,
"unique_operands": 10,
"total_operands": 20,
"length": 44,
"estimated_program_length": 66.43856189774725,
"purity_ratio": 1.5099673158578921,
"vocabulary": 20,
"volume": 190.16483617504394,
"difficulty": 10.0,
"level": 0.1,
"effort": 1901.6483617504396,
"time": 105.64713120835775,
"bugs": 0.05116412536051621
}
"#
);
},
);
}
#[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` is the `.` operator applied to the two
// identifier leaves; the composite `member_expression`
// text is deliberately not a third operand (#1263), so
// n2/N2 are 10/20 rather than the pre-#1263 11/21.
insta::assert_json_snapshot!(
metric.halstead,
@r#"
{
"unique_operators": 10,
"total_operators": 24,
"unique_operands": 10,
"total_operands": 20,
"length": 44,
"estimated_program_length": 66.43856189774725,
"purity_ratio": 1.5099673158578921,
"vocabulary": 20,
"volume": 190.16483617504394,
"difficulty": 10.0,
"level": 0.1,
"effort": 1901.6483617504396,
"time": 105.64713120835775,
"bugs": 0.05116412536051621
}
"#
);
},
);
}
#[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` is the `.` operator applied to the two
// identifier leaves; the composite `member_expression`
// text is deliberately not a third operand (#1263), so
// n2/N2 are 10/20 rather than the pre-#1263 11/21.
insta::assert_json_snapshot!(
metric.halstead,
@r#"
{
"unique_operators": 10,
"total_operators": 24,
"unique_operands": 10,
"total_operands": 20,
"length": 44,
"estimated_program_length": 66.43856189774725,
"purity_ratio": 1.5099673158578921,
"vocabulary": 20,
"volume": 190.16483617504394,
"difficulty": 10.0,
"level": 0.1,
"effort": 1901.6483617504396,
"time": 105.64713120835775,
"bugs": 0.05116412536051621
}
"#
);
},
);
}
#[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.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 2);
});
}
/// Regression for #695. The `get` / `set` property-accessor keywords
/// are operators, matching the C# getter's `Get | Set | Init | Add |
/// Remove` accessor arm. Before #695 the JS family classified them as
/// operands, so the same accessor keyword landed in opposite Halstead
/// groups across languages. This pins them in the operator store and
/// out of the operand store.
#[test]
fn js_get_set_accessors_are_operators() {
let source = "class C { get x() { return 1; } set x(v) { this._x = v; } }";
let path = PathBuf::from("foo.js");
let parser = JavascriptParser::new(source.as_bytes().to_vec(), &path, None);
let ops = crate::ops::ops_inner(&parser, None).expect("ops walk succeeds");
assert!(
ops.operators.iter().any(|o| o.as_str() == "get")
&& ops.operators.iter().any(|o| o.as_str() == "set"),
"`get`/`set` accessors must be operators; operators were {:?}",
ops.operators
);
assert!(
!ops.operands.iter().any(|o| o.as_str() == "get")
&& !ops.operands.iter().any(|o| o.as_str() == "set"),
"`get`/`set` accessors must not be operands; operands were {:?}",
ops.operands
);
}
#[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.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 3);
},
);
}
#[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.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 2);
});
}
#[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.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 3);
},
);
}
#[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.
//
// The `: string` annotation contributes no operand — its
// keyword counts once, as the text-keyed operator (#1261) — so
// the operands are `f` and `` `hello` `` (2 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.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 2);
},
);
}
#[test]
fn typescript_template_string_interpolation_no_double_count() {
// Regression: issue #192. Mirrors
// `javascript_template_string_interpolation_no_double_count`
// for TypeScript.
//
// The `: string` annotations contribute no operands (#1261).
// Unique operands: `f`, `name` (2). Total operands: `f`, `name`
// (param), `name` (in the interpolation) (3). 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.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 3);
},
);
}
#[test]
fn tsx_template_string_plain_is_operand() {
// Regression: issue #192. Mirrors
// `javascript_template_string_plain_is_operand` for the
// TSX (TypeScript + JSX) variant.
//
// TSX's type-keyword `string` (`String3`) contributes no
// operand, mirroring TS::String2 (#1261): operands are `f` and
// `` `hello` `` (2 each).
check_metrics::<TsxParser>(
"function f(): string { return `hello`; }",
"foo.tsx",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 2);
},
);
}
#[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.
//
// The `: string` annotations contribute no `String3` operands
// (#1261); 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.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 3);
},
);
}
/// The JS-family regex fixture, asserted against all four grammars.
///
/// `impl_js_family_get_op_type!` is instantiated four times against
/// four distinct `kind_id` enums (`SLASH` 87/81/90/87, `Regex`
/// 224/250/264/225), so each expansion is a separate compiled arm
/// and a drift in one grammar is invisible if only one is checked
/// (grammar-dispatch section 11).
fn assert_js_family_counts(source: &str, expected: [u64; 4]) {
assert_halstead_counts::<JavascriptParser>(source, "foo.js", expected, "javascript");
assert_halstead_counts::<MozjsParser>(source, "foo.jsm", expected, "mozjs");
assert_halstead_counts::<TypescriptParser>(source, "foo.ts", expected, "typescript");
assert_halstead_counts::<TsxParser>(source, "foo.tsx", expected, "tsx");
}
#[test]
fn js_family_regex_delimiters_are_not_operators() {
// Regression: issue #1314, the JS-family sibling of Elixir
// #1256 and Ruby/Perl #1312. A `regex` literal spells both of
// its delimiters `SLASH` — the kind id real division uses — so
// `const a = /abc/g;` reported a `/` operator with no division
// in the source, and n1/N1 counted the literal's punctuation as
// arithmetic.
//
// The same fixture pins the second, independent half: `Regex`
// was in neither arm, so the literal contributed no operand
// either and reached the vocabulary from *neither* side.
//
// expected: operators `const`, `=`, `;`, `let` → n1 = 4;
// `const` `=` `;` on line 1, `let` `=` `;` on line 2, `=` `;`
// on line 3 → N1 = 8. Operands `a`, `/abc/g`, `b` → n2 = 3,
// with `a` used three times and `b` twice → N2 = 6.
//
// Before the fix: n1 = 5 and N1 = 10 (the two fabricated `/`),
// n2 = 2 and N2 = 5 (no operand for the literal).
//
// The four values are deliberately distinct so no transposition
// of the unique-vs-total axes inside `assert_halstead_counts`
// can pass (#1312).
assert_js_family_counts("const a = /abc/g;\nlet b = a;\nb = a;\n", [4, 8, 3, 6]);
}
#[test]
fn js_family_division_survives_the_regex_guard() {
// Control for #1314: the guard is scoped to a `Regex` parent,
// so real division must still count. This fixture holds both
// sides at once — two divisions and one regex literal — so a
// guard widened to every `SLASH` fails here rather than
// silently passing the test above.
//
// expected: operators `const`, `=`, `;`, `/` → n1 = 4; two
// `const`, two `=`, two `;` and two `/` → N1 = 8. Operands
// `q`, `a`, `b`, `c`, `r`, `/x/` → n2 = N2 = 6.
assert_js_family_counts("const q = a / b / c;\nconst r = /x/;\n", [4, 8, 6, 6]);
}
#[test]
fn js_regex_delimiter_guard_is_parent_scoped_is_unobservable() {
// Companion to the two above, and a statement of what they do
// *not* cover. Ruby's guard has
// `ruby_regex_guard_is_parent_scoped_not_ancestor_scoped`
// because a division inside `#{…}` sits under a `Regex`
// ancestor without being its child. No JS fixture can do that:
// a regex literal admits no nested expression at all, its
// `regex_pattern` and `regex_flags` children being leaves. So
// the ancestor-scoped mutant of this guard — the one #1256's
// post-mortem says survives every ordinary fixture — is
// unobservable here. Measured, not assumed.
//
// Rather than write a fixture that would pass under both
// spellings and read as coverage, pin the grammar property the
// claim rests on: within a fixture that puts a division, a
// template substitution and a regex in one file, every `SLASH`
// reachable *below* a `Regex` is its immediate child. Should a
// bump start nesting expressions inside a regex, this turns red
// and the distinction becomes both observable and worth a real
// test.
//
// Checked against all four grammars, not just JavaScript: the
// guard is instantiated four times against four distinct enums,
// and the property this test exists to watch could hold in one
// and lapse in another.
let source = b"const a = /abc/g;\nconst q = x / y;\nconst t = `p ${x / y} ${/zz/} q`;\n";
assert_regex_slashes_are_immediate_children::<crate::langs::JavascriptCode>(
source,
Javascript::SLASH as u16,
Javascript::Regex as u16,
"javascript",
);
assert_regex_slashes_are_immediate_children::<crate::langs::MozjsCode>(
source,
Mozjs::SLASH as u16,
Mozjs::Regex as u16,
"mozjs",
);
assert_regex_slashes_are_immediate_children::<crate::langs::TypescriptCode>(
source,
Typescript::SLASH as u16,
Typescript::Regex as u16,
"typescript",
);
assert_regex_slashes_are_immediate_children::<crate::langs::TsxCode>(
source,
Tsx::SLASH as u16,
Tsx::Regex as u16,
"tsx",
);
}
/// Asserts every `slash` token below a `regex` node in `source` is
/// that node's *immediate* child, for one grammar.
///
/// Backs `js_regex_delimiter_guard_is_parent_scoped_is_unobservable`
/// — see there for why the property is worth pinning.
fn assert_regex_slashes_are_immediate_children<L: crate::traits::LanguageInfo>(
source: &[u8],
slash: u16,
regex: u16,
label: &str,
) {
let mut slashes_below_a_regex = 0;
let visited = for_each_node_with_chain::<L>(source, |node: &Node<'_>, chain| {
if node.kind_id() != slash {
return;
}
let Some(depth) = chain.iter().position(|a| a.kind_id() == regex) else {
return;
};
slashes_below_a_regex += 1;
assert_eq!(
depth,
chain.len() - 1,
"{label}: a slash at row {} has a regex ancestor that is not its parent, so \
the parent-vs-ancestor mutant is now observable and needs a real test",
node.start_row()
);
});
assert!(visited > 20, "{label}: fixture is too small to prove much");
// Without this the assertion above is vacuous whenever the
// fixture stops containing a regex at all — the failure mode a
// filter that matches nothing always has.
assert_eq!(
slashes_below_a_regex, 4,
"{label}: expected the two regex literals' four delimiters; the fixture no \
longer exercises what this test claims"
);
}
// 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.unique_operators(), 6);
assert_eq!(m.halstead.total_operators(), 7);
});
}
#[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.unique_operators(), 6);
assert_eq!(m.halstead.total_operators(), 7);
});
}
#[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.unique_operators(), 6);
assert_eq!(m.halstead.total_operators(), 7);
});
}
#[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.unique_operators(), 6);
assert_eq!(m.halstead.total_operators(), 7);
});
}
// 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` (parameter), `a`, `b`, `c` — the identifier
// and property leaves only (5 total, 4 unique). Until #1263 the
// two wrapping member expressions (`a?.b`, `a?.b?.c`) were
// classified as `MemberExpression*` operands on top of the leaves
// they contain, making this 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`, the
// JS/MozJS/TSX string-literal `String2`); drift in
// those is out of scope for this regression guard and would need a
// separate fixture. The `PredefinedType` operator path (`: void`
// double-count) is now covered by `ts_void_return_type_single_operator_453`
// below.
#[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.unique_operators(), 6);
assert_eq!(m.halstead.total_operators(), 7);
assert_eq!(m.halstead.unique_operands(), 4);
assert_eq!(m.halstead.total_operands(), 5);
};
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 #1263: a member access contributes its leaves and the `.`
// operator, never the `member_expression` composite as well. The
// classification does not stop the walk, so `a` and `b` were always
// counted; listing the wrapper billed a third operand keyed on the
// whole `a.b` text, which no other language here does.
//
// expected, for `var r = a.b;`:
//
// * Operators: `var`, `=`, `.`, `;` — 4 total, 4 unique.
// * Operands: `r`, `a`, `b` — 3 total, 3 unique. Before the fix
// the `member_expression` wrapper added `a.b`, making both 4.
//
// All four JS-family languages are asserted because
// `impl_js_family_get_op_type!` emits one shared operand arm: the
// lockstep is the point of the macro, and a per-language extras
// list is exactly where a future edit could break it.
#[test]
fn js_family_member_access_counts_leaves_not_the_composite_1263() {
const SRC: &str = "var r = a.b;";
let check = |m: crate::CodeMetrics| {
assert_eq!(m.halstead.unique_operators(), 4);
assert_eq!(m.halstead.total_operators(), 4);
assert_eq!(m.halstead.unique_operands(), 3);
assert_eq!(m.halstead.total_operands(), 3);
};
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 #1263, the grammar-dispatch section 6 half: dropping
// `MemberExpression*` from the operand arm would have regressed
// private-field access to *zero* operands for the field, because
// `PrivatePropertyIdentifier` — the `#x` leaf — was in no operand
// list and the composite `this.#x` had been its only count. Adding
// the leaf also fixes the declaration site `#x = 1`, which no
// wrapper covered and which therefore counted nothing at all.
//
// expected, for `class C { #x = 1; m() { return this.#x; } }`:
//
// * Operators: `{`×2 (class body, method body), `=`, `;`×2, `(`,
// `return`, `.` — 8 total, 6 unique. (`class` is not in the
// JS-family operator arm, so it contributes nothing; that is
// pre-existing and unrelated.)
// * Operands: `C`, `#x`, `1`, `m`, `this`, `#x` — 6 total, 5
// unique under JS/MozJS. Under TS/TSX the class *name* `C`
// parses as `type_identifier`, which those getters do not
// classify, so both counts drop by one to 5/4 — a pre-existing
// divergence this fixture records rather than fixes.
#[test]
fn js_family_private_field_leaf_is_the_operand_1263() {
const SRC: &str = "class C { #x = 1; m() { return this.#x; } }";
let check_js = |m: crate::CodeMetrics| {
assert_eq!(m.halstead.unique_operators(), 6);
assert_eq!(m.halstead.total_operators(), 8);
assert_eq!(m.halstead.unique_operands(), 5);
assert_eq!(m.halstead.total_operands(), 6);
};
let check_ts = |m: crate::CodeMetrics| {
assert_eq!(m.halstead.unique_operators(), 6);
assert_eq!(m.halstead.total_operators(), 8);
assert_eq!(m.halstead.unique_operands(), 4);
assert_eq!(m.halstead.total_operands(), 5);
};
check_metrics::<JavascriptParser>(SRC, "foo.js", check_js);
check_metrics::<MozjsParser>(SRC, "foo.js", check_js);
check_metrics::<TypescriptParser>(SRC, "foo.ts", check_ts);
check_metrics::<TsxParser>(SRC, "foo.tsx", check_ts);
}
// Issue #1263, the other section 6 half: `meta_property` is the one
// composite the leaves-not-composites drop has to keep. `import.meta`
// / `new.target` have no classified leaf — `meta` and `target` are
// anonymous tokens in no arm — so with `MemberExpression*` gone the
// meta-object contributed no operand at all while `this.env.x` still
// yielded three.
//
// expected operands, for `var t = import.meta.url; function f() {
// return new.target; }`: `t`, `import.meta`, `url`, `f`,
// `new.target` — 5 total, 5 unique. Operators are deliberately not
// asserted: the `import` / `new` keyword tokens inside the
// meta-property keep their pre-existing operator classification,
// which this fixture neither pins nor contests.
#[test]
fn js_family_meta_property_is_one_operand_1263() {
const SRC: &str = "var t = import.meta.url; function f() { return new.target; }";
let check = |m: crate::CodeMetrics| {
assert_eq!(m.halstead.unique_operands(), 5);
assert_eq!(m.halstead.total_operands(), 5);
};
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 #1263: TS/TSX `nested_identifier` (`namespace N.M`) is the
// same container/leaf double-count as `member_expression`.
//
// expected, for `namespace N.M { }`:
//
// * Operators: `.`, `{` — 2 total, 2 unique. (`namespace` is not in
// the JS-family operator arm.)
// * Operands: `N`, `M` — 2 total, 2 unique. Before the fix the
// `nested_identifier` added `N.M`, making both 3.
#[test]
fn ts_nested_identifier_counts_leaves_not_the_composite_1263() {
const SRC: &str = "namespace N.M { }";
let check = |m: crate::CodeMetrics| {
assert_eq!(m.halstead.unique_operators(), 2);
assert_eq!(m.halstead.total_operators(), 2);
assert_eq!(m.halstead.unique_operands(), 2);
assert_eq!(m.halstead.total_operands(), 2);
};
check_metrics::<TypescriptParser>(SRC, "foo.ts", check);
check_metrics::<TsxParser>(SRC, "foo.tsx", check);
}
// Issue #1261 (inverting the #313 pin): the `"string"` type-keyword
// aliases the TS / TSX grammars expose must contribute NO operand.
// #313 put them in `operand_extras` for parity with the then-wider
// `Checker::is_string`, but the `predefined_type` wrapper already
// counts as the text-keyed `"string"` operator, so one `: string`
// token tallied as operator AND operand while `: number` counted
// once. #1261 drops the aliases from both `operand_extras` and
// `is_string`, so the keyword counts once, as the operator.
//
// 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).
//
// Verified by test-via-revert: restoring `String2` to TS's
// `operand_extras` (or `String3` to TSX's) trips this test on
// `u_operands` / `operands` for the affected language.
#[test]
fn ts_family_type_keyword_counts_once_1261() {
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 = 2, N2 = 2):
// `x` and the `"y"` literal. Under #313 the type-keyword
// child of `predefined_type` added a third, phantom
// `"string"` operand (n2 = 3 / N2 = 3).
let check = |m: crate::CodeMetrics| {
assert_eq!(m.halstead.unique_operators(), 5);
assert_eq!(m.halstead.total_operators(), 5);
assert_eq!(m.halstead.unique_operands(), 2);
assert_eq!(m.halstead.total_operands(), 2);
};
check_metrics::<TypescriptParser>(SRC, "foo.ts", check);
check_metrics::<TsxParser>(SRC, "foo.tsx", check);
}
// Issue #1261 regression, the issue's reproducer plus a literal
// whose contents spell the keyword: `: string` and `: number` must
// contribute symmetrically — one text-keyed operator each, zero
// operands — while a string *literal* `"string"` stays an operand
// (distinct from the keyword: TS kind `String`, TSX kind `String2`,
// both quoted in the operand key).
#[test]
fn ts_family_string_annotation_symmetric_with_number_1261() {
const SRC: &str = "let x: string = \"a\";\nlet y: number = 1;\nlet s = \"string\";";
// Operators (n1 = 6, N1 = 13):
// `let` ×3, `:` ×2, `=` ×3, `;` ×3, `string` ×1, `number` ×1.
// Pre-fix N1 was identical — the wrapper operator was always
// counted; the defect was the extra operand below.
// Operands (n2 = 6, N2 = 6):
// `x`, `"a"`, `y`, `1`, `s`, `"string"` — one each. Pre-fix
// the `: string` keyword added a bare `string` operand
// (n2 = 7 / N2 = 7) that `: number` had no analogue of.
let check = |m: crate::CodeMetrics| {
assert_eq!(m.halstead.unique_operators(), 6);
assert_eq!(m.halstead.total_operators(), 13);
assert_eq!(m.halstead.unique_operands(), 6);
assert_eq!(m.halstead.total_operands(), 6);
};
check_metrics::<TypescriptParser>(SRC, "foo.ts", check);
check_metrics::<TsxParser>(SRC, "foo.tsx", check);
}
/// Drift marker for #1261 (lesson 34 / grammar-dispatch §2): the
/// anonymous `string` type-keyword token appears **only** as a
/// `predefined_type` child.
///
/// That is the whole argument for classifying the keyword without a
/// parent guard — the wrapper is guaranteed to be there to carry the
/// operator. The two tests above measure the consequence and would
/// still pass if the grammar started emitting the keyword somewhere
/// else, as long as their own two fixtures kept their counts; this one
/// measures the premise, over every position #1261's dump probes
/// covered: annotation, parameter and return type, union member,
/// generic argument, and template-literal type. A string *literal*
/// spelling `"string"` is a different kind and must not be confused
/// for the keyword, so one is in the fixture too.
#[test]
fn ts_family_type_keyword_only_appears_under_predefined_type_1261() {
// Exercises each position the keyword can take. Valid in both
// grammars: no angle-bracket cast, which TSX would read as JSX.
const SRC: &str = "const a: string = \"string\";\n\
function f(x: string): string {\n\
return x;\n\
}\n\
type U = string | number;\n\
type A = Array<string>;\n\
type M = Map<string, number>;\n\
type T = `id-${string}`;\n";
// Seven type positions: `a`, `x`, `f`'s return, the union member,
// `Array`'s argument, `Map`'s first argument, and the template
// placeholder. The `"string"` initialiser is a literal, not the
// keyword, and must not be among them.
const EXPECTED_OCCURRENCES: usize = 7;
fn keyword_occurrences<P: ParserTrait>(
path: &str,
keyword: u16,
predefined_type: u16,
) -> usize {
let parser = P::new(SRC.as_bytes().to_vec(), &PathBuf::from(path), None);
parser
.root()
.preorder()
.filter(|node| node.kind_id() == keyword)
.inspect(|node| {
assert_eq!(
node.parent().map(|parent| parent.kind_id()),
Some(predefined_type),
"the `string` type keyword surfaced outside \
`predefined_type` in {path}; the operator is carried \
by the wrapper, so `get_op_type` needs a parent guard \
before that arm can be trusted (#1261)",
);
})
.count()
}
// Kind ids re-read from the generated enums, not carried over: TS
// `String2` = 135, TSX `String3` = 141 (TSX's `String2` = 261 is the
// string-literal production and stays an operand).
assert_eq!(
keyword_occurrences::<TypescriptParser>(
"foo.ts",
Typescript::String2 as u16,
Typescript::PredefinedType as u16,
),
EXPECTED_OCCURRENCES,
"TypeScript no longer emits the `string` type keyword in every \
position #1261 probed",
);
assert_eq!(
keyword_occurrences::<TsxParser>(
"foo.tsx",
Tsx::String3 as u16,
Tsx::PredefinedType as u16,
),
EXPECTED_OCCURRENCES,
"TSX no longer emits the `string` type keyword in every position \
#1261 probed",
);
}
// Issue #453: a `void` return type must contribute exactly one
// Halstead operator. The TS / TSX grammars parse `: void` as a
// `predefined_type` wrapper around an inner `void` token. `is_primitive`
// routes the wrapper into the text-keyed `primitive_operators` map as
// `"void"`, while the inner `Void` token is independently a standalone
// expression operator (`void 0`). Pre-fix both classified as operators
// and one source `void` counted as TWO distinct Halstead operators.
// The fix suppresses the wrapper when its child is a `Void` token, so
// only the inner token carries the operator — matching expression
// `void 0` and keeping the kind_id-keyed count consistent.
//
// For `function f(): void { return; }`:
//
// * Operators (n1 = 7, N1 = 7): `function`, `()`, `{}`, `:`, `return`,
// `;`, and a single `void`. (The untyped form is n1 = 5; the `: void`
// annotation adds the `:` operator and one `void`, NOT two — the
// issue's "n1 = 6" target overlooked the annotation colon.)
//
// Verified by test-via-revert: removing the `predefined_void` guard
// restores the pre-fix `u_operators` 7 -> 8 with a duplicate `"void"`
// (one kind_id-keyed, one in `primitive_operators`). Both `metrics()`
// and the `ops`-list dedup invariant (`ts_void_return_and_expression_*`
// in `ops.rs`) are pinned per lesson 4.
#[test]
fn ts_void_return_type_single_operator_453() {
const SRC: &str = "function f(): void { return; }";
let check = |m: crate::CodeMetrics| {
assert_eq!(m.halstead.unique_operators(), 7);
assert_eq!(m.halstead.total_operators(), 7);
};
check_metrics::<TypescriptParser>(SRC, "foo.ts", check);
check_metrics::<TsxParser>(SRC, "foo.tsx", check);
}
// Issue #453 over-suppression guard: expression `void 0` (a
// `unary_expression`, NOT a `predefined_type` wrapper) must still
// count `void` as exactly one operator. The fix keys only on a
// `predefined_type` whose child is a `Void` token, so the bare
// expression operator is untouched.
//
// For `const x = void 0;`:
//
// * Operators (n1 = 4, N1 = 4): `const`, `=`, `void`, `;`.
// * Operands (n2 = 2, N2 = 2): `x`, `0`.
#[test]
fn ts_void_expression_still_single_operator_453() {
const SRC: &str = "const x = void 0;";
let check = |m: crate::CodeMetrics| {
assert_eq!(m.halstead.unique_operators(), 4);
assert_eq!(m.halstead.total_operators(), 4);
assert_eq!(m.halstead.unique_operands(), 2);
assert_eq!(m.halstead.total_operands(), 2);
};
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#"
{
"unique_operators": 0,
"total_operators": 0,
"unique_operands": 0,
"total_operands": 0,
"length": 0,
"estimated_program_length": 0.0,
"purity_ratio": 0.0,
"vocabulary": 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#"
{
"unique_operators": 2,
"total_operators": 2,
"unique_operands": 1,
"total_operands": 1,
"length": 3,
"estimated_program_length": 2.0,
"purity_ratio": 0.6666666666666666,
"vocabulary": 3,
"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#"
{
"unique_operators": 11,
"total_operators": 26,
"unique_operands": 12,
"total_operands": 22,
"length": 48,
"estimated_program_length": 81.07329781366414,
"purity_ratio": 1.6890270377846697,
"vocabulary": 23,
"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#"
{
"unique_operators": 11,
"total_operators": 28,
"unique_operands": 19,
"total_operands": 19,
"length": 47,
"estimated_program_length": 118.76437056043838,
"purity_ratio": 2.526901501285923,
"vocabulary": 30,
"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.unique_operators(), 8);
assert_eq!(metric.halstead.unique_operands(), 13);
insta::assert_json_snapshot!(
metric.halstead,
@r#"
{
"unique_operators": 8,
"total_operators": 22,
"unique_operands": 13,
"total_operands": 23,
"length": 45,
"estimated_program_length": 72.10571633583419,
"purity_ratio": 1.6023492519074265,
"vocabulary": 21,
"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.unique_operators(), 2);
assert_eq!(metric.halstead.unique_operands(), 27);
insta::assert_json_snapshot!(
metric.halstead,
@r#"
{
"unique_operators": 2,
"total_operators": 10,
"unique_operands": 27,
"total_operands": 28,
"length": 38,
"estimated_program_length": 130.38196255841365,
"purity_ratio": 3.4311042778529908,
"vocabulary": 29,
"volume": 184.60327781484773,
"difficulty": 1.037037037037037,
"level": 0.9642857142857143,
"effort": 191.44043625243467,
"time": 10.635579791801925,
"bugs": 0.01107221547116606
}
"#
);
},
);
}
// Issue #1263 swept Groovy alongside the JS family and C#: its
// operand arm listed `QualifiedName` (a `package` / `import` path)
// and `QualifiedType` on top of the identifier leaves the walker
// already reached.
//
// Only the `QualifiedName` half was observable. The runtime emits
// `qualified_type` as the *alias* `QualifiedType2` (kind_id 228),
// which the arm never named — a lesson-2 miss that, by accident,
// made that half already leaves-only and is why #1263's issue body
// recorded Groovy as compliant. Both kinds are gone rather than
// completed.
//
// expected, for `package com.example`: operators `.` (1/1);
// operands `com`, `example` (2/2). Pre-fix the `qualified_name`
// added `com.example`, making the operand counts 3/3.
#[test]
fn groovy_qualified_name_counts_leaves_not_the_composite_1263() {
check_metrics::<GroovyParser>("package com.example", "foo.groovy", |metric| {
assert_eq!(metric.halstead.unique_operators(), 1);
assert_eq!(metric.halstead.total_operators(), 1);
assert_eq!(metric.halstead.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 2);
});
}
// The type half of the same arm (#1352). #1263 dropped
// `QualifiedType` alongside `QualifiedName`, but only the latter
// was pinned: adding `QualifiedType2` back to the operand arm
// failed none of the 3,523 tests then in the lib targets, so the
// leaves-only reading of a qualified *type* was correct by accident
// rather than by contract. The tempting "fix" for the alias miss
// #1263 recorded is to complete the list with 228, which is exactly
// the double count #1263 removed — this test is what stops that.
//
// The kind assertions are the grammar-dispatch section 1 / 2 drift
// marker: if a grammar bump renumbers the alias, the operand
// assertions below would keep passing while measuring a construct
// this arm no longer describes.
//
// expected, for `java.util.List x = null`: operators `.` × 2 and
// `=` → n1 = 2, N1 = 3; operands `java`, `util`, `List`, `x`,
// `null` → n2 = 5, N2 = 5. Listing the wrapper would add the whole
// span `java.util.List`, making the operand counts 6/6.
#[test]
fn groovy_qualified_type_counts_leaves_not_the_composite_1352() {
const SOURCE: &str = "java.util.List x = null";
let parser = GroovyParser::new(
SOURCE.as_bytes().to_vec(),
&PathBuf::from("foo.groovy"),
None,
);
assert!(
ast_has_kind_id(&parser, Groovy::QualifiedType2 as u16),
"the dekobon grammar no longer emits `qualified_type` as the \
alias `QualifiedType2`; re-derive the Groovy operand arm \
before trusting the counts below",
);
assert!(
!ast_has_kind_id(&parser, Groovy::QualifiedType as u16),
"the unsuffixed `QualifiedType` is now reachable; it is a \
second wrapper this arm must keep excluded",
);
check_metrics::<GroovyParser>(SOURCE, "foo.groovy", |metric| {
assert_eq!(metric.halstead.unique_operators(), 2);
assert_eq!(metric.halstead.total_operators(), 3);
assert_eq!(metric.halstead.unique_operands(), 5);
assert_eq!(metric.halstead.total_operands(), 5);
});
}
#[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.unique_operators(), 5);
assert_eq!(metric.halstead.unique_operands(), 3);
});
}
/// 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| {
// Exact pin: with the dekobon Groovy grammar this
// fixture exercises 16 Groovy-specific tokens (`?:`,
// `?.`, `??.`, `*.`, `.&`, `.@`, `===`, `!==`, `<=>`,
// `=~`, `==~`, `..<`, `<..`, `<..<`, `as`, `?[`) plus
// 6 ambient Java-shaped operators the fixture also
// uses (`def`, `=`, `,`, `{}`, `()`, `return`), for a
// total of 22 distinct operator kinds. A regression
// that drops any one of the 16 #247 operators would
// push the count below 22 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 23) still flags the loss of a #247
// operator at the per-token level.
//
// Was 23 until #1314. The extra entry was a `/` — the
// fixture's two slashy literals (`/pat/`, `/^pat\$/`)
// each spelled their closing delimiter with the
// division kind, and the arm now guards them. The
// enumeration above was wrong in two ways at that
// count: it listed an ambient `[`, which this fixture
// never emits (`list?[0]` is the single `?[` token),
// and omitted the fabricated `/` that made up the
// difference. Both are corrected here.
assert_eq!(
metric.halstead.unique_operators(),
22,
"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 groovy_gstring_no_double_count() {
// Issue #454: before the fix Groovy had no interpolation guard
// at all — `StringLiteral` was classified as a plain operand, so
// a GString counted the wrapping literal AND descended into its
// interpolated expression, double-counting the inner identifier
// in N2. The fix routes `StringLiteral` through
// `string_operand_type` with both GString interpolation child
// kinds (`gstring_brace_interpolation` / `gstring_dollar_-
// interpolation`), so the wrapper is Unknown and only the inner
// expression contributes.
//
// `def greet(name) {\n return "Hi ${name}"\n}\n`
// operands by token text: `greet` × 1, `name` × 2 (param +
// inside `${name}`). The wrapping `"Hi ${name}"` is suppressed
// → u_operands = 2 (`greet`, `name`), N2 = 3. Without the fix
// the wrapping literal would also count → u_operands = 3,
// N2 = 4.
let src = "def greet(name) {\n return \"Hi ${name}\"\n}\n";
check_metrics::<GroovyParser>(src, "foo.groovy", |metric| {
assert_eq!(metric.halstead.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 3);
});
assert_ops_operands::<GroovyParser>(src, "foo.groovy", 2, vec!["greet", "name"]);
}
#[test]
fn groovy_gstring_dollar_form_no_double_count() {
// Issue #454: the short `$name` GString form emits a distinct
// `gstring_dollar_interpolation` child whose inner `identifier`
// text is `$name` (the grammar's identifier node spans the
// leading `$`). The wrapper is suppressed; the inner `$name`
// operand is distinct from the bare `name` param.
//
// `def greet(name) {\n return "Hi $name"\n}\n`
// operands: `greet`, `name` (param), `$name` (interp) →
// u_operands = 3, N2 = 3. Without the fix the wrapping
// `"Hi $name"` would also count → u_operands = 4, N2 = 4.
let src = "def greet(name) {\n return \"Hi $name\"\n}\n";
check_metrics::<GroovyParser>(src, "foo.groovy", |metric| {
assert_eq!(metric.halstead.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 3);
});
assert_ops_operands::<GroovyParser>(src, "foo.groovy", 3, vec!["greet", "name", "$name"]);
}
#[test]
fn groovy_plain_string_still_operand() {
// Counterpart to `groovy_gstring_no_double_count`: a plain
// non-interpolated literal has neither GString interpolation
// child and must still contribute exactly one operand.
//
// `def f() {\n return "plain"\n}\n`
// operands: `f`, `"plain"` → u_operands = 2, N2 = 2.
let src = "def f() {\n return \"plain\"\n}\n";
check_metrics::<GroovyParser>(src, "foo.groovy", |metric| {
assert_eq!(metric.halstead.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 2);
});
assert_ops_operands::<GroovyParser>(src, "foo.groovy", 2, vec!["f", "\"plain\""]);
}
#[test]
fn groovy_slashy_string_delimiter_is_not_an_operator() {
// Regression: issue #1314, the Groovy sibling of Elixir #1256
// and Ruby/Perl #1312. A slashy string is a `StringLiteral`
// whose closing delimiter is a `SLASH` — the kind id real
// division uses — so `def b = /xyz/` reported a `/` operator
// with no division in the source. Only the closer is a child
// (the grammar folds the opening `/` into the literal's span),
// so this fabricated one `/` per literal rather than Ruby's two.
//
// expected: operators `def` × 3, `=` × 3 → n1 = 2, N1 = 6.
// Operands `b`, `/xyz/` × 2, `c`, `s` → n2 = 4, N2 = 6. Before
// the guard the two closers added `/` → n1 = 3, N1 = 8.
check_metrics::<GroovyParser>(
"def b = /xyz/\ndef c = /xyz/\ndef s = b\n",
"foo.groovy",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 2);
assert_eq!(metric.halstead.total_operators(), 6);
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 6);
},
);
}
#[test]
fn groovy_division_survives_the_slashy_guard() {
// Control for #1314: the guard is scoped to a `StringLiteral`
// parent, so real division must still count. Both sides are in
// one fixture — two divisions and one slashy literal — so a
// guard widened to every `SLASH` fails here rather than
// silently passing the test above.
//
// expected: operators `def` × 2, `=` × 2, `/` × 2 → n1 = 3,
// N1 = 6. Operands `q`, `a`, `b`, `c`, `r`, `/x/` → n2 = N2 = 6.
check_metrics::<GroovyParser>("def q = a / b / c\ndef r = /x/\n", "foo.groovy", |metric| {
assert_eq!(metric.halstead.unique_operators(), 3);
assert_eq!(metric.halstead.total_operators(), 6);
assert_eq!(metric.halstead.unique_operands(), 6);
assert_eq!(metric.halstead.total_operands(), 6);
});
}
#[test]
fn groovy_slashy_guard_is_parent_scoped_not_ancestor_scoped() {
// The input that separates the parent-scoped guard from the
// ancestor-scanning mutant of it — the mutant #1256's
// post-mortem says survives every ordinary fixture. Groovy is
// one of only two languages in #1314 where such an input
// exists at all: a slashy string may carry a GString
// interpolation, so `/x${a / b}y/` puts a real division under a
// `StringLiteral` *ancestor* while its parent is the
// `binary_expression`. An ancestor scan swallows it; the parent
// check leaves it alone. (The JS, C++ and Tcl/iRules guards
// have no such input — see
// `js_regex_delimiter_guard_is_parent_scoped_is_unobservable`.)
//
// expected: operators `def` × 2, `=` × 2, `/` (the
// interpolated division) → n1 = 3, N1 = 5. The wrapping literal
// is not an operand — it carries an interpolation, so
// `string_operand_type` yields `Unknown` and the inner
// expression's operands carry the count (#454) — leaving `r`,
// `a`, `b`, `s` → n2 = 4, with `a` twice → N2 = 5. Under the
// ancestor-scoped mutant the division vanishes: n1 = 2, N1 = 4.
check_metrics::<GroovyParser>(
"def r = /x${a / b}y/\ndef s = a\n",
"foo.groovy",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 3);
assert_eq!(metric.halstead.total_operators(), 5);
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 5);
},
);
}
#[test]
fn groovy_every_string_spelling_scores_alike() {
// Companion to the three above (#1314). Groovy has five ways to
// write an inert one-character string, and the choice is
// spelling rather than semantics, so all five must score
// identically. Before the guard the two slashy forms reported
// an extra `/` operator that the other three did not — the
// author's delimiter choice moved n1/N1.
//
// The dollar-slashy and quoted forms are no-change controls:
// `$/…/$` closes with `/$` (kind 144) and `"…"` with `"` (134),
// neither of which the operator arm classifies. `'x'` is a
// childless leaf. The escaped-slash row is the one that would
// regress if the guard were ever narrowed to a literal whose
// *only* child is the closer.
//
// expected per spelling: operators `def` × 3, `=` × 3 → n1 = 2,
// N1 = 6; operands `a`, the literal, `b`, `c` → n2 = 4, with
// `a` used three times → N2 = 6.
for literal in ["/x/", "$/x/$", "'x'", "\"x\"", r"/esc\/aped/"] {
assert_halstead_counts::<GroovyParser>(
&format!("def a = {literal}\ndef b = a\ndef c = a\n"),
"foo.groovy",
[2, 6, 4, 6],
&format!("literal {literal}"),
);
}
}
#[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.unique_operators(), 15);
assert_eq!(metric.halstead.total_operators(), 32);
assert_eq!(metric.halstead.unique_operands(), 13);
assert_eq!(metric.halstead.total_operands(), 23);
// Pin every Halstead field; values are whatever the
// classifier produces and become the regression spec.
insta::assert_json_snapshot!(metric.halstead);
},
);
}
// Issue #1263: C#'s three name *containers* — `qualified_name`
// (`System.Text`), `generic_name` (`List<int>`) and
// `alias_qualified_name` (`global::Foo`) — were operands alongside
// every leaf the walker already reached, so one occurrence of each
// billed twice. `member_access_expression` never was, which is why
// `csharp_operators_and_operands`' `System.Console.WriteLine` is
// unaffected by this change: the bug lived in the *name* grammar,
// not in member access.
//
// Three fixtures rather than one, so a regression names which
// container came back. Each is hand-tallied; the removed composite
// is called out per case.
#[test]
fn csharp_name_containers_count_leaves_not_the_composite_1263() {
// expected: operators `using`, `.`, `;` (3/3); operands
// `System`, `Text` (2/2). Pre-fix the `qualified_name` added
// `System.Text`, making the operand counts 3/3.
check_metrics::<CsharpParser>("using System.Text;", "foo.cs", |metric| {
assert_eq!(metric.halstead.unique_operators(), 3);
assert_eq!(metric.halstead.total_operators(), 3);
assert_eq!(metric.halstead.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 2);
});
// expected: operators `class`, `{`×2, `void`, `(`, `;`, `<`,
// `>`, `int` — 9 total, 8 unique (`int` is the text-keyed
// primitive operator, per #286). Operands `C`, `M`, `List`, `l`
// — 4/4. Pre-fix the `generic_name` added `List<int>`, making
// them 5/5.
check_metrics::<CsharpParser>(
"class C { void M() { List<int> l; } }",
"foo.cs",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 8);
assert_eq!(metric.halstead.total_operators(), 9);
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 4);
},
);
// expected: operators `class`, `{`×2, `void`, `(`, `;`, `=`,
// `::`, `.` — 9 total, 8 unique. `var` has no operator arm.
// Operands `C`, `M`, `x`, `global`, `Foo`, `Bar` — 6/6. Pre-fix
// the `alias_qualified_name` added `global::Foo`, making them
// 7/7. The `::` staying an operator is what makes the leaf-only
// tally lossless here, so it is asserted by the operator count
// rather than assumed.
check_metrics::<CsharpParser>(
"class C { void M() { var x = global::Foo.Bar; } }",
"foo.cs",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 8);
assert_eq!(metric.halstead.total_operators(), 9);
assert_eq!(metric.halstead.unique_operands(), 6);
assert_eq!(metric.halstead.total_operands(), 6);
},
);
}
#[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.
//
// N2 dropped 23 → 21 with issue #1253: `true` and `false` each
// reached the walker twice — once as `boolean_literal`, once as
// the keyword leaf under it — so each added one spurious
// occurrence. n2 is unchanged at 21 because operands are keyed
// by source text, so the duplicate collapsed into the existing
// vocabulary entry; that is exactly why the inflation was
// invisible in n2. Every operand here is distinct, so
// N2 == n2 == 21 after the fix.
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.unique_operators(), 14);
assert_eq!(metric.halstead.total_operators(), 33);
assert_eq!(metric.halstead.unique_operands(), 21);
assert_eq!(metric.halstead.total_operands(), 21);
insta::assert_json_snapshot!(metric.halstead);
},
);
}
#[test]
fn csharp_boolean_literal_counts_once() {
// Regression: issue #1253. `boolean_literal: choice('true',
// 'false')` wraps the keyword leaf, and both kinds sat in the
// operand arm, so every `true` / `false` occurrence added +1 to
// N2. Operands are keyed by source text, so the duplicate
// collapsed into the same vocabulary entry and n2 stayed
// correct — which is why nothing caught it.
//
// Source repeats `true` so N2 exceeds n2 and the assertions can
// tell "counted once per occurrence" from "deduplicated into
// the vocabulary".
//
// Operands by text key: `A`, `M`, `a`, `b`, `c`, `d`, `true` × 2,
// `false`, `null` ⇒ n2 = 9, N2 = 10. Before the fix the keyword
// leaves added one occurrence per boolean ⇒ N2 = 13.
check_metrics::<CsharpParser>(
"class A {\n void M() {\n bool a = true;\n bool b = false;\n bool c = true;\n object d = null;\n }\n}\n",
"foo.cs",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 9);
assert_eq!(metric.halstead.total_operands(), 10);
},
);
}
#[test]
fn csharp_boolean_keyword_outside_a_literal_still_counts() {
// Companion to the test above (#1253): the suppression fires on
// the *parent* kind, never on `True` / `False` alone. C#'s
// overloadable-operator list emits a bare `true` / `false` token
// with no `boolean_literal` wrapper — `operator_declaration` is
// the grammar's only such position — so a blanket exclusion
// would drop the operand that is the sole difference between
// `operator true` and `operator false`, leaving two such
// declarations with identical Halstead vocabularies whenever
// their bodies match.
//
// Each declaration names one boolean and returns the other, so
// the fixture exercises both the guarded and the unguarded
// position for each keyword.
//
// Operands: `A` × 3 (class name, two parameter types), `a` × 2,
// `true` × 2 (operator name + literal), `false` × 2 (likewise)
// ⇒ n2 = 4, N2 = 9. A blanket exclusion gives N2 = 7; no guard
// at all restores the double count at N2 = 11.
check_metrics::<CsharpParser>(
"class A {\n public static bool operator true(A a) => false;\n public static bool operator false(A a) => true;\n}\n",
"foo.cs",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 9);
},
);
}
#[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.unique_operators(), 9);
},
);
}
#[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.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 5);
},
);
}
#[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.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 4);
},
);
}
#[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.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 4);
},
);
}
#[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#"
{
"unique_operators": 7,
"total_operators": 7,
"unique_operands": 5,
"total_operands": 8,
"length": 15,
"estimated_program_length": 31.26112492884004,
"purity_ratio": 2.0840749952560027,
"vocabulary": 12,
"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#"
{
"unique_operators": 10,
"total_operators": 14,
"unique_operands": 4,
"total_operands": 6,
"length": 20,
"estimated_program_length": 41.219280948873624,
"purity_ratio": 2.0609640474436812,
"vocabulary": 14,
"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.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 6);
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.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 4);
},
);
}
#[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.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 4);
},
);
}
#[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.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 2);
});
}
#[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.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 4);
},
);
}
#[test]
fn perl_bare_pattern_delimiters_are_not_operators() {
// Regression: issue #1312, the Perl sibling of Elixir #1256.
// The bare match form is the only one of Perl's regex literals
// whose delimiters are spelled with an operator token kind —
// `bca dump` shows `/abc/` emitting two `SLASH` under
// `PatternMatcher` — so `$s =~ /abc/;` reported a `/` operator
// with no division in the source.
//
// expected: operators `$` (the `scalar_variable` sigil), `=~`
// and `;` → n1 = N1 = 3. Operands `$s` and the `/abc/` pattern
// → n2 = N2 = 2. Before the guard the two delimiters added `/`
// → n1 = 4, N1 = 5; the pattern operand arrived with #1314,
// which promoted all three pattern spellings together (see
// `perl_every_pattern_value_spelling_scores_alike`).
check_metrics::<PerlParser>("$s =~ /abc/;\n", "foo.pl", |metric| {
assert_eq!(metric.halstead.unique_operators(), 3);
assert_eq!(metric.halstead.total_operators(), 3);
assert_eq!(metric.halstead.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 2);
});
}
#[test]
fn perl_every_pattern_value_spelling_scores_alike() {
// Companion to the test above (#1312, extended by #1314).
// `m/abc/` is exactly `/abc/` in Perl and `qr/abc/` is the same
// pattern as a value, so the three spellings of a pattern
// *value* must score identically whatever delimiters they use.
//
// Until #1314 they scored alike at *zero*: no Perl pattern
// wrapper was in the operand arm, so the literal never counted,
// unlike Ruby's `Regex` and Elixir's `Sigil`. #1312 declined to
// promote the bare form on its own precisely because that would
// have scored `/abc/` at one operand and its synonyms at zero,
// reintroducing the spelling sensitivity this test pins.
// Promoting all three together closes the gap and keeps the
// equality, which is what this test now asserts.
//
// `s///` and `tr///` are deliberately *not* rows here any more.
// They are operations applied to a target rather than pattern
// values, so #1314 made them operators; their own equality is
// pinned by `perl_every_pattern_operation_spelling_scores_alike`
// below. Splitting the one loop in two is the substantive
// disagreement #1314 had with the reasoning recorded here: this
// test governs *synonyms*, and `s///` is not a synonym of
// `/abc/`.
//
// The fixture matches twice against one variable so that no two
// of `[n1, N1, n2, N2]` are equal. A square tuple would leave
// `assert_halstead_counts`' unique-vs-total axes unpinned —
// transposing n1 with N1 inside the helper failed no test while
// all three of its callers expected a square tuple.
//
// expected per variant: operators `$` × 2 (one per
// `scalar_variable`), `=~` × 2, `and`, `;` → n1 = 4, N1 = 6.
// The pattern contributes no *operator* — that is #1312's half
// — and one operand, so with `$s` twice and the pattern twice
// → n2 = 2, N2 = 4.
for pattern in ["/abc/", "m/abc/", "m{abc}", "qr/abc/"] {
assert_halstead_counts::<PerlParser>(
&format!("$s =~ {pattern} and $s =~ {pattern};\n"),
"foo.pl",
[4, 6, 2, 4],
&format!("pattern {pattern}"),
);
}
}
#[test]
fn perl_every_pattern_operation_spelling_scores_alike() {
// The other half of the split (#1314). Substitution and
// transliteration are operations applied to a target, so they
// are operators — and like the value spellings, their delimiter
// choice must not move the count. `y///` is a synonym of
// `tr///` and shares `TransliterationTrOrY`, so the two fold to
// one operator entry, which is why all four rows agree on n1.
//
// expected per variant: operators `$` × 2, `=~` × 2, `and`,
// `;`, and the operation itself × 2 → n1 = 5, N1 = 8. The
// pattern and replacement text is invisible to this grammar —
// `substitution_pattern_s` emits only its keyword and
// delimiters, no content node — so the sole operand is `$s`,
// twice → n2 = 1, N2 = 2.
for pattern in ["s/a/b/", "s{a}{b}", "tr/a/b/", "y/a/b/"] {
assert_halstead_counts::<PerlParser>(
&format!("$s =~ {pattern} and $s =~ {pattern};\n"),
"foo.pl",
[5, 8, 1, 2],
&format!("pattern {pattern}"),
);
}
}
#[test]
fn perl_interpolated_pattern_operands_agree_but_operators_do_not() {
// Two things at once (#1314), because they are the same
// measurement: why the three pattern-value spellings route
// through `string_operand_type` rather than a plain operand
// arm, and what that routing does *not* fix.
//
// `m/$x/` and `qr/$x/` emit a real `Interpolation` wrapping a
// `scalar_variable`, while the bare form keeps its `$x` inside
// an unclassified `regex_pattern_content`. So:
//
// * Operands agree at n2 = N2 = 2 (`$s` plus one contribution
// from the pattern) only because of the interpolation guard.
// A plain operand arm would count the wrapper *and* the inner
// `$x` for the suffixed forms — n2 = 3 — reintroducing
// through the back door the divergence
// `perl_every_pattern_value_spelling_scores_alike` exists to
// prevent. Which node carries the one operand still differs
// by spelling: the wrapper for the bare form, the inner `$x`
// for the other two.
// * Operators do *not* agree: the exposed `scalar_variable`
// brings a `$` sigil, an operator here, that the bare form
// has no node for. Over two matches N1 is 6 for `/$x/` and
// 8 for the other two.
//
// The operator asymmetry is a grammar gap this classifier
// cannot repair — there is nothing to classify in the bare
// form — so it is pinned rather than papered over, the same
// treatment `perl_division_emits_no_slash_token` gives the
// missing division token. A bump that starts exposing the bare
// form's interpolation turns this red, at which point the
// expectations above need re-deriving.
// Each fixture matches twice, so `N1 > n1` and `N2 > n2` and no
// row is a square tuple that a transposition inside
// `assert_halstead_counts` could pass (#1312).
assert_halstead_counts::<PerlParser>(
"$s =~ /$x/ and $s =~ /$x/;\n",
"foo.pl",
[4, 6, 2, 4],
"bare /$x/",
);
for pattern in ["m/$x/", "qr/$x/"] {
assert_halstead_counts::<PerlParser>(
&format!("$s =~ {pattern} and $s =~ {pattern};\n"),
"foo.pl",
[4, 8, 2, 4],
&format!("suffixed {pattern}"),
);
}
}
#[test]
fn perl_division_emits_no_slash_token() {
// Drift marker, not an endorsement. Ruby's counterpart
// (`ruby_division_survives_the_regex_guard`) proves #1312's
// guard cannot swallow a real division; Perl has no such
// fixture to write, because at the pinned grammar `$a / $b`
// emits *no* `SLASH` token at all — `binary_expression`'s
// children skip straight from one `scalar_variable` to the
// other. Perl division therefore counts zero operators today,
// a pre-existing grammar gap this fix neither causes nor
// repairs.
//
// Pinning it keeps the gap in CI: a bump that starts emitting
// the token turns this red, at which point the division would
// begin counting (its parent is `BinaryExpression`, not
// `PatternMatcher`, so the guard leaves it alone) and the
// expectations above need re-deriving.
//
// The same gap is why no Perl test can distinguish the
// parent-scoped guard from an ancestor-scoped one: with no
// `SLASH` reachable below a `PatternMatcher`, that mutant is
// unobservable here — measured, not assumed. Perl's guard is
// parent-scoped for correctness by construction and for
// symmetry with Ruby's, where the distinction *is* observable
// and is pinned by
// `ruby_regex_guard_is_parent_scoped_not_ancestor_scoped`.
let path = PathBuf::from("foo.pl");
let source = "my $z = $a / $b;\n";
let parser = PerlParser::new(source.as_bytes().to_vec(), &path, None);
assert!(
!ast_has_kind_id(&parser, Perl::SLASH as u16),
"tree-sitter-perl still emits no SLASH for `{source}`"
);
// Anchor the negative assertion to *this* fixture. Without it
// the test stays green when `source` is edited to something
// containing no division at all — measured: swapping in
// `my $z = 1;` failed nothing.
//
// expected: operators `my`, `=`, `$` × 3 (one per
// `scalar_variable`), `;` → n1 = 4, N1 = 6, with no `/` among
// them. Operands `$z`, `$a`, `$b` → n2 = N2 = 3.
check_metrics::<PerlParser>(source, "foo.pl", |metric| {
assert_eq!(metric.halstead.unique_operators(), 4);
assert_eq!(metric.halstead.total_operators(), 6);
assert_eq!(metric.halstead.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 3);
});
// Positive control: the same kind *is* reachable in this
// grammar, so the assertion above is about division and not
// about `Perl::SLASH` being enum-only dead weight.
let matcher = PerlParser::new(b"$s =~ /abc/;\n".to_vec(), &path, None);
assert!(
ast_has_kind_id(&matcher, Perl::SLASH as u16),
"Perl::SLASH must be the bare pattern delimiter kind"
);
}
/// Every (name wrapper, contained operand) pairing tree-sitter-perl's
/// node-types.json admits, and the single source of truth for both
/// halves of #1355's guard: its parent set is the distinct first
/// components, the kinds it subsumes the distinct second ones.
/// `perl_name_wrappers_bill_the_name_once_1355` witnesses every row
/// and fails on an eleventh pairing.
const PERL_NAME_WRAPPER_PAIRINGS: [(Perl, Perl); 10] = [
(Perl::PackageName, Perl::Identifier),
(Perl::PackageName, Perl::ScalarVariable),
(Perl::PackageName, Perl::ArrayVariable),
(Perl::PackageName, Perl::HashVariable),
(Perl::PackageName, Perl::SpecialScalarVariable),
(Perl::PackageName, Perl::Typeglob),
(Perl::PackageName, Perl::PackageVariable),
(Perl::PackageVariable, Perl::PackageName),
(Perl::PackageVariable, Perl::ScalarVariable),
(Perl::Typeglob, Perl::Identifier),
];
/// The anonymous tokens those wrappers also hold. `::` and `*` are
/// operators (matched above the guard, so they keep that reading);
/// `{` folds into the `{}` glyph and `}` has never been classified
/// at all. Listing them is what lets
/// `perl_name_wrappers_bill_the_name_once_1355` police *every*
/// child rather than only the named ones — the operand arm carries
/// token-shaped kinds too (`True`, `FILE`, `SUB`, …), and a bump
/// that let one of those inside a wrapper would otherwise be
/// silenced with nothing failing.
const PERL_NAME_WRAPPER_TOKENS: [Perl; 4] =
[Perl::COLONCOLON, Perl::STAR, Perl::LBRACE, Perl::RBRACE];
/// The occurrences #1355's guard suppresses in `source`, paired
/// with the (wrapper kind, child kind) pairings they witness.
///
/// Walks with `for_each_node_with_chain`, which maintains the
/// ancestor chain exactly as `spaces::compute` does, so "parent"
/// here means what `Ancestors::parent` means inside the guard
/// rather than what a differently-built chain would say.
fn perl_subsumed_operands(source: &str) -> (Vec<String>, HashSet<(u16, u16)>) {
let wrappers: HashSet<u16> = PERL_NAME_WRAPPER_PAIRINGS
.map(|(wrapper, _)| wrapper as u16)
.into();
let subsumed: HashSet<u16> = PERL_NAME_WRAPPER_PAIRINGS
.map(|(_, child)| child as u16)
.into();
let tokens: HashSet<u16> = PERL_NAME_WRAPPER_TOKENS.map(|kind| kind as u16).into();
let code = source.as_bytes();
let mut hidden = Vec::new();
let mut pairings = HashSet::new();
for_each_node_with_chain::<PerlCode>(code, |node, chain| {
let Some(parent) = chain.last() else { return };
if !wrappers.contains(&parent.kind_id()) {
return;
}
assert!(
subsumed.contains(&node.kind_id()) || tokens.contains(&node.kind_id()),
"`{source}`: a `{}` inside a `{}` is a child this guard was not \
derived against; re-read node-types.json before trusting it",
node.kind(),
parent.kind(),
);
if subsumed.contains(&node.kind_id()) {
pairings.insert((parent.kind_id(), node.kind_id()));
hidden.push(
node.utf8_text(code)
.expect("fixture is valid UTF-8")
.to_owned(),
);
}
});
(hidden, pairings)
}
/// One row of `perl_name_wrappers_bill_the_name_once_1355`'s
/// table: a fixture, what it must measure now, what it measured
/// before #1355, and the operand text behind the counts.
struct PerlNameWrapperCase {
source: &'static str,
/// `[n1, N1, n2, N2]` with the guard in place.
counts: [u64; 4],
/// `[n2, N2]` without it. Re-derived by the loop rather than
/// trusted, so a stale row fails instead of misinforming.
before: [u64; 2],
operands: &'static [&'static str],
}
/// Regression for #1355. `package_name`, `package_variable` and
/// `typeglob` are operands spanning a whole name, so every
/// operand-classified node *inside* one was billed a second time:
/// `use strict;` scored `N2` 2 for one name, `our $Foo::count = 3;`
/// n2 5 / N2 6 for two, and the vocabulary grew a bare `::` entry
/// because a `package_variable`'s qualifier slot is itself a
/// childless `package_name`.
///
/// Each row's `before` column is what it measured without the
/// guard, and the loop re-derives both halves from the current
/// parse rather than trusting the column — the guard is the only
/// difference between the two classifications, so the occurrences
/// it removes are exactly the subsumed-kind children of a wrapper:
///
/// - `N2` before minus `N2` after must equal how many of those
/// there are. That identity *is* the defect: one spurious operand
/// per contained name part.
/// - `n2` before is the post-fix vocabulary unioned with their
/// texts. It exceeds `n2` after wherever a part's spelling is not
/// already an operand on its own (`Data`, `::`, `count`).
///
/// The walk doubles as the grammar-dispatch §1 / §2 drift marker.
/// It asserts that every *named* child of a wrapper is one of the
/// eight subsumed kinds — which is what makes keying the arm on the
/// parent alone safe — and that all ten pairings node-types.json
/// admits are exercised here, so a bump that renumbers or re-parents
/// one fails loudly instead of leaving the counts below measuring a
/// construct the arm no longer reaches.
///
/// Two mutants this does *not* catch, measured rather than assumed.
/// Widening the guard from parent- to ancestor-scoped fails nothing,
/// for the reason `perl_division_emits_no_slash_token` already
/// records about the other guard in this getter: every operand-kinded
/// descendant of a wrapper is also a direct child of one, and the
/// intervening sigil tokens are matched by the operator arm above
/// before the guard is reached. Parent-scoping stands on
/// grammar-dispatch §5 and on symmetry with that guard, not on a
/// test. What *is* pinned is the arm's position: moving it above the
/// operator arm swallows `::`, `*` and the typeglob's opening brace,
/// and the operator columns below fail.
#[test]
fn perl_name_wrappers_bill_the_name_once_1355() {
let cases: [PerlNameWrapperCase; 12] = [
// identifier under package_name, the single-segment form.
PerlNameWrapperCase {
source: "use strict;\n",
counts: [2, 2, 1, 1],
before: [1, 2],
operands: &["strict"],
},
// …and the multi-segment one, twice over.
PerlNameWrapperCase {
source: "require Data::Dumper;\n",
counts: [3, 3, 1, 1],
before: [3, 3],
operands: &["Data::Dumper"],
},
PerlNameWrapperCase {
source: "package Foo::Bar;\n",
counts: [3, 3, 1, 1],
before: [3, 3],
operands: &["Foo::Bar"],
},
// The `bar` of a qualified call is a *sibling* of the
// `package_name`, not a child, so it still counts while the
// `Foo` inside the wrapper does not. That is the row saying
// the guard reads position and not kind: keying it on the
// child kinds instead fails 14 tests here, this one among
// them.
PerlNameWrapperCase {
source: "Foo::bar();\n",
counts: [3, 3, 2, 2],
before: [2, 3],
operands: &["Foo", "bar"],
},
// identifier under typeglob, bare and brace-delimited.
PerlNameWrapperCase {
source: "my $g = *STDOUT;\n",
counts: [5, 5, 2, 2],
before: [3, 3],
operands: &["$g", "*STDOUT"],
},
PerlNameWrapperCase {
source: "my $t = *{Foo};\n",
counts: [6, 6, 2, 2],
before: [3, 3],
operands: &["$t", "*{Foo}"],
},
// package_name and scalar_variable under package_variable,
// and scalar_variable under package_name — the reported
// fixture, where `$Foo` was billed twice and `::` once.
PerlNameWrapperCase {
source: "our $Foo::count = 3;\n",
counts: [4, 4, 2, 2],
before: [5, 6],
operands: &["$Foo::count", "3"],
},
// array_variable / hash_variable / special_scalar_variable
// under package_name: the same shape with the other sigils.
PerlNameWrapperCase {
source: "my @l = @Foo::list;\n",
counts: [3, 3, 2, 2],
before: [5, 6],
operands: &["@l", "@Foo::list"],
},
PerlNameWrapperCase {
source: "my %h = %Foo::hash;\n",
counts: [3, 3, 2, 2],
before: [5, 6],
operands: &["%h", "%Foo::hash"],
},
PerlNameWrapperCase {
source: "my $z = $_::x;\n",
counts: [4, 5, 2, 2],
before: [5, 6],
operands: &["$z", "$_::x"],
},
// typeglob under package_name.
PerlNameWrapperCase {
source: "*Foo::glob = 1;\n",
counts: [3, 3, 2, 2],
before: [6, 7],
operands: &["*Foo::glob", "1"],
},
// package_variable under package_name: the nesting that
// makes qualifier depth unbounded. One variable reference
// used to spell seven vocabulary entries.
PerlNameWrapperCase {
source: "my $x = $Foo::Bar::baz;\n",
counts: [4, 5, 2, 2],
before: [7, 10],
operands: &["$x", "$Foo::Bar::baz"],
},
];
let mut witnessed: HashSet<(u16, u16)> = HashSet::new();
for PerlNameWrapperCase {
source,
counts,
before: [n2_before, total_before],
operands,
} in cases
{
let (hidden, pairings) = perl_subsumed_operands(source);
assert!(
!hidden.is_empty(),
"row {source:?} contains no name-wrapper child, so it witnesses nothing",
);
witnessed.extend(pairings);
// Phrased as an addition rather than a subtraction so a
// future edit that inverts the two underflows nothing and
// fails with the message below.
assert_eq!(
total_before,
counts[3] + hidden.len() as u64,
"row {source:?} must shed exactly one operand per contained \
name part; recorded N2_before {total_before}, parts {hidden:?}",
);
let mut vocabulary: HashSet<&str> = operands.iter().copied().collect();
vocabulary.extend(hidden.iter().map(String::as_str));
assert_eq!(
vocabulary.len() as u64,
n2_before,
"row {source:?}: n2 before the fix is the post-fix vocabulary \
plus the contained name parts; got {vocabulary:?}",
);
assert_halstead_counts::<PerlParser>(source, "foo.pl", counts, source);
assert_ops_operands::<PerlParser>(source, "foo.pl", operands.len(), operands.to_vec());
}
let mut got: Vec<(u16, u16)> = witnessed.into_iter().collect();
got.sort_unstable();
let mut expected_pairings: Vec<(u16, u16)> = PERL_NAME_WRAPPER_PAIRINGS
.map(|(wrapper, child)| (wrapper as u16, child as u16))
.into();
expected_pairings.sort_unstable();
assert_eq!(
got, expected_pairings,
"the table must exercise every (wrapper, child) pairing \
node-types.json admits, and no other",
);
}
/// The over-suppression half of #1355 (grammar-dispatch §6 and §11).
/// The guard is keyed on the parent, so the same kinds it silences
/// inside a name wrapper have to keep counting everywhere else —
/// otherwise "one operand per name" would have been bought by
/// zeroing ordinary variables and calls.
///
/// `module_name` rides along because the issue asserted it shares
/// the `identifier` leaf and would be collateral damage. It does
/// not: `use 'Foo.pm'` parses to a leaf holding only its two quote
/// tokens, so it wraps nothing and is untouched either way.
#[test]
fn perl_qw_list_bills_one_operand_per_element() {
// `qw(a b c)` was invisible to Halstead — neither the elements,
// the wrapper nor the `qw` keyword had an arm — so it billed
// nothing where its synonym `("a", "b", "c")` billed three
// operands. Each `list_item` is now one operand and the
// `word_list_qw` wrapper is gated on holding one, the #1353
// Ruby `%w[]` rule: one operand per element, or one for the
// empty literal.
assert_ops_operands::<PerlParser>(
"my @a = qw(a b c);\n",
"foo.pl",
4,
vec!["@a", "a", "b", "c"],
);
assert_ops_operands::<PerlParser>("my @a = qw();\n", "foo.pl", 2, vec!["@a", "qw()"]);
assert_ops_operands::<PerlParser>(
"use POSIX qw(floor ceil);\n",
"foo.pl",
3,
vec!["POSIX", "floor", "ceil"],
);
// expected: [n1, N1, n2, N2] = [3, 3, 4, 4] for every delimiter —
// operators `my`, `=`, `;`; the `qw` keyword and its delimiters
// are unclassified, as Ruby's `%w[` is, so the choice of
// delimiter cannot move the score (#1312).
for spelling in [
"qw(a b c)",
"qw/a b c/",
"qw{a b c}",
"qw[a b c]",
"qw<a b c>",
] {
assert_halstead_counts::<PerlParser>(
&format!("my @a = {spelling};\n"),
"foo.pl",
[3, 3, 4, 4],
spelling,
);
}
// The synonym: the same four operands, plus the `()` and `,`
// operators the list spelling carries.
assert_halstead_counts::<PerlParser>(
"my @a = (\"a\", \"b\", \"c\");\n",
"foo.pl",
[5, 6, 4, 4],
"list literal",
);
}
#[test]
fn perl_qualified_name_leaves_still_count_elsewhere_1355() {
// expected: operators `my` × 4, `$` × 3 (one per `$`-sigilled
// variable), `=` × 4, `;` × 5, `()` × 3 and the fat comma
// → n1 = 6, N1 = 20. Operands are the four declared variables,
// the three integers, the hash key, `$_` and the call target
// → n2 = N2 = 10. Five of the eight kinds the guard silences
// under a name wrapper appear among them — `scalar_variable`,
// `array_variable`, `hash_variable`, `special_scalar_variable`
// and `identifier` — and all five still count here.
let bare = "my $x = 1;\nmy @a = (2);\nmy %h = (k => 3);\nmy $u = $_;\nfoo();\n";
assert_halstead_counts::<PerlParser>(bare, "foo.pl", [6, 20, 10, 10], bare);
assert_ops_operands::<PerlParser>(
bare,
"foo.pl",
10,
vec!["$x", "1", "@a", "2", "%h", "k", "3", "$u", "$_", "foo"],
);
let (hidden, _) = perl_subsumed_operands(bare);
assert!(
hidden.is_empty(),
"no name wrapper appears here, so the guard must be inert; got {hidden:?}",
);
// expected: operators `use`, `;` → n1 = N1 = 2; the quoted
// module name is the sole operand → n2 = N2 = 1.
let quoted = "use 'Some.pm';\n";
assert_halstead_counts::<PerlParser>(quoted, "foo.pl", [2, 2, 1, 1], quoted);
assert_ops_operands::<PerlParser>(quoted, "foo.pl", 1, vec!["'Some.pm'"]);
assert!(
ast_has_kind_id(
&PerlParser::new(quoted.as_bytes().to_vec(), &PathBuf::from("foo.pl"), None),
Perl::ModuleName as u16,
),
"the quoted `use` form no longer parses to `module_name`, so this \
row no longer says anything about it",
);
}
#[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=11: local,function,(,,,=,+,if,>,then,return,end
// (after #695 the `)` closer no longer counts — only the
// folded `(` opener does; was n1=12).
// n2=5: add,a,b,result,0
insta::assert_json_snapshot!(metric.halstead, @r#"
{
"unique_operators": 11,
"total_operators": 14,
"unique_operands": 5,
"total_operands": 10,
"length": 24,
"estimated_program_length": 49.66338827944708,
"purity_ratio": 2.0693078449769615,
"vocabulary": 16,
"volume": 96.0,
"difficulty": 11.0,
"level": 0.09090909090909091,
"effort": 1056.0,
"time": 58.666666666666664,
"bugs": 0.03456644293839657
}
"#);
},
);
}
/// Regression for #695. Lua/Bash/Tcl/iRules/PHP/Ruby/Elixir used to
/// classify the *closing* delimiter (`)`/`]`/`}`) as a separate
/// operator, while the C-family majority folds each balanced pair to a
/// single glyph via `get_operator_id_as_str` and counts only the
/// opener. A balanced `(1)` therefore double-counted as `()` + `)`,
/// inflating n1 and N1. With the fix only the folded `(` opener counts:
/// `local x = (1)` yields operators `local`, `=`, `()` — n1 = N1 = 3,
/// with no standalone `)`.
#[test]
fn lua_balanced_paren_counts_opener_only() {
let source = "local x = (1)\n";
let path = PathBuf::from("foo.lua");
let parser = LuaParser::new(source.as_bytes().to_vec(), &path, None);
let ops = crate::ops::ops_inner(&parser, None).expect("ops walk succeeds");
let paren = ops.operators.iter().filter(|o| o.as_str() == "()").count();
assert_eq!(
paren, 1,
"balanced `(1)` must be one `()` operator; operators were {:?}",
ops.operators
);
assert!(
!ops.operators.iter().any(|o| o.as_str() == ")"),
"the closing `)` must not be a separate operator; operators were {:?}",
ops.operators
);
}
/// Guard for #768. Several `get_op_type` impls (Cpp/C/Objc/Mozcpp/
/// Tcl/iRules/Php/Elixir/Ruby) classify a grammar's *second-alias*
/// opener — `LPAREN2`, and for Elixir/Ruby `LBRACK2`/`LBRACK3` — as a
/// Halstead operator alongside the base `LPAREN`/`LBRACK`. #768 worried
/// that an alias opener would reach `compute_halstead` with a kind_id
/// distinct from the base, inflating n1 (a second `()` entry) and
/// rendering a bare `"("` instead of the folded `"()"`.
///
/// That cannot happen: tree-sitter's runtime collapses each alias to
/// its base via the grammar's `public_symbol_map` *before*
/// `Node::kind_id()` (`ts_node_symbol`) ever returns. So the alias
/// kind_id is unobservable to the metric layer and the alias match arms
/// are defensive — they only fire if a future grammar bump drops that
/// collapse. This test pins the invariant: parsing the exact
/// constructs each grammar produces the alias for internally
/// (pp-conditional `defined(...)` for Cpp; call arg-list / subscript /
/// constant-array-pattern for Ruby) must yield **no** node carrying the
/// alias kind_id, and the balanced opener must count once and render as
/// the pair glyph. If a grammar bump makes an alias id observable, this
/// goes red and signals that the alias arms must additionally fold to
/// the base in `get_operator_id_as_str` (the fix #768 proposed).
#[test]
fn second_alias_opener_collapses_to_base_kind_id() {
fn assert_no_alias<T: crate::ParserTrait>(
source: &str,
file: &str,
alias_id: u16,
alias_name: &str,
) {
let path = PathBuf::from(file);
let parser = T::new(source.as_bytes().to_vec(), &path, None);
let mut stack = vec![parser.root()];
while let Some(node) = stack.pop() {
assert_ne!(
node.kind_id(),
alias_id,
"{alias_name} (kind_id {alias_id}) must never reach kind_id() \
for `{source}`; the runtime public_symbol_map should have \
collapsed it to the base opener. If this fires after a \
grammar bump, fold {alias_name} to its pair glyph in \
get_operator_id_as_str (issue #768)."
);
for child in node.children() {
stack.push(child);
}
}
}
// Balanced openers must count once and render folded (no bare
// `(`/`[`, no n1 inflation) — the property #768 feared was broken.
fn assert_folded_openers<T: crate::ParserTrait>(source: &str, file: &str) {
let path = PathBuf::from(file);
let parser = T::new(source.as_bytes().to_vec(), &path, None);
let ops = crate::ops::ops_inner(&parser, None).expect("ops walk succeeds");
assert!(
!ops.operators.iter().any(|o| o.as_str() == "("),
"no bare `(` operator (must fold to `()`); operators were {:?}",
ops.operators
);
assert!(
!ops.operators.iter().any(|o| o.as_str() == "["),
"no bare `[` operator (must fold to `[]`); operators were {:?}",
ops.operators
);
// Each pair glyph appears at most once — the alias does not add
// a second `()`/`[]` entry to n1.
assert!(
ops.operators.iter().filter(|o| o.as_str() == "()").count() <= 1,
"`()` must be a single n1 entry; operators were {:?}",
ops.operators
);
assert!(
ops.operators.iter().filter(|o| o.as_str() == "[]").count() <= 1,
"`[]` must be a single n1 entry; operators were {:?}",
ops.operators
);
}
// Cpp/C/Mozcpp: LPAREN2 = 20. The grammar emits it internally only
// inside preprocessor-conditional expressions (`#if defined(FOO)`).
assert_no_alias::<crate::CppParser>(
"#if defined(FOO)\n#endif\n",
"a.cpp",
20,
"Cpp::LPAREN2",
);
assert_no_alias::<crate::CParser>("#if defined(FOO)\n#endif\n", "a.c", 20, "C::LPAREN2");
// Ruby: LPAREN2 = 47 (call arg-list), LBRACK3 = 155 (element-
// reference subscript), LBRACK2 = 46 (constant array pattern).
assert_no_alias::<crate::RubyParser>("f(1)\n", "a.rb", 47, "Ruby::LPAREN2");
assert_no_alias::<crate::RubyParser>("a[0]\n", "a.rb", 155, "Ruby::LBRACK3");
assert_no_alias::<crate::RubyParser>(
"case p\nin Point[1, 2] then 1\nend\n",
"a.rb",
46,
"Ruby::LBRACK2",
);
// Elixir: LPAREN2 = 95 (immediate call paren), LBRACK2 = 96
// (access / subscript).
assert_no_alias::<crate::ElixirParser>("f(1)\n", "a.ex", 95, "Elixir::LPAREN2");
assert_no_alias::<crate::ElixirParser>("x[0]\n", "a.ex", 96, "Elixir::LBRACK2");
assert_folded_openers::<crate::CppParser>("int main(){ int a[3]; return a[0]; }", "b.cpp");
assert_folded_openers::<crate::RubyParser>("f(1)\nb = [1]\nb[0]\n", "b.rb");
}
#[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#"
{
"unique_operators": 9,
"total_operators": 11,
"unique_operands": 5,
"total_operands": 10,
"length": 21,
"estimated_program_length": 40.13896548741762,
"purity_ratio": 1.9113793089246487,
"vocabulary": 14,
"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() {
// Re-anchored for issue #454. The pre-#454 comment claimed
// kotlin-ng emits an `identifier` node for the short `$name`
// form whose bytes include the leading `$`. That is factually
// false: AST dump shows the short form produces bare
// `string_content` tokens (`$`, then `name`) with **no**
// structured node. The old assertion (u_operands = 4, N2 = 5)
// passed for the wrong reason (lesson 6): the wrapping literal
// was counted (+1) and the inner `name` was dropped (-1), and
// the two errors cancelled. The `$name!` it used also defeats
// recovery because the grammar glues the trailing `!` onto the
// name token.
//
// Correct mechanism (clean end-of-segment short form):
// `fun greet(name: String): String {\n return "Hi $name"\n}\n`
// operators: fun, (, ), :, {}, return → as classified.
// operands by token text:
// `greet` × 1, `name` × 2 (param + recovered short-interp),
// `String` × 2 (param type + return type).
// The wrapping `"Hi $name"` literal is suppressed and the
// inner `name` recovered → u_operands = 3 (`greet`, `name`,
// `String`), N2 = 5. Pre-#454: wrapper counted, inner dropped
// → u_operands = 4, N2 = 6.
check_metrics::<KotlinParser>(
"fun greet(name: String): String {\n return \"Hi $name\"\n}\n",
"foo.kt",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 5);
},
);
// Lesson 4: the ops store agrees on n2 and the exact operand set
// (inner `name` present, wrapper absent).
assert_ops_operands::<KotlinParser>(
"fun greet(name: String): String {\n return \"Hi $name\"\n}\n",
"foo.kt",
3,
vec!["greet", "name", "String"],
);
}
#[test]
fn kotlin_short_interpolation_counts_inner_not_wrapper() {
// Issue #454: the short `$name` template — distinct from the
// long `${expr}` form, which the kotlin-ng grammar gives a
// structured `interpolation` node (see
// `kotlin_string_template_long_form_no_double_count`). The short
// form has no such node; the variable arrives as a bare
// `string_content` token preceded by a `$` `string_content`.
// The fix recovers the clean-identifier variable as an operand
// and suppresses the opaque wrapper.
//
// `fun f() { val x = 1; println("v=$x") }\n`
// operands by token text: `f`, `x` × 2 (decl + recovered),
// `println`, `1`. The wrapping `"v=$x"` is suppressed →
// u_operands = 4 (`f`, `x`, `println`, `1`), N2 = 5.
// Pre-#454 the wrapper `"v=$x"` counted and the inner `x` was
// dropped → u_operands = 4 but the wrapper, not `x`, was the
// fourth operand, and N2 = 5 with the wrong member — the ops
// assertion below pins the exact set so the cancellation cannot
// hide it.
let src = "fun f() { val x = 1; println(\"v=$x\") }\n";
check_metrics::<KotlinParser>(src, "foo.kt", |metric| {
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 5);
});
assert_ops_operands::<KotlinParser>(src, "foo.kt", 4, vec!["f", "x", "println", "1"]);
}
#[test]
fn kotlin_short_interpolation_space_separated() {
// Issue #454 follow-up: tree-sitter-kotlin-ng splits the literal
// only at each `$`, so a `$name` segment's name token absorbs any
// trailing inter-segment text into its byte range. For `"$a $b"`
// the token after the first `$` is `"a "` (with the trailing
// space). Pre-fix `kotlin_is_identifier("a ")` returned false and
// the leading variable `a` was silently dropped, yielding
// operands `{b, f, s}` (verified: `a` missing) — breaking parity
// with the long form `"${a} ${b}"`, which recovers `{a, b, f, s}`.
//
// The fix takes the maximal leading-identifier prefix of the name
// token, recovering `a` and keying it as the bare `"a"` (not
// `"a "`). Short and long forms must now agree exactly.
//
// `fun f() { val s = "$a $b" }\n`
// operands by token text: `f`, `s`, `a` (recovered), `b`
// (recovered). Wrapper suppressed → u_operands = 4, N2 = 4.
let short = "fun f() { val s = \"$a $b\" }\n";
let long = "fun f() { val s = \"${a} ${b}\" }\n";
check_metrics::<KotlinParser>(short, "foo.kt", |metric| {
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 4);
});
// Both `a` and `b` present, wrapper absent, n2 == dedupe(operands).
assert_ops_operands::<KotlinParser>(short, "foo.kt", 4, vec!["f", "s", "a", "b"]);
// Exact parity with the long `${a} ${b}` form.
assert_ops_operands::<KotlinParser>(long, "foo.kt", 4, vec!["f", "s", "a", "b"]);
// Comma after the name (`"$a, $b"`): the first name token is
// `"a, "`; its leading identifier prefix is `a`.
let comma = "fun f() { val s = \"$a, $b\" }\n";
assert_ops_operands::<KotlinParser>(comma, "foo.kt", 4, vec!["f", "s", "a", "b"]);
// Name preceded by literal text and at end-of-segment (`"x=$a"`):
// the `a` token has no trailing text, so recovery is unchanged.
let prefixed = "fun f() { val s = \"x=$a\" }\n";
assert_ops_operands::<KotlinParser>(prefixed, "foo.kt", 3, vec!["f", "s", "a"]);
// Mid-prose `"$x is "`: the name token is `"x is "`. The leading
// identifier prefix is `x`, matching the long form `"${x} is "`,
// which also recovers `x` and treats `" is "` as literal text.
let prose_short = "fun f() { val s = \"$x is \" }\n";
let prose_long = "fun f() { val s = \"${x} is \" }\n";
assert_ops_operands::<KotlinParser>(prose_short, "foo.kt", 3, vec!["f", "s", "x"]);
assert_ops_operands::<KotlinParser>(prose_long, "foo.kt", 3, vec!["f", "s", "x"]);
}
#[test]
fn kotlin_dollar_non_identifier_stays_literal() {
// Issue #454 boundary: a `$` not followed by a clean identifier
// is literal text, not an interpolation. `"price: $5"` (digit
// after `$`) must keep the wrapping literal as a single operand
// and recover nothing.
//
// `fun f() { val a = "price: $5" }\n`
// operands: `f`, `a`, `"price: $5"` → u_operands = 3, N2 = 3.
let src = "fun f() { val a = \"price: $5\" }\n";
check_metrics::<KotlinParser>(src, "foo.kt", |metric| {
assert_eq!(metric.halstead.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 3);
});
assert_ops_operands::<KotlinParser>(src, "foo.kt", 3, vec!["f", "a", "\"price: $5\""]);
}
#[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.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 5);
},
);
}
#[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.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 3);
},
);
}
#[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.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 3);
},
);
}
#[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.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 2);
});
}
#[test]
fn python_concatenated_docstring_suppressed() {
// Regression for #695. An implicit-concatenation docstring
// (`"""doc""" "more"`) parses as `expression_statement >
// concatenated_string > [string, string]`. The single-literal
// docstring guard (`parent == expression_statement &&
// child_count == 1`) never fired here, so each fragment counted
// as a separate operand and the docstring's N2 contribution
// depended on how many literals it was split into. With the fix,
// every fragment of such a docstring is suppressed.
//
// Source: `def f():\n """doc""" "more"\n return 1\n`
// Operands: `f`, `1` only — both docstring fragments suppressed →
// u_operands = 2, N2 = 2.
check_metrics::<PythonParser>(
"def f():\n \"\"\"doc\"\"\" \"more\"\n return 1\n",
"foo.py",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 2);
},
);
}
#[test]
fn python_concatenated_non_docstring_still_counts() {
// The #695 fix must only suppress concatenated literals in the
// *docstring* position (sole child of an `expression_statement`).
// A concatenated string used as a value (`x = "a" "b"`) is not a
// docstring — its `concatenated_string` parent's grandparent is
// an assignment, not a single-child statement — so both fragments
// must still be operands.
//
// Source: `def f():\n x = "a" "b"\n return x\n`
// Operands: `f`, `x` (twice: assign + return), `"a"`, `"b"` →
// u_operands = 4, N2 = 5.
check_metrics::<PythonParser>(
"def f():\n x = \"a\" \"b\"\n return x\n",
"foo.py",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 5);
},
);
}
#[test]
fn python_empty_file_halstead() {
check_metrics::<PythonParser>("", "empty.py", |metric| {
let h = &metric.halstead;
assert_eq!(h.unique_operators(), 0);
assert_eq!(h.total_operands(), 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);
});
}
/// Regression #413, sub-fix (1): `await` was double-counted because the
/// operator arm listed both the await-expression node (Await=237) and the
/// nested `await` keyword token (Await2=95). Only the node should count,
/// mirroring how `yield` counts only the Yield node.
#[test]
fn python_await_counted_once_per_use() {
check_metrics::<PythonParser>(
"async def f():\n await a()\n await b()\n await c()\n",
"foo.py",
|metric| {
// expected operators: async, def, await (3 unique)
// await used three times -> N1 counts: async(1) def(1) await(3) = 5
// Before #413, Await + Await2 both matched, so `await` was a
// distinct operator twice: n1=4, N1=8.
assert_eq!(metric.halstead.unique_operators(), 3);
assert_eq!(metric.halstead.total_operators(), 5);
},
);
}
/// Regression #413, sub-fix (3): `lambda` was dropped entirely. Only the
/// `lambda` keyword token (Lambda3=73) is classified, not the wrapping
/// Lambda/Lambda2 expression nodes, to avoid an await-style double count.
#[test]
fn python_lambda_counted_once() {
check_metrics::<PythonParser>("g = lambda x: x + 1\n", "foo.py", |metric| {
// expected operators: =, lambda, + (3 unique, each used once)
// Before #413, lambda was absent: only =, + were counted.
assert_eq!(metric.halstead.unique_operators(), 3);
assert_eq!(metric.halstead.total_operators(), 3);
});
}
/// Regression #413, sub-fix (2): `match` / `case` keyword tokens
/// (Match=26, Case=27) were dropped. Each should now count as an operator,
/// matching the cyclomatic metric which already counts every `case`.
#[test]
fn python_match_case_counted() {
check_metrics::<PythonParser>(
"match x:\n case 1:\n pass\n case _:\n pass\n",
"foo.py",
|metric| {
// expected operators: match, case, pass (3 unique)
// match(1) + case(2) + pass(2) = 5 total occurrences.
// Before #413, neither match nor case was counted (only pass).
assert_eq!(metric.halstead.unique_operators(), 3);
assert_eq!(metric.halstead.total_operators(), 5);
},
);
}
/// Regression #413, sub-fix (2): `nonlocal` (Nonlocal=41) was dropped while
/// `global` was already classified. Both should count, for parity.
#[test]
fn python_nonlocal_and_global_counted() {
check_metrics::<PythonParser>(
"def f():\n global a\n nonlocal b\n",
"foo.py",
|metric| {
// expected operators: def, global, nonlocal (3 unique)
// Before #413, nonlocal was absent: only def, global counted.
assert_eq!(metric.halstead.unique_operators(), 3);
assert_eq!(metric.halstead.total_operators(), 3);
},
);
}
/// Regression #413, sub-fix (4): `not in` (Notin=193) and `is not`
/// (Isnot=194) are single compound operators. The parent-guard suppresses
/// the inner Not/In/Is leaves only under those compounds, so standalone
/// `not x`, `a in b`, `a is b`, and `for x in y` still count their leaves.
#[test]
fn python_not_in_is_not_counted_as_single_operator() {
check_metrics::<PythonParser>(
"a not in b\na is not b\nnot c\nd in e\nf is g\nfor h in i:\n pass\n",
"foo.py",
|metric| {
// expected operators (7 unique):
// "not in" (compound, once), "is not" (compound, once),
// "not" (standalone `not c`, once),
// "in" (standalone `d in e` + `for h in i` = twice),
// "is" (standalone `f is g`, once),
// "for" (once), "pass" (once)
// Total occurrences: 1+1+1+2+1+1+1 = 8.
// Before #413, `a not in b` counted not+in (two) and
// `a is not b` counted is+not (two); the compounds were
// never classified.
assert_eq!(metric.halstead.unique_operators(), 7);
assert_eq!(metric.halstead.total_operators(), 8);
},
);
}
#[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| {
// Operators (9 unique, 9 occurrences): the opening
// delimiters `()`/`{}`/`[]` (each folded to one glyph and
// counted once per balanced pair, #695 — the closers no
// longer add a second operator), `local`, `=`, `if`,
// `then`, `fi`, `;`.
// Operands (6 unique, 7 occurrences): `f`, `x` (the
// assignment LHS `variable_name`, kind 160), `1` (twice:
// `=1` and `-eq 1`), `$x` (the `simple_expansion` — its
// inner `variable_name` leaf is now suppressed so `$x`
// counts once, #695), `echo`, `'one'`.
// N2 was 8 before #1351: `echo` counted twice, once as the
// `command_name` wrapper and once as the `word` it wraps.
assert_eq!(metric.halstead.unique_operators(), 9);
assert_eq!(metric.halstead.total_operators(), 9);
assert_eq!(metric.halstead.unique_operands(), 6);
assert_eq!(metric.halstead.total_operands(), 7);
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` (its inner
// variable_name `x` leaf is suppressed under #695) → 2.
// Total unique operands: 4 (`a`, `b`, `"plain"`, `$x`), each
// appearing once → N2 = 4. Before #695 the inner `x` leaf of
// `$x` was also counted (u_operands = 5, N2 = 5); before the
// earlier #180 fix the wrapping `"$x"` literal was counted too.
// 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.unique_operators(), 1);
assert_eq!(metric.halstead.total_operators(), 2);
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 4);
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`, `(`, `=` → u = N = 4.
// Only the *opening* delimiters count after #695, so the `)`
// and the `}` interpolation closer add no operator; #1314 then
// dropped the `#{` opener too, on the rule that an
// interpolation opener is spelling rather than an operation
// (was 5 here, and 7 before #695).
check_metrics::<ElixirParser>(
"def greet(name) do\n msg = \"Hi #{name}\"\nend\n",
"foo.ex",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 4);
assert_eq!(metric.halstead.total_operators(), 4);
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 5);
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.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 3);
});
}
#[test]
fn elixir_boolean_and_nil_literals_count_once() {
// Regression: issue #1253. `boolean: choice("true", "false")`
// and `nil: "nil"` each wrap a keyword leaf, and both the
// wrapper and the leaf sat in the operand arm — so every
// literal occurrence added +1 to N2. Operands are keyed by
// source text, so the duplicate collapsed into the same
// vocabulary entry and n2 stayed correct, which is why nothing
// caught it.
//
// Source is the issue's reproducer plus a repeat of `true` and
// `nil`, so N2 exceeds n2 and the assertions can tell "counted
// once per occurrence" from "deduplicated into the vocabulary".
// All three keywords appear, so restoring any one of `True`,
// `False`, or `Nil2` to the operand arm trips this test.
//
// Operands by text key: `x`, `y`, `z`, `w`, `v`, `true` × 2,
// `nil` × 2, `false` ⇒ n2 = 8, N2 = 10. Before the fix each of
// the five literals counted twice ⇒ N2 = 15.
//
// This also guards the drift in the other direction. Elixir
// classifies the wrapper and drops the leaf outright rather
// than parent-guarding it, so a grammar bump that stopped
// emitting `boolean` / `nil` would leave the leaves unclassified
// and the literals would vanish from N2 entirely (⇒ 5 / 5)
// rather than merely being miscounted.
check_metrics::<ElixirParser>(
"x = true\ny = nil\nz = false\nw = true\nv = nil\n",
"foo.ex",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 8);
assert_eq!(metric.halstead.total_operands(), 10);
},
);
}
#[test]
fn elixir_reserved_word_after_a_dot_stays_an_operand() {
// Companion to the test above (#1253). Elixir drops `True` /
// `False` / `Nil2` from the operand arm outright, which is only
// safe because the one grammar position that accepts a reserved
// word outside the `boolean` / `nil` wrapper — the right-hand
// side of a remote dot — aliases it to `identifier`. This pins
// that alias: if a grammar bump emitted the bare keyword there
// instead, `Foo.nil` and `Foo.true` would silently stop
// contributing an operand.
//
// Source: a = Foo.nil / b = Foo.true / c = nil
//
// Operands by text key: `a`, `Foo` × 2, `nil` × 2 (the aliased
// identifier and the real literal, which share a text key),
// `b`, `true`, `c` ⇒ n2 = 6, N2 = 8. Losing the alias drops the
// two dotted references ⇒ N2 = 6.
check_metrics::<ElixirParser>("a = Foo.nil\nb = Foo.true\nc = nil\n", "foo.ex", |metric| {
assert_eq!(metric.halstead.unique_operands(), 6);
assert_eq!(metric.halstead.total_operands(), 8);
});
}
#[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.unique_operands(), 5);
assert_eq!(metric.halstead.total_operands(), 6);
},
);
}
#[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.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 5);
},
);
}
#[test]
fn elixir_sigil_delimiters_are_not_operators() {
// Regression: issue #1256. Sigil delimiter tokens share their
// kind ids with real operators (`SLASH`, `LPAREN`, `LBRACE`,
// …) and were classified unconditionally, so `~r/abc/`
// fabricated two division operators and the author's delimiter
// choice moved n1/N1. The parent guard suppresses them under
// `Sigil`; `~` stays the single per-sigil operator.
//
// expected: operators `=` × 3 and `~` × 3 → n1 = 2, N1 = 6.
// Without the guard the delimiters added `/` × 2, `(`, `{` →
// n1 = 5, N1 = 10. Operands: `a`, `~r/abc/i`, `r`, `i` (sigil
// modifiers), `b`, `~w(one two)`, `w`, `c`, `~s{hi}`, `s` →
// n2 = N2 = 10.
check_metrics::<ElixirParser>(
"a = ~r/abc/i\nb = ~w(one two)\nc = ~s{hi}\n",
"foo.ex",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 2);
assert_eq!(metric.halstead.total_operators(), 6);
assert_eq!(metric.halstead.unique_operands(), 10);
assert_eq!(metric.halstead.total_operands(), 10);
},
);
}
#[test]
fn elixir_sigil_delimiter_choice_is_invariant() {
// Companion to the test above (#1256): two sigils differing
// only in delimiter are the same literal, so every delimiter
// choice must produce identical Halstead counts. `(` `[` `{`
// `<` `/` `|` are the operator-kind delimiters the guard
// covers; `"` and `'` never had an operator arm and pin the
// already-correct path.
//
// expected per variant: operators `=`, `~` → n1 = 2, N1 = 2;
// operands `x`, the sigil literal text, `w` (sigil name) →
// n2 = 3, N2 = 3.
for (open, close) in [
("(", ")"),
("[", "]"),
("{", "}"),
("<", ">"),
("/", "/"),
("|", "|"),
("\"", "\""),
("'", "'"),
] {
assert_halstead_counts::<ElixirParser>(
&format!("x = ~w{open}one two{close}\n"),
"foo.ex",
[2, 2, 3, 3],
&format!("delimiter pair {open} {close}"),
);
}
}
#[test]
fn elixir_standalone_operators_survive_the_sigil_guard() {
// Control for #1256: the guard is parent-scoped, so the same
// token kinds outside a sigil still count. Covers every guarded
// kind standalone: `/` (division), `<` / `>` (comparison), `[`
// and `|` (list cons), `(` (call), `{` (map literal, with its
// `%`).
//
// expected: operators `=` × 6, `/`, `<`, `>`, `[`, `|`, `(`,
// `%`, `{` → n1 = 9, N1 = 14. Operands: `x`, `a`, `b`, `y`,
// `c`, `d`, `z`, `e`, `f`, `q`, `h`, `t`, `p`, `g`, `1`, `m`,
// the `k:` keyword, `2` → n2 = N2 = 18.
check_metrics::<ElixirParser>(
"x = a / b\ny = c < d\nz = e > f\nq = [h | t]\np = g(1)\nm = %{k: 2}\n",
"foo.ex",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 9);
assert_eq!(metric.halstead.total_operators(), 14);
assert_eq!(metric.halstead.unique_operands(), 18);
assert_eq!(metric.halstead.total_operands(), 18);
},
);
}
#[test]
fn elixir_interpolated_sigil_keeps_inner_nodes_counting() {
// Interpolation inside a sigil after #1256: the `{` delimiter
// is suppressed (its parent is the `Sigil`), while the
// `interpolation` child is a separate node whose inner
// identifier must still count — the guard must not reach past
// the delimiter tokens.
//
// expected: operators `=`, `~` → n1 = N1 = 2. Operands:
// `v`, `s` (sigil name), `b` (interpolated identifier); the
// wrapping sigil is skipped (`Interpolation` child, #180) and
// `quoted_content` is unclassified → n2 = N2 = 3. The `#{`
// marker was a third operator until #1314 dropped it.
check_metrics::<ElixirParser>("v = ~s{a#{b} c}\n", "foo.ex", |metric| {
assert_eq!(metric.halstead.unique_operators(), 2);
assert_eq!(metric.halstead.total_operators(), 2);
assert_eq!(metric.halstead.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 3);
});
// A guarded kind *inside* the interpolation: the `/` in
// `#{a / b}` has `binary_operator` as its parent but the
// `Sigil` as a further ancestor, so this input is the one
// discriminator between the correct parent-scoped guard and a
// wrong ancestor-scoped one that would swallow it.
//
// expected: operators `=`, `~`, `/` → n1 = N1 = 3 (the `#{`
// opener stopped counting with #1314); operands `v`, `s`, `a`,
// `b` → n2 = N2 = 4. The division is what this row is for, and
// it still counts — the ancestor-scoped mutant drops it.
check_metrics::<ElixirParser>("v = ~s{x #{a / b} y}\n", "foo.ex", |metric| {
assert_eq!(metric.halstead.unique_operators(), 3);
assert_eq!(metric.halstead.total_operators(), 3);
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 4);
});
}
#[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` (its
// inner var_name `v` leaf is suppressed under #695; wrapper
// skipped) → 2
// line 2 `b="${v[0]}"`: var_name `b`, var_name `v` (inside
// subscript — parent is `expansion`, not `simple_expansion`,
// so it still counts), number `0` (wrapper skipped,
// `expansion` itself is not in the operand list) → 3
// line 3 `c="$(date)"`: var_name `c`, the `word` `date` under
// the `command_name` (wrapper skipped, `command_substitution`
// not in operand list, and since #1351 the `command_name`
// wrapper is not either) → 2
// line 4 `d="$((1+2))"`: var_name `d`, numbers `1` and `2`
// (wrapper skipped, `arithmetic_expansion` not in operand
// list) → 3
// Unique operands: a, b, c, d, $v, v, 0, date, 1, 2 → 10. Total
// occurrences: 10 (`v` appears once — only line 2's subscript
// leaf; line 1's `$v` inner leaf is suppressed — and `date` once,
// as the `word`; before #1351 the `command_name` wrapping it
// added a second `date` and N2 was 11). Operators after
// #695: only the openers `[` (folded `[]`) and `+`, plus `=` four
// times — the `}`/`)`/`))`/`]` closers no longer count.
check_metrics::<BashParser>(
"a=\"$v\"\nb=\"${v[0]}\"\nc=\"$(date)\"\nd=\"$((1+2))\"\n",
"foo.sh",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 3);
assert_eq!(metric.halstead.total_operators(), 6);
assert_eq!(metric.halstead.unique_operands(), 10);
assert_eq!(metric.halstead.total_operands(), 10);
},
);
}
/// Regression for #695. A bare `$x` (outside any string) parses as a
/// `simple_expansion` wrapping a `variable_name` leaf — and `$?` / `$1`
/// as a `simple_expansion` wrapping a `special_variable_name` leaf. Both
/// the wrapper and the inner leaf used to be classified as operands, so
/// each bare variable reference double-counted (the same hazard Tcl
/// guards with its `Id2` exclusion and iRules with a parent check). The
/// `variable_name` / `special_variable_name` arm now yields `Unknown`
/// when its parent is a `simple_expansion`, so `$x` contributes exactly
/// one operand while the assignment LHS `variable_name` (`x` in `x=…`,
/// parent is `variable_assignment`) still counts.
#[test]
fn bash_bare_variable_no_double_count() {
let source = "x=1\necho $x\necho $?\n";
let path = PathBuf::from("foo.sh");
let parser = BashParser::new(source.as_bytes().to_vec(), &path, None);
let ops = crate::ops::ops_inner(&parser, None).expect("ops walk succeeds");
let bare_x = ops.operands.iter().filter(|o| o.as_str() == "$x").count();
let special = ops.operands.iter().filter(|o| o.as_str() == "$?").count();
// Each bare reference is exactly one operand; the inner leaf is not
// double-counted. If the guard regressed, the inner `variable_name`
// `x` would add a second `x` occurrence (text-colliding with the
// assignment LHS) and the inner `special_variable_name` `?` would
// appear as a standalone `?` operand.
assert_eq!(
bare_x, 1,
"bare $x must be one operand; operands were {:?}",
ops.operands
);
assert_eq!(
special, 1,
"bare $? must be one operand; operands were {:?}",
ops.operands
);
assert!(
!ops.operands.iter().any(|o| o.as_str() == "?"),
"the inner special_variable_name `?` leaf must be suppressed; operands were {:?}",
ops.operands
);
// The assignment LHS `variable_name` `x` (parent `variable_assignment`,
// not `simple_expansion`) must still be an operand.
assert!(
ops.operands.iter().any(|o| o.as_str() == "x"),
"assignment LHS `x` must still be an operand; operands were {:?}",
ops.operands
);
}
/// Regression for #1351, the command-name sibling of #695's bare
/// `$x`. `command_name` is a pure wrapper: the grammar gives it
/// exactly one required child (a `_primary_expression` or a
/// `concatenation`) and it adds no text of its own, so classifying it
/// as an operand *and* letting the walk reach the child counted every
/// command name twice in `N2`.
///
/// The table is the grammar-dispatch §6 evidence that deleting the arm
/// zeroes nothing: it names every kind `command_name` can wrap, and in
/// every row the command name still contributes at least one operand
/// once the trailing `arg` is discounted.
///
/// `n2_before` / `N2_before` are what each row measured with the
/// wrapper arm in place. They are not free-floating prose — the loop
/// re-derives both from the current parse, because the arm was the
/// only difference between the two classifications:
///
/// - `N2_before - N2` must equal the number of `command_name` nodes.
/// That identity *is* the defect: one spurious operand per command
/// name.
/// - `n2_before` must equal the size of the post-fix operand
/// vocabulary unioned with the `command_name` spellings. It exceeds
/// `n2` wherever the wrapper's whole text is not already an operand
/// in its own right — either because it differs from its single
/// child's (`"$cmd"`, `${cmd}`) or because it spans several
/// (`foo$x`, `$(which ls)`, `{1..3}`).
///
/// A mistyped or stale column therefore fails rather than misinforming
/// the next reader; one did, during review of this very fix.
#[test]
fn bash_command_name_wrapper_no_double_count() {
// (source, [n1, N1, n2, N2], (n2_before, N2_before))
let cases: [(&str, [u64; 4], (u64, u64)); 14] = [
// word
("ls bar\n", [0, 0, 2, 2], (2, 3)),
// number
("1 arg\n", [0, 0, 2, 2], (2, 3)),
// string, inert
("\"ls\" arg\n", [0, 0, 2, 2], (2, 3)),
// string wrapping an expansion: the wrapper string is already
// skipped (#180), so before #1351 the `command_name` was the
// only thing counting the quoted spelling — which also planted
// a spurious `"$cmd"` entry in n2 beside `$cmd`.
("\"$cmd\" arg\n", [0, 0, 2, 2], (3, 3)),
// raw_string
("'ls' arg\n", [0, 0, 2, 2], (2, 3)),
// ansi_c_string
("$'ls' arg\n", [0, 0, 2, 2], (2, 3)),
// translated_string. FIXME(#1358): N2 3 rather than 2 because
// a `translated_string` wraps a `string` and both are
// operands — the same wrapper/leaf shape as this fix, in the
// same match, but reachable from an assignment RHS and a
// `case` subject as well, so it is its own change. This row
// pins today's wrong value; flip it with #1358.
("$\"ls\" arg\n", [0, 0, 3, 3], (3, 4)),
// simple_expansion
("$cmd arg\n", [0, 0, 2, 2], (2, 3)),
// brace expansion: counts through its inner `variable_name`,
// whose `SimpleExpansion` parent guard does not apply here.
("${cmd} arg\n", [0, 0, 2, 2], (3, 3)),
// command_substitution: counts through the nested command.
// Two command names here — the outer one and `which`.
("$(which ls) arg\n", [0, 0, 3, 3], (4, 5)),
// process_substitution, likewise two command names.
("<(ls) arg\n", [0, 0, 2, 2], (3, 4)),
// arithmetic_expansion
("$((1+1)) arg\n", [1, 1, 2, 3], (3, 4)),
// brace_expression
("{1..3} arg\n", [1, 1, 3, 3], (4, 4)),
// concatenation
("foo$x arg\n", [0, 0, 3, 3], (4, 4)),
];
let path = PathBuf::from("foo.sh");
for (source, expected, (n2_before, total_before)) in cases {
let code = source.as_bytes();
let parser = BashParser::new(code.to_vec(), &path, None);
let spellings: Vec<&str> = parser
.root()
.preorder()
.filter(|node| node.kind_id() == Bash::CommandName as u16)
.filter_map(|node| node.utf8_text(code))
.collect();
assert!(
!spellings.is_empty(),
"row {source:?} parses without a command_name, so it \
witnesses nothing",
);
// Phrased as an addition rather than `total_before -
// expected[3]`: a future edit that inverts the two would
// underflow `u64` and panic with a raw overflow message
// instead of the one below.
assert_eq!(
total_before,
expected[3] + spellings.len() as u64,
"row {source:?} must shed exactly one operand per \
command_name; recorded N2_before {total_before}",
);
let ops = crate::ops::ops_inner(&parser, None).expect("ops walk succeeds");
let mut vocabulary: HashSet<&str> = ops.operands.iter().map(String::as_str).collect();
vocabulary.extend(spellings);
assert_eq!(
vocabulary.len() as u64,
n2_before,
"row {source:?}: n2 before the fix is the post-fix \
vocabulary plus the command_name spellings; got \
{vocabulary:?}",
);
assert!(
expected[3] > 1,
"row {source:?} must leave the command name at least one \
operand beside `arg`; a zero here means the deleted arm \
was load-bearing for this spelling",
);
assert_halstead_counts::<BashParser>(source, "foo.sh", expected, source);
}
}
/// Pins the one residue of #1351: a brace `expansion` with no
/// `variable_name` leaf. `${#}` (positional-parameter count) and `${!}`
/// (last background PID) hold only anonymous tokens, and
/// `Bash::Expansion` is not an operand, so the whole expansion
/// contributes nothing.
///
/// That was already true in *argument* position before the fix, which
/// is the reason grammar-dispatch §6's gate-don't-delete rule did not
/// apply to the `command_name` arm: deleting it made command-name
/// position agree with argument position rather than newly disagree.
/// The parity is the load-bearing half of that argument and nothing
/// else asserts it, so if a future arm starts classifying these the
/// two positions have to move together.
#[test]
fn bash_operandless_expansion_scores_alike_in_both_positions() {
// `${!}` carries a `!`, which the operator arm counts; `${#}`'s `#`
// is not an operator. Both positions must agree per spelling.
for (spelling, expected) in [("${#}", [0, 0, 1, 1]), ("${!}", [1, 1, 1, 1])] {
let as_command_name = format!("{spelling} arg\n");
let as_argument = format!("cmd {spelling}\n");
assert_halstead_counts::<BashParser>(
&as_command_name,
"foo.sh",
expected,
&as_command_name,
);
assert_halstead_counts::<BashParser>(&as_argument, "foo.sh", expected, &as_argument);
}
}
/// Drift marker for #1351 (lesson 34 / grammar-dispatch §2). `_concat`
/// (`Bash::Concat`) is a hidden zero-width external token the scanner
/// emits between `concatenation` parts; the parser never surfaces it as
/// a node, and it spells no operand, so `BashCode::get_op_type` lists
/// neither it nor the visible `concatenation` wrapper. If a grammar
/// bump starts emitting it, this fails and the classification must be
/// re-derived rather than assumed still absent.
///
/// Measured, not assumed: putting `Bash::Concat` back in the operand
/// arm fails no test in the suite, because the token is unreachable.
/// Unreachability is the only coverage such an arm can have, which is
/// why this test asserts it directly instead of asserting a count.
#[test]
fn bash_hidden_concat_token_is_unreachable() {
let source = "a=foo$x\nb=pre\"$y\"post\ncmd bar$z\n";
let path = PathBuf::from("foo.sh");
let parser = BashParser::new(source.as_bytes().to_vec(), &path, None);
// Non-vacuity: the visible `concatenation` this source is written
// to produce must actually be in the parse, so the negative below
// is about `_concat` and not about a source that concatenates
// nothing.
assert!(
ast_has_kind_id(&parser, Bash::Concatenation as u16),
"expected a visible `concatenation` node in the parse",
);
assert!(
!ast_has_kind_id(&parser, Bash::Concat as u16),
"the hidden `_concat` token surfaced; re-derive its \
classification in BashCode::get_op_type against the new grammar",
);
}
#[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| {
// Anchored per the snapshot policy in AGENTS.md, which
// this call predates. Operators `proc`, `set`, `[]`,
// `{}`, `expr`, `+`, `if`, `>`, `&&`, `!=` → n1 = 10,
// N1 = 14 (`{}` × 4 for the proc parameter list, the
// proc body, the two `expr`/`if` conditions and the
// `if` body — the `expr` braces are an `Expr`, the
// bodies a `BracedWord`). Operands `f`, `a`, `b`, `x`,
// `$a`, `$b`, `$x`, `0` and `return` → n2 = 9,
// N2 = 14. Before #1354 the proc body and the `if`
// body were operands too → 11 / 16.
assert_eq!(metric.halstead.unique_operators(), 10);
assert_eq!(metric.halstead.total_operators(), 14);
assert_eq!(metric.halstead.unique_operands(), 9);
assert_eq!(metric.halstead.total_operands(), 14);
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| {
// Anchored per the snapshot policy in AGENTS.md, which
// this call predates. N1 fell 33 → 31 with #1314: the
// `if` condition's `{x}` and `{y}` are braced *words*,
// so their openers stopped fabricating a `{}` operator.
// n1 is unchanged at 18 because the `{}` entry survives
// on the proc body and the `expr` braces — which is
// exactly why the fabrication was invisible in n1 and
// is the reason to assert N1 as well (#1294).
//
// The operand columns fell 17 / 30 → 13 / 26 with
// #1354, and the operator columns did not move: the two
// script bodies (the proc's and the `if`'s) stopped
// being operands, and the `x` / `y` inside the braced
// words `{x}` and `{y}` are now part of the one operand
// each word contributes.
assert_eq!(metric.halstead.unique_operators(), 18);
assert_eq!(metric.halstead.total_operators(), 31);
assert_eq!(metric.halstead.unique_operands(), 13);
assert_eq!(metric.halstead.total_operands(), 26);
insta::assert_json_snapshot!(metric.halstead);
},
);
}
#[test]
fn tcl_array_reference_bills_the_reference_and_the_index() {
// `$arr($i)` is the reference plus the index Tcl substitutes
// inside the parens, and `arr(k)` as a `set` target is the name
// plus the literal index; the `array_index` wrapper is neither.
// The quoted spelling is deliberate — the vendored grammar
// mis-parses a bare `$arr(k)` in command-word position. Pinned
// per dialect and as a parity in `tests/parity/`, because the
// iRules twin listed the wrapper as a third operand.
assert_ops_operands::<TclParser>(
"set arr(k) 1\nset z \"$arr($i)\"\n",
"foo.tcl",
6,
vec!["arr", "k", "1", "z", "$arr($i)", "$i"],
);
}
#[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| {
// Anchored per the snapshot policy in AGENTS.md, which
// this call predates. Operators `proc` and `{}` × 2
// (the parameter list and the body) → n1 = 2, N1 = 3.
// Operands `f`, the parameter `x`, `return` and `$x` —
// one occurrence each, so a re-counted `x` leaf inside
// `$x` would show up in N2 even though it collides with
// the parameter in n2. Before #1354 the proc body was a
// fifth operand.
assert_eq!(metric.halstead.unique_operators(), 2);
assert_eq!(metric.halstead.total_operators(), 3);
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 4);
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`, the `set` target `s`, `"hello world"` —
// 3 unique, 3 total. Before #1294 this read 3/3 for a
// different reason, with `s` missing and the proc-body
// `braced_word` making the count coincidentally
// plausible; #1354 removed that body operand, so the
// three named here are now the whole list. 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.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 3);
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), the `set` target
// `s`, `$x`, `$y` — 6 unique, 6 total. The wrapping
// `QuotedWord` contributes nothing, and since #1354
// neither does the proc-body `braced_word`. Before #277
// the wrapper double-counted.
assert_eq!(metric.halstead.unique_operands(), 6);
assert_eq!(metric.halstead.total_operands(), 6);
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`, the `set` target `s`, `foo` — 3 unique,
// 3 total. The wrapping `QuotedWord` and the inert text
// `result: ` do not contribute extra operands, and since
// #1354 neither does the proc-body `braced_word`. Before
// #277 the wrapper double-counted.
assert_eq!(metric.halstead.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 3);
insta::assert_json_snapshot!(metric.halstead);
},
);
}
/// Regression for #1294. The `set` target parses as the anonymous
/// `id` token (`Tcl::Id2`) — the same kind as the leaf inside a
/// `variable_substitution` — and the getter used to exclude that kind
/// wholesale, so every variable a Tcl script assigned was absent from
/// n2/N2. The guard is now parent-scoped: a target `id` counts, a
/// var-sub leaf does not. Exact occurrence counts distinguish this
/// fix from a regression in either direction: a re-blanketed
/// exclusion drops `s`/`t` (total 2), while losing the guard
/// double-counts the `$s` leaf as a second `s` (total 5).
#[test]
fn tcl_set_target_is_operand() {
let source = "set s 1\nset t $s\n";
let path = PathBuf::from("foo.tcl");
let parser = TclParser::new(source.as_bytes().to_vec(), &path, None);
let ops = crate::ops::ops_inner(&parser, None).expect("ops walk succeeds");
// expected operands: targets `s` and `t`, literal `1`, reference
// `$s` (wrapper only) — 4 total, each exactly once.
for operand in ["s", "t", "1", "$s"] {
assert_eq!(
ops.operands
.iter()
.filter(|o| o.as_str() == operand)
.count(),
1,
"`{operand}` must be exactly one operand; operands were {:?}",
ops.operands
);
}
assert_eq!(
ops.operands.len(),
4,
"operands must be exactly s, t, 1, $s; got {:?}",
ops.operands
);
check_metrics::<TclParser>(source, "foo.tcl", |metric| {
// expected: n2 = 4 (s, t, 1, $s), N2 = 4; operators are the
// two `set` keywords — n1 = 1, N1 = 2.
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 4);
assert_eq!(metric.halstead.unique_operators(), 1);
assert_eq!(metric.halstead.total_operators(), 2);
});
}
/// Drift marker for #1294 (lesson 34 / grammar-dispatch §2): the
/// *named* `id` rule (`Tcl::Id`, kind_id 84) never surfaces at the
/// pinned tree-sitter-tcl — the parser emits the anonymous `Id2` in
/// both positions the getter guards (the `set` target and the
/// var-sub leaf). The `Tcl::Id` arm in `get_op_type` is therefore
/// defensive; if a grammar bump starts emitting 84 this fails and
/// the arm's classification must be re-derived instead of trusted.
#[test]
fn tcl_named_id_variant_is_unreachable() {
let source = "proc f {x} {\n set s $x\n foreach v {1 2} { puts \"$v\" }\n}\n";
let path = PathBuf::from("foo.tcl");
let parser = TclParser::new(source.as_bytes().to_vec(), &path, None);
// Non-vacuity: the anonymous token must be present in this parse
// (both the `set` target and the `$x` / `$v` leaves emit it).
assert!(
ast_has_kind_id(&parser, Tcl::Id2 as u16),
"expected the anonymous Tcl::Id2 token to appear in the parse",
);
assert!(
!ast_has_kind_id(&parser, Tcl::Id as u16),
"the named Tcl::Id rule surfaced; re-derive the defensive \
`Tcl::Id` arm in TclCode::get_op_type against the new grammar",
);
}
#[test]
fn tcl_braced_word_delimiter_is_not_an_operator() {
// Regression: issue #1314, the Tcl sibling of Elixir #1256 and
// Ruby/Perl #1312. A braced *word* — a literal value, not a
// script — carries its `{` as an `LBRACE` child, the kind id a
// real block uses, so `set a {braced word}` reported a `{}`
// operator with no block in the source.
//
// expected: operator `set` × 3 → n1 = 1, N1 = 3. Operands
// `a`, `b`, `c`, `$a` and `{braced word}` × 2 → n2 = 5,
// N2 = 6. Before the guard the two openers added `{}` →
// n1 = 2, N1 = 5; before #1354 the inner `braced` / `word`
// counted alongside the word containing them → n2 = 7,
// N2 = 10.
check_metrics::<TclParser>(
"set a {braced word}\nset b {braced word}\nset c $a\n",
"foo.tcl",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 1);
assert_eq!(metric.halstead.total_operators(), 3);
assert_eq!(metric.halstead.unique_operands(), 5);
assert_eq!(metric.halstead.total_operands(), 6);
},
);
}
#[test]
fn tcl_script_bodies_keep_their_braces() {
// Control for #1314, and the reason a kind-scoped guard is safe
// in Tcl where it would not be elsewhere: the grammar gives the
// literal and the block *different* kinds. A `proc` body, an
// `if` body and an `if` condition are `BracedWord` (88) and
// `Expr` (97); only the value form is `BracedWordSimple` (89).
// This fixture nests a braced word inside a real script body,
// so a guard that keyed on the brace alone would drop the
// block's `{}` and fail here.
//
// expected: operators `proc`, `set` × 2, `if`, `>`, and `{}`
// × 4 (the proc parameter list, the proc body, the `if`
// condition, the `if` body) → n1 = 5, N1 = 9. Operands, all
// distinct → n2 = N2 = 8: `p`, `x`, `a`, `$x`, `1`, `b` and
// the two braced *words* `{v w}` and `{y}`, each one operand
// rather than one per inner word.
//
// Before #1354 this read 13 / 13. The five extra entries were
// the inner words `v`, `w`, `y` and the two *script* bodies,
// which were `BracedWord` operands in their own right — so a
// block counted twice over, once as the operand and once as
// the `{}` operator this test is about. Both halves are gone;
// the operator columns are what this test guards and they did
// not move.
check_metrics::<TclParser>(
"proc p {x} {\n set a {v w}\n if {$x > 1} { set b {y} }\n}\n",
"foo.tcl",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 5);
assert_eq!(metric.halstead.total_operators(), 9);
assert_eq!(metric.halstead.unique_operands(), 8);
assert_eq!(metric.halstead.total_operands(), 8);
},
);
}
#[test]
fn tcl_braced_word_guard_is_parent_scoped_not_ancestor_scoped() {
// The input that separates the parent-scoped guard from the
// ancestor-scanning mutant. I first recorded this distinction
// as *unobservable* in Tcl, reasoning that a braced word holds
// only simple words and nested braced words. `bca dump` says
// otherwise: the grammar parses a `[…]` command substitution
// inside a braced word, and the `if` inside it brings an `Expr`
// condition and a `BracedWord` body, each with its own `{`,
// both of them non-immediate descendants of the
// `BracedWordSimple`. An ancestor scan swallows both.
//
// (Real Tcl does not substitute inside braces — this is the
// grammar modelling structure it will not evaluate. What the
// classifier sees is what the metric reports, so it is the
// right fixture regardless.)
//
// expected: operators `set`, `[]`, `if`, and `{}` × 2 (the
// `if` condition's `Expr` and its `BracedWord` body; the outer
// value word's own `{` is suppressed) → n1 = 4, N1 = 5.
// Operands `z`, the whole braced word, and `$q` / `puts` / `w`
// from inside the command substitution → n2 = N2 = 5. Under
// the ancestor-scoped mutant both surviving braces vanish:
// n1 = 3, N1 = 3.
//
// #1354 widened the guard from the `{` alone to every direct
// child of the braced word, which is why `x` and `v` are no
// longer operands and the nested script body no longer is
// either. It did not change the *scope*: the three operands
// from inside the command substitution are grandchildren, and
// an ancestor-scoped guard would drop them too.
check_metrics::<TclParser>("set z {x [if {$q} {puts w}] v}\n", "foo.tcl", |metric| {
assert_eq!(metric.halstead.unique_operators(), 4);
assert_eq!(metric.halstead.total_operators(), 5);
assert_eq!(metric.halstead.unique_operands(), 5);
assert_eq!(metric.halstead.total_operands(), 5);
});
}
#[test]
fn irules_braced_word_guard_is_parent_scoped_not_ancestor_scoped() {
// The iRules twin of the test above — the two getters are
// clones, so the mutant must fail in both.
//
// expected: operators `when`, `set`, `[]`, `if`, `{}` × 3 (the
// handler body, the `if` condition and the `if` body) → n1 = 5,
// N1 = 7. Operands `HTTP_REQUEST`, `z`, the whole braced word,
// and `$q` / `log` / `w` from inside the command substitution →
// n2 = N2 = 6 (10 before #1354, which also took the direct
// children `x` / `v` and the two script bodies out of the
// operand set without moving the operator columns this test
// guards).
check_metrics::<IrulesParser>(
"when HTTP_REQUEST {\n set z {x [if {$q} {log w}] v}\n}\n",
"foo.irule",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 5);
assert_eq!(metric.halstead.total_operators(), 7);
assert_eq!(metric.halstead.unique_operands(), 6);
assert_eq!(metric.halstead.total_operands(), 6);
},
);
}
/// How one dialect of the Tcl family spells the braced-word
/// construct. The two grammars are deliberate clones with different
/// id blocks, so #1354's guard is derived once and instantiated
/// twice — and a fix that landed in only one dialect fails the
/// second instantiation rather than going unnoticed.
struct BracedWordKinds {
/// `braced_word_simple`, the literal *value* form the guard
/// keys on.
wrapper: u16,
/// `braced_word`, the *script* form #1354 gated on holding a
/// command: an operand only when it holds none.
script_body: u16,
/// `comment`, the one named child of a script that is not a
/// command and that the gate must not mistake for one.
comment: u16,
/// Every named kind node-types.json admits directly inside
/// `wrapper`. A child outside this set means the grammar moved
/// and the parent-keyed arm has to be re-derived
/// (grammar-dispatch §1).
children: [u16; 6],
/// The `{` / `}` the wrapper also holds. Suppressing the opener
/// was the whole of #1314's narrower guard; the closer has
/// never been classified, since `get_operator_id_as_str` folds
/// the pair to one `{}` glyph.
delimiters: [u16; 2],
/// Of `children`, the three the operand arm classified
/// unconditionally before the guard.
operand_children: [u16; 3],
/// `quoted_word`, which was an operand only when *inert* —
/// `string_operand_type`'s own rule, replicated here so the
/// shed count below is what `N2` actually shed.
quoted_word: u16,
/// The interpolation kinds that decide that.
interpolation: [u16; 2],
}
const TCL_BRACED_WORD_KINDS: BracedWordKinds = BracedWordKinds {
wrapper: Tcl::BracedWordSimple as u16,
script_body: Tcl::BracedWord as u16,
comment: Tcl::Comment as u16,
children: [
Tcl::SimpleWord as u16,
Tcl::EscapedCharacter as u16,
Tcl::QuotedWord as u16,
Tcl::VariableSubstitution as u16,
Tcl::CommandSubstitution as u16,
Tcl::BracedWordSimple as u16,
],
delimiters: [Tcl::LBRACE as u16, Tcl::RBRACE as u16],
operand_children: [
Tcl::SimpleWord as u16,
Tcl::VariableSubstitution as u16,
Tcl::BracedWordSimple as u16,
],
quoted_word: Tcl::QuotedWord as u16,
interpolation: [
Tcl::VariableSubstitution as u16,
Tcl::CommandSubstitution as u16,
],
};
const IRULES_BRACED_WORD_KINDS: BracedWordKinds = BracedWordKinds {
wrapper: Irules::BracedWordSimple as u16,
script_body: Irules::BracedWord as u16,
comment: Irules::Comment as u16,
children: [
Irules::SimpleWord as u16,
Irules::EscapedCharacter as u16,
Irules::QuotedWord as u16,
Irules::VariableSubstitution as u16,
Irules::CommandSubstitution as u16,
Irules::BracedWordSimple as u16,
],
delimiters: [Irules::LBRACE as u16, Irules::RBRACE as u16],
operand_children: [
Irules::SimpleWord as u16,
Irules::VariableSubstitution as u16,
Irules::BracedWordSimple as u16,
],
quoted_word: Irules::QuotedWord as u16,
interpolation: [
Irules::VariableSubstitution as u16,
Irules::CommandSubstitution as u16,
],
};
/// The operand occurrences #1354 removed from `source`, as their
/// source texts, plus the set of `braced_word_simple` child kinds
/// the fixture witnessed.
///
/// Walks with `for_each_node_with_chain`, which maintains the
/// ancestor chain exactly as `spaces::compute` does, so "parent"
/// here means what `Ancestors::parent` means inside the guard.
/// Doubles as the grammar-dispatch §1 / §2 drift marker: a child of
/// the wrapper outside `children` ∪ `delimiters` fails on the spot,
/// which is what makes keying the arm on the parent alone — rather
/// than on an enumerated child list — safe to rely on.
fn braced_word_shed<L: crate::LanguageInfo>(
source: &str,
kinds: &BracedWordKinds,
) -> (Vec<String>, HashSet<u16>) {
let code = source.as_bytes();
let mut shed = Vec::new();
let mut witnessed = HashSet::new();
for_each_node_with_chain::<L>(code, |node, chain| {
let text = || {
node.utf8_text(code)
.expect("fixture is valid UTF-8")
.to_owned()
};
// The script form was an operand of its own wherever it
// appeared until #1354, which now gates it on holding a
// command — a named child that is not a comment. This is not
// a child of the wrapper, so it is counted before the parent
// test below.
if node.kind_id() == kinds.script_body
&& node
.children()
.any(|child| child.is_named() && child.kind_id() != kinds.comment)
{
shed.push(text());
}
if chain.last().is_none_or(|p| p.kind_id() != kinds.wrapper) {
return;
}
assert!(
kinds.children.contains(&node.kind_id())
|| kinds.delimiters.contains(&node.kind_id()),
"`{source}`: a `{}` inside a braced word is a child this guard \
was not derived against; re-read node-types.json before \
trusting it",
node.kind(),
);
if kinds.children.contains(&node.kind_id()) {
witnessed.insert(node.kind_id());
}
let was_operand = kinds.operand_children.contains(&node.kind_id())
|| (node.kind_id() == kinds.quoted_word && !node.wraps_any(&kinds.interpolation));
if was_operand {
shed.push(text());
}
});
(shed, witnessed)
}
/// One row of the #1354 tables: a fixture, what it measures now,
/// what it measured before, and the operand texts behind the counts.
struct BracedWordCase {
source: &'static str,
/// `[n1, N1, n2, N2]` with the guard in place.
counts: [u64; 4],
/// `[n2, N2]` without it. Re-derived by the loop rather than
/// trusted, so a stale row fails instead of misinforming.
before: [u64; 2],
operands: &'static [&'static str],
}
/// Every row is measured in *both* dialects, so a fix applied to
/// one getter and not its clone fails here. `braced_word_shed`'s
/// drift assertion likewise runs against both grammars.
fn check_braced_word_cases<T: crate::ParserTrait, L: crate::LanguageInfo>(
cases: &[BracedWordCase],
file: &str,
kinds: &BracedWordKinds,
) -> HashSet<u16> {
let mut witnessed = HashSet::new();
for case in cases {
let (shed, seen) = braced_word_shed::<L>(case.source, kinds);
witnessed.extend(seen);
// Phrased as an addition rather than a subtraction so a
// future edit that inverts the two underflows nothing.
assert_eq!(
case.before[1],
case.counts[3] + shed.len() as u64,
"{file} `{}`: N2 must shed exactly one occurrence per \
previously-billed part; recorded {}, parts {shed:?}",
case.source,
case.before[1],
);
let mut vocabulary: HashSet<&str> = case.operands.iter().copied().collect();
vocabulary.extend(shed.iter().map(String::as_str));
assert_eq!(
vocabulary.len() as u64,
case.before[0],
"{file} `{}`: n2 before the fix is the post-fix vocabulary \
plus those parts; got {vocabulary:?}",
case.source,
);
assert_halstead_counts::<T>(case.source, file, case.counts, case.source);
assert_ops_operands::<T>(
case.source,
file,
case.operands.len(),
case.operands.to_vec(),
);
}
witnessed
}
/// The rows shared by both dialects: one per named child kind
/// `braced_word_simple` admits, the childless spelling, the
/// repeated-value row that separates `n2` from `N2` (#1294), and
/// the braced/quoted parity pair #1317 asks for.
const BRACED_WORD_CASES: [BracedWordCase; 11] = [
// simple_word, the reported fixture. Two words inside one
// value scored two operands beside the value itself.
BracedWordCase {
source: "set x {literal here}\n",
counts: [1, 1, 2, 2],
before: [4, 4],
operands: &["x", "{literal here}"],
},
// The childless spelling, and the reason the wrapper is kept
// rather than dropped in favour of its contents
// (grammar-dispatch §6): with nothing inside, the wrapper is
// the empty string's only carrier. Nothing is shed here, so
// this row asserts the two columns agree.
BracedWordCase {
source: "set y {}\n",
counts: [1, 1, 2, 2],
before: [2, 2],
operands: &["y", "{}"],
},
// braced_word_simple inside braced_word_simple: the nesting
// that makes the over-count unbounded in depth. One value
// spelled six vocabulary entries.
BracedWordCase {
source: "set a {x {y z}}\n",
counts: [1, 1, 2, 2],
before: [6, 6],
operands: &["a", "{x {y z}}"],
},
// quoted_word, inert — an operand in its own right elsewhere,
// and shed here.
BracedWordCase {
source: "set a {x \"q w\" v}\n",
counts: [1, 1, 2, 2],
before: [5, 5],
operands: &["a", "{x \"q w\" v}"],
},
// quoted_word carrying an interpolation, which was *not* an
// operand before the guard either (`string_operand_type` had
// already suppressed it) — so only `x` and `v` are shed. Its
// `$q` is a grandchild of the braced word and still counts,
// which is the parent-scoping this arm inherits from #1314.
BracedWordCase {
source: "set a {x \"$q\" v}\n",
counts: [1, 1, 3, 3],
before: [5, 5],
operands: &["a", "$q", "{x \"$q\" v}"],
},
// escaped_character, never classified — so it sheds nothing
// and the row measures the two `simple_word`s around it.
BracedWordCase {
source: "set a {x \\n y}\n",
counts: [1, 1, 2, 2],
before: [4, 4],
operands: &["a", "{x \\n y}"],
},
// variable_substitution. Tcl substitutes nothing between
// braces, so `{$x}` is the two-character string `$x` — the row
// that makes "the wrapper is the value" more than a tie-break.
BracedWordCase {
source: "set a {$x}\n",
counts: [1, 1, 2, 2],
before: [3, 3],
operands: &["a", "{$x}"],
},
// command_substitution, likewise never an operand itself. Its
// interior is, and stays so: `$q`, `puts` and `w` are
// grandchildren. The nested `{puts w}` is a *script* body and
// sheds under the other half of #1354.
BracedWordCase {
source: "set z {x [if {$q} {puts w}] v}\n",
counts: [4, 5, 5, 5],
before: [8, 8],
operands: &["z", "$q", "puts", "w", "{x [if {$q} {puts w}] v}"],
},
// The same value twice: n2 3 against N2 4, so a row that
// asserted only the vocabulary could not tell the two axes
// apart (#1294).
BracedWordCase {
source: "set a {b c}\nset d {b c}\n",
counts: [1, 2, 3, 4],
before: [5, 8],
operands: &["a", "d", "{b c}"],
},
// The parity pair #1317 named: two spellings of one literal
// value must score alike. They did not before — braced 4 / 4
// against quoted 2 / 2 — which is the spelling sensitivity
// #695, #1312 and #1314 each removed elsewhere.
BracedWordCase {
source: "set a {one two}\n",
counts: [1, 1, 2, 2],
before: [4, 4],
operands: &["a", "{one two}"],
},
BracedWordCase {
source: "set a \"one two\"\n",
counts: [1, 1, 2, 2],
before: [2, 2],
operands: &["a", "\"one two\""],
},
];
/// The script half of #1354, shared by both dialects: a
/// `braced_word` holding commands is a block whose contents the
/// walk already counts, so it is no longer also an operand
/// spanning the whole block.
///
/// The three childless rows are the gate, and the reason this is a
/// gate and not a deletion (grammar-dispatch §6). `braced_word` is
/// not only the script kind: it is the value slot of every command
/// the grammar does not special-case, where `lappend l {}` is an
/// empty list whose brace pair is its only carrier. Deleting the
/// kind scored that zero while its `lappend l ""` synonym — the
/// last row, the control — scored one. An empty `proc` body is
/// spelled identically and so also keeps an operand; no
/// kind-scoped arm can separate the two roles.
const SCRIPT_BODY_CASES: [BracedWordCase; 9] = [
BracedWordCase {
source: "proc p {} { set b 1 }\n",
counts: [3, 4, 3, 3],
before: [4, 4],
operands: &["p", "b", "1"],
},
BracedWordCase {
source: "proc p {} {}\n",
counts: [2, 3, 2, 2],
before: [2, 2],
operands: &["p", "{}"],
},
// A comment is a named child of the script but not a command,
// and no arm bills it, so a comment-only body scores like the
// empty one above rather than like nothing: the block's whole
// text is its one operand. Gating on "any named child" billed
// it zero — adding a comment to an empty block lowered N2.
BracedWordCase {
source: "proc p {} {\n # only a comment\n}\n",
counts: [2, 3, 2, 2],
before: [2, 2],
operands: &["p", "{\n # only a comment\n}"],
},
BracedWordCase {
source: "if {$q} {\n # noop\n}\n",
counts: [2, 3, 2, 2],
before: [2, 2],
operands: &["$q", "{\n # noop\n}"],
},
// The control: a comment *beside* a command changes nothing, so a
// gate keyed on "contains a comment" would fail this row.
BracedWordCase {
source: "proc p {} {\n # c\n set b 1\n}\n",
counts: [3, 4, 3, 3],
before: [4, 4],
operands: &["p", "b", "1"],
},
// The value-role twin: inside a literal string Tcl performs no
// substitution, so `# x` is not a comment at all, and the word
// is its one operand exactly as `lappend l {}` below is.
BracedWordCase {
source: "lappend l {\n # x\n}\n",
counts: [1, 1, 3, 3],
before: [3, 3],
operands: &["lappend", "l", "{\n # x\n}"],
},
// A `braced_word` in *value* position — the #1318 misparse,
// where the same kind carries a literal list. Its interior
// words counted before and still do; only the whole-block
// operand that was double-billing them is gone.
BracedWordCase {
source: "lappend l {a b}\n",
counts: [1, 1, 4, 4],
before: [5, 5],
operands: &["lappend", "l", "a", "b"],
},
// …and the childless spelling of that value, which sheds
// nothing: the brace pair is the empty list's only carrier.
BracedWordCase {
source: "lappend l {}\nreturn {}\n",
counts: [1, 2, 4, 5],
before: [4, 5],
operands: &["lappend", "l", "return", "{}"],
},
// The control the row above is measured against: the quoted
// spelling of the same empty value, which never depended on
// the arm and must keep scoring one operand.
BracedWordCase {
source: "lappend l \"\"\nreturn \"\"\n",
counts: [0, 0, 4, 5],
before: [4, 5],
operands: &["lappend", "l", "return", "\"\""],
},
];
/// The table must exercise every named child kind the grammar
/// admits inside a braced word, and no other — the other half of
/// the drift marker in `braced_word_shed`, which can only police
/// kinds a fixture actually produces.
fn assert_braced_word_children_witnessed(
witnessed: &HashSet<u16>,
kinds: &BracedWordKinds,
dialect: &str,
) {
let mut got: Vec<u16> = witnessed.iter().copied().collect();
got.sort_unstable();
let mut expected = kinds.children;
expected.sort_unstable();
assert_eq!(
got.as_slice(),
expected.as_slice(),
"{dialect}: the fixtures must witness every child kind \
node-types.json admits inside a braced word",
);
}
/// Regression for #1354 and #1317. `braced_word_simple` is a
/// literal value and `braced_word` a script, and both were
/// operands *beside* the content the walk counts anyway: a braced
/// word was billed once per inner word plus once for itself, and a
/// block once for every command in it plus once for its whole
/// text. `set x {literal here}` scored n2 4 / N2 4 for one value.
/// The name is the invariant either way — the value's content is
/// the literal, the script's is its commands, and each is billed
/// once.
///
/// Each row's `before` column is re-derived by the loop from the
/// current parse rather than trusted. That derivation is a replica
/// of the pre-#1354 arms and could in principle drift from what
/// they did, so every column was also measured directly against a
/// build of the old getters — `lappend l {a b}` at n2 5 / N2 5,
/// `lappend l {}` at 4 / 5, `proc p {} {}` at 2 / 2 — rather than
/// derived only from the model here.
///
/// The same walk doubles as the drift marker for the parent-keyed
/// arm: it fails if the grammar ever puts a seventh kind directly
/// inside a braced word, and the union assertion below fails if a
/// bump stops emitting one of the six.
#[test]
fn tcl_braced_word_bills_its_content_once_1354() {
let mut witnessed = check_braced_word_cases::<TclParser, TclCode>(
&BRACED_WORD_CASES,
"foo.tcl",
&TCL_BRACED_WORD_KINDS,
);
witnessed.extend(check_braced_word_cases::<TclParser, TclCode>(
&SCRIPT_BODY_CASES,
"foo.tcl",
&TCL_BRACED_WORD_KINDS,
));
assert_braced_word_children_witnessed(&witnessed, &TCL_BRACED_WORD_KINDS, "tcl");
}
/// The iRules twin. The tables are shared, so a fix that reached
/// only `src/getter/tcl.rs` fails every row here — the two getters
/// are deliberate clones and #1354 names both.
#[test]
fn irules_braced_word_bills_its_content_once_1354() {
let mut witnessed = check_braced_word_cases::<IrulesParser, IrulesCode>(
&BRACED_WORD_CASES,
"foo.irule",
&IRULES_BRACED_WORD_KINDS,
);
witnessed.extend(check_braced_word_cases::<IrulesParser, IrulesCode>(
&SCRIPT_BODY_CASES,
"foo.irule",
&IRULES_BRACED_WORD_KINDS,
));
// The `when` handler body is the iRules-only spelling of a
// script body, and the largest instance of the defect: its
// operand text was the entire event handler.
let handlers: [BracedWordCase; 3] = [
BracedWordCase {
source: "when HTTP_REQUEST { set x 1 }\n",
counts: [3, 3, 3, 3],
before: [4, 4],
operands: &["HTTP_REQUEST", "x", "1"],
},
BracedWordCase {
source: "when HTTP_REQUEST {}\n",
counts: [2, 2, 2, 2],
before: [2, 2],
operands: &["HTTP_REQUEST", "{}"],
},
// The comment-only twin of the empty handler above; see the
// shared table for why it scores like it.
BracedWordCase {
source: "when HTTP_REQUEST {\n # only a comment\n}\n",
counts: [2, 2, 2, 2],
before: [2, 2],
operands: &["HTTP_REQUEST", "{\n # only a comment\n}"],
},
];
witnessed.extend(check_braced_word_cases::<IrulesParser, IrulesCode>(
&handlers,
"foo.irule",
&IRULES_BRACED_WORD_KINDS,
));
assert_braced_word_children_witnessed(&witnessed, &IRULES_BRACED_WORD_KINDS, "irules");
}
#[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| {
// After #695 only the opening delimiters count: `()` and
// `{}` fold to one operator each per balanced pair, so the
// former `)`/`}` closers no longer inflate n1/N1 (was
// 11 unique / 15 total).
//
// Operands after #1293, tallied by `get_id` (source bytes):
// `avg` × 1, `int` × 4 (the `primitive_type` wrapper at
// all four type positions — its `int` keyword child is
// suppressed under it), `$a` / `$b` / `$c` × 2 each,
// `3` × 1 ⇒ n2 = 6, N2 = 12. Between #1259 and #1293 the
// keyword leaf doubled the type count ⇒ 6 / 16; before
// #1259 each `$v` also contributed its sigil-less `name`
// leaf ⇒ 9 / 22.
assert_eq!(metric.halstead.unique_operators(), 9);
assert_eq!(metric.halstead.total_operators(), 12);
assert_eq!(metric.halstead.unique_operands(), 6);
assert_eq!(metric.halstead.total_operands(), 12);
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| {
// After #695 only opening delimiters count: the `)`/`}`
// closers no longer add operators (was 9 unique / 9 total).
//
// Operands after #1293: `inc` × 1, `int` × 2 (the
// `primitive_type` wrapper at both type positions, its
// `int` keyword child suppressed under it), `$x` × 2,
// `1` × 1 ⇒ n2 = 4, N2 = 6. Between #1259 and #1293 the
// keyword leaf doubled the type count ⇒ 4 / 8; before
// #1259 `$x` also contributed its `x` leaf twice ⇒ 5 / 10.
assert_eq!(metric.halstead.unique_operators(), 7);
assert_eq!(metric.halstead.total_operators(), 7);
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 6);
insta::assert_json_snapshot!(metric.halstead);
},
);
}
#[test]
fn php_variable_reference_counts_once() {
// Regression: issue #1259. `$x` parses as a `variable_name`
// wrapping a `name` leaf, and both kinds were in the operand
// arm — so every variable reference contributed twice to N2 and
// planted a sigil-less twin (`x` beside `$x`) in the n2
// vocabulary. Since `$var` is the most common token class in
// PHP, that roughly doubled N2 for real files.
//
// Source: the issue's reproducer plus a re-reference of `$a` and
// `$b`, so N2 exceeds n2 and the assertions can tell "counted
// once per occurrence" from "deduplicated into the vocabulary".
// <?php $a = null; $b = true; $c = NULL; $a = $b;
//
// Operands by text key: `$a` × 2, `$b` × 2, `$c`, `null`, `true`,
// `NULL` ⇒ n2 = 6, N2 = 8. Before the fix the `a` / `b` / `c`
// leaves added 3 unique and 5 occurrences ⇒ 9 / 13.
check_metrics::<PhpParser>(
"<?php\n$a = null;\n$b = true;\n$c = NULL;\n$a = $b;\n",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 6);
assert_eq!(metric.halstead.total_operands(), 8);
},
);
}
#[test]
fn php_dynamic_variable_name_counts_once_at_any_depth() {
// Regression: issue #1259. Variable-variable syntax nests the
// wrappers, so the double count compounds: `$$a` is a
// `dynamic_variable_name` → `variable_name` → `name` chain that
// scored 3 for one reference, and `$$$b` scored 4. Only the
// outermost wrapper may count.
//
// Source: <?php $$a = 1; $$$b = 2; ${$c} = 3; $$a = 4;
// The trailing re-assignment repeats `$$a` so N2 exceeds n2 and
// the assertions can tell "counted once per occurrence" from
// "deduplicated into the vocabulary".
//
// Operands: `$$a` × 2, `$$$b`, `${$c}`, `1`, `2`, `3`, `4`
// ⇒ n2 = 7, N2 = 8. Before the fix: 14 / 17 (measured), each
// target contributing its whole nesting chain — `$$a` → `$a` →
// `a` is 3 (twice over), `$$$b` → `$$b` → `$b` → `b` is 4, and
// `${$c}` → `$c` → `c` is 3, plus the four integers.
check_metrics::<PhpParser>(
"<?php $$a = 1; $$$b = 2; ${$c} = 3; $$a = 4;",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 7);
assert_eq!(metric.halstead.total_operands(), 8);
},
);
}
#[test]
fn php_dynamic_variable_name_guard_is_parent_scoped() {
// Companion to the two tests above (#1259): the guards fire on
// the *parent* kind, never on the kind alone, so the two
// positions where a nested node is a reference in its own right
// keep counting.
//
// Source: <?php $y = "brace ${z} end"; $s = ${$a . 'b'};
//
// `"${z}"` is a `dynamic_variable_name` whose `name` child is
// suppressed (the wrapper `${z}` carries the reference), while
// `${$a . 'b'}` reaches its `$a` through a `binary_expression`,
// so that `variable_name`'s parent is not a
// `dynamic_variable_name` and it counts normally.
//
// Operands: `$y`, `${z}`, `$s`, `${$a . 'b'}`, `$a`, `'b'` — one
// each ⇒ n2 = 6, N2 = 6. A guard written as a blanket kind
// exclusion instead of a parent check would drop `$a` ⇒ 5 / 5.
check_metrics::<PhpParser>(
"<?php $y = \"brace ${z} end\"; $s = ${$a . 'b'};",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 6);
assert_eq!(metric.halstead.total_operands(), 6);
},
);
}
#[test]
fn php_type_wrappers_count_the_type_once() {
// Regression: issue #1293. A parameter type nests wrapper nodes
// whose text spans the node below them — `primitive_type` around
// the `int` keyword token, `named_type` around a `name`,
// `optional_type` around either — and every level was in the
// operand arm, so `int` scored 2 and `?int` scored 3.
//
// Source: the issue's first reproducer.
// <?php
// function f(int $a, bool $b, float $c, string $d, array $e,
// Foo $g): ?int { return 0; }
//
// Operands by text key: `f`, the five `primitive_type` parameter
// types, `Foo` (the `name` under its `named_type`), `$a`..`$g`,
// the return `int`, and `0`. `int` occurs twice (parameter and
// return) ⇒ n2 = 14, N2 = 15. Before the fix: 15 / 23 — the
// extra vocabulary entry being `?int`, which the `?` operator
// already accounts for.
check_metrics::<PhpParser>(
"<?php\nfunction f(int $a, bool $b, float $c, string $d, \
array $e, Foo $g): ?int { return 0; }\n",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 14);
assert_eq!(metric.halstead.total_operands(), 15);
},
);
}
#[test]
fn php_qualified_name_counts_its_components_once() {
// Regression: issue #1293. `Foo\Bar\Baz` parses as
// `qualified_name` → `namespace_name` → `name` × N, and all
// three kinds were operands, so one three-part path scored 5 and
// planted `Foo`, `Foo\Bar` and `Foo\Bar\Baz` in the vocabulary.
// The components carry the operand and `\` stays an operator,
// matching how PHP's own `::` and `->` already read here.
//
// Source: the issue's second reproducer.
// <?php
// namespace App\Sub;
// use Foo\Bar\Baz;
// $o = new \Vendor\Pkg\Thing();
//
// Operands: `App`, `Sub`, `Foo`, `Bar`, `Baz`, `$o`, `Vendor`,
// `Pkg`, `Thing` — one each ⇒ n2 = 9, N2 = 9. Before the fix:
// 14 / 14.
check_metrics::<PhpParser>(
"<?php\nnamespace App\\Sub;\nuse Foo\\Bar\\Baz;\n\
$o = new \\Vendor\\Pkg\\Thing();\n",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 9);
assert_eq!(metric.halstead.total_operands(), 9);
},
);
}
#[test]
fn php_nested_type_wrappers_count_once_at_any_depth() {
// Companion to the two tests above (#1293): the type and
// qualified-name wrappers compose, so a single annotation can
// stack five levels — `?A\B` is `optional_type` → `named_type` →
// `qualified_name` → `namespace_name` → `name`, which scored 6
// operands for two identifiers. `union_type` and
// `intersection_type` stack the same way over their members;
// their `|` and `&` are already operators.
//
// Source:
// <?php function k(?A\B $p, int|string $q, C&D $r): ?A\B
// { return 0; }
// The return type repeats `?A\B` so N2 exceeds n2 and the
// assertions can tell "counted once per occurrence" from
// "deduplicated into the vocabulary".
//
// Operands: `k`, `A` × 2, `B` × 2, `$p`, `int`, `string`, `$q`,
// `C`, `D`, `$r`, `0` ⇒ n2 = 11, N2 = 13.
check_metrics::<PhpParser>(
"<?php function k(?A\\B $p, int|string $q, C&D $r): ?A\\B { return 0; }",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 11);
assert_eq!(metric.halstead.total_operands(), 13);
},
);
}
#[test]
fn php_childless_primitive_types_still_count() {
// Guards the direction of the #1293 fix for `primitive_type`,
// where — unlike the qualified-name wrappers — the *wrapper*
// carries the operand and the keyword leaf is suppressed. The
// grammar emits no token node under `primitive_type` for
// `callable`, `iterable`, `mixed`, `void`, `false` or `true`
// (verified with `bca dump`), so the other direction would score
// those six types zero — grammar-dispatch §6.
//
// Source:
// <?php function q(callable $a, iterable $b, mixed $c,
// false $d, true $e): void { }
//
// Operands: `q`, `callable`, `iterable`, `mixed`, `false`,
// `true`, `void`, `$a`..`$e` ⇒ n2 = 12, N2 = 12. Dropping
// `PrimitiveType` from the operand arm instead of gating its
// leaf gives 6 / 6.
check_metrics::<PhpParser>(
"<?php function q(callable $a, iterable $b, mixed $c, \
false $d, true $e): void { }",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 12);
assert_eq!(metric.halstead.total_operands(), 12);
},
);
}
#[test]
fn php_primitive_type_keyword_guard_is_parent_scoped() {
// Companion to the test above (#1293): the keyword suppression
// fires on the *parent* kind, never on the kind alone.
// `array` is also the head token of an `array(…)` literal, where
// it is the construct's only operand and must keep counting; a
// `(int)` / `(string)` cast is a childless `cast_type` that
// never reaches the guard at all.
//
// Source: <?php $x = array(1, 2); $y = (int) $x; $z = (string) $x;
//
// Operands: `$x` × 3, `array`, `1`, `2`, `$y`, `int`, `$z`,
// `string` ⇒ n2 = 8, N2 = 10. A blanket kind exclusion instead
// of a parent check would drop the `array` head ⇒ 7 / 9.
check_metrics::<PhpParser>(
"<?php $x = array(1, 2); $y = (int) $x; $z = (string) $x;",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 8);
assert_eq!(metric.halstead.total_operands(), 10);
},
);
}
#[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), `"world"` × 1.
// u_operands = 2, N2 = 3.
// Without the #184 fix the wrapping `"Hello $name!"` would also
// count → 3 / 4. This test additionally pinned the *inner* `name`
// leaf of each `variable_name` (a further 2 occurrences, 1 unique
// ⇒ the historical 3 / 5) until #1259 recognised that as the same
// double count one level down.
check_metrics::<PhpParser>(
"<?php $name = \"world\"; echo \"Hello $name!\";",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 3);
},
);
}
#[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.unique_operands(), 1);
assert_eq!(metric.halstead.total_operands(), 1);
});
}
#[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, `"x"` × 1 (inert encapsed
// string, still an operand). With the fix u_operands = 2,
// N2 = 3. Without it the wrapping heredoc text would add one
// more unique operand. The sigil-less `name` leaf inside each
// `variable_name` was counted too until #1259.
check_metrics::<PhpParser>(
"<?php $name = \"x\"; echo <<<EOT\nhi $name\nEOT;\n",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 3);
},
);
}
#[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.unique_operands(), 1);
assert_eq!(metric.halstead.total_operands(), 1);
},
);
}
#[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)
// `prop` (name) × 2 (member-access RHS twice — a bare `name`
// outside any `variable_name`, so #1259's
// guard leaves it an operand)
// `stdClass` × 1
// `"x"` × 1
// ⇒ u_operands = 4, N2 = 7.
// With the bug the wrapping `"Hi $obj->prop!"` text adds one
// more unique operand and one more occurrence ⇒ 5 / 8.
check_metrics::<PhpParser>(
"<?php $obj = new stdClass; $obj->prop = \"x\"; echo \"Hi $obj->prop!\";",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 7);
},
);
}
#[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, `1` × 1, `0` × 1.
// ⇒ u_operands = 3, N2 = 4.
// With the bug the wrapping `"Hi $arr[0]!"` text adds 1 / 1.
// The inner `arr` leaf of each `variable_name` added a further
// 1 / 2 until #1259.
check_metrics::<PhpParser>(
"<?php $arr = [1]; echo \"Hi $arr[0]!\";",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 4);
},
);
}
#[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, backtick literal × 1.
// ⇒ u_operands = 2, N2 = 2.
// Before the fix the backtick literal vanished from the count
// ⇒ u_operands = 1, N2 = 1. (The inner `out` leaf of the
// `variable_name` added another 1 / 1 until #1259.)
check_metrics::<PhpParser>("<?php $out = `ls`;", "foo.php", |metric| {
assert_eq!(metric.halstead.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 2);
});
}
#[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),
// `$out` × 1, `"/tmp"` × 1.
// ⇒ u_operands = 3, N2 = 4.
// Without the interpolation guard the wrapping backtick literal
// would also count ⇒ u_operands = 4, N2 = 5. The sigil-less
// `dir` / `out` leaves added a further 2 / 3 until #1259.
check_metrics::<PhpParser>(
"<?php $dir = \"/tmp\"; $out = `ls $dir`;",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 4);
},
);
}
#[test]
fn php_interpolation_opener_is_not_an_operator() {
// Regression: issue #1314. `Php::LBRACE` is *both* the
// compound-statement brace and the complex-interpolation
// opener, so `"dq {$y} end"` reported a `{}` operator — and
// reported it against the same vocabulary entry a real block
// uses, which no other language does.
//
// expected: operators `=` × 2, `;` × 2 → n1 = 2, N1 = 4.
// Operands `$s`, `$t`, `$y` × 2 → n2 = 3, N2 = 4. Before the
// guard the two openers added `{}` → n1 = 3, N1 = 6.
check_metrics::<PhpParser>(
"<?php\n$s = \"dq {$y} end\";\n$t = \"dq {$y} end\";\n",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 2);
assert_eq!(metric.halstead.total_operators(), 4);
assert_eq!(metric.halstead.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 4);
},
);
}
#[test]
fn php_interpolation_opener_guard_covers_every_wrapper() {
// The opener is a direct child of four distinct parents, and
// each is an independent leg of the guard (grammar-dispatch
// section 11) — a fixture covering only `encapsed_string`
// leaves the other three dead.
//
// One row per parent, so a failure names the leg that broke.
// The heredoc's brace hangs off `heredoc_body` rather than
// `heredoc`; the backtick form is `shell_command_expression`;
// and the bare `${$y}` variable-variable is a
// `dynamic_variable_name`, the one position that is not inside
// a string at all.
//
// expected per row: operators `=` × 2, `;` × 2 → n1 = 2,
// N1 = 4; three distinct operands with one repeated → n2 = 3,
// N2 = 4.
for (label, source) in [
(
"encapsed_string",
"<?php\n$s = \"dq {$y} end\";\n$t = \"dq {$y} end\";\n",
),
(
"heredoc_body",
"<?php\n$h = <<<EOT\na {$y} b\nEOT;\n$i = <<<EOT\na {$y} b\nEOT;\n",
),
(
"shell_command_expression",
"<?php\n$b = `ls {$y}`;\n$c = `ls {$y}`;\n",
),
("dynamic_variable_name", "<?php\n$q = ${$y};\n$r = ${$y};\n"),
] {
assert_halstead_counts::<PhpParser>(source, "foo.php", [2, 4, 3, 4], label);
}
}
#[test]
fn php_every_interpolation_spelling_scores_alike() {
// The policy stated as a test (#1314). PHP writes one
// interpolation three ways; the choice is spelling, so all
// three must score identically. Before the guard the two
// braced forms reported a `{}` the bare `$y` form did not.
//
// `"${y}"` is deprecated as of PHP 8.2 and removed in 9.0, but
// the pinned grammar still parses it and it is still in the
// wild, so it stays a row here.
//
// The fixture deliberately omits a `$y = …` declaration: with
// one, the bare and `{$y}` forms key their operand as `$y` and
// collapse into the declaration's entry while `${y}` keys as
// `${y}` and does not, so n2 would differ for a reason that has
// nothing to do with this guard.
//
// expected per spelling: operators `=` × 2, `;` × 2 → n1 = 2,
// N1 = 4; operands `$s`, `$t`, the interpolated reference × 2
// → n2 = 3, N2 = 4.
for literal in ["\"a $y b\"", "\"a {$y} b\"", "\"a ${y} b\""] {
assert_halstead_counts::<PhpParser>(
&format!("<?php\n$s = {literal};\n$t = {literal};\n"),
"foo.php",
[2, 4, 3, 4],
&format!("interpolation {literal}"),
);
}
}
#[test]
fn php_compound_statement_brace_still_counts() {
// Control for #1314: the guard is scoped to the four
// interpolating wrappers, so a real block keeps its `{}`. A
// guard widened to every `LBRACE` would take `{}` out of the
// operator set entirely and fail here.
//
// expected: operators `function`, `()`, `{}` × 2, `if`,
// `return`, `;` → n1 = 6, N1 = 8. Operands `f`, `1`, `2` →
// n2 = N2 = 3.
check_metrics::<PhpParser>(
"<?php\nfunction f() { if (1) { return 2; } }\n",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 6);
assert_eq!(metric.halstead.total_operators(), 8);
assert_eq!(metric.halstead.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 3);
},
);
}
#[test]
fn php_interpolation_guard_is_parent_scoped_not_ancestor_scoped() {
// The input that separates the parent-scoped guard from the
// ancestor-scanning mutant — the mutant #1256's post-mortem
// says survives every ordinary fixture. PHP is one of only two
// languages in #1314 where such an input exists: a closure
// inside a complex interpolation puts a *compound-statement*
// brace under an `encapsed_string` ancestor while its parent is
// the `compound_statement`. An ancestor scan swallows it.
//
// expected: operators `=`, `;` × 2, `->`, `()` × 2, `function`,
// `{}`, `return` → n1 = 7, N1 = 9. Operands `$s`, `$o`, `m`,
// `1` → n2 = N2 = 4. Under the ancestor-scoped mutant the
// closure's brace vanishes: n1 = 6, N1 = 8.
check_metrics::<PhpParser>(
"<?php\n$s = \"{$o->m(function() { return 1; })}\";\n",
"foo.php",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 7);
assert_eq!(metric.halstead.total_operators(), 9);
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 4);
},
);
}
#[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 — only the *opening* delimiters `(`,
// `[` count after #695 (the `)`/`]` closers were dropped), plus
// `,`, `.`, `@`,
// 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. After
// #695 only opening delimiters count: the `)`/`]` closers
// no longer add operators (was 15 unique / 23 total).
assert_eq!(metric.halstead.unique_operators(), 13);
assert_eq!(metric.halstead.total_operators(), 21);
assert_eq!(metric.halstead.unique_operands(), 16);
assert_eq!(metric.halstead.total_operands(), 27);
insta::assert_json_snapshot!(
metric.halstead,
@r#"
{
"unique_operators": 13,
"total_operators": 21,
"unique_operands": 16,
"total_operands": 27,
"length": 48,
"estimated_program_length": 112.10571633583419,
"purity_ratio": 2.3355357569965456,
"vocabulary": 29,
"volume": 233.18308776612344,
"difficulty": 10.96875,
"level": 0.09116809116809117,
"effort": 2557.7269939346666,
"time": 142.09594410748147,
"bugs": 0.062342115670886794
}
"#
);
},
);
}
#[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| {
// After #695 only the `(` opener counts (folded `()`); the
// `)` closer — which appeared twice across the two calls —
// no longer adds an operator (was 9 unique / 11 total).
assert_eq!(metric.halstead.unique_operators(), 8);
assert_eq!(metric.halstead.total_operators(), 9);
assert_eq!(metric.halstead.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 9);
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.unique_operators(), 2);
assert_eq!(metric.halstead.total_operators(), 2);
assert_eq!(metric.halstead.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 2);
});
}
#[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.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 3);
});
}
#[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.unique_operators(), 2);
assert_eq!(metric.halstead.unique_operands(), 2);
});
}
#[test]
fn ruby_halstead_regex_operand() {
// `/foo/` parses as a `Regex` node — one operand. Its two
// `SLASH` delimiters used to fall through to the shared
// arithmetic arm and add a `/` operator that is nowhere in the
// source; #1312 parent-guards them to `Unknown`.
// expected: u_operators = {def, (, =~, end} = 4, N1 = 4 (only
// the `(` opener counts after #695 — the `)` closer was
// dropped; was 5 with the fabricated `/`); u_operands =
// {f, s, /foo/} = 3, N2 = 4 (`s` twice: parameter and use).
check_metrics::<RubyParser>("def f(s)\n s =~ /foo/\nend\n", "foo.rb", |metric| {
assert_eq!(metric.halstead.unique_operators(), 4);
assert_eq!(metric.halstead.total_operators(), 4);
assert_eq!(metric.halstead.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 4);
});
}
#[test]
fn ruby_regex_delimiters_are_not_operators() {
// Regression: issue #1312, the Ruby sibling of Elixir #1256.
// Both of a `Regex` literal's delimiter tokens are `SLASH` —
// the same kind id real division uses — so `x = /abc/`
// reported a `/` operator with no division in the source.
//
// expected: operators `=` → n1 = N1 = 1. Operands `x` and the
// `/abc/` literal → n2 = N2 = 2. Before the guard the two
// delimiters added `/` → n1 = 2, N1 = 3.
check_metrics::<RubyParser>("x = /abc/\n", "foo.rb", |metric| {
assert_eq!(metric.halstead.unique_operators(), 1);
assert_eq!(metric.halstead.total_operators(), 1);
assert_eq!(metric.halstead.unique_operands(), 2);
assert_eq!(metric.halstead.total_operands(), 2);
});
}
#[test]
fn ruby_regex_delimiter_choice_is_invariant() {
// Companion to the test above (#1312): `%r`-form regexes are
// the same literal spelled differently, so every delimiter
// choice must produce identical counts. tree-sitter-ruby
// aliases all of them to `SLASH` — verified with `bca dump`,
// which shows `%r{`/`}`, `%r(`/`)`, `%r[`/`]`, `%r<`/`>`,
// `%r|`/`|` and `%r!`/`!` every one emitting kind `SLASH` —
// so each row here genuinely exercises the guard rather than
// reaching a different, already-clean path.
//
// expected per variant: operator `=` → n1 = N1 = 1; operands
// `x` and the literal → n2 = N2 = 2.
for literal in [
"/abc/", "%r{abc}", "%r(abc)", "%r[abc]", "%r<abc>", "%r|abc|", "%r!abc!",
] {
assert_halstead_counts::<RubyParser>(
&format!("x = {literal}\n"),
"foo.rb",
[1, 1, 2, 2],
&format!("regex literal {literal}"),
);
}
}
#[test]
fn ruby_division_survives_the_regex_guard() {
// Control for #1312: the guard is scoped to a `Regex` parent,
// so real division still counts. Two divisions, so a mutant
// that collapsed repeated hits would move `N1` even though
// `n1` held (the #1294 count-only-anchor lesson).
//
// expected: operators `=` and `/` × 2 → n1 = 2, N1 = 3.
// Operands `z`, `a`, `b`, `c` → n2 = N2 = 4.
check_metrics::<RubyParser>("z = a / b / c\n", "foo.rb", |metric| {
assert_eq!(metric.halstead.unique_operators(), 2);
assert_eq!(metric.halstead.total_operators(), 3);
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 4);
});
}
#[test]
fn ruby_regex_guard_is_parent_scoped_not_ancestor_scoped() {
// The one input that separates the correct parent-scoped guard
// from the ancestor-scoped mutant of it (#1312, mirroring
// #1256's Elixir case): a division *inside* a regex's `#{…}`
// interpolation. Its `/` has `Binary` as its parent but the
// `Regex` as a further ancestor, so an ancestor scan would
// swallow it. Every other fixture in this file passes under
// both spellings. Two interpolations, so the mutant moves both
// n1 (2 → 1) and N1 (3 → 1).
//
// expected: operators `=`, `/` × 2 → n1 = 2, N1 = 3. Operands
// `w`, `p`, `q`, `r`, `t` → n2 = N2 = 5; the wrapping `Regex`
// is skipped because it carries an `Interpolation` child (the
// #180 double-count guard).
//
// Was n1 = 3, N1 = 5 until #1314 dropped `#{` from the operator
// arm. The mutant still moves both axes, so this fixture is as
// discriminating as it was — it just no longer counts the two
// interpolation openers alongside the two divisions.
check_metrics::<RubyParser>("w = /a#{p / q}c#{r / t}b/\n", "foo.rb", |metric| {
assert_eq!(metric.halstead.unique_operators(), 2);
assert_eq!(metric.halstead.total_operators(), 3);
assert_eq!(metric.halstead.unique_operands(), 5);
assert_eq!(metric.halstead.total_operands(), 5);
});
}
#[test]
fn ruby_regex_start_alias_never_reaches_kind_id() {
// Drift marker for the `R::SLASH2` half of #1312's guard.
// `SLASH2` is the aliased regex-start token: it sits in the
// enum beside the other literal-start aliases (`DQUOTE`,
// `COLONDQUOTE`, `BQUOTE2`, `PERCENTwLPAREN`) and the runtime
// `public_symbol_map` collapses it to `SLASH` before
// `kind_id()`, exactly like `LPAREN2` in #768. It is listed in
// the guard rather than the arithmetic arm because a regex
// delimiter is the only thing it could ever be; this pins that
// it is currently unreachable, so a grammar bump that starts
// emitting it fails here instead of silently changing a metric.
let path = PathBuf::from("foo.rb");
for source in ["x = /abc/\n", "x = %r{abc}\n"] {
let parser = RubyParser::new(source.as_bytes().to_vec(), &path, None);
assert!(
!ast_has_kind_id(&parser, Ruby::SLASH2 as u16),
"Ruby::SLASH2 must stay collapsed to Ruby::SLASH for `{source}`"
);
// Positive control: the id the guard actually fires on is
// present, so the assertion above cannot pass merely
// because no delimiter was parsed at all.
assert!(
ast_has_kind_id(&parser, Ruby::SLASH as u16),
"Ruby::SLASH must be the delimiter kind for `{source}`"
);
}
}
#[test]
fn ruby_interpolation_opener_is_not_an_operator() {
// Behaviour change, not a fabrication fix: #1314 drops
// `HASHLBRACE` from Ruby's operator arm. `#{` is a token of its
// own here — unlike PHP's `{`, which aliases the
// compound-statement brace — so nothing was being miscounted;
// the question was whether an interpolation opener is an
// operation at all, and across the five interpolating languages
// three already said no. Ruby Halstead operator counts drop for
// interpolated literals as a result.
//
// Asserted as an invariance: the interpolated and plain
// spellings of one string must now score identically, which is
// the policy rather than a magic number. Before the change the
// interpolated row was n1 = 2, N1 = 3.
//
// expected per row: operator `=` × 2 → n1 = 1, N1 = 2; operands
// `s`, `t`, and the literal's content contribution × 2 →
// n2 = 3, N2 = 4.
for literal in ["\"a #{y} b\"", "\"a b\""] {
assert_halstead_counts::<RubyParser>(
&format!("s = {literal}\nt = {literal}\n"),
"foo.rb",
[1, 2, 3, 4],
&format!("literal {literal}"),
);
}
}
#[test]
fn ruby_interpolation_opener_drop_covers_every_literal() {
// `HASHLBRACE` is one arm, but it fires under every Ruby
// literal that interpolates, so the drop is not specific to
// double-quoted strings. A symbol and a regex — two literals
// whose `#{…}` reaches the same token — must contribute no
// operator for the opener either.
//
// expected: operator `=` × 3 → n1 = 1, N1 = 3. Operands `y`,
// `1`, `a`, `b`, plus the two interpolated `y` references →
// n2 = 4, N2 = 6. Before the change each `#{` added one →
// n1 = 2, N1 = 5.
check_metrics::<RubyParser>("y = 1\na = :\"s#{y}\"\nb = /r#{y}/\n", "foo.rb", |metric| {
assert_eq!(metric.halstead.unique_operators(), 1);
assert_eq!(metric.halstead.total_operators(), 3);
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 6);
});
}
#[test]
fn ruby_element_containers_count_elements_not_the_composite_1353() {
// #1353. `chained_string`, `string_array` and `symbol_array`
// hold *classified operand* children instead of the raw
// `string_content` every other string-like literal wraps, so
// the arm's shared `Interpolation` guard never fired and the
// wrapper was billed alongside each element. Every row below
// scored n2 4 / N2 4 for three operands, the extra entry being
// the wrapper's whole-span text — which made the vocabulary
// depend on how the author grouped the literals.
//
// `assert_ops_operands` pins the operand *text*, not just the
// count: a wrapper coming back would show up as `"one" "two"` /
// `%w[x y]` / `%i[p q]` rather than as an off-by-one number.
//
// The kind assertions are the grammar-dispatch §1 / §2 drift
// marker — a bump that renumbers a wrapper or an element would
// otherwise leave these counts passing while measuring a
// construct the arm no longer names.
//
// Two of the three rows also pin the arm's *membership*:
// dropping `StringArray` or `SymbolArray` from it fails
// `ruby_empty_word_and_symbol_arrays_still_bill_one_operand_1353`.
// `ChainedString`'s membership is unobservable and no test can
// pin it — `repeat1($.string)` guarantees the guard always
// fires, so `Unknown` and "not in the arm at all" are the same
// answer for every input. It is listed for symmetry with its
// siblings, and correct-by-construction is the only defence
// available there.
for (source, wrapper, element, operands) in [
(
"a = \"one\" \"two\"\n",
Ruby::ChainedString,
Ruby::String,
vec!["a", "\"one\"", "\"two\""],
),
(
"b = %w[x y]\n",
Ruby::StringArray,
Ruby::BareString,
vec!["b", "x", "y"],
),
(
"c = %i[p q]\n",
Ruby::SymbolArray,
Ruby::BareSymbol,
vec!["c", "p", "q"],
),
] {
let parser =
RubyParser::new(source.as_bytes().to_vec(), &PathBuf::from("foo.rb"), None);
assert!(
ast_has_kind_id(&parser, wrapper as u16),
"the container kind this arm gates on is unreachable for `{source}`"
);
assert!(
ast_has_kind_id(&parser, element as u16),
"the element kind this arm gates on is unreachable for `{source}`"
);
// expected: operator `=` → n1 = N1 = 1; operands are the
// assignment target and the two elements → n2 = N2 = 3.
assert_halstead_counts::<RubyParser>(source, "foo.rb", [1, 1, 3, 3], source);
assert_ops_operands::<RubyParser>(source, "foo.rb", 3, operands);
}
}
#[test]
fn ruby_empty_word_and_symbol_arrays_still_bill_one_operand_1353() {
// The childless spelling, and the whole reason #1353 gates the
// three container kinds instead of dropping them from the arm
// (grammar-dispatch §6). `%w[]` / `%i[]` parse to a wrapper
// holding nothing but its two delimiter tokens, so the tempting
// "just delete the wrapper" fix — the one #1351 was right to
// take for Bash's `command_name` — would score an empty literal
// zero operands where the source plainly has a literal. This is
// the assertion to watch fail against that alternative.
//
// expected: operator `=` → n1 = N1 = 1; operands the assignment
// target and the empty literal itself → n2 = N2 = 2.
for (source, operands) in [
("d = %w[]\n", vec!["d", "%w[]"]),
("e = %i[]\n", vec!["e", "%i[]"]),
] {
assert_halstead_counts::<RubyParser>(source, "foo.rb", [1, 1, 2, 2], source);
assert_ops_operands::<RubyParser>(source, "foo.rb", 2, operands);
}
}
#[test]
fn ruby_interpolated_array_elements_are_not_double_counted_1353() {
// `bare_string` and `bare_symbol` are two aliases of a single
// grammar production (`_literal_contents`), one per array form,
// so `%W[…]` and `%I[…]` must score identically. Until #1353
// only `bare_string` carried the interpolation guard and
// `bare_symbol` sat in the plain operand arm, so `%I[a#{n}b c]`
// billed the element `a#{n}b` *and* the `n` inside it (n2 4)
// where `%W[a#{n}b c]` billed 3.
//
// Asserted as an invariance over the two spellings, the way
// `ruby_interpolation_opener_is_not_an_operator` is — the
// policy is the claim, not the magic number. The third row is
// the composed case: a `chained_string` whose own guard defers
// to an element that is itself interpolated.
//
// expected per row: operator `=` → n1 = N1 = 1; operands the
// assignment target, the interpolated expression `n`, and the
// one inert element → n2 = N2 = 3. The operand *text* is pinned
// too, because 3 is also the count an implementation that
// suppressed the inert element instead of the wrapper would
// report.
for (source, operands) in [
("w = %W[a#{n}b c]\n", vec!["w", "n", "c"]),
("w = %I[a#{n}b c]\n", vec!["w", "n", "c"]),
("a = \"x#{n}\" \"y\"\n", vec!["a", "n", "\"y\""]),
] {
assert_halstead_counts::<RubyParser>(source, "foo.rb", [1, 1, 3, 3], source);
assert_ops_operands::<RubyParser>(source, "foo.rb", 3, operands);
}
}
/// Comprehensive iRules Halstead test exercising every operator family
/// classified in `get_op_type`: declaration/control keywords (`proc`,
/// `set`, `if`, `return`), structural punctuation (`{}` `[]` `()`),
/// arithmetic (`+`), comparison (`>`), the word-form string comparator
/// (`eq`), and short-circuit logical (`&&`). Anchored on the integer
/// `n1`/`N1`/`n2`/`N2` headline values; the float fields are derived and
/// bit-brittle, so they are not pinned.
///
/// The second half pins the lesson-4 invariant: the independent
/// text-keyed `operands_and_operators` store must dedupe to the same
/// `n1`/`n2`. A classification change that moved one store without the
/// other (e.g. a kind landing in both the operator and operand arms)
/// would break this even though the snapshot stayed green.
#[test]
fn irules_operators_and_operands() {
let source = "proc f { a b } {
set x [expr { $a + $b }]
if { $x > 0 && $a eq \"go\" } {
return $x
}
return 0
}
";
check_metrics::<IrulesParser>(source, "foo.irule", |metric| {
// After #695 only opening delimiters count: the `}`/`]`
// closers no longer add operators (was 12 unique / 20 total).
assert_eq!(metric.halstead.unique_operators(), 10);
assert_eq!(metric.halstead.total_operators(), 14);
// Operands fell 12 / 16 → 10 / 14 with #1354: the proc body
// and the `if` body are `BracedWord` script kinds and are no
// longer operands beside the commands they contain.
assert_eq!(metric.halstead.unique_operands(), 10);
assert_eq!(metric.halstead.total_operands(), 14);
});
let path = PathBuf::from("foo.irule");
let parser = IrulesParser::new(source.as_bytes().to_vec(), &path, None);
let ops = crate::ops::ops_inner(&parser, None).expect("ops walk succeeds");
let unique_operators: HashSet<&str> = ops.operators.iter().map(String::as_str).collect();
let unique_operands: HashSet<&str> = ops.operands.iter().map(String::as_str).collect();
assert_eq!(
unique_operators.len(),
10,
"dedupe(ops.operators) must equal n1; operators were {:?}",
ops.operators
);
assert_eq!(
unique_operands.len(),
10,
"dedupe(ops.operands) must equal n2; operands were {:?}",
ops.operands
);
}
/// An inert `"hello world"` double-quoted string (no `$var` / `[cmd]`
/// interpolation child) contributes exactly **one** operand — the
/// wrapping `QuotedWord`. Operands are `f`, `s` and `"hello world"` —
/// n2 = 3, the same as Tcl since #1294 restored its `set` target to
/// the operand count and #1354 dropped the proc-body `braced_word`
/// from both. Mirrors `tcl_inert_quoted_word_counts_as_operand`
/// (#277).
#[test]
fn irules_inert_quoted_word_counts_as_operand() {
let source = "proc f {} {\n set s \"hello world\"\n}\n";
check_metrics::<IrulesParser>(source, "foo.irule", |metric| {
// After #695 only the `{` opener counts; the `}` closer no
// longer adds an operator (was 4 unique / 6 total).
assert_eq!(metric.halstead.unique_operators(), 3);
assert_eq!(metric.halstead.total_operators(), 4);
assert_eq!(metric.halstead.unique_operands(), 3);
assert_eq!(metric.halstead.total_operands(), 3);
});
let path = PathBuf::from("foo.irule");
let parser = IrulesParser::new(source.as_bytes().to_vec(), &path, None);
let ops = crate::ops::ops_inner(&parser, None).expect("ops walk succeeds");
// The inert quoted word is present as exactly one operand (not
// dropped, not split): dropping it would mean the inert branch was
// over-guarded.
let quoted = ops
.operands
.iter()
.filter(|o| o.as_str() == "\"hello world\"")
.count();
assert_eq!(quoted, 1, "inert quoted word must be one operand");
let unique_operands: HashSet<&str> = ops.operands.iter().map(String::as_str).collect();
assert_eq!(unique_operands.len(), 3, "operands were {:?}", ops.operands);
}
/// Regression for the `QuotedWord` interpolation guard (the #277 /
/// Bash-#180 / C#-#183 / PHP-#184 pattern). An interpolated
/// `"$x is $y"` must contribute **zero** operands for the wrapping
/// `QuotedWord`; the inner `$x` / `$y` `variable_substitution` nodes are
/// walked separately and count on their own. Operands are `f`, `x`, `y`,
/// `s`, `$x`, `$y` = 6 (7 before #1354 dropped the proc-body
/// `braced_word`). If the guard regressed (wrapper classified
/// `Operand`), the wrapper string would add a 7th operand. This is the
/// branch that had no test before.
#[test]
fn irules_interpolated_quoted_word_no_double_count() {
let source = "proc f {x y} {\n set s \"$x is $y\"\n}\n";
check_metrics::<IrulesParser>(source, "foo.irule", |metric| {
// After #695 only the `{` opener counts; the `}` closer no
// longer adds an operator (was 4 unique / 6 total).
assert_eq!(metric.halstead.unique_operators(), 3);
assert_eq!(metric.halstead.total_operators(), 4);
assert_eq!(metric.halstead.unique_operands(), 6);
assert_eq!(metric.halstead.total_operands(), 6);
});
let path = PathBuf::from("foo.irule");
let parser = IrulesParser::new(source.as_bytes().to_vec(), &path, None);
let ops = crate::ops::ops_inner(&parser, None).expect("ops walk succeeds");
// The wrapping interpolated string must NOT appear as an operand;
// its inner substitutions must. The wrapper, if wrongly counted,
// would surface as the quoted literal `"$x is $y"` (with quotes,
// like the inert `"hello world"` operand). Match that exact token —
// a substring check would false-match the proc-body `braced_word`
// operand, which legitimately contains the source text.
assert!(
!ops.operands.iter().any(|o| o.as_str() == "\"$x is $y\""),
"interpolated wrapper must not be an operand; operands were {:?}",
ops.operands
);
assert!(
ops.operands.iter().any(|o| o.as_str() == "$x")
&& ops.operands.iter().any(|o| o.as_str() == "$y"),
"inner $x / $y substitutions must each be operands; operands were {:?}",
ops.operands
);
let unique_operands: HashSet<&str> = ops.operands.iter().map(String::as_str).collect();
assert_eq!(unique_operands.len(), 6, "operands were {:?}", ops.operands);
}
/// Exercises the operator families not covered by
/// `irules_operators_and_operands`: bitwise (`& | ^ ~ << >>`), ternary
/// (`? :`), the keyword string comparators (`starts_with`, `ends_with`,
/// `contains`, `matches`, `eq`, `ne`), and the keyword logical operator
/// (`and`). Pins every operator-family arm in `get_op_type` plus the
/// lesson-4 dedupe invariant.
#[test]
fn irules_bitwise_ternary_string_ops() {
let source = "proc f { a b } {
set bits [expr { $a & $b | $a ^ ~$b }]
set sh [expr { $a << 2 | $b >> 1 }]
set t [expr { $a > 0 ? $a : $b }]
if { $a starts_with \"x\" && $b ends_with \"y\" } { return 1 }
if { $a contains \"z\" || $b matches \"q\" } { return 2 }
if { $a eq \"m\" and $b ne \"n\" } { return 3 }
return $b
}
";
check_metrics::<IrulesParser>(source, "foo.irule", |metric| {
// After #695 only opening delimiters count: the `}`/`]`
// closers no longer add operators (was 26 unique / 57 total).
assert_eq!(metric.halstead.unique_operators(), 24);
assert_eq!(metric.halstead.total_operators(), 43);
// Operands fell 23 / 42 → 19 / 38 with #1354: the proc body
// and the three single-statement `if` bodies are
// `BracedWord` script kinds and no longer count as operands.
assert_eq!(metric.halstead.unique_operands(), 19);
assert_eq!(metric.halstead.total_operands(), 38);
});
let path = PathBuf::from("foo.irule");
let parser = IrulesParser::new(source.as_bytes().to_vec(), &path, None);
let ops = crate::ops::ops_inner(&parser, None).expect("ops walk succeeds");
let unique_operators: HashSet<&str> = ops.operators.iter().map(String::as_str).collect();
let unique_operands: HashSet<&str> = ops.operands.iter().map(String::as_str).collect();
assert_eq!(
unique_operators.len(),
24,
"dedupe(ops.operators) must equal n1; operators were {:?}",
ops.operators
);
assert_eq!(
unique_operands.len(),
19,
"dedupe(ops.operands) must equal n2; operands were {:?}",
ops.operands
);
}
/// A bare `$x` produces one `variable_substitution` operand. Its inner
/// `id` leaf (the *named* `Id` node — not the anonymous `Id2` token Tcl
/// has there) must NOT be counted separately, or every variable
/// reference double-counts. `get_op_type` excludes `Id` whose parent is
/// a `VariableSubstitution`. Operands: `f`, the proc arg `x`, `return`
/// and `$x` — four, with no duplicate (`total_operands()` == 4; the
/// proc-body `braced_word` was a fifth before #1354). If the guard
/// regressed, the inner `id` "x" would add a fifth operand occurrence
/// (it text-collides with the proc arg `x`, so `u_operands` would stay
/// 4 but `total_operands()` would rise to 5 — hence the total, not just
/// the unique count, is asserted).
#[test]
fn irules_array_reference_bills_the_reference_and_the_index() {
// The iRules twin of
// `tcl_array_reference_bills_the_reference_and_the_index`. Until
// `ArrayIndex` left the operand arm this fixture billed `(k)` and
// `($i)` beside the six operands below — the grammar-dispatch §5
// wrapper-plus-leaf count, and a divergence from Tcl.
assert_ops_operands::<IrulesParser>(
"set arr(k) 1\nset z \"$arr($i)\"\n",
"foo.irule",
6,
vec!["arr", "k", "1", "z", "$arr($i)", "$i"],
);
}
#[test]
fn irules_bare_variable_operand() {
let source = "proc f {x} {\n return $x\n}\n";
check_metrics::<IrulesParser>(source, "foo.irule", |metric| {
// After #695 only the `{` opener counts (folded `{}`); the
// `}` closer no longer adds an operator (was 3 unique / 5 total).
assert_eq!(metric.halstead.unique_operators(), 2);
assert_eq!(metric.halstead.total_operators(), 3);
assert_eq!(metric.halstead.unique_operands(), 4);
assert_eq!(metric.halstead.total_operands(), 4);
});
let path = PathBuf::from("foo.irule");
let parser = IrulesParser::new(source.as_bytes().to_vec(), &path, None);
let ops = crate::ops::ops_inner(&parser, None).expect("ops walk succeeds");
let bare_var = ops.operands.iter().filter(|o| o.as_str() == "$x").count();
assert_eq!(
bare_var, 1,
"bare $x must be exactly one operand (inner id leaf not double-counted); operands were {:?}",
ops.operands
);
}
#[test]
fn irules_braced_word_delimiter_is_not_an_operator() {
// Regression: issue #1314. The iRules twin of
// `tcl_braced_word_delimiter_is_not_an_operator` — the two
// getters are deliberate clones, so the guard lands in both and
// is asserted in both.
//
// One fixture covers the guard and its control: `{braced word}`
// and `{y}` are values whose openers must not count, while the
// handler body, the `if` condition and the `if` body are
// `BracedWord` / `Expr` and must keep theirs. A guard keyed on
// the brace alone would take `{}` out of the operator set
// entirely and fail here.
//
// expected: operators `when`, `set` × 2, `if`, `contains`,
// `[]`, `{}` × 3 → n1 = 6, N1 = 9. Every operand is distinct →
// n2 = N2 = 7: `HTTP_REQUEST`, `a`, `b`, `HTTP::uri`, `"x"` and
// the two braced words `{braced word}` and `{y}`. Before the
// guard the two value openers added two more `{}` occurrences →
// N1 = 11; before #1354 the handler and `if` bodies and the
// inner `braced` / `word` / `y` were operands too → n2 = 12.
check_metrics::<IrulesParser>(
"when HTTP_REQUEST {\n set a {braced word}\n if {[HTTP::uri] contains \"x\"} { set b {y} }\n}\n",
"foo.irule",
|metric| {
assert_eq!(metric.halstead.unique_operators(), 6);
assert_eq!(metric.halstead.total_operators(), 9);
assert_eq!(metric.halstead.unique_operands(), 7);
assert_eq!(metric.halstead.total_operands(), 7);
},
);
}
/// Regression for #563: the two Halstead `Display` labels must use the
/// underscore key that matches the JSON/CSV field name, so a user can grep
/// the same token across `Display` and JSON. The space-separated forms
/// (`estimated program length` / `purity ratio`) were the only outliers,
/// mirroring the `dump` fix in #562.
#[test]
fn display_halstead_labels_use_underscore_keys() {
check_metrics::<CppParser>("int a = 42;", "foo.cpp", |metric| {
let out = metric.halstead.to_string();
assert!(
out.contains("estimated_program_length: "),
"Display must use the underscore key `estimated_program_length`:\n{out}"
);
assert!(
out.contains("purity_ratio: "),
"Display must use the underscore key `purity_ratio`:\n{out}"
);
assert!(
!out.contains("estimated program length"),
"Display must not emit the space-separated `estimated program length`:\n{out}"
);
assert!(
!out.contains("purity ratio"),
"Display must not emit the space-separated `purity ratio`:\n{out}"
);
});
}
/// `@"…"` is one `string_literal` holding its `@` as a child, so the
/// literal is the operand, keyed by its whole text, and the marker is
/// not an operator on top — it was, which planted a phantom `@` in
/// n1 for a file whose only `@` was in NSString literals and billed
/// the same byte in both streams. Boxing (`@42`) keeps its `@`: there
/// the token is a child of the `at_expression`, not of the literal.
#[test]
fn objc_nsstring_literal_is_one_operand() {
// expected: [n1, N1, n2, N2]. Before the guard the first two rows
// read [8, 8, 5, 5] and [8, 9, 6, 6] — one `@` operator per
// literal; the boxing control is unchanged.
let cases = [
("NSString *s = @\"str\";", [7, 7, 5, 5]),
("NSString *t = @\"x\" @\"y\";", [7, 7, 6, 6]),
("NSNumber *n = @42;", [8, 8, 5, 5]),
];
for (body, counts) in cases {
let source = format!("@implementation Foo\n- (void)m {{\n {body}\n}}\n@end\n");
assert_halstead_counts::<ObjcParser>(&source, "foo.m", counts, body);
}
assert_ops_operands::<ObjcParser>(
"@implementation Foo\n- (void)m {\n NSString *s = @\"str\";\n}\n@end\n",
"foo.m",
5,
vec!["Foo", "m", "NSString", "s", "@\"str\""],
);
}
/// Comprehensive Objective-C Halstead fixture exercising a message
/// send (`[self log:@"hi"]`), an ObjC string literal (`@"hi"`), an
/// `if`, a short-circuit `&&`, arithmetic (`+`), comparisons, and
/// assignment. Pins every field and enforces the lesson-4 invariants
/// `unique_operators == n1` / `unique_operands == n2` via the
/// independent `--ops` store.
#[test]
fn objc_operators_and_operands() {
let source = "@implementation Foo
- (int)bar:(int)x {
int y = x + 1;
if (x > 0 && y < 10) {
[self log:@\"hi\"];
}
return y;
}
@end
";
check_metrics::<ObjcParser>(source, "foo.m", |metric| {
// n1 = 14 unique operators:
// `&&`, `()`, `+`, `-`, `:`, `;`, `<`, `=`, `>`,
// `[]` (message send), `if`, `int`, `return`, `{}`.
// The `@` of `@"hi"` is part of the literal's operand
// key, not an operator (see `objc_nsstring_literal_is_one_operand`).
// n2 = 10 unique operands:
// `Foo`, `bar`, `log`, `self`, `x`, `y`, `0`, `1`, `10`,
// `@"hi"` (the ObjC string literal).
assert_eq!(metric.halstead.unique_operators(), 14);
assert_eq!(metric.halstead.unique_operands(), 10);
insta::assert_json_snapshot!(metric.halstead, @r#"
{
"unique_operators": 14,
"total_operators": 22,
"unique_operands": 10,
"total_operands": 14,
"length": 36,
"estimated_program_length": 86.52224985768008,
"purity_ratio": 2.403395829380002,
"vocabulary": 24,
"volume": 165.0586500259616,
"difficulty": 9.8,
"level": 0.1020408163265306,
"effort": 1617.5747702544238,
"time": 89.86526501413465,
"bugs": 0.04593266617952463
}
"#);
});
// Lesson-4 invariant: dedupe(ops.operands) == n2 (10), via the
// independent text-keyed `--ops` store.
assert_ops_operands::<ObjcParser>(
source,
"foo.m",
10,
vec![
"Foo", "bar", "log", "self", "x", "y", "0", "1", "10", "@\"hi\"",
],
);
}
/// #1316 fixture separating the vocabulary and occurrence axes
/// (#1294): `'x'` appears twice, so a correct fix adds four `n2`
/// entries and five `N2` hits. The `'ab'` multi-character constant
/// is also the grammar-dispatch section 5 pin — that literal carries
/// *two* `character` children and must still bill one operand.
///
/// Both #1316 fixtures are plain C, which every C-family grammar
/// parses to the same shape, so one source proves the same thing
/// about each of the four clones.
const C_FAMILY_CHAR_REPEATS: &str =
"char a = 'x';\nchar b = 'x';\nchar c = 'y';\nchar d = '\\n';\nint e = 'ab';\n";
/// #1316 fixture holding all five spellings the grammars admit. Each
/// opens on a distinct delimiter kind (`'`, `L'`, `u'`, `U'`, `u8'`),
/// and operands key on source text, so the five are five vocabulary
/// entries rather than one.
const C_FAMILY_CHAR_PREFIXES: &str =
"char a = 'x';\nchar b = L'x';\nchar c = u'x';\nchar d = U'x';\nchar e = u8'x';\n";
/// Asserts both #1316 fixtures for one C-family language, through
/// the metrics store *and* the text-keyed `--ops` store (the
/// lesson-4 invariant `n2 == len(dedupe(ops.operands))`).
///
/// The `--ops` half pins *which text* each literal is billed under,
/// which the counts cannot see: billing a literal's `character`
/// payload instead of the whole literal keeps `n2` at 9 while the
/// vocabulary silently becomes `x` rather than `'x'`. (Billing
/// *both* is caught earlier, by the counts.) It is a second *walk*
/// rather than a second classification — `ops_inner` reads the keys
/// of the same `HalsteadMaps` — which is worth knowing before
/// reading it as independent corroboration of the count.
#[track_caller]
fn assert_char_literal_operands<T: crate::ParserTrait>(file: &str, label: &str) {
// `char` x4 and `int` are text-keyed primitive operators, so
// n1 = 4 (`;`, `=`, `char`, `int`) and N1 = 5 + 5 + 4 + 1.
// Operands: `a`..`e`, plus `'x'` (twice), `'y'`, `'\n'`, `'ab'`.
let repeats = format!("{label}: repeated / escaped / multi-char literals");
assert_halstead_counts::<T>(C_FAMILY_CHAR_REPEATS, file, [4, 15, 9, 10], &repeats);
assert_ops_operands::<T>(
C_FAMILY_CHAR_REPEATS,
file,
9,
vec!["a", "b", "c", "d", "e", "'x'", "'y'", "'\\n'", "'ab'"],
);
// Every declaration is `char` here, so the `int` primitive
// operator of the other fixture is gone and n1 drops to 3. Ten
// distinct operands, each seen once.
let prefixes = format!("{label}: L / u / U / u8 prefixed literals");
assert_halstead_counts::<T>(C_FAMILY_CHAR_PREFIXES, file, [3, 15, 10, 10], &prefixes);
assert_ops_operands::<T>(
C_FAMILY_CHAR_PREFIXES,
file,
10,
vec![
"a", "b", "c", "d", "e", "'x'", "L'x'", "u'x'", "U'x'", "u8'x'",
],
);
}
/// Regression for #1316: a C-family character literal is a Halstead
/// operand.
///
/// `char_literal` was in no arm of `CCode` / `CppCode` /
/// `MozcppCode` / `ObjcCode`'s `get_op_type`, so a character literal
/// contributed *nothing* — not an operator (correct) and not an
/// operand (wrong) — while Rust, Java, Kotlin, C#, Go and Elixir all
/// counted theirs. Both fixtures measured `n2` 5, `N2` 5 before the
/// fix: the five declared identifiers and not one literal.
///
/// Each language asserts separately over the same source rather than
/// sharing one call, so reverting one clone's arm fails that row
/// alone (grammar-dispatch section 11) — verified by perturbing each
/// of the four arms in turn. A single shared assertion would be
/// satisfied by whichever clone still had the arm.
///
/// Mozcpp owns no file extension, so no integration snapshot ever
/// reaches its clone; its row is the whole coverage that arm has.
#[test]
fn c_family_char_literals_are_operands() {
assert_char_literal_operands::<CParser>("chars.c", "c");
assert_char_literal_operands::<CppParser>("chars.cpp", "cpp");
assert_char_literal_operands::<MozcppParser>("chars.cpp", "mozcpp");
assert_char_literal_operands::<ObjcParser>("chars.m", "objc");
}
/// ObjC boxes a character literal as `@'y'` — an `at_expression`
/// wrapping the same `char_literal`, with the `@` counted as its own
/// operator. The wrapper is in no operand arm, so the boxed form
/// bills exactly the literal it wraps and stays distinct from a bare
/// one (#1316).
#[test]
fn objc_boxed_char_literal_is_one_operand() {
let source = "char a = 'x';\nid b = @'y';\n";
// n1: `char`, `=`, `;`, `@`. N1: 1 + 2 + 2 + 1.
// n2 / N2: `a`, `b`, `'x'`, `'y'` — `id` is a `typedefed_specifier`
// and is classified by neither arm. Before #1316 this was n2 2,
// N2 2.
assert_halstead_counts::<ObjcParser>(source, "boxed.m", [4, 6, 4, 4], "objc @'y'");
assert_ops_operands::<ObjcParser>(source, "boxed.m", 4, vec!["a", "b", "'x'", "'y'"]);
}
/// Walks both #1316 fixtures under all four C-family `Getter`s and
/// pins the two grammar facts the new operand arm rests on.
///
/// * **Grammar-dispatch section 1.** In the positions these
/// fixtures exercise, every node the grammar spells `char_literal`
/// carries the one `kind_id` the arm lists. That is the weaker
/// half of the alias evidence — an alias arises in a *different*
/// syntactic position, which no fixture can enumerate. The strong
/// half is that these generated enums do carry numeric-suffix
/// aliases in quantity (`language_c.rs` alone has ninety) and none
/// of the four spells a `CharLiteral2`, so its absence is a
/// measurement rather than a silence. This loop is what notices if
/// a grammar bump changes that under an existing fixture.
/// * **Grammar-dispatch section 5.** No child of a `char_literal` is
/// classified. That is what makes listing the wrapper safe rather
/// than a wrapper/leaf double count: the opening delimiter, the
/// closing `'`, and the `character` / `escape_sequence` payload
/// must all stay `Unknown`, or every literal would bill two
/// operands and a prefixed one three.
///
/// Both loops are non-vacuous by assertion, since a fixture that
/// stopped containing a character literal would otherwise make this
/// test pass having checked nothing.
#[test]
fn c_family_char_literal_internals_stay_unclassified() {
fn check<L: LanguageInfo + Getter>(char_literal: u16, label: &str) {
let mut literals = 0_usize;
let mut children = 0_usize;
for source in [C_FAMILY_CHAR_REPEATS, C_FAMILY_CHAR_PREFIXES] {
for_each_node_with_chain::<L>(source.as_bytes(), |node, chain| {
if node.kind() == "char_literal" {
assert_eq!(
node.kind_id(),
char_literal,
"{label}: a `char_literal` carries kind_id {} rather than the \
{char_literal} the operand arm lists — an alias the arm cannot see",
node.kind_id()
);
literals += 1;
}
if chain
.last()
.is_none_or(|parent| parent.kind_id() != char_literal)
{
return;
}
children += 1;
// `_with_code` is the spelling `compute_halstead`
// calls. The default forwards to the byte-less form,
// so today the two agree for every C-family
// language — which is exactly why asking the wrong
// one would read as correct right up until one of
// these four grew an override (grammar-dispatch
// section 7).
assert!(
matches!(
L::get_op_type_with_code(
node,
source.as_bytes(),
Ancestors::known(chain)
),
HalsteadType::Unknown
),
"{label}: `{}` inside a character literal is classified, so the \
literal now double-counts against its wrapper",
node.kind()
);
});
}
// Ten literals across the two fixtures; each holds two
// delimiters plus at least one payload leaf, and `'ab'` two.
assert_eq!(literals, 10, "{label}: fixtures lost a character literal");
assert_eq!(children, 31, "{label}: fixtures lost a literal's internals");
}
check::<CCode>(C::CharLiteral as u16, "c");
check::<CppCode>(Cpp::CharLiteral as u16, "cpp");
check::<MozcppCode>(Mozcpp::CharLiteral as u16, "mozcpp");
check::<ObjcCode>(Objc::CharLiteral as u16, "objc");
}
/// Builds a `HalsteadMaps` from explicit occurrence counts.
///
/// The per-language tests above reach these maps only through a
/// parse, which cannot produce a *chosen* overlap between a child
/// and its parent — the cases `merge` exists to get right.
fn halstead_maps_of<'a>(
operators: &[(u16, u64)],
primitive_operators: &[(&'a [u8], u64)],
operands: &[(&'a [u8], u64)],
) -> HalsteadMaps<'a> {
HalsteadMaps {
operators: operators.iter().copied().collect(),
primitive_operators: primitive_operators.iter().copied().collect(),
operands: operands.iter().copied().collect(),
}
}
/// `HalsteadMaps::operators` must stay on the crate's integer hasher.
///
/// Swapping a hasher moves no metric value, so every other test in
/// this file passes just as well with #1108 reverted. Both halves
/// here are needed: the typed binding stops compiling if the field
/// goes back to a default-hasher `HashMap`, and the `type_name`
/// comparison still fails at runtime if `IntKeyHashMap` itself is
/// ever redefined to wrap `RandomState`.
///
/// The two text-keyed maps are pinned to SipHash in the same test,
/// because moving *them* would be a regression rather than an
/// optimisation. `crate::int_hash`'s module doc is the single place
/// that argues why analysed source text does not qualify.
#[test]
fn halstead_operator_map_uses_the_int_key_hasher() {
use std::any::{type_name, type_name_of_val};
use std::hash::BuildHasherDefault;
use crate::int_hash::IntKeyHasher;
let maps = HalsteadMaps::new();
let operators: &IntKeyHashMap<u16, u64> = &maps.operators;
assert_eq!(
type_name_of_val(operators.hasher()),
type_name::<BuildHasherDefault<IntKeyHasher>>(),
"the kind_id-keyed operator map must use the int_hash hasher"
);
let siphash = type_name::<std::collections::hash_map::RandomState>();
assert_eq!(
type_name_of_val(maps.operands.hasher()),
siphash,
"operand keys come from the analysed source, so the keyed hash \
is what stops a crafted file from flooding this map"
);
assert_eq!(
type_name_of_val(maps.primitive_operators.hasher()),
siphash,
"primitive-operator keys come from the analysed source, so the \
keyed hash is what stops a crafted file from flooding this map"
);
}
/// `merge` sums overlapping keys and adopts disjoint ones, in all
/// three maps, and `finalize` reads the union back as n1/N1/n2/N2.
///
/// Every count differs from every other and none is zero, so a
/// dropped key, an overwrite where an addition belongs, or a map
/// crossed with its neighbour all change the totals.
#[test]
fn halstead_maps_merge_sums_overlaps_and_adopts_disjoint_keys() {
let mut parent = halstead_maps_of(
&[(1, 2), (2, 3)],
&[(b"int", 1)],
&[(b"alpha", 4), (b"beta", 7)],
);
let child = halstead_maps_of(
&[(2, 5), (7, 11)],
&[(b"double", 13)],
&[(b"alpha", 17), (b"gamma", 19)],
);
parent.merge(&child);
// expected: operators {1: 2, 2: 3+5, 7: 11}; primitives
// {int: 1, double: 13}; operands {alpha: 4+17, beta: 7,
// gamma: 19}.
assert_eq!(
parent,
halstead_maps_of(
&[(1, 2), (2, 8), (7, 11)],
&[(b"int", 1), (b"double", 13)],
&[(b"alpha", 21), (b"beta", 7), (b"gamma", 19)],
)
);
let mut stats = Stats::default();
parent.finalize(&mut stats);
// expected: n1 = 3 kind ids + 2 primitives; N1 = (2+8+11) +
// (1+13); n2 = 3 texts; N2 = 21+7+19.
assert_eq!(stats.unique_operators(), 5);
assert_eq!(stats.total_operators(), 35);
assert_eq!(stats.unique_operands(), 3);
assert_eq!(stats.total_operands(), 47);
}
/// Merging an empty child leaves the parent untouched.
///
/// A space with no operators or operands is the common case for a
/// leaf getter or an empty function body, and `finalize` runs on
/// the parent afterwards either way.
#[test]
fn halstead_maps_merge_of_empty_child_is_a_no_op() {
let mut parent = halstead_maps_of(&[(3, 5)], &[(b"char", 2)], &[(b"delta", 9)]);
let before = parent.clone();
parent.merge(&HalsteadMaps::new());
assert_eq!(parent, before);
let mut stats = Stats::default();
parent.finalize(&mut stats);
// expected: n1 = 1 kind id + 1 primitive; N1 = 5 + 2; n2 = 1;
// N2 = 9.
assert_eq!(stats.unique_operators(), 2);
assert_eq!(stats.total_operators(), 7);
assert_eq!(stats.unique_operands(), 1);
assert_eq!(stats.total_operands(), 9);
}
/// Folding a chain of nested spaces bottom-up must reach the union
/// of every level, re-merging already-merged maps on the way up.
///
/// This is what `spaces.rs` and `ops.rs` actually do: each space is
/// merged into its parent as the walk pops it, so by the time the
/// root sees a grandchild's counts they have already passed through
/// one `merge`. The literal expectation below is what discriminates
/// — the `nested == flat` cross-check on its own does not, because
/// any entry-wise fold over the same levels agrees with itself
/// however it is associated, including a broken one.
#[test]
fn halstead_maps_merge_folds_a_nested_chain() {
let levels = [
halstead_maps_of(&[(1, 1)], &[(b"int", 1)], &[(b"a", 1)]),
halstead_maps_of(&[(1, 2), (2, 3)], &[], &[(b"a", 2), (b"b", 4)]),
halstead_maps_of(&[(2, 5)], &[(b"long", 6)], &[(b"b", 7)]),
halstead_maps_of(&[(3, 8)], &[(b"int", 9)], &[(b"c", 10)]),
];
// Bottom-up: the deepest level folds into its parent, that
// result into *its* parent, and so on up to the root.
let mut nested = levels[levels.len() - 1].clone();
for level in levels.iter().rev().skip(1) {
let mut outer = level.clone();
outer.merge(&nested);
nested = outer;
}
// Flat: every level merged directly into the root.
let mut flat = levels[0].clone();
for level in &levels[1..] {
flat.merge(level);
}
// expected: every key summed across the four levels — operators
// {1: 1+2, 2: 3+5, 3: 8}, primitives {int: 1+9, long: 6},
// operands {a: 1+2, b: 4+7, c: 10}.
assert_eq!(
nested,
halstead_maps_of(
&[(1, 3), (2, 8), (3, 8)],
&[(b"int", 10), (b"long", 6)],
&[(b"a", 3), (b"b", 11), (b"c", 10)],
)
);
assert_eq!(nested, flat);
let mut stats = Stats::default();
nested.finalize(&mut stats);
// expected: n1 = 3 kind ids + 2 primitives; N1 = (3+8+8) +
// (10+6); n2 = 3 texts; N2 = 3+11+10.
assert_eq!(stats.unique_operators(), 5);
assert_eq!(stats.total_operators(), 35);
assert_eq!(stats.unique_operands(), 3);
assert_eq!(stats.total_operands(), 24);
}
/// A `kind_id` at the top of the `u16` range must behave like any
/// other key.
///
/// The largest grammar in the workspace (`mozcpp`) tops out around
/// 640 symbols, so nothing near `u16::MAX` occurs today — but the
/// map is keyed by the raw id, and a dense-array representation
/// (the shape #1108 considered and rejected) is exactly what such a
/// key would break. Pinning it keeps that trade-off honest if the
/// representation is ever revisited.
#[test]
fn halstead_maps_handle_the_full_kind_id_range() {
let mut parent = halstead_maps_of(&[(0, 3), (u16::MAX, 5)], &[], &[]);
parent.merge(&halstead_maps_of(&[(u16::MAX, 7)], &[], &[]));
let mut stats = Stats::default();
parent.finalize(&mut stats);
// expected: two distinct kind ids, occurrences 3 and 5+7.
assert_eq!(stats.unique_operators(), 2);
assert_eq!(stats.total_operators(), 15);
}
}