1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
//! C language support (also works for basic C++).
//!
//! Implements full extraction for C code including:
//! - Function definitions (function_definition)
//! - Function declarations (declaration with function_declarator)
//! - Structs (struct_specifier)
//! - Typedefs (type_definition)
//! - Includes (preproc_include with system and local paths)
//! - Macro definitions (preproc_def, preproc_function_def)
//! - Function pointer types (function_declarator in parenthesized_declarator)
//! - Preprocessor conditionals (#ifdef, #ifndef, #if, #elif, #else, #endif)
//! - Anonymous structs and unions (embedded within other structs)
//!
//! C11/C23 features:
//! - Static assertions (`_Static_assert`, `static_assert`) with decorator "static_assert"
//! - Thread-local storage (`__thread`) with decorator "thread_local"
//! - Inline assembly detection (`asm`, `__asm__`) with decorator "inline_assembly"
//!
//! C-specific patterns handled:
//! - Static functions (storage_class_specifier)
//! - Pointer types (pointer_declarator)
//! - Const qualifiers (type_qualifier)
//! - Header vs source file distinction
//! - Doc comments (/* */ and // style preceding declarations)
//! - Object-like macros (#define FOO 42)
//! - Function-like macros (#define MAX(a,b) ((a)>(b)?(a):(b)))
//! - Function pointer typedefs (typedef int (*fn_ptr)(int, int))
//! - Preprocessor conditional compilation blocks
//! - Anonymous struct/union members in composite types
use std::collections::HashMap;
use std::path::Path;
use tree_sitter::{Node, Parser, Tree};
use crate::ast::types::{ClassInfo, FunctionInfo, ImportInfo};
use crate::cfg::types::{BlockId, BlockType, CFGBlock, CFGEdge, CFGInfo};
use crate::dfg::types::{DFGInfo, DataflowEdge, DataflowKind};
use crate::error::{Result, BrrrError};
use crate::lang::traits::Language;
/// Detect if a `.h` header file contains C++ code.
///
/// This heuristic checks for C++ keywords and patterns that are not valid C.
/// Used to prevent the C parser from attempting to parse C++ headers,
/// which would result in parse errors or incorrect extraction.
///
/// # C++ Indicators Checked
///
/// - `template<` or `template <` - C++ templates
/// - `namespace ` followed by identifier - C++ namespaces
/// - `class ` followed by identifier (not typedef) - C++ classes
/// - `constexpr ` - C++11 constant expressions
/// - `consteval ` - C++20 immediate functions
/// - `nullptr` - C++11 null pointer literal
/// - `noexcept` - C++ exception specification
/// - `decltype` - C++11 type deduction
/// - `static_assert(` with no leading `_Static_assert` - C++11 static assertions
/// - `typename ` - C++ type parameter
/// - `using namespace` - C++ using directive
/// - `auto ` followed by identifier and `=` - C++11 type inference
/// - `private:`, `public:`, `protected:` - C++ access specifiers
///
/// # Arguments
///
/// * `content` - File content as bytes
///
/// # Returns
///
/// * `true` if C++ indicators are found, `false` otherwise
///
/// # Performance
///
/// Only scans the first 32KB of the file for efficiency.
/// Most C++ indicators appear near the top (includes, namespaces, templates).
fn is_cpp_header(content: &[u8]) -> bool {
// Only scan the first 32KB for efficiency
let scan_limit = content.len().min(32 * 1024);
let content = match std::str::from_utf8(&content[..scan_limit]) {
Ok(s) => s,
Err(_) => return false, // Invalid UTF-8, likely binary - let parser handle it
};
// C++ keyword patterns that are definitively not valid C
// Using simple substring search for performance (avoid regex overhead)
// template<T> or template <T>
if content.contains("template<") || content.contains("template <") {
return true;
}
// namespace identifier { or namespace identifier::
// Check for 'namespace' followed by a space and then an identifier
if let Some(pos) = content.find("namespace ") {
let after = &content[pos + 10..];
// Check that it's followed by an identifier (letter or underscore)
if let Some(first_char) = after.chars().next() {
if first_char.is_alphabetic() || first_char == '_' {
return true;
}
}
}
// class Foo : or class Foo { (but not 'enum class' which we need to distinguish)
// Also avoid false positives from comments like "Every class is associated..."
// A real C++ class declaration has: class Name { or class Name :
for (idx, _) in content.match_indices("class ") {
// Make sure it's not preceded by 'enum '
let prefix_start = idx.saturating_sub(5);
let prefix = &content[prefix_start..idx];
if !prefix.ends_with("enum ") {
// Check if followed by identifier
let after = &content[idx + 6..];
if let Some(first_char) = after.chars().next() {
if first_char.is_alphabetic() || first_char == '_' {
// Look for class definition indicators: { or : within reasonable distance
// This avoids false positives from "class is" or "class configuration" in comments
let scan_ahead = &after[..after.len().min(100)];
// Check if we find { or : before a newline or semicolon (statement end)
let mut found_def = false;
for ch in scan_ahead.chars() {
match ch {
'{' | ':' => {
found_def = true;
break;
}
'\n' | ';' | '.' | ',' => {
// Statement/sentence ended without class definition
break;
}
_ => continue,
}
}
if found_def {
return true;
}
}
}
}
}
// constexpr - C++11 constant expressions
if content.contains("constexpr ") || content.contains("constexpr\n") {
return true;
}
// consteval - C++20 immediate functions
if content.contains("consteval ") {
return true;
}
// nullptr - C++11 null pointer
if content.contains("nullptr") {
return true;
}
// noexcept - C++ exception specification
if content.contains("noexcept") {
return true;
}
// decltype - C++11 type deduction
if content.contains("decltype(") || content.contains("decltype (") {
return true;
}
// typename - C++ type parameter
if content.contains("typename ") {
return true;
}
// using namespace - C++ using directive
if content.contains("using namespace") {
return true;
}
// C++ access specifiers (public:, private:, protected:)
// These inside struct/class definitions indicate C++
if content.contains("public:") || content.contains("private:") || content.contains("protected:") {
return true;
}
// C++ style casts
if content.contains("static_cast<")
|| content.contains("dynamic_cast<")
|| content.contains("const_cast<")
|| content.contains("reinterpret_cast<")
{
return true;
}
// References with & in type declarations (tricky - avoid function address-of)
// Look for patterns like "Type& name" or "const Type&"
if content.contains("& ") && (content.contains("const ") || content.contains("int&") || content.contains("char&")) {
// Additional check - C++ style reference in parameter/return
for pattern in ["int& ", "char& ", "void& ", "bool& ", "auto& "] {
if content.contains(pattern) {
return true;
}
}
}
false
}
/// C language implementation.
pub struct C;
impl C {
/// Extract text from source bytes for a node.
#[inline]
fn get_text<'a>(&self, node: Node, source: &'a [u8]) -> &'a str {
std::str::from_utf8(&source[node.start_byte()..node.end_byte()]).unwrap_or("")
}
/// Extract text as owned String.
fn node_text(&self, node: Node, source: &[u8]) -> String {
self.get_text(node, source).to_string()
}
/// Get child node by field name.
fn child_by_field<'a>(&self, node: Node<'a>, field: &str) -> Option<Node<'a>> {
node.child_by_field_name(field)
}
/// Extract preceding comment as documentation.
/// Supports both /* */ block comments and // line comments.
///
/// Comments are considered adjacent if there is at most MAX_GAP blank lines
/// between them and the declaration (or between consecutive comments).
fn get_doc_comment(&self, node: Node, source: &[u8]) -> Option<String> {
let mut comments = Vec::new();
// Track the row we expect comments to end before.
// Initially, this is the function's start row.
let mut expected_before_row = node.start_position().row;
// Maximum allowed gap (blank lines) between comment and declaration
// or between consecutive comments. Setting to 1 allows a single blank line.
const MAX_GAP: usize = 1;
// Walk backwards through siblings to find comments
if let Some(parent) = node.parent() {
let mut found_self = false;
let child_count = parent.child_count();
for i in (0..child_count).rev() {
if let Some(sibling) = parent.child(i as u32) {
if sibling.id() == node.id() {
found_self = true;
continue;
}
if found_self && sibling.kind() == "comment" {
let comment_end_row = sibling.end_position().row;
// Calculate gap: number of blank lines between comment end and expected position
// Example: comment ends at row 8, function at row 10 -> gap = 10 - 9 = 1
let gap = expected_before_row.saturating_sub(comment_end_row + 1);
if gap <= MAX_GAP {
let text = self.get_text(sibling, source);
let cleaned = self.clean_comment(text);
if !cleaned.is_empty() {
comments.push(cleaned);
}
// Update: next comment should end before this one starts
expected_before_row = sibling.start_position().row;
} else {
break;
}
} else if found_self && sibling.kind() != "comment" {
break;
}
}
}
}
if comments.is_empty() {
None
} else {
comments.reverse();
Some(comments.join("\n"))
}
}
/// Clean a comment string by removing comment markers.
fn clean_comment(&self, text: &str) -> String {
let text = text.trim();
// Block comment: /* ... */ or /** ... */
if text.starts_with("/*") {
let inner = text
.strip_prefix("/**")
.or_else(|| text.strip_prefix("/*"))
.unwrap_or(text);
let inner = inner.strip_suffix("*/").unwrap_or(inner);
return inner
.lines()
.map(|line| {
let line = line.trim();
line.strip_prefix('*').unwrap_or(line).trim()
})
.filter(|line| !line.is_empty())
.collect::<Vec<_>>()
.join(" ");
}
// Line comment: // ...
if text.starts_with("//") {
return text.strip_prefix("//").unwrap_or(text).trim().to_string();
}
text.to_string()
}
/// Extract the full type from a type node, handling pointers and qualifiers.
/// Reserved for future use in enhanced type extraction.
#[allow(dead_code)]
fn extract_type(&self, node: Node, source: &[u8]) -> String {
let mut parts = Vec::new();
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"type_qualifier" => {
parts.push(self.node_text(child, source));
}
"primitive_type" | "type_identifier" | "sized_type_specifier" => {
parts.push(self.node_text(child, source));
}
"struct_specifier" => {
// Handle struct Type
if let Some(name) = self.child_by_field(child, "name") {
parts.push(format!("struct {}", self.node_text(name, source)));
} else {
parts.push("struct".to_string());
}
}
"enum_specifier" => {
if let Some(name) = self.child_by_field(child, "name") {
parts.push(format!("enum {}", self.node_text(name, source)));
} else {
parts.push("enum".to_string());
}
}
"union_specifier" => {
if let Some(name) = self.child_by_field(child, "name") {
parts.push(format!("union {}", self.node_text(name, source)));
} else {
parts.push("union".to_string());
}
}
_ => {}
}
}
// If no children matched, use the node text directly
if parts.is_empty() {
return self.node_text(node, source);
}
parts.join(" ")
}
/// Extract parameter list from a parameter_list node.
fn extract_params(&self, node: Node, source: &[u8]) -> Vec<String> {
let mut params = Vec::new();
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "parameter_declaration" {
let param = self.extract_parameter(child, source);
if !param.is_empty() {
params.push(param);
}
} else if child.kind() == "variadic_parameter" {
params.push("...".to_string());
}
}
params
}
/// Extract a single parameter declaration.
fn extract_parameter(&self, node: Node, source: &[u8]) -> String {
let mut type_parts = Vec::new();
let mut name = String::new();
let mut pointer_count = 0;
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"type_qualifier" => {
type_parts.push(self.node_text(child, source));
}
"primitive_type" | "type_identifier" | "sized_type_specifier" => {
type_parts.push(self.node_text(child, source));
}
"struct_specifier" => {
if let Some(n) = self.child_by_field(child, "name") {
type_parts.push(format!("struct {}", self.node_text(n, source)));
}
}
"pointer_declarator" => {
let (n, ptrs) = self.extract_pointer_declarator(child, source);
name = n;
pointer_count = ptrs;
}
"identifier" => {
name = self.node_text(child, source);
}
"array_declarator" => {
// Handle array parameters like int arr[]
let (n, suffix) = self.extract_array_declarator(child, source);
name = format!("{}{}", n, suffix);
}
"abstract_pointer_declarator" => {
// Handle unnamed pointer parameters like (const void*, int*)
// Count nested pointer levels for void**, int***, etc.
pointer_count += self.count_abstract_pointer_levels(child);
}
_ => {}
}
}
let type_str = type_parts.join(" ");
let pointers = "*".repeat(pointer_count);
if name.is_empty() {
// Unnamed parameter (just type)
format!("{}{}", type_str, pointers)
} else {
format!("{}{} {}", type_str, pointers, name)
}
}
/// Extract identifier and pointer count from a pointer_declarator.
fn extract_pointer_declarator(&self, node: Node, source: &[u8]) -> (String, usize) {
let mut pointer_count = 0;
let mut current = node;
loop {
if current.kind() == "pointer_declarator" {
pointer_count += 1;
if let Some(declarator) = self.child_by_field(current, "declarator") {
current = declarator;
} else {
// Find the declarator child manually, skipping type qualifiers and pointer symbols.
// For `const int * const * ptr`, AST may have: const -> * -> const -> * -> identifier
// We must skip type_qualifier nodes to find the actual declarator.
let mut found = false;
let mut cursor = current.walk();
for child in current.children(&mut cursor) {
match child.kind() {
// Skip pointer symbols and type qualifiers
"*" | "type_qualifier" | "const" | "volatile" | "restrict" | "_Atomic" => {
continue;
}
// Found a declarator or identifier - use it
"identifier" | "field_identifier" | "pointer_declarator"
| "array_declarator" | "function_declarator" => {
current = child;
found = true;
break;
}
// For any other node type, try recursing into it
_ => {
current = child;
found = true;
break;
}
}
}
if !found {
break;
}
}
} else if current.kind() == "identifier" || current.kind() == "field_identifier" {
return (self.node_text(current, source), pointer_count);
} else if current.kind() == "function_declarator" {
// Function pointer - extract the identifier from it
if let Some(decl) = self.child_by_field(current, "declarator") {
return self.extract_pointer_declarator(decl, source);
}
break;
} else {
break;
}
}
(String::new(), pointer_count)
}
/// Extract identifier and array suffix from an array_declarator.
fn extract_array_declarator(&self, node: Node, source: &[u8]) -> (String, String) {
let mut name = String::new();
let mut suffix = String::new();
if let Some(declarator) = self.child_by_field(node, "declarator") {
name = self.node_text(declarator, source);
}
// Build array suffix
if let Some(size) = self.child_by_field(node, "size") {
suffix = format!("[{}]", self.node_text(size, source));
} else {
suffix = "[]".to_string();
}
(name, suffix)
}
/// Count pointer levels in an abstract_pointer_declarator.
///
/// Handles nested pointers for types like `void**`, `int***`.
/// The AST structure for `void**` is:
/// ```text
/// abstract_pointer_declarator
/// *
/// abstract_pointer_declarator
/// *
/// ```
fn count_abstract_pointer_levels(&self, node: Node) -> usize {
let mut count = 1; // Current node is one pointer level
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "abstract_pointer_declarator" {
count += self.count_abstract_pointer_levels(child);
}
}
count
}
/// Extract object-like macro definition (#define FOO 42).
/// Returns FunctionInfo with decorator "macro" and no params.
fn extract_object_macro(&self, node: Node, source: &[u8]) -> Option<FunctionInfo> {
// preproc_def has: name (identifier), value (preproc_arg)
let name = self
.child_by_field(node, "name")
.map(|n| self.node_text(n, source))?;
// Get the macro value/body if present
let value = self
.child_by_field(node, "value")
.map(|v| self.node_text(v, source).trim().to_string());
let docstring = self.get_doc_comment(node, source);
Some(FunctionInfo {
name,
params: Vec::new(),
return_type: value, // Store macro value in return_type field
docstring,
is_method: false,
is_async: false,
decorators: vec!["macro".to_string()],
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
})
}
/// Extract function-like macro definition (#define MAX(a,b) ...).
/// Returns FunctionInfo with decorator "macro" and params extracted from preproc_params.
fn extract_function_macro(&self, node: Node, source: &[u8]) -> Option<FunctionInfo> {
// preproc_function_def has: name (identifier), parameters (preproc_params), value (preproc_arg)
let name = self
.child_by_field(node, "name")
.map(|n| self.node_text(n, source))?;
// Extract macro parameters from preproc_params
let params = self
.child_by_field(node, "parameters")
.map(|p| self.extract_macro_params(p, source))
.unwrap_or_default();
// Get the macro body if present
let value = self
.child_by_field(node, "value")
.map(|v| self.node_text(v, source).trim().to_string());
let docstring = self.get_doc_comment(node, source);
Some(FunctionInfo {
name,
params,
return_type: value, // Store macro body in return_type field
docstring,
is_method: false,
is_async: false,
decorators: vec!["macro".to_string()],
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
})
}
/// Extract parameter names from a preproc_params node (for function-like macros).
fn extract_macro_params(&self, node: Node, source: &[u8]) -> Vec<String> {
let mut params = Vec::new();
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "identifier" {
params.push(self.node_text(child, source));
} else if child.kind() == "..." {
params.push("...".to_string());
}
}
params
}
/// Extract preprocessor conditional (#ifdef, #ifndef, #if).
/// Returns ClassInfo with decorator indicating the conditional type.
fn extract_preproc_conditional(&self, node: Node, source: &[u8]) -> Option<ClassInfo> {
match node.kind() {
"preproc_ifdef" => {
// #ifdef or #ifndef - determined by first child
let mut cursor = node.walk();
let mut is_ifndef = false;
for child in node.children(&mut cursor) {
if child.kind() == "#ifndef" {
is_ifndef = true;
break;
} else if child.kind() == "#ifdef" {
break;
}
}
let name = self
.child_by_field(node, "name")
.map(|n| self.node_text(n, source))?;
let decorator = if is_ifndef {
"preproc_ifndef"
} else {
"preproc_ifdef"
};
Some(ClassInfo {
name,
bases: Vec::new(),
docstring: self.get_doc_comment(node, source),
methods: Vec::new(),
fields: Vec::new(),
inner_classes: self.extract_nested_preproc_conditionals(node, source),
decorators: vec![decorator.to_string()],
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
})
}
"preproc_if" => {
// #if with condition expression
let condition = self
.child_by_field(node, "condition")
.map(|n| self.node_text(n, source))
.unwrap_or_else(|| "unknown".to_string());
// Extract nested conditionals from alternatives (elif/else chains)
let mut inner = self.extract_nested_preproc_conditionals(node, source);
// Also extract from alternative branch if present
if let Some(alt) = self.child_by_field(node, "alternative") {
inner.extend(self.extract_preproc_alternative_chain(alt, source));
}
Some(ClassInfo {
name: condition,
bases: Vec::new(),
docstring: self.get_doc_comment(node, source),
methods: Vec::new(),
fields: Vec::new(),
inner_classes: inner,
decorators: vec!["preproc_if".to_string()],
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
})
}
_ => None,
}
}
/// Extract #elif and #else chains as nested ClassInfo entries.
fn extract_preproc_alternative_chain(&self, node: Node, source: &[u8]) -> Vec<ClassInfo> {
let mut results = Vec::new();
match node.kind() {
"preproc_elif" => {
let condition = self
.child_by_field(node, "condition")
.map(|n| self.node_text(n, source))
.unwrap_or_else(|| "unknown".to_string());
let mut inner = self.extract_nested_preproc_conditionals(node, source);
// Continue chain if there's another alternative
if let Some(alt) = self.child_by_field(node, "alternative") {
inner.extend(self.extract_preproc_alternative_chain(alt, source));
}
results.push(ClassInfo {
name: condition,
bases: Vec::new(),
docstring: None,
methods: Vec::new(),
fields: Vec::new(),
inner_classes: inner,
decorators: vec!["preproc_elif".to_string()],
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
});
}
"preproc_else" => {
results.push(ClassInfo {
name: "#else".to_string(),
bases: Vec::new(),
docstring: None,
methods: Vec::new(),
fields: Vec::new(),
inner_classes: self.extract_nested_preproc_conditionals(node, source),
decorators: vec!["preproc_else".to_string()],
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
});
}
_ => {}
}
results
}
/// Extract nested preprocessor conditionals from a node's children.
fn extract_nested_preproc_conditionals(&self, node: Node, source: &[u8]) -> Vec<ClassInfo> {
let mut results = Vec::new();
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"preproc_ifdef" | "preproc_if" => {
if let Some(cond) = self.extract_preproc_conditional(child, source) {
results.push(cond);
}
}
_ => {}
}
}
results
}
/// Extract anonymous struct or union from a field_declaration.
/// Returns ClassInfo with auto-generated name based on parent context.
fn extract_anonymous_struct_or_union(
&self,
node: Node,
source: &[u8],
parent_name: &str,
index: usize,
) -> Option<ClassInfo> {
// node is a struct_specifier or union_specifier without a name
let kind = node.kind();
// Verify it has no name (anonymous)
if self.child_by_field(node, "name").is_some() {
return None;
}
// Verify it has a body (not just a forward reference)
if self.child_by_field(node, "body").is_none() {
return None;
}
let type_tag = if kind == "struct_specifier" {
"struct"
} else if kind == "union_specifier" {
"union"
} else {
return None;
};
// Generate a synthetic name for the anonymous type
let synthetic_name = format!("{}_anon_{}_{}", parent_name, type_tag, index);
let decorator = format!("anonymous_{}", type_tag);
// Extract nested anonymous types from this anonymous type's body
let inner_classes = self.extract_anonymous_members_from_body(node, source, &synthetic_name);
Some(ClassInfo {
name: synthetic_name,
bases: Vec::new(),
docstring: self.get_doc_comment(node, source),
methods: Vec::new(),
fields: Vec::new(),
inner_classes,
decorators: vec![decorator],
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
})
}
/// Extract all anonymous struct/union members from a struct/union body.
fn extract_anonymous_members_from_body(
&self,
parent_node: Node,
source: &[u8],
parent_name: &str,
) -> Vec<ClassInfo> {
let mut results = Vec::new();
let body = match self.child_by_field(parent_node, "body") {
Some(b) => b,
None => return results,
};
let mut cursor = body.walk();
let mut anon_index = 0;
for child in body.children(&mut cursor) {
if child.kind() == "field_declaration" {
// Check if this field's type is an anonymous struct/union
let mut field_cursor = child.walk();
for field_child in child.children(&mut field_cursor) {
if field_child.kind() == "struct_specifier"
|| field_child.kind() == "union_specifier"
{
// Check if it's anonymous (no name field)
if self.child_by_field(field_child, "name").is_none() {
if let Some(anon) = self.extract_anonymous_struct_or_union(
field_child,
source,
parent_name,
anon_index,
) {
results.push(anon);
anon_index += 1;
}
}
}
}
}
}
results
}
/// Extract struct/union field declarations including bitfield information.
///
/// Handles:
/// - Regular fields: `int x;`
/// - Pointer fields: `int *ptr;`
/// - Array fields: `int arr[10];`
/// - Bitfield fields: `unsigned int flag : 1;`
///
/// Bitfield width is stored in the field's annotations as "bitfield:N".
fn extract_struct_fields(&self, node: Node, source: &[u8]) -> Vec<crate::ast::types::FieldInfo> {
use crate::ast::types::FieldInfo;
let mut fields = Vec::new();
let body = match self.child_by_field(node, "body") {
Some(b) => b,
None => return fields,
};
let mut cursor = body.walk();
for child in body.children(&mut cursor) {
if child.kind() != "field_declaration" {
continue;
}
// Extract field type
let mut type_parts = Vec::new();
let mut field_name = String::new();
let mut pointer_count = 0;
let mut array_suffix = String::new();
let mut bitfield_width: Option<String> = None;
let mut field_cursor = child.walk();
for field_child in child.children(&mut field_cursor) {
match field_child.kind() {
"type_qualifier" => {
type_parts.push(self.node_text(field_child, source));
}
"primitive_type" | "type_identifier" | "sized_type_specifier" => {
type_parts.push(self.node_text(field_child, source));
}
"struct_specifier" | "union_specifier" | "enum_specifier" => {
// Handle embedded type specifiers (including anonymous)
if let Some(name) = self.child_by_field(field_child, "name") {
let kind = if field_child.kind() == "struct_specifier" {
"struct"
} else if field_child.kind() == "union_specifier" {
"union"
} else {
"enum"
};
type_parts.push(format!("{} {}", kind, self.node_text(name, source)));
}
}
"field_identifier" => {
field_name = self.node_text(field_child, source);
}
"pointer_declarator" => {
let (name, ptrs) = self.extract_pointer_declarator(field_child, source);
if !name.is_empty() {
field_name = name;
}
pointer_count = ptrs;
}
"array_declarator" => {
let (name, suffix) = self.extract_array_declarator(field_child, source);
field_name = name;
array_suffix = suffix;
}
"bitfield_clause" => {
// Extract bit width from bitfield_clause
let mut bf_cursor = field_child.walk();
for bf_child in field_child.children(&mut bf_cursor) {
if bf_child.kind() == "number_literal" {
bitfield_width = Some(self.node_text(bf_child, source));
break;
}
}
}
_ => {}
}
}
// Skip if no field name (shouldn't happen for valid C)
if field_name.is_empty() {
continue;
}
// Build the complete type string
let pointers = "*".repeat(pointer_count);
let type_str = if type_parts.is_empty() {
None
} else {
Some(format!("{}{}{}", type_parts.join(" "), pointers, array_suffix))
};
// Build annotations including bitfield info
let mut annotations = Vec::new();
if let Some(width) = bitfield_width {
annotations.push(format!("bitfield:{}", width));
}
fields.push(FieldInfo {
name: field_name,
field_type: type_str,
visibility: None,
is_static: false,
is_final: false,
default_value: None,
annotations,
line_number: child.start_position().row + 1,
});
}
fields
}
/// Extract K&R style (old-style) parameter declarations.
///
/// In K&R style, function parameters are declared without types in the
/// parameter list, and type declarations follow:
/// ```c
/// int foo(a, b)
/// int a;
/// int b;
/// { ... }
/// ```
///
/// Returns a map from parameter name to its full type string.
fn extract_knr_params(&self, node: Node, source: &[u8]) -> std::collections::HashMap<String, String> {
let mut type_map = std::collections::HashMap::new();
// K&R declarations are direct children of function_definition,
// appearing between the declarator and the body
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() != "declaration" {
continue;
}
// Extract type from the declaration
let mut type_parts = Vec::new();
let mut names = Vec::new();
let mut decl_cursor = child.walk();
for decl_child in child.children(&mut decl_cursor) {
match decl_child.kind() {
"type_qualifier" => {
type_parts.push(self.node_text(decl_child, source));
}
"primitive_type" | "type_identifier" | "sized_type_specifier" => {
type_parts.push(self.node_text(decl_child, source));
}
"struct_specifier" => {
if let Some(name) = self.child_by_field(decl_child, "name") {
type_parts.push(format!("struct {}", self.node_text(name, source)));
}
}
"identifier" => {
names.push(self.node_text(decl_child, source));
}
"pointer_declarator" => {
let (name, ptrs) = self.extract_pointer_declarator(decl_child, source);
if !name.is_empty() {
let pointers = "*".repeat(ptrs);
// For K&R, store the full type with pointers
let base_type = type_parts.join(" ");
type_map.insert(name, format!("{}{}", base_type, pointers));
}
}
"array_declarator" => {
let (name, suffix) = self.extract_array_declarator(decl_child, source);
if !name.is_empty() {
let base_type = type_parts.join(" ");
type_map.insert(name, format!("{}{}", base_type, suffix));
}
}
_ => {}
}
}
// Map each identifier to its type
let base_type = type_parts.join(" ");
for name in names {
if !type_map.contains_key(&name) {
type_map.insert(name, base_type.clone());
}
}
}
type_map
}
/// Check if a function definition uses K&R style parameters.
///
/// K&R style is detected when:
/// 1. The parameter_list contains bare identifiers (no type specifiers)
/// 2. There are declaration nodes between declarator and body
fn is_knr_style(&self, node: Node) -> bool {
if node.kind() != "function_definition" {
return false;
}
// Check for declaration nodes that are direct children (K&R type declarations)
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
// If we find a declaration that's not inside the body, it's K&R style
if child.kind() == "declaration" {
return true;
}
}
false
}
/// Extract GCC __attribute__ specifiers from a node.
///
/// Handles attributes on:
/// - Function declarations/definitions
/// - Struct/union/enum specifiers
/// - Variable declarations
///
/// Returns a list of attribute strings like "packed", "aligned(4)", "noreturn".
fn extract_attributes(&self, node: Node, source: &[u8]) -> Vec<String> {
let mut attributes = Vec::new();
// Look for attribute_specifier nodes in the current node and its children
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "attribute_specifier" {
self.extract_attribute_content(child, source, &mut attributes);
}
// Also check in declarators (e.g., for function attributes)
if child.kind() == "function_declarator" {
let mut decl_cursor = child.walk();
for decl_child in child.children(&mut decl_cursor) {
if decl_child.kind() == "attribute_specifier" {
self.extract_attribute_content(decl_child, source, &mut attributes);
}
}
}
}
attributes
}
/// Extract the content of an attribute_specifier node.
fn extract_attribute_content(&self, node: Node, source: &[u8], attributes: &mut Vec<String>) {
// attribute_specifier structure:
// __attribute__ ( argument_list ( ... ) )
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "argument_list" {
// The inner argument_list contains the actual attributes
let mut inner_cursor = child.walk();
for inner_child in child.children(&mut inner_cursor) {
match inner_child.kind() {
"argument_list" => {
// This is the ((...)) inner list
let mut attr_cursor = inner_child.walk();
for attr_child in inner_child.children(&mut attr_cursor) {
match attr_child.kind() {
"identifier" => {
// Simple attribute like "packed"
let attr_name = self.node_text(attr_child, source);
attributes.push(format!("__attribute__(({}))", attr_name));
}
"call_expression" => {
// Attribute with arguments like "aligned(4)"
let attr_text = self.node_text(attr_child, source);
attributes.push(format!("__attribute__(({}))", attr_text));
}
_ => {}
}
}
}
_ => {}
}
}
}
}
}
/// Extract function pointer from a type_definition or declaration.
/// Handles: typedef int (*fn_ptr)(int, int); or void (*callback)(void);
fn extract_function_pointer(&self, node: Node, source: &[u8]) -> Option<FunctionInfo> {
let is_typedef = node.kind() == "type_definition";
// Find the function_declarator containing parenthesized_declarator
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "function_declarator" {
return self.extract_fn_ptr_from_declarator(child, node, source, is_typedef);
}
}
None
}
/// Extract function pointer details from a function_declarator node.
fn extract_fn_ptr_from_declarator(
&self,
func_decl: Node,
parent: Node,
source: &[u8],
is_typedef: bool,
) -> Option<FunctionInfo> {
// Look for parenthesized_declarator containing pointer_declarator
let paren_decl = self.child_by_field(func_decl, "declarator")?;
if paren_decl.kind() != "parenthesized_declarator" {
return None;
}
// Find the pointer_declarator inside parenthesized_declarator
let mut cursor = paren_decl.walk();
let mut fn_ptr_name = None;
for child in paren_decl.children(&mut cursor) {
if child.kind() == "pointer_declarator" {
// Get the name - could be identifier or type_identifier
if let Some(decl) = self.child_by_field(child, "declarator") {
fn_ptr_name = Some(self.node_text(decl, source));
}
}
}
let name = fn_ptr_name?;
// Extract return type from parent node
let return_type = self.extract_return_type(parent, source);
// Extract parameters from function_declarator
let params = self
.child_by_field(func_decl, "parameters")
.map(|p| self.extract_params(p, source))
.unwrap_or_default();
let docstring = self.get_doc_comment(parent, source);
let mut decorators = vec!["function_pointer".to_string()];
if is_typedef {
decorators.push("typedef".to_string());
}
Some(FunctionInfo {
name,
params,
return_type,
docstring,
is_method: false,
is_async: false,
decorators,
line_number: parent.start_position().row + 1,
end_line_number: Some(parent.end_position().row + 1),
language: "c".to_string(),
})
}
/// Extract return type from a function definition or declaration.
fn extract_return_type(&self, node: Node, source: &[u8]) -> Option<String> {
let mut type_parts = Vec::new();
let mut pointer_count = 0;
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"storage_class_specifier" => {
// Skip storage class (static, extern, etc.) for return type
}
"type_qualifier" => {
type_parts.push(self.node_text(child, source));
}
"primitive_type" | "type_identifier" | "sized_type_specifier" => {
type_parts.push(self.node_text(child, source));
}
"struct_specifier" => {
if let Some(name) = self.child_by_field(child, "name") {
type_parts.push(format!("struct {}", self.node_text(name, source)));
}
}
"pointer_declarator" => {
// Return type with pointer: int* func()
// Count asterisks at the start of the declarator chain
let mut current = child;
while current.kind() == "pointer_declarator" {
pointer_count += 1;
if let Some(decl) = self.child_by_field(current, "declarator") {
current = decl;
} else {
let mut c = current.walk();
let mut found = false;
for ch in current.children(&mut c) {
if ch.kind() != "*" {
current = ch;
found = true;
break;
}
}
if !found {
break;
}
}
}
}
_ => {}
}
}
if type_parts.is_empty() {
return None;
}
let pointers = "*".repeat(pointer_count);
Some(format!("{}{}", type_parts.join(" "), pointers))
}
/// Check if a function has a specific storage class specifier.
fn has_storage_class(&self, node: Node, source: &[u8], specifier: &str) -> bool {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "storage_class_specifier" {
if self.get_text(child, source).trim() == specifier {
return true;
}
}
}
false
}
/// Check if a function body contains inline assembly (gnu_asm_expression).
///
/// Detects both `asm` and `__asm__` statements, including extended asm
/// with volatile, goto, and operand specifications.
fn contains_inline_assembly(&self, node: Node) -> bool {
// Check current node
if node.kind() == "gnu_asm_expression" {
return true;
}
// Recursively check children
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if self.contains_inline_assembly(child) {
return true;
}
}
false
}
/// Extract a static assertion declaration.
///
/// Handles both `_Static_assert` (C11) and `static_assert` (C23) forms.
/// Since tree-sitter-c parses these as call_expression, we detect them
/// by checking the function identifier name.
///
/// Returns a FunctionInfo with decorator "static_assert" containing
/// the condition expression and optional message.
fn extract_static_assert(&self, node: Node, source: &[u8]) -> Option<FunctionInfo> {
// Must be an expression_statement containing a call_expression
if node.kind() != "expression_statement" {
return None;
}
let call_expr = node.children(&mut node.walk()).find(|c| c.kind() == "call_expression")?;
// Check if function name is _Static_assert or static_assert
let func_node = self.child_by_field(call_expr, "function")?;
let func_name = self.node_text(func_node, source);
if func_name != "_Static_assert" && func_name != "static_assert" {
return None;
}
// Extract arguments
let args_node = self.child_by_field(call_expr, "arguments")?;
let mut params = Vec::new();
let mut cursor = args_node.walk();
for child in args_node.children(&mut cursor) {
match child.kind() {
"binary_expression" | "sizeof_expression" | "identifier" | "number_literal" => {
// The condition expression
params.push(self.node_text(child, source));
}
"string_literal" => {
// The message (optional in C23)
params.push(self.node_text(child, source));
}
_ => {}
}
}
// Format: condition as first param, message as second (if present)
let docstring = if params.len() > 1 {
Some(params[1].trim_matches('"').to_string())
} else {
None
};
Some(FunctionInfo {
name: format!("static_assert({})", params.first().unwrap_or(&String::new())),
params: Vec::new(),
return_type: None,
docstring,
is_method: false,
is_async: false,
decorators: vec!["static_assert".to_string()],
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
})
}
/// Extract a thread-local variable declaration.
///
/// Detects variables with `__thread` (GCC extension) or `_Thread_local` (C11)
/// storage class specifier. Note: tree-sitter-c reliably parses `__thread`,
/// but `_Thread_local` may produce parse errors in some tree-sitter versions.
fn extract_thread_local_variable(&self, node: Node, source: &[u8]) -> Option<FunctionInfo> {
if node.kind() != "declaration" {
return None;
}
// Check for __thread storage class specifier
let has_thread_local = self.has_storage_class(node, source, "__thread");
if !has_thread_local {
return None;
}
// Skip function declarations - they should be handled elsewhere
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "function_declarator" {
return None;
}
}
// Extract variable name from init_declarator or identifier
let mut var_name = String::new();
let mut var_type = String::new();
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"primitive_type" | "type_identifier" | "sized_type_specifier" => {
var_type = self.node_text(child, source);
}
"init_declarator" => {
if let Some(decl) = self.child_by_field(child, "declarator") {
var_name = self.node_text(decl, source);
}
}
"identifier" => {
if var_name.is_empty() {
var_name = self.node_text(child, source);
}
}
"pointer_declarator" => {
let (name, ptr_count) = self.extract_pointer_declarator(child, source);
var_name = name;
var_type = format!("{}{}", var_type, "*".repeat(ptr_count));
}
_ => {}
}
}
if var_name.is_empty() {
return None;
}
let mut decorators = vec!["thread_local".to_string(), "variable".to_string()];
// Check for other storage class specifiers
if self.has_storage_class(node, source, "static") {
decorators.push("static".to_string());
}
if self.has_storage_class(node, source, "extern") {
decorators.push("extern".to_string());
}
let docstring = self.get_doc_comment(node, source);
Some(FunctionInfo {
name: var_name,
params: Vec::new(),
return_type: if var_type.is_empty() {
None
} else {
Some(var_type)
},
docstring,
is_method: false,
is_async: false,
decorators,
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
})
}
/// Extract function name from a function_declarator.
fn extract_function_name(&self, node: Node, source: &[u8]) -> Option<String> {
// The declarator field contains the actual identifier (possibly wrapped in pointer_declarator)
if let Some(declarator) = self.child_by_field(node, "declarator") {
return self.extract_name_from_declarator(declarator, source);
}
// Fallback: search children
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "identifier" {
return Some(self.node_text(child, source));
}
if child.kind() == "pointer_declarator" {
let (name, _) = self.extract_pointer_declarator(child, source);
if !name.is_empty() {
return Some(name);
}
}
}
None
}
/// Extract name from a declarator node (handles nested pointer_declarator).
fn extract_name_from_declarator(&self, node: Node, source: &[u8]) -> Option<String> {
match node.kind() {
"identifier" => Some(self.node_text(node, source)),
"pointer_declarator" => {
let (name, _) = self.extract_pointer_declarator(node, source);
if name.is_empty() {
None
} else {
Some(name)
}
}
"function_declarator" => self.extract_function_name(node, source),
_ => None,
}
}
/// Extract variable name from parent declaration for anonymous struct/union/enum.
///
/// For code like `struct { int x; } my_var;`, extracts "my_var" from the declaration.
/// Returns None if parent is not a declaration or no identifier found.
fn extract_name_from_declaration_parent(
&self,
node: Node,
source: &[u8],
) -> Option<String> {
let parent = node.parent()?;
if parent.kind() != "declaration" {
return None;
}
// In a declaration like `struct { ... } var;`, the declarator contains the variable name
let mut cursor = parent.walk();
for child in parent.children(&mut cursor) {
match child.kind() {
"identifier" => {
return Some(self.node_text(child, source));
}
"init_declarator" => {
// Handle `struct { ... } var = {...};`
if let Some(decl) = self.child_by_field(child, "declarator") {
return self.extract_name_from_declarator(decl, source);
}
}
"pointer_declarator" => {
// Handle `struct { ... } *ptr;`
let (name, _) = self.extract_pointer_declarator(child, source);
if !name.is_empty() {
return Some(name);
}
}
"array_declarator" => {
// Handle `struct { ... } arr[10];`
let (name, _) = self.extract_array_declarator(child, source);
if !name.is_empty() {
return Some(name);
}
}
_ => {}
}
}
None
}
/// Build CFG for a C function.
///
/// Supports goto/label control flow: creates proper CFG edges from goto
/// statements to their target labels, handling both forward and backward jumps.
fn build_c_cfg(&self, node: Node, source: &[u8], func_name: &str) -> CFGInfo {
let mut blocks = HashMap::new();
let mut edges = Vec::new();
let mut block_id = 0;
let mut exits = Vec::new();
// Label tracking for goto support
let mut label_blocks: HashMap<String, BlockId> = HashMap::new();
let mut pending_gotos: Vec<(BlockId, String)> = Vec::new();
// Entry block
let entry = BlockId(block_id);
blocks.insert(
entry,
CFGBlock {
id: entry,
label: "entry".to_string(),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: node.start_position().row + 1,
end_line: node.start_position().row + 1,
},
);
block_id += 1;
// Find body (compound_statement)
if let Some(body) = self.child_by_field(node, "body") {
self.process_cfg_block(
body,
source,
&mut blocks,
&mut edges,
&mut block_id,
entry,
&mut exits,
&mut Vec::new(),
&mut Vec::new(),
&mut label_blocks,
&mut pending_gotos,
);
}
// Resolve pending goto edges (forward references to labels)
for (from_block, target_label) in pending_gotos {
if let Some(&target_block) = label_blocks.get(&target_label) {
edges.push(CFGEdge::from_label(from_block, target_block, Some(format!("goto {}", target_label))));
}
}
// If no explicit exits, the entry block is also an exit
if exits.is_empty() {
exits.push(entry);
}
CFGInfo {
function_name: func_name.to_string(),
blocks,
edges,
entry,
exits,
decision_points: 0, // TODO: Count decision points for accurate cyclomatic complexity
comprehension_decision_points: 0, // C doesn't have comprehensions
nested_cfgs: HashMap::new(), // C doesn't have closures but may have nested functions via GCC extension
is_async: false, // C doesn't have async/await
await_points: 0, // C doesn't have await
blocking_calls: Vec::new(), // C doesn't have async context
..Default::default()
}
}
/// Process a compound statement for CFG construction.
///
/// Handles goto/label control flow by tracking label blocks and pending goto edges.
/// Labels create new blocks that can be targeted by goto statements.
/// Gotos create edges to their target labels (resolved immediately if label seen,
/// or queued in pending_gotos for forward references).
#[allow(clippy::too_many_arguments)]
fn process_cfg_block(
&self,
node: Node,
source: &[u8],
blocks: &mut HashMap<BlockId, CFGBlock>,
edges: &mut Vec<CFGEdge>,
block_id: &mut usize,
current_block: BlockId,
exits: &mut Vec<BlockId>,
loop_headers: &mut Vec<BlockId>,
loop_exits: &mut Vec<BlockId>,
label_blocks: &mut HashMap<String, BlockId>,
pending_gotos: &mut Vec<(BlockId, String)>,
) -> BlockId {
// Handle the case where a single statement is passed directly (not a block-like construct)
// This happens when if/while/for consequences are single statements without braces
let node_kind = node.kind();
// These are block-like constructs that contain children we should iterate over
let is_block_like = matches!(
node_kind,
"compound_statement" | "case_statement" | "translation_unit"
);
if !is_block_like {
// Single statement - delegate to statement handler
let mut unreachable = false;
return self.process_cfg_statement(
node,
source,
blocks,
edges,
block_id,
current_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
&mut unreachable,
);
}
let mut last_block = current_block;
let mut cursor = node.walk();
// Track if we're in unreachable code after goto/return/break/continue (no fall-through)
let mut unreachable = false;
for child in node.children(&mut cursor) {
match child.kind() {
"return_statement" => {
if unreachable {
continue;
}
*block_id += 1;
let ret_block = BlockId(*block_id);
let stmt = self.node_text(child, source);
blocks.insert(
ret_block,
CFGBlock {
id: ret_block,
label: "return".to_string(),
block_type: BlockType::Body,
statements: vec![stmt],
func_calls: Vec::new(),
start_line: child.start_position().row + 1,
end_line: child.end_position().row + 1,
},
);
edges.push(CFGEdge::from_label(last_block, ret_block, None));
exits.push(ret_block);
last_block = ret_block;
unreachable = true;
}
"labeled_statement" => {
// labeled_statement has structure: label: statement
// The label field contains the statement_identifier
let label_name = self
.child_by_field(child, "label")
.map(|n| self.node_text(n, source))
.unwrap_or_else(|| "unknown_label".to_string());
// Create a new block for this label
*block_id += 1;
let label_block = BlockId(*block_id);
blocks.insert(
label_block,
CFGBlock {
id: label_block,
label: format!("{}:", label_name),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: child.start_position().row + 1,
end_line: child.end_position().row + 1,
},
);
// Register this label for goto resolution
label_blocks.insert(label_name.clone(), label_block);
// Add fall-through edge from previous block (if not unreachable)
if !unreachable {
edges.push(CFGEdge::from_label(last_block, label_block, None));
}
// A label makes subsequent code reachable again
unreachable = false;
last_block = label_block;
// Process the nested statement that follows the label
// The statement is typically the last child after 'label' and ':'
let mut stmt_cursor = child.walk();
for stmt_child in child.children(&mut stmt_cursor) {
// Skip the label identifier and the colon
if stmt_child.kind() != "statement_identifier" && stmt_child.kind() != ":" {
last_block = self.process_cfg_statement(
stmt_child,
source,
blocks,
edges,
block_id,
last_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
&mut unreachable,
);
}
}
}
"goto_statement" => {
if unreachable {
continue;
}
// goto_statement has structure: goto label;
// The label field contains the target identifier
let target_label = self
.child_by_field(child, "label")
.map(|n| self.node_text(n, source))
.unwrap_or_else(|| "unknown_label".to_string());
// Add the goto statement to current block
if let Some(block) = blocks.get_mut(&last_block) {
let stmt = self.node_text(child, source);
block.statements.push(stmt);
block.end_line = child.end_position().row + 1;
}
// Create edge to target label
if let Some(&target_block) = label_blocks.get(&target_label) {
// Label already seen (backward goto)
edges.push(CFGEdge::from_label(last_block, target_block, Some(format!("goto {}", target_label))));
} else {
// Label not yet seen (forward goto) - queue for later resolution
pending_gotos.push((last_block, target_label));
}
// After goto, there's no fall-through
unreachable = true;
}
"if_statement" => {
if unreachable {
continue;
}
last_block = self.process_if_cfg(
child,
source,
blocks,
edges,
block_id,
last_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
);
}
"while_statement" => {
if unreachable {
continue;
}
last_block = self.process_while_cfg(
child,
source,
blocks,
edges,
block_id,
last_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
);
}
"for_statement" => {
if unreachable {
continue;
}
last_block = self.process_for_cfg(
child,
source,
blocks,
edges,
block_id,
last_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
);
}
"do_statement" => {
if unreachable {
continue;
}
last_block = self.process_do_while_cfg(
child,
source,
blocks,
edges,
block_id,
last_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
);
}
"switch_statement" => {
if unreachable {
continue;
}
last_block = self.process_switch_cfg(
child,
source,
blocks,
edges,
block_id,
last_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
);
}
"break_statement" => {
if unreachable {
continue;
}
if let Some(&exit_block) = loop_exits.last() {
edges.push(CFGEdge::from_label(last_block, exit_block, Some("break".to_string())));
}
unreachable = true;
}
"continue_statement" => {
if unreachable {
continue;
}
if let Some(&header) = loop_headers.last() {
edges.push(CFGEdge::from_label(last_block, header, Some("continue".to_string())));
}
unreachable = true;
}
"compound_statement" => {
// Process compound statements even if unreachable (for labels inside)
last_block = self.process_cfg_block(
child,
source,
blocks,
edges,
block_id,
last_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
);
}
// Regular statements
"declaration" | "expression_statement" => {
if unreachable {
continue;
}
if let Some(block) = blocks.get_mut(&last_block) {
let stmt = self.node_text(child, source);
block.statements.push(stmt);
block.end_line = child.end_position().row + 1;
}
}
_ => {}
}
}
last_block
}
/// Process a single statement for CFG (used by labeled_statement).
///
/// This handles the statement that follows a label, which could be any
/// statement type including control flow statements.
#[allow(clippy::too_many_arguments)]
fn process_cfg_statement(
&self,
node: Node,
source: &[u8],
blocks: &mut HashMap<BlockId, CFGBlock>,
edges: &mut Vec<CFGEdge>,
block_id: &mut usize,
current_block: BlockId,
exits: &mut Vec<BlockId>,
loop_headers: &mut Vec<BlockId>,
loop_exits: &mut Vec<BlockId>,
label_blocks: &mut HashMap<String, BlockId>,
pending_gotos: &mut Vec<(BlockId, String)>,
unreachable: &mut bool,
) -> BlockId {
match node.kind() {
"compound_statement" => self.process_cfg_block(
node,
source,
blocks,
edges,
block_id,
current_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
),
"if_statement" => self.process_if_cfg(
node,
source,
blocks,
edges,
block_id,
current_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
),
"while_statement" => self.process_while_cfg(
node,
source,
blocks,
edges,
block_id,
current_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
),
"for_statement" => self.process_for_cfg(
node,
source,
blocks,
edges,
block_id,
current_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
),
"do_statement" => self.process_do_while_cfg(
node,
source,
blocks,
edges,
block_id,
current_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
),
"switch_statement" => self.process_switch_cfg(
node,
source,
blocks,
edges,
block_id,
current_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
),
"goto_statement" => {
let target_label = self
.child_by_field(node, "label")
.map(|n| self.node_text(n, source))
.unwrap_or_else(|| "unknown_label".to_string());
if let Some(block) = blocks.get_mut(¤t_block) {
let stmt = self.node_text(node, source);
block.statements.push(stmt);
block.end_line = node.end_position().row + 1;
}
if let Some(&target_block) = label_blocks.get(&target_label) {
edges.push(CFGEdge::from_label(current_block, target_block, Some(format!("goto {}", target_label))));
} else {
pending_gotos.push((current_block, target_label));
}
*unreachable = true;
current_block
}
"return_statement" => {
*block_id += 1;
let ret_block = BlockId(*block_id);
let stmt = self.node_text(node, source);
blocks.insert(
ret_block,
CFGBlock {
id: ret_block,
label: "return".to_string(),
block_type: BlockType::Body,
statements: vec![stmt],
func_calls: Vec::new(),
start_line: node.start_position().row + 1,
end_line: node.end_position().row + 1,
},
);
edges.push(CFGEdge::from_label(current_block, ret_block, None));
exits.push(ret_block);
*unreachable = true;
ret_block
}
"break_statement" => {
if let Some(&exit_block) = loop_exits.last() {
edges.push(CFGEdge::from_label(current_block, exit_block, Some("break".to_string())));
}
*unreachable = true;
current_block
}
"continue_statement" => {
if let Some(&header) = loop_headers.last() {
edges.push(CFGEdge::from_label(current_block, header, Some("continue".to_string())));
}
*unreachable = true;
current_block
}
_ => {
// Regular statement - add to current block
if let Some(block) = blocks.get_mut(¤t_block) {
let stmt = self.node_text(node, source);
block.statements.push(stmt);
block.end_line = node.end_position().row + 1;
}
current_block
}
}
}
/// Process if statement for CFG.
#[allow(clippy::too_many_arguments)]
fn process_if_cfg(
&self,
node: Node,
source: &[u8],
blocks: &mut HashMap<BlockId, CFGBlock>,
edges: &mut Vec<CFGEdge>,
block_id: &mut usize,
current_block: BlockId,
exits: &mut Vec<BlockId>,
loop_headers: &mut Vec<BlockId>,
loop_exits: &mut Vec<BlockId>,
label_blocks: &mut HashMap<String, BlockId>,
pending_gotos: &mut Vec<(BlockId, String)>,
) -> BlockId {
*block_id += 1;
let cond_block = BlockId(*block_id);
let condition = self
.child_by_field(node, "condition")
.map(|n| self.node_text(n, source))
.unwrap_or_else(|| "condition".to_string());
blocks.insert(
cond_block,
CFGBlock {
id: cond_block,
label: format!("if {}", condition),
block_type: BlockType::Branch,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: node.start_position().row + 1,
end_line: node.start_position().row + 1,
},
);
edges.push(CFGEdge::from_label(current_block, cond_block, None));
// Merge block after if
*block_id += 1;
let merge_block = BlockId(*block_id);
blocks.insert(
merge_block,
CFGBlock {
id: merge_block,
label: "endif".to_string(),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: node.end_position().row + 1,
end_line: node.end_position().row + 1,
},
);
// True branch (consequence)
if let Some(consequence) = self.child_by_field(node, "consequence") {
*block_id += 1;
let true_block = BlockId(*block_id);
blocks.insert(
true_block,
CFGBlock {
id: true_block,
label: "then".to_string(),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: consequence.start_position().row + 1,
end_line: consequence.end_position().row + 1,
},
);
edges.push(CFGEdge::from_label(cond_block, true_block, Some("true".to_string())));
let true_end = self.process_cfg_block(
consequence,
source,
blocks,
edges,
block_id,
true_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
);
if !exits.contains(&true_end) {
edges.push(CFGEdge::from_label(true_end, merge_block, None));
}
}
// False branch (alternative)
if let Some(alternative) = self.child_by_field(node, "alternative") {
*block_id += 1;
let false_block = BlockId(*block_id);
blocks.insert(
false_block,
CFGBlock {
id: false_block,
label: "else".to_string(),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: alternative.start_position().row + 1,
end_line: alternative.end_position().row + 1,
},
);
edges.push(CFGEdge::from_label(cond_block, false_block, Some("false".to_string())));
let false_end = self.process_cfg_block(
alternative,
source,
blocks,
edges,
block_id,
false_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
);
if !exits.contains(&false_end) {
edges.push(CFGEdge::from_label(false_end, merge_block, None));
}
} else {
// No else branch
edges.push(CFGEdge::from_label(cond_block, merge_block, Some("false".to_string())));
}
merge_block
}
/// Process while statement for CFG.
#[allow(clippy::too_many_arguments)]
fn process_while_cfg(
&self,
node: Node,
source: &[u8],
blocks: &mut HashMap<BlockId, CFGBlock>,
edges: &mut Vec<CFGEdge>,
block_id: &mut usize,
current_block: BlockId,
exits: &mut Vec<BlockId>,
loop_headers: &mut Vec<BlockId>,
loop_exits: &mut Vec<BlockId>,
label_blocks: &mut HashMap<String, BlockId>,
pending_gotos: &mut Vec<(BlockId, String)>,
) -> BlockId {
*block_id += 1;
let header_block = BlockId(*block_id);
let condition = self
.child_by_field(node, "condition")
.map(|n| self.node_text(n, source))
.unwrap_or_else(|| "condition".to_string());
blocks.insert(
header_block,
CFGBlock {
id: header_block,
label: format!("while {}", condition),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: node.start_position().row + 1,
end_line: node.start_position().row + 1,
},
);
edges.push(CFGEdge::from_label(current_block, header_block, None));
// Exit block
*block_id += 1;
let exit_block = BlockId(*block_id);
blocks.insert(
exit_block,
CFGBlock {
id: exit_block,
label: "endwhile".to_string(),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: node.end_position().row + 1,
end_line: node.end_position().row + 1,
},
);
loop_headers.push(header_block);
loop_exits.push(exit_block);
// Body
if let Some(body) = self.child_by_field(node, "body") {
*block_id += 1;
let body_block = BlockId(*block_id);
blocks.insert(
body_block,
CFGBlock {
id: body_block,
label: "loop_body".to_string(),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: body.start_position().row + 1,
end_line: body.end_position().row + 1,
},
);
edges.push(CFGEdge::from_label(header_block, body_block, Some("true".to_string())));
let body_end = self.process_cfg_block(
body,
source,
blocks,
edges,
block_id,
body_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
);
if !exits.contains(&body_end) {
edges.push(CFGEdge::from_label(body_end, header_block, Some("back_edge".to_string())));
}
}
edges.push(CFGEdge::from_label(header_block, exit_block, Some("false".to_string())));
loop_headers.pop();
loop_exits.pop();
exit_block
}
/// Process for statement for CFG.
#[allow(clippy::too_many_arguments)]
fn process_for_cfg(
&self,
node: Node,
source: &[u8],
blocks: &mut HashMap<BlockId, CFGBlock>,
edges: &mut Vec<CFGEdge>,
block_id: &mut usize,
current_block: BlockId,
exits: &mut Vec<BlockId>,
loop_headers: &mut Vec<BlockId>,
loop_exits: &mut Vec<BlockId>,
label_blocks: &mut HashMap<String, BlockId>,
pending_gotos: &mut Vec<(BlockId, String)>,
) -> BlockId {
// For loop: for (init; cond; update) body
*block_id += 1;
let header_block = BlockId(*block_id);
let header_text = self
.node_text(node, source)
.lines()
.next()
.unwrap_or("for")
.to_string();
blocks.insert(
header_block,
CFGBlock {
id: header_block,
label: header_text,
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: node.start_position().row + 1,
end_line: node.start_position().row + 1,
},
);
edges.push(CFGEdge::from_label(current_block, header_block, None));
// Exit block
*block_id += 1;
let exit_block = BlockId(*block_id);
blocks.insert(
exit_block,
CFGBlock {
id: exit_block,
label: "endfor".to_string(),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: node.end_position().row + 1,
end_line: node.end_position().row + 1,
},
);
loop_headers.push(header_block);
loop_exits.push(exit_block);
// Process body - handles both compound_statement (braces) and single statements
if let Some(body) = self.child_by_field(node, "body") {
*block_id += 1;
let body_block = BlockId(*block_id);
blocks.insert(
body_block,
CFGBlock {
id: body_block,
label: "loop_body".to_string(),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: body.start_position().row + 1,
end_line: body.end_position().row + 1,
},
);
edges.push(CFGEdge::from_label(header_block, body_block, Some("iterate".to_string())));
let body_end = self.process_cfg_block(
body,
source,
blocks,
edges,
block_id,
body_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
);
if !exits.contains(&body_end) {
edges.push(CFGEdge::from_label(body_end, header_block, Some("back_edge".to_string())));
}
}
edges.push(CFGEdge::from_label(header_block, exit_block, Some("done".to_string())));
loop_headers.pop();
loop_exits.pop();
exit_block
}
/// Process do-while statement for CFG.
#[allow(clippy::too_many_arguments)]
fn process_do_while_cfg(
&self,
node: Node,
source: &[u8],
blocks: &mut HashMap<BlockId, CFGBlock>,
edges: &mut Vec<CFGEdge>,
block_id: &mut usize,
current_block: BlockId,
exits: &mut Vec<BlockId>,
loop_headers: &mut Vec<BlockId>,
loop_exits: &mut Vec<BlockId>,
label_blocks: &mut HashMap<String, BlockId>,
pending_gotos: &mut Vec<(BlockId, String)>,
) -> BlockId {
// Body block (executes at least once)
*block_id += 1;
let body_block = BlockId(*block_id);
blocks.insert(
body_block,
CFGBlock {
id: body_block,
label: "do".to_string(),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: node.start_position().row + 1,
end_line: node.start_position().row + 1,
},
);
edges.push(CFGEdge::from_label(current_block, body_block, None));
// Condition block (at the end)
*block_id += 1;
let cond_block = BlockId(*block_id);
let condition = self
.child_by_field(node, "condition")
.map(|n| self.node_text(n, source))
.unwrap_or_else(|| "condition".to_string());
blocks.insert(
cond_block,
CFGBlock {
id: cond_block,
label: format!("while {}", condition),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: node.end_position().row,
end_line: node.end_position().row + 1,
},
);
// Exit block
*block_id += 1;
let exit_block = BlockId(*block_id);
blocks.insert(
exit_block,
CFGBlock {
id: exit_block,
label: "enddo".to_string(),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: node.end_position().row + 1,
end_line: node.end_position().row + 1,
},
);
loop_headers.push(cond_block);
loop_exits.push(exit_block);
// Process body
if let Some(body) = self.child_by_field(node, "body") {
let body_end = self.process_cfg_block(
body,
source,
blocks,
edges,
block_id,
body_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
);
if !exits.contains(&body_end) {
edges.push(CFGEdge::from_label(body_end, cond_block, None));
}
}
// Condition edges
edges.push(CFGEdge::from_label(cond_block, body_block, Some("true".to_string())));
edges.push(CFGEdge::from_label(cond_block, exit_block, Some("false".to_string())));
loop_headers.pop();
loop_exits.pop();
exit_block
}
/// Process switch statement for CFG.
#[allow(clippy::too_many_arguments)]
fn process_switch_cfg(
&self,
node: Node,
source: &[u8],
blocks: &mut HashMap<BlockId, CFGBlock>,
edges: &mut Vec<CFGEdge>,
block_id: &mut usize,
current_block: BlockId,
exits: &mut Vec<BlockId>,
loop_headers: &mut Vec<BlockId>,
loop_exits: &mut Vec<BlockId>,
label_blocks: &mut HashMap<String, BlockId>,
pending_gotos: &mut Vec<(BlockId, String)>,
) -> BlockId {
*block_id += 1;
let switch_block = BlockId(*block_id);
let expr = self
.child_by_field(node, "condition")
.map(|n| self.node_text(n, source))
.unwrap_or_else(|| "expr".to_string());
blocks.insert(
switch_block,
CFGBlock {
id: switch_block,
label: format!("switch {}", expr),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: node.start_position().row + 1,
end_line: node.start_position().row + 1,
},
);
edges.push(CFGEdge::from_label(current_block, switch_block, None));
// Exit block
*block_id += 1;
let exit_block = BlockId(*block_id);
blocks.insert(
exit_block,
CFGBlock {
id: exit_block,
label: "endswitch".to_string(),
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: node.end_position().row + 1,
end_line: node.end_position().row + 1,
},
);
// Push exit for break statements
loop_exits.push(exit_block);
// Find body and process cases
if let Some(body) = self.child_by_field(node, "body") {
let mut cursor = body.walk();
for child in body.children(&mut cursor) {
if child.kind() == "case_statement" {
*block_id += 1;
let case_block = BlockId(*block_id);
let case_label = self
.node_text(child, source)
.lines()
.next()
.unwrap_or("case")
.to_string();
blocks.insert(
case_block,
CFGBlock {
id: case_block,
label: case_label,
block_type: BlockType::Body,
statements: Vec::new(),
func_calls: Vec::new(),
start_line: child.start_position().row + 1,
end_line: child.end_position().row + 1,
},
);
edges.push(CFGEdge::from_label(switch_block, case_block, None));
let case_end = self.process_cfg_block(
child,
source,
blocks,
edges,
block_id,
case_block,
exits,
loop_headers,
loop_exits,
label_blocks,
pending_gotos,
);
if !exits.contains(&case_end) {
edges.push(CFGEdge::from_label(case_end, exit_block, None));
}
}
}
}
loop_exits.pop();
exit_block
}
/// Build DFG for a C function.
fn build_c_dfg(&self, node: Node, source: &[u8], func_name: &str) -> DFGInfo {
let mut edges = Vec::new();
let mut definitions: HashMap<String, Vec<usize>> = HashMap::new();
let mut uses: HashMap<String, Vec<usize>> = HashMap::new();
// Extract parameters as initial definitions
if let Some(declarator) = self.child_by_field(node, "declarator") {
if let Some(params) = self.child_by_field(declarator, "parameters") {
let line = params.start_position().row + 1;
let mut cursor = params.walk();
for child in params.children(&mut cursor) {
if child.kind() == "parameter_declaration" {
self.extract_param_definition(
child,
source,
line,
&mut edges,
&mut definitions,
);
}
}
}
}
// Process body
if let Some(body) = self.child_by_field(node, "body") {
self.extract_dfg_from_block(body, source, &mut edges, &mut definitions, &mut uses);
}
DFGInfo::new(func_name.to_string(), edges, definitions, uses)
}
/// Extract parameter definitions for DFG.
fn extract_param_definition(
&self,
node: Node,
source: &[u8],
line: usize,
edges: &mut Vec<DataflowEdge>,
definitions: &mut HashMap<String, Vec<usize>>,
) {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"identifier" => {
let name = self.node_text(child, source);
if !name.is_empty() {
definitions.entry(name.clone()).or_default().push(line);
edges.push(DataflowEdge {
variable: name,
from_line: line,
to_line: line,
kind: DataflowKind::Param,
});
}
}
"pointer_declarator" => {
let (name, _) = self.extract_pointer_declarator(child, source);
if !name.is_empty() {
definitions.entry(name.clone()).or_default().push(line);
edges.push(DataflowEdge {
variable: name,
from_line: line,
to_line: line,
kind: DataflowKind::Param,
});
}
}
_ => {}
}
}
}
/// Extract data flow from a compound statement.
fn extract_dfg_from_block(
&self,
node: Node,
source: &[u8],
edges: &mut Vec<DataflowEdge>,
definitions: &mut HashMap<String, Vec<usize>>,
uses: &mut HashMap<String, Vec<usize>>,
) {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
let line = child.start_position().row + 1;
match child.kind() {
"declaration" => {
self.extract_declaration_dfg(child, source, line, edges, definitions, uses);
}
"expression_statement" => {
self.extract_expression_dfg(child, source, line, edges, definitions, uses);
}
"return_statement" => {
self.extract_return_dfg(child, source, line, edges, definitions, uses);
}
"if_statement" | "while_statement" | "for_statement" | "do_statement"
| "switch_statement" => {
self.extract_dfg_from_block(child, source, edges, definitions, uses);
}
"compound_statement" => {
self.extract_dfg_from_block(child, source, edges, definitions, uses);
}
_ => {}
}
}
}
/// Extract DFG from a declaration.
fn extract_declaration_dfg(
&self,
node: Node,
source: &[u8],
line: usize,
edges: &mut Vec<DataflowEdge>,
definitions: &mut HashMap<String, Vec<usize>>,
uses: &mut HashMap<String, Vec<usize>>,
) {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "init_declarator" {
// Variable with initialization
if let Some(declarator) = self.child_by_field(child, "declarator") {
let name = self.extract_name_from_declarator(declarator, source);
if let Some(name) = name {
definitions.entry(name.clone()).or_default().push(line);
edges.push(DataflowEdge {
variable: name,
from_line: line,
to_line: line,
kind: DataflowKind::Definition,
});
}
}
// Extract uses from value
if let Some(value) = self.child_by_field(child, "value") {
self.extract_uses_from_expr(value, source, line, edges, definitions, uses);
}
} else if child.kind() == "identifier" || child.kind() == "pointer_declarator" {
// Declaration without initialization
let name = self.extract_name_from_declarator(child, source);
if let Some(name) = name {
definitions.entry(name.clone()).or_default().push(line);
edges.push(DataflowEdge {
variable: name,
from_line: line,
to_line: line,
kind: DataflowKind::Definition,
});
}
}
}
}
/// Extract DFG from an expression statement.
fn extract_expression_dfg(
&self,
node: Node,
source: &[u8],
line: usize,
edges: &mut Vec<DataflowEdge>,
definitions: &mut HashMap<String, Vec<usize>>,
uses: &mut HashMap<String, Vec<usize>>,
) {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "assignment_expression" {
// Left side is definition/mutation
if let Some(left) = self.child_by_field(child, "left") {
let name = self.extract_name_from_declarator(left, source);
if let Some(name) = name {
definitions.entry(name.clone()).or_default().push(line);
edges.push(DataflowEdge {
variable: name,
from_line: line,
to_line: line,
kind: DataflowKind::Mutation,
});
}
}
// Right side has uses
if let Some(right) = self.child_by_field(child, "right") {
self.extract_uses_from_expr(right, source, line, edges, definitions, uses);
}
} else if child.kind() == "update_expression" {
// x++ or ++x is both use and mutation
self.extract_uses_from_expr(child, source, line, edges, definitions, uses);
} else if child.kind() == "call_expression" {
self.extract_uses_from_expr(child, source, line, edges, definitions, uses);
}
}
}
/// Extract DFG from a return statement.
fn extract_return_dfg(
&self,
node: Node,
source: &[u8],
line: usize,
edges: &mut Vec<DataflowEdge>,
definitions: &HashMap<String, Vec<usize>>,
uses: &mut HashMap<String, Vec<usize>>,
) {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.is_named() && child.kind() != "return" {
self.extract_return_uses(child, source, line, edges, definitions, uses);
}
}
}
/// Extract uses from a return expression.
fn extract_return_uses(
&self,
node: Node,
source: &[u8],
line: usize,
edges: &mut Vec<DataflowEdge>,
definitions: &HashMap<String, Vec<usize>>,
uses: &mut HashMap<String, Vec<usize>>,
) {
if node.kind() == "identifier" {
let name = self.node_text(node, source);
uses.entry(name.clone()).or_default().push(line);
// Create return edge
if let Some(def_lines) = definitions.get(&name) {
if let Some(&def_line) = def_lines.last() {
edges.push(DataflowEdge {
variable: name,
from_line: def_line,
to_line: line,
kind: DataflowKind::Return,
});
}
}
} else {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.is_named() {
self.extract_return_uses(child, source, line, edges, definitions, uses);
}
}
}
}
/// Extract variable uses from an expression.
fn extract_uses_from_expr(
&self,
node: Node,
source: &[u8],
line: usize,
edges: &mut Vec<DataflowEdge>,
definitions: &HashMap<String, Vec<usize>>,
uses: &mut HashMap<String, Vec<usize>>,
) {
if node.kind() == "identifier" {
let name = self.node_text(node, source);
uses.entry(name.clone()).or_default().push(line);
// Create use edge from most recent definition
if let Some(def_lines) = definitions.get(&name) {
if let Some(&def_line) = def_lines.last() {
edges.push(DataflowEdge {
variable: name,
from_line: def_line,
to_line: line,
kind: DataflowKind::Use,
});
}
}
} else {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.is_named() {
self.extract_uses_from_expr(child, source, line, edges, definitions, uses);
}
}
}
}
}
impl Language for C {
fn name(&self) -> &'static str {
"c"
}
fn extensions(&self) -> &[&'static str] {
&[".c", ".h"]
}
fn parser(&self) -> Result<Parser> {
let mut parser = Parser::new();
parser
.set_language(&tree_sitter_c::LANGUAGE.into())
.map_err(|e| BrrrError::TreeSitter(e.to_string()))?;
Ok(parser)
}
fn extract_function(&self, node: Node, source: &[u8]) -> Option<FunctionInfo> {
match node.kind() {
"function_definition" => {
// func_definition has type, declarator, body
let declarator = self.child_by_field(node, "declarator")?;
let name = self.extract_function_name(declarator, source)?;
// Check for K&R style parameters
let is_knr = self.is_knr_style(node);
// Extract parameters - handle K&R style differently
let params = if is_knr {
// K&R style: parameter names are in parameter_list,
// types are in separate declarations
let knr_types = self.extract_knr_params(node, source);
// Get parameter names from the parameter_list
let param_names: Vec<String> = self
.child_by_field(declarator, "parameters")
.map(|p| {
let mut names = Vec::new();
let mut cursor = p.walk();
for child in p.children(&mut cursor) {
if child.kind() == "identifier" {
names.push(self.node_text(child, source));
}
}
names
})
.unwrap_or_default();
// Merge names with their types
param_names
.into_iter()
.map(|name| {
if let Some(ty) = knr_types.get(&name) {
format!("{} {}", ty, name)
} else {
name
}
})
.collect()
} else {
// Modern style: types and names together in parameter_list
self.child_by_field(declarator, "parameters")
.map(|p| self.extract_params(p, source))
.unwrap_or_default()
};
// Extract return type
let return_type = self.extract_return_type(node, source);
// Extract doc comment
let docstring = self.get_doc_comment(node, source);
// Build decorators list
let mut decorators = Vec::new();
// Mark K&R style functions
if is_knr {
decorators.push("knr_style".to_string());
}
// Storage class specifiers
if self.has_storage_class(node, source, "static") {
decorators.push("static".to_string());
}
if self.has_storage_class(node, source, "inline") {
decorators.push("inline".to_string());
}
if self.has_storage_class(node, source, "extern") {
decorators.push("extern".to_string());
}
// Extract __attribute__ decorators
decorators.extend(self.extract_attributes(node, source));
// Check for inline assembly in function body
if let Some(body) = self.child_by_field(node, "body") {
if self.contains_inline_assembly(body) {
decorators.push("inline_assembly".to_string());
}
}
Some(FunctionInfo {
name,
params,
return_type,
docstring,
is_method: false,
is_async: false,
decorators,
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
})
}
"declaration" => {
// Function declaration (prototype): int foo(int x);
// Or function pointer variable: void (*callback)(void);
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "function_declarator" {
// Check if this is a function pointer (has parenthesized_declarator)
if let Some(decl) = self.child_by_field(child, "declarator") {
if decl.kind() == "parenthesized_declarator" {
// This is a function pointer variable
return self.extract_function_pointer(node, source);
}
}
// Regular function declaration
let name = self.extract_function_name(child, source)?;
let params = self
.child_by_field(child, "parameters")
.map(|p| self.extract_params(p, source))
.unwrap_or_default();
let return_type = self.extract_return_type(node, source);
let docstring = self.get_doc_comment(node, source);
let mut decorators = vec!["declaration".to_string()];
if self.has_storage_class(node, source, "static") {
decorators.push("static".to_string());
}
if self.has_storage_class(node, source, "extern") {
decorators.push("extern".to_string());
}
// Extract __attribute__ decorators
decorators.extend(self.extract_attributes(node, source));
return Some(FunctionInfo {
name,
params,
return_type,
docstring,
is_method: false,
is_async: false,
decorators,
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
});
}
// Also handle pointer return type: int* foo()
if child.kind() == "pointer_declarator" {
let mut current = child;
while current.kind() == "pointer_declarator" {
if let Some(decl) = self.child_by_field(current, "declarator") {
current = decl;
} else {
let mut c = current.walk();
let mut found = false;
for ch in current.children(&mut c) {
if ch.kind() != "*" {
current = ch;
found = true;
break;
}
}
if !found {
break;
}
}
}
if current.kind() == "function_declarator" {
let name = self.extract_function_name(current, source)?;
let params = self
.child_by_field(current, "parameters")
.map(|p| self.extract_params(p, source))
.unwrap_or_default();
let return_type = self.extract_return_type(node, source);
let docstring = self.get_doc_comment(node, source);
let mut decorators = vec!["declaration".to_string()];
if self.has_storage_class(node, source, "static") {
decorators.push("static".to_string());
}
// Extract __attribute__ decorators
decorators.extend(self.extract_attributes(node, source));
return Some(FunctionInfo {
name,
params,
return_type,
docstring,
is_method: false,
is_async: false,
decorators,
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
});
}
}
}
// If not a function declaration, check for thread-local variable
self.extract_thread_local_variable(node, source)
}
// Macro definitions
"preproc_def" => self.extract_object_macro(node, source),
"preproc_function_def" => self.extract_function_macro(node, source),
// Function pointer typedef: typedef int (*fn_ptr)(int, int);
"type_definition" => self.extract_function_pointer(node, source),
// Static assertions (C11): _Static_assert or static_assert
"expression_statement" => self.extract_static_assert(node, source),
_ => None,
}
}
fn extract_class(&self, node: Node, source: &[u8]) -> Option<ClassInfo> {
match node.kind() {
"struct_specifier" => {
// Struct definition: struct Name { ... } or anonymous struct { ... } var;
let explicit_name = self
.child_by_field(node, "name")
.map(|n| self.node_text(n, source));
// Determine name and whether this is anonymous
let (name, is_anonymous) = match explicit_name {
Some(n) => (n, false),
None => {
// Anonymous struct - try to get name from declaration context
// e.g., `struct { int x; } my_var;` -> use "my_var"
let context_name = self.extract_name_from_declaration_parent(node, source);
match context_name {
Some(n) => (n, true),
None => ("<anonymous>".to_string(), true),
}
}
};
let docstring = self.get_doc_comment(node, source);
// Extract fields including bitfield information
let fields = self.extract_struct_fields(node, source);
// Extract anonymous struct/union members
let inner_classes = self.extract_anonymous_members_from_body(node, source, &name);
// Extract __attribute__ decorators
// Attributes may be on parent declaration node
let mut decorators = Vec::new();
if is_anonymous {
decorators.push("anonymous_struct".to_string());
}
if let Some(parent) = node.parent() {
if parent.kind() == "declaration" || parent.kind() == "type_definition" {
decorators.extend(self.extract_attributes(parent, source));
}
}
Some(ClassInfo {
name,
bases: Vec::new(),
docstring,
methods: Vec::new(),
fields,
inner_classes,
decorators,
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
})
}
"type_definition" => {
// typedef struct X X; or typedef struct { ... } Name;
let mut struct_name = None;
let mut typedef_name = None;
let mut struct_node: Option<Node> = None;
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "struct_specifier" || child.kind() == "union_specifier" {
struct_name = self
.child_by_field(child, "name")
.map(|n| self.node_text(n, source));
struct_node = Some(child);
} else if child.kind() == "type_identifier" {
typedef_name = Some(self.node_text(child, source));
}
}
// Check for alias before consuming the values
let mut decorators = vec!["typedef".to_string()];
if struct_name.is_some() && typedef_name.is_some() && struct_name != typedef_name {
decorators.push(format!(
"alias:{}",
struct_name.as_ref().unwrap_or(&String::new())
));
}
// Extract __attribute__ decorators
decorators.extend(self.extract_attributes(node, source));
let name = typedef_name.or(struct_name)?;
let docstring = self.get_doc_comment(node, source);
// Extract fields from the embedded struct/union if present
let fields = struct_node
.map(|s| self.extract_struct_fields(s, source))
.unwrap_or_default();
// Extract inner classes from embedded struct/union
let inner_classes = struct_node
.map(|s| self.extract_anonymous_members_from_body(s, source, &name))
.unwrap_or_default();
Some(ClassInfo {
name,
bases: Vec::new(),
docstring,
methods: Vec::new(),
fields,
inner_classes,
decorators,
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
})
}
"enum_specifier" => {
// enum Name { ... } or anonymous enum { ... } var;
let explicit_name = self
.child_by_field(node, "name")
.map(|n| self.node_text(n, source));
// Determine name and whether this is anonymous
let (name, is_anonymous) = match explicit_name {
Some(n) => (n, false),
None => {
// Anonymous enum - try to get name from declaration context
let context_name = self.extract_name_from_declaration_parent(node, source);
match context_name {
Some(n) => (n, true),
None => ("<anonymous>".to_string(), true),
}
}
};
let docstring = self.get_doc_comment(node, source);
let mut decorators = vec!["enum".to_string()];
if is_anonymous {
decorators.push("anonymous_enum".to_string());
}
Some(ClassInfo {
name,
bases: Vec::new(),
docstring,
methods: Vec::new(),
fields: Vec::new(),
inner_classes: Vec::new(),
decorators,
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
})
}
"union_specifier" => {
// union Name { ... } or anonymous union { ... } var;
let explicit_name = self
.child_by_field(node, "name")
.map(|n| self.node_text(n, source));
// Determine name and whether this is anonymous
let (name, is_anonymous) = match explicit_name {
Some(n) => (n, false),
None => {
// Anonymous union - try to get name from declaration context
let context_name = self.extract_name_from_declaration_parent(node, source);
match context_name {
Some(n) => (n, true),
None => ("<anonymous>".to_string(), true),
}
}
};
let docstring = self.get_doc_comment(node, source);
// Extract fields including bitfield information
let fields = self.extract_struct_fields(node, source);
// Extract anonymous struct/union members
let inner_classes = self.extract_anonymous_members_from_body(node, source, &name);
// Extract __attribute__ decorators
// Attributes may be on parent declaration node
let mut decorators = vec!["union".to_string()];
if is_anonymous {
decorators.push("anonymous_union".to_string());
}
if let Some(parent) = node.parent() {
if parent.kind() == "declaration" || parent.kind() == "type_definition" {
decorators.extend(self.extract_attributes(parent, source));
}
}
Some(ClassInfo {
name,
bases: Vec::new(),
docstring,
methods: Vec::new(),
fields,
inner_classes,
decorators,
line_number: node.start_position().row + 1,
end_line_number: Some(node.end_position().row + 1),
language: "c".to_string(),
})
}
// Preprocessor conditionals
"preproc_ifdef" | "preproc_if" => self.extract_preproc_conditional(node, source),
_ => None,
}
}
fn extract_imports(&self, tree: &Tree, source: &[u8]) -> Vec<ImportInfo> {
let mut imports = Vec::new();
let root = tree.root_node();
self.collect_includes_recursive(root, source, &mut imports);
imports
}
fn function_query(&self) -> &'static str {
r#"[
(function_definition
declarator: (function_declarator
declarator: (identifier) @name)) @function
(function_definition
declarator: (pointer_declarator
declarator: (function_declarator
declarator: (identifier) @name))) @function
(declaration
declarator: (function_declarator
declarator: (identifier) @name)) @function
(preproc_def
name: (identifier) @name) @function
(preproc_function_def
name: (identifier) @name) @function
(type_definition
declarator: (function_declarator
declarator: (parenthesized_declarator
(pointer_declarator
declarator: (type_identifier) @name)))) @function
(declaration
declarator: (function_declarator
declarator: (parenthesized_declarator
(pointer_declarator
declarator: (identifier) @name)))) @function
(expression_statement
(call_expression
function: (identifier) @name)) @function
(declaration
(storage_class_specifier)
declarator: (init_declarator
declarator: (identifier) @name)) @function
]"#
}
fn class_query(&self) -> &'static str {
r#"[
(struct_specifier name: (type_identifier) @name) @struct
(struct_specifier body: (field_declaration_list) @name) @struct
(enum_specifier name: (type_identifier) @name) @enum
(enum_specifier body: (enumerator_list) @name) @enum
(union_specifier name: (type_identifier) @name) @union
(union_specifier body: (field_declaration_list) @name) @union
(type_definition declarator: (type_identifier) @name) @typedef
(preproc_ifdef name: (identifier) @name) @preproc_ifdef
(preproc_if condition: (_) @name) @preproc_if
]"#
}
fn call_query(&self) -> &'static str {
r#"[
; Direct function call: foo()
(call_expression function: (identifier) @callee) @call
; Member access call: obj->method() or obj.method()
(call_expression
function: (field_expression
field: (field_identifier) @callee)) @call
; Pointer dereference call: (*ptr)()
(call_expression
function: (parenthesized_expression
(pointer_expression) @callee)) @call
; Subscript call: callbacks[i]()
(call_expression
function: (subscript_expression) @callee) @call
]"#
}
fn build_cfg(&self, node: Node, source: &[u8]) -> Result<CFGInfo> {
if node.kind() != "function_definition" {
return Err(BrrrError::UnsupportedLanguage(
"Node is not a function definition".to_string(),
));
}
let func_name = self
.child_by_field(node, "declarator")
.and_then(|d| self.extract_function_name(d, source))
.unwrap_or_else(|| "anonymous".to_string());
Ok(self.build_c_cfg(node, source, &func_name))
}
fn build_dfg(&self, node: Node, source: &[u8]) -> Result<DFGInfo> {
if node.kind() != "function_definition" {
return Err(BrrrError::UnsupportedLanguage(
"Node is not a function definition".to_string(),
));
}
let func_name = self
.child_by_field(node, "declarator")
.and_then(|d| self.extract_function_name(d, source))
.unwrap_or_else(|| "anonymous".to_string());
Ok(self.build_c_dfg(node, source, &func_name))
}
/// Skip `.h` header files that contain C++ code.
///
/// Many projects have mixed C/C++ headers. When the user specifies `--lang c`,
/// we should not attempt to parse C++ headers with the C parser, as this would
/// result in parse errors or incorrect extraction.
///
/// This method checks `.h` files for C++ indicators and returns `true` if
/// the file should be skipped (parsed with C++ parser instead).
fn should_skip_file(&self, path: &Path, content: &[u8]) -> bool {
// Only check .h files - .c files are always C
if let Some(ext) = path.extension() {
if ext == "h" {
return is_cpp_header(content);
}
}
false
}
}
impl C {
/// Recursively traverse AST to find all preproc_include nodes.
/// This handles includes nested inside preprocessor conditionals:
/// #ifdef, #ifndef, #if, #else, #elif blocks.
fn collect_includes_recursive(
&self,
node: Node,
source: &[u8],
imports: &mut Vec<ImportInfo>,
) {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"preproc_include" => {
if let Some(import) = self.extract_include(child, source) {
imports.push(import);
}
}
// Recurse into preprocessor conditional blocks
"preproc_ifdef" | "preproc_ifndef" | "preproc_if" | "preproc_else"
| "preproc_elif" => {
self.collect_includes_recursive(child, source, imports);
}
_ => {
// Also check other container nodes that might have includes
if child.child_count() > 0 {
self.collect_includes_recursive(child, source, imports);
}
}
}
}
}
/// Extract a single #include directive.
fn extract_include(&self, node: Node, source: &[u8]) -> Option<ImportInfo> {
let mut path = String::new();
let mut is_system = false;
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"system_lib_string" => {
// #include <stdio.h>
path = self.node_text(child, source);
// Remove < and >
path = path
.trim_start_matches('<')
.trim_end_matches('>')
.to_string();
is_system = true;
}
"string_literal" => {
// #include "myheader.h"
path = self.node_text(child, source);
// Remove quotes
path = path.trim_matches('"').to_string();
is_system = false;
}
_ => {}
}
}
if path.is_empty() {
return None;
}
let mut aliases = HashMap::new();
if is_system {
aliases.insert(path.clone(), "system".to_string());
} else {
aliases.insert(path.clone(), "local".to_string());
}
Some(ImportInfo {
module: path,
names: Vec::new(),
aliases,
is_from: false, // C doesn't have "from X import Y"
level: 0, // C doesn't have relative imports
line_number: node.start_position().row + 1,
visibility: None,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_c(source: &str) -> (Tree, Vec<u8>) {
let c = C;
let mut parser = c.parser().unwrap();
let source_bytes = source.as_bytes().to_vec();
let tree = parser.parse(&source_bytes, None).unwrap();
(tree, source_bytes)
}
#[test]
fn test_extract_simple_function() {
let source = r#"
/* Adds two integers */
int add(int a, int b) {
return a + b;
}
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut found = false;
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "function_definition" {
let func = c.extract_function(child, &source_bytes);
assert!(func.is_some());
let func = func.unwrap();
assert_eq!(func.name, "add");
assert_eq!(func.params.len(), 2);
assert!(func.params[0].contains("int"));
assert!(func.params[0].contains("a"));
assert_eq!(func.return_type, Some("int".to_string()));
assert!(func.docstring.is_some());
assert!(func.docstring.unwrap().contains("Adds two integers"));
assert_eq!(func.language, "c");
found = true;
}
}
assert!(found, "Function definition not found");
}
#[test]
fn test_extract_static_function() {
let source = r#"
static int helper(void) {
return 42;
}
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "function_definition" {
let func = c.extract_function(child, &source_bytes).unwrap();
assert_eq!(func.name, "helper");
assert!(func.decorators.contains(&"static".to_string()));
}
}
}
#[test]
fn test_extract_pointer_return() {
let source = r#"
int* create_array(size_t len) {
return malloc(len * sizeof(int));
}
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "function_definition" {
let func = c.extract_function(child, &source_bytes).unwrap();
assert_eq!(func.name, "create_array");
assert_eq!(func.return_type, Some("int*".to_string()));
}
}
}
#[test]
fn test_extract_struct() {
let source = r#"
/* Person structure */
struct Person {
char* name;
int age;
};
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "struct_specifier" {
let cls = c.extract_class(child, &source_bytes);
assert!(cls.is_some());
let cls = cls.unwrap();
assert_eq!(cls.name, "Person");
assert_eq!(cls.language, "c");
assert!(cls.docstring.is_some());
}
}
}
#[test]
fn test_extract_typedef() {
let source = r#"
typedef struct Node {
int value;
struct Node* next;
} Node;
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "type_definition" {
let cls = c.extract_class(child, &source_bytes);
assert!(cls.is_some());
let cls = cls.unwrap();
assert_eq!(cls.name, "Node");
assert!(cls.decorators.contains(&"typedef".to_string()));
}
}
}
#[test]
fn test_extract_includes() {
let source = r#"
#include <stdio.h>
#include <stdlib.h>
#include "myheader.h"
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let imports = c.extract_imports(&tree, &source_bytes);
assert_eq!(imports.len(), 3);
// System includes
let stdio = imports.iter().find(|i| i.module == "stdio.h").unwrap();
assert_eq!(stdio.aliases.get("stdio.h"), Some(&"system".to_string()));
let stdlib = imports.iter().find(|i| i.module == "stdlib.h").unwrap();
assert_eq!(stdlib.aliases.get("stdlib.h"), Some(&"system".to_string()));
// Local include
let myheader = imports.iter().find(|i| i.module == "myheader.h").unwrap();
assert_eq!(
myheader.aliases.get("myheader.h"),
Some(&"local".to_string())
);
}
#[test]
fn test_extract_includes_in_conditionals() {
// Test that includes nested inside preprocessor conditionals are found
let source = r#"
#include <stdio.h>
#ifdef USE_FEATURE
#include "feature.h"
#endif
#ifndef HAVE_STDLIB
#include <stdlib.h>
#endif
#if defined(LINUX)
#include <unistd.h>
#else
#include <windows.h>
#endif
#ifdef NESTED
#ifdef DEEP
#include "deep.h"
#endif
#endif
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let imports = c.extract_imports(&tree, &source_bytes);
// Should find all 6 includes: stdio.h, feature.h, stdlib.h, unistd.h, windows.h, deep.h
assert_eq!(imports.len(), 6);
// Top-level include
assert!(imports.iter().any(|i| i.module == "stdio.h"));
// Include inside #ifdef
assert!(imports.iter().any(|i| i.module == "feature.h"));
// Include inside #ifndef
assert!(imports.iter().any(|i| i.module == "stdlib.h"));
// Includes inside #if/#else
assert!(imports.iter().any(|i| i.module == "unistd.h"));
assert!(imports.iter().any(|i| i.module == "windows.h"));
// Deeply nested include
assert!(imports.iter().any(|i| i.module == "deep.h"));
}
#[test]
fn test_extract_function_declaration() {
let source = r#"
int process(const char* data, size_t len);
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "declaration" {
let func = c.extract_function(child, &source_bytes);
if let Some(func) = func {
assert_eq!(func.name, "process");
assert!(func.decorators.contains(&"declaration".to_string()));
assert_eq!(func.params.len(), 2);
}
}
}
}
#[test]
fn test_function_signature() {
let func = FunctionInfo {
name: "process".to_string(),
params: vec!["const char* data".to_string(), "size_t len".to_string()],
return_type: Some("int*".to_string()),
docstring: None,
is_method: false,
is_async: false,
decorators: Vec::new(),
line_number: 1,
end_line_number: Some(5),
language: "c".to_string(),
};
assert_eq!(
func.signature(),
"int* process(const char* data, size_t len)"
);
}
#[test]
fn test_extract_enum() {
let source = r#"
enum Color {
RED,
GREEN,
BLUE
};
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "enum_specifier" {
let cls = c.extract_class(child, &source_bytes);
assert!(cls.is_some());
let cls = cls.unwrap();
assert_eq!(cls.name, "Color");
assert!(cls.decorators.contains(&"enum".to_string()));
}
}
}
#[test]
fn test_build_cfg() {
let source = r#"
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "function_definition" {
let cfg = c.build_cfg(child, &source_bytes);
assert!(cfg.is_ok());
let cfg = cfg.unwrap();
assert_eq!(cfg.function_name, "factorial");
assert!(!cfg.blocks.is_empty());
assert!(!cfg.edges.is_empty());
}
}
}
#[test]
fn test_build_dfg() {
let source = r#"
int sum(int a, int b) {
int result = a + b;
return result;
}
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "function_definition" {
let dfg = c.build_dfg(child, &source_bytes);
assert!(dfg.is_ok());
let dfg = dfg.unwrap();
assert_eq!(dfg.function_name, "sum");
// Should have definitions for a, b, result
assert!(dfg.definitions.contains_key("a"));
assert!(dfg.definitions.contains_key("b"));
assert!(dfg.definitions.contains_key("result"));
}
}
}
#[test]
fn test_extract_object_macro() {
let source = r#"
/* Buffer size constant */
#define BUFFER_SIZE 1024
#define NULL_PTR ((void*)0)
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut macros = Vec::new();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "preproc_def" {
if let Some(func) = c.extract_function(child, &source_bytes) {
macros.push(func);
}
}
}
assert_eq!(macros.len(), 2);
let buffer_size = macros.iter().find(|m| m.name == "BUFFER_SIZE").unwrap();
assert!(buffer_size.decorators.contains(&"macro".to_string()));
assert_eq!(buffer_size.return_type, Some("1024".to_string()));
assert!(buffer_size.params.is_empty());
assert!(buffer_size.docstring.is_some());
let null_ptr = macros.iter().find(|m| m.name == "NULL_PTR").unwrap();
assert!(null_ptr.decorators.contains(&"macro".to_string()));
assert_eq!(null_ptr.return_type, Some("((void*)0)".to_string()));
}
#[test]
fn test_extract_function_macro() {
let source = r#"
/* Returns the maximum of two values */
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define SWAP(x, y, T) do { T tmp = x; x = y; y = tmp; } while(0)
#define DEBUG_LOG(fmt, ...) printf(fmt, __VA_ARGS__)
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut macros = Vec::new();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "preproc_function_def" {
if let Some(func) = c.extract_function(child, &source_bytes) {
macros.push(func);
}
}
}
assert_eq!(macros.len(), 3);
let max_macro = macros.iter().find(|m| m.name == "MAX").unwrap();
assert!(max_macro.decorators.contains(&"macro".to_string()));
assert_eq!(max_macro.params, vec!["a", "b"]);
assert!(max_macro.return_type.is_some());
assert!(max_macro.docstring.is_some());
let swap_macro = macros.iter().find(|m| m.name == "SWAP").unwrap();
assert_eq!(swap_macro.params, vec!["x", "y", "T"]);
let debug_macro = macros.iter().find(|m| m.name == "DEBUG_LOG").unwrap();
assert_eq!(debug_macro.params, vec!["fmt", "..."]);
}
#[test]
fn test_extract_function_pointer_typedef() {
let source = r#"
/* Comparator function type */
typedef int (*comparator_fn)(const void*, const void*);
typedef void (*callback_t)(int status, void* data);
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut fn_ptrs = Vec::new();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "type_definition" {
if let Some(func) = c.extract_function(child, &source_bytes) {
fn_ptrs.push(func);
}
}
}
assert_eq!(fn_ptrs.len(), 2);
let comparator = fn_ptrs.iter().find(|f| f.name == "comparator_fn").unwrap();
assert!(comparator.decorators.contains(&"function_pointer".to_string()));
assert!(comparator.decorators.contains(&"typedef".to_string()));
assert_eq!(comparator.return_type, Some("int".to_string()));
assert_eq!(comparator.params.len(), 2);
// Verify unnamed pointer parameters preserve the * (abstract_pointer_declarator fix)
assert_eq!(comparator.params[0], "const void*");
assert_eq!(comparator.params[1], "const void*");
assert!(comparator.docstring.is_some());
let callback = fn_ptrs.iter().find(|f| f.name == "callback_t").unwrap();
assert!(callback.decorators.contains(&"function_pointer".to_string()));
assert_eq!(callback.return_type, Some("void".to_string()));
// Verify mixed named and pointer parameters
assert_eq!(callback.params.len(), 2);
assert_eq!(callback.params[0], "int status");
assert_eq!(callback.params[1], "void* data");
}
#[test]
fn test_extract_function_pointer_variable() {
let source = r#"
void (*signal_handler)(int);
int (*operation)(int, int);
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut fn_ptrs = Vec::new();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "declaration" {
if let Some(func) = c.extract_function(child, &source_bytes) {
if func.decorators.contains(&"function_pointer".to_string()) {
fn_ptrs.push(func);
}
}
}
}
assert_eq!(fn_ptrs.len(), 2);
let signal_h = fn_ptrs.iter().find(|f| f.name == "signal_handler").unwrap();
assert!(signal_h.decorators.contains(&"function_pointer".to_string()));
assert!(!signal_h.decorators.contains(&"typedef".to_string()));
assert_eq!(signal_h.return_type, Some("void".to_string()));
assert_eq!(signal_h.params.len(), 1);
let operation = fn_ptrs.iter().find(|f| f.name == "operation").unwrap();
assert_eq!(operation.return_type, Some("int".to_string()));
assert_eq!(operation.params.len(), 2);
}
#[test]
fn test_abstract_pointer_multi_level() {
// Test multi-level unnamed pointers (void**, char***, etc.)
let source = r#"
typedef void (*double_ptr_fn)(void**, int**);
typedef int (*triple_ptr_fn)(char***, void****);
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut fn_ptrs = Vec::new();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "type_definition" {
if let Some(func) = c.extract_function(child, &source_bytes) {
fn_ptrs.push(func);
}
}
}
assert_eq!(fn_ptrs.len(), 2);
let double_fn = fn_ptrs.iter().find(|f| f.name == "double_ptr_fn").unwrap();
assert_eq!(double_fn.params[0], "void**");
assert_eq!(double_fn.params[1], "int**");
let triple_fn = fn_ptrs.iter().find(|f| f.name == "triple_ptr_fn").unwrap();
assert_eq!(triple_fn.params[0], "char***");
assert_eq!(triple_fn.params[1], "void****");
}
#[test]
fn test_macro_signature() {
let func = FunctionInfo {
name: "MAX".to_string(),
params: vec!["a".to_string(), "b".to_string()],
return_type: Some("((a)>(b)?(a):(b))".to_string()),
docstring: None,
is_method: false,
is_async: false,
decorators: vec!["macro".to_string()],
line_number: 1,
end_line_number: Some(1),
language: "c".to_string(),
};
// Signature should show the macro with params
assert_eq!(func.signature(), "((a)>(b)?(a):(b)) MAX(a, b)");
}
#[test]
fn test_function_pointer_signature() {
let func = FunctionInfo {
name: "comparator_fn".to_string(),
params: vec!["const void*".to_string(), "const void*".to_string()],
return_type: Some("int".to_string()),
docstring: None,
is_method: false,
is_async: false,
decorators: vec!["function_pointer".to_string(), "typedef".to_string()],
line_number: 1,
end_line_number: Some(1),
language: "c".to_string(),
};
assert_eq!(func.signature(), "int comparator_fn(const void*, const void*)");
}
#[test]
fn test_extract_preproc_ifdef() {
let source = r#"
#ifdef DEBUG
int debug_mode = 1;
#endif
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut found = false;
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "preproc_ifdef" {
let cls = c.extract_class(child, &source_bytes);
assert!(cls.is_some());
let cls = cls.unwrap();
assert_eq!(cls.name, "DEBUG");
assert!(cls.decorators.contains(&"preproc_ifdef".to_string()));
assert_eq!(cls.language, "c");
found = true;
}
}
assert!(found, "preproc_ifdef not found");
}
#[test]
fn test_extract_preproc_ifndef() {
let source = r#"
#ifndef HEADER_H
#define HEADER_H
int value;
#endif
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut found = false;
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "preproc_ifdef" {
let cls = c.extract_class(child, &source_bytes);
assert!(cls.is_some());
let cls = cls.unwrap();
assert_eq!(cls.name, "HEADER_H");
assert!(cls.decorators.contains(&"preproc_ifndef".to_string()));
found = true;
}
}
assert!(found, "preproc_ifndef not found");
}
#[test]
fn test_extract_preproc_if_elif_else() {
let source = r#"
#if defined(FEATURE_A)
int feature_a = 1;
#elif defined(FEATURE_B)
int feature_b = 1;
#else
int default_feature = 1;
#endif
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut found = false;
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "preproc_if" {
let cls = c.extract_class(child, &source_bytes);
assert!(cls.is_some());
let cls = cls.unwrap();
assert!(cls.name.contains("FEATURE_A"));
assert!(cls.decorators.contains(&"preproc_if".to_string()));
// Should have inner_classes for elif and else branches
assert!(!cls.inner_classes.is_empty());
// Find elif
let elif = cls
.inner_classes
.iter()
.find(|c| c.decorators.contains(&"preproc_elif".to_string()));
assert!(elif.is_some());
let elif = elif.unwrap();
assert!(elif.name.contains("FEATURE_B"));
// Find else (nested in elif's inner_classes)
let else_branch = elif
.inner_classes
.iter()
.find(|c| c.decorators.contains(&"preproc_else".to_string()));
assert!(else_branch.is_some());
found = true;
}
}
assert!(found, "preproc_if not found");
}
#[test]
fn test_extract_nested_preproc() {
let source = r#"
#ifdef OUTER
#ifdef INNER
int nested = 1;
#endif
#endif
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "preproc_ifdef" {
let cls = c.extract_class(child, &source_bytes);
assert!(cls.is_some());
let cls = cls.unwrap();
assert_eq!(cls.name, "OUTER");
// Should have nested preproc
assert!(!cls.inner_classes.is_empty());
let inner = &cls.inner_classes[0];
assert_eq!(inner.name, "INNER");
assert!(inner.decorators.contains(&"preproc_ifdef".to_string()));
}
}
}
#[test]
fn test_extract_anonymous_struct() {
let source = r#"
struct outer {
int x;
struct {
int a, b;
};
};
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "struct_specifier" {
let cls = c.extract_class(child, &source_bytes);
assert!(cls.is_some());
let cls = cls.unwrap();
assert_eq!(cls.name, "outer");
// Should have anonymous struct as inner class
assert_eq!(cls.inner_classes.len(), 1);
let anon = &cls.inner_classes[0];
assert!(anon.name.contains("outer_anon_struct"));
assert!(anon.decorators.contains(&"anonymous_struct".to_string()));
}
}
}
#[test]
fn test_extract_anonymous_union() {
let source = r#"
struct container {
int type;
union {
float f;
int i;
char c;
};
};
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "struct_specifier" {
let cls = c.extract_class(child, &source_bytes);
assert!(cls.is_some());
let cls = cls.unwrap();
assert_eq!(cls.name, "container");
// Should have anonymous union as inner class
assert_eq!(cls.inner_classes.len(), 1);
let anon = &cls.inner_classes[0];
assert!(anon.name.contains("container_anon_union"));
assert!(anon.decorators.contains(&"anonymous_union".to_string()));
}
}
}
#[test]
fn test_extract_multiple_anonymous_members() {
let source = r#"
struct mixed {
int x;
struct {
int a, b;
};
union {
float f;
int i;
};
};
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "struct_specifier" {
let cls = c.extract_class(child, &source_bytes);
assert!(cls.is_some());
let cls = cls.unwrap();
assert_eq!(cls.name, "mixed");
// Should have both anonymous struct and union
assert_eq!(cls.inner_classes.len(), 2);
let has_anon_struct = cls
.inner_classes
.iter()
.any(|c| c.decorators.contains(&"anonymous_struct".to_string()));
let has_anon_union = cls
.inner_classes
.iter()
.any(|c| c.decorators.contains(&"anonymous_union".to_string()));
assert!(has_anon_struct, "Missing anonymous struct");
assert!(has_anon_union, "Missing anonymous union");
}
}
}
#[test]
fn test_extract_nested_anonymous() {
let source = r#"
struct outer {
struct {
union {
int x;
float y;
};
};
};
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "struct_specifier" {
let cls = c.extract_class(child, &source_bytes);
assert!(cls.is_some());
let cls = cls.unwrap();
assert_eq!(cls.name, "outer");
// Should have anonymous struct
assert_eq!(cls.inner_classes.len(), 1);
let anon_struct = &cls.inner_classes[0];
assert!(anon_struct.decorators.contains(&"anonymous_struct".to_string()));
// Anonymous struct should have nested anonymous union
assert_eq!(anon_struct.inner_classes.len(), 1);
let nested_union = &anon_struct.inner_classes[0];
assert!(nested_union.decorators.contains(&"anonymous_union".to_string()));
}
}
}
#[test]
fn test_union_with_anonymous_struct() {
let source = r#"
union data {
int raw;
struct {
char low;
char high;
};
};
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "union_specifier" {
let cls = c.extract_class(child, &source_bytes);
assert!(cls.is_some());
let cls = cls.unwrap();
assert_eq!(cls.name, "data");
assert!(cls.decorators.contains(&"union".to_string()));
// Should have anonymous struct as inner class
assert_eq!(cls.inner_classes.len(), 1);
let anon = &cls.inner_classes[0];
assert!(anon.decorators.contains(&"anonymous_struct".to_string()));
}
}
}
#[test]
fn test_inline_assembly_detection() {
let source = r#"
void enable_interrupts(void) {
__asm__ volatile ("sti" : : : "memory");
}
void nop_function(void) {
asm("nop");
}
int normal_function(int x) {
return x + 1;
}
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut functions = Vec::new();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "function_definition" {
if let Some(func) = c.extract_function(child, &source_bytes) {
functions.push(func);
}
}
}
assert_eq!(functions.len(), 3);
// enable_interrupts should have inline_assembly decorator
let enable_ints = functions.iter().find(|f| f.name == "enable_interrupts").unwrap();
assert!(
enable_ints.decorators.contains(&"inline_assembly".to_string()),
"enable_interrupts should have inline_assembly decorator"
);
// nop_function should have inline_assembly decorator
let nop_fn = functions.iter().find(|f| f.name == "nop_function").unwrap();
assert!(
nop_fn.decorators.contains(&"inline_assembly".to_string()),
"nop_function should have inline_assembly decorator"
);
// normal_function should NOT have inline_assembly decorator
let normal_fn = functions.iter().find(|f| f.name == "normal_function").unwrap();
assert!(
!normal_fn.decorators.contains(&"inline_assembly".to_string()),
"normal_function should NOT have inline_assembly decorator"
);
}
#[test]
fn test_static_assert_extraction() {
let source = r#"
_Static_assert(sizeof(void*) == 8, "64-bit only");
_Static_assert(sizeof(int) == 4, "int must be 4 bytes");
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut assertions = Vec::new();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "expression_statement" {
if let Some(func) = c.extract_function(child, &source_bytes) {
assertions.push(func);
}
}
}
assert_eq!(assertions.len(), 2);
// Check first static_assert
let first = &assertions[0];
assert!(first.decorators.contains(&"static_assert".to_string()));
assert!(first.name.contains("static_assert"));
assert!(first.name.contains("sizeof"));
assert_eq!(first.docstring, Some("64-bit only".to_string()));
// Check second static_assert
let second = &assertions[1];
assert!(second.decorators.contains(&"static_assert".to_string()));
assert_eq!(second.docstring, Some("int must be 4 bytes".to_string()));
}
#[test]
fn test_thread_local_storage() {
let source = r#"
/* Thread-local counter */
__thread int thread_counter = 0;
static __thread int static_thread_local = 42;
extern __thread void* thread_data;
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut variables = Vec::new();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "declaration" {
if let Some(func) = c.extract_function(child, &source_bytes) {
variables.push(func);
}
}
}
// Should find 3 thread-local variables
assert_eq!(variables.len(), 3);
// Check thread_counter
let counter = variables.iter().find(|v| v.name == "thread_counter").unwrap();
assert!(counter.decorators.contains(&"thread_local".to_string()));
assert!(counter.decorators.contains(&"variable".to_string()));
assert_eq!(counter.return_type, Some("int".to_string()));
assert!(counter.docstring.is_some());
assert!(counter.docstring.as_ref().unwrap().contains("Thread-local counter"));
// Check static_thread_local
let static_tl = variables.iter().find(|v| v.name == "static_thread_local").unwrap();
assert!(static_tl.decorators.contains(&"thread_local".to_string()));
assert!(static_tl.decorators.contains(&"static".to_string()));
assert_eq!(static_tl.return_type, Some("int".to_string()));
// Check extern thread_data
let extern_tl = variables.iter().find(|v| v.name == "thread_data").unwrap();
assert!(extern_tl.decorators.contains(&"thread_local".to_string()));
assert!(extern_tl.decorators.contains(&"extern".to_string()));
}
// ============= GOTO/LABEL CFG TESTS =============
#[test]
fn test_cfg_forward_goto() {
// Test forward goto: goto appears before label
let source = r#"
void test_forward_goto() {
int x = 0;
goto end;
x = 1;
end:
return;
}
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "function_definition" {
let cfg = c.build_c_cfg(child, &source_bytes, "test_forward_goto");
// Verify we have blocks for: entry, goto block, end label block
assert!(cfg.blocks.len() >= 3, "Should have at least 3 blocks");
// Find the edge labeled "goto end"
let goto_edge = cfg.edges.iter().find(|e| e.label().contains("goto end"));
assert!(goto_edge.is_some(), "Should have a goto end edge");
// Verify the end label block exists
let end_block = cfg.blocks.values().find(|b| b.label.contains("end:"));
assert!(end_block.is_some(), "Should have an 'end:' label block");
}
}
}
#[test]
fn test_cfg_backward_goto() {
// Test backward goto: label appears before goto (loop pattern)
let source = r#"
void test_backward_goto() {
int x = 0;
start:
x++;
if (x < 10)
goto start;
return;
}
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "function_definition" {
let cfg = c.build_c_cfg(child, &source_bytes, "test_backward_goto");
// Find the start label block
let start_block = cfg.blocks.values().find(|b| b.label.contains("start:"));
assert!(start_block.is_some(), "Should have a 'start:' label block");
// Find the edge labeled "goto start"
let goto_edge = cfg.edges.iter().find(|e| e.label().contains("goto start"));
assert!(goto_edge.is_some(), "Should have a goto start edge");
// Verify the goto edge points to the start block
if let (Some(start), Some(edge)) = (start_block, goto_edge) {
assert_eq!(edge.to, start.id, "Goto edge should point to start label block");
}
}
}
}
#[test]
fn test_cfg_multiple_gotos_same_label() {
// Test multiple gotos targeting the same label
let source = r#"
void test_multiple_gotos() {
int x = 0;
if (x == 0)
goto end;
if (x == 1)
goto end;
x = 2;
end:
return;
}
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "function_definition" {
let cfg = c.build_c_cfg(child, &source_bytes, "test_multiple_gotos");
// Find the end label block
let end_block = cfg.blocks.values().find(|b| b.label.contains("end:"));
assert!(end_block.is_some(), "Should have an 'end:' label block");
// Count edges targeting the end label
if let Some(end) = end_block {
let goto_edges_to_end: Vec<_> = cfg.edges.iter()
.filter(|e| e.to == end.id && e.label().contains("goto"))
.collect();
// Should have at least 2 goto edges to end (from the two if branches)
assert!(goto_edges_to_end.len() >= 2,
"Should have at least 2 goto edges to end label, found {}",
goto_edges_to_end.len());
}
}
}
}
#[test]
fn test_cfg_goto_in_loop() {
// Test goto used to break out of nested structure
let source = r#"
void test_goto_in_loop() {
for (int i = 0; i < 10; i++) {
if (i == 5)
goto done;
}
done:
return;
}
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "function_definition" {
let cfg = c.build_c_cfg(child, &source_bytes, "test_goto_in_loop");
// Verify we have the done label block
let done_block = cfg.blocks.values().find(|b| b.label.contains("done:"));
assert!(done_block.is_some(), "Should have a 'done:' label block");
// Verify we have a goto done edge
let goto_edge = cfg.edges.iter().find(|e| e.label().contains("goto done"));
assert!(goto_edge.is_some(), "Should have a goto done edge");
}
}
}
#[test]
fn test_cfg_label_makes_code_reachable() {
// Test that labels make code reachable even after goto
let source = r#"
void test_reachability() {
goto skip;
int unreachable = 1; // This should be skipped
skip:
int reachable = 2; // This should be in the CFG
return;
}
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "function_definition" {
let cfg = c.build_c_cfg(child, &source_bytes, "test_reachability");
// Find the skip label block
let skip_block = cfg.blocks.values().find(|b| b.label.contains("skip:"));
assert!(skip_block.is_some(), "Should have a 'skip:' label block");
// The skip block or its successors should contain "reachable = 2"
// or have an edge leading to it
if let Some(skip) = skip_block {
// Verify there's a goto edge to skip
let goto_to_skip = cfg.edges.iter().any(|e| e.to == skip.id);
assert!(goto_to_skip, "Should have edge to skip label");
}
}
}
}
#[test]
fn test_cfg_multiple_labels() {
// Test function with multiple labels
let source = r#"
int test_state_machine(int state) {
switch (state) {
case 0: goto state_a;
case 1: goto state_b;
default: goto state_c;
}
state_a:
return 1;
state_b:
return 2;
state_c:
return 3;
}
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "function_definition" {
let cfg = c.build_c_cfg(child, &source_bytes, "test_state_machine");
// Verify all three state labels exist
let state_a = cfg.blocks.values().find(|b| b.label.contains("state_a:"));
let state_b = cfg.blocks.values().find(|b| b.label.contains("state_b:"));
let state_c = cfg.blocks.values().find(|b| b.label.contains("state_c:"));
assert!(state_a.is_some(), "Should have 'state_a:' label");
assert!(state_b.is_some(), "Should have 'state_b:' label");
assert!(state_c.is_some(), "Should have 'state_c:' label");
// Verify goto edges exist for each state
let has_goto_a = cfg.edges.iter().any(|e| e.label().contains("goto state_a"));
let has_goto_b = cfg.edges.iter().any(|e| e.label().contains("goto state_b"));
let has_goto_c = cfg.edges.iter().any(|e| e.label().contains("goto state_c"));
assert!(has_goto_a, "Should have goto state_a edge");
assert!(has_goto_b, "Should have goto state_b edge");
assert!(has_goto_c, "Should have goto state_c edge");
}
}
}
// ============= ANONYMOUS STRUCT/UNION/ENUM TESTS =============
#[test]
fn test_extract_toplevel_anonymous_struct() {
// Test anonymous struct with variable name extracted from declaration
let source = r#"
struct { int x; int y; } global_point;
struct { float real; float imag; } *complex_ptr;
struct { char name[32]; int age; } person_arr[10];
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut structs = Vec::new();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "declaration" {
// Look for struct_specifier inside declaration
let mut inner_cursor = child.walk();
for inner in child.children(&mut inner_cursor) {
if inner.kind() == "struct_specifier" {
if let Some(cls) = c.extract_class(inner, &source_bytes) {
structs.push(cls);
}
}
}
}
}
// Should extract all 3 anonymous structs
assert_eq!(structs.len(), 3, "Should find 3 anonymous structs");
// Check global_point
let point = structs.iter().find(|s| s.name == "global_point");
assert!(point.is_some(), "Should extract global_point");
let point = point.unwrap();
assert!(point.decorators.contains(&"anonymous_struct".to_string()));
assert_eq!(point.fields.len(), 2);
// Check complex_ptr
let complex = structs.iter().find(|s| s.name == "complex_ptr");
assert!(complex.is_some(), "Should extract complex_ptr");
assert!(complex.unwrap().decorators.contains(&"anonymous_struct".to_string()));
// Check person_arr
let person = structs.iter().find(|s| s.name == "person_arr");
assert!(person.is_some(), "Should extract person_arr");
assert!(person.unwrap().decorators.contains(&"anonymous_struct".to_string()));
}
#[test]
fn test_extract_toplevel_anonymous_union() {
let source = r#"
union { int i; float f; } data_union;
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "declaration" {
let mut inner_cursor = child.walk();
for inner in child.children(&mut inner_cursor) {
if inner.kind() == "union_specifier" {
let cls = c.extract_class(inner, &source_bytes);
assert!(cls.is_some(), "Should extract anonymous union");
let cls = cls.unwrap();
assert_eq!(cls.name, "data_union");
assert!(cls.decorators.contains(&"union".to_string()));
assert!(cls.decorators.contains(&"anonymous_union".to_string()));
return;
}
}
}
}
panic!("Anonymous union not found");
}
#[test]
fn test_extract_toplevel_anonymous_enum() {
let source = r#"
enum { RED, GREEN, BLUE } color_var;
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "declaration" {
let mut inner_cursor = child.walk();
for inner in child.children(&mut inner_cursor) {
if inner.kind() == "enum_specifier" {
let cls = c.extract_class(inner, &source_bytes);
assert!(cls.is_some(), "Should extract anonymous enum");
let cls = cls.unwrap();
assert_eq!(cls.name, "color_var");
assert!(cls.decorators.contains(&"enum".to_string()));
assert!(cls.decorators.contains(&"anonymous_enum".to_string()));
return;
}
}
}
}
panic!("Anonymous enum not found");
}
// ==========================================================================
// C++ HEADER DETECTION TESTS
// ==========================================================================
#[test]
fn test_is_cpp_header_detects_templates() {
let content = b"template<typename T>\nclass Container {};";
assert!(is_cpp_header(content));
let content = b"template <typename T>\nclass Container {};";
assert!(is_cpp_header(content));
}
#[test]
fn test_is_cpp_header_detects_namespace() {
let content = b"namespace fast_float {\n int x;\n}";
assert!(is_cpp_header(content));
}
#[test]
fn test_is_cpp_header_detects_class_definition() {
let content = b"class Foo : public Bar {\n int x;\n};";
assert!(is_cpp_header(content));
let content = b"class Foo {\npublic:\n int x;\n};";
assert!(is_cpp_header(content));
}
#[test]
fn test_is_cpp_header_ignores_class_in_comment() {
// This tests the fix for false positives from comment prose
let content = b"/* Keyspace changes notification classes. Every class is associated */";
assert!(!is_cpp_header(content));
let content = b"/* Key metadata class configuration structure. */";
assert!(!is_cpp_header(content));
}
#[test]
fn test_is_cpp_header_detects_constexpr() {
let content = b"constexpr int MAX_SIZE = 100;";
assert!(is_cpp_header(content));
}
#[test]
fn test_is_cpp_header_detects_nullptr() {
let content = b"int* ptr = nullptr;";
assert!(is_cpp_header(content));
}
#[test]
fn test_is_cpp_header_detects_noexcept() {
let content = b"void func() noexcept;";
assert!(is_cpp_header(content));
}
#[test]
fn test_is_cpp_header_detects_static_cast() {
let content = b"auto x = static_cast<int>(y);";
assert!(is_cpp_header(content));
}
#[test]
fn test_is_cpp_header_detects_access_specifiers() {
let content = b"public:\n int x;";
assert!(is_cpp_header(content));
let content = b"private:\n int _y;";
assert!(is_cpp_header(content));
let content = b"protected:\n int z;";
assert!(is_cpp_header(content));
}
#[test]
fn test_is_cpp_header_pure_c_code() {
// Pure C code should NOT trigger C++ detection
let content = b"#include <stdio.h>\nvoid main() { printf(\"Hello\"); }";
assert!(!is_cpp_header(content));
let content = b"struct Point { int x; int y; };";
assert!(!is_cpp_header(content));
let content = b"typedef struct { int x; int y; } Point;";
assert!(!is_cpp_header(content));
let content = b"enum { RED, GREEN, BLUE };";
assert!(!is_cpp_header(content));
let content = b"#define MAX(a,b) ((a)>(b)?(a):(b))";
assert!(!is_cpp_header(content));
}
#[test]
fn test_is_cpp_header_detects_enum_class() {
// 'enum class' is C++11 but our heuristic should not false positive on this
// because we check for 'enum ' prefix before 'class '
let content = b"enum class Color { Red, Green, Blue };";
assert!(!is_cpp_header(content));
}
#[test]
fn test_is_cpp_header_detects_using_namespace() {
let content = b"using namespace std;";
assert!(is_cpp_header(content));
}
#[test]
fn test_is_cpp_header_detects_typename() {
let content = b"typename T::value_type";
assert!(is_cpp_header(content));
}
#[test]
fn test_extract_anonymous_struct_no_context() {
// Test anonymous struct without declaration context (pure specifier)
// This would happen if we extract the struct_specifier directly
let source = r#"
struct Named { int x; };
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "struct_specifier" {
let cls = c.extract_class(child, &source_bytes);
assert!(cls.is_some());
let cls = cls.unwrap();
// Named struct should NOT have anonymous decorator
assert_eq!(cls.name, "Named");
assert!(!cls.decorators.contains(&"anonymous_struct".to_string()));
}
}
}
#[test]
fn test_extract_typedef_anonymous_struct() {
// Typedef anonymous structs should still work via type_definition branch
let source = r#"
typedef struct { float real; float imag; } Complex;
"#;
let (tree, source_bytes) = parse_c(source);
let c = C;
let root = tree.root_node();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "type_definition" {
let cls = c.extract_class(child, &source_bytes);
assert!(cls.is_some(), "Should extract typedef anonymous struct");
let cls = cls.unwrap();
assert_eq!(cls.name, "Complex");
assert!(cls.decorators.contains(&"typedef".to_string()));
assert_eq!(cls.fields.len(), 2);
}
}
}
}