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
|
unit LexicalTools;
// Copyright (C) 2003, 2004 MySQL AB
//
// This program 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 program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//----------------------------------------------------------------------------------------------------------------------
//
// Description:
// This unit contains general purpose classes for lexical tasks like tokenizing text.
//
// Initial implementor:
// 2004 Mike Lischke
//
//----------------------------------------------------------------------------------------------------------------------
//
interface
{$I Compilers.inc}
uses
Windows, Classes, Unicode;
const
LexerBufferSize = 32768;
// Tokens returned to caller when processing text.
toEOF = WideChar(0);
toBOF = WideChar(1); // set if the lexer has not yet read the first token
toSymbol = WideChar(2);
toString = WideChar(3);
toInteger = WideChar(4);
toFloat = WideChar(5);
toHexNumber = WideChar(6);
toWhiteSpace = WideChar(7);
toSLComment = WideChar(8);
toMLComment = WideChar(9);
toUserVariable = WideChar(10);
toSystemVariable = WideChar(11);
tohexString = WideChar(12); // A string containing hex numbers, preceded by a single 'x'.
type
// TDelphiLexer is a class to quickly split input into tokens while automatically skipping
// comments or conditional code if necessary.
TDelphiLexer = class;
TNewLineEvent = procedure(Sender: TObject; Line: Cardinal) of object;
TLexerErrorEvent = procedure(Pos: TPoint; const Error: WideString) of object;
// This class is used to tokenize Delphi source code like text.
TDelphiLexer = class(TObject)
private
FStream: TStream;
FOrigin: Integer;
FBuffer: PWideChar;
FBufPtr: PWideChar;
FBufEnd: PWideChar;
FSourcePtr: PWideChar;
FSourceEnd: PWideChar;
FTokenPtr: PWideChar;
FLineStart: PWideChar;
FSourceLine: Cardinal;
FSaveChar: WideChar;
FToken: WideChar;
FFloatType: WideChar;
FTokenString: WideString;
FIsUnicode,
FNeedSwap: Boolean;
FDefines: TWideStringList; // Currently defined compiler symbols.
FCompilerSwitch: array[0..25] of Boolean; // One entry for each letter from 'a' to 'z'.
FOnNewLine: TNewLineEvent;
FOnLexerError: TLexerErrorEvent;
procedure AdvanceSource(Amount: Cardinal = 1);
function GetCompilerOption(Option: Char): Boolean;
function GetToken: WideChar;
procedure HandleDirective(UseStar: Boolean);
function NeedChars(Count: Cardinal): Boolean;
procedure ReadBuffer;
procedure SkipConditionalPart(WithElse: Boolean);
function ScanIdentifier: WideString;
procedure SetCompilerOption(Option: Char; const Value: Boolean);
procedure SetDefines(const Value: TWideStringList);
procedure SkipBlanks;
procedure SkipComments;
procedure SkipLine;
procedure SkipString;
procedure SkipToDirectiveEnd(UseStar: Boolean);
procedure SkipToEndIf;
procedure SkipToElseOrEndIf;
procedure SkipUntil(S: WideString);
protected
procedure DoNewLine;
public
constructor Create(Stream: TStream; IsUnicode: Boolean);
destructor Destroy; override;
procedure CheckToken(T: WideChar);
procedure CheckTokenSymbol(const S: WideString);
procedure LexerError(const Message: WideString);
procedure HexToBinary(Stream: TStream);
function NextToken: WideChar;
procedure ShowToken(Token: WideChar);
function SourcePos: Integer;
function TokenComponentIdent: WideString;
function TokenFloat: Extended;
function TokenInteger: Integer;
function TokenInt64: Int64;
function TokenString: WideString;
function TokenSymbolIs(const S: WideString): Boolean;
property CompilerOption[Option: Char]: Boolean read GetCompilerOption write SetCompilerOption;
property Defines: TWideStringList read FDefines write SetDefines;
property FloatType: WideChar read FFloatType;
property SourceLine: Cardinal read FSourceLine;
property Token: WideChar read GetToken;
property OnNewLine: TNewLineEvent read FOnNewLine write FOnNewLine;
property OnLexerError: TLexerErrorEvent read FOnLexerError write FOnLexerError;
end;
// A lexer to tokenize SQL text. This class is very similar to the Delphi lexer but without any support
// for conditional parts. It can only handle text encoded as UTF-16 (LE and BE).
TSQLLexer = class
private
FStream: TStream;
FOrigin: Integer;
FBuffer: PWideChar;
FBufPtr: PWideChar;
FBufEnd: PWideChar;
FSourcePtr: PWideChar;
FSourceEnd: PWideChar;
FTokenPtr: PWideChar;
FLineStart: PWideChar;
FSourceLine: Cardinal;
FSaveChar: WideChar;
FToken: WideChar;
FFloatType: WideChar;
FNeedSwap: Boolean;
FOnNewLine: TNewLineEvent;
FOnLexerError: TLexerErrorEvent;
protected
procedure AdvanceSource(Amount: Cardinal = 1); virtual;
procedure DoNewLine; virtual;
function GetToken: WideChar; virtual;
function NeedChars(Count: Cardinal): Boolean;
procedure ReadBuffer; virtual;
procedure SkipBlanks; virtual;
procedure SkipComments; virtual;
procedure SkipLine; virtual;
procedure SkipUntil(S: WideString); virtual;
public
constructor Create(Stream: TStream); virtual;
destructor Destroy; override;
procedure CheckToken(T: WideChar);
procedure CheckTokenSymbol(const S: WideString);
function NextToken: WideChar;
function ScanRawText: WideString;
function TokenFloat: Extended;
function TokenInteger: Integer;
function TokenInt64: Int64;
function TokenString: WideString;
function TokenSymbolIs(const S: WideString): Boolean;
procedure LexerError(const Message: WideString);
property FloatType: WideChar read FFloatType;
property SourceLine: Cardinal read FSourceLine;
property Token: WideChar read GetToken;
property OnNewLine: TNewLineEvent read FOnNewLine write FOnNewLine;
property OnLexerError: TLexerErrorEvent read FOnLexerError write FOnLexerError;
end;
// The tokenizer state tells where the tokenizer left of the last run. States other than tsNormal are usually
// used if the input was exhausted but the token was not finished.
TTokenizerState = (
tsNormal,
tsSingleQuoteString,
tsBackQuoteString,
tsDoubleQuoteString,
tsComment
);
// This class is similar to the TSQLLexer but returns any encountered token (e.g. line breaks, spaces, comments
// etc. are not simply skipped). It does not throw any error (except for wrong data conversions).
TSQLTokenizer = class
private
FStream: TStream;
FOrigin: Integer;
FBuffer: array[0..LexerBufferSize] of WideChar;
FBufPtr: PWideChar;
FBufEnd: PWideChar;
FSourcePtr: PWideChar;
FSourceEnd: PWideChar;
FTokenPtr: PWideChar;
FLineStart: PWideChar;
FSourceLine: Cardinal;
FToken: WideChar;
FFloatType: WideChar;
FNeedSwap: Boolean;
FState: TTokenizerState;
protected
function AdvanceSource(Amount: Cardinal = 1): Boolean; virtual;
function GetToken: WideChar; virtual;
function NeedChars(Count: Cardinal): Boolean;
procedure ReadBuffer; virtual;
public
function NextToken: WideChar;
procedure Initialize(Stream: TStream; State: TTokenizerState);
function SourcePosition: Integer;
function TokenFloat: Extended;
function TokenInteger: Integer;
function TokenInt64: Int64;
function TokenPosition: Integer;
function TokenString: WideString;
function TokenSymbolIs(const S: WideString): Boolean;
property FloatType: WideChar read FFloatType;
property SourceLine: Cardinal read FSourceLine;
property State: TTokenizerState read FState;
property Token: WideChar read GetToken;
end;
// Hash trie implementation.
const
// LeafSize must be 256. No changes allowed.
LeafSize = 256;
// BucketSize determines max length of the list. Very big|small values decrease performance, while
// the optimum value in range 4..16.
BucketSize = 8;
type
THashLinkedItem = class(TObject)
private
FValue: Cardinal;
FData: Pointer;
FNext: THashLinkedItem;
public
constructor Create(Value: Cardinal; Data: Pointer; Next: THashLinkedItem);
destructor Destroy; override;
end;
THashTrie = class;
TTraverseProc = procedure(UserData, UserProc: Pointer; Value: Cardinal; Data: Pointer; var Done: Boolean) of object;
THashTreeItem = class(TObject)
private
FOwner: THashTrie;
FLevel: Integer;
FFilled: Integer;
FItems: array of TObject; // This will be at most LeafSize entries.
protected
procedure AddDown(Value, Hash: Cardinal; const Data: Pointer);
procedure Delete(Value, Hash: Cardinal);
function Find(Value, Hash: Cardinal; var Data: Pointer): Boolean;
function GetFilled: Integer;
function Modify(Value, Hash: Cardinal; const Data: Pointer): Boolean;
function ROR(Value: Cardinal): Cardinal;
function RORN(Value: Cardinal; Level: Integer): Cardinal;
function Traverse(UserData, UserProc: Pointer; TraverseProc: TTraverseProc): Boolean;
public
constructor Create(AOwner: THashTrie);
destructor Destroy; override;
procedure Clear;
end;
THashTrie = class(TObject)
private
FRoot: THashTreeItem;
function GetCount: Integer;
protected
procedure AddDown(Value, Hash: Cardinal; const Data: Pointer);
function CompareValue(Value1, Value2: Cardinal): Boolean; virtual; abstract;
procedure Delete(Value, Hash: Cardinal);
procedure DestroyItem(var Value: Cardinal; var Data: Pointer); virtual; abstract;
function HashValue(Value: Cardinal): Cardinal; virtual; abstract;
procedure Traverse(UserData, UserProc: Pointer; TraverseProc: TTraverseProc);
public
constructor Create; virtual;
destructor Destroy; override;
procedure Clear;
function Find(Value, Hash: Cardinal; var Data: Pointer): Boolean; overload;
property Count: Integer read GetCount;
end;
TStringHashTrie = class;
TStrHashTraverseProc = procedure(UserData: Pointer; const Value: string; Data: Pointer; var Done: Boolean);
TStrHashTraverseMeth = procedure(UserData: Pointer; const Value: string; Data: Pointer; var Done: Boolean) of object;
TSHTFreeItemEvent = procedure(Sender: TStringHashTrie; const S: string; const Data: Pointer) of object;
TStringHashTrie = class(THashTrie)
private
FCaseSensitive: Boolean;
FOnFreeItem: TSHTFreeItemEvent;
protected
function HashValue(Value: Cardinal): Cardinal; override;
procedure DestroyItem(var Value: Cardinal; var Data: Pointer); override;
function CompareValue(Value1, Value2: Cardinal): Boolean; override;
function HashStr(const S: string): Cardinal;
procedure TraverseProc(UserData, UserProc: Pointer; Value: Cardinal; Data: Pointer; var Done: Boolean);
procedure TraverseMeth(UserData, UserProc: Pointer; Value: Cardinal; Data: Pointer; var Done: Boolean);
public
procedure Add(const S: string; const Data: Pointer);
procedure Delete(const S: string);
function Find(const S: string; var Data: Pointer): Boolean; overload;
procedure Traverse(UserData: Pointer; UserProc: TStrHashTraverseProc); overload;
procedure Traverse(UserData: Pointer; UserProc: TStrHashTraverseMeth); overload;
property CaseSensitive: Boolean read FCaseSensitive write FCaseSensitive default False;
property OnFreeItem: TSHTFreeItemEvent read FOnFreeItem write FOnFreeItem;
end;
// Support for trie statistics.
TLengthStatistics = array[1..BucketSize] of Integer;
function CalcStrCRC32(const S: string): Cardinal;
function JHash(Key: Pointer; Length, InitVal: Cardinal): Cardinal;
procedure TrieStatistics(Trie: THashTrie; var MaxLevel, PeakCount, FillCount, EmptyCount: Integer;
var LengthStatistics: TLengthStatistics);
procedure BinToHex(Buffer: Pointer; Text: PWideChar; BufSize: Integer);
function HexToBin(Text: PWideChar; Buffer: Pointer; BufSize: Integer): Integer;
//----------------------------------------------------------------------------------------------------------------------
implementation
uses
{$ifdef Compiler_6_UP}
RTLConsts,
{$else}
Consts,
{$endif Compiler_6_UP}
SysUtils, Math, Variants;
resourcestring
SUnexpectedEOF = 'Unexpected end of file';
SInvalidDirective = 'Invalid compiler directive.';
SDacapoXMLErrorUnknown = 'Invalid input found';
SDacapoXMLInvalidTag = 'Invalid tag found';
SDacapoXMLUnmatchedStartTag = 'End tag does not match start tag';
SDacapoXMLInvalidAttribute = 'Invalid attribute format';
SDacapoXMLStringExpected = 'String expected but quote character is missing';
SDacapoXMLUnfinishedString = 'Unexpected end of string found';
SDacapoXMLInvalidNumber = 'Invalid number';
SDacapoXMLInvalidEntity = 'Invalid entity';
SDacapoXMLSpaceMissing = 'Required space character is missing';
// HTML/XML entities, taken from http://www.w3.org/TR/REC-html40/sgml/entities.html.
type
TEntity = record
Name: string;
Value: WideChar;
end;
const
// Delphi directives.
DirectiveStrings: array[0..50] of string = (
'ifdef', 'ifndef', 'define', 'undef', 'else', 'endif', 'ifopt', 'nodefine',
'align', 'apptype', 'assertions', 'booleval', 'debuginfo', 'denypackageunit', 'description',
'designonly', 'objexportall', 'extendedsyntax', 'externalsym', 'hints', 'hppemit', 'implicitbuild',
'importeddata', 'imagebase', 'include', 'iochecks', 'link', 'localsymbols', 'longstrings', 'minstacksize',
'maxstacksize', 'minenumsize', 'openstrings', 'optimization', 'overflowchecks', 'savedivide', 'noinclude',
'rangechecks', 'realcompatibility', 'resource', 'runonly', 'typeinfo', 'referenceinfo', 'definitioninfo',
'typedaddress', 'varstringchecks', 'warnings', 'weakpackageunit', 'stackframes', 'writableconst', 'warn'
);
// Mapping of a directive string to a one letter compiler switch.
// Note: small letters are used here instead capital letters to indicate the conversion
// (need to look for on/off keyword)
DirectiveToSwitch: array[0..50] of Integer = (
0, 1, 2, 3, 4, 5, 6, 7, // ifdef ... nodefine
Ord('a'),
9,
Ord('c'), // assertions
Ord('b'), // booleval
Ord('d'), // debuginfo
13, 14, 15, 16, // denypackageunit .. objexportall
Ord('x'), // extendedsyntax
18, 19, 20, 21, // externalsym .. implicitbuild
Ord('g'), // importeddata
23, 24, // imagebase .. include
Ord('i'), // iochecks
26, // link
Ord('l'), // localsymbols
Ord('h'), // longstrings
29, 30, 31, // minstacksize .. minenumsize
Ord('p'), // openstrings
Ord('o'), // optimization
Ord('q'), // overflowchecks
Ord('u'), // savedivide',
36, // noinclude
Ord('r'), // rangechecks
38, 39, 40, // realcompatibility .. runonly
Ord('m'), // typeinfo
Ord('y'), // referenceinfo
43, // definitioninfo
Ord('t'), // typedaddress
Ord('v'), // varstringchecks
46, 47, // warnings .. weakpackageunit
Ord('w'), // stackframes
Ord('j'), // writableconst
48 // warn
);
var
Directives: TStringList;
//----------------------------------------------------------------------------------------------------------------------
procedure InitializeDirectives;
var
I: Integer;
begin
// Prepare an internal list of directive strings to make converting them into IDs quick.
Directives := TStringList.Create;
// The object property of each entry is used to hold an ID to be returned from the search code.
for I := 0 to 50 do
Directives.AddObject(DirectiveStrings[I], Pointer(DirectiveToSwitch[I]));
Directives.Sort;
end;
//----------------------------------------------------------------------------------------------------------------------
const
CRC32_POLYNOMIAL = $EDB88320;
var
// Dynamic crc32 table.
CCITT32Table: array of Cardinal;
procedure BuildCRCTable;
var
i, j: longint;
value: Cardinal;
begin
SetLength(CCITT32Table, 256);
for i := 0 to 255 do begin
value := i;
for j := 8 downto 1 do
if ((value and 1) <> 0) then
value := (value shr 1) xor CRC32_POLYNOMIAL
else
value := value shr 1;
Ccitt32Table[i] := value;
end
end;
//----------------------------------------------------------------------------------------------------------------------
function CalcStrCRC32(const S: string): Cardinal;
var
I: Integer;
begin
// Create CRC table if not yet done.
if CCITT32Table = nil then
BuildCRCTable;
Result := $FFFFFFFF;
for I:=1 to Length(S) do
Result:= (((Result shr 8) and $00FFFFFF) xor (CCITT32Table[(Result xor Byte(S[I])) and $FF]));
end;
//----------------------------------------------------------------------------------------------------------------------
// By Bob Jenkins, 1996. bob_jenkins@burtleburtle.net
//
// If you are hashing n strings (ub1 **)k, do it like this:
// for (i=0, h=0; i<n; ++i) h = jhash( k[i], len[i], h);
procedure Mix(var A, B, C: Cardinal);
begin
Dec(A, B); Dec(A, C); A := A xor (C shr 13);
Dec(B, C); Dec(B, A); B := A xor (A shl 8);
Dec(C, A); Dec(C, B); C := C xor (B shr 13);
Dec(A, B); Dec(A, C); A := A xor (C shr 12);
Dec(B, C); Dec(B, A); B := B xor (A shl 16);
Dec(C, A); Dec(C, B); C := C xor (B shr 5);
Dec(A, B); Dec(A, C); A := A xor (C shr 3);
Dec(B, C); Dec(B, A); B := B xor (A shl 10);
Dec(C, A); Dec(C, B); C := C xor (B shr 15);
end;
//----------------------------------------------------------------------------------------------------------------------
function JHash(Key: Pointer; Length, InitVal: Cardinal): Cardinal;
// Length: the length of the key.
// InitVal: the previous hash, or an arbitrary value.
var
A, B, C, Len: Cardinal;
K: PByteArray;
begin
// Set up the internal state.
Len := Length;
K := Key;
A := $9E3779B9; // The golden ratio; an arbitrary value.
B := $9E3779B9;
C := InitVal; // The previous hash value.
// Handle most of the key.
while Len >= 12 do
begin
Inc(A, K[0] + (Cardinal(K[1]) shl 8) + (Cardinal(K[2]) shl 16) + (Cardinal(K[3]) shl 24));
Inc(B, K[4] +(Cardinal(K[5]) shl 8) + (Cardinal(K[6]) shl 16) + (Cardinal(K[7]) shl 24));
Inc(C, K[8] + (Cardinal(K[9]) shl 8) + (Cardinal(K[10]) shl 16) + (Cardinal(K[11]) shl 24));
Mix(A, B, C);
Inc(PByte(K), 12);
Dec(Len, 12);
end;
// Handle the last 11 bytes.
Inc(C, Length);
if Len >= 11 then
Inc(C, Cardinal(K[10]) shl 24);
if Len >= 10 then
Inc(C, Cardinal(K[9]) shl 16);
if Len >= 9 then
Inc(C, Cardinal(K[8]) shl 8);
if Len >= 8 then
Inc(B, Cardinal(K[7]) shl 24);
if Len >= 7 then
Inc(B, Cardinal(K[6]) shl 16);
if Len >= 6 then
Inc(B, Cardinal(K[5]) shl 8);
if Len >= 5 then
Inc(B, Cardinal(K[4]));
if Len >= 4 then
Inc(A, Cardinal(K[3]) shl 24);
if Len >= 3 then
Inc(A, Cardinal(K[2]) shl 16);
if Len >= 2 then
Inc(A, Cardinal(K[1]) shl 8);
if Len >= 1 then
Inc(A, Cardinal(K[0]));
// Case 0: nothing left to add.
Mix(A, B, C);
Result := C;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure BinToHex(Buffer: Pointer; Text: PWideChar; BufSize: Integer);
// converts a stream of byte values into a hexadecimal text representation
// EAX contains Buffer, EDX contains Text and ECX contains BufSize on enter
// Note: BufSize gives the source size in bytes. Text must be able to keep twice this amount,
// because each source byte will be converted into two hex digits.
asm
PUSH ESI
PUSH EDI
MOV ESI, EAX
MOV EDI, EDX
XOR EDX, EDX
JMP @@1
@@0:
DB '0123456789ABCDEF'
@@1:
LODSB
MOV DL, AL
AND AL, 0FH
MOV AL, @@0.Byte[EAX]
STOSW
MOV AL, DL
SHR AL, 4
MOV AL, @@0.Byte[EAX]
STOSW
DEC ECX
JNE @@1
POP EDI
POP ESI
end;
//----------------------------------------------------------------------------------------------------------------------
function HexToBin(Text: PWideChar; Buffer: Pointer; BufSize: Integer): Integer;
// although this procedure takes a wide string as parameter it can still only convert values within the ANSI range
// EAX contains Text, EDX contains Buffer and ECX contains BufSize on enter
// Note: It will twice as much input consumed as given in BufSize which denotes the amount of bytes
// which can be stored into Buffer.
// Return value is the number of bytes written to Buffer.
asm
PUSH ESI
PUSH EDI
PUSH EBX
MOV ESI, EAX
MOV EDI, EDX
MOV EBX, EDX
XOR EDX, EDX
XOR EAX, EAX
JMP @@1
@@0:
DB 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1
DB -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1
DB -1, -1, -1, -1,- 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
DB -1, 10, 11, 12, 13, 14, 15
@@1:
LODSW
CMP AX, '0' // check for 0..F range
JB @@2
CMP AX, 'f'
JA @@2
MOV DL, @@0.Byte[EAX - '0'] // keep converted value,
CMP DL, -1 // but stop conversion if the value is invalid
JE @@2
SHL DL, 4
LODSW // load second (we can store two digits into one byte)
CMP AX, '0'
JB @@2
CMP AX, 'f'
JA @@2
MOV DH, @@0.Byte[EAX - '0']
CMP DH, -1
JE @@2
OR DL, DH
STOSB
DEC ECX
JNE @@1
@@2:
MOV EAX, EDI
SUB EAX, EBX
POP EBX
POP EDI
POP ESI
end;
//----------------------------------------------------------------------------------------------------------------------
function LineStart(Buffer, BufPos: PWideChar): PWideChar; assembler;
// Use LineStart to find the start of the last partial line in the buffer. LineStart starts at BufPos and scans
// backwards for a line separator or line feed. It returns a pointer to the position following that character.
// If no line separator is found then the Buffer pointer is returned. Buffer should point to the begining of a block of
// memory and BufPos to the end of the block you want to scan.
// EAX contains Buffer, EDX BufPos on enter.
asm
MOV ECX, EDX
SUB ECX, EAX
SHR ECX, 1 // calculate difference (in characters) between BufPos and Buffer
JECXZ @@Finish
@@2:
MOV AX, [EDX]
CMP AX, WideLineSeparator
JZ @@1 // found a line separator
CMP AX, WideLineFeed
JZ @@1 // found a line feed
SUB EDX, 2
DEC ECX
JNZ @@2
JMP @@Finish
@@1:
MOV EAX, EDX
@@Finish:
end;
//----------------- TDelphiLexer --------------------------------------------------------------------------------
constructor TDelphiLexer.Create(Stream: TStream; IsUnicode: Boolean);
var
BOM: WideChar;
Count: Integer;
begin
FStream := Stream;
FIsUnicode := IsUnicode;
FNeedSwap := False;
if IsUnicode then
begin
// determine byte order in source if possible,
// if there is no byte order mark at stream start then assume LSB first order (little endian, no swap)
Count := Stream.Read(BOM, SizeOf(BOM));
if (BOM = BOM_LSB_FIRST) or (BOM = BOM_MSB_FIRST) then
begin
FNeedSwap := BOM = BOM_MSB_FIRST;
end
else
Stream.Seek(-Count, soFromCurrent);
end;
GetMem(FBuffer, 2 * LexerBufferSize);
FBuffer[0] := WideNull;
FBufPtr := FBuffer;
FBufEnd := FBuffer + LexerBufferSize;
FSourcePtr := FBuffer;
FSourceEnd := FBuffer;
FTokenPtr := FBuffer;
FLineStart := FSourcePtr;
FSourceLine := 1;
FToken := toBOF;
FDefines := TWideStringList.Create;
FDefines.Duplicates := dupIgnore;
FDefines.Sorted := True;
end;
//----------------------------------------------------------------------------------------------------------------------
destructor TDelphiLexer.Destroy;
begin
FDefines.Free;
FStream.Seek(Integer(FTokenPtr) - Integer(FBufPtr), 1);
FreeMem(FBuffer);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.DoNewLine;
begin
Inc(FSourceLine);
FLineStart := FSourcePtr + 1;
if Assigned(FOnNewLine) then
FOnNewLine(Self, FSourceLine);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.CheckToken(T: WideChar);
begin
if Token <> T then
case T of
toSymbol:
LexerError(SIdentifierExpected + ' but ''' + Token + ''' found');
toString:
LexerError(SStringExpected + ' but ''' + Token + ''' found');
toInteger, toFloat:
LexerError(SNumberExpected + ' but ''' + Token + ''' found');
else
LexerError('"' + WideString(T) + '" expected but ' + Token + ' found');
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.CheckTokenSymbol(const S: WideString);
begin
if not TokenSymbolIs(S) then
LexerError('"' + S + '" expected but "' + TokenString + '" found');
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.LexerError(const Message: WideString);
// Shows an error message.
var
S: WideString;
begin
if Assigned(FOnLexerError) then
FOnLexerError(Point(FSourcePtr - FLineStart + 1, FSourceLine), Message) // 1 based position
else
begin
S := Message + ' on line ' + IntToStr(FSourceLine);
MessageBoxW(0, PWideChar(S), 'Lexer Error', MB_OK or MB_ICONERROR or MB_APPLMODAL);
end;
Abort;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.HexToBinary(Stream: TStream);
var
Count: Integer;
Buffer: array[0..255] of Byte;
begin
SkipBlanks;
while FSourcePtr^ <> '}' do
begin
Count := HexToBin(FSourcePtr, @Buffer, 256);
if Count = 0 then
LexerError(SInvalidBinary);
Stream.Write(Buffer, Count);
Inc(FSourcePtr, Count);
SkipBlanks;
end;
NextToken;
end;
//----------------------------------------------------------------------------------------------------------------------
function TDelphiLexer.NextToken: WideChar;
// Advances the lexer to the next valid token. This excludes code which is put into a $ifdef $endif part for which the
// test fails, any comment and any white space.
var
I, J: Integer;
P, S: PWideChar;
begin
Result := toEOF;
// loop until a valid token has been found
while True do
begin
// first remove heading comments (this will automatically skip blanks too)
SkipComments;
if (FSourcePtr^ = '{') or NeedChars(2) and (FSourcePtr^ = '(') and ((FSourcePtr + 1)^ = '*') then
begin
// comment skipper encountered a compiler directive, handle this first and then start over
HandleDirective(FSourcePtr^ = '(');
Continue;
end;
// at this point we have the start of a valid token, now extract and return it to the application
P := FSourcePtr;
FTokenPtr := P;
FTokenString := '';
// Low lines (underlines) are not part of the formal Unicode identifier syntax. So test for them explicitly.
if (P^ = '_') or UnicodeIsIdentifierStart(Word(P^)) then
begin
Inc(P);
while UnicodeIsIdentifierPart(Word(P^)) do
Inc(P);
Result := toSymbol;
end
else
begin
case P^ of
'#', '''', '"': // string
begin
J := 0;
S := P;
while True do
case P^ of
'#':
begin
Inc(P);
I := 0;
while UnicodeIsNumber(Word(P^)) do
begin
I := I * 10 + (Ord(P^) - Ord('0'));
Inc(P);
end;
Inc(J);
end;
'"': // Have to allow " " too. This is not valid Delphi syntax, but used in some VCL assembler code.
begin
Inc(P);
while not (P^ in [WideNull, WideLF, WideCR, WideChar('"')]) and (P^ <> WideLineSeparator) do
begin
Inc(P);
Inc(J);
end;
if P^ <> '"' then
LexerError(SInvalidString)
else
Inc(P);
end;
'''':
begin
Inc(P);
while True do
begin
case P^ of
WideNull, WideLF, WideCR, WideLineSeparator:
LexerError(SInvalidString);
'''':
begin
Inc(P);
if P^ <> '''' then
Break;
end;
end;
Inc(J);
Inc(P);
end;
end;
else
Break;
end;
P := S;
SetLength(FTokenString, J);
J := 1;
while True do
case P^ of
'#':
begin
Inc(P);
I := 0;
while UnicodeIsNumber(Word(P^)) do
begin
I := I * 10 + (Ord(P^) - Ord('0'));
Inc(P);
end;
FTokenString[J] := WideChar(Word(I));
Inc(J);
end;
'"': // Have to allow " " too. This is not valid Delphi syntax, but used in some VCL assembler code.
begin
Inc(P);
while not (P^ in [WideNull, WideLF, WideCR, WideCHar('"')]) and (P^ <> WideLineSeparator) do
begin
FTokenString[J] := P^;
Inc(P);
Inc(J);
end;
if P^ <> '"' then
LexerError(SInvalidString)
else
Inc(P);
end;
'''':
begin
Inc(P);
while True do
begin
case P^ of
WideNull, WideLF, WideCR, WideLineSeparator:
LexerError(SInvalidString);
'''':
begin
Inc(P);
if P^ <> '''' then
Break;
end;
end;
FTokenString[J] := P^;
Inc(J);
Inc(P);
end;
end;
else
Break;
end;
Result := toString;
end;
'$': // hex number
begin
Inc(P);
while UnicodeIsHexDigit(Word(P^)) do
Inc(P);
Result := toInteger;
end;
'-', '0'..'9': // Integer, float number or Integer subrange of which the lower bound will be returned
begin
Inc(P);
while UnicodeIsNumber(Word(P^)) do
Inc(P);
Result := toInteger;
// if we have a subrange then we are done, otherwise scan further
if not ((P^ = '.') and NeedChars(2) and ((P + 1)^ = '.')) then
begin
if P^ in [WideChar('.'), WideChar('e'), WideChar('E')] then
begin
// it is actually a floating point value
Result := toFloat;
// skip irrelevant period character if directly followed by exponent character
if (P^ = '.') and NeedChars(2) and ((P + 1)^ in [WideChar('e'), WideChar('E')]) then
Inc(P);
// skip exponent letter if there is one followed by a plus or minus sign
if (P^ in [WideChar('e'), WideChar('E')]) and NeedChars(2) and
((P + 1)^ in [WideChar('+'), WideChar('-')]) then
Inc(P);
// skip whatever left over, the period, the expontent symbol or the sign
Inc(P);
while UnicodeIsNumber(Word(P^)) do
Inc(P);
if (P^ in [WideChar('c'), WideChar('C'), WideChar('d'), WideChar('D'), WideChar('s'), WideChar('S')]) then
begin
Result := toFloat;
FFloatType := P^;
Inc(P);
end
else
FFloatType := WideNull;
end;
end;
end;
else
// any other symbol not consumed above
Result := P^;
if Result <> toEOF then
Inc(P);
end;
end;
FSourcePtr := P;
FToken := Result;
Break; // if we come here then we have a valid token and can return
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function IDFromDirective(const S: WideString): Integer;
// Converts the given directive ID string into a number which can be used to uniquely identify the directive.
// A result of -1 indicates that the directive was not recognized. Otherwise single letter directives
// are returned with their ordinal value and all other directives as a number between 0..49.
// Directives which correspond to a single letter WideString will be handled as if the single letter WideString
// has been given
begin
Result := -1;
if (Length(S) > 0) and (S[1] in [WideChar('A')..WideChar('Z'), WideChar('a')..WideChar('z')]) then
begin
// single char directives occupy the range 0..25 (the check above ensures that the first character is plain Latin)
if Length(S) = 1 then
Result := Ord(UpCase(Char(S[1])))
else
begin
if Directives = nil then
InitializeDirectives;
// Return the ID (the position in the original array) instead of the index in the list
// because this might have changed when sorting the list
if Directives.Find(S, Result) then
Result := Integer(Directives.Objects[Result])
else
Result := -1;
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function TDelphiLexer.GetToken: WideChar;
begin
if FToken = toBOF then
NextToken;
Result := FToken;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.HandleDirective(UseStar: Boolean);
// the current input pointer is placed on the start of a compiler directive ('{$'), now evaluate this
var
DirectiveID: WideString;
ID: Integer;
IsOn, IsOff: Boolean;
begin
// skip initial curly bracket and dollar sign or parenthesis with star and dollar sign
Inc(FSourcePtr, 2 + Ord(UseStar));
// determine what kind of directive we actually have
if UnicodeIsIdentifierStart(Word(FSourcePtr^)) then
begin
// in some cases several directives might be in one {} pair
repeat
// extract directive identifier
DirectiveID := ScanIdentifier;
ID := IDFromDirective(DirectiveID);
case ID of
Ord('A')..Ord('Z'): // single letter directive, others might follow
if FSourcePtr^ in [WideChar('+'), WideChar('-')] then
begin
FCompilerSwitch[ID - 65] := FSourcePtr^ = '+';
Inc(FSourcePtr);
// several switches might be written in the form a+,b+,c- etc. with no spaces between them
if FSourcePtr^ <> ',' then
Break;
Inc(FSourcePtr);
if not UnicodeIsIdentifierStart(Word(FSourcePtr^)) then
Break;
end
else
Break; // single letter without + or - is a directive like $E with extension or $I with filename
Ord('a')..Ord('z'): // single letter directive derived from a multiletter directive, check for on/off
begin
SkipBlanks;
// check 'on' or 'off'
DirectiveID := ScanIdentifier;
IsOn := WideUpperCase(DirectiveID) = 'ON';
IsOff := not IsOn;
if IsOff then
IsOff := WideUpperCase(DirectiveID) = 'OFF';
if IsOn or IsOff then
FCompilerSwitch[ID - 97] := IsOn
else
LexerError(SInvalidDirective);
Break;
end;
0, 1: // ifdef, ifndef
begin
// enter conditional source part
SkipBlanks;
DirectiveID := ScanIdentifier;
if (ID = 1) xor FDefines.Find(DirectiveID, ID) then
Break // conditional part must be parsed normally
else
begin
// conditional part must be skipped
SkipToDirectiveEnd(UseStar);
SkipToElseOrEndIf; // look for a matching $endif before returning
end;
// at this point all code until the final {$endif} clause has been parsed
Break;
end;
2: // define (a new conditional symbol)
begin
SkipBlanks;
DirectiveID := ScanIdentifier;
FDefines.Add(DirectiveID);
Break;
end;
3: // undef (a conditional symbol)
begin
SkipBlanks;
DirectiveID := ScanIdentifier;
if FDefines.Find(DirectiveID, ID) then
FDefines.Delete(ID);
Break;
end;
4: // else
begin
// if we come here regulary then we just parsed an ifdef construct so the 'else'
// branch can be skipped
SkipToEndIf;
Break;
end;
5: // endif
begin
// if we come here then we just parsed either an ifdef endif or else endif construct
// which is now finished and needs no further action
Break;
end;
6: // ifopt
begin
// enter conditional source part
SkipBlanks;
DirectiveID := ScanIdentifier;
ID := IDFromDirective(DirectiveID);
if not (ID in [Ord('A')..Ord('Z')]) then
LexerError(SInvalidDirective);
if FCompilerSwitch[ID - 65] then
begin
// conditional part must be parsed normally
Break;
end
else
begin
// conditional part must be skipped
SkipToDirectiveEnd(UseStar);
SkipToElseOrEndIf; // look for a matching $endif before returning
end;
// at this point all code until the final {$endif} clause has been parsed
Break;
end;
else // unknown or unimportant directive
Break;
end;
until False;
end;
SkipToDirectiveEnd(UseStar);
end;
//----------------------------------------------------------------------------------------------------------------------
function TDelphiLexer.NeedChars(Count: Cardinal): Boolean;
// Ensure that at least Count bytes are available in the current input buffer if possible.
// If less input is available than Count bytes then Result is set to False.
begin
Result := True;
// check if we need to load new data
if Count > Cardinal(FSourceEnd - FSourcePtr) then
begin
ReadBuffer;
Result := Count <= Cardinal(FBufEnd - FSourcePtr);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.ReadBuffer;
var
Count: Integer;
ANSIChars: array[0..LexerBufferSize - 1] of Char;
begin
Inc(FOrigin, FSourcePtr - FBuffer);
FSourceEnd^ := FSaveChar;
Count := FBufPtr - FSourcePtr;
if Count <> 0 then
Move(FSourcePtr^, FBuffer^, 2 * Count);
FBufPtr := FBuffer + Count;
// The actual source may not be Unicode (and if Unicode then in two different byte orders) so handle this properly.
if FIsUnicode then
begin
// Count needs the character count, not the byte count as TStream.Read returns.
Count := FStream.Read(FBufPtr^, 2 * (FBufEnd - FBufPtr)) div 2;
end
else
begin
// ANSI source, data must be converted to Unicode,
// the source is expected as being plain text (no UTF8, MBCS etc.)
Count := FStream.Read(ANSIChars, FBufEnd - FBufPtr);
ExpandANSIString(ANSIChars, FBufPtr, Count);
end;
FSourcePtr := FBuffer;
FSourceEnd := FBufPtr + Count;
if FSourceEnd = FBufEnd then
begin
FSourceEnd := LineStart(FBuffer, FSourceEnd - 1);
if FSourceEnd = FBuffer then
LexerError(SLineTooLong);
end;
FSaveChar := FSourceEnd^;
FSourceEnd^ := WideNull;
if FNeedSwap then
StrSwapByteOrder(FBufPtr);
Inc(FBufPtr, Count);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.AdvanceSource(Amount: Cardinal = 1);
begin
NeedChars(Amount);
Inc(FSourcePtr, Amount);
end;
//----------------------------------------------------------------------------------------------------------------------
function TDelphiLexer.GetCompilerOption(Option: Char): Boolean;
begin
Option := Upcase(Option);
if Option in ['A'..'Z'] then
Result := FCompilerSwitch[Ord(Option) - 65]
else
Result := False;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.SkipConditionalPart(WithElse: Boolean);
// skips all text until an {$endif} part is found, handles recursion too
// If WithElse is True then an $else part is considered as correct end too. Otherwise an exception is raised.
var
DirectiveID: WideString;
ID: Integer;
UseStar: Boolean;
begin
repeat
// Skip all characters until either a comment ('{', '//' and '(*') or a string started.
SkipUntil('{(''/');
case FSourcePtr^ of
WideNull:
LexerError(SUnexpectedEOF);
'''': // string start
SkipString;
'/': // Single line comment.
if NeedChars(2) and ((FSourcePtr + 1)^ = '/') then
SkipLine;
else
// possible comment start
if (FSourcePtr^ = '{') or
NeedChars(2) and (FSourcePtr^ = '(') and ((FSourcePtr + 1)^ = '*') then
begin
UseStar := FSourcePtr^ <> '{';
// perhaps found a directive, check this and then check for end or recursive definitions
// (no inherent limit to 16 levels here as in Delphi)
AdvanceSource(1 + Ord(UseStar));
if FSourcePtr^ = '$' then
begin
AdvanceSource;
// determine what kind of directive we actually have
if UnicodeIsIdentifierStart(Word(FSourcePtr^)) then
begin
// extract directive identifier
DirectiveID := ScanIdentifier;
ID := IDFromDirective(DirectiveID);
case ID of
0, 1, 6: // ifdef, ifndef, ifopt
begin
// recursive conditional source part, reenter skipping
SkipToDirectiveEnd(UseStar);
SkipToEndIf;
SkipToDirectiveEnd(UseStar);
end;
4: // else
begin
// coming across an $else when looking for $endif does only break the
// loop if we are looking for the $else part, otherwise continue to $endif
if WithElse then
Exit;
end;
5: // endif
begin
// $endif is what we are looking for
Exit;
end;
end;
end;
end
else
begin
SkipUntil('}'); // Normal comment. Skip until the comment's end.
AdvanceSource; // Skip the closing curly bracket too.
end;
end
else
AdvanceSource;
end;
until False;
end;
//----------------------------------------------------------------------------------------------------------------------
function TDelphiLexer.ScanIdentifier: WideString;
var
P: PWideChar;
begin
P := FSourcePtr;
while UnicodeIsIdentifierPart(Word(P^)) do
Inc(P);
SetString(Result, FSourcePtr, P - FSourcePtr);
FSourcePtr := P;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.SetCompilerOption(Option: Char; const Value: Boolean);
begin
Option := Upcase(Option);
if Option in ['A'..'Z'] then
FCompilerSwitch[Ord(Option) - 65] := Value;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.SetDefines(const Value: TWideStringList);
begin
FDefines.Assign(Value);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.SkipBlanks;
begin
while True do
begin
case FSourcePtr^ of
WideNull:
begin
ReadBuffer;
if FSourcePtr^ = WideNull then
Break;
Continue;
end;
WideLineSeparator,
WideLineFeed:
DoNewLine;
WideCarriageReturn:
// increase line counter only for Macintosh style text (CR only)
// otherwise just ignore CR characters
if NeedChars(2) and ((FSourcePtr + 1)^ <> WideLineFeed) then
DoNewLine;
else
if not UnicodeIsWhiteSpace(Word(FSourcePtr^)) then
begin
Break;
end;
end;
AdvanceSource;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.SkipComments;
// skips any Delphi style comment
// Note: The styles //, {} and (* *) are currently hard coded hence you cannot skip C comments like /* */.
// In order to determine whether the current input is to be considered as being a comment we need some lookahead.
begin
repeat
SkipBlanks;
case FSourcePtr^ of
'{': // multi line comment first type (consider case of compiler directives
if NeedChars(2) and ((FSourcePtr + 1)^ <> '$') then
begin
SkipUntil('}');
if FSourcePtr^ = WideNull then
LexerError(SUnexpectedEOF)
else
AdvanceSource;
end
else
Break; // get out of here if we found a compiler directive
'/':
begin
if NeedChars(2) and ((FSourcePtr + 1)^ = '/') then
SkipLine
else
Break; // some other construct but not a comment
end;
'(':
begin
if NeedChars(3) and ((FSourcePtr + 1)^ = '*') and ((FSourcePtr + 2)^ <> '$') then
begin
// multi line comment second type, skip to '*)' combination
repeat
SkipUntil('*');
if NeedChars(2) and (FSourcePtr^ = '*') and ((FSourcePtr + 1)^ = ')') then
Break
else
if FSourcePtr^ <> WideNull then
AdvanceSource;
until FSourcePtr^ = WideNull;
if FSourcePtr^ = WideNull then
LexerError(SUnexpectedEOF)
else
AdvanceSource(2);
end
else
Break; // some other construct but not a comment
end;
else
Break; // no more comments, get out of here
end;
until False;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.SkipLine;
// Skips all characters until the end of line.
var
S: WideString;
begin
S := WideLineSeparator;
S := S + WideLineFeed + WideCarriageReturn;
AdvanceSource;
SkipUntil(S);
SkipBlanks;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.SkipString;
// skips a Delphi string (used to skip conditional code parts)
// On enter FSourcePtr points to the initial ' character on exit it points to the first character after the terminating
// ' character.
begin
repeat
AdvanceSource;
// find next apostrophe
SkipUntil('''');
// advance to position after apostrophe
if FSourcePtr^ = '''' then
AdvanceSource;
// is there another apostrophe then continue looking for string end, otherwise get out of here
if FSourcePtr^ <> '''' then
Break;
until False;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.SkipToEndIf;
// skips all text until an {$endif} part is found, handles recursion too
begin
SkipConditionalPart(False);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.SkipToDirectiveEnd(UseStar: Boolean);
begin
// skip to closing curly bracket or *)
if UseStar then
begin
repeat
SkipUntil('*');
case FSourcePtr^ of
WideNull:
LexerError(SInvalidDirective);
'*':
begin
AdvanceSource;
if FSourcePtr^ = ')' then
begin
AdvanceSource;
Break;
end;
end;
end;
until False;
end
else
begin
SkipUntil('}');
if FSourcePtr^ = '}' then
AdvanceSource
else
LexerError(SInvalidDirective);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.SkipToElseOrEndIf;
// skips all text until either an {$else} or an {$endif} part is found, handles recursion too
begin
SkipConditionalPart(True);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.SkipUntil(S: WideString);
// skips all characters until one of the characters in S is found or the source is exhausted
var
L: Cardinal;
Ch: WideChar;
begin
L := Length(S);
if L = 1 then
begin
// optimized version for single char
Ch := S[1];
while FSourcePtr^ <> Ch do
begin
case FSourcePtr^ of
WideNull:
begin
ReadBuffer;
if FSourcePtr^ = WideNull then
Exit;
Continue;
end;
WideLineSeparator, WideLineFeed:
DoNewLine;
WideCarriageReturn:
// increase line counter only for Macintosh style text (CR only)
// otherwise just ignore CR characters
if NeedChars(2) and ((FSourcePtr + 1)^ <> WideLineFeed) then
DoNewLine;
end;
AdvanceSource;
end;
end
else
begin
// check for all characters in S
while StrScanW(PWideChar(S), FSourcePtr^, L) = nil do
begin
case FSourcePtr^ of
WideNull:
begin
ReadBuffer;
if FSourcePtr^ = WideNull then
Exit;
end;
WideLineSeparator, WideLineFeed:
DoNewLine;
WideCarriageReturn:
// increase line counter only for Macintosh style text (CR only)
// otherwise just ignore CR characters
if NeedChars(2) and ((FSourcePtr + 1)^ <> WideLineFeed) then
DoNewLine;
end;
AdvanceSource;
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TDelphiLexer.ShowToken(Token: WideChar);
// Used for debugging purposes and shows a message box with a description string of the current token along
// with its value.
var
TokenName: WideString;
begin
case Token of
toEOF:
TokenName := '(end of file)';
toBOF:
TokenName := '(begin of file)';
toSymbol:
TokenName := '(symbol) = "' + TokenString + '"';
toString:
TokenName := '(string) = "' + TokenString + '"';
toInteger:
TokenName := '(Integer) = "' + TokenString + '"';
toFloat:
TokenName := '(float) = "' + TokenString + '"';
else
TokenName := Format('(other) = "%s" (hex: %x)', [WideString(Token), Word(Token)]) ;
end;
MessageBoxW(0, PWideChar(TokenName), 'Current token', MB_OK or MB_APPLMODAL);
end;
//----------------------------------------------------------------------------------------------------------------------
function TDelphiLexer.SourcePos: Integer;
begin
Result := FOrigin + (FTokenPtr - FBuffer);
end;
//----------------------------------------------------------------------------------------------------------------------
function TDelphiLexer.TokenFloat: Extended;
begin
if FFloatType <> WideNull then
Dec(FSourcePtr);
Result := StrToFloat(TokenString);
if FFloatType <> WideNull then
AdvanceSource;
end;
//----------------------------------------------------------------------------------------------------------------------
function TDelphiLexer.TokenInteger: Integer;
begin
Result := StrToInt(TokenString);
end;
//----------------------------------------------------------------------------------------------------------------------
function TDelphiLexer.TokenInt64: Int64;
begin
Result := StrToInt64(TokenString);
end;
//----------------------------------------------------------------------------------------------------------------------
function TDelphiLexer.TokenString: WideString;
begin
if FToken = toString then
Result := FTokenString
else
SetString(Result, FTokenPtr, FSourcePtr - FTokenPtr);
end;
//----------------------------------------------------------------------------------------------------------------------
function TDelphiLexer.TokenSymbolIs(const S: WideString): Boolean;
begin
Result := (Token = toSymbol) and (StrICompW(PWideChar(S), PWideChar(TokenString)) = 0);
end;
//----------------------------------------------------------------------------------------------------------------------
function TDelphiLexer.TokenComponentIdent: WideString;
var
P: PWideChar;
begin
CheckToken(toSymbol);
P := FSourcePtr;
while P^ = '.' do
begin
Inc(P);
if not UnicodeIsIdentifierStart(Word(P^)) then
LexerError(SIdentifierExpected);
repeat
Inc(P)
until not UnicodeIsIdentifierPart(Word(P^));
end;
FSourcePtr := P;
Result := TokenString;
end;
//----------------- TSQLLexer ------------------------------------------------------------------------------------------
constructor TSQLLexer.Create(Stream: TStream);
var
BOM: WideChar;
Count: Integer;
begin
FStream := Stream;
FNeedSwap := False;
// Determine byte order in source if possible.
// If there is no byte order mark at stream start then assume LSB first order (little endian, no swap).
Count := Stream.Read(BOM, SizeOf(BOM));
if (BOM = BOM_LSB_FIRST) or (BOM = BOM_MSB_FIRST) then
FNeedSwap := BOM = BOM_MSB_FIRST
else
Stream.Seek(-Count, soFromCurrent);
GetMem(FBuffer, 2 * LexerBufferSize);
FBuffer[0] := WideNull;
FBufPtr := FBuffer;
FBufEnd := FBuffer + LexerBufferSize;
FSourcePtr := FBuffer;
FSourceEnd := FBuffer;
FTokenPtr := FBuffer;
FLineStart := FSourcePtr;
FSourceLine := 1;
FToken := toBOF;
end;
//----------------------------------------------------------------------------------------------------------------------
destructor TSQLLexer.Destroy;
begin
FStream.Seek(Integer(FTokenPtr) - Integer(FBufPtr), 1);
FreeMem(FBuffer);
inherited;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSQLLexer.AdvanceSource(Amount: Cardinal = 1);
begin
NeedChars(Amount);
Inc(FSourcePtr, Amount);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSQLLexer.DoNewLine;
begin
Inc(FSourceLine);
FLineStart := FSourcePtr + 1;
if Assigned(FOnNewLine) then
FOnNewLine(Self, FSourceLine);
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLLexer.GetToken: WideChar;
begin
if FToken = toBOF then
NextToken;
Result := FToken;
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLLexer.NeedChars(Count: Cardinal): Boolean;
// Ensure that at least Count bytes are available in the current input buffer if possible.
// If less input is available than Count bytes then Result is set to False.
begin
Result := True;
// check if we need to load new data
if Count > Cardinal(FSourceEnd - FSourcePtr) then
begin
ReadBuffer;
Result := Count <= Cardinal(FBufEnd - FSourcePtr);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSQLLexer.ReadBuffer;
var
Count: Integer;
begin
Inc(FOrigin, FSourcePtr - FBuffer);
FSourceEnd^ := FSaveChar;
Count := FBufPtr - FSourcePtr;
if Count <> 0 then
Move(FSourcePtr^, FBuffer^, 2 * Count);
FBufPtr := FBuffer + Count;
Count := FStream.Read(FBufPtr^, 2 * (FBufEnd - FBufPtr)) div 2;
FSourcePtr := FBuffer;
FSourceEnd := FBufPtr + Count;
if FSourceEnd = FBufEnd then
begin
FSourceEnd := LineStart(FBuffer, FSourceEnd - 1);
if FSourceEnd = FBuffer then
LexerError(SLineTooLong);
end;
FSaveChar := FSourceEnd^;
FSourceEnd^ := WideNull;
if FNeedSwap then
StrSwapByteOrder(FBufPtr);
Inc(FBufPtr, Count);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSQLLexer.SkipBlanks;
// Skips white spaces like new line, carriage return and any other white space defined by the Unicode standard.
begin
while True do
begin
case FSourcePtr^ of
WideNull:
begin
ReadBuffer;
if FSourcePtr^ = WideNull then
Break;
Continue;
end;
WideLineSeparator,
WideLineFeed:
DoNewLine;
WideCarriageReturn:
// increase line counter only for Macintosh style text (CR only)
// otherwise just ignore CR characters
if NeedChars(2) and ((FSourcePtr + 1)^ <> WideLineFeed) then
DoNewLine;
else
if not UnicodeIsWhiteSpace(Word(FSourcePtr^)) then
begin
Break;
end;
end;
AdvanceSource;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSQLLexer.SkipComments;
// Skips any SQL comment.
// Supported styles are /+ ... */ (C like comments), # and -- when followed by a white space. The last two styles
// represent single line comments and everything following them on the same line is considered as part of the comment.
begin
repeat
SkipBlanks;
case FSourcePtr^ of
'#': // Single line comment, first type.
SkipLine;
'-': // Potential single line comment.
begin
if NeedChars(3) and ((FSourcePtr + 1)^ = '-') and UnicodeIsWhiteSpace(UCS4Char((FSourcePtr + 2)^)) then
// Single line comment type 2 found.
SkipLine;
end;
'/': // Potential multi line comment.
begin
if NeedChars(2) and ((FSourcePtr + 1)^ = '*') then
begin
Inc(FSourcePtr, 2);
// Multi line comment, skip to '*/' combination.
repeat
SkipUntil('*');
if NeedChars(2) and (FSourcePtr^ = '*') and ((FSourcePtr + 1)^ = '/') then
Break
else
if FSourcePtr^ <> WideNull then
AdvanceSource;
until FSourcePtr^ = WideNull;
if FSourcePtr^ = WideNull then
LexerError(SUnexpectedEOF)
else
AdvanceSource(2);
end
else
// Some other construct but not a comment.
Break;
end;
else
// No more comments, get out of here.
Break;
end;
until False;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSQLLexer.SkipLine;
// Skips all characters until the end of line.
var
S: WideString;
begin
S := WideLineSeparator;
S := S + WideLineFeed + WideCarriageReturn;
AdvanceSource;
SkipUntil(S);
SkipBlanks;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSQLLexer.SkipUntil(S: WideString);
// Skips all characters until one of the characters in S is found or the source is exhausted.
var
L: Cardinal;
Ch: WideChar;
begin
L := Length(S);
if L = 1 then
begin
// Optimized version for single char.
Ch := S[1];
while FSourcePtr^ <> Ch do
begin
case FSourcePtr^ of
WideNull:
begin
ReadBuffer;
if FSourcePtr^ = WideNull then
Exit;
Continue;
end;
WideLineSeparator, WideLineFeed:
DoNewLine;
WideCarriageReturn:
// Increase line counter only for Macintosh style text (CR only)
// otherwise just ignore CR characters.
if NeedChars(2) and ((FSourcePtr + 1)^ <> WideLineFeed) then
DoNewLine;
end;
AdvanceSource;
end;
end
else
begin
// Check for all characters in S.
while StrScanW(PWideChar(S), FSourcePtr^, L) = nil do
begin
case FSourcePtr^ of
WideNull:
begin
ReadBuffer;
if FSourcePtr^ = WideNull then
Exit;
end;
WideLineSeparator, WideLineFeed:
DoNewLine;
WideCarriageReturn:
// Increase line counter only for Macintosh style text (CR only)
// otherwise just ignore CR characters.
if NeedChars(2) and ((FSourcePtr + 1)^ <> WideLineFeed) then
DoNewLine;
end;
AdvanceSource;
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSQLLexer.CheckToken(T: WideChar);
begin
if Token <> T then
case T of
toSymbol:
LexerError(SIdentifierExpected + ' but ''' + Token + ''' found');
toString:
LexerError(SStringExpected + ' but ''' + Token + ''' found');
toInteger, toFloat:
LexerError(SNumberExpected + ' but ''' + Token + ''' found');
else
LexerError('"' + WideString(T) + '" expected but ' + Token + ' found');
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSQLLexer.CheckTokenSymbol(const S: WideString);
begin
if not TokenSymbolIs(S) then
LexerError('"' + S + '" expected but "' + TokenString + '" found');
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLLexer.NextToken: WideChar;
// Advances the lexer to the next valid token. Comments and white spaces are skipped.
var
P: PWideChar;
StringEndChar: WideChar;
begin
Result := toEOF;
while True do
begin
// First remove heading comments (this will automatically skip blanks too).
SkipComments;
// At this point we have the start of a valid token, now extract and return it to the caller.
P := FSourcePtr;
FTokenPtr := P;
// Low lines (underlines) are not part of the formal Unicode identifier syntax. So test for them explicitly.
if (P^ = '_') or UnicodeIsIdentifierStart(Word(P^)) then
begin
Inc(P);
// XML allows namespace identification. The name space is kept as part of the identifier here.
// Additionally, there can contain any number of hyphens and periods.
while UnicodeIsIdentifierPart(Word(P^)) do
Inc(P);
Result := toSymbol;
end
else
begin
case P^ of
'''', '"':
begin
if P^ = '"' then
StringEndChar := '"'
else
StringEndChar := '''';
repeat
Inc(P);
while not (P^ in [WideNull, WideLF, WideCR, StringEndChar, WideChar('\')]) and (P^ <> WideLineSeparator) do
Inc(P);
// If there is an escape character then ignore the next character unless we reached the input end.
if (P^ = '\') and ((P + 1)^ <> WideNull) then
Inc(P)
else
Break;
until False;
if P^ <> StringEndChar then
LexerError(SInvalidString)
else
Inc(P);
Result := toString;
end;
'+', '-', '0'..'9': // Integer or float number
begin
if (P^ = '+') or (P^ = '-') then
Inc(P);
if NeedChars(2) and (P^ = '0') and (P^ = 'x') then
begin
// Found a hex number. Note: only small x is allowed currently.
Inc(P, 2);
while UnicodeIsHexDigit(Word(P^)) do
Inc(P);
Result := toHexNumber;
end
else
begin
Inc(P);
while UnicodeIsNumber(Word(P^)) do
Inc(P);
Result := toInteger;
// Check for a floating point number (possibly with exponent).
if P^ in [WideChar('.'), WideChar('e'), WideChar('E')] then
begin
// It is actually a floating point value.
Result := toFloat;
// Skip irrelevant period character if directly followed by exponent character.
if (P^ = '.') and ((P + 1)^ in [WideChar('e'), WideChar('E')]) then
Inc(P);
// Skip exponent letter if there is one followed by a plus or minus sign
if (P^ in [WideChar('e'), WideChar('E')]) and ((P + 1)^ in [WideChar('+'), WideChar('-')]) then
Inc(P);
// Skip whatever left over, the period, the expontent symbol or the exponent sign.
Inc(P);
while UnicodeIsNumber(Word(P^)) do
Inc(P);
end;
end;
end;
else
// Any other symbol not consumed above.
Result := P^;
if Result <> toEOF then
Inc(P);
end;
end;
FSourcePtr := P;
FToken := Result;
Break; // if we come here then we have a valid token and can return
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLLexer.ScanRawText: WideString;
// Skips any leading white spaces and comments and collects then all input until a following white space is found.
// The input is not classified in any way but returned as it appears in the input.
var
P: PWideChar;
begin
SkipComments;
P := FSourcePtr;
while not UnicodeIsWhiteSpace(Word(FSourcePtr^)) and (FSourcePtr^ <> WideNull) do
AdvanceSource;
SetString(Result, P, FSourcePtr - P);
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLLexer.TokenFloat: Extended;
begin
Result := StrToFloat(TokenString);
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLLexer.TokenInt64: Int64;
begin
Result := StrToInt64(TokenString);
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLLexer.TokenInteger: Integer;
begin
Result := StrToInt(TokenString);
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLLexer.TokenString: WideString;
begin
SetString(Result, FTokenPtr, FSourcePtr - FTokenPtr);
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLLexer.TokenSymbolIs(const S: WideString): Boolean;
begin
Result := (FToken = toSymbol) and (StrICompW(PWideChar(S), PWideChar(TokenString)) = 0);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSQLLexer.LexerError(const Message: WideString);
var
S: WideString;
begin
if Assigned(FOnLexerError) then
FOnLexerError(Point(FSourcePtr - FLineStart + 1, FSourceLine), Message) // 1 based position
else
begin
S := Message + ' on line ' + IntToStr(FSourceLine);
MessageBoxW(0, PWideChar(S), 'Lexer Error', MB_OK or MB_ICONERROR or MB_APPLMODAL);
Abort;
end;
end;
//----------------- TSQLTokenizer --------------------------------------------------------------------------------------
function TSQLTokenizer.AdvanceSource(Amount: Cardinal = 1): Boolean;
begin
Result := NeedChars(Amount);
if Result then
Inc(FSourcePtr, Amount)
else
FSourcePtr := FSourceEnd;
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLTokenizer.GetToken: WideChar;
begin
if FToken = toBOF then
NextToken;
Result := FToken;
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLTokenizer.NeedChars(Count: Cardinal): Boolean;
// Ensure that at least Count bytes are available in the current input buffer if possible.
// If less input is available than Count bytes then Result is set to False.
begin
Result := True;
// Check if we need to load new data.
if Count > Cardinal(FSourceEnd - FSourcePtr) then
begin
ReadBuffer;
Result := Count <= Cardinal(FSourceEnd - FSourcePtr);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSQLTokenizer.ReadBuffer;
var
RemainingChars: Integer;
NewChars: Integer;
begin
// Copy all not yet consumed input to the start of the buffer.
if FSourcePtr > @FBuffer then
begin
Inc(FOrigin, FSourcePtr - @FBuffer);
RemainingChars := FSourceEnd - FSourcePtr;
if RemainingChars > 0 then
Move(FSourcePtr^, FBuffer, 2 * RemainingChars);
FSourceEnd := FBuffer + RemainingChars;
end;
if Assigned(FStream) then
NewChars := FStream.Read(FSourceEnd^, 2 * (FBufEnd - FSourceEnd)) div 2
else
NewChars := 0;
FSourcePtr := FSourceEnd;
Inc(FSourceEnd, NewChars);
FSourceEnd^ := WideNull;
if FNeedSwap then
StrSwapByteOrder(FSourcePtr);
FSourcePtr := @FBuffer;
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLTokenizer.NextToken: WideChar;
// Advances the lexer to the next valid token. Comments and white spaces are skipped.
//--------------- local functions --------------------------------------------
procedure ScanString(EndChar: WideChar);
begin
repeat
if not AdvanceSource then
Break;
while not (FSourcePtr^ in [WideNull, WideLF, WideCR, EndChar, WideChar('\')]) and (FSourcePtr^ <> WideLineSeparator) do
if not AdvanceSource then
Break;
// If there is an escape character then ignore the next character unless we reached the input end.
if (FSourcePtr^ = '\') and ((FSourcePtr + 1)^ <> WideNull) then
begin
if not AdvanceSource then
Break;
end
else
Break;
until False;
end;
//----------------------------------------------------------------------------
procedure ScanLine;
begin
while not (FSourcePtr^ in [WideNull, WideLF, WideCR]) and (FSourcePtr^ <> WideLineSeparator) do
if not AdvanceSource then
Break;
end;
//----------------------------------------------------------------------------
procedure ScanSymbol;
begin
// Low lines (underlines) are not part of the formal Unicode identifier syntax. So test for them explicitly.
if AdvanceSource then
begin
// SQL allows qualifiers. The qualifiers are kept as part of the symbol here.
while UnicodeIsIdentifierPart(Word(FSourcePtr^)) or (FSourcePtr^ in [WideChar('_'), WideChar('.')]) do
if not AdvanceSource then
Break;
Result := toSymbol;
end;
end;
//----------------------------------------------------------------------------
procedure ScanPureSymbol;
begin
if AdvanceSource then
begin
// No qualifiers allowed here.
while UnicodeIsIdentifierPart(Word(FSourcePtr^)) or (FSourcePtr^ = '_') do
if not AdvanceSource then
Break;
Result := toSymbol;
end;
end;
//--------------- end local functions ----------------------------------------
var
ScanNumber: Boolean;
begin
if FSourcePtr^ = WideNull then
ReadBuffer;
Result := toEOF;
// Initialize token start pointer for this run.
FTokenPtr := FSourcePtr;
if FSourcePtr^ <> WideNull then
begin
// Input scanning depends on current state, which could be a left over from a previous pass.
case FState of
tsNormal:
begin
case FSourcePtr^ of
'@': // User variable or system (global) variable.
begin
if AdvanceSource then
begin
if FSourcePtr^ = '@' then
begin
Result := toSystemVariable;
AdvanceSource;
end
else
Result := toUserVariable;
ScanPureSymbol;
end;
end;
'x':
begin
// Special case: hex number in quotes, but only if 'x' is directly followed by a quote char.
if NeedChars(2) and ((FSourcePtr + 1)^ in [WideChar('"'), WideChar('''')]) then
begin
// Hex string.
if AdvanceSource then
begin
ScanString(FSourcePtr^);
Result := toHexString;
end;
end
else
begin
// Normal identifier.
ScanSymbol;
end;
end;
'''': // String literal
begin
FState := tsSingleQuoteString;
ScanString(FSourcePtr^);
if FSourcePtr^ = '''' then
FState := tsNormal;
if FSourcePtr^ <> WideNull then
AdvanceSource;
Result := toString;
end;
'"': // String literal
begin
FState := tsDoubleQuoteString;
ScanString(FSourcePtr^);
if FSourcePtr^ = '"' then
FState := tsNormal;
if FSourcePtr^ <> WideNull then
AdvanceSource;
Result := toString;
end;
'`': // String literal
begin
FState := tsBackQuoteString;
ScanString(FSourcePtr^);
if FSourcePtr^ = '`' then
FState := tsNormal;
if FSourcePtr^ <> WideNull then
AdvanceSource;
Result := toString;
end;
'#': // Single line comment, first type.
begin
ScanLine;
Result := toSLComment;
end;
'/': // Potential single or multi line comment.
begin
if NeedChars(2) then
begin
if (FSourcePtr + 1)^ = '*' then
begin
FState := tsComment;
Result := toMLComment;
Inc(FSourcePtr, 2);
// Multi line comment, skip to '*/' combination or end of line.
repeat
while not (FSourcePtr^ in [WideNull, WideLF, WideCR, WideChar('*')]) and (FSourcePtr^ <> WideLineSeparator) do
if not AdvanceSource then
Break;
if FSourcePtr^ = '*' then
begin
if NeedChars(2) and ((FSourcePtr + 1)^ = '/') then
begin
AdvanceSource(2);
FState := tsNormal;
Break;
end
else
if not AdvanceSource then
Break;
// If * is not followed by / then continue scanning.
end
else
Break;
until False;
end
else
if (FSourcePtr + 1)^ = '/' then
begin
Scanline;
Result := toSLComment;
end;
if Result = toEOF then
begin
Result := FSourcePtr^;
AdvanceSource;
end;
end;
end;
'-':
begin
AdvanceSource;
if FSourcePtr^ = '-' then
begin
// Potential single line comment type 3 found.
if (NeedChars(2) and UnicodeIsWhiteSpace(UCS4Char((FSourcePtr + 1)^))) or
((FSourcePtr + 1)^ = WideNull) then
begin
ScanLine;
Result := toSLComment;
end
else
// There is a double minus but with additional content after it. Return the first minus only.
Result := '-';
end
else
begin
// A single minus.
Result := '-';
end;
end;
'0'..'9': // Integer or float number or (for MySQL) identifier starting with one or more digits.
begin
if NeedChars(2) and (FSourcePtr^ = '0') and (FSourcePtr^ = 'x') then
begin
// Found a hex number. Note: only small x is allowed currently.
if AdvanceSource(2) then
begin
while UnicodeIsHexDigit(Word(FSourcePtr^)) do
if not AdvanceSource then
Break;
Result := toHexNumber;
end;
end
else
begin
if AdvanceSource then
begin
while UnicodeIsNumber(Word(FSourcePtr^)) do
if not AdvanceSource then
Break;
Result := toInteger;
ScanNumber := True;
// Check if we have a MySQL identifier here.
if UnicodeIsIdentifierPart(Word(FSourcePtr^)) or (FSourcePtr^ = '_') then
begin
// Special case letter 'e' must be handled. If followed by a digit or sign it belongs to a number.
if NeedChars(2) and not ((FSourcePtr^ in [WideChar('e'), WideChar('E')]) and UnicodeIsNumber(Word(FSourcePtr^))) then
begin
// It's an identifier.
// Low lines (underlines) are not part of the formal Unicode identifier syntax. So test for them explicitly.
while UnicodeIsIdentifierPart(Word(FSourcePtr^)) or (FSourcePtr^ = '_') do
if not AdvanceSource then
Break;
Result := toSymbol;
ScanNumber := False;
end;
end;
// Check for a floating point number (possibly with exponent).
if ScanNumber and (FSourcePtr^ in [WideChar('.'), WideChar('e'), WideChar('E')]) then
begin
// It is actually a floating point value.
Result := toFloat;
// Skip irrelevant period character if directly followed by exponent character.
if (FSourcePtr^ = '.') and ((FSourcePtr + 1)^ in [WideChar('e'), WideChar('E')]) then
AdvanceSource;
// Skip exponent letter if there is one followed by a plus or minus sign
if (FSourcePtr^ in [WideChar('e'), WideChar('E')]) and ((FSourcePtr + 1)^ in [WideChar('+'), WideChar('-')]) then
AdvanceSource;
// Skip whatever left over, the period, the expontent symbol or the exponent sign.
if AdvanceSource then
begin
while UnicodeIsNumber(Word(FSourcePtr^)) do
if not AdvanceSource then
Break;
end;
end;
end;
end;
end;
else
if (FSourcePtr^ = '_') or UnicodeIsIdentifierStart(Word(FSourcePtr^)) then
ScanSymbol
else
begin
if UnicodeIsWhiteSpace(Word(FSourcePtr^)) then
Result := toWhiteSpace
else
// Any other symbol not consumed above.
Result := FSourcePtr^;
if Result <> toEOF then
AdvanceSource;
end;
end;
end;
tsSingleQuoteString:
begin
// A single quoted string is still unfinished.
Result := toString;
ScanString('''');
if FSourcePtr^ = '''' then
FState := tsNormal;
if FSourcePtr^ <> WideNull then
AdvanceSource;
end;
tsDoubleQuoteString:
begin
// A double quoted string is still unfinished.
Result := toString;
ScanString('"');
if FSourcePtr^ = '"' then
FState := tsNormal;
if FSourcePtr^ <> WideNull then
AdvanceSource;
end;
tsBackQuoteString:
begin
// A double quoted string is still unfinished.
Result := toString;
ScanString('`');
if FSourcePtr^ = '`' then
FState := tsNormal;
if FSourcePtr^ <> WideNull then
AdvanceSource;
end;
tsComment:
begin
// Multi line comment pending, skip to '*/' combination or end of line.
Result := toMLComment;
repeat
while not (FSourcePtr^ in [WideNull, WideLF, WideCR, WideChar('*')]) and (FSourcePtr^ <> WideLineSeparator) do
if not AdvanceSource then
Break;
if FSourcePtr^ = '*' then
begin
if NeedChars(2) and ((FSourcePtr + 1)^ = '/') then
begin
AdvanceSource(2);
FState := tsNormal;
Break;
end
else
if not AdvanceSource then
Break;
// If * is not followed by / then continue scanning.
end
else
Break;
until False;
end;
end;
end;
FToken := Result;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSQLTokenizer.Initialize(Stream: TStream; State: TTokenizerState);
// Resets the curent state of the tokenizer and initializes a few variables according to the values given.
// Used to start a new tokenizing run on fresh input.
var
BOM: WideChar;
Count: Integer;
begin
FStream := Stream;
FState := State;
FNeedSwap := False;
FOrigin := 0;
// Determine byte order in source if possible.
// If there is no byte order mark at stream start then assume LSB first order (little endian, no swap).
if Assigned(FStream) then
begin
Count := Stream.Read(BOM, SizeOf(BOM));
if (BOM = BOM_LSB_FIRST) or (BOM = BOM_MSB_FIRST) then
FNeedSwap := BOM = BOM_MSB_FIRST
else
Stream.Seek(-Count, soFromCurrent);
end;
FBuffer[0] := WideNull;
FBufPtr := FBuffer;
FBufEnd := FBuffer + LexerBufferSize;
FSourcePtr := FBuffer;
FSourceEnd := FBuffer;
FTokenPtr := FBuffer;
FLineStart := FSourcePtr;
FSourceLine := 1;
FToken := toBOF;
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLTokenizer.SourcePosition: Integer;
begin
Result := FOrigin + (FSourcePtr - FBuffer);
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLTokenizer.TokenFloat: Extended;
begin
Result := StrToFloat(TokenString);
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLTokenizer.TokenInt64: Int64;
begin
Result := StrToInt64(TokenString);
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLTokenizer.TokenInteger: Integer;
begin
Result := StrToInt(TokenString);
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLTokenizer.TokenPosition: Integer;
begin
Result := FOrigin + (FTokenPtr - FBuffer);
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLTokenizer.TokenString: WideString;
begin
SetString(Result, FTokenPtr, FSourcePtr - FTokenPtr);
end;
//----------------------------------------------------------------------------------------------------------------------
function TSQLTokenizer.TokenSymbolIs(const S: WideString): Boolean;
var
Len: Integer;
begin
Len := Length(S);
Result := (FToken = toSymbol) and (Len = (FSourcePtr - FTokenPtr));
if Result then
Result := StrLCompW(PWideChar(S), FTokenPtr, Len) = 0;
end;
//----------------- TrieStatistics -------------------------------------------------------------------------------------
procedure TrieStatistics(Trie: THashTrie; var MaxLevel, PeakCount, FillCount, EmptyCount: Integer;
var LengthStatistics: TLengthStatistics);
// Helper procedure to return information about a trie.
//--------------- local function --------------------------------------------
procedure TreeStat(Item: THashTreeItem);
var
I, J: Integer;
LinkedItem: THashLinkedItem;
begin
Inc(PeakCount);
if Item.FLevel + 1 > MaxLevel then
MaxLevel := Item.FLevel + 1;
for J := 0 to High(Item.FItems) do
if Assigned(Item.FItems[J]) then
begin
Inc(FillCount);
if Item.FItems[J] is THashTreeItem then
TreeStat(THashTreeItem(Item.FItems[J]))
else
begin
I := 0;
LinkedItem := THashLinkedItem(Item.FItems[J]);
while Assigned(LinkedItem) do
begin
Inc(I);
LinkedItem := LinkedItem.FNext;
end;
Inc(LengthStatistics[I]);
end;
end
else
Inc(EmptyCount);
end;
//--------------- end local function ----------------------------------------
begin
MaxLevel := 0;
PeakCount := 0;
FillCount := 0;
EmptyCount := 0;
if Assigned(Trie.FRoot) then
TreeStat(Trie.FRoot);
end;
//----------------- THashTreeItem --------------------------------------------------------------------------------------
constructor THashTreeItem.Create(AOwner: THashTrie);
begin
FOwner := AOwner;
end;
//----------------------------------------------------------------------------------------------------------------------
destructor THashTreeItem.Destroy;
begin
Clear;
inherited;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure THashTreeItem.Clear;
var
I: Integer;
LinkedItem: THashLinkedItem;
begin
for I := 0 to High(FItems) do
if FItems[I] is THashTreeItem then
THashTreeItem(FItems[I]).Free
else
begin
LinkedItem := THashLinkedItem(FItems[I]);
while Assigned(LinkedItem) do
begin
FOwner.DestroyItem(LinkedItem.FValue, LinkedItem.FData);
LinkedItem := LinkedItem.FNext;
end;
THashLinkedItem(FItems[I]).Free;
end;
FItems := nil;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure THashTreeItem.AddDown(Value, Hash: Cardinal; const Data: Pointer);
var
I, J: Integer;
TreeItem: THashTreeItem;
LinkedItem: THashLinkedItem;
begin
I := Hash and $FF;
if High(FItems) < I then
SetLength(FItems, I + 1);
if FItems[I] = nil then
begin
FItems[I] := THashLinkedItem.Create(Value, Data, nil);
Inc(FFilled);
end
else
if FItems[I] is THashTreeItem then
THashTreeItem(FItems[I]).AddDown(Value, ROR(Hash), Data)
else
begin
J := 0;
LinkedItem := THashLinkedItem(FItems[I]);
while Assigned(LinkedItem) do
begin
if FOwner.CompareValue(LinkedItem.FValue, Value) then
begin
// found
LinkedItem.FData := Data;
Exit;
end;
LinkedItem := LinkedItem.FNext;
Inc(J)
end;
if J >= BucketSize then
begin
// full
TreeItem := THashTreeItem.Create(FOwner);
TreeItem.FLevel := FLevel + 1;
LinkedItem := THashLinkedItem(FItems[I]);
while Assigned(LinkedItem) do
begin
TreeItem.AddDown(LinkedItem.FValue, RORN(FOwner.HashValue(LinkedItem.FValue), FLevel + 1), LinkedItem.FData);
LinkedItem := LinkedItem.FNext;
end;
TreeItem.AddDown(Value, ROR(Hash), Data);
THashLinkedItem(FItems[I]).Free;
FItems[I] := TreeItem;
end
else
FItems[I] := THashLinkedItem.Create(Value, Data, THashLinkedItem(FItems[I]));
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure THashTreeItem.Delete(Value, Hash: Cardinal);
var
I: Integer;
PrevLinkedItem,
LinkedItem: THashLinkedItem;
begin
I := Hash and $FF;
if High(FItems) < I then
SetLength(FItems, I + 1);
if Assigned(FItems[I]) then
begin
if FItems[i] is THashTreeItem then
begin
THashTreeItem(FItems[I]).Delete(Value, ROR(Hash));
if THashTreeItem(FItems[I]).FFilled = 0 then
begin
THashTreeItem(FItems[I]).Free;
FItems[I] := nil;
end;
end
else
begin
PrevLinkedItem := nil;
LinkedItem := THashLinkedItem(FItems[I]);
while Assigned(LinkedItem) do
begin
if FOwner.CompareValue(LinkedItem.FValue, Value) then
begin
// found
if PrevLinkedItem = nil then
begin
FItems[I] := LinkedItem.FNext;
if FItems[I] = nil then
Dec(FFilled);
end
else
PrevLinkedItem.FNext := LinkedItem.FNext;
LinkedItem.FNext := nil;
FOwner.DestroyItem(LinkedItem.FValue, LinkedItem.FData);
LinkedItem.Free;
Exit;
end;
PrevLinkedItem := LinkedItem;
LinkedItem := LinkedItem.FNext;
end;
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function THashTreeItem.Find(Value, Hash: Cardinal; var Data: Pointer): Boolean;
var
I: Integer;
LinkedItem: THashLinkedItem;
begin
Result := False;
I := Hash and $FF;
if High(FItems) < I then
SetLength(FItems, I + 1);
if Assigned(FItems[I]) then
begin
if FItems[I] is THashTreeItem then
Result := THashTreeItem(FItems[I]).Find(Value, ROR(Hash), Data)
else
begin
LinkedItem := THashLinkedItem(FItems[I]);
while Assigned(LinkedItem) do
begin
if FOwner.CompareValue(LinkedItem.FValue, Value) then
begin
// found
Data := LinkedItem.FData;
Result := True;
Exit;
end;
LinkedItem := LinkedItem.FNext;
end;
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function THashTreeItem.GetFilled: Integer;
var
I: Integer;
LinkedItem: THashLinkedItem;
begin
Result := 0;
for I := 0 to High(FItems) do
if FItems[I] is THashTreeItem then
Inc(Result, THashTreeItem(FItems[I]).GetFilled)
else
begin
LinkedItem := THashLinkedItem(FItems[I]);
while Assigned(LinkedItem) do
begin
Inc(Result);
LinkedItem := LinkedItem.FNext;
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function THashTreeItem.Modify(Value, Hash: Cardinal; const Data: Pointer): Boolean;
var
I: Integer;
LinkedItem: THashLinkedItem;
begin
Result := False;
I := Hash and $FF;
if High(FItems) < I then
SetLength(FItems, I + 1);
if Assigned(FItems[I]) then
begin
if FItems[I] is THashTreeItem then
Result := THashTreeItem(FItems[I]).Modify(Value, ROR(Hash), Data)
else
begin
LinkedItem := THashLinkedItem(FItems[I]);
while Assigned(LinkedItem) do
begin
if FOwner.CompareValue(LinkedItem.FValue, Value) then
begin
// found
LinkedItem.FData := Data;
Result := True;
Exit;
end;
LinkedItem := LinkedItem.FNext;
end;
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function THashTreeItem.ROR(Value: Cardinal): Cardinal;
begin
Result := ((Value and $FF) shl 24) or ((Value shr 8) and $FFFFFF);
end;
//----------------------------------------------------------------------------------------------------------------------
function THashTreeItem.RORN(Value: Cardinal; Level: Integer): Cardinal;
begin
Result := Value;
while Level > 0 do
begin
Result := ROR(Result);
Dec(Level);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function THashTreeItem.Traverse(UserData, UserProc: Pointer; TraverseProc: TTraverseProc): Boolean;
var
I: Integer;
LinkedItem: THashLinkedItem;
begin
Result := False;
for I := 0 to High(FItems) do
if Assigned(FItems[I]) then
begin
if FItems[I] is THashTreeItem then
Result := THashTreeItem(FItems[I]).Traverse(UserData, UserProc, TraverseProc)
else
begin
LinkedItem := THashLinkedItem(FItems[I]);
while Assigned(LinkedItem) do
begin
TraverseProc(UserData, UserProc, LinkedItem.FValue, LinkedItem.FData, Result);
LinkedItem := LinkedItem.FNext;
end;
end;
if Result then
Break;
end;
end;
//----------------- THashLinkedItem ------------------------------------------------------------------------------------
constructor THashLinkedItem.Create(Value: Cardinal; Data: Pointer; Next: THashLinkedItem);
begin
FValue := Value;
FData := Data;
FNext := Next;
end;
//----------------------------------------------------------------------------------------------------------------------
destructor THashLinkedItem.Destroy;
begin
FNext.Free;
end;
//----------------- THashTrei ------------------------------------------------------------------------------------------
constructor THashTrie.Create;
begin
inherited;
FRoot := THashTreeItem.Create(Self);
end;
//----------------------------------------------------------------------------------------------------------------------
destructor THashTrie.Destroy;
begin
FRoot.Free;
inherited;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure THashTrie.Clear;
begin
FRoot.Clear;
end;
//----------------------------------------------------------------------------------------------------------------------
function THashTrie.Find(Value, Hash: Cardinal; var Data: Pointer): Boolean;
begin
Result := FRoot.Find(Value, Hash, Data);
end;
//----------------------------------------------------------------------------------------------------------------------
function THashTrie.GetCount: Integer;
begin
Result := FRoot.GetFilled;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure THashTrie.AddDown(Value, Hash: Cardinal; const Data: Pointer);
begin
FRoot.AddDown(Value, Hash, Data);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure THashTrie.Delete(Value, Hash: Cardinal);
begin
FRoot.Delete(Value, Hash);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure THashTrie.Traverse(UserData, UserProc: Pointer; TraverseProc: TTraverseProc);
begin
FRoot.Traverse(UserData, UserProc, TraverseProc);
end;
//----------------- TStringHashTrie ------------------------------------------------------------------------------------
procedure TStringHashTrie.Add(const S: string; const Data: Pointer);
var
Value: PChar;
begin
Value := StrNew(PChar(S));
AddDown(Cardinal(Value), HashStr(S), Data);
end;
//----------------------------------------------------------------------------------------------------------------------
function TStringHashTrie.CompareValue(Value1, Value2: Cardinal): Boolean;
begin
if FCaseSensitive then
Result := StrComp(PChar(Value1), PChar(Value2)) = 0
else
Result := StrIComp(PChar(Value1), PChar(Value2)) = 0
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TStringHashTrie.Delete(const S: string);
begin
inherited Delete(Cardinal(@S), HashStr(S));
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TStringHashTrie.DestroyItem(var Value: Cardinal; var Data: Pointer);
begin
if Assigned(FOnFreeItem) then
FOnFreeItem(Self, PChar(Value), Data);
StrDispose(PChar(Value));
Value := 0;
Data := nil;
end;
//----------------------------------------------------------------------------------------------------------------------
function TStringHashTrie.Find(const S: string; var Data: Pointer): Boolean;
begin
Result := Find(Cardinal(PChar(S)), HashStr(S), Data);
end;
//----------------------------------------------------------------------------------------------------------------------
function TStringHashTrie.HashStr(const S: string): Cardinal;
begin
if FCaseSensitive then
Result := CalcStrCRC32(S)
else
Result := CalcStrCRC32(ANSIUpperCase(S));
end;
//----------------------------------------------------------------------------------------------------------------------
function TStringHashTrie.HashValue(Value: Cardinal): Cardinal;
begin
Result := HashStr(PChar(Value));
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TStringHashTrie.Traverse(UserData: Pointer; UserProc: TStrHashTraverseProc);
begin
inherited Traverse(UserData, @UserProc, TraverseProc);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TStringHashTrie.TraverseProc(UserData, UserProc: Pointer; Value: Cardinal; Data: Pointer; var Done: Boolean);
begin
TStrHashTraverseProc(UserProc)(UserData, PChar(Value), Data, Done);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TStringHashTrie.Traverse(UserData: Pointer; UserProc: TStrHashTraverseMeth);
begin
inherited Traverse(UserData, @TMethod(UserProc), TraverseMeth);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TStringHashTrie.TraverseMeth(UserData, UserProc: Pointer; Value: Cardinal; Data: Pointer; var Done: Boolean);
type
PTStrHashTraverseMeth = ^TStrHashTraverseMeth;
begin
PTStrHashTraverseMeth(UserProc)^(UserData, PChar(Value), Data, Done);
end;
//----------------------------------------------------------------------------------------------------------------------
initialization
finalization
Directives.Free;
end.
|