Menu

[327ada]: / Source / VCL / ClassBrowsing / CppParser.pas  Maximize  Restore  History

Download this file

2971 lines (2677 with data), 100.7 kB

   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
{
This file is part of Dev-C++
Copyright (c) 2004 Bloodshed Software
Dev-C++ is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Dev-C++ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Dev-C++; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
}
unit CppParser;
interface
uses
{$IFDEF WIN32}
Dialogs, Windows, Classes, SysUtils, StrUtils, ComCtrls, StatementList, IntList, CppTokenizer, CppPreprocessor,
cbutils;
{$ENDIF}
{$IFDEF LINUX}
QDialogs, Classes, SysUtils, StrUtils, QComCtrls, U_IntList, CppTokenizer;
{$ENDIF}
type
TCppParser = class(TComponent)
private
fEnabled: boolean;
fIndex: integer;
fIsHeader: boolean;
fIsSystemHeader: boolean;
fCurrentFile: String;
fCurrentClass: TList; // list of lists
fSkipList: TIntList;
fClassScope: TStatementClassScope;
fStatementList: TStatementList;
fIncludesList: TList;
fTokenizer: TCppTokenizer;
fPreprocessor: TCppPreprocessor;
fIncludePaths: TStringList;
fProjectIncludePaths: TStringList;
fProjectFiles: TStringList;
fFilesToScan: TStringList; // list of base files to scan
fFilesScannedCount: Integer; // count of files that have been scanned
fFilesToScanCount: Integer; // count of files and files included in files that have to be scanned
fScannedFiles: TStringList;
fParseLocalHeaders: boolean;
fParseGlobalHeaders: boolean;
fProjectDir: String;
fOnBusy: TNotifyEvent;
fOnUpdate: TNotifyEvent;
fOnTotalProgress: TProgressEvent;
fLaterScanning: boolean;
fOnStartParsing: TNotifyEvent;
fOnEndParsing: TProgressEndEvent;
fIsProjectFile: boolean;
fInvalidatedStatements: TList;
fPendingDeclarations: TList;
function AddChildStatements(// support for multiple parents
Parents: TList;
const FileName: String;
const HintText: String;
const aType: String; // "Type" is already in use
const Command: String;
const Args: String;
Line: integer;
Kind: TStatementKind;
Scope: TStatementScope;
ClassScope: TStatementClassScope;
Visible: boolean;
FindDeclaration: boolean;
IsDefinition: boolean): PStatement; // TODO: InheritanceList not supported
function AddStatement(
Parent: PStatement;
const FileName: String;
const HintText: String;
const aType: String; // "Type" is already in use
const Command: String;
const Args: String;
Line: integer;
Kind: TStatementKind;
Scope: TStatementScope;
ClassScope: TStatementClassScope;
Visible: boolean;
FindDeclaration: boolean;
IsDefinition: boolean;
InheritanceList: TList): PStatement;
function IsSystemHeaderFile(const FileName: String): boolean;
procedure SetInheritance(Index: integer; ClassStatement: PStatement);
function GetLastCurrentClass: PStatement; // gets last item from lastt level
function GetCurrentClassLevel: TList;
function IsInCurrentClassLevel(const Command: String): PStatement;
procedure AddSoloClassLevel(Statement: PStatement); // adds new solo level
procedure AddMultiClassLevel(StatementList: TList); // adds new multi level
procedure RemoveClassLevel; // removes level
procedure CheckForSkipStatement;
function SkipBraces(StartAt: integer): integer;
function CheckForPreprocessor: boolean;
function CheckForKeyword: boolean;
function CheckForTypedef: boolean;
function CheckForTypedefEnum: boolean;
function CheckForTypedefStruct: boolean;
function CheckForStructs: boolean;
function CheckForMethod(var sType, sName, sArgs: String): boolean; // caching of results
function CheckForScope: boolean;
function CheckForVar: boolean;
function CheckForEnum: boolean;
function GetScope: TStatementScope;
procedure HandlePreprocessor;
procedure HandleOtherTypedefs;
procedure HandleStructs(IsTypedef: boolean = False);
procedure HandleMethod(const sType, sName, sArgs: String);
procedure ScanMethodArgs(const ArgStr: String; const Filename: String; Line: Integer);
procedure HandleScope;
procedure HandleKeyword;
procedure HandleVar;
procedure HandleEnum;
function HandleStatement: boolean;
procedure InternalParse(const FileName: String; ManualUpdate: boolean = False; Stream: TMemoryStream = nil);
procedure DeleteTemporaries;
function FindFileIncludes(const Filename: String; DeleteIt: boolean = False): PFileIncludes;
public
procedure ResetDefines;
procedure AddHardDefineByParts(const Name, Args, Value: String);
procedure AddHardDefineByLine(const Line: String);
procedure InvalidateFile(const FileName: String);
procedure GetFileIncludes(const Filename: String; var List: TStringList);
function IsCfile(const Filename: String): boolean;
function IsHfile(const Filename: String): boolean;
procedure GetSourcePair(const FName: String; var CFile, HFile: String);
procedure GetClassesList(var List: TStringList);
function SuggestMemberInsertionLine(ParentStatement: PStatement; Scope: TStatementClassScope; var AddScopeStr:
boolean):
integer;
function GetSystemHeaderFileName(const FileName: String): String; // <file.h>
function GetLocalHeaderFileName(const RelativeTo, FileName: String): String; // "file.h"
function GetHeaderFileName(const RelativeTo, Line: String): String; // both
function IsIncludeLine(const Line: String): boolean;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ParseFileList;
procedure ParseFile(const FileName: String; InProject: boolean; OnlyIfNotParsed: boolean = False; UpdateView:
boolean = True; Stream: TMemoryStream = nil);
function StatementKindStr(Value: TStatementKind): String;
function StatementClassScopeStr(Value: TStatementClassScope): String;
function GetIncompleteClass(const Command: String): PStatement;
function FetchPendingDeclaration(const Command, Args: String; Kind: TStatementKind; Parent: PStatement):
PStatement;
procedure Reset;
procedure ClearIncludePaths;
procedure ClearProjectIncludePaths;
procedure AddIncludePath(const Value: String);
procedure AddProjectIncludePath(const Value: String);
procedure AddFileToScan(Value: String; InProject: boolean = False);
procedure ReProcessInheritance;
function PrettyPrintStatement(Statement: PStatement): String;
procedure FillListOfFunctions(const Full: String; List: TStringList);
function FindAndScanBlockAt(const Filename: String; Row: integer; Stream: TMemoryStream): PStatement;
function FindStatementOf(FileName, Phrase: String; Row: integer; Stream: TMemoryStream): PStatement; overload;
function FindStatementOf(Phrase: String; CurrentClass: PStatement): PStatement; overload;
function FindVariableOf(const Phrase: String; CurrentClass: PStatement): PStatement;
function FindTypeDefinitionOf(const aType: String; CurrentClass: PStatement): PStatement;
function GetClass(const Phrase: String): String;
function GetMember(const Phrase: String): String;
function GetOperator(const Phrase: String): String;
function FindLastOperator(const Phrase: String): integer;
procedure GetMultipleInheritanceStatements(Statement: PStatement; List: TList);
published
property Enabled: boolean read fEnabled write fEnabled;
property OnUpdate: TNotifyEvent read fOnUpdate write fOnUpdate;
property OnBusy: TNotifyEvent read fOnBusy write fOnBusy;
property OnTotalProgress: TProgressEvent read fOnTotalProgress write fOnTotalProgress;
property Tokenizer: TCppTokenizer read fTokenizer write fTokenizer;
property Preprocessor: TCppPreprocessor read fPreprocessor write fPreprocessor;
property Statements: TStatementList read fStatementList write fStatementList;
property ParseLocalHeaders: boolean read fParseLocalHeaders write fParseLocalHeaders;
property ParseGlobalHeaders: boolean read fParseGlobalHeaders write fParseGlobalHeaders;
property ScannedFiles: TStringList read fScannedFiles;
property ProjectDir: String read fProjectDir write fProjectDir;
property OnStartParsing: TNotifyEvent read fOnStartParsing write fOnStartParsing;
property OnEndParsing: TProgressEndEvent read fOnEndParsing write fOnEndParsing;
property FilesToScan: TStringList read fFilesToScan;
end;
procedure Register;
implementation
uses
DateUtils, IniFiles;
procedure Register;
begin
RegisterComponents('Dev-C++', [TCppParser]);
end;
constructor TCppParser.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fStatementList := TStatementList.Create; // owns the objects
fIncludesList := TList.Create;
fFilesToScan := TStringList.Create;
fScannedFiles := TStringList.Create;
fIncludePaths := TStringList.Create;
fProjectIncludePaths := TStringList.Create;
fProjectFiles := TStringList.Create;
fInvalidatedStatements := TList.Create;
fPendingDeclarations := TList.Create;
fCurrentClass := TList.Create;
fSkipList := TIntList.Create;
fParseLocalHeaders := False;
fParseGlobalHeaders := False;
end;
destructor TCppParser.Destroy;
var
i: Integer;
begin
FreeAndNil(fPendingDeclarations);
FreeAndNil(fInvalidatedStatements);
FreeAndNil(fCurrentClass);
FreeAndNil(fSkipList);
FreeAndNil(fProjectFiles);
for i := 0 to fIncludesList.Count - 1 do
Dispose(PFileIncludes(fIncludesList.Items[i]));
FreeAndNil(fIncludesList);
FreeAndNil(fStatementList);
FreeAndNil(fFilesToScan);
FreeAndNil(fScannedFiles);
FreeAndNil(fIncludePaths);
FreeAndNil(fProjectIncludePaths);
inherited Destroy;
end;
function TCppParser.StatementClassScopeStr(Value: TStatementClassScope): String;
begin
case Value of
scsPublic: Result := 'public';
scsPrivate: Result := 'private';
scsProtected: Result := 'protected';
scsNone: Result := '';
end;
end;
function TCppParser.StatementKindStr(Value: TStatementKind): String;
begin
case Value of
skPreprocessor: Result := 'preprocessor';
skVariable: Result := 'variable';
skConstructor: Result := 'constructor';
skDestructor: Result := 'destructor';
skFunction: Result := 'function';
skClass: Result := 'class';
skTypedef: Result := 'typedef';
skEnum: Result := 'enum';
skUnknown: Result := 'unknown';
end;
end;
function TCppParser.SkipBraces(StartAt: integer): integer;
var
I, Level: integer;
begin
I := StartAt;
Level := 0; // assume we start on top of {
while (I < fTokenizer.Tokens.Count) do begin
case fTokenizer[I]^.Text[1] of
'{': Inc(Level);
'}': begin
Dec(Level);
if Level = 0 then begin
Result := I;
Exit;
end;
end;
end;
Inc(I);
end;
Result := StartAt;
end;
// When finding declaration/definition pairs only search the separate incomplete pair list
function TCppParser.FetchPendingDeclaration(const Command, Args: String; Kind: TStatementKind; Parent: PStatement):
PStatement;
var
Statement: PStatement;
I: integer;
begin
// we do a backward search, because most possible is to be found near the end ;) - if it exists :(
for I := fPendingDeclarations.Count - 1 downto 0 do begin
Statement := fPendingDeclarations[i];
// Only do an expensive string compare with the right kinds and parents
if Statement^._Parent = Parent then begin
if Statement^._Kind = Kind then begin
if Statement^._Command = Command then begin
if Statement^._Args = Args then begin
fPendingDeclarations.Delete(i); // remove it when we have found it
Result := Statement;
Exit;
end;
end;
end;
end;
end;
Result := nil;
end;
// When finding a parent class for a function definition, only search classes of incomplete decl/def pairs
function TCppParser.GetIncompleteClass(const Command: String): PStatement;
var
Statement, ParentStatement: PStatement;
I: integer;
begin
// we do a backward search, because most possible is to be found near the end ;) - if it exists :(
for I := fPendingDeclarations.Count - 1 downto 0 do begin
Statement := fPendingDeclarations[i];
ParentStatement := Statement^._Parent;
if Assigned(ParentStatement) then begin
if ParentStatement^._Command = Command then begin
Result := ParentStatement;
Exit;
end;
end;
end;
Result := nil;
end;
function TCppParser.AddChildStatements(
Parents: TList;
const FileName: String;
const HintText: String;
const aType: String; // "Type" is already in use
const Command: String;
const Args: String;
Line: integer;
Kind: TStatementKind;
Scope: TStatementScope;
ClassScope: TStatementClassScope;
Visible: boolean;
FindDeclaration: boolean;
IsDefinition: boolean): PStatement;
var
I: integer;
begin
Result := nil;
if Assigned(Parents) then begin
for I := 0 to Parents.Count - 1 do
Result := AddStatement(
Parents[i],
FileName,
HintText,
aType,
Command,
Args,
Line,
Kind,
Scope,
ClassScope,
Visible,
FindDeclaration,
IsDefinition,
nil);
end else begin
Result := AddStatement(
nil,
FileName,
HintText,
aType,
Command,
Args,
Line,
Kind,
Scope,
ClassScope,
Visible,
FindDeclaration,
IsDefinition,
nil);
end;
end;
function TCppParser.AddStatement(
Parent: PStatement;
const FileName: String;
const HintText: String;
const aType: String; // "Type" is already in use
const Command: String;
const Args: String;
Line: integer;
Kind: TStatementKind;
Scope: TStatementScope;
ClassScope: TStatementClassScope;
Visible: boolean;
FindDeclaration: boolean;
IsDefinition: boolean;
InheritanceList: TList): PStatement;
var
Declaration: PStatement;
OperatorPos: integer;
NewKind: TStatementKind;
NewType, NewCommand: String;
function AddToList: PStatement;
begin
Result := New(PStatement);
with Result^ do begin
_Parent := Parent;
_HintText := HintText;
_Type := NewType;
_Command := NewCommand;
_Args := Args;
_Kind := Kind;
_InheritanceList := InheritanceList;
_Scope := Scope;
_ClassScope := ClassScope;
_HasDefinition := IsDefinition;
_Line := Line;
_DefinitionLine := Line;
_FileName := FileName;
_DefinitionFileName := FileName;
_Visible := Visible; // sets visibility in class browser
_Temporary := fLaterScanning; // true if it's added by a function body scan
_InProject := fIsProjectFile;
_InSystemHeader := fIsSystemHeader;
end;
fStatementList.Add(Result);
end;
begin
// Move '*', '&' to type rather than cmd (it's in the way for code-completion)
NewType := aType;
NewCommand := Command;
while (Length(NewCommand) > 0) and CharInSet(NewCommand[1], ['*', '&']) do begin
NewType := NewType + NewCommand[1];
Delete(NewCommand, 1, 1); // remove first
end;
NewKind := Kind;
// Remove namespace stuff from type (until we support namespaces)
if NewKind in [skFunction, skVariable] then begin
OperatorPos := Pos('::', NewType);
if OperatorPos > 0 then
Delete(NewType, 1, OperatorPos + 1);
end;
// Find a declaration/definition pair
if FindDeclaration and IsDefinition then
Declaration := FetchPendingDeclaration(NewCommand, Args, Kind, Parent)
else
Declaration := nil;
// We already have a statement with the same identifier...
if Assigned(Declaration) then begin
Declaration^._DefinitionLine := Line;
Declaration^._DefinitionFileName := FileName;
Declaration^._HasDefinition := True;
Result := Declaration;
// No duplicates found. Proceed as usual
end else begin
Result := AddToList;
if not IsDefinition then // add declarations to separate list to speed up searches for them
fPendingDeclarations.Add(Result);
end;
end;
function TCppParser.GetLastCurrentClass: PStatement;
var
CurrentClassLevel: TList;
begin
if fCurrentClass.Count = 0 then begin
Result := nil;
Exit;
end;
// Get current classes at same level
CurrentClassLevel := fCurrentClass[fCurrentClass.Count - 1];
// Pick last one
if CurrentClassLevel.Count > 0 then
Result := CurrentClassLevel[CurrentClassLevel.Count - 1]
else
Result := nil;
end;
function TCppParser.GetCurrentClassLevel: TList;
begin
if fCurrentClass.Count = 0 then begin
Result := nil;
Exit;
end;
Result := fCurrentClass[fCurrentClass.Count - 1];
end;
function TCppParser.IsInCurrentClassLevel(const Command: String): PStatement;
var
CurrentClassLevel: TList;
I: integer;
Statement: PStatement;
begin
Result := nil;
CurrentClassLevel := GetCurrentClassLevel;
if Assigned(CurrentClassLevel) then begin
for I := 0 to CurrentClassLevel.Count - 1 do begin
Statement := CurrentClassLevel[i];
if Assigned(Statement) and SameStr(Command, Statement^._Command) then begin
Result := Statement;
Break;
end;
end;
end;
end;
procedure TCppParser.AddSoloClassLevel(Statement: PStatement);
var
NewLevel: TList;
begin
// Add class list
NewLevel := TList.Create;
NewLevel.Add(Statement);
fCurrentClass.Add(NewLevel);
// Set new scope
if Statement = nil then begin
fClassScope := scsNone // {}, namespace or class that doesn't exist
end else if Statement^._Type = 'class' then
fClassScope := scsPrivate // classes are private by default
else
fClassScope := scsPublic; // structs are public by default
end;
procedure TCppParser.AddMultiClassLevel(StatementList: TList);
var
Statement: PStatement;
ListCopy: TList;
begin
// Add list to list
ListCopy := TList.Create;
ListCopy.Assign(StatementList);
fCurrentClass.Add(ListCopy);
// Check scope of first one
if StatementList.Count > 0 then
Statement := StatementList[0]
else
Statement := nil;
// Set new scope
if Statement = nil then begin
fClassScope := scsNone // {}, namespace or class that doesn't exist
end else if Statement^._Type = 'class' then
fClassScope := scsPrivate // classes are private by default
else
fClassScope := scsPublic; // structs are public by default
end;
procedure TCppParser.RemoveClassLevel;
var
CurrentLevel: TList;
CurrentClass: PStatement;
begin
// Remove class list
if fCurrentClass.Count = 0 then
Exit; // TODO: should be an exception
TList(fCurrentClass[fCurrentClass.Count - 1]).Free;
fCurrentClass.Delete(fCurrentClass.Count - 1);
// Set new scope
CurrentLevel := GetCurrentClassLevel;
if not Assigned(CurrentLevel) then begin
fClassScope := scsNone // no classes or structs remaining
end else begin
CurrentClass := GetLastCurrentClass;
if Assigned(CurrentClass) and (CurrentClass^._Type = 'class') then
fClassScope := scsPrivate // classes are private by default
else
fClassScope := scsPublic;
end;
end;
procedure TCppParser.SetInheritance(Index: integer; ClassStatement: PStatement);
var
I: Integer;
Node: PStatementNode;
Statement: PStatement;
function CheckForScopeKeyword(Index: integer): boolean;
begin
Result := (Index < fTokenizer.Tokens.Count - 1) and
(SameStr(fTokenizer[Index]^.Text, 'public') or
SameStr(fTokenizer[Index]^.Text, 'protected') or
SameStr(fTokenizer[Index]^.Text, 'private'));
end;
var
sl: TStringList;
begin
sl := TStringList.Create;
try
// Assemble a list of statements in text form we inherit from
repeat
if not CheckForScopeKeyword(Index) then
if not CharInSet(fTokenizer[Index]^.Text[1], [',', ':', '(']) then
sl.Add(fTokenizer[Index]^.Text);
Inc(Index);
until (Index >= fTokenizer.Tokens.Count) or CharInSet(fTokenizer[Index]^.Text[1], ['{', ';']);
// Clear it. Assume it is assigned
ClassStatement._InheritanceList.Clear;
// Get their PStatement]
for I := 0 to sl.Count - 1 do begin
// Find the corresponding PStatements
Node := fStatementList.LastNode;
while Assigned(Node) do begin
Statement := Node^.Data;
if (Statement^._Kind = skClass) and SameStr(sl[I], Statement^._Command) then begin
ClassStatement._InheritanceList.Add(Statement); // next I please
break;
end;
Node := Node^.PrevNode;
end;
end;
finally
sl.Free;
end;
end;
function TCppParser.GetScope: TStatementScope;
var
CurrentClass: PStatement;
begin
// We are scanning function bodies
if fLaterScanning then begin
Result := ssLocal;
Exit;
end;
// Don't blindly trust levels. Namespaces and externs can have levels too
CurrentClass := GetLastCurrentClass;
// Invalid class or namespace/extern
if CurrentClass = nil then
Result := ssGlobal
// We are inside a class body
else if Assigned(CurrentClass) then
Result := ssClassLocal
// Everything else
else
Result := ssLocal;
end;
procedure TCppParser.CheckForSkipStatement;
var
iSkip: integer;
begin
iSkip := fSkipList.IndexOf(fIndex);
if iSkip >= 0 then begin // skip to next ';'
repeat
Inc(fIndex);
until (fIndex >= fTokenizer.Tokens.Count) or (fTokenizer[fIndex]^.Text[1] = ';');
Inc(fIndex); //skip ';'
fSkipList.Delete(iSkip);
end;
end;
function TCppParser.CheckForPreprocessor: boolean;
begin
result := StartsStr('#', fTokenizer[fIndex]^.Text);
end;
function TCppParser.CheckForKeyword: boolean;
begin
Result :=
SameStr(fTokenizer[fIndex]^.Text, 'alignas') or // skip to )
SameStr(fTokenizer[fIndex]^.Text, 'alignof') or // skip to )
SameStr(fTokenizer[fIndex]^.Text, 'and') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'and_eq') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'asm') or // skip to }
// auto is a type
SameStr(fTokenizer[fIndex]^.Text, 'bitand') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'bitor') or // skip
// bool is a type
SameStr(fTokenizer[fIndex]^.Text, 'break') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'case') or // skip to :
SameStr(fTokenizer[fIndex]^.Text, 'catch') or // skip to {
// char is a type
// char16_t is a type
// char32_t is a type
// class is handled elsewhere
SameStr(fTokenizer[fIndex]^.Text, 'compl') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'const') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'constexpr') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'const_cast') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'continue') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'decltype') or // skip to )
SameStr(fTokenizer[fIndex]^.Text, 'default') or // skip to :
SameStr(fTokenizer[fIndex]^.Text, 'delete') or // skip to ;
SameStr(fTokenizer[fIndex]^.Text, 'do') or // skip to {
// double is a type
SameStr(fTokenizer[fIndex]^.Text, 'dynamic_cast') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'else') or // skip
// enum is handled elsewhere
SameStr(fTokenizer[fIndex]^.Text, 'explicit') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'export') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'extern') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'false') or // skip
// float is a type
SameStr(fTokenizer[fIndex]^.Text, 'for') or // skip to ), ( when scanning code blocks
SameStr(fTokenizer[fIndex]^.Text, 'friend') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'goto') or // skip to ;
SameStr(fTokenizer[fIndex]^.Text, 'if') or // skip to )
SameStr(fTokenizer[fIndex]^.Text, 'inline') or // skip
// int is a type
// long is a type
SameStr(fTokenizer[fIndex]^.Text, 'mutable') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'namespace') or // skip to {
SameStr(fTokenizer[fIndex]^.Text, 'new') or // skip to ;
SameStr(fTokenizer[fIndex]^.Text, 'noexcept') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'not') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'not_eq') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'nullptr') or // skip
// operator is handled elsewhere
SameStr(fTokenizer[fIndex]^.Text, 'or') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'or_eq') or // skip
// private is handled elsewhere
// protected is handled elsewhere
// public is handled elsewhere
SameStr(fTokenizer[fIndex]^.Text, 'register') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'reinterpret_cast') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'return') or // skip to ;
// short is a type
// signed is a type
SameStr(fTokenizer[fIndex]^.Text, 'sizeof') or // skip to )
SameStr(fTokenizer[fIndex]^.Text, 'static') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'static_assert') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'static_cast') or // skip
// struct is handled elsewhere
SameStr(fTokenizer[fIndex]^.Text, 'switch') or // skip to )
SameStr(fTokenizer[fIndex]^.Text, 'template') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'this') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'thread_local') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'throw') or // skip to ;
SameStr(fTokenizer[fIndex]^.Text, 'true') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'try') or //skip to {
// typedef is handled elsewhere
SameStr(fTokenizer[fIndex]^.Text, 'typeid') or //skip to )
SameStr(fTokenizer[fIndex]^.Text, 'typename') or //skip
// union is handled elsewhere
// unsigned is a type
SameStr(fTokenizer[fIndex]^.Text, 'using') or // skip to ;
SameStr(fTokenizer[fIndex]^.Text, 'virtual') or // skip
// void is a type
SameStr(fTokenizer[fIndex]^.Text, 'volatile') or // skip
// wchar_t is a type
SameStr(fTokenizer[fIndex]^.Text, 'while') or // skip to )
SameStr(fTokenizer[fIndex]^.Text, 'xor') or // skip
SameStr(fTokenizer[fIndex]^.Text, 'xor_eq'); // skip
end;
function TCppParser.CheckForTypedef: boolean;
begin
Result := SameStr(fTokenizer[fIndex]^.Text, 'typedef');
end;
function TCppParser.CheckForEnum: boolean;
begin
Result := SameStr(fTokenizer[fIndex]^.Text, 'enum');
end;
function TCppParser.CheckForTypedefEnum: boolean;
begin
//we assume that typedef is the current index, so we check the next
//should call CheckForTypedef first!!!
Result := (fIndex < fTokenizer.Tokens.Count - 1) and
SameStr(fTokenizer[fIndex + 1]^.Text, 'enum');
end;
function TCppParser.CheckForTypedefStruct: boolean;
begin
//we assume that typedef is the current index, so we check the next
//should call CheckForTypedef first!!!
Result := (fIndex < fTokenizer.Tokens.Count - 1) and (
SameStr(fTokenizer[fIndex + 1]^.Text, 'struct') or
SameStr(fTokenizer[fIndex + 1]^.Text, 'class') or
SameStr(fTokenizer[fIndex + 1]^.Text, 'union'));
end;
function TCppParser.CheckForStructs: boolean;
var
I: integer;
begin
Result := (fIndex < fTokenizer.Tokens.Count - 2) and (
SameStr(fTokenizer[fIndex]^.Text, 'struct') or
SameStr(fTokenizer[fIndex]^.Text, 'class') or
SameStr(fTokenizer[fIndex]^.Text, 'union'));
if Result then begin
if fTokenizer[fIndex + 2]^.Text[1] <> ';' then begin // not: class something;
I := fIndex;
// the check for ']' was added because of this example:
// struct option long_options[] = {
// {"debug", 1, 0, 'D'},
// {"info", 0, 0, 'i'},
// ...
// };
while (I < fTokenizer.Tokens.Count) and not CharInSet(fTokenizer[I]^.Text[Length(fTokenizer[I]^.Text)], [';', ':', '{',
'}', ',', ')', ']']) do
Inc(I);
if (I < fTokenizer.Tokens.Count) and not CharInSet(fTokenizer[I]^.Text[1], ['{', ':']) then
Result := False;
end;
end;
end;
function TCppParser.CheckForMethod(var sType, sName, sArgs: String): boolean;
var
CurrentClassLevel: TList;
fIndexBackup, DelimPos: integer;
bTypeOK, bNameOK, bArgsOK: boolean;
begin
// Function template:
// compiler directives (>= 0 words), added to type
// type (>= 1 words)
// name (1 word)
// (argument list)
// ; or {
sType := ''; // should contain type "int"
sName := ''; // should contain function name "foo::function"
sArgs := ''; // should contain argument list "(int a)"
bTypeOK := false;
bNameOK := false;
bArgsOK := false;
// Don't modify index
fIndexBackup := fIndex;
// Gather data for the string parts
while (fIndex < fTokenizer.Tokens.Count) and not CharInSet(fTokenizer[fIndex]^.Text[1], ['(', ';', ':', '{', '}', '#']) do
begin
// Skip some compiler extensions BEFORE our function type
if not bTypeOK and StartsText('__mingw', fTokenizer[fIndex]^.Text) or SameStr('__attribute__',
fTokenizer[fIndex]^.Text) then begin
// TODO: this should be fixed by performing macro expansion
if (fIndex + 1 < fTokenizer.Tokens.Count) and (fTokenizer[fIndex + 1]^.Text[1] = '(') then
Inc(fIndex); // skip keyword. argument list is skipped at end of loop body
// If the first brace is ahead, we've found the function name. Stop adding to type
end else if (fIndex + 1 < fTokenizer.Tokens.Count) and (fTokenizer[fIndex + 1]^.Text[1] = '(') then
begin // and start of a function
sName := fTokenizer[fIndex]^.Text;
sArgs := fTokenizer[fIndex + 1]^.Text;
bTypeOK := sType <> '';
bNameOK := sName <> '';
bArgsOK := sArgs <> '';
// Allow constructor/destructor too
if not bTypeOk then begin
// Check for constructor/destructor outside class body
DelimPos := Pos('::', sName);
if DelimPos > 0 then begin
bTypeOK := true;
sType := Copy(sName, 1, DelimPos - 1);
end;
end;
// Are we inside a class body?
if not bTypeOK then begin
CurrentClassLevel := GetCurrentClassLevel;
if Assigned(CurrentClassLevel) then begin
sType := fTokenizer[fIndex]^.Text;
if sType[1] = '~' then
Delete(sType, 1, 1);
bTypeOK := Assigned(IsInCurrentClassLevel(sType)); // constructor/destructor
end;
end;
break;
// Still walking through type
end else {if IsValidIdentifier(fTokenizer[fIndex]^.Text) then} begin
sType := sType + fTokenizer[fIndex]^.Text + ' ';
bTypeOK := sType <> '';
end;
Inc(fIndex);
end;
fIndex := fIndexBackup;
// Correct function, don't jump over
if bTypeOK and bNameOK and bArgsOK then begin
Result := true;
sType := TrimRight(sType); // should contain type "int"
sName := TrimRight(sName); // should contain function name "foo::function"
sArgs := TrimRight(sArgs); // should contain argument list "(int a)"
end else
Result := false;
end;
function TCppParser.CheckForScope: boolean;
begin
Result := (fIndex < fTokenizer.Tokens.Count - 1) and
(fTokenizer[fIndex + 1]^.Text = ':') and
(SameStr(fTokenizer[fIndex]^.Text, 'public') or
SameStr(fTokenizer[fIndex]^.Text, 'protected') or
SameStr(fTokenizer[fIndex]^.Text, 'private'));
end;
function TCppParser.CheckForVar: boolean;
var
I, fIndexBackup: integer;
begin
// Be pessimistic
Result := False;
// Store old index
fIndexBackup := fIndex;
// Use fIndex so we can reuse checking functions
if fIndex + 1 < fTokenizer.Tokens.Count then begin
// Check the current and the next token
for I := 0 to 1 do begin
if CheckForKeyword or
CharInSet(fTokenizer[fIndex]^.Text[1], ['#', ',', ';', ':', '{', '}', '!', '/', '+', '-', '<', '>']) or
(fTokenizer[fIndex]^.Text[Length(fTokenizer[fIndex]^.Text)] = '.') or
((Length(fTokenizer[fIndex]^.Text) > 1) and
(fTokenizer[fIndex]^.Text[Length(fTokenizer[fIndex]^.Text) - 1] = '-') and
(fTokenizer[fIndex]^.Text[Length(fTokenizer[fIndex]^.Text)] = '>')) then begin
// Reset index and fail
fIndex := fIndexBackup;
Exit; // fail
// Could be a function pointer?
end else if (fTokenizer[fIndex]^.Text[1] = '(') then begin
// Quick fix: there must be a pointer operator in the first tiken
if (fIndex + 1 >= fTokenizer.Tokens.Count) or
(fTokenizer[fIndex + 1]^.Text[1] <> '(') or
(Pos('*', fTokenizer[fIndex]^.Text) = 0) then begin
// Reset index and fail
fIndex := fIndexBackup;
Exit; // fail
end;
end;
Inc(fIndex);
end;
end;
// Revert to the point we started at
fIndex := fIndexBackup;
// Fail if we do not find a comma or a semicolon or a ( (inline constructor)
while fIndex < fTokenizer.Tokens.Count do begin
if CharInSet(fTokenizer[fIndex]^.Text[1], ['#', '{', '}']) or CheckForKeyword then begin
Break; // fail
end else if (fIndex + 1 < fTokenizer.Tokens.Count) and (fTokenizer[fIndex]^.Text[1] = '(') and
(fTokenizer[fIndex]^.Text[2] = '(') then begin // TODO: is this used to remove __attribute stuff?
Break;
end else if CharInSet(fTokenizer[fIndex]^.Text[1], [',', ';']) then begin
Result := True;
Break;
end;
Inc(fIndex);
end;
// Revert to the point we started at
fIndex := fIndexBackup;
end;
procedure TCppParser.HandleOtherTypedefs;
var
NewType, OldType: String;
begin
// Skip typedef word
Inc(fIndex);
// Walk up to first new word (before first comma or ;)
while (fIndex + 1 < fTokenizer.Tokens.Count) and (not CharInSet(fTokenizer[fIndex + 1]^.Text[1], ['(', ',', ';'])) do begin
OldType := OldType + fTokenizer[fIndex]^.Text + ' ';
Inc(fIndex);
end;
OldType := TrimRight(OldType);
// Add synonyms for old
if (fIndex < fTokenizer.Tokens.Count) and (OldType <> '') then begin
repeat
// Support multiword typedefs
if (fIndex + 1 < fTokenizer.Tokens.Count) and
(fTokenizer[fIndex + 0]^.Text[1] = '(') and
(fTokenizer[fIndex + 1]^.Text[1] = '(') then begin
break; // TODO: do NOT handle function pointer defines
end else if not CharInSet(fTokenizer[fIndex]^.Text[1], [',', ';']) then begin
NewType := NewType + fTokenizer[fIndex]^.Text + ' '
end else begin
NewType := TrimRight(NewType);
AddStatement(
GetLastCurrentClass,
fCurrentFile,
'typedef ' + OldType + ' ' + NewType, // override hint
OldType,
NewType,
'',
fTokenizer[fIndex]^.Line,
skTypedef,
GetScope,
fClassScope,
False,
False,
True,
nil);
NewType := '';
if fTokenizer[fIndex]^.Text[1] = ';' then
break;
end;
Inc(fIndex);
until (fIndex >= fTokenizer.Tokens.Count);
end;
// Step over semicolon (saves one HandleStatement loop)
Inc(fIndex);
end;
procedure TCppParser.HandlePreprocessor;
var
DelimPos, Line: Integer;
S, Name, Args, Value, HintText: String;
begin
if StartsStr('#include ', fTokenizer[fIndex]^.Text) then begin // start of new file
// format: #include fullfilename:line
// Strip keyword
S := Copy(fTokenizer[fIndex]^.Text, Length('#include ') + 1, MaxInt);
DelimPos := LastPos(':', S);
if DelimPos > 3 then begin // ignore full file name stuff
fCurrentFile := Copy(S, 1, DelimPos - 1);
fIsSystemHeader := IsSystemHeaderFile(fCurrentFile);
fIsProjectFile := fProjectFiles.IndexOf(fCurrentFile) <> -1;
fIsHeader := IsHfile(fCurrentFile);
// Mention progress to user if we enter a NEW file
Line := StrToIntDef(Copy(S, DelimPos + 1, MaxInt), -1);
if Line = 1 then begin
Inc(fFilesScannedCount);
Inc(fFilesToScanCount);
if Assigned(fOnTotalProgress) and not fLaterScanning then
fOnTotalProgress(Self, fCurrentFile, fFilesToScanCount, fFilesScannedCount);
end;
end;
end else if StartsStr('#define ', fTokenizer[fIndex]^.Text) then begin
// format: #define A B, remove define keyword
S := TrimLeft(Copy(fTokenizer[fIndex]^.Text, Length('#define ') + 1, MaxInt));
// Ask the preprocessor to cut parts up
if Assigned(fPreprocessor) then
fPreprocessor.GetDefineParts(S, Name, Args, Value);
// Generate custom hint
HintText := '#define';
if Name <> '' then
HintText := HintText + ' ' + Name;
if Args <> '' then
HintText := HintText + ' ' + Args;
if Value <> '' then
HintText := HintText + ' ' + Value;
AddStatement(
nil, // defines don't belong to any scope
fCurrentFile,
HintText, // override hint
'', // define has no type
Name,
Args,
fTokenizer[FIndex]^.Line,
skPreprocessor,
ssGlobal,
scsNone,
False, // not visible
False,
True,
nil);
end;
Inc(fIndex);
end;
procedure TCppParser.HandleStructs(IsTypedef: boolean = False);
var
Command, Prefix, OldType, NewType: String;
I: integer;
IsStruct: boolean;
FirstSynonym, LastStatement: PStatement;
SharedInheritance, NewClassLevel: TList;
begin
// Check if were dealing with a struct or union
Prefix := fTokenizer[fIndex]^.Text;
IsStruct := SameStr(Prefix, 'struct') or SameStr(Prefix, 'union');
Inc(fIndex); //skip struct/class/union
// Do not modifiy index initially
I := fIndex;
// Skip until the struct body starts
while (I < fTokenizer.Tokens.Count) and not CharInSet(fTokenizer[I]^.Text[1], [';', '{']) do
Inc(I);
// Forward class/struct decl *or* typedef, e.g. typedef struct some_struct synonym1, synonym2;
if (I < fTokenizer.Tokens.Count) and (fTokenizer[I]^.Text[1] = ';') then begin
// typdef struct Foo Bar
if IsTypedef then begin
OldType := fTokenizer[fIndex]^.Text;
repeat
// Add definition statement for the synonym
if (fIndex + 1 < fTokenizer.Tokens.Count) and CharInSet(fTokenizer[fIndex + 1]^.Text[1], [',', ';']) then begin
NewType := fTokenizer[fIndex]^.Text;
AddStatement(
GetLastCurrentClass,
fCurrentFile,
'typedef ' + Prefix + ' ' + OldType + ' ' + NewType, // override hint
OldType,
NewType,
'',
fTokenizer[fIndex]^.Line,
skTypedef,
GetScope,
fClassScope,
False,
False,
True,
nil);
end;
Inc(fIndex);
until (fIndex >= fTokenizer.Tokens.Count) or (fTokenizer[fIndex]^.Text[1] = ';');
// Forward declaration, struct Foo. Don't mention in class browser
end else begin
Inc(I); // step over ;
fIndex := I;
end;
// normal class/struct decl
end else begin
FirstSynonym := nil;
// Add class/struct name BEFORE opening brace
if fTokenizer[fIndex]^.Text[1] <> '{' then begin
repeat
if (fIndex + 1 < fTokenizer.Tokens.Count) and CharInSet(fTokenizer[fIndex + 1]^.Text[1], [',', ';', '{', ':']) then
begin
Command := fTokenizer[fIndex]^.Text;
if Command <> '' then begin
FirstSynonym := AddStatement(
GetLastCurrentClass,
fCurrentFile,
'', // do not override hint
Prefix, // type
Command, // command
'', // args
fTokenizer[fIndex]^.Line,
skClass,
GetScope,
fClassScope,
True,
False,
True,
TList.Create);
Command := '';
end;
end;
Inc(fIndex);
until (fIndex >= fTokenizer.Tokens.Count) or CharInSet(fTokenizer[fIndex]^.Text[1], [':', '{', ';']);
end;
// Walk to opening brace if we encountered inheritance statements
if (fIndex < fTokenizer.Tokens.Count) and (fTokenizer[fIndex]^.Text[1] = ':') then begin
if Assigned(FirstSynonym) then
SetInheritance(fIndex, FirstSynonym); // set the _InheritanceList value
while (fIndex < fTokenizer.Tokens.Count) and (fTokenizer[fIndex]^.Text[1] <> '{') do // skip decl after ':'
Inc(fIndex);
end;
// Check for struct synonyms after close brace
if IsStruct then begin
// Walk to closing brace
I := SkipBraces(fIndex); // step onto closing brace
// When encountering names again after struct body scanning, skip it
if (I + 1 < fTokenizer.Tokens.Count) and not CharInSet(fTokenizer[I + 1]^.Text[1], [';', '}']) then
fSkipList.Add(I + 1); // add first name to skip statement so that we can skip it until the next ;
// Add class/struct synonyms after close brace
if (I + 1 < fTokenizer.Tokens.Count) and not CharInSet(fTokenizer[I + 1]^.Text[1], [';', '}']) then begin
Command := '';
NewClassLevel := TList.Create;
try
// Add synonym before opening brace
if Assigned(FirstSynonym) then
NewClassLevel.Add(FirstSynonym);
repeat
Inc(I);
if not CharInSet(fTokenizer[I]^.Text[1], ['{', ',', ';']) then begin
if (fTokenizer[I]^.Text[1] = '_') and (fTokenizer[I]^.Text[Length(fTokenizer[I]^.Text)] = '_') then begin
// skip possible gcc attributes
// start and end with 2 underscores (i.e. __attribute__)
// so, to avoid slow checks of strings, we just check the first and last letter of the token
// if both are underscores, we split
Break;
end else begin
if fTokenizer[I]^.Text[Length(fTokenizer[I]^.Text)] = ']' then // cut-off array brackets
Command := Command + Copy(fTokenizer[I]^.Text, 1, Pos('[', fTokenizer[I]^.Text) - 1) + ' '
else if CharInSet(fTokenizer[I]^.Text[1], ['*', '&']) then // do not add spaces after pointer operator
Command := Command + fTokenizer[I]^.Text
else
Command := Command + fTokenizer[I]^.Text + ' ';
end;
end else begin
Command := TrimRight(Command);
if Command <> '' then begin
if Assigned(FirstSynonym) then begin
SharedInheritance := TList.Create;
SharedInheritance.Assign(FirstSynonym^._InheritanceList);
end else
SharedInheritance := nil;
LastStatement := AddStatement(
GetLastCurrentClass,
fCurrentFile,
'', // do not override hint
Prefix,
Command,
'',
fTokenizer[I]^.Line,
skClass,
GetScope,
fClassScope,
True,
False,
True,
SharedInheritance); // all synonyms inherit from the same statements
NewClassLevel.Add(LastStatement);
Command := '';
end;
end;
until (I >= fTokenizer.Tokens.Count - 1) or CharInSet(fTokenizer[I]^.Text[1], ['{', ';']);
// Set current class level
AddMultiClassLevel(NewClassLevel);
finally
NewClassLevel.Free;
end;
// Nothing worth mentioning after closing brace
// Proceed to set first synonym as current class
end else if Assigned(FirstSynonym) then
AddSoloClassLevel(FirstSynonym);
// Classes do not have synonyms after the brace
// Proceed to set first synonym as current class
end else
AddSoloClassLevel(FirstSynonym);
// Step over {
if (fIndex < fTokenizer.Tokens.Count) and (fTokenizer[fIndex]^.Text[1] = '{') then
Inc(fIndex);
end;
end;
procedure TCppParser.HandleMethod(const sType, sName, sArgs: String);
var
IsValid, IsDeclaration: boolean;
I, DelimPos: integer;
FunctionKind: TStatementKind;
ParentClassName, ScopelessName: String;
FunctionClass: PStatement;
begin
IsValid := True;
IsDeclaration := False; // assume it's not a prototype
I := fIndex;
// Skip over argument list
while (fIndex < fTokenizer.Tokens.Count) and not CharInSet(fTokenizer[fIndex]^.Text[1], [';', ':', '{', '}']) do
Inc(fIndex);
// Check if this is a prototype
FunctionClass := GetLastCurrentClass;
if (fIndex < fTokenizer.Tokens.Count) and CharInSet(fTokenizer[fIndex]^.Text[1], [';', '}']) then begin // prototype
IsDeclaration := True;
if not fIsHeader and not Assigned(FunctionClass) then // in a CPP file
IsValid := False; // not valid
end else begin
// Find the function body start after the inherited constructor
if (fIndex < fTokenizer.Tokens.Count) and (fTokenizer[fIndex]^.Text[1] = ':') then
while (fIndex < fTokenizer.Tokens.Count) and (not CharInSet(fTokenizer[fIndex]^.Text[1], [';', '{', '}'])) do
Inc(fIndex);
// Still a prototype
if (fIndex < fTokenizer.Tokens.Count) and CharInSet(fTokenizer[fIndex]^.Text[1], [';', '}']) then begin
IsDeclaration := True;
if not fIsHeader and not Assigned(FunctionClass) then
IsValid := False;
end;
end;
if IsValid then begin
// Use the class the function belongs to as the parent ID if the function is declared outside of the class body
DelimPos := Pos('::', sName);
if DelimPos > 0 then begin
// Provide Bar instead of Foo::Bar
ScopelessName := Copy(sName, DelimPos + 2, MaxInt);
// Check what class this function belongs to
ParentClassName := Copy(sName, 1, DelimPos - 1);
FunctionClass := GetIncompleteClass(ParentClassName);
end else
ScopelessName := sName;
// Determine function type
if SameStr(ScopelessName, sType) then
FunctionKind := skConstructor
else if SameStr(ScopelessName, '~' + sType) then
FunctionKind := skDestructor
else
FunctionKind := skFunction;
// For function definitions, the parent class is given. Only use that as a parent
if not IsDeclaration then
AddStatement(
FunctionClass,
fCurrentFile,
'', // do not override hint
sType,
ScopelessName,
sArgs,
fTokenizer[fIndex - 1]^.Line,
FunctionKind,
GetScope,
fClassScope,
True,
not IsDeclaration, // check for declarations when we find an definition of a function
not IsDeclaration,
nil)
// For function declarations, any given statement can belong to multiple typedef names
else
AddChildStatements(
GetCurrentClassLevel,
fCurrentFile,
'', // do not override hint
sType,
ScopelessName,
sArgs,
fTokenizer[fIndex - 1]^.Line,
FunctionKind,
GetScope,
fClassScope,
True,
not IsDeclaration, // check for declarations when we find an definition of a function
not IsDeclaration);
end;
// Don't parse the function's block now... It will be parsed when user presses ctrl+space inside it ;)
if (fIndex < fTokenizer.Tokens.Count) and (fTokenizer[fIndex]^.Text[1] = '{') then
fIndex := SkipBraces(fIndex) + 1 // add 1 so that '}' is not visible to parser
else if (fIndex < fTokenizer.Tokens.Count) and (fTokenizer[fIndex]^.Text[1] = ';') then
Inc(fIndex);
if I = fIndex then // if not moved ahead, something is wrong but don't get stuck ;)
if fIndex < fTokenizer.Tokens.Count then
if not CharInSet(fTokenizer[fIndex]^.Text[1], ['{', '}']) then
Inc(fIndex);
end;
procedure TCppParser.HandleScope;
begin
if SameStr(fTokenizer[fIndex]^.Text, 'public') then
fClassScope := scsPublic
else if SameStr(fTokenizer[fIndex]^.Text, 'private') then
fClassScope := scsPrivate
else if SameStr(fTokenizer[fIndex]^.Text, 'protected') then
fClassScope := scsProtected
else
fClassScope := scsNone;
Inc(fIndex, 2); // the scope is followed by a ':'
end;
procedure TCppParser.HandleKeyword;
begin
// Skip
if SameStr(fTokenizer[fIndex]^.Text, 'and') or
SameStr(fTokenizer[fIndex]^.Text, 'and_eq') or
SameStr(fTokenizer[fIndex]^.Text, 'bitand') or
SameStr(fTokenizer[fIndex]^.Text, 'bitor') or
SameStr(fTokenizer[fIndex]^.Text, 'break') or
SameStr(fTokenizer[fIndex]^.Text, 'compl') or
SameStr(fTokenizer[fIndex]^.Text, 'const') or
SameStr(fTokenizer[fIndex]^.Text, 'constexpr') or
SameStr(fTokenizer[fIndex]^.Text, 'const_cast') or
SameStr(fTokenizer[fIndex]^.Text, 'continue') or
SameStr(fTokenizer[fIndex]^.Text, 'dynamic_cast') or
SameStr(fTokenizer[fIndex]^.Text, 'else') or
SameStr(fTokenizer[fIndex]^.Text, 'explicit') or
SameStr(fTokenizer[fIndex]^.Text, 'export') or
SameStr(fTokenizer[fIndex]^.Text, 'extern') or
SameStr(fTokenizer[fIndex]^.Text, 'false') or
SameStr(fTokenizer[fIndex]^.Text, 'for') or
SameStr(fTokenizer[fIndex]^.Text, 'friend') or
SameStr(fTokenizer[fIndex]^.Text, 'inline') or
SameStr(fTokenizer[fIndex]^.Text, 'mutable') or
SameStr(fTokenizer[fIndex]^.Text, 'noexcept') or
SameStr(fTokenizer[fIndex]^.Text, 'not') or
SameStr(fTokenizer[fIndex]^.Text, 'not_eq') or
SameStr(fTokenizer[fIndex]^.Text, 'nullptr') or
SameStr(fTokenizer[fIndex]^.Text, 'or') or
SameStr(fTokenizer[fIndex]^.Text, 'or_eq') or
SameStr(fTokenizer[fIndex]^.Text, 'register') or
SameStr(fTokenizer[fIndex]^.Text, 'reinterpret_cast') or
SameStr(fTokenizer[fIndex]^.Text, 'static') or
SameStr(fTokenizer[fIndex]^.Text, 'static_assert') or
SameStr(fTokenizer[fIndex]^.Text, 'static_cast') or
SameStr(fTokenizer[fIndex]^.Text, 'template') or
SameStr(fTokenizer[fIndex]^.Text, 'this') or
SameStr(fTokenizer[fIndex]^.Text, 'thread_local') or
SameStr(fTokenizer[fIndex]^.Text, 'true') or
SameStr(fTokenizer[fIndex]^.Text, 'typename') or
SameStr(fTokenizer[fIndex]^.Text, 'virtual') or
SameStr(fTokenizer[fIndex]^.Text, 'volatile') or
SameStr(fTokenizer[fIndex]^.Text, 'xor') or
SameStr(fTokenizer[fIndex]^.Text, 'xor_eq') then begin
Inc(fIndex);
// Skip to ;
end else if SameStr(fTokenizer[fIndex]^.Text, 'delete') or
SameStr(fTokenizer[fIndex]^.Text, 'goto') or
SameStr(fTokenizer[fIndex]^.Text, 'new') or
SameStr(fTokenizer[fIndex]^.Text, 'return') or
SameStr(fTokenizer[fIndex]^.Text, 'throw') or
SameStr(fTokenizer[fIndex]^.Text, 'using') then begin
repeat
Inc(fIndex);
until (fIndex >= fTokenizer.Tokens.Count) or (fTokenizer[fIndex]^.Text[1] = ';');
Inc(fIndex); // step over
// Skip to :
end else if SameStr(fTokenizer[fIndex]^.Text, 'case') or
SameStr(fTokenizer[fIndex]^.Text, 'default') then begin
repeat
Inc(fIndex);
until (fIndex >= fTokenizer.Tokens.Count) or (fTokenizer[fIndex]^.Text[1] = ':');
// Skip to )
end else if SameStr(fTokenizer[fIndex]^.Text, 'alignas') or
SameStr(fTokenizer[fIndex]^.Text, 'alignof') or
SameStr(fTokenizer[fIndex]^.Text, 'decltype') or
SameStr(fTokenizer[fIndex]^.Text, 'if') or
SameStr(fTokenizer[fIndex]^.Text, 'sizeof') or
SameStr(fTokenizer[fIndex]^.Text, 'switch') or
SameStr(fTokenizer[fIndex]^.Text, 'typeid') or
SameStr(fTokenizer[fIndex]^.Text, 'while') then begin
repeat
Inc(fIndex);
until (fIndex >= fTokenizer.Tokens.Count) or (fTokenizer[fIndex]^.Text[Length(fTokenizer[fIndex]^.Text)] = ')');
Inc(fIndex); // step over
// Skip to {
end else if SameStr(fTokenizer[fIndex]^.Text, 'catch') or
SameStr(fTokenizer[fIndex]^.Text, 'do') or
SameStr(fTokenizer[fIndex]^.Text, 'namespace') or
SameStr(fTokenizer[fIndex]^.Text, 'try') then begin
repeat
Inc(fIndex);
until (fIndex >= fTokenizer.Tokens.Count) or (fTokenizer[fIndex]^.Text[1] = '{');
// Skip to }
end else if SameStr(fTokenizer[fIndex]^.Text, 'asm') then begin
repeat
Inc(fIndex);
until (fIndex >= fTokenizer.Tokens.Count) or (fTokenizer[fIndex]^.Text[1] = '}');
Inc(fIndex); // step over
end;
end;
procedure TCppParser.HandleVar;
var
LastType, Args, Cmd, S: String;
IsFunctionPointer: boolean;
begin
// Keep going and stop on top of the variable name
LastType := '';
IsFunctionPointer := False;
repeat
if (fIndex + 2 < fTokenizer.Tokens.Count) and (fTokenizer[fIndex + 1]^.Text[1] = '(') and (fTokenizer[fIndex +
2]^.Text[1] = '(') then begin
IsFunctionPointer := Pos('*', fTokenizer[fIndex + 1]^.Text) > 0;
if not IsFunctionPointer then
break; // inline constructor
end else if (fIndex + 1 < fTokenizer.Tokens.Count) and CharInSet(fTokenizer[fIndex + 1]^.Text[1], ['(', ',', ';', ':', '}',
'#']) then begin
Break;
end;
// TODO: why is this needed?
if (not SameStr(fTokenizer[fIndex]^.Text, 'struct')) and
(not SameStr(fTokenizer[fIndex]^.Text, 'class')) and
(not SameStr(fTokenizer[fIndex]^.Text, 'union')) then
LastType := LastType + ' ' + fTokenizer[fIndex]^.Text;
Inc(fIndex);
until (fIndex >= fTokenizer.Tokens.Count) or IsFunctionPointer;
LastType := Trim(LastType);
// Don't bother entering the scanning loop when we have failed
if fIndex >= fTokenizer.Tokens.Count then
Exit;
// Find the variable name
repeat
// Skip bit identifiers,
// e.g.:
// handle
// unsigned short bAppReturnCode:8,reserved:6,fBusy:1,fAck:1
// as
// unsigned short bAppReturnCode,reserved,fBusy,fAck
if (fIndex < fTokenizer.Tokens.Count) and (fTokenizer[fIndex]^.Text[1] = ':') then begin
repeat
Inc(fIndex);
until (fIndex >= fTokenizer.Tokens.Count) or CharInSet(fTokenizer[fIndex]^.Text[1], [',', ';', '{', '}']);
end;
// Skip inline constructors,
// e.g.:
// handle
// int a(3)
// as
// int a
if (not IsFunctionPointer) and (fIndex < fTokenizer.Tokens.Count) and (fTokenizer[fIndex]^.Text[1] = '(') then begin
while (fIndex < fTokenizer.Tokens.Count) and not CharInSet(fTokenizer[fIndex]^.Text[1], [',', ';', '{', '}']) do
Inc(fIndex);
end;
// Did we stop on top of the variable name?
if fIndex < fTokenizer.Tokens.Count then begin
if not CharInSet(fTokenizer[fIndex]^.Text[1], [',', ';']) then begin
if IsFunctionPointer and (fIndex + 1 < fTokenizer.Tokens.Count) then begin
S := fTokenizer[fIndex]^.Text;
Cmd := Trim(Copy(S, 3, Length(S) - 3)); // (*foo) -> foo
Args := fTokenizer[fIndex + 1]^.Text; // (int a,int b)
LastType := LastType + '(*)' + Args; // void(int a,int b)
Inc(fIndex);
end else if fTokenizer[fIndex]^.Text[Length(fTokenizer[fIndex]^.Text)] = ']' then begin //array; break args
Cmd := Copy(fTokenizer[fIndex]^.Text, 1, Pos('[', fTokenizer[fIndex]^.Text) - 1);
Args := Copy(fTokenizer[fIndex]^.Text, Pos('[', fTokenizer[fIndex]^.Text), Length(fTokenizer[fIndex]^.Text) -
Pos('[', fTokenizer[fIndex]^.Text) + 1);
end else begin
Cmd := fTokenizer[fIndex]^.Text;
Args := '';
end;
// Add a statement for every struct we are in
AddChildStatements(
GetCurrentClassLevel,
fCurrentFile,
'', // do not override hint
LastType,
Cmd,
Args,
fTokenizer[fIndex]^.Line,
skVariable,
GetScope,
fClassScope,
True,
False,
True); // TODO: not supported to pass list
end;
// Step over the variable name
if not CharInSet(fTokenizer[fIndex]^.Text[1], [';', '{', '}']) then
Inc(fIndex);
end;
until (fIndex >= fTokenizer.Tokens.Count) or CharInSet(fTokenizer[fIndex]^.Text[1], [';', '{', '}']);
// Skip ; and ,
if (fIndex < fTokenizer.Tokens.Count) and not CharInSet(fTokenizer[fIndex]^.Text[1], ['{', '}']) then
Inc(fIndex);
end;
procedure TCppParser.HandleEnum;
var
LastType: String;
Args: String;
Cmd: String;
EnumName: String;
I: integer;
begin
EnumName := '';
Inc(fIndex); //skip 'enum'
if fTokenizer[fIndex]^.Text[1] = '{' then begin // enum {...} NAME
// Skip to the closing brace
I := SkipBraces(fIndex);
// Have we found the name?
if (I + 1 < fTokenizer.Tokens.Count) and (fTokenizer[I]^.Text[1] = '}') then
if fTokenizer[I + 1]^.Text[1] <> ';' then
EnumName := Trim(fTokenizer[I + 1]^.Text);
end else begin // enum NAME {...};
while (fIndex < fTokenizer.Tokens.Count) and (not CharInSet(fTokenizer[fIndex]^.Text[1], ['{', ';'])) do begin
EnumName := EnumName + fTokenizer[fIndex]^.Text + ' ';
Inc(fIndex);
end;
EnumName := Trim(EnumName);
// An opening brace must be present after NAME
if (fIndex >= fTokenizer.Tokens.Count) or (fTokenizer[fIndex]^.Text[1] <> '{') then
Exit;
end;
// Add statement for enum name too
if EnumName <> '' then
AddStatement(
GetLastCurrentClass,
fCurrentFile,
'', // do not override hint
'enum',
EnumName,
Args,
fTokenizer[fIndex]^.Line,
skTypedef,
GetScope,
fClassScope,
False,
False,
True,
nil);
// Skip opening brace
Inc(fIndex);
// Call every member "enum NAME ITEMNAME"
LastType := TrimRight('enum ' + EnumName);
repeat
if not CharInSet(fTokenizer[fIndex]^.Text[1], [',', ';']) then begin
if fTokenizer[fIndex]^.Text[Length(fTokenizer[fIndex]^.Text)] = ']' then begin //array; break args
Cmd := Copy(fTokenizer[fIndex]^.Text, 1, Pos('[', fTokenizer[fIndex]^.Text) - 1);
Args := Copy(fTokenizer[fIndex]^.Text, Pos('[', fTokenizer[fIndex]^.Text), Length(fTokenizer[fIndex]^.Text) -
Pos('[', fTokenizer[fIndex]^.Text) + 1);
end else begin
Cmd := fTokenizer[fIndex]^.Text;
Args := '';
end;
AddStatement(
GetLastCurrentClass,
fCurrentFile,
LastType + ' ' + fTokenizer[fIndex]^.Text, // override hint
LastType,
Cmd,
Args,
fTokenizer[fIndex]^.Line,
skEnum,
GetScope,
fClassScope,
False,
False,
True,
nil);
end;
Inc(fIndex);
until (fIndex >= fTokenizer.Tokens.Count) or CharInSet(fTokenizer[fIndex]^.Text[1], [';', '{', '}']);
// Step over closing brace
if (fIndex < fTokenizer.Tokens.Count) and (fTokenizer[fIndex]^.Text[1] = '}') then
Inc(fIndex);
end;
function TCppParser.HandleStatement: boolean;
var
S1, S2, S3: String;
begin
if fTokenizer[fIndex]^.Text[1] = '{' then begin
AddSoloClassLevel(nil);
Inc(fIndex);
end else if fTokenizer[fIndex]^.Text[1] = '}' then begin
RemoveClassLevel;
Inc(fIndex);
end else if CheckForPreprocessor then begin
HandlePreprocessor;
end else if CheckForKeyword then begin // includes template now
HandleKeyword;
end else if CheckForScope then begin
HandleScope;
end else if CheckForEnum then begin
HandleEnum;
end else if CheckForTypedef then begin
if CheckForTypedefStruct then begin // typedef struct something
Inc(fIndex); // skip 'typedef'
HandleStructs(True)
end else if CheckForTypedefEnum then begin // typedef enum something
Inc(fIndex); // skip 'typedef'
HandleEnum;
end else
HandleOtherTypedefs; // typedef Foo Bar
end else if CheckForStructs then begin
HandleStructs(False);
end else if CheckForMethod(S1, S2, S3) then begin
HandleMethod(S1, S2, S3); // don't recalculate parts
end else if CheckForVar then begin
HandleVar;
end else
Inc(fIndex);
CheckForSkipStatement;
Result := fIndex < fTokenizer.Tokens.Count;
end;
procedure TCppParser.InternalParse(const FileName: String; ManualUpdate: boolean = False; Stream: TMemoryStream =
nil);
begin
// Perform some validation before we start
if not fEnabled then
Exit;
if not Assigned(Stream) and not (IsCfile(Filename) or IsHfile(Filename)) then // support only known C/C++ files
Exit;
if (fTokenizer = nil) or (fPreprocessor = nil) then
Exit;
// Start a timer here
if (not ManualUpdate) and Assigned(fOnStartParsing) then
fOnStartParsing(Self);
// Preprocess the file...
try
// Let the preprocessor augment the include records
fPreprocessor.SetIncludesList(fIncludesList);
fPreprocessor.SetIncludePaths(fIncludePaths);
fPreprocessor.SetProjectIncludePaths(fProjectIncludePaths);
fPreprocessor.SetScannedFileList(fScannedFiles);
fPreprocessor.SetScanOptions(fParseGlobalHeaders, fParseLocalHeaders);
if Assigned(Stream) then
fPreprocessor.PreprocessStream(FileName, Stream)
else
fPreprocessor.PreprocessFile(FileName); // load contents from disk
except
if (not ManualUpdate) and Assigned(fOnEndParsing) then
fOnEndParsing(Self, -1);
fPreprocessor.Reset; // remove buffers from memory
Exit;
end;
// Tokenize the preprocessed buffer file
try
fTokenizer.TokenizeBuffer(PChar(fPreprocessor.Result));
if fTokenizer.Tokens.Count = 0 then begin
fPreprocessor.Reset;
fTokenizer.Reset;
Exit;
end;
except
if (not ManualUpdate) and Assigned(fOnEndParsing) then
fOnEndParsing(Self, -1);
fPreprocessor.Reset;
fTokenizer.Reset;
Exit;
end;
// Tokenize the token list
fIndex := 0;
fClassScope := scsNone;
try
repeat
until not HandleStatement;
finally
fSkipList.Clear; // remove data from memory, but reuse structures
fCurrentClass.Clear;
fPreprocessor.Reset;
fTokenizer.Reset;
if (not ManualUpdate) and Assigned(fOnEndParsing) then
fOnEndParsing(Self, 1);
end;
if not ManualUpdate then
if Assigned(fOnUpdate) then
fOnUpdate(Self);
end;
procedure TCppParser.Reset;
var
I: integer;
begin
if Assigned(fOnBusy) then
fOnBusy(Self);
fPendingDeclarations.Clear; // should be empty anyways
fFilesToScan.Clear;
if Assigned(fTokenizer) then
fTokenizer.Reset;
// Remove all statements
fStatementList.Clear;
// We haven't scanned anything anymore
fScannedFiles.Clear;
// We don't include anything anymore
for I := fIncludesList.Count - 1 downto 0 do
Dispose(PFileIncludes(fIncludesList[I]));
fIncludesList.Clear;
fProjectFiles.Clear;
if Assigned(fOnUpdate) then
fOnUpdate(Self);
end;
procedure TCppParser.ParseFileList;
var
I: integer;
begin
if not fEnabled then
Exit;
if Assigned(fOnBusy) then
fOnBusy(Self);
if Assigned(fOnStartParsing) then
fOnStartParsing(Self);
try
// Support stopping of parsing when files closes unexpectedly
I := 0;
fFilesScannedCount := 0;
fFilesToScanCount := fFilesToScan.Count;
while I < fFilesToScan.Count do begin
Inc(fFilesScannedCount); // progress is mentioned before scanning begins
if Assigned(fOnTotalProgress) then
fOnTotalProgress(Self, fFilesToScan[i], fFilesToScanCount, fFilesScannedCount);
if fScannedFiles.IndexOf(fFilesToScan[i]) = -1 then begin
InternalParse(fFilesToScan[i], True);
end;
Inc(I);
end;
fPendingDeclarations.Clear; // should be empty anyways
fFilesToScan.Clear;
finally
if Assigned(fOnEndParsing) then
fOnEndParsing(Self, fFilesScannedCount);
end;
if Assigned(fOnUpdate) then
fOnUpdate(Self);
end;
function TCppParser.GetSystemHeaderFileName(const FileName: String): String;
begin
Result := cbutils.GetSystemHeaderFileName(FileName, fIncludePaths);
end;
function TCppParser.GetLocalHeaderFileName(const RelativeTo, FileName: String): String;
begin
Result := cbutils.GetLocalHeaderFileName(RelativeTo, FileName, fProjectIncludePaths);
end;
function TCppParser.GetHeaderFileName(const RelativeTo, Line: String): String;
begin
Result := cbutils.GetHeaderFileName(RelativeTo, Line, fIncludePaths, fProjectIncludePaths);
end;
function TCppParser.IsIncludeLine(const Line: String): boolean;
begin
Result := cbutils.IsIncludeLine(Line);
end;
procedure TCppParser.AddFileToScan(Value: String; InProject: boolean);
begin
Value := StringReplace(Value, '/', '\', [rfReplaceAll]); // only accept full file names
// Update project listing
if InProject then
if fProjectFiles.IndexOf(Value) = -1 then
fProjectFiles.Add(Value);
// Only parse given file
if fFilesToScan.IndexOf(Value) = -1 then // check scheduled files
if fScannedFiles.IndexOf(Value) = -1 then // check files already parsed
fFilesToScan.Add(Value);
end;
procedure TCppParser.AddIncludePath(const Value: String);
var
S: String;
begin
S := AnsiDequotedStr(Value, '"');
if fIncludePaths.IndexOf(S) = -1 then
fIncludePaths.Add(S);
end;
procedure TCppParser.AddProjectIncludePath(const Value: String);
var
S: String;
begin
S := AnsiDequotedStr(Value, '"');
if fProjectIncludePaths.IndexOf(S) = -1 then
fProjectIncludePaths.Add(S);
end;
procedure TCppParser.ClearIncludePaths;
begin
fIncludePaths.Clear;
end;
procedure TCppParser.ClearProjectIncludePaths;
begin
fProjectIncludePaths.Clear;
end;
procedure TCppParser.ResetDefines;
begin
if Assigned(fPreprocessor) then
fPreprocessor.ResetDefines;
end;
procedure TCppParser.AddHardDefineByParts(const Name, Args, Value: String);
begin
if Assigned(fPreprocessor) then
fPreprocessor.AddDefineByParts(Name, Args, Value, True);
end;
procedure TCppParser.AddHardDefineByLine(const Line: String);
begin
if Assigned(fPreprocessor) then begin
if Pos('#', Line) = 1 then
fPreprocessor.AddDefineByLine(TrimLeft(Copy(Line, 2, MaxInt)), True)
else
fPreprocessor.AddDefineByLine(Line, True);
end;
end;
function TCppParser.IsSystemHeaderFile(const FileName: String): boolean;
begin
Result := cbutils.IsSystemHeaderFile(FileName, fIncludePaths);
end;
procedure TCppParser.ParseFile(const FileName: String; InProject: boolean; OnlyIfNotParsed: boolean = False;
UpdateView: boolean = True; Stream: TMemoryStream = nil);
var
FName: String;
CFile, HFile: String;
I: integer;
begin
if not fEnabled then
Exit;
FName := FileName;
if OnlyIfNotParsed and (fScannedFiles.IndexOf(FName) <> -1) then
Exit;
if Assigned(fOnBusy) then
fOnBusy(Self);
// Always invalidate file pairs. If we don't, reparsing the header
// screws up the information inside the source file
GetSourcePair(FName, CFile, HFile);
fInvalidatedStatements.Clear;
InvalidateFile(CFile);
InvalidateFile(HFile);
if InProject then begin
if (CFile <> '') and (fProjectFiles.IndexOf(CFile) = -1) then
fProjectFiles.Add(CFile);
if (HFile <> '') and (fProjectFiles.IndexOf(HFile) = -1) then
fProjectFiles.Add(HFile);
end else begin
I := fProjectFiles.IndexOf(CFile);
if I <> -1 then
fProjectFiles.Delete(I);
I := fProjectFiles.IndexOf(HFile);
if I <> -1 then
fProjectFiles.Delete(I);
end;
// Parse from disk or stream
if Assigned(fOnStartParsing) then
fOnStartParsing(Self);
try
fFilesToScanCount := 0;
fFilesScannedCount := 0;
if not Assigned(Stream) then begin
if CFile = '' then
InternalParse(HFile, True) // headers should be parsed via include
else
InternalParse(CFile, True); // headers should be parsed via include
end else
InternalParse(FileName, True, Stream); // or from stream
fFilesToScan.Clear;
fPendingDeclarations.Clear; // should be empty anyways
ReProcessInheritance; // account for inherited statements that have dissappeared
finally
if Assigned(fOnEndParsing) then
fOnEndParsing(Self, 1);
end;
if UpdateView then
if Assigned(fOnUpdate) then
fOnUpdate(Self);
end;
procedure TCppParser.InvalidateFile(const FileName: String);
var
I: integer;
P: PFileIncludes;
Node, NextNode: PStatementNode;
Statement: PStatement;
begin
if Filename = '' then
Exit;
// delete statements of file
Node := fStatementList.FirstNode;
while Assigned(Node) do begin
Statement := Node^.Data;
NextNode := Node^.NextNode; // parent classname is encountered first
// Is this statement part of this file? Remove
if SameText(Statement^._FileName, FileName) or SameText(Statement^._DefinitionFileName, FileName) then begin
if Statement^._Kind = skClass then // only classes have inheritance
fInvalidatedStatements.Add(Statement);
fStatementList.Delete(Node);
end;
Node := NextNode;
end;
// delete it from scannedfiles
I := fScannedFiles.IndexOf(FileName);
if I <> -1 then
fScannedFiles.Delete(I);
// remove its include files list
P := FindFileIncludes(FileName, True);
if Assigned(P) then
Dispose(PFileIncludes(P));
end;
procedure TCppParser.GetMultipleInheritanceStatements(Statement: PStatement; List: TList);
var
I: integer;
procedure AddFromStatement(Statement: PStatement);
var
I: integer;
begin
if Assigned(Statement^._InheritanceList) then
for I := 0 to Statement^._InheritanceList.Count - 1 do
List.Add(Statement^._InheritanceList[i]);
end;
begin
List.Clear;
if not Assigned(Statement) then
Exit;
// Add first level inheritance
AddFromStatement(Statement);
// then process inheritance of inherited items
I := 0;
while I < List.Count do begin
AddFromStatement(List[I]);
Inc(I); // step over
end;
end;
procedure TCppParser.ReProcessInheritance;
var
Node: PStatementNode;
Statement, InvalidatedStatement: PStatement;
I: integer;
sl: TStringList;
begin
// after reparsing a file, we have to reprocess inheritance,
// because by invalidating the file, we might have deleted
// some Statements that were inherited by other, valid, statements.
// we need to re-adjust the IDs now...
if fInvalidatedStatements.Count = 0 then
Exit;
sl := TStringList.Create;
try
sl.Sorted := True;
sl.Duplicates := dupIgnore;
// Create a list of files that contain invalidated IDs that are inherited from
Node := fStatementList.FirstNode;
while Assigned(Node) do begin
Statement := Node^.Data;
// Does this statement inherit from any invalidated statement?
for I := 0 to fInvalidatedStatements.Count - 1 do begin
InvalidatedStatement := fInvalidatedStatements[i];
if Assigned(Statement._InheritanceList) and (Statement._InheritanceList.IndexOf(InvalidatedStatement) <> -1) then
begin
sl.Add(Statement^._FileName);
break; // don't bother checking other invalidated statements
end;
end;
Node := Node^.NextNode;
end;
// Reparse every file that contains invalidated IDs
for I := 0 to sl.Count - 1 do
ParseFile(sl[I], fProjectFiles.IndexOf(sl[I]) <> -1, False, False);
//InternalParse(sl[I], True, nil); // TODO: do not notify user
finally
sl.Free;
end;
end;
function TCppParser.SuggestMemberInsertionLine(ParentStatement: PStatement; Scope: TStatementClassScope; var
AddScopeStr: boolean): integer;
var
Node: PStatementNode;
Statement: PStatement;
maxInScope: integer;
maxInGeneral: integer;
begin
// this function searches in the statements list for statements with
// a specific _ParentID, and returns the suggested line in file for insertion
// of a new var/method of the specified class scope. The good thing is that
// if there is no var/method by that scope, it still returns the suggested
// line for insertion (the last line in the class).
maxInScope := -1;
maxInGeneral := -1;
Node := fStatementList.FirstNode;
while Assigned(Node) do begin
Statement := Node^.Data;
if Statement^._Parent = ParentStatement then begin
if Statement^._HasDefinition then begin
if Statement^._Line > maxInGeneral then
maxInGeneral := Statement^._Line;
if Statement^._ClassScope = scope then
if Statement^._Line > maxInScope then
maxInScope := Statement^._Line;
end else begin
if Statement^._DefinitionLine > maxInGeneral then
maxInGeneral := Statement^._Line;
if Statement^._ClassScope = scope then
if Statement^._DefinitionLine > maxInScope then
maxInScope := Statement^._DefinitionLine;
end;
end;
Node := Node^.NextNode;
end;
if maxInScope = -1 then begin
AddScopeStr := True;
Result := maxInGeneral;
end else begin
AddScopeStr := False;
Result := maxInScope;
end;
end;
procedure TCppParser.GetClassesList(var List: TStringList);
var
Node: PStatementNode;
Statement: PStatement;
begin
// fills List with a list of all the known classes
List.Clear;
Node := fStatementList.LastNode;
while Assigned(Node) do begin
Statement := Node^.Data;
if Statement^._Kind = skClass then
List.AddObject(Statement^._Command, Pointer(Statement));
Node := Node^.PrevNode;
end;
end;
function TCppParser.FindAndScanBlockAt(const Filename: String; Row: integer; Stream: TMemoryStream): PStatement;
function GetFuncStartLine(Index, StartLine: integer): integer;
begin
Result := Index;
// Keep advancing until we find the start line
while Index < fTokenizer.Tokens.Count do begin
if fTokenizer[Index]^.Line = StartLine then begin
// Find the opening brace from here
while (Index < fTokenizer.Tokens.Count) and (fTokenizer[Index]^.Text[1] <> '{') do
Inc(Index);
// Found it before the file stopped? Yay
if (Index < fTokenizer.Tokens.Count) and (fTokenizer[Index]^.Text[1] = '{') then begin
Result := Index;
Break;
end;
end;
Inc(Index);
end;
end;
function GetFuncEndLine(Index: integer): integer; // basic brace skipper
var
Level: integer;
begin
Level := 0; // when this goes negative, we 're there (we have skipped the opening brace already)
while (Index < fTokenizer.Tokens.Count) and (Level >= 0) do begin
if fTokenizer[Index]^.Text[1] = '{' then
Inc(Level)
else if fTokenizer[Index]^.Text[1] = '}' then
Dec(Level);
Inc(Index);
end;
Result := Index;
end;
var
ClosestLine, FuncStartIndex, FuncEndIndex: integer;
Node: PStatementNode;
Statement, ClosestStatement, ParentStatement: PStatement;
InsideBody: Boolean;
begin
Result := nil;
if (fTokenizer = nil) or (fPreprocessor = nil) then
Exit;
DeleteTemporaries;
ClosestLine := -1;
ClosestStatement := nil;
InsideBody := False;
// Search for the current function/class we are pointing at
Node := fStatementList.FirstNode;
while Assigned(Node) do begin
Statement := Node^.Data;
case Statement^._Kind of
skClass: begin
if SameFileName(Statement^._FileName, FileName) then
if (Statement^._Line <= Row) and (Statement^._Line > ClosestLine) then begin
ClosestStatement := Statement;
ClosestLine := Statement^._Line;
InsideBody := Statement^._Line < Row;
end;
end;
skFunction, skConstructor, skDestructor: begin
// Check definition
if Statement^._HasDefinition and SameFileName(Statement^._DefinitionFileName, Filename) then begin
if (Statement^._DefinitionLine <= Row) and (Statement^._DefinitionLine > ClosestLine) then begin
ClosestStatement := Statement;
ClosestLine := Statement^._DefinitionLine;
InsideBody := Statement^._Line < Row;
end;
end;
// Check declaration
if SameFileName(Statement^._FileName, Filename) then begin
if (Statement^._Line <= Row) and (Statement^._Line > ClosestLine) then begin
ClosestStatement := Statement;
ClosestLine := Statement^._Line;
InsideBody := True; // no body, so assume true
end;
end;
end;
end;
Node := Node^.NextNode;
end;
// We have found the function or class body we are in
if Assigned(ClosestStatement) then begin
// For classes, the line with the class keyword on it belongs to the parent
if ClosestStatement^._Kind = skClass then begin
if not InsideBody then begin // Hovering above a class name
ParentStatement := ClosestStatement^._Parent;
end else begin // inside class body
ParentStatement := ClosestStatement; // class
end;
// For functions, it does not
end else begin // it's a function
ParentStatement := ClosestStatement^._Parent; // class::function
end;
// The result is the class the function belongs to or the class body we're in
Result := ParentStatement;
// Scan the function definition body if we're inside a function
if (ClosestStatement^._Kind in [skFunction, skConstructor, skDestructor]) and (ClosestStatement^._HasDefinition) and
(ClosestStatement^._DefinitionLine = ClosestLine) then begin
// Preprocess the stream that contains the latest version of the current file (not on disk)
fPreprocessor.SetIncludesList(fIncludesList);
fPreprocessor.SetIncludePaths(fIncludePaths);
fPreprocessor.SetProjectIncludePaths(fProjectIncludePaths);
fPreprocessor.SetScannedFileList(fScannedFiles);
fPreprocessor.SetScanOptions(fParseGlobalHeaders, fParseLocalHeaders);
fPreprocessor.PreProcessStream(FileName, Stream);
// Tokenize the stream so we can find the start and end of the function body
fTokenizer.TokenizeBuffer(PChar(fPreprocessor.Result));
// Find start of the function block and start from the opening brace
FuncStartIndex := GetFuncStartLine(0, ClosestLine);
// Now find the end of the function block and check that the Row is still in scope
FuncEndIndex := GetFuncEndLine(FuncStartIndex + 1);
// if we 're past the end or before the start of function or class body, we are not in the scope...
if (Row > fTokenizer[FuncEndIndex - 1]^.Line) or (Row < fTokenizer[FuncStartIndex]^.Line) then begin
Result := nil;
Exit;
end;
// Set current file manually because we aren't parsing whole files
fCurrentFile := Filename;
fIsSystemHeader := IsSystemHeaderFile(fCurrentFile);
fIsProjectFile := fProjectFiles.IndexOf(fCurrentFile) <> -1;
fIsHeader := IsHfile(fCurrentFile);
// We've found the function body. Scan it
fIndex := FuncStartIndex;
fClassScope := scsNone;
fLaterScanning := True;
repeat
if fTokenizer[fIndex]^.Text[1] = '{' then begin
AddSoloClassLevel(nil);
Inc(fIndex);
end else if fTokenizer[fIndex]^.Text[1] = '}' then begin
RemoveClassLevel;
Inc(fIndex);
if fCurrentClass.Count = 0 then
Break; // we've gone out of scope
end else if CheckForPreprocessor then begin
HandlePreprocessor;
end else if CheckForKeyword then begin
HandleKeyword;
end else if CheckForEnum then begin
HandleEnum;
end else if CheckForVar then begin
HandleVar;
end else
Inc(fIndex);
CheckForSkipStatement;
until (fIndex >= fTokenizer.Tokens.Count) or (fIndex >= FuncEndIndex);
// add the all-important "this" pointer as a local variable
if Assigned(ParentStatement) then begin
AddStatement(
ParentStatement,
Filename,
'',
ParentStatement^._Command + '*',
'this',
'',
ParentStatement^._DefinitionLine + 1,
skVariable,
ssClassLocal,
scsPrivate,
False,
False,
True,
nil);
end;
// Try to use arglist which includes names (implementation, not declaration)
ScanMethodArgs(
ClosestStatement^._Args,
ClosestStatement^._DefinitionFileName,
ClosestStatement^._DefinitionLine);
// Everything scanned before this point should be removed
fLaterScanning := False;
end;
end;
end;
function TCppParser.GetClass(const Phrase: String): String;
var
I, FirstOp: integer;
begin
// Obtain stuff before first operator
FirstOp := Length(Phrase) + 1;
for I := 1 to Length(Phrase) - 1 do begin
if (phrase[i] = '-') and (Phrase[i + 1] = '>') then begin
FirstOp := I;
break;
end else if (Phrase[i] = ':') and (Phrase[i + 1] = ':') then begin
FirstOp := I;
break;
end else if (Phrase[i] = '.') then begin
FirstOp := I;
break;
end;
end;
Result := Copy(Phrase, 1, FirstOp - 1);
end;
function TCppParser.GetMember(const Phrase: String): String;
var
FirstOp, SecondOp, I: integer;
begin
// Obtain stuff after first operator
FirstOp := 0;
for I := 1 to Length(Phrase) - 1 do begin
if (phrase[i] = '-') and (Phrase[i + 1] = '>') then begin
FirstOp := I + 2;
break;
end else if (Phrase[i] = ':') and (Phrase[i + 1] = ':') then begin
FirstOp := I + 2;
break;
end else if (Phrase[i] = '.') then begin
FirstOp := I + 1;
break;
end;
end;
if FirstOp = 0 then begin
Result := '';
Exit;
end;
// ... and before second op, if there is one
SecondOp := 0;
for I := firstop to Length(Phrase) - 1 do begin
if (phrase[i] = '-') and (Phrase[i + 1] = '>') then begin
SecondOp := I;
break;
end else if (Phrase[i] = ':') and (Phrase[i + 1] = ':') then begin
SecondOp := I;
break;
end else if (Phrase[i] = '.') then begin
SecondOp := I;
break;
end;
end;
if SecondOp = 0 then
Result := Copy(Phrase, FirstOp, MaxInt)
else
Result := Copy(Phrase, FirstOp, SecondOp - FirstOp);
end;
function TCppParser.GetOperator(const Phrase: String): String;
var
I: integer;
begin
Result := '';
// Find first operator
for I := 1 to Length(Phrase) - 1 do begin
if (phrase[i] = '-') and (Phrase[i + 1] = '>') then begin
Result := '->';
break;
end else if (Phrase[i] = ':') and (Phrase[i + 1] = ':') then begin
Result := '::';
break;
end else if (Phrase[i] = '.') then begin
Result := '.';
break;
end;
end;
end;
function TCppParser.FindLastOperator(const Phrase: String): integer;
var
I: integer;
begin
I := Length(phrase);
// Obtain stuff after first operator
while I > 0 do begin
if (phrase[i + 1] = '>') and (phrase[i] = '-') then begin
Result := i;
Exit;
end else if (phrase[i + 1] = ':') and (phrase[i] = ':') then begin
Result := i;
Exit;
end else if (phrase[i] = '.') then begin
Result := i;
Exit;
end;
Dec(i);
end;
Result := 0;
end;
function TCppParser.PrettyPrintStatement(Statement: PStatement): String;
function GetScopePrefix: String;
var
ScopeStr: String;
begin
ScopeStr := StatementClassScopeStr(Statement^._ClassScope); // can be blank
if ScopeStr <> '' then
Result := ScopeStr + ' '
else
Result := '';
end;
function GetParentPrefix: String;
var
WalkStatement: PStatement;
begin
Result := '';
WalkStatement := Statement;
while Assigned(WalkStatement^._Parent) do begin
Result := WalkStatement^._Parent^._Command + '::' + Result;
WalkStatement := WalkStatement^._Parent;
end;
end;
function GetArgsSuffix: String;
begin
if Statement^._Args <> '' then
Result := ' ' + Statement^._Args
else
Result := '';
end;
begin
Result := '';
if Statement^._HintText <> '' then begin
Result := Statement^._HintText;
end else begin
case Statement^._Kind of
skFunction,
skVariable,
skClass: begin
Result := GetScopePrefix; // public
Result := Result + Statement^._Type + ' '; // void
Result := Result + GetParentPrefix; // A::B::C::
Result := Result + Statement^._Command; // Bar
Result := Result + GetArgsSuffix; // (int a)
end;
skConstructor: begin
Result := GetScopePrefix; // public
Result := Result + 'constructor' + ' '; // constructor
Result := Result + GetParentPrefix; // A::B::C::
Result := Result + Statement^._Command; // Bar
Result := Result + GetArgsSuffix; // (int a)
end;
skDestructor: begin
Result := GetScopePrefix; // public
Result := Result + 'destructor' + ' '; // destructor
Result := Result + GetParentPrefix; // A::B::C::
Result := Result + Statement^._Command; // Bar
Result := Result + GetArgsSuffix; // (int a)
end;
skTypedef: begin
Result := 'skTypedef hint'; // should be set by HintText
end;
skEnum: begin
Result := 'skEnum hint'; // should be set by HintText
end;
skPreprocessor: begin
Result := 'skPreprocessor hint'; // should be set by HintText
end;
skUnknown: begin
Result := 'skUnknown hint'; // should be set by HintText
end;
end;
end;
end;
procedure TCppParser.FillListOfFunctions(const Full: String; List: TStringList);
var
Node: PStatementNode;
Statement: PStatement;
begin
List.Clear;
// Tweaked for specific use by CodeToolTip. Also avoids String compares whenever possible
Node := fStatementList.LastNode; // Prefer user declared names
while Assigned(Node) do begin
Statement := Node^.Data;
if Statement^._Kind in [skFunction, skConstructor, skDestructor] then begin
// Also add Win32 Ansi/Wide variants...
if SameStr(Full, Statement^._Command) or
SameStr(Full + 'A', Statement^._Command) or
SameStr(Full + 'W', Statement^._Command) then begin
List.Add(PrettyPrintStatement(Statement));
end;
end;
Node := Node^.PrevNode;
end;
end;
function TCppParser.FindTypeDefinitionOf(const aType: String; CurrentClass: PStatement): PStatement;
var
Node: PStatementNode;
Statement: PStatement;
position: integer;
s: String;
begin
// Remove pointer stuff from type
s := aType; // 'Type' is a keyword
position := Length(s);
while (position > 0) and CharInSet(s[position], ['*', '&']) do
Dec(position);
if position <> Length(s) then
Delete(s, position + 1, Length(s) - 1);
// Strip template stuff
position := Pos('<', s);
if position > 0 then
Delete(s, position, MaxInt);
// Use last word only (strip 'const', 'static', etc)
position := LastPos(' ', s);
if position > 0 then
Delete(s, 1, position);
// Seach them
Node := fStatementList.LastNode;
while Assigned(Node) do begin
Statement := Node^.Data;
if Statement^._Parent = CurrentClass then begin // TODO: type definitions can have scope too
if Statement^._Kind = skClass then begin // these have type 'class'
// We have found the statement of the type directly
if SameStr(Statement^._Command, s) then begin
Result := Statement; // 'class foo'
Exit;
end;
end else if Statement^._Kind = skTypedef then begin
// We have found a variable with the same name, search for type
if SameStr(Statement^._Command, s) then begin
if not SameStr(aType, Statement^._Type) then // prevent infinite loop
Result := FindTypeDefinitionOf(Statement^._Type, CurrentClass)
else
Result := Statement; // stop walking the trail here
if Result = nil then // found end of typedef trail, return result
Result := Statement;
Exit;
end;
end;
end;
Node := Node^.PrevNode;
end;
Result := nil;
end;
function TCppParser.FindVariableOf(const Phrase: String; CurrentClass: PStatement): PStatement;
var
Node: PStatementNode;
Statement: PStatement;
begin
// Check local variables
Node := fStatementList.LastNode;
while Assigned(Node) do begin
Statement := Node^.Data;
// Class members
if (Statement^._Scope = ssClassLocal) and Assigned(CurrentClass) and (Statement^._Parent = CurrentClass) then begin
if SameStr(Statement^._Command, Phrase) then begin
result := Statement;
Exit;
end;
// Local scope variables (includes function arguments)
end else if (Statement^._Scope = ssLocal) then begin
if SameStr(Statement^._Command, Phrase) then begin
result := Statement;
Exit;
end;
end;
Node := Node^.PrevNode;
end;
// Then, assume the variable belongs to the current scope/class, if there is one
if Assigned(CurrentClass) then begin
Node := fStatementList.LastNode; // Start scanning backwards, because owner data is found there
while Assigned(Node) do begin
Statement := Node^.Data;
if Statement^._Parent = CurrentClass then begin
if SameStr(Statement^._Command, Phrase) then begin
result := Statement;
Exit;
end;
end else if Assigned(CurrentClass^._InheritanceList) and
(CurrentClass^._InheritanceList.IndexOf(Statement^._Parent) <> -1) then begin // try inheritance
// hide private stuff?
if SameStr(Statement^._Command, Phrase) then begin
result := Statement;
Exit;
end;
end;
Node := Node^.PrevNode;
end;
end;
// What remains are globals. Just do a raw scan...
Node := fStatementList.LastNode; // prefer globals inside source files
while Assigned(Node) do begin
Statement := Node^.Data;
if Statement^._Scope = ssGlobal then begin
if SameStr(Statement^._Command, Phrase) then begin
result := Statement;
Exit;
end;
end;
Node := Node^.PrevNode;
end;
Result := nil;
end;
function TCppParser.FindStatementOf(Phrase: String; CurrentClass: PStatement): PStatement;
var
Node: PStatementNode;
ParentWord, MemberWord, OperatorToken: String;
InheritanceStatements: TList;
Statement, MemberStatement, TypedefStatement, VariableStatement, CurrentClassParent: PStatement;
begin
Result := nil;
// We need to reuse this
if Assigned(CurrentClass) then
CurrentClassParent := CurrentClass^._Parent
else
CurrentClassParent := nil;
// Get the FIRST class and member, surrounding the FIRST operator
ParentWord := GetClass(Phrase);
OperatorToken := GetOperator(Phrase);
MemberWord := GetMember(Phrase);
// First, assume the parentword is a type (type names have more priority than variables)
// For example, find "class Foo" or "typedef Foo"
TypedefStatement := FindTypeDefinitionOf(ParentWord, CurrentClass);
if Assigned(TypedefStatement) then
Result := TypedefStatement;
// If it was not a type, check if it was a variable name
if not Assigned(TypedefStatement) then begin
VariableStatement := FindVariableOf(ParentWord, CurrentClass);
// We have found a variable with name "Phrase"
if Assigned(VariableStatement) then begin
// If we do not need to find children of this variable, stop here
if OperatorToken = '' then begin
Result := VariableStatement;
Exit;
// We need to find children of this variable.
// What we need to find now is the type of the variable
end else begin
if VariableStatement^._Kind = skClass then
TypedefStatement := VariableStatement // a class statement is equal to its type
else begin
TypedefStatement := FindTypeDefinitionOf(VariableStatement^._Type, CurrentClassParent);
end;
// If we cannot find the type, stop here
if not Assigned(TypedefStatement) then begin
Result := VariableStatement;
Exit;
end;
end;
end;
end;
InheritanceStatements := TList.Create;
try
// Walk the chain of operators
while (MemberWord <> '') do begin
MemberStatement := nil;
// Get inheritance and inheritance of inheritance and (etc)
InheritanceStatements.Clear;
GetMultipleInheritanceStatements(TypedefStatement, InheritanceStatements);
// Add members of this type
Node := fStatementList.LastNode; // Start scanning backwards, because owner data is found there
while Assigned(Node) do begin
Statement := Node^.Data;
if Statement^._Parent = TypedefStatement then begin
if SameStr(Statement^._Command, MemberWord) then begin
MemberStatement := Statement;
break; // there can be only one with an equal name
end;
end else if (InheritanceStatements.IndexOf(Statement^._Parent) <> -1) then begin // try inheritance
// hide private stuff?
if SameStr(Statement^._Command, MemberWord) then begin
MemberStatement := Statement;
break;
end;
end;
Node := Node^.PrevNode;
end;
// Child not found. Stop searching
if not Assigned(MemberStatement) then
break;
Result := MemberStatement; // otherwise, continue
// next operator
Delete(Phrase, 1, Length(ParentWord) + Length(OperatorToken));
// Get the NEXT member, surrounding the next operator
ParentWord := GetClass(Phrase);
OperatorToken := GetOperator(Phrase);
MemberWord := GetMember(Phrase);
// Don't bother finding types
if MemberWord = '' then
break;
// At this point, we have a list of statements that conform to the a(operator)b demand.
// Now make these statements "a(operator)b" the parents, so we can use them as filters again
if MemberStatement^._Kind = skClass then
TypedefStatement := MemberStatement // a class statement is equal to its type
else
TypedefStatement := FindTypeDefinitionOf(MemberStatement^._Type, CurrentClass);
if not Assigned(TypedefStatement) then
break;
end;
finally
InheritanceStatements.Free;
end;
end;
function TCppParser.FindStatementOf(FileName, Phrase: String; Row: integer; Stream: TMemoryStream): PStatement;
begin
Result := FindStatementOf(Phrase, FindAndScanBlockAt(FileName, Row, Stream));
end;
procedure TCppParser.DeleteTemporaries;
var
Node, NextNode: PStatementNode;
Statement: PStatement;
begin
// Remove every statement when Temporary = true
Node := fStatementList.FirstNode;
while Assigned(Node) do begin
NextNode := Node^.NextNode;
Statement := Node^.Data;
if Statement^._Temporary then
fStatementList.Delete(Node);
Node := NextNode;
end;
end;
procedure TCppParser.ScanMethodArgs(const ArgStr: String; const Filename: String; Line: Integer);
var
I, ParamStart, SpacePos, BracePos: integer;
S: String;
begin
// Split up argument string by ,
I := 2; // assume it starts with ( and ends with )
ParamStart := I;
while I <= Length(ArgStr) do begin
if (ArgStr[i] = ',') or ((I = Length(ArgStr)) and (ArgStr[i] = ')')) then begin
// We've found "int* a" for example
S := Trim(Copy(ArgStr, ParamStart, I - ParamStart));
// Can be a function pointer. If so, scan after last )
BracePos := LastPos(')', S);
if BracePos > 0 then // it's a function pointer...
SpacePos := LastPos(' ', Copy(S, BracePos, MaxInt)) // start search at brace
else
SpacePos := LastPos(' ', S); // Cut up at last space
if SpacePos > 0 then begin
AddStatement(
nil,
Filename,
'', // do not override hint
Copy(S, 1, SpacePos - 1), // 'int*'
Copy(S, SpacePos + 1, MaxInt), // a
'',
Line,
skVariable,
ssLocal,
scsNone,
False,
False,
True,
nil);
end;
ParamStart := I + 1; // step over ,
end;
Inc(I);
end;
end;
function TCppParser.FindFileIncludes(const Filename: String; DeleteIt: boolean): PFileIncludes;
var
I: integer;
begin
Result := nil;
for I := 0 to fIncludesList.Count - 1 do
if SameText(PFileIncludes(fIncludesList[I])^.BaseFile, Filename) then begin
Result := PFileIncludes(fIncludesList[I]);
if DeleteIt then
fIncludesList.Delete(I);
Break;
end;
end;
function TCppParser.IsCfile(const Filename: String): boolean;
begin
result := cbutils.IsCfile(FileName);
end;
function TCppParser.IsHfile(const Filename: String): boolean;
begin
result := cbutils.IsHfile(Filename);
end;
procedure TCppParser.GetSourcePair(const FName: String; var CFile, HFile: String);
begin
cbutils.GetSourcePair(FName, CFile, HFile);
end;
procedure TCppParser.GetFileIncludes(const Filename: String; var List: TStringList);
procedure RecursiveFind(const FileName: String);
var
I: integer;
P: PFileIncludes;
sl: TStrings;
begin
if FileName = '' then
Exit;
List.Add(FileName);
// Find the files this file includes
P := FindFileIncludes(FileName);
if Assigned(P) then begin
// recursively search included files
sl := TStringList.Create;
try
// For each file this file includes, perform the same trick
sl.CommaText := P^.IncludeFiles;
for I := 0 to sl.Count - 2 do // Last one is always an empty item
if FastIndexOf(List, sl[I]) = -1 then
RecursiveFind(sl[I]);
finally
sl.Free;
end;
end;
end;
begin
List.Clear;
List.Sorted := false;
RecursiveFind(Filename);
end;
end.
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.