big-code-analysis 1.1.0

Tool to compute and export code metrics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
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
// Per-language metric and AST modules deliberately consume the macro-
// generated tree-sitter token enums via `use crate::*` and `use Foo::*`
// inside match expressions — explicit imports would list dozens of
// variants per arm and obscure the per-language token sets that are the
// point of these files. Allowed at the module level rather than per
// function so the per-language impl blocks stay readable.
#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
// 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 serde::Serialize;
use serde::ser::{SerializeStruct, Serializer};
use std::fmt;

use crate::checker::Checker;
use crate::langs::*;
use crate::macros::{csharp_var_decl_kinds, csharp_var_declarator_kinds, implement_metric_trait};
use crate::node::Node;
use crate::*;

/// The `Npa` metric.
///
/// This metric counts the number of public attributes
/// of classes/interfaces.
#[derive(Clone, Debug, Default)]
pub struct Stats {
    class_npa: usize,
    interface_npa: usize,
    class_na: usize,
    interface_na: usize,
    class_npa_sum: usize,
    interface_npa_sum: usize,
    class_na_sum: usize,
    interface_na_sum: usize,
    is_class_space: bool,
}

impl Serialize for Stats {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut st = serializer.serialize_struct("npa", 9)?;
        st.serialize_field("classes", &self.class_npa_sum())?;
        st.serialize_field("interfaces", &self.interface_npa_sum())?;
        st.serialize_field("class_attributes", &self.class_na_sum())?;
        st.serialize_field("interface_attributes", &self.interface_na_sum())?;
        st.serialize_field("classes_average", &self.class_cda())?;
        st.serialize_field("interfaces_average", &self.interface_cda())?;
        st.serialize_field("total", &self.total_npa())?;
        st.serialize_field("total_attributes", &self.total_na())?;
        st.serialize_field("average", &self.total_cda())?;
        st.end()
    }
}

impl fmt::Display for Stats {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "classes: {}, interfaces: {}, class_attributes: {}, interface_attributes: {}, classes_average: {}, interfaces_average: {}, total: {}, total_attributes: {}, average: {}",
            self.class_npa_sum(),
            self.interface_npa_sum(),
            self.class_na_sum(),
            self.interface_na_sum(),
            self.class_cda(),
            self.interface_cda(),
            self.total_npa(),
            self.total_na(),
            self.total_cda()
        )
    }
}

impl Stats {
    /// Merges a second `Npa` metric into the first one
    pub fn merge(&mut self, other: &Stats) {
        self.class_npa_sum += other.class_npa_sum;
        self.interface_npa_sum += other.interface_npa_sum;
        self.class_na_sum += other.class_na_sum;
        self.interface_na_sum += other.interface_na_sum;
    }

    /// Returns the number of class public attributes in a space.
    #[inline]
    #[must_use]
    pub fn class_npa(&self) -> f64 {
        self.class_npa as f64
    }

    /// Returns the number of interface public attributes in a space.
    #[inline]
    #[must_use]
    pub fn interface_npa(&self) -> f64 {
        self.interface_npa as f64
    }

    /// Returns the number of class attributes in a space.
    #[inline]
    #[must_use]
    pub fn class_na(&self) -> f64 {
        self.class_na as f64
    }

    /// Returns the number of interface attributes in a space.
    #[inline]
    #[must_use]
    pub fn interface_na(&self) -> f64 {
        self.interface_na as f64
    }

    /// Returns the number of class public attributes sum in a space.
    #[inline]
    #[must_use]
    pub fn class_npa_sum(&self) -> f64 {
        self.class_npa_sum as f64
    }

    /// Returns the number of interface public attributes sum in a space.
    #[inline]
    #[must_use]
    pub fn interface_npa_sum(&self) -> f64 {
        self.interface_npa_sum as f64
    }

    /// Returns the number of class attributes sum in a space.
    #[inline]
    #[must_use]
    pub fn class_na_sum(&self) -> f64 {
        self.class_na_sum as f64
    }

    /// Returns the number of interface attributes sum in a space.
    #[inline]
    #[must_use]
    pub fn interface_na_sum(&self) -> f64 {
        self.interface_na_sum as f64
    }

    /// Returns the class `Cda` metric value
    ///
    /// The `Class Data Accessibility` metric value for a class
    /// is computed by dividing the `Npa` value of the class
    /// by the total number of attributes defined in the class.
    ///
    /// This metric is an adaptation of the `Classified Class Data Accessibility` (`CCDA`)
    /// security metric for not classified attributes.
    /// Paper: <https://ieeexplore.ieee.org/abstract/document/5381538>
    #[inline]
    #[must_use]
    pub fn class_cda(&self) -> f64 {
        self.class_npa_sum() / self.class_na_sum as f64
    }

    /// Returns the interface `Cda` metric value
    ///
    /// The `Class Data Accessibility` metric value for an interface
    /// is computed by dividing the `Npa` value of the interface
    /// by the total number of attributes defined in the interface.
    ///
    /// This metric is an adaptation of the `Classified Class Data Accessibility` (`CCDA`)
    /// security metric for not classified attributes.
    /// Paper: <https://ieeexplore.ieee.org/abstract/document/5381538>
    #[inline]
    #[must_use]
    pub fn interface_cda(&self) -> f64 {
        // For the Java language it's not necessary to compute the metric value
        // The metric value in Java can only be 1.0 or f64:NAN
        if self.interface_npa_sum == self.interface_na_sum && self.interface_npa_sum != 0 {
            1.0
        } else {
            self.interface_npa_sum() / self.interface_na_sum()
        }
    }

    /// Returns the total `Cda` metric value
    ///
    /// The total `Class Data Accessibility` metric value
    /// is computed by dividing the total `Npa` value
    /// by the total number of attributes.
    ///
    /// This metric is an adaptation of the `Classified Class Data Accessibility` (`CCDA`)
    /// security metric for not classified attributes.
    /// Paper: <https://ieeexplore.ieee.org/abstract/document/5381538>
    #[inline]
    #[must_use]
    pub fn total_cda(&self) -> f64 {
        self.total_npa() / self.total_na()
    }

    /// Returns the total number of public attributes in a space.
    #[inline]
    #[must_use]
    pub fn total_npa(&self) -> f64 {
        self.class_npa_sum() + self.interface_npa_sum()
    }

    /// Returns the total number of attributes in a space.
    #[inline]
    #[must_use]
    pub fn total_na(&self) -> f64 {
        self.class_na_sum() + self.interface_na_sum()
    }

    // Accumulates the number of class and interface
    // public and not public attributes into the sums
    #[inline]
    pub(crate) fn compute_sum(&mut self) {
        self.class_npa_sum += self.class_npa;
        self.interface_npa_sum += self.interface_npa;
        self.class_na_sum += self.class_na;
        self.interface_na_sum += self.interface_na;
    }

    // Checks if the `Npa` metric is disabled
    #[inline]
    pub(crate) fn is_disabled(&self) -> bool {
        !self.is_class_space
    }
}

#[doc(hidden)]
/// Per-language counting of public attributes.
pub trait Npa
where
    Self: Checker,
{
    /// Walk `node` and update `stats` with this metric for the language
    /// implementing the trait.
    ///
    /// `code` is the raw source-bytes buffer; languages whose visibility
    /// rules are encoded in identifier text (Ruby's keyword-style
    /// `private` / `public` / `protected`) read identifier text from
    /// it. Languages whose visibility rules are encoded purely in
    /// distinct token kinds (Java's `Public` / `Private`, PHP's
    /// `VisibilityModifier`) ignore the parameter.
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], stats: &mut Stats);
}

// Java and Groovy share their grammar tokens for class/interface
// bodies, so `Npa::compute` differs only by the language enum.
// `impl_npa_java_like!` emits the same body against each enum
// (issue #280).
//
// `ClassBody` covers classes and records (records reuse `class_body`
// for their explicit declaration body). Record components in
// `formal_parameters` are implicit public final fields, but only
// explicit body members are counted here for parity with C#'s record
// handling (lesson 11). `EnumBodyDeclarations` is the optional
// declarations block inside `EnumBody`, following the enum constants.
// Annotation type bodies hold `ConstantDeclaration`s with the same
// implicit `public static final` rule as interfaces
// (https://docs.oracle.com/javase/specs/jls/se7/html/jls-9.html).
//
// Groovy note: `def field` at class scope is parsed as a
// `FieldDeclaration` with `Def` in the modifiers list (no `Public`),
// so it's correctly excluded from `class_npa` unless explicitly
// annotated `public` — consistent with Groovy's access semantics
// (default class members are package-private under `@CompileStatic`,
// public otherwise; we conservatively follow Java).
macro_rules! impl_npa_java_like {
    ($code:ty, $lang:ident) => {
        impl Npa for $code {
            fn compute<'a>(node: &Node<'a>, _code: &'a [u8], stats: &mut Stats) {
                use $lang::*;

                if Self::is_func_space(node) && stats.is_disabled() {
                    stats.is_class_space = true;
                }

                match node.kind_id().into() {
                    ClassBody | EnumBodyDeclarations => {
                        for declaration in node
                            .children()
                            .filter(|n| matches!(n.kind_id().into(), FieldDeclaration))
                        {
                            let attributes = declaration
                                .children()
                                .filter(|n| matches!(n.kind_id().into(), VariableDeclarator))
                                .count();
                            stats.class_na += attributes;
                            // The first child node contains the list of
                            // attribute modifiers. Source:
                            // https://docs.oracle.com/javase/tutorial/reflect/member/fieldModifiers.html
                            if declaration.child(0).is_some_and(|modifiers| {
                                matches!(modifiers.kind_id().into(), Modifiers)
                                    && modifiers.first_child(|id| id == Public).is_some()
                            }) {
                                stats.class_npa += attributes;
                            }
                        }
                    }
                    InterfaceBody | AnnotationTypeBody => {
                        stats.interface_na += node
                            .children()
                            .filter(|n| matches!(n.kind_id().into(), ConstantDeclaration))
                            .flat_map(|n| n.children())
                            .filter(|n| matches!(n.kind_id().into(), VariableDeclarator))
                            .count();
                        stats.interface_npa = stats.interface_na;
                    }
                    _ => {}
                }
            }
        }
    };
}

impl_npa_java_like!(JavaCode, Java);

// Groovy uses the dekobon grammar, which models class/interface/trait/
// annotation-type/record bodies as a single `class_body` node and
// flattens modifiers as direct children of the declaration (the
// `_modifier` rule is hidden — no `Modifiers` wrapper). That rules out
// the Java macro, so an explicit impl is required.
//
// `def field` at class scope parses as a `FieldDeclaration` with `Def`
// in the modifier slot and no `Public`, so it's correctly excluded from
// `class_npa` unless explicitly annotated `public` — consistent with
// Groovy's access semantics (we conservatively follow Java).
impl Npa for GroovyCode {
    fn compute<'a>(node: &Node<'a>, _code: &'a [u8], stats: &mut Stats) {
        use Groovy::*;

        if Self::is_func_space(node) && stats.is_disabled() {
            stats.is_class_space = true;
        }

        match node.kind_id().into() {
            ClassBody | EnumBody => {
                let is_interface_like = groovy_body_is_interface_like(node);

                for declaration in node
                    .children()
                    .filter(|n| matches!(n.kind_id().into(), FieldDeclaration))
                {
                    let attributes = declaration
                        .children()
                        .filter(|n| matches!(n.kind_id().into(), VariableDeclarator))
                        .count();
                    if is_interface_like {
                        stats.interface_na += attributes;
                        stats.interface_npa += attributes;
                    } else {
                        stats.class_na += attributes;
                        if groovy_has_explicit_public(&declaration) {
                            stats.class_npa += attributes;
                        }
                    }
                }
            }
            _ => {}
        }
    }
}

// Distinguishes interface-like containers (interface, trait, annotation
// type) — whose members are implicitly public — from class-like
// containers (class, enum, record) that need an explicit `public`
// modifier. The dekobon grammar models all of these bodies as
// `class_body`, so the discriminant lives on the parent. Shared with
// `impl Npm for GroovyCode` (`metrics::npm`).
pub(crate) fn groovy_body_is_interface_like(body: &Node) -> bool {
    use Groovy::*;
    body.parent().is_some_and(|p| {
        matches!(
            p.kind_id().into(),
            InterfaceDeclaration | TraitDeclaration | AnnotationTypeDeclaration
        )
    })
}

// Detects an explicit `public` modifier on a class member declaration.
// The dekobon grammar flattens the `_modifier` rule, so modifier
// tokens appear as direct children of the declaration — no `Modifiers`
// wrapper to descend into. Shared with `impl Npm for GroovyCode`.
pub(crate) fn groovy_has_explicit_public(declaration: &Node) -> bool {
    declaration.first_child(|id| id == Groovy::Public).is_some()
}

// C# uses individual `Modifier` nodes (not wrapped under a single
// `modifiers` node like Java); detecting `public` requires scanning
// every Modifier child of the declaration for a `public` keyword.
pub(crate) fn csharp_is_explicit_public(declaration: &Node) -> bool {
    declaration.children().any(|child| {
        matches!(child.kind_id().into(), Csharp::Modifier)
            && child.first_child(|id| id == Csharp::Public).is_some()
    })
}

impl Npa for CsharpCode {
    fn compute<'a>(node: &Node<'a>, _code: &'a [u8], stats: &mut Stats) {
        use Csharp::*;

        if Self::is_func_space(node) && stats.is_disabled() {
            stats.is_class_space = true;
        }

        // Class / struct / record / interface bodies all share
        // `DeclarationList`; the parent kind disambiguates.
        if !matches!(node.kind_id().into(), DeclarationList) {
            return;
        }
        let Some(parent_kind) = node.parent().map(|p| p.kind_id().into()) else {
            return;
        };
        match parent_kind {
            // For `RecordDeclaration`, only explicit body fields are
            // counted. The implicit `parameter_list` of a positional
            // record (`record Person(string Name, int Age);`) is not
            // walked here — its parameters become auto-generated public
            // properties at the IL level, but modelling them would
            // require synthesizing nodes that don't appear in the AST.
            ClassDeclaration | StructDeclaration | RecordDeclaration => {
                for declaration in node
                    .children()
                    .filter(|c| matches!(c.kind_id().into(), FieldDeclaration))
                {
                    let attributes = csharp_count_field_declarators(&declaration);
                    stats.class_na += attributes;
                    if csharp_is_explicit_public(&declaration) {
                        stats.class_npa += attributes;
                    }
                }
            }
            // C# 8+ interfaces can declare fields with explicit modifiers
            // (rare); members declared without an explicit modifier default
            // to public, mirroring Java's interface convention.
            InterfaceDeclaration => {
                for declaration in node
                    .children()
                    .filter(|c| matches!(c.kind_id().into(), FieldDeclaration))
                {
                    let attributes = csharp_count_field_declarators(&declaration);
                    stats.interface_na += attributes;
                    stats.interface_npa = stats.interface_na;
                }
            }
            _ => {}
        }
    }
}

// Count `VariableDeclarator`s nested under any aliased `VariableDeclaration`
// inside a C# `FieldDeclaration`. Both kinds emit two aliased `kind_id`s
// each; the macros centralize the alias union (lesson #2).
fn csharp_count_field_declarators(field_decl: &Node) -> usize {
    field_decl
        .children()
        .filter(|c| matches!(c.kind_id().into(), csharp_var_decl_kinds!()))
        .flat_map(|c| c.children())
        .filter(|c| matches!(c.kind_id().into(), csharp_var_declarator_kinds!()))
        .count()
}

// PHP's strict-explicit visibility rule (mirroring Java's pattern): a
// declaration is treated as public only when it carries an explicit
// `public` modifier. Modifier-less declarations — deprecated for
// properties since PHP 8 and merely conventional for methods — are NOT
// counted, even though PHP semantically defaults methods to public.
pub(crate) fn php_is_explicit_public(declaration: &Node) -> bool {
    declaration.children().any(|child| {
        matches!(child.kind_id().into(), Php::VisibilityModifier)
            && child.first_child(|id| id == Php::Public).is_some()
    })
}

// Counts the number of symbol arguments passed to an `attr_accessor` /
// `attr_reader` / `attr_writer` macro `Call` node. `attr_accessor :a,
// :b, :c` exposes three attributes; an `attr_*` call with no arguments
// is ill-formed Ruby but defensively returns zero rather than one.
pub(crate) fn ruby_attr_macro_symbol_count(call: &Node) -> usize {
    use Ruby::*;

    call.children()
        .find(|c| matches!(c.kind_id().into(), ArgumentList | ArgumentList2))
        .map_or(0, |args| {
            args.children()
                .filter(|c| {
                    matches!(
                        c.kind_id().into(),
                        SimpleSymbol | DelimitedSymbol | HashKeySymbol | BareSymbol
                    )
                })
                .count()
        })
}

// Ruby class-body visibility state. `private` / `public` / `protected`
// keywords flip this flag for every subsequent declaration in the same
// body until another marker overrides them. The default at the top of
// every class body is `Public`.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum RubyVisibility {
    Public,
    Private,
    Protected,
}

// Recognises a bare visibility-keyword `identifier` child of a Ruby
// class body (`private` / `public` / `protected` with no arguments).
// tree-sitter-ruby emits the keyword-form as a literal `identifier`
// token; the argument-form (`private :foo`, `private def bar`) is a
// `Call` node instead and does NOT flip the body-wide flag.
pub(crate) fn ruby_visibility_marker(node: &Node, source: &[u8]) -> Option<RubyVisibility> {
    if !matches!(node.kind_id().into(), Ruby::Identifier) {
        return None;
    }
    match node.utf8_text(source)? {
        "private" => Some(RubyVisibility::Private),
        "public" => Some(RubyVisibility::Public),
        "protected" => Some(RubyVisibility::Protected),
        _ => None,
    }
}

// Identifies the `attr_*` macro family on a Ruby `Call` node. Each
// macro takes a list of attribute symbols and synthesises the matching
// reader / writer / accessor methods on the enclosing class.
pub(crate) fn ruby_attr_macro_name(call: &Node, source: &[u8]) -> Option<&'static str> {
    let ident = call
        .children()
        .find(|c| matches!(c.kind_id().into(), Ruby::Identifier))?;
    match ident.utf8_text(source)? {
        "attr_accessor" => Some("attr_accessor"),
        "attr_reader" => Some("attr_reader"),
        "attr_writer" => Some("attr_writer"),
        _ => None,
    }
}

// Walks the direct children of a Ruby class / singleton-class body
// (`BodyStatement` under `Class` / `SingletonClass`) tallying:
// - class-scope assignments to `@var` (`InstanceVariable`) and
//   `@@var` (`ClassVariable`) — one attribute per assignment, regardless
//   of whether the RHS is a constant or another expression.
// - `attr_accessor` / `attr_reader` / `attr_writer` macros — one
//   attribute per symbol argument.
//
// Visibility flags follow Ruby's keyword-marker convention: a bare
// `private` / `public` / `protected` identifier flips the default for
// every subsequent declaration in the body. The default visibility at
// the top of every class body is `public`. The argument-form of those
// keywords (`private :foo`, `private def x`) does not flip the body-
// wide flag — matching Ruby's runtime behaviour.
//
// Attribute assignments to instance/class variables are visible only
// via the methods that wrap them, so the visibility flag at the point
// of declaration is what `npa` should reflect.
pub(crate) fn ruby_walk_class_body(body: &Node, source: &[u8], stats: &mut Stats) {
    use Ruby::*;

    let mut visibility = RubyVisibility::Public;
    for child in body.children() {
        if let Some(marker) = ruby_visibility_marker(&child, source) {
            visibility = marker;
            continue;
        }
        match child.kind_id().into() {
            Assignment | Assignment2 => {
                let Some(lhs) = child.children().next() else {
                    continue;
                };
                if matches!(lhs.kind_id().into(), InstanceVariable | ClassVariable) {
                    stats.class_na += 1;
                    if visibility == RubyVisibility::Public {
                        stats.class_npa += 1;
                    }
                }
            }
            Call | Call2 | Call3 | Call4 if ruby_attr_macro_name(&child, source).is_some() => {
                let count = ruby_attr_macro_symbol_count(&child);
                stats.class_na += count;
                if visibility == RubyVisibility::Public {
                    stats.class_npa += count;
                }
            }
            _ => {}
        }
    }
}

impl Npa for RubyCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], stats: &mut Stats) {
        use Ruby::*;

        if Self::is_func_space(node) && stats.is_disabled() {
            stats.is_class_space = true;
        }

        if !matches!(node.kind_id().into(), BodyStatement | BodyStatement2) {
            return;
        }
        let Some(parent_kind) = node.parent().map(|p| p.kind_id().into()) else {
            return;
        };
        if !matches!(parent_kind, Class | SingletonClass) {
            return;
        }
        ruby_walk_class_body(node, code, stats);
    }
}

impl Npa for PhpCode {
    fn compute<'a>(node: &Node<'a>, _code: &'a [u8], stats: &mut Stats) {
        use Php::*;

        // Enables the `Npa` metric if computing stats of a class-like space.
        if Self::is_func_space(node) && stats.is_disabled() {
            stats.is_class_space = true;
        }

        match node.kind_id().into() {
            // Class / trait / anonymous-class / interface bodies all share
            // the `DeclarationList` kind; the parent kind disambiguates.
            DeclarationList => {
                let Some(parent_kind) = node.parent().map(|p| p.kind_id().into()) else {
                    return;
                };
                match parent_kind {
                    ClassDeclaration | TraitDeclaration | AnonymousClass => {
                        for declaration in node
                            .children()
                            .filter(|c| matches!(c.kind_id().into(), PropertyDeclaration))
                        {
                            let attributes = declaration
                                .children()
                                .filter(|c| matches!(c.kind_id().into(), PropertyElement))
                                .count();
                            stats.class_na += attributes;
                            if php_is_explicit_public(&declaration) {
                                stats.class_npa += attributes;
                            }
                        }
                    }
                    // Interfaces cannot declare properties but can declare
                    // class constants, which are implicitly public.
                    InterfaceDeclaration => {
                        let count: usize = node
                            .children()
                            .filter(|c| {
                                matches!(c.kind_id().into(), ConstDeclaration | ConstDeclaration2)
                            })
                            .map(|decl| {
                                decl.children()
                                    .filter(|n| {
                                        matches!(n.kind_id().into(), ConstElement | ConstElement2)
                                    })
                                    .count()
                            })
                            .sum();
                        stats.interface_na += count;
                        stats.interface_npa = stats.interface_na;
                    }
                    _ => {}
                }
            }
            // Enum cases are public read-only constants of the enum.
            EnumDeclarationList => {
                let count = node
                    .children()
                    .filter(|c| matches!(c.kind_id().into(), EnumCase))
                    .count();
                stats.class_na += count;
                stats.class_npa += count;
            }
            _ => {}
        }
    }
}

// Python attribute counting.
//
// Python has two flavours of class attributes:
// 1. Class-level (a.k.a. static): direct assignments inside the class
//    body — `class C: x = 1` or `class C: x: int = 1`.
// 2. Instance attributes: `self.x = …` assigned inside any method
//    body, conventionally inside `__init__`.
//
// Python has no visibility keyword. The PEP-8 convention `_x` for
// "internal" and `__x` for "name-mangled private" is purely advisory
// and not represented in the AST. `Npa::compute` is also called
// without access to the source bytes (only the `Node`), so reading
// the identifier text is not possible from this trait. We therefore
// treat every class attribute as public — `class_npa == class_na` —
// matching the Python ethos of "consenting adults". Documented as
// part of the trait contract for Python.
//
// Strategy: when the visitor hits a `ClassDefinition`, walk the body
// once and tally both class-level assignments and the `self.X = …`
// targets introduced by any method body. Counting on the
// `ClassDefinition` node (not its enclosed function spaces) keeps the
// attribution local to the surrounding class space, even though
// `self.X = …` lives inside a child `FunctionDefinition` space whose
// own `npa` stats are not class spaces.
impl Npa for PythonCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], stats: &mut Stats) {
        use Python::*;

        // Gate on `ClassDefinition` specifically: `is_func_space` is
        // also true for `Module` / `FunctionDefinition`, which would
        // over-eagerly mark every space as a class space.
        if !matches!(node.kind_id().into(), ClassDefinition) {
            return;
        }

        // Mark the current space as a class space so the metric is
        // emitted (otherwise it is suppressed by `is_disabled`).
        if stats.is_disabled() {
            stats.is_class_space = true;
        }

        let Some(body) = python_class_body(node) else {
            return;
        };

        // Counts of distinct class attributes (class-level + self.*).
        // `self.x` may appear in several methods — and in different
        // branches of the same method — but per Fitzpatrick's intent
        // each *attribute* counts once. We deduplicate by the
        // attribute identifier text (read via the `code` bytes
        // widened into the trait by #219), so:
        //   class C:
        //       def __init__(self): self.value = None
        //       def reset(self):    self.value = None
        // counts `value` once, not twice. Closes #215.
        let class_level = python_count_class_level_attrs(&body);
        let self_attrs = python_count_unique_self_attrs(&body, code);
        let total = class_level + self_attrs;

        stats.class_na += total;
        // No visibility keyword in Python — every attribute is "public".
        stats.class_npa += total;
    }
}

// Rust attribute counting.
//
// Rust's "class" maps to a `struct` plus its `impl` blocks. Since each
// `impl` block opens its own func_space (`SpaceKind::Impl`), the
// natural place to record attributes per "class" is at the impl space
// and at the struct itself:
//
// 1. `StructItem`: every direct child in the struct's
//    `field_declaration_list` (named fields) or
//    `ordered_field_declaration_list` (tuple-struct positional fields)
//    is one attribute. Because `struct_item` is NOT a func_space, the
//    fields are attributed to whichever func_space is on the stack
//    when the StructItem is visited (typically `Unit`). The enclosing
//    space is marked as a class space so the npa metric is emitted.
//
// 2. `ImplItem`: every `ConstItem` and `StaticItem` direct child of the
//    impl's `declaration_list` is one associated attribute. These
//    accumulate on the Impl space (which is itself a class-style
//    func_space).
//
// 3. `TraitItem`: every `ConstItem`, `StaticItem`, and `AssociatedType`
//    direct child of the trait's `declaration_list` is one attribute.
//    Trait members are always visible to implementers, so they are
//    counted as public (`interface_npa == interface_na`), mirroring
//    Java's interface-body rule.
//
// Limitations (documented):
// - Multiple `impl Foo` blocks each open their own Impl space and
//   accumulate independently. Their `_sum` accumulators roll up to
//   the parent during finalisation, so the file-level
//   `class_npa_sum` is the sum across every impl.
// - Struct fields are attributed to the enclosing func_space (usually
//   Unit), not to a per-struct space. Two structs in the same module
//   therefore contribute to the same `class_na` bucket on that Unit.
//   This matches the issue's intent of "count struct fields + impl
//   associated consts" without inventing a synthetic per-struct
//   space.
// - Enum variants are NOT counted as attributes (they are sum-type
//   tags, not data fields), mirroring Kotlin's `enum_class_body`
//   treatment.
impl Npa for RustCode {
    fn compute<'a>(node: &Node<'a>, _code: &'a [u8], stats: &mut Stats) {
        use Rust::*;

        // Mark Impl / Trait spaces as class spaces so the metric is
        // emitted on them.
        if matches!(node.kind_id().into(), ImplItem | TraitItem) && stats.is_disabled() {
            stats.is_class_space = true;
        }

        match node.kind_id().into() {
            // Counted on the StructItem so each struct's fields are
            // tallied exactly once. The enclosing func_space (Unit or
            // nested) is the recipient — marking it a class space
            // makes the npa metric visible.
            StructItem => {
                let mut attrs = 0;
                let mut public_attrs = 0;
                for body in node.children() {
                    match body.kind_id().into() {
                        // Named-field struct: each `field_declaration`
                        // is one attribute. Visibility is the
                        // `visibility_modifier` first child.
                        FieldDeclarationList => {
                            for field in body
                                .children()
                                .filter(|c| matches!(c.kind_id().into(), FieldDeclaration))
                            {
                                attrs += 1;
                                if rust_item_is_public(&field) {
                                    public_attrs += 1;
                                }
                            }
                        }
                        // Tuple struct: the field count is positional.
                        // The grammar emits each field as either a
                        // type-bearing node (`primitive_type`,
                        // `type_identifier`, `generic_type`, ...) or a
                        // `visibility_modifier` followed by such a
                        // node. We count one attribute per non-token
                        // child that is not a delimiter, comma, or
                        // visibility modifier.
                        OrderedFieldDeclarationList => {
                            let (count, public) = rust_count_tuple_struct_fields(&body);
                            attrs += count;
                            public_attrs += public;
                        }
                        _ => {}
                    }
                }
                if attrs > 0 {
                    if stats.is_disabled() {
                        stats.is_class_space = true;
                    }
                    stats.class_na += attrs;
                    stats.class_npa += public_attrs;
                }
            }
            // Associated const/static declared in an `impl` block.
            // The current top-of-stack is the Impl space (because we
            // are inside its body), so attribution lands there.
            ConstItem | StaticItem => {
                let Some(parent) = node.parent() else {
                    return;
                };
                let Some(grand) = parent.parent() else {
                    return;
                };
                match grand.kind_id().into() {
                    ImplItem if matches!(parent.kind_id().into(), DeclarationList) => {
                        stats.class_na += 1;
                        if rust_item_is_public(node) {
                            stats.class_npa += 1;
                        }
                    }
                    TraitItem if matches!(parent.kind_id().into(), DeclarationList) => {
                        stats.interface_na += 1;
                        stats.interface_npa = stats.interface_na;
                    }
                    _ => {}
                }
            }
            // `type Foo;` inside a trait body is an associated type —
            // a placeholder bound that the implementer must supply.
            // Counted as an interface attribute, public by default.
            AssociatedType => {
                let Some(parent) = node.parent() else {
                    return;
                };
                let Some(grand) = parent.parent() else {
                    return;
                };
                if matches!(grand.kind_id().into(), TraitItem)
                    && matches!(parent.kind_id().into(), DeclarationList)
                {
                    stats.interface_na += 1;
                    stats.interface_npa = stats.interface_na;
                }
            }
            _ => {}
        }
    }
}

// Go attribute counting.
//
// Go has no `class` concept; struct types declared at file scope
// (`type Foo struct { … }`) play that role. Methods live separately
// as `MethodDeclaration` nodes attached to a receiver type. Because
// `StructType` is NOT a func_space (per `Checker::is_func_space`),
// the iterator visits it with the enclosing func_space's stats
// (typically the file-level `Unit`). Each direct `FieldDeclaration`
// child of the struct's `FieldDeclarationList` counts as one
// attribute, including embedded types (an embedded type parses as a
// `FieldDeclaration` with no name field, just a type — still one
// attribute per the issue spec).
//
// Visibility note: Go exports identifiers whose first character is
// uppercase. The `Npa::compute` trait signature does not include the
// source byte slice, so reading the identifier text from the node
// alone is not possible. We therefore treat every counted attribute
// as public (`class_npa == class_na`), matching the choice Python's
// Npm makes when no visibility token is present in the AST. The
// alternative — adding a `code: &[u8]` parameter to the trait — is a
// cross-language API change out of scope for this fix.
//
// Limitations:
// - Struct fields are attributed to the enclosing func_space (the
//   file's `Unit`, or a local function space for `type T struct{…}`
//   declared inside a function body). Multiple structs at the same
//   level contribute to the same `class_na` bucket. This mirrors the
//   Rust impl's "fields land on the enclosing space" approach.
// - Interface methods (`interface { Foo() }`) are not attributes —
//   they are method signatures, counted by Npm under
//   `interface_nm`, not by Npa.
impl Npa for GoCode {
    fn compute<'a>(node: &Node<'a>, _code: &'a [u8], stats: &mut Stats) {
        use Go as G;

        if !matches!(node.kind_id().into(), G::StructType) {
            return;
        }

        // The struct body is the `field_declaration_list` direct
        // child. An empty struct (`struct{}`) has the list with no
        // FieldDeclaration children → 0 attributes.
        let Some(body) = node
            .children()
            .find(|c| matches!(c.kind_id().into(), G::FieldDeclarationList))
        else {
            return;
        };

        let attrs = body
            .children()
            .filter(|c| matches!(c.kind_id().into(), G::FieldDeclaration))
            .count();

        if attrs == 0 {
            return;
        }

        if stats.is_disabled() {
            stats.is_class_space = true;
        }
        stats.class_na += attrs;
        // Visibility cannot be detected without the source bytes;
        // every field is treated as public (see module-level note).
        stats.class_npa += attrs;
    }
}

impl Npa for CppCode {
    fn compute<'a>(node: &Node<'a>, _code: &'a [u8], stats: &mut Stats) {
        use Cpp::*;

        // Mark class / struct spaces as class spaces so the metric is
        // emitted on them.
        if matches!(node.kind_id().into(), ClassSpecifier | StructSpecifier) && stats.is_disabled()
        {
            stats.is_class_space = true;
        }

        if !matches!(node.kind_id().into(), FieldDeclarationList) {
            return;
        }
        let Some(parent) = node.parent() else {
            return;
        };
        // C++ `class` defaults to private; `struct` defaults to public.
        let mut current_is_public = match parent.kind_id().into() {
            ClassSpecifier => false,
            StructSpecifier => true,
            _ => return,
        };

        for child in node.children() {
            match child.kind_id().into() {
                AccessSpecifier => {
                    // Update the current visibility to the access
                    // specifier's keyword. `protected` is bucketed with
                    // `private` for `npa` purposes (matches Java's
                    // "non-public" treatment), so any keyword other
                    // than `public` flips us back to private.
                    current_is_public = child
                        .first_child(|id| {
                            id == Cpp::Public || id == Cpp::Protected || id == Cpp::Private
                        })
                        .is_some_and(|tok| tok.kind_id() == Cpp::Public);
                }
                FieldDeclaration => {
                    // Member functions surface as `field_declaration`
                    // when declared without a body. They are counted
                    // by `Npm`, not as attributes — detect them by
                    // their `function_declarator` and skip.
                    if cpp_has_function_declarator(&child) {
                        continue;
                    }
                    // Data field — count every `field_identifier` in
                    // the declarator subtree. Pointer (`int* p`),
                    // array (`int a[N]`), and plain (`int x`) forms
                    // all reduce to one or more `field_identifier`
                    // leaves; the comma-separated form `int b, c`
                    // adds them as siblings.
                    let count = cpp_count_field_identifiers(&child);
                    stats.class_na += count;
                    if current_is_public {
                        stats.class_npa += count;
                    }
                }
                _ => {}
            }
        }
    }
}

pub(crate) fn cpp_has_function_declarator(node: &Node) -> bool {
    use Cpp::*;
    node.children().any(|child| match child.kind_id().into() {
        FunctionDeclarator | FunctionDeclarator2 | FunctionDeclarator3 => true,
        // Recurse through declarator wrappers that can sit above the
        // function_declarator (`Foo* operator->()`,
        // `template<...> T fn();`, constructor / destructor
        // `declaration`s inside a class body).
        PointerDeclarator | PointerDeclarator2 | ReferenceDeclarator | ReferenceDeclarator2
        | ReferenceDeclarator3 | ReferenceDeclarator4 | Declaration | Declaration2
        | Declaration3 | Declaration4 => cpp_has_function_declarator(&child),
        _ => false,
    })
}

pub(crate) fn cpp_count_field_identifiers(node: &Node) -> usize {
    use Cpp::*;
    let mut count = 0;
    for child in node.children() {
        match child.kind_id().into() {
            FieldIdentifier => count += 1,
            PointerDeclarator | PointerDeclarator2 | ArrayDeclarator | ArrayDeclarator2
            | ArrayDeclarator3 | InitDeclarator | ReferenceDeclarator | ReferenceDeclarator2
            | ReferenceDeclarator3 | ReferenceDeclarator4 => {
                count += cpp_count_field_identifiers(&child);
            }
            _ => {}
        }
    }
    count
}

// Counts positional fields inside an `ordered_field_declaration_list`
// (tuple struct). Each non-token child that is a type node represents
// one field. A leading `visibility_modifier` may decorate the field;
// counts that field as public. Returns `(total_count, public_count)`.
fn rust_count_tuple_struct_fields(list: &Node) -> (usize, usize) {
    use Rust::*;

    let mut total = 0;
    let mut public = 0;
    let mut pending_pub = false;
    for child in list.children() {
        match child.kind_id().into() {
            // Open / close parens and comma separators — skipped.
            LPAREN | RPAREN | COMMA => {
                pending_pub = false;
            }
            // `pub` / `pub(crate)` / `pub(super)` / ... — applies to
            // the next type child.
            VisibilityModifier => {
                pending_pub = true;
            }
            // `attribute_item` decorates the next field but does not
            // contribute to visibility. Skip without resetting the
            // pending-pub flag. `line_comment` / `block_comment` may
            // sit between fields (e.g. `pub struct Foo(/* x */ i32);`)
            // and similarly must not count as a field.
            AttributeItem | LineComment | BlockComment => {}
            // Any other child is treated as a positional field type
            // (primitive_type, type_identifier, generic_type,
            // reference_type, tuple_type, ...). One increment per
            // type child.
            _ => {
                total += 1;
                if pending_pub {
                    public += 1;
                }
                pending_pub = false;
            }
        }
    }
    (total, public)
}

// Returns `true` if `pat` contains exactly one `UNDERSCORE` token
// (identified by `underscore_id`) and no other named children.
// Anonymous tokens such as a leading `|` in a Rust or-pattern
// (`| _ => ...`) are skipped — they do not change the semantic
// meaning of the pattern.
//
// Shared between languages whose `default:`-equivalent wildcard
// pattern is a single `_`:
//   - Rust `match_pattern` (`Cyclomatic` and `Abc` for `RustCode`)
//   - Python `case_pattern` (`Abc` for `PythonCode`)
//
// The Rust caller passes its grammar's `UNDERSCORE` kind id; Python
// passes its own. Guard handling is the caller's responsibility —
// in Rust the guard is a sibling inside `match_pattern` and so adds
// a named child here (this helper returns `false`); in Python the
// guard is an `if_clause` sibling on the enclosing `case_clause`,
// so the caller must check the surrounding node separately.
pub(crate) fn pattern_is_bare_underscore(pat: &Node, underscore_id: u16) -> bool {
    let mut found_underscore = false;
    for child in pat.children() {
        if child.kind_id() == underscore_id {
            if found_underscore {
                return false;
            }
            found_underscore = true;
        } else if child.is_named() {
            return false;
        }
        // else: anonymous non-`_` token (like `|`) — skip.
    }
    found_underscore
}

// Returns `true` iff a Python `case_clause` should count as a
// non-trivial decision: either the pattern is not a bare `_`, or
// the clause carries an `if`-guard (`case _ if g:`).
//
// Shared between the `Cyclomatic` and `Abc` implementations for
// `PythonCode`. The bare wildcard without a guard is Python's
// `default:`-equivalent and is filtered out, matching Rust's bare-`_`
// MatchArm rule and Java/C#'s `default:` rule.
//
// `underscore_id` is the grammar's `Python::UNDERSCORE` kind id,
// passed in so the helper does not assume a particular module-path
// to the language enum.
pub(crate) fn python_case_clause_counts(node: &Node, underscore_id: u16) -> bool {
    let mut bare_underscore = false;
    for child in node.children() {
        match child.kind_id().into() {
            Python::IfClause => return true,
            Python::CasePattern => {
                bare_underscore = pattern_is_bare_underscore(&child, underscore_id);
                if !bare_underscore {
                    return true;
                }
            }
            _ => {}
        }
    }
    !bare_underscore
}

// Returns true if `node`'s first child is a `visibility_modifier`
// containing the `pub` keyword. Matches Rust's "public-only-when-`pub`"
// model — `pub(crate)` / `pub(super)` / `pub(in path)` are also
// `visibility_modifier` and count as public for ABC purposes
// (`pub(crate)` is still "public to its crate"); only the absence of
// `pub` means private.
pub(crate) fn rust_item_is_public(node: &Node) -> bool {
    node.children()
        .any(|c| c.kind_id() == Rust::VisibilityModifier)
}

// Returns the `Block2` body child of a `ClassDefinition` if present.
// `ClassDefinition` children are: `class` keyword, identifier,
// optional type-parameters, optional argument-list (base classes),
// `:`, `Block2`. The body is always the final child.
fn python_class_body<'a>(class_def: &Node<'a>) -> Option<Node<'a>> {
    class_def.children().find(|c| c.kind_id() == Python::Block2)
}

// Counts class-level attribute assignments: direct
// `ExpressionStatement` children of the class body whose contained
// `Assignment` carries an `=` token (excluding bare type-only
// annotations like `x: int`, which parse as `Assignment` without an
// `=` — these declare a type but bind nothing and are not counted as
// attributes).
fn python_count_class_level_attrs(body: &Node) -> usize {
    use Python::*;

    let mut count = 0_usize;
    for stmt in body.children() {
        if stmt.kind_id() != ExpressionStatement {
            continue;
        }
        for child in stmt.children() {
            if child.kind_id() == Assignment && child.first_child(|id| id == EQ).is_some() {
                count += 1;
            }
        }
    }
    count
}

// Like `python_count_self_assignments` but deduplicates by the
// attribute identifier text. Walks every method body once and
// collects the set of unique `self.<attr>` names; the count is the
// size of that set. Fixes #215 — re-binding `self.x` across methods
// or across branches no longer inflates the attribute count.
//
// Capacity hint: typical Python classes declare under a dozen
// instance attributes (often documented as a class-level
// `__slots__`); `with_capacity(8)` covers the common case without
// any rehash and costs negligibly when a class has fewer.
fn python_count_unique_self_attrs(body: &Node, code: &[u8]) -> usize {
    let mut seen: std::collections::HashSet<&[u8]> = std::collections::HashSet::with_capacity(8);
    for stmt in body.children() {
        if let Some(func) = python_unwrap_function(&stmt) {
            python_collect_self_attrs_in_subtree(&func, code, &mut seen);
        }
    }
    seen.len()
}

fn python_collect_self_attrs_in_subtree<'a>(
    root: &Node<'a>,
    code: &'a [u8],
    seen: &mut std::collections::HashSet<&'a [u8]>,
) {
    use Python::*;

    let mut stack: Vec<Node<'a>> = Vec::with_capacity(32);
    for child in root.children() {
        stack.push(child);
    }
    while let Some(node) = stack.pop() {
        // Boundary: do not descend into nested classes, functions, or
        // lambdas. Their attributes belong to their inner scope.
        if matches!(
            node.kind_id().into(),
            FunctionDefinition | ClassDefinition | DecoratedDefinition | Lambda
        ) {
            continue;
        }

        if node.kind_id() == Assignment
            && python_lhs_is_self_attribute(&node)
            && let Some(name) = python_self_attr_name_bytes(&node, code)
        {
            seen.insert(name);
        }

        for child in node.children() {
            stack.push(child);
        }
    }
}

// Returns the byte slice for the attribute identifier in a
// `self.<attr> = …` assignment. The LHS is an `Attribute` node whose
// last named child is the attribute identifier (the `.` and the
// preceding `self` are siblings; the identifier comes last).
// Borrows directly from `code` so the returned slice is the
// canonical key for deduplication — two `self.value` assignments
// share the same identifier text and therefore the same key.
fn python_self_attr_name_bytes<'a>(assignment: &Node<'a>, code: &'a [u8]) -> Option<&'a [u8]> {
    // Fully-qualified `Python::Attribute` / `Python::Identifier` — this
    // function deliberately does NOT `use Python::*;` so unqualified
    // `None` keeps its `Option` meaning rather than being shadowed by
    // the `Python::None` token kind.
    let target = assignment.child(0)?;
    if target.kind_id() != Python::Attribute {
        return None;
    }
    // The grammar guarantees the trailing identifier is the last
    // `Identifier` child of the Attribute node; `.last()` walks the
    // children once and yields the right one.
    let id = target
        .children()
        .filter(|c| c.kind_id() == Python::Identifier)
        .last()?;
    // First `Identifier` was the receiver (`self`); only count when
    // we have a distinct second Identifier (the attribute name).
    let receiver = target.child(0)?;
    if id.start_byte() == receiver.start_byte() {
        return None;
    }
    code.get(id.start_byte()..id.end_byte())
}

fn python_unwrap_function<'a>(node: &Node<'a>) -> Option<Node<'a>> {
    // Use fully-qualified names here: `use Python::*` would shadow
    // `Option::None` with `Python::None` and break the last arm.
    match node.kind_id().into() {
        Python::FunctionDefinition => Some(*node),
        Python::DecoratedDefinition => node
            .children()
            .find(|c| c.kind_id() == Python::FunctionDefinition),
        _ => None,
    }
}

// Checks whether the LHS of an `Assignment` is `self.<identifier>`.
// `Assignment` children are: target, optional `:` + type, `=`, value.
// The target is the first child; for `self.x` it parses as an
// `Attribute` node with three children: identifier "self", `.`, and
// the attribute identifier. We cannot read the "self" text without
// source bytes, so we use the structural shape (Attribute whose
// first child is an Identifier) as a robust proxy. Standard Python
// style binds instance attributes via the *only* available alias
// inside a method body — the first parameter, conventionally called
// `self` — so the structural check is a safe under-approximation:
// it captures `self.x`, `this.x`, `cls.x` (i.e. classmethod alias),
// and any user-renamed first parameter alike. All three are
// idiomatic forms of "instance / class attribute assignment".
fn python_lhs_is_self_attribute(assignment: &Node) -> bool {
    use Python::*;

    let Some(target) = assignment.child(0) else {
        return false;
    };
    if target.kind_id() != Attribute {
        return false;
    }
    target.child(0).is_some_and(|c| c.kind_id() == Identifier)
}

// Kotlin's grammar models classes and interfaces under a single
// `class_declaration` node; the `class` / `interface` keyword child
// disambiguates. A `ClassBody` belongs to an interface iff its parent
// `class_declaration` has an `interface` keyword child.
pub(crate) fn kotlin_class_body_is_interface(class_body: &Node) -> bool {
    class_body.parent().is_some_and(|p| {
        matches!(p.kind_id().into(), Kotlin::ClassDeclaration)
            && p.first_child(|id| id == Kotlin::Interface).is_some()
    })
}

// Counts how many `VariableDeclaration`s a Kotlin `PropertyDeclaration`
// introduces. Kotlin allows destructuring (`val (a, b) = pair`) via
// `MultiVariableDeclaration`; each leaf binding counts as one attribute.
// Empty multi-variable destructurings cannot occur in well-formed Kotlin,
// but a defensive `.max(1)` keeps `property_declaration` at ≥1 attribute
// (matches the C# accessor-counting fallback).
fn kotlin_count_property_attrs(decl: &Node) -> usize {
    use Kotlin::*;
    decl.children()
        .map(|c| match c.kind_id().into() {
            VariableDeclaration => 1,
            MultiVariableDeclaration => c
                .children()
                .filter(|n| matches!(n.kind_id().into(), VariableDeclaration))
                .count(),
            _ => 0,
        })
        .sum::<usize>()
        .max(1)
}

// Kotlin's default visibility is `public`. A declaration is non-public
// only when it carries an explicit `private` / `protected` / `internal`
// modifier under its `Modifiers` child. Returns `true` for missing
// `Modifiers`, missing `VisibilityModifier`, or an explicit `public`
// modifier.
pub(crate) fn kotlin_is_public(decl: &Node) -> bool {
    let Some(modifiers) = decl.first_child(|id| id == Kotlin::Modifiers) else {
        return true;
    };
    let Some(visibility) = modifiers.first_child(|id| id == Kotlin::VisibilityModifier) else {
        return true;
    };
    // The visibility modifier holds exactly one keyword child; absence or
    // an explicit `public` both mean public.
    visibility
        .first_child(|id| {
            matches!(
                id.into(),
                Kotlin::Private | Kotlin::Protected | Kotlin::Internal
            )
        })
        .is_none()
}

impl Npa for KotlinCode {
    fn compute<'a>(node: &Node<'a>, _code: &'a [u8], stats: &mut Stats) {
        use Kotlin::*;

        // Enables the `Npa` metric for both class and interface spaces
        // (and `object` singletons, which `Getter` reports as `Class`).
        if Self::is_func_space(node) && stats.is_disabled() {
            stats.is_class_space = true;
        }

        match node.kind_id().into() {
            // A `ClassParameter` carrying `val` / `var` is a Kotlin
            // primary-constructor parameter property — counts once toward
            // the enclosing class. Parameters without `val`/`var` are plain
            // constructor arguments, not attributes.
            ClassParameter
                if node
                    .children()
                    .any(|c| matches!(c.kind_id().into(), Val | Var)) =>
            {
                stats.class_na += 1;
                if kotlin_is_public(node) {
                    stats.class_npa += 1;
                }
            }
            // Every `ClassBody` we visit attributes its direct
            // `property_declaration` children to whichever func_space is
            // currently on the state stack. Companion objects are not
            // func_spaces, so companion `val`/`var` declarations land on
            // the enclosing class — matching Kotlin's "static members"
            // semantics. Nested class / interface bodies start a new
            // func_space (handled by `spaces.rs`), so they do NOT leak
            // attributes into their outer space.
            ClassBody => {
                let is_interface = kotlin_class_body_is_interface(node);
                // tree-sitter-kotlin elides the `class_member_declaration`
                // and `declaration` rule layers when those rules are pure
                // forwarding choices, so property declarations appear as
                // direct children of `class_body`.
                for prop in node
                    .children()
                    .filter(|c| matches!(c.kind_id().into(), PropertyDeclaration))
                {
                    let attrs = kotlin_count_property_attrs(&prop);
                    if is_interface {
                        stats.interface_na += attrs;
                        // Interface members are always public.
                        stats.interface_npa += attrs;
                    } else {
                        stats.class_na += attrs;
                        if kotlin_is_public(&prop) {
                            stats.class_npa += attrs;
                        }
                    }
                }
            }
            _ => {}
        }
    }
}

// TypeScript / TSX share the same OOP node shape: `class_declaration`
// and `abstract_class_declaration` both contain a `class_body`;
// `interface_declaration` contains an `interface_body`. The
// `ts_npa_compute!` macro expands the same compute logic for each enum,
// so TS and TSX cannot drift.
//
// Visibility rule: a `public_field_definition` or `method_definition`
// is considered public unless it carries an explicit
// `accessibility_modifier` child whose only child is `private` or
// `protected`. Default (no modifier) is public, matching TypeScript's
// own semantics.
//
// Parameter properties (`constructor(private x: number)`) are class
// attributes: each `required_parameter` carrying an
// `accessibility_modifier` adds one to the enclosing class's `na`
// (and to `npa` when the modifier is `public` or absent). The
// grammar allows accessibility modifiers on parameters of any
// `method_definition`, not only `constructor` — TypeScript itself
// rejects that at type-check time, but accepting any method here
// avoids fragile name-matching against the `constructor` identifier
// (the grammar does not expose a dedicated constructor token).
//
// Interface decision: `property_signature` children of
// `interface_body` count toward `interface_npa` / `interface_na`.
// All interface members are implicitly public (TypeScript spec).
// `index_signature` and `method_signature` are NOT attributes — they
// belong to `npm`.
macro_rules! ts_npa_compute {
    ($lang:ident) => {
        fn compute<'a>(node: &Node<'a>, _code: &'a [u8], stats: &mut Stats) {
            use $lang::*;

            if Self::is_func_space(node) && stats.is_disabled() {
                stats.is_class_space = true;
            }

            match node.kind_id().into() {
                ClassBody => {
                    for member in node.children() {
                        match member.kind_id().into() {
                            // Plain field declaration (`x: T = expr;`, `private x: T;`,
                            // `static x: T = expr;`). Each is one attribute.
                            // Skip fields whose initializer is an arrow function or
                            // function expression — those are methods written as
                            // field initializers and are counted by `npm` instead.
                            PublicFieldDefinition
                                if member
                                    .first_child(|id| {
                                        id == $lang::ArrowFunction
                                            || id == $lang::FunctionExpression
                                    })
                                    .is_none() =>
                            {
                                stats.class_na += 1;
                                if ts_member_is_public!($lang, member) {
                                    stats.class_npa += 1;
                                }
                            }
                            // Parameter properties on any `method_definition`. In
                            // practice these only appear on the constructor.
                            // Scan formal_parameters at the class-body level so
                            // the attribute lands on the class space, not the
                            // method's own function space.
                            MethodDefinition => {
                                let Some(params) =
                                    member.first_child(|id| id == $lang::FormalParameters)
                                else {
                                    continue;
                                };
                                for param in params.children().filter(|c| {
                                    matches!(
                                        c.kind_id().into(),
                                        RequiredParameter | RequiredParameter2
                                    )
                                }) {
                                    if param
                                        .first_child(|id| id == $lang::AccessibilityModifier)
                                        .is_some()
                                    {
                                        stats.class_na += 1;
                                        if ts_member_is_public!($lang, param) {
                                            stats.class_npa += 1;
                                        }
                                    }
                                }
                            }
                            _ => {}
                        }
                    }
                }
                InterfaceBody => {
                    let count = node
                        .children()
                        .filter(|c| matches!(c.kind_id().into(), PropertySignature))
                        .count();
                    stats.interface_na += count;
                    stats.interface_npa = stats.interface_na;
                }
                _ => {}
            }
        }
    };
}

// Class members are public unless they declare an explicit
// `accessibility_modifier` whose only child is `private` or `protected`.
// Missing modifier means public, matching TypeScript's spec. The helper
// is a macro rather than a generic function so both TS and TSX expand
// the same code against their own enum without a marker trait.
macro_rules! ts_member_is_public {
    ($lang:ident, $member:expr) => {{
        match $member.first_child(|id| id == $lang::AccessibilityModifier) {
            None => true,
            Some(m) => m
                .first_child(|id| id == $lang::Private || id == $lang::Protected)
                .is_none(),
        }
    }};
}
pub(crate) use ts_member_is_public;

impl Npa for TypescriptCode {
    ts_npa_compute!(Typescript);
}

impl Npa for TsxCode {
    ts_npa_compute!(Tsx);
}

// JavaScript / Mozjs share the same class vocabulary. JS has no
// `accessibility_modifier` — every class member is public, so each
// class field maps 1:1 to both `na` and `npa`.
//
// We count ES2022 class fields (`class Foo { x = 1; }`):
// `field_definition` direct children of `class_body`. Fields whose
// initializer is an `arrow_function` or `function_expression` are
// methods written as field initializers and belong to `Npm`, not
// `Npa`.
//
// Prototype-based attribute assignments (`Foo.prototype.x = 5;`)
// would also be legitimate JS attributes per Fenton's metric
// taxonomy, but detecting them requires matching the `prototype`
// property-identifier text. The `Npa::compute` trait signature
// does not carry source bytes, so prototype-shaped attributes are
// intentionally not counted by this impl. Modern ES2015+ class
// syntax — the dominant style — is unaffected; legacy prototype-
// only files under-report. A follow-up that widens the trait
// signature to `(node, code, stats)` would unlock prototype
// detection (see `Abc::compute` for the existing pattern).

macro_rules! js_npa_compute {
    ($lang:ident) => {
        fn compute<'a>(node: &Node<'a>, _code: &'a [u8], stats: &mut Stats) {
            use $lang::*;

            if Self::is_func_space(node) && stats.is_disabled() {
                stats.is_class_space = true;
            }

            if !matches!(node.kind_id().into(), ClassBody) {
                return;
            }

            for member in node.children() {
                if matches!(member.kind_id().into(), FieldDefinition)
                    && member
                        .first_child(|id| {
                            id == $lang::ArrowFunction || id == $lang::FunctionExpression
                        })
                        .is_none()
                {
                    stats.class_na += 1;
                    stats.class_npa += 1;
                }
            }
        }
    };
}

impl Npa for JavascriptCode {
    js_npa_compute!(Javascript);
}

impl Npa for MozjsCode {
    js_npa_compute!(Mozjs);
}

// Default no-op `Npa` impls. Audited in #188.
//
// Real defaults (no first-class class / OO grammar construct, so the
// metric is genuinely 0):
//   - PreprocCode, CcommentCode: no executable code.
//   - BashCode: shell has no class concept.
//   - PerlCode, LuaCode, TclCode: prototype / table / package-based
//     OO is convention-only, not a grammar construct the audit treats
//     as class-shaped.
// Elixir Npa is implemented below (#275).
implement_metric_trait!(
    Npa,
    PreprocCode,
    CcommentCode,
    PerlCode,
    BashCode,
    LuaCode,
    TclCode
);

// Elixir Npa (#275). `defmodule` is treated as a class via source-aware
// Checker dispatch; `defstruct` is its closest analog to a field-set
// declaration. When entering a `defmodule` Class space we look for a
// direct-child `defstruct` Call in the `do_block` and count its
// field arguments. Three syntactic forms are accepted, matching the
// Elixir docs (https://hexdocs.pm/elixir/Kernel.html#defstruct/1):
//
// - `defstruct [:a, :b]` — bracketed list of atoms.
// - `defstruct a: 1, b: 2` — bare keyword list (the most common form).
// - `defstruct [a: 1, b: 2]` — bracketed keyword list.
//
// All fields are counted as public (`class_npa`); Elixir struct fields
// have no Java-style visibility modifier and the runtime exposes every
// field via pattern matching and `Map.get/2`.
impl Npa for ElixirCode {
    fn compute<'a>(node: &Node<'a>, code: &'a [u8], stats: &mut Stats) {
        use crate::metrics::cognitive::{elixir_call_keyword, elixir_do_block_call_children};

        if !stats.is_disabled() || !Self::is_func_space_with_code(node, code) {
            return;
        }
        if !matches!(elixir_call_keyword(node, code), Some("defmodule")) {
            return;
        }

        stats.is_class_space = true;

        for stmt in elixir_do_block_call_children(node) {
            if matches!(elixir_call_keyword(&stmt, code), Some("defstruct")) {
                let fields = count_defstruct_fields(&stmt);
                stats.class_na += fields;
                stats.class_npa += fields;
            }
        }
    }
}

// Counts the field entries of an Elixir `defstruct` Call's arguments.
// `defstruct` accepts three syntactic forms:
//   * `defstruct [:a, :b]` — a `List` of atoms.
//   * `defstruct a: 1, b: 2` — a bare `Keywords` keyword list, which
//     in the tree-sitter-elixir grammar appears directly inside
//     `Arguments` without an extra wrapper.
//   * `defstruct [a: 1, b: 2]` — a `List` wrapping a `Keywords`.
// We descend through the `Arguments` / `List` / `Keywords` wrapper
// nodes (skipping the leading `target` Identifier that names the
// macro itself) and tally `Atom` leaves (bare-list form) and `Pair`s
// (keyword form). `defstruct nil` and an empty `defstruct` correctly
// return 0.
fn count_defstruct_fields(call: &Node) -> usize {
    use Elixir as E;

    // `Arguments` is the wrapper around the macro's positional
    // arguments. `List` is the bracketed form. Keyword pairs without
    // brackets appear directly inside `Arguments` (no `Keywords`
    // wrapper) in the tree-sitter-elixir grammar. The leading
    // `target` Identifier is never one of these kinds, so no
    // explicit target-skip filter is needed.
    call.children()
        .filter(|child| matches!(child.kind_id().into(), E::Arguments | E::List | E::Keywords))
        .map(|child| count_field_entries(&child))
        .sum()
}

fn count_field_entries(node: &Node) -> usize {
    use Elixir as E;

    node.children()
        .map(|child| match child.kind_id().into() {
            // Bare-list form (`defstruct [:a, :b]`): each atom is a
            // field. Keyword form (`defstruct a: 1, b: 2`): each
            // `Pair` is a field.
            E::Atom | E::QuotedAtom | E::Atom2 | E::Pair => 1,
            // A `List` or `Keywords` may wrap the entries one level
            // deeper (`defstruct [a: 1, b: 2]` puts a `List` inside
            // `Arguments`, which then contains a `Keywords`).
            E::List | E::Keywords => count_field_entries(&child),
            _ => 0,
        })
        .sum()
}

#[cfg(test)]
#[allow(
    clippy::float_cmp,
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::similar_names,
    clippy::doc_markdown,
    clippy::needless_raw_string_hashes,
    clippy::too_many_lines
)]
mod tests {
    use crate::tools::{assert_child_space_kind, check_func_space, check_metrics};

    use super::*;

    #[test]
    fn java_single_attributes() {
        check_metrics::<JavaParser>(
            "class X {
                public byte a;      // +1
                public short b;     // +1
                public int c;       // +1
                public long d;      // +1
                public float e;     // +1
                public double f;    // +1
                public boolean g;   // +1
                public char h;      // +1
                byte i;
                short j;
                int k;
                long l;
                float m;
                double n;
                boolean o;
                char p;
            }",
            "foo.java",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.npa,
                    @r###"
                    {
                      "classes": 8.0,
                      "interfaces": 0.0,
                      "class_attributes": 16.0,
                      "interface_attributes": 0.0,
                      "classes_average": 0.5,
                      "interfaces_average": null,
                      "total": 8.0,
                      "total_attributes": 16.0,
                      "average": 0.5
                    }"###
                );
            },
        );
    }

    #[test]
    fn java_multiple_attributes() {
        check_metrics::<JavaParser>(
            "class X {
                public byte a1;                 // +1
                public short b1, b2;            // +2
                public int c1, c2, c3;          // +3
                public long d1, d2, d3, d4;     // +4
                public float e1, e2, e3, e4;    // +4
                public double f1, f2, f3;       // +3
                public boolean g1, g2;          // +2
                public char h1;                 // +1
                byte i1, i2, i3, i4;
                short j1, j2, j3;
                int k1, k2;
                long l1;
                float m1;
                double n1, n2;
                boolean o1, o2, o3;
                char p1, p2, p3, p4;
            }",
            "foo.java",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.npa,
                    @r###"
                    {
                      "classes": 20.0,
                      "interfaces": 0.0,
                      "class_attributes": 40.0,
                      "interface_attributes": 0.0,
                      "classes_average": 0.5,
                      "interfaces_average": null,
                      "total": 20.0,
                      "total_attributes": 40.0,
                      "average": 0.5
                    }"###
                );
            },
        );
    }

    #[test]
    fn java_initialized_attributes() {
        check_metrics::<JavaParser>(
            "class X {
                public byte a1 = 1;                             // +1
                public short b1 = 2, b2;                        // +2
                public int c1, c2 = 3, c3;                      // +3
                public long d1 = 4, d2, d3, d4 = 5;             // +4
                public float e1, e2 = 6.0f, e3 = 7.0f, e4;      // +4
                public double f1 = 8.0, f2 = 9.0, f3 = 10.0;    // +3
                public boolean g1 = true, g2;                   // +2
                public char h1 = 'a';                           // +1
                byte i1 = 1, i2 = 2, i3 = 3, i4 = 4;
                short j1 = 5, j2, j3 = 6;
                int k1, k2 = 7;
                long l1 = 8;
                float m1 = 9.0f;
                double n1, n2 = 10.0;
                boolean o1, o2 = false, o3;
                char p1 = 'a', p2 = 'b', p3 = 'c', p4 = 'd';
            }",
            "foo.java",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.npa,
                    @r###"
                    {
                      "classes": 20.0,
                      "interfaces": 0.0,
                      "class_attributes": 40.0,
                      "interface_attributes": 0.0,
                      "classes_average": 0.5,
                      "interfaces_average": null,
                      "total": 20.0,
                      "total_attributes": 40.0,
                      "average": 0.5
                    }"###
                );
            },
        );
    }

    #[test]
    fn java_array_attributes() {
        check_metrics::<JavaParser>(
            "class X {
                public byte[] a1, a2, a3, a4;                       // +4
                public short b1[], b2[], b3[];                      // +3
                public int[] c1 = { 1 }, c2;                        // +2
                public long d1[] = { 1 };                           // +1
                public float[] e1 = { 1.0f, 2.0f, 3.0f };           // +1
                public double f1[] = { 1.0, 2.0, 3.0 }, f2[];       // +2
                public boolean[] g1 = new boolean[5], g2, g3;       // +3
                public char[] h1 = new char[5], h2[], h3[], h4[];   // +4
                byte[] i1;
                short j1[], j2[];
                int[] k1, k2, k3 = { 1 };
                long l1[], l2[] = { 1 }, l3[] = { 2 }, l4[];
                float[] m1, m2, m3, m4 = { 1.0f, 2.0f, 3.0f };
                double n1[], n2[] = { 1.0, 2.0, 3.0 }, n3[];
                boolean[] o1, o2 = new boolean[5];
                char[] p1 = new char[5];
            }",
            "foo.java",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.npa,
                    @r###"
                    {
                      "classes": 20.0,
                      "interfaces": 0.0,
                      "class_attributes": 40.0,
                      "interface_attributes": 0.0,
                      "classes_average": 0.5,
                      "interfaces_average": null,
                      "total": 20.0,
                      "total_attributes": 40.0,
                      "average": 0.5
                    }"###
                );
            },
        );
    }

    #[test]
    fn java_object_attributes() {
        check_metrics::<JavaParser>(
            "class X {
                public Integer[] a1 = { 1 };                                    // +1
                public Integer b1, b2;                                          // +2
                public String[] c1 = { \"Hello\" }, c2, c3 = { \"World!\" };    // +3
                public String d1[][] = { { \"Hello\" }, { \"World!\" } };       // +1
                public Y[] e1, e2[];                                            // +2
                public Y f1[], f2[][], f3[][][];                                // +3
                Integer[] g1 = { new Integer(1) };
                Integer h1 = new Integer(1), h2 = new Integer(2);
                String[] i1, i2 = { \"Hello World!\" }, i3;
                String j1 = \"Hello World!\";
                Y[] k1[], k2;
                Y l1[][], l2[], l3 = new Y();
            }",
            "foo.java",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.npa,
                    @r###"
                    {
                      "classes": 12.0,
                      "interfaces": 0.0,
                      "class_attributes": 24.0,
                      "interface_attributes": 0.0,
                      "classes_average": 0.5,
                      "interfaces_average": null,
                      "total": 12.0,
                      "total_attributes": 24.0,
                      "average": 0.5
                    }"###
                );
            },
        );
    }

    #[test]
    fn groovy_no_attributes() {
        check_metrics::<GroovyParser>("class A { void foo() {} }", "foo.groovy", |metric| {
            assert_eq!(metric.npa.total_na(), 0.0);
            assert_eq!(metric.npa.total_npa(), 0.0);
        });
    }

    #[test]
    fn groovy_public_attributes() {
        check_metrics::<GroovyParser>(
            "class A {
                public int x
                public String name
                private int hidden
            }",
            "foo.groovy",
            |metric| {
                // 3 total attributes, 2 public
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
            },
        );
    }

    #[test]
    fn groovy_def_attributes_not_public() {
        // `def field` at class scope is a FieldDeclaration whose
        // modifier list contains `Def`, not `Public`. Mirror Java's
        // semantics: only explicit `public` is counted.
        check_metrics::<GroovyParser>(
            "class A {
                def field1
                def field2
            }",
            "foo.groovy",
            |metric| {
                // Both `def` fields parse as FieldDeclarations.
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                assert_eq!(metric.npa.class_npa_sum(), 0.0);
            },
        );
    }

    #[test]
    fn groovy_interface_attributes() {
        // Structural `assert_child_space_kind` guards against an
        // `InterfaceDeclaration` revert in `GroovyCode::is_func_space`
        // — see #311.
        check_func_space::<GroovyParser, _>(
            "interface I {
                public static final int A = 1
                public static final int B = 2
            }",
            "foo.groovy",
            |func_space| {
                let metric = &func_space.metrics;
                // Interface fields are implicitly public+static+final.
                assert_eq!(metric.npa.interface_na_sum(), 2.0);
                assert_eq!(metric.npa.interface_npa_sum(), 2.0);
                assert_child_space_kind(&func_space, "I", SpaceKind::Interface);
            },
        );
    }

    #[test]
    fn groovy_no_attributes_in_unit_scope() {
        check_metrics::<GroovyParser>("int x = 1", "foo.groovy", |metric| {
            assert_eq!(metric.npa.total_na(), 0.0);
        });
    }

    #[test]
    fn groovy_multiple_classes() {
        check_metrics::<GroovyParser>(
            "class A { public int a }
            class B { public int b }",
            "foo.groovy",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
            },
        );
    }

    #[test]
    fn groovy_initialized_attributes() {
        // Mirror of `java_initialized_attributes`: each
        // `variable_declarator` inside a `field_declaration` counts
        // as one attribute, with or without an initializer; `public`
        // modifier promotes them all to NPA.
        check_metrics::<GroovyParser>(
            "class X {
                public int a1 = 1, a2
                public int b1 = 2
                int c1, c2 = 3
            }",
            "foo.groovy",
            |metric| {
                // 5 attributes total, 3 public.
                assert_eq!(metric.npa.class_na_sum(), 5.0);
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
            },
        );
    }

    #[test]
    fn groovy_object_attributes() {
        // Object-typed attributes (boxed primitives, user types,
        // String, arrays). Each declarator is one attribute.
        check_metrics::<GroovyParser>(
            "class X {
                public Integer a1
                public String b1 = 'hello'
                public Y[] c1
            }",
            "foo.groovy",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
            },
        );
    }

    #[test]
    fn groovy_attribute_modifiers() {
        // Multiple modifier orderings (public/static/final/transient/
        // volatile etc.) must all be detected — what matters for NPA
        // is whether the `Modifiers` block contains `Public`.
        check_metrics::<GroovyParser>(
            "class X {
                public static int a
                static public int b
                public final int c = 1
                final public int d = 2
                private static int e
                int f
            }",
            "foo.groovy",
            |metric| {
                // 6 attributes total, 4 public (regardless of order).
                assert_eq!(metric.npa.class_na_sum(), 6.0);
                assert_eq!(metric.npa.class_npa_sum(), 4.0);
            },
        );
    }

    #[test]
    #[ignore = "dekobon Groovy grammar v1 does not yet support inner classes inside class bodies (https://github.com/dekobon/tree-sitter-groovy SPECIFICATION.md §4 — 'Field declarations, static initialisers, and inner classes land later')"]
    fn groovy_nested_inner_classes() {
        // Each nested `class` declaration is its own class space
        // with its own NPA. Mirrors `java_nested_inner_classes`.
        check_metrics::<GroovyParser>(
            "class X {
                public int a
                class Y {
                    public boolean b
                    class Z {
                        public char c
                    }
                }
            }",
            "foo.groovy",
            |metric| {
                // 3 classes, 3 public attributes.
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
            },
        );
    }

    #[test]
    fn groovy_array_attributes() {
        // Array-typed attributes. Mirrors `java_array_attributes`.
        check_metrics::<GroovyParser>(
            "class X {
                public int[] a
                public String[] b
                int[] c
            }",
            "foo.groovy",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
            },
        );
    }

    #[test]
    fn groovy_anonymous_inner_class() {
        // Object-creation expression containing a `class_body` —
        // anonymous inner class. Its attributes are counted in a
        // separate class space.
        check_metrics::<GroovyParser>(
            "class X {
                public Runnable r = new Runnable() {
                    public int x
                    void run() {}
                }
            }",
            "foo.groovy",
            |metric| {
                // outer X has 1 public attr `r`; inner anonymous
                // has 1 public attr `x` => total 2.
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
            },
        );
    }

    // Regression for issue #280: Groovy mirrors Java's enum / record /
    // annotation handling. Record support in the dekobon Groovy grammar
    // lags behind groovyc, but the grammar exposes `record_declaration`
    // and the `Npa` body walker treats it identically.
    #[test]
    fn groovy_enum_counts_explicit_public_fields() {
        check_metrics::<GroovyParser>(
            "enum Status {
                ACTIVE, INACTIVE;
                public int code;
                private int hidden;
            }",
            "foo.groovy",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
            },
        );
    }

    #[test]
    fn groovy_annotation_type_counts_constants_as_implicit_public() {
        // The dekobon Groovy grammar parses `@interface` like Java
        // (modifier required, statements terminated with `;`). Mirror of
        // `java_annotation_type_counts_constants_as_implicit_public`
        // — the body-walker count is identical whether or not
        // Groovy's `AnnotationTypeDeclaration` is wired into
        // `is_func_space`, so the structural `check_func_space`
        // assertion is what catches a revert.
        check_func_space::<GroovyParser, _>(
            "public @interface Marker {
                int VERSION = 1;
                String NAME = \"x\";
            }",
            "foo.groovy",
            |func_space| {
                assert_eq!(func_space.metrics.npa.interface_na_sum(), 2.0);
                assert_eq!(func_space.metrics.npa.interface_npa_sum(), 2.0);
                assert_child_space_kind(&func_space, "Marker", SpaceKind::Interface);
            },
        );
    }

    #[test]
    fn java_generic_attributes() {
        check_metrics::<JavaParser>(
            "class X<T, S extends T> {
                public T a1;                            // +1
                public Entry<T, S> b1, b2[];            // +2
                public ArrayList<T> c1, c2, c3;         // +3
                public HashMap<Long, Double> d1, d2;    // +2
                public TreeSet<String> e1;              // +1
                S f1;
                Entry<S, T> g1[], g2;
                ArrayList<S> h1, h2, h3;
                HashMap<Long, Float> i1, i2;
                TreeSet<Entry<S, T>> j1;
            }",
            "foo.java",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.npa,
                    @r###"
                    {
                      "classes": 9.0,
                      "interfaces": 0.0,
                      "class_attributes": 18.0,
                      "interface_attributes": 0.0,
                      "classes_average": 0.5,
                      "interfaces_average": null,
                      "total": 9.0,
                      "total_attributes": 18.0,
                      "average": 0.5
                    }"###
                );
            },
        );
    }

    #[test]
    fn java_attribute_modifiers() {
        check_metrics::<JavaParser>(
            "class X {
                public transient volatile static int a;     // +1
                transient public volatile static int b;     // +1
                transient volatile public static int c;     // +1
                transient volatile static public int d;     // +1
                public transient static final int e = 1;    // +1
                transient public static final int f = 2;    // +1
                transient static public final int g = 3;    // +1
                transient static final public int h = 4;    // +1
                protected transient volatile static int i;
                transient volatile static protected int j;
                private transient volatile static int k;
                transient volatile static private int l;
                transient volatile static int m;
                transient static final int n = 5;
                static public final int o = 6;              // +1
                final public int p = 7;                     // +1
            }",
            "foo.java",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.npa,
                    @r###"
                    {
                      "classes": 10.0,
                      "interfaces": 0.0,
                      "class_attributes": 16.0,
                      "interface_attributes": 0.0,
                      "classes_average": 0.625,
                      "interfaces_average": null,
                      "total": 10.0,
                      "total_attributes": 16.0,
                      "average": 0.625
                    }"###
                );
            },
        );
    }

    #[test]
    fn java_classes() {
        check_metrics::<JavaParser>(
            "class X {
                public int a;       // +1
                public boolean b;   // +1
                private char c;
            }
            class Y {
                private double d;
                private long e;
                public float f;      // +1
            }",
            "foo.java",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.npa,
                    @r###"
                    {
                      "classes": 3.0,
                      "interfaces": 0.0,
                      "class_attributes": 6.0,
                      "interface_attributes": 0.0,
                      "classes_average": 0.5,
                      "interfaces_average": null,
                      "total": 3.0,
                      "total_attributes": 6.0,
                      "average": 0.5
                    }"###
                );
            },
        );
    }

    #[test]
    fn java_nested_inner_classes() {
        check_metrics::<JavaParser>(
            "class X {
                public int a;           // +1
                class Y {
                    public boolean b;   // +1
                    class Z {
                        public char c;  // +1
                    }
                }
            }",
            "foo.java",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.npa,
                    @r###"
                    {
                      "classes": 3.0,
                      "interfaces": 0.0,
                      "class_attributes": 3.0,
                      "interface_attributes": 0.0,
                      "classes_average": 1.0,
                      "interfaces_average": null,
                      "total": 3.0,
                      "total_attributes": 3.0,
                      "average": 1.0
                    }"###
                );
            },
        );
    }

    #[test]
    fn java_local_inner_classes() {
        check_metrics::<JavaParser>(
            "class X {
                public int a;                   // +1
                void x() {
                    class Y {
                        public boolean b;       // +1
                        void y() {
                            class Z {
                                public char c;  // +1
                                void z() {}
                            }
                        }
                    }
                }
            }",
            "foo.java",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.npa,
                    @r###"
                    {
                      "classes": 3.0,
                      "interfaces": 0.0,
                      "class_attributes": 3.0,
                      "interface_attributes": 0.0,
                      "classes_average": 1.0,
                      "interfaces_average": null,
                      "total": 3.0,
                      "total_attributes": 3.0,
                      "average": 1.0
                    }"###
                );
            },
        );
    }

    #[test]
    fn java_anonymous_inner_classes() {
        check_metrics::<JavaParser>(
            "abstract class X {
                public int a;               // +1
            }
            abstract class Y {
                boolean b;
            }
            class Z {
                public char c;              // +1
                public void z(){
                    X x1 = new X() {
                        public double d;    // +1
                    };
                    Y y1 = new Y() {
                        long e;
                    };
                }
            }",
            "foo.java",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.npa,
                    @r###"
                    {
                      "classes": 3.0,
                      "interfaces": 0.0,
                      "class_attributes": 5.0,
                      "interface_attributes": 0.0,
                      "classes_average": 0.6,
                      "interfaces_average": null,
                      "total": 3.0,
                      "total_attributes": 5.0,
                      "average": 0.6
                    }"###
                );
            },
        );
    }

    #[test]
    fn java_interface() {
        check_metrics::<JavaParser>(
            "interface X {
                public int a = 0;           // +1
                static boolean b = false;   // +1
                final char c = ' ';         // +1
            }",
            "foo.java",
            |metric| {
                insta::assert_json_snapshot!(
                    metric.npa,
                    @r###"
                    {
                      "classes": 0.0,
                      "interfaces": 3.0,
                      "class_attributes": 0.0,
                      "interface_attributes": 3.0,
                      "classes_average": null,
                      "interfaces_average": 1.0,
                      "total": 3.0,
                      "total_attributes": 3.0,
                      "average": 1.0
                    }"###
                );
            },
        );
    }

    // Regression for issue #280: Java `EnumDeclaration` must be
    // classified as a class space so `Npa` walks its body and counts
    // explicit public fields declared after the enum constants.
    #[test]
    fn java_enum_counts_explicit_public_fields() {
        check_metrics::<JavaParser>(
            "enum Status {
                ACTIVE, INACTIVE;
                public static final int FLAG = 1;   // implicit static final, still public
                public int code;                    // +1 explicit public
                private int hidden;                 // not public
            }",
            "foo.java",
            |metric| {
                // 1 class space (the enum), 3 total fields, 2 explicit public.
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
            },
        );
    }

    // Regression for issue #280: Java `RecordDeclaration` reuses
    // `ClassBody` for its explicit body, so explicit fields declared
    // inside it count. Record components in the parameter list are
    // implicit public final fields at the bytecode level but are NOT
    // counted here, matching the C# precedent (only explicit body
    // members count).
    #[test]
    fn java_record_counts_explicit_body_fields() {
        check_metrics::<JavaParser>(
            "record Point(int x, int y) {
                public static int origin = 0;       // explicit body, public
                private int cached;                 // explicit body, private
            }",
            "foo.java",
            |metric| {
                // Only explicit body fields are counted; the `x` / `y`
                // record components are not.
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
            },
        );
    }

    #[test]
    fn java_annotation_type_counts_constants_as_implicit_public() {
        // Asserting only `interface_na_sum` / `interface_npa_sum`
        // would pass vacuously if `AnnotationTypeDeclaration` were
        // dropped from `JavaCode::is_func_space`: the body walker
        // counts annotation-type constants regardless of the
        // surrounding FuncSpace kind, so the file-level Unit would
        // still report 2.0 for both. The `check_func_space`
        // assertion catches that revert by requiring the annotation
        // type to actually open an `Interface` FuncSpace.
        check_func_space::<JavaParser, _>(
            "@interface Marker {
                int VERSION = 1;        // implicit public static final
                String NAME = \"x\";    // implicit public static final
            }",
            "foo.java",
            |func_space| {
                assert_eq!(func_space.metrics.npa.interface_na_sum(), 2.0);
                assert_eq!(func_space.metrics.npa.interface_npa_sum(), 2.0);
                assert_child_space_kind(&func_space, "Marker", SpaceKind::Interface);
            },
        );
    }

    #[test]
    fn php_no_class_attributes() {
        check_metrics::<PhpParser>(
            "<?php class A { public function f(): void {} }",
            "foo.php",
            |metric| insta::assert_json_snapshot!(metric.npa),
        );
    }

    #[test]
    fn csharp_single_attributes() {
        check_metrics::<CsharpParser>(
            "class X {
                public byte a;
                public short b;
                public int c;
                public long d;
                public float e;
                public double f;
                public bool g;
                public char h;
                byte i;
                short j;
                int k;
                long l;
                float m;
                double n;
                bool o;
                char p;
            }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 8.0);
                assert_eq!(metric.npa.class_na_sum(), 16.0);
                assert_eq!(metric.npa.interface_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn csharp_multiple_attributes() {
        check_metrics::<CsharpParser>(
            "class X {
                public byte a1;
                public short b1, b2;
                public int c1, c2, c3;
                public long d1, d2, d3, d4;
                public bool g1, g2;
                byte i1, i2, i3, i4;
                int k1, k2;
            }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 12.0);
                assert_eq!(metric.npa.class_na_sum(), 18.0);
                assert_eq!(metric.npa.interface_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn csharp_initialized_attributes() {
        check_metrics::<CsharpParser>(
            "class X {
                public int a = 1;
                public bool b = true;
                public string c = \"hello\";
                public double d = 3.14;
                int e = 0;
            }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 4.0);
                assert_eq!(metric.npa.class_na_sum(), 5.0);
                assert_eq!(metric.npa.interface_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn csharp_array_attributes() {
        check_metrics::<CsharpParser>(
            "class X {
                public int[] a;
                public string[] b = new string[5];
                int[] c;
            }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.interface_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn csharp_object_attributes() {
        check_metrics::<CsharpParser>(
            "class Point { public int X, Y; }
             class Shape {
                public Point origin;
                public Point endpoint = new Point();
                Point hidden;
             }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 4.0);
                assert_eq!(metric.npa.class_na_sum(), 5.0);
                assert_eq!(metric.npa.interface_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn csharp_generic_attributes() {
        check_metrics::<CsharpParser>(
            "class X {
                public System.Collections.Generic.List<int> a;
                public System.Collections.Generic.Dictionary<string, int> b;
                System.Collections.Generic.List<string> c;
            }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.interface_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn csharp_attribute_modifiers() {
        check_metrics::<CsharpParser>(
            "class X {
                public int a;
                private int b;
                protected int c;
                internal int d;
                public static int e;
                public readonly int f;
                public const int g = 1;
            }",
            "foo.cs",
            |metric| {
                // Modifiers test: 4 of 7 fields are explicitly `public`. The
                // visibility-filter split is the spec.
                assert_eq!(metric.npa.class_npa_sum(), 4.0);
                assert_eq!(metric.npa.class_na_sum(), 7.0);
                assert_eq!(metric.npa.interface_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn csharp_classes() {
        check_metrics::<CsharpParser>(
            "class A {
                public int a;
                public int b;
                int c;
            }
            class B {
                public string s;
                int n;
            }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
                assert_eq!(metric.npa.class_na_sum(), 5.0);
                assert_eq!(metric.npa.interface_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn csharp_nested_inner_classes() {
        check_metrics::<CsharpParser>(
            "class Outer {
                public int a;
                int b;
                public class Inner {
                    public string s;
                    int n;
                }
            }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 4.0);
                assert_eq!(metric.npa.interface_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn csharp_struct_attributes() {
        // C#-only: structs declare fields like classes; visibility rule
        // applies the same way (default is private).
        check_metrics::<CsharpParser>(
            "struct Point {
                public int X;
                public int Y;
                int Hidden;
            }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.interface_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn csharp_record_attributes() {
        // C#-only: records can declare body fields just like classes.
        // Positional record properties are not modelled (EC9).
        check_metrics::<CsharpParser>(
            "record Person {
                public string Name;
                int Age;
            }",
            "foo.cs",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                assert_eq!(metric.npa.interface_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn csharp_interface() {
        // EC14 — interface members default to public; all fields count.
        // Structural `assert_child_space_kind` guards against an
        // `InterfaceDeclaration` revert in `CsharpCode::is_func_space`
        // — see #311.
        check_func_space::<CsharpParser, _>(
            "interface I {
                static int A = 1;
                static string B = \"hello\";
            }",
            "foo.cs",
            |func_space| {
                let metric = &func_space.metrics;
                assert_eq!(metric.npa.class_na_sum(), 0.0);
                assert_eq!(metric.npa.interface_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
                assert_child_space_kind(&func_space, "I", SpaceKind::Interface);
            },
        );
    }

    #[test]
    fn php_one_public_attribute() {
        check_metrics::<PhpParser>(
            "<?php class A { public int $x = 0; }",
            "foo.php",
            |metric| insta::assert_json_snapshot!(metric.npa),
        );
    }

    #[test]
    fn php_one_private_attribute() {
        check_metrics::<PhpParser>(
            "<?php class A { private int $x = 0; }",
            "foo.php",
            |metric| insta::assert_json_snapshot!(metric.npa),
        );
    }

    #[test]
    fn php_one_protected_attribute() {
        check_metrics::<PhpParser>(
            "<?php class A { protected int $x = 0; }",
            "foo.php",
            |metric| insta::assert_json_snapshot!(metric.npa),
        );
    }

    #[test]
    fn php_mixed_visibility_attributes() {
        check_metrics::<PhpParser>(
            "<?php
            class A {
                public int $a = 0;
                public int $b = 0;
                private int $c = 0;
                protected int $d = 0;
            }",
            "foo.php",
            |metric| insta::assert_json_snapshot!(metric.npa),
        );
    }

    #[test]
    fn php_static_public_attribute() {
        check_metrics::<PhpParser>(
            "<?php class A { public static int $x = 0; }",
            "foo.php",
            |metric| insta::assert_json_snapshot!(metric.npa),
        );
    }

    #[test]
    fn php_readonly_public_attribute() {
        check_metrics::<PhpParser>(
            "<?php class A { public readonly int $x; }",
            "foo.php",
            |metric| insta::assert_json_snapshot!(metric.npa),
        );
    }

    #[test]
    fn php_multiple_attributes_per_declaration() {
        // A single property_declaration can declare several
        // property_elements; each counts.
        check_metrics::<PhpParser>(
            "<?php class A { public int $a = 0, $b = 0, $c = 0; }",
            "foo.php",
            |metric| insta::assert_json_snapshot!(metric.npa),
        );
    }

    #[test]
    fn php_interface_constants() {
        // Interface constants are implicitly public.
        check_metrics::<PhpParser>(
            "<?php
            interface I {
                const A = 1;
                const B = 2;
            }",
            "foo.php",
            |metric| insta::assert_json_snapshot!(metric.npa),
        );
    }

    #[test]
    fn php_enum_cases() {
        // Enum cases are public read-only constants.
        check_metrics::<PhpParser>(
            "<?php
            enum Color {
                case Red;
                case Green;
                case Blue;
            }",
            "foo.php",
            |metric| insta::assert_json_snapshot!(metric.npa),
        );
    }

    #[test]
    fn php_trait_attributes() {
        check_metrics::<PhpParser>(
            "<?php
            trait T {
                public int $a = 0;
                private int $b = 0;
            }",
            "foo.php",
            |metric| insta::assert_json_snapshot!(metric.npa),
        );
    }

    #[test]
    fn php_no_explicit_visibility_excluded() {
        // PHP 8.x deprecates implicit-public for properties; we follow
        // Java's strict-explicit rule and do NOT count properties without
        // an explicit `public` modifier.
        check_metrics::<PhpParser>("<?php class A { var $x = 0; }", "foo.php", |metric| {
            // The property is excluded from the public-count (npa) because
            // `var` is not an explicit `public` modifier, but still
            // contributes to the total-count (na). This split is the spec.
            assert_eq!(metric.npa.class_npa_sum(), 0.0);
            assert_eq!(metric.npa.class_na_sum(), 1.0);
            assert_eq!(metric.npa.interface_na_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn php_anonymous_class_attributes() {
        // Anonymous classes have their own DeclarationList space and
        // their public properties count. The Npa impl branches on
        // `parent_kind == AnonymousClass` and this test exercises that
        // arm.
        check_metrics::<PhpParser>(
            "<?php
            $obj = new class {
                public int $a = 0;
                private int $b = 0;
            };",
            "foo.php",
            |metric| insta::assert_json_snapshot!(metric.npa),
        );
    }

    #[test]
    fn php_property_promotion_excluded() {
        // Constructor property promotion (PHP 8.0+) declares both a
        // parameter AND a property in one syntax. The promoted property
        // lives under `formal_parameters`, NOT under
        // `declaration_list`, so the current Npa impl naturally
        // excludes it. This is a documented limitation; this test
        // pins the behavior so a future change that starts counting
        // promoted properties has to update the test deliberately.
        check_metrics::<PhpParser>(
            "<?php
            class A {
                public function __construct(public string $x, public int $y) {}
            }",
            "foo.php",
            |metric| insta::assert_json_snapshot!(metric.npa),
        );
    }

    // --- Kotlin NPA tests -------------------------------------------------
    //
    // Reference: Kotlin properties (`val` / `var`) declared inside a class
    // body are attributes. Default visibility is `public`. Primary
    // constructor parameters carrying `val` / `var` are parameter
    // properties and count. Companion-object members fold into the
    // enclosing class. Top-level properties belong to the `Unit` space
    // and are excluded.

    #[test]
    fn kotlin_empty_class_no_attributes() {
        check_metrics::<KotlinParser>("class C {}", "foo.kt", |metric| {
            assert_eq!(metric.npa.class_npa_sum(), 0.0);
            assert_eq!(metric.npa.class_na_sum(), 0.0);
            assert_eq!(metric.npa.interface_na_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn kotlin_public_val_var_default() {
        // Kotlin's default visibility is public — no modifier means public.
        check_metrics::<KotlinParser>(
            "class C {
                val a: Int = 1
                var b: Int = 2
                val c: String = \"hi\"
            }",
            "foo.kt",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn kotlin_private_val_var() {
        // Private properties contribute to total `na` but not to `npa`.
        check_metrics::<KotlinParser>(
            "class C {
                val a: Int = 1               // public
                private val b: Int = 2       // not public
                var c: Int = 3               // public
                private var d: Int = 4       // not public
            }",
            "foo.kt",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 4.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn kotlin_protected_internal_excluded_from_public() {
        check_metrics::<KotlinParser>(
            "open class C {
                protected val a: Int = 1
                internal val b: Int = 2
                public val c: Int = 3        // explicit public
            }",
            "foo.kt",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn kotlin_primary_constructor_parameter_property() {
        // `val`/`var` on primary constructor parameters declares both a
        // parameter AND a property. Bare `name: Type` parameters are NOT
        // attributes.
        check_metrics::<KotlinParser>(
            "class C(val a: Int, var b: Int, c: Int) {
                val d: Int = c
            }",
            "foo.kt",
            |metric| {
                // a, b, d -> public; c -> not an attribute (no val/var)
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn kotlin_primary_constructor_private_param_property() {
        check_metrics::<KotlinParser>(
            "class C(private val a: Int, val b: Int)",
            "foo.kt",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn kotlin_secondary_constructor_does_not_add_attrs() {
        // Secondary constructors are methods, not attribute declarations.
        check_metrics::<KotlinParser>(
            "class C {
                private var a: Int = 0
                constructor(n: Int) { a = n }
            }",
            "foo.kt",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 0.0);
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn kotlin_companion_object_attributes() {
        // Companion-object properties fold into the enclosing class as
        // "static" attributes.
        check_metrics::<KotlinParser>(
            "class Holder {
                val instance: Int = 1
                companion object {
                    val SCALE: Int = 10
                    private val SECRET: Int = 7
                }
            }",
            "foo.kt",
            |metric| {
                // instance (public) + SCALE (public) = 2 public
                // SECRET counts toward total na but not npa
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn kotlin_data_class_attributes() {
        // `data class` parameters are the canonical positional attributes.
        check_metrics::<KotlinParser>(
            "data class Point(val x: Int, val y: Int)",
            "foo.kt",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn kotlin_object_singleton_attributes() {
        check_metrics::<KotlinParser>(
            "object Config {
                val DEFAULT: Int = 42
                private val SEED: Int = 0
                var debug: Boolean = false
            }",
            "foo.kt",
            |metric| {
                // DEFAULT, debug -> public; SEED -> not.
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn kotlin_interface_attributes() {
        // Interface members are implicitly public; all properties count
        // toward `interface_npa` and `interface_na`. Structural
        // `assert_child_space_kind` guards against an
        // `InterfaceDeclaration` revert in `KotlinCode::is_func_space`
        // — see #311.
        check_func_space::<KotlinParser, _>(
            "interface I {
                val a: Int
                val b: String
            }",
            "foo.kt",
            |func_space| {
                let metric = &func_space.metrics;
                assert_eq!(metric.npa.interface_npa_sum(), 2.0);
                assert_eq!(metric.npa.interface_na_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
                assert_child_space_kind(&func_space, "I", SpaceKind::Interface);
            },
        );
    }

    #[test]
    fn kotlin_nested_class_attributes() {
        // Each class space has its own attribute count; nested class
        // attributes do not leak into the outer class.
        check_metrics::<KotlinParser>(
            "class Outer {
                val o1: Int = 1
                class Nested {
                    val n1: Int = 1
                    val n2: Int = 2
                }
            }",
            "foo.kt",
            |metric| {
                // 2 classes total — Outer's 1 + Nested's 2 = 3 attributes
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn kotlin_inner_class_attributes() {
        check_metrics::<KotlinParser>(
            "class Outer {
                val o1: Int = 1
                inner class Inner {
                    val i1: Int = 1
                }
            }",
            "foo.kt",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn kotlin_top_level_properties_excluded() {
        // Top-level `val` belongs to `Unit`, not a class — must not
        // contribute to `class_na`.
        check_metrics::<KotlinParser>(
            "val topVal: Int = 0
            var topVar: Int = 1
            class C { val x: Int = 0 }",
            "foo.kt",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn kotlin_multiple_classes_attributes() {
        check_metrics::<KotlinParser>(
            "class A {
                val a1: Int = 0
                var a2: Int = 0
            }
            class B {
                val b1: Int = 0
                private val b2: Int = 0
            }",
            "foo.kt",
            |metric| {
                // A: 2 public; B: 1 public + 1 private = 2 total, 1 public
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
                assert_eq!(metric.npa.class_na_sum(), 4.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn kotlin_class_with_methods_no_attrs() {
        // Methods are not attributes.
        check_metrics::<KotlinParser>(
            "class C {
                fun m1() {}
                fun m2(): Int = 0
            }",
            "foo.kt",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 0.0);
                assert_eq!(metric.npa.class_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    // --- TypeScript / TSX NPA tests --------------------------------------
    //
    // TypeScript class fields are `public_field_definition` direct children
    // of `class_body`. Default visibility is public; an explicit
    // `accessibility_modifier` whose only child is `private`/`protected`
    // demotes a field. Constructor parameter properties
    // (`constructor(private x: number)`) count as class attributes.
    // Fields whose initializer is an arrow function are methods, not
    // attributes. Interface property signatures count as implicitly
    // public attributes.

    #[test]
    fn typescript_empty_class_no_attributes() {
        check_metrics::<TypescriptParser>("class C {}", "foo.ts", |metric| {
            assert_eq!(metric.npa.class_npa_sum(), 0.0);
            assert_eq!(metric.npa.class_na_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn typescript_default_public_fields() {
        // No accessibility modifier means public.
        check_metrics::<TypescriptParser>(
            "class C {
                a: number = 1;
                b: string = \"\";
                c: boolean = false;
            }",
            "foo.ts",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn typescript_visibility_modifiers() {
        // Public / private / protected. Default public.
        check_metrics::<TypescriptParser>(
            "class C {
                public a: number = 1;
                private b: number = 2;
                protected c: number = 3;
                d: number = 4;
            }",
            "foo.ts",
            |metric| {
                // public + default(public) = 2 npa; total na = 4.
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 4.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn typescript_static_fields() {
        // `static` is orthogonal to visibility — the field still counts.
        check_metrics::<TypescriptParser>(
            "class C {
                static a: number = 0;
                public static b: number = 0;
                private static c: number = 0;
            }",
            "foo.ts",
            |metric| {
                // a (default public) + b (public) = 2 npa; c is private.
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn typescript_parameter_properties() {
        // Constructor parameter properties are class attributes.
        check_metrics::<TypescriptParser>(
            "class C {
                constructor(public a: number, private b: string, c: boolean) {}
            }",
            "foo.ts",
            |metric| {
                // a, b are parameter properties (modifiered); c is a plain
                // parameter and does NOT count. a is public, b is private.
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn typescript_readonly_field() {
        // `readonly` is a non-visibility modifier — the field still counts
        // and stays public unless paired with private/protected.
        check_metrics::<TypescriptParser>(
            "class C {
                readonly a: number = 1;
                private readonly b: number = 2;
            }",
            "foo.ts",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn typescript_abstract_class_attributes() {
        // `abstract_class_declaration` opens its own class space; fields
        // count just like a concrete class.
        check_metrics::<TypescriptParser>(
            "abstract class C {
                public a: number = 1;
                protected b: number = 2;
                abstract m(): void;
            }",
            "foo.ts",
            |metric| {
                // a (public) + b (protected) = 2 attrs; npa = 1.
                // `abstract m()` is a method, not an attribute.
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn typescript_arrow_field_is_method_not_attribute() {
        // A field whose initializer is an arrow function is counted by
        // npm, not npa.
        check_metrics::<TypescriptParser>(
            "class C {
                a: number = 0;
                arrow = () => this.a;
            }",
            "foo.ts",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn typescript_interface_property_signatures() {
        // Interface property signatures count as implicitly-public
        // attributes; method signatures are not attributes.
        // Structural `assert_child_space_kind` guards against an
        // `InterfaceDeclaration` revert in
        // `TypescriptCode::is_func_space` — see #311.
        check_func_space::<TypescriptParser, _>(
            "interface I {
                a: number;
                b: string;
                m(): void;
            }",
            "foo.ts",
            |func_space| {
                let metric = &func_space.metrics;
                assert_eq!(metric.npa.interface_npa_sum(), 2.0);
                assert_eq!(metric.npa.interface_na_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
                assert_child_space_kind(&func_space, "I", SpaceKind::Interface);
            },
        );
    }

    #[test]
    fn typescript_generic_class_attributes() {
        // Type parameters on the class do not contribute attributes.
        check_metrics::<TypescriptParser>(
            "class Box<T, U> {
                value: T;
                other: U;
                constructor(v: T, o: U) { this.value = v; this.other = o; }
            }",
            "foo.ts",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn typescript_getters_setters_not_attributes() {
        // `get x()` / `set x(v)` are method_definitions, not attributes.
        check_metrics::<TypescriptParser>(
            "class C {
                private _x: number = 0;
                get x(): number { return this._x; }
                set x(v: number) { this._x = v; }
            }",
            "foo.ts",
            |metric| {
                // Only `_x` counts as an attribute (private → not public).
                assert_eq!(metric.npa.class_npa_sum(), 0.0);
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn typescript_multiple_classes_and_interface() {
        check_func_space::<TypescriptParser, _>(
            "class A { x: number = 0; }
             class B { private y: number = 0; }
             interface I { z: number; }",
            "foo.ts",
            |func_space| {
                let metric = &func_space.metrics;
                // A: 1 npa / 1 na (public). B: 0 npa / 1 na (private).
                // I: 1 interface_npa / 1 interface_na.
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                assert_eq!(metric.npa.interface_npa_sum(), 1.0);
                assert_eq!(metric.npa.interface_na_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
                assert_child_space_kind(&func_space, "A", SpaceKind::Class);
                assert_child_space_kind(&func_space, "B", SpaceKind::Class);
                assert_child_space_kind(&func_space, "I", SpaceKind::Interface);
            },
        );
    }

    #[test]
    fn typescript_nested_class_attributes_independent() {
        // Each class space tracks its own attributes; the outer class's
        // sum gets the inner-class sum via merge. The Outer class has
        // two `public_field_definition` direct children — `a` and the
        // `Inner` static field whose value is a class expression.
        // The class expression itself opens a separate `class` space
        // with its own two fields. Total counted across both spaces:
        // 2 (Outer: a + Inner) + 2 (inner anonymous class: b, c) = 4.
        check_metrics::<TypescriptParser>(
            "class Outer {
                a: number = 0;
                static Inner = class {
                    b: number = 0;
                    c: number = 0;
                };
            }",
            "foo.ts",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 4.0);
                assert_eq!(metric.npa.class_na_sum(), 4.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    // TSX parity tests — mirror the TS rules to confirm the shared helper
    // expansion behaves identically on the TSX grammar.

    #[test]
    fn tsx_empty_class_no_attributes() {
        check_metrics::<TsxParser>("class C {}", "foo.tsx", |metric| {
            assert_eq!(metric.npa.class_npa_sum(), 0.0);
            assert_eq!(metric.npa.class_na_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn tsx_default_public_fields() {
        check_metrics::<TsxParser>(
            "class C {
                a: number = 1;
                b: string = \"\";
            }",
            "foo.tsx",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn tsx_visibility_modifiers() {
        check_metrics::<TsxParser>(
            "class C {
                public a: number = 1;
                private b: number = 2;
                protected c: number = 3;
            }",
            "foo.tsx",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn tsx_parameter_properties() {
        check_metrics::<TsxParser>(
            "class C {
                constructor(public a: number, private b: string) {}
            }",
            "foo.tsx",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn tsx_abstract_class_attributes() {
        check_metrics::<TsxParser>(
            "abstract class C {
                public a: number = 1;
                private b: number = 2;
                abstract m(): void;
            }",
            "foo.tsx",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn tsx_interface_property_signatures() {
        check_func_space::<TsxParser, _>(
            "interface I {
                a: number;
                b: string;
                m(): void;
            }",
            "foo.tsx",
            |func_space| {
                let metric = &func_space.metrics;
                assert_eq!(metric.npa.interface_npa_sum(), 2.0);
                assert_eq!(metric.npa.interface_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
                assert_child_space_kind(&func_space, "I", SpaceKind::Interface);
            },
        );
    }

    #[test]
    fn tsx_arrow_field_is_method_not_attribute() {
        check_metrics::<TsxParser>(
            "class C {
                a: number = 0;
                arrow = () => this.a;
            }",
            "foo.tsx",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn tsx_static_fields() {
        check_metrics::<TsxParser>(
            "class C {
                static a: number = 0;
                private static b: number = 0;
            }",
            "foo.tsx",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn tsx_readonly_field() {
        check_metrics::<TsxParser>(
            "class C {
                readonly a: number = 1;
                private readonly b: number = 2;
            }",
            "foo.tsx",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn tsx_generic_class_attributes() {
        check_metrics::<TsxParser>("class Box<T> { value: T; }", "foo.tsx", |metric| {
            assert_eq!(metric.npa.class_npa_sum(), 1.0);
            assert_eq!(metric.npa.class_na_sum(), 1.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn tsx_getters_setters_not_attributes() {
        check_metrics::<TsxParser>(
            "class C {
                private _x: number = 0;
                get x(): number { return this._x; }
                set x(v: number) { this._x = v; }
            }",
            "foo.tsx",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 0.0);
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn tsx_multiple_classes_and_interface() {
        check_func_space::<TsxParser, _>(
            "class A { x: number = 0; }
             class B { private y: number = 0; }
             interface I { z: number; }",
            "foo.tsx",
            |func_space| {
                let metric = &func_space.metrics;
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                assert_eq!(metric.npa.interface_npa_sum(), 1.0);
                assert_eq!(metric.npa.interface_na_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
                assert_child_space_kind(&func_space, "A", SpaceKind::Class);
                assert_child_space_kind(&func_space, "B", SpaceKind::Class);
                assert_child_space_kind(&func_space, "I", SpaceKind::Interface);
            },
        );
    }

    // --- Ruby NPA tests ---------------------------------------------------
    //
    // Ruby has no field-declaration syntax; class-scope instance and
    // class variables are introduced by direct assignment in the class
    // body (`@var = …`, `@@var = …`). `attr_accessor` / `attr_reader`
    // / `attr_writer` macros synthesise reader/writer pairs and also
    // introduce attributes. Visibility flows from keyword markers as
    // in `Npm`.

    #[test]
    fn ruby_no_class_attributes() {
        check_metrics::<RubyParser>(
            "class A\n  def f\n    1\n  end\nend\n",
            "foo.rb",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 0.0);
                assert_eq!(metric.npa.class_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn ruby_instance_variable_attribute() {
        // Bare `@x = …` at class scope is one public attribute.
        check_metrics::<RubyParser>("class A\n  @x = 1\nend\n", "foo.rb", |metric| {
            assert_eq!(metric.npa.class_npa_sum(), 1.0);
            assert_eq!(metric.npa.class_na_sum(), 1.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn ruby_class_variable_attribute() {
        // `@@y = …` at class scope is one attribute.
        check_metrics::<RubyParser>("class A\n  @@y = 1\nend\n", "foo.rb", |metric| {
            assert_eq!(metric.npa.class_npa_sum(), 1.0);
            assert_eq!(metric.npa.class_na_sum(), 1.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn ruby_attr_accessor_counts_symbols() {
        // `attr_accessor :x, :y, :z` declares three attributes.
        check_metrics::<RubyParser>(
            "class A\n  attr_accessor :x, :y, :z\nend\n",
            "foo.rb",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn ruby_attr_reader_and_writer() {
        check_metrics::<RubyParser>(
            "class A\n  attr_reader :r1, :r2\n  attr_writer :w\nend\n",
            "foo.rb",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn ruby_mixed_attributes_and_assignments() {
        check_metrics::<RubyParser>(
            "class A\n  attr_accessor :x, :y\n  @z = 1\n  @@w = 2\nend\n",
            "foo.rb",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 4.0);
                assert_eq!(metric.npa.class_na_sum(), 4.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn ruby_private_attributes() {
        // Bare `private` flips visibility for the subsequent attr.
        check_metrics::<RubyParser>(
            "class A\n  attr_accessor :pub\n  private\n  attr_accessor :hidden\nend\n",
            "foo.rb",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn ruby_visibility_public_resets_private() {
        // `private` then `public` returns to default-public.
        check_metrics::<RubyParser>(
            "class A\n  attr_reader :a\n  private\n  attr_reader :b\n  public\n  attr_reader :c\nend\n",
            "foo.rb",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn ruby_method_scope_assignments_excluded() {
        // `@x = 1` inside a method does NOT count — it's a method-local
        // instance-variable write, not a class-scope attribute
        // declaration.
        check_metrics::<RubyParser>(
            "class A\n  def init\n    @x = 1\n    @@y = 2\n  end\nend\n",
            "foo.rb",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 0.0);
                assert_eq!(metric.npa.class_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn ruby_module_attributes_not_counted() {
        // `module M` is a `Namespace` space — its attr_* macros and
        // class-variable assignments do NOT contribute to NPA.
        check_metrics::<RubyParser>(
            "module M\n  attr_accessor :x\n  @@m = 1\nend\n",
            "foo.rb",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 0.0);
                assert_eq!(metric.npa.class_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn ruby_inheritance_attributes() {
        // Inheritance does not change the attribute count for this class.
        check_metrics::<RubyParser>(
            "class A < B\n  attr_accessor :x\n  @y = 0\nend\n",
            "foo.rb",
            |metric| {
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn ruby_constant_assignments_excluded() {
        // `CONST = …` at class scope binds a constant, not an
        // attribute; the LHS is a `Constant`, not an
        // `InstanceVariable` / `ClassVariable`.
        check_metrics::<RubyParser>(
            "class A\n  PI = 3.14\n  E = 2.71\n  attr_reader :x\nend\n",
            "foo.rb",
            |metric| {
                // Only `attr_reader :x` counts.
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn ruby_multiple_classes_attribute_rollup() {
        check_metrics::<RubyParser>(
            "class A\n  attr_accessor :x\nend\nclass B\n  private\n  attr_accessor :y\nend\n",
            "foo.rb",
            |metric| {
                // A: 1 public attr. B: 0 public, 1 total.
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    // ---------------------------------------------------------------
    // Default-impl placeholder smoke tests (audited in #188).
    //
    // Each test feeds a class / struct with public attributes to a
    // language whose `Npa` is currently the default no-op. The
    // assertion pins the current 0 value with a TODO pointing at the
    // follow-up issue — when the real impl lands the assertion will
    // fire and force a test update, which is the gate.
    // ---------------------------------------------------------------

    // --- Python NPA ---------------------------------------------------

    #[test]
    fn python_empty_class_no_attributes() {
        check_metrics::<PythonParser>("class C:\n    pass\n", "foo.py", |metric| {
            assert_eq!(metric.npa.class_na_sum(), 0.0);
            assert_eq!(metric.npa.class_npa_sum(), 0.0);
            assert_eq!(metric.npa.interface_na_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn python_class_level_assignments_are_attributes() {
        // Two class-level `=` assignments → 2 attributes, all public
        // (Python has no visibility keyword).
        check_metrics::<PythonParser>("class C:\n    x = 1\n    y = 2\n", "foo.py", |metric| {
            assert_eq!(metric.npa.class_na_sum(), 2.0);
            assert_eq!(metric.npa.class_npa_sum(), 2.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn python_bare_type_annotation_not_attribute() {
        // `x: int` is a bare annotation (declares a type, binds
        // nothing); only `y: int = 2` actually creates an attribute.
        check_metrics::<PythonParser>(
            "class C:\n    x: int\n    y: int = 2\n",
            "foo.py",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn python_self_attributes_in_init() {
        // `self.x` and `self.y` assigned in `__init__` → 2 instance
        // attributes attributed to the class space.
        check_metrics::<PythonParser>(
            "class C:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n",
            "foo.py",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn python_self_attributes_in_nested_control_flow() {
        // `self.z = 1` and `self.z = 2` in if/else now count once —
        // #215 added identifier-text deduplication. Both branches
        // bind the same attribute `z`, so `class_na == 1`.
        check_metrics::<PythonParser>(
            "class C:\n    def __init__(self, flag):\n        if flag:\n            self.z = 1\n        else:\n            self.z = 2\n",
            "foo.py",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    /// Regression #215: `self.value = …` bound in `__init__` and again
    /// in `reset()` should count the attribute exactly once. Before
    /// identifier-text deduplication, each binding inflated
    /// `class_na` by one — the defensive re-init pattern reported 2.
    ///
    /// The two assignments use DIFFERENT right-hand sides (`None`
    /// vs `0`) so a hypothetical byte-content-of-Assignment dedup
    /// (rather than identifier-name dedup) would NOT collapse them.
    /// This pins the rule to the attribute *name*, not the
    /// assignment text.
    #[test]
    fn python_defensive_reinit_self_attribute_counts_once() {
        check_metrics::<PythonParser>(
            "class C:\n    def __init__(self):\n        self.value = None\n    def reset(self):\n        self.value = 0\n",
            "foo.py",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    /// Distinct attribute names still accumulate normally — the
    /// dedup is per-name, not per-method.
    #[test]
    fn python_distinct_self_attributes_count_independently() {
        check_metrics::<PythonParser>(
            "class C:\n    def __init__(self):\n        self.x = 1\n        self.y = 2\n        self.z = 3\n",
            "foo.py",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    /// Annotated `self.x: int = 1` inside a method body parses as
    /// `Assignment(target=Attribute(self, x), type, value)` in
    /// tree-sitter-python — the same node type as plain `self.x = 1`.
    /// The dedup helper must see both forms and treat them as the
    /// same attribute. Regression guard for the review finding on
    /// #215: ensure annotated assignments aren't missed.
    #[test]
    fn python_self_attribute_annotated_assignment_dedupes() {
        check_metrics::<PythonParser>(
            "class C:\n    def __init__(self):\n        self.value: int = 1\n    def reset(self):\n        self.value = 0\n",
            "foo.py",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn python_class_level_and_self_attrs_combine() {
        // 1 class-level + 2 instance = 3 total attributes.
        check_metrics::<PythonParser>(
            "class C:\n    counter = 0\n    def __init__(self):\n        self.name = 'a'\n        self.value = 1\n",
            "foo.py",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn python_self_attrs_isolated_per_class() {
        // Nested class `Inner` opens its own class space; its
        // `self.z = …` belongs to Inner. The class_na_sum aggregates
        // across class spaces in the file, so we see both attributes
        // (Outer.x + Inner.z) in the unit-level sum; the snapshot
        // pins the per-space breakdown.
        check_metrics::<PythonParser>(
            "class Outer:\n\
             \x20   def __init__(self):\n\
             \x20       self.x = 1\n\
             \x20   class Inner:\n\
             \x20       def __init__(self):\n\
             \x20           self.z = 2\n",
            "foo.py",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn python_decorated_methods_do_not_inflate_attrs() {
        // `@property` / `@staticmethod` wrap a `FunctionDefinition` in
        // `DecoratedDefinition`. These contribute methods, not
        // attributes — Npa must stay at 0.
        check_metrics::<PythonParser>(
            "class C:\n\
             \x20   @property\n\
             \x20   def p(self):\n\
             \x20       return 1\n\
             \x20   @staticmethod\n\
             \x20   def s():\n\
             \x20       return 2\n",
            "foo.py",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn python_module_level_assignments_not_attributes() {
        // `x = 1` at module scope is not a class attribute.
        check_metrics::<PythonParser>("x = 1\ny = 2\nclass C:\n    a = 3\n", "foo.py", |metric| {
            // Only `a = 3` lives in the class space.
            assert_eq!(metric.npa.class_na_sum(), 1.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn rust_empty_unit_no_attributes() {
        check_metrics::<RustParser>("", "empty.rs", |metric| {
            assert_eq!(metric.npa.class_na_sum(), 0.0);
            assert_eq!(metric.npa.class_npa_sum(), 0.0);
            assert_eq!(metric.npa.interface_na_sum(), 0.0);
            assert_eq!(metric.npa.interface_npa_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn rust_struct_fields_are_attributes() {
        // 3 named fields → class_na = 3. `pub a` and `pub c` are public
        // → class_npa = 2. `b` is private, so it's not in `npa`.
        check_metrics::<RustParser>(
            "struct Foo { pub a: i32, b: String, pub c: bool }",
            "foo.rs",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn rust_tuple_struct_fields_are_attributes() {
        // Tuple-struct field counting is positional. `Bar(pub i32,
        // String)` → 2 fields, 1 public.
        check_metrics::<RustParser>("struct Bar(pub i32, String);", "foo.rs", |metric| {
            assert_eq!(metric.npa.class_na_sum(), 2.0);
            assert_eq!(metric.npa.class_npa_sum(), 1.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn rust_unit_struct_has_no_attributes() {
        // `struct Empty;` is a unit struct (no fields). 0 attributes.
        check_metrics::<RustParser>("struct Empty;", "foo.rs", |metric| {
            assert_eq!(metric.npa.class_na_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn rust_empty_struct_body_has_no_attributes() {
        // `struct Empty {}` is named-field with zero fields.
        check_metrics::<RustParser>("struct Empty { }", "foo.rs", |metric| {
            assert_eq!(metric.npa.class_na_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn rust_impl_associated_consts_are_attributes() {
        // `const X` and `pub const Y` and `static Z` and `pub static W`
        // → 4 associated attributes, 2 public.
        check_metrics::<RustParser>(
            "struct Foo;\n\
             impl Foo {\n\
             \x20   const X: i32 = 1;\n\
             \x20   pub const Y: i32 = 2;\n\
             \x20   static Z: i32 = 3;\n\
             \x20   pub static W: i32 = 4;\n\
             }\n",
            "foo.rs",
            |metric| {
                // The Impl-space class_na is 4; rolled up to Unit
                // class_na_sum it is also 4 (no struct fields in `Foo;`).
                assert_eq!(metric.npa.class_na_sum(), 4.0);
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn rust_trait_consts_and_associated_types_are_attributes() {
        // `const DEFAULT_COLOR` + `type Item` → 2 interface attributes,
        // both public by trait convention. Structural
        // `assert_child_space_kind` pins the trait FuncSpace against
        // an `is_func_space` revert (see #311).
        check_func_space::<RustParser, _>(
            "trait Drawable { const DEFAULT_COLOR: u32; type Item; }",
            "foo.rs",
            |func_space| {
                let metric = &func_space.metrics;
                assert_eq!(metric.npa.interface_na_sum(), 2.0);
                assert_eq!(metric.npa.interface_npa_sum(), 2.0);
                assert_eq!(metric.npa.class_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
                assert_child_space_kind(&func_space, "Drawable", SpaceKind::Trait);
            },
        );
    }

    #[test]
    fn rust_multiple_impls_aggregate() {
        // Two `impl Foo` blocks each have one associated const. The
        // unit-level rollup should be class_na_sum = 2.
        check_metrics::<RustParser>(
            "struct Foo;\n\
             impl Foo { const X: i32 = 1; }\n\
             impl Foo { pub const Y: i32 = 2; }\n",
            "foo.rs",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn rust_module_level_consts_not_attributes() {
        // `const PI: f64 = 3.14;` at file scope is a free-standing
        // constant — NOT a class attribute. Only consts INSIDE an
        // `impl` / `trait` body count.
        check_metrics::<RustParser>(
            "const PI: f64 = 3.14;\nstatic Q: i32 = 0;\n",
            "foo.rs",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 0.0);
                assert_eq!(metric.npa.interface_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    // ----- Go -----

    #[test]
    fn go_empty_unit_no_attributes() {
        // Package-only file declares no struct → npa stays disabled,
        // class_na_sum = 0.
        check_metrics::<GoParser>("package main\n", "empty.go", |metric| {
            assert_eq!(metric.npa.class_na_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn go_empty_struct_has_no_attributes() {
        // `type Empty struct{}` has an empty FieldDeclarationList →
        // 0 fields → npa stays disabled.
        check_metrics::<GoParser>("package main\ntype Empty struct{}\n", "foo.go", |metric| {
            assert_eq!(metric.npa.class_na_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn go_struct_fields_are_attributes() {
        // Three named fields: `X int`, `y string`, `Z float64` → 3
        // attributes. Visibility is by identifier case in Go, but the
        // trait signature does not give us source bytes, so every
        // field is counted as public: class_npa == class_na.
        check_metrics::<GoParser>(
            "package main\ntype Foo struct { X int; y string; Z float64 }\n",
            "foo.go",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn go_grouped_struct_fields_each_count() {
        // `X, Y int` parses as ONE field_declaration with two name
        // identifiers — counted as 1 attribute per the
        // "FieldDeclaration is the unit" rule. The trailing `Z` is a
        // separate field_declaration → 2 attributes total. This
        // mirrors Rust's per-FieldDeclaration counting.
        check_metrics::<GoParser>(
            "package main\ntype Point struct { X, Y int; Z float64 }\n",
            "foo.go",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn go_embedded_type_counts_as_attribute() {
        // `io.Reader` and `*Foo` are embedded types — field
        // declarations with no name, just a type. Each is one
        // attribute per the issue spec ("Embedded types: a field
        // with no name, just a type — count as one field"). Plus
        // `n int` → 3 attributes total.
        check_metrics::<GoParser>(
            "package main\nimport \"io\"\ntype Bar struct { io.Reader; *Foo; n int }\ntype Foo struct {}\n",
            "foo.go",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn go_multiple_structs_aggregate_at_unit() {
        // Two structs declared at file scope each contribute their
        // fields to the same Unit space (no per-receiver class
        // grouping in Go). `Foo` has 1 field, `Bar` has 2 → total
        // class_na_sum = 3.
        check_metrics::<GoParser>(
            "package main\ntype Foo struct { x int }\ntype Bar struct { a int; b string }\n",
            "foo.go",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn go_top_level_var_const_not_attributes() {
        // Package-level `var` and `const` declarations are NOT
        // struct fields — they are free-standing identifiers.
        // Expected class_na_sum = 0.
        check_metrics::<GoParser>(
            "package main\nvar Counter int\nconst Pi = 3.14\n",
            "foo.go",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    // ----- Elixir -----

    // Issue #275: `defstruct` is Elixir's closest analog to a class
    // field-set declaration. We count its field arguments as
    // (public) attributes.
    #[test]
    fn elixir_npa_defstruct_keyword_list() {
        check_metrics::<ElixirParser>(
            "defmodule User do\n  defstruct name: nil, age: 0, email: nil\nend\n",
            "foo.ex",
            |metric| {
                // Three keyword pairs → 3 fields, all public.
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
            },
        );
    }

    #[test]
    fn elixir_npa_defstruct_atom_list() {
        check_metrics::<ElixirParser>(
            "defmodule User do\n  defstruct [:name, :age, :email]\nend\n",
            "foo.ex",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
            },
        );
    }

    #[test]
    fn elixir_npa_defstruct_bracketed_keyword_list() {
        check_metrics::<ElixirParser>(
            "defmodule User do\n  defstruct [name: nil, age: 0]\nend\n",
            "foo.ex",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 2.0);
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
            },
        );
    }

    #[test]
    fn elixir_npa_defstruct_single_field() {
        check_metrics::<ElixirParser>(
            "defmodule Box do\n  defstruct value: nil\nend\n",
            "foo.ex",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
            },
        );
    }

    #[test]
    fn elixir_npa_no_defstruct_is_zero() {
        check_metrics::<ElixirParser>(
            "defmodule Foo do\n  def m, do: :ok\nend\n",
            "foo.ex",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 0.0);
                assert_eq!(metric.npa.class_npa_sum(), 0.0);
            },
        );
    }

    // ----- C++ -----

    #[test]
    fn cpp_empty_unit_no_attributes() {
        // No code → no class spaces → npa = 0. Establishes the trait
        // is wired and the per-language compute is reachable.
        check_metrics::<CppParser>("", "empty.cpp", |metric| {
            assert_eq!(metric.npa.class_na_sum(), 0.0);
            assert_eq!(metric.npa.class_npa_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn cpp_empty_class_no_attributes() {
        // `class Foo {};` has no fields. Marked as class space (npa
        // becomes visible) but counts stay at 0.
        check_metrics::<CppParser>("class Foo {};", "foo.cpp", |metric| {
            assert_eq!(metric.npa.class_na_sum(), 0.0);
            assert_eq!(metric.npa.class_npa_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn cpp_class_public_attributes() {
        // `class` defaults to private. `public:` flips visibility →
        // `int a; int b, c;` becomes 3 public attributes (multi-
        // declarator declaration emits one `field_identifier` per
        // name). Total: class_na = 3, class_npa = 3.
        check_metrics::<CppParser>(
            "class Foo { public: int a; int b, c; };",
            "foo.cpp",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn cpp_class_private_default_visibility() {
        // No access specifier → `class` keeps its default private
        // visibility → `int value_;` counts as 1 attribute but 0 are
        // public. class_na = 1, class_npa = 0.
        check_metrics::<CppParser>("class Foo { int value_; };", "foo.cpp", |metric| {
            assert_eq!(metric.npa.class_na_sum(), 1.0);
            assert_eq!(metric.npa.class_npa_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn cpp_struct_default_public_visibility() {
        // `struct` defaults to public — opposite of `class`. The same
        // field counts once and is public.
        check_metrics::<CppParser>("struct Bar { int value_; };", "foo.cpp", |metric| {
            assert_eq!(metric.npa.class_na_sum(), 1.0);
            assert_eq!(metric.npa.class_npa_sum(), 1.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn cpp_mixed_visibility_sections() {
        // Public section: 1 field. Protected section (bucketed with
        // private for npa): 1 field. Private section: 1 field.
        // class_na = 3, class_npa = 1.
        check_metrics::<CppParser>(
            "class Foo {\n\
                 public: int a;\n\
                 protected: int b;\n\
                 private: int c;\n\
             };",
            "foo.cpp",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn cpp_methods_not_counted_as_attributes() {
        // Inline-defined methods (`function_definition`) and
        // declaration-only methods (`field_declaration` containing
        // `function_declarator`) must NOT be counted as attributes.
        // Only the data field `value_` adds to `class_na`.
        check_metrics::<CppParser>(
            "class Foo {\n\
                 public:\n\
                     void method1() {}\n\
                     void method2();\n\
                 private:\n\
                     int value_;\n\
             };",
            "foo.cpp",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                assert_eq!(metric.npa.class_npa_sum(), 0.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn cpp_pointer_array_fields_count() {
        // `int* p;` wraps the `field_identifier` inside
        // `pointer_declarator`. `int a[10];` wraps it inside
        // `array_declarator`. Both must be reached by the recursive
        // helper. Plus a plain `int x;` → 3 attributes total.
        check_metrics::<CppParser>(
            "struct S {\n\
                 int* p;\n\
                 int a[10];\n\
                 int x;\n\
             };",
            "foo.cpp",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                // Struct → all public.
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn cpp_multiple_classes_aggregate_at_unit() {
        // Two classes in one file. Each contributes to its own
        // class space; the file-level (Unit) class_na_sum aggregates
        // both. Foo has 2 attrs (1 public, 1 private). Bar has 1.
        // Total class_na_sum at Unit = 3.
        check_metrics::<CppParser>(
            "class Foo { public: int a; private: int b; };\nstruct Bar { int c; };",
            "foo.cpp",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                // Public: Foo::a (1) + Bar::c (1) = 2.
                assert_eq!(metric.npa.class_npa_sum(), 2.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn javascript_empty_unit_no_attributes() {
        // Wires up the trait and ensures no spurious attribute counts
        // on an empty file.
        check_metrics::<JavascriptParser>("", "empty.js", |metric| {
            assert_eq!(metric.npa.class_na_sum(), 0.0);
            assert_eq!(metric.npa.class_npa_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn javascript_empty_class_no_attributes() {
        // A class with no body and no fields has zero attributes.
        check_metrics::<JavascriptParser>("class Foo {}", "foo.js", |metric| {
            assert_eq!(metric.npa.class_na_sum(), 0.0);
            assert_eq!(metric.npa.class_npa_sum(), 0.0);
            insta::assert_json_snapshot!(metric.npa);
        });
    }

    #[test]
    fn javascript_class_fields_count() {
        // ES2022 class fields: `class Foo { x = 1; y; static z = 2; }`.
        // All three are `field_definition` direct children of
        // `class_body`. JS has no visibility — everything is public.
        // class_na = class_npa = 3.
        check_metrics::<JavascriptParser>(
            "class Foo { x = 1; y; static z = 2; }",
            "foo.js",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn javascript_arrow_field_is_method_not_attribute() {
        // `class Foo { x = () => {} }` declares a method, not an
        // attribute. The arrow function initializer makes this an
        // `Npm` member, not an `Npa` member.
        check_metrics::<JavascriptParser>(
            "class Foo { x = () => {}; y = function() {}; z = 1; }",
            "foo.js",
            |metric| {
                // Only `z = 1` is an attribute.
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn javascript_methods_not_counted_as_attributes() {
        // `method_definition` direct children of `class_body` are
        // methods, not fields. They must not show up in `npa`.
        check_metrics::<JavascriptParser>(
            "class Foo { constructor() {} bar() {} get baz() { return 1; } x = 1; }",
            "foo.js",
            |metric| {
                // Only `x = 1` is a true attribute.
                assert_eq!(metric.npa.class_na_sum(), 1.0);
                assert_eq!(metric.npa.class_npa_sum(), 1.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn javascript_multiple_classes_aggregate_at_unit() {
        // Two classes contribute their attribute counts to the
        // Unit-level rollup. Foo has 2 fields; Bar has 1. Total
        // class_na_sum = 3.
        check_metrics::<JavascriptParser>(
            "class Foo { a = 1; b = 2; }\nclass Bar { c = 3; }",
            "foo.js",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }

    #[test]
    fn mozjs_class_fields_count() {
        // Mozjs shares JS's class vocabulary. Same expectation as the
        // JS parity test above.
        check_metrics::<MozjsParser>(
            "class Foo { x = 1; y; static z = 2; }",
            "foo.js",
            |metric| {
                assert_eq!(metric.npa.class_na_sum(), 3.0);
                assert_eq!(metric.npa.class_npa_sum(), 3.0);
                insta::assert_json_snapshot!(metric.npa);
            },
        );
    }
}