big-code-analysis 2.4.0

Tool to compute and export code metrics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
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
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
// 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;

// The operator / operand classification is syntactic and lives beside
// the per-language `Getter` tables that produce it; re-exported here
// because this metric is what consumes it.
pub use crate::token_role::TokenRole;

/// The former name of [`TokenRole`], kept so the
/// `metrics::halstead::HalsteadType` path still resolves.
///
/// The classification never was Halstead-specific — it answers whether
/// a node acts as an operator or an operand, which the grammar decides
/// and other consumers can use (#1376). Renaming it outright would be a
/// SemVer break, so the old spelling stays until the next major.
#[deprecated(
    since = "2.3.0",
    note = "renamed to `TokenRole`: the classification is syntactic, not Halstead-specific"
)]
pub type HalsteadType = TokenRole;

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,
}

/// 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. Also
    /// holds the operators a getter keys by a fixed spelling
    /// ([`Getter::get_operator_spelling`]), such as the generic `<>`
    /// pair (#1559).
    ///
    /// 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>,
) {
    // Halstead counts the tokens written, and a zero-width node spells
    // none, so it bills neither half (#1546). Error recovery is where
    // they come from: every MISSING node tree-sitter inserts for a token
    // the source lacks (a `;`, a `)`, an identifier) is zero-width, and
    // so is the identifier C#'s and Elixir's recovery builds without
    // flagging it MISSING. Checked here rather than per getter because
    // every getter that classifies the kind would otherwise bill it, an
    // identifier as the empty-string operand.
    if node.start_byte() == node.end_byte() {
        return;
    }
    match T::get_op_type_with_code(node, code, ancestors) {
        TokenRole::Operator => {
            if let Some(spelling) = T::get_operator_spelling(node, ancestors) {
                *halstead_maps
                    .primitive_operators
                    .entry(spelling.as_bytes())
                    .or_insert(0) += 1;
            } else 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;
            }
        }
        TokenRole::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 `big-code-analysis-ast/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::{BTreeSet, 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);

    // `HalsteadType` is the pre-#1376 name for `TokenRole`, kept as a
    // deprecated alias because removing it before `3.0` would be a
    // SemVer break (STABILITY.md). Nothing in this repository uses the
    // old spelling any more, so only this guard would notice it being
    // dropped — and dropping it silently is exactly what the promise
    // rules out.
    //
    // The `matches!` arms are the assertion: a value typed through the
    // alias can only be matched against `TokenRole`'s variants if the
    // alias still names that enum, so this fails to *compile* if the
    // alias is removed or re-pointed, rather than failing at runtime.
    // `TokenRole` derives nothing, so there is no `assert_eq!` to reach
    // for here.
    #[test]
    #[allow(deprecated)]
    fn halstead_type_alias_still_names_token_role() {
        let via_alias: HalsteadType = HalsteadType::Operand;
        assert!(matches!(via_alias, TokenRole::Operand));
        assert!(!matches!(via_alias, TokenRole::Operator));
    }

    /// Runs the `--ops` walk over `source` and returns the root space's
    /// merged vocabulary, with every nested space still reachable
    /// through [`crate::ops::Ops::spaces`].
    #[cfg(any(
        feature = "c",
        feature = "cpp",
        feature = "csharp",
        feature = "groovy",
        feature = "irules",
        feature = "java",
        feature = "javascript",
        feature = "kotlin",
        feature = "mozcpp",
        feature = "mozjs",
        feature = "objc",
        feature = "perl",
        feature = "ruby",
        feature = "tcl",
        feature = "typescript",
    ))]
    fn ops_of<T: crate::MetricSuite>(source: &str, file: &str) -> crate::ops::Ops {
        let path = PathBuf::from(file);
        let parser = T::new(source.as_bytes().to_vec(), &path, None);
        crate::ops::ops_inner(&parser, None).expect("ops walk succeeds")
    }

    // 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.
    #[cfg(any(
        feature = "c",
        feature = "cpp",
        feature = "groovy",
        feature = "irules",
        feature = "kotlin",
        feature = "mozcpp",
        feature = "objc",
        feature = "perl",
        feature = "ruby",
        feature = "tcl",
    ))]
    #[track_caller]
    fn assert_ops_operands<T: crate::MetricSuite>(
        source: &str,
        file: &str,
        expected_n2: usize,
        mut expected_operands: Vec<&str>,
    ) {
        let ops = ops_of::<T>(source, file);

        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 each keyword in `keywords` reaches the operand vocabulary
    /// and reaches the operator vocabulary nowhere.
    ///
    /// Both halves are load-bearing for #1380. A keyword listed in two
    /// arms is billed twice — once into `n1`/`N1` and once into
    /// `n2`/`N2` — and an assertion that only looked for its arrival
    /// among the operands would pass on that. The operator side is what
    /// pins the removal.
    #[cfg(any(
        feature = "cpp",
        feature = "csharp",
        feature = "groovy",
        feature = "java",
        feature = "kotlin",
        feature = "mozcpp",
        feature = "objc",
        feature = "typescript"
    ))]
    #[track_caller]
    fn assert_keywords_are_operands_only<T: crate::MetricSuite>(
        source: &str,
        file: &str,
        keywords: &[&str],
    ) {
        let ops = ops_of::<T>(source, file);

        for keyword in keywords {
            assert!(
                ops.operands.iter().any(|o| o == keyword),
                "{file}: `{keyword}` must be an operand; operands were {:?}",
                ops.operands
            );
            assert!(
                !ops.operators.iter().any(|o| o == keyword),
                "{file}: `{keyword}` must not be an operator; operators were {:?}",
                ops.operators
            );
        }
    }

    /// How one space's vocabularies classify a single keyword.
    #[derive(Debug, PartialEq, Eq)]
    enum Role {
        OperatorOnly,
        OperandOnly,
        Both,
    }

    /// Records `keyword`'s role in `ops` and in every space below it.
    ///
    /// A space that bills the keyword in neither vocabulary contributes
    /// no row, so the result is the set of places the keyword actually
    /// reaches — which is what distinguishes a parent gate from its own
    /// inverse, and what the merged root vocabulary cannot show.
    #[cfg(feature = "csharp")]
    fn collect_keyword_roles(ops: &crate::ops::Ops, keyword: &str, out: &mut Vec<Role>) {
        let operator = ops.operators.iter().any(|o| o == keyword);
        let operand = ops.operands.iter().any(|o| o == keyword);
        match (operator, operand) {
            (true, true) => out.push(Role::Both),
            (true, false) => out.push(Role::OperatorOnly),
            (false, true) => out.push(Role::OperandOnly),
            (false, false) => {}
        }
        for space in &ops.spaces {
            collect_keyword_roles(space, keyword, out);
        }
    }

    /// Pins the three grammar facts every #1380 operand arm rests on,
    /// over a fixture that samples one self- or super-reference per
    /// syntactic position the language allows.
    ///
    /// Each `keywords` row is `(spelling, kind_id, occurrences)`.
    ///
    /// * **Grammar-dispatch section 1.** Every node the grammar spells
    ///   `this` / `super` / `base` / `this@` / `super@` carries the one
    ///   `kind_id` its arm lists. An alias arises in a *different*
    ///   syntactic position, which no fixture can enumerate, so this is
    ///   the weaker half of the alias evidence — the strong half is that
    ///   these generated enums carry numeric-suffix aliases in quantity
    ///   and none spells a `This2`. What this loop catches is a grammar
    ///   bump introducing one under an existing fixture.
    /// * **Grammar-dispatch section 5.** Each is a childless leaf and no
    ///   node *containing* it is classified, so the reference cannot be
    ///   billed twice. Every ancestor is checked, not just the parent:
    ///   Kotlin puts `this_expression` *and* `navigation_expression`
    ///   between the leaf and the nearest classified node, and the claim
    ///   the arms make is about containment, not parentage.
    /// * **Grammar-dispatch section 11.** The arm is unconditional. A
    ///   parent-scoped guard added later — the shape the two deliberate
    ///   carve-outs use, and so the shape a reviewer might reasonably
    ///   add — would satisfy the single-position count tests and still
    ///   drop `this` in a method reference or a constructor delegation.
    ///
    /// The fixtures deliberately exclude the two gated positions (C#'s
    /// indexer declarator, Java's wildcard bound); those are operators,
    /// and their own tests pin them.
    #[cfg(any(feature = "csharp", feature = "java", feature = "kotlin"))]
    #[track_caller]
    fn assert_self_reference_leaves<L: LanguageInfo + Getter>(
        source: &str,
        keywords: &[(&str, u16, usize)],
        label: &str,
    ) {
        let code = source.as_bytes();
        let mut seen = vec![0_usize; keywords.len()];

        for_each_node_with_chain::<L>(code, |node, chain| {
            let Some(index) = keywords.iter().position(|(kw, _, _)| *kw == node.kind()) else {
                return;
            };
            let (keyword, kind_id, _) = keywords[index];
            seen[index] += 1;

            assert_eq!(
                node.kind_id(),
                kind_id,
                "{label}: a `{keyword}` carries kind_id {} rather than the {kind_id} its arm \
                 lists — an alias the arm cannot see",
                node.kind_id()
            );
            assert_eq!(
                node.child_count(),
                0,
                "{label}: `{keyword}` grew children, which the operand arm would now \
                 double-count against"
            );
            for (depth, ancestor) in chain.iter().enumerate() {
                assert!(
                    matches!(
                        L::get_op_type_with_code(ancestor, code, Ancestors::known(&chain[..depth])),
                        TokenRole::Unknown
                    ),
                    "{label}: `{}` contains a `{keyword}` and is itself classified, so the \
                     reference now counts twice",
                    ancestor.kind()
                );
            }
            // `_with_code` is the spelling `compute_halstead` calls. The
            // default forwards to the byte-less form, so asking the wrong
            // one reads as correct right up until a language grows an
            // override (grammar-dispatch section 7).
            assert!(
                matches!(
                    L::get_op_type_with_code(node, code, Ancestors::known(chain)),
                    TokenRole::Operand
                ),
                "{label}: a `{keyword}` under `{}` is not an operand",
                chain.last().map_or("<root>", Node::kind)
            );
        });

        for ((keyword, _, expected), got) in keywords.iter().zip(&seen) {
            assert_eq!(
                got, expected,
                "{label}: fixture holds {got} `{keyword}` rather than {expected}"
            );
        }
    }

    /// 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.
    #[cfg(any(
        feature = "bash",
        feature = "c",
        feature = "cpp",
        feature = "csharp",
        feature = "elixir",
        feature = "groovy",
        feature = "irules",
        feature = "java",
        feature = "javascript",
        feature = "kotlin",
        feature = "mozcpp",
        feature = "mozjs",
        feature = "objc",
        feature = "perl",
        feature = "php",
        feature = "ruby",
        feature = "tcl",
        feature = "typescript",
    ))]
    fn assert_halstead_counts<T: crate::MetricSuite>(
        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}"
                );
            },
        );
    }

    #[cfg(feature = "python")]
    #[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, (), : for each of the three headers,
                //   then =, =, =, +, +, + (the `()` and `:` since #1486)
                // unique operands: foo, bar, toto, a, b, c, 1, 2, 3
                // operands: foo, bar, toto, a, b, c, 1, 1, 2, a, 3, 3
                assert_eq!(metric.halstead.unique_operators(), 5);
                assert_eq!(metric.halstead.total_operators(), 15);
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r#"
                {
                  "unique_operators": 5,
                  "total_operators": 15,
                  "unique_operands": 9,
                  "total_operands": 12,
                  "length": 27,
                  "estimated_program_length": 40.13896548741762,
                  "purity_ratio": 1.4866283513858378,
                  "vocabulary": 14,
                  "volume": 102.79858289555531,
                  "difficulty": 3.3333333333333335,
                  "level": 0.3,
                  "effort": 342.6619429851844,
                  "time": 19.03677461028802,
                  "bugs": 0.01632259960095138
                }
                "#
                );
            },
        );
    }

    /// 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.
    #[cfg(feature = "c")]
    #[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.
    #[cfg(feature = "c")]
    #[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.
    #[cfg(feature = "c")]
    #[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);
            },
        );
    }

    #[cfg(feature = "cpp")]
    #[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.
    #[cfg(feature = "cpp")]
    #[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.
    #[cfg(feature = "cpp")]
    #[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.
    #[cfg(feature = "cpp")]
    #[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.
    #[cfg(feature = "cpp")]
    #[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, .*, the
            //   `operator` keyword (#1296) and `struct` (#1552).
            //   `.*` is the regression target — without the fix it
            //   falls through to `Unknown` and `u_operators` is 7.
            // Unique operands: S
            let s = &metric.halstead;
            assert_eq!(s.unique_operators(), 8);
            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.
    #[cfg(feature = "cpp")]
    #[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, ->*,
                //   the `operator` keyword (#1296) and `struct` (#1552).
                //   `->*` is the regression target — without the fix it
                //   falls through to `Unknown` and `u_operators` is 7.
                // Unique operands: S
                let s = &metric.halstead;
                assert_eq!(s.unique_operators(), 8);
                assert_eq!(s.unique_operands(), 1);
            },
        );
    }

    #[cfg(feature = "cpp")]
    #[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);
            },
        );
    }

    #[cfg(feature = "rust")]
    #[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
                }
                "#
                );
            },
        );
    }

    #[cfg(feature = "rust")]
    #[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
        // `big-code-analysis-ast/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). #1486 adds the
                // annotation `:` — one entry, 23 occurrences: `C`, the
                // two fields, `p`, the four params of `f`, and the
                // fifteen `let` bindings. #1559 bills `Option<u32>`'s
                // brackets as one `<>` pair: one entry and one
                // occurrence fewer.
                assert_eq!(metric.halstead.unique_operators(), 33);
                assert_eq!(metric.halstead.total_operators(), 143);
                // 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);
            },
        );
    }

    #[cfg(feature = "rust")]
    #[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
        // `TokenRole::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);
                // N1: fn, (), {} ×2, let ×2, = ×2, +, ; ×2, . ×2, `,`,
                // and the struct literal's two field `:` (#1486) = 16.
                assert_eq!(metric.halstead.unique_operators(), 10);
                assert_eq!(metric.halstead.total_operators(), 16);
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r#"
                {
                  "unique_operators": 10,
                  "total_operators": 16,
                  "unique_operands": 8,
                  "total_operands": 12,
                  "length": 28,
                  "estimated_program_length": 57.219280948873624,
                  "purity_ratio": 2.043545748174058,
                  "vocabulary": 18,
                  "volume": 116.75790004038474,
                  "difficulty": 7.5,
                  "level": 0.13333333333333333,
                  "effort": 875.6842503028855,
                  "time": 48.64912501682697,
                  "bugs": 0.03051010983631521
                }
                "#
                );
            },
        );
    }

    #[cfg(feature = "rust")]
    #[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
        // `TokenRole::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. #1486 then billed the two
        // annotation `:` tokens as their own entry: 12 and 21. #1559
        // billed each generic's brackets as one `<>` pair, replacing the
        // `<` and `>` entries and their four occurrences: 11 and 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.
                // `:` appears twice and stays distinct from `::`.
                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
                }
                "#
                );
            },
        );
    }

    /// #1486: Rust's single `:` is vocabulary in every position it is
    /// spelled, and stays a separate entry from `::`.
    #[cfg(feature = "rust")]
    #[test]
    fn rust_colon_is_operator_1486() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `let`, `:`, `u8`, `=`, `;`
            ("let annotation", "let x: u8 = 1;\n", [5, 5]),
            // `struct`, `{}`, `:`, `u8`
            ("field declaration", "struct S { a: u8 }\n", [4, 4]),
            // `const`, `:` twice, `=`, `{}`, `;`
            ("field initializer", "const C: S = S { a: 1 };\n", [5, 6]),
            // `fn`, `{}` twice, `()`, `let`, `{}` (pattern), `:`, `=`, `;`
            ("field pattern", "fn f() { let S { a: b } = s; }\n", [7, 8]),
            // `fn`, `()`, `:`, `u8`, `{}`
            ("parameter", "fn f(x: u8) {}\n", [5, 5]),
            // `fn`, `<>`, `:`, `()`, `{}`
            ("trait bound", "fn f<T: Clone>() {}\n", [5, 5]),
            // `fn`, `<>`, `()`, `where`, `:`, `{}`
            ("where clause", "fn f<T>() where T: Clone {}\n", [6, 6]),
            // `fn`, `()`, `{}` twice, `:`, `loop`, `break`, `;`
            ("loop label", "fn f() { 'a: loop { break 'a; } }\n", [7, 8]),
            // `fn`, `()`, `{}`, `let`, `=`, `|` twice, `:`, `u8`, `;`
            (
                "closure parameter",
                "fn f() { let c = |q: u8| q; }\n",
                [9, 10],
            ),
            // `fn`, `()` twice, `{}`, `let`, `:`, `<>`, `u8`, `=`, `::`,
            // `;` — `:` and `::` are two entries
            (
                "beside a path",
                "fn f() { let v: Vec<u8> = Vec::new(); }\n",
                [10, 11],
            ),
        ];
        assert_operator_rows::<RustParser>("foo.rs", ROWS);
    }

    #[cfg(feature = "rust")]
    #[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
        // TokenRole::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);
            },
        );
    }

    #[cfg(feature = "rust")]
    #[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);
            },
        );
    }

    #[cfg(feature = "javascript")]
    #[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
                }
                "#
                );
            },
        );
    }

    #[cfg(feature = "mozjs")]
    #[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
                }
                "#
                );
            },
        );
    }

    #[cfg(feature = "typescript")]
    #[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
                }
                "#
                );
            },
        );
    }

    #[cfg(feature = "typescript")]
    #[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
                }
                "#
                );
            },
        );
    }

    #[cfg(feature = "javascript")]
    #[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 `TokenRole::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.
    #[cfg(feature = "javascript")]
    #[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
        );
    }

    #[cfg(feature = "javascript")]
    #[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);
            },
        );
    }

    #[cfg(feature = "mozjs")]
    #[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);
        });
    }

    #[cfg(feature = "mozjs")]
    #[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);
            },
        );
    }

    /// One JSX shape per row of #1483's decision: the source, the
    /// expected `n2` / `N2`, and the deduplicated operand vocabulary.
    /// Every row is a single element bound to `a`, so the operands
    /// outside the element's content are always `a` plus the tag names.
    #[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    const JSX_TEXT_CASES: &[(&str, &str, [u64; 2], &[&str])] = &[
        // Element text is one operand. N2: a, p x2 (both tags), hi.
        ("text", "const a = <p>hi</p>;\n", [3, 4], &["a", "p", "hi"]),
        // The same-line space between `<b/>` and `<i/>` is a jsx_text
        // node of its own, and bills nothing. Billing it would key an
        // empty operand: (5, 6).
        (
            "whitespace",
            "const a = <p><b/> <i/></p>;\n",
            [4, 5],
            &["a", "p", "b", "i"],
        ),
        // `Start` at two indentation depths is one distinct operand,
        // because the key is the trimmed text. Untrimmed: (5, 7).
        (
            "indentation",
            "const a = (\n  <p>\n    Start\n    <span>\n      Start\n    </span>\n  </p>\n);\n",
            [4, 7],
            &["a", "p", "span", "Start"],
        ),
        // An entity splits the text into three siblings, each an
        // operand. Without the entity arm: (4, 5).
        (
            "entity in text",
            "const a = <p>x &amp; y</p>;\n",
            [5, 6],
            &["a", "p", "x", "&amp;", "y"],
        ),
        // Inside an attribute string the entity is part of the string
        // operand and bills nothing of its own. Without the parent
        // guard: (5, 5).
        (
            "entity in attribute",
            "const a = <p title=\"x &amp; y\" />;\n",
            [4, 4],
            &["a", "p", "title", "\"x &amp; y\""],
        ),
        // An expression child is unchanged by #1483: its identifier was
        // already an operand.
        (
            "expression",
            "const a = <p>{v}</p>;\n",
            [3, 4],
            &["a", "p", "v"],
        ),
    ];

    /// Asserts every row of [`JSX_TEXT_CASES`] under parser `T`, through
    /// the metrics store (`n2` / `N2`) and the `--ops` vocabulary.
    #[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    #[track_caller]
    fn assert_jsx_text_operands<T: crate::MetricSuite>(file: &str) {
        for (label, source, expected, vocabulary) in JSX_TEXT_CASES {
            crate::test_support::check_func_space_only::<T, _>(
                source,
                file,
                &[crate::Metric::Halstead],
                |space| {
                    let halstead = &space.metrics.halstead;
                    assert_eq!(
                        [halstead.unique_operands(), halstead.total_operands()],
                        *expected,
                        "{file}: {label}"
                    );
                },
            );
            let ops = ops_of::<T>(source, file);
            let got: BTreeSet<&str> = ops.operands.iter().map(String::as_str).collect();
            let want: BTreeSet<&str> = vocabulary.iter().copied().collect();
            assert_eq!(got, want, "{file}: {label} operand vocabulary");
        }
    }

    /// Regression for #1483: JSX element text and its character
    /// references are operands. One row per grammar, so reverting one
    /// invocation's `jsx:` argument fails its own row.
    #[cfg(all(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    #[test]
    fn jsx_text_is_an_operand() {
        // A whitespace-only node bills nothing, so no count can tell the
        // "whitespace" row's fixture from one that stopped spelling the
        // same-line space. Pin the node's presence directly.
        let (_, source, _, _) = JSX_TEXT_CASES
            .iter()
            .find(|(label, ..)| *label == "whitespace")
            .expect("the whitespace row exists");
        let parser =
            JavascriptParser::new(source.as_bytes().to_vec(), &PathBuf::from("foo.jsx"), None);
        assert!(
            parser.root().preorder().any(|n| {
                n.kind_id() == Javascript::JsxText as u16
                    && source.as_bytes()[n.start_byte()..n.end_byte()]
                        .trim_ascii()
                        .is_empty()
            }),
            "the whitespace row must carry a whitespace-only jsx_text node"
        );

        assert_jsx_text_operands::<JavascriptParser>("foo.jsx");
        assert_jsx_text_operands::<MozjsParser>("foo.js");
        assert_jsx_text_operands::<TsxParser>("foo.tsx");
    }

    /// The `.ts` grammar's enum carries `JsxText` in the externals it
    /// shares with TSX, but no production emits it, which is why the
    /// TypeScript invocation passes no `jsx:` argument (#1483). Pinned
    /// so a grammar that starts emitting it cannot go unbilled quietly.
    #[cfg(feature = "typescript")]
    #[test]
    fn typescript_never_emits_jsx_text() {
        let parser = TypescriptParser::new(
            b"const a = <p>hi</p>;\nlet b = <T>(x);\n".to_vec(),
            &PathBuf::from("foo.ts"),
            None,
        );
        // The positive half: the parse reached the angle-bracket syntax
        // TSX would read as JSX, so the absence below is a property of
        // the grammar rather than of a parse that produced nothing.
        assert!(
            ast_has_kind_id(&parser, Typescript::TypeAssertion as u16),
            "fixture lost the `<T>(x)` type assertion"
        );
        assert!(
            !ast_has_kind_id(&parser, Typescript::JsxText as u16),
            "the .ts grammar now emits jsx_text; give its invocation a `jsx:` argument"
        );
    }

    #[cfg(feature = "typescript")]
    #[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);
            },
        );
    }

    #[cfg(feature = "typescript")]
    #[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);
            },
        );
    }

    #[cfg(feature = "typescript")]
    #[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);
            },
        );
    }

    #[cfg(feature = "typescript")]
    #[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).
    #[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    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");
    }

    #[cfg(all(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    #[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]);
    }

    #[cfg(all(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    #[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]);
    }

    #[cfg(all(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    #[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.
    #[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    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.
    #[cfg(feature = "javascript")]
    #[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);
        });
    }

    #[cfg(feature = "mozjs")]
    #[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);
        });
    }

    #[cfg(feature = "typescript")]
    #[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);
        });
    }

    #[cfg(feature = "typescript")]
    #[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.
    #[cfg(all(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    #[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.
        #[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))]
        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.
    #[cfg(all(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    #[test]
    fn js_family_member_access_counts_leaves_not_the_composite_1263() {
        #[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))]
        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: `class`, `{`×2 (class body, method body), `=`,
    //   `;`×2, `(`, `return`, `.` — 9 total, 7 unique. (`class` joined
    //   the JS-family operator arm in #1552.)
    // * Operands: `C`, `#x`, `1`, `m`, `this`, `#x` — 6 total, 5
    //   unique in all four grammars. Under TS/TSX the class *name* `C`
    //   is a `type_identifier`, which those getters did not classify
    //   until #1557, so they read 5/4 before it.
    #[cfg(all(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    #[test]
    fn js_family_private_field_leaf_is_the_operand_1263() {
        #[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))]
        const SRC: &str = "class C { #x = 1; m() { return this.#x; } }";
        let check = |m: crate::CodeMetrics| {
            assert_eq!(m.halstead.unique_operators(), 7);
            assert_eq!(m.halstead.total_operators(), 9);
            assert_eq!(m.halstead.unique_operands(), 5);
            assert_eq!(m.halstead.total_operands(), 6);
        };

        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 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.
    #[cfg(all(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    #[test]
    fn js_family_meta_property_is_one_operand_1263() {
        #[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))]
        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: `namespace`, `.`, `{` — 3 total, 3 unique.
    //   (`namespace` joined the TS operator extras in #1557.)
    // * Operands: `N`, `M` — 2 total, 2 unique. Before the fix the
    //   `nested_identifier` added `N.M`, making both 3.
    #[cfg(feature = "typescript")]
    #[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(), 3);
            assert_eq!(m.halstead.total_operators(), 3);
            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.
    #[cfg(feature = "typescript")]
    #[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).
    #[cfg(feature = "typescript")]
    #[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.
    #[cfg(feature = "typescript")]
    #[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.
    #[cfg(feature = "typescript")]
    #[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`.
    #[cfg(feature = "typescript")]
    #[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);
    }

    #[cfg(feature = "python")]
    #[test]
    fn python_wrong_operators() {
        // Not valid Python — the parser recovers `()` as a tuple, the `[`
        // as a bare token and `{}` as a dict — but each opener is still a
        // delimiter the source spells, so since #1486 the three are
        // billed once each as `()`, `[]` and `{}`. The closers never are.
        check_metrics::<PythonParser>("()[]{}", "foo.py", |metric| {
            assert_eq!(metric.halstead.unique_operators(), 3);
            assert_eq!(metric.halstead.total_operators(), 3);
            insta::assert_json_snapshot!(
                metric.halstead,
                @r#"
            {
              "unique_operators": 3,
              "total_operators": 3,
              "unique_operands": 0,
              "total_operands": 0,
              "length": 3,
              "estimated_program_length": 4.754887502163468,
              "purity_ratio": 1.584962500721156,
              "vocabulary": 3,
              "volume": 4.754887502163468,
              "difficulty": 0.0,
              "level": 0.0,
              "effort": 0.0,
              "time": 0.0,
              "bugs": 0.0
            }
            "#
            );
        });
    }

    #[cfg(feature = "python")]
    #[test]
    fn python_check_metrics() {
        check_metrics::<PythonParser>(
            "def f():
                 pass",
            "foo.py",
            |metric| {
                // expected operators: def, (), :, pass — one each (#1486
                // added the `()` and the block `:`).
                assert_eq!(metric.halstead.unique_operators(), 4);
                assert_eq!(metric.halstead.total_operators(), 4);
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r#"
                {
                  "unique_operators": 4,
                  "total_operators": 4,
                  "unique_operands": 1,
                  "total_operands": 1,
                  "length": 5,
                  "estimated_program_length": 8.0,
                  "purity_ratio": 1.6,
                  "vocabulary": 5,
                  "volume": 11.60964047443681,
                  "difficulty": 2.0,
                  "level": 0.5,
                  "effort": 23.21928094887362,
                  "time": 1.289960052715201,
                  "bugs": 0.002712967490108627
                }
                "#
                );
            },
        );
    }

    #[cfg(feature = "java")]
    #[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=14): public static class {} void () [] , . ; int = + /
                // (`public` x2 and `static` since #1565)
                // Operands (n2=13): Main main string args a b c avg 5 3 MessageFormat format "{0}"
                // (`string` is the parameter's type name, an operand since #1560)
                assert_eq!(metric.halstead.unique_operators(), 14);
                assert_eq!(metric.halstead.total_operators(), 30);
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r#"
                {
                  "unique_operators": 14,
                  "total_operators": 30,
                  "unique_operands": 13,
                  "total_operands": 23,
                  "length": 53,
                  "estimated_program_length": 101.40868524464065,
                  "purity_ratio": 1.913371419710201,
                  "vocabulary": 27,
                  "volume": 252.0090376146638,
                  "difficulty": 12.384615384615385,
                  "level": 0.08074534161490683,
                  "effort": 3121.035004304683,
                  "time": 173.3908335724824,
                  "bugs": 0.07118871793971378
                }
                "#
                );
            },
        );
    }

    #[cfg(feature = "java")]
    #[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. The other five operators
                // are `public` (#1565), `class` (#1552), `{}`, `=` and `;`.
                assert_eq!(metric.halstead.unique_operators(), 13);
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r#"
                {
                  "unique_operators": 13,
                  "total_operators": 30,
                  "unique_operands": 19,
                  "total_operands": 19,
                  "length": 49,
                  "estimated_program_length": 128.8163390912623,
                  "purity_ratio": 2.6289048794135166,
                  "vocabulary": 32,
                  "volume": 245.0,
                  "difficulty": 6.5,
                  "level": 0.15384615384615385,
                  "effort": 1592.5,
                  "time": 88.47222222222223,
                  "bugs": 0.04545674902336332
                }
                "#
                );
            },
        );
    }

    // #1380: `this` and `super` were swept into the operator arm under a
    // `// Operator: … keywords` heading — classification by lexical
    // class rather than by Halstead role. A member access is
    // `<receiver> <op> <field>`, so billing the receiver as an operator
    // scored `this.x` as a binary operator with one operand while `p.x`
    // is one operator and two operands. Both are operands now, matching
    // the eleven other languages that classify a self-reference.
    #[cfg(feature = "java")]
    #[test]
    fn java_self_and_super_references_are_operands() {
        let source = "class T {\n    int f() { return this.x + super.y; }\n}";
        // Operators (n1=8, N1=10): class (#1552), {} x2, int, (),
        // return, . x2, +, ;
        // Operands (n2=6, N2=6): T, f, this, x, super, y
        // Before the fix this read (10, 12, 4, 4) — `this` and `super`
        // billed into the operator side of both counts.
        assert_halstead_counts::<JavaParser>(
            source,
            "foo.java",
            [8, 10, 6, 6],
            "java self/super references",
        );
        assert_keywords_are_operands_only::<JavaParser>(source, "foo.java", &["this", "super"]);
    }

    // The `super` of a wildcard type bound denotes no value, so it keeps
    // the operator classification `? extends T`'s `extends` already has
    // — the two keywords are siblings under the same `wildcard` node and
    // nothing but the parent separates them from a real self-reference
    // (#1380). The explicit receiver parameter in the same fixture is
    // the independent path through the operand arm (grammar-dispatch
    // section 11): only it can put `this` in the operand vocabulary
    // here, and only the wildcard can put `super` in the operator one.
    #[cfg(feature = "java")]
    #[test]
    fn java_wildcard_super_bound_stays_an_operator() {
        let source = "import java.util.List;\n\
                      class T {\n    \
                      void m(T T.this, List<? super String> a, List<? extends String> b) { }\n\
                      }";
        let ops = ops_of::<JavaParser>(source, "foo.java");

        assert!(
            ops.operators.iter().any(|o| o == "super"),
            "`? super String` must keep `super` an operator; operators were {:?}",
            ops.operators
        );
        assert!(
            !ops.operands.iter().any(|o| o == "super"),
            "a wildcard bound must not bill `super` as an operand; operands were {:?}",
            ops.operands
        );
        assert!(
            ops.operators.iter().any(|o| o == "extends"),
            "the fixture must still contain the `? extends String` \
             bound this arm mirrors; operators were {:?}",
            ops.operators
        );
        assert_keywords_are_operands_only::<JavaParser>(source, "foo.java", &["this"]);
    }

    /// One `this` and one `super` per container the pinned
    /// `tree-sitter-java` can put them in: a delegating constructor
    /// call, an explicit superclass constructor call, a field access, a
    /// method-invocation receiver, a method reference, a call argument,
    /// and the two qualified forms an inner class allows.
    #[cfg(feature = "java")]
    const JAVA_SELF_POSITIONS: &str = "class Pos extends P {
        int x;
        Pos() { this(1); }
        Pos(int v) { super(v); this.x = v; }
        int a() { return this.x; }
        int b() { return super.h(); }
        java.util.function.IntSupplier c() { return this::a; }
        void d() { g(this); }
        void g(Object o) { }
        class In {
            int e() { return Pos.this.x; }
            int f() { return Pos.super.h(); }
        }
    }";

    #[cfg(feature = "java")]
    #[test]
    fn java_self_and_super_leaves_are_unaliased_and_unconditional() {
        assert_self_reference_leaves::<JavaCode>(
            JAVA_SELF_POSITIONS,
            &[
                ("this", Java::This as u16, 6),
                ("super", Java::Super as u16, 3),
            ],
            "java",
        );
    }

    // Groovy's `Super` arm, pinned from all three sides. The pinned
    // grammar emits the `super` token only as a `wildcard` bound, where it
    // is an operator exactly as in Java above; every super-*reference* is
    // a plain `identifier`, and so an operand.
    //
    // Since #1419 the arm carries Java's `Wildcard` parent gate, so the
    // bound half below exercises the gate's operator branch — inverting
    // the gate fails it. The gate's operand branch is unreachable under
    // the pin (only error recovery on invalid Groovy, `List<? super>`,
    // detaches a `super` token from its `wildcard`), so it is
    // deliberately untested rather than pinned against an invalid
    // fixture. The node census is the drift marker for it: a grammar bump
    // that routes a reference to `Groovy::Super` fails here by name.
    #[cfg(feature = "groovy")]
    #[test]
    fn groovy_wildcard_super_bound_stays_an_operator() {
        let bounds =
            "class T {\n    void m(List<? super String> a, List<? extends String> b) { }\n}";
        let ops = ops_of::<GroovyParser>(bounds, "foo.groovy");
        assert!(
            ops.operators.iter().any(|o| o == "super"),
            "`? super String` must keep `super` an operator; operators were {:?}",
            ops.operators
        );
        assert!(
            !ops.operands.iter().any(|o| o == "super"),
            "a wildcard bound must not bill `super` as an operand; operands were {:?}",
            ops.operands
        );
        assert!(
            ops.operators.iter().any(|o| o == "extends"),
            "the fixture must still contain the `? extends String` bound this arm \
             mirrors; operators were {:?}",
            ops.operators
        );

        let mixed = "class T extends B {\n    void m(List<? super String> a) { super.h() }\n}";
        let mut tokens = 0;
        for_each_node_with_chain::<GroovyCode>(mixed.as_bytes(), |node, chain| {
            if node.kind_id() == Groovy::Super as u16 {
                tokens += 1;
                assert_eq!(
                    chain.last().map(Node::kind_id),
                    Some(Groovy::Wildcard as u16),
                    "groovy: a `super` token outside a wildcard bound now reaches \
                     the gate's operand branch, which the pinned grammar made \
                     unreachable — re-check the arm against the new grammar (#1419)"
                );
            }
        });
        assert_eq!(
            tokens, 1,
            "the fixture's one wildcard bound must still spell `super`, and its \
             `super.h()` reference must not"
        );

        // The reference direction, on valid input the gate must leave
        // alone: every super-reference form the grammar accepts stays an
        // operand, so splitting `Super` out of the operator alternation
        // cannot have moved one. `this` rides along for the same reason
        // Java's test carries it.
        let refs = "class A extends B {\n    A() { super(1) }\n    \
                    def g() { return super.h() }\n    \
                    def i() { return A.super.h() }\n    \
                    def j() { return super::h }\n    \
                    def k() { return super?.h() }\n    \
                    def l() { return this.x }\n}";
        assert_keywords_are_operands_only::<GroovyParser>(refs, "foo.groovy", &["super", "this"]);
    }

    #[cfg(feature = "groovy")]
    #[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 the primitive type names
                // `void` and `int` as `type_identifier`, the kind of
                // `String`; since #1568 their spelling bills them as
                // operators, as Java's keyword tokens are, while
                // `String` stays an operand.
                // `class` is an operator since #1552, `static` since
                // #1565, and `void` and `int` since #1568.
                assert_eq!(metric.halstead.unique_operators(), 12);
                assert_eq!(metric.halstead.unique_operands(), 11);
                // `bugs` is `effort.powf(2/3) / 3000`, and the platform libm's
                // `powf` differs in the last ulp: macOS rendered this value
                // as `…92342184` where Linux and Windows gave `…923421845`.
                // Round it so the snapshot pins the metric, not the libm.
                insta::assert_json_snapshot!(
                    metric.halstead,
                    { ".bugs" => insta::rounded_redaction(12) },
                    @r#"
                {
                  "unique_operators": 12,
                  "total_operators": 26,
                  "unique_operands": 11,
                  "total_operands": 21,
                  "length": 47,
                  "estimated_program_length": 81.07329781366414,
                  "purity_ratio": 1.7249637832694498,
                  "vocabulary": 23,
                  "volume": 212.60741193467962,
                  "difficulty": 11.454545454545455,
                  "level": 0.0873015873015873,
                  "effort": 2435.3212639790577,
                  "time": 135.29562577661432,
                  "bugs": 0.06033688972
                }
                "#
                );
            },
        );
    }

    #[cfg(feature = "groovy")]
    #[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`;
                // since #1568 each bills as a distinct operator keyed by
                // its text, as Java's `java_primitive_ops` twin does.
                // 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`.
                // expected: operators `=` x9, `class`, `{}` and the eight
                // primitives (`boolean` twice) — n1 11, N1 20; operands
                // `Prims`, the nine names and nine values — n2 19, N2 19.
                assert_eq!(metric.halstead.unique_operators(), 11);
                assert_eq!(metric.halstead.total_operators(), 20);
                assert_eq!(metric.halstead.unique_operands(), 19);
                assert_eq!(metric.halstead.total_operands(), 19);
                insta::assert_json_snapshot!(
                    metric.halstead,
                    @r#"
                {
                  "unique_operators": 11,
                  "total_operators": 20,
                  "unique_operands": 19,
                  "total_operands": 19,
                  "length": 39,
                  "estimated_program_length": 118.76437056043838,
                  "purity_ratio": 3.045240270780471,
                  "vocabulary": 30,
                  "volume": 191.36873322873222,
                  "difficulty": 5.5,
                  "level": 0.18181818181818182,
                  "effort": 1052.5280327580272,
                  "time": 58.47377959766818,
                  "bugs": 0.0344906352248725
                }
                "#
                );
            },
        );
    }

    // 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.
    #[cfg(feature = "groovy")]
    #[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.
    #[cfg(feature = "groovy")]
    #[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);
        });
    }

    #[cfg(feature = "groovy")]
    #[test]
    fn groovy_closure_operators_and_operands() {
        // `twice`, not the original `double`: Groovy reserves the
        // primitive type names, so `def double` is not valid Groovy and
        // `double` would bill as the primitive operator (#1568).
        check_metrics::<GroovyParser>("def twice = { x -> x * 2 }", "foo.groovy", |metric| {
            // Closure with arrow-style parameter list.
            // Distinct operators: def, =, {}, ->, * = 5.
            // Distinct operands: twice, 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).
    #[cfg(feature = "groovy")]
    #[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)",
                );
            },
        );
    }

    #[cfg(feature = "groovy")]
    #[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"]);
    }

    #[cfg(feature = "groovy")]
    #[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"]);
    }

    // `Groovy::Identifier2` (141) is the grammar's external token
    // `_gstring_dollar_path` — the `$a.b` path of a dollar interpolation —
    // whose public symbol is `identifier`, so the parser reports it as
    // the unsuffixed `Identifier` and never as 141 (#1475). That is why
    // the operand arm lists `Identifier` but not `Identifier2`; if a
    // grammar bump starts emitting 141, the dotted path drops out of N2
    // with no error.
    //
    // expected: operands `greet`, `name` (param), `$name.b` (the whole
    // path, one node) → n2 = 3, N2 = 3.
    #[cfg(feature = "groovy")]
    #[test]
    fn groovy_gstring_dollar_path_is_the_public_identifier() {
        let src = "def greet(name) {\n  return \"Hi $name.b\"\n}\n";
        let parser = GroovyParser::new(src.as_bytes().to_vec(), &PathBuf::from("foo.groovy"), None);
        assert!(
            ast_has_kind_id(&parser, Groovy::GstringDollarInterpolation as u16),
            "the fixture no longer spells a dollar interpolation",
        );
        assert!(
            !ast_has_kind_id(&parser, Groovy::Identifier2 as u16),
            "the hidden `_gstring_dollar_path` token is now emitted as \
             `Identifier2`; add it to the Groovy operand arm",
        );
        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.b"]);
    }

    #[cfg(feature = "groovy")]
    #[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\""]);
    }

    #[cfg(feature = "groovy")]
    #[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);
            },
        );
    }

    #[cfg(feature = "groovy")]
    #[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);
        });
    }

    #[cfg(feature = "groovy")]
    #[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);
            },
        );
    }

    #[cfg(feature = "groovy")]
    #[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}"),
            );
        }
    }

    #[cfg(feature = "csharp")]
    #[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.
    #[cfg(feature = "csharp")]
    #[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` — 8 total, 7 unique (`int` is the text-keyed primitive
        // operator, per #286; `<>` is the type-argument pair, #1559). 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(), 7);
                assert_eq!(metric.halstead.total_operators(), 8);
                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);
            },
        );
    }

    #[cfg(feature = "csharp")]
    #[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);
            },
        );
    }

    #[cfg(feature = "csharp")]
    #[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);
            },
        );
    }

    #[cfg(feature = "csharp")]
    #[test]
    fn csharp_operator_true_names_an_operator_not_a_value() {
        // 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. There the keyword names
        // the operator being declared, as `+` does in `operator +`, so it
        // is an operator (#1296); the companion test above pins the
        // wrapped literal, which bills only its wrapper (#1253).
        //
        // Each declaration names one boolean and returns the other, so
        // the fixture carries each keyword once as a name and once as a
        // value.
        //
        // Operators (n1 = 11, N1 = 18): class 1, {} 1, public 2,
        // static 2, bool 2, operator 2, true 1, false 1, () 2, => 2,
        // ; 2. Operands (n2 = 4, N2 = 7): A × 3 (class name, two
        // parameter types), a × 2, and the literals false and true once
        // each. Before #1296 the two names were operands instead:
        // (9, 16, 4, 9). A blanket exclusion of the leaf would give
        // (9, 16, 4, 7), and no guard at all (11, 18, 4, 9).
        let source = "class A {\n    public static bool operator true(A a) => false;\n    public static bool operator false(A a) => true;\n}\n";
        assert_halstead_counts::<CsharpParser>(source, "foo.cs", [11, 18, 4, 7], "operator true");

        // `true` and `false` are each an operator *and* an operand here,
        // once apiece: the name and the literal land in different halves.
        let ops = ops_of::<CsharpParser>(source, "foo.cs");
        for keyword in ["true", "false"] {
            for (half, list) in [("operators", &ops.operators), ("operands", &ops.operands)] {
                assert_eq!(
                    list.iter().filter(|o| *o == keyword).count(),
                    1,
                    "`{keyword}` must appear once among the {half}; they were {list:?}"
                );
            }
        }

        // The fallback arm: outside both positions — here a bare `true`
        // under error recovery, the only other parent the grammar
        // produces — the keyword keeps its role as a value.
        assert_halstead_counts::<CsharpParser>("true\n", "foo.cs", [0, 0, 1, 1], "bare true");
    }

    #[cfg(feature = "csharp")]
    #[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);
            },
        );
    }

    #[cfg(feature = "csharp")]
    #[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);
            },
        );
    }

    #[cfg(feature = "csharp")]
    #[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);
            },
        );
    }

    #[cfg(feature = "csharp")]
    #[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);
            },
        );
    }

    /// #1573: an interpolation's alignment `,` and format `:` delimit the
    /// field, as Python's format-spec `:` does (#1486), and bill nothing.
    /// The alignment value is an ordinary expression, so `8`, `Width`
    /// and `-w` keep their vocabulary. The guard reads the token's
    /// parent: the last seven rows put the same `,` / `:` inside and
    /// outside a hole in a position that is not a clause, and each keeps
    /// billing. Pre-fix, every row with a clause billed one extra `,`
    /// and/or `:`.
    ///
    /// Each row is `(label, source, operators, operands)`, the two
    /// vocabularies space-separated. No row repeats a token, so the
    /// expected `[n1, N1, n2, N2]` is the two vocabulary sizes, each twice.
    #[cfg(feature = "csharp")]
    #[test]
    fn csharp_interpolation_clause_delimiters_are_not_operators_1573() {
        const ROWS: &[(&str, &str, &str, &str)] = &[
            ("control", "s = $\"{x}\";", "; =", "s x"),
            ("format", "s = $\"{x:F2}\";", "; =", "s x"),
            ("alignment", "s = $\"{x,8}\";", "; =", "8 s x"),
            ("both", "s = $\"{x,8:F2}\";", "; =", "8 s x"),
            // a `const` width is a `constant_expression` the spec allows
            ("named width", "s = $\"{x,Width}\";", "; =", "Width s x"),
            ("negated width", "s = $\"{x,-w}\";", "- ; =", "s w x"),
            // the format string's `,` is text, not a token
            ("comma in format", "s = $\"{x:#,##0}\";", "; =", "s x"),
            ("raw", "s = $$\"\"\"{{x,8:F2}}\"\"\";", "; =", "8 s x"),
            ("verbatim", "s = $@\"{x:F2}\";", "; =", "s x"),
            ("call in hole", "s = $\"{f(a, b)}\";", "() , ; =", "a b f s"),
            (
                "ternary in hole",
                "s = $\"{(a ? b : c)}\";",
                "() : ; = ?",
                "a b c s",
            ),
            (
                "named arg in hole",
                "s = $\"{f(x: 1)}\";",
                "() : ; =",
                "1 f s x",
            ),
            ("ternary", "s = a ? b : c;", ": ; = ?", "a b c s"),
            ("named argument", "f(x: 1);", "() : ;", "1 f x"),
            (
                "case label",
                "switch (x) { case 1: break; }",
                "() : ; break case switch {}",
                "1 x",
            ),
            ("argument list", "f(a, b);", "() , ;", "a b f"),
        ];
        for (label, source, operators, operands) in ROWS {
            // `bca ops` sorts its vocabulary, so the observation is
            // compared as returned; the rows are written in that order.
            let operators: Vec<&str> = operators.split(' ').collect();
            let operands: Vec<&str> = operands.split(' ').collect();
            let ops = ops_of::<CsharpParser>(source, "foo.cs");
            assert_eq!(ops.operators, operators, "{label}: {source:?}");
            assert_eq!(ops.operands, operands, "{label}: {source:?}");
            let n1 = operators.len() as u64;
            let n2 = operands.len() as u64;
            assert_halstead_counts::<CsharpParser>(source, "foo.cs", [n1, n1, n2, n2], label);
        }
    }

    // C# half of #1380 — see `java_self_and_super_references_are_operands`
    // for the structural argument. `base` moves with `this`: both are
    // receivers of a member access.
    #[cfg(feature = "csharp")]
    #[test]
    fn csharp_self_and_base_references_are_operands() {
        let source = "class T {\n    int F() { return this.x + base.y; }\n}";
        // Operators (n1=8, N1=10): class, {} x2, int, (), return, . x2, +, ;
        // Operands (n2=6, N2=6): T, F, this, x, base, y
        // Before the fix this read (10, 12, 4, 4).
        assert_halstead_counts::<CsharpParser>(
            source,
            "foo.cs",
            [8, 10, 6, 6],
            "csharp self/base references",
        );
        assert_keywords_are_operands_only::<CsharpParser>(source, "foo.cs", &["this", "base"]);
    }

    // An `indexer_declaration` spells the member's *name* with the same
    // `this` token kind the receiver uses (both are kind 91), so a
    // blanket move would have billed a declarator keyword as a value.
    // The declaration keeps the operator classification that the
    // `operator` keyword of an overload declaration already has (#1380).
    //
    // The fixture carries both uses, which is what makes the gate
    // observable: `this` has to reach *both* vocabularies from one file.
    // Asserting only the operand side would pass with the gate deleted,
    // and only the operator side would pass with the whole #1380 change
    // reverted (grammar-dispatch section 11).
    #[cfg(feature = "csharp")]
    #[test]
    fn csharp_indexer_declaration_keyword_is_not_a_self_reference() {
        let source = "class C {\n    int[] _a;\n    \
                      public int this[int i] { get { return this._a[i]; } }\n}";

        // Asserted per space, not through the root. The root merges
        // every space's vocabulary, and the fixture has one declarator
        // `this` and one receiver `this`, so at the root `this` is a
        // member of *both* vocabularies whether the gate is right or
        // exactly backwards — and every Halstead count is bit-identical
        // under the swap, one occurrence on each side either way. The
        // space tree is where the two uses stay apart: the declarator
        // sits in the class's own vocabulary and the receiver in the
        // accessor's.
        let mut roles = Vec::new();
        collect_keyword_roles(
            &ops_of::<CsharpParser>(source, "foo.cs"),
            "this",
            &mut roles,
        );

        // `Both` can only arise from two `this` nodes in one space that
        // the getter classifies differently — it is the gate's whole
        // effect, and it disappears the moment `this` gets one role.
        // `OperandOnly` is the accessor, the innermost space and the one
        // holding the receiver alone; it is what flips when the gate is
        // inverted rather than dropped. Correct gives
        // `[Both, Both, OperandOnly]`; inverting gives
        // `[Both, Both, OperatorOnly]`; dropping the gate gives three
        // `OperandOnly`; reverting #1380 gives three `OperatorOnly`.
        // Asserting the whole sequence rather than two `contains` calls:
        // the comment above already derives it, and a `contains` pair
        // leaves the length unasserted, so a space appearing or vanishing
        // goes unnoticed and `[Both, X, OperandOnly]` passes for any `X`.
        assert_eq!(
            roles,
            vec![Role::Both, Role::Both, Role::OperandOnly],
            "the declarator and the receiver must disagree in the two outer spaces \
             and the accessor must bill `this` as an operand alone",
        );
    }

    /// One `this` and one `base` per container the pinned
    /// `tree-sitter-c-sharp` can put them in: a delegating constructor
    /// initializer, a base-constructor initializer, a member access, an
    /// element access, and a call argument. No `indexer_declaration` —
    /// that position is the gated one and is an operator.
    #[cfg(feature = "csharp")]
    const CSHARP_SELF_POSITIONS: &str = "class Pos : B {
        int[] _a;
        public Pos() : this(1) { }
        public Pos(int x) : base(x) { }
        int A() { return this._a[0]; }
        int C() { return base.H(); }
        int E() { return base[0]; }
        int F() { return this[0]; }
        void G() { M(this); }
        void M(object o) { }
    }";

    #[cfg(feature = "csharp")]
    #[test]
    fn csharp_self_and_base_leaves_are_unaliased_and_unconditional() {
        assert_self_reference_leaves::<CsharpCode>(
            CSHARP_SELF_POSITIONS,
            &[
                ("this", Csharp::This as u16, 4),
                ("base", Csharp::Base as u16, 3),
            ],
            "csharp",
        );
    }

    /// Every spelling of the six keywords `_parameter_type_with_modifiers`
    /// aliases to `modifier`, plus two controls that were billed before
    /// #1418: the bare `params` of a parameter array (kind 94, never
    /// aliased) and the bare `out` of a call argument (kind 56).
    ///
    /// `D` is declared *and* called so the argument `out` has a caller
    /// to sit in, which is what makes the two spellings of one keyword
    /// meet in one file.
    #[cfg(feature = "csharp")]
    const CSHARP_PARAMETER_MODIFIERS: &str = "static class E {
    static void A(this Foo f) { }
    static void B(scoped ref Foo f) { }
    static void C(ref readonly Foo f) { }
    static void D(out int x) { x = 1; }
    static void G(in Foo f) { }
    static void H(params int[] xs) { }
    static void I(ref int y) { D(out y); }
}";

    /// Each of the five operator keywords in *both* of its kind
    /// spellings — the childless `modifier` of a parameter, and the
    /// keyword's own token elsewhere: `ref` as a ref local, ref
    /// initializer and ref argument (kind 28); `readonly` as the leaf
    /// under a field's `modifier` wrapper (48); `in` as the `foreach`
    /// separator and an `in` argument (55); `out` as an out argument
    /// (56); `scoped` as a scoped ref local (93).
    ///
    /// Separate from [`CSHARP_PARAMETER_MODIFIERS`] because that fixture
    /// pairs the two spellings for `out` alone, which left four of the
    /// five bare kinds `CsharpCode::is_primitive` lists with no input
    /// (#1418).
    #[cfg(feature = "csharp")]
    const CSHARP_MODIFIER_BOTH_SPELLINGS: &str = "class S {
    static readonly int q = 0;
    static void M(scoped ref int a, ref readonly int b, in int c, out int d) { d = q; }
    static void N(int[] xs) {
        ref int r = ref xs[0];
        scoped ref int s = ref xs[1];
        foreach (var e in xs) { }
        M(ref r, in s, in s, out r);
    }
}";

    /// The six aliased parameter modifiers reach a Halstead half, and
    /// each reaches the same one its bare token reaches elsewhere
    /// (#1418).
    #[cfg(feature = "csharp")]
    #[test]
    fn csharp_parameter_modifiers_are_classified_1418() {
        // Operators (n1 = 15, N1 = 48): class 1; {} 8 (the class body
        // and seven method bodies); static 8 (the class and seven
        // methods); void 7; () 8 (seven parameter lists and the call);
        // int 3 (`out int x`, `int[]`, `ref int y`); [] 1; = 1; ; 2;
        // scoped 1; ref 3; readonly 1; out 2 (the parameter and the
        // argument); in 1; params 1.
        //
        // Operands (n2 = 15, N2 = 24): E 1; A/B/C/G/H/I 1 each; D 2
        // (declaration and call); this 1; Foo 4; f 4; x 2; 1 1; xs 1;
        // y 2.
        //
        // Before the fix this read (11, 41, 14, 23). The eight childless
        // `modifier` nodes were billed nowhere, which cost seven
        // operator occurrences and one operand occurrence, and emptied
        // `scoped`, `ref`, `readonly` and `in` out of the operator
        // vocabulary entirely — `out` survived only because the call
        // argument spells it with the unaliased kind.
        assert_halstead_counts::<CsharpParser>(
            CSHARP_PARAMETER_MODIFIERS,
            "foo.cs",
            [15, 48, 15, 24],
            "csharp parameter modifiers",
        );

        // The receiver is an operand, matching every other C# `this`
        // (#1380). Both halves matter: an arm listing it twice would
        // still put it among the operands.
        assert_keywords_are_operands_only::<CsharpParser>(
            CSHARP_PARAMETER_MODIFIERS,
            "foo.cs",
            &["this"],
        );

        let ops = ops_of::<CsharpParser>(CSHARP_PARAMETER_MODIFIERS, "foo.cs");
        for keyword in ["ref", "out", "in", "scoped", "readonly", "params"] {
            assert!(
                ops.operators.iter().any(|o| o == keyword),
                "`{keyword}` must be an operator; operators were {:?}",
                ops.operators
            );
            assert!(
                !ops.operands.iter().any(|o| o == keyword),
                "`{keyword}` must not be an operand; operands were {:?}",
                ops.operands
            );
        }

        // The vocabulary is not deduplicated — it is the concatenation
        // of the kind-keyed and the lexeme-keyed operator maps — so a
        // keyword appearing twice is the #453 shape: one keyword split
        // across the two maps and counted twice in `n1`. Keeping both
        // spellings in one map is what `CsharpCode::is_primitive`
        // listing the five bare kinds buys, and this is the only
        // assertion that can see it.
        //
        // It needs a fixture carrying *both* spellings of each keyword,
        // which `CSHARP_PARAMETER_MODIFIERS` does for `out` alone: its
        // `ref`, `in`, `scoped` and `readonly` are all in parameter
        // position, so for those the count can only ever be one and the
        // assertion is dead. That left four of the five bare kinds with
        // no input at all — dropping `Csharp::Ref`, `In`, `Readonly` or
        // `Scoped` from `is_primitive` failed no test in the workspace.
        assert_modifier_spellings_are_one_operator(
            CSHARP_MODIFIER_BOTH_SPELLINGS,
            &[
                ("ref", Csharp::Ref as u16),
                ("out", Csharp::Out as u16),
                ("in", Csharp::In as u16),
                ("scoped", Csharp::Scoped as u16),
                ("readonly", Csharp::Readonly as u16),
            ],
        );
    }

    /// Asserts each keyword in `spellings` appears in `source` both as
    /// its own `kind` and as a childless aliased `modifier`, and that the
    /// two spellings render as exactly one entry in the operator
    /// vocabulary.
    ///
    /// The vocabulary is the concatenation of the kind-keyed and the
    /// lexeme-keyed operator maps, so a keyword listed twice is one
    /// keyword split across both maps and counted twice in `n1`.
    #[cfg(feature = "csharp")]
    #[track_caller]
    fn assert_modifier_spellings_are_one_operator(source: &str, spellings: &[(&str, u16)]) {
        let code = source.as_bytes();
        // (bare, aliased) occurrences per keyword.
        let mut seen = vec![(0_usize, 0_usize); spellings.len()];

        for_each_node_with_chain::<CsharpCode>(code, |node, _| {
            let text = &code[node.start_byte()..node.end_byte()];
            let Some(index) = spellings.iter().position(|(kw, _)| kw.as_bytes() == text) else {
                return;
            };
            if node.kind_id() == Csharp::Modifier as u16 && node.child_count() == 0 {
                seen[index].1 += 1;
            } else if node.kind_id() == spellings[index].1 {
                seen[index].0 += 1;
            }
        });

        // Without this the vocabulary count below is vacuous for any
        // keyword the fixture stopped spelling both ways — the decay
        // that once left four of #1418's bare kinds with no input.
        for ((keyword, _), (bare, aliased)) in spellings.iter().zip(&seen) {
            assert!(
                *bare > 0 && *aliased > 0,
                "fixture must spell `{keyword}` both ways; it has {bare} bare and {aliased} aliased"
            );
        }

        let ops = ops_of::<CsharpParser>(source, "both.cs");
        for (keyword, _) in spellings {
            assert_eq!(
                ops.operators.iter().filter(|o| o == keyword).count(),
                1,
                "`{keyword}` must be one operator across both of its kind spellings; \
                 operators were {:?}",
                ops.operators
            );
        }
    }

    /// Pins the grammar shape the #1418 arm gates on, in both
    /// directions.
    ///
    /// The arm reads `modifier` nodes with no children as aliased bare
    /// keywords and leaves the rest to their classified keyword leaf.
    /// That is a claim about two populations, and a grammar bump can
    /// break either: giving an alias a token child would double-count
    /// it, and flattening a declaration modifier to a childless node
    /// would bill `public` / `static` as an unknown keyword. Both are
    /// checked here, so neither can move quietly.
    ///
    /// Childlessness says "aliased", *not* "parameter modifier" —
    /// `_lambda_expression_init` and `anonymous_method_expression` alias
    /// a bare `static` / `async` onto the same kind, which the second
    /// walk below pins so the distinction cannot be forgotten. Both are
    /// operators, as their declaration spelling is (#1482).
    #[cfg(feature = "csharp")]
    #[test]
    fn csharp_aliased_modifier_is_childless() {
        let code = CSHARP_PARAMETER_MODIFIERS.as_bytes();
        let (mut aliased, mut declaration) = (0_usize, 0_usize);

        for_each_node_with_chain::<CsharpCode>(code, |node, chain| {
            if node.kind_id() != Csharp::Modifier as u16 {
                return;
            }
            let role = CsharpCode::get_op_type_with_code(node, code, Ancestors::known(chain));
            let text = &code[node.start_byte()..node.end_byte()];

            if node.child_count() == 0 {
                aliased += 1;
                // Spelled out rather than `this`-versus-everything-else,
                // so a text this fixture does not carry fails loudly;
                // the lambda spellings are owned by the second walk.
                let (correct, expected) = match text {
                    b"this" => (matches!(role, TokenRole::Operand), "an operand"),
                    b"scoped" | b"ref" | b"out" | b"in" | b"readonly" => {
                        (matches!(role, TokenRole::Operator), "an operator")
                    }
                    other => panic!(
                        "`{}` is not one of the six parameter spellings this fixture carries",
                        String::from_utf8_lossy(other)
                    ),
                };
                assert!(
                    correct,
                    "`{}` is an aliased parameter modifier and must be {expected}",
                    String::from_utf8_lossy(text)
                );
                // Grammar-dispatch section 5: nothing containing the
                // token is classified, so billing the token cannot
                // count the same source text twice. Every ancestor,
                // not just `parameter` — `parameter_list` and the
                // declaration above it contain it too.
                for (depth, ancestor) in chain.iter().enumerate() {
                    assert!(
                        matches!(
                            CsharpCode::get_op_type_with_code(
                                ancestor,
                                code,
                                Ancestors::known(&chain[..depth])
                            ),
                            TokenRole::Unknown
                        ),
                        "`{}` contains an aliased modifier and is itself classified, so the \
                         keyword now counts twice",
                        ancestor.kind()
                    );
                }
            } else {
                declaration += 1;
                assert_eq!(
                    node.child_count(),
                    1,
                    "a declaration `modifier` wraps exactly one keyword leaf"
                );
                assert!(
                    matches!(role, TokenRole::Unknown),
                    "the `{}` wrapper must stay unclassified; its leaf carries the operator",
                    String::from_utf8_lossy(text)
                );
                let leaf = node.child(0).expect("child_count is 1");
                let mut leaf_chain = chain.to_vec();
                leaf_chain.push(*node);
                assert!(
                    matches!(
                        CsharpCode::get_op_type_with_code(
                            &leaf,
                            code,
                            Ancestors::known(&leaf_chain)
                        ),
                        TokenRole::Operator
                    ),
                    "the leaf under a declaration `modifier` must carry the operator"
                );
            }
        });

        // Eight of each: `this`, `scoped`, `ref` x3, `readonly`, `out`,
        // `in` in parameter position, and the `static` of the class and
        // of its seven methods. Asserted so a fixture that stopped
        // carrying one population cannot pass having checked nothing.
        assert_eq!(aliased, 8, "fixture lost an aliased parameter modifier");
        assert_eq!(declaration, 8, "fixture lost a declaration modifier");

        // The second alias site. `static (int x) => …` and `async
        // delegate (int y) { … }` put a bare keyword under the same
        // childless `modifier`, so `csharp_is_aliased_modifier` holds
        // for a node that is not in a parameter at all — which is why
        // the getter dispatches on the text and not on the kind.
        let lambda = "static class L {
    static void M() {
        var a = static (int x) => x + 1;
        var b = async delegate (int y) { return y; };
    }
}"
        .as_bytes();
        let mut lambda_aliases = 0_usize;

        for_each_node_with_chain::<CsharpCode>(lambda, |node, chain| {
            if node.kind_id() != Csharp::Modifier as u16 || node.child_count() != 0 {
                return;
            }
            lambda_aliases += 1;
            let text = &lambda[node.start_byte()..node.end_byte()];
            assert!(
                matches!(text, b"static" | b"async"),
                "`{}` is not a lambda modifier the grammar aliases",
                String::from_utf8_lossy(text)
            );
            assert!(
                matches!(
                    CsharpCode::get_op_type_with_code(node, lambda, Ancestors::known(chain)),
                    TokenRole::Operator
                ),
                "`{}` on a lambda must be an operator, as its declaration spelling is (#1482)",
                String::from_utf8_lossy(text)
            );
        });

        assert_eq!(
            lambda_aliases, 2,
            "fixture lost a lambda / anonymous-method modifier alias"
        );
    }

    /// `static` and `async` in both of their kind spellings: the keyword
    /// leaf under a method's `modifier` wrapper, and the childless
    /// `modifier` the grammar aliases a lambda's keyword to (#1482).
    #[cfg(feature = "csharp")]
    const CSHARP_LAMBDA_MODIFIER_BOTH_SPELLINGS: &str = "class L {
    static void N() { }
    async void M() { }
    void P() {
        var a = static (int x) => x;
        var b = async (int y) => y;
    }
}";

    /// A C# lambda's bare parameter (`x => x`) is the operand its
    /// parenthesised twin (`(x) => x`) bills (#1544). Each row is one
    /// lambda in a method body; the twins differ only by the `()` the
    /// parenthesised spelling writes, so the operand halves must match
    /// and the operator halves differ by exactly that one `()`.
    #[cfg(feature = "csharp")]
    #[test]
    fn csharp_implicit_lambda_parameter_is_an_operand() {
        let wrap = |lambda: &str| {
            format!("class C {{\n    void M() {{\n        var f = {lambda};\n    }}\n}}\n")
        };
        // Operators: class, {} x2, void, () x1 (M's parameter list), =,
        // =>, ; — n1 = 7, N1 = 8 — plus the lambda's own `()` in the
        // parenthesised spelling. Operands: C, M, f, and the parameter
        // twice; `var` is an unclassified `implicit_type`. `_ => 0`
        // names `_` once and adds the literal `0`.
        //
        // Before #1544 the bare rows read (7, 8, 4, 4) for both: `x`
        // lost one occurrence, and `_` left the vocabulary entirely.
        for (lambda, expected) in [
            ("x => x", [7, 8, 4, 5]),
            ("(x) => x", [7, 9, 4, 5]),
            ("_ => 0", [7, 8, 5, 5]),
            ("(_) => 0", [7, 9, 5, 5]),
        ] {
            assert_halstead_counts::<CsharpParser>(&wrap(lambda), "foo.cs", expected, lambda);
        }

        // The bare parameter is billed under its own text, not under
        // the kind name, and as an operand only.
        assert_keywords_are_operands_only::<CsharpParser>(&wrap("_ => 0"), "foo.cs", &["_"]);
    }

    /// A lambda's `static` / `async` is the same operator as the
    /// declaration's, counted once in `n1` across both spellings
    /// (#1482).
    #[cfg(feature = "csharp")]
    #[test]
    fn csharp_lambda_modifiers_are_operators_1482() {
        // Operators (n1 = 10, N1 = 25): class 1; {} 4 (the class body
        // and three method bodies); static 2; async 2; void 3; () 5
        // (three method parameter lists and two lambda ones); int 2;
        // = 2; ; 2; => 2.
        //
        // Operands (n2 = 8, N2 = 10): L, N, M, P, a, b once each; x 2
        // and y 2 (the parameter and the lambda body). `var` is an
        // unclassified `implicit_type` wrapper.
        //
        // Before the fix this read (10, 23, 8, 10): the two lambda
        // keywords were billed nowhere. Billing them without listing
        // `Static` / `Async` in `CsharpCode::is_primitive` reads
        // (12, 25, 8, 10) — each keyword split across the kind-keyed
        // and the lexeme-keyed operator map.
        assert_halstead_counts::<CsharpParser>(
            CSHARP_LAMBDA_MODIFIER_BOTH_SPELLINGS,
            "foo.cs",
            [10, 25, 8, 10],
            "csharp lambda modifiers",
        );

        assert_modifier_spellings_are_one_operator(
            CSHARP_LAMBDA_MODIFIER_BOTH_SPELLINGS,
            &[
                ("static", Csharp::Static as u16),
                ("async", Csharp::Async as u16),
            ],
        );
    }

    #[cfg(feature = "go")]
    #[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
                }
                "#
                );
            },
        );
    }

    #[cfg(feature = "perl")]
    #[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
                }
                "#
                );
            },
        );
    }

    #[cfg(feature = "perl")]
    #[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);
            },
        );
    }

    #[cfg(feature = "perl")]
    #[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);
            },
        );
    }

    #[cfg(feature = "perl")]
    #[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);
            },
        );
    }

    #[cfg(feature = "perl")]
    #[test]
    fn perl_plain_heredoc_counts_as_one_operand() {
        // Regression: issue #287. A plain (non-interpolating) Perl
        // heredoc body used to be classified `TokenRole::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);
        });
    }

    #[cfg(feature = "perl")]
    #[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);
            },
        );
    }

    #[cfg(feature = "perl")]
    #[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);
        });
    }

    #[cfg(feature = "perl")]
    #[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}"),
            );
        }
    }

    #[cfg(feature = "perl")]
    #[test]
    fn perl_comment_leader_is_not_an_operator_1549() {
        // tree-sitter-perl emits a comment's leading `#` as a `#` token
        // under `comments`, and the getter listed it as an operator, so
        // every comment billed one `#` (#1549). The oracle is the same
        // source with its comments deleted, which must score identically.
        // `$#a` and `qw#…#` are kept to pin that dropping `#` leaves the
        // distinct `$#` operator and the `qw` delimiters alone.
        //
        // expected: operators `sub`, `{}`, `my`, `=`, `;` × 2, `return`,
        // `$#` × 2, `+` → n1 = 8, N1 = 10. Operands `f`, `@a`, `x`, `y`,
        // `a` × 2 → n2 = 5, N2 = 6. Before the fix the commented row
        // added `#` → n1 = 9, N1 = 13. Once excluded, a comment feeds no
        // axis to anchor on, so only the revert run guards the fixture:
        // keep its comments.
        for (source, label) in [
            (
                "sub f {\n  # leading\n  my @a = qw#x y#; # tail\n  return $#a + $#a; # tail\n}\n",
                "commented",
            ),
            (
                "sub f {\n  my @a = qw#x y#;\n  return $#a + $#a;\n}\n",
                "comment-free twin",
            ),
        ] {
            assert_halstead_counts::<PerlParser>(source, "foo.pl", [8, 10, 5, 6], label);
        }
    }

    #[cfg(feature = "perl")]
    #[test]
    fn perl_bare_pattern_text_bills_no_operator_1549() {
        // The bare `/…/` form keeps its pattern text in a
        // `regex_pattern_content` that spells `#`, `[`, `]` and `\` as
        // anonymous tokens, three of which an operator arm listed, so
        // `/a#b[c]\#/` billed `#`, `[]` and `\` operators. `m//` and
        // `qr//` emit no node for the same text, so they are the oracle:
        // all three spellings must score as `/abc/` does in
        // `perl_every_pattern_value_spelling_scores_alike`.
        //
        // expected per variant: operators `$` × 2, `=~` × 2, `and`, `;`
        // → n1 = 4, N1 = 6; operands `$s` × 2 and the pattern × 2 →
        // n2 = 2, N2 = 4. Before the fix the bare row scored n1 = 7,
        // N1 = 14. The `#`, `[c]` and `\#` feed no axis once excluded,
        // so nothing anchors them and only the revert run guards the
        // fixture: keep them in the bare row.
        for pattern in [r"/a#b[c]\#/", r"m/a#b[c]\#/", r"qr/a#b[c]\#/"] {
            assert_halstead_counts::<PerlParser>(
                &format!("$s =~ {pattern} and $s =~ {pattern};\n"),
                "foo.pl",
                [4, 6, 2, 4],
                &format!("pattern {pattern}"),
            );
        }
    }

    #[cfg(feature = "perl")]
    #[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}"),
            );
        }
    }

    #[cfg(feature = "perl")]
    #[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}"),
            );
        }
    }

    #[cfg(feature = "perl")]
    #[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"
        );
    }

    #[cfg(feature = "perl")]
    #[test]
    fn perl_readline_closer_alias_never_reaches_kind_id() {
        // Drift marker for `Perl::GT2` (#1395). The grammar closes
        // `<FH>` / `<$fh>` with `token.immediate('>')`, which the
        // generated parser gives its own symbol — hence the `GT2`
        // variant sitting next to `FileHandle` in the enum — but whose
        // `public_symbol_map` entry collapses it onto `GT` before
        // `kind_id()`, exactly like `LPAREN2` in #768 and Ruby's
        // `SLASH2` in #1312. Nothing in `getter/perl.rs` names it, and
        // nothing should: `compute_halstead` keys a non-primitive
        // operator on `kind_id()`, so two live kinds both rendering
        // `">"` would split one `>` across two `n1` entries. If a bump
        // ever starts emitting it, the repair is to route `>` through
        // the lexeme-keyed map, not to list both — and this test is
        // what says so.
        //
        // The C++ grammars' template-list closer collapses the same way;
        // `cpp_template_closer_alias_never_reaches_kind_id` pins that.
        let path = PathBuf::from("foo.pl");
        for source in ["my $l = <FH>;\n", "my $l = <$fh>;\n", "my $b = $x > $y;\n"] {
            let parser = PerlParser::new(source.as_bytes().to_vec(), &path, None);
            assert!(
                !ast_has_kind_id(&parser, Perl::GT2 as u16),
                "Perl::GT2 must stay collapsed to Perl::GT for `{source}`"
            );
            // Positive control: the id the operator arm fires on is
            // present, so the assertion above cannot pass merely
            // because the fixture grew no `>` at all.
            assert!(
                ast_has_kind_id(&parser, Perl::GT as u16),
                "Perl::GT must be the `>` kind for `{source}`"
            );
        }
    }

    /// Drift marker for `Cpp::GT2` / `Mozcpp::GT2`. Both grammars close
    /// a template parameter or argument list with
    /// `alias(token(prec(1, '>')), '>')`, which the generated parser
    /// numbers separately, but `ts_symbol_map` folds that symbol onto
    /// `GT` before `kind_id()`, as with Perl's readline closer above. The
    /// `GT2` arms in `getter/cpp.rs` and `getter/mozcpp.rs` are therefore
    /// defensive; this fails if a grammar bump makes them live, at which
    /// point the two kinds would split one `>` across two `n1` entries.
    #[cfg(any(feature = "cpp", feature = "mozcpp"))]
    fn assert_template_closer_folds_to_gt<P: crate::ParserTrait>(gt: u16, gt2: u16, label: &str) {
        // One parameter list (`S<T>`'s declaration) and two argument
        // lists, the inner one closed by the first half of a `>>`.
        let source = "template <typename T> struct S {};\n\
                      std::vector<std::vector<int>> v;\n\
                      bool b = x > y;\n";
        let parser = P::new(source.as_bytes().to_vec(), &PathBuf::from("foo.cpp"), None);
        assert!(
            !ast_has_kind_id(&parser, gt2),
            "{label}::GT2 must stay collapsed to {label}::GT",
        );
        // Positive control: every template-list closer is present and
        // carries `GT`, so the assertion above cannot pass merely
        // because the fixture stopped producing template lists.
        let closers = parser
            .root()
            .preorder()
            .filter(|n| {
                n.kind_id() == gt
                    && n.parent().is_some_and(|p| {
                        matches!(
                            p.kind(),
                            "template_parameter_list" | "template_argument_list"
                        )
                    })
            })
            .count();
        assert_eq!(
            closers, 3,
            "{label}: each template-list closer must be a `GT`"
        );
    }

    #[cfg(feature = "cpp")]
    #[test]
    fn cpp_template_closer_alias_never_reaches_kind_id() {
        assert_template_closer_folds_to_gt::<CppParser>(Cpp::GT as u16, Cpp::GT2 as u16, "Cpp");
    }

    #[cfg(feature = "mozcpp")]
    #[test]
    fn mozcpp_template_closer_alias_never_reaches_kind_id() {
        assert_template_closer_folds_to_gt::<MozcppParser>(
            Mozcpp::GT as u16,
            Mozcpp::GT2 as u16,
            "Mozcpp",
        );
    }

    /// Asserts a grammar's wrapped generic-list opener, `LT2`, never
    /// reaches a node, so the `LT` its getter pairs as `<>` is the only
    /// `<` a list opens with (#1559, grammar-dispatch §2). `lists` are the
    /// lists the wrapped token opens; the positive control counts their
    /// `LT` openers, so the assertion cannot pass on a fixture that
    /// stopped producing those lists.
    #[cfg(any(feature = "groovy", feature = "objc", feature = "rust"))]
    #[track_caller]
    fn assert_generic_opener_folds_to_lt<P: crate::ParserTrait>(
        source: &str,
        [lt, lt2]: [u16; 2],
        lists: &[&str],
        openers: usize,
        label: &str,
    ) {
        let parser = P::new(source.as_bytes().to_vec(), &PathBuf::from("foo"), None);
        assert!(
            !ast_has_kind_id(&parser, lt2),
            "{label}::LT2 must stay collapsed to {label}::LT",
        );
        let found = parser
            .root()
            .preorder()
            .filter(|n| n.kind_id() == lt && n.parent().is_some_and(|p| lists.contains(&p.kind())))
            .count();
        assert_eq!(
            found, openers,
            "{label}: each generic-list opener must be an `LT`"
        );
    }

    #[cfg(feature = "rust")]
    #[test]
    fn rust_generic_opener_alias_never_reaches_kind_id() {
        assert_generic_opener_folds_to_lt::<RustParser>(
            "fn u<T>(x: Vec<T>) -> impl Sized + use<T> { x }\n",
            [Rust::LT as u16, Rust::LT2 as u16],
            &["type_arguments", "use_bounds"],
            2,
            "Rust",
        );
    }

    #[cfg(feature = "groovy")]
    #[test]
    fn groovy_generic_opener_alias_never_reaches_kind_id() {
        assert_generic_opener_folds_to_lt::<GroovyParser>(
            "class A<T> { List<T> v }\n",
            [Groovy::LT as u16, Groovy::LT2 as u16],
            &["type_parameters", "type_arguments"],
            2,
            "Groovy",
        );
    }

    #[cfg(feature = "objc")]
    #[test]
    fn objc_generic_opener_alias_never_reaches_kind_id() {
        assert_generic_opener_folds_to_lt::<ObjcParser>(
            "int f(void) { return g(NSArray<NSString *>); }\n",
            [Objc::LT as u16, Objc::LT2 as u16],
            &["argument_list"],
            1,
            "Objc",
        );
    }

    #[cfg(feature = "perl")]
    #[test]
    fn perl_readline_brackets_are_operators() {
        // #1395: a readline's `<` / `>` delimit syntax, not a literal,
        // so under the policy on `Getter::get_op_type` they are
        // ordinary operators — even though ABC's `conditions` excludes
        // them (#1297). `<STDIN>` is the one spelling that cannot show
        // this: the grammar lexes it as a single `standard_input`
        // token, so there are no brackets to classify.
        //
        // expected: operators `sub`, `{}`, `my`, `$` × 2 (one per
        // `scalar_variable`), `=`, `<`, `>`, `;` × 2, `return` →
        // n1 = 9, N1 = 11. Operands `r`, `$l` × 2, `FH` →
        // n2 = 3, N2 = 4.
        check_metrics::<PerlParser>("sub r { my $l = <FH>; return $l; }\n", "foo.pl", |metric| {
            assert_eq!(metric.halstead.unique_operators(), 9);
            assert_eq!(metric.halstead.total_operators(), 11);
            assert_eq!(metric.halstead.unique_operands(), 3);
            assert_eq!(metric.halstead.total_operands(), 4);
        });
    }

    /// 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.
    #[cfg(feature = "perl")]
    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.
    #[cfg(feature = "perl")]
    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.
    #[cfg(feature = "perl")]
    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.
    #[cfg(feature = "perl")]
    #[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.
    #[cfg(feature = "perl")]
    #[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",
        );
    }

    #[cfg(feature = "perl")]
    #[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",
        );
    }

    #[cfg(feature = "lua")]
    #[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 `)`.
    #[cfg(feature = "lua")]
    #[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).
    #[cfg(all(feature = "c", feature = "cpp", feature = "elixir", feature = "ruby"))]
    #[test]
    fn second_alias_opener_collapses_to_base_kind_id() {
        #[cfg(any(feature = "c", feature = "cpp", feature = "elixir", feature = "ruby"))]
        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.
        #[cfg(any(feature = "c", feature = "cpp", feature = "elixir", feature = "ruby"))]
        fn assert_folded_openers<T: crate::MetricSuite>(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");
    }

    #[cfg(feature = "kotlin")]
    #[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
                }
                "#
                );
            },
        );
    }

    #[cfg(feature = "kotlin")]
    #[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"],
        );
    }

    #[cfg(feature = "kotlin")]
    #[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"]);
    }

    #[cfg(feature = "kotlin")]
    #[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"]);
    }

    #[cfg(feature = "kotlin")]
    #[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\""]);
    }

    #[cfg(feature = "kotlin")]
    #[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);
            },
        );
    }

    #[cfg(feature = "kotlin")]
    #[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);
            },
        );
    }

    // Kotlin half of #1380 — see
    // `java_self_and_super_references_are_operands` for the structural
    // argument.
    #[cfg(feature = "kotlin")]
    #[test]
    fn kotlin_self_and_super_references_are_operands() {
        let source = "class T {\n    fun f() = this.x + super.y\n}";
        // Operators (n1=7, N1=8): class, {}, fun, (), =, . x2, +
        // Operands (n2=6, N2=6): T, f, this, x, super, y
        // Before the fix this read (9, 10, 4, 4).
        assert_halstead_counts::<KotlinParser>(
            source,
            "foo.kt",
            [7, 8, 6, 6],
            "kotlin self/super references",
        );
        assert_keywords_are_operands_only::<KotlinParser>(source, "foo.kt", &["this", "super"]);
    }

    // The label-qualified spellings are their own leaf kinds — `this@`
    // (106) and `super@` (107) — carrying no `this` / `super` leaf, so
    // listing only the two bare kinds would score every `this@Outer`
    // reference zero (grammar-dispatch section 1). The labels `Outer`
    // and `Inner` stay separate operands: the `this_expression` wrapper
    // whose span would have swallowed them is deliberately unclassified
    // (section 5).
    #[cfg(feature = "kotlin")]
    #[test]
    fn kotlin_labelled_self_and_super_references_are_operands() {
        let source = "class Outer {\n    inner class Inner : A() {\n        \
                      fun f() = this@Outer.x + super@Inner.y\n    }\n}";
        assert_keywords_are_operands_only::<KotlinParser>(source, "foo.kt", &["this@", "super@"]);
        assert_ops_operands::<KotlinParser>(
            source,
            "foo.kt",
            8,
            vec!["A", "Inner", "Outer", "f", "super@", "this@", "x", "y"],
        );
        // The metrics store is a second, independent walk — it keys
        // operands by `get_operand_id` where `ops_inner` keys by text —
        // so `assert_ops_operands` on its own pins the ops store against
        // a literal rather than against the metric (lesson 4).
        //
        // `N2` is what makes the "the labels stay separate operands"
        // claim above testable. Both labels duplicate an enclosing class
        // name, so dropping their contribution entirely leaves `n2` at 8
        // with the same eight strings; only `N2` falls, 10 to 8.
        check_metrics::<KotlinParser>(source, "foo.kt", |metric| {
            assert_eq!(metric.halstead.unique_operands(), 8);
            assert_eq!(metric.halstead.total_operands(), 10);
        });
    }

    // The keeper question of grammar-dispatch section 6: a
    // `constructor_delegation_call` emits a bare `this` / `super` leaf
    // with no `this_expression` / `super_expression` wrapper around it,
    // so classifying the wrapper instead would score constructor
    // delegation zero. This is the only spelling that can tell the two
    // choices apart — every other `this` carries both nodes — so it is
    // the independent path grammar-dispatch section 11 asks for.
    #[cfg(feature = "kotlin")]
    #[test]
    fn kotlin_constructor_delegation_self_reference_is_an_operand() {
        let source = "class C(val n: Int) {\n    constructor() : this(0)\n}";
        assert_keywords_are_operands_only::<KotlinParser>(source, "foo.kt", &["this"]);
        assert_ops_operands::<KotlinParser>(
            source,
            "foo.kt",
            5,
            vec!["0", "C", "Int", "n", "this"],
        );
        check_metrics::<KotlinParser>(source, "foo.kt", |metric| {
            assert_eq!(metric.halstead.unique_operands(), 5);
            assert_eq!(metric.halstead.total_operands(), 5);
        });
    }

    /// One `this` / `super` per container the pinned
    /// `tree-sitter-kotlin-ng` can put them in: a bare expression, a
    /// call argument, a navigation receiver, a type-argument-qualified
    /// `super<P>`, both label-qualified forms, and the
    /// `constructor_delegation_call` that carries no wrapper.
    #[cfg(feature = "kotlin")]
    const KOTLIN_SELF_POSITIONS: &str = "class P {
        fun h() = 1
    }
    class Outer : P() {
        val x = 1
        fun c() = super.h()
        fun d() = this
        fun e(o: Any): Any = e(this)
        inner class Inner : P() {
            fun a() = this@Outer.x
            fun b() = this.hashCode()
            fun f() = super@Inner.h()
            fun g() = super<P>.h()
        }
    }
    class Del(val n: Int) {
        constructor() : this(0)
    }
";

    #[cfg(feature = "kotlin")]
    #[test]
    fn kotlin_self_and_super_leaves_are_unaliased_and_unconditional() {
        assert_self_reference_leaves::<KotlinCode>(
            KOTLIN_SELF_POSITIONS,
            &[
                ("this", Kotlin::This as u16, 4),
                ("super", Kotlin::Super as u16, 2),
                ("this@", Kotlin::ThisAT as u16, 1),
                ("super@", Kotlin::SuperAT as u16, 1),
            ],
            "kotlin",
        );
    }

    #[cfg(feature = "python")]
    #[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);
            },
        );
    }

    #[cfg(feature = "python")]
    #[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);
        });
    }

    #[cfg(feature = "python")]
    #[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);
            },
        );
    }

    #[cfg(feature = "python")]
    #[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);
            },
        );
    }

    #[cfg(feature = "python")]
    #[test]
    fn python_bare_tuple_of_strings_is_not_a_docstring() {
        // `"a", "b"` as a statement is a discarded tuple with two
        // expression children, so the docstring predicate's
        // `child_count == 1` gate keeps both literals as operands.
        //
        // Source: `def f():\n    "a", "b"\n    return 1\n`
        // Operands: `f`, `"a"`, `"b"`, `1` → u_operands = 4, N2 = 4.
        check_metrics::<PythonParser>(
            "def f():\n    \"a\", \"b\"\n    return 1\n",
            "foo.py",
            |metric| {
                assert_eq!(metric.halstead.unique_operands(), 4);
                assert_eq!(metric.halstead.total_operands(), 4);
            },
        );
    }

    #[cfg(feature = "python")]
    #[test]
    fn python_parenthesized_docstring_suppressed() {
        // CPython drops the parentheses around a docstring (#1610), so
        // `("""doc""")` must bill what `"""doc"""` bills: neither the
        // string nor its `(`. Operators: `def`, `(` of the parameter list,
        // `:`, `return`; operands: `f`, `1`.
        let sources: [&[u8]; 4] = [
            b"def f():\n    \"\"\"doc\"\"\"\n    return 1\n",
            b"def f():\n    (\"\"\"doc\"\"\")\n    return 1\n",
            b"def f():\n    ((\"doc\"))\n    return 1\n",
            b"def f():\n    (\n        # c\n        \"doc\" \"more\"\n    )\n    return 1\n",
        ];
        for source in sources {
            let h = crate::test_support::metrics_verbatim(
                crate::LANG::Python,
                source,
                crate::MetricsOptions::default(),
            )
            .halstead;
            assert_eq!(
                [
                    h.unique_operators(),
                    h.total_operators(),
                    h.unique_operands(),
                    h.total_operands()
                ],
                [4, 4, 2, 2],
                "{}",
                String::from_utf8_lossy(source)
            );
        }
        // A parenthesized value keeps its `(` and its operand, and so does
        // a parenthesized name statement. Operators: `=`, `(`; operands:
        // `x`, `"a"`.
        check_metrics::<PythonParser>("x = (\"a\")\n", "foo.py", |metric| {
            let h = &metric.halstead;
            assert_eq!([h.total_operators(), h.total_operands()], [2, 2]);
        });
        // Operators: `(`; operands: `x`.
        check_metrics::<PythonParser>("(x)\n", "foo.py", |metric| {
            let h = &metric.halstead;
            assert_eq!([h.total_operators(), h.total_operands()], [1, 1]);
        });
        // A tuple led by a parenthesized string is a value, not a bare
        // string. Operators: `(`, `,`; operands: `"a"`, `"b"`.
        check_metrics::<PythonParser>("(\"a\"), \"b\"\n", "foo.py", |metric| {
            let h = &metric.halstead;
            assert_eq!([h.total_operators(), h.total_operands()], [2, 2]);
        });
    }

    #[cfg(feature = "python")]
    #[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.
    #[cfg(feature = "python")]
    #[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  (5 unique)
                //   N1: async(1) def(1) await(3) = 5, plus the four call
                //   and parameter-list `(` and the block `:` (#1486) = 10.
                //   Before #413, Await + Await2 both matched, so `await` was a
                //   distinct operator twice: one more unique and three more total.
                assert_eq!(metric.halstead.unique_operators(), 5);
                assert_eq!(metric.halstead.total_operators(), 10);
            },
        );
    }

    /// 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.
    #[cfg(feature = "python")]
    #[test]
    fn python_lambda_counted_once() {
        check_metrics::<PythonParser>("g = lambda x: x + 1\n", "foo.py", |metric| {
            // expected operators: =, lambda, :, +  (4 unique, each used
            // once; the parameter-list `:` since #1486).
            // Before #413, lambda was absent: only =, + were counted.
            assert_eq!(metric.halstead.unique_operators(), 4);
            assert_eq!(metric.halstead.total_operators(), 4);
        });
    }

    /// 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`.
    #[cfg(feature = "python")]
    #[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, :  (4 unique)
                //   match(1) + case(2) + pass(2) + one block `:` per
                //   header (3, #1486) = 8 total occurrences.
                // Before #413, neither match nor case was counted (only pass).
                assert_eq!(metric.halstead.unique_operators(), 4);
                assert_eq!(metric.halstead.total_operators(), 8);
            },
        );
    }

    /// Regression #413, sub-fix (2): `nonlocal` (Nonlocal=41) was dropped while
    /// `global` was already classified. Both should count, for parity.
    #[cfg(feature = "python")]
    #[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
                //   (5 unique, each once; `()` and `:` since #1486)
                // Before #413, nonlocal was absent: only def, global counted.
                assert_eq!(metric.halstead.unique_operators(), 5);
                assert_eq!(metric.halstead.total_operators(), 5);
            },
        );
    }

    /// 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.
    #[cfg(feature = "python")]
    #[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 (8 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), and the `for` header's
                //   block ":" (once, #1486)
                // Total occurrences: 1+1+1+2+1+1+1+1 = 9.
                // 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(), 8);
                assert_eq!(metric.halstead.total_operators(), 9);
            },
        );
    }

    /// Asserts `count(halstead)` for each `(label, source, expected)`
    /// row, one parse per row so a row's counts are its own.
    #[cfg(any(
        feature = "c",
        feature = "cpp",
        feature = "groovy",
        feature = "java",
        feature = "javascript",
        feature = "kotlin",
        feature = "mozcpp",
        feature = "mozjs",
        feature = "objc",
        feature = "python",
        feature = "rust",
        feature = "typescript"
    ))]
    fn assert_halstead_rows<T: crate::MetricSuite>(
        file: &str,
        rows: &[(&str, &str, [u64; 2])],
        count: fn(&Stats) -> [u64; 2],
    ) {
        for (label, source, expected) in rows {
            crate::test_support::check_func_space_only::<T, _>(
                source,
                file,
                &[crate::Metric::Halstead],
                |space| {
                    assert_eq!(
                        count(&space.metrics.halstead),
                        *expected,
                        "{label}: {source:?}"
                    );
                },
            );
        }
    }

    /// Asserts `[n1, N1]` for each row.
    #[cfg(any(
        feature = "c",
        feature = "cpp",
        feature = "groovy",
        feature = "java",
        feature = "javascript",
        feature = "kotlin",
        feature = "mozcpp",
        feature = "mozjs",
        feature = "objc",
        feature = "python",
        feature = "rust",
        feature = "typescript"
    ))]
    fn assert_operator_rows<T: crate::MetricSuite>(file: &str, rows: &[(&str, &str, [u64; 2])]) {
        assert_halstead_rows::<T>(file, rows, |h| [h.unique_operators(), h.total_operators()]);
    }

    /// Asserts `[n2, N2]` for each row.
    #[cfg(any(feature = "java", feature = "typescript"))]
    fn assert_operand_rows<T: crate::MetricSuite>(file: &str, rows: &[(&str, &str, [u64; 2])]) {
        assert_halstead_rows::<T>(file, rows, |h| [h.unique_operands(), h.total_operands()]);
    }

    /// #1486: Python's bracket openers, `;` and `:` are vocabulary, as
    /// they are in every other getter (#1395). Each row isolates one
    /// position, so the expected `[n1, N1]` is derivable from the row
    /// alone; a bracket pair bills its opener once, as `()` / `[]` / `{}`.
    #[cfg(feature = "python")]
    #[test]
    fn python_punctuation_is_vocabulary_1486() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `()`
            ("call", "f(x)\n", [1, 1]),
            // `()`, `=`
            ("keyword argument", "f(a=1)\n", [2, 2]),
            // `()`, `*`, `,`, `**`
            ("splat arguments", "f(*a, **k)\n", [4, 4]),
            // `[]`
            ("index", "a[1]\n", [1, 1]),
            // `[]`, `:` twice
            ("slice", "a[1:2:3]\n", [2, 3]),
            // `{}`, `:`
            ("dict", "{k: v}\n", [2, 2]),
            // `{}`, `,`
            ("set", "{1, 2}\n", [2, 2]),
            // `[]`, `,` twice, `()`
            ("list and tuple", "[1, (2, 3)]\n", [3, 4]),
            // `()`, `for`, `in`
            ("generator", "(x for x in y)\n", [3, 3]),
            // `{}`, `:`, `for`, `in`
            ("dict comprehension", "{k: v for k in y}\n", [4, 4]),
            // `()`, `:=` — the walrus is its own token, not a `:`
            ("walrus", "(n := 3)\n", [2, 2]),
            // `lambda`, `:`
            ("lambda", "lambda x: x\n", [2, 2]),
            // `def`, `()`, `:` twice, `->`, `pass`
            ("annotations", "def f(x: int) -> int:\n    pass\n", [5, 6]),
            // `:`, `=`
            ("annotated assignment", "x: int = 1\n", [2, 2]),
            // `@`, `def`, `()`, `:`, `pass`
            ("decorator", "@d\ndef f():\n    pass\n", [5, 5]),
            // `if`, `:`, `pass`
            ("if block", "if x:\n    pass\n", [3, 3]),
            // `while`, `:`, `pass`
            ("while block", "while x:\n    pass\n", [3, 3]),
            // `for`, `in`, `:`, `pass`
            ("for block", "for i in y:\n    pass\n", [4, 4]),
            // `with`, `:`, `pass`
            ("with block", "with o:\n    pass\n", [3, 3]),
            // `try`, `except`, `:` twice, `pass` twice
            ("try block", "try:\n    pass\nexcept E:\n    pass\n", [4, 6]),
            // `class`, `:`, `pass` — the keyword is billed like `def`
            // (#1550)
            ("class block", "class C:\n    pass\n", [3, 3]),
            // `class` twice, `()`, `:` twice, `pass` — one `class` per
            // keyword, nothing for the `ClassDefinition` wrapper
            (
                "nested class",
                "class C(B):\n    class D:\n        pass\n",
                [4, 6],
            ),
            // `;`
            ("statement separator", "a; b\n", [1, 1]),
        ];
        assert_operator_rows::<PythonParser>("foo.py", ROWS);
    }

    /// #1486: an f-string replacement field's `{` and format-spec `:` are
    /// spelling, not operations, like every other language's
    /// interpolation opener (#1314) — the f-string rows bill nothing.
    /// #1551 adds the self-documenting `=` (`f"{z=}"`), a directive of
    /// the same field. The guard reads the token's *parent*, so a dict,
    /// a keyword argument or a walrus written inside a replacement field
    /// keeps its own operators.
    #[cfg(feature = "python")]
    #[test]
    fn python_f_string_delimiters_are_not_operators_1486() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            ("interpolation opener", "f\"{x}\"\n", [0, 0]),
            ("format spec colon", "f\"{x:>10}\"\n", [0, 0]),
            ("nested format expression", "f\"{a:{w}}\"\n", [0, 0]),
            // `{}`, `:`, `[]` of the dict and its subscript, nothing of
            // the replacement field around them
            ("dict inside a field", "f\"{ {k: v}[k] }\"\n", [3, 3]),
            ("self-documenting =", "f\"{z=}\"\n", [0, 0]),
            // the `=` keeps its spaces in the output; `!r` and `:` follow it
            ("spaced = with conversion", "f\"{z = !r:>10}\"\n", [0, 0]),
            // a `=` in a nested format expression (Python 3.12+)
            ("nested self-documenting =", "f\"{a:{w=}}\"\n", [0, 0]),
            // `()`, `=` — a keyword argument's `=` is a real operator
            ("keyword argument inside a field", "f\"{g(a=1)}\"\n", [2, 2]),
            // `()`, `:=`
            ("walrus inside a field", "f\"{(y := 1)}\"\n", [2, 2]),
        ];
        assert_operator_rows::<PythonParser>("foo.py", ROWS);
    }

    /// #1552: a JS-family `class` keyword bills as `function` does, once
    /// per keyword. Shared by the four grammars of the macro; each runs
    /// its own call so a grammar whose `Class2` stops being the keyword
    /// leaf fails alone. Before #1552 every row billed one fewer.
    #[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    const JS_FAMILY_CLASS_ROWS: &[(&str, &str, [u64; 2])] = &[
        // `class`, `{}`
        ("declaration", "class C {}\n", [2, 2]),
        // `const`, `=`, `class`, `{}`, `;` — the class *expression*
        // node wraps the keyword and bills nothing of its own
        ("expression", "const D = class {};\n", [5, 5]),
        // `class` twice, `extends`, `{}` twice
        ("two classes", "class A {}\nclass B extends A {}\n", [3, 5]),
    ];

    #[cfg(any(feature = "javascript", feature = "mozjs"))]
    #[test]
    fn js_class_keyword_is_an_operator_1552() {
        #[cfg(feature = "javascript")]
        assert_operator_rows::<JavascriptParser>("foo.js", JS_FAMILY_CLASS_ROWS);
        #[cfg(feature = "mozjs")]
        assert_operator_rows::<MozjsParser>("foo.js", JS_FAMILY_CLASS_ROWS);
    }

    /// #1554: a function *expression* bills its `function` keyword once,
    /// as a declaration does — the `function_expression` wrapper bills
    /// nothing of its own. Before #1554 the plain and `async` rows billed
    /// one extra unique and total operator, and the nested row one extra
    /// unique and two extra totals. The declaration and generator rows
    /// are controls: neither node was ever in the operator arm.
    #[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    const JS_FAMILY_FUNCTION_ROWS: &[(&str, &str, [u64; 2])] = &[
        // `function`, `()`, `{}`
        ("declaration", "function h() {}\n", [3, 3]),
        // `const`, `=`, `function`, `()`, `{}`, `;`
        ("expression", "const f = function () {};\n", [6, 6]),
        // `const`, `=`, `async`, `function`, `()`, `{}`, `;`
        (
            "async expression",
            "const f = async function () {};\n",
            [7, 7],
        ),
        // `const`, `=`, `function`, `*`, `()`, `{}`, `;` — a generator
        // expression is its own `generator_function` node, never billed
        (
            "generator expression",
            "const f = function* () {};\n",
            [7, 7],
        ),
        // `const`, `=`, `return`, `;` x2, and `function`, `()`, `{}`
        // twice each
        (
            "nested expressions",
            "const f = function () { return function () {}; };\n",
            [7, 11],
        ),
    ];

    #[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))]
    #[test]
    fn js_family_function_expression_bills_function_once_1554() {
        #[cfg(feature = "javascript")]
        assert_operator_rows::<JavascriptParser>("foo.js", JS_FAMILY_FUNCTION_ROWS);
        #[cfg(feature = "mozjs")]
        assert_operator_rows::<MozjsParser>("foo.js", JS_FAMILY_FUNCTION_ROWS);
        #[cfg(feature = "typescript")]
        {
            assert_operator_rows::<TypescriptParser>("foo.ts", JS_FAMILY_FUNCTION_ROWS);
            assert_operator_rows::<TsxParser>("foo.tsx", JS_FAMILY_FUNCTION_ROWS);
        }
    }

    /// #1552 for the two TypeScript grammars: the shared `class` rows,
    /// plus their own `interface` and `enum` declaration keywords.
    #[cfg(feature = "typescript")]
    #[test]
    fn typescript_declaration_keywords_are_operators_1552() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `interface`, `{}`
            ("interface", "interface I {}\n", [2, 2]),
            // `enum`, `{}`
            ("enum", "enum E { A }\n", [2, 2]),
        ];
        assert_operator_rows::<TypescriptParser>("foo.ts", JS_FAMILY_CLASS_ROWS);
        assert_operator_rows::<TypescriptParser>("foo.ts", ROWS);
        assert_operator_rows::<TsxParser>("foo.tsx", JS_FAMILY_CLASS_ROWS);
        assert_operator_rows::<TsxParser>("foo.tsx", ROWS);
    }

    /// #1552: Java's type-declaration keywords are operators, as C#'s
    /// are. The class-literal row pins the guard: the `class` tail of
    /// `C.class` is an operand (#1566), not a declaration keyword.
    #[cfg(feature = "java")]
    #[test]
    fn java_declaration_keywords_are_operators_1552() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `class`, `{}`
            ("class", "class C {}\n", [2, 2]),
            // `interface`, `{}`
            ("interface", "interface I {}\n", [2, 2]),
            // `enum`, `{}`
            ("enum", "enum E { A }\n", [2, 2]),
            // `record`, `()`, `int`, `{}`
            ("record", "record R(int x) {}\n", [4, 4]),
            // `@interface`, `{}`
            ("annotation type", "@interface N {}\n", [2, 2]),
            // `class`, `{}`, `=`, `.`, `;` — one `class`: the literal's
            // tail is an operand (#1566)
            ("class literal", "class U { Object o = C.class; }\n", [5, 5]),
        ];
        assert_operator_rows::<JavaParser>("Foo.java", ROWS);
    }

    /// #1560: a Java type name is an operand, as in C#, Rust, the C
    /// family, Go, Groovy and TypeScript. Each row isolates one position
    /// of the single `type_identifier` kind. The class-literal rows pin
    /// that a type inside `Foo.class` bills like any other (#1566),
    /// whether it sits there directly or under an array or scoped type,
    /// beside the literal's `class` tail; the `var` rows, that the inferred-type
    /// keyword bills nothing while a variable named `var` stays an
    /// operand.
    #[cfg(feature = "java")]
    #[test]
    fn java_type_names_are_operands_1560() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `C`, `I` x2, `Foo`, `f`
            (
                "field type and implements",
                "class C implements I { Foo f; }\ninterface I {}\n",
                [4, 5],
            ),
            // `C`, `java`, `util`, `List`, `Foo`, `l`
            (
                "scoped and generic",
                "class C { java.util.List<Foo> l; }\n",
                [6, 6],
            ),
            // `C`, `T` x2, `Comparable`
            (
                "type parameter",
                "class C<T extends Comparable<T>> {}\n",
                [3, 4],
            ),
            // `C`, `m`, `Ex`
            ("throws", "class C { void m() throws Ex {} }\n", [3, 3]),
            // `C`, `Object`, `a`, `Foo`, `class`
            (
                "class literal",
                "class C { Object a = Foo.class; }\n",
                [5, 5],
            ),
            // `C`, `Object`, `a`, `Foo`, `class`
            (
                "array class literal",
                "class C { Object a = Foo[].class; }\n",
                [5, 5],
            ),
            // `C`, `Object`, `a`, `java`, `util`, `List`, `class`
            (
                "scoped class literal",
                "class C { Object a = java.util.List.class; }\n",
                [7, 7],
            ),
            // `C`, `m`, `x`, `1` — no `var`
            (
                "inferred type",
                "class C { void m() { var x = 1; } }\n",
                [4, 4],
            ),
            // `C`, `m`, `var`, `1` — the variable's name
            (
                "variable named var",
                "class C { void m() { int var = 1; } }\n",
                [4, 4],
            ),
        ];
        assert_operand_rows::<JavaParser>("Foo.java", ROWS);
    }

    /// One class literal's own vocabulary: the source spelling, then the
    /// operators and operands it adds to the fixture's frame.
    #[cfg(any(feature = "groovy", feature = "java"))]
    type ClassLiteralParts = (
        &'static str,
        &'static [&'static str],
        &'static [&'static str],
    );

    /// #1566: the class-literal shapes Java and Groovy spell alike. The
    /// expected parts are what Groovy — untouched by #1566 — already
    /// billed for `Foo.class`: the type name an operand, the `.` and
    /// `[]` operators, and the `class` tail an operand. A primitive or
    /// `void` receiver is an operator keyed by its spelling, as Java's
    /// keyword is; Groovy joined that half in #1568. Both tests below
    /// read this one table, so the two languages cannot drift apart.
    #[cfg(any(feature = "groovy", feature = "java"))]
    const SHARED_CLASS_LITERALS: &[ClassLiteralParts] = &[
        ("Foo.class", &["."], &["Foo", "class"]),
        ("Foo[].class", &[".", "[]"], &["Foo", "class"]),
        (
            "java.util.List.class",
            &["."],
            &["List", "class", "java", "util"],
        ),
        ("int.class", &[".", "int"], &["class"]),
        ("int[].class", &[".", "[]", "int"], &["class"]),
        ("void.class", &[".", "void"], &["class"]),
    ];

    /// Asserts each literal's operator and operand vocabularies inside
    /// `frame`, which spells the fixture around it and contributes
    /// `frame_ops` / `frame_operands` of its own.
    #[cfg(any(feature = "groovy", feature = "java"))]
    #[track_caller]
    fn assert_class_literal_parts<T: crate::MetricSuite>(
        file: &str,
        frame: fn(&str) -> String,
        frame_ops: &[&str],
        frame_operands: &[&str],
        rows: &[ClassLiteralParts],
    ) {
        let merged = |frame: &[&str], parts: &[&str]| {
            let mut all: Vec<String> = frame.iter().chain(parts).map(|s| (*s).to_owned()).collect();
            all.sort_unstable();
            all.dedup();
            all
        };
        for (literal, ops, operands) in rows {
            let got = ops_of::<T>(&frame(literal), file);
            assert_eq!(
                got.operators,
                merged(frame_ops, ops),
                "operators of {literal}"
            );
            assert_eq!(
                got.operands,
                merged(frame_operands, operands),
                "operands of {literal}"
            );
        }
    }

    /// #1566: a Java class literal bills its parts. JLS §15.8.2 makes it
    /// a primary expression rather than a literal (§3.10 lists none), so
    /// the type name is an operand as anywhere else, `.` and `[]` are
    /// operators, and the `class` tail is the operand they act on — the
    /// split Kotlin's and PHP's `Foo::class` and Groovy's `Foo.class`
    /// already made. Before the fix the literal billed as one operand
    /// spelled by its whole text while `.`, `[]` and a primitive inside
    /// it also billed as operators. The shared rows take their expected
    /// values from Groovy, whose primitive and `void` rows joined them
    /// in #1568.
    #[cfg(feature = "java")]
    #[test]
    fn java_class_literal_bills_its_parts_1566() {
        const FRAME_OPS: &[&str] = &[";", "=", "class", "{}"];
        const FRAME_OPERANDS: &[&str] = &["C", "Object", "c"];
        let frame = |literal: &str| format!("class C {{ Object c = {literal}; }}\n");
        assert_class_literal_parts::<JavaParser>(
            "Foo.java",
            frame,
            FRAME_OPS,
            FRAME_OPERANDS,
            SHARED_CLASS_LITERALS,
        );
        // The totals pin the multiplicities a vocabulary cannot: the frame
        // bills four operators (`class`, `{}`, `=`, `;`) and three operands
        // (`C`, `Object`, `c`), and each literal adds its parts once —
        // `java.util.List.class` its three `.` and four names.
        assert_halstead_rows::<JavaParser>(
            "Foo.java",
            &[
                ("int", "class C { Object c = int.class; }\n", [6, 4]),
                ("array", "class C { Object c = Foo[].class; }\n", [6, 5]),
                (
                    "scoped",
                    "class C { Object c = java.util.List.class; }\n",
                    [7, 7],
                ),
                ("void", "class C { Object c = void.class; }\n", [6, 4]),
            ],
            |h| [h.total_operators(), h.total_operands()],
        );
    }

    /// #1566's oracle: Groovy bills the shared class-literal shapes the
    /// way Java now does. A Groovy field needs no `;`.
    #[cfg(feature = "groovy")]
    #[test]
    fn groovy_class_literal_bills_its_parts_1566() {
        assert_class_literal_parts::<GroovyParser>(
            "foo.groovy",
            |literal| format!("class C {{ Object c = {literal} }}\n"),
            &["=", "class", "{}"],
            &["C", "Object", "c"],
            SHARED_CLASS_LITERALS,
        );
    }

    /// #1568: a Groovy primitive type bills as the operator Java's
    /// keyword does, keyed by its spelling, in every position the
    /// grammar gives it: a `type_identifier` where a type is declared,
    /// a plain `identifier` where the grammar misreads an uninitialised
    /// local (`int t` parses as two expression statements). Each row's
    /// operators are what the Java twin of the issue fixture bills, which
    /// `groovy_primitive_type_matches_java_1568` checks directly.
    #[cfg(feature = "groovy")]
    #[test]
    fn groovy_primitive_types_are_operators_1568() {
        const ROWS: &[(&str, &[&str], &[&str])] = &[
            (
                "class A { boolean m() { int x = 1; } }\n",
                &["()", ";", "=", "boolean", "class", "int", "{}"],
                &["1", "A", "m", "x"],
            ),
            (
                "void m(long a, char b) {}\n",
                &["()", ",", "char", "long", "void", "{}"],
                &["a", "b", "m"],
            ),
            (
                "def m() { short s\n  double d }\n",
                &["()", "def", "double", "short", "{}"],
                &["d", "m", "s"],
            ),
            (
                "byte[] a = (float) b as byte\n",
                &["()", "=", "[]", "as", "byte", "float"],
                &["a", "b"],
            ),
            // A user type's name stays an operand, however close its
            // spelling: only the exact keyword bills.
            (
                "Integer a\nInt b\ninte c\n",
                &[],
                &["Int", "Integer", "a", "b", "c", "inte"],
            ),
        ];
        for (source, operators, operands) in ROWS {
            let ops = ops_of::<GroovyParser>(source, "foo.groovy");
            assert_eq!(ops.operators, *operators, "operators of {source:?}");
            assert_eq!(ops.operands, *operands, "operands of {source:?}");
        }
    }

    /// #1568's oracle: the issue's fixture scores the same in Groovy and
    /// Java, vocabulary and multiplicities alike.
    #[cfg(all(feature = "groovy", feature = "java"))]
    #[test]
    fn groovy_primitive_type_matches_java_1568() {
        let source = "class A { boolean m() { int x = 1; } }\n";
        let groovy = ops_of::<GroovyParser>(source, "foo.groovy");
        let java = ops_of::<JavaParser>(source, "Foo.java");
        assert_eq!(groovy.operators, java.operators);
        assert_eq!(groovy.operands, java.operands);
        // `()`, `;`, `=`, `boolean`, `class`, `int`, `{}` x2 / `A`, `m`,
        // `x`, `1`
        assert_halstead_rows::<GroovyParser>(
            "foo.groovy",
            &[("issue fixture", source, [8, 4])],
            |h| [h.total_operators(), h.total_operands()],
        );
        assert_halstead_rows::<JavaParser>("Foo.java", &[("issue fixture", source, [8, 4])], |h| {
            [h.total_operators(), h.total_operands()]
        });
    }

    /// #1568: Groovy reserves the primitive type names, so one can name
    /// something only as a member selector after a `.`-family operator
    /// or as a map or named-argument label. Each position stays an
    /// operand; each row is its own source so a selector kind dropped
    /// from the gate fails by name.
    #[cfg(feature = "groovy")]
    #[test]
    fn groovy_primitive_spelled_names_stay_operands_1568() {
        for source in [
            "x.int\n",
            "x?.int\n",
            "x??.int\n",
            "x*.int\n",
            "x.@int\n",
            "x.&int\n",
            "x::int\n",
            "def m = [int: 1]\n",
            "f(int: 1)\n",
        ] {
            assert_keywords_are_operands_only::<GroovyParser>(source, "foo.groovy", &["int"]);
        }
    }

    /// #1552: Groovy's type-declaration keywords are operators, as
    /// Java's are. `String.class` is a `field_access` whose `class` is a
    /// plain identifier, so it stays an operand with no guard needed.
    #[cfg(feature = "groovy")]
    #[test]
    fn groovy_declaration_keywords_are_operators_1552() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `class`, `{}`
            ("class", "class C {}\n", [2, 2]),
            // `interface`, `{}`
            ("interface", "interface I {}\n", [2, 2]),
            // `trait`, `{}`
            ("trait", "trait T {}\n", [2, 2]),
            // `enum`, `{}`
            ("enum", "enum E { A }\n", [2, 2]),
            // `record`, `()`, `int`, `{}` — as Java's row, since #1568
            ("record", "record R(int x) {}\n", [4, 4]),
            // `def`, `=`, `.` — no `class`
            ("class reference", "def a = String.class\n", [3, 3]),
            // `=` twice: a script-level `record` / `trait` used as a name
            // falls into error recovery with the keyword leaf, which is
            // not a declaration and bills nothing
            ("contextual names", "record = 3\ntrait = 4\n", [1, 2]),
        ];
        assert_operator_rows::<GroovyParser>("foo.groovy", ROWS);
    }

    /// #1565: Java bills every modifier, as C# and Kotlin do, each as
    /// its keyword leaf and never as the `modifiers` wrapper. Before the
    /// fix only `abstract`, `final`, `transient`, `synchronized` and
    /// `default` billed. The rows from "import static" on are controls:
    /// a directive's `static` and the contextual words used as names add
    /// no operator.
    #[cfg(feature = "java")]
    #[test]
    fn java_modifiers_are_operators_1565() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `class`, `{}`, `public`, `private`, `protected`, `int` x3,
            // `;` x3
            (
                "visibility",
                "class C { public int a; private int b; protected int c; }\n",
                [7, 11],
            ),
            // `class`, `{}`, `static`, `final`, `int` x2, `=`, `;` x2,
            // `transient`, `volatile`
            (
                "field modifiers",
                "class C { static final int a = 1; transient volatile int b; }\n",
                [9, 11],
            ),
            // `class`, `{}` x3, `native`, `synchronized`, `strictfp`,
            // `void` x3, `()` x3, `;`
            (
                "method modifiers",
                "class C { native void n(); synchronized void s() {} strictfp void f() {} }\n",
                [8, 14],
            ),
            // `sealed`, `class` x2, `permits`, `{}` x2, `non-sealed`,
            // `extends`
            (
                "sealed hierarchy",
                "sealed class S permits T {}\nnon-sealed class T extends S {}\n",
                [6, 8],
            ),
            // `class`, `{}` x2, `static`: the initializer's `static`
            ("static initializer", "class C { static {} }\n", [3, 4]),
            // `class`, `{}` x2, `public`, `()`, `return`, `;`: the
            // annotation beside the modifier bills nothing of its own
            (
                "annotation in modifiers",
                "class C { @Override public String toString() { return s; } }\n",
                [6, 7],
            ),
            // `.` x3, `;`, `class`, `{}`: no `static`
            (
                "import static",
                "import static java.lang.Math.max;\nclass C {}\n",
                [4, 6],
            ),
            // `{}`, `;`: no `static`, and `transitive` stays unbilled
            // with the rest of the module directive
            (
                "requires static",
                "module m { requires static transitive a; }\n",
                [2, 2],
            ),
            // `class`, `{}` x2, `void`, `()`, `=` x3, `;` x3, `int`
            (
                "names",
                "class C { void m() { var sealed = 1; int permits = 2; sealed = permits; } }\n",
                [7, 12],
            ),
            // `class`, `{}`, `int` x2, `,`, `;` x2, `=`, `-`
            (
                "non-sealed as a subtraction",
                "class C { int non, sealed; int z = non-sealed; }\n",
                [7, 9],
            ),
        ];
        assert_operator_rows::<JavaParser>("Foo.java", ROWS);
    }

    /// #1565: the issue's fixture, by vocabulary. Each modifier is
    /// listed by its own word, never by `modifiers`, and the contextual
    /// words used as names are operands only. No getter edit makes that
    /// second half fail, since Java's arms carry no guard on those
    /// words: it pins the grammar emitting an `identifier` for a name,
    /// so a bump that routes one to the keyword kind trips it.
    #[cfg(feature = "java")]
    #[test]
    fn java_modifier_vocabulary_1565() {
        let ops = ops_of::<JavaParser>(
            "public abstract class C { private static final int a = 1; \
             protected transient int b; public synchronized void m() {} }\n",
            "Foo.java",
        );
        assert_eq!(
            ops.operators,
            [
                "()",
                ";",
                "=",
                "abstract",
                "class",
                "final",
                "int",
                "private",
                "protected",
                "public",
                "static",
                "synchronized",
                "transient",
                "void",
                "{}",
            ]
        );
        assert_eq!(ops.operands, ["1", "C", "a", "b", "m"]);

        assert_keywords_are_operands_only::<JavaParser>(
            "class C { int sealed() { return permits; } void m() { sealed(); } }\n",
            "Foo.java",
            &["sealed", "permits"],
        );
    }

    /// #1565: Groovy bills every modifier, as Java now does. Its grammar
    /// has no `modifiers` wrapper, so each leaf sits directly under its
    /// declaration. The rows declare with `def`, so the only primitive
    /// type counted is `void`, an operator since #1568. The last two
    /// rows are controls.
    #[cfg(feature = "groovy")]
    #[test]
    fn groovy_modifiers_are_operators_1565() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `class`, `{}`, `public`, `private`, `protected`, `def` x3
            (
                "visibility",
                "class C {\n  public def a\n  private def b\n  protected def c\n}\n",
                [6, 8],
            ),
            // `class`, `{}`, `static`, `final`, `def` x2, `=`,
            // `transient`, `volatile`
            (
                "field modifiers",
                "class C {\n  static final def a = 1\n  transient volatile def b\n}\n",
                [8, 9],
            ),
            // `class`, `{}` x3, `native`, `synchronized`, `strictfp`,
            // `void` x3 (#1568), `()` x3
            (
                "method modifiers",
                "class C {\n  native void n()\n  synchronized void s() {}\n  \
                 strictfp void f() {}\n}\n",
                [7, 13],
            ),
            // `sealed`, `class` x2, `permits`, `{}` x2, `non-sealed`,
            // `extends`
            (
                "sealed hierarchy",
                "sealed class S permits T {}\nnon-sealed class T extends S {}\n",
                [6, 8],
            ),
            // `sealed` x2, `interface`, `trait`, `permits` x2, `{}` x2
            (
                "sealed interface and trait",
                "sealed interface I permits A {}\nsealed trait T permits A {}\n",
                [5, 8],
            ),
            // `class`, `{}` x3, `static` x2, `void` (#1568), `()`: an
            // initializer and a script-level method
            (
                "static initializer and method",
                "class C {\n  static {}\n}\nstatic void top() {}\n",
                [5, 8],
            ),
            // `.` x3: no `static`, as `import` bills nothing
            (
                "import static",
                "import static java.lang.Math.max\n",
                [1, 3],
            ),
            // `=` x2, `.`, `()` x2, `def`: a statement opening with
            // `sealed` as a name fails into an `ERROR` holding the
            // keyword leaf, which bills nothing
            (
                "contextual names",
                "sealed = 1\nsealed.call()\ndef permits = 2\nfoo(permits)\n",
                [4, 6],
            ),
        ];
        assert_operator_rows::<GroovyParser>("foo.groovy", ROWS);
    }

    /// #1565: the issue's Groovy fixture, by vocabulary, plus the
    /// modifier words in positions the grammar parses as a name. Unlike
    /// Java, Groovy accepts even its hard keywords as a map key, a named
    /// argument and a member name. No getter edit makes that half fail:
    /// it pins the grammar emitting an `identifier` there, so a bump
    /// that routes one to the keyword kind trips it.
    #[cfg(feature = "groovy")]
    #[test]
    fn groovy_modifier_vocabulary_1565() {
        let ops = ops_of::<GroovyParser>(
            "public abstract class C { private static final def a = 1; protected def m() {} }\n",
            "foo.groovy",
        );
        assert_eq!(
            ops.operators,
            [
                "()",
                ";",
                "=",
                "abstract",
                "class",
                "def",
                "final",
                "private",
                "protected",
                "public",
                "static",
                "{}",
            ]
        );
        assert_eq!(ops.operands, ["1", "C", "a", "m"]);

        assert_keywords_are_operands_only::<GroovyParser>(
            "x = sealed\nfoo(permits)\ndef m = [static: 1, public: 2]\n\
             foo(native: 1, volatile: 2)\ny = obj.private\n",
            "foo.groovy",
            &[
                "sealed", "permits", "static", "public", "native", "volatile", "private",
            ],
        );
    }

    /// #1565's oracle: Groovy accepts Java's modifier-heavy fixture
    /// verbatim, and the two languages bill it alike, vocabulary and
    /// multiplicities. Neither side's expectation is typed by the fix
    /// alone: a modifier one getter drops shows as a disagreement.
    #[cfg(all(feature = "groovy", feature = "java"))]
    #[test]
    fn groovy_modifiers_match_java_1565() {
        let source = "public abstract class C { private static final int a = 1; \
                      protected transient int b; public synchronized void m() {} }\n";
        let groovy = ops_of::<GroovyParser>(source, "foo.groovy");
        let java = ops_of::<JavaParser>(source, "Foo.java");
        assert_eq!(groovy.operators, java.operators);
        assert_eq!(groovy.operands, java.operands);
        // `public` x2, `abstract`, `class`, `{}` x2, `private`, `static`,
        // `final`, `int` x2, `=`, `;` x2, `protected`, `transient`,
        // `synchronized`, `void`, `()`
        let rows = [("modifier fixture", source, [15, 19])];
        assert_operator_rows::<GroovyParser>("foo.groovy", &rows);
        assert_operator_rows::<JavaParser>("Foo.java", &rows);
    }

    /// #1552 rows shared by the two C++ clones. The template-parameter
    /// rows pin the synonym: `class T` is `typename T`, and the two
    /// spellings score alike. Both were unbilled until #1557 billed
    /// `typename`, and the parameter `class` with it.
    #[cfg(any(feature = "cpp", feature = "mozcpp"))]
    const CPP_DECLARATION_KEYWORD_ROWS: &[(&str, &str, [u64; 2])] = &[
        // `class`, `{}`, `;`
        ("class", "class C {};\n", [3, 3]),
        // `struct`, `{}`, `;`
        ("struct", "struct S {};\n", [3, 3]),
        // `union`, `{}`, `int`, `;` twice
        ("union", "union U { int a; };\n", [4, 5]),
        // `enum`, `{}`, `;`
        ("enum", "enum E { A };\n", [3, 3]),
        // `enum`, `class`, `{}`, `;`
        ("enum class", "enum class F { B };\n", [4, 4]),
        // `struct`, `;` — an elaborated type bills its keyword
        ("elaborated type", "struct S s;\n", [2, 2]),
        // `template`, `<>`, `class`, `struct`, `{}`, `;` — the parameter
        // list's brackets are one pair (#1559)
        (
            "class parameter",
            "template <class T> struct W {};\n",
            [6, 6],
        ),
        // as above, `typename` in place of `class`
        (
            "typename parameter",
            "template <typename T> struct W {};\n",
            [6, 6],
        ),
        // `template`, `<>`, `class`, `=`, `int`, `struct`, `{}`, `;`
        (
            "optional class parameter",
            "template <class T = int> struct W {};\n",
            [8, 8],
        ),
        // `template`, `<>`, `class`, `struct`, `{}`, `;` — `...` is an
        // operand
        (
            "variadic class parameter",
            "template <class... T> struct W {};\n",
            [6, 6],
        ),
    ];

    /// One call per clone, so reverting either arm fails its own row;
    /// Mozcpp owns no file extension, so this is its only coverage.
    #[cfg(all(feature = "cpp", feature = "mozcpp"))]
    #[test]
    fn cpp_declaration_keywords_are_operators_1552() {
        assert_operator_rows::<CppParser>("foo.cpp", CPP_DECLARATION_KEYWORD_ROWS);
        assert_operator_rows::<MozcppParser>("foo.cpp", CPP_DECLARATION_KEYWORD_ROWS);
    }

    /// #1552: C bills `struct` / `union` / `enum` as C++ does, so a
    /// header scores the same whichever grammar parses it.
    #[cfg(feature = "c")]
    #[test]
    fn c_declaration_keywords_are_operators_1552() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `struct`, `{}`, `int`, `;` twice
            ("struct", "struct S { int a; };\n", [4, 5]),
            // `union`, `{}`, `int`, `;` twice
            ("union", "union U { int a; };\n", [4, 5]),
            // `enum`, `{}`, `;`
            ("enum", "enum E { A };\n", [3, 3]),
            // `struct`, `;`
            ("elaborated type", "struct S s;\n", [2, 2]),
        ];
        assert_operator_rows::<CParser>("foo.c", ROWS);
    }

    /// #1578: C bills each storage class, function specifier and type
    /// qualifier as its keyword leaf, never as the
    /// `storage_class_specifier` / `type_qualifier` wrapper. Before the
    /// fix none of them billed.
    #[cfg(feature = "c")]
    #[test]
    fn c_modifiers_are_operators_1578() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `static`, `extern`, `register`, `auto`, `int` x4, `;` x4
            (
                "storage classes",
                "static int a;\nextern int b;\nregister int c;\nauto int d;\n",
                [6, 12],
            ),
            // `const`, `volatile`, `int` x3, `;` x3, `*`, `restrict`,
            // `_Atomic`
            (
                "qualifiers",
                "const volatile int a;\nint * restrict p;\n_Atomic int g;\n",
                [7, 11],
            ),
            // `inline`, `int`, `()` x2, `void` x3, `;` x2, `_Noreturn`
            (
                "function specifiers",
                "inline int f(void);\n_Noreturn void g(void);\n",
                [6, 10],
            ),
            // `__inline`, `int` x3, `()`, `void`, `;` x3, `__thread`, `*`,
            // `__restrict__`: each vendor spelling is its own operator
            (
                "vendor spellings",
                "__inline int f(void);\n__thread int t;\nint * __restrict__ q;\n",
                [8, 12],
            ),
            // `int`, `*`, `const`, `=`, `;`: a pointer's own qualifier
            ("pointer qualifier", "int * const p = 0;\n", [5, 5]),
            // `_Alignas`, `()`, `int`, `;`
            ("alignas", "_Alignas(8) int m;\n", [4, 4]),
            // `int`, `=`, `__extension__`, `;`: the expression prefix
            ("extension expression", "int q = __extension__ 1;\n", [4, 4]),
        ];
        assert_operator_rows::<CParser>("foo.c", ROWS);
    }

    /// #1578: the issue's C fixture, by vocabulary.
    #[cfg(feature = "c")]
    #[test]
    fn c_modifier_vocabulary_1578() {
        let ops = ops_of::<CParser>(
            "static inline const volatile int a = 1;\nextern int b;\nregister int c;\n",
            "foo.c",
        );
        assert_eq!(
            ops.operators,
            [
                ";", "=", "const", "extern", "inline", "int", "register", "static", "volatile",
            ]
        );
        assert_eq!(ops.operands, ["1", "a", "b", "c"]);
    }

    /// #1578 rows shared by the two C++ clones: C's modifiers plus C++'s
    /// own. Each bills as its keyword leaf, never as the
    /// `access_specifier` / `virtual_specifier` / `type_qualifier` /
    /// `explicit_function_specifier` wrapper.
    #[cfg(any(feature = "cpp", feature = "mozcpp"))]
    const CPP_MODIFIER_ROWS: &[(&str, &str, [u64; 2])] = &[
        // `class`, `{}`, `public`, `protected`, `private`, `:` x3,
        // `int` x3, `;` x4
        (
            "access labels",
            "class C { public: int a; protected: int b; private: int c; };\n",
            [8, 15],
        ),
        // `struct`, `{}`, `static`, `int` x2, `;` x4, `mutable`,
        // `virtual`, `void`, `()`, `const`, `override`, `final`
        (
            "member modifiers",
            "struct S { static int a; mutable int b; virtual void f() const override final; };\n",
            [12, 16],
        ),
        // `struct`, `{}`, `friend`, `class`, `;` x3, `explicit`, `()`,
        // `int`
        (
            "friend and explicit",
            "struct S { friend class D; explicit S(int); };\n",
            [8, 10],
        ),
        // `extern`, `inline`, `constexpr`, `int`, `()`, `{}`, `return`,
        // `;`: the `"C"` is an operand
        (
            "linkage specification",
            "extern \"C\" inline constexpr int g() { return 1; }\n",
            [8, 8],
        ),
        // `consteval`, `int` x2, `()`, `;` x2, `constinit`,
        // `thread_local`, `=`
        (
            "C++20 specifiers",
            "consteval int h();\nconstinit thread_local int t = 1;\n",
            [7, 9],
        ),
        // `void` x2, `()` x3, `noexcept` x2, `;` x2: the leaf bills, the
        // `noexcept` wrapper does not
        (
            "exception specification",
            "void k() noexcept;\nvoid k2() noexcept(true);\n",
            [4, 9],
        ),
        // `struct`, `final`, `{}` x3, `;` x3, `class` x2, `:` x2,
        // `public`, `private`, `virtual`
        (
            "base clauses",
            "struct B final {};\nclass E : public B {};\nclass F : private virtual B {};\n",
            [9, 15],
        ),
        // `void`, `()` x2, `{}` x2, `if`, `constexpr`
        (
            "if constexpr",
            "void f() { if constexpr (true) {} }\n",
            [5, 7],
        ),
        // `inline`, `namespace`, `{}`
        ("inline namespace", "inline namespace v1 {}\n", [3, 3]),
        // `int` x2, `=` x2, `;` x2: the contextual words as names add
        // no operator
        (
            "contextual names",
            "int override = 1;\nint final = override;\n",
            [3, 6],
        ),
    ];

    /// One call per clone, so reverting either arm fails its own row;
    /// Mozcpp owns no file extension, so this is its only lib coverage.
    #[cfg(all(feature = "cpp", feature = "mozcpp"))]
    #[test]
    fn cpp_modifiers_are_operators_1578() {
        assert_operator_rows::<CppParser>("foo.cpp", CPP_MODIFIER_ROWS);
        assert_operator_rows::<MozcppParser>("foo.cpp", CPP_MODIFIER_ROWS);
    }

    /// #1578: the issue's C++ fixture, by vocabulary, in both clones,
    /// plus `override` and `final` used as names. No getter edit makes
    /// that second half fail, since the arms carry no guard on those
    /// words: it pins the grammar emitting an `identifier` for a name,
    /// so a bump that routes one to the keyword kind trips it.
    #[cfg(all(feature = "cpp", feature = "mozcpp"))]
    #[test]
    fn cpp_modifier_vocabulary_1578() {
        const SOURCE: &str = "class C { public: static int a; \
             virtual void f() const override final; mutable int b; };\n\
             extern \"C\" inline constexpr int g() { return 1; }\n";
        const NAMES: &str = "int override = 1;\nint final() { return override; }\n";
        let expected_operators = [
            "()",
            ":",
            ";",
            "class",
            "const",
            "constexpr",
            "extern",
            "final",
            "inline",
            "int",
            "mutable",
            "override",
            "public",
            "return",
            "static",
            "virtual",
            "void",
            "{}",
        ];
        let expected_operands = ["\"C\"", "1", "C", "a", "b", "f", "g"];

        let cpp = ops_of::<CppParser>(SOURCE, "foo.cpp");
        assert_eq!(cpp.operators, expected_operators);
        assert_eq!(cpp.operands, expected_operands);
        let mozcpp = ops_of::<MozcppParser>(SOURCE, "foo.cpp");
        assert_eq!(mozcpp.operators, expected_operators);
        assert_eq!(mozcpp.operands, expected_operands);

        assert_keywords_are_operands_only::<CppParser>(NAMES, "foo.cpp", &["override", "final"]);
        assert_keywords_are_operands_only::<MozcppParser>(NAMES, "foo.cpp", &["override", "final"]);
    }

    /// #1578: every modifier spelling the arms list bills under its own
    /// name, one fixture line apiece, so dropping any one kind from an
    /// arm fails its own entry. The row tests above pin the counts; this
    /// one pins the spellings they leave out.
    #[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))]
    #[track_caller]
    fn assert_modifier_spellings_bill<T: crate::MetricSuite>(file: &str, rows: &[(&str, &str)]) {
        for (spelling, source) in rows {
            let ops = ops_of::<T>(source, file);
            assert!(
                ops.operators.iter().any(|o| o == spelling),
                "{file}: `{spelling}` must be an operator in {source:?}; operators were {:?}",
                ops.operators
            );
            assert!(
                !ops.operands.iter().any(|o| o == spelling),
                "{file}: `{spelling}` must not be an operand; operands were {:?}",
                ops.operands
            );
        }
    }

    /// The spellings C and C++ share, each in a declaration both
    /// grammars parse without error.
    #[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))]
    const C_FAMILY_MODIFIER_SPELLINGS: &[(&str, &str)] = &[
        ("static", "static int a;\n"),
        ("extern", "extern int a;\n"),
        ("register", "register int a;\n"),
        ("inline", "inline int f(void);\n"),
        ("__inline", "__inline int f(void);\n"),
        ("__inline__", "__inline__ int f(void);\n"),
        ("__forceinline", "__forceinline int f(void);\n"),
        ("thread_local", "thread_local int a;\n"),
        ("__thread", "__thread int a;\n"),
        ("const", "const int a = 1;\n"),
        ("constexpr", "constexpr int a = 1;\n"),
        ("volatile", "volatile int a;\n"),
        ("restrict", "int * restrict p;\n"),
        ("__restrict__", "int * __restrict__ p;\n"),
        ("_Atomic", "_Atomic int a;\n"),
        ("_Noreturn", "_Noreturn void f(void);\n"),
        ("noreturn", "noreturn void f(void);\n"),
        ("_Nonnull", "int * _Nonnull p;\n"),
        ("alignas", "alignas(8) int a;\n"),
        ("_Alignas", "_Alignas(8) int a;\n"),
        ("__extension__", "__extension__ int a;\n"),
        // The one place the grammar emits `__volatile__`: as a GNU `asm`
        // qualifier, where the plain spelling bills too.
        (
            "__volatile__",
            "void f(void) { __asm__ __volatile__(\"nop\"); }\n",
        ),
        ("volatile", "void f(void) { asm volatile(\"nop\"); }\n"),
    ];

    #[cfg(feature = "c")]
    #[test]
    fn c_modifier_spellings_bill_1578() {
        assert_modifier_spellings_bill::<CParser>("foo.c", C_FAMILY_MODIFIER_SPELLINGS);
        // C's storage class `auto`; C++ has none (see the Cpp arm).
        assert_modifier_spellings_bill::<CParser>("foo.c", &[("auto", "auto int a;\n")]);
    }

    #[cfg(all(feature = "cpp", feature = "mozcpp"))]
    #[test]
    fn cpp_modifier_spellings_bill_1578() {
        const CPP_ONLY: &[(&str, &str)] = &[
            ("virtual", "struct S { virtual void f(); };\n"),
            ("mutable", "struct S { mutable int a; };\n"),
            ("constinit", "constinit int a = 1;\n"),
            ("consteval", "consteval int f() { return 1; }\n"),
            ("explicit", "struct S { explicit S(int); };\n"),
            ("friend", "struct S { friend class D; };\n"),
            ("public", "class C { public: int a; };\n"),
            ("private", "class C { private: int a; };\n"),
            ("protected", "class C { protected: int a; };\n"),
            ("override", "struct S { void f() override; };\n"),
            ("final", "struct S final {};\n"),
            ("noexcept", "void f() noexcept;\n"),
        ];
        for rows in [C_FAMILY_MODIFIER_SPELLINGS, CPP_ONLY] {
            assert_modifier_spellings_bill::<CppParser>("foo.cpp", rows);
            assert_modifier_spellings_bill::<MozcppParser>("foo.cpp", rows);
        }
    }

    /// #1552: ObjC bills C's `struct` and its own class and protocol
    /// declaration keywords. `@class` already billed its `@` and stays
    /// as it was.
    #[cfg(feature = "objc")]
    #[test]
    fn objc_declaration_keywords_are_operators_1552() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `@interface`, `:`
            ("interface", "@interface C : NSObject\n@end\n", [2, 2]),
            // `@implementation`
            ("implementation", "@implementation C\n@end\n", [1, 1]),
            // `@protocol`
            ("protocol", "@protocol P\n@end\n", [1, 1]),
            // `struct`, `{}`, `int`, `;` twice
            ("struct", "struct S { int a; };\n", [4, 5]),
            // `@`, `;` — unchanged by #1552
            ("forward class", "@class Fwd;\n", [2, 2]),
        ];
        assert_operator_rows::<ObjcParser>("foo.m", ROWS);
    }

    /// #1579: ObjC bills C's declaration modifiers as `c.rs` does
    /// (#1578), and its own: ivar visibility labels, property attribute
    /// words, ARC ownership and nullability qualifiers, protocol section
    /// labels, method-type qualifiers and generic variance. Before the
    /// fix none of them billed.
    #[cfg(feature = "objc")]
    #[test]
    fn objc_modifiers_are_operators_1579() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `static`, `const`, `int`, `=`, `;`: the issue's first line
            ("C modifiers", "static const int a = 1;\n", [5, 5]),
            // `@interface`, `{}`, `@public`, `@private`, `int` x2, `;` x2
            (
                "ivar visibility",
                "@interface C { @public int x; @private int y; }\n@end\n",
                [6, 8],
            ),
            // `@interface`, `()`, `nonatomic`, `,` x2, `strong`,
            // `getter`, `=`, `;`: `isY` is an operand, `id` and
            // `@property` bill nothing
            (
                "property attributes",
                "@interface C\n@property (nonatomic, strong, getter=isY) id y;\n@end\n",
                [8, 9],
            ),
            // `__weak`, `__strong`, `__block`, `int`, `;` x3
            (
                "ownership qualifiers",
                "__weak id a;\n__strong id b;\n__block int c;\n",
                [5, 7],
            ),
            // `*` x2, `_Nullable`, `nullable`, `;` x2
            (
                "nullability qualifiers",
                "NSString * _Nullable f;\nNSString * nullable k;\n",
                [4, 6],
            ),
            // `@protocol`, `@optional`, `@required`, `-` x2, `()` x3,
            // `void` x2, `;` x2, `oneway`, `:`, `out`, `*`
            (
                "protocol sections and method qualifiers",
                "@protocol P\n@optional\n- (void)m;\n@required\n\
                 - (oneway void)n:(out id *)b;\n@end\n",
                [11, 16],
            ),
            // `@interface`, `<>`, `__covariant`, `:`
            (
                "generic variance",
                "@interface G<__covariant T> : NSObject\n@end\n",
                [4, 4],
            ),
        ];
        assert_operator_rows::<ObjcParser>("foo.m", ROWS);
    }

    /// #1579: the `nullable` qualifier and the `nullable` property
    /// attribute are one operator. The attribute has no keyword kind, so
    /// it is keyed by text, and keying the qualifier by kind would list
    /// the one word twice in `n1`.
    #[cfg(feature = "objc")]
    #[test]
    fn objc_nullable_is_one_operator_1579() {
        const SOURCE: &str = "@interface C\n@property (nullable) id y;\n- (nullable id)m;\n@end\n";
        // `@interface`, `()` x2, `nullable` x2, `-`, `;` x2
        assert_operator_rows::<ObjcParser>("foo.m", &[("nullable", SOURCE, [5, 8])]);
        let ops = ops_of::<ObjcParser>(SOURCE, "foo.m");
        assert_eq!(ops.operators, ["()", "-", ";", "@interface", "nullable"]);
        assert_eq!(ops.operands, ["C", "m", "y"]);
    }

    /// #1579's oracle: a `.m` is a C translation unit, so C's
    /// modifier-heavy declarations score alike in both grammars,
    /// vocabulary and multiplicities. Neither expectation is typed by
    /// the fix: a modifier one getter drops shows as a disagreement.
    #[cfg(all(feature = "c", feature = "objc"))]
    #[test]
    fn objc_c_modifiers_match_c_1579() {
        let source = "static inline const volatile int a = 1;\nextern int b;\n\
                      register int c;\nauto int d;\nint * restrict p;\n_Atomic int g;\n\
                      __thread int t;\n_Noreturn void h(void);\n_Alignas(8) int m;\n";
        let objc = ops_of::<ObjcParser>(source, "foo.m");
        let c = ops_of::<CParser>(source, "foo.c");
        assert_eq!(objc.operators, c.operators);
        assert_eq!(objc.operands, c.operands);
        // `static`, `inline`, `const`, `volatile`, `int` x8, `=`, `;` x9,
        // `extern`, `register`, `auto`, `*`, `restrict`, `_Atomic`,
        // `__thread`, `_Noreturn`, `void` x2, `()` x2, `_Alignas`
        let rows = [("C modifiers", source, [18, 35])];
        assert_operator_rows::<ObjcParser>("foo.m", &rows);
        assert_operator_rows::<CParser>("foo.c", &rows);
    }

    /// #1579: every modifier word the ObjC arm lists bills under its own
    /// name, one fixture apiece, so dropping any kind from the arm fails
    /// its own entry. The spellings C shares with C++ run through the
    /// #1578 table; `OBJC_ONLY` holds the rest, C's `auto` included, plus
    /// a sample of the text-keyed property attributes.
    #[cfg(feature = "objc")]
    #[test]
    fn objc_modifier_spellings_bill_1579() {
        const OBJC_ONLY: &[(&str, &str)] = &[
            ("auto", "auto int a;\n"),
            ("__const", "__const int a;\n"),
            ("_Complex", "double _Complex z;\n"),
            ("__complex", "double __complex z;\n"),
            ("nullable", "NSString * nullable p;\n"),
            ("_Nullable", "NSString * _Nullable p;\n"),
            ("__nullable", "NSString * __nullable p;\n"),
            ("_Nullable_result", "NSString * _Nullable_result p;\n"),
            ("_Null_unspecified", "NSString * _Null_unspecified p;\n"),
            ("__nonnull", "NSString * __nonnull p;\n"),
            ("__autoreleasing", "__autoreleasing id a;\n"),
            ("__block", "__block int a;\n"),
            ("__strong", "__strong id a;\n"),
            ("__unsafe_unretained", "__unsafe_unretained id a;\n"),
            ("__weak", "__weak id a;\n"),
            ("__bridge", "void f(void) { id x = (__bridge id)p; }\n"),
            (
                "__bridge_retained",
                "void f(void) { void *x = (__bridge_retained void *)p; }\n",
            ),
            (
                "__bridge_transfer",
                "void f(void) { id x = (__bridge_transfer id)p; }\n",
            ),
            ("__kindof", "__kindof NSView *v;\n"),
            (
                "__covariant",
                "@interface G<__covariant T> : NSObject\n@end\n",
            ),
            (
                "__contravariant",
                "@interface G<__contravariant T> : NSObject\n@end\n",
            ),
            ("in", "@protocol P\n- (void)m:(in id)a;\n@end\n"),
            ("out", "@protocol P\n- (void)m:(out id *)a;\n@end\n"),
            ("inout", "@protocol P\n- (void)m:(inout id *)a;\n@end\n"),
            ("bycopy", "@protocol P\n- (void)m:(bycopy id)a;\n@end\n"),
            ("byref", "@protocol P\n- (void)m:(byref id)a;\n@end\n"),
            ("oneway", "@protocol P\n- (oneway void)m;\n@end\n"),
            ("@public", "@interface C { @public int x; }\n@end\n"),
            ("@private", "@interface C { @private int x; }\n@end\n"),
            ("@protected", "@interface C { @protected int x; }\n@end\n"),
            ("@package", "@interface C { @package int x; }\n@end\n"),
            ("@optional", "@protocol P\n@optional\n- (void)m;\n@end\n"),
            ("@required", "@protocol P\n@required\n- (void)m;\n@end\n"),
            ("copy", "@interface C\n@property (copy) id y;\n@end\n"),
            (
                "readonly",
                "@interface C\n@property (readonly) id y;\n@end\n",
            ),
            ("class", "@interface C\n@property (class) id y;\n@end\n"),
            (
                "setter",
                "@interface C\n@property (setter=sY:) id y;\n@end\n",
            ),
        ];
        assert_modifier_spellings_bill::<ObjcParser>("foo.m", C_FAMILY_MODIFIER_SPELLINGS);
        assert_modifier_spellings_bill::<ObjcParser>("foo.m", OBJC_ONLY);
    }

    /// #1579: the plain-word modifiers stay operands where they name a
    /// variable, and a property attribute's `getter=` value is the
    /// selector it names, not a modifier. The arms carry no guard on
    /// these words, so this pins the grammar: it emits an `identifier`
    /// for each name, and only the first word of a `property_attribute`
    /// bills.
    #[cfg(feature = "objc")]
    #[test]
    fn objc_modifier_words_as_names_stay_operands_1579() {
        assert_keywords_are_operands_only::<ObjcParser>(
            "int out = 1;\nint copy = 2;\nint oneway = 3;\nint strong = out + copy;\n",
            "foo.m",
            &["out", "copy", "oneway", "strong"],
        );
        assert_keywords_are_operands_only::<ObjcParser>(
            "@interface C\n@property (getter=atomic, setter=weak:) id y;\n@end\n",
            "foo.m",
            &["atomic", "weak"],
        );
    }

    /// #1579: the Apple SDK macros the grammar files as storage classes
    /// and qualifiers bill nothing, as Mozcpp's `MOZ_*` macros do: each
    /// annotates a declaration, and a `.c` parses the spelling as a name.
    #[cfg(feature = "objc")]
    #[test]
    fn objc_sdk_macros_bill_nothing_1579() {
        // `int` x4, `;` x4, `()`, `void`, `{}`, `return`: the macros add
        // nothing, and the declared names and `1` are the operands
        const SOURCE: &str = "NS_INLINE int f(void) { return 1; }\nFOUNDATION_EXPORT int g;\n\
                              IBOutlet int h;\n__unused int u;\n";
        let ops = ops_of::<ObjcParser>(SOURCE, "foo.m");
        assert_eq!(ops.operators, ["()", ";", "int", "return", "void", "{}"]);
        assert_eq!(ops.operands, ["1", "f", "g", "h", "u"]);
    }

    /// #1556: Kotlin's `interface` bills as its `class` and `object`
    /// do. The modifier rows score one above the bare keyword since
    /// #1558: `enum` in `enum class` is a `class_modifier` like `data`
    /// and `sealed`, and Kotlin bills its modifiers as C# does.
    #[cfg(feature = "kotlin")]
    #[test]
    fn kotlin_declaration_keywords_are_operators_1556() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `class`, `{}`
            ("class", "class C {}\n", [2, 2]),
            // `interface`, `{}`
            ("interface", "interface I {}\n", [2, 2]),
            // `object`, `{}`
            ("object", "object O {}\n", [2, 2]),
            // `enum`, `class`, `{}`
            ("enum class", "enum class E { A }\n", [3, 3]),
            // `data`, `class`, `{}`
            ("data class", "data class D {}\n", [3, 3]),
            // `sealed`, `interface`, `{}`
            ("sealed interface", "sealed interface S {}\n", [3, 3]),
            // `interface`, `class`, `:`, `{}` twice
            (
                "implementing class",
                "interface J {}\nclass K : J {}\n",
                [4, 5],
            ),
        ];
        assert_operator_rows::<KotlinParser>("foo.kt", ROWS);
    }

    /// #1558: Kotlin bills its modifier keywords as C# bills its own,
    /// one family per row, each keyword the leaf and never
    /// its `*_modifier` wrapper. The "names" row is the control: the same
    /// words used as names are operands, and add no operator. The rows
    /// after it are names the grammar fails to parse, whose recovery keeps
    /// the keyword leaf, and their control.
    #[cfg(feature = "kotlin")]
    #[test]
    fn kotlin_modifiers_are_operators_1558() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `public`, `private`, `protected`, `internal`, `val` x4,
            // `=` x4, `class`, `{}`
            (
                "visibility",
                "class C {\n    public val a = 1\n    private val b = 1\n    \
                 protected val c = 1\n    internal val d = 1\n}\n",
                [8, 14],
            ),
            // `abstract` x2, `open`, `final`, `override`, `class`, `{}` x2,
            // `fun` x3, `()` x3, `=`
            (
                "inheritance and member",
                "abstract class A {\n    abstract fun f()\n    open fun g() {}\n    \
                 final override fun toString() = \"\"\n}\n",
                [9, 15],
            ),
            // `inner`, `value`, `annotation`, `class` x3, `()`, `val`, `:`
            (
                "class",
                "inner class I\nvalue class V(val x: Int)\nannotation class N\n",
                [7, 9],
            ),
            // `lateinit`, `companion`, `const`, `class`, `object`, `var`,
            // `val`, `:`, `=`, `{}` x2
            (
                "property and companion",
                "class C {\n    lateinit var a: String\n    companion object {\n        \
                 const val b = 1\n    }\n}\n",
                [10, 11],
            ),
            // six modifiers, `fun` x6, `()` x6, `{}` x5
            (
                "function",
                "tailrec fun a() {}\noperator fun b() {}\ninfix fun c() {}\n\
                 inline fun d() {}\nexternal fun e()\nsuspend fun f() {}\n",
                [9, 23],
            ),
            // `inline`, `noinline`, `crossinline`, `vararg`, `fun`,
            // `()` x3, `:` x3, `->` x2, `,` x2, `{}`
            (
                "parameter",
                "inline fun f(noinline a: () -> Unit, crossinline b: () -> Unit, \
                 vararg c: Int) {}\n",
                [10, 16],
            ),
            // `inline`, `reified`, `in`, `out`, `fun`, `class`, `<>` x2,
            // `,`, `()`, `{}`
            (
                "type parameter",
                "inline fun <reified T> f() {}\nclass Box<in A, out B>\n",
                [10, 11],
            ),
            // `expect`, `actual`, `fun` x2, `()` x2, `{}`
            ("platform", "expect fun f()\nactual fun g() {}\n", [5, 7]),
            // `fun`, `()`, `{}`: an `@N` use is the `annotation` node, not
            // the keyword, so it bills no `annotation` operator
            ("annotation use", "@N fun k() {}\n", [3, 3]),
            // `val` x3, `=` x3: `open`, `out` and `value` are names here
            (
                "names",
                "val open = 1\nval out = 2\nval value = 3\n",
                [2, 6],
            ),
            // The rows below are names the grammar fails to parse. Its
            // recovery keeps the keyword leaf, which must bill nothing;
            // each expected value is what the source scored before #1558.
            // `class`, `{}` x2, `var`, `=` x2, `fun`, `()`: `open = !open`
            // recovers into an `ERROR` holding `inheritance_modifier`.
            (
                "name stranded in an ERROR",
                "class Drawer {\n    var open = false\n    fun toggle() { open = !open }\n}\n",
                [6, 8],
            ),
            // `val`: `suspend` never parses as a name.
            ("suspend as a name", "val suspend = 1\n", [1, 1]),
            // `fun`, `()`, `:` x2, `=`: a modifier list followed by an
            // inserted zero-width parameter name.
            (
                "parameter named vararg",
                "fun f(vararg: Int): Int = vararg\n",
                [4, 5],
            ),
            // The same row with a comment before the inserted name: an
            // extra, so the name is still the next token. It scored
            // [5, 6], a phantom `vararg` operator.
            (
                "parameter named vararg, commented",
                "fun f(vararg /*note*/: Int): Int = vararg\n",
                [4, 5],
            ),
            // Control: a real `vararg` before a commented parameter keeps
            // its operator. `vararg`, `fun`, `()`, `:`, `{}`.
            (
                "vararg modifier, commented",
                "fun f(vararg /*note*/ x: Int) {}\n",
                [5, 5],
            ),
            // `class`, `()`, `:`
            ("class parameter named open", "class C(open: Int)\n", [3, 3]),
            // `val`, `=`, `{}`, `:`
            (
                "lambda parameter named open",
                "val l = { open: Int -> open }\n",
                [4, 4],
            ),
            // Control for the gate: a real `suspend` in a function type's
            // `type_modifiers` and in a declaration's `modifiers` bills
            // twice. `val`, `:`, `suspend` x2, `()` x2, `->`, `=`, `{}` x2,
            // `fun`.
            (
                "suspend modifiers",
                "val f: suspend () -> Unit = {}\nsuspend fun g() {}\n",
                [8, 11],
            ),
        ];
        assert_operator_rows::<KotlinParser>("foo.kt", ROWS);
    }

    /// #1558: `reified` is the one Kotlin modifier spelled as an aliased
    /// named kind. `KotlinCode::is_primitive` keys it by its text, so
    /// `bca ops` lists the word written, not the grammar's
    /// `reification_modifier`. `n1` cannot see the difference — the kind
    /// has one spelling either way — so the vocabulary is the only place
    /// this is observable.
    #[cfg(feature = "kotlin")]
    #[test]
    fn kotlin_reified_is_listed_by_its_text_1558() {
        let ops = ops_of::<KotlinParser>("fun <reified T> f() {}\n", "foo.kt");
        assert!(
            ops.operators.iter().any(|op| op == "reified"),
            "{:?}",
            ops.operators
        );
        assert!(
            !ops.operators.iter().any(|op| op == "reification_modifier"),
            "{:?}",
            ops.operators
        );
    }

    /// #1564: `typealias`, `init`, `where`, `by`, `get` and `set` bill
    /// as Kotlin's other declaration keywords do, and as C# bills its
    /// `get` / `set` / `init` / `where`. Each is the keyword leaf, never
    /// its wrapper. The rows after "accessors" are controls: the
    /// `@get:` / `@set:` use-site targets and the words used as names
    /// add no operator.
    #[cfg(feature = "kotlin")]
    #[test]
    fn kotlin_declaration_keywords_are_operators_1564() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `typealias`, `=`
            ("typealias", "typealias A = Int\n", [2, 2]),
            // `class`, `init`, `{}` x2
            ("init", "class C {\n    init {}\n}\n", [3, 4]),
            // `class`, `<>`, `where`, `:`
            ("class where", "class C<T> where T : Any\n", [4, 4]),
            // `fun`, `<>`, `()`, `where`, `:`, `{}`
            ("function where", "fun <T> f() where T : Any {}\n", [6, 6]),
            // `val`, `by`, `{}`
            ("property delegate", "val d by lazy { 1 }\n", [3, 3]),
            // `class`, `()`, `:` x2, `by`
            ("class delegation", "class D(d: I) : I by d\n", [4, 5]),
            // `var`, `:`, `=` x3, `get`, `()` x2, `set`, `{}`
            (
                "accessors",
                "var p: Int = 0\n    get() = field\n    set(v) { field = v }\n",
                [7, 10],
            ),
            // `var`, `=`, `:` x2: the use-site targets bill nothing, as
            // `@field:` does
            ("use-site targets", "@get:A @set:B var q = 0\n", [3, 4]),
            // `val`, `=`
            (
                "names",
                "val get = 1\nval set = 2\nval by = 3\nval where = 4\nval init = 5\n",
                [2, 10],
            ),
            // `fun`, `()` x4, `:`, `{}`, `.` x2
            (
                "calls",
                "fun g(x: X) {\n    x.get(by)\n    x.set(where)\n    init(x)\n}\n",
                [5, 9],
            ),
            // `fun`, `()` x2, `{}`, `val`, `=`: valid Kotlin that kotlin-ng
            // misreads, leaving the call's `get` leaf in an `ERROR`
            (
                "call after a local val",
                "fun g() {\n    val f = 6\n    get(1)\n}\n",
                [5, 6],
            ),
        ];
        assert_operator_rows::<KotlinParser>("foo.kt", ROWS);
    }

    /// #1564: the six words are listed by their own spelling, and the
    /// accessor body's `field` stays an operand like any variable.
    #[cfg(feature = "kotlin")]
    #[test]
    fn kotlin_declaration_keyword_vocabulary_1564() {
        let ops = ops_of::<KotlinParser>(
            "typealias A = Int\nclass C<T> where T : Any {\n    init {}\n    \
             val d by lazy { 1 }\n    var p: Int = 0\n        get() = field\n        \
             set(v) { field = v }\n}\n",
            "foo.kt",
        );
        for word in ["typealias", "init", "where", "by", "get", "set"] {
            assert!(
                ops.operators.iter().any(|op| op == word),
                "{word}: {:?}",
                ops.operators
            );
        }
        assert!(
            ops.operands.iter().any(|op| op == "field"),
            "{:?}",
            ops.operands
        );

        // The words used as names are operands, not merely non-operators:
        // the operator rows above cannot see a name that bills nothing.
        let names = ops_of::<KotlinParser>(
            "fun get(x: X) {\n    val set = 1\n    val by = 2\n    x.init(where(set, by))\n}\n",
            "foo.kt",
        );
        for word in ["init", "where", "by", "get", "set"] {
            assert!(
                names.operands.iter().any(|op| op == word),
                "{word}: {:?}",
                names.operands
            );
            assert!(
                !names.operators.iter().any(|op| op == word),
                "{word}: {:?}",
                names.operators
            );
        }
    }

    /// #1557 rows shared by the two C++ clones: the declaration keywords
    /// #1552 left out, one per row, plus the two disambiguator positions
    /// (`typename T::x`, `x.template f`) that bill the same leaf.
    #[cfg(any(feature = "cpp", feature = "mozcpp"))]
    const CPP_MORE_DECLARATION_KEYWORD_ROWS: &[(&str, &str, [u64; 2])] = &[
        // `namespace`, `{}`
        ("namespace", "namespace N {}\n", [2, 2]),
        // `typedef`, `int`, `;`
        ("typedef", "typedef int T;\n", [3, 3]),
        // `using`, `=`, `int`, `;`
        ("alias declaration", "using U = int;\n", [4, 4]),
        // `using`, `namespace`, `;`
        ("using directive", "using namespace std;\n", [3, 3]),
        // `template`, `<>`, `typename`, `;` and the `struct` of `S`
        (
            "template declaration",
            "template <typename T> struct S;\n",
            [5, 5],
        ),
        // `typename`, `::`, `;`
        ("dependent type", "typename T::type x;\n", [3, 3]),
        // `void`, `()` twice, `{}`, `.`, `template`, `<>`, `int`, `;`
        (
            "template disambiguator",
            "void g() { x.template f<int>(); }\n",
            [8, 9],
        ),
    ];

    /// One call per clone, as for the #1552 rows.
    #[cfg(all(feature = "cpp", feature = "mozcpp"))]
    #[test]
    fn cpp_more_declaration_keywords_are_operators_1557() {
        assert_operator_rows::<CppParser>("foo.cpp", CPP_MORE_DECLARATION_KEYWORD_ROWS);
        assert_operator_rows::<MozcppParser>("foo.cpp", CPP_MORE_DECLARATION_KEYWORD_ROWS);
    }

    /// #1557: `typedef` is a C keyword, so C and ObjC bill it as C++
    /// does — a header scores alike whichever grammar parses it.
    #[cfg(any(feature = "c", feature = "objc"))]
    const C_TYPEDEF_ROWS: &[(&str, &str, [u64; 2])] = &[
        // `typedef`, `int`, `;`
        ("typedef", "typedef int T;\n", [3, 3]),
        // `typedef`, `struct`, `{}`, `int`, `;` twice
        ("typedef struct", "typedef struct S { int a; } S;\n", [5, 6]),
    ];

    #[cfg(any(feature = "c", feature = "objc"))]
    #[test]
    fn c_family_typedef_is_an_operator_1557() {
        #[cfg(feature = "c")]
        assert_operator_rows::<CParser>("foo.c", C_TYPEDEF_ROWS);
        #[cfg(feature = "objc")]
        assert_operator_rows::<ObjcParser>("foo.m", C_TYPEDEF_ROWS);
    }

    /// #1557: the TypeScript declaration keywords #1552 left out. The
    /// "keywords as names" row pins that each word, used as a *name*,
    /// stays an operand: the grammar emits an `identifier` there. The two
    /// exported-binding rows are the one place it emits the `type` leaf
    /// for a name, which must bill nothing; the last two rows are their
    /// controls, a type-only specifier and re-export whose `type` still
    /// bills.
    #[cfg(feature = "typescript")]
    const TS_DECLARATION_KEYWORD_ROWS: &[(&str, &str, [u64; 2])] = &[
        // `type`, `=`, `number`, `;`
        ("type alias", "type T = number;\n", [4, 4]),
        // `namespace`, `{}`
        ("namespace", "namespace N {}\n", [2, 2]),
        // `module`, `{}`. Billing the `module` declaration node instead
        // of its keyword leaf would score this row the same: every
        // spelling probed (bodiless, quoted, dotted, exported, ERROR
        // recovery) emits the two together, so only the getter's
        // choice of the leaf, not this row, keeps them from both billing.
        ("module", "module M {}\n", [2, 2]),
        // `declare`, `module`, `{}`
        ("ambient module", "declare module \"m\" {}\n", [3, 3]),
        // `declare`, `global`, `{}`
        ("global augmentation", "declare global {}\n", [3, 3]),
        // `import`, `type`, `{}`, `from`, `;`
        (
            "type-only import",
            "import type { A } from \"a\";\n",
            [5, 5],
        ),
        // `let`, `=` twice, `;` twice, `.` — no keyword
        (
            "keywords as names",
            "let type = 1;\nmodule.exports = declare;\n",
            [4, 6],
        ),
        // `const`, `=`, `;` twice, `export`, `{}` — no keyword. The
        // grammar recovers an exported binding named `type` as the
        // keyword leaf, under an `ERROR` or beside one in the specifier.
        (
            "exported binding named type",
            "const type = 1;\nexport { type };\n",
            [5, 6],
        ),
        (
            "renamed exported binding named type",
            "const type = 1;\nexport { type as kind };\n",
            [5, 6],
        ),
        // `export`, `{}`, `type`, `from`, `;` — a type-only specifier
        // parses cleanly, so its keyword still bills.
        (
            "type-only export specifier",
            "export { type Foo } from \"m\";\n",
            [5, 5],
        ),
        // `export`, `type`, `*`, `from`, `;` — the pinned grammar fails
        // TS 5.0's type-only re-export into an `ERROR` that hangs from the
        // statement, not from an export clause, and its keyword bills.
        (
            "type-only re-export",
            "export type * from \"./types\";\n",
            [5, 5],
        ),
    ];

    /// #1557: a TypeScript type name is an operand, as C#, Rust and the
    /// C family bill theirs. Each row's names are `type_identifier`
    /// leaves except where noted, and before #1557 none of them billed.
    #[cfg(feature = "typescript")]
    const TS_TYPE_NAME_OPERAND_ROWS: &[(&str, &str, [u64; 2])] = &[
        // `T`
        ("alias name", "type T = number;\n", [1, 1]),
        // `I`
        ("interface name", "interface I {}\n", [1, 1]),
        // `C`
        ("class name", "class C {}\n", [1, 1]),
        // `x` (an identifier), `Foo`
        ("annotation", "let x: Foo;\n", [2, 2]),
        // `m`, `Map`, `K` twice
        ("generic", "let m: Map<K, K>;\n", [3, 4]),
        // `f`, `a` (identifiers), `U` twice
        ("type parameter", "function f<U>(a: U) {}\n", [3, 4]),
        // `q`, `ns` (identifiers), `T` — the `nested_type_identifier`
        // wrapper is unlisted, so its text is not a fourth operand
        ("qualified type", "let q: ns.T;\n", [3, 3]),
        // `C`, `I`
        ("implements", "class C implements I {}\n", [2, 2]),
    ];

    #[cfg(feature = "typescript")]
    #[test]
    fn typescript_declaration_keywords_and_type_names_1557() {
        assert_operator_rows::<TypescriptParser>("foo.ts", TS_DECLARATION_KEYWORD_ROWS);
        assert_operator_rows::<TsxParser>("foo.tsx", TS_DECLARATION_KEYWORD_ROWS);
        assert_operand_rows::<TypescriptParser>("foo.ts", TS_TYPE_NAME_OPERAND_ROWS);
        assert_operand_rows::<TsxParser>("foo.tsx", TS_TYPE_NAME_OPERAND_ROWS);
    }

    /// #1561: TypeScript's type-level operator keywords bill as their
    /// value-level siblings `as`, `typeof` and `extends` do, each as its
    /// keyword leaf under an unbilled wrapper. The `asserts a is Baz` row
    /// pins that the `asserts` node and its keyword token bill once
    /// between them, and the last row that the same words used as names
    /// are operands. Both TypeScript grammars carry the change.
    #[cfg(feature = "typescript")]
    #[test]
    fn typescript_type_operator_keywords_1561() {
        const ROWS: &[(&str, &str, [u64; 2])] = &[
            // `let`, `=`, `satisfies`, `;`
            ("satisfies", "let s = w satisfies Sat;\n", [4, 4]),
            // `type`, `=`, `keyof`, `;`
            ("keyof", "type K = keyof T;\n", [4, 4]),
            // `type`, `<>` x2, `=`, `extends`, `infer`, `?`, `:`, `;`
            (
                "infer",
                "type I<X> = X extends Array<infer E> ? E : X;\n",
                [8, 9],
            ),
            // `function`, `()`, `:` x2, `unknown`, `is`, `{}`, `return`, `;`
            (
                "type predicate",
                "function g(a: unknown): a is Baz { return true; }\n",
                [8, 9],
            ),
            // `function`, `()`, `:` x2, `unknown`, `asserts`, `is`, `{}`
            (
                "asserts predicate",
                "function h(a: unknown): asserts a is Baz {}\n",
                [7, 8],
            ),
            // `function`, `()`, `:` x2, `unknown`, `asserts`, `{}`
            (
                "bare asserts",
                "function k(a: unknown): asserts a {}\n",
                [6, 7],
            ),
            // `const`, `=` and `;` five times each: the words are names
            (
                "names",
                "const keyof = 1;\nconst infer = 2;\nconst is = 3;\nconst asserts = 4;\n\
                 const satisfies = 5;\n",
                [3, 15],
            ),
        ];
        assert_operator_rows::<TypescriptParser>("foo.ts", ROWS);
        assert_operator_rows::<TsxParser>("foo.tsx", ROWS);
    }

    /// #1563: TypeScript bills its member modifiers as C# and Kotlin bill
    /// theirs, each as the keyword leaf and never as the
    /// `accessibility_modifier` / `override_modifier` wrapper. The rows
    /// after the class members are the same leaves outside a class; the
    /// last two are the words used as names, which add no operator.
    #[cfg(feature = "typescript")]
    const TS_MEMBER_MODIFIER_ROWS: &[(&str, &str, [u64; 2])] = &[
        // `class`, `{}`, `public`, `private`, `protected`, `=` x3, `;` x3
        (
            "visibility",
            "class C {\n  public a = 1;\n  private b = 2;\n  protected c = 3;\n}\n",
            [7, 11],
        ),
        // `class`, `extends`, `{}`, `static`, `readonly`, `override`,
        // `=` x2, `;` x2
        (
            "static, readonly, override",
            "class D extends B {\n  static readonly x = 1;\n  override y = 2;\n}\n",
            [8, 10],
        ),
        // `abstract` x2, `class`, `{}`, `()`, `:`, `void`, `;`
        (
            "abstract",
            "abstract class A {\n  abstract m(): void;\n}\n",
            [7, 8],
        ),
        // `class`, `{}`, `accessor`, `=`, `;`
        ("accessor", "class E {\n  accessor q = 1;\n}\n", [5, 5]),
        // `class`, `{}` x3, `static` x2, `()`
        (
            "static block and method",
            "class F {\n  static {}\n  static m() {}\n}\n",
            [4, 7],
        ),
        // `class`, `{}` x2, `()`, `private`, `readonly`, `:` x2, `number`,
        // `,`, `public`, `string`
        (
            "parameter properties",
            "class G {\n  constructor(private readonly p: number, public o: string) {}\n}\n",
            [10, 12],
        ),
        // `type`, `=`, `readonly`, `string`, `[]`, `;`
        ("readonly type", "type R = readonly string[];\n", [6, 6]),
        // `type`, `=`, `{}`, `-`, `readonly`, `[]`, `in`, `:`, `;`
        (
            "mapped type modifier",
            "type M = { -readonly [k in K]: T };\n",
            [9, 9],
        ),
        // `type`, `=`, `abstract`, `new`, `()`, `=>`, `void`, `;`
        (
            "abstract constructor type",
            "type A = abstract new () => void;\n",
            [8, 8],
        ),
        // `let`, `const` x2, `=` x3, `;` x4, `.`, `()`, `{}`, `:` x5,
        // `,` x4 — no modifier
        (
            "names",
            "let readonly = 1;\nobj.static;\nconst a = abstract();\n\
             const o = { public: 1, private: 2, protected: 3, override: 4, accessor: 5 };\n",
            [9, 22],
        ),
        // `class`, `{}` x2, `static`, `=`, `;` x2, `()` — the modifier
        // bills once; the field named `static`, the method named
        // `readonly` and the field named `public` bill none
        (
            "member names",
            "class K {\n  static static = 1;\n  readonly() {}\n  public;\n}\n",
            [6, 8],
        ),
    ];

    #[cfg(feature = "typescript")]
    #[test]
    fn typescript_member_modifiers_are_operators_1563() {
        assert_operator_rows::<TypescriptParser>("foo.ts", TS_MEMBER_MODIFIER_ROWS);
        assert_operator_rows::<TsxParser>("foo.tsx", TS_MEMBER_MODIFIER_ROWS);
    }

    /// #1563: the issue's own fixture, by vocabulary. Every modifier
    /// reaches the operator list once, by its word and never by its
    /// wrapper's kind name, and the names stay the only operands.
    #[cfg(feature = "typescript")]
    #[test]
    fn typescript_member_modifier_vocabulary_1563() {
        const SOURCE: &str = "abstract class C {\n  declare x: number;\n  \
                              public static readonly y = 1;\n  private z = 2;\n  \
                              protected override w = 3;\n  abstract m(): void;\n  \
                              accessor q = 4;\n}\n";
        const OPERATORS: &[&str] = &[
            "()",
            ":",
            ";",
            "=",
            "abstract",
            "accessor",
            "class",
            "declare",
            "number",
            "override",
            "private",
            "protected",
            "public",
            "readonly",
            "static",
            "void",
            "{}",
        ];
        const OPERANDS: &[&str] = &["1", "2", "3", "4", "C", "m", "q", "w", "x", "y", "z"];
        for (file, ops) in [
            ("foo.ts", ops_of::<TypescriptParser>(SOURCE, "foo.ts")),
            ("foo.tsx", ops_of::<TsxParser>(SOURCE, "foo.tsx")),
        ] {
            assert_eq!(ops.operators, OPERATORS, "{file}");
            assert_eq!(ops.operands, OPERANDS, "{file}");
        }
    }

    /// #1563: the modifier words used as names are operands and never
    /// operators, in an expression, a member access, a call, an object
    /// key and a class member name. No getter edit makes this fail: the
    /// modifier arms key on the keyword kinds, and the grammar emits an
    /// identifier for each name. It pins that grammar property, so a
    /// grammar bump or a text-keyed arm that bills a name trips it.
    #[cfg(feature = "typescript")]
    #[test]
    fn typescript_modifier_words_as_names_are_operands_1563() {
        const SOURCE: &str = "let readonly = 1;\nobj.static;\nconst a = abstract();\n\
                              const o = { public: 1, private: 2, protected: 3, override: 4, \
                              accessor: 5 };\nclass K { static() {} }\n";
        const KEYWORDS: &[&str] = &[
            "readonly",
            "static",
            "abstract",
            "public",
            "private",
            "protected",
            "override",
            "accessor",
        ];
        assert_keywords_are_operands_only::<TypescriptParser>(SOURCE, "foo.ts", KEYWORDS);
        assert_keywords_are_operands_only::<TsxParser>(SOURCE, "foo.tsx", KEYWORDS);
    }

    /// #1563: JavaScript's `static` bills as TypeScript's does, in a
    /// field, a method and a `static { … }` block. `static get` with the
    /// name on the next line is one token, so it is one operator. The
    /// last row is the word used as names, which adds no operator.
    #[cfg(any(feature = "javascript", feature = "mozjs"))]
    const JS_STATIC_ROWS: &[(&str, &str, [u64; 2])] = &[
        // `class`, `{}`, `static`, `=`, `;`
        ("static field", "class K {\n  static x = 1;\n}\n", [5, 5]),
        // `class`, `{}` x3, `static` x2, `()`
        (
            "static method and block",
            "class K {\n  static m() {}\n  static {}\n}\n",
            [4, 7],
        ),
        // `class`, `{}` x2, `static`, `get`, `()`
        (
            "static getter",
            "class K {\n  static get y() {}\n}\n",
            [5, 6],
        ),
        // `class`, `{}` x2, `static get`, `()`
        (
            "static get before a newline",
            "class K {\n  static get\n  y() {}\n}\n",
            [4, 5],
        ),
        // `.`, `;` x3, `()`, `var`, `=`, `{}`, `:` — no `static`
        (
            "names",
            "obj.static;\nstatic();\nvar o = { static: 1 };\n",
            [7, 9],
        ),
    ];

    #[cfg(any(feature = "javascript", feature = "mozjs"))]
    #[test]
    fn javascript_static_is_an_operator_1563() {
        const NAMES: &str = "obj.static;\nstatic();\nvar o = { static: 1 };\n\
                             class K { static static = 1; }\n";
        #[cfg(feature = "javascript")]
        {
            assert_operator_rows::<JavascriptParser>("foo.js", JS_STATIC_ROWS);
            let ops = ops_of::<JavascriptParser>(NAMES, "foo.js");
            assert!(ops.operands.iter().any(|o| o == "static"), "{ops:?}");
            assert!(ops.operators.iter().any(|o| o == "static"), "{ops:?}");
        }
        #[cfg(feature = "mozjs")]
        {
            assert_operator_rows::<MozjsParser>("foo.js", JS_STATIC_ROWS);
            let ops = ops_of::<MozjsParser>(NAMES, "foo.js");
            assert!(ops.operands.iter().any(|o| o == "static"), "{ops:?}");
            assert!(ops.operators.iter().any(|o| o == "static"), "{ops:?}");
        }
    }

    #[cfg(feature = "bash")]
    #[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);
            },
        );
    }

    #[cfg(feature = "bash")]
    #[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);
        });
    }

    #[cfg(feature = "elixir")]
    #[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);
            },
        );
    }

    #[cfg(feature = "elixir")]
    #[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);
        });
    }

    #[cfg(feature = "elixir")]
    #[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);
            },
        );
    }

    #[cfg(feature = "elixir")]
    #[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);
        });
    }

    #[cfg(feature = "elixir")]
    #[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);
            },
        );
    }

    #[cfg(feature = "elixir")]
    #[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);
            },
        );
    }

    #[cfg(feature = "elixir")]
    #[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);
            },
        );
    }

    #[cfg(feature = "elixir")]
    #[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}"),
            );
        }
    }

    #[cfg(feature = "elixir")]
    #[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);
            },
        );
    }

    #[cfg(feature = "elixir")]
    #[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);
        });
    }

    #[cfg(feature = "bash")]
    #[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.
    #[cfg(feature = "bash")]
    #[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
        );
    }

    /// Drives one row of a Bash wrapper/leaf double-count table: a grammar
    /// wrapper whose entire contribution to `N2` was its single,
    /// already-counted child (`command_name`, #1351; `translated_string`,
    /// #1358).
    ///
    /// `expected` is the post-fix `[n1, N1, n2, N2]`. `(n2_before,
    /// N2_before)` is what the same source scored while `wrapper` was still
    /// classified as an operand. Both columns are checked against the
    /// *current* parse under the model "one spurious operand per wrapper
    /// node" — they are not measured against the old code, which no longer
    /// exists to run:
    ///
    /// - `N2_before - N2` must equal the number of `wrapper` nodes. That
    ///   identity *is* the defect: one spurious operand per wrapper.
    /// - `n2_before` must equal the post-fix operand vocabulary unioned
    ///   with the wrapper 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}`,
    ///   `$"ls"`) or because it spans several (`foo$x`, `$(which ls)`,
    ///   `{1..3}`).
    ///
    /// So a mistyped or stale column fails rather than misinforming the next
    /// reader — one did, during review of #1351 — but neither check can
    /// catch a *production* regression, because both hold whatever
    /// `get_op_type` answers. `assert_halstead_counts` below is the only
    /// assertion here that fails when the wrapper arm comes back; measured
    /// by neutralising it under the pre-fix arm, which leaves both tables
    /// green.
    #[cfg(feature = "bash")]
    #[track_caller]
    fn assert_bash_wrapper_sheds_one_operand(
        source: &str,
        expected: [u64; 4],
        (n2_before, total_before): (u64, u64),
        wrapper: Bash,
    ) {
        let name: &'static str = wrapper.clone().into();
        let kind = wrapper as u16;
        let code = source.as_bytes();
        let parser = BashParser::new(code.to_vec(), &PathBuf::from("foo.sh"), None);
        let spellings: Vec<&str> = parser
            .root()
            .preorder()
            .filter(|node| node.kind_id() == kind)
            .filter_map(|node| node.utf8_text(code))
            .collect();
        assert!(
            !spellings.is_empty(),
            "row {source:?} parses without a {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 {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 {name} spellings; got {vocabulary:?}",
        );

        assert_halstead_counts::<BashParser>(source, "foo.sh", expected, source);
    }

    /// 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 scores with the
    /// `command_name` arm restored *against today's tree*, not a historical
    /// measurement — the `$"ls" arg` row has since lost a
    /// `translated_string` wrapper to #1358 as well.
    /// `assert_bash_wrapper_sheds_one_operand` re-derives both from the
    /// current parse rather than trusting them.
    #[cfg(feature = "bash")]
    #[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. Two wrappers stacked here — `command_name`
            // over `translated_string` — so the pre-#1351 column below is
            // measured against a tree #1358 has already thinned to
            // `"ls"` + `arg`.
            ("$\"ls\" arg\n", [0, 0, 2, 2], (3, 3)),
            // 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)),
        ];
        for (source, expected, before) in cases {
            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_bash_wrapper_sheds_one_operand(source, expected, before, Bash::CommandName);
        }
    }

    /// Regression for #1358, the sibling of #1351 in the same `match`.
    /// `translated_string: $ => seq('$', $.string)` carries exactly one
    /// required `string` child and no text of its own beyond the `$`, so
    /// classifying the wrapper *and* letting the walk reach the child
    /// counted every `$"…"` twice in `N2`.
    ///
    /// The rows assert the total, `N2`. `n2` alone cannot witness this
    /// double count: the wrapper and its child spell *different* text
    /// (`$"x"` against `"x"`), so the pre-fix tree split one operand into
    /// two vocabulary entries rather than repeating one — which is why the
    /// `n2_before` column is carried too, and checked against the wrapper
    /// spellings the row actually parses to.
    #[cfg(feature = "bash")]
    #[test]
    fn bash_translated_string_wrapper_no_double_count() {
        // (source, [n1, N1, n2, N2], (n2_before, N2_before))
        let cases: [(&str, [u64; 4], (u64, u64)); 7] = [
            // Assignment RHS.
            ("a=$\"x\"\n", [1, 1, 2, 2], (3, 3)),
            // Empty translated string. The grammar makes the inner `string`
            // required, so the wrapper is never childless — the condition
            // grammar-dispatch §6 warns that deletion would regress.
            ("a=$\"\"\n", [1, 1, 2, 2], (3, 3)),
            // The one spelling the deleted arm *was* load-bearing for: the
            // inner `string` wraps an operandless brace `expansion`, so the
            // whole `$"…"` now scores zero. That is #1351's residue one
            // level down rather than a new gap — a plain `a="${#}"` already
            // scored `[1, 1, 1, 1]` — and
            // `bash_translated_string_scores_alike_in_both_positions` pins
            // that both positions agree on it.
            ("a=$\"${#}\"\n", [1, 1, 1, 1], (2, 2)),
            // `${!}` is the same residue plus a `!`, which the operator arm
            // counts; it must not turn into an operand along the way.
            ("a=$\"${!}\"\n", [2, 2, 1, 1], (2, 2)),
            // `case` subject.
            ("case $\"y\" in *) ;; esac\n", [4, 4, 1, 1], (2, 2)),
            // Command-name position, where #1351's wrapper stacks on top of
            // this one; the `_before` columns here price the
            // `translated_string` alone.
            ("$\"ls\" arg\n", [0, 0, 2, 2], (3, 3)),
            // Interpolating form. `bash_string_has_expansion` inspects the
            // node's own children, and a `translated_string` has only `$`
            // and `string`, so it never saw the `simple_expansion` one level
            // down: the wrapper reintroduced exactly the double count #180
            // removed, for the `$"…"` spelling alone. Only `$y` and `b` may
            // survive.
            ("b=$\"$y\"\n", [1, 1, 2, 2], (3, 3)),
        ];
        for (source, expected, before) in cases {
            assert_bash_wrapper_sheds_one_operand(source, expected, before, Bash::TranslatedString);
        }
    }

    /// The load-bearing half of #1358's grammar-dispatch §6 argument, which
    /// nothing else asserts. In ordinary argument position the grammar emits
    /// no `translated_string` at all — just a `$` token and a `string` — so
    /// the `string` is the node present for *every* spelling, and dropping
    /// the wrapper makes the wrapper-bearing positions agree with argument
    /// position rather than newly disagree. If a grammar bump starts
    /// emitting the wrapper here, the deletion has to be re-derived.
    #[cfg(feature = "bash")]
    #[test]
    fn bash_translated_string_scores_alike_in_both_positions() {
        // `${#}` carries the residue: it contributes no operand of its own,
        // so the second row pins that the deletion left *both* positions at
        // zero rather than only the wrapper-bearing one.
        //
        // Only the command-name half moves under the pre-fix arm; the
        // argument-position half is the reference the parity is measured
        // against, and `cmd $"…"` is asserted nowhere else. Measured — with
        // the argument assertions dropped this test still fails pre-fix,
        // with the command-name ones dropped it passes — so do not
        // "simplify" it down to the failing half.
        for (spelling, expected) in [("$\"hi\"", [0, 0, 2, 2]), ("$\"${#}\"", [0, 0, 1, 1])] {
            let as_command_name = format!("{spelling} arg\n");
            let as_argument = format!("cmd {spelling}\n");
            let parse = |source: &str| {
                BashParser::new(source.as_bytes().to_vec(), &PathBuf::from("foo.sh"), None)
            };
            assert!(
                !ast_has_kind_id(&parse(&as_argument), Bash::TranslatedString as u16),
                "argument position must still parse {spelling} as a bare `$` \
                 plus a `string`; a grammar bump that emits the wrapper here \
                 invalidates the parity this test rests on",
            );
            assert!(
                ast_has_kind_id(&parse(&as_command_name), Bash::TranslatedString as u16),
                "command-name position must still emit the wrapper, or the \
                 pair witnesses nothing",
            );
            assert_halstead_counts::<BashParser>(
                &as_command_name,
                "foo.sh",
                expected,
                &as_command_name,
            );
            assert_halstead_counts::<BashParser>(&as_argument, "foo.sh", expected, &as_argument);
        }
    }

    /// 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.
    #[cfg(feature = "bash")]
    #[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.
    #[cfg(feature = "bash")]
    #[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",
        );
    }

    #[cfg(feature = "tcl")]
    #[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);
            },
        );
    }

    #[cfg(feature = "tcl")]
    #[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);
            },
        );
    }

    #[cfg(feature = "tcl")]
    #[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"],
        );
    }

    #[cfg(feature = "tcl")]
    #[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);
            },
        );
    }

    #[cfg(feature = "tcl")]
    #[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);
            },
        );
    }

    #[cfg(feature = "tcl")]
    #[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 `TokenRole::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);
            },
        );
    }

    #[cfg(feature = "tcl")]
    #[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).
    #[cfg(feature = "tcl")]
    #[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.
    #[cfg(feature = "tcl")]
    #[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",
        );
    }

    #[cfg(feature = "tcl")]
    #[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);
            },
        );
    }

    #[cfg(feature = "tcl")]
    #[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);
            },
        );
    }

    #[cfg(feature = "tcl")]
    #[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);
        });
    }

    #[cfg(feature = "irules")]
    #[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],
    }

    #[cfg(feature = "tcl")]
    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,
        ],
    };

    #[cfg(feature = "irules")]
    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.
    #[cfg(any(feature = "irules", feature = "tcl"))]
    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.
    #[cfg(any(feature = "irules", feature = "tcl"))]
    fn check_braced_word_cases<T: crate::MetricSuite, 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.
    #[cfg(any(feature = "irules", feature = "tcl"))]
    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; #1318 tells
    /// the two roles apart by the enclosing command, but it bills them
    /// alike, so this gate is still what keeps the operand.
    ///
    /// The rows' *operator* columns moved with #1318 wherever the
    /// enclosing command takes a value, which is why the `lappend`
    /// rows here read `0` where the `proc` and `if` rows read the
    /// block's `{}`. The operand columns are untouched by it — #1318
    /// revises the brace and nothing else — so every `before` here
    /// still describes #1354 alone.
    #[cfg(any(feature = "irules", feature = "tcl"))]
    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. Its
        // operator columns are zero since #1318 — `lappend` takes a
        // value, so the brace pair is a quote and not a block.
        BracedWordCase {
            source: "lappend l {\n    # x\n}\n",
            counts: [0, 0, 3, 3],
            before: [3, 3],
            operands: &["lappend", "l", "{\n    # x\n}"],
        },
        // A `braced_word` in *value* position — the #1318 role, where
        // the same kind carries a literal list. Its interior words
        // counted before #1354 and still do; what #1354 removed is the
        // whole-block operand that was double-billing them, and what
        // #1318 removed is the `{}` operator (`lappend` takes a value,
        // so the brace pair quotes rather than opens).
        BracedWordCase {
            source: "lappend l {a b}\n",
            counts: [0, 0, 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: [0, 0, 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. Since #1318 the
        // two rows agree on all four columns rather than only on the
        // operand pair — an empty list is an empty list however it is
        // spelled.
        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.
    #[cfg(any(feature = "irules", feature = "tcl"))]
    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.
    #[cfg(feature = "tcl")]
    #[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 `big-code-analysis-ast/src/getter/tcl.rs` fails every row
    /// here — the two getters are deliberate clones and #1354 names
    /// both.
    #[cfg(feature = "irules")]
    #[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");
    }

    /// One row of the #1318 tables: a fixture and the four Halstead
    /// columns plus the operand vocabulary behind them.
    ///
    /// No `before` column, unlike [`BracedWordCase`]: #1318 is not a
    /// guard whose absence a walk can model, it is a *classification*.
    /// The pre-fix counts are recorded per row in prose instead, and
    /// each was measured against a build without the
    /// `get_op_type_with_code` overrides.
    struct BracedWordValueCase {
        source: &'static str,
        /// `[n1, N1, n2, N2]`.
        counts: [u64; 4],
        operands: &'static [&'static str],
    }

    /// Runs one #1318 table against one dialect. Both dialects run
    /// every shared row, so a fix that reached one getter and not its
    /// clone fails here.
    #[cfg(any(feature = "irules", feature = "tcl"))]
    fn check_braced_word_value_cases<T: crate::MetricSuite>(
        cases: &[BracedWordValueCase],
        file: &str,
    ) {
        for case in cases {
            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(),
            );
        }
    }

    /// The #1318 rows both dialects share. Every independent path
    /// through the role test gets a row of its own
    /// (`.claude/rules/testing.md`, "give one input to each independent
    /// path"): the value default, the script-command list, a modelled
    /// construct reached through a `word_list`, the two modelled slots
    /// that hold values, an unresolvable command name, and both
    /// nesting directions.
    ///
    /// **Every row asserts the operand columns too, and they are the
    /// half that must not move.** #1318 revises one operator and
    /// nothing else, so a mutant that suppressed a value word's
    /// *contents* — the tidier-looking rule, which collapses an
    /// `oo::class create C {…}` body into a single operand — fails
    /// here rather than passing as an improvement. #1382 keeps to the
    /// same discipline: it withdraws further `{}` operators and moves
    /// no operand column in this table.
    ///
    /// The trailing rows are #1382's. The first four are two *pairs*:
    /// a braced value slot beside the bare spelling of the same
    /// argument, which must score alike. Before #1382 they did not —
    /// the braced spelling billed one extra `{}`. The four after them
    /// carry no bare partner: each braces a value with a space in it
    /// (`proc {my proc}`, `{a b}`, `{code msg}`), which is the whole
    /// reason the braces are there. Their pre-#1382 counts are
    /// recorded per row instead.
    #[cfg(any(feature = "irules", feature = "tcl"))]
    const BRACED_WORD_VALUE_CASES: [BracedWordValueCase; 24] = [
        // The rule reaches the opener and *only* the opener. A `;`
        // separating two commands is a direct child of the
        // `braced_word` — `_terminator` is a hidden rule, so it is
        // inlined rather than wrapped — and both dialects classify
        // `SEMI` as an operator, so a revision keyed on the parent
        // kind alone swallowed it too: this row read n1 0 / N1 0 and
        // `halstead.effort` 0.0, against a line that is two commands.
        // The pairing with the `eval` row below is the point — same
        // brace, same separator, one command name apart.
        BracedWordValueCase {
            source: "lappend l {puts a ; puts b}\n",
            counts: [1, 1, 5, 6],
            operands: &["lappend", "l", "puts", "a", "b"],
        },
        BracedWordValueCase {
            source: "eval {puts a ; puts b}\n",
            counts: [2, 2, 4, 5],
            operands: &["eval", "puts", "a", "b"],
        },
        // The reported fixture. `lappend` takes a list, so `{a b}`
        // quotes rather than opens: no operator. Before #1318 this
        // read n1 1 / N1 1 — a `{}` block the line does not contain.
        BracedWordValueCase {
            source: "lappend l {a b}\n",
            counts: [0, 0, 4, 4],
            operands: &["lappend", "l", "a", "b"],
        },
        // The issue's second line, and the one showing the defect
        // needs no second argument to appear.
        BracedWordValueCase {
            source: "puts {c d}\n",
            counts: [0, 0, 3, 3],
            operands: &["puts", "c", "d"],
        },
        // The headline: one value, two commands, and until #1318 two
        // different operator counts — `set` reported none, `lappend` a
        // `{}`. `set` is an operator and `lappend` an operand because
        // the grammar models one command and not the other; that
        // asymmetry is the grammar's, not this rule's.
        BracedWordValueCase {
            source: "set x {a b}\nlappend y {a b}\n",
            counts: [1, 1, 6, 6],
            operands: &["lappend", "x", "y", "{a b}", "a", "b"],
        },
        // The script side of the same shape, and the reason `LBRACE`
        // is gated rather than deleted (grammar-dispatch §6): `eval`
        // evaluates its argument, so the block is real and keeps its
        // `{}`.
        BracedWordValueCase {
            source: "eval {puts hi}\n",
            counts: [1, 1, 3, 3],
            operands: &["eval", "puts", "hi"],
        },
        // The same command named through the global namespace, which
        // is the spelling a `namespace eval` body uses to guarantee the
        // core command over a local proc shadowing it. `::eval` *is*
        // `eval`, so the two rows must agree on the operator column;
        // before the leading `::` was stripped this one fell to the
        // value default and lost its block.
        BracedWordValueCase {
            source: "::eval {puts hi}\n",
            counts: [1, 1, 3, 3],
            operands: &["::eval", "puts", "hi"],
        },
        // The control for that strip: only the *leading* qualifier is
        // a namespace path to the core command. `ns::eval` is a
        // different proc living in `ns`, so it takes the value default
        // like any other unrecognised name — a strip of every `::`
        // segment would have promoted it to a script.
        BracedWordValueCase {
            source: "ns::eval {a b}\n",
            counts: [0, 0, 3, 3],
            operands: &["ns::eval", "a", "b"],
        },
        // The default for an unrecognised command — a user proc here,
        // but equally any package command. Nothing distinguishes it
        // from `lappend` structurally, so the row exists to pin which
        // way the coin lands. Note the words inside are still
        // operands: the rule withdraws the block, never the code.
        BracedWordValueCase {
            source: "myproc {g h}\n",
            counts: [0, 0, 3, 3],
            operands: &["myproc", "g", "h"],
        },
        // `namespace` is the one construct either grammar models that
        // still reaches its body through a `word_list`, so it is the
        // row that fails if the rule stops at the parent instead of
        // reading the grandparent. Its body must stay a script.
        BracedWordValueCase {
            source: "namespace eval ns {\n    set a 1\n}\n",
            counts: [3, 3, 4, 4],
            operands: &["eval", "ns", "a", "1"],
        },
        // A literal nested in a literal: neither brace opens a block,
        // and both words survive.
        BracedWordValueCase {
            source: "puts {a {b c}}\n",
            counts: [0, 0, 4, 4],
            operands: &["puts", "a", "b", "c"],
        },
        // A `set` inside a literal. The `set` keyword and the `[]`
        // substitution are real operators of a command the walk
        // descends into, and they stay — the rule reaches exactly the
        // one brace whose parent it can classify, never a subtree.
        // `{x [foo] v}` is a `braced_word_simple`, so #1354 bills it
        // whole and its `[foo]` interior separately, unchanged.
        BracedWordValueCase {
            source: "lappend l {set a {x [foo] v}}\n",
            counts: [2, 2, 5, 5],
            operands: &["lappend", "l", "a", "{x [foo] v}", "foo"],
        },
        // A braced word in the command *name* position. Legal Tcl —
        // `{puts} hi` invokes `puts` — and the one generic position
        // that is not an argument, so it is answered before the
        // command lookup. It must also never reach the `switch`-arm
        // rescue, which is what the braced-pattern row in the Tcl
        // table checks.
        BracedWordValueCase {
            source: "{puts} hi\n",
            counts: [0, 0, 2, 2],
            operands: &["puts", "hi"],
        },
        // A defaulted `proc` parameter — the other modelled slot that
        // holds a value, decided by the parent kind rather than by a
        // command name. `{x y}` is data the interpreter assigns, never
        // a script it runs, and it billed a fourth `{}` before #1318.
        // The three that remain are the parameter list, the parameter
        // spec and the body: those two list delimiters group a
        // declaration rather than quote a value, the line #1354 drew
        // for `Arguments`.
        BracedWordValueCase {
            source: "proc p {a {b {x y}}} { puts $a }\n",
            counts: [2, 4, 7, 7],
            operands: &["p", "a", "b", "x", "y", "puts", "$a"],
        },
        // A literal nested in a script, the direction that must keep
        // working: the `proc` body is a block (`{}` twice with the
        // parameter list) and the list it appends is not.
        BracedWordValueCase {
            source: "proc p {} { lappend l {a b} }\n",
            counts: [2, 3, 5, 5],
            operands: &["p", "lappend", "l", "a", "b"],
        },
        // A computed command name resolves to nothing, so the value
        // default decides. `$c` is the reference's own operand.
        BracedWordValueCase {
            source: "set c puts\n$c {a b}\n",
            counts: [1, 1, 5, 5],
            operands: &["c", "puts", "$c", "a", "b"],
        },
        // #1382's headline, and the pair that names the defect: `after`
        // is a script-taking command, but only from its *second*
        // argument — the first is a millisecond count. Both spellings
        // of that count are one operand and no operator; before #1382
        // the braced one billed a `{}` for a block the line does not
        // contain, reading N1 2 against the bare form's 1. The `{}`
        // both rows do report is the `{puts hi}` script, which is real.
        BracedWordValueCase {
            source: "after {100} {puts hi}\n",
            counts: [1, 1, 4, 4],
            operands: &["after", "100", "puts", "hi"],
        },
        BracedWordValueCase {
            source: "after 100 {puts hi}\n",
            counts: [1, 1, 4, 4],
            operands: &["after", "100", "puts", "hi"],
        },
        // The same pair for `time script ?count?`, whose value slot is
        // the *last* rather than the first — so a rule that hard-coded
        // "argument 0 is the value" passes the `after` pair and fails
        // this one. The script argument keeps its `{}` in both rows,
        // which is what makes the operator column a 1 and not a 0.
        //
        // The *bare* row is the half that catches it, which is not the
        // half it looks like. Measured by giving `time` `after`'s slot
        // rule: `time {puts hi} 3` reads n1 0 / N1 0, its one block
        // demoted to a value — while the braced row below is unmoved
        // at [1, 1, 4, 4], because `{puts hi}` loses the `{}` that
        // `{3}` gains and the operand texts are the same either way.
        // Do not trim the bare spelling as redundant with the braced
        // one; here it is the discriminating row of the two.
        BracedWordValueCase {
            source: "time {puts hi} {3}\n",
            counts: [1, 1, 4, 4],
            operands: &["time", "puts", "hi", "3"],
        },
        BracedWordValueCase {
            source: "time {puts hi} 3\n",
            counts: [1, 1, 4, 4],
            operands: &["time", "puts", "hi", "3"],
        },
        // A braced `proc` *name*, the one value slot the grammar names
        // as a field rather than by position. `{my proc}` is an
        // identifier containing a space, not a body, and billed a
        // fourth `{}` before #1382. The three operators left are the
        // `proc` keyword and the two braces of the parameter list and
        // the body — and note the interior words survive, `proc` being
        // an operand here and an operator one column over.
        BracedWordValueCase {
            source: "proc {my proc} {} {}\n",
            counts: [2, 3, 3, 3],
            operands: &["my", "proc", "{}"],
        },
        // The two `namespace` subcommands that take values throughout,
        // both of them Tcl 8.6 standard-library spellings. Their braced
        // argument is a pattern list and a dictionary; neither is
        // evaluated, and each billed a `{}` before #1382 — n1 2 / N1 2
        // against the 1 / 1 here. The `namespace` keyword is the
        // operator that remains, which is what keeps these two rows
        // from reading `effort` 0.0.
        BracedWordValueCase {
            source: "namespace export {a b}\n",
            counts: [1, 1, 3, 3],
            operands: &["export", "a", "b"],
        },
        BracedWordValueCase {
            source: "namespace ensemble create -map {a b}\n",
            counts: [1, 1, 5, 5],
            operands: &["ensemble", "create", "-map", "a", "b"],
        },
        // A `trap` clause written outside a `try`, which is how both
        // grammars reach the generic-command path for it. This is the
        // `ScriptSlots::LastOf` row — the pattern and the variable list
        // are values and the handler is the script — and the only one
        // whose slot is counted from the *end* of the list, so a rule
        // that read `Only(2)` from the front would need the arity to
        // pass it. Before #1382 all three braces billed: N1 3.
        BracedWordValueCase {
            source: "trap {POSIX} {code msg} {puts hi}\n",
            counts: [1, 1, 6, 6],
            operands: &["trap", "POSIX", "code", "msg", "puts", "hi"],
        },
    ];

    /// Regression for #1318. `braced_word` carries both a block and a
    /// plain literal, and the grammars spell the two identically, so
    /// #1314's kind-scoped guard reached only the value slots they
    /// special-case: `set x {a b}` reported no operator while
    /// `lappend x {a b}` reported a `{}` for a block the line does not
    /// contain. The role is recognised out-of-band, by the enclosing
    /// command's leading word (grammar-dispatch §9).
    ///
    /// The Tcl-only rows are the constructs this grammar models with
    /// no node of its own (#467, #1264) — `switch` and `for` — plus the
    /// braced `switch` *pattern* that must not be mistaken for an arm
    /// body, in both the one-arm-per-line and the one-line layouts.
    /// Their iRules counterparts are dedicated nodes and are covered by
    /// the sibling test.
    #[cfg(feature = "tcl")]
    #[test]
    fn tcl_braced_word_role_follows_the_enclosing_command_1318() {
        check_braced_word_value_cases::<TclParser>(&BRACED_WORD_VALUE_CASES, "foo.tcl");
        let tcl_only: [BracedWordValueCase; 8] = [
            // `switch` arm bodies. The grammar flattens `pat body pat
            // body` into a `command` named after the first pattern, so
            // the bodies read as arguments of a command called `a` —
            // the shape the value default would call a literal. The
            // arm list's own `switch` name is what rescues them, and
            // `puts` occurring in both bodies is what separates n2
            // from N2.
            BracedWordValueCase {
                source: "switch $v { a { puts A } b { puts B } }\n",
                counts: [1, 3, 7, 8],
                operands: &["switch", "$v", "a", "b", "puts", "A", "B"],
            },
            // …and the limit of that rescue. A braced *pattern* is the
            // arm command's `name`, not an argument, so it is a
            // literal — `switch -regexp $v { {^a.*b$} {…} }` is
            // idiomatic and its regex must not be wrapped in a block.
            // Rescuing the whole arm command would read N1 4 here.
            // The leading `-exact` / `--` options are `simple_word`
            // operands of the *`switch`* command and shift nothing:
            // the arm list is found as the sole `braced_word` argument,
            // not by index (grammar-dispatch §9).
            BracedWordValueCase {
                source: "switch -exact -- $v {\n    {a b}   { puts X }\n    default { puts Y }\n}\n",
                counts: [1, 3, 10, 11],
                operands: &[
                    "switch", "-exact", "--", "$v", "a", "b", "puts", "X", "default", "Y",
                ],
            },
            // The same arms on one line. Only the *first* pattern is
            // the arm command's name; `{^b}` is its third argument, and
            // the name test alone rescued it as a body — N1 4 here,
            // against N1 3 for the identical arms written one per line.
            // The arm list is `pattern body pattern body …` by Tcl's
            // own definition, so the arguments alternate and the
            // even-indexed ones are the bodies.
            BracedWordValueCase {
                source: "switch -regexp $v { {^a} { puts A } {^b} { puts B } }\n",
                counts: [1, 3, 8, 9],
                operands: &["switch", "-regexp", "$v", "^a", "puts", "A", "^b", "B"],
            },
            // The words that can interpose between a pattern and its
            // body take one slot each and leave the parity intact: a
            // `-` fall-through body and a `default` pattern are both
            // `simple_word`s. The two braced bodies are at indexes 2
            // and 4 of the run and both keep their `{}`.
            BracedWordValueCase {
                source: "switch $v { a - b { puts AB } default { puts D } }\n",
                counts: [1, 3, 9, 10],
                operands: &["switch", "$v", "a", "-", "b", "puts", "AB", "default", "D"],
            },
            // `for` has four braced arguments and all four are
            // evaluated, so all four keep their braces. `i` appears as
            // the `set` target and again inside `incr`, and `$i` in
            // the condition and the body, which is what separates
            // n2 = 8 from N2 = 10. `<` is an *operand* here rather
            // than a comparison operator: with no `for` rule there is
            // no `expr` slot, so the condition parses as a command and
            // its comparison never surfaces as a token — the same
            // grammar limitation #1264 recorded for ABC.
            BracedWordValueCase {
                source: "for {set i 0} {$i < 3} {incr i} { puts $i }\n",
                counts: [2, 5, 8, 10],
                operands: &["for", "i", "0", "$i", "<", "3", "incr", "puts"],
            },
            // #1382's guard rows: an arm *pattern* spelled like a
            // command whose value slots the rule now withdraws. An arm
            // list parses as commands, so the pattern becomes a real
            // command name and the arm *body* lands in one of that
            // command's value slots — where only `Getter::is_switch_arm`
            // keeps it a block. Both rows are `switch` bodies that must
            // keep their `{}`, and both were measured with the guard
            // short-circuited to `false`.
            //
            // This one is the positional half: `after`'s slot 0 is the
            // millisecond count, so without the guard `{ puts B }` reads
            // as that value and the row drops to N1 1.
            BracedWordValueCase {
                source: "switch $v { after { puts B } }\n",
                counts: [1, 2, 5, 5],
                operands: &["switch", "$v", "after", "puts", "B"],
            },
            // …and this is the field-keyed half. `proc` needs three
            // words, so the arm patterns must be written one per line
            // for the grammar to build a `procedure` at all — on one
            // line it recovers into an `ERROR` and no rule fires. Here
            // it swallows two arms, taking `{ puts A }` as its `name`
            // field and `{ puts B }` as its body; without the guard the
            // name's brace goes and the row reads N1 5. The `namespace`
            // arm is the third spelling of the same hazard and is not
            // discriminating: its subcommand slot holds the braced body
            // itself rather than a `simple_word`, so no layout resolves
            // and the construct-wide script answer stands either way.
            // `proc` and `namespace` are operators here and `after` an
            // operand, which is the three patterns' whole difference.
            BracedWordValueCase {
                source: "switch $v {\n    proc { puts A }\n    after { puts B }\n    namespace { puts C }\n}\n",
                counts: [3, 6, 7, 9],
                operands: &["switch", "$v", "after", "puts", "A", "B", "C"],
            },
            // The arity guard on `ScriptSlots::LastOf`, Tcl-only
            // because the iRules grammar models `trap_handler` and so
            // never reaches the generic-command path (#1382 review).
            // Tcl models neither `on` nor `trap`, so the whole tail
            // after the `try` body parses as *one* `trap` command with
            // five arguments — `{p} {v} {puts b} finally {puts c}`.
            // Reading "the script is the last argument" off that names
            // the `finally` body and calls `{puts b}` a value, which
            // dropped the `{}` of a block the line does contain and
            // read N1 3. All five braces are blocks here, which is the
            // answer a list the signature cannot explain has to get.
            // The `trap` row in the shared table is the same clause at
            // its documented arity, where two of the three braces
            // really are values — so a guard stuck on "always script"
            // fails there and one stuck on "always last" fails here.
            BracedWordValueCase {
                source: "try {puts a} trap {p} {v} {puts b} finally {puts c}\n",
                counts: [2, 6, 8, 10],
                operands: &["a", "b", "c", "finally", "p", "puts", "trap", "v"],
            },
        ];
        check_braced_word_value_cases::<TclParser>(&tcl_only, "foo.tcl");
    }

    /// The iRules twin of the test above. The shared table runs
    /// unchanged — the two getters are deliberate clones and #1318
    /// names both — and the dialect rows cover the handler bodies,
    /// which have no Tcl spelling.
    #[cfg(feature = "irules")]
    #[test]
    fn irules_braced_word_role_follows_the_enclosing_command_1318() {
        check_braced_word_value_cases::<IrulesParser>(&BRACED_WORD_VALUE_CASES, "foo.irule");
        let irules_only: [BracedWordValueCase; 4] = [
            // A `when` handler body is a modelled slot, so the literal
            // inside it is classified independently of the block that
            // holds it.
            BracedWordValueCase {
                source: "when HTTP_REQUEST {\n    lappend b {x y}\n}\n",
                counts: [2, 2, 5, 5],
                operands: &["HTTP_REQUEST", "lappend", "b", "x", "y"],
            },
            // This grammar models `switch` with `switch_arm` children,
            // so the arm body fills a modelled slot and never reaches
            // the command-name list the Tcl rows need.
            BracedWordValueCase {
                source: "when HTTP_REQUEST {\n    switch $v { a { pool p1 } }\n}\n",
                counts: [3, 5, 5, 5],
                operands: &["HTTP_REQUEST", "$v", "a", "pool", "p1"],
            },
            // `on` and `trap` are why the command list carries two
            // words no *Tcl* command spells. The grammar emits
            // `on_handler` / `trap_handler` only under `try` — pinned
            // by `irules_try_handler_kinds_appear_only_under_try` — so
            // a statement-level handler is a generic command, and
            // without the list entry its body would lose the `{}` that
            // the second occurrence here counts.
            BracedWordValueCase {
                source: "when RULE_INIT { set x 1 }\non error { log local0. oops }\n",
                counts: [3, 4, 8, 8],
                operands: &[
                    "RULE_INIT",
                    "x",
                    "1",
                    "on",
                    "error",
                    "log",
                    "local0.",
                    "oops",
                ],
            },
            // #1382 inside a modelled handler slot: the `when` body is
            // a block and keeps its `{}`, and the `after` delay nested
            // in it is a value and does not. Before #1382 this read
            // N1 4. The shared table's `after` pair already runs for
            // this dialect; what this row adds is that the rule reaches
            // a command nested inside a handler, where the `{}` billed
            // for the handler could otherwise mask a withdrawal.
            BracedWordValueCase {
                source: "when HTTP_REQUEST {\n    after {100} {puts hi}\n}\n",
                counts: [2, 3, 5, 5],
                operands: &["HTTP_REQUEST", "after", "100", "puts", "hi"],
            },
        ];
        check_braced_word_value_cases::<IrulesParser>(&irules_only, "foo.irule");
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
        });
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
        });
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
        }
    }

    #[cfg(feature = "php")]
    #[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}"),
            );
        }
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[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);
            },
        );
    }

    #[cfg(feature = "php")]
    #[test]
    fn php_promoted_asymmetric_visibility_scores_like_a_property() {
        // tree-sitter-php 0.24.2 parsed `private(set)` on a promoted
        // parameter as ERROR and billed `private` and `set` as operands.
        // 0.25.1 parses it as the `visibility_modifier` a property
        // declaration already gets, so it now scores the same way.
        //
        // expected: operators `class`, `{}` × 2, `public` × 2, `function`,
        // `()` × 2 (parameters, `(set)`), `private` → n1 = 6, N1 = 9.
        // Operands `A`, `__construct`, `int`, `$x` → n2 = N2 = 4.
        check_metrics::<PhpParser>(
            "<?php\nclass A {\n    public function __construct(public private(set) int $x) {}\n}\n",
            "foo.php",
            |metric| {
                assert_eq!(metric.halstead.unique_operators(), 6);
                assert_eq!(metric.halstead.total_operators(), 9);
                assert_eq!(metric.halstead.unique_operands(), 4);
                assert_eq!(metric.halstead.total_operands(), 4);
            },
        );
    }

    #[cfg(feature = "elixir")]
    #[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
                }
                "#
                );
            },
        );
    }

    #[cfg(feature = "ruby")]
    #[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);
            },
        );
    }

    #[cfg(feature = "ruby")]
    #[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 `get_op_type`'s `R::String | …` case in
        // `big-code-analysis-ast/src/getter.rs`).
        // 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);
        });
    }

    #[cfg(feature = "ruby")]
    #[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);
        });
    }

    #[cfg(feature = "ruby")]
    #[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);
        });
    }

    #[cfg(feature = "ruby")]
    #[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);
        });
    }

    #[cfg(feature = "ruby")]
    #[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);
        });
    }

    #[cfg(feature = "ruby")]
    #[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}"),
            );
        }
    }

    #[cfg(feature = "ruby")]
    #[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);
        });
    }

    #[cfg(feature = "ruby")]
    #[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);
        });
    }

    #[cfg(feature = "ruby")]
    #[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}`"
            );
        }
    }

    #[cfg(feature = "ruby")]
    #[test]
    fn ruby_subshell_delimiters_are_not_operators() {
        // Regression: issue #1360, the second delimiter family of the
        // fabrication #1312 removed for regexes. tree-sitter-ruby
        // aliases both ends of a subshell literal to `BQUOTE` — the
        // same kind id the `` def ` `` method-name marker uses — so
        // `` x = `echo hi` `` reported a `` ` `` operator with no
        // backtick method call in the source.
        //
        // expected: operator `=` → n1 = N1 = 1. Operands `x` and the
        // `` `echo hi` `` literal → n2 = N2 = 2. Before the guard the
        // two delimiters added `` ` `` → n1 = 2, N1 = 3.
        assert_halstead_counts::<RubyParser>(
            "x = `echo hi`\n",
            "foo.rb",
            [1, 1, 2, 2],
            "backtick subshell",
        );
    }

    #[cfg(feature = "ruby")]
    #[test]
    fn ruby_subshell_delimiter_choice_is_invariant() {
        // Companion to the test above (#1360): `%x`-form subshells are
        // the same literal spelled differently, so every delimiter
        // choice must produce identical counts. tree-sitter-ruby
        // aliases all of them to `BQUOTE` — verified with `bca dump`,
        // which shows `` ` ``/`` ` ``, `%x{`/`}`, `%x(`/`)`, `%x[`/`]`,
        // `%x<`/`>`, `%x|`/`|` and `%x!`/`!` every one emitting kind
        // `BQUOTE` — so each row here genuinely exercises the guard
        // rather than reaching a different, already-clean path. Note
        // the `%x!…!` and `%x|…|` closers in particular: they are
        // `BQUOTE`, not the `BANG` / `PIPE` operators they look like.
        //
        // The empty row records that `` `` `` parses to a `Subshell`
        // holding nothing but its two delimiters, and still bills that
        // wrapper as one operand once both are suppressed. It is
        // documentation, not a discriminator: the guard deletes nothing
        // from the operand arm, so grammar-dispatch §6's
        // childless-variant-regresses-to-zero hazard cannot arise here
        // and this row moves with the first row under every mutant.
        //
        // expected per variant: operator `=` → n1 = N1 = 1; operands
        // `x` and the literal → n2 = N2 = 2.
        for literal in [
            "`echo`", "%x{echo}", "%x(echo)", "%x[echo]", "%x<echo>", "%x|echo|", "%x!echo!", "``",
        ] {
            assert_halstead_counts::<RubyParser>(
                &format!("x = {literal}\n"),
                "foo.rb",
                [1, 1, 2, 2],
                &format!("subshell literal {literal}"),
            );
        }
    }

    #[cfg(feature = "ruby")]
    #[test]
    fn ruby_backtick_method_name_survives_the_subshell_guard() {
        // Control for #1360, and the reason the kind is gated rather
        // than dropped from the operator arm (grammar-dispatch §6):
        // `` ` `` is a legal Ruby method name. `bca dump` at the pinned
        // grammar shows `` def `(cmd) `` emitting a `BQUOTE` wrapped in
        // a named `operator` node, so its parent is `Operator` and the
        // parent-scoped guard leaves it alone. Deleting `BQUOTE` from
        // the operator arm would have scored this construct zero.
        //
        // expected: operators `def`, `` ` ``, `(` and `end` →
        // n1 = N1 = 4 (only the `(` opener counts after #695).
        // Operand `cmd` twice, parameter and use → n2 = 1, N2 = 2.
        assert_halstead_counts::<RubyParser>(
            "def `(cmd)\n  cmd\nend\n",
            "foo.rb",
            [4, 4, 1, 2],
            "backtick method name",
        );
    }

    #[cfg(feature = "ruby")]
    #[test]
    fn ruby_subshell_guard_is_parent_scoped_not_ancestor_scoped() {
        // The one input that separates the correct parent-scoped guard
        // from the ancestor-scoped mutant of it (#1360, mirroring
        // #1312's regex case): backtick *methods* used inside a
        // subshell's `#{…}` interpolation. Their `BQUOTE` has the named
        // `operator` node as its parent but the `Subshell` as a further
        // ancestor, so an ancestor scan would swallow both. Every other
        // fixture in this file passes under either spelling. Two
        // markers — a definition and a call — so the mutant moves both
        // n1 (7 → 6) and N1 (10 → 8), per the #1294 count-only-anchor
        // lesson.
        //
        // expected: operators `=` (1), `def` (1), `` ` `` (2), `(` (2),
        // `;` (2), `end` (1), `.` (1) → n1 = 7, N1 = 10. Operands `n`,
        // `c` × 2, `s`, `"x"` → n2 = 4, N2 = 5; the wrapping `Subshell`
        // is skipped because it carries `Interpolation` children (the
        // #180 double-count guard), and its `a` / `b` string content is
        // classified by no arm.
        check_metrics::<RubyParser>(
            "n = `a#{def `(c); c; end}b#{s.`(\"x\")}`\n",
            "foo.rb",
            |metric| {
                assert_eq!(metric.halstead.unique_operators(), 7);
                assert_eq!(metric.halstead.total_operators(), 10);
                assert_eq!(metric.halstead.unique_operands(), 4);
                assert_eq!(metric.halstead.total_operands(), 5);
            },
        );
    }

    #[cfg(feature = "ruby")]
    #[test]
    fn ruby_subshell_start_alias_never_reaches_kind_id() {
        // Drift marker for #1360's guard, the `BQUOTE2` sibling of
        // `ruby_regex_start_alias_never_reaches_kind_id`. `BQUOTE2`
        // sits in the enum's literal-start alias block beside `DQUOTE`,
        // `COLONDQUOTE` and `SLASH2`, and the runtime
        // `public_symbol_map` collapses it to `BQUOTE` before
        // `kind_id()`, exactly like `LPAREN2` in #768.
        //
        // `BQUOTE2` is therefore in no dispatch arm at all — not the
        // guard and not the operator arm — which is the asymmetry with
        // `SLASH2`, a kind #1312 had to *move* out of the arithmetic
        // arm. Adding it to the guard would change nothing, since the
        // wildcard already answers `Unknown` for it. What that leaves
        // unguarded is the reverse direction: a bump that started
        // emitting `BQUOTE2` would drop a subshell opener silently
        // (already the wanted answer) but would also stop counting a
        // `` def ` `` marker spelled that way. This pins the
        // reachability so such a bump fails here rather than moving a
        // metric unobserved.
        let path = PathBuf::from("foo.rb");
        for source in ["x = `echo`\n", "x = %x{echo}\n"] {
            let parser = RubyParser::new(source.as_bytes().to_vec(), &path, None);
            assert!(
                !ast_has_kind_id(&parser, Ruby::BQUOTE2 as u16),
                "Ruby::BQUOTE2 must stay collapsed to Ruby::BQUOTE 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::BQUOTE as u16),
                "Ruby::BQUOTE must be the delimiter kind for `{source}`"
            );
        }
    }

    #[cfg(feature = "ruby")]
    #[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}"),
            );
        }
    }

    #[cfg(feature = "ruby")]
    #[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);
        });
    }

    #[cfg(feature = "ruby")]
    #[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);
        }
    }

    #[cfg(feature = "ruby")]
    #[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);
        }
    }

    #[cfg(feature = "ruby")]
    #[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);
        }
    }

    #[cfg(feature = "ruby")]
    #[test]
    fn ruby_suffixed_numeric_literals_bill_one_operand_1359() {
        // #1359, the wrapper/leaf double count one arm below #1353's.
        // `rational` and `complex` wrap the numeral they suffix, and
        // `get_op_type` billed every level: `a = 1r` scored n2 3 / N2 3
        // for two operands, and `c = 3ri` — a `complex` over a
        // `rational` over an `integer` — scored n2 3 / N2 4 for the
        // same two.
        //
        // The rows are ordered by nesting depth on purpose, because the
        // half-fix is a plausible one to write. Guard the two leaf
        // kinds and not the intermediate `rational` — `R::Integer |
        // R::Float` where the arm says `R::Integer | R::Float |
        // R::Rational` — and the `1r` and `2i` rows still pass; the
        // `ri` rows, whose middle `rational` must be suppressed as well
        // as the leaf beneath it, are the two that fail (measured:
        // `c = 3ri` reports n2 3 / N2 3).
        //
        // The trailing rows are the ones that must *not* move. `g = 4`
        // has no wrapper at all and pins that the guard is scoped to
        // the numerals inside one (grammar-dispatch §6 — nothing
        // regresses to zero). `"#{4r}"` and `-3r` put the wrapper
        // somewhere other than an assignment right-hand side, under a
        // node that guards its own children (`Interpolation`, whose
        // enclosing `String` is suppressed by the arm above) and under
        // one that does not (`unary`); both must still bill the
        // wrapper once. They do *not* pin parent-versus-ancestor
        // scoping and nothing can: `complex` and `rational` admit
        // numeral children only, so an ancestor-scoped guard would
        // classify every Ruby input identically. And `1r + 1r` is the
        // row where N2 and n2 come apart, so the `N2` column is
        // load-bearing on its own rather than tracking `n2`.
        //
        // The kind assertions are the grammar-dispatch §1 / §2 drift
        // marker: a bump that renumbered `complex` or `rational`, or
        // stopped nesting them, would leave the counts passing while
        // measuring a construct the guard no longer names. `IntOrFloat`
        // is the §2 half — the hidden `_int_or_float` the two wrappers
        // are written over, which a bump could promote into the
        // numeral's parent and silently stop the guard firing. Not
        // every kind a row mentions is one the guard names
        // (`Interpolation` is context), and `unary` and `binary` are
        // deliberately absent: they carry five and three aliased
        // variants here, so naming one would pin the alias rather than
        // the shape.
        for (source, kinds, counts, operands) in [
            (
                "a = 1r\n",
                &[Ruby::Rational as u16, Ruby::Integer as u16][..],
                [1, 1, 2, 2],
                vec!["a", "1r"],
            ),
            (
                "b = 2i\n",
                &[Ruby::Complex as u16, Ruby::Integer as u16][..],
                [1, 1, 2, 2],
                vec!["b", "2i"],
            ),
            (
                "c = 3ri\n",
                &[
                    Ruby::Complex as u16,
                    Ruby::Rational as u16,
                    Ruby::Integer as u16,
                ][..],
                [1, 1, 2, 2],
                vec!["c", "3ri"],
            ),
            (
                "d = 1.5r\n",
                &[Ruby::Rational as u16, Ruby::Float as u16][..],
                [1, 1, 2, 2],
                vec!["d", "1.5r"],
            ),
            (
                "e = 2.5i\n",
                &[Ruby::Complex as u16, Ruby::Float as u16][..],
                [1, 1, 2, 2],
                vec!["e", "2.5i"],
            ),
            (
                "f = 1.5ri\n",
                &[
                    Ruby::Complex as u16,
                    Ruby::Rational as u16,
                    Ruby::Float as u16,
                ][..],
                [1, 1, 2, 2],
                vec!["f", "1.5ri"],
            ),
            (
                "g = 4\n",
                &[Ruby::Integer as u16][..],
                [1, 1, 2, 2],
                vec!["g", "4"],
            ),
            (
                "h = \"#{4r}\"\n",
                &[Ruby::Interpolation as u16, Ruby::Rational as u16][..],
                [1, 1, 2, 2],
                vec!["h", "4r"],
            ),
            (
                "i = -3r\n",
                &[Ruby::Rational as u16, Ruby::Integer as u16][..],
                [2, 2, 2, 2],
                vec!["i", "3r"],
            ),
            (
                "j = 1r + 1r\n",
                &[Ruby::Rational as u16, Ruby::Integer as u16][..],
                [2, 2, 2, 3],
                vec!["j", "1r"],
            ),
        ] {
            let parser =
                RubyParser::new(source.as_bytes().to_vec(), &PathBuf::from("foo.rb"), None);
            for kind in kinds {
                assert!(
                    ast_has_kind_id(&parser, *kind),
                    "the kind this row measures is unreachable for `{source}`"
                );
            }
            assert!(
                !ast_has_kind_id(&parser, Ruby::IntOrFloat as u16),
                "`_int_or_float` is hidden; a grammar that emits it would \
                 sit between the wrapper and the numeral for `{source}`"
            );

            assert_halstead_counts::<RubyParser>(source, "foo.rb", counts, source);
            assert_ops_operands::<RubyParser>(source, "foo.rb", operands.len(), operands);
        }
    }

    #[cfg(feature = "ruby")]
    #[test]
    fn ruby_numeric_suffixes_stay_distinct_operands_1359() {
        // The reason #1359 keeps the *wrapper* and gates the leaf
        // rather than dropping the two wrapper kinds from the arm, as
        // #1351 and #1358 did for their Bash wrappers. `1`, `1r`, `1i`
        // and `1ri` are four distinct Ruby constants — Integer,
        // Rational, Complex and Complex-of-Rational — and only the
        // wrapper's span carries the suffix that says which.
        //
        // This is the assertion to watch fail against the leaf-keeping
        // alternative: billing the `integer` would file all four under
        // the operand text `1`, reporting n2 5 / N2 8 where the source
        // plainly has eight distinct operands. The count alone does not
        // say that, so the vocabulary is pinned by text.
        //
        // expected: operator `=` → n1 1, N1 4; four targets and four
        // constants, none repeated → n2 = N2 = 8.
        let source = "w = 1\nx = 1r\ny = 1i\nz = 1ri\n";
        assert_halstead_counts::<RubyParser>(source, "foo.rb", [1, 4, 8, 8], source);
        assert_ops_operands::<RubyParser>(
            source,
            "foo.rb",
            8,
            vec!["w", "x", "y", "z", "1", "1r", "1i", "1ri"],
        );
    }

    /// 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.
    #[cfg(feature = "irules")]
    #[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).
    #[cfg(feature = "irules")]
    #[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.
    #[cfg(feature = "irules")]
    #[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.
    #[cfg(feature = "irules")]
    #[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).
    #[cfg(feature = "irules")]
    #[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"],
        );
    }

    #[cfg(feature = "irules")]
    #[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
        );
    }

    #[cfg(feature = "irules")]
    #[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.
    #[cfg(feature = "cpp")]
    #[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.
    #[cfg(feature = "objc")]
    #[test]
    fn objc_nsstring_literal_is_one_operand() {
        // expected: [n1, N1, n2, N2], each operator count including the
        // wrapper's `@implementation` (#1552). Before the guard the first
        // two rows read [9, 9, 5, 5] and [9, 10, 6, 6] — one `@` operator
        // per literal; the boxing control is unchanged.
        let cases = [
            ("NSString *s = @\"str\";", [8, 8, 5, 5]),
            ("NSString *t = @\"x\" @\"y\";", [8, 8, 6, 6]),
            ("NSNumber *n = @42;", [9, 9, 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.
    #[cfg(feature = "objc")]
    #[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 = 15 unique operators:
            //   `&&`, `()`, `+`, `-`, `:`, `;`, `<`, `=`, `>`,
            //   `[]` (message send), `if`, `int`, `return`, `{}`,
            //   `@implementation` (#1552).
            //   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(), 15);
            assert_eq!(metric.halstead.unique_operands(), 10);
            insta::assert_json_snapshot!(metric.halstead, @r#"
            {
              "unique_operators": 15,
              "total_operators": 23,
              "unique_operands": 10,
              "total_operands": 14,
              "length": 37,
              "estimated_program_length": 91.82263988300141,
              "purity_ratio": 2.481692969810849,
              "vocabulary": 25,
              "volume": 171.8226790216648,
              "difficulty": 10.5,
              "level": 0.09523809523809523,
              "effort": 1804.1381297274804,
              "time": 100.22989609597113,
              "bugs": 0.049399808887691035
            }
            "#);
        });
        // 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.
    #[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))]
    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.
    #[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))]
    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.
    #[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))]
    #[track_caller]
    fn assert_char_literal_operands<T: crate::MetricSuite>(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.
    #[cfg(all(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))]
    #[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).
    #[cfg(feature = "objc")]
    #[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.
    #[cfg(all(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))]
    #[test]
    fn c_family_char_literal_internals_stay_unclassified() {
        #[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))]
        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)
                            ),
                            TokenRole::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");
    }

    /// #1361 fixture pairing the two spellings of a member access whose
    /// receiver is the enclosing object: `this->x` and `p->x`.
    ///
    /// The pairing is the point, not decoration. `field_expression` is
    /// `<receiver> -> <field>`, so the two lines are the same AST shape
    /// and must bill the same *kinds* of thing — a receiver operand, the
    /// `->` operator, a field operand. Before the fix `this` was in
    /// neither arm, so the two shapes scored differently and `m1` billed
    /// a `->` with only one operand around it.
    ///
    /// Plain C++ that the mozcpp fork parses identically, so one source
    /// proves the same thing about both clones.
    #[cfg(any(feature = "cpp", feature = "mozcpp"))]
    const CPP_THIS_RECEIVER_PARITY: &str = "struct S {
         int x;
         int m1() { return this->x; }
         int m2(S* p) { return p->x; }
     };";

    /// #1361 fixture holding one representative position per kind of
    /// container the pinned `tree-sitter-cpp` can put a `this` in: the
    /// `->` receiver, a dereference inside a parenthesised expression, a
    /// bare return value, both lambda-capture spellings (`[this]` and
    /// `[=, this]`), a `decltype` trailing return type, a constructor
    /// body following a member-initialiser list, and a call argument.
    ///
    /// Representative, not exhaustive — `delete this;`, `throw this;`,
    /// `[&, this]`, a default member initialiser and a `this->template
    /// f<int>()` all parse cleanly too. Every one of them is the same
    /// childless `{this:215}` leaf under an unclassified wrapper, which
    /// is precisely why the arm needs no guard and why enumerating them
    /// would add rows without adding a distinct path (grammar-dispatch
    /// section 11).
    ///
    /// C++23's explicit object parameter (`int g(this S&& self)`) is
    /// deliberately absent: the pinned grammar cannot parse it and emits
    /// `type_identifier "this"` plus an `ERROR`, which
    /// `for_each_node_with_chain` rejects outright. That spelling is
    /// already an operand through `TypeIdentifier`, so the construct is
    /// unaffected by this arm either way.
    #[cfg(any(feature = "cpp", feature = "mozcpp"))]
    const CPP_THIS_POSITIONS: &str = "struct S {
         int x;
         void g(S*);
         int arrow() { return this->x; }
         int deref() { return (*this).x; }
         S* ret() { return this; }
         void cap() { auto l = [this]() { return x; }; }
         void cap2() { auto l = [=, this]() { return x; }; }
         auto trail() -> decltype(this->x) { return x; }
         S(int v) : x(v) { this->x = v; }
         void call() { g(this); }
     };";

    /// Asserts `CPP_THIS_RECEIVER_PARITY` 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* the new operand is billed
    /// under, which the counts alone cannot see: billing the enclosing
    /// `field_expression` instead of the `this` leaf would hold `n2` at
    /// 6 while the vocabulary silently became `this->x`.
    #[cfg(any(feature = "cpp", feature = "mozcpp"))]
    #[track_caller]
    fn assert_this_receiver_parity<T: crate::MetricSuite>(file: &str, label: &str) {
        // Operators, keyed by kind_id except the text-keyed primitives:
        // `{` x3 (class body, `m1`, `m2`), `int` x3, `;` x4 (the field,
        // the two returns, the struct terminator), `(` x2, `return` x2,
        // `->` x2, the one `*` of `S* p`, and `struct` (#1552). #695
        // dropped every closing delimiter. n1 = 8, N1 = 18.
        //
        // Operands, keyed by source text: `S` x2 (the name and the
        // parameter type), `x` x3, `m1`, `m2`, `p` x2, and — the fix —
        // `this` x1. n2 = 6, N2 = 10. Before #1361: n2 5, N2 9, with
        // every operator count identical, which is the whole claim.
        let counts = format!("{label}: this->x and p->x are the same shape");
        assert_halstead_counts::<T>(CPP_THIS_RECEIVER_PARITY, file, [8, 18, 6, 10], &counts);
        assert_ops_operands::<T>(
            CPP_THIS_RECEIVER_PARITY,
            file,
            6,
            vec!["S", "x", "m1", "m2", "p", "this"],
        );
    }

    /// Every C++ overloaded-operator name the grammar spells as a token
    /// of its own, plus the `co_await` expression and the conversion
    /// operator's `operator` keyword (#1296).
    #[cfg(any(feature = "cpp", feature = "mozcpp"))]
    const CPP_OPERATOR_NAMES: &str =
        "struct S { int operator[](int); void operator()(); bool operator co_await(); };
long operator\"\"_x(unsigned long long);
S::operator bool() const;
S s; int a = s[1]; auto t = co_await s;
";

    /// Asserts `CPP_OPERATOR_NAMES` bills each operator name, keyword and
    /// `co_await` as an operator under parser `T`.
    #[cfg(any(feature = "cpp", feature = "mozcpp"))]
    #[track_caller]
    fn assert_cpp_operator_names<T: crate::MetricSuite>(label: &str) {
        // Operators (n1 = 18, N1 = 41): `operator` 5 (four
        // `operator_name`s and the `operator_cast`); the names `[]` 1,
        // `()` 1, `""` 1; `co_await` 2 (the name and the expression);
        // the `(` of a parameter list 5; `;` 9; `int` 3; `long` 3;
        // `bool` 2; `=` 2; `{` 1; `void` 1; `unsigned` 1; `::` 1; the
        // subscript `[` 1; `struct` 1 (#1552); the trailing `const` 1
        // (#1578). `auto` is in no arm.
        //
        // Operands (n2 = 6, N2 = 9): `s` 3, `S` 2 (the qualifier in
        // `S::operator bool` is a namespace identifier, which #1096
        // leaves unbilled), `_x`, `a`, `1`, `t`.
        //
        // Before #1296: (12, 30, 6, 9) with `struct`, the five operator
        // kinds billed nowhere.
        assert_halstead_counts::<T>(CPP_OPERATOR_NAMES, "ops.cpp", [18, 41, 6, 9], label);

        // `operator[]` / `operator()` are kinds of their own, so they sit
        // beside the subscript `[` and the parameter-list `(` as two more
        // operators, each rendered as the operator it names so that every
        // listed entry is distinct.
        let ops = ops_of::<T>(CPP_OPERATOR_NAMES, "ops.cpp");
        for (name, entries) in [
            ("operator", 1),
            ("co_await", 1),
            ("\"\"", 1),
            ("operator[]", 1),
            ("operator()", 1),
            ("[]", 1),
            ("()", 1),
        ] {
            assert_eq!(
                ops.operators.iter().filter(|o| *o == name).count(),
                entries,
                "{label}: `{name}` must be {entries} operator entry; operators were {:?}",
                ops.operators
            );
            assert!(
                !ops.operands.iter().any(|o| o == name),
                "{label}: `{name}` must not be an operand; operands were {:?}",
                ops.operands
            );
        }
    }

    /// Regression for #1296: a C++ operator name is a Halstead operator,
    /// as `operator +`'s `+` already was. One row per clone, so reverting
    /// either arm fails its own row (grammar-dispatch section 11); Mozcpp
    /// owns no file extension, so this row is its only coverage.
    #[cfg(all(feature = "cpp", feature = "mozcpp"))]
    #[test]
    fn cpp_operator_names_are_operators() {
        assert_cpp_operator_names::<CppParser>("cpp");
        assert_cpp_operator_names::<MozcppParser>("mozcpp");
    }

    /// Asserts a coroutine's `co_yield` and `co_return` keywords bill as
    /// operators under parser `T`, as `return` does (#1547).
    #[cfg(any(feature = "cpp", feature = "mozcpp"))]
    #[track_caller]
    fn assert_cpp_coroutine_keywords<T: crate::MetricSuite>(label: &str) {
        let source = "T gen() { co_yield 1; co_yield 2; co_return 3; }";
        // Operators (n1 = 5, N1 = 8): `()` 1, `{}` 1, `co_yield` 2,
        // `co_return` 1, `;` 3. Operands (n2 = 5, N2 = 5): `T`, `gen`,
        // `1`, `2`, `3`. Before #1547: (3, 5, 5, 5), both keywords
        // billed nowhere.
        assert_halstead_counts::<T>(source, "foo.cpp", [5, 8, 5, 5], label);
        let ops = ops_of::<T>(source, "foo.cpp");
        for keyword in ["co_yield", "co_return"] {
            assert!(
                ops.operators.iter().any(|o| o == keyword),
                "{label}: `{keyword}` must be an operator; operators were {:?}",
                ops.operators
            );
        }
    }

    /// Regression for #1546: a zero-width node is billed in neither
    /// Halstead half. Error recovery inserts one for a token the source
    /// lacks, usually flagged MISSING, and every getter that classifies
    /// the kind billed it — an identifier as the empty-string operand.
    /// One fixture per language, each a parse on which recovery inserts
    /// an operand-classified zero-width node; before the fix every row
    /// billed `""`. C#'s and Elixir's are not flagged MISSING, which is
    /// why the guard keys on width: an `is_missing()` guard leaves those
    /// two rows billing `""`. Each row names its zero-width operand's
    /// kind and flag, so the two unflagged rows keep discriminating. The
    /// rows pin no counts, since the recovery trees are the grammars' to
    /// change (grammar-dispatch §6); the operator half, an inserted `;` or
    /// `)`, is anchored by `cpp_missing_tokens_in_valid_code_are_not_billed`.
    #[cfg(any(
        feature = "bash",
        feature = "c",
        feature = "cpp",
        feature = "csharp",
        feature = "elixir",
        feature = "go",
        feature = "groovy",
        feature = "irules",
        feature = "java",
        feature = "javascript",
        feature = "kotlin",
        feature = "lua",
        feature = "mozcpp",
        feature = "mozjs",
        feature = "objc",
        feature = "perl",
        feature = "php",
        feature = "python",
        feature = "ruby",
        feature = "rust",
        feature = "tcl",
        feature = "typescript",
    ))]
    #[test]
    fn zero_width_nodes_bill_neither_halstead_half() {
        // `(language, file, source, kind, is_missing)`: the last two name
        // the zero-width operand each fixture's recovery inserts, so a
        // grammar bump that recovers some other way fails the row rather
        // than passing it on an unrelated zero-width node.
        let cases: &[(LANG, &str, &str, &str, bool)] = &[
            #[cfg(feature = "bash")]
            (LANG::Bash, "foo.sh", "echo a $( )\n", "word", true),
            #[cfg(feature = "c")]
            (
                LANG::C,
                "foo.c",
                "int x; void () { x = 1; }\n",
                "identifier",
                true,
            ),
            #[cfg(feature = "cpp")]
            (
                LANG::Cpp,
                "foo.cpp",
                "void f(S *s) {\n  s->~D<F>();\n}\n",
                "identifier",
                true,
            ),
            #[cfg(feature = "csharp")]
            (
                LANG::Csharp,
                "foo.cs",
                "class A { int = 1; }\n",
                "identifier",
                false,
            ),
            #[cfg(feature = "elixir")]
            (LANG::Elixir, "foo.ex", "x = a.\n", "identifier", false),
            #[cfg(feature = "go")]
            (
                LANG::Go,
                "foo.go",
                "package m\nfunc f() { a.() }\n",
                "type_identifier",
                true,
            ),
            #[cfg(feature = "groovy")]
            (
                LANG::Groovy,
                "foo.groovy",
                "def x = a.\n",
                "identifier",
                true,
            ),
            #[cfg(feature = "irules")]
            (
                LANG::Irules,
                "foo.irule",
                "when HTTP_REQUEST { set x [expr {1 + }] }\n",
                "number",
                true,
            ),
            #[cfg(feature = "java")]
            (
                LANG::Java,
                "Foo.java",
                "class A { int = 1; }\n",
                "identifier",
                true,
            ),
            #[cfg(feature = "javascript")]
            (
                LANG::Javascript,
                "foo.js",
                "let {a: } = b;\n",
                "identifier",
                true,
            ),
            #[cfg(feature = "kotlin")]
            (
                LANG::Kotlin,
                "foo.kt",
                "fun f(: Int) {}\n",
                "identifier",
                true,
            ),
            #[cfg(feature = "lua")]
            (LANG::Lua, "foo.lua", "x = a.\n", "identifier", true),
            #[cfg(feature = "mozcpp")]
            (
                LANG::Mozcpp,
                "foo.cpp",
                "void f(S *s) {\n  s->~D<F>();\n}\n",
                "identifier",
                true,
            ),
            #[cfg(feature = "mozjs")]
            (
                LANG::Mozjs,
                "foo.jsm",
                "let {a: } = b;\n",
                "identifier",
                true,
            ),
            #[cfg(feature = "objc")]
            (
                LANG::Objc,
                "foo.m",
                "@interface A\n- (void)f:;\n@end\n",
                "identifier",
                true,
            ),
            #[cfg(feature = "perl")]
            (LANG::Perl, "foo.pl", "sub { $x = ; }\n", "identifier", true),
            #[cfg(feature = "php")]
            (LANG::Php, "foo.php", "<?php $x = $a->;\n", "name", true),
            #[cfg(feature = "python")]
            (
                LANG::Python,
                "foo.py",
                "for in x:\n  pass\n",
                "identifier",
                true,
            ),
            #[cfg(feature = "ruby")]
            (LANG::Ruby, "foo.rb", "x = a.\n", "identifier", true),
            #[cfg(feature = "rust")]
            (
                LANG::Rust,
                "foo.rs",
                "fn f() { let x = a.; }\n",
                "field_identifier",
                true,
            ),
            #[cfg(feature = "tcl")]
            (LANG::Tcl, "foo.tcl", "puts [expr {1 + }]\n", "number", true),
            #[cfg(feature = "typescript")]
            (
                LANG::Typescript,
                "foo.ts",
                "let {a: } = b;\n",
                "identifier",
                true,
            ),
            #[cfg(feature = "typescript")]
            (LANG::Tsx, "foo.tsx", "let {a: } = b;\n", "identifier", true),
        ];
        crate::test_support::assert_fixtures_present(cases);

        let mut billed = Vec::new();
        for (lang, file, source, kind, missing) in cases {
            let ast = crate::test_support::parse_named(*lang, file, source);
            assert!(
                ast.root_node().preorder().any(|node| {
                    node.start_byte() == node.end_byte()
                        && node.kind() == *kind
                        && node.is_missing() == *missing
                }),
                "{lang:?}: `{source}` no longer recovers with a zero-width `{kind}` \
                 (is_missing: {missing}); find another fixture"
            );
            let ops = ast.ops().expect("ops walk must yield a top-level Ops");
            assert!(
                !ops.operands.is_empty(),
                "{lang:?}: `{source}` billed no operand at all"
            );
            billed.extend(ops.operands.iter().any(String::is_empty).then_some(*lang));
        }
        assert!(
            billed.is_empty(),
            "a zero-width node was billed as the empty operand in {billed:?}"
        );
    }

    /// Asserts two valid C++ programs that tree-sitter-cpp 0.23.4 can only
    /// parse by inserting MISSING tokens bill only the tokens written
    /// (#1546), under parser `T`. Both come from the DeepSpeech corpus.
    #[cfg(any(feature = "cpp", feature = "mozcpp"))]
    #[track_caller]
    fn assert_cpp_missing_tokens_unbilled<T: crate::MetricSuite>(label: &str) {
        // `openfst/dfs-visit.h:75`: an explicit destructor call through a
        // template name. Recovery reads `s->~D<F` as comparisons and
        // inserts a MISSING identifier inside the trailing `()`.
        // Operators (n1 = 9, N1 = 10): `void`, `()` 2, `*`, `{}`, `->`,
        // `~`, `<`, `>`, `;`. Operands (n2 = 5, N2 = 6): `f`, `S`, `s` 2,
        // `D`, `F`. Before #1546: (9, 10, 6, 7), the extra being `""`.
        let destructor = "void f(S *s) {\n  s->~D<F>();\n}\n";
        assert_halstead_counts::<T>(destructor, "foo.cpp", [9, 10, 5, 6], label);
        let ops = ops_of::<T>(destructor, "foo.cpp");
        assert_eq!(ops.operands, ["D", "F", "S", "f", "s"], "{label}");

        // `kenlm/lm/search_trie.cc:286`: a `typename` functional cast
        // used as a statement. Recovery inserts a MISSING `)` after
        // `quant_` and a MISSING `;` after `order`. Operators (n1 = 9,
        // N1 = 11): `void`, `()` 3, `{}`, `::`, `,`, `-`, `.`, the one
        // written `;`, and `typename` (#1557). Operands (n2 = 7, N2 = 7):
        // `f`, `MiddlePointer`, `quant_`, `order`, `2`, `Write`, `w`.
        // Before #1546 the MISSING `;` was a second `;`.
        let cast = "void f() {\n  typename Quant::MiddlePointer(quant_, order - 2).Write(w);\n}\n";
        assert_halstead_counts::<T>(cast, "foo.cpp", [9, 11, 7, 7], label);
    }

    /// Regression for #1546 on the two C++ clones. Mozcpp owns no file
    /// extension, so this row is its only coverage.
    #[cfg(all(feature = "cpp", feature = "mozcpp"))]
    #[test]
    fn cpp_missing_tokens_in_valid_code_are_not_billed() {
        assert_cpp_missing_tokens_unbilled::<CppParser>("cpp");
        assert_cpp_missing_tokens_unbilled::<MozcppParser>("mozcpp");
    }

    /// Regression for #1547: `co_return` and `co_yield` are Halstead
    /// operators. One row per clone, so reverting either arm fails its
    /// own row; Mozcpp owns no file extension, so this row is its only
    /// coverage.
    #[cfg(all(feature = "cpp", feature = "mozcpp"))]
    #[test]
    fn cpp_coroutine_keywords_are_operators() {
        assert_cpp_coroutine_keywords::<CppParser>("cpp");
        assert_cpp_coroutine_keywords::<MozcppParser>("mozcpp");
    }

    /// Regression for #1361: a C++ `this` is a Halstead operand.
    ///
    /// `Cpp::This` / `Mozcpp::This` were in neither arm of
    /// `CppCode::get_op_type` / `MozcppCode::get_op_type`, so a `this`
    /// contributed *nothing* — not an operator and not an operand —
    /// while eleven of the fourteen languages here bill their
    /// self-reference as an operand. Same shape as #1316's character
    /// literals, and the inverse of the #1351-#1355 over-counts.
    ///
    /// 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). Mozcpp owns no file
    /// extension, so no integration snapshot reaches its clone; this row
    /// and `cpp_and_mozcpp_agree_on_this` in `tests/parity/` are the
    /// whole coverage that arm has.
    #[cfg(all(feature = "cpp", feature = "mozcpp"))]
    #[test]
    fn cpp_this_is_an_operand() {
        assert_this_receiver_parity::<CppParser>("this.cpp", "cpp");
        assert_this_receiver_parity::<MozcppParser>("this.cpp", "mozcpp");
    }

    /// The `This` arm is unconditional: every `this` in
    /// `CPP_THIS_POSITIONS` classifies as an operand whatever encloses
    /// it (#1361).
    ///
    /// The counts in `cpp_this_is_an_operand` are measured on one
    /// position only. An arm reached through a parent-scoped guard —
    /// the shape the neighbouring `RawStringLiteral` `LPAREN` arm uses,
    /// and the shape a reviewer might reasonably add here — would pass
    /// that test and still drop `this` in a lambda capture or a
    /// `decltype`. This walk is what makes the arm's unconditional
    /// reach a measurement rather than an assumption.
    ///
    /// Named for the *property* rather than for the fixture: the fixture
    /// samples one position per container kind and is deliberately not
    /// exhaustive (see `CPP_THIS_POSITIONS`), so a name promising "every
    /// position" would claim more than it checks.
    #[cfg(all(feature = "cpp", feature = "mozcpp"))]
    #[test]
    fn cpp_this_is_an_operand_regardless_of_position() {
        #[cfg(any(feature = "cpp", feature = "mozcpp"))]
        fn check<L: LanguageInfo + Getter>(label: &str) {
            let mut seen = 0_usize;
            for_each_node_with_chain::<L>(CPP_THIS_POSITIONS.as_bytes(), |node, chain| {
                if node.kind() != "this" {
                    return;
                }
                seen += 1;
                // `_with_code` is the spelling `compute_halstead` calls.
                // The default forwards to the byte-less form, so the two
                // agree for both languages today — which is exactly why
                // asking the wrong one would read as correct right up
                // until one of them grew an override
                // (grammar-dispatch section 7).
                assert!(
                    matches!(
                        L::get_op_type_with_code(
                            node,
                            CPP_THIS_POSITIONS.as_bytes(),
                            Ancestors::known(chain)
                        ),
                        TokenRole::Operand
                    ),
                    "{label}: a `this` under `{}` is not an operand",
                    chain.last().map_or("<root>", Node::kind)
                );
            });
            // One per position: `->` receiver, `(*this)`, bare return,
            // `[this]`, `[=, this]`, `decltype(this->x)`, the
            // constructor body, and the call argument.
            assert_eq!(seen, 8, "{label}: fixture lost a `this` position");
        }

        check::<CppCode>("cpp");
        check::<MozcppCode>("mozcpp");
    }

    /// Pins the two grammar facts the #1361 operand arm rests on, across
    /// both fixtures and both languages.
    ///
    /// * **Grammar-dispatch section 1.** Every node the grammar spells
    ///   `this` 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 carry
    ///   numeric-suffix aliases in quantity (`FunctionDefinition2..4`,
    ///   `QualifiedIdentifier2..4`, `LPAREN2`, `Try2`, `GT2` in this one
    ///   file) and neither spells a `This2` — `This = 215` is the sole
    ///   variant rendering `"this"` in `language_cpp.rs` and
    ///   `language_mozcpp.rs`. This loop is what notices if a grammar
    ///   bump changes that under an existing fixture.
    /// * **Grammar-dispatch section 5.** A `this` is a childless leaf and
    ///   no node containing it is classified. That is both halves of the
    ///   double-count question: nothing below it can be billed a second
    ///   time, and no `field_expression` / `pointer_expression` /
    ///   `lambda_capture_specifier` / `argument_list` wrapper bills the
    ///   same source text from above.
    #[cfg(all(feature = "cpp", feature = "mozcpp"))]
    #[test]
    fn cpp_this_is_a_childless_unaliased_leaf() {
        #[cfg(any(feature = "cpp", feature = "mozcpp"))]
        fn check<L: LanguageInfo + Getter>(this: u16, label: &str) {
            let mut seen = 0_usize;
            for source in [CPP_THIS_RECEIVER_PARITY, CPP_THIS_POSITIONS] {
                for_each_node_with_chain::<L>(source.as_bytes(), |node, chain| {
                    if node.kind() != "this" {
                        return;
                    }
                    seen += 1;
                    assert_eq!(
                        node.kind_id(),
                        this,
                        "{label}: a `this` carries kind_id {} rather than the {this} the \
                         operand arm lists — an alias the arm cannot see",
                        node.kind_id()
                    );
                    assert_eq!(
                        node.child_count(),
                        0,
                        "{label}: `this` grew children, which the operand arm would now \
                         double-count against"
                    );
                    assert!(!chain.is_empty(), "{label}: a `this` cannot be the root");
                    // Every ancestor, not just the parent. The claim is
                    // that *no node containing* a `this` is classified,
                    // and `(*this)` alone puts two wrappers between the
                    // leaf and the nearest classified node — checking
                    // only `chain.last()` would assert something
                    // narrower than the comment on the arm promises.
                    // `chain` is the *node's* ancestry, so the ancestor
                    // at `i` has `chain[..i]` for its own.
                    for (i, ancestor) in chain.iter().enumerate() {
                        assert!(
                            matches!(
                                L::get_op_type_with_code(
                                    ancestor,
                                    source.as_bytes(),
                                    Ancestors::known(&chain[..i])
                                ),
                                TokenRole::Unknown
                            ),
                            "{label}: `{}` contains a `this` and is itself classified, so the \
                             reference now counts twice",
                            ancestor.kind()
                        );
                    }
                });
            }
            // One `this` in the parity fixture, eight in the positions
            // fixture. Asserted so a fixture that stopped containing one
            // cannot make this test pass having checked nothing.
            assert_eq!(seen, 9, "{label}: fixtures lost a `this`");
        }

        check::<CppCode>(Cpp::This as u16, "cpp");
        check::<MozcppCode>(Mozcpp::This as u16, "mozcpp");
    }

    /// 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);
    }
}