1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005
|
{
Copyright 1998-2018 PasDoc developers.
This file is part of "PasDoc".
"PasDoc" 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.
"PasDoc" 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 "PasDoc"; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
----------------------------------------------------------------------------
}
{ @abstract(Parse ObjectPascal code.)
@author(Ralf Junker (delphi@zeitungsjunge.de))
@author(Marco Schmidt (marcoschmidt@geocities.com))
@author(Johannes Berg <johannes@sipsolutions.de>)
@author(Michalis Kamburelis)
@author(Arno Garrels <first name.name@nospamgmx.de>)
Contains the @link(TParser) object, which can parse an ObjectPascal
code, and put the collected information into the TPasUnit instance. }
unit PasDoc_Parser;
{$I pasdoc_defines.inc}
interface
uses SysUtils, Classes, Contnrs, StrUtils,
PasDoc_Types,
PasDoc_Items,
PasDoc_Scanner,
PasDoc_Tokenizer,
PasDoc_StringPairVector,
PasDoc_StringVector;
type
{ Raised when an impossible situation (indicating bug in
pasdoc) occurs. }
EInternalParserError = class(Exception);
TItemParseMode = (pmUndefined, pmConst, pmVar, pmType);
{ @name stores a CIO reference and current state. }
TPasCioHelper = class(TObject)
private
FCio: TPasCio;
FCurVisibility: TVisibility;
FMode: TItemParseMode;
FSkipCioDecl: Boolean;
public
{ Frees included objects and calls its own destructor. Objects are not
owned by default. }
procedure FreeAll;
property Cio: TPasCio read FCio write FCio;
property CurVisibility: TVisibility read FCurVisibility write FCurVisibility;
property Mode: TItemParseMode read FMode write FMode;
property SkipCioDecl: Boolean read FSkipCioDecl write FSkipCioDecl;
end;
{ A stack of @link(TPasCioHelper) objects currently used to parse nested
classes and records }
TPasCioHelperStack = class(TObjectStack)
public
{ Frees all items including their CIOs and clears the stack }
procedure Clear;
function Push(AHelper: TPasCioHelper): TPasCioHelper;
{$IFDEF USE_INLINE} inline; {$ENDIF}
function Pop: TPasCioHelper; {$IFDEF USE_INLINE} inline; {$ENDIF}
function Peek: TPasCioHelper; {$IFDEF USE_INLINE} inline; {$ENDIF}
end;
// @name stores a series of @link(TRawDescriptionInfo TRawDescriptionInfos).
// It is modelled after TStringList but has only the minimum number
// of methods required for use in PasDoc.
TRawDescriptionInfoList = class(TObject)
private
// @name holds the @link(TRawDescriptionInfo TRawDescriptionInfos) in @classname
FItems: array of TRawDescriptionInfo;
// @name holds the number of items currently stored in @classname.
// @seealso(Count).
FCount: integer;
// @name is the read specifier for @link(Items)
function GetItems(Index: integer): TRawDescriptionInfo;
// @name expands the capacity of @link(FItems).
procedure Grow;
public
// @name adds a new @link(TRawDescriptionInfo) to @classname.
function Append(Comment: TRawDescriptionInfo): integer;
// @name is the number of @link(TRawDescriptionInfo TRawDescriptionInfos) in
// @classname.
property Count: integer read FCount;
Constructor Create;
// @name provides read access to the
// @link(TRawDescriptionInfo TRawDescriptionInfos) in @classname.
property Items[Index: integer]: TRawDescriptionInfo read GetItems; default;
end;
TOwnerItemType = (otUnit, otCio);
{ Parser class that will process a complete unit file and all of its
include files, regarding directives.
When creating this object constructor @link(Create) takes as an argument
an input stream and a list of directives.
Parsing work is done by calling @link(ParseUnitOrProgram) method.
If no errors appear, should return a @link(TPasUnit) object with
all information on the unit. Else exception is raised.
Things that parser inits in items it returns:
@unorderedList(
@item(Of every TPasItem :
Name, RawDescription, Visibility, HintDirectives, DeprecatedNote,
FullDeclararation (note: for now not all items
get sensible FullDeclararation, but the intention is to improve this
over time; see @link(TPasItem.FullDeclaration) to know where
FullDeclararation is available now).
Note to IsDeprecated: parser inits it basing on hint directive
"deprecated" presence in source file; it doesn't handle the fact
that @@deprecated tag may be specified inside RawDescription.
Note to RawDescription: parser inits them from user's comments
that preceded given item in source file.
It doesn't handle the fact that @@member and @@value tags
may also assign RawDescription for some item.)
@item Of TPasCio: Ancestors, Fields, Methods, Properties, MyType.
@item Of TPasEnum: Members, FullDeclararation.
@item Of TPasMethod: What.
@item Of TPasVarConst: FullDeclaration.
@item(Of TPasProperty: IndexDecl, FullDeclaration.
PropType (only if was specified in property declaration).
It was intended that parser will also set Default,
NoDefault, StoredId, DefaultId, Reader, Writer attributes,
but it's still not implemented.)
@item(Of TPasUnit; UsesUnits, Types, Variables, CIOs, Constants,
FuncsProcs.)
)
It doesn't init other values.
E.g. AbstractDescription or DetailedDescription of TPasItem
should be inited while expanding this item's tags.
E.g. SourceFileDateTime and SourceFileName of TPasUnit must
be set by other means. }
TParser = class
private
FImplicitVisibility: TImplicitVisibility;
FCioSk : TPasCioHelperStack;
{ Last comment found in input.
This only takes into account normal comments, i.e. not back-comments.
Modified by @link(GetLastComment) and @link(PeekNextToken)
(and consequently by all @link(PeekNextToken) and @link(GetNextToken)
versions).
LastCommentContent is only the comment content, with comment braces
and markers already stripped. }
IsLastComment: boolean;
LastCommentWasCStyle, LastCommentHelpInsight: boolean;
LastCommentInfo: TRawDescriptionInfo;
AttributeIsPossible: boolean;
CurrentAttributes: TStringPairVector;
{ The underlying scanner object. }
Scanner: TScanner;
FOnMessage: TPasDocMessageEvent;
FVerbosity: Cardinal;
FCommentMarkers: TStringList;
FIgnoreMarkers: TStringList;
FMarkersOptional: boolean;
FIgnoreLeading: string;
FShowVisibilities: TVisibilities;
FAutoBackComments: boolean;
FInfoMergeType: TInfoMergeType;
{ These are the items that the next "back-comment"
(the comment starting with "<", see
[https://github.com/pasdoc/pasdoc/wiki/WhereToPlaceComments]
section "Placing comments after the item") will apply to. }
ItemsForNextBackComment: TPasItems;
{ Returns @link(TMethodType) value for corresponding @link(TKeyWord) value.
@raises(EInternalParserError
If given KeyWord has no corresponding @link(TMethodType) value.) }
function KeyWordToMethodType(KeyWord: TKeyWord): TMethodType;
procedure DoError(const AMessage: string;
const AArguments: array of const);
procedure DoMessage(const AVerbosity: Cardinal; const MessageType:
TPasDocMessageType; const AMessage: string; const AArguments: array of const);
{ Checks if T.MyType is ATokenType, if not calls DoError
with appropriate error mesg. }
procedure CheckToken(T: TToken; ATokenType: TTokenType); overload;
{ Checks if T.IsSymbol(ASymbolType), if not calls DoError
with appropriate error mesg. }
procedure CheckToken(T: TToken; ASymbolType: TSymbolType); overload;
{ Checks if T.IsKeyWord(AKeyWord), if not calls DoError
with appropriate error mesg. }
procedure CheckToken(T: TToken; AKeyWord: TKeyWord); overload;
{ Replaces HelpInsight XML tags like <summary> with PasDoc tags }
procedure ExpandHelpInsightDescriptions(var DescriptionInfo: TRawDescriptionInfo);
{ Remove Lazarus %region declarations from a description,
see http://wiki.freepascal.org/IDE_Window:_Editor_Options_Code_Folding#About_.7B.25Region.7D }
procedure RemoveRegionDeclarations(var DescriptionInfo: TRawDescriptionInfo);
{ If not IsLastComment, then returns @link(EmptyRawDescriptionInfo)
otherwise returns LastCommentInfo and sets IsLastComment to false. }
function GetLastComment: TRawDescriptionInfo;
{ Reads tokens and throws them away as long as they are either whitespace
or comments.
Sets WhitespaceCollector to all the whitespace that was skipped.
(Does @italic(not) append them to WhitespaceCollector,
it @italic(sets) WhitespaceCollector to them, deleting previous
WhitespaceCollector value.)
The overloaded version with WhitespaceCollectorItem
@italic(appends) whitespace to WhitespaceCollectorItem.FullDeclaration
(unless WhitespaceCollectorItem is @nil).
Remember that whitespace is always consumed --- unlike the token itself
(which is not "eaten" by peek operation),
whitespace is consumed, so you @italic(must) capture it here, or lose it.
Comments are collected to [Is]LastCommentXxx properties, so that you can
use GetLastComment.
Returns non-white token that was found.
This token is equal to @code(Scanner.PeekToken).
Note that this token was @italic(peeked)
from the stream, i.e. the caller is still responsible for doing
@code(Scanner.ConsumeToken).
Calling this method twice in a row will return the same thing.
Always returns something non-nil (will raise exception in case
of problems, e.g. when stream ended). }
function PeekNextToken(out WhitespaceCollector: string): TToken; overload;
function PeekNextToken(const WhitespaceCollectorItem: TPasItem): TToken; overload;
{ Same thing as PeekNextToken(Dummy) }
function PeekNextToken: TToken; overload;
{ Just like @link(PeekNextToken), but returned token is already consumed.
Next call to @name will return next token. }
function GetNextToken(out WhitespaceCollector: string): TToken; overload;
{ Just like @link(PeekNextToken), but returned token is already consumed.
Moreover, whitespace collected is appended to
WhitespaceCollectorItem.FullDeclaration
(does not delete previous WhitespaceCollectorItem.FullDeclaration value,
it only appends to it).
Unless WhitespaceCollectorItem is @nil. }
function GetNextToken(const WhitespaceCollectorItem: TPasItem): TToken; overload;
function GetNextToken: TToken; overload;
function GetNextTokenNotAttribute(const WhitespaceCollectorItem: TPasItem): TToken; overload;
{ This does @link(GetNextToken), then checks is it a ATokenType
(using @link(CheckToken)), then frees the token.
Returns token Data.
Just a comfortable routine. }
function GetAndCheckNextToken(ATokenType: TTokenType): string; overload;
{ This is an overload for parsing a unit name that may contain one or
more dots ('.')
@param AIsUnitName is a dummy parameter to allow overloading that is assumed to be true }
function GetAndCheckNextToken(ATokenType: TTokenType; AIsUnitname: boolean): string; overload;
{ This does @link(GetNextToken), then checks is it a symbol with
ASymbolType (using @link(CheckToken)), then frees the token.
Returns token Data.
Just a comfortable routine. }
function GetAndCheckNextToken(ASymbolType: TSymbolType): string; overload;
{ This does @link(GetNextToken), then checks is it a keyword with
AKeyWord (using @link(CheckToken)), then frees the token.
Returns token Data.
Just a comfortable routine. }
function GetAndCheckNextToken(AKeyWord: TKeyWord): string; overload;
{ Parses a constructor, a destructor, a function or a procedure
or an operator (for FPC).
Resulting @link(TPasMethod) item will be returned in M.
ClassKeywordString contains the keyword 'class'
in the exact spelling as it was found in input,
for class methods. Else it contains ''.
MethodTypeString contains the keyword 'constructor', 'destructor',
'function' or 'procedure' or standard directive 'operator'
in the exact spelling as it was found in input.
You can specify MethodTypeString = '', this way you avoid including
such keyword at the beginning of returned M.FullDeclaration.
MethodType is used for the What field of the resulting TPasMethod.
This should correspond to MethodTypeString.
D may contain a description or nil. }
procedure ParseCDFP(out M: TPasMethod;
const ClassKeywordString: string;
const MethodTypeString: string; MethodType: TMethodType;
const RawDescriptionInfo: TRawDescriptionInfo;
const NeedName: boolean; InitItemsForNextBackComment: boolean;
const IsGeneric: String);
{ Parses a class, an interface or an object.
U is the unit this item will be added to on success.
N is the name of this item.
CIOType describes if item is class, interface or object.
D may contain a description or nil. }
procedure ParseCIO(const U: TPasUnit;
const CioName, CioNameWithGeneric: string; CIOType: TCIOType;
const RawDescriptionInfo: TRawDescriptionInfo;
const IsInRecordCase: boolean);
procedure ParseCioEx(const U: TPasUnit;
const CioName, CioNameWithGeneric: string; CIOType: TCIOType;
const RawDescriptionInfo: TRawDescriptionInfo;
const IsInRecordCase: boolean);
function ParseCioMembers(const ACio: TPasCio; var Mode: TItemParseMode;
const IsInRecordCase: Boolean; var Visibility: TVisibility): Boolean;
{ Assume that T is "<" symbol, and parse everything up to a matching ">".
Append everything (including this "<") to Content string.
At the end, T is freed and nil. }
procedure ParseGenericTypeIdentifierList(var T: TToken; var Content: string);
procedure ParseCioTypeDecl(out ACio: TPasCio;
const CioName, CioNameWithGeneric: string; CIOType: TCIOType;
const RawDescriptionInfo: TRawDescriptionInfo; var Visibility: TVisibility);
procedure ParseRecordCase(const R: TPasCio; const SubCase: boolean);
procedure ParseConstant(OwnerItemType: TOwnerItemType; out Constant: TPasItem);
{ This parses type, var or const section that doesn't belong to a CIO
(unit intf section, unit impl section, inside a standalone routine).
This assumes that next token is a keyword starting the section.
Method stops when it encounters a keyword that is not part of
type/variable/constant declaration.
U is optional unit object. If it's assigned, parsed items will be added
to corresponding list. If it's @nil, items will be just parsed and
immediately disposed. }
procedure ParseTVCSection(U: TPasUnit);
procedure ParseInterfaceSection(const U: TPasUnit);
procedure ParseImplementationSection(const U: TPasUnit);
procedure ParseProperty(out p: TPasProperty);
procedure ParseType(const U: TPasUnit; IsGeneric: String);
{ This assumes that you just read left parenthesis starting
an enumerated type. It finishes parsing of TPasEnum,
returning is as P. }
procedure ParseEnum(out p: TPasEnum; const Name: string;
const RawDescriptionInfo: TRawDescriptionInfo);
procedure ParseUses(const U: TPasUnit);
{ This parses the sequence of identifiers separated by commas
and ended by symbol FinalSymbol. More specifically in EBNF it parses
TOK_IDENTIFIER (SYM_COMMA TOK_IDENTIFIER)+ FinalSymbol
FinalSymbol must be something else than SYM_COMMA.
After executing this, next token (returned by GetNextToken and PeekNextToken)
will point to the next token right after FinalSymbol.
All found identifiers will be appended to Names.
If RawDescriptions <> nil then this will also get
all comments documenting the identifiers in Names
(it will append the same number of items to
RawDescriptions as it appended to Names).
The strategy how comments are assigned to item in this case is
described on [https://github.com/pasdoc/pasdoc/wiki/WhereToPlaceComments]
(see section "Multiple fields/variables in one declaration"). }
procedure ParseCommaSeparatedIdentifiers(Names: TStrings;
FinalSymbol: TSymbolType;
RawDescriptions: TRawDescriptionInfoList);
procedure ParseVariables(const U: TPasUnit);
{ Parse one variables or fields clause
("one clause" is something like
NAME1, NAME2, ... : TYPE;
i.e. a list of variables/fields sharing one type declaration.)
@param(Items If Items <> nil then it adds parsed variables/fields to Items.)
@param(Visibility will be assigned to Visibility of
each variable/field instance.)
@param(IsInRecordCase indicates if we're within record's case.
It's relevant only if OfObject is true.) }
procedure ParseFieldsVariables(Items: TPasItems;
OfObject: boolean; Visibility: TVisibility; IsInRecordCase: boolean;
const ClassKeyWordString: string = '');
{ Read all tokens until you find a semicolon at brace-level 0 and
end-level (between "record" and "end" keywords) also 0.
Alternatively, also stops before reading "end" without beginning
"record" (so it can handle some cases where declaration doesn't end
with semicolon).
Alternatively, only if IsInRecordCase, also stops before reading
')' without matching '('. That's because fields' declarations
inside record case may be terminated by just ')' indicating
that this case clause terminates, without a semicolon.
If you pass Item <> nil then all read data will be
appended to Item.FullDeclaration. Also hint directives
(Item.HintDirectives, Item.DeprecatedNote) may be set (to true/non-empty) if appropriate
hint directive will occur in source file. }
procedure SkipDeclaration(const Item: TPasItem; IsInRecordCase: boolean);
procedure SetCommentMarkers(const Value: TStringList);
procedure SetIgnoreMarkers(const Value: TStringList);
{ Consume a hint directive (platform, library or deprecated) as long as you
see one. Skips all whitespace and comments.
Sets the Item.HintDirectives and Item.DeprecatedNote as necessary.
Stops when PeekNextToken returns some token that is not a whitespace,
comment or hint directive.
If ConsumeFollowingSemicolon then we will also look for, and consume,
a semicolon following (any one of) the hint directives. This is a little
hazy, but parsing rules for hint directives *are* hazy, the semicolon
sometimes is optional and sometimes required, see tests/ok_hint_directives.pas
testcase.
If ExtendFullDeclaration then the hint directives (and eventual semicolons,
if ConsumeFollowingSemicolon) will also be added to the Item.FullDeclaration). }
procedure ParseHintDirectives(Item: TPasItem;
const ConsumeFollowingSemicolon: boolean = false;
const ExtendFullDeclaration: boolean = false);
procedure ParseUnit(U: TPasUnit);
procedure ParseProgram(U: TPasUnit);
procedure ParseProgramOrLibraryUses(U: TPasUnit);
procedure ParseLibrary(U: TPasUnit);
public
{ Create a parser, initialize the scanner with input stream S.
All strings in SD are defined compiler directives. }
constructor Create(
const InputStream: TStream;
const Directives: TStringVector;
const IncludeFilePaths: TStringVector;
const OnMessageEvent: TPasDocMessageEvent;
const VerbosityLevel: Cardinal;
const AStreamName, AStreamPath: string;
const AHandleMacros: boolean);
{ Release all dynamically allocated memory. }
destructor Destroy; override;
{ This does the real parsing work, creating U unit and parsing
InputStream and filling all U properties. }
procedure ParseUnitOrProgram(var U: TPasUnit);
property OnMessage: TPasDocMessageEvent read FOnMessage write FOnMessage;
property CommentMarkers: TStringList read FCommentMarkers write SetCommentMarkers;
property MarkersOptional: boolean read fMarkersOptional write fMarkersOptional;
property IgnoreLeading: string read FIgnoreLeading write FIgnoreLeading;
property IgnoreMarkers: TStringList read FIgnoreMarkers write SetIgnoreMarkers;
property ShowVisibilities: TVisibilities
read FShowVisibilities write FShowVisibilities;
{ See command-line option @--implicit-visibility documentation at
[https://github.com/pasdoc/pasdoc/wiki/ImplicitVisibilityOption] }
property ImplicitVisibility: TImplicitVisibility
read FImplicitVisibility write FImplicitVisibility;
{ See command-line option @--auto-back-comments documentation at
[https://github.com/pasdoc/pasdoc/wiki/AutoBackComments] }
property AutoBackComments: boolean read FAutoBackComments write FAutoBackComments;
{}{ TODO comment }
property InfoMergeType: TInfoMergeType read FInfoMergeType write FInfoMergeType;
end;
implementation
uses
{$ifdef FPC_RegExpr} RegExpr, {$endif}
{$ifdef DELPHI_RegularExpressions} RegularExpressions, {$endif}
PasDoc_Utils, PasDoc_Hashes;
{ ---------------------------------------------------------------------------- }
{ TParser }
{ ---------------------------------------------------------------------------- }
constructor TParser.Create(
const InputStream: TStream;
const Directives: TStringVector;
const IncludeFilePaths: TStringVector;
const OnMessageEvent: TPasDocMessageEvent;
const VerbosityLevel: Cardinal;
const AStreamName, AStreamPath: string;
const AHandleMacros: boolean);
begin
inherited Create;
FOnMessage := OnMessageEvent;
FVerbosity := VerbosityLevel;
Scanner := TScanner.Create(InputStream, OnMessageEvent,
VerbosityLevel, AStreamName, AStreamPath, AHandleMacros);
Scanner.AddSymbols(Directives);
Scanner.IncludeFilePaths := IncludeFilePaths;
FCommentMarkers := TStringlist.Create;
FIgnoreMarkers := TStringlist.Create;
ItemsForNextBackComment := TPasItems.Create(false);
FCioSk := TPasCioHelperStack.Create;
CurrentAttributes := TStringPairVector.Create(true);
end;
{ ---------------------------------------------------------------------------- }
destructor TParser.Destroy;
begin
CurrentAttributes.Free;
FCommentMarkers.Free;
FIgnoreMarkers.Free;
Scanner.Free;
ItemsForNextBackComment.Free;
FCioSk.Free;
inherited;
end;
{ ---------------------------------------------------------------------------- }
function TParser.KeyWordToMethodType(KeyWord: TKeyWord): TMethodType;
begin
case KeyWord of
KEY_CONSTRUCTOR: Result := METHOD_CONSTRUCTOR;
KEY_DESTRUCTOR: Result := METHOD_DESTRUCTOR;
KEY_FUNCTION: Result := METHOD_FUNCTION;
KEY_PROCEDURE: Result := METHOD_PROCEDURE;
else
raise EInternalParserError.Create('KeyWordToMethodType: invalid keyword');
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.DoError(const AMessage: string;
const AArguments: array of const);
begin
raise EPasDoc.Create(Scanner.GetStreamInfo + ': ' + AMessage, AArguments, 1);
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.DoMessage(const AVerbosity: Cardinal; const MessageType:
TPasDocMessageType; const AMessage: string; const AArguments: array of const);
begin
if (AVerbosity <= FVerbosity) and Assigned(FOnMessage) then
FOnMessage(MessageType, Format(AMessage, AArguments), AVerbosity);
end;
procedure TParser.ExpandHelpInsightDescriptions(var DescriptionInfo: TRawDescriptionInfo);
{$ifdef FPC_RegExpr}
function ReplaceRegEx(const AInputStr, ARegExpr, AReplaceStr: string): string;
begin
Result := ReplaceRegExpr(ARegExpr, AInputStr, AReplaceStr, true);
end;
{$else}
{$ifdef DELPHI_RegularExpressions}
function ReplaceRegEx(const AInputStr, ARegExpr, AReplaceStr: string): string;
begin
Result := TRegEx.Replace(AInputStr, ARegExpr, AReplaceStr);
end;
{$else}
{ No regular expressions support, help insight comments will not work. }
function ReplaceRegEx(const AInputStr, ARegExpr, AReplaceStr: string): string;
begin
Result := AInputStr;
end;
{$endif}
{$endif}
var s: string;
begin
s := DescriptionInfo.Content;
s := ReplaceRegEx(s, '<summary[^>]*>', '@abstract(');
s := ReplaceRegEx(s, '</summary>', ')');
{ handle <param.. before <para.., otherwise <para.. would match <param.. too }
s := ReplaceRegEx(s, '<param[ \t]+name[ \t]*=[ \t]*"([^"]*)"[ \t]*>', '@param($1 ');
s := ReplaceRegEx(s, '</param>', ')'+LineEnding + LineEnding);
s := ReplaceRegEx(s, '<para[^>]*>', LineEnding + LineEnding);
s := ReplaceRegEx(s, '</para>', LineEnding + LineEnding);
s := ReplaceRegEx(s, '<returns[ ]*([^>]*)>', '@returns($1');
s := ReplaceRegEx(s, '</returns>', ')');
s := ReplaceRegEx(s, '<exception[ \t]+cref[ \t]*=[ \t]*"([^"]*)"[ \t]*>', '@raises($1 ');
s := ReplaceRegEx(s, '<exception[ ]*([^>]*)>', '@raises($1');
s := ReplaceRegEx(s, '</exception>', ')');
s := ReplaceRegEx(s, '<permission[ ]*([^>]*)>', '@permission($1'); //not yet implemented
s := ReplaceRegEx(s, '</permission>', ')');
s := ReplaceRegEx(s, '<c>', '@code(');
s := ReplaceRegEx(s, '</c>', ')');
s := ReplaceRegEx(s, '<code>', '@preformatted(');
s := ReplaceRegEx(s, '</code>', ')');
s := ReplaceRegEx(s, '<b>', '@bold(');
s := ReplaceRegEx(s, '</b>', ')');
s := ReplaceRegEx(s, '<strong>', '@bold(');
s := ReplaceRegEx(s, '</strong>', ')');
s := ReplaceRegEx(s, '<i>', '@italic(');
s := ReplaceRegEx(s, '</i>', ')');
s := ReplaceRegEx(s, '<em>', '@italic(');
s := ReplaceRegEx(s, '</em>', ')');
s := ReplaceRegEx(s, '<u>', '@underline('); // not yet implemented
s := ReplaceRegEx(s, '</u>', ')');
s := ReplaceRegEx(s, '<br */?>', '@br');
s := ReplaceRegEx(s, '<ul>', '@unorderedList(');
s := ReplaceRegEx(s, '</ul>', ')');
s := ReplaceRegEx(s, '<ol>', '@orderedList(');
s := ReplaceRegEx(s, '</ol>', ')');
s := ReplaceRegEx(s, '<li>', '@item(');
s := ReplaceRegEx(s, '</li>', ')');
s := ReplaceRegEx(s, '<remark>', '');
s := ReplaceRegEx(s, '</remark>', '');
s := ReplaceRegEx(s, '<remarks>', '');
s := ReplaceRegEx(s, '</remarks>', '');
s := ReplaceRegEx(s, '<comment>', '');
s := ReplaceRegEx(s, '</comment>', '');
s := ReplaceRegEx(s, '<exclude[^/]*/>', '@exclude');
s := ReplaceRegEx(s, '<see[ \t]+cref[ \t]*=[ \t]*"([^"]*)"[ \t]*/>', '@link($1)');
s := ReplaceRegEx(s, '<see[ \t]+cref[ \t]*=[ \t]*"([^"]*)"[ \t]*>', '@link($1 ');
s := ReplaceRegEx(s, '</see>', ')');
s := ReplaceRegEx(s, '<seealso[ \t]+cref[ \t]*=[ \t]*"([^"]*)"[ \t]*/>', '@seealso($1)');
s := ReplaceRegEx(s, '<seealso[ \t]+cref[ \t]*=[ \t]*"([^"]*)"[ \t]*>', '@seealso($1 ');
s := ReplaceRegEx(s, '</seealso>', ')');
DescriptionInfo.Content := s;
end;
procedure TParser.RemoveRegionDeclarations(var DescriptionInfo: TRawDescriptionInfo);
begin
if IsPrefix('%region /fold', DescriptionInfo.Content) then
DescriptionInfo.Content := RemovePrefix('%region /fold', DescriptionInfo.Content)
else
if IsPrefix('%region', DescriptionInfo.Content) then
DescriptionInfo.Content := RemovePrefix('%region', DescriptionInfo.Content)
else
if IsPrefix('%endregion', DescriptionInfo.Content) then
DescriptionInfo.Content := RemovePrefix('%endregion', DescriptionInfo.Content);
end;
{ ---------------------------------------------------------------------------- }
const
SExpectedButFound = '%s expected but %s found';
procedure TParser.CheckToken(T: TToken; ATokenType: TTokenType);
begin
if T.MyType <> ATokenType then
DoError(SExpectedButFound,
[TOKEN_TYPE_NAMES[ATokenType], T.Description]);
end;
procedure TParser.CheckToken(T: TToken; ASymbolType: TSymbolType);
begin
if not T.IsSymbol(ASymbolType) then
DoError(SExpectedButFound,
[Format('symbol "%s"', [SymbolNames[ASymbolType]]), T.Description]);
end;
procedure TParser.CheckToken(T: TToken; AKeyWord: TKeyWord);
begin
if not T.IsKeyWord(AKeyWord) then
DoError(SExpectedButFound,
[Format('reserved word "%s"', [LowerCase(KeyWordArray[AKeyWord])]),
T.Description]);
end;
{ ---------------------------------------------------------------------------- }
function TParser.GetLastComment: TRawDescriptionInfo;
begin
if IsLastComment then
begin
if LastCommentHelpInsight then
ExpandHelpInsightDescriptions(LastCommentInfo);
RemoveRegionDeclarations(LastCommentInfo);
Result := LastCommentInfo;
IsLastComment := false;
end else
Result := EmptyRawDescriptionInfo;
end;
{ ---------------------------------------------------------------------------- }
function TParser.GetNextToken(out WhitespaceCollector: string): TToken;
begin
Result := PeekNextToken(WhitespaceCollector);
Scanner.ConsumeToken;
end;
function TParser.GetNextToken(const WhitespaceCollectorItem: TPasItem): TToken;
begin
Result := PeekNextToken(WhitespaceCollectorItem);
Scanner.ConsumeToken;
end;
function TParser.GetNextToken: TToken;
begin
Result := PeekNextToken;
Scanner.ConsumeToken;
end;
function TParser.GetNextTokenNotAttribute(const WhitespaceCollectorItem: TPasItem): TToken;
var
OldAttributeIsPossible: Boolean;
begin
OldAttributeIsPossible := AttributeIsPossible;
AttributeIsPossible := False;
Result := GetNextToken(WhitespaceCollectorItem);
AttributeIsPossible := OldAttributeIsPossible;
end;
{ ---------------------------------------------------------------------------- }
function TParser.GetAndCheckNextToken(ATokenType: TTokenType): string;
var
T: TToken;
begin
T := GetNextToken;
try
CheckToken(T, ATokenType);
Result := T.Data;
finally
T.Free;
end;
end;
function TParser.GetAndCheckNextToken(ATokenType: TTokenType; AIsUnitname: boolean): string;
var
T: TToken;
s: string;
begin
// note: the Value of AIsUnitName is ignored, assume it is true
Result := '';
while true do begin
T := GetNextToken;
try
CheckToken(T, ATokenType);
Result := Result + T.Data;
finally
T.Free;
end;
t := PeekNextToken(s);
if (s = '') and t.IsSymbol(SYM_PERIOD) then begin
Result := Result + '.';
Scanner.ConsumeToken;
t.Free;
end else
exit;
end;
end;
function TParser.GetAndCheckNextToken(ASymbolType: TSymbolType): string;
var
T: TToken;
begin
T := GetNextToken;
try
CheckToken(T, ASymbolType);
Result := T.Data;
finally
T.Free;
end;
end;
function TParser.GetAndCheckNextToken(AKeyWord: TKeyWord): string;
var
T: TToken;
begin
T := GetNextToken;
try
CheckToken(T, AKeyWord);
Result := T.Data;
finally
T.Free;
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseCDFP(out M: TPasMethod;
const ClassKeywordString: string;
const MethodTypeString: string; MethodType: TMethodType;
const RawDescriptionInfo: TRawDescriptionInfo;
const NeedName: boolean; InitItemsForNextBackComment: boolean;
const IsGeneric: String);
procedure ReadNestedName;
var t: TToken;
begin
t := nil;
repeat
FreeAndNil(t);
t := GetNextToken;
if (t.MyType = TOK_IDENTIFIER) or t.IsSymbol(SYM_PERIOD) then
M.Name := M.Name + t.Data
else
// Whitespaces are allowed ("function TClass . Foo"), just skip them
if t.MyType = TOK_WHITESPACE then
// skip
else
begin
Scanner.UnGetToken(t);
Break;
end;
until False;
end;
{ Reads tokens (adding them to M.FullDeclaration) until a semicolon
(on parenthesis level zero) is found (this final semicolon
is also read and appended to M.FullDeclaration). }
procedure ReadTokensUntilSemicolon;
var
T: TToken;
Level: Integer;
IsSemicolon: Boolean;
begin
Level := 0;
repeat
T := Scanner.GetToken;
try
if T.MyType = TOK_WHITESPACE then
begin
{ add exactly *one space* at the end of M.FullDeclaration }
if Length(M.FullDeclaration) > 0 then
begin
if (M.FullDeclaration[Length(M.FullDeclaration)] <> ' ') then
M.FullDeclaration := M.FullDeclaration + ' ';
end;
end else
if not (T.MyType in TokenCommentTypes) then
M.FullDeclaration := M.FullDeclaration + T.Data;
if T.IsSymbol(SYM_LEFT_PARENTHESIS) then Inc(level);
if T.IsSymbol(SYM_RIGHT_PARENTHESIS) then Dec(level);
IsSemicolon := T.IsSymbol(SYM_SEMICOLON);
finally
FreeAndNil(T);
end;
until IsSemicolon and (Level = 0);
end;
var
t: TToken;
InvalidType, WasDeprecatedDirective: boolean;
begin
t := nil;
WasDeprecatedDirective := false;
M := TPasMethod.Create;
try
M.RawDescriptionInfo^ := RawDescriptionInfo;
M.SetAttributes(CurrentAttributes);
if InitItemsForNextBackComment then
ItemsForNextBackComment.ClearAndAdd(M);
M.What := MethodType;
if IsGeneric <> '' then
M.FullDeclaration := SAppendPart(M.FullDeclaration, ' ', IsGeneric);
if ClassKeyWordString <> '' then
M.FullDeclaration := SAppendPart(M.FullDeclaration, ' ', ClassKeyWordString);
M.FullDeclaration := SAppendPart(M.FullDeclaration, ' ', MethodTypeString);
{ next non-wc token must be the name }
if NeedName then
begin
t := GetNextToken;
if (MethodType = METHOD_OPERATOR) then
begin
{ In FPC operators "or", "and", "xor" (expressed as keywords) can be
overloaded, also symbolic operators like "+", "*" etc..
In Delphi 2006+ "operator" is followed by identifiers like
"Implicit", "Explicit" or "LogicalNot", "BitwiseAnd" etc.. }
InvalidType := (t.MyType <> TOK_IDENTIFIER) and
(t.MyType <> TOK_SYMBOL) and (t.MyType <> TOK_KEYWORD);
end
else
InvalidType := (t.MyType <> TOK_IDENTIFIER);
if InvalidType then
DoError('Unexpected token %s', [T.Description]);
{ Consume all following period-delimited identifiers as a single name.
Actual only when reading impl section. Resulting name requires additional
processing (splitting to class and method names).
Not used for FPC keyword and symbol operators }
if (MethodType = METHOD_OPERATOR) and (t.MyType <> TOK_IDENTIFIER) then
M.Name := t.Data
else
begin
Scanner.UnGetToken(t);
ReadNestedName;
end;
DoMessage(5, pmtInformation, 'Parsing %s "%s"',
[MethodTypeToString(MethodType), M.Name]);
M.FullDeclaration := M.FullDeclaration + ' ' + M.Name;
FreeAndNil(t);
end;
ReadTokensUntilSemicolon;
{ first get non-WC token - if it is not an identifier in SD_SET put it back
into stream and leave; otherwise copy tokens until semicolon }
repeat
FreeAndNil(t);
t := GetNextToken;
if t.MyType = TOK_IDENTIFIER then
begin
case t.Info.StandardDirective of
SD_ABSTRACT, SD_ASSEMBLER, SD_CDECL, SD_DYNAMIC, SD_EXPORT,
SD_FAR, SD_FORWARD, SD_NEAR, SD_OVERLOAD, SD_OVERRIDE, SD_INLINE,
SD_PASCAL, SD_REGISTER, SD_SAFECALL, SD_STATIC,
SD_STDCALL, SD_REINTRODUCE, SD_VIRTUAL,
SD_VARARGS, SD_FINAL:
begin
M.Directives := M.Directives + [t.Info.StandardDirective];
M.FullDeclaration := M.FullDeclaration + ' ' + t.Data;
FreeAndNil(t);
t := GetNextToken;
end;
{ * External declarations might be followed by a string constant.
* Messages are followed by an integer constant between 1 and 49151 which
specifies the message ID.
* Deprecated might be followed by a string constant since D2010. }
SD_EXTERNAL, SD_MESSAGE, SD_NAME, SD_DEPRECATED:
begin
M.Directives := M.Directives + [t.Info.StandardDirective];
WasDeprecatedDirective := t.Info.StandardDirective = SD_DEPRECATED;
if WasDeprecatedDirective then
M.HintDirectives := M.HintDirectives + [hdDeprecated];
M.FullDeclaration := M.FullDeclaration + ' ' + t.Data;
FreeAndNil(t);
// Keep on reading up to the next semicolon or declaration
repeat
t := GetNextToken;
if t.IsSymbol(SYM_SEMICOLON) then
Break;
{ Some directives mean that the next part starts immediately,
without a semicolon between. For example,
"deprecated platform" may be placed after a procedure
(without a semicolon after "deprecated"). }
if t.MyType = TOK_IDENTIFIER then
case t.Info.StandardDirective of
SD_ABSTRACT, SD_ASSEMBLER, SD_CDECL, SD_DYNAMIC, SD_EXPORT,
SD_EXTERNAL,
SD_FAR, SD_FORWARD, SD_NEAR, SD_OVERLOAD, SD_OVERRIDE,
SD_PASCAL, SD_REGISTER, SD_SAFECALL, SD_STATIC,
SD_STDCALL, SD_REINTRODUCE, SD_VIRTUAL,
SD_DEPRECATED, SD_PLATFORM, SD_EXPERIMENTAL:
begin
M.Directives := M.Directives + [t.Info.StandardDirective];
Scanner.UnGetToken(t);
Break;
end;
end;
if WasDeprecatedDirective then
begin
if T.MyType = TOK_STRING then
M.DeprecatedNote := M.DeprecatedNote + T.StringContent else
{ end WasDeprecatedDirective on non-string token, summing
all previous string tokens into M.DeprecatedNote }
WasDeprecatedDirective := false;
end;
M.FullDeclaration := M.FullDeclaration + ' ' + t.Data;
FreeAndNil(t);
until False;
end;
SD_PLATFORM:
begin
M.FullDeclaration := M.FullDeclaration + ' ' + t.Data;
M.HintDirectives := M.HintDirectives + [hdPlatform];
FreeAndNil(t);
t := GetNextToken;
end;
SD_EXPERIMENTAL:
begin
M.FullDeclaration := M.FullDeclaration + ' ' + t.Data;
M.HintDirectives := M.HintDirectives + [hdExperimental];
FreeAndNil(t);
t := GetNextToken;
end;
SD_DISPID:
begin
M.FullDeclaration := M.FullDeclaration + ' ' + t.Data;
FreeAndNil(T);
ReadTokensUntilSemicolon;
t := GetNextToken;
end;
else //case
Scanner.UnGetToken(t);
Break;
end; // case
end else
if t.MyType = TOK_KEYWORD then
begin
case t.Info.KeyWord of
KEY_INLINE: begin
M.FullDeclaration := M.FullDeclaration + ' ' + t.Data;
FreeAndNil(t);
t := GetNextToken;
end;
KEY_LIBRARY:
begin
M.FullDeclaration := M.FullDeclaration + ' ' + t.Data;
M.HintDirectives := M.HintDirectives + [hdLibrary];
FreeAndNil(t);
t := GetNextToken;
end;
else
begin
Scanner.UnGetToken(t);
Break;
end;
end;
end else
begin
Scanner.UnGetToken(t);
Break;
end;
{ Directives don't have to be separated and be terminated by a semicolon.
This is known at least for combination "deprecated platform".
Apparently, some Delphi versions also allowed not using semicolon
at other places (and we have to mimic compiler behavior, not only
documented behavior, since in practice people (over)use everything
that compiler allows).
So, check is current token a semicolon and append to FullDeclaration.
Note that T may be nil now (e.g. because we used UnGetToken last). }
if (t <> nil) and t.IsSymbol(SYM_SEMICOLON) then
M.FullDeclaration := M.FullDeclaration + ';'
else begin
M.FullDeclaration := M.FullDeclaration + ' ';
if t <> nil then Scanner.UnGetToken(t);
end;
until False;
except
M.Free;
t.Free;
raise;
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseCIO(const U: TPasUnit;
const CioName, CioNameWithGeneric: string; CIOType: TCIOType;
const RawDescriptionInfo: TRawDescriptionInfo;
const IsInRecordCase: boolean);
begin
try
ParseCioEx(U, CioName, CioNameWithGeneric, CIOType, RawDescriptionInfo,
IsInRecordCase);
finally
FCioSk.Clear;
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseConstant(OwnerItemType: TOwnerItemType; out Constant: TPasItem);
var
t: TToken;
WhitespaceCollector: string;
{ Same as SkipDeclaration() except that it returns TRUE if we hit a }
{ procedural constant, it might be followed by a calling convention }
function LocalSkipDeclaration: Boolean;
var
EndLevel, PLevel: Integer;
IsSemicolon: Boolean;
WhitespaceCollectorToAdd: string;
begin
EndLevel := 0;
PLevel := 0;
Result := False;
{AG}
repeat
t := GetNextToken(Constant);
WhitespaceCollectorToAdd := '';
try
case t.MyType of
TOK_SYMBOL:
case t.Info.SymbolType of
SYM_LEFT_PARENTHESIS: Inc(PLevel);
SYM_RIGHT_PARENTHESIS: Dec(PLevel);
end;
TOK_KEYWORD:
case t.Info.KeyWord of
KEY_END: Dec(EndLevel);
KEY_RECORD: Inc(EndLevel);
KEY_LIBRARY:
Constant.HintDirectives := Constant.HintDirectives + [hdLibrary];
KEY_FUNCTION,
KEY_PROCEDURE:
Result := True;
end;
TOK_IDENTIFIER:
case t.Info.StandardDirective of
SD_PLATFORM:
Constant.HintDirectives := Constant.HintDirectives + [hdPlatform];
SD_EXPERIMENTAL:
Constant.HintDirectives := Constant.HintDirectives + [hdExperimental];
SD_DEPRECATED:
begin
Constant.HintDirectives := Constant.HintDirectives + [hdDeprecated];
while PeekNextToken(WhitespaceCollectorToAdd).MyType = TOK_STRING do
begin
{ consume the following string as DeprecatedNote }
Constant.FullDeclaration := Constant.FullDeclaration + t.Data + WhitespaceCollectorToAdd;
FreeAndNil(t);
t := GetNextToken(Constant);
Assert(T.MyType = TOK_STRING); // T is now the same thing we saw with PeekNextToken
Constant.DeprecatedNote := Constant.DeprecatedNote + t.StringContent;
end;
{ otherwise WhitespaceCollectorToAdd will be added later }
end;
end;
end;
IsSemicolon := t.IsSymbol(SYM_SEMICOLON);
{ Reason for "EndLevel < 0" condition:
Within records et al. the last declaration need not be terminated by ;
Reason for "(PLevel < 0) and IsInRecordCase" condition:
See autodoc of SkipDeclaration in TParser interface. }
if (EndLevel < 0) {or
( (PLevel < 0) and IsInRecordCase )} then
begin
Scanner.UnGetToken(t);
Exit;
end;
Constant.FullDeclaration := Constant.FullDeclaration + t.Data + WhitespaceCollectorToAdd;
t.Free;
except
t.Free;
raise;
end;
until IsSemicolon and (EndLevel = 0) and (PLevel = 0);
end;
{/AG}
begin
{ When in CIO treat this constant as a constant field }
case OwnerItemType of
otUnit: Constant := TPasConstant.Create;
otCio: Constant := TPasFieldVariable.Create;
end;
try
Constant.Name := GetAndCheckNextToken(TOK_IDENTIFIER);
DoMessage(5, pmtInformation, 'Parsing constant %s', [Constant.Name]);
Constant.RawDescriptionInfo^ := GetLastComment;
Constant.FullDeclaration := Constant.Name;
Constant.SetAttributes(CurrentAttributes);
{AG}
if LocalSkipDeclaration then
begin
{ Check for following calling conventions }
t := GetNextToken(WhitespaceCollector);
try
case t.Info.StandardDirective of
SD_CDECL, SD_STDCALL, SD_PASCAL, SD_REGISTER, SD_SAFECALL:
begin
Constant.FullDeclaration := Constant.FullDeclaration + WhitespaceCollector;
Constant.FullDeclaration := Constant.FullDeclaration + t.Data;
FreeAndNil(t);
SkipDeclaration(Constant, false);
end;
else
Scanner.UnGetToken(t);
end;
except
t.Free;
raise;
end;
end;
//SkipDeclaration(i, false);
{/AG}
ItemsForNextBackComment.ClearAndAdd(Constant);
if OwnerItemType = otCio then
begin
Constant.FullDeclaration := 'const ' + Constant.FullDeclaration;
TPasFieldVariable(Constant).IsConstant := True;
end;
except
FreeAndNil(Constant);
raise;
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseEnum(out p: TPasEnum;
const Name: string; const RawDescriptionInfo: TRawDescriptionInfo);
var
T: TToken;
Item: TPasItem;
ParenLevel: Integer;
begin
t := nil;
p := TPasEnum.Create;
try
p.Name := Name;
p.RawDescriptionInfo^ := RawDescriptionInfo;
p.FullDeclaration := Name + ' = (...)';
p.SetAttributes(CurrentAttributes);
ItemsForNextBackComment.ClearAndAdd(P);
T := GetNextToken;
while not T.IsSymbol(SYM_RIGHT_PARENTHESIS) do
begin
CheckToken(T, TOK_IDENTIFIER);
Item := TPasItem.Create;
Item.Name := T.Data;
Item.RawDescriptionInfo^ := GetLastComment;
Item.FullDeclaration := Item.Name;
p.Members.Add(Item);
ItemsForNextBackComment.ClearAndAdd(Item);
FreeAndNil(T);
T := GetNextToken;
if T.IsSymbol(SYM_EQUAL) or T.IsSymbol(SYM_ASSIGN) then
begin
Item.FullDeclaration := Item.FullDeclaration + ' ' + T.Data + ' ';
FreeAndNil(T);
{ Now read tokens until comma or right paren (but only on ParenLevel = 0). }
ParenLevel := 0;
repeat
T := GetNextToken;
if (ParenLevel = 0) and
(T.IsSymbol(SYM_COMMA) or T.IsSymbol(SYM_RIGHT_PARENTHESIS)) then
Break;
if T.MyType = TOK_SYMBOL then
case T.Info.SymbolType of
SYM_LEFT_PARENTHESIS, SYM_LEFT_BRACKET: Inc(ParenLevel);
SYM_RIGHT_PARENTHESIS, SYM_RIGHT_BRACKET: Dec(ParenLevel);
end;
Item.FullDeclaration := Item.FullDeclaration + T.Data;
FreeAndNil(T);
until false;
end;
if T.IsSymbol(SYM_COMMA) then
begin
FreeAndNil(T);
T := GetNextToken;
end;
end;
FreeAndNil(T);
{ Read semicolon, as an optional token.
Actually, the stricter rule would be
- if some hint directive ("deprecated" or such) follows,
then semicolon here is prohibited.
- otherwise, semicolon here is required. }
T := PeekNextToken;
if T.IsSymbol(SYM_SEMICOLON) then
begin
P.FullDeclaration := P.FullDeclaration + ';';
Scanner.ConsumeToken;
FreeAndNil(T);
end;
ParseHintDirectives(P, true, true);
except
p.Free;
T.Free;
raise;
end;
end;
procedure TParser.ParseTVCSection(U: TPasUnit);
var
Mode: TItemParseMode;
t, t2: TToken;
ConstantParsed: TPasItem;
begin
Mode := pmUndefined;
repeat
t := GetNextToken;
try
case t.MyType of
TOK_IDENTIFIER:
begin
if t.Info.StandardDirective = SD_OPERATOR then
begin
Scanner.UnGetToken(t);
Break;
end;
case Mode of
pmConst:
begin
Scanner.UnGetToken(t);
ParseConstant(otUnit, ConstantParsed);
if U <> nil then
U.AddConstant(ConstantParsed)
else
FreeAndNil(ConstantParsed);
end;
pmType:
begin
//In latest FPC version it is posible to define generic functions and procedures
if t.IsStandardDirective(SD_GENERIC) then
begin
t2 := PeekNextToken;
if t2.IsKeyWord(KEY_FUNCTION) or t2.IsKeyWord(KEY_PROCEDURE) then
Break
else
ParseType(U, t.Data)
end
else
begin
Scanner.UnGetToken(t);
ParseType(U, '')
end;
AttributeIsPossible := True;
end;
pmVar:
begin
Scanner.UnGetToken(t);
ParseVariables(U);
end;
else
DoError('Unexpected %s', [t.Description]);
end;
end;
TOK_KEYWORD:
begin
// Back comments after a keyword are senseless
ItemsForNextBackComment.Clear;
case t.Info.KeyWord of
KEY_RESOURCESTRING, KEY_CONST:
Mode := pmConst;
KEY_THREADVAR, KEY_VAR:
Mode := pmVar;
KEY_TYPE:
begin
Mode := pmType;
AttributeIsPossible := True;
end;
else
begin
Scanner.UnGetToken(t);
Break;
end;
end;
end;
end;
finally
FreeAndNil(t);
end;
until False;
end;
procedure TParser.ParseInterfaceSection(const U: TPasUnit);
var
M: TPasMethod;
t, t2: TToken;
PropertyParsed: TPasProperty;
begin
DoMessage(4, pmtInformation, 'Entering interface section of unit %s',[U.Name]);
AttributeIsPossible := False;
repeat
t := GetNextToken;
try
case t.MyType of
TOK_IDENTIFIER:
if t.Info.StandardDirective = SD_OPERATOR then
begin
ParseCDFP(M, '', t.Data, METHOD_OPERATOR,
GetLastComment, true, true, '');
U.FuncsProcs.Add(M);
end
//Generics functions and procedures
else if t.IsStandardDirective(SD_GENERIC) then
begin
//Skip generics directive because delphi do not have and we can't return two tokens
t2 := PeekNextToken();
if t2.IsKeyWord(KEY_FUNCTION) or t2.IsKeyWord(KEY_PROCEDURE) then
begin
t := GetNextToken;
try
ParseCDFP(M, '', t.Data, KeyWordToMethodType(t.Info.KeyWord),
GetLastComment, true, true, '');
U.FuncsProcs.Add(M)
finally
FreeAndNil(t)
end;
end
else
DoError('Unexpected %s', [t2.Description]);
end
else
DoError('Unexpected %s', [t.Description]);
TOK_KEYWORD:
begin
case t.Info.KeyWord of
KEY_RESOURCESTRING, KEY_CONST,
KEY_TYPE,
KEY_THREADVAR, KEY_VAR:
begin
Scanner.UnGetToken(t);
ParseTVCSection(U);
end;
KEY_FUNCTION, KEY_PROCEDURE:
begin
ParseCDFP(M, '', t.Data, KeyWordToMethodType(t.Info.KeyWord),
GetLastComment, true, true, '');
U.FuncsProcs.Add(M);
end;
KEY_IMPLEMENTATION:
begin
Scanner.UnGetToken(t);
Break;
end;
KEY_USES:
ParseUses(U);
KEY_PROPERTY:
begin
ParseProperty(PropertyParsed);
U.Variables.Add(PropertyParsed);
end;
else
DoError('Unexpected %s', [t.Description]);
end;
end;
end;
finally
FreeAndNil(t);
end;
until False;
end;
{ Return string value calculated from old and new values according to merge method }
function MergeStringValues(MergeType: TInfoMergeType; const OldValue, NewValue: string): string;
begin
case MergeType of
imtNone:
Result := OldValue;
imtPreferIntf:
Result := IfThen(OldValue <> '', OldValue, NewValue);
// Also process case when OldValue is fully contained in NewValue.
// This allows specifying short abstract in intf section and full description
// in impl section.
// At this stage values are raw, that is, could contain multiple whitespaces.
// We must exclude whitespaces from check.
imtJoin:
// Note: this could be optimized to not use 2nd Trim or even check in-place without
// creation of new string variables.
if (Trim(OldValue) <> '') and not AnsiStartsStr(Trim(OldValue), Trim(NewValue)) then
Result := OldValue + LineEnding + NewValue
else
Result := NewValue;
imtPreferImpl:
Result := IfThen(NewValue <> '', NewValue, OldValue);
end;
end;
{ Merge metadata of Source and Dest method items.
At the stage of parsing impl section these items only have RawDescriptionInfo
so that's the only data we've to merge.
NB: this merge is only correct if method items haven't been processed yet so
there's no sense in moving it to common util unit or TPasMethod members }
procedure MergeMethodData(MergeType: TInfoMergeType; Dest: TPasMethod; const SourceData: TRawDescriptionInfo);
begin
Dest.RawDescriptionInfo^.Content :=
MergeStringValues(MergeType, Dest.RawDescriptionInfo^.Content, SourceData.Content);
end;
procedure TParser.ParseImplementationSection(const U: TPasUnit);
var
// Collector of all ignored items that won't go to `U`
DummyUnit: TPasUnit;
// Clear all comment data that was accumulated by PeekNextToken
procedure ClearComments;
begin
IsLastComment := False;
LastCommentWasCStyle := False;
LastCommentHelpInsight := False;
LastCommentInfo := EmptyRawDescriptionInfo;
end;
{ Function to skip header (parameters declarations) of anon method aka lambda.
Just read until "begin" }
procedure SkipLambdaHeader;
var t: TToken;
begin
t := nil;
repeat
t := PeekNextToken;
if t.IsKeyWord(KEY_BEGIN) then
Break;
Scanner.ConsumeToken;
FreeAndNil(t);
until False;
end;
{ Here we stand:
- at the beginning of a routine's (function/procedure/constructor/destructor)
valuable (non-comment) inner contents (after ParseCDFP invokation)
or
- right after function/procedure keyword (lambda assignment/declaration; parameters
or comment or contents following)
Skip everything until "end;" }
procedure SkipMethodBody(IsLambda: Boolean = False);
var
t: TToken;
EndLevel: Integer;
InsideMethodBody, AsmBlock: Boolean;
M: TPasMethod;
begin
EndLevel := 0; InsideMethodBody := False; AsmBlock := False; t := nil;
repeat
if t = nil then
t := GetNextToken;
// Check only keywords; skip all keywords inside ASM blocks except "end"
if (t.MyType = TOK_KEYWORD) and (not AsmBlock or (t.Info.KeyWord = KEY_END)) then
case t.Info.KeyWord of
// nested var/const/type section
// KEY_RESOURCESTRING and KEY_THREADVAR are not allowed here but let them remain
KEY_RESOURCESTRING, KEY_CONST,
KEY_TYPE,
KEY_THREADVAR, KEY_VAR:
begin
Scanner.UnGetToken(t);
ParseTVCSection(DummyUnit); // ignore section contents
end;
// If we encounter BEGIN or ASM - check that current nesting level is 0,
// this means we've started the entrypoint of this method
KEY_BEGIN, KEY_ASM:
begin
if EndLevel = 0 then
InsideMethodBody := True;
// Asm blocks have different syntax that allows any Pascal keyword, even "end"
// so handle them specially
AsmBlock := (t.Info.KeyWord = KEY_ASM);
Inc(EndLevel);
end;
// Other constructions in the code section that must end with END keyword
KEY_CASE, KEY_TRY:
Inc(EndLevel);
// Nested subroutine / lambda. Run the skip recursively.
KEY_PROCEDURE, KEY_FUNCTION:
begin
// if InsideMethodBody - it's a lambda without name
// otherwise it's a nested subroutine that requires name
if not InsideMethodBody then
begin
ParseCDFP(M, '', '', KeyWordToMethodType(t.Info.KeyWord), GetLastComment, True, False, '');
FreeAndNil(M);
end
else
SkipLambdaHeader;
// There could not be external methods inside a method so skip body unconditionally
SkipMethodBody(InsideMethodBody);
end;
KEY_END:
begin
// ASM blocks can contain labels or identifiers named "end" so check
// whether the "end" is followed by ";". Skip if not
if AsmBlock then
begin
if not PeekNextToken.IsSymbol(SYM_SEMICOLON) then
begin
FreeAndNil(t);
t := GetNextToken;
Continue;
end;
end;
AsmBlock := False;
Dec(EndLevel);
if InsideMethodBody and (EndLevel = 0) then
begin
// for subroutines ";" after "end" is obligatory
if not IsLambda then
GetAndCheckNextToken(SYM_SEMICOLON)
// lambdas could end with
// ";" (var assignment),
// ")" (as parameter in method),
// "," (as one of parameters in method, item of array etc),
// "]" (last item in array)
// ...
else
try
FreeAndNil(t);
t := GetNextToken;
if not ((t.MyType = TOK_SYMBOL) and
(t.Info.SymbolType in [SYM_SEMICOLON, SYM_COMMA,
SYM_RIGHT_PARENTHESIS, SYM_RIGHT_BRACKET])) then
DoError(SExpectedButFound,
['one of ";", ")", ",", "]" symbols', T.Description]);
finally
FreeAndNil(t);
end;
Break;
end;
end;
end;
FreeAndNil(t);
until False;
FreeAndNil(t);
// Empty all comments accumulated inside method body by PeekNextToken
// Otherwise they will go to a next item
ClearComments;
end;
{ Search for method object added by parsing intf section.
Method could be standalone routine, FPC operator or CIO member.
In the latter case it will have fully specified name (TClass.TNestedClass.Proc).
Corresponding method likely could not exist in lists from intf section because
of ignoring or visibility settings.
@param U - unit to search in
@param MethodName - full method name to search for
@param Index - 0-based index of a method overload to search for. Currently
method lists could contain multiple entries with identical names because
of overload feature. Specifying Index allows to search for a concrete item.
Of course this will work correctly only if methods were declared in the
same order as they appear in impl section }
function FindExistingMethod(U: TPasUnit; const MethodName: string; Index: Integer): TPasMethod;
var
NameParts: TNameParts;
i: Integer;
item: TBaseItem;
begin
Result := nil;
// Check if we got a standalone routine or a class/record method
// NB: method could be FPC operator with symbolic name so just check for dot inside
if Pos('.', MethodName) = 0 then
begin
item := U.FuncsProcs.FindListItem(MethodName, Index);
if item <> nil then
Result := item as TPasMethod;
end
else
begin
if not SplitNameParts(MethodName, NameParts) then
DoError('Method name %s is invalid', [MethodName]);
// Search for method owner
item := U.CIOs.FindListItem(NameParts[0]);
// Also in nested classes
if item <> nil then
for i := Low(NameParts) + 1 to High(NameParts) - 1 do
begin
item := (item as TPasCio).CIOs.FindListItem(NameParts[i]);
if item = nil then
Break;
end;
if item <> nil then
Result := (item as TPasCio).Methods.FindListItem(NameParts[High(NameParts)], Index);
end;
// print message for debug purposes
if Result = nil then
DoMessage(5, pmtInformation, 'No definition of %d-th method "%s" found - probably internal or ignored', [Index, MethodName])
end;
{ Read proc/func/class method/operator header and merge its description with
existing item }
procedure HandleMethod(U: TPasUnit; MethodType: TMethodType; IsGeneric: String; MethodCounts: THash = nil;
const ClassKeyWordString: string = '');
var
M, ExistingMethod: TPasMethod;
Count: NativeUInt;
begin
ParseCDFP(M, ClassKeyWordString, MethodTypeToString(MethodType), MethodType,
GetLastComment, True, True, IsGeneric);
// ParseCDFP was called with InitItemsForNextBackComment so it added M to
// ItemsForNextBackComment list. We must clear it so that following comments
// in AutoBackComments mode won't glue to method object which is already disposed
ItemsForNextBackComment.Clear;
// If a method counter is given, search for method inside it. Otherwise
// assume Count is 1.
if MethodCounts <> nil then
begin
Count := NativeUInt(MethodCounts.GetObject(M.Name));
Inc(Count);
MethodCounts.SetObject(M.Name, Pointer(Count));
end
else
Count := 1;
ExistingMethod := FindExistingMethod(U, M.Name, Count - 1);
// NB: Currently we don't add methods not declared in intf section
if ExistingMethod <> nil then
MergeMethodData(FInfoMergeType, ExistingMethod, M.RawDescriptionInfo^);
// External and forward methods have no body
if [SD_FORWARD, SD_EXTERNAL]*M.Directives = [] then
begin
SkipMethodBody;
DoMessage(5, pmtInformation, 'Skipped body of %s "%s"',
[MethodTypeToString(MethodType), M.Name]);
end;
FreeAndNil(M);
end;
var
t, t2: TToken;
PropertyParsed: TPasProperty;
MethodCounts: THash;
begin
{ Parsing impl section clears the comment otherwise comment before "implementation"
keyword would descend to first item of impl section }
ClearComments;
if FInfoMergeType = imtNone then Exit;
DoMessage(4, pmtInformation, 'Entering implementation section of unit %s',[U.Name]);
AttributeIsPossible := False;
MethodCounts := THash.Create; // "[method name]=>count" hash map
{ We can't immediately dispose parsed items because we've got to handle back
comments. So we create dummy container that will gather all ignored items. }
DummyUnit := TPasUnit.Create;
try
repeat
t := GetNextToken;
try
case t.MyType of
TOK_IDENTIFIER:
if t.Info.StandardDirective = SD_OPERATOR then
begin
HandleMethod(U, METHOD_OPERATOR, '');
end
else if t.IsStandardDirective(SD_GENERIC) then
begin
t2 := PeekNextToken;
if t2.Info.KeyWord in [KEY_FUNCTION, KEY_PROCEDURE] then
begin
t2 := GetNextToken;
try
HandleMethod(U, KeyWordToMethodType(t2.Info.KeyWord), t.Data, MethodCounts)
finally
FreeAndNil(t2)
end
end
else
DoError('Unexpected %s', [t2.Description])
end
else
DoError('Unexpected %s', [t.Description]);
TOK_KEYWORD:
begin
case t.Info.KeyWord of
KEY_RESOURCESTRING, KEY_CONST,
KEY_TYPE,
KEY_THREADVAR, KEY_VAR:
begin
Scanner.UnGetToken(t);
ParseTVCSection(DummyUnit); // parse section but don't add to resulting unit
end;
KEY_CLASS:
//ClassKeyWordString := t.Data; // not needed after all
;
KEY_FUNCTION, KEY_PROCEDURE, KEY_CONSTRUCTOR, KEY_DESTRUCTOR:
begin
HandleMethod(U, KeyWordToMethodType(t.Info.KeyWord), '', MethodCounts);
end;
// Do not read unit used internally for now - maybe will do in the future
KEY_USES:
ParseUses(nil);
KEY_PROPERTY:
begin
ParseProperty(PropertyParsed);
FreeAndNil(PropertyParsed);
end;
// Stop parsing on "initialization", "finalization"
KEY_INITIALIZATION, KEY_FINALIZATION:
Break;
// Stop parsing on "end.". Must come here only on final "end" so
// don't care about other cases
KEY_END:
begin
// skip possible whitespaces
repeat
FreeAndNil(t);
t := GetNextToken;
until not (t.MyType = TOK_WHITESPACE);
// token must be period
if t.IsSymbol(SYM_PERIOD) then
Break;
DoError('Unexpected %s', [t.Description]);
end;
else
DoError('Unexpected %s', [t.Description]);
end;
end;
end;
finally
FreeAndNil(t);
end;
until False;
finally
FreeAndNil(MethodCounts);
FreeAndNil(DummyUnit);
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseProperty(out p: TPasProperty);
var
Finished: Boolean;
t: TToken;
begin
t := nil;
p := TPasProperty.Create;
try
p.Name := GetAndCheckNextToken(TOK_IDENTIFIER);
DoMessage(5, pmtInformation, 'Parsing property %s', [p.Name]);
p.IndexDecl := '';
p.Proptype := '';
p.FullDeclaration := 'property ' + p.Name;
p.RawDescriptionInfo^ := GetLastComment;
p.SetAttributes(CurrentAttributes);
ItemsForNextBackComment.ClearAndAdd(P);
{ Is this only a redeclaration of property from ancestor
(to e.g. change it's visibility, or add a hint directive) }
t := GetNextToken(P);
if t.IsSymbol(SYM_SEMICOLON) then
begin
p.FullDeclaration := p.FullDeclaration + ';';
FreeAndNil(t);
ParseHintDirectives(P, true, true);
Exit;
end;
{ get index }
if t.IsSymbol(SYM_LEFT_BRACKET) then
begin
FreeAndNil(t);
p.IndexDecl := '[';
p.FullDeclaration := p.FullDeclaration + '[';
repeat
t := GetNextToken;
if not (t.MyType in TokenCommentTypes + [TOK_DIRECTIVE]) then
begin
p.IndexDecl := p.IndexDecl + t.Data;
p.FullDeclaration := p.FullDeclaration + t.Data;
end;
Finished := t.IsSymbol(SYM_RIGHT_BRACKET);
FreeAndNil(t);
until Finished;
t := GetNextToken;
end;
{ now if there is a colon, it is followed by the type }
if t.IsSymbol(SYM_COLON) then
begin
FreeAndNil(t);
{ get property type }
t := GetNextToken;
if (t.MyType <> TOK_IDENTIFIER) and (t.MyType <> TOK_KEYWORD) then
DoError('Identifier or keyword expected but %s found', [T.Description]);
p.Proptype := t.Data;
FreeAndNil(t);
p.FullDeclaration := p.FullDeclaration + ': ' + p.Proptype;
end else
begin
p.FullDeclaration := p.FullDeclaration + t.Data;
FreeAndNil(t);
end;
{ read the rest of declaration }
SkipDeclaration(P, false);
ParseHintDirectives(P, true, true);
except
p.Free;
t.Free;
raise
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseRecordCase(const R: TPasCio;
const SubCase: boolean);
var
t: TToken;
LNeedId: boolean;
P: TPasFieldVariable;
OldAttribPossible: Boolean;
begin
t := GetNextToken;
try
CheckToken(t, TOK_IDENTIFIER);
if PeekNextToken.IsSymbol(SYM_COLON) then
begin
{ Then we have "case FieldName: FieldType of" }
{ consume and free the colon token }
GetNextToken.Free;
P := TPasFieldVariable.Create;
p.Name := t.Data;
p.RawDescriptionInfo^ := GetLastComment;
p.FullDeclaration := p.Name + ': ' + GetAndCheckNextToken(TOK_IDENTIFIER);
p.SetAttributes(CurrentAttributes);
ItemsForNextBackComment.ClearAndAdd(P);
R.Fields.Add(p);
end;
FreeAndNil(t);
GetAndCheckNextToken(KEY_OF);
CurrentAttributes.Clear;
OldAttribPossible := AttributeIsPossible;
AttributeIsPossible := False;
{ no support for attributes in case record, if found, unexpected behaviour }
t := GetNextToken;
LNeedId := True;
repeat
while true do
begin
case t.MyType of
TOK_SYMBOL:
begin
case t.Info.SymbolType of
SYM_COLON: break;
SYM_COMMA: LNeedId := True;
end;
end;
TOK_IDENTIFIER,
TOK_NUMBER:
if not LNeedId then
DoError('Unexpected %s', [t.Description]);
TOK_KEYWORD:
begin
if not (t.Info.KeyWord in [KEY_OR, KEY_AND]) then
DoError('Unexpected %s', [t.Description]);
end;
else // case
DoError('Unexpected %s', [t.Description]);
end; // case
FreeAndNil(t);
t := GetNextToken;
end;
// read all identifiers before colon
FreeAndNil(t);
GetAndCheckNextToken(SYM_LEFT_PARENTHESIS);
while not PeekNextToken.IsSymbol(SYM_RIGHT_PARENTHESIS) do
begin
if PeekNextToken.IsKeyWord(KEY_CASE) then
begin
GetNextToken.Free; { consume and free "case" token }
ParseRecordCase(R, true);
end else
ParseFieldsVariables(R.Fields, true, viPublic, true);
end;
GetNextToken.Free; // free ')' token
t := GetNextToken;
if t.IsSymbol(SYM_SEMICOLON) then
begin
FreeAndNil(t);
t := GetNextToken;
end;
until t.IsKeyWord(KEY_END) or
(SubCase and t.IsSymbol(SYM_RIGHT_PARENTHESIS));
AttributeIsPossible := OldAttribPossible;
Scanner.UnGetToken(t);
except
t.Free;
raise;
end;
end;
procedure TParser.ParseType(const U: TPasUnit; IsGeneric: String);
function KeyWordToCioType(KeyWord: TKeyword; IsPacked: Boolean): TCIOType;
begin
if not IsPacked then
case KeyWord of
KEY_CLASS: Result := CIO_CLASS;
KEY_DISPINTERFACE: Result := CIO_DISPINTERFACE;
KEY_INTERFACE: Result := CIO_INTERFACE;
KEY_OBJECT: Result := CIO_OBJECT;
KEY_RECORD: Result := CIO_RECORD;
else raise EInternalParserError.Create('KeyWordToCioType: invalid keyword');
end
else
case KeyWord of
KEY_CLASS: Result := CIO_PACKEDCLASS;
KEY_OBJECT: Result := CIO_PACKEDOBJECT;
KEY_RECORD: Result := CIO_PACKEDRECORD;
else raise EInternalParserError.Create('KeyWordToCioType: invalid keyword');
end;
end;
var
RawDescriptionInfo: TRawDescriptionInfo;
NormalType: TPasType;
TypeName: string;
LCollected, LTemp, TypeNameWithGeneric: string;
MethodType: TPasMethod;
EnumType: TPasEnum;
T: TToken;
begin
{ Read the type name, preceded by optional "generic" directive.
Calculate TypeName, IsGeneric, TypeNameWithGeneric.
FPC requires "generic" directive, but Delphi doesn't,
so it's just optional for us (serves for some checks later). }
T := GetNextToken;
try
if IsGeneric = '' then
TypeNameWithGeneric := ''
else
TypeNameWithGeneric := IsGeneric + ' ';
CheckToken(T, TOK_IDENTIFIER);
TypeName := T.Data;
TypeNameWithGeneric := TypeNameWithGeneric + TypeName;
finally FreeAndNil(T) end;
DoMessage(5, pmtInformation, 'Parsing type "%s"', [TypeName]);
RawDescriptionInfo := GetLastComment;
AttributeIsPossible := False;
t := GetNextToken(LCollected);
try
if T.IsSymbol(SYM_LESS_THAN) then
begin
ParseGenericTypeIdentifierList(T, TypeNameWithGeneric);
T := GetNextToken(LCollected);
end;
if T.IsSymbol(SYM_SEMICOLON) then
begin
FreeAndNil(T);
Exit;
end else
if T.IsSymbol(SYM_EQUAL) then
begin
LCollected := TypeNameWithGeneric + LCollected + T.Data;
FreeAndNil(T);
end else
begin
FreeAndNil(T);
DoError('Symbol "=" expected', []);
end;
t := GetNextToken(LTemp);
LCollected := LCollected + LTemp + t.Data;
if (t.MyType = TOK_KEYWORD) then
case t.Info.KeyWord of
KEY_CLASS: begin
FreeAndNil(t);
t := GetNextToken(LTemp);
LCollected := LCollected + LTemp + t.Data;
if t.IsKeyWord(KEY_OF) then
begin
{ include "identifier = class of something;" as standard type }
end else begin
Scanner.UnGetToken(t);
ParseCIO(U, TypeName, TypeNameWithGeneric, CIO_CLASS,
RawDescriptionInfo, False);
Exit;
end;
end;
KEY_DISPINTERFACE,
KEY_INTERFACE,
KEY_OBJECT,
KEY_RECORD: begin
ParseCIO(U, TypeName, TypeNameWithGeneric, KeyWordToCioType(t.Info.KeyWord, False),
RawDescriptionInfo, False);
FreeAndNil(t);
Exit;
end;
KEY_PACKED: begin
FreeAndNil(t);
t := GetNextToken(LTemp);
LCollected := LCollected + LTemp + t.Data;
if t.Info.KeyWord in [KEY_RECORD, KEY_OBJECT, KEY_CLASS] then
begin
// for class - no check for "of", no packed classpointers allowed
ParseCIO(U, TypeName, TypeNameWithGeneric, KeyWordToCioType(t.Info.KeyWord, True),
RawDescriptionInfo, False);
FreeAndNil(t);
Exit;
end;
end;
end;
if Assigned(t) then begin
if (t.MyType = TOK_KEYWORD) then begin
if t.Info.KeyWord in [KEY_FUNCTION, KEY_PROCEDURE] then
begin
ParseCDFP(MethodType, '', t.Data, KeyWordToMethodType(t.Info.KeyWord),
RawDescriptionInfo, false, true, '');
MethodType.Name := TypeName;
MethodType.FullDeclaration :=
TypeName + ' = ' + MethodType.FullDeclaration;
if U <> nil then
U.AddType(MethodType)
else
FreeAndNil(MethodType);
FreeAndNil(t);
Exit;
end;
end;
if t.IsSymbol(SYM_LEFT_PARENTHESIS) then
begin
ParseEnum(EnumType, TypeName, RawDescriptionInfo);
if U <> nil then
U.AddType(EnumType)
else
FreeAndNil(EnumType);
FreeAndNil(t);
Exit;
end;
SetLength(LCollected, Length(LCollected)-Length(t.Data));
Scanner.UnGetToken(t);
end;
FreeAndNil(t);
AttributeIsPossible := True;
NormalType := TPasType.Create;
try
NormalType.FullDeclaration := LCollected;
SkipDeclaration(NormalType, false);
NormalType.Name := TypeName;
NormalType.RawDescriptionInfo^ := RawDescriptionInfo;
NormalType.SetAttributes(CurrentAttributes);
ItemsForNextBackComment.ClearAndAdd(NormalType);
if U <> nil then
U.AddType(NormalType) { This is the last line here since "U" owns the
objects, bad luck if adding the item raised an
exception. }
else
FreeAndNil(NormalType);
except
FreeAndNil(NormalType);
raise;
end;
except
FreeAndNil(t);
raise;
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseUnit(U: TPasUnit);
begin
GetAndCheckNextToken(KEY_UNIT);
U.RawDescriptionInfo^ := GetLastComment;
{ get unit name identifier }
U.Name := GetAndCheckNextToken(TOK_IDENTIFIER, true);
ItemsForNextBackComment.ClearAndAdd(U);
ParseHintDirectives(U);
{ skip semicolon }
GetAndCheckNextToken(SYM_SEMICOLON);
{ get 'interface' keyword }
GetAndCheckNextToken(KEY_INTERFACE);
{ now parse the interface section of that unit }
ParseInterfaceSection(U);
{ get 'implementation' keyword }
GetAndCheckNextToken(KEY_IMPLEMENTATION);
{ now parse the implementation section of that unit }
ParseImplementationSection(U);
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseProgramOrLibraryUses(U: TPasUnit);
var
T: TToken;
begin
U.RawDescriptionInfo^ := GetLastComment;
{ get program/library name identifier }
U.Name := GetAndCheckNextToken(TOK_IDENTIFIER);
ItemsForNextBackComment.ClearAndAdd(U);
ParseHintDirectives(U);
{ skip semicolon }
GetAndCheckNextToken(SYM_SEMICOLON);
T := GetNextToken;
try
if T.IsKeyWord(KEY_USES) then
ParseUses(U);
finally
FreeAndNil(T);
end;
end;
procedure TParser.ParseProgram(U: TPasUnit);
begin
GetAndCheckNextToken(KEY_PROGRAM);
ParseProgramOrLibraryUses(U);
end;
procedure TParser.ParseLibrary(U: TPasUnit);
begin
GetAndCheckNextToken(KEY_LIBRARY);
ParseProgramOrLibraryUses(U);
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseUnitOrProgram(var U: TPasUnit);
var
t: TToken;
begin
U := TPasUnit.Create;
try
t := PeekNextToken;
CheckToken(t, TOK_KEYWORD);
case t.Info.KeyWord of
KEY_UNIT:
begin
U.IsUnit := True;
ParseUnit(U);
end;
KEY_PROGRAM:
begin
U.IsProgram := True;
ParseProgram(U);
end;
KEY_LIBRARY:
ParseLibrary(U);
else
DoError(SExpectedButFound,
[Format('one of reserved words "%s", "%s" or "%s"',
[LowerCase(KeyWordArray[KEY_UNIT]), LowerCase(KeyWordArray[KEY_LIBRARY]), LowerCase(KeyWordArray[KEY_PROGRAM])]),
T.Description]);
end;
except
FreeAndNil(U);
raise;
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseUses(const U: TPasUnit);
var
T: TToken;
UsedUnit: string;
begin
{ Parsing uses clause clears the comment, otherwise
- normal comments before "uses" clause would be assigned to normal unit
items (like a procedure), which is quite unexpected
(see ok_comment_over_uses_clause.pas testcase).
- analogously, back comments after "uses" clause would be assigned to the unit
description (see ok_comment_over_uses_clause_2.pas testcase).
}
IsLastComment := false;
ItemsForNextBackComment.Clear;
repeat
UsedUnit := GetAndCheckNextToken(TOK_IDENTIFIER, true);
if U <> nil then
U.UsesUnits.Append(UsedUnit);
T := GetNextToken;
try
if T.IsKeyWord(KEY_IN) then
begin
FreeAndNil(T);
{ Below we just ignore the value of next string token.
We can do this -- because PasDoc (at least for now)
does not recursively parse units on "uses" clause.
So we are not interested in the value of
given string (which should be a file-name (usually relative,
but absolute is also allowed AFAIK) with given unit.)
If we will ever want to implement such "recursive parsing
of units" in PasDoc, we will have to fix this to
*not* ignore value of token below. }
GetAndCheckNextToken(TOK_STRING);
T := GetNextToken;
end;
if T.IsSymbol(SYM_COMMA) then Continue else
if T.IsSymbol(SYM_SEMICOLON) then Break else
DoError('One of "," or ";" expected', []);
finally
FreeAndNil(T);
end;
until false;
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseCommaSeparatedIdentifiers(Names: TStrings;
FinalSymbol: TSymbolType;
RawDescriptions: TRawDescriptionInfoList);
var
T: TToken;
FirstIdentifier: boolean;
begin
FirstIdentifier := true;
repeat
Names.Append(GetAndCheckNextToken(TOK_IDENTIFIER));
{ Now we modify FirstIdentifier and append item to RawDescriptions }
if FirstIdentifier then
begin
FirstIdentifier := false;
if RawDescriptions <> nil then
RawDescriptions.Append(GetLastComment);
end else
if RawDescriptions <> nil then
begin
if IsLastComment then
RawDescriptions.Append(GetLastComment) else
RawDescriptions.Append(RawDescriptions[RawDescriptions.Count - 1]);
end;
T := GetNextToken;
try
if (T.MyType <> TOK_SYMBOL) or
( (T.Info.SymbolType <> SYM_COMMA) and
(T.Info.SymbolType <> FinalSymbol) ) then
DoError('One of symbols "," or "%s" expected', [SymbolNames[FinalSymbol]]);
if T.Info.SymbolType = FinalSymbol then
break;
finally
FreeAndNil(T);
end;
until false;
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseVariables(const U: TPasUnit);
begin
if U <> nil then
ParseFieldsVariables(U.Variables, false, viPublished, false)
else
ParseFieldsVariables(nil, false, viPublished, false);
end;
procedure TParser.ParseFieldsVariables(Items: TPasItems;
OfObject: boolean; Visibility: TVisibility; IsInRecordCase: boolean;
const ClassKeyWordString: string = '');
// Parse variable/field modifiers in FPC.
// See: http://www.freepascal.org/docs-html/ref/refse19.html for variable
// modifiers.
// This consumes some tokens and appends them to ItemCollector.FullDeclaration.
procedure ParseModifiers(ItemCollector: TPasFieldVariable);
const
Modifiers: array [boolean { OfObject }] of set of TStandardDirective =
( ([SD_CVAR, SD_EXPORT, SD_EXTERNAL, SD_PUBLIC]),
([SD_STATIC]) );
var
ModifierFound: Boolean;
SemicolonFound: boolean;
ttemp: TToken;
begin
repeat
ttemp := GetNextToken;
try
// The first token after the semicolon may be a variable or field modifier.
// If we see it, we eat it, up to the next semicolon.
// This does not take into account the "absolute" modifier
// (which is not preceeded by a semicolon).
ModifierFound :=
(ttemp.MyType = TOK_IDENTIFIER) and
(ttemp.Info.StandardDirective in Modifiers[OfObject]);
if ModifierFound then
begin
ItemCollector.FullDeclaration := ItemCollector.FullDeclaration + ' ' + ttemp.Data;
FreeAndNil(ttemp);
{ now eat tokens up to a ";" }
SemicolonFound := false;
while not SemicolonFound do
begin
ttemp := GetNextToken;
if ttemp.IsSymbol(SYM_SEMICOLON) then
begin
SemicolonFound := True;
ItemCollector.FullDeclaration := ItemCollector.FullDeclaration + ttemp.Data;
end
else
begin
ItemCollector.FullDeclaration := ItemCollector.FullDeclaration + ' ' + ttemp.Data;
end;
FreeAndNil(ttemp);
end;
end else
Scanner.UnGetToken(ttemp);
except
ttemp.Free;
raise;
end;
until not ModifierFound;
end;
var
NewItem: TPasFieldVariable;
ItemCollector: TPasFieldVariable;
m: TPasMethod;
t: TToken;
NewItemNames: TStringList;
I: Integer;
RawDescriptions: TRawDescriptionInfoList;
NewItems: TPasItems;
begin
NewItemNames := nil;
RawDescriptions := nil;
NewItems := nil;
try
NewItemNames := TStringList.Create;
RawDescriptions := TRawDescriptionInfoList.Create;
{ When Items = nil, we will gather NewItems only for internal use,
so we will free them ourselves. }
NewItems := TPasItems.Create(Items = nil);
ParseCommaSeparatedIdentifiers(NewItemNames, SYM_COLON, RawDescriptions);
ItemCollector := TPasFieldVariable.Create;
try
ItemCollector.FullDeclaration := ':';
t := GetNextToken(ItemCollector);
{ If symnbol is "(", we will later unget it and read it once again.
This way SkipDeclaration can read type declaration up to the matching
parenthesis, which is needed to handle fiels/var declarations with
inline enumareted type, like
var MyVar: (One, Two);
}
if not t.IsSymbol(SYM_LEFT_PARENTHESIS) then
begin
ItemCollector.FullDeclaration := ItemCollector.FullDeclaration + t.Data;
end;
if (t.MyType = TOK_KEYWORD) and
(t.Info.KeyWord in [KEY_FUNCTION, KEY_PROCEDURE]) then
begin
{ MethodTypeString for ParseCDFP below is '', because we already included
t.Data inside ItemCollector.FullDeclaration.
If MethodTypeString would be t.Data, then we would incorrectly
append t.Data twice to ItemCollector.FullDeclaration
when appending m.FullDeclaration to ItemCollector.FullDeclaration.
Note that param InitItemsForNextBackComment for ParseCDFP
below is false. We will free M in the near time, and we don't
want M to grab back-comment intended for our fields. }
ParseCDFP(M, '', '', KeyWordToMethodType(t.Info.KeyWord),
EmptyRawDescriptionInfo, false, false, '');
try
ItemCollector.FullDeclaration :=
ItemCollector.FullDeclaration + M.FullDeclaration;
finally
M.Free;
end;
FreeAndNil(t);
t := GetNextToken(ItemCollector);
if t.IsSymbol(SYM_EQUAL) then
begin
ItemCollector.FullDeclaration :=
ItemCollector.FullDeclaration + t.Data;
SkipDeclaration(ItemCollector, IsInRecordCase);
end else
begin
Scanner.UnGetToken(t);
end;
end else
if t.IsKeyWord(KEY_RECORD) then
begin
ParseCIO(nil, '', '', CIO_RECORD, EmptyRawDescriptionInfo, IsInRecordCase);
end else
if t.IsKeyWord(KEY_PACKED) then
begin
FreeAndNil(t);
t := GetNextToken;
if t.IsKeyWord(KEY_RECORD) then
begin
ParseCIO(nil, '', '', CIO_PACKEDRECORD, EmptyRawDescriptionInfo, IsInRecordCase);
end else
begin
SkipDeclaration(ItemCollector, IsInRecordCase);
end;
end else
begin
if t.IsSymbol(SYM_LEFT_PARENTHESIS) then
begin
Scanner.UnGetToken(t);
end;
SkipDeclaration(ItemCollector, IsInRecordCase);
end;
{ Create and add (to Items and ItemsForNextBackComment and NewItems)
new items now.
We must do it, because we want to init ItemsForNextBackComment *now*,
not later (after ParseModifiers).
Otherwise we could accidentaly "miss"
some back-comment while searching for variable/field modifiers
in ParseModifiers.
Note that we have to set ItemsForNextBackComment regardless
of Items being nil or not. Items may be nil when caller is not interested
in gathering them, e.g. a private fields section.
Even in this case, we still want to capture back comments and assign them
to private fields (that will be thrown out later), instead of accidentally
assigning back comments to previous non-private item.
See tests/ok_back_comment_private.pas for example when this is important.
Note that when parsing variable modifiers, Get/PeekNextToken
inside may actually use ItemsForNextBackComment and clear it,
that's why we can't count on ItemsForNextBackComment to hold
all our new items and we have to use NewItems. }
ItemsForNextBackComment.Clear;
for I := 0 to NewItemNames.Count - 1 do
begin
NewItem := TPasFieldVariable.Create;
NewItem.Name := NewItemNames[I];
NewItem.RawDescriptionInfo^ := RawDescriptions[I];
NewItem.Visibility := Visibility;
NewItem.SetAttributes(CurrentAttributes);
if Items <> nil then Items.Add(NewItem);
NewItems.Add(NewItem);
ItemsForNextBackComment.Add(NewItem);
end;
CurrentAttributes.Clear;
ParseModifiers(ItemCollector);
{ Now, when whole parsing work is finished, finish initializing NewItems. }
if Items <> nil then
begin
for I := 0 to NewItems.Count - 1 do
begin
NewItem := NewItems[I] as TPasFieldVariable;
NewItem.FullDeclaration := NewItem.Name + ItemCollector.FullDeclaration;
if ClassKeyWordString <> '' then
begin
NewItem.FullDeclaration := ClassKeyWordString
+ ' ' + NewItem.FullDeclaration;
end;
NewItem.HintDirectives := ItemCollector.HintDirectives;
NewItem.DeprecatedNote := ItemCollector.DeprecatedNote;
end;
end;
finally
ItemCollector.Free;
t.Free;
end;
finally
NewItemNames.Free;
RawDescriptions.Free;
NewItems.Free;
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.SetCommentMarkers(const Value: TStringList);
begin
FCommentMarkers.Assign(Value);
end;
procedure TParser.SetIgnoreMarkers(const Value: TStringList);
begin
FIgnoreMarkers.Assign(Value);
end;
procedure TParser.SkipDeclaration(const Item: TPasItem; IsInRecordCase: boolean);
var
EndLevel: Integer;
IsSemicolon: Boolean;
PLevel: Integer;
t: TToken;
WhitespaceCollectorToAdd: string;
begin
EndLevel := 0;
PLevel := 0;
repeat
WhitespaceCollectorToAdd := '';
t := GetNextTokenNotAttribute(Item);
try
case t.MyType of
TOK_SYMBOL:
case t.Info.SymbolType of
SYM_LEFT_PARENTHESIS: Inc(PLevel);
SYM_RIGHT_PARENTHESIS: Dec(PLevel);
end;
TOK_KEYWORD:
case t.Info.KeyWord of
KEY_END: Dec(EndLevel);
KEY_RECORD: Inc(EndLevel);
KEY_LIBRARY:
if Assigned(Item) then
Item.HintDirectives := Item.HintDirectives + [hdLibrary];
end;
TOK_IDENTIFIER:
case t.Info.StandardDirective of
SD_PLATFORM:
if Assigned(Item) then
Item.HintDirectives := Item.HintDirectives + [hdPlatform];
SD_EXPERIMENTAL:
if Assigned(Item) then
Item.HintDirectives := Item.HintDirectives + [hdExperimental];
SD_DEPRECATED:
begin
if Assigned(Item) then
Item.HintDirectives := Item.HintDirectives + [hdDeprecated];
while PeekNextToken(WhitespaceCollectorToAdd).MyType = TOK_STRING do
begin
{ consume the following string as DeprecatedNote }
if Assigned(Item) then
Item.FullDeclaration := Item.FullDeclaration + t.Data + WhitespaceCollectorToAdd;
FreeAndNil(t);
t := GetNextTokenNotAttribute(Item);
if Assigned(Item) then
begin
Assert(T.MyType = TOK_STRING); // T is now the same thing we saw with PeekNextToken
Item.DeprecatedNote := Item.DeprecatedNote + t.StringContent;
end;
end;
end;
end;
end;
IsSemicolon := t.IsSymbol(SYM_SEMICOLON);
{ Reason for "EndLevel < 0" condition:
Within records et al. the last declaration need not be terminated by ;
Reason for "(PLevel < 0) and IsInRecordCase" condition:
See autodoc of SkipDeclaration in TParser interface. }
if (EndLevel < 0) or
( (PLevel < 0) and IsInRecordCase ) then
begin
Scanner.UnGetToken(t);
Exit;
end;
if Assigned(Item) then Item.FullDeclaration := Item.FullDeclaration + t.Data + WhitespaceCollectorToAdd;
FreeAndNil(t);
except
t.Free;
raise;
end;
until IsSemicolon and (EndLevel = 0) and (PLevel = 0);
end;
{ ---------------------------------------------------------------------------- }
function TParser.PeekNextToken(out WhitespaceCollector: string): TToken;
{ Returns the offset of the next line in string S after position Index }
function FindNextLine(const S: string; Index: integer): integer;
begin
while SCharIs(S, Index, AllChars - WhiteSpaceNL) do Inc(Index);
while SCharIs(S, Index, WhiteSpaceNL) do Inc(Index);
if (Index > Length(S)) then
Result := 0
else
Result := Index;
end;
{ Checks whether string S starts with sub-string SubS at Index.
Returns true is S starts with SubS, false otherwise. }
function SStartsWith(const S: string; Index: integer; const SubS: string): boolean;
var
I: integer;
begin
Result := false;
if Length(S) < Length(SubS) + Index - 1 then
Exit;
for I := 0 to Length(SubS)-1 do
begin
if S[Index + I] <> SubS[I+1] then
Exit;
end;
Result := true;
end;
{ Extracts the documentation comment from T.CommentContent
(and some other T properties needed for TRawDescriptionInfo)
to CommentInfo. Always T.MyType must be within TokenCommentTypes.
T must not be nil.
The comment is intended to be a "documentation comment",
i.e. we intend to put it inside output documentation.
So comment markers, if present,
are removed from the beginning and end of the data.
Also, if comment markers were required but were not present,
then CommentInfo.Content is an empty string.
Also back-comment marker, the '<', is removed, if exists,
and BackComment is set to @true. Otherwise BackComment is @false. }
procedure ExtractDocComment(
const t: TToken; out CommentInfo: TRawDescriptionInfo;
out BackComment: boolean);
const
BackCommentMarker = '<';
var
i: integer;
Marker: string;
WasMarker: boolean;
CurPos: integer;
begin
BackComment := false;
CommentInfo.Content := T.CommentContent;
CommentInfo.StreamName := T.StreamName;
CommentInfo.BeginPosition := T.BeginPosition;
CommentInfo.EndPosition := T.EndPosition;
// Check if comment should be ignored
if IgnoreMarkers.Count <> 0 then
begin
for i := 0 to IgnoreMarkers.Count - 1 do
if IsPrefix(IgnoreMarkers[i], CommentInfo.Content) then
begin
CommentInfo.Content := '';
Exit;
end;
end;
if CommentMarkers.Count <> 0 then
begin
WasMarker := false;
for i := 0 to CommentMarkers.Count - 1 do
begin
Marker := CommentMarkers[i];
if IsPrefix(Marker, CommentInfo.Content) then
begin
Delete(CommentInfo.Content, 1, Length(Marker));
WasMarker := true;
Break;
end;
end;
if (not MarkersOptional) and (not WasMarker) then
begin
CommentInfo.Content := '';
Exit;
end;
end;
if (not (T.MyType = TOK_COMMENT_HELPINSIGHT)) and SCharIs(CommentInfo.Content, 1, BackCommentMarker) then
begin
BackComment := true;
Delete(CommentInfo.Content, 1, Length(BackCommentMarker));
end;
{ Replace leading characters (Nothing to do for single-line (//) comments) }
if (IgnoreLeading <> '') and
(T.MyType in [TOK_COMMENT_PAS, TOK_COMMENT_EXT]) then
begin
CurPos := 1;
repeat
while SCharIs(CommentInfo.Content, CurPos, WhiteSpace) do Inc(CurPos);
while SStartsWith(CommentInfo.Content, CurPos, IgnoreLeading) do
Delete(CommentInfo.Content, CurPos, Length(IgnoreLeading));
CurPos := FindNextLine(CommentInfo.Content, CurPos);
until CurPos = 0;
end;
end;
var
T: TToken;
TBackComment, TIsCStyle, THelpInsight: boolean;
TCommentInfo: TRawDescriptionInfo;
i: Integer;
name, value: string;
AttribPair: TStringPair;
innerBrackets: Integer;
parenthesis: Integer;
firstToken, WasLineFeed: Boolean;
begin
Result := nil;
WhitespaceCollector := ''; WasLineFeed := False;
repeat
t := Scanner.PeekToken;
try
{ when identifier is found, it cannot be attribute until next semicolon }
if T.MyType = TOK_IDENTIFIER then AttributeIsPossible := False;
if t.MyType = TOK_SYMBOL then
begin
if AttributeIsPossible and T.IsSymbol(SYM_LEFT_BRACKET) then begin
name := '';
value := '';
innerBrackets := 0;
parenthesis := 0;
firstToken := True;
repeat
Scanner.ConsumeToken;
FreeAndNil(T);
t := Scanner.PeekToken;
{ first token is the attribute class, at this moment unevaluated }
if firstToken then begin
case t.MyType of
TOK_IDENTIFIER:
begin
name := t.Data;
firstToken := False;
end;
TOK_STRING:
begin
{ this is GUID, belongs to the interface, but no check for
interface only is performed }
name := 'GUID';
value := '[' + t.Data + ']';
firstToken := False;
end;
end;
continue;
end;
{ check for start of attribute parameters }
{ there might be more nested parenthesis }
if T.IsSymbol(SYM_LEFT_PARENTHESIS) then Inc(parenthesis);
if T.IsSymbol(SYM_RIGHT_PARENTHESIS) then begin
if parenthesis = 0 then DoError('parenthesis do not match.', []);
Dec(parenthesis);
end;
{there might be some square brackets used in attributes parameters,
ignore them, but count them (example: param is set)}
if T.IsSymbol(SYM_LEFT_BRACKET) then Inc(innerBrackets);
if T.IsSymbol(SYM_RIGHT_BRACKET) then begin
if innerBrackets > 0 then begin
Dec(innerBrackets);
value := value + t.Data;
end else Break;
end else begin
{ there is list of attributes separated by coma }
if t.IsSymbol(SYM_COMMA) and (parenthesis = 0) then begin
AttribPair := TStringPair.Create(name, value);
CurrentAttributes.Add(AttribPair);
firstToken := True;
name := '';
value := '';
end else value := value + t.Data; // anything other
end;
until False;
Scanner.ConsumeToken;
FreeAndNil(T);
AttribPair := TStringPair.Create(name, value);
CurrentAttributes.Add(AttribPair);
end else
begin
Result := t;
break;
end;
end else
if t.MyType in TokenCommentTypes then
begin
Scanner.ConsumeToken;
{ Get info from T }
ExtractDocComment(T, TCommentInfo, TBackComment);
TIsCStyle := (t.MyType in [TOK_COMMENT_CSTYLE, TOK_COMMENT_HELPINSIGHT]);
THelpInsight := t.MyType = TOK_COMMENT_HELPINSIGHT;
{ Automatic back-comments.
The logic behind is following: this function stops at an identifier and
in the next call it will start from a whitespace if it's present and the
next token after a whitespace will be peeked inside the same loop.
So when we encounter //-style comment, we check if there was a whitespace
containing line feed. If yes, proceed as usual (comment is at a new line).
If no, the comment probably should be auto-back-ed. We check if there's
any items saved for next back comment and if they are, that's our case. }
if AutoBackComments then
if (t.MyType = TOK_COMMENT_CSTYLE) and not WasLineFeed and
(ItemsForNextBackComment.Count > 0) then
TBackComment := True;
FreeAndNil(T);
if TBackComment then
begin
if ItemsForNextBackComment.Count = 0 then
DoMessage(1, pmtWarning,
'%s: This is a back-comment (comment starting with "<") ' +
'but there is no item declared right before it: "%s"',
[Scanner.GetStreamInfo, TCommentInfo.Content]);
for i := 0 to ItemsForNextBackComment.Count - 1 do
begin
// use Trim(), see https://sourceforge.net/p/pasdoc/bugs/89/
if Trim(ItemsForNextBackComment.PasItemAt[i].RawDescription) <> '' then
DoMessage(1, pmtWarning,
'%s: Item %s already has one description, now it''s ' +
'overridden by back-comment (comment starting with "<"): "%s"',
[ Scanner.GetStreamInfo,
ItemsForNextBackComment.PasItemAt[i].QualifiedName,
TCommentInfo.Content]);
ItemsForNextBackComment.PasItemAt[i].RawDescriptionInfo^ := TCommentInfo;
end;
ItemsForNextBackComment.Clear;
end else
if IsLastComment and LastCommentWasCStyle and TIsCStyle then
begin
{ If there are several //-style comments in a row, combine them }
LastCommentInfo.Content := LastCommentInfo.Content +
LineEnding + TCommentInfo.Content;
if LastCommentInfo.StreamName = TCommentInfo.StreamName then
LastCommentInfo.EndPosition := TCommentInfo.EndPosition else
// ' ' is used to indicate that there is no
// single stream containing the entire comment.
LastCommentInfo.StreamName := ' ';
end else
begin
{ This is a normal comment, so fill [Is]LastCommentXxx properties }
IsLastComment := true;
LastCommentWasCStyle := TIsCStyle;
LastCommentHelpInsight := THelpInsight;
LastCommentInfo := TCommentInfo;
end;
end else
if t.MyType = TOK_WHITESPACE then
begin
Scanner.ConsumeToken;
if (Pos(#10, t.Data) <> 0) or (Pos(#13, t.Data) <> 0) then
WasLineFeed := True;
WhitespaceCollector := WhitespaceCollector + t.Data;
FreeAndNil(t);
end else
begin
Result := t;
break;
end;
except
t.Free;
raise;
end;
until False;
end;
function TParser.PeekNextToken: TToken;
var
Dummy: string;
begin
Result := PeekNextToken(Dummy);
end;
function TParser.PeekNextToken(const WhitespaceCollectorItem: TPasItem): TToken;
var
WhitespaceCollector: string;
begin
Result := PeekNextToken(WhitespaceCollector);
if Assigned(WhitespaceCollectorItem) then
WhitespaceCollectorItem.FullDeclaration :=
WhitespaceCollectorItem.FullDeclaration + WhitespaceCollector;
end;
{ ------------------------------------------------------------ }
procedure TParser.ParseHintDirectives(Item: TPasItem;
const ConsumeFollowingSemicolon: boolean; const ExtendFullDeclaration: boolean);
var
T: TToken;
WasDeprecatedDirective: boolean;
begin
repeat
WasDeprecatedDirective := false;
T := PeekNextToken;
if T.IsStandardDirective(SD_PLATFORM) then
Item.HintDirectives := Item.HintDirectives + [hdPlatform]
else
if T.IsStandardDirective(SD_EXPERIMENTAL) then
Item.HintDirectives := Item.HintDirectives + [hdExperimental]
else
if T.IsStandardDirective(SD_DEPRECATED) then
begin
Item.HintDirectives := Item.HintDirectives + [hdDeprecated];
WasDeprecatedDirective := true;
end else
if T.IsKeyWord(KEY_LIBRARY) then
Item.HintDirectives := Item.HintDirectives + [hdLibrary]
else
break;
if ExtendFullDeclaration then
Item.FullDeclaration := Item.FullDeclaration + ' ' + T.Data;
Scanner.ConsumeToken;
FreeAndNil(T);
if WasDeprecatedDirective then
begin
while PeekNextToken.MyType = TOK_STRING do
begin
T := PeekNextToken;
if ExtendFullDeclaration then
Item.FullDeclaration := Item.FullDeclaration + ' ' + T.Data;
Item.DeprecatedNote := Item.DeprecatedNote + T.StringContent;
Scanner.ConsumeToken;
FreeAndNil(T);
end;
end;
if ConsumeFollowingSemicolon then
begin
T := PeekNextToken;
if T.IsSymbol(SYM_SEMICOLON) then
begin
if ExtendFullDeclaration then
Item.FullDeclaration := Item.FullDeclaration + T.Data;
Scanner.ConsumeToken;
FreeAndNil(T);
end;
end;
until false;
end;
{ ------------------------------------------------------------ }
function TParser.ParseCioMembers(const ACio: TPasCio; var Mode: TItemParseMode;
const IsInRecordCase: Boolean; var Visibility: TVisibility): Boolean;
{ Parse fields clause, i.e. something like
NAME1, NAME2, ... : TYPE;
If AddToFields then adds parsed fields to i.Fields.
Visibility of created fields is set to given Visibility parameter. }
procedure ParseFields(AddToFields: Boolean;
Visibility: TVisibility; const ClassKeyWordString: string);
var Items: TPasItems;
begin
if AddToFields then
Items := ACio.Fields
else
Items := nil;
{ Note: 4th arg for ParseFieldsVariables is always "false",
not "IsInRecordCase". That's because even if declaration
of this CIO is within a record case, then we want to
see record's terminating "end" keyword anyway.
So it doesn't matter here whether our IsInRecordCase
parameter is true. }
ParseFieldsVariables(Items, True, Visibility, False, ClassKeyWordString);
end;
// Adds `Item` to `Items` if it should be visible according to `Visibility`
// Clears back comments and frees the item otherwise
procedure AddItemIfVisible(var Item: TPasItem; Items: TPasItems; Visibility: TVisibility);
begin
if Visibility in ShowVisibilities then
begin
Item.Visibility := Visibility;
Items.Add(Item);
end
else begin
ItemsForNextBackComment.Clear;
FreeAndNil(Item);
end;
end;
var
ClassKeyWordString: string;
M: TPasMethod;
ConstantParsed: TPasItem;
p: TPasProperty;
StrictVisibility: Boolean;
t, t2: TToken;
begin
t := nil;
try
{ ClassKeyWordString is used to include 'class' in
class methods, properties and variables declarations. }
ClassKeyWordString := '';
StrictVisibility := False;
Result := False;
repeat
FreeAndNil(t);
{ Attribute can be just in front of keyword or identifier }
AttributeIsPossible := True;
t := GetNextToken;
AttributeIsPossible := False;
if (t.IsSymbol(SYM_SEMICOLON)) then
begin
{ A declaration of type "name = class(ancestor);" }
Scanner.UnGetToken(T);
Result := TRUE;
Break;
end
else if (t.MyType = TOK_KEYWORD) then
begin
Mode := pmUndefined;
if StrictVisibility then
DoError('"strict" found in an unexpected location', []);
case t.Info.KeyWord of
KEY_THREADVAR,
KEY_VAR:
begin
if ClassKeyWordString = '' then
begin
Mode := pmVar;
ClassKeyWordString := t.Data;
ParseFields(Visibility in ShowVisibilities, Visibility,
ClassKeyWordString);
if not (Visibility in ShowVisibilities) then
ItemsForNextBackComment.Clear;
ClassKeyWordString := '';
end
else
ClassKeyWordString := Trim(ClassKeyWordString + ' ' + t.Data);
end;
KEY_CLASS: ClassKeyWordString := t.Data;
KEY_CONSTRUCTOR,
KEY_DESTRUCTOR,
KEY_FUNCTION,
KEY_PROCEDURE:
begin
ParseCDFP(M, ClassKeyWordString,
t.Data, KeyWordToMethodType(t.Info.KeyWord),
GetLastComment, true, true, '');
ClassKeyWordString := '';
AddItemIfVisible(TPasItem(M), ACio.Methods, Visibility);
end;
KEY_END:
begin
Result := TRUE;
FreeAndNil(t);
Break;
end;
KEY_PROPERTY:
begin
ParseProperty(p);
{ append ClassKeyWordString to property FullDeclaration,
to have 'class property Foo: ...'. }
if ClassKeyWordString <> '' then
begin
P.FullDeclaration := ClassKeyWordString + ' ' + P.FullDeclaration;
ClassKeyWordString := '';
end;
AddItemIfVisible(TPasItem(p), ACio.Properties, Visibility);
end;
KEY_CASE:
ParseRecordCase(ACio, False);
KEY_TYPE:
begin
Mode := pmType;
FreeAndNil(t);
Exit;
end;
KEY_CONST:
begin
Mode := pmConst;
FreeAndNil(t);
ParseConstant(otCio, ConstantParsed);
AddItemIfVisible(ConstantParsed, ACio.Fields, Visibility);
end;
else
DoError('Unexpected %s', [T.Description]);
end; // case
end
else if (t.MyType = TOK_IDENTIFIER) then
begin
case t.Info.StandardDirective of
SD_OPERATOR:
begin
{ Same code as for KEY_CONSTRUCTOR, KEY_DESTRUCTOR,
KEY_FUNCTION, KEY_PROCEDURE above, something to be optimized. }
Mode := pmUndefined;
ParseCDFP(M, ClassKeyWordString, t.Data, METHOD_OPERATOR,
GetLastComment, true, true, '');
ClassKeyWordString := '';
AddItemIfVisible(TPasItem(M), ACio.Methods, Visibility);
end;
SD_DEFAULT:
begin
if StrictVisibility then
DoError('"strict" found in an unexpected location', []);
{ Note: 2nd arg for SkipDeclaration is always "false",
not "IsInRecordCase". That's because even if declaration
of this CIO is within a record case, then we want to
see record's terminating "end" keyword anyway.
So it doesn't matter here whether our IsInRecordCase
parameter is true. }
SkipDeclaration(nil, false);
DoMessage(5, pmtInformation, 'Skipped default property keyword.', []);
end;
SD_PUBLIC:
begin
if StrictVisibility then
DoError('"strict" found in an unexpected location', []);
Visibility := viPublic;
Mode := pmUndefined;
end;
SD_PUBLISHED:
begin
if StrictVisibility then
DoError('"strict" found in an unexpected location', []);
Visibility := viPublished;
Mode := pmUndefined;
end;
SD_PRIVATE:
begin
if StrictVisibility then
begin
StrictVisibility := False;
Visibility := viStrictPrivate;
end
else
Visibility := viPrivate;
Mode := pmUndefined;
end;
SD_PROTECTED:
begin
if StrictVisibility then
begin
StrictVisibility := False;
Visibility := viStrictProtected;
end
else
Visibility := viProtected;
Mode := pmUndefined;
end;
SD_AUTOMATED:
begin
Visibility := viAutomated;
Mode := pmUndefined;
end;
SD_STRICT:
begin
StrictVisibility := True;
Mode := pmUndefined;
end;
SD_GENERIC:
begin
t2 := PeekNextToken;
if t2.Info.KeyWord in [KEY_FUNCTION, KEY_PROCEDURE] then
begin
t2 := GetNextToken;
try
ParseCDFP(M, ClassKeyWordString,
t2.Data, KeyWordToMethodType(t2.Info.KeyWord),
GetLastComment, true, true, t.Data);
ClassKeyWordString := '';
AddItemIfVisible(TPasItem(M), ACio.Methods, Visibility)
finally
FreeAndNil(t2)
end
end
else
DoError('Unexpected %s', [t2.Description])
end
else // case
Scanner.UnGetToken(T);
if Mode = pmType then
Exit;
if Mode = pmConst then
begin
ParseConstant(otCio, ConstantParsed);
AddItemIfVisible(ConstantParsed, ACio.Fields, Visibility);
end
else begin
ParseFields(Visibility in ShowVisibilities, Visibility,
ClassKeyWordString);
if not (Visibility in ShowVisibilities) then
ItemsForNextBackComment.Clear;
ClassKeyWordString := '';
end;
end; // case
end;
FreeAndNil(t);
until False;
CurrentAttributes.Clear;
ParseHintDirectives(ACio);
t := GetNextToken;
if not t.IsSymbol(SYM_SEMICOLON) then
begin
if IsInRecordCase then
begin
if t.IsSymbol(SYM_RIGHT_PARENTHESIS) then
Scanner.UnGetToken(t)
else
DoError('Unexpected symbol at end of sub-record', []);
end
else
DoError('Semicolon at the end of Class / Object / Interface' +
' / Record expected', []);
end;
finally
t.Free;
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseGenericTypeIdentifierList(var T: TToken; var Content: string);
var
Level: Cardinal;
begin
Content := Content + T.Data;
Level := 1;
repeat
FreeAndNil(T);
T := GetNextToken;
Content := Content + T.Data;
if T.IsSymbol(SYM_LESS_THAN) then
Inc(Level) else
if T.IsSymbol(SYM_GREATER_THAN) then
Dec(Level);
until Level = 0;
FreeAndNil(T); { free last ">" }
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseCioTypeDecl(out ACio: TPasCio;
const CioName, CioNameWithGeneric: string; CIOType: TCIOType;
const RawDescriptionInfo: TRawDescriptionInfo; var Visibility: TVisibility);
var
Finished: Boolean;
AncestorName, AncestorFullDeclaration: string;
t: TToken;
begin
DoMessage(5, pmtInformation, 'Parsing class/interface/object "%s"', [CioNameWithGeneric]);
t := nil;
try
AttributeIsPossible := True;
t := GetNextToken;
AttributeIsPossible := False;
{ Test for forward class definition here:
class MyClass = class;
with no ancestor or class members listed after the word class. }
if t.IsSymbol(SYM_SEMICOLON) then
// No error, continue the parsing.
Exit;
ACio := TPasCio.Create;
try
ACio.Name := CioName;
ACio.NameWithGeneric := CioNameWithGeneric;
ACio.RawDescriptionInfo^ := RawDescriptionInfo;
ACio.MyType := CIOType;
if (CIOType in [ CIO_CLASS, CIO_PACKEDCLASS ] ) and
(t.MyType = TOK_IDENTIFIER) and
(t.Info.StandardDirective in [SD_ABSTRACT, SD_SEALED]) then
begin
if t.Info.StandardDirective = SD_ABSTRACT then
ACio.ClassDirective := CT_ABSTRACT
else
ACio.ClassDirective := CT_SEALED;
FreeAndNil(t);
t := GetNextToken;
end
else if (CIOType in [ CIO_CLASS, CIO_RECORD ]) and
(t.MyType = TOK_IDENTIFIER) and
(t.Info.StandardDirective = SD_HELPER) then
begin
{ Class or record helpers are declared as:
identifierName = class|record helper [(ancestor list)] for TypeIdentifierName
memberList
end;
Ancestor list is optional, records cannot have ancestors, accepted nevertheless.
}
ACio.ClassDirective := CT_HELPER;
FreeAndNil(t);
t := GetNextToken;
end;
{ This allows to write back-comment for class declarations like
TMyClass = class(TMyAncestor) //< back comment
}
ItemsForNextBackComment.ClearAndAdd(ACio);
{ get all ancestors; remember, this could look like
TNewClass = class ( Classes.TClass, MyClasses.TFunkyClass, MoreClasses.YAC) ... end;
All class ancestors are supposed to be included in the docs!
}
{ TODO -otwm :
That's not quite true since multiple inheritance is not supported by
Delphi/Kylix or FPC. Every entry but the first must be an interface. }
if t.IsSymbol(SYM_LEFT_PARENTHESIS) then begin
{ optional ancestor introduced by ( }
FreeAndNil(t);
Finished := False;
{ outer repeat loop: one ancestor per pass }
repeat
FreeAndNil(t);
t := GetNextToken;
if t.MyType = TOK_IDENTIFIER then { an ancestor }
begin
AncestorFullDeclaration := t.Data;
AncestorName := t.Data;
{ For FPC-style generic specialization, the "specialize"
directive is specified before generic name.
That's easy to handle, just move to the next token. }
if t.IsStandardDirective(SD_SPECIALIZE) then
begin
FreeAndNil(t);
t := GetNextToken;
CheckToken(T, TOK_IDENTIFIER);
AncestorFullDeclaration := AncestorFullDeclaration + ' ' + t.Data;
AncestorName := t.Data; { previous AncestorName was wrong }
end;
{ inner repeat loop: one part of the ancestor per name }
repeat
FreeAndNil(t);
t := GetNextToken;
if not t.IsSymbol(SYM_PERIOD) then
begin
Scanner.UnGetToken(t);
Break; { leave inner repeat loop }
end;
FreeAndNil(t);
t := GetNextToken;
if t.MyType <> TOK_IDENTIFIER then
DoError('Expected class, object or interface in ancestor' +
' declaration', []);
AncestorFullDeclaration := AncestorFullDeclaration + '.' + T.Data;
AncestorName := AncestorName + '.' + T.Data;
until False;
{ Dumb reading of generic specialization, just blindly consume
(add to AncestorFullDeclaration) everything between <...>. }
t := GetNextToken;
if t.IsSymbol(SYM_LESS_THAN) then
ParseGenericTypeIdentifierList(T, AncestorFullDeclaration) else
Scanner.UnGetToken(t);
ACio.Ancestors.Add(TStringPair.Create(AncestorName, AncestorFullDeclaration));
end
else begin
if (t.IsSymbol(SYM_COMMA)) then
{ comma, separating two ancestors }
FreeAndNil(t)
else begin
CheckToken(t, SYM_RIGHT_PARENTHESIS);
FreeAndNil(t);
Finished := true;
end;
end;
until Finished;
end
else begin
Scanner.UnGetToken(t);
case ACio.MyType of
CIO_CLASS, CIO_PACKEDCLASS:
begin
if not SameText(ACio.Name, 'tobject') then
ACio.Ancestors.Add(TStringPair.Create('TObject', 'TObject'));
end;
CIO_DISPINTERFACE:
begin
if not SameText(ACio.Name, 'idispinterface') then
ACio.Ancestors.Add(TStringPair.Create('IDispInterface', 'IDispInterface'));
end;
CIO_INTERFACE:
begin
if not SameText(ACio.Name, 'iinterface') then
ACio.Ancestors.Add(TStringPair.Create('IInterface', 'IInterface'));
end;
CIO_OBJECT, CIO_PACKEDOBJECT:
begin
if not SameText(ACio.Name, 'tobject') then
ACio.Ancestors.Add(TStringPair.Create('TObject', 'TObject'));
end;
end;
end;
t := GetNextToken;
if (CIOType in [ CIO_CLASS, CIO_RECORD ]) and
(ACio.ClassDirective = CT_HELPER) then
begin
if t.IsKeyWord(KEY_FOR) then
begin
FreeAndNil(t);
t := GetNextToken;
if t.MyType = TOK_IDENTIFIER then
begin
ACio.HelperTypeIdentifier := t.Data;
FreeAndNil(t);
t := GetNextToken;
end
else
DoError('Identifier expected but %s found', ['''' + t.Data + '''']);
end
else
DoError('Keyword FOR expected but %s found', ['''' + t.Data + '''']);
end;
if (t.IsSymbol(SYM_LEFT_BRACKET)) then
begin
FreeAndNil(t);
{ for the time being, we throw away the ID itself }
t := GetNextToken;
if (t.MyType <> TOK_STRING) and (t.MyType <> TOK_IDENTIFIER) then
DoError('Literal String or identifier as interface ID expected', [])
else begin
CurrentAttributes.Add(TStringPair.Create('GUID', '[' + t.Data + ']'));
end;
FreeAndNil(t);
t := GetNextToken;
CheckToken(T, SYM_RIGHT_BRACKET);
FreeAndNil(t);
end
else
Scanner.UnGetToken(t);
if ACio.MyType in [ CIO_CLASS, CIO_PACKEDCLASS ] then
begin
{ Visibility of members at the beginning of a class declaration
that don't have a specified visibility is controlled
by ImplicitVisibility value. }
case ImplicitVisibility of
ivPublic:
if Scanner.SwitchOptions['M'] then
Visibility := viPublished
else
Visibility := viPublic;
ivPublished:
Visibility := viPublished;
ivImplicit:
Visibility := viImplicit;
else
raise EInternalParserError.Create('ImplicitVisibility = ??');
end;
end
else
{ Everything besides a class always starts with visibility "public". }
Visibility := viPublic;
ACio.SetAttributes(CurrentAttributes);
{ now collect methods, fields and properties }
{ Flag is set when the class is finished }
{ Code moved to ParseCioMembers }
except
FreeAndNil(ACio);
raise;
end;
finally
t.Free;
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TParser.ParseCioEx(const U: TPasUnit;
const CioName, CioNameWithGeneric: string;
CIOType: TCIOType; const RawDescriptionInfo: TRawDescriptionInfo;
const IsInRecordCase: Boolean);
{ TODO: this is mostly a copy&paste of ParseType! Should be merged,
otherwise modifying one of them always needs to be carefully duplicated. }
procedure ParseNestedType;
var
RawDescriptionInfo: TRawDescriptionInfo;
NormalType: TPasType;
TypeName: string;
LCollected, LTemp, TypeNameWithGeneric: string;
MethodType: TPasMethod;
EnumType: TPasEnum;
T: TToken;
IsGeneric: boolean;
begin
{ Read the type name, preceded by optional "generic" directive.
Calculate TypeName, IsGeneric, TypeNameWithGeneric.
FPC requires "generic" directive, but Delphi doesn't,
so it's just optional for us (serves for some checks later). }
T := GetNextToken;
try
TypeNameWithGeneric := '';
IsGeneric := T.IsStandardDirective(SD_GENERIC);
if IsGeneric then
begin
TypeNameWithGeneric := T.Data + ' ';
TypeName := GetAndCheckNextToken(TOK_IDENTIFIER);
end else
begin
CheckToken(T, TOK_IDENTIFIER);
TypeName := T.Data;
end;
TypeNameWithGeneric := TypeNameWithGeneric + TypeName;
finally FreeAndNil(T) end;
RawDescriptionInfo := GetLastComment;
t := GetNextToken(LCollected);
try
if T.IsSymbol(SYM_LESS_THAN) then
begin
ParseGenericTypeIdentifierList(T, TypeNameWithGeneric);
T := GetNextToken(LCollected);
end;
if T.IsSymbol(SYM_SEMICOLON) then
begin
FreeAndNil(T);
Exit;
end else
if T.IsSymbol(SYM_EQUAL) then
begin
LCollected := TypeNameWithGeneric + LCollected + T.Data;
FreeAndNil(T);
end else
begin
FreeAndNil(T);
DoError('Symbol "=" expected', []);
end;
t := GetNextToken(LTemp);
LCollected := LCollected + LTemp + t.Data;
if (t.MyType = TOK_KEYWORD) then
begin
FCioSk.Peek.SkipCioDecl := FALSE;
case t.Info.KeyWord of
KEY_CLASS:
begin
FreeAndNil(t);
t := GetNextToken(LTemp);
LCollected := LCollected + LTemp + t.Data;
if t.IsKeyWord(KEY_OF) then
begin
{ include "identifier = class of something;" as standard type }
end
else begin
Scanner.UnGetToken(t);
ParseCioEx(U, TypeName, TypeNameWithGeneric, CIO_CLASS,
RawDescriptionInfo, False);
Exit;
end;
end;
KEY_DISPINTERFACE:
begin
FreeAndNil(t);
ParseCioEx(U, TypeName, TypeNameWithGeneric, CIO_DISPINTERFACE,
RawDescriptionInfo, False);
Exit;
end;
KEY_INTERFACE:
begin
FreeAndNil(t);
ParseCioEx(U, TypeName, TypeNameWithGeneric, CIO_INTERFACE,
RawDescriptionInfo, False);
Exit;
end;
KEY_OBJECT:
begin
FreeAndNil(t);
ParseCioEx(U, TypeName, TypeNameWithGeneric, CIO_OBJECT,
RawDescriptionInfo, False);
Exit;
end;
KEY_RECORD:
begin
FreeAndNil(t);
ParseCioEx(U, TypeName, TypeNameWithGeneric, CIO_RECORD,
RawDescriptionInfo, False);
Exit;
end;
KEY_PACKED:
begin
FreeAndNil(t);
t := GetNextToken(LTemp);
LCollected := LCollected + LTemp + t.Data;
if t.IsKeyWord(KEY_RECORD) then
begin
FreeAndNil(t);
ParseCioEx(U, TypeName, TypeNameWithGeneric, CIO_PACKEDRECORD,
RawDescriptionInfo, False);
exit;
end
else if t.IsKeyWord(KEY_OBJECT) then
begin
FreeAndNil(t);
ParseCioEx(U, TypeName, TypeNameWithGeneric, CIO_PACKEDOBJECT,
RawDescriptionInfo, False);
Exit;
end
else if t.IsKeyWord(KEY_CLASS) then
begin
// no check for "of", no packed classpointers allowed
FreeAndNil(t);
ParseCioEx(U, TypeName, TypeNameWithGeneric, CIO_PACKEDCLASS,
RawDescriptionInfo, False);
Exit;
end;
end;
end;
end;
if Assigned(t) then
begin
if (t.MyType = TOK_KEYWORD) then
begin
if t.Info.KeyWord in [KEY_FUNCTION, KEY_PROCEDURE] then
begin
ParseCDFP(MethodType, '', t.Data, KeyWordToMethodType(t.Info.KeyWord),
RawDescriptionInfo, false, true, '');
MethodType.Name := TypeName;
MethodType.FullDeclaration :=
TypeName + ' = ' + MethodType.FullDeclaration;
FCioSk.Peek.Cio.Types.Add(MethodType);
FreeAndNil(t);
FCioSk.Peek.SkipCioDecl := TRUE;
ParseCioEx(U, TypeName, TypeNameWithGeneric, CIOType, RawDescriptionInfo, False); //recursion
Exit;
end;
end;
if t.IsSymbol(SYM_LEFT_PARENTHESIS) then
begin
ParseEnum(EnumType, TypeName, RawDescriptionInfo);
FCioSk.Peek.Cio.Types.Add(EnumType);
FreeAndNil(t);
FCioSk.Peek.SkipCioDecl := TRUE;
ParseCioEx(U, TypeName, TypeNameWithGeneric, CIOType, RawDescriptionInfo, False); //recursion
Exit;
end;
SetLength(LCollected, Length(LCollected)-Length(t.Data));
Scanner.UnGetToken(t);
end;
FreeAndNil(t);
NormalType := TPasType.Create;
try
NormalType.FullDeclaration := LCollected;
SkipDeclaration(NormalType, false);
NormalType.Name := TypeName;
NormalType.RawDescriptionInfo^ := RawDescriptionInfo;
NormalType.Visibility := FCioSk.Peek.CurVisibility;
ItemsForNextBackComment.ClearAndAdd(NormalType);
if FCioSk.Peek.CurVisibility in ShowVisibilities then
FCioSk.Peek.Cio.Types.Add(NormalType)
else
NormalType.Free;
except
NormalType.Free;
raise;
end;
FCioSk.Peek.SkipCioDecl := TRUE;
ParseCioEx(U, TypeName, TypeNameWithGeneric, CIOType, RawDescriptionInfo, False); //recursion
except
FreeAndNil(t);
raise;
end;
end;
{ - - - - - - }
{ This is the attempt to change as less as possible and to reuse as much code
as possible to support nested types. A design change as DoDi suggested in
PasDoc2 should be considered sooner or later. }
var
LCio : TPasCio;
LHlp : TPasCioHelper;
LMode : TItemParseMode;
LVisibility : TVisibility;
begin
LCio := nil;
LHlp := nil;
try
if FCioSk.Count > 0 then
begin
if FCioSk.Peek.SkipCioDecl then
begin
LCio := FCioSk.Peek.Cio;
LMode := FCioSk.Peek.Mode;
LVisibility := FCioSk.Peek.CurVisibility;
FCioSk.Pop.Free;
end
else begin
LMode := pmUndefined;
end;
end
else
LMode := pmUndefined;
if not Assigned(LCio) then
ParseCioTypeDecl(LCio, CioName, CioNameWithGeneric, CioType,
RawDescriptionInfo, LVisibility);
if not Assigned(LCio) then
Exit;
while ParseCioMembers(LCio, LMode, IsInRecordCase, LVisibility) do
begin // A Cio completed, nested or outer CIO
{ Clear any orthan comments - do not let them break away from the CIO }
IsLastComment := false;
ItemsForNextBackComment.ClearAndAdd(LCio);
if (FCioSk.Count > 0) then
begin
LVisibility := FCioSk.Peek.CurVisibility;
if LVisibility in ShowVisibilities then
begin
LCio.Visibility := LVisibility;
FCioSk.Peek.Cio.Cios.Add(LCio);
end
else
FreeAndNil(LCio);
LCio := FCioSk.Peek.Cio;
LMode := FCioSk.Peek.Mode;
FCioSk.Pop.Free;
end
else begin
if Assigned(U) then
begin
ItemsForNextBackComment.ClearAndAdd(LCio);
U.AddCIO(LCio);
LCio := nil;
end
else
LCio.Free;
Exit; // Finished
end;
end;
LHlp := TPasCioHelper.Create;
LHlp.Mode := LMode;
LHlp.CurVisibility := LVisibility;
LHlp.Cio := LCio;
FCioSk.Push(LHlp);
LHlp := nil;
LCio := nil;
ParseNestedType;
except
LCio.Free;
LHlp.Free;
FCioSk.Clear;
raise;
end;
end;
{ TRawDescriptionInfoList ---------------------------------------------------- }
function TRawDescriptionInfoList.GetItems(Index: integer): TRawDescriptionInfo;
begin
{ FItems is a dynarray, so compiler will automatically
add appropriate range checks here in $R+ mode.
So no need to explicitly check Index for validity here. }
Result := FItems[Index];
end;
procedure TRawDescriptionInfoList.Grow;
var
Delta: integer;
begin
if Length(FItems) < 16 then begin
Delta := 4;
end
else begin
Delta := Length(FItems) div 4;
end;
SetLength(FItems, Length(FItems) + Delta);
end;
function TRawDescriptionInfoList.Append(Comment: TRawDescriptionInfo): integer;
begin
if Length(FItems) = Count then Grow;
FItems[Count] := Comment;
result := Count;
Inc(FCount);
end;
constructor TRawDescriptionInfoList.Create;
begin
inherited;
SetLength(FItems, 4);
FCount := 0;
end;
{ TPasCioHelperStack }
procedure TPasCioHelperStack.Clear;
begin
while Count > 0 do
Pop.FreeAll;
end;
function TPasCioHelperStack.Peek: TPasCioHelper;
begin
Result := TPasCioHelper(inherited Peek);
end;
function TPasCioHelperStack.Pop: TPasCioHelper;
begin
Result := TPasCioHelper(inherited Pop);
end;
function TPasCioHelperStack.Push(AHelper: TPasCioHelper): TPasCioHelper;
begin
Result := TPasCioHelper(inherited Push(AHelper));
end;
{ TPasCioHelper }
procedure TPasCioHelper.FreeAll;
begin
FCio.Free;
Destroy;
end;
end.
|