1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249
|
{
***************************************************************************
* *
* This source 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. *
* *
* This code 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. *
* *
* A copy of the GNU General Public License is available on the World *
* Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also *
* obtain it by writing to the Free Software Foundation, *
* Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA. *
* *
***************************************************************************
Author: Mattias Gaertner
Abstract:
TLinkScanner scans a source file, reacts to compiler directives, replaces
macros and reads include files. It builds one source and a link list. The
resulting source is called the cleaned source. A link points from a position
of the cleaned source to its position in the real source.
The link list makes it possible to find scanned code in the source files.
}
unit LinkScanner;
{$mode objfpc}{$H+}
{$I codetools.inc}
{ $DEFINE ShowIgnoreErrorAfter}
// debugging
{ $DEFINE ShowUpdateCleanedSrc}
{ $DEFINE VerboseIncludeSearch}
{ $DEFINE VerboseUpdateNeeded}
interface
uses
{$IFDEF MEM_CHECK}
MemCheck,
{$ENDIF}
// RTL + FCL
Classes, SysUtils, math, Laz_AVL_Tree,
// CodeTools
CodeToolsStrConsts, CodeToolMemManager, FileProcs, ExprEval, SourceLog,
KeywordFuncLists, BasicCodeTools,
// LazUtils
LazFileUtils, LazUtilities, LazDbgLog;
var
FPCSystemUnitName: String = 'system';
DelphiSystemUnitName: String = 'System';
const
PascalCompilerDefine = ExternalMacroStart+'Compiler';
MacroUseHeapTrc = ExternalMacroStart+'UseHeapTrcUnit';
MacroUseLineInfo = ExternalMacroStart+'UseLineInfo';
MacroUselnfodwrf = ExternalMacroStart+'Uselnfodwrf';
MacroUseValgrind = ExternalMacroStart+'UseValgrind';
MacroUseProfiler = ExternalMacroStart+'UseProfiler';
MacroUseFPCylix = ExternalMacroStart+'UseFPCylix';
MacroUseSysThrds = ExternalMacroStart+'UseSysThrds';
MacroControllerUnit = ExternalMacroStart+'ControllerUnit';
type
TLinkScanner = class;
//----------------------------------------------------------------------------
TOnGetSource = function(Sender: TObject; Code: Pointer): TSourceLog
of object;
TOnLoadSource = function(Sender: TObject; const AFilename: string;
OnlyIfExists: boolean): pointer of object;
TOnGetSourceStatus = procedure(Sender: TObject; Code: Pointer;
var ReadOnly: boolean) of object;
TOnDeleteSource = procedure(Sender: TObject; Code: Pointer; Pos, Len: integer)
of object;
TOnGetFileName = function(Sender: TObject; Code: Pointer): string of object;
TOnCheckFileOnDisk = function(Code: Pointer): boolean of object;
TOnGetInitValues = function(Scanner: TLinkScanner; Code: Pointer;
out ChangeStep: integer): TExpressionEvaluator of object;
TOnIncludeCode = procedure(ParentCode, IncludeCode: Pointer) of object;
TOnSetWriteLock = procedure(Lock: boolean) of object;
TLSOnGetGlobalChangeSteps = procedure(out SourcesChangeStep, FilesChangeStep: int64;
out InitValuesChangeStep: integer) of object;
{ TSourceLink is used to map between the codefiles and the cleaned source }
TSourceLinkKind = (
slkCode,
slkMissingIncludeFile,
slkSkipStart, // start of skipped code due to IFDEFs {#3
slkSkipEnd, // end of skipped code due to IFDEFs #3}
slkCompilerString // e.g. {$I %FPCVERSION%}
);
TSourceLinkKinds = set of TSourceLinkKind;
PSourceLink = ^TSourceLink;
TSourceLink = record
CleanedPos: integer;
SrcPos: integer;
Code: Pointer;
Kind: TSourceLinkKind;
Next: PSourceLink;
end;
TSourceLinkMacro = record
Name: PChar;
Code: Pointer;
Src: string;
SrcFilename: string;
StartPos, EndPos: integer;
end;
PSourceLinkMacro = ^TSourceLinkMacro;
{ TSourceChangeStep is used to save the ChangeStep of every used file
A ChangeStep is switching to or from an include file }
PSourceChangeStep = ^TSourceChangeStep;
TSourceChangeStep = record
Code: Pointer;
ChangeStep: integer;
Next: PSourceChangeStep;
end;
TLinkScannerRange = (
lsrNone, // undefined
lsrInit, // init, but do not scan any code
lsrSourceType, // read till source type (e.g. keyword program or unit)
lsrSourceName, // read till source name
lsrInterfaceStart, // read till keyword interface
lsrMainUsesSectionStart, // uses section of interface/program
lsrMainUsesSectionEnd, // uses section of interface/program
lsrImplementationStart, // scan at least to interface end (e.g. till implementation keyword)
lsrImplementationUsesSectionStart, // uses section of implementation
lsrImplementationUsesSectionEnd, // uses section of implementation
lsrInitializationStart,
lsrFinalizationStart,
lsrEnd // scan till 'end.'
);
TCommentStyle = (
CommentNone,
CommentCurly, // {}
CommentRound, // (* *)
CommentLine // //
);
TCompilerMode = (
cmFPC,
cmDELPHI,
cmDELPHIUNICODE,
cmGPC,
cmTP,
cmOBJFPC,
cmMacPas,
cmISO,
cmExtPas
);
const
// upper case
CompilerModeNames: array[TCompilerMode] of string=(
'FPC',
'DELPHI',
'DELPHIUNICODE',
'GPC',
'TP',
'OBJFPC',
'MACPAS',
'ISO',
'EXTPAS'
);
type
{ TCompilerModeSwitch - see fpc/compiler/globtype.pas tmodeswitch }
TCompilerModeSwitch = (
//cms_FPC,cms_ObjFPC,cms_Delphi,cms_TP7,cms_Mac,cms_ISO,cms_ExtPas,
cmsAdd_pointer, { ? }
cmsClass, { delphi class model }
cmsObjpas, { load objpas unit }
cmsResult, { result in functions }
cmsString_pchar, { pchar 2 string conversion }
cmsCvar_support, { cvar variable directive }
cmsNested_comment, { nested comments }
cmsTp_procvar, { tp style procvars (no @ needed) }
cmsMac_procvar, { macpas style procvars }
cmsRepeat_forward, { repeating forward declarations is needed }
cmsPointer_2_procedure,{ allows the assignement of pointers to procedure variables }
cmsAutoderef, { does auto dereferencing of struct. vars, e.g. a.b -> a^.b }
cmsInitfinal, { initialization/finalization for units }
cmsDefault_ansistring, { ansistring turned on by default }
cmsOut, { support the calling convention OUT }
cmsDefault_para, { support default parameters }
cmsHintdirective, { support hint directives }
cmsDuplicate_names, { allow locals/paras to have duplicate names of globals }
cmsProperty, { allow properties }
cmsDefault_inline, { allow inline proc directive }
cmsExcept, { allow exception-related keywords }
cmsObjectiveC1, { support interfacing with Objective-C (1.0) }
cmsObjectiveC2, { support interfacing with Objective-C (2.0), includes cmsObjectiveC1 }
cmsNestedProcVars, { support nested procedural variables }
cmsNonLocalGoto, { support non local gotos (like iso pascal) }
cmsAdvancedRecords, { advanced record syntax with visibility sections, methods and properties }
cmsISOLike_unary_minus,{ unary minus like in iso pascal: same precedence level as binary minus/plus }
cmsSystemcodepage, { use system codepage as compiler codepage by default, emit ansistrings with system codepage }
cmsFinalFields, { allows declaring fields as "final", which means they must be initialised
in the (class) constructor and are constant from then on (same as final
fields in Java) }
cmsDefault_unicodestring, { makes the default string type in $h+ mode unicodestring rather than
ansistring; similarly, char becomes unicodechar rather than ansichar }
cmsTypeHelpers, { allows the declaration of "type helper" (non-Delphi) or "record helper"
(Delphi) for primitive types }
cmsCBlocks, { support for http://en.wikipedia.org/wiki/Blocks_(C_language_extension) }
cmsISOlike_IO, { I/O as it required by an ISO compatible compiler }
cmsISOLike_Program_Para, { program parameters as it required by an ISO compatible compiler }
cmsISOLike_Mod, { mod operation as it is required by an iso compatible compiler }
cmsArrayOperators, { use Delphi compatible array operators instead of custom ones ("+") }
// not yet in FPC, supported by pas2js:
cmsPrefixedAttributes, { allow Delphi attributes, disable FPC [] proc modifier }
cmsExternalClass, { pas2js: allow class external [pkgname] name [symbol] }
cmsIgnoreAttributes { pas2js: ignore attributes }
);
TCompilerModeSwitches = set of TCompilerModeSwitch;
const
// see fpc/compiler/globals.pp
DefaultCompilerModeSwitches: array[TCompilerMode] of TCompilerModeSwitches = (
// cmFPC
[cmsString_pchar,cmsNested_comment,cmsRepeat_forward,cmsCvar_support,
cmsInitfinal,cmsHintdirective,cmsProperty,cmsDefault_inline,
cmsResult],
// cmDELPHI
[cmsClass,cmsObjpas,cmsResult,cmsString_pchar,
cmsPointer_2_procedure,cmsAutoderef,cmsTp_procvar,cmsInitfinal,cmsDefault_ansistring,
cmsOut,cmsDefault_para,cmsDuplicate_names,cmsHintdirective,
cmsProperty,cmsDefault_inline,cmsExcept,cmsAdvancedRecords,
cmsPrefixedAttributes,cmsArrayOperators],
// cmDELPHIUNICODE
[cmsClass,cmsObjpas,cmsResult,cmsString_pchar,
cmsPointer_2_procedure,cmsAutoderef,cmsTp_procvar,cmsInitfinal,
cmsOut,cmsDefault_para,cmsDuplicate_names,cmsHintdirective,
cmsProperty,cmsDefault_inline,cmsExcept,cmsAdvancedRecords,
cmsSystemcodepage,cmsDefault_unicodestring,
cmsPrefixedAttributes,cmsArrayOperators],
// cmGPC
[cmsTp_procvar],
// cmTP
[cmsResult,cmsTp_procvar,cmsDuplicate_names],
// cmOBJFPC
[cmsClass,cmsObjpas,cmsResult,cmsString_pchar,cmsNested_comment,
cmsRepeat_forward,cmsCvar_support,cmsInitfinal,cmsOut,cmsDefault_para,
cmsHintdirective,cmsProperty,cmsDefault_inline,cmsExcept],
// cmMacPas
[cmsCvar_support,cmsMac_procvar,cmsNestedProcVars,
cmsNonLocalGoto,cmsISOLike_unary_minus,cmsDefault_inline],
// cmISO
[cmsTp_procvar,cmsDuplicate_names,cmsNestedProcVars,cmsNonLocalGoto,
cmsISOLike_unary_minus],
// cmExtPas
[cmsTp_procvar,cmsDuplicate_names,cmsNestedProcVars,cmsNonLocalGoto,
cmsISOLike_unary_minus,cmsISOlike_IO,
cmsISOLike_Program_Para,
cmsISOLike_Mod]
);
cmAllModesWithGeneric = [cmDELPHI,cmDELPHIUNICODE,cmOBJFPC];
// upper case (see fpc/compiler/globtype.pas modeswitchstr )
CompilerModeSwitchNames: array[TCompilerModeSwitch] of string=(
'POINTERARITHMETICS',
'CLASS',
'OBJPAS',
'RESULT',
'PCHARTOSTRING',
'CVAR',
'NESTEDCOMMENTS',
'CLASSICPROCVARS',
'MACPROCVARS',
'REPEATFORWARD',
'POINTERTOPROCVAR',
'AUTODEREF',
'INITFINAL',
'ANSISTRINGS',
'OUT',
'DEFAULTPARAMETERS',
'HINTDIRECTIVE',
'DUPLICATELOCALS',
'PROPERTIES',
'ALLOWINLINE',
'EXCEPTIONS',
'OBJECTIVEC1',
'OBJECTIVEC2',
'NESTEDPROCVARS',
'NONLOCALGOTO',
'ADVANCEDRECORDS',
'ISOUNARYMINUS',
'SYSTEMCODEPAGE',
'FINALFIELDS',
'UNICODESTRINGS',
'TYPEHELPERS',
'CBLOCKS',
'ISOIO',
'ISOPROGRAMPARAS',
'ISOMOD',
'ARRAYOPERATORS',
'PREFIXEDATTRIBUTES',
'EXTERNALCLASS',
'IGNOREATTRIBUTES'
);
type
// see fpcsrc/compiler/globtype.pas toptimizerswitch
TOptimizerSwitch = (
cs_opt_none,
cs_opt_level1,cs_opt_level2,cs_opt_level3,cs_opt_level4,
cs_opt_regvar,cs_opt_uncertain,cs_opt_size,cs_opt_stackframe,
cs_opt_peephole,cs_opt_loopunroll,cs_opt_tailrecursion,cs_opt_nodecse,
cs_opt_nodedfa,cs_opt_loopstrength,cs_opt_scheduler,cs_opt_autoinline,cs_useebp,cs_userbp,
cs_opt_reorder_fields,cs_opt_fastmath,
cs_opt_dead_values,
cs_opt_remove_emtpy_proc,
cs_opt_constant_propagate,
cs_opt_dead_store_eliminate,
cs_opt_forcenostackframe
);
toptimizerswitches = set of toptimizerswitch;
const
OptimizerSwitchStr : array[toptimizerswitch] of string[17] = ('',
'LEVEL1','LEVEL2','LEVEL3','LEVEL4',
'REGVAR','UNCERTAIN','SIZE','STACKFRAME',
'PEEPHOLE','LOOPUNROLL','TAILREC','CSE',
'DFA','STRENGTH','SCHEDULE','AUTOINLINE','USEEBP','USERBP',
'ORDERFIELDS','FASTMATH','DEADVALUES','REMOVEEMPTYPROCS',
'CONSTPROP',
'DEADSTORE','FORCENOSTACKFRAME'
);
type
TPascalCompiler = (
pcFPC,
pcDelphi,
pcPas2js);
const
// upper case
PascalCompilerNames: array[TPascalCompiler] of string=(
'FPC', 'DELPHI', 'PAS2JS'
);
PascalCompilerUnitExt: array[TPascalCompiler] of string = (
'pp;pas;ppu', // + p if TCompilerMode=cmMacPas
'pas;dcu',
'pas;pp;pcu;pju'
);
PascalCompilerSrcExt: array[TPascalCompiler] of string = (
'pp;pas', // + p if TCompilerMode=cmMacPas
'pas',
'pas;pp'
);
type
TLSSkippingDirective = (
lssdNone,
lssdTillElse,
lssdTillEndIf
);
TLSDirectiveKind = (
lsdkNone,
// if
lsdkIf,
lsdkIfC,
lsdkIfDef,
lsdkIfNDef,
lsdkIfOpt,
// else
lsdkElIfC,
lsdkElse,
lsdkElseC,
lsdkElseIf,
// end
lsdkEndC,
lsdkEndif,
lsdkIfEnd,
// misc
lsdkDefine,
lsdkInclude,
lsdkIncludePath,
lsdkLongSwitch,
lsdkMacro,
lsdkMode,
lsdkModeSwitch,
lsdkSetC,
lsdkShortSwitch,
lsdkThreading,
lsdkUndef
);
TLSDirectiveKinds = set of TLSDirectiveKind;
const
lsdkAllIf = [lsdkIf,lsdkIfC,lsdkIfDef,lsdkIfNDef,lsdkIfOpt];
lsdkAllElse = [lsdkElIfC,lsdkElse,lsdkElseC,lsdkElseIf];
lsdkAllEnd = [lsdkEndC,lsdkEndif,lsdkIfEnd];
type
TLSDirectiveState = (
lsdsActive, // was executed
lsdsInactive,// was executed, but expression result was false and following code was skipped
lsdsSkipped // was not executed
);
TLSDirectiveStates = set of TLSDirectiveState;
TLSDirective = record
CleanPos: integer;
Level: integer;
State: TLSDirectiveState;
Code: Pointer; // TCodeBuffer
SrcPos: integer; // 1-based position in Code
Kind: TLSDirectiveKind;
end;
PLSDirective = ^TLSDirective;
PPLSDirective = ^PLSDirective;
type
{ TMissingIncludeFile is a missing include file together with all
params involved in the search }
TMissingIncludeFile = class
public
IncludePath: string;
Filename: string;
constructor Create(const AFilename, AIncludePath: string);
function CalcMemSize: PtrUInt;
end;
{ TMissingIncludeFiles is a list of TMissingIncludeFile }
TMissingIncludeFiles = class(TList)
private
function GetIncFile(Index: Integer): TMissingIncludeFile;
procedure SetIncFile(Index: Integer; const AValue: TMissingIncludeFile);
public
procedure Clear; override;
procedure Delete(Index: Integer);
function CalcMemSize: PtrUInt;
property Items[Index: Integer]: TMissingIncludeFile
read GetIncFile write SetIncFile; default;
end;
TDirectiveSequenceItemValue = record
CleanPos: integer;
Value: string;
end;
TSequenceDirective = (sdScopedEnums);
TDirectiveSequenceItem = class
private
FItems: array of TDirectiveSequenceItemValue;
FLastItem: integer;
public
constructor Create;
procedure Add(const AValue: string; ACleanPos: integer);
function FindValue(const ACleanPos: integer; out Value: string): Boolean;
procedure Clear(FreeMemory: boolean);
function CalcMemSize: PtrUInt;
end;
TDirectiveSequence = class
private
FDirectives: array[TSequenceDirective] of TDirectiveSequenceItem;
public
constructor Create;
destructor Destroy; override;
procedure Add(ADirective: TSequenceDirective; const ADirectiveValue: string;
ACleanPos: Integer);
function FindValue(ADirective: TSequenceDirective;
ACleanPos: Integer; out Value: string): Boolean;
procedure Clear(FreeMemory: boolean);
function CalcMemSize: PtrUInt;
end;
{ LinkScanner Token Types }
TLSTokenType = (
lsttNone,
lsttSrcEnd, // no more tokens
lsttWord,
lsttEqual,
lsttPoint,
lsttSemicolon,
lsttComma,
lsttStringConstant,
lsttEnd
);
{ Error handling }
{ ELinkScannerError }
ELinkScannerError = class(Exception)
Sender: TLinkScanner;
Id: int64;
constructor Create(ASender: TLinkScanner; TheId: int64; const AMessage: string);
end;
ELinkScannerErrors = class of ELinkScannerError;
TLinkScannerProgress = function(Sender: TLinkScanner): boolean of object;
ELinkScannerAbort = class(ELinkScannerError);
ELinkScannerConsistency = class(ELinkScannerError);
{ ELinkScannerEditError }
ELinkScannerEditError = class(ELinkScannerError)
Buffer: Pointer;
BufferPos: integer;
constructor Create(ASender: TLinkScanner; TheId: int64; const AMessage: string;
ABuffer: Pointer; ABufferPos: integer);
end;
TLinkScannerState = (
lssSourcesChanged, // used source buffers changed
lssInitValuesChanged, // used init values changed
lssFilesChanged, // used files on disk changed
lssIgnoreMissingIncludeFiles
);
TLinkScannerStates = set of TLinkScannerState;
{ TLinkScanner }
TLinkScanner = class(TObject)
private
FLinks: PSourceLink; // list of TSourceLink, sorted for CleanedPos
FLinkCount: integer;
FLinkCapacity: integer;
FCleanedSrc: string;
FLastCleanedSrcLen: integer;
FOnGetSource: TOnGetSource;
FOnGetFileName: TOnGetFileName;
FOnGetSourceStatus: TOnGetSourceStatus;
FOnLoadSource: TOnLoadSource;
FOnDeleteSource: TOnDeleteSource;
FOnCheckFileOnDisk: TOnCheckFileOnDisk;
FOnGetInitValues: TOnGetInitValues;
FOnIncludeCode: TOnIncludeCode;
FOnProgress: TLinkScannerProgress;
FIgnoreErrorAfterCode: Pointer;
FIgnoreErrorAfterCursorPos: integer;
FInitValues: TExpressionEvaluator;
FInitValuesChangeStep: integer;
FSourceChangeSteps: TFPList; // list of PSourceChangeStep sorted with Code
FChangeStep: integer;
FMainSourceFilename: string;
FMainCode: pointer;
FScanTill: TLinkScannerRange;
FNestedComments: boolean; // for speed reasons keep this flag redundant with the CompilerModeSwitches
FStates: TLinkScannerStates;
FHiddenUsedUnits: string; // comma separated
// global write lock
FOnSetGlobalWriteLock: TOnSetWriteLock;
FGlobalSourcesChangeStep: int64;
FGlobalFilesChangeStep: int64;
FGlobalInitValuesChangeStep: integer;
function GetLinks(Index: integer): TSourceLink; inline;
function GetLinkP(Index: integer): PSourceLink; inline;
procedure SetLinks(Index: integer; const Value: TSourceLink);
procedure SetSource(ACode: Pointer); // set current source
procedure AddSourceChangeStep(ACode: pointer; AChangeStep: integer);
procedure AddLink(ASrcPos: integer; ACode: Pointer;
AKind: TSourceLinkKind = slkCode);
procedure IncreaseChangeStep; inline;
procedure SetMainCode(const Value: pointer);
procedure SetScanTill(const Value: TLinkScannerRange);
function GetIgnoreMissingIncludeFiles: boolean;
procedure SetIgnoreMissingIncludeFiles(const Value: boolean);
function TokenIs(const AToken: string): boolean;
function UpTokenIs(const AToken: string): boolean;
private
// parsing
CommentStyle: TCommentStyle;
CommentLevel: integer;
CommentStartPos: integer; // position of '{', '(*', '//'
CommentInnerStartPos: integer; // position after '{', '(*', '//'
CommentInnerEndPos: integer; // position of '}', '*)', #10
CommentEndPos: integer; // postion after '}', '*)', #10
CopiedSrcPos: integer;
IfLevel: integer;
procedure ReadNextToken;
function ReturnFromIncludeFileAndIsEnd: boolean;
function ReadIdentifier: string;
function ReadUpperIdentifier: string;
procedure ReadSpace; inline;
procedure ReadCurlyComment;
procedure ReadLineComment;
procedure ReadRoundComment;
procedure CommentEndNotFound(id: int64);
procedure EndComment; inline;
procedure IncCommentLevel; inline;
procedure DecCommentLevel; inline;
procedure HandleDirective;
procedure UpdateCleanedSource(NewCopiedSrcPos: integer);
function ReturnFromIncludeFile: boolean;
function ParseKeyWord(StartPos: integer; LastTokenType: TLSTokenType): boolean;
function DoEndToken: boolean; inline;
function DoSourceTypeToken: boolean; inline;
function DoInterfaceToken: boolean; inline;
function DoImplementationToken: boolean; inline;
function DoFinalizationToken: boolean; inline;
function DoInitializationToken: boolean; inline;
function DoUsesToken: boolean; inline;
function TokenIsWord(p: PChar): boolean; inline;
private
// directives
FDirectives: PLSDirective;
FDirectivesCount: integer;
FDirectivesCapacity: integer;
FDirectivesSorted: PPLSDirective; // array of PLSDirective to items of FDirectives
FDirectiveName: string;
FDirectiveCleanPos: integer;
FDirectivesStored: boolean;
FMacrosOn: boolean;
FMissingIncludeFiles: TMissingIncludeFiles;
FIncludeStack: TFPList; // list of TSourceLink
FOnGetGlobalChangeSteps: TLSOnGetGlobalChangeSteps;
FSkippingDirectives: TLSSkippingDirective;
FSkipIfLevel: integer;
FStoreDirectives: integer;
FCompilerMode: TCompilerMode;
FCompilerModeSwitches: TCompilerModeSwitches;
FPascalCompiler: TPascalCompiler;
FMacros: PSourceLinkMacro;
FMacroCount, fMacroCapacity: integer;
FDirectiveSequence: TDirectiveSequence;
function GetDirectives(Index: integer): PLSDirective; inline;
function GetDirectivesSorted(Index: integer): PLSDirective; inline;
procedure SetCompilerMode(const AValue: TCompilerMode);
procedure SetPascalCompiler(const AValue: TPascalCompiler);
procedure SkipTillEndifElse(SkippingUntil: TLSSkippingDirective);
procedure SortDirectives;
function InternalIfDirective: boolean;
procedure EndSkipping;
procedure AddSkipComment(IsStart: boolean);
procedure SetDirectiveValueWithSequence(ADirective: TSequenceDirective;
const ADirectiveValue: string);
function IfdefDirective: boolean;
function IfCDirective: boolean;
function IfndefDirective: boolean;
function IfDirective: boolean;
function IfOptDirective: boolean;
function EndifDirective: boolean;
function EndCDirective: boolean;
function IfEndDirective: boolean;
function ElseDirective: boolean;
function ElseCDirective: boolean;
function ElseIfDirective: boolean;
function ElIfCDirective: boolean;
function DefineDirective: boolean;
function UndefDirective: boolean;
function SetCDirective: boolean;
function IncludeDirective: boolean;
function IncludePathDirective: boolean;
function ShortSwitchDirective: boolean;
function ReadNextSwitchDirective: boolean;
function LongSwitchDirective: boolean;
function LongSwitchDirectiveWithSequence(const ADirective: TSequenceDirective): boolean;
function MacroDirective: boolean;
function ModeDirective: boolean;
function ModeSwitchDirective: boolean;
function ThreadingDirective: boolean;
function DoDirective(StartPos, DirLen: integer): boolean;
function IncludeFile(const AFilename: string): boolean;
procedure PushIncludeLink(ACleanedPos, ASrcPos: integer; ACode: Pointer);
function PopIncludeLink: TSourceLink;
function GetIncludeFileIsMissing: boolean;
function MissingIncludeFilesNeedsUpdate: boolean;
procedure ClearMissingIncludeFiles;
// code macros
procedure AddMacroValue(MacroName: PChar; ValueStart, ValueEnd: integer);
procedure ClearMacros;
function IndexOfMacro(MacroName: PChar; InsertPos: boolean): integer;
procedure AddMacroSource(MacroID: integer);
protected
// error: the error is in range Succ(ScannedRange)
LastErrorMessage: string;
LastErrorSrcPos: integer;
LastErrorCode: pointer;
LastErrorIsValid: boolean;
LastErrorBehindIgnorePosition: boolean;
LastErrorCheckedForIgnored: boolean;
LastErrorId: int64;
CleanedIgnoreErrorAfterPosition: integer;// ignore if valid and >=
procedure RaiseExceptionFmt(id: int64; const AMessage: string; const Args: array of const);
procedure RaiseException(id: int64; const AMessage: string);
procedure RaiseExceptionClass(id: int64; const AMessage: string;
ExceptionClass: ELinkScannerErrors);
procedure RaiseEditException(id: int64; const AMessage: string; ABuffer: Pointer;
ABufferPos: integer);
procedure RaiseConsistencyException(id: int64; const AMessage: string);
procedure ClearLastError;
procedure RaiseLastError;
procedure DoCheckAbort;
public
// current values, positions, source, flags
CleanedLen: integer;
Src: string; // current parsed source (= TCodeBuffer(Code).Source)
SrcPos: integer; // current position (1-based in Src)
TokenStart: integer; // start position of current token
TokenType: TLSTokenType;
SrcLen: integer; // length of current source
Code: pointer; // current code object (TCodeBuffer)
Values: TExpressionEvaluator;
SrcFilename: string;// current parsed filename (= TCodeBuffer(Code).Filename)
IsUnit: boolean;
SourceName: string;
ScannedRange: TLinkScannerRange; // excluding the section with a syntax error
function MainFilename: string;
property ChangeStep: integer read FChangeStep; // see CTInvalidChangeStamp
// links
property Links[Index: integer]: TSourceLink read GetLinks write SetLinks;
property LinkP[Index: integer]: PSourceLink read GetLinkP;
property LinkCount: integer read FLinkCount;
function LinkIndexAtCleanPos(ACleanPos: integer): integer;
function LinkIndexAtCursorPos(ACursorPos: integer; ACode: Pointer): integer;
function LinkSize(Index: integer): integer;
function LinkSize_Inline(Index: integer): integer; inline;
function LinkCleanedEndPos(Index: integer): integer;
function LinkCleanedEndPos_Inline(Index: integer): integer; inline;
function LinkSourceLog(Index: integer): TSourceLog;
function FindFirstSiblingLink(LinkIndex: integer): integer;
function FindParentLink(LinkIndex: integer): integer;
function LinkIndexNearCursorPos(ACursorPos: integer; ACode: Pointer;
var CursorInLink: boolean): integer;
function CreateTreeOfSourceCodes: TAVLTree;
// directives
property Directives[Index: integer]: PLSDirective read GetDirectives;
property DirectivesSorted[Index: integer]: PLSDirective read GetDirectivesSorted; // sorted for Code and SrcPos
property DirectiveCount: integer read FDirectivesCount;
procedure ClearDirectives(FreeMemory: boolean);
function StoreDirectives: boolean; inline; // store directives on next Scan
procedure DemandStoreDirectives; // increase internal counter to StoreDirectives
procedure ReleaseStoreDirectives; // decrease internal counter to StoreDirectives
property DirectivesStored: boolean read FDirectivesStored; // directives were stored on last scan
function FindDirective(aCode: Pointer; aSrcPos: integer;
out FirstSortedIndex, LastSortedIndex: integer): boolean;
function FindFirstDirective(aCode: Pointer; aSrcPos: integer;
const AllowedStates: TLSDirectiveStates): PLSDirective;
function GetDirectiveValueAt(ADirective: TSequenceDirective; ACleanPos: integer): string;
// source mapping (Cleaned <-> Original)
function CleanedSrc: string;
function CursorToCleanPos(ACursorPos: integer; ACode: pointer;
out ACleanPos: integer): integer; // 0=valid CleanPos
//-1=CursorPos was skipped, CleanPos between two links
// 1=CursorPos beyond scanned code
function CleanedPosToCursor(ACleanedPos: integer; out ACursorPos: integer;
out ACode: Pointer): boolean;
function CleanedPosToStr(ACleanedPos: integer): string;
function LastErrorIsInFrontOfCleanedPos(ACleanedPos: integer): boolean;
procedure RaiseLastErrorIfInFrontOfCleanedPos(ACleanedPos: integer);
// ranges
function WholeRangeIsWritable(CleanStartPos, CleanEndPos: integer;
ErrorOnFail: boolean): boolean;
procedure FindCodeInRange(CleanStartPos, CleanEndPos: integer;
UniqueSortedCodeList: TFPList);
procedure DeleteRange(CleanStartPos,CleanEndPos: integer);
// scanning
procedure Scan(Range: TLinkScannerRange; CheckFilesOnDisk: boolean);
function UpdateNeeded(Range: TLinkScannerRange;
CheckFilesOnDisk: boolean): boolean;
procedure SetIgnoreErrorAfter(ACursorPos: integer; ACode: Pointer);
procedure ClearIgnoreErrorAfter;
function IgnoreErrAfterPositionIsInFrontOfLastErrMessage: boolean;
function IgnoreErrorAfterCleanedPos: integer;// before using this, check if valid!
function IgnoreErrorAfterValid: boolean;
function CleanPosIsAfterIgnorePos(CleanPos: integer): boolean;
function LoadSourceCaseLoUp(const AFilename: string; AllowVirtual: boolean = false): pointer;
function SearchIncludeFile(AFilename: string; out NewCode: Pointer;
var MissingIncludeFile: TMissingIncludeFile): boolean;
function GuessMisplacedIfdefEndif(StartCursorPos: integer;
StartCode: pointer;
out EndCursorPos: integer;
out EndCode: Pointer): boolean;
function GetHiddenUsedUnits: string; // comma separated
// global write lock
procedure ActivateGlobalWriteLock;
procedure DeactivateGlobalWriteLock;
property OnGetGlobalChangeSteps: TLSOnGetGlobalChangeSteps
read FOnGetGlobalChangeSteps write FOnGetGlobalChangeSteps;
property OnSetGlobalWriteLock: TOnSetWriteLock
read FOnSetGlobalWriteLock write FOnSetGlobalWriteLock;
// properties
property OnGetSource: TOnGetSource read FOnGetSource write FOnGetSource;
property OnLoadSource: TOnLoadSource read FOnLoadSource write FOnLoadSource;
property OnDeleteSource: TOnDeleteSource read FOnDeleteSource write FOnDeleteSource;
property OnGetSourceStatus: TOnGetSourceStatus
read FOnGetSourceStatus write FOnGetSourceStatus;
property OnGetFileName: TOnGetFileName read FOnGetFileName write FOnGetFileName;
property OnCheckFileOnDisk: TOnCheckFileOnDisk
read FOnCheckFileOnDisk write FOnCheckFileOnDisk;
property OnGetInitValues: TOnGetInitValues
read FOnGetInitValues write FOnGetInitValues;
property OnIncludeCode: TOnIncludeCode read FOnIncludeCode write FOnIncludeCode;
property OnProgress: TLinkScannerProgress read FOnProgress write FOnProgress;
property IgnoreMissingIncludeFiles: boolean read GetIgnoreMissingIncludeFiles
write SetIgnoreMissingIncludeFiles;
property InitialValues: TExpressionEvaluator read FInitValues write FInitValues;
property MainCode: pointer read FMainCode write SetMainCode;
property IncludeFileIsMissing: boolean read GetIncludeFileIsMissing;
property NestedComments: boolean read FNestedComments;
property CompilerMode: TCompilerMode read FCompilerMode write SetCompilerMode;
property CompilerModeSwitches: TCompilerModeSwitches
read FCompilerModeSwitches write FCompilerModeSwitches;
property PascalCompiler: TPascalCompiler read FPascalCompiler write SetPascalCompiler;
property ScanTill: TLinkScannerRange read FScanTill write SetScanTill;
procedure Clear;
procedure ConsistencyCheck;
procedure WriteDebugReport;
procedure CalcMemSize(Stats: TCTMemStats);
constructor Create;
destructor Destroy; override;
end;
//----------------------------------------------------------------------------
// memory system for PSourceLink(s)
TPSourceLinkMemManager = class(TCodeToolMemManager)
protected
procedure FreeFirstItem; override;
public
procedure DisposePSourceLink(Link: PSourceLink);
function NewPSourceLink: PSourceLink;
end;
// memory system for PSourceLink(s)
TPSourceChangeStepMemManager = class(TCodeToolMemManager)
protected
procedure FreeFirstItem; override;
public
procedure DisposePSourceChangeStep(Step: PSourceChangeStep);
function NewPSourceChangeStep: PSourceChangeStep;
end;
const
DirectiveSequenceName: array [TSequenceDirective] of string =
('SCOPEDENUMS');
var
CompilerModeVars: array[TCompilerMode] of string;
PSourceLinkMemManager: TPSourceLinkMemManager;
PSourceChangeStepMemManager: TPSourceChangeStepMemManager;
function StrToCompilerMode(const aName: string): TCompilerMode;
function StrToPascalCompiler(const aName: string): TPascalCompiler;
procedure AddCodeToUniqueList(ACode: Pointer; UniqueSortedCodeList: TFPList);
function IndexOfCodeInUniqueList(ACode: Pointer;
UniqueSortedCodeList: TList): integer;
function IndexOfCodeInUniqueList(ACode: Pointer;
UniqueSortedCodeList: TFPList): integer;
function dbgs(r: TLinkScannerRange): string; overload;
function dbgs(const ModeSwitches: TCompilerModeSwitches): string; overload;
function dbgs(k: TSourceLinkKind): string; overload;
function dbgs(s: TLSDirectiveState): string; overload;
function dbgs(s: TLSDirectiveKind): string; overload;
implementation
// useful procs ----------------------------------------------------------------
function IndexOfCodeInUniqueList(ACode: Pointer;
UniqueSortedCodeList: TList): integer;
var l,m,r: integer;
begin
l:=0;
r:=UniqueSortedCodeList.Count-1;
m:=0;
while r>=l do begin
m:=(l+r) shr 1;
if ACode<UniqueSortedCodeList[m] then
r:=m-1
else if ACode>UniqueSortedCodeList[m] then
l:=m+1
else begin
Result:=m;
exit;
end;
end;
Result:=-1;
end;
function IndexOfCodeInUniqueList(ACode: Pointer;
UniqueSortedCodeList: TFPList): integer;
var l,m,r: integer;
begin
l:=0;
r:=UniqueSortedCodeList.Count-1;
m:=0;
while r>=l do begin
m:=(l+r) shr 1;
if ACode<UniqueSortedCodeList[m] then
r:=m-1
else if ACode>UniqueSortedCodeList[m] then
l:=m+1
else begin
Result:=m;
exit;
end;
end;
Result:=-1;
end;
function dbgs(r: TLinkScannerRange): string; overload;
begin
WriteStr(Result, r);
end;
function dbgs(const ModeSwitches: TCompilerModeSwitches): string;
var
ms: TCompilerModeSwitch;
begin
Result:='';
for ms:=Low(TCompilerModeSwitches) to high(TCompilerModeSwitches) do
if ms in ModeSwitches then begin
Result:=Result+CompilerModeSwitchNames[ms]+',';
end;
System.Delete(Result,length(Result),1); // cut comma
Result:='['+Result+']';
end;
function dbgs(k: TSourceLinkKind): string;
begin
case k of
slkCode: Result:='Code';
slkMissingIncludeFile: Result:='MissingInc';
slkSkipStart: Result:='SkipStart';
slkSkipEnd: Result:='SkipEnd';
else Result:='?';
end;
end;
function dbgs(s: TLSDirectiveState): string;
begin
case s of
lsdsActive: Result:='Active';
lsdsInactive: Result:='Inactive';
lsdsSkipped: Result:='Skipped';
end;
end;
function dbgs(s: TLSDirectiveKind): string;
begin
WriteStr(Result,s);
end;
function StrToCompilerMode(const aName: string): TCompilerMode;
begin
for Result:=low(Result) to high(Result) do
if SysUtils.CompareText(aName,CompilerModeNames[Result])=0 then
exit;
Result:=cmFPC;
end;
function StrToPascalCompiler(const aName: string): TPascalCompiler;
begin
for Result:=low(Result) to high(Result) do
if SysUtils.CompareText(aName,PascalCompilerNames[Result])=0 then
exit;
Result:=pcFPC;
end;
procedure AddCodeToUniqueList(ACode: Pointer; UniqueSortedCodeList: TFPList);
var l,m,r: integer;
begin
l:=0;
r:=UniqueSortedCodeList.Count-1;
m:=0;
while r>=l do begin
m:=(l+r) shr 1;
if ACode<UniqueSortedCodeList[m] then
r:=m-1
else if ACode>UniqueSortedCodeList[m] then
l:=m+1
else
exit;
end;
if (m<UniqueSortedCodeList.Count) and (ACode>UniqueSortedCodeList[m]) then
inc(m);
UniqueSortedCodeList.Insert(m,ACode);
end;
function CompareUpToken(const UpToken: string; const Txt: string;
TxtStartPos, TxtEndPos: integer): boolean;
var len, i: integer;
begin
Result:=false;
len:=TxtEndPos-TxtStartPos;
if len<>length(UpToken) then exit;
i:=1;
while i<len do begin
if (UpToken[i]<>UpChars[Txt[TxtStartPos]]) then exit;
inc(i);
inc(TxtStartPos);
end;
Result:=true;
end;
function CompareLSDirectiveCodeSrcPos(Item1, Item2: Pointer): Integer;
var
Dir1: PLSDirective absolute Item1;
Dir2: PLSDirective absolute Item2;
begin
Result:=ComparePointers(Dir1^.Code,Dir2^.Code);
if Result<>0 then exit;
Result:=Dir1^.SrcPos-Dir2^.SrcPos;
end;
function CompareLSDirectiveCodeSrcPosCleanPos(Item1, Item2: Pointer): Integer;
var
Dir1: PLSDirective absolute Item1;
Dir2: PLSDirective absolute Item2;
begin
Result:=ComparePointers(Dir1^.Code,Dir2^.Code);
if Result<>0 then exit;
Result:=Dir1^.SrcPos-Dir2^.SrcPos;
if Result<>0 then exit;
Result:=Dir1^.CleanPos-Dir2^.CleanPos;
end;
{ TDirectiveSequenceItem }
constructor TDirectiveSequenceItem.Create;
begin
FLastItem := -1;
end;
procedure TDirectiveSequenceItem.Add(const AValue: string; ACleanPos: integer);
begin
if (FLastItem >= 0) and (ACleanPos <= FItems[FLastItem].CleanPos) then
raise Exception.Create('Internal error: TDirectiveSequenceItem.Add: ACleanPos not sorted.');
if Length(FItems) = 0 then
SetLength(FItems, 1)
else if FLastItem = High(FItems) then
SetLength(FItems, Length(FItems)+Min(128, Length(FItems)));
Inc(FLastItem);
FItems[FLastItem].CleanPos := ACleanPos;
FItems[FLastItem].Value := AValue;
end;
function TDirectiveSequenceItem.CalcMemSize: PtrUInt;
var
Item: TDirectiveSequenceItemValue;
begin
Result:=PtrUInt(InstanceSize)
+PtrUInt(Length(FItems))*PtrUInt(SizeOf(TDirectiveSequenceItemValue));
for Item in FItems do
Inc(Result, MemSizeString(Item.Value));
end;
procedure TDirectiveSequenceItem.Clear(FreeMemory: boolean);
begin
if FreeMemory then
SetLength(FItems, 0);
FLastItem := -1;
end;
function TDirectiveSequenceItem.FindValue(const ACleanPos: integer; out
Value: string): Boolean;
function BinarySearch: integer;
var
I, Max, Min: Integer;
ResIndex, ResCleanPos: integer;
begin
Max := FLastItem;
Min := 0;
ResIndex := -1;
ResCleanPos := -1;
while (Min <= Max) do
begin
I := (Max+Min) div 2;
if (FItems[I].CleanPos = ACleanPos) then
Exit(I)
else
if (FItems[I].CleanPos < ACleanPos) then
begin
if ResCleanPos < FItems[I].CleanPos then
begin
//store the closest
ResIndex := I;
ResCleanPos := FItems[I].CleanPos;
end;
Min := I + 1;
end else
begin
Max := I - 1;
end;
end;
Result := ResIndex;
end;
var
ItemIndex: integer;
begin
ItemIndex := BinarySearch;
Result := ItemIndex >= 0;
if Result then
Value := FItems[ItemIndex].Value
else
Value := '';
end;
{ TDirectiveSequence }
constructor TDirectiveSequence.Create;
var
I: TSequenceDirective;
begin
for I := Low(FDirectives) to High(FDirectives) do
FDirectives[I] := TDirectiveSequenceItem.Create;
end;
procedure TDirectiveSequence.Add(ADirective: TSequenceDirective;
const ADirectiveValue: string; ACleanPos: Integer);
begin
FDirectives[ADirective].Add(ADirectiveValue, ACleanPos);
end;
function TDirectiveSequence.CalcMemSize: PtrUInt;
var
Item: TDirectiveSequenceItem;
begin
Result:=PtrUInt(InstanceSize);
for Item in FDirectives do
Inc(Result, Item.CalcMemSize);
end;
procedure TDirectiveSequence.Clear(FreeMemory: boolean);
var
Item: TDirectiveSequenceItem;
begin
for Item in FDirectives do
Item.Clear(FreeMemory);
end;
destructor TDirectiveSequence.Destroy;
var
Item: TDirectiveSequenceItem;
begin
for Item in FDirectives do
Item.Free;
inherited Destroy;
end;
function TDirectiveSequence.FindValue(ADirective: TSequenceDirective;
ACleanPos: Integer; out Value: string): Boolean;
begin
Result := FDirectives[ADirective].FindValue(ACleanPos, Value);
end;
{ TLinkScanner }
// inline
function TLinkScanner.GetLinks(Index: integer): TSourceLink;
begin
Result:=FLinks[Index];
end;
// inline
function TLinkScanner.GetLinkP(Index: integer): PSourceLink;
begin
Result:=@FLinks[Index];
end;
// inline
procedure TLinkScanner.IncreaseChangeStep;
begin
if FChangeStep=$7fffffff then FChangeStep:=-$7fffffff
else inc(FChangeStep);
end;
// inline
procedure TLinkScanner.ReadSpace;
begin
while (SrcPos<=SrcLen) and (IsSpaceChar[Src[SrcPos]]) do inc(SrcPos);
end;
// inline
procedure TLinkScanner.EndComment;
begin
CommentStyle:=CommentNone;
end;
// inline
procedure TLinkScanner.IncCommentLevel;
begin
if FNestedComments then inc(CommentLevel)
else CommentLevel:=1;
end;
// inline
procedure TLinkScanner.DecCommentLevel;
begin
if FNestedComments then dec(CommentLevel)
else CommentLevel:=0;
end;
// inline
function TLinkScanner.DoEndToken: boolean;
begin
TokenType:=lsttEnd;
Result:=true;
end;
// inline
function TLinkScanner.DoSourceTypeToken: boolean;
// program, unit, library, package
// unit unit1;
// unit a.b.unit1 platform;
// unit unit1 unimplemented;
begin
if ScannedRange<>lsrInit then exit(false);
Result:=true;
ScannedRange:=lsrSourceType;
IsUnit:=TokenIsWord('UNIT');
if ScannedRange=ScanTill then exit;
repeat
ReadNextToken; // read identifier
if TokenType=lsttWord then begin
if SourceName<>'' then
SourceName:=SourceName+'.';
SourceName:=SourceName+GetIdentifier(@Src[TokenStart]);
ReadNextToken; // read ';' or '.' or hint modifier
end;
until TokenType<>lsttPoint;
ScannedRange:=lsrSourceName;
if ScannedRange=ScanTill then exit;
end;
// inline
function TLinkScanner.DoInterfaceToken: boolean;
begin
if ord(ScannedRange)>=ord(lsrInterfaceStart) then exit(false);
ScannedRange:=lsrInterfaceStart;
Result:=true;
end;
// inline
function TLinkScanner.DoFinalizationToken: boolean;
begin
if ord(ScannedRange)>=ord(lsrFinalizationStart) then exit(false);
ScannedRange:=lsrFinalizationStart;
Result:=true;
end;
// inline
function TLinkScanner.DoInitializationToken: boolean;
begin
if ord(ScannedRange)>=ord(lsrInitializationStart) then exit(false);
ScannedRange:=lsrInitializationStart;
Result:=true;
end;
function TLinkScanner.DoUsesToken: boolean;
// uses name, name in 'string';
begin
if ord(ScannedRange)<=ord(lsrInterfaceStart) then
ScannedRange:=lsrMainUsesSectionStart
else if ScannedRange=lsrImplementationStart then
ScannedRange:=lsrImplementationUsesSectionStart
else
exit(false);
repeat
// read unit name
repeat
ReadNextToken;
if (TokenType<>lsttWord)
or WordIsKeyWord.DoItCaseInsensitive(@Src[SrcPos]) then exit(false);
ReadNextToken;
until TokenType<>lsttPoint;
if TokenIs('in') then begin
// read "in" filename
ReadNextToken;
if TokenType=lsttStringConstant then
ReadNextToken;
end;
if TokenType=lsttSemicolon then break;
if TokenType<>lsttComma then begin
// syntax error -> this token does not belong to the uses section
SrcPos:=TokenStart;
break;
end;
until false;
ScannedRange:=succ(ScannedRange); // lsrMainUsesSectionEnd, lsrImplementationUsesSectionEnd;
Result:=true;
end;
// inline
function TLinkScanner.DoImplementationToken: boolean;
begin
if ord(ScannedRange)>=ord(lsrImplementationStart) then exit(false);
ScannedRange:=lsrImplementationStart;
Result:=true;
end;
// inline
function TLinkScanner.TokenIsWord(p: PChar): boolean;
begin
Result:=(TokenType=lsttWord) and (CompareIdentifiers(p,@Src[TokenStart])=0);
end;
// inline
function TLinkScanner.GetDirectives(Index: integer): PLSDirective;
begin
Result:=@FDirectives[Index];
end;
// inline
function TLinkScanner.GetDirectivesSorted(Index: integer): PLSDirective;
begin
Result:=FDirectivesSorted[Index];
end;
function TLinkScanner.GetDirectiveValueAt(ADirective: TSequenceDirective;
ACleanPos: integer): string;
begin
if not FDirectiveSequence.FindValue(ADirective, ACleanPos, Result) then
Result := FInitValues.Variables[DirectiveSequenceName[ADirective]];
end;
// inline
function TLinkScanner.LinkSize_Inline(Index: integer): integer;
var
Link: PSourceLink;
begin
Link:=@FLinks[Index];
if Index+1<LinkCount then
Result:=Link[1].CleanedPos-Link^.CleanedPos
else
Result:=CleanedLen-Link^.CleanedPos+1;
end;
// inline
function TLinkScanner.LinkCleanedEndPos_Inline(Index: integer): integer;
var
Link: PSourceLink;
begin
Link:=@FLinks[Index];
if Index+1<LinkCount then
Result:=Link[1].CleanedPos
else
Result:=CleanedLen+1;
end;
// inline
function TLinkScanner.StoreDirectives: boolean;
begin
Result:=FStoreDirectives>0;
end;
procedure TLinkScanner.SortDirectives;
var
i: Integer;
begin
// try to keep memory allocated
ReAllocMem(FDirectivesSorted,SizeOf(Pointer)*FDirectivesCapacity);
for i:=0 to FDirectivesCount-1 do
FDirectivesSorted[i]:=@FDirectives[i];
for i:=FDirectivesCount to FDirectivesCapacity-1 do
FDirectivesSorted[i]:=nil;
MergeSortWithLen(PPointer(FDirectivesSorted),FDirectivesCount,
@CompareLSDirectiveCodeSrcPosCleanPos);
end;
procedure TLinkScanner.AddLink(ASrcPos: integer; ACode: Pointer;
AKind: TSourceLinkKind);
var
NewCapacity: Integer;
Link: PSourceLink;
begin
if (LinkCount>0) and (FLinks[FLinkCount-1].CleanedPos=CleanedLen+1) then begin
// last link is empty => remove
{$IFDEF ShowUpdateCleanedSrc}
Link:=@FLinks[FLinkCount-1];
debugln(['TLinkScanner.AddLink removing empty link: ',dbgs(Link^.Kind)]);
{$ENDIF}
dec(FLinkCount);
end else if FLinkCount=FLinkCapacity then begin
NewCapacity:=FLinkCapacity*2;
if NewCapacity<16 then NewCapacity:=16;
ReAllocMem(FLinks,NewCapacity*SizeOf(TSourceLink));
FLinkCapacity:=NewCapacity;
end;
Link:=@FLinks[FLinkCount];
with Link^ do begin
CleanedPos:=CleanedLen+1;
SrcPos:=ASrcPos;
Code:=ACode;
Kind:=AKind;
end;
inc(FLinkCount);
end;
function TLinkScanner.CleanedSrc: string;
begin
if length(FCleanedSrc)<>CleanedLen then begin
SetLength(FCleanedSrc,CleanedLen);
end;
Result:=FCleanedSrc;
if FLastCleanedSrcLen<CleanedLen then FLastCleanedSrcLen:=CleanedLen;
end;
procedure TLinkScanner.Clear;
var i: integer;
PLink: PSourceLink;
PStamp: PSourceChangeStep;
begin
IsUnit:=false;
SourceName:='';
FHiddenUsedUnits:='';
ClearMacros;
ClearLastError;
ClearDirectives(false);
ClearMissingIncludeFiles;
for i:=0 to FIncludeStack.Count-1 do begin
PLink:=PSourceLink(FIncludeStack[i]);
PSourceLinkMemManager.DisposePSourceLink(PLink);
end;
FIncludeStack.Clear;
FLinkCount:=0;
FCleanedSrc:='';
for i:=0 to FSourceChangeSteps.Count-1 do begin
PStamp:=PSourceChangeStep(FSourceChangeSteps[i]);
PSourceChangeStepMemManager.DisposePSourceChangeStep(PStamp);
end;
FSourceChangeSteps.Clear;
IncreaseChangeStep;
end;
constructor TLinkScanner.Create;
begin
inherited Create;
FInitValues:=TExpressionEvaluator.Create;
Values:=TExpressionEvaluator.Create;
FDirectiveSequence:=TDirectiveSequence.Create;
IncreaseChangeStep;
FSourceChangeSteps:=TFPList.Create;
FMainCode:=nil;
FMainSourceFilename:='';
FIncludeStack:=TFPList.Create;
FPascalCompiler:=pcFPC;
FCompilerMode:=cmFPC;
FCompilerModeSwitches:=DefaultCompilerModeSwitches[CompilerMode];
FNestedComments:=cmsNested_comment in CompilerModeSwitches;
end;
destructor TLinkScanner.Destroy;
begin
Clear;
ClearDirectives(true);
ReAllocMem(FMacros,0);
FreeAndNil(FIncludeStack);
FreeAndNil(FSourceChangeSteps);
FreeAndNil(Values);
FreeAndNil(FDirectiveSequence);
FreeAndNil(FInitValues);
ReAllocMem(FLinks,0);
inherited Destroy;
end;
function TLinkScanner.LinkSize(Index: integer): integer;
procedure IndexOutOfBounds;
begin
RaiseConsistencyException(20170422125948,'TLinkScanner.LinkSize index '
+IntToStr(Index)+' out of bounds: 0..'+IntToStr(LinkCount-1));
end;
begin
if (Index<0) or (Index>=LinkCount) then
IndexOutOfBounds;
Result:=LinkSize_Inline(Index);
end;
function TLinkScanner.LinkCleanedEndPos(Index: integer): integer;
begin
Result:=LinkSize(Index)+FLinks[Index].CleanedPos;
end;
function TLinkScanner.LinkSourceLog(Index: integer): TSourceLog;
begin
if Assigned(OnGetSource) then
Result:=OnGetSource(Self,FLinks[Index].Code)
else
Result:=nil;
end;
function TLinkScanner.FindFirstSiblingLink(LinkIndex: integer): integer;
{ find link at the start of the code
e.g. The resulting link SrcPos is always 1
if LinkIndex is in the main code, the result will be 0
if LinkIndex is in an include file, the result will be the first link of
the include file. If the include file is included multiple times, it is
treated as if they are different files.
}
var
LastIndex: integer;
begin
Result:=LinkIndex;
if LinkIndex>=0 then begin
LastIndex:=LinkIndex;
while (Result>=0) do begin
if FLinks[Result].Code=FLinks[LinkIndex].Code then begin
if Links[Result].SrcPos>FLinks[LastIndex].SrcPos then begin
// the include file was (in-)directly included by itself
// -> skip
Result:=FindParentLink(Result);
end else if FLinks[Result].SrcPos=1 then begin
// start found
exit;
end;
LastIndex:=Result;
end;
dec(Result);
end;
end;
end;
function TLinkScanner.FindParentLink(LinkIndex: integer): integer;
// a parent link is the link of the include directive
// or in other words: the link in front of the first sibling link
begin
Result:=FindFirstSiblingLink(LinkIndex);
if Result>=0 then dec(Result);
end;
function TLinkScanner.LinkIndexNearCursorPos(ACursorPos: integer;
ACode: Pointer; var CursorInLink: boolean): integer;
// returns the nearest link at cursorpos
// (either covering the cursorpos or in front)
var
CurLinkSize: integer;
BestLinkIndex: integer;
begin
BestLinkIndex:=-1;
Result:=0;
CursorInLink:=false;
while Result<LinkCount do begin
if (ACode=FLinks[Result].Code) and (ACursorPos>=FLinks[Result].SrcPos) then
begin
CurLinkSize:=LinkSize(Result);
if ACursorPos<FLinks[Result].SrcPos+CurLinkSize then begin
CursorInLink:=true;
exit;
end else begin
if (BestLinkIndex<0)
or (FLinks[BestLinkIndex].SrcPos<FLinks[Result].SrcPos) then begin
BestLinkIndex:=Result;
end;
end;
end;
inc(Result);
end;
Result:=BestLinkIndex;
end;
function TLinkScanner.CreateTreeOfSourceCodes: TAVLTree;
var
CurCode: Pointer;
i: Integer;
begin
Result:=TAVLTree.Create(@ComparePointers);
for i:=0 to LinkCount-1 do begin
CurCode:=FLinks[i].Code;
if CurCode=nil then continue;
if Result.Find(CurCode)=nil then
Result.Add(CurCode);
end;
end;
procedure TLinkScanner.ClearDirectives(FreeMemory: boolean);
begin
FDirectivesCount:=0;
if FreeMemory then begin
ReAllocMem(FDirectives,0);
ReAllocMem(FDirectivesSorted,0);
FDirectivesCapacity:=0;
end else begin
if FDirectivesSorted<>nil then
FDirectivesSorted[0]:=nil;
end;
FDirectiveSequence.Clear(FreeMemory);
end;
procedure TLinkScanner.DemandStoreDirectives;
begin
inc(FStoreDirectives);
end;
procedure TLinkScanner.ReleaseStoreDirectives;
begin
if FStoreDirectives=0 then
raise Exception.Create('');
dec(FStoreDirectives);
if FStoreDirectives=0 then
ClearDirectives(true);
end;
function TLinkScanner.FindDirective(aCode: Pointer; aSrcPos: integer; out
FirstSortedIndex, LastSortedIndex: integer): boolean;
var
l: Integer;
r: Integer;
m: Integer;
Dir: TLSDirective;
cmp: Integer;
begin
Dir.Code:=aCode;
Dir.SrcPos:=aSrcPos;
l:=0;
r:=FDirectivesCount-1;
while l<=r do begin
m:=(l+r) div 2;
cmp:=CompareLSDirectiveCodeSrcPos(@Dir,DirectivesSorted[m]);
if cmp<0 then
r:=m-1
else if cmp>0 then
l:=m+1
else begin
// found
FirstSortedIndex:=m;
LastSortedIndex:=m;
while (FirstSortedIndex>0)
and (CompareLSDirectiveCodeSrcPos(@Dir,DirectivesSorted[FirstSortedIndex-1])=0) do
dec(FirstSortedIndex);
while (LastSortedIndex+1<FDirectivesCount)
and (CompareLSDirectiveCodeSrcPos(@Dir,DirectivesSorted[LastSortedIndex+1])=0) do
inc(LastSortedIndex);
Result:=true;
exit;
end;
end;
Result:=false;
FirstSortedIndex:=-1;
LastSortedIndex:=-1;
end;
function TLinkScanner.FindFirstDirective(aCode: Pointer; aSrcPos: integer;
const AllowedStates: TLSDirectiveStates): PLSDirective;
var
FirstSortedIndex, LastSortedIndex, i: integer;
begin
Result:=nil;
if not FindDirective(aCode,aSrcPos,FirstSortedIndex,LastSortedIndex) then exit;
for i:=FirstSortedIndex to LastSortedIndex do begin
Result:=DirectivesSorted[i];
if Result^.State in AllowedStates then exit;
end;
Result:=nil;
end;
function TLinkScanner.LinkIndexAtCleanPos(ACleanPos: integer): integer;
procedure ConsistencyError1;
begin
raise Exception.Create(
'TLinkScanner.LinkAtCleanPos Consistency-Error 1');
end;
procedure ConsistencyError2;
begin
raise Exception.Create(
'TLinkScanner.LinkAtCleanPos Consistency-Error 2');
end;
var l,r,m: integer;
begin
Result:=-1;
if (ACleanPos<1) or (ACleanPos>CleanedLen) then exit;
// binary search through the links
l:=0;
r:=LinkCount-1;
while l<=r do begin
m:=(l+r) div 2;
if m<LinkCount-1 then begin
if ACleanPos<FLinks[m].CleanedPos then
r:=m-1
else if ACleanPos>=FLinks[m+1].CleanedPos then
l:=m+1
else begin
Result:=m;
exit;
end;
end else begin
if ACleanPos>=FLinks[m].CleanedPos then begin
Result:=m;
exit;
end else
ConsistencyError2;
end;
end;
ConsistencyError1;
end;
function TLinkScanner.LinkIndexAtCursorPos(ACursorPos: integer; ACode: Pointer
): integer;
var
CurLinkSize: integer;
begin
Result:=0;
while Result<LinkCount do begin
if (ACode=FLinks[Result].Code) and (ACursorPos>=FLinks[Result].SrcPos) then begin
CurLinkSize:=LinkSize(Result);
if ACursorPos<FLinks[Result].SrcPos+CurLinkSize then begin
exit;
end;
end;
inc(Result);
end;
Result:=-1;
end;
procedure TLinkScanner.SetSource(ACode: Pointer);
procedure RaiseUnableToGetCode;
begin
RaiseConsistencyException(20170422125957,'unable to get source with Code='+DbgS(Code));
end;
var SrcLog: TSourceLog;
begin
if Assigned(FOnGetSource) then begin
SrcLog:=FOnGetSource(Self,ACode);
if SrcLog=nil then
RaiseUnableToGetCode;
SrcFilename:=FOnGetFileName(Self,ACode);
AddSourceChangeStep(ACode,SrcLog.ChangeStep);
Src:=SrcLog.Source;
Code:=ACode;
SrcPos:=1;
TokenStart:=1;
TokenType:=lsttNone;
SrcLen:=length(Src);
CopiedSrcPos:=0;
end else begin
RaiseUnableToGetCode;
end;
end;
procedure TLinkScanner.HandleDirective;
var DirStart, DirLen: integer;
CurDirective: PLSDirective;
begin
FDirectiveCleanPos:=CommentStartPos-CopiedSrcPos+CleanedLen;
if StoreDirectives then begin
if FDirectivesCount=FDirectivesCapacity then begin
// grow
if FDirectivesCapacity=0 then
FDirectivesCapacity:=16
else
FDirectivesCapacity:=FDirectivesCapacity*2;
ReAllocMem(FDirectives,FDirectivesCapacity*SizeOf(TLSDirective));
end;
CurDirective:=@FDirectives[FDirectivesCount];
CurDirective^.Kind:=lsdkNone;
CurDirective^.Code:=Code;
CurDirective^.SrcPos:=CommentStartPos;
CurDirective^.CleanPos:=FDirectiveCleanPos;
if FSkippingDirectives=lssdNone then
CurDirective^.State:=lsdsActive
else
CurDirective^.State:=lsdsSkipped;
CurDirective^.Level:=IfLevel;
inc(FDirectivesCount);
end;
SrcPos:=CommentInnerStartPos+1;
DirStart:=SrcPos;
while (SrcPos<=SrcLen) and (IsIdentStartChar[Src[SrcPos]]) do
inc(SrcPos);
DirLen:=SrcPos-DirStart;
if DirLen>255 then DirLen:=255;
FDirectiveName:=copy(Src,DirStart,DirLen);
DoDirective(DirStart,DirLen);
SrcPos:=CommentEndPos;
end;
function TLinkScanner.ReturnFromIncludeFileAndIsEnd: boolean;
begin
Result:=false;
if not ReturnFromIncludeFile then begin
SrcPos:=SrcLen+1; // make sure SrcPos stands somewhere
TokenStart:=SrcPos;
TokenType:=lsttSrcEnd;
Result:=true;
end;
end;
{$IFOPT R+}{$DEFINE RangeChecking}{$ENDIF}
{$R-}
procedure TLinkScanner.ReadNextToken;
var
c1: char;
c2: char;
MacroID: LongInt;
p: PChar;
begin
//DebugLn([' TLinkScanner.ReadNextToken SrcPos=',SrcPos,' SrcLen=',SrcLen,' "',dbgstr(Src,SrcPos,5),'"']);
if (SrcPos>SrcLen) and ReturnFromIncludeFileAndIsEnd then exit;
//DebugLn([' TLinkScanner.ReadNextToken SrcPos=',SrcPos,' SrcLen=',SrcLen,' "',copy(Src,SrcPos,5),'"']);
// Skip all spaces and comments
p:=@Src[SrcPos];
while true do begin
case p^ of
#0:
begin
SrcPos:=p-PChar(Src)+1;
if (SrcPos>SrcLen) then begin
if ReturnFromIncludeFileAndIsEnd then exit;
if (SrcPos>SrcLen) then break;
end else
inc(SrcPos);
p:=@Src[SrcPos];
end;
'{' :
begin
SrcPos:=p-PChar(Src)+1;
ReadCurlyComment;
p:=@Src[SrcPos];
end;
'/':
if p[1]='/' then begin
SrcPos:=p-PChar(Src)+1;
ReadLineComment;
p:=@Src[SrcPos];
end else
break;
'(':
if p[1]='*' then begin
SrcPos:=p-PChar(Src)+1;
ReadRoundComment;
p:=@Src[SrcPos];
end else
break;
' ',#9,#10,#13:
repeat
inc(p);
until not (p^ in [' ',#9,#10,#13]);
else
break;
end;
end;
TokenStart:=p-PChar(Src)+1;
// read token
c1:=p^;
case c1 of
'_','A'..'Z','a'..'z':
begin
// keyword or identifier
inc(p);
while IsIdentChar[p^] do
inc(p);
TokenType:=lsttWord;
SrcPos:=p-PChar(Src)+1;
if FMacrosOn then begin
MacroID:=IndexOfMacro(@Src[TokenStart],false);
if MacroID>=0 then begin
AddMacroSource(MacroID);
end;
end;
end;
'&':
begin
// identifier with "&" character or an octal number
inc(p);
case p^ of
'_','A'..'Z','a'..'z'://identifier: &uses
begin
inc(p);
while IsIdentChar[p^] do
inc(p);
TokenType:=lsttWord;
end;
'0'..'7'://octal number: &10
begin
inc(p);
while IsOctNumberChar[p^] do
inc(p);
TokenType:=lsttNone;
end;
else
TokenType:=lsttNone;
end;
SrcPos:=p-PChar(Src)+1;
end;
'''','#':
begin
TokenType:=lsttStringConstant;
while true do begin
case p^ of
#0:
begin
SrcPos:=p-PChar(Src)+1;
if SrcPos>SrcLen then break;
inc(p);
end;
'#':
begin
inc(p);
while IsNumberChar[p^] do
inc(p);
end;
'''':
begin
inc(p);
while true do begin
case p^ of
#0:
begin
SrcPos:=p-PChar(Src)+1;
if SrcPos>SrcLen then break;
inc(p);
end;
'''':
begin
inc(p);
break;
end;
#10,#13:
break;
else
inc(p);
end;
end;
end;
else
break;
end;
end;
SrcPos:=p-PChar(Src)+1;
end;
'0'..'9':
begin
TokenType:=lsttNone;
inc(p);
while IsNumberChar[p^] do
inc(p);
if (p^='.') and (p[1]<>'.') then begin
// real type number
inc(p);
while IsNumberChar[p^] do
inc(p);
if (p^ in ['E','e']) then begin
// read exponent
inc(p);
if (p^ in ['-','+']) then inc(p);
while IsNumberChar[p^] do
inc(p);
end;
end;
SrcPos:=p-PChar(Src)+1;
end;
'%': // boolean
begin
TokenType:=lsttNone;
inc(p);
while p^ in ['0'..'1'] do
inc(p);
SrcPos:=p-PChar(Src)+1;
end;
'$': // hex
begin
TokenType:=lsttNone;
inc(p);
while IsHexNumberChar[p^] do
inc(p);
SrcPos:=p-PChar(Src)+1;
end;
'=':
begin
SrcPos:=p-PChar(Src)+2;
TokenType:=lsttEqual;
end;
'.':
begin
SrcPos:=p-PChar(Src)+2;
TokenType:=lsttPoint;
end;
';':
begin
SrcPos:=p-PChar(Src)+2;
TokenType:=lsttSemicolon;
end;
',':
begin
SrcPos:=p-PChar(Src)+2;
TokenType:=lsttComma;
end;
else
TokenType:=lsttNone;
inc(p);
c2:=p^;
// test for double char operators
// :=, +=, -=, /=, *=, <>, <=, >=, **, ><, ..
if ((c2='=') and (IsEqualOperatorStartChar[c1]))
or ((c1='<') and (c2='>'))
or ((c1='>') and (c2='<'))
or ((c1='.') and (c2='.'))
or ((c1='*') and (c2='*'))
then inc(p);
SrcPos:=p-PChar(Src)+1;
end;
end;
{$IFDEF RangeChecking}{$R+}{$UNDEF RangeChecking}{$ENDIF}
procedure TLinkScanner.Scan(Range: TLinkScannerRange; CheckFilesOnDisk: boolean);
var
LastTokenType: TLSTokenType;
cm: TCompilerMode;
pc: TPascalCompiler;
s: string;
LastProgressPos: integer;
CheckForAbort: boolean;
NewSrcLen: Integer;
begin
if (not UpdateNeeded(Range,CheckFilesOnDisk)) then begin
// input is the same as last time -> output is the same
// -> if there was an error and it was in a needed range, raise it again
if LastErrorIsValid then begin
// the error has happened in ScannedRange
if ord(ScannedRange)>=ord(Range) then begin
// error is behind needed range => ok
end else if (not IgnoreErrorAfterValid)
or (not IgnoreErrAfterPositionIsInFrontOfLastErrMessage)
then
RaiseLastError;
end;
exit;
end;
{$IFDEF CTDEBUG}
DebugLn('TLinkScanner.Scan A -------- Range=',dbgs(Range));
{$ENDIF}
ScanTill:=Range;
Clear;
if Assigned(OnGetGlobalChangeSteps) then
OnGetGlobalChangeSteps(FGlobalSourcesChangeStep,FGlobalFilesChangeStep,
FGlobalInitValuesChangeStep);
FStates:=FStates-[lssSourcesChanged,lssFilesChanged,lssInitValuesChanged];
{$IFDEF CTDEBUG}
DebugLn('TLinkScanner.Scan B ');
{$ENDIF}
SetSource(FMainCode);
NewSrcLen:=length(Src);
if NewSrcLen<FLastCleanedSrcLen+1000 then
NewSrcLen:=FLastCleanedSrcLen+1000;
SetLength(FCleanedSrc,NewSrcLen);
CleanedLen:=0;
{$IFDEF CTDEBUG}
DebugLn('TLinkScanner.Scan C ',dbgs(SrcLen));
{$ENDIF}
ScannedRange:=lsrNone;
IsUnit:=false;
SourceName:='';
CommentStyle:=CommentNone;
CommentLevel:=0;
FPascalCompiler:=pcFPC;
CompilerMode:=cmFPC;
FNestedComments:=cmsNested_comment in DefaultCompilerModeSwitches[CompilerMode];
IfLevel:=0;
FSkippingDirectives:=lssdNone;
FDirectivesStored:=StoreDirectives;
//DebugLn('TLinkScanner.Scan D --------');
// initialize Defines
if Assigned(FOnGetInitValues) then
FInitValues.Assign(FOnGetInitValues(Self,FMainCode,FInitValuesChangeStep));
Values.Assign(FInitValues);
// compiler
s:=FInitValues.Variables[PascalCompilerDefine];
if s<>'' then begin
for pc:=Low(TPascalCompiler) to High(TPascalCompiler) do
if (s=PascalCompilerNames[pc]) then
PascalCompiler:=pc;
end else if InitialValues.IsDefined('pas2js') then
PascalCompiler:=pcPas2js
else if InitialValues.IsDefined('delphi') and not InitialValues.IsDefined('fpc') then
PascalCompiler:=pcDelphi;
// compiler mode
for cm:=Low(TCompilerMode) to High(TCompilerMode) do
if FInitValues.IsDefined(CompilerModeVars[cm]) then begin
CompilerMode:=cm;
break;
end;
// nested comments override
if Values.IsDefined(ExternalMacroStart+'NestedComments') then
FNestedComments:=true;
//DebugLn(['TLinkScanner.Scan ',MainFilename,' ',PascalCompilerNames[PascalCompiler],' ',CompilerModeNames[CompilerMode],' FNestedComments=',FNestedComments,' ModeSwitches=',dbgs(CompilerModeSwitches)]);
//DebugLn(Values.AsString);
FMacrosOn:=(Values.Variables['MACROS']<>'0');
if Src='' then exit;
// begin scanning
AddLink(SrcPos,Code);
LastTokenType:=lsttNone;
LastProgressPos:=0;
CheckForAbort:=Assigned(OnProgress);
{$IFDEF CTDEBUG}
DebugLn('TLinkScanner.Scan F ',dbgs(SrcLen));
{$ENDIF}
ScannedRange:=lsrInit;
if ScanTill=lsrInit then exit;
try
try
ReadNextToken;
if TokenIsWord('USES') then
DoUsesToken
else
SrcPos:=TokenStart;
while ord(ScanTill)>ord(ScannedRange) do begin
// check every 100.000 bytes for abort
if CheckForAbort and ((LastProgressPos-CopiedSrcPos)>100000) then begin
LastProgressPos:=CopiedSrcPos;
DoCheckAbort;
end;
//debugln(['TLinkScanner.Scan Token ',dbgstr(Src,TokenStart,SrcPos-TokenStart)]);
ReadNextToken;
if TokenType=lsttWord then
ParseKeyWord(TokenStart,LastTokenType);
//writeln('TLinkScanner.Scan G "',copy(Src,TokenStart,SrcPos-TokenStart),'" LastTokenType=',LastTokenType,' TokenType=',TokenType);
if (LastTokenType=lsttEnd) and (TokenType=lsttPoint) then begin
//DebugLn(['TLinkScanner.Scan END. ',MainFilename]);
ScannedRange:=lsrEnd;
break;
end;
if (SrcPos>SrcLen) and ReturnFromIncludeFileAndIsEnd then
break;
LastTokenType:=TokenType;
end;
finally
{$IFDEF ShowUpdateCleanedSrc}
DebugLn('TLinkScanner.Scan UpdatePos=',DbgS(SrcPos-1));
{$ENDIF}
if (SrcPos>CopiedSrcPos) then
UpdateCleanedSource(SrcPos-1);
if FDirectivesCount>0 then
SortDirectives;
if FSkippingDirectives<>lssdNone then begin
{$IFDEF ShowUpdateCleanedSrc}
DebugLn(['TLinkScanner.Scan missing $ENDIF']);
{$ENDIF}
end;
end;
IncreaseChangeStep;
FLastCleanedSrcLen:=CleanedLen;
except
on E: ELinkScannerError do begin
if (not IgnoreErrorAfterValid)
or (not IgnoreErrAfterPositionIsInFrontOfLastErrMessage) then
raise;
{$IFDEF ShowIgnoreErrorAfter}
DebugLn('TLinkScanner.Scan IGNORING ERROR: ',LastErrorMessage);
{$ENDIF}
end;
end;
{$IFDEF CTDEBUG}
DebugLn('TLinkScanner.Scan END ',dbgs(CleanedLen),' ',dbgs(ScannedRange));
{$ENDIF}
end;
procedure TLinkScanner.SetLinks(Index: integer; const Value: TSourceLink);
begin
FLinks[Index]:=Value;
end;
procedure TLinkScanner.ReadCurlyComment;
// a normal pascal {} comment
var
p: PChar;
begin
CommentStyle:=CommentCurly;
CommentStartPos:=SrcPos;
IncCommentLevel;
CommentInnerStartPos:=SrcPos+1;
p:=@Src[SrcPos];
inc(p);
// HandleSwitches can dec CommentLevel
while true do begin
case p^ of
#0:
begin
SrcPos:=p-PChar(Src)+1;
if SrcPos>SrcLen then
break;
end;
'{' :
IncCommentLevel;
'}' :
begin
DecCommentLevel;
if CommentLevel=0 then begin
inc(p);
break;
end;
end;
end;
inc(p);
end;
SrcPos:=p-PChar(Src)+1;
CommentEndPos:=SrcPos;
CommentInnerEndPos:=SrcPos-1;
if (CommentLevel>0) then CommentEndNotFound(20170422130048);
// handle compiler switches
if Src[CommentInnerStartPos]='$' then
HandleDirective;
EndComment;
end;
procedure TLinkScanner.ReadLineComment;
// a // newline comment
var
p: PChar;
begin
CommentStyle:=CommentLine;
CommentStartPos:=SrcPos;
IncCommentLevel;
p:=@Src[SrcPos];
inc(p,2);
CommentInnerStartPos:=SrcPos;
while not (p^ in [#0,#10,#13]) do inc(p);
DecCommentLevel;
if p^<>#0 then inc(p);
SrcPos:=p-PChar(Src)+1;
CommentEndPos:=SrcPos;
CommentInnerEndPos:=SrcPos-1;
// handle compiler switches (ignore)
EndComment;
end;
procedure TLinkScanner.ReadRoundComment;
// a delphi comment (* *)
var
p: PChar;
begin
CommentStyle:=CommentLine;
CommentStartPos:=SrcPos;
IncCommentLevel;
CommentInnerStartPos:=SrcPos+2;
p:=@Src[SrcPos];
inc(p,2);
while true do begin
case p^ of
#0:
begin
SrcPos:=p-PChar(Src)+1;
if SrcPos>SrcLen then
break;
end;
'*':
begin
inc(p);
if p^=')' then begin
inc(p);
DecCommentLevel;
if CommentLevel=0 then break;
end;
end;
'(':
begin
inc(p);
if FNestedComments and (p^='*') then begin
inc(p);
IncCommentLevel;
end;
end;
else
inc(p);
end;
end;
SrcPos:=p-PChar(Src)+1;
CommentEndPos:=SrcPos;
CommentInnerEndPos:=SrcPos-2;
if (CommentLevel>0) then CommentEndNotFound(20170422130050);
// handle compiler switches
if Src[CommentInnerStartPos]='$' then
HandleDirective;
EndComment;
end;
procedure TLinkScanner.CommentEndNotFound(id: int64);
begin
SrcPos:=CommentStartPos;
RaiseException(id,ctsCommentEndNotFound);
end;
procedure TLinkScanner.UpdateCleanedSource(NewCopiedSrcPos: integer);
// add new parsed code to cleaned source string
procedure RaiseInvalid;
begin
debugln(['TLinkScanner.UpdateCleanedSource inconsistency found: Srclen=',SrcLen,'=',length(Src),' FCleanedSrc=',CleanedLen,'/',length(FCleanedSrc),' CopiedSrcPos=',CopiedSrcPos,' NewCopiedSrcPos=',NewCopiedSrcPos,' AddLen=',NewCopiedSrcPos-CopiedSrcPos]);
RaiseConsistencyException(20170422130054,'TLinkScanner.UpdateCleanedSource inconsistency found AddLen='+dbgs(NewCopiedSrcPos-CopiedSrcPos));
end;
var AddLen: integer;
begin
if NewCopiedSrcPos>SrcLen then NewCopiedSrcPos:=SrcLen+1;
if NewCopiedSrcPos=CopiedSrcPos then exit;
AddLen:=NewCopiedSrcPos-CopiedSrcPos;
if AddLen<=0 then RaiseInvalid;
if AddLen>length(FCleanedSrc)-CleanedLen then begin
// expand cleaned source string by at least 1024
SetLength(FCleanedSrc,length(FCleanedSrc)+SrcLen+1024);
end;
System.Move(Src[CopiedSrcPos+1],FCleanedSrc[CleanedLen+1],AddLen);
inc(CleanedLen,AddLen);
{$IFDEF ShowUpdateCleanedSrc}
DebugLn('TLinkScanner.UpdateCleanedSource A ',
DbgS(CopiedSrcPos),'-',DbgS(NewCopiedSrcPos),'="',
StringToPascalConst(copy(Src,CopiedSrcPos+1,20)),
'".."',StringToPascalConst(copy(Src,NewCopiedSrcPos-19,20)),'"');
{$ENDIF}
CopiedSrcPos:=NewCopiedSrcPos;
end;
procedure TLinkScanner.AddSourceChangeStep(ACode: pointer; AChangeStep: integer);
procedure RaiseCodeNil;
begin
RaiseConsistencyException(20170422130109,'TLinkScanner.AddSourceChangeStep ACode=nil');
end;
var l,r,m: integer;
NewSrcChangeStep: PSourceChangeStep;
c: pointer;
begin
//DebugLn('[TLinkScanner.AddSourceChangeStep] ',DbgS(ACode));
if ACode=nil then
RaiseCodeNil;
l:=0;
r:=FSourceChangeSteps.Count-1;
m:=0;
c:=nil;
while (l<=r) do begin
m:=(l+r) shr 1;
c:=PSourceChangeStep(FSourceChangeSteps[m])^.Code;
if c<ACode then l:=m+1
else if c>ACode then r:=m-1
else exit;
end;
NewSrcChangeStep:=PSourceChangeStepMemManager.NewPSourceChangeStep;
NewSrcChangeStep^.Code:=ACode;
NewSrcChangeStep^.ChangeStep:=AChangeStep;
if (FSourceChangeSteps.Count>0) and (c<ACode) then inc(m);
FSourceChangeSteps.Insert(m,NewSrcChangeStep);
//DebugLn(' ADDING ',DbgS(ACode),',',FSourceChangeSteps.Count);
end;
function TLinkScanner.TokenIs(const AToken: string): boolean;
var ATokenLen: integer;
i: integer;
begin
Result:=false;
if (SrcPos<=SrcLen+1) and (TokenStart>=1) then begin
ATokenLen:=length(AToken);
if ATokenLen=SrcPos-TokenStart then begin
for i:=1 to ATokenLen do
if AToken[i]<>Src[TokenStart-1+i] then exit;
Result:=true;
end;
end;
end;
function TLinkScanner.UpTokenIs(const AToken: string): boolean;
var ATokenLen: integer;
i: integer;
begin
Result:=false;
if (SrcPos<=SrcLen+1) and (TokenStart>=1) then begin
ATokenLen:=length(AToken);
if ATokenLen=SrcPos-TokenStart then begin
for i:=1 to ATokenLen do
if AToken[i]<>UpChars[Src[TokenStart-1+i]] then exit;
Result:=true;
end;
end;
end;
procedure TLinkScanner.ConsistencyCheck;
var i: integer;
begin
if (FLinks=nil) xor (FLinkCapacity=0) then
RaiseCatchableException('');
if FLinks<>nil then begin
for i:=0 to FLinkCount-1 do begin
if (FLinks[i].Code=nil) and (FLinks[i].Kind=slkCode) then
RaiseCatchableException('');
if (FLinks[i].CleanedPos<1) or (FLinks[i].CleanedPos>SrcLen) then
RaiseCatchableException('');
end;
end;
if SrcLen<>length(Src) then
RaiseCatchableException('');
if Values<>nil then
Values.ConsistencyCheck;
end;
procedure TLinkScanner.WriteDebugReport;
var i: integer;
begin
// header
DebugLn('');
DebugLn('[TLinkScanner.WriteDebugReport]',
' ChangeStepCount=',dbgs(FSourceChangeSteps.Count),
' LinkCount=',dbgs(LinkCount),
' CleanedLen=',dbgs(CleanedLen));
// time stamps
for i:=0 to FSourceChangeSteps.Count-1 do begin
DebugLn(' ChangeStep ',dbgs(i),': '
,' Code=',dbgs(PSourceChangeStep(FSourceChangeSteps[i])^.Code)
,' ChangeStep=',dbgs(PSourceChangeStep(FSourceChangeSteps[i])^.ChangeStep));
end;
// links
for i:=0 to LinkCount-1 do begin
DebugLn([' Link ',i,':'
,' CleanedPos=',FLinks[i].CleanedPos
,' SrcPos=',FLinks[i].SrcPos
,' Code=',dbgs(FLinks[i].Code)
,' Kind=',dbgs(FLinks[i].Kind)
,' Src="',dbgstr(CleanedSrc,FLinks[i].CleanedPos,Min(50,LinkSize(i))),'"'
]);
end;
end;
procedure TLinkScanner.CalcMemSize(Stats: TCTMemStats);
begin
Stats.Add('TLinkScanner',
PtrUInt(InstanceSize)
+MemSizeString(FMainSourceFilename)
+length(FDirectiveName)
+MemSizeString(LastErrorMessage)
+MemSizeString(SrcFilename));
Stats.Add('TLinkScanner.CleanedSrc',MemSizeString(FCleanedSrc));
// Note: Src belongs to the codebuffer
if FLinks<>nil then
Stats.Add('TLinkScanner.FLinks',
FLinkCapacity*SizeOf(TSourceLink));
if FInitValues<>nil then
Stats.Add('TLinkScanner.FInitValues',
FInitValues.CalcMemSize(false)); // FInitValues are copies of strings of TDefineTree
if FSourceChangeSteps<>nil then
Stats.Add('TLinkScanner.FSourceChangeSteps',
FSourceChangeSteps.InstanceSize
+FSourceChangeSteps.Capacity*SizeOf(TSourceChangeStep));
if FIncludeStack<>nil then
Stats.Add('TLinkScanner.FIncludeStack',
FIncludeStack.InstanceSize+FIncludeStack.Capacity*SizeOf(TSourceLink));
if Values<>nil then
Stats.Add('TLinkScanner.Values',
Values.CalcMemSize(true,FInitValues));
if FDirectiveSequence<>nil then
Stats.Add('TLinkScanner.FDirectiveSequence',
FDirectiveSequence.CalcMemSize);
if FMissingIncludeFiles<>nil then
Stats.Add('TLinkScanner.FMissingIncludeFiles',
FMissingIncludeFiles.InstanceSize);
end;
function TLinkScanner.UpdateNeeded(
Range: TLinkScannerRange; CheckFilesOnDisk: boolean): boolean;
{ the clean source must be rebuilt if
1. a former check says so
2. scanrange increased
3. unit source changed
4. one of its include files changed
5. init values changed (e.g. initial compiler defines)
6. a missing include file can now be found
}
var i: integer;
SrcLog: TSourceLog;
NewInitValues: TExpressionEvaluator;
NewInitValuesChangeStep: integer;
SrcChange: PSourceChangeStep;
CurSourcesChangeStep, CurFilesChangeStep: int64;
CurInitValuesChangeStep: integer;
begin
Result:=true;
if Range=lsrNone then exit(false);
if not Assigned(FOnCheckFileOnDisk) then CheckFilesOnDisk:=false;
// use the last check result
if [lssSourcesChanged,lssInitValuesChanged]*FStates<>[] then exit;
if CheckFilesOnDisk and (lssFilesChanged in FStates) then exit;
// check options
if StoreDirectives and (not DirectivesStored) then exit;
// check if range increased
// Note: if there was an error, then a range increase will raise the same error
// and no update is needed
if (ord(Range)>ord(ScannedRange)) and (not LastErrorIsValid) then begin
{$IFDEF VerboseUpdateNeeded}
DebugLn(['TLinkScanner.UpdateNeeded because range increased from ',dbgs(ScannedRange),' to ',dbgs(Range),' ',ExtractFilename(MainFilename)]);
{$ENDIF}
exit;
end;
// do a quick test: check the global change steps for sources and values
if Assigned(OnGetGlobalChangeSteps) then begin
OnGetGlobalChangeSteps(CurSourcesChangeStep,CurFilesChangeStep,CurInitValuesChangeStep);
if (CurSourcesChangeStep=FGlobalSourcesChangeStep)
and (CurInitValuesChangeStep=FGlobalInitValuesChangeStep)
and ((not CheckFilesOnDisk) or (CurFilesChangeStep=FGlobalSourcesChangeStep))
then begin
// sources and values did not change since last check
//debugln(['TLinkScanner.UpdateNeeded global change steps still the same: ',MainFilename]);
Result:=false;
exit;
end;
end else begin
CurSourcesChangeStep:=1;
CurFilesChangeStep:=1;
CurInitValuesChangeStep:=1;
end;
// check initvalues
//if ExtractFileNameOnly(MainFilename)='androidr14' then
//debugln(['TLinkScanner.UpdateNeeded FGlobalInitValuesChangeStep=',FGlobalInitValuesChangeStep,' CurInitValuesChangeStep=',CurInitValuesChangeStep]);
if FGlobalInitValuesChangeStep<>CurInitValuesChangeStep then begin
FGlobalInitValuesChangeStep:=CurInitValuesChangeStep;
if Assigned(FOnGetInitValues) then begin
NewInitValues:=FOnGetInitValues(Self,Code,NewInitValuesChangeStep);
if (NewInitValues<>nil)
and (NewInitValuesChangeStep<>FInitValuesChangeStep)
and (not FInitValues.Equals(NewInitValues)) then begin
{$IFDEF VerboseUpdateNeeded}
//if ExtractFileNameOnly(MainFilename)='androidr14' then
DebugLn(['TLinkScanner.UpdateNeeded because InitValues changed ',MainFilename]);
{$ENDIF}
Include(FStates,lssInitValuesChanged);
exit;
end;
end;
end;
// check all used codebuffers
if FGlobalSourcesChangeStep<>CurSourcesChangeStep then begin
FGlobalSourcesChangeStep:=CurSourcesChangeStep;
if Assigned(FOnGetSource) then begin
for i:=0 to FSourceChangeSteps.Count-1 do begin
SrcChange:=PSourceChangeStep(FSourceChangeSteps[i]);
SrcLog:=FOnGetSource(Self,SrcChange^.Code);
//debugln(['TLinkScanner.UpdateNeeded ',ExtractFilename(MainFilename),' i=',i,' File=',FOnGetFileName(Self,SrcLog),' Last=',SrcChange^.ChangeStep,' Now=',SrcLog.ChangeStep]);
if SrcChange^.ChangeStep<>SrcLog.ChangeStep then begin
{$IFDEF VerboseUpdateNeeded}
DebugLn(['TLinkScanner.UpdateNeeded because source buffer changed: ',OnGetFileName(Self,SrcLog),' MainFilename=',MainFilename]);
{$ENDIF}
Include(FStates,lssSourcesChanged);
exit;
end;
end;
end;
end;
// check all file dates
if CheckFilesOnDisk then begin
if FGlobalFilesChangeStep<>CurFilesChangeStep then begin
FGlobalFilesChangeStep:=CurFilesChangeStep;
if Assigned(FOnGetSource) then begin
// if files changed on disk, reload them
for i:=0 to FSourceChangeSteps.Count-1 do begin
SrcChange:=PSourceChangeStep(FSourceChangeSteps[i]);
SrcLog:=FOnGetSource(Self,SrcChange^.Code);
if FOnCheckFileOnDisk(SrcLog) then begin
{$IFDEF VerboseUpdateNeeded}
DebugLn(['TLinkScanner.UpdateNeeded because file on disk changed: ',OnGetFileName(Self,SrcLog),' MainFilename=',MainFilename]);
{$ENDIF}
Include(FStates,lssFilesChanged);
exit;
end;
end;
end;
end;
end;
// check missing include files
if CheckFilesOnDisk and MissingIncludeFilesNeedsUpdate then begin
{$IFDEF VerboseUpdateNeeded}
DebugLn(['TLinkScanner.UpdateNeeded because MissingIncludeFilesNeedsUpdate']);
{$ENDIF}
Include(FStates,lssFilesChanged);
exit;
end;
// no update needed :)
//DebugLn('TLinkScanner.UpdateNeeded END');
Result:=false;
end;
procedure TLinkScanner.SetIgnoreErrorAfter(ACursorPos: integer; ACode: Pointer);
begin
if (FIgnoreErrorAfterCode=ACode)
and (FIgnoreErrorAfterCursorPos=ACursorPos) then exit;
FIgnoreErrorAfterCode:=ACode;
FIgnoreErrorAfterCursorPos:=ACursorPos;
LastErrorCheckedForIgnored:=false;
{$IFDEF ShowIgnoreErrorAfter}
DbgOut('TLinkScanner.SetIgnoreErrorAfter ');
if FIgnoreErrorAfterCode<>nil then
DbgOut(OnGetFileName(Self,FIgnoreErrorAfterCode))
else
DbgOut('nil');
DbgOut(' ',dbgs(FIgnoreErrorAfterCursorPos));
DebugLn('');
{$ENDIF}
end;
procedure TLinkScanner.ClearIgnoreErrorAfter;
begin
SetIgnoreErrorAfter(0,nil);
end;
function TLinkScanner.IgnoreErrAfterPositionIsInFrontOfLastErrMessage: boolean;
var
CleanResult: integer;
begin
//DebugLn('TLinkScanner.IgnoreErrAfterPositionIsInFrontOfLastErrMessage');
//DebugLn([' LastErrorCheckedForIgnored=',LastErrorCheckedForIgnored,
// ' LastErrorBehindIgnorePosition=',LastErrorBehindIgnorePosition]);
if LastErrorCheckedForIgnored then
Result:=LastErrorBehindIgnorePosition
else begin
CleanedIgnoreErrorAfterPosition:=-1;
if (FIgnoreErrorAfterCode<>nil) and (FIgnoreErrorAfterCursorPos>0) then
begin
CleanResult:=CursorToCleanPos(FIgnoreErrorAfterCursorPos,
FIgnoreErrorAfterCode,CleanedIgnoreErrorAfterPosition);
{$IFDEF ShowIgnoreErrorAfter}
DebugLn([' CleanResult=',CleanResult,
' CleanedIgnoreErrorAfterPosition=',CleanedIgnoreErrorAfterPosition,
' FIgnoreErrorAfterCursorPos=',FIgnoreErrorAfterCursorPos,
' CleanedLen=',CleanedLen,
' LastErrorIsValid=',LastErrorIsValid]);
{$ENDIF}
if (CleanResult=0) or (CleanResult=-1)
or (not LastErrorIsValid) then begin
Result:=true;
end else begin
Result:=false;
end;
end else begin
Result:=false;
end;
LastErrorBehindIgnorePosition:=Result;
LastErrorCheckedForIgnored:=true;
end;
{$IFDEF ShowIgnoreErrorAfter}
DebugLn('TLinkScanner.IgnoreErrAfterPositionIsInFrontOfLastErrMessage Result=',dbgs(Result));
{$ENDIF}
end;
function TLinkScanner.IgnoreErrorAfterCleanedPos: integer;
begin
if IgnoreErrAfterPositionIsInFrontOfLastErrMessage then
Result:=CleanedIgnoreErrorAfterPosition
else
Result:=-1;
{$IFDEF ShowIgnoreErrorAfter}
DebugLn('TLinkScanner.IgnoreErrorAfterCleanedPos Result=',dbgs(Result));
{$ENDIF}
end;
function TLinkScanner.IgnoreErrorAfterValid: boolean;
begin
Result:=(FIgnoreErrorAfterCode<>nil);
{$IFDEF ShowIgnoreErrorAfter}
DebugLn('TLinkScanner.IgnoreErrorAfterValid Result=',dbgs(Result));
{$ENDIF}
end;
function TLinkScanner.CleanPosIsAfterIgnorePos(CleanPos: integer): boolean;
var
p: LongInt;
begin
if IgnoreErrorAfterValid then begin
p:=IgnoreErrorAfterCleanedPos;
if p<1 then
Result:=false
else
Result:=CleanPos>=p;
end else begin
Result:=false
end;
end;
function TLinkScanner.LastErrorIsInFrontOfCleanedPos(ACleanedPos: integer
): boolean;
begin
Result:=LastErrorIsValid and (CleanedLen<ACleanedPos);
{$IFDEF ShowIgnoreErrorAfter}
DebugLn('TLinkScanner.LastErrorIsInFrontOfCleanedPos Result=',dbgs(Result));
{$ENDIF}
end;
procedure TLinkScanner.RaiseLastErrorIfInFrontOfCleanedPos(ACleanedPos: integer);
begin
if LastErrorIsInFrontOfCleanedPos(ACleanedPos) then
RaiseLastError;
end;
{-------------------------------------------------------------------------------
function TLinkScanner.GuessMisplacedIfdefEndif
Params: StartCursorPos: integer; StartCode: pointer;
var EndCursorPos: integer; var EndCode: Pointer;
Result: boolean;
-------------------------------------------------------------------------------}
function TLinkScanner.GuessMisplacedIfdefEndif(StartCursorPos: integer;
StartCode: pointer;
out EndCursorPos: integer; out EndCode: Pointer): boolean;
type
TIf = record
StartPos: integer; // comment start e.g. {
EndPos: integer; // comment end e.g. the char behind }
Expression: string;
HasElse: boolean;
end;
PIf = ^TIf;
TTokenType = (ttNone,
ttCommentStart, ttCommentEnd, // '{' '}'
ttTPCommentStart, ttTPCommentEnd, // '(*' '*)'
ttDelphiCommentStart, // '//'
ttLineEnd
);
TTokenRange = (trCode, trComment, trTPComment, trDelphiComment);
TToken = record
StartPos: integer;
EndPos: integer;
TheType: TTokenType;
Range: TTokenRange;
NestedComments: boolean;
end;
TDirectiveType = (dtUnknown, dtIf, dtIfDef, dtIfNDef, dtIfOpt,
dtElse, dtEndif);
function FindNextToken(const ASrc: string; var AToken: TToken): boolean;
var
ASrcLen: integer;
OldRange: TTokenRange;
begin
Result:=true;
AToken.StartPos:=AToken.EndPos;
ASrcLen:=length(ASrc);
OldRange:=AToken.Range;
while (AToken.StartPos<=ASrcLen) do begin
case ASrc[AToken.StartPos] of
'{': // pascal comment start
begin
AToken.EndPos:=AToken.StartPos+1;
AToken.TheType:=ttCommentStart;
AToken.Range:=trComment;
if (OldRange=trCode) then
exit
else if AToken.NestedComments then begin
if (not FindNextToken(ASrc,AToken)) then begin
Result:=false;
exit;
end;
AToken.StartPos:=AToken.EndPos-1;
AToken.Range:=OldRange;
end;
end;
'(': // check if Turbo Pascal comment start
if (AToken.StartPos<ASrcLen) and (ASrc[AToken.StartPos+1]='*') then
begin
AToken.EndPos:=AToken.StartPos+2;
AToken.TheType:=ttTPCommentStart;
AToken.Range:=trTPComment;
if (OldRange=trCode) then
exit
else if AToken.NestedComments then begin
if (not FindNextToken(ASrc,AToken)) then begin
Result:=false;
exit;
end;
AToken.StartPos:=AToken.EndPos-1;
AToken.Range:=OldRange;
end;
end;
'/': // check if Delphi comment start
if (AToken.StartPos<ASrcLen) and (ASrc[AToken.StartPos+1]='/') then
begin
AToken.EndPos:=AToken.StartPos+2;
AToken.TheType:=ttDelphiCommentStart;
AToken.Range:=trDelphiComment;
if (OldRange=trCode) then
exit
else if AToken.NestedComments then begin
if (not FindNextToken(ASrc,AToken)) then begin
Result:=false;
exit;
end;
AToken.StartPos:=AToken.EndPos-1;
AToken.Range:=OldRange;
end;
end;
'}': // pascal comment end
case AToken.Range of
trComment:
begin
AToken.EndPos:=AToken.StartPos+1;
AToken.TheType:=ttCommentEnd;
AToken.Range:=trCode;
exit;
end;
trCode:
begin
// error (comment was never openend)
// -> skip rest of code
AToken.StartPos:=ASrcLen;
end;
else
// in different kind of comment -> ignore
end;
'*': // turbo pascal comment end
if (AToken.StartPos<ASrcLen) and (ASrc[AToken.StartPos+1]=')') then
begin
case AToken.Range of
trTPComment:
begin
AToken.EndPos:=AToken.StartPos+1;
AToken.TheType:=ttTPCommentEnd;
AToken.Range:=trCode;
exit;
end;
trCode:
begin
// error (comment was never openend)
// -> skip rest of code
AToken.StartPos:=ASrcLen;
end;
else
// in different kind of comment -> ignore
end;
end;
#10,#13: // line end
if AToken.Range in [trDelphiComment] then begin
AToken.EndPos:=AToken.StartPos+1;
if (AToken.StartPos<ASrcLen)
and (ASrc[AToken.StartPos+1] in [#10,#13])
and (ASrc[AToken.StartPos+1]<>ASrc[AToken.StartPos]) then
inc(AToken.EndPos);
AToken.TheType:=ttLineEnd;
AToken.Range:=trCode;
exit;
end else begin
// in different kind of comment -> ignore
end;
'''': // skip string constant
begin
inc(AToken.StartPos);
while (AToken.StartPos<=ASrcLen) do begin
if (not (ASrc[AToken.StartPos] in ['''',#10,#13])) then begin
inc(AToken.StartPos);
end else begin
break;
end;
end;
end;
end;
inc(AToken.StartPos);
end;
// at the end of the code
AToken.EndPos:=AToken.StartPos;
AToken.TheType:=ttNone;
Result:=false;
end;
procedure FreeIfStack(var IfStack: TFPList);
var
i: integer;
AnIf: PIf;
begin
if IfStack=nil then exit;
for i:=0 to IfStack.Count-1 do begin
AnIf:=PIf(IfStack[i]);
AnIf^.Expression:='';
Dispose(AnIf);
end;
IfStack.Free;
IfStack:=nil;
end;
function InitGuessMisplaced(out CurToken: TToken; ACode: Pointer;
out ASrc: string; out ASrcLen: integer): boolean;
var
ASrcLog: TSourceLog;
begin
Result:=false;
// get source
if (FOnGetSource=nil) then exit;
ASrcLog:=FOnGetSource(Self,ACode);
if ASrcLog=nil then exit;
ASrc:=ASrcLog.Source;
ASrcLen:=length(ASrc);
CurToken.StartPos:=1;
CurToken.EndPos:=1;
CurToken.Range:=trCode;
CurToken.TheType:=ttNone;
CurToken.NestedComments:=NestedComments;
Result:=true;
end;
function ReadDirectiveType(const ASrc: string;
AToken: TToken): TDirectiveType;
const
DIR_RST: array[0..5] of TDirectiveType = (
dtIfDef, dtIfNDef, dtIfOpt, dtIf, dtElse, dtEndif
);
DIR_TXT: array[0..5] of PChar = (
'IFDEF', 'IFNDEF', 'IFOPT', 'IF', 'ELSE', 'ENDIF'
);
var
ASrcLen, p: integer;
n: Integer;
begin
Result:=dtUnknown;
ASrcLen:=length(ASrc);
p:=AToken.EndPos;
if (p<ASrcLen) and (ASrc[p]='$') then
begin
// compiler directive
inc(p);
for n := Low(DIR_TXT) to High(DIR_TXT) do
begin
if CompareIdentifiers(@ASrc[p], DIR_TXT[n]) = 0
then begin
Result := DIR_RST[n];
Exit;
end;
end;
end;
end;
procedure PushIfOnStack(const ASrc: string; AToken: TToken; IfStack: TFPList);
var
NewIf: PIf;
begin
New(NewIf);
FillChar(NewIf^,SizeOf(PIf),0);
NewIf^.StartPos:=AToken.StartPos;
FindNextToken(ASrc,AToken);
NewIf^.EndPos:=AToken.EndPos;
NewIf^.Expression:=copy(ASrc,NewIf^.StartPos+1,
AToken.EndPos-NewIf^.StartPos-1);
NewIf^.HasElse:=false;
IfStack.Add(NewIf);
end;
procedure PopIfFromStack(IfStack: TFPList);
var Topif: PIf;
begin
TopIf:=PIf(IfStack[IfStack.Count-1]);
Dispose(TopIf);
IfStack.Delete(IfStack.Count-1);
end;
function GuessMisplacedIfdefEndifInCode(ACode: Pointer;
var EndCursorPos: integer; var EndCode: Pointer): boolean;
var
ASrc: string;
ASrcLen: integer;
CurToken: TToken;
IfStack: TFPList;
DirectiveType: TDirectiveType;
begin
Result:=false;
if not InitGuessMisplaced(CurToken,ACode,ASrc,ASrcLen) then exit;
IfStack:=TFPList.Create;
try
repeat
if (not FindNextToken(ASrc,CurToken)) then begin
exit;
end;
if CurToken.Range in [trComment] then begin
DirectiveType:=ReadDirectiveType(ASrc,CurToken);
case DirectiveType of
dtIf, dtIfDef, dtIfNDef, dtIfOpt:
PushIfOnStack(ASrc,CurToken,IfStack);
dtElse:
begin
if (IfStack.Count=0) or (PIf(IfStack[IfStack.Count-1])^.HasElse)
then begin
// this $ELSE has no $IF
// -> misplaced directive found
EndCursorPos:=CurToken.EndPos;
EndCode:=ACode;
DebugLn('GuessMisplacedIfdefEndif $ELSE has no $IF');
Result:=true;
exit;
end;
PIf(IfStack[IfStack.Count-1])^.HasElse:=true;
end;
dtEndif:
begin
if (IfStack.Count=0) then begin
// this $ENDIF has no $IF
// -> misplaced directive found
EndCursorPos:=CurToken.EndPos;
EndCode:=ACode;
DebugLn('GuessMisplacedIfdefEndif $ENDIF has no $IF');
Result:=true;
exit;
end;
PopIfFromStack(IfStack);
end;
end;
end;
until CurToken.TheType=ttNone;
if IfStack.Count>0 then begin
// there is an $IF without $ENDIF
// -> misplaced directive found
EndCursorPos:=PIf(IfStack[IfStack.Count-1])^.StartPos+1;
EndCode:=ACode;
DebugLn('GuessMisplacedIfdefEndif $IF without $ENDIF');
Result:=true;
exit;
end;
finally
FreeIfStack(IfStack);
end;
end;
var
LinkID, i, BestSrcPos: integer;
LastCode: Pointer;
SearchedCodes: TFPList;
begin
Result:=false;
EndCursorPos:=0;
EndCode:=nil;
if StartCode=nil then exit;
// search link before start position
LinkID:=-1;
BestSrcPos:=0;
i:=0;
while i<LinkCount do begin
if (StartCode=FLinks[i].Code) and (StartCursorPos>=FLinks[i].SrcPos) then begin
if (LinkID<0) or (BestSrcPos<FLinks[i].SrcPos) then
LinkID:=i;
end;
inc(i);
end;
if LinkID<0 then exit;
// go through all following sources and guess misplaced ifdef/endif
SearchedCodes:=TFPList.Create;
try
while LinkId<LinkCount do begin
Result:=GuessMisplacedIfdefEndifInCode(FLinks[LinkID].Code,
EndCursorPos,EndCode);
if Result then exit;
// search next code
LastCode:=FLinks[LinkID].Code;
SearchedCodes.Add(LastCode);
repeat
inc(LinkID);
if LinkID>=LinkCount then exit;
if FLinks[LinkID].Code=nil then continue;
until (FLinks[LinkID].Code<>LastCode)
and (SearchedCodes.IndexOf(FLinks[LinkID].Code)<0);
end;
finally
SearchedCodes.Free;
end;
end;
function TLinkScanner.GetHiddenUsedUnits: string;
var
Controller: String;
AnUnitName: String;
p: Integer;
begin
if FHiddenUsedUnits='' then begin
// see fpc/compiler/pmodules.pp loaddefaultunits
if PascalCompiler=pcDelphi then
FHiddenUsedUnits:=DelphiSystemUnitName
else
FHiddenUsedUnits:=FPCSystemUnitName;
if InitialValues.IsDefined('VER1_0')
then begin
if InitialValues.IsDefined('LINUX') then
FHiddenUsedUnits:='SYSLINUX'
else if InitialValues.IsDefined('BSD') then
FHiddenUsedUnits:='SYSBSD'
else if InitialValues.IsDefined('WIN32') then
FHiddenUsedUnits:='SYSWIN32';
end;
if InitialValues.IsDefined(MacroUseLineInfo) then
FHiddenUsedUnits:=FHiddenUsedUnits+',lineinfo'
else if InitialValues.IsDefined(MacroUselnfodwrf) then
FHiddenUsedUnits:=FHiddenUsedUnits+',lnfodwrf';
if InitialValues.IsDefined(MacroUseValgrind) then
FHiddenUsedUnits:=FHiddenUsedUnits+',cmem';
if InitialValues.IsDefined(MacroUseHeapTrc) then
FHiddenUsedUnits:=FHiddenUsedUnits+',HeapTrc';
if InitialValues.IsDefined('FPC_HAS_WinLikeResources') then begin
// ToDo: fpintres
FHiddenUsedUnits:=FHiddenUsedUnits+',fpextres';
end;
if (cmsObjpas in CompilerModeSwitches) and (PascalCompiler=pcFPC) then
FHiddenUsedUnits:=FHiddenUsedUnits+',ObjPas';
if (CompilerMode=cmMacPas) then
FHiddenUsedUnits:=FHiddenUsedUnits+',MacPas';
if (CompilerMode=cmISO) then
FHiddenUsedUnits:=FHiddenUsedUnits+',ISO7185';
if (CompilerMode=cmExtPas) then
FHiddenUsedUnits:=FHiddenUsedUnits+',ISO7185,ExtPas';
if (cmsCBlocks in CompilerModeSwitches) and (PascalCompiler=pcFPC) then
FHiddenUsedUnits:=FHiddenUsedUnits+',BlockRTL';
if (cmsDefault_unicodestring in CompilerModeSwitches) then
FHiddenUsedUnits:=FHiddenUsedUnits+',UUChar';
if CompilerMode=cmISO then
FHiddenUsedUnits:=FHiddenUsedUnits+',iso7185';
if cmsObjectiveC1 in CompilerModeSwitches then
FHiddenUsedUnits:=FHiddenUsedUnits+',ObjC,ObjCBase';
if InitialValues.IsDefined(MacroUseProfiler) then
// Note: only valid on i386_go32v2,i386_watcom
FHiddenUsedUnits:=FHiddenUsedUnits+',profile';
if InitialValues.IsDefined(MacroUseSysThrds) then
FHiddenUsedUnits:=FHiddenUsedUnits+',SysThrds';
if InitialValues.IsDefined(MacroUseFPCylix) then
FHiddenUsedUnits:=FHiddenUsedUnits+',fpcylix,dynlibs';
Controller:=InitialValues[MacroControllerUnit];
if (Controller<>'') and IsDottedIdentifier(Controller) then
FHiddenUsedUnits:=FHiddenUsedUnits+','+Controller;
// check if this is a hidden used unit
AnUnitName:=ExtractFileNameOnly(MainFilename);
if AnUnitName<>'' then begin
if AnUnitName='system' then
FHiddenUsedUnits:=''
else begin
p:=length(FHiddenUsedUnits);
while p>=1 do begin
while (p>1) and (FHiddenUsedUnits[p-1]<>',') do dec(p);
if (CompareDottedIdentifiers(@FHiddenUsedUnits[p],PChar(AnUnitName))=0)
or (IsUnit and (SourceName<>'')
and (CompareDottedIdentifiers(@FHiddenUsedUnits[p],PChar(SourceName))=0))
then begin
// this unit is a hidden unit => remove this and all behind from list
if p>1 then
System.Delete(FHiddenUsedUnits,p-1,length(FHiddenUsedUnits))
else
FHiddenUsedUnits:='';
break;
end;
dec(p); // skip comma
end;
end;
end;
//debugln(['TLinkScanner.GetHiddenUsedUnits ',dbgs(CompilerModeSwitches),' ',PascalCompilerNames[PascalCompiler],' Mode=',CompilerModeNames[CompilerMode],' units=',FHiddenUsedUnits]);
end;
Result:=FHiddenUsedUnits;
end;
procedure TLinkScanner.SetMainCode(const Value: pointer);
begin
if FMainCode=Value then exit;
FMainCode:=Value;
FMainSourceFilename:=FOnGetFileName(Self,FMainCode);
Clear;
end;
procedure TLinkScanner.SetScanTill(const Value: TLinkScannerRange);
var
OldScanRange: TLinkScannerRange;
begin
if FScanTill=Value then exit;
OldScanRange:=FScanTill;
FScanTill := Value;
if ord(OldScanRange)<ord(FScanTill) then Clear;
end;
function TLinkScanner.ShortSwitchDirective: boolean;
// example: {$H+} or {$H+, R- comment}
var
c: Char;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkShortSwitch;
c:=UpChars[FDirectiveName[1]];
FDirectiveName:=CompilerSwitchesNames[c];
if FDirectiveName<>'' then begin
if (SrcPos<=SrcLen) and (Src[SrcPos] in ['-','+']) then begin
if Src[SrcPos]='-' then
Values.Variables[FDirectiveName] := '0'
else
Values.Variables[FDirectiveName] := '1';
inc(SrcPos);
Result:=ReadNextSwitchDirective;
end else begin
if c='I' then
Result:=IncludeDirective
else
Result:=LongSwitchDirective;
end;
end else
Result:=true;
end;
function TLinkScanner.DoDirective(StartPos, DirLen: integer): boolean;
var
p: PChar;
begin
Result:=false;
if StartPos>SrcLen then exit;
p:=@Src[StartPos];
//DebugLn(['TLinkScanner.DoDirective ',copy(Src,StartPos,DirLen),' FSkippingDirectives=',ord(FSkippingDirectives)]);
if FSkippingDirectives=lssdNone then begin
if DirLen=1 then begin
Result:=(CompilerSwitchesNames[UpChars[p^]]<>'')
and ShortSwitchDirective;
end else begin
case UpChars[p^] of
'A':
case UpChars[p[1]] of
'L': if CompareIdentifiers(p,'ALIGN')=0 then Result:=LongSwitchDirective;
'S': if CompareIdentifiers(p,'ASSERTIONS')=0 then Result:=LongSwitchDirective;
end;
'B':
if CompareIdentifiers(p,'BOOLEVAL')=0 then Result:=LongSwitchDirective;
'D':
case UpChars[p[1]] of
'E':
case UpChars[p[2]] of
'F': if CompareIdentifiers(p,'DEFINE')=0 then Result:=DefineDirective;
'B': if CompareIdentifiers(p,'DEBUGINFO')=0 then Result:=LongSwitchDirective;
end;
end;
'E':
case UpChars[p[1]] of
'L':
case UpChars[p[2]] of
'I': if CompareIdentifiers(p,'ELIFC')=0 then Result:=ElIfCDirective;
'S':
case UpChars[p[3]] of
'E':
if CompareIdentifiers(p,'ELSE')=0 then Result:=ElseDirective
else if CompareIdentifiers(p,'ELSEC')=0 then Result:=ElseCDirective
else if CompareIdentifiers(p,'ELSEIF')=0 then Result:=ElseIfDirective;
end;
end;
'N':
if CompareIdentifiers(p,'ENDC')=0 then Result:=EndCDirective
else if CompareIdentifiers(p,'ENDIF')=0 then Result:=EndIfDirective;
'X':
if CompareIdentifiers(p,'EXTENDEDSYNTAX')=0 then Result:=LongSwitchDirective;
end;
'I':
case UpChars[p[1]] of
'F':
case UpChars[p[2]] of
'C': if CompareIdentifiers(p,'IFC')=0 then Result:=IfCDirective;
'D': if CompareIdentifiers(p,'IFDEF')=0 then Result:=IfDefDirective;
'E': if CompareIdentifiers(p,'IFEND')=0 then Result:=IfEndDirective;
'N': if CompareIdentifiers(p,'IFNDEF')=0 then Result:=IfndefDirective;
'O': if CompareIdentifiers(p,'IFOPT')=0 then Result:=IfOptDirective;
else if DirLen=2 then Result:=IfDirective;
end;
'N':
if CompareIdentifiers(p,'INCLUDE')=0 then Result:=IncludeDirective
else if CompareIdentifiers(p,'INCLUDEPATH')=0 then Result:=IncludePathDirective;
'O': if CompareIdentifiers(p,'IOCHECKS')=0 then Result:=LongSwitchDirective;
end;
'L':
if CompareIdentifiers(p,'LOCALSYMBOLS')=0 then Result:=LongSwitchDirective
else if CompareIdentifiers(p,'LONGSTRINGS')=0 then Result:=LongSwitchDirective;
'M':
if CompareIdentifiers(p,'MODE')=0 then Result:=ModeDirective
else if CompareIdentifiers(p,'MODESWITCH')=0 then Result:=ModeSwitchDirective
else if CompareIdentifiers(p,'MACRO')=0 then Result:=MacroDirective;
'O':
if CompareIdentifiers(p,'OPENSTRINGS')=0 then Result:=LongSwitchDirective
else if CompareIdentifiers(p,'OVERFLOWCHECKS')=0 then Result:=LongSwitchDirective;
'R':
if CompareIdentifiers(p,'RANGECHECKS')=0 then Result:=LongSwitchDirective
else if CompareIdentifiers(p,'REFERENCEINFO')=0 then Result:=LongSwitchDirective;
'S':
if CompareIdentifiers(p,'SETC')=0 then Result:=SetCDirective
else if CompareIdentifiers(p,'STACKFRAMES')=0 then Result:=LongSwitchDirective
else if CompareIdentifiers(p,'SCOPEDENUMS')=0 then Result:=LongSwitchDirectiveWithSequence(sdScopedEnums);
'T':
if CompareIdentifiers(p,'THREADING')=0 then Result:=ThreadingDirective
else if CompareIdentifiers(p,'TYPEADDRESS')=0 then Result:=LongSwitchDirective
else if CompareIdentifiers(p,'TYPEINFO')=0 then Result:=LongSwitchDirective;
'U':
if CompareIdentifiers(p,'UNDEF')=0 then Result:=UndefDirective;
'V':
if CompareIdentifiers(p,'VARSTRINGCHECKS')=0 then Result:=LongSwitchDirective;
end;
end;
end else begin
// skipping code => read only IF directives
case UpChars[p^] of
'E':
case UpChars[p[1]] of
'L':
case UpChars[p[2]] of
'I': if CompareIdentifiers(p,'ELIFC')=0 then Result:=ElIfCDirective;
'S':
case UpChars[p[3]] of
'E':
if CompareIdentifiers(p,'ELSE')=0 then Result:=ElseDirective
else if CompareIdentifiers(p,'ELSEC')=0 then Result:=ElseCDirective
else if CompareIdentifiers(p,'ELSEIF')=0 then Result:=ElseIfDirective;
end;
end;
'N':
if CompareIdentifiers(p,'ENDC')=0 then Result:=EndCDirective
else if CompareIdentifiers(p,'ENDIF')=0 then Result:=EndIfDirective;
end;
'I':
case UpChars[p[1]] of
'F':
case UpChars[p[2]] of
'C': if CompareIdentifiers(p,'IFC')=0 then Result:=IfCDirective;
'D': if CompareIdentifiers(p,'IFDEF')=0 then Result:=IfDefDirective;
'E': if CompareIdentifiers(p,'IFEND')=0 then Result:=IfEndDirective;
'N': if CompareIdentifiers(p,'IFNDEF')=0 then Result:=IfndefDirective;
'O': if CompareIdentifiers(p,'IFOPT')=0 then Result:=IfOptDirective;
else if DirLen=2 then Result:=IfDirective;
end;
end;
end;
end;
end;
function TLinkScanner.LongSwitchDirective: boolean;
// example: {$ASSERTIONS ON comment}
var ValStart: integer;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkLongSwitch;
ReadSpace;
ValStart:=SrcPos;
while (SrcPos<=SrcLen) and IsWordChar[Src[SrcPos]] do
inc(SrcPos);
if CompareUpToken('ON',Src,ValStart,SrcPos) then
Values.Variables[FDirectiveName] := '1'
else if CompareUpToken('OFF',Src,ValStart,SrcPos) then
Values.Variables[FDirectiveName] := '0'
else if CompareUpToken('PRELOAD',Src,ValStart,SrcPos)
and (FDirectiveName='ASSERTIONS') then
Values.Variables[FDirectiveName] := 'PRELOAD'
else if (FDirectiveName='LOCALSYMBOLS') then
// ignore "localsymbols <something>"
else if (FDirectiveName='RANGECHECKS') then
// ignore "rangechecks <something>"
else if (FDirectiveName='ALIGN') then
// set record align size
else begin
RaiseExceptionFmt(20170422130112,ctsInvalidFlagValueForDirective,
[copy(Src,ValStart,SrcPos-ValStart),FDirectiveName]);
end;
Result:=ReadNextSwitchDirective;
end;
function TLinkScanner.LongSwitchDirectiveWithSequence(
const ADirective: TSequenceDirective): boolean;
var ValStart: integer;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkLongSwitch;
ReadSpace;
ValStart:=SrcPos;
while (SrcPos<=SrcLen) and IsWordChar[Src[SrcPos]] do
inc(SrcPos);
if CompareUpToken('ON',Src,ValStart,SrcPos) then
SetDirectiveValueWithSequence(ADirective, '1')
else if CompareUpToken('OFF',Src,ValStart,SrcPos) then
SetDirectiveValueWithSequence(ADirective, '0')
else begin
RaiseExceptionFmt(20170422130115,ctsInvalidFlagValueForDirective,
[copy(Src,ValStart,SrcPos-ValStart),FDirectiveName]);
end;
Result:=ReadNextSwitchDirective;
end;
function TLinkScanner.MacroDirective: boolean;
var
ValStart: LongInt;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkMacro;
ReadSpace;
ValStart:=SrcPos;
while (SrcPos<=SrcLen) and (IsWordChar[Src[SrcPos]]) do
inc(SrcPos);
if CompareUpToken('ON',Src,ValStart,SrcPos) then
FMacrosOn:=true
else if CompareUpToken('OFF',Src,ValStart,SrcPos) then
FMacrosOn:=false
else
RaiseExceptionFmt(20170422130118,ctsInvalidFlagValueForDirective,
[copy(Src,ValStart,SrcPos-ValStart),FDirectiveName]);
Result:=true;
end;
function TLinkScanner.ModeDirective: boolean;
// $MODE DEFAULT, OBJFPC, TP, FPC, GPC, DELPHI
var ValStart: integer;
AMode: TCompilerMode;
ModeValid: boolean;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkMode;
ReadSpace;
ValStart:=SrcPos;
while (SrcPos<=SrcLen) and (IsIdentChar[Src[SrcPos]]) do
inc(SrcPos);
// undefine all mode macros
for AMode:=Low(TCompilerMode) to High(TCompilerMode) do
Values.Undefine(CompilerModeVars[AMode]);
// define new mode macro
if CompareUpToken('DEFAULT',Src,ValStart,SrcPos) then begin
// set mode to initial mode
for AMode:=Low(TCompilerMode) to High(TCompilerMode) do
if FInitValues.IsDefined(CompilerModeVars[AMode]) then begin
CompilerMode:=AMode;
break;
end;
end else begin
ModeValid:=false;
for AMode:=Low(TCompilerMode) to High(TCompilerMode) do
if CompareUpToken(CompilerModeNames[AMode],Src,ValStart,SrcPos) then
begin
CompilerMode:=AMode;
ModeValid:=true;
break;
end;
if not ModeValid then
RaiseExceptionFmt(20170422130122,ctsInvalidMode,[copy(Src,ValStart,SrcPos-ValStart)]);
end;
Result:=true;
end;
function TLinkScanner.ModeSwitchDirective: boolean;
// $MODESWITCH objectivec1
// $MODESWITCH objectivec1 on|off
// $MODESWITCH systemcodepage-
var
p, ValStart: PChar;
ModeSwitch: TCompilerModeSwitch;
Switches: TCompilerModeSwitches;
Enable: Boolean;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkModeSwitch;
ReadSpace;
p:=@Src[SrcPos];
ValStart:=p;
while IsIdentChar[p^] do inc(p);
Result:=false;
for ModeSwitch := Succ(Low(ModeSwitch)) to High(ModeSwitch) do begin
if CompareIdentifiers(@CompilerModeSwitchNames[ModeSwitch][1],ValStart)=0
then begin
Result:=true;
Switches:=[ModeSwitch];
Enable:=true;
if p^='-' then
Enable:=false
else if IsSpaceChar[p^] then begin
repeat
inc(p);
until not IsSpaceChar[p^];
if CompareIdentifiers(p,'off')=0 then
Enable:=false;
end;
case ModeSwitch of
cmsObjectiveC2: Include(Switches,cmsObjectiveC1);
end;
if Enable then begin
FCompilerModeSwitches:=FCompilerModeSwitches+Switches;
case ModeSwitch of
cmsDefault_unicodestring:
begin
Values.Variables['FPC_UNICODESTRINGS'] := '1';
Values.Variables['UNICODE'] := '1';
end;
end;
end else begin
FCompilerModeSwitches:=FCompilerModeSwitches-Switches;
case ModeSwitch of
cmsDefault_unicodestring:
begin
Values.Undefine('FPC_UNICODESTRINGS');
Values.Undefine('UNICODE');
end;
end;
end;
exit;
end;
end;
RaiseExceptionFmt(20170422130125,ctsInvalidModeSwitch,[GetIdentifier(ValStart)]);
end;
function TLinkScanner.ThreadingDirective: boolean;
// example: {$threading on}
var
ValStart: integer;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkThreading;
ReadSpace;
ValStart:=SrcPos;
while (SrcPos<=SrcLen) and (IsWordChar[Src[SrcPos]]) do
inc(SrcPos);
if CompareUpToken('ON',Src,ValStart,SrcPos) then begin
// define
Values.Variables[MacroUseSysThrds]:='1';
end else begin
// undefine
Values.Undefine(MacroUseSysThrds);
end;
Result:=true;
end;
function TLinkScanner.ReadNextSwitchDirective: boolean;
var DirStart, DirLen: integer;
begin
ReadSpace;
if (SrcPos<=SrcLen) and (Src[SrcPos]=',') then begin
inc(SrcPos);
DirStart:=SrcPos;
while (SrcPos<=SrcLen) and (IsIdentChar[Src[SrcPos]]) do
inc(SrcPos);
DirLen:=SrcPos-DirStart;
if DirLen>255 then DirLen:=255;
FDirectiveName:=copy(Src,DirStart,DirLen);
Result:=DoDirective(DirStart,DirLen);
end else
Result:=true;
end;
function TLinkScanner.IfdefDirective: boolean;
// {$ifdef name comment}
var VariableName: string;
begin
inc(IfLevel);
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkIfdef;
if FSkippingDirectives<>lssdNone then exit(true);
ReadSpace;
VariableName:=ReadUpperIdentifier;
if (VariableName<>'') and (not Values.IsDefined(VariableName)) then
SkipTillEndifElse(lssdTillElse);
Result:=true;
end;
function TLinkScanner.IfCDirective: boolean;
// {$ifc expression} or indirectly called by {$elifc expression}
begin
//DebugLn(['TLinkScanner.IfCDirective FSkippingDirectives=',ord(FSkippingDirectives),' IfLevel=',IfLevel]);
inc(IfLevel);
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkIfC;
if FSkippingDirectives<>lssdNone then exit(true);
Result:=InternalIfDirective;
end;
function TLinkScanner.ReadIdentifier: string;
var StartPos: integer;
begin
StartPos:=SrcPos;
if (SrcPos<=SrcLen) and (IsIdentStartChar[Src[SrcPos]]) then begin
inc(SrcPos);
while (SrcPos<=SrcLen) and (IsIdentChar[Src[SrcPos]]) do
inc(SrcPos);
Result:=copy(Src,StartPos,SrcPos-StartPos);
end else
Result:='';
end;
function TLinkScanner.ReadUpperIdentifier: string;
var StartPos: integer;
begin
StartPos:=SrcPos;
if (SrcPos<=SrcLen) and (IsIdentStartChar[Src[SrcPos]]) then begin
inc(SrcPos);
while (SrcPos<=SrcLen) and (IsIdentChar[Src[SrcPos]]) do
inc(SrcPos);
Result:=UpperCaseStr(copy(Src,StartPos,SrcPos-StartPos));
end else
Result:='';
end;
function TLinkScanner.IfndefDirective: boolean;
// {$ifndef name comment}
var VariableName: string;
begin
inc(IfLevel);
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkIfndef;
if FSkippingDirectives<>lssdNone then exit(true);
ReadSpace;
VariableName:=ReadUpperIdentifier;
if (VariableName<>'') and (Values.IsDefined(VariableName)) then
SkipTillEndifElse(lssdTillElse);
Result:=true;
end;
function TLinkScanner.EndifDirective: boolean;
// {$endif comment}
procedure RaiseAWithoutB;
begin
RaiseExceptionFmt(20170422130128,ctsAwithoutB,['$ENDIF','$IF'])
end;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkEndif;
if IfLevel<=0 then
RaiseAWithoutB;
dec(IfLevel);
if (IfLevel<FSkipIfLevel) and (FSkippingDirectives<>lssdNone) then begin
{$IFDEF ShowUpdateCleanedSrc}
debugln(['TLinkScanner.EndifDirective end skip']);
{$ENDIF}
EndSkipping;
end;
if StoreDirectives then begin
FDirectives[FDirectivesCount-1].Level:=IfLevel;
end;
Result:=true;
end;
function TLinkScanner.EndCDirective: boolean;
// {$endc comment}
procedure RaiseAWithoutB;
begin
RaiseExceptionFmt(20170422130131,ctsAwithoutB,['$ENDC','$IFC'])
end;
begin
//DebugLn(['TLinkScanner.EndCDirective FSkippingDirectives=',ord(FSkippingDirectives),' IfLevel=',IfLevel]);
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkEndC;
if IfLevel<=0 then
RaiseAWithoutB;
dec(IfLevel);
if (IfLevel<FSkipIfLevel) and (FSkippingDirectives<>lssdNone) then begin
{$IFDEF ShowUpdateCleanedSrc}
debugln(['TLinkScanner.EndCDirective end skip']);
{$ENDIF}
EndSkipping;
end;
Result:=true;
end;
function TLinkScanner.IfEndDirective: boolean;
// {$IfEnd comment}
procedure RaiseAWithoutB;
begin
RaiseExceptionFmt(20170422130134,ctsAwithoutB,['$IfEnd','$ElseIf'])
end;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkIfEnd;
if IfLevel<=0 then
RaiseAWithoutB;
dec(IfLevel);
if (IfLevel<FSkipIfLevel) and (FSkippingDirectives<>lssdNone) then begin
{$IFDEF ShowUpdateCleanedSrc}
debugln(['TLinkScanner.IfEndDirective end skip']);
{$ENDIF}
EndSkipping;
end;
Result:=true;
end;
function TLinkScanner.ElseDirective: boolean;
// {$else comment}
procedure RaiseAWithoutB;
begin
RaiseExceptionFmt(20170422130138,ctsAwithoutB,['$ELSE','$IF']);
end;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkElse;
if IfLevel=0 then
RaiseAWithoutB;
case FSkippingDirectives of
lssdNone:
// last block was executed, skip all other
SkipTillEndifElse(lssdTillEndIf);
lssdTillElse:
if IfLevel=FSkipIfLevel then begin
{$IFDEF ShowUpdateCleanedSrc}
debugln(['TLinkScanner.ElseDirective skipped front, using ELSE part']);
{$ENDIF}
EndSkipping;
end;
end;
Result:=true;
end;
function TLinkScanner.ElseCDirective: boolean;
// {$elsec comment}
procedure RaiseAWithoutB;
begin
RaiseExceptionFmt(20170422130140,ctsAwithoutB,['$ELSEC','$IFC']);
end;
begin
//DebugLn(['TLinkScanner.ElseCDirective FSkippingDirectives=',ord(FSkippingDirectives),' IfLevel=',IfLevel]);
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkElseC;
if IfLevel=0 then
RaiseAWithoutB;
case FSkippingDirectives of
lssdNone:
// last block was executed, skip all other
SkipTillEndifElse(lssdTillEndIf);
lssdTillElse:
if IfLevel=FSkipIfLevel then begin
{$IFDEF ShowUpdateCleanedSrc}
debugln(['TLinkScanner.ElseCDirective skipped front, using ELSEC part']);
{$ENDIF}
EndSkipping;
end;
end;
Result:=true;
end;
function TLinkScanner.ElseIfDirective: boolean;
// {$elseif expression}
procedure RaiseAWithoutB;
begin
RaiseExceptionFmt(20170422130143,ctsAwithoutB,['$ELSEIF','$IF']);
end;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkElseIf;
if IfLevel=0 then
RaiseAWithoutB;
case FSkippingDirectives of
lssdNone:
// last block was executed, skip all other
SkipTillEndifElse(lssdTillEndIf);
lssdTillElse:
if IfLevel=FSkipIfLevel then
exit(InternalIfDirective);
end;
Result:=true;
end;
function TLinkScanner.ElIfCDirective: boolean;
// {$elifc expression}
procedure RaiseAWithoutB;
begin
RaiseExceptionFmt(20170422130146,ctsAwithoutB,['$ELIFC','$IFC']);
end;
begin
//DebugLn(['TLinkScanner.ElIfCDirective FSkippingDirectives=',ord(FSkippingDirectives),' IfLevel=',IfLevel]);
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkElseC;
if IfLevel=0 then
RaiseAWithoutB;
case FSkippingDirectives of
lssdNone:
// last block was executed, skip all other
SkipTillEndifElse(lssdTillEndIf);
lssdTillElse:
if IfLevel=FSkipIfLevel then
exit(InternalIfDirective);
end;
Result:=true;
end;
function TLinkScanner.DefineDirective: boolean;
// {$define name} or {$define name:=value}
var VariableName, NewValue: string;
NamePos: LongInt;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkDefine;
ReadSpace;
NamePos:=SrcPos;
VariableName:=ReadUpperIdentifier;
if (VariableName<>'') then begin
ReadSpace;
if FMacrosOn and (SrcPos<SrcLen)
and (Src[SrcPos]=':') and (Src[SrcPos+1]='=')
then begin
// makro => store the value
inc(SrcPos,2);
ReadSpace;
NewValue:=copy(Src,SrcPos,CommentInnerEndPos-SrcPos);
if CompareIdentifiers(PChar(NewValue),'false')=0 then
NewValue:='0'
else if CompareIdentifiers(PChar(NewValue),'true')=0 then
NewValue:='1';
Values.Variables[VariableName]:=NewValue;
AddMacroValue(@Src[NamePos],SrcPos,CommentInnerEndPos);
end else begin
// flag
Values.Variables[VariableName]:='1';
end;
end;
Result:=true;
end;
function TLinkScanner.UndefDirective: boolean;
// {$undefine name}
var VariableName: string;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkUndef;
ReadSpace;
VariableName:=ReadUpperIdentifier;
if (VariableName<>'') then
Values.Undefine(VariableName);
Result:=true;
end;
function TLinkScanner.SetCDirective: boolean;
// {$setc name} or {$setc name:=value}
var VariableName, NewValue: string;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkSetC;
ReadSpace;
VariableName:=ReadUpperIdentifier;
if (VariableName<>'') then begin
ReadSpace;
if FMacrosOn and (SrcPos<SrcLen)
and (Src[SrcPos]=':') and (Src[SrcPos+1]='=')
then begin
inc(SrcPos,2);
ReadSpace;
NewValue:=copy(Src,SrcPos,CommentInnerEndPos-SrcPos);
if CompareIdentifiers(PChar(NewValue),'false')=0 then
NewValue:='0'
else if CompareIdentifiers(PChar(NewValue),'true')=0 then
NewValue:='1';
Values.Variables[VariableName]:=NewValue;
end else begin
Values.Variables[VariableName]:='1';
end;
end;
Result:=true;
end;
function TLinkScanner.IncludeDirective: boolean;
// {$i filename} or {$include filename}
// filename can be 'filename with spaces'
var
IncFilename: string;
begin
Result:=false;
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkInclude;
inc(SrcPos);
if (Src[SrcPos]='%') then begin
UpdateCleanedSource(CommentStartPos-1);
// insert ''
// ToDo: insert more useful string constant: %date%, %fpcversion%
if 2>length(FCleanedSrc)-CleanedLen then begin
// expand cleaned source string by at least 1024
SetLength(FCleanedSrc,length(FCleanedSrc)+1024);
end;
AddLink(1,nil,slkCompilerString);
inc(CleanedLen);
FCleanedSrc[CleanedLen]:='''';
inc(CleanedLen);
FCleanedSrc[CleanedLen]:='''';
// continue after directive
CopiedSrcPos:=CommentEndPos-1;
AddLink(CommentEndPos,Code);
end else begin
IncFilename:=Trim(copy(Src,SrcPos,CommentInnerEndPos-SrcPos));
if (IncFilename<>'') and (IncFilename[1]='''') then begin
if (IncFilename[length(IncFilename)]='''') then
IncFilename:=copy(IncFilename,2,length(IncFilename)-2)
else begin
SrcPos:=CommentInnerEndPos;
RaiseException(20170422130149,'missing ''');
end;
end;
ForcePathDelims(IncFilename);
{$IFDEF ShowUpdateCleanedSrc}
DebugLn('TLinkScanner.IncludeDirective A IncFilename="',IncFilename,'" UpdatePos=',DbgS(CommentEndPos-1));
{$ENDIF}
UpdateCleanedSource(CommentEndPos-1);
// put old position on stack
PushIncludeLink(CleanedLen,CommentEndPos,Code);
// load include file
Result:=IncludeFile(IncFilename);
if Result then begin
if (SrcPos<=SrcLen) then
CommentEndPos:=SrcPos
else
ReturnFromIncludeFile;
end else begin
PopIncludeLink;
end;
end;
//DebugLn('[TLinkScanner.IncludeDirective] END ',CommentEndPos,',',SrcPos,',',SrcLen);
end;
function TLinkScanner.IncludePathDirective: boolean;
// {$includepath path_addition}
var AddPath, PathDivider: string;
begin
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkIncludePath;
inc(SrcPos);
AddPath:=Trim(copy(Src,SrcPos,CommentInnerEndPos-SrcPos));
PathDivider:=':';
Values.Variables[ExternalMacroStart+'INCPATH']:=
Values.Variables[ExternalMacroStart+'INCPATH']+PathDivider+AddPath;
Result:=true;
end;
function TLinkScanner.LoadSourceCaseLoUp(const AFilename: string;
AllowVirtual: boolean): pointer;
var
Path, FileNameOnly: string;
SecondaryFileNameOnly: String;
begin
{$IFDEF VerboseIncludeSearch}
debugln(['TLinkScanner.LoadSourceCaseLoUp AFilename="',AFilename,'" AllowVirtual=',AllowVirtual]);
{$ENDIF}
Result:=nil;
Path:=ResolveDots(ExtractFilePath(AFilename));
if (not AllowVirtual) and (Path<>'') and (not FilenameIsAbsolute(Path)) then
exit;
FileNameOnly:=ExtractFilename(AFilename);
Result:=FOnLoadSource(Self,Path+FileNameOnly,true);
if (Result<>nil) then exit;
SecondaryFileNameOnly:=LowerCase(FileNameOnly);
if (SecondaryFileNameOnly<>FileNameOnly) then begin
Result:=FOnLoadSource(Self,Path+SecondaryFileNameOnly,true);
if (Result<>nil) then exit;
end;
SecondaryFileNameOnly:=UpperCaseStr(FileNameOnly);
if (SecondaryFileNameOnly<>FileNameOnly) then begin
Result:=FOnLoadSource(Self,Path+SecondaryFileNameOnly,true);
if (Result<>nil) then exit;
end;
end;
function TLinkScanner.SearchIncludeFile(AFilename: string;
out NewCode: Pointer; var MissingIncludeFile: TMissingIncludeFile): boolean;
var
PathStart, PathEnd: integer;
IncludePath, CurPath: string;
ExpFilename: string;
HasPathDelims: Boolean;
function SearchPath(const APath, RelFilename: string): boolean;
begin
Result:=false;
if APath='' then exit;
{$IFDEF VerboseIncludeSearch}
DebugLn('TLinkScanner.SearchPath CurIncPath="',APath,'" / "',RelFilename,'"');
{$ENDIF}
ExpFilename:=AppendPathDelim(APath)+RelFilename;
if not FilenameIsAbsolute(ExpFilename) then
ExpFilename:=ExtractFilePath(FMainSourceFilename)+ExpFilename;
NewCode:=LoadSourceCaseLoUp(ExpFilename);
Result:=NewCode<>nil;
end;
procedure SetMissingIncludeFile;
begin
if MissingIncludeFile=nil then
MissingIncludeFile:=TMissingIncludeFile.Create(AFilename,'');
MissingIncludeFile.IncludePath:=IncludePath;
end;
function SearchCasedInIncPath(const RelFilename: string): boolean;
begin
if FilenameIsAbsolute(FMainSourceFilename) then begin
// main source has absolute filename
// search in directory of unit
ExpFilename:=ExtractFilePath(FMainSourceFilename)+RelFilename;
NewCode:=LoadSourceCaseLoUp(ExpFilename);
Result:=(NewCode<>nil);
if Result then exit;
// search in directory of source of include directive
if FilenameIsAbsolute(SrcFilename)
and (CompareFilenames(SrcFilename,FMainSourceFilename)<>0) then begin
ExpFilename:=ExtractFilePath(SrcFilename)+RelFilename;
NewCode:=LoadSourceCaseLoUp(ExpFilename);
Result:=(NewCode<>nil);
if Result then exit;
end;
end else begin
// main source is virtual -> allow virtual include file
NewCode:=LoadSourceCaseLoUp(RelFilename,true);
Result:=(NewCode<>nil);
if Result then exit;
end;
// then search the include file in directories defines in fpc.cfg (by -Fi option)
if FindIncFileInCfgCache(AFilename,ExpFilename) then
begin
NewCode:=LoadSourceCaseLoUp(ExpFilename);
Result:=(NewCode<>nil);
if Result then exit;
end;
// then search the include file in the include path
if not HasPathDelims then begin
if MissingIncludeFile=nil then
IncludePath:=Values.Variables[ExternalMacroStart+'INCPATH']
else
IncludePath:=MissingIncludeFile.IncludePath;
{$IFDEF VerboseIncludeSearch}
DebugLn('TLinkScanner.SearchIncludeFile IncPath="',IncludePath,'"');
{$ENDIF}
PathStart:=1;
PathEnd:=PathStart;
while PathEnd<=length(IncludePath) do begin
if IncludePath[PathEnd]=';' then begin
if PathEnd>PathStart then begin
CurPath:=TrimFilename(copy(IncludePath,PathStart,PathEnd-PathStart));
Result:=SearchPath(CurPath,RelFilename);
if Result then exit;
end;
PathStart:=PathEnd+1;
PathEnd:=PathStart;
end else
inc(PathEnd);
end;
if PathEnd>PathStart then begin
CurPath:=TrimFilename(copy(IncludePath,PathStart,PathEnd-PathStart));
Result:=SearchPath(CurPath,RelFilename);
if Result then exit;
end;
end;
Result:=false;
end;
begin
{$IFDEF VerboseIncludeSearch}
DebugLn('TLinkScanner.SearchIncludeFile Filename="',AFilename,'"');
{$ENDIF}
NewCode:=nil;
IncludePath:='';
// beware of 'dir/file.inc'
HasPathDelims:=(System.Pos('/',AFilename)>0) or (System.Pos('\',AFilename)>0);
if HasPathDelims then
ForcePathDelims(AFilename);
AFilename:=ResolveDots(AFilename);
if not Assigned(FOnLoadSource) then begin
NewCode:=nil;
SetMissingIncludeFile;
Result:=false;
exit;
end;
// if include filename is absolute then load it directly
if FilenameIsAbsolute(AFilename) then begin
NewCode:=LoadSourceCaseLoUp(AFilename);
Result:=(NewCode<>nil);
if not Result then SetMissingIncludeFile;
exit;
end;
// first search without touching the extension
{$IFDEF VerboseIncludeSearch}
debugln(['TLinkScanner.SearchIncludeFile FMainSourceFilename="',FMainSourceFilename,'" SrcFile="',SrcFilename,'" AFilename="',AFilename,'"']);
{$ENDIF}
if SearchCasedInIncPath(AFilename) then exit(true);
if ExtractFileExt(AFilename)='' then begin
// search with the default file extensions
if SearchCasedInIncPath(AFilename+'.inc') then exit(true);
if SearchCasedInIncPath(AFilename+'.pp') then exit(true);
if SearchCasedInIncPath(AFilename+'.pas') then exit(true);
end;
SetMissingIncludeFile;
Result:=false;
end;
function TLinkScanner.IncludeFile(const AFilename: string): boolean;
var
NewCode: Pointer;
MissingIncludeFile: TMissingIncludeFile;
begin
MissingIncludeFile:=nil;
Result:=SearchIncludeFile(AFilename,NewCode,MissingIncludeFile);
if Result then begin
// change source
if Assigned(FOnIncludeCode) then
FOnIncludeCode(FMainCode,NewCode);
SetSource(NewCode);
AddLink(SrcPos,Code);
end else begin
if MissingIncludeFile<>nil then begin
if FMissingIncludeFiles=nil then
FMissingIncludeFiles:=TMissingIncludeFiles.Create;
FMissingIncludeFiles.Add(MissingIncludeFile);
end;
if (not IgnoreMissingIncludeFiles) then begin
// ToDo: add an event to let application improve the error message
RaiseExceptionFmt(20170422130152,ctsIncludeFileNotFound,[AFilename])
end else begin
// add a dummy link
AddLink(SrcPos,nil,slkMissingIncludeFile);
AddLink(SrcPos,Code);
end;
end;
end;
function TLinkScanner.IfDirective: boolean;
// {$if expression} or indirectly called by {$elseif expression}
begin
inc(IfLevel);
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkIf;
if FSkippingDirectives<>lssdNone then exit(true);
Result:=InternalIfDirective;
end;
function TLinkScanner.IfOptDirective: boolean;
// {$ifopt o+} or {$ifopt o-}
var Option, c: char;
v: String;
begin
inc(IfLevel);
if StoreDirectives then
FDirectives[FDirectivesCount-1].Kind:=lsdkIfOpt;
if FSkippingDirectives<>lssdNone then exit(true);
Result:=true;
inc(SrcPos);
Option:=UpChars[Src[SrcPos]];
if (IsWordChar[Option]) and (CompilerSwitchesNames[Option]<>'')
then begin
inc(SrcPos);
if (SrcPos<=SrcLen) then begin
c:=Src[SrcPos];
if c in ['+','-'] then begin
v:=Values.Variables[CompilerSwitchesNames[Option]];
if (c='-')<>((v='0') or (v='')) then
begin
SkipTillEndifElse(lssdTillElse);
exit;
end;
end;
end;
end;
end;
procedure TLinkScanner.SetIgnoreMissingIncludeFiles(const Value: boolean);
begin
if Value then
Include(FStates,lssIgnoreMissingIncludeFiles)
else
Exclude(FStates,lssIgnoreMissingIncludeFiles);
end;
procedure TLinkScanner.PushIncludeLink(ACleanedPos, ASrcPos: integer;
ACode: Pointer);
procedure RaiseIncludeCircleDetected;
begin
RaiseException(20170422130154,ctsIncludeCircleDetected);
end;
var NewLink: PSourceLink;
i: integer;
begin
for i:=0 to FIncludeStack.Count-1 do
if PSourceLink(FIncludeStack[i])^.Code=ACode then
RaiseIncludeCircleDetected;
NewLink:=PSourceLinkMemManager.NewPSourceLink;
with NewLink^ do begin
CleanedPos:=ACleanedPos;
SrcPos:=ASrcPos;
Code:=ACode;
end;
FIncludeStack.Add(NewLink);
end;
function TLinkScanner.PopIncludeLink: TSourceLink;
var PLink: PSourceLink;
begin
PLink:=PSourceLink(FIncludeStack[FIncludeStack.Count-1]);
Result:=PLink^;
PSourceLinkMemManager.DisposePSourceLink(PLink);
FIncludeStack.Delete(FIncludeStack.Count-1);
end;
function TLinkScanner.GetIncludeFileIsMissing: boolean;
begin
Result:=(FMissingIncludeFiles<>nil);
end;
function TLinkScanner.MissingIncludeFilesNeedsUpdate: boolean;
var
i: integer;
MissingIncludeFile: TMissingIncludeFile;
NewCode: Pointer;
begin
Result:=false;
if (not IncludeFileIsMissing) or IgnoreMissingIncludeFiles then exit;
{ last scan missed an include file (i.e. was not in searchpath)
-> Check all missing include files again }
for i:=0 to FMissingIncludeFiles.Count-1 do begin
MissingIncludeFile:=FMissingIncludeFiles[i];
if SearchIncludeFile(MissingIncludeFile.Filename,NewCode,MissingIncludeFile)
then begin
Result:=true;
exit;
end;
end;
end;
procedure TLinkScanner.ClearMissingIncludeFiles;
begin
FreeAndNil(FMissingIncludeFiles);
end;
procedure TLinkScanner.AddMacroValue(MacroName: PChar; ValueStart, ValueEnd: integer);
var
i: LongInt;
Macro: PSourceLinkMacro;
begin
i:=IndexOfMacro(MacroName,false);
if i<0 then begin
// insert new macro
i:=IndexOfMacro(MacroName,true);
if FMacroCount=fMacroCapacity then begin
fMacroCapacity:=fMacroCapacity*2;
if fMacroCapacity<4 then fMacroCapacity:=4;
ReAllocMem(FMacros,SizeOf(TSourceLinkMacro)*fMacroCapacity);
end;
if i<FMacroCount then
System.Move(FMacros[i],FMacros[i+1],
SizeOf(TSourceLinkMacro)*(FMacroCount-i));
FillByte(FMacros[i],SizeOf(TSourceLinkMacro),0);
inc(FMacroCount);
end;
Macro:=@FMacros[i];
Macro^.Name:=MacroName;
Macro^.Code:=Code;
Macro^.Src:=Src;
Macro^.SrcFilename:=SrcFilename;
Macro^.StartPos:=ValueStart;
Macro^.EndPos:=ValueEnd;
//DebugLn(['TLinkScanner.AddMacroValue ',GetIdentifier(MacroName),' ',copy(Src,ValueStart,ValueEnd-ValueStart)]);
end;
procedure TLinkScanner.ClearMacros;
var
i: Integer;
begin
for i:=0 to FMacroCount-1 do begin
with FMacros[i] do begin
//DebugLn(['TLinkScanner.ClearMacros ',GetIdentifier(Name),' ',SrcFilename]);
Src:='';
SrcFilename:='';
end;
end;
FMacroCount:=0;
end;
function TLinkScanner.IndexOfMacro(MacroName: PChar; InsertPos: boolean): integer;
var
l: Integer;
r: Integer;
m: Integer;
cmp: LongInt;
begin
l:=0;
r:=FMacroCount-1;
m:=0;
cmp:=0;
while l<=r do begin
m:=(l+r) div 2;
cmp:=CompareIdentifierPtrs(MacroName,FMacros[m].Name);
if cmp<0 then
r:=m-1
else if cmp>0 then
l:=m+1
else begin
Result:=m;
exit;
end;
end;
if InsertPos then begin
if cmp>0 then inc(m);
Result:=m;
end else begin
Result:=-1;
end;
end;
procedure TLinkScanner.AddMacroSource(MacroID: integer);
var
Macro: PSourceLinkMacro;
OldCode: Pointer;
OldSrc: String;
OldSrcFilename: String;
begin
Macro:=@FMacros[MacroID];
//DebugLn(['TLinkScanner.AddMacroSource ID=',MacroID,' ',GetIdentifier(Macro^.Name)]);
// update cleaned source
UpdateCleanedSource(TokenStart-1);
// store old code pos
OldCode:=Code;
OldSrc:=Src;
OldSrcFilename:=SrcFilename;
//DebugLn(['TLinkScanner.AddMacroSource BEFORE CleanedSrc=',dbgstr(copy(FCleanedSrc,CleanedLen-19,20))]);
// add macro source
AddLink(Macro^.StartPos,Macro^.Code);
Code:=Macro^.Code;
Src:=Macro^.Src;
SrcLen:=length(Src);
SrcFilename:=Macro^.SrcFilename;
CopiedSrcPos:=Macro^.StartPos-1;
UpdateCleanedSource(Macro^.EndPos-1);
//DebugLn(['TLinkScanner.AddMacroSource MACRO CleanedSrc=',dbgstr(copy(FCleanedSrc,CleanedLen-19,20))]);
// restore code pos
Code:=OldCode;
Src:=OldSrc;
SrcLen:=length(Src);
SrcFilename:=OldSrcFilename;
CopiedSrcPos:=SrcPos-1;
AddLink(SrcPos,Code);
// clear token type
TokenType:=lsttNone;
// SrcPos was not touched and still stands behind the macro name
//DebugLn(['TLinkScanner.AddMacroSource END Token=',copy(Src,TokenStart,SrcPos-TokenStart)]);
end;
procedure TLinkScanner.AddSkipComment(IsStart: boolean);
begin
//DebugLn(['TLinkScanner.AddSkipComment InFront="',dbgstr(CleanedSrc,CleanedLen-12,13),'" isstart=',IsStart]);
// insert {#3 or #3}
if 2>length(FCleanedSrc)-CleanedLen then begin
// expand cleaned source string by at least 1024
SetLength(FCleanedSrc,length(FCleanedSrc)+1024);
end;
if IsStart then begin
AddLink(1,nil,slkSkipStart);
inc(CleanedLen);
FCleanedSrc[CleanedLen]:='{';
inc(CleanedLen);
FCleanedSrc[CleanedLen]:=#3;
end else begin
if (LinkCount>0) and (FLinks[FLinkCount-1].CleanedPos=CleanedLen+1) then begin
// last link is empty
dec(FLinkCount);
{$IFDEF ShowUpdateCleanedSrc}
debugln(['TLinkScanner.AddSkipComment SkipEnd: removing empty link: ',dbgs(FLinks[FLinkCount].Kind)]);
{$ENDIF}
if (LinkCount>0) and (FLinks[FLinkCount-1].Kind=slkSkipStart) then begin
// remove unneeded SkipStart
dec(FLinkCount);
CleanedLen:=FLinks[FLinkCount].CleanedPos;
exit;
end;
end;
AddLink(1,nil,slkSkipEnd);
inc(CleanedLen);
FCleanedSrc[CleanedLen]:=#3;
inc(CleanedLen);
FCleanedSrc[CleanedLen]:='}';
end;
// SrcPos was not touched and still stands at the same position
//DebugLn(['TLinkScanner.AddSkipComment END']);
end;
function TLinkScanner.ReturnFromIncludeFile: boolean;
var OldPos: TSourceLink;
begin
if (SrcPos-1>CopiedSrcPos) then begin
{$IFDEF ShowUpdateCleanedSrc}
DebugLn('TLinkScanner.ReturnFromIncludeFile A UpdatePos=',DbgS(SrcPos-1));
{$ENDIF}
UpdateCleanedSource(SrcPos-1);
end;
while SrcPos>SrcLen do begin
Result:=FIncludeStack.Count>0;
if not Result then exit;
OldPos:=PopIncludeLink;
SetSource(OldPos.Code);
SrcPos:=OldPos.SrcPos;
CopiedSrcPos:=SrcPos-1;
AddLink(SrcPos,Code);
end;
Result:=SrcPos<=SrcLen;
end;
function TLinkScanner.ParseKeyWord(StartPos: integer;
LastTokenType: TLSTokenType): boolean;
var
p: PChar;
begin
if StartPos>SrcLen then exit(false);
p:=@Src[StartPos];
//writeln('TLinkScanner.ParseKeyWord ',copy(Src,StartPos,WordLen));
case UpChars[p^] of
'E': if CompareIdentifiers(p,'END')=0 then exit(DoEndToken);
'F': if CompareIdentifiers(p,'FINALIZATION')=0 then exit(DoFinalizationToken);
'I':
case UpChars[p[1]] of
'M': if CompareIdentifiers(p,'IMPLEMENTATION')=0 then exit(DoImplementationToken);
'N':
case UpChars[p[2]] of
'I': if CompareIdentifiers(p,'INITIALIZATION')=0 then exit(DoInitializationToken);
'T': if (LastTokenType<>lsttEqual)
and (CompareIdentifiers(p,'INTERFACE')=0) then exit(DoInterfaceToken);
end;
end;
'L': if CompareIdentifiers(p,'LIBRARY')=0 then exit(DoSourceTypeToken);
'P':
case UpChars[p[1]] of
'R': if CompareIdentifiers(p,'PROGRAM')=0 then exit(DoSourceTypeToken);
'A': if CompareIdentifiers(p,'PACKAGE')=0 then exit(DoSourceTypeToken);
end;
'U':
case UpChars[p[1]] of
'N': if CompareIdentifiers(p,'UNIT')=0 then exit(DoSourceTypeToken);
'S': if CompareIdentifiers(p,'USES')=0 then exit(DoUsesToken);
end;
end;
Result:=false;
end;
procedure TLinkScanner.SkipTillEndifElse(SkippingUntil: TLSSkippingDirective);
procedure RaiseAlreadySkipping;
begin
raise Exception.Create('TLinkScanner.SkipTillEndifElse inconsistency: already skipping '
+' Old='+dbgs(ord(FSkippingDirectives))
+' New='+dbgs(ord(SkippingUntil)));
end;
var
p: PChar;
begin
if FDirectivesCount>0 then
FDirectives[FDirectivesCount-1].State:=lsdsInactive;
if FSkippingDirectives<>lssdNone then begin
FSkippingDirectives:=SkippingUntil;
exit;
end;
FSkippingDirectives:=SkippingUntil;
SrcPos:=CommentEndPos;
{$IFDEF ShowUpdateCleanedSrc}
DebugLn('TLinkScanner.SkipTillEndifElse A UpdatePos=',DbgS(SrcPos-1),' Src=',DbgStr(Src,SrcPos-15,15)+'|'+DbgStr(Src,SrcPos,15));
{$ENDIF}
UpdateCleanedSource(SrcPos-1);
AddSkipComment(true);
AddLink(SrcPos,Code);
// parse till $else, $elseif or $endif
FSkipIfLevel:=IfLevel;
if (SrcPos<=SrcLen) then begin
p:=@Src[SrcPos];
while true do begin
case p^ of
'{':
begin
SrcPos:=p-PChar(Src)+1;
ReadCurlyComment;
if (FSkippingDirectives=lssdNone) or (SrcPos>SrcLen) then break;
p:=@Src[SrcPos];
end;
'/':
if p[1]='/' then begin
SrcPos:=p-PChar(Src)+1;
ReadLineComment;
if (FSkippingDirectives=lssdNone) or (SrcPos>SrcLen) then break;
p:=@Src[SrcPos];
end else
inc(p);
'(':
if p[1]='*' then begin
SrcPos:=p-PChar(Src)+1;
ReadRoundComment;
if (FSkippingDirectives=lssdNone) or (SrcPos>SrcLen) then break;
p:=@Src[SrcPos];
end else
inc(p);
'''':
begin
// skip string constant
inc(p);
while not (p^ in ['''',#0,#10,#13]) do inc(p);
if p^='''' then
inc(p);
end;
#0:
begin
// FPC allows that corresponding IFDEF and ENDIF are in different files
SrcPos:=p-PChar(Src)+1;
if (SrcPos>SrcLen) then begin
if not ReturnFromIncludeFile then begin
CopiedSrcPos:=SrcLen+1;
break;
end;
p:=@Src[SrcPos];
end else
inc(p);
end;
else
inc(p);
end;
end;
SrcPos:=p-PChar(Src)+1;
end else begin
CopiedSrcPos:=SrcLen+1;
end;
{$IFDEF ShowUpdateCleanedSrc}
DebugLn('TLinkScanner.SkipTillEndifElse B Continuing after: ',
' Src=',DbgStr(copy(Src,CommentStartPos-15,15))+'|'+DbgStr(copy(Src,CommentStartPos,15)));
{$ENDIF}
FSkippingDirectives:=lssdNone;
end;
procedure TLinkScanner.SetCompilerMode(const AValue: TCompilerMode);
var
OldModeSwitches, EnabledModeSwitches,
DisabledModeSwitches: TCompilerModeSwitches;
begin
if FCompilerMode=AValue then exit;
Values.Undefine(CompilerModeVars[FCompilerMode]);
FCompilerMode:=AValue;
OldModeSwitches:=FCompilerModeSwitches;
FCompilerModeSwitches:=DefaultCompilerModeSwitches[CompilerMode];
FNestedComments:=cmsNested_comment in CompilerModeSwitches;
Values.Variables[CompilerModeVars[FCompilerMode]]:='1';
EnabledModeSwitches:=FCompilerModeSwitches-OldModeSwitches;
DisabledModeSwitches:=OldModeSwitches-FCompilerModeSwitches;
if cmsDefault_unicodestring in EnabledModeSwitches then begin
Values.Variables['FPC_UNICODESTRINGS'] := '1';
Values.Variables['UNICODE'] := '1';
end else if cmsDefault_unicodestring in DisabledModeSwitches then begin
Values.Undefine('FPC_UNICODESTRINGS');
Values.Undefine('UNICODE');
end;
end;
procedure TLinkScanner.SetPascalCompiler(const AValue: TPascalCompiler);
begin
if FPascalCompiler=AValue then Exit;
FPascalCompiler:=AValue;
case PascalCompiler of
pcPas2js: ;
end;
end;
procedure TLinkScanner.SetDirectiveValueWithSequence(
ADirective: TSequenceDirective; const ADirectiveValue: string);
begin
Values.Variables[DirectiveSequenceName[ADirective]] := ADirectiveValue;
FDirectiveSequence.Add(ADirective, ADirectiveValue, FDirectiveCleanPos);
end;
function TLinkScanner.GetIgnoreMissingIncludeFiles: boolean;
begin
Result:=lssIgnoreMissingIncludeFiles in FStates;
end;
function TLinkScanner.InternalIfDirective: boolean;
// {$if expression} or {$ifc expression}
// or indirectly called by {$elifc expression} or {$elseif expression}
procedure RaiseMissingExpr;
begin
RaiseException(20170422130156,'missing expression');
end;
var
ExprResult: Boolean;
begin
//DebugLn(['TLinkScanner.InternalIfDirective FSkippingDirectives=',ord(FSkippingDirectives),' IfLevel=',IfLevel]);
inc(SrcPos);
if SrcPos>SrcLen then
RaiseMissingExpr;
ExprResult:=Values.EvalBoolean(@Src[SrcPos],CommentInnerEndPos-SrcPos);
Result:=true;
//DebugLn(['TLinkScanner.InternalIfDirective ExprResult=',ExprResult]);
if Values.ErrorPosition>=0 then begin
inc(SrcPos,Values.ErrorPosition);
RaiseException(20170422130200,Values.ErrorMsg)
end else if ExprResult then begin
// expression evaluates to true => stop skipping and parse block
if FDirectivesCount>0 then
FDirectives[FDirectivesCount-1].State:=lsdsActive;
if FSkippingDirectives<>lssdNone then begin
{$IFDEF ShowUpdateCleanedSrc}
debugln(['TLinkScanner.InternalIfDirective skipped front, using ELIFC part']);
{$ENDIF}
EndSkipping;
end;
end else begin
// expression evaluates to false => skip this block
SkipTillEndifElse(lssdTillElse);
end;
end;
procedure TLinkScanner.EndSkipping;
procedure ErrorNotSkipping;
begin
debugln(['ErrorNotSkipping internal error, please report this bug']);
CTDumpStack;
end;
var
Dir: PLSDirective;
begin
if FSkippingDirectives=lssdNone then begin
ErrorNotSkipping;
exit;
end;
FSkippingDirectives:=lssdNone;
UpdateCleanedSource(CommentStartPos-1);
AddSkipComment(false);
AddLink(CommentStartPos,Code);
//debugln(['TLinkScanner.EndSkipping ',StoreDirectives]);
if StoreDirectives then begin
// update cleaned position of directive
Dir:=@FDirectives[FDirectivesCount-1];
Dir^.CleanPos:=CleanedLen+1;
Dir^.State:=lsdsActive;
end;
FSkipIfLevel:=-1;
end;
function TLinkScanner.CursorToCleanPos(ACursorPos: integer; ACode: pointer;
out ACleanPos: integer): integer;
// 0=valid CleanPos
//-1=CursorPos was skipped, CleanPos is between two links
// 1=CursorPos beyond scanned code
// ACleanPos starts at 1
type
TLinkQuality = (qNone,qSkipped,qSkippedInFront,qDisabled,qClean);
var
i, BestCleanPos: integer;
Link: PSourceLink;
BestQuality: TLinkQuality;
LinkEnd: Integer;
Enabled: Boolean;
begin
Result:=1;
ACleanPos:=0;
if ACode=nil then exit;
i:=0;
BestQuality:=qNone;
BestCleanPos:=0;
Enabled:=true;
while i<LinkCount do begin
Link:=@FLinks[i];
if Link^.Kind=slkSkipStart then
Enabled:=false
else if Link^.Kind=slkSkipEnd then
Enabled:=true;
//DebugLn(['[TLinkScanner.CursorToCleanPos] A ACursorPos=',ACursorPos,', Code=',Link^.Code=ACode,', Link^.SrcPos=',Link^.SrcPos,', Link^.CleanedPos=',Link^.CleanedPos]);
if (Link^.Code=ACode) then begin
// link in same code found
if (Link^.SrcPos<=ACursorPos) then begin
ACleanPos:=ACursorPos-Link^.SrcPos+Link^.CleanedPos;
//DebugLn(['[TLinkScanner.CursorToCleanPos] Same code ACursorPos=',ACursorPos,', Code=',Link^.Code=ACode,', Link^.SrcPos=',Link^.SrcPos,', Link^.CleanedPos=',Link^.CleanedPos,' EndCleanPos=',Link^.CleanedPos+LinkSize(i)]);
LinkEnd:=LinkCleanedEndPos_Inline(i);
if ACleanPos<LinkEnd then begin
// link covers the cursor position
//debugln(['TLinkScanner.CursorToCleanPos Found LinkStartInSrc="',dbgstr(LinkSourceLog(i).Source,Link^.SrcPos,40),'" LinkStartInCleanSrc="',dbgstr(FCleanedSrc,Link^.CleanedPos,40),'" CursorSrc="',dbgstr(copy(LinkSourceLog(i).Source,ACursorPos-20,20)),'|',dbgstr(copy(LinkSourceLog(i).Source,ACursorPos,20)),'" CleanCursorSrc="',dbgstr(FCleanedSrc,ACleanPos-20,20),'|',dbgstr(FCleanedSrc,ACleanPos,20),'"']);
if Enabled then begin
exit(0); // position in parsed code
end else begin
// position in disabled code
// Note: maybe this include file was parsed a second time and the
// position is then enabled => save position and continue search
if BestQuality<qDisabled then begin
BestQuality:=qDisabled;
BestCleanPos:=ACleanPos;
end;
end;
end else begin
// link is in front of the cursor
if BestQuality<=qSkipped then begin
// remember last link in front
BestQuality:=qSkipped;
BestCleanPos:=LinkEnd;
end;
end;
end else begin
// link is behind cursor
if BestQuality=qSkipped then begin
// the cursor lies in between two links
BestQuality:=qSkippedInFront;
end;
end;
end;
inc(i);
end;
ACleanPos:=BestCleanPos;
if (BestQuality=qSkippedInFront) and (ACleanPos<=CleanedLen) then begin
// cursor position lies between two links
Result:=-1;
end else if BestQuality=qDisabled then begin
// cursor position lies in disabled code (in the special comment #3)
Result:=0;
end else
Result:=1; // default: CursorPos beyond/outside scanned code
end;
function TLinkScanner.CleanedPosToCursor(ACleanedPos: integer; out
ACursorPos: integer; out ACode: Pointer): boolean;
procedure ConsistencyCheckI(i: integer);
begin
raise Exception.Create(
'TLinkScanner.CleanedPosToCursor Consistency-Error '+IntToStr(i));
end;
procedure ConsistencyCheckStart;
begin
raise Exception.Create(
'TLinkScanner.CleanedPosToCursor Consistency-Error no start link with code found');
end;
procedure Found(LinkID: integer);
begin
ACode:=FLinks[LinkID].Code;
if ACode=nil then begin
repeat
dec(LinkID);
if LinkID<0 then
ConsistencyCheckStart;
ACode:=FLinks[LinkID].Code;
until ACode<>nil;
end;
ACursorPos:=ACleanedPos-FLinks[LinkID].CleanedPos+FLinks[LinkID].SrcPos;
end;
var l,r,m: integer;
begin
Result:=(ACleanedPos>=1) and (ACleanedPos<=CleanedLen);
if Result then begin
// ACleanedPos in Cleaned Code -> binary search through the links
l:=0;
r:=LinkCount-1;
while l<=r do begin
m:=(l+r) div 2;
if m<LinkCount-1 then begin
if ACleanedPos<FLinks[m].CleanedPos then
r:=m-1
else if ACleanedPos>=FLinks[m+1].CleanedPos then
l:=m+1
else begin
Found(m);
exit;
end;
end else begin
if ACleanedPos>=FLinks[m].CleanedPos then begin
Found(m);
exit;
end else
ConsistencyCheckI(2);
end;
end;
ConsistencyCheckI(1);
end;
ACode:=nil;
ACursorPos:=0;
end;
function TLinkScanner.CleanedPosToStr(ACleanedPos: integer): string;
var
p: integer;
ACode: Pointer;
begin
if CleanedPosToCursor(ACleanedPos,p,ACode) then begin
Result:=TSourceLog(ACode).AbsoluteToLineColStr(p);
end else begin
Result:='p='+IntToStr(ACleanedPos)+',y=?,x=?';
end;
end;
function TLinkScanner.WholeRangeIsWritable(CleanStartPos, CleanEndPos: integer;
ErrorOnFail: boolean): boolean;
procedure EditError(const AMessage: string; ACode: Pointer);
begin
if ErrorOnFail then
RaiseEditException(20170422130202,AMessage,ACode,0);
end;
var
ACode: Pointer;
LinkIndex: integer;
CodeIsReadOnly: boolean;
begin
Result:=false;
if (CleanStartPos<1) or (CleanStartPos>=CleanEndPos)
or (CleanEndPos>CleanedLen+1) or (not Assigned(FOnGetSourceStatus)) then begin
EditError('TLinkScanner.WholeRangeIsWritable: Invalid range',nil);
exit;
end;
LinkIndex:=LinkIndexAtCleanPos(CleanStartPos);
if LinkIndex<0 then begin
EditError('TLinkScanner.WholeRangeIsWritable: position out of scan range',nil);
exit;
end;
ACode:=FLinks[LinkIndex].Code;
CodeIsReadOnly:=false;
FOnGetSourceStatus(Self,ACode,CodeIsReadOnly);
if CodeIsReadOnly then begin
EditError(ctsfileIsReadOnly, ACode);
exit;
end;
repeat
inc(LinkIndex);
if (LinkIndex>=LinkCount) or (FLinks[LinkIndex].CleanedPos>CleanEndPos) then
begin
Result:=true;
exit;
end;
if ACode<>FLinks[LinkIndex].Code then begin
ACode:=FLinks[LinkIndex].Code;
if ACode<>nil then begin
FOnGetSourceStatus(Self,ACode,CodeIsReadOnly);
if CodeIsReadOnly then begin
EditError(ctsfileIsReadOnly, ACode);
exit;
end;
end;
end;
until false;
end;
procedure TLinkScanner.FindCodeInRange(CleanStartPos, CleanEndPos: integer;
UniqueSortedCodeList: TFPList);
var ACode: Pointer;
LinkIndex: integer;
Link: PSourceLink;
begin
if (CleanStartPos<1) or (CleanStartPos>CleanEndPos)
or (CleanEndPos>CleanedLen+1) or (UniqueSortedCodeList=nil) then exit;
LinkIndex:=LinkIndexAtCleanPos(CleanStartPos);
if LinkIndex<0 then exit;
ACode:=FLinks[LinkIndex].Code;
if ACode<>nil then
AddCodeToUniqueList(ACode,UniqueSortedCodeList);
repeat
inc(LinkIndex);
if (LinkIndex>=LinkCount) then
exit;
Link:=@FLinks[LinkIndex];
if (Link^.CleanedPos>CleanEndPos) then
exit;
if (ACode<>Link^.Code) then begin
ACode:=Link^.Code;
if ACode<>nil then
AddCodeToUniqueList(ACode,UniqueSortedCodeList);
end;
until false;
end;
procedure TLinkScanner.DeleteRange(CleanStartPos,CleanEndPos: integer);
{ delete all code in links (=parsed code) starting with the last link
before you call this, test with WholeRangeIsWritable
this can do unexpected things if
- include files are included twice
- compiler directives like IFDEF - ENDIF are partially destroyed
ToDo: keep include directives
}
var
LinkIndex, StartPos, Len, aLinkSize: integer;
ACode: Pointer;
begin
if CleanStartPos<1 then CleanStartPos:=1;
if CleanEndPos>CleanedLen then CleanEndPos:=CleanedLen+1;
if (CleanStartPos>=CleanEndPos) or (not Assigned(FOnDeleteSource)) then exit;
LinkIndex:=LinkIndexAtCleanPos(CleanEndPos-1);
//debugln(['TLinkScanner.DeleteRange CleanStartPos=',CleanStartPos,' CleanEndPos=',CleanEndPos,' LinkIndex=',LinkIndex]);
while LinkIndex>=0 do begin
StartPos:=CleanStartPos-FLinks[LinkIndex].CleanedPos;
if StartPos<0 then StartPos:=0;
aLinkSize:=LinkSize(LinkIndex);
//debugln(['TLinkScanner.DeleteRange LinkIndex=',LinkIndex,' aLinkSize=',aLinkSize,' StartPosInLink=',StartPos]);
Len:=CleanEndPos-FLinks[LinkIndex].CleanedPos;
if Len>aLinkSize then Len:=aLinkSize;
dec(Len,StartPos);
inc(StartPos,FLinks[LinkIndex].SrcPos);
//DebugLn(['[TLinkScanner.DeleteRange] Pos=',StartPos,'-',StartPos+Len,' ',dbgstr(copy(Src,StartPos,Len))]);
ACode:=FLinks[LinkIndex].Code;
if ACode<>nil then
FOnDeleteSource(Self,ACode,StartPos,Len);
if FLinks[LinkIndex].CleanedPos<=CleanStartPos then break;
dec(LinkIndex);
end;
end;
procedure TLinkScanner.ActivateGlobalWriteLock;
begin
if Assigned(OnSetGlobalWriteLock) then OnSetGlobalWriteLock(true);
end;
procedure TLinkScanner.DeactivateGlobalWriteLock;
begin
if Assigned(OnSetGlobalWriteLock) then OnSetGlobalWriteLock(false);
end;
procedure TLinkScanner.RaiseExceptionFmt(id: int64; const AMessage: string;
const Args: array of const);
begin
RaiseException(id,Format(AMessage,args));
end;
procedure TLinkScanner.RaiseException(id: int64; const AMessage: string);
begin
RaiseExceptionClass(id,AMessage,ELinkScannerError);
end;
procedure TLinkScanner.RaiseExceptionClass(id: int64; const AMessage: string;
ExceptionClass: ELinkScannerErrors);
begin
LastErrorMessage:=AMessage;
LastErrorSrcPos:=SrcPos;
LastErrorCode:=Code;
LastErrorCheckedForIgnored:=false;
LastErrorId:=id;
LastErrorIsValid:=true;
raise ExceptionClass.Create(Self,id,AMessage);
end;
procedure TLinkScanner.RaiseEditException(id: int64; const AMessage: string;
ABuffer: Pointer; ABufferPos: integer);
begin
raise ELinkScannerEditError.Create(Self,id,AMessage,ABuffer,ABufferPos);
end;
procedure TLinkScanner.RaiseConsistencyException(id: int64;
const AMessage: string);
begin
RaiseExceptionClass(id,AMessage,ELinkScannerConsistency);
end;
procedure TLinkScanner.ClearLastError;
begin
LastErrorIsValid:=false;
LastErrorCheckedForIgnored:=false;
end;
procedure TLinkScanner.RaiseLastError;
begin
SrcPos:=LastErrorSrcPos;
Code:=LastErrorCode;
RaiseException(20170422130205,LastErrorMessage);
end;
procedure TLinkScanner.DoCheckAbort;
begin
if not Assigned(OnProgress) then exit;
if OnProgress(Self) then exit;
// raise abort exception
RaiseExceptionClass(20170422130207,'Abort',ELinkScannerAbort);
end;
function TLinkScanner.MainFilename: string;
begin
if Assigned(OnGetFileName) and (FMainCode<>nil) then
Result:=OnGetFileName(Self,FMainCode)
else
Result:='';
end;
{ ELinkScannerError }
constructor ELinkScannerError.Create(ASender: TLinkScanner; TheId: int64;
const AMessage: string);
begin
inherited Create(AMessage);
Sender:=ASender;
id:=TheId;
end;
{ TPSourceLinkMemManager }
procedure TPSourceLinkMemManager.FreeFirstItem;
var Link: PSourceLink;
begin
Link:=PSourceLink(FFirstFree);
PSourceLink(FFirstFree):=Link^.Next;
Dispose(Link);
end;
procedure TPSourceLinkMemManager.DisposePSourceLink(Link: PSourceLink);
begin
if (FFreeCount<FMinFree) or (FFreeCount<((FCount shr 3)*FMaxFreeRatio)) then
begin
// add Link to Free list
FillChar(Link^,SizeOf(TSourceLink),0);
Link^.Next:=PSourceLink(FFirstFree);
PSourceLink(FFirstFree):=Link;
inc(FFreeCount);
end else begin
// free list full -> free Link
Dispose(Link);
{$IFDEF DebugCTMemManager}
inc(FFreedCount);
{$ENDIF}
end;
dec(FCount);
end;
function TPSourceLinkMemManager.NewPSourceLink: PSourceLink;
begin
if FFirstFree<>nil then begin
// take from free list
Result:=PSourceLink(FFirstFree);
PSourceLink(FFirstFree):=Result^.Next;
Result^.Next:=nil;
dec(FFreeCount);
end else begin
// free list empty -> create new PSourceLink
New(Result);
FillChar(Result^,SizeOf(TSourceLink),0);
{$IFDEF DebugCTMemManager}
inc(FAllocatedCount);
{$ENDIF}
end;
inc(FCount);
end;
{ TPSourceChangeStep }
procedure TPSourceChangeStepMemManager.FreeFirstItem;
var Step: PSourceChangeStep;
begin
Step:=PSourceChangeStep(FFirstFree);
PSourceChangeStep(FFirstFree):=Step^.Next;
Dispose(Step);
end;
procedure TPSourceChangeStepMemManager.DisposePSourceChangeStep(
Step: PSourceChangeStep);
begin
if (FFreeCount<FMinFree) or (FFreeCount<((FCount shr 3)*FMaxFreeRatio)) then
begin
// add Link to Free list
FillChar(Step^,SizeOf(TSourceChangeStep),0);
Step^.Next:=PSourceChangeStep(FFirstFree);
PSourceChangeStep(FFirstFree):=Step;
inc(FFreeCount);
end else begin
// free list full -> free Step
Dispose(Step);
{$IFDEF DebugCTMemManager}
inc(FFreedCount);
{$ENDIF}
end;
dec(FCount);
end;
function TPSourceChangeStepMemManager.NewPSourceChangeStep: PSourceChangeStep;
begin
if FFirstFree<>nil then begin
// take from free list
Result:=PSourceChangeStep(FFirstFree);
PSourceChangeStep(FFirstFree):=Result^.Next;
Result^.Next:=nil;
dec(FFreeCount);
end else begin
// free list empty -> create new PSourceChangeStep
New(Result);
FillChar(Result^,SizeOf(TSourceChangeStep),0);
{$IFDEF DebugCTMemManager}
inc(FAllocatedCount);
{$ENDIF}
end;
inc(FCount);
end;
{ TMissingIncludeFile }
constructor TMissingIncludeFile.Create(const AFilename, AIncludePath: string);
begin
inherited Create;
Filename:=AFilename;
IncludePath:=AIncludePath;
end;
function TMissingIncludeFile.CalcMemSize: PtrUInt;
begin
Result:=PtrUInt(InstanceSize)
+MemSizeString(IncludePath)
+MemSizeString(Filename);
end;
{ TMissingIncludeFiles }
function TMissingIncludeFiles.GetIncFile(Index: Integer): TMissingIncludeFile;
begin
Result:=TMissingIncludeFile(Get(Index));
end;
procedure TMissingIncludeFiles.SetIncFile(Index: Integer;
const AValue: TMissingIncludeFile);
begin
Put(Index,AValue);
end;
procedure TMissingIncludeFiles.Clear;
var i: integer;
begin
for i:=0 to Count-1 do Items[i].Free;
inherited Clear;
end;
procedure TMissingIncludeFiles.Delete(Index: Integer);
begin
Items[Index].Free;
inherited Delete(Index);
end;
function TMissingIncludeFiles.CalcMemSize: PtrUInt;
var
i: Integer;
begin
Result:=PtrUInt(InstanceSize)
+SizeOf(Pointer)*PtrUInt(Capacity);
for i:=0 to Count-1 do
inc(Result,Items[i].CalcMemSize);
end;
//------------------------------------------------------------------------------
procedure InternalInit;
var
CompMode: TCompilerMode;
begin
for CompMode:=Low(TCompilerMode) to High(TCompilerMode) do
CompilerModeVars[CompMode]:='FPC_'+CompilerModeNames[CompMode];
PSourceLinkMemManager:=TPSourceLinkMemManager.Create;
PSourceChangeStepMemManager:=TPSourceChangeStepMemManager.Create;
end;
procedure InternalFinal;
begin
PSourceChangeStepMemManager.Free;
PSourceLinkMemManager.Free;
end;
{ ELinkScannerEditError }
constructor ELinkScannerEditError.Create(ASender: TLinkScanner; TheId: int64;
const AMessage: string; ABuffer: Pointer; ABufferPos: integer);
begin
inherited Create(ASender,TheId,AMessage);
Buffer:=ABuffer;
BufferPos:=ABufferPos;
end;
initialization
InternalInit;
finalization
InternalFinal;
end.
|