1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089
|
{
***************************************************************************
* *
* This source is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This code is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License for more details. *
* *
* A copy of the GNU General Public License is available on the World *
* Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also *
* obtain it by writing to the Free Software Foundation, *
* Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA. *
* *
***************************************************************************
Author: Mattias Gaertner
Abstract:
TFindDeclarationTool enhances the TPascalReaderTool with the ability
to find the source position or code tree node of a declaration.
ToDo:
- high type expression evaluation
(i.e. at the moment: integer+integer=longint
wanted: integer+integer=integer)
- make @Proc context sensitive (started, but not complete)
- operator overloading
- ppu, dcu files
- many things, search for 'ToDo'
}
unit FindDeclarationTool;
{$ifdef FPC}{$mode objfpc}{$endif}{$H+}
interface
{$I codetools.inc}
// activate for debugging:
// mem check
{ $DEFINE MEM_CHECK}
// verbosity
{ $DEFINE CTDEBUG}
{ $DEFINE ShowTriedFiles}
{ $DEFINE ShowTriedContexts}
{ $DEFINE ShowTriedBaseContexts}
{ $DEFINE ShowTriedParentContexts}
{ $DEFINE ShowTriedIdentifiers}
{ $DEFINE ShowTriedUnits}
{ $DEFINE ShowExprEval}
{ $DEFINE ShowForInEval}
{ $DEFINE ShowFoundIdentifier}
{ $DEFINE ShowNodeCache}
{ $DEFINE ShowBaseTypeCache}
{ $DEFINE ShowCacheDependencies}
{ $DEFINE ShowCollect}
{ $DEFINE ShowProcSearch}
{ $DEFINE VerboseFindDeclarationFail}
{ $DEFINE DebugAddToolDependency}
{ $DEFINE VerboseCPS}
{ $DEFINE VerboseFindDeclarationAndOverload}
{ $DEFINE VerboseFindFileAtCursor}
{$IFDEF CTDEBUG}{$DEFINE DebugPrefix}{$ENDIF}
{$IFDEF ShowTriedIdentifiers}{$DEFINE DebugPrefix}{$ENDIF}
{$IFDEF ShowTriedContexts}{$DEFINE DebugPrefix}{$ENDIF}
{$IFDEF ShowExprEval}{$DEFINE ShowForInEval}{$ENDIF}
uses
{$IFDEF MEM_CHECK}
MemCheck,
{$ENDIF}
Classes, SysUtils, Laz_AVL_Tree,
// LazUtils
LazFileUtils, LazUtilities,
// Codetools
CodeToolsStrConsts, CodeTree, CodeAtom, CustomCodeTool,
SourceLog, KeywordFuncLists, BasicCodeTools, LinkScanner, CodeCache,
DirectoryCacher, PascalParserTool, PascalReaderTool, FileProcs,
DefineTemplates, FindDeclarationCache;
type
TFindDeclarationTool = class;
//----------------------------------------------------------------------------
// variable atoms
TVariableAtomType = (
vatNone, // undefined
vatSpace, // empty or space
vatIdentifier, // an identifier
vatPreDefIdentifier, // an identifier with special meaning to the compiler
vatPoint, // .
vatAS, // AS keyword
vatINHERITED, // INHERITED keyword
vatUp, // ^
vatRoundBracketOpen, // (
vatRoundBracketClose,// )
vatEdgedBracketOpen, // [
vatEdgedBracketClose,// ]
vatAddrOp, // @
vatKeyword, // other keywords
vatNumber, // decimal, & octal, % binary, $ hex
vatStringConstant // '' or #
);
const
// for nicer debugging output
VariableAtomTypeNames: array[TVariableAtomType] of string =
('<None>',
'Space',
'Ident',
'PreDefIdent',
'Point',
'AS',
'INHERITED',
'Up^ ',
'Bracket(',
'Bracket)',
'Bracket[',
'Bracket]',
'AddrOperator@ ',
'Keyword',
'Number',
'StringConstant'
);
type
//----------------------------------------------------------------------------
// searchpath delimiter is semicolon
TOnGetSearchPath = function(Sender: TObject): string of object;
TOnGetSrcPathForCompiledUnit =
function(Sender: TObject; const Filename: string): string of object;
//----------------------------------------------------------------------------
TOnGetMethodName = function(const AMethod: TMethod;
CheckOwner: TObject): string of object;
//----------------------------------------------------------------------------
// flags/states for searching
TFindDeclarationFlag = (
fdfSearchInAncestors, // if context is a class, search also in
// ancestors/interfaces
fdfSearchInParentNodes, // if identifier not found in current context,
// proceed in prior nodes on same lvl and parents
fdfIgnoreCurContextNode,// skip context and proceed in prior/parent context
fdfIgnoreUsedUnits, // stay in current source
fdfSearchForward, // instead of searching in prior nodes, search in
// next nodes (successors)
fdfExceptionOnNotFound, // raise exception if identifier not found
// predefined identifiers will not raise
fdfExceptionOnPredefinedIdent,// raise an exception even if the identifier
// is a predefined identifier
fdfIgnoreClassVisibility,//find inaccessible private+protected fields
fdfIgnoreMissingParams, // found proc fits, even if parameters are missing
fdfOnlyCompatibleProc, // incompatible procs are ignored
fdfIgnoreOverloadedProcs,// ignore param lists and take the first proc found
fdfFindVariable, // do not search for the base type of a variable,
// instead return the variable declaration
fdfFunctionResult, // if function is found, return result type
fdfEnumIdentifier, // do not resolve enum to its enum type
fdfFindChildren, // search the class of a 'class of', the interface of a unit
fdfSkipClassForward, // when a class forward was found search the class
fdfCollect, // return every reachable identifier
fdfTopLvlResolving, // set, when searching for an identifier of the
// top lvl variable. Calling DoOnIdentifierFound.
fdfDoNotCache, // result will not be cached
fdfExtractOperand, // operand will be extracted
fdfPropertyResolving, // used with fdfExtractOperand to resolve properties to getters
fdfSearchInHelpers, // search in class/record/type helpers too
fdfSearchInHelpersInTheEnd, // search in helpers after current class (used with inherited call in helper)
fdfTypeType, // do not resolve TMyString = type string;
fdfIgnoreOperatorError, // return expression type even if an operator error was found
fdfOverrideStringTypesWithFirstParamType // if you search for an expression result type of a "function A(B: string): string", override the result type with type of B expression
);
TFindDeclarationFlags = set of TFindDeclarationFlag;
const
// masks to pass flags to sub searches
fdfGlobals = [fdfExceptionOnNotFound, fdfTopLvlResolving,
fdfExtractOperand, fdfPropertyResolving,
fdfOverrideStringTypesWithFirstParamType];
fdfGlobalsSameIdent = fdfGlobals+[fdfExceptionOnPredefinedIdent,
fdfIgnoreMissingParams, fdfIgnoreUsedUnits, fdfDoNotCache,
fdfOnlyCompatibleProc, fdfSearchInAncestors, fdfCollect, fdfSearchInHelpers];
// initial flags for searches
fdfDefaultForExpressions = [fdfSearchInParentNodes, fdfSearchInAncestors, fdfSearchInHelpers,
fdfExceptionOnNotFound,fdfIgnoreCurContextNode];
type
// flags/states for result
TFoundDeclarationFlag = (
fodDoNotCache
);
TFoundDeclarationFlags = set of TFoundDeclarationFlag;
//----------------------------------------------------------------------------
type
TFindDeclarationParams = class;
TFindContext = record
Node: TCodeTreeNode;
Tool: TFindDeclarationTool;
end;
PFindContext = ^TFindContext;
const
CleanFindContext: TFindContext = (Node:nil; Tool:nil);
type
//----------------------------------------------------------------------------
{ TExpressionTypeDesc describes predefined types
The Freepascal compiler can automatically convert them
}
TExpressionTypeDesc = (
xtNone, // undefined
xtContext, // a node
xtChar, // char
xtWideChar, // widechar
xtReal, // real
xtSingle, // single
xtDouble, // double
xtExtended, // extended
xtCExtended, // cextended
xtCurrency, // currency
xtComp, // comp
xtInt64, // int64
xtCardinal, // cardinal
xtQWord, // qword
xtBoolean, // boolean
xtByteBool, // bytebool
xtWordBool, // wordbool
xtLongBool, // longbool
xtQWordBool, // qwordbool
xtString, // string
xtAnsiString, // ansistring
xtShortString, // shortstring
xtWideString, // widestring
xtUnicodeString,// unicodestring
xtPChar, // pchar
xtPointer, // pointer
xtFile, // file
xtText, // text
xtConstOrdInteger,// enum, number, integer
xtConstString, // string, string constant, char constant
xtConstReal, // real number
xtConstSet, // [] set
xtConstBoolean,// true, false
xtLongint, // longint
xtLongWord, // longword
xtWord, // word
xtSmallInt, // smallint
xtShortInt, // shortint
xtByte, // byte
xtNativeInt, // depends on compiler and platform
xtNativeUInt, // depends on compiler and platform
xtCompilerFunc,// SUCC, PREC, LOW, HIGH, ORD, LENGTH, COPY (1.1), ...
xtVariant, // variant
xtJSValue, // jsvalue only in Pas2JS, similar to variant
xtNil // nil = pointer, class, procedure, method, ...
);
// Do not define: TExpressionTypeDescs = set of TExpressionTypeDesc;
// There are too many enums, so the set would be big and slow
var
ExpressionTypeDescNames: array[TExpressionTypeDesc] of string = (
'None',
'Context',
'Char',
'WideChar',
'Real',
'Single',
'Double',
'Extended',
'CExtended',
'Currency',
'Comp',
'Int64',
'Cardinal',
'QWord',
'Boolean',
'ByteBool',
'WordBool',
'LongBool',
'QWordBool',
'String',
'AnsiString',
'ShortString',
'WideString',
'UnicodeString',
'PChar',
'Pointer',
'File',
'TextFile',
'ConstOrdInt',
'ConstString',
'ConstReal',
'ConstSet',
'ConstBoolean',
'LongInt',
'LongWord',
'Word',
'SmallInt',
'ShortInt',
'Byte',
'NativeInt',
'NativeUInt',
'CompilerFunc',
'Variant',
'JSValue',
'Nil'
);
const
xtAllTypes = [Low(TExpressionTypeDesc)..High(TExpressionTypeDesc)]-[xtNone];
xtAllPredefinedTypes = xtAllTypes-[xtContext];
xtAllConstTypes = [xtConstOrdInteger,xtConstBoolean,xtConstReal,
xtConstString,xtConstSet,xtCompilerFunc,xtNil];
xtAllIdentTypes = xtAllTypes - xtAllConstTypes;
xtAllIdentPredefinedTypes = xtAllIdentTypes - [xtContext];
xtAllIntegerTypes = [xtInt64, xtQWord, xtConstOrdInteger, xtLongint,
xtLongWord, xtWord, xtCardinal, xtSmallInt, xtShortInt,
xtByte,xtNativeInt,xtNativeUInt];
xtAllBooleanTypes = [xtBoolean, xtByteBool, xtWordBool, xtLongBool,xtQWordBool];
xtAllRealTypes = [xtReal, xtConstReal, xtSingle, xtDouble,
xtExtended, xtCExtended, xtCurrency, xtComp];
xtAllStringTypes = [xtConstString, xtShortString, xtString, xtAnsiString];
xtAllWideStringTypes = [xtConstString, xtWideString, xtUnicodeString];
xtAllPointerTypes = [xtPointer, xtNil];
xtAllTypeHelperTypes = xtAllPredefinedTypes-[xtCompilerFunc,xtVariant,xtJSValue,xtNil];
xtAllStringCompatibleTypes = xtAllStringTypes+[xtChar,xtJSValue];
xtAllWideStringCompatibleTypes = xtAllWideStringTypes+[xtWideChar,xtChar];
xtAllIntegerConvertibles = xtAllIntegerTypes;
xtAllRealConvertibles = xtAllRealTypes+xtAllIntegerTypes;
xtAllStringConvertibles = xtAllStringCompatibleTypes+[xtPChar];
xtAllWideStringConvertibles = xtAllWideStringCompatibleTypes+[xtPChar];
xtAllBooleanConvertibles = xtAllBooleanTypes+[xtConstBoolean];
xtAllPointerConvertibles = xtAllPointerTypes+[xtPChar];
xtAllPas2JSExtraTypes = [xtJSValue,xtNativeInt,xtNativeUInt];
type
{ TExpressionType is used for compatibility check
A compatibility check is done by comparing two TExpressionType
if Desc = xtConstSet, SubDesc contains the type of the set
if Context.Node<>nil, it contains the corresponding codetree node
if Desc = xtPointer then SubDesc contains the type e.g. xtChar
}
TExpressionType = record
Desc: TExpressionTypeDesc;
SubDesc: TExpressionTypeDesc;
Context: TFindContext;
end;
PExpressionType = ^TExpressionType;
const
CleanExpressionType : TExpressionType =
(Desc:xtNone; SubDesc:xtNone; Context:(Node:nil; Tool:nil));
type
//----------------------------------------------------------------------------
// TTypeCompatibility is the result of a compatibility check
TTypeCompatibility = (
tcExact, // exactly same type, can be used for var parameters
tcCompatible, // type can be auto converted, can not be used for var parameters
tcIncompatible // type is incompatible
);
TTypeCompatibilityList = ^TTypeCompatibility;
const
TypeCompatibilityNames: array[TTypeCompatibility] of string = (
'Exact',
'Compatible', // convertable, but not allowed for var params
'Incompatible'
);
type
//----------------------------------------------------------------------------
// TExprTypeList is used for compatibility checks of whole parameter lists
TExprTypeList = class
private
FCapacity: integer;
procedure SetCapacity(const AValue: integer);
protected
procedure Grow;
public
Count: integer;
Items: PExpressionType;
AliasTypes: PFindContext;
procedure Add(const ExprType: TExpressionType);
procedure Add(const ExprType: TExpressionType; const AliasType: TFindContext);
procedure AddFirst(const ExprType: TExpressionType);
property Capacity: integer read FCapacity write SetCapacity;
destructor Destroy; override;
function AsString: string;
function CalcMemSize: PtrUInt;
end;
type
{ TOperand }
TOperand = record
Expr: TExpressionType;
AliasType: TFindContext;
end;
//----------------------------------------------------------------------------
// TTypeAliasOrderList is used for comparing type aliases in binary operators
TTypeAliasItem = class
public
AliasName: string;
Position: Integer;
end;
TTypeAliasOrderList = class
private
FTree: TAVLTree;
public
constructor Create(const AliasNames: array of string);
destructor Destroy; override;
procedure Add(const AliasName: string);
procedure Add(const AliasNames: array of string);
procedure Insert(const AliasName: string; const Pos: Integer);
procedure InsertBefore(const AliasName, BeforeAlias: string);
procedure InsertAfter(const AliasName, AfterAlias: string);
procedure Delete(const Pos: Integer);
procedure Delete(const AliasName: string);
function IndexOf(const AliasName: string): Integer;
function Compare(const AliasName1, AliasName2: string): Integer;
function Compare(const Operand1, Operand2: TOperand;
Tool: TFindDeclarationTool; CleanPos: Integer): TOperand;
end;
function CompareTypeAliasItems(Item1, Item2: Pointer): Integer;
function CompareTypeAliasItemString(AliasName, Item: Pointer): Integer;
type
//----------------------------------------------------------------------------
// TFoundProc is used for comparing overloaded procs
PFoundProc = ^TFoundProc;
TFoundProc = record
// the expression input list, which should fit into the searched proc
ExprInputList: TExprTypeList;
// the best proc found till now
Context: TFindContext;
// if the proc was already compared (CacheValid=true), then some of the
// compatibility check results are cached.
CacheValid: boolean;
ProcCompatibility: TTypeCompatibility;
ParamCompatibilityList: TTypeCompatibilityList;
// each TFindDeclarationParams has a list of PFoundProc
Owner: TObject;
Next, Prior: PFoundProc;
end;
//---------------------------------------------------------------------------
type
TIdentifierFoundResult = (ifrProceedSearch, ifrAbortSearch, ifrSuccess);
const
IdentifierFoundResultNames: array[TIdentifierFoundResult] of string =
('ProceedSearch', 'AbortSearch', 'Success');
type
TOnIdentifierFound = function(Params: TFindDeclarationParams;
const FoundContext: TFindContext): TIdentifierFoundResult of object;
TOnFindUsedUnit = function(SrcTool: TFindDeclarationTool;
const TheUnitName, TheUnitInFilename: string): TCodeBuffer of object;
TOnGetCodeToolForBuffer = function(Sender: TObject;
Code: TCodeBuffer; GoToMainCode: boolean): TFindDeclarationTool of object;
TOnGetDirectoryCache = function(const ADirectory: string
): TCTDirectoryCache of object;
TFDHelpersListKind = (
fdhlkDelphiHelper,
fdhlkObjCCategory
);
{ TFDHelpersListItem }
TFDHelpersListItem = class(TObject)
ForExprType: TExpressionType;
HelperContext: TFindContext; // Node.Desc (ctnClassHelper, ctnRecordHelper, ctnTypeHelper) or (ctnObjCCategory)
function CalcMemSize: PtrUInt;
end;
{ TFDHelpersListRec }
TFDHelpersListRec = record
ForExprType: TExpressionType;
HelperContext: TFindContext;
end;
{ TFDHelpersList }
TFDHelpersList = class
private
FKind: TFDHelpersListKind;
FTree: TAVLTree; { tree of TFDHelpersListItem sorted for CompareHelpersList.
Nodes with same key (ForExprType) are chronologically ordered from left to right. }
procedure AddChronologically(Item: TFDHelpersListItem);
public
function AddFromHelperNode(HelperNode: TCodeTreeNode;
Tool: TFindDeclarationTool; Replace: Boolean): TFDHelpersListItem;
procedure AddFromList(const ExtList: TFDHelpersList);
function IterateFromClassNode(ClassNode: TCodeTreeNode;
Tool: TFindDeclarationTool; out HelperContext: TFindContext; out Iterator: TAVLTreeNode): boolean; // returns newest (rightmost)
function GetNext(out HelperContext: TFindContext; var Iterator: TAVLTreeNode): boolean;
function FindFromExprType(const ExprType: TExpressionType): TFindContext; // returns newest (rightmost)
procedure DeleteHelperNode(HelperNode: TCodeTreeNode; Tool: TFindDeclarationTool);
constructor Create(aKind: TFDHelpersListKind);
destructor Destroy; override;
procedure Clear;
function Count: Integer;
function CalcMemSize: PtrUInt;
procedure WriteDebugReport;
property Kind: TFDHelpersListKind read FKind;
property Tree: TAVLTree read FTree;
end;
{ TGenericParams }
TGenericParams = record
ParamValuesTool: TFindDeclarationTool;
SpecializeParamsNode: TCodeTreeNode;
end;
TFindDeclarationInput = record
Flags: TFindDeclarationFlags;
Identifier: PChar;
ContextNode: TCodeTreeNode;
OnIdentifierFound: TOnIdentifierFound;
IdentifierTool: TFindDeclarationTool;
FoundProc: PFoundProc;
end;
{ TFindDeclarationParams
This contains the parameters for find declaration, the result, the hooks
and the memory management for dynamic search data.
It can be re-used. That means, the search parameters can be saved, changed
and restored (load).
The static parameters are stored on the stack, while the dynamic data
(e.g. FoundProc) is stored in a private list (FirstFoundProc).
For speed reasons the find declaration does not use try..finally and that's
why some saved data is not explicitely freed. Therefore the Load method
frees all dynamic data, that was later saved too.
That's why the following code is forbidden:
Save(Data1);
Save(Data2);
Load(Data1); // this will free Data2
Load(Data2);
When searching a procedure, the parameter list must be compared.
The parameter list of the currently best fitting procedure is stored in
FoundProc.
}
TFindDeclarationParams = class(TObject)
private
FFoundProcStackFirst: PFoundProc;//list of all saved PFoundProc
FFoundProcStackLast: PFoundProc;
FExtractedOperand: string;
FHelpers: array[TFDHelpersListKind] of TFDHelpersList;
FFreeHelpers: array[TFDHelpersListKind] of Boolean;
FNeedHelpers: Boolean;
procedure ClearFoundProc;
procedure FreeFoundProc(aFoundProc: PFoundProc; FreeNext: boolean);
procedure RemoveFoundProcFromList(aFoundProc: PFoundProc);
private
procedure SetFoundProc(const ProcContext: TFindContext);
procedure ChangeFoundProc(const ProcContext: TFindContext;
ProcCompatibility: TTypeCompatibility;
ParamCompatibilityList: TTypeCompatibilityList);
private
procedure SetGenericParamValues(SpecializeParamsTool: TFindDeclarationTool;
SpecializeNode: TCodeTreeNode);
function FindGenericParamType: Boolean;
procedure AddOperandPart(aPart: string);
property ExtractedOperand: string read FExtractedOperand;
function IsFoundProcFinal: boolean;
procedure PrettifyResult;
procedure ConvertResultCleanPosToCaretPos;
procedure ClearResult(CopyCacheFlags: boolean);
procedure ClearInput;
public
// input parameters:
Flags: TFindDeclarationFlags;
Identifier: PChar;
StartTool: TFindDeclarationTool;
StartNode: TCodeTreeNode;
Parent: TFindDeclarationParams;
ContextNode: TCodeTreeNode;
OnIdentifierFound: TOnIdentifierFound;
IdentifierTool: TFindDeclarationTool;
FoundProc: PFoundProc;
Data: Pointer;
// global params
OnTopLvlIdentifierFound: TOnIdentifierFound;
GenParams: TGenericParams;
// results:
NewNode: TCodeTreeNode;
NewCleanPos: integer;
NewCodeTool: TFindDeclarationTool;
NewPos: TCodeXYPosition;
NewTopLine: integer;
NewFlags: TFoundDeclarationFlags;
constructor Create(ParentParams: TFindDeclarationParams = nil);
constructor Create(Tool: TFindDeclarationTool; AContextNode: TCodeTreeNode);
destructor Destroy; override;
procedure Clear;
procedure Save(out Input: TFindDeclarationInput);
procedure Load(Input: TFindDeclarationInput; FreeInput: boolean);
procedure SetResult(const AFindContext: TFindContext);
procedure SetResult(ANewCodeTool: TFindDeclarationTool;
ANewNode: TCodeTreeNode);
procedure SetResult(ANewCodeTool: TFindDeclarationTool;
ANewNode: TCodeTreeNode; ANewCleanPos: integer);
procedure SetResult(NodeCacheEntry: PCodeTreeNodeCacheEntry);
procedure SetIdentifier(NewIdentifierTool: TFindDeclarationTool;
NewIdentifier: PChar; NewOnIdentifierFound: TOnIdentifierFound);
procedure WriteDebugReport;
function GetHelpers(HelperKind: TFDHelpersListKind; CreateIfNotExists: boolean = false): TFDHelpersList;
end;
//----------------------------------------------------------------------------
// TFindDeclarationTool is source based and can therefore search for more
// than declarations:
type
TFindSmartFlag = (
fsfIncludeDirective, // search for include file
fsfFindMainDeclaration, // stop if already on a declaration
fsfSearchSourceName, // if searching for a unit name, return the source name node
fsfSkipClassForward // when a forward class was found, jump further to the class
);
TFindSmartFlags = set of TFindSmartFlag;
const
DefaultFindSmartFlags = [fsfIncludeDirective];
DefaultFindSmartHintFlags = DefaultFindSmartFlags+[fsfFindMainDeclaration];
type
TFindSrcStartType = (
fsstIdentifier
);
TFindDeclarationListFlag = (
fdlfWithoutEmptyProperties, // omit properties without type and attributes
fdlfWithoutForwards, // omit foward classes and procedures
fdlfIfStartIsDefinitionStop,// omit overloads when start is a definition
fdlfOneOverloadPerUnit // ignore other overloads of an identifier within the same unit
);
TFindDeclarationListFlags = set of TFindDeclarationListFlag;
TFindOperatorEnumerator = (
foeProcNode, // proc node of operator
foeResultClassNode, // classnode of result type of operator
foeEnumeratorCurrentNode, // function or property with modifier 'enumerator Current'
foeEnumeratorCurrentExprType // expression type of 'enumerator Current'
);
TFindFileAtCursorFlag = (
ffatNone,
ffatUsedUnit,
ffatIncludeFile,
ffatDisabledIncludeFile,
ffatResource,
ffatDisabledResource,
ffatLiteral,
ffatComment,
ffatUnit // unit by name
);
TFindFileAtCursorFlags = set of TFindFileAtCursorFlag;
const
DefaultFindFileAtCursorAllowed = [Low(TFindFileAtCursorFlag)..high(TFindFileAtCursorFlag)];
type
//----------------------------------------------------------------------------
ECodeToolUnitNotFound = class(ECodeToolFileNotFound)
end;
//----------------------------------------------------------------------------
TFindIdentifierInUsesSection_FindMissingFPCUnit = class;
//----------------------------------------------------------------------------
{ TFindDeclarationTool }
TFindDeclarationTool = class(TPascalReaderTool)
private
FAdjustTopLineDueToComment: boolean;
FDirectoryCache: TCTDirectoryCache;
FFindMissingFPCUnits: TFindIdentifierInUsesSection_FindMissingFPCUnit;
FInterfaceIdentifierCache: TInterfaceIdentifierCache;
FInterfaceHelperCache: array[TFDHelpersListKind] of TFDHelpersList;
FOnFindUsedUnit: TOnFindUsedUnit;
FOnGetCodeToolForBuffer: TOnGetCodeToolForBuffer;
FOnGetDirectoryCache: TOnGetDirectoryCache;
FOnGetMethodName: TOnGetMethodname;
FOnGetSrcPathForCompiledUnit: TOnGetSrcPathForCompiledUnit;
FOnGetUnitSourceSearchPath: TOnGetSearchPath;
FFirstNodeCache: TCodeTreeNodeCache;
FOnRescanFPCDirectoryCache: TNotifyEvent;
FRootNodeCache: TCodeTreeNodeCache;
FFirstBaseTypeCache: TBaseTypeCache;
FDependentCodeTools: TAVLTree;// the codetools, that depend on this codetool
FDependsOnCodeTools: TAVLTree;// the codetools, that this codetool depends on
FClearingDependentNodeCaches: boolean;
FCheckingNodeCacheDependencies: boolean;
FSourcesChangeStep, FFilesChangeStep: int64;
FInitValuesChangeStep: integer;
{$IFDEF DebugPrefix}
DebugPrefix: string;
procedure IncPrefix;
procedure DecPrefix;
{$ENDIF}
function FindDeclarationInUsesSection(UsesNode: TCodeTreeNode;
CleanPos: integer;
out NewPos: TCodeXYPosition; out NewTopLine: integer): boolean;
function FindUnitFileInUsesSection(UsesNode: TCodeTreeNode;
const AFilename: string): TCodeTreeNode;
function FindUnitFileInAllUsesSections(const AFilename: string;
CheckMain: boolean = true; CheckImplementation: boolean = true): TCodeTreeNode;
function FindEnumInContext(Params: TFindDeclarationParams): boolean;
// sub methods for FindIdentifierInContext
function DoOnIdentifierFound(Params: TFindDeclarationParams;
FoundNode: TCodeTreeNode): TIdentifierFoundResult;
function FindIdentifierInProcContext(ProcContextNode: TCodeTreeNode;
Params: TFindDeclarationParams): TIdentifierFoundResult;
function FindIdentifierInClassOfMethod(ProcContextNode: TCodeTreeNode;
Params: TFindDeclarationParams): boolean;
function FindIdentifierInWithVarContext(WithVarNode: TCodeTreeNode;
Params: TFindDeclarationParams): boolean;
function FindIdentifierInAncestors(ClassNode: TCodeTreeNode;
Params: TFindDeclarationParams; var IdentFoundResult: TIdentifierFoundResult): boolean;
function FindIdentifierInAncestors(ClassNode: TCodeTreeNode;
Params: TFindDeclarationParams): boolean;
function FindIdentifierInUsesSection(UsesNode: TCodeTreeNode;
Params: TFindDeclarationParams; FindMissingFPCUnits: Boolean): boolean;
function FindIdentifierInHiddenUsedUnits(
Params: TFindDeclarationParams): boolean;
function FindIdentifierInUsedUnit(const AnUnitName: string;
Params: TFindDeclarationParams; ErrorPos: integer): boolean;
function FindIdentifierInTypeOfConstant(VarConstNode: TCodeTreeNode;
Params: TFindDeclarationParams): boolean;
protected
WordIsPredefinedIdentifier: TKeyWordFunctionList;
procedure RaiseUsesExpected(id: int64);
procedure RaiseStrConstExpected(id: int64);
protected
// node caches
procedure DoDeleteNodes(StartNode: TCodeTreeNode); override;
function CheckDependsOnNodeCaches(CheckedTools: TAVLTree = nil): boolean;
procedure ClearNodeCaches;
procedure ClearDependentNodeCaches;
procedure ClearDependsOnToolRelationships;
procedure AddToolDependency(DependOnTool: TFindDeclarationTool);
function CreateNewNodeCache(Node: TCodeTreeNode): TCodeTreeNodeCache;
function CreateNewBaseTypeCache(Tool: TFindDeclarationTool;
Node: TCodeTreeNode): TBaseTypeCache;
procedure CreateBaseTypeCaches(NodeStack: PCodeTreeNodeStack;
const Result: TFindContext);
function GetNodeCache(Node: TCodeTreeNode;
CreateIfNotExists: boolean): TCodeTreeNodeCache;
procedure AddResultToNodeCaches(
StartNode, EndNode: TCodeTreeNode; SearchedForward: boolean;
Params: TFindDeclarationParams; SearchRangeFlags: TNodeCacheEntryFlags);
protected
// expressions, operands, variables
function GetCurrentAtomType: TVariableAtomType;
function FindEndOfTerm(StartPos: integer;
ExceptionIfNoVariableStart, WithAsOperator: boolean): integer; // read one operand
function FindStartOfTerm(EndPos: integer; InType: boolean): integer;
function NodeTermInType(Node: TCodeTreeNode): boolean;
function FindExpressionTypeOfTerm(StartPos, EndPos: integer;
Params: TFindDeclarationParams; WithAsOperator: boolean;
AliasType: PFindContext = nil): TExpressionType;
function FindEndOfExpression(StartPos: integer): integer; // read all operands and operators
function ReadOperandTypeAtCursor(Params: TFindDeclarationParams;
MaxEndPos: integer = -1; AliasType: PFindContext = nil): TExpressionType;
function FindExpressionTypeOfPredefinedIdentifier(StartPos: integer;
Params: TFindDeclarationParams; AliasType: PFindContext = nil): TExpressionType;
function FindExpressionTypeOfConstSet(Node: TCodeTreeNode): TExpressionType;
function GetDefaultStringType: TExpressionTypeDesc;
function CalculateBinaryOperator(LeftOperand, RightOperand: TOperand;
BinaryOperator: TAtomPosition;
Params: TFindDeclarationParams): TOperand;
function GetParameterNode(Node: TCodeTreeNode): TCodeTreeNode;
function GetExpressionTypeOfTypeIdentifier(
Params: TFindDeclarationParams): TExpressionType;
function FindTermTypeAsString(TermPos: TAtomPosition;
Params: TFindDeclarationParams; out ExprType: TExpressionType): string;
function FindForInTypeAsString(TermPos: TAtomPosition;
CursorNode: TCodeTreeNode; Params: TFindDeclarationParams;
out ExprType: TExpressionType): string;
function FindEnumeratorOfClass(ClassNode: TCodeTreeNode;
ExceptionOnNotFound: boolean; out ExprType: TExpressionType;
AliasType: PFindContext = nil; ParentParams: TFindDeclarationParams = nil): boolean;
function FindOperatorEnumerator(Node: TCodeTreeNode;
ExprType: TExpressionType; Need: TFindOperatorEnumerator;
out ResultExprType: TExpressionType): boolean;
function FindEnumerationTypeOfSetType(SetTypeNode: TCodeTreeNode;
out Context: TFindContext): boolean;
function FindElementTypeOfArrayType(ArrayNode: TCodeTreeNode;
out ExprType: TExpressionType; AliasType: PFindContext): boolean;
function CheckOperatorEnumerator(Params: TFindDeclarationParams;
const FoundContext: TFindContext): TIdentifierFoundResult;
function CheckModifierEnumeratorCurrent({%H-}Params: TFindDeclarationParams;
const FoundContext: TFindContext): TIdentifierFoundResult;
function IsTermEdgedBracket(TermPos: TAtomPosition;
out EdgedBracketsStartPos: integer): boolean;
function IsTermNamedPointer(TermPos: TAtomPosition;
out ExprType: TExpressionType): boolean;
function FindSetOfEnumerationType(EnumNode: TCodeTreeNode): TCodeTreeNode;
function FindPointerOfIdentifier(TypeNode: TCodeTreeNode): TCodeTreeNode;
function FindExprTypeAsString(const ExprType: TExpressionType;
TermCleanPos: integer;
AliasType: PFindContext = nil): string;
protected
function CheckSrcIdentifier(Params: TFindDeclarationParams;
const FoundContext: TFindContext): TIdentifierFoundResult;
function FindDeclarationOfIdentAtParam(
Params: TFindDeclarationParams; out ExprType: TExpressionType): boolean;
function FindDeclarationOfIdentAtParam(
Params: TFindDeclarationParams): boolean;
function IdentifierIsDefined(const IdentAtom: TAtomPosition;
ContextNode: TCodeTreeNode; Params: TFindDeclarationParams): boolean;
function FindContextNodeAtCursor(
Params: TFindDeclarationParams): TFindContext;
function FindClassOfMethod(ProcNode: TCodeTreeNode;
FindClassContext, ExceptionOnNotFound: boolean): TCodeTreeNode;
function FindClassMember(aClassNode: TCodeTreeNode; Identifier: PChar): TCodeTreeNode;
function FindForwardIdentifier(Params: TFindDeclarationParams;
out IsForward: boolean): boolean;
function FindNonForwardClass(ForwardNode: TCodeTreeNode): TCodeTreeNode;
function FindNonForwardClass(Params: TFindDeclarationParams): boolean;
function FindIdentifierInInterface(AskingTool: TFindDeclarationTool;
Params: TFindDeclarationParams): boolean;
function CompareNodeIdentifier(Node: TCodeTreeNode;
Params: TFindDeclarationParams): boolean;
function GetInterfaceNode: TCodeTreeNode;
function CompatibilityList1IsBetter(List1, List2: TTypeCompatibilityList;
ListCount: integer): boolean;
function IsParamExprListCompatibleToNodeList(
FirstTargetParameterNode: TCodeTreeNode;
SourceExprParamList: TExprTypeList; IgnoreMissingParameters: boolean;
Params: TFindDeclarationParams;
CompatibilityList: TTypeCompatibilityList): TTypeCompatibility;
function IsParamNodeListCompatibleToParamNodeList(FirstTargetParameterNode,
FirstSourceParameterNode: TCodeTreeNode;
Params: TFindDeclarationParams;
CompatibilityList: TTypeCompatibilityList): TTypeCompatibility;
function CreateParamExprListFromStatement(StartPos: integer;
Params: TFindDeclarationParams; GetAlias: boolean = false): TExprTypeList;
function ContextIsDescendOf(
const DescendContext, AncestorContext: TFindContext;
Params: TFindDeclarationParams): boolean;
function IsCompatible(TargetNode: TCodeTreeNode;
const ExpressionType: TExpressionType;
Params: TFindDeclarationParams): TTypeCompatibility;
function IsCompatible(TargetType, ExpressionType: TExpressionType;
Params: TFindDeclarationParams): TTypeCompatibility;
function IsBaseCompatible(const TargetType, ExpressionType: TExpressionType;
Params: TFindDeclarationParams): TTypeCompatibility;
function CheckParameterSyntax(StartPos, CleanCursorPos: integer;
out ParameterAtom, ProcNameAtom: TAtomPosition;
out ParameterIndex: integer): boolean;
procedure OnFindUsedUnitIdentifier(Sender: TPascalParserTool;
IdentifierCleanPos: integer; Range: TEPRIRange;
Node: TCodeTreeNode; Data: Pointer; var {%H-}Abort: boolean);
public
constructor Create;
destructor Destroy; override;
procedure ConsistencyCheck; override;
procedure CalcMemSize(Stats: TCTMemStats); override;
procedure BeginParsing(Range: TLinkScannerRange); override;
procedure ValidateToolDependencies; override;
function BuildInterfaceIdentifierCache(ExceptionOnNotUnit: boolean): boolean;
function FindDeclaration(const CursorPos: TCodeXYPosition;
out NewPos: TCodeXYPosition; out NewTopLine: integer): boolean;
function FindMainDeclaration(const CursorPos: TCodeXYPosition;
out NewPos: TCodeXYPosition; out NewTopLine: integer): boolean;
function FindDeclarationOfIdentifier(const CursorPos: TCodeXYPosition;
Identifier: PChar;
out NewPos: TCodeXYPosition; out NewTopLine: integer): boolean;
function FindDeclaration(const CursorPos: TCodeXYPosition;
SearchSmartFlags: TFindSmartFlags;
out NewTool: TFindDeclarationTool; out NewNode: TCodeTreeNode;
out NewPos: TCodeXYPosition; out NewTopLine: integer): boolean;
function FindDeclaration(const CursorPos: TCodeXYPosition;
SearchSmartFlags: TFindSmartFlags;
out NewTool: TFindDeclarationTool; out NewNode: TCodeTreeNode;
out NewPos: TCodeXYPosition; out NewTopLine, BlockTopLine, BlockBottomLine: integer): boolean;
function FindDeclaration(const CursorPos: TCodeXYPosition;
SearchSmartFlags: TFindSmartFlags;
out NewExprType: TExpressionType;
out NewPos: TCodeXYPosition; out NewTopLine: integer): boolean;
function FindDeclaration(const CursorPos: TCodeXYPosition;
SearchSmartFlags: TFindSmartFlags;
out NewExprType: TExpressionType;
out NewPos: TCodeXYPosition; out NewTopLine,BlockTopLine,BlockBottomLine: integer): boolean;
function FindDeclarationInInterface(const Identifier: string;
out NewPos: TCodeXYPosition; out NewTopLine, BlockTopLine, BlockBottomLine: integer): boolean;
function FindDeclarationWithMainUsesSection(const Identifier: string;
out NewPos: TCodeXYPosition; out NewTopLine: integer): boolean;
function FindClassMember(aClassNode: TCodeTreeNode;
const Identifier: String; SearchInAncestors: boolean): TFindContext;
function FindDeclarationOfPropertyPath(const PropertyPath: string;
out NewContext: TFindContext; IgnoreTypeLess: boolean = false): boolean;
function FindDeclarationOfPropertyPath(const PropertyPath: string;
out NewPos: TCodeXYPosition; out NewTopLine: integer;
IgnoreTypeLess: boolean = false): boolean;
function FindDeclarationNodeInInterface(const Identifier: string;
BuildTheTree: Boolean): TCodeTreeNode;// search for type, const, var, proc, prop
function FindDeclarationNodeInImplementation(Identifier: string;
BuildTheTree: Boolean): TCodeTreeNode;// search for type, const, var, proc, prop
function FindSubDeclaration(Identifier: string; ParentNode: TCodeTreeNode
): TCodeTreeNode; // search for type, const, var, proc, prop
function FindNameInUsesSection(UsesNode: TCodeTreeNode; const AUnitName: string): TCodeTreeNode;
function FindUnitInUsesSection(UsesNode: TCodeTreeNode; const AnUnitName: string;
out NamePos, InPos: TAtomPosition): boolean;
function FindUnitInAllUsesSections(const AnUnitName: string;
out NamePos, InPos: TAtomPosition): boolean;
function GetUnitNameForUsesSection(TargetTool: TFindDeclarationTool): string;
function IsHiddenUsedUnit(TheUnitName: PChar): boolean;
function FindCodeToolForUsedUnit(const AnUnitName, AnUnitInFilename: string;
ExceptionOnNotFound: boolean): TFindDeclarationTool;
function FindUnitSource(const AnUnitName,
AnUnitInFilename: string; ExceptionOnNotFound: boolean;
ErrorPos: integer = 0): TCodeBuffer;
function FindUnitCaseInsensitive(var AnUnitName,
AnUnitInFilename: string): string;
procedure GatherUnitAndSrcPath(var UnitPath, CompleteSrcPath: string);
function SearchUnitInUnitSet(const TheUnitName: string): string;
function GetNameSpaces: string;
function IsIncludeDirectiveAtPos(CleanPos, CleanCodePosInFront: integer;
out IncludeCode: TCodeBuffer): boolean;
function FindFileAtCursor(const CursorPos: TCodeXYPosition;
out Found: TFindFileAtCursorFlag; out FoundFilename: string;
SearchFor: TFindFileAtCursorFlags = DefaultFindFileAtCursorAllowed;
StartPos: PCodeXYPosition = nil): boolean;
function FindSmartHint(const CursorPos: TCodeXYPosition;
Flags: TFindSmartFlags = DefaultFindSmartHintFlags): string;
function GetSmartHint(Node: TCodeTreeNode; XYPos: TCodeXYPosition;
WithPosition: boolean; WithDefinition: boolean = True): string;
function BaseTypeOfNodeHasSubIdents(ANode: TCodeTreeNode): boolean;
function FindBaseTypeOfNode(Params: TFindDeclarationParams;
Node: TCodeTreeNode; AliasType: PFindContext = nil;
NodeStack: PCodeTreeNodeStack = nil): TFindContext;
function ConvertNodeToExpressionType(Node: TCodeTreeNode;
Params: TFindDeclarationParams; AliasType: PFindContext = nil): TExpressionType;
function FindExpressionResultType(Params: TFindDeclarationParams;
StartPos, EndPos: integer; AliasType: PFindContext = nil): TExpressionType;
function FindDeclarationAndOverload(const CursorPos: TCodeXYPosition;
out ListOfPCodeXYPosition: TFPList;
Flags: TFindDeclarationListFlags): boolean;
function FindIdentifierContextsAtStatement(CleanPos: integer;
out IsSubIdentifier: boolean; out ListOfPFindContext: TFPList): boolean;
// ancestors
function FindClassAndAncestors(ClassNode: TCodeTreeNode;
var ListOfPFindContext: TFPList; ExceptionOnNotFound: boolean
): boolean; // without interfaces, recursive
function FindContextClassAndAncestorsAndExtendedClassOfHelper(const CursorPos: TCodeXYPosition;
var ListOfPFindContext: TFPList): boolean; // without interfaces
function FindAncestorOfClass(ClassNode: TCodeTreeNode;
Params: TFindDeclarationParams; FindClassContext: boolean): boolean; // returns false for TObject, IInterface, IUnknown
function FindDefaultAncestorOfClass(ClassNode: TCodeTreeNode;
Params: TFindDeclarationParams; FindClassContext: boolean): boolean; // returns false for TObject, IInterface, IUnknown
function FindAncestorOfClassInheritance(IdentifierNode: TCodeTreeNode;
ResultParams: TFindDeclarationParams; FindClassContext: boolean): boolean;
function FindAncestorsOfClass(ClassNode: TCodeTreeNode;
var ListOfPFindContext: TFPList;
Params: TFindDeclarationParams; FindClassContext: boolean;
ExceptionOnNotFound: boolean = true): boolean; // with interfaces, not recursive
function FindExtendedExprOfHelper(HelperNode: TCodeTreeNode): TExpressionType;
function FindReferences(const CursorPos: TCodeXYPosition;
SkipComments: boolean; out ListOfPCodeXYPosition: TFPList): boolean;
function FindUnitReferences(UnitCode: TCodeBuffer;
SkipComments: boolean; out ListOfPCodeXYPosition: TFPList): boolean; // searches unitname of UnitCode
procedure FindUsedUnitReferences(const CursorPos: TCodeXYPosition;
SkipComments: boolean; out UsedUnitFilename: string;
out ListOfPCodeXYPosition: TFPList); // searches all references of unit in uses clause
procedure FindUsedUnitReferences(TargetTool: TFindDeclarationTool;
SkipComments: boolean;
out ListOfPCodeXYPosition: TFPList); // searches all references of TargetTool
function CleanPosIsDeclarationIdentifier(CleanPos: integer;
Node: TCodeTreeNode): boolean;
procedure FindHelpersInContext(Params: TFindDeclarationParams);
procedure FindHelpersInUsesSection(UsesNode: TCodeTreeNode;
Params: TFindDeclarationParams);
procedure FindHelpersInInterface(AskingTool: TFindDeclarationTool;
Params: TFindDeclarationParams);
function FindIdentifierInContext(Params: TFindDeclarationParams;
var IdentFoundResult: TIdentifierFoundResult): boolean;
function FindIdentifierInContext(Params: TFindDeclarationParams): boolean;
function FindIdentifierInBasicTypeHelpers(ExprType: TExpressionTypeDesc;
Params: TFindDeclarationParams): Boolean;
function FindNthParameterNode(Node: TCodeTreeNode;
ParameterIndex: integer): TCodeTreeNode;
function GetFirstParameterNode(Node: TCodeTreeNode): TCodeTreeNode;
function IsParamNodeListCompatibleToExprList(
TargetExprParamList: TExprTypeList;
FirstSourceParameterNode: TCodeTreeNode;
Params: TFindDeclarationParams;
CompatibilityList: TTypeCompatibilityList = nil): TTypeCompatibility;
function CreateParamExprListFromProcNode(ProcNode: TCodeTreeNode;
Params: TFindDeclarationParams): TExprTypeList;
function JumpToNode(ANode: TCodeTreeNode;
out NewPos: TCodeXYPosition; out NewTopLine: integer;
IsCodeBlock: boolean): boolean;
function JumpToNode(ANode: TCodeTreeNode;
out NewPos: TCodeXYPosition; out NewTopLine, BlockTopLine, BlockBottomLine: integer;
IsCodeBlock: boolean): boolean;
function JumpToCleanPos(NewCleanPos, NewTopLineCleanPos,
NewBottomLineCleanPos: integer;
out NewPos: TCodeXYPosition; out NewTopLine: integer;
IsCodeBlock: boolean): boolean;
function JumpToCleanPos(NewCleanPos, NewTopLineCleanPos,
NewBottomLineCleanPos: integer;
out NewPos: TCodeXYPosition; out NewTopLine, BlockTopLine, BlockBottomLine: integer;
IsCodeBlock: boolean): boolean;
function NodeIsForwardDeclaration(Node: TCodeTreeNode): boolean;
function GetExpandedOperand(const CursorPos: TCodeXYPosition;
out Operand: string; ResolveProperty: Boolean): Boolean;
property InterfaceIdentifierCache: TInterfaceIdentifierCache
read FInterfaceIdentifierCache;
property OnGetUnitSourceSearchPath: TOnGetSearchPath
read FOnGetUnitSourceSearchPath write FOnGetUnitSourceSearchPath;
property OnFindUsedUnit: TOnFindUsedUnit
read FOnFindUsedUnit write FOnFindUsedUnit;
property OnGetCodeToolForBuffer: TOnGetCodeToolForBuffer
read FOnGetCodeToolForBuffer write FOnGetCodeToolForBuffer;
property OnGetDirectoryCache: TOnGetDirectoryCache read FOnGetDirectoryCache
write FOnGetDirectoryCache;
property OnGetSrcPathForCompiledUnit: TOnGetSrcPathForCompiledUnit
read FOnGetSrcPathForCompiledUnit write fOnGetSrcPathForCompiledUnit;
property OnGetMethodName: TOnGetMethodname read FOnGetMethodName
write FOnGetMethodName;
property AdjustTopLineDueToComment: boolean
read FAdjustTopLineDueToComment write FAdjustTopLineDueToComment;
property DirectoryCache: TCTDirectoryCache read FDirectoryCache write FDirectoryCache;
property OnRescanFPCDirectoryCache: TNotifyEvent read FOnRescanFPCDirectoryCache write FOnRescanFPCDirectoryCache;
end;
TFindIdentifierInUsesSection_FindMissingFPCUnit = class
private
FUnitName: string;
FFound: Boolean;
FResults: TStringList;
procedure Iterate(const AFilename: string);
public
constructor Create;
destructor Destroy; override;
function Find(const AUnitName: string; const ADirectoryCache: TCTDirectoryCache): Boolean;
function IsInResults(const AUnitName: string): Boolean;
end;
function ExprTypeToString(const ExprType: TExpressionType): string;
function CreateExpressionType(const Desc, SubDesc: TExpressionTypeDesc;
const Context: TFindContext): TExpressionType;
function FindContextToString(const FindContext: TFindContext; RelativeFilename: boolean = true): string; overload;
function FindContextToString(const FindContext: PFindContext; RelativeFilename: boolean = true): string; overload;
function CreateFindContext(NewTool: TFindDeclarationTool;
NewNode: TCodeTreeNode): TFindContext;
function CreateFindContext(Params: TFindDeclarationParams): TFindContext;
function CreateFindContext(BaseTypeCache: TBaseTypeCache): TFindContext;
function FindContextAreEqual(const Context1, Context2: TFindContext): boolean;
function CompareFindContexts(const Context1, Context2: PFindContext): integer;
procedure AddFindContext(var ListOfPFindContext: TFPList;
const NewContext: TFindContext);
function IndexOfFindContext(var ListOfPFindContext: TFPList;
const AContext: PFindContext): integer;
procedure FreeListOfPFindContext(var ListOfPFindContext: TFPList);
function ListOfPFindContextToStr(const ListOfPFindContext: TFPList): string;
function dbgsFC(const Context: TFindContext): string;
function PredefinedIdentToExprTypeDesc(Identifier: PChar; Compiler: TPascalCompiler): TExpressionTypeDesc;
function dbgs(const Flags: TFindDeclarationFlags): string; overload;
function dbgs(const Flags: TFoundDeclarationFlags): string; overload;
function dbgs(const vat: TVariableAtomType): string; overload;
function dbgs(const Kind: TFDHelpersListKind): string; overload;
function BooleanTypesOrderList: TTypeAliasOrderList;
function IntegerTypesOrderList: TTypeAliasOrderList;
function RealTypesOrderList: TTypeAliasOrderList;
function StringTypesOrderList: TTypeAliasOrderList;
implementation
var
FBooleanTypesOrderList: TTypeAliasOrderList;
FIntegerTypesOrderList: TTypeAliasOrderList;
FRealTypesOrderList: TTypeAliasOrderList;
FStringTypesOrderList: TTypeAliasOrderList;
type
{ TFindUsedUnitReferences }
TFindUsedUnitReferences = class
public
TargetTool: TFindDeclarationTool;
TargetUnitName: string;
ListOfPCodeXYPosition: TFPList;
Params: TFindDeclarationParams;
constructor Create(Tool: TFindDeclarationTool; AContextNode: TCodeTreeNode);
destructor Destroy; override;
end;
function dbgs(const Flags: TFindDeclarationFlags): string;
var
Flag: TFindDeclarationFlag;
s: string;
begin
Result:='';
for Flag:=Low(TFindDeclarationFlag) to High(TFindDeclarationFlag) do begin
if Flag in Flags then begin
if Result<>'' then
Result:=Result+', ';
WriteStr(s, Flag);
Result:=Result+s;
end;
end;
end;
function dbgs(const Flags: TFoundDeclarationFlags): string;
var
Flag: TFoundDeclarationFlag;
s: string;
begin
Result:='';
for Flag:=Low(TFoundDeclarationFlag) to High(TFoundDeclarationFlag) do begin
if Flag in Flags then begin
if Result<>'' then
Result:=Result+', ';
WriteStr(s, Flag);
Result:=Result+s;
end;
end;
end;
function dbgs(const vat: TVariableAtomType): string;
begin
Result:=VariableAtomTypeNames[vat];
end;
function dbgs(const Kind: TFDHelpersListKind): string;
begin
WriteStr(Result, Kind);
end;
function BooleanTypesOrderList: TTypeAliasOrderList;
begin
if FBooleanTypesOrderList=nil then
FBooleanTypesOrderList:=TTypeAliasOrderList.Create([
'LongBool', 'WordBool', 'Boolean', 'ByteBool']);
Result := FBooleanTypesOrderList;
end;
function IntegerTypesOrderList: TTypeAliasOrderList;
begin
if FIntegerTypesOrderList=nil then
FIntegerTypesOrderList:=TTypeAliasOrderList.Create([
'Int64', 'QWord',
'NativeInt', 'IntPtr', 'SizeInt', 'NativeUInt', 'UIntPtr',
'Int32', 'Integer', 'LongInt', 'UInt32', 'Cardinal', 'LongWord',
'Int16', 'SmallInt', 'UInt16', 'Word',
'Int8', 'ShortInt', 'UInt8', 'Byte']);
Result := FIntegerTypesOrderList;
end;
function RealTypesOrderList: TTypeAliasOrderList;
begin
if FRealTypesOrderList=nil then
FRealTypesOrderList:=TTypeAliasOrderList.Create([
'Extended', 'Real', 'Double', 'Single']);
Result := FRealTypesOrderList;
end;
function StringTypesOrderList: TTypeAliasOrderList;
begin
if FStringTypesOrderList=nil then
FStringTypesOrderList:=TTypeAliasOrderList.Create([
'string', 'AnsiString', 'WideString', 'ShortString', 'Char', 'WideChar', 'AnsiChar']);
Result := FStringTypesOrderList;
end;
function ListOfPFindContextToStr(const ListOfPFindContext: TFPList): string;
var
Context: TFindContext;
i: Integer;
begin
if ListOfPFindContext=nil then
Result:='nil'
else begin
Result:='';
for i:=0 to ListOfPFindContext.Count-1 do begin
Context:=PFindContext(ListOfPFindContext[i])^;
Result:=Result+' '+DbgsFC(Context)+LineEnding;
end;
end;
end;
function dbgsFC(const Context: TFindContext): string;
var
CursorPos: TCodeXYPosition;
begin
if Context.Tool=nil then
Result:='nil'
else begin
Result:=Context.Tool.MainFilename;
if Context.Node=nil then
Result:=Result+'()'
else begin
Context.Tool.CleanPosToCaret(Context.Node.StartPos,CursorPos);
Result:=Result+'(y='+dbgs(CursorPos.Y)+',x='+dbgs(CursorPos.X)+')';
end;
end;
end;
function PredefinedIdentToExprTypeDesc(Identifier: PChar;
Compiler: TPascalCompiler): TExpressionTypeDesc;
begin
// predefined identifiers
if CompareIdentifiers(Identifier,'NIL')=0 then
Result:=xtNil
else if CompareIdentifiers(Identifier,'POINTER')=0 then
Result:=xtPointer
else if (CompareIdentifiers(Identifier,'TRUE')=0)
or (CompareIdentifiers(Identifier,'FALSE')=0) then
Result:=xtConstBoolean
else if CompareIdentifiers(Identifier,'STRING')=0 then
Result:=xtString
else if CompareIdentifiers(Identifier,'SHORTSTRING')=0 then
Result:=xtShortString
else if CompareIdentifiers(Identifier,'ANSISTRING')=0 then
Result:=xtAnsiString
else if CompareIdentifiers(Identifier,'WIDESTRING')=0 then
Result:=xtWideString
else if CompareIdentifiers(Identifier,'UNICODESTRING')=0 then
Result:=xtUnicodeString
else if CompareIdentifiers(Identifier,'INT64')=0 then
Result:=xtInt64
else if CompareIdentifiers(Identifier,'CARDINAL')=0 then
Result:=xtCardinal
else if CompareIdentifiers(Identifier,'QWORD')=0 then
Result:=xtQWord
else if CompareIdentifiers(Identifier,'BOOLEAN')=0 then
Result:=xtBoolean
else if CompareIdentifiers(Identifier,'BYTEBOOL')=0 then
Result:=xtByteBool
else if CompareIdentifiers(Identifier,'WORDBOOL')=0 then
Result:=xtWordBool
else if CompareIdentifiers(Identifier,'LONGBOOL')=0 then
Result:=xtLongBool
else if CompareIdentifiers(Identifier,'QWORDBOOL')=0 then
Result:=xtQWordBool
else if CompareIdentifiers(Identifier,'CHAR')=0 then
Result:=xtChar
else if CompareIdentifiers(Identifier,'WIDECHAR')=0 then
Result:=xtWideChar
else if CompareIdentifiers(Identifier,'REAL')=0 then
Result:=xtReal
else if CompareIdentifiers(Identifier,'SINGLE')=0 then
Result:=xtSingle
else if CompareIdentifiers(Identifier,'DOUBLE')=0 then
Result:=xtDouble
else if CompareIdentifiers(Identifier,'EXTENDED')=0 then
Result:=xtExtended
else if CompareIdentifiers(Identifier,'CEXTENDED')=0 then
Result:=xtCExtended
else if CompareIdentifiers(Identifier,'COMP')=0 then
Result:=xtComp
else if CompareIdentifiers(Identifier,'FILE')=0 then
Result:=xtFile
else if CompareIdentifiers(Identifier,'TEXT')=0 then
Result:=xtText
else if CompareIdentifiers(Identifier,'SIZEOF')=0 then
Result:=xtConstOrdInteger
else if CompareIdentifiers(Identifier,'ORD')=0 then
Result:=xtConstOrdInteger
else if CompareIdentifiers(Identifier,'ASSIGNED')=0 then
Result:=xtConstBoolean
else if CompareIdentifiers(Identifier,'VARIANT')=0 then
Result:=xtVariant
else if CompareIdentifiers(Identifier,'CURRENCY')=0 then
Result:=xtCurrency
else if CompareIdentifiers(Identifier,'LONGINT')=0 then
Result:=xtLongInt
else if CompareIdentifiers(Identifier,'LONGWORD')=0 then
Result:=xtLongWord
else if CompareIdentifiers(Identifier,'WORD')=0 then
Result:=xtWord
else if CompareIdentifiers(Identifier,'LONGWORD')=0 then
Result:=xtCardinal
else if CompareIdentifiers(Identifier,'SMALLINT')=0 then
Result:=xtSmallInt
else if CompareIdentifiers(Identifier,'SHORTINT')=0 then
Result:=xtShortInt
else if CompareIdentifiers(Identifier,'BYTE')=0 then
Result:=xtByte
else if CompareIdentifiers(Identifier,'PCHAR')=0 then
Result:=xtPChar
else if IsWordBuiltInFunc.DoItCaseInsensitive(Identifier) then
Result:=xtCompilerFunc
else begin
// compiler specific
if (Compiler=pcPas2js) then begin
if CompareIdentifiers(Identifier,'JSVALUE')=0 then
exit(xtJSValue);
if CompareIdentifiers(Identifier,'NATIVEINT')=0 then
exit(xtNativeInt);
if CompareIdentifiers(Identifier,'NATIVEUINT')=0 then
exit(xtNativeUInt);
end;
if (Compiler=pcDelphi) then begin
if CompareIdentifiers(Identifier,'NATIVEINT')=0 then
exit(xtNativeInt);
if CompareIdentifiers(Identifier,'NATIVEUINT')=0 then
exit(xtNativeUInt);
end;
Result:=xtNone;
end;
end;
function CompareTypeAliasItems(Item1, Item2: Pointer): Integer;
var
xItem1: TTypeAliasItem absolute Item1;
xItem2: TTypeAliasItem absolute Item2;
begin
Result := CompareIdentifiers(PChar(xItem1.AliasName), PChar(xItem2.AliasName));
end;
function CompareTypeAliasItemString(AliasName, Item: Pointer): Integer;
var
xAliasName: PChar absolute AliasName;
xItem: TTypeAliasItem absolute Item;
begin
Result := CompareIdentifiers(xAliasName, PChar(xItem.AliasName));
end;
function ExprTypeToString(const ExprType: TExpressionType): string;
begin
Result:='Desc='+ExpressionTypeDescNames[ExprType.Desc]
+' SubDesc='+ExpressionTypeDescNames[ExprType.SubDesc]
+' '+FindContextToString(ExprType.Context);
end;
function CreateExpressionType(const Desc, SubDesc: TExpressionTypeDesc;
const Context: TFindContext): TExpressionType;
begin
Result.Desc:=Desc;
Result.SubDesc:=SubDesc;
Result.Context:=Context;
end;
{ TFindContext }
function FindContextToString(const FindContext: TFindContext;
RelativeFilename: boolean): string;
var
IdentNode: TCodeTreeNode;
begin
Result:='';
if FindContext.Node<>nil then begin
Result:=Result+'Node="'+FindContext.Node.DescAsString+'"';
IdentNode:=FindContext.Node;
while IdentNode<>nil do begin
if IdentNode.Desc in AllSimpleIdentifierDefinitions
+[ctnIdentifier,ctnEnumIdentifier,ctnLabel]
then begin
Result:=Result+' Ident="'+
FindContext.Tool.ExtractIdentifier(IdentNode.StartPos)+'"';
break;
end else if IdentNode.Desc=ctnGenericType then begin
if IdentNode.FirstChild<>nil then
Result:=Result+' Generic="'+
FindContext.Tool.ExtractIdentifier(IdentNode.FirstChild.StartPos)+'"'
else
Result:=Result+' Generic=?';
end else if IdentNode.Desc in [ctnProperty,ctnGlobalProperty] then begin
Result:=Result+' PropName="'+
FindContext.Tool.ExtractPropName(IdentNode,false)+'"';
break;
end else if IdentNode.Desc=ctnProcedure then begin
Result:=Result+' Proc="'+FindContext.Tool.ExtractProcName(IdentNode,[])+'"';
break;
end;
IdentNode:=IdentNode.Parent;
end;
if RelativeFilename then
Result:=Result+' at "'+FindContext.Tool.CleanPosToStr(FindContext.Node.StartPos,true)+'"'
else
Result:=Result+' at "'+FindContext.Tool.CleanPosToRelativeStr(FindContext.Node.StartPos,'')+'"'
end else
Result:='nil';
end;
function FindContextToString(const FindContext: PFindContext;
RelativeFilename: boolean): string;
begin
if FindContext=nil then
Result:='-'
else
Result:=FindContextToString(FindContext^,RelativeFilename);
end;
function CreateFindContext(NewTool: TFindDeclarationTool;
NewNode: TCodeTreeNode): TFindContext;
begin
Result.Node:=NewNode;
Result.Tool:=NewTool;
end;
function CreateFindContext(Params: TFindDeclarationParams): TFindContext;
begin
Result.Node:=Params.NewNode;
Result.Tool:=TFindDeclarationTool(Params.NewCodeTool);
end;
function CreateFindContext(BaseTypeCache: TBaseTypeCache): TFindContext;
begin
Result.Node:=BaseTypeCache.BaseNode;
Result.Tool:=TFindDeclarationTool(BaseTypeCache.BaseTool);
end;
function FindContextAreEqual(const Context1, Context2: TFindContext): boolean;
begin
Result:=(Context1.Tool=Context2.Tool) and (Context1.Node=Context2.Node);
end;
function CompareFindContexts(const Context1, Context2: PFindContext): integer;
begin
if Pointer(Context1^.Tool)>Pointer(Context2^.Tool) then
Result:=1
else if Pointer(Context1^.Tool)<Pointer(Context2^.Tool) then
Result:=-1
else if Pointer(Context1^.Node)>Pointer(Context2^.Node) then
Result:=1
else if Pointer(Context1^.Node)<Pointer(Context2^.Node) then
Result:=-1
else
Result:=0;
end;
procedure AddFindContext(var ListOfPFindContext: TFPList;
const NewContext: TFindContext);
var
AddContext: PFindContext;
begin
if ListOfPFindContext=nil then ListOfPFindContext:=TFPList.Create;
New(AddContext);
AddContext^:=NewContext;
ListOfPFindContext.Add(AddContext);
end;
function IndexOfFindContext(var ListOfPFindContext: TFPList;
const AContext: PFindContext): integer;
begin
if ListOfPFindContext=nil then
Result:=-1
else begin
Result:=ListOfPFindContext.Count-1;
while (Result>=0)
and (CompareFindContexts(AContext,
PFindContext(ListOfPFindContext[Result]))<>0)
do
dec(Result);
end;
end;
procedure FreeListOfPFindContext(var ListOfPFindContext: TFPList);
var
CurContext: PFindContext;
i: Integer;
begin
if ListOfPFindContext=nil then exit;
for i:=0 to ListOfPFindContext.Count-1 do begin
CurContext:=PFindContext(ListOfPFindContext[i]);
Dispose(CurContext);
end;
ListOfPFindContext.Free;
ListOfPFindContext:=nil;
end;
{ TFindIdentifierInUsesSection_FindMissingFPCUnit }
constructor TFindIdentifierInUsesSection_FindMissingFPCUnit.Create;
begin
inherited;
FResults := TStringList.Create;
FResults.CaseSensitive := True;
FResults.Duplicates := dupIgnore;
FResults.Sorted := True;
end;
destructor TFindIdentifierInUsesSection_FindMissingFPCUnit.Destroy;
begin
FResults.Free;
inherited Destroy;
end;
function TFindIdentifierInUsesSection_FindMissingFPCUnit.Find(
const AUnitName: string; const ADirectoryCache: TCTDirectoryCache): Boolean;
var
IRes: Integer;
begin
IRes := FResults.IndexOf(AUnitName);
if IRes>=0 then
Exit(Boolean(PtrInt(FResults.Objects[IRes])));
FUnitName := AUnitName;
ADirectoryCache.IterateFPCUnitsInSet(@Iterate);
Result := FFound;
FResults.AddObject(AUnitName, TObject(PtrInt(Result)));
end;
function TFindIdentifierInUsesSection_FindMissingFPCUnit.IsInResults(
const AUnitName: string): Boolean;
begin
Result := FResults.IndexOf(AUnitName)>=0;
end;
procedure TFindIdentifierInUsesSection_FindMissingFPCUnit.Iterate(
const AFilename: string);
begin
FFound := FFound or SameFileName(FUnitName, ExtractFileNameOnly(AFilename));
end;
{ TTypeAliasOrderList }
constructor TTypeAliasOrderList.Create(const AliasNames: array of string);
begin
inherited Create;
FTree := TAVLTree.Create(@CompareTypeAliasItems);
Add(AliasNames);
end;
procedure TTypeAliasOrderList.Add(const AliasNames: array of string);
var
AliasName: string;
begin
for AliasName in AliasNames do
Add(AliasName);
end;
procedure TTypeAliasOrderList.Add(const AliasName: string);
var
NewItem: TTypeAliasItem;
begin
if IndexOf(AliasName) > -1 then Exit;
NewItem := TTypeAliasItem.Create;
NewItem.AliasName := AliasName;
NewItem.Position := FTree.Count;
FTree.Add(NewItem);
end;
function TTypeAliasOrderList.Compare(const AliasName1, AliasName2: string
): Integer;
var
xAliasIndex1, xAliasIndex2: Integer;
begin
xAliasIndex1 := IndexOf(AliasName1);
xAliasIndex2 := IndexOf(AliasName2);
if (xAliasIndex1=-1) and (xAliasIndex2=-1) then
Exit(0)
else if (xAliasIndex2=-1) then
Exit(-1)
else if (xAliasIndex1=-1) then
Exit(1)
else
Result := xAliasIndex1-xAliasIndex2;
end;
function TTypeAliasOrderList.Compare(const Operand1,
Operand2: TOperand; Tool: TFindDeclarationTool; CleanPos: Integer
): TOperand;
var
xCompRes: Integer;
begin
// first check if one of the operands is a constant -> if yes, automatically
// return the other
// (x := f + 1; should return always type of f)
if (Operand1.Expr.Desc in xtAllConstTypes) and not (Operand2.Expr.Desc in xtAllConstTypes) then
Exit(Operand2)
else
if (Operand2.Expr.Desc in xtAllConstTypes) and not (Operand1.Expr.Desc in xtAllConstTypes) then
Exit(Operand1);
// then compare base types
xCompRes := Compare(
Tool.FindExprTypeAsString(Operand1.Expr, CleanPos, nil),
Tool.FindExprTypeAsString(Operand2.Expr, CleanPos, nil));
// if base types are same, compare aliases
if xCompRes = 0 then
xCompRes := Compare(
Tool.FindExprTypeAsString(Operand1.Expr, CleanPos, @Operand1.AliasType),
Tool.FindExprTypeAsString(Operand2.Expr, CleanPos, @Operand2.AliasType));
if xCompRes > 0 then
Result := Operand2
else
Result := Operand1;
end;
procedure TTypeAliasOrderList.Delete(const Pos: Integer);
var
xAVItem, xDelItem: TAVLTreeNode;
xItem: TTypeAliasItem;
begin
xDelItem := nil;
for xAVItem in FTree do
begin
xItem := TTypeAliasItem(xAVItem.Data);
if xItem.Position = Pos then
xDelItem := xAVItem
else if xItem.Position > Pos then
Dec(xItem.Position);
end;
if xDelItem<>nil then
FTree.FreeAndDelete(xDelItem);
end;
procedure TTypeAliasOrderList.Delete(const AliasName: string);
var
xIndex: Integer;
begin
xIndex := IndexOf(AliasName);
if xIndex<0 then Exit;
Delete(xIndex);
end;
destructor TTypeAliasOrderList.Destroy;
begin
FTree.FreeAndClear;
FTree.Free;
inherited Destroy;
end;
function TTypeAliasOrderList.IndexOf(const AliasName: string): Integer;
var
xAVNode: TAVLTreeNode;
begin
xAVNode := FTree.FindKey(PChar(AliasName), @CompareTypeAliasItemString);
if xAVNode<>nil then
Result := TTypeAliasItem(xAVNode.Data).Position
else
Result := -1;
end;
procedure TTypeAliasOrderList.Insert(const AliasName: string; const Pos: Integer
);
var
xAVItem: TAVLTreeNode;
xItem, NewItem: TTypeAliasItem;
begin
for xAVItem in FTree do
begin
xItem := TTypeAliasItem(xAVItem.Data);
if xItem.Position >= Pos then
Inc(xItem.Position);
end;
NewItem := TTypeAliasItem.Create;
NewItem.AliasName := AliasName;
NewItem.Position := Pos;
FTree.Add(NewItem);
end;
procedure TTypeAliasOrderList.InsertAfter(const AliasName, AfterAlias: string);
var
xIndex: Integer;
begin
if IndexOf(AliasName) = -1 then
begin
xIndex := IndexOf(AfterAlias);
if xIndex >= 0 then
Insert(AliasName, xIndex+1)
else
Add(AliasName);
end;
end;
procedure TTypeAliasOrderList.InsertBefore(const AliasName, BeforeAlias: string
);
var
xIndex: Integer;
begin
if IndexOf(AliasName) = -1 then
begin
xIndex := IndexOf(BeforeAlias);
if xIndex >= 0 then
Insert(AliasName, xIndex)
else
Add(AliasName);
end;
end;
{ TFDHelpersListItem }
function TFDHelpersListItem.CalcMemSize: PtrUInt;
begin
Result := InstanceSize;
end;
{ TFDHelpersList }
function CompareHelpersList(Item1, Item2: Pointer): Integer;
var
I1: TFDHelpersListItem absolute Item1;
I2: TFDHelpersListItem absolute Item2;
begin
Result := ord(I1.ForExprType.Desc)-ord(I2.ForExprType.Desc);
if Result<>0 then exit;
Result := ComparePointers(I1.ForExprType.Context.Node, I2.ForExprType.Context.Node);
end;
function CompareHelpersListExprType(Item1, Item2: Pointer): Integer;
var
I1: PExpressionType absolute Item1;
I2: TFDHelpersListItem absolute Item2;
begin
Result := ord(I1^.Desc)-ord(I2.ForExprType.Desc);
if Result<>0 then exit;
Result := ComparePointers(I1^.Context.Node, I2.ForExprType.Context.Node);
end;
procedure TFDHelpersList.AddFromList(const ExtList: TFDHelpersList);
function CopyNode(ANode: TAVLTreeNode): TFDHelpersListItem;
var
FromNode: TFDHelpersListItem;
begin
FromNode := TFDHelpersListItem(ANode.Data);
if Kind=fdhlkDelphiHelper then
if FTree.FindKey(FromNode, @CompareHelpersList) <> nil then
Exit(nil); //FPC & Delphi don't support duplicate class helpers!
Result := TFDHelpersListItem.Create;
Result.HelperContext := FromNode.HelperContext;
Result.ForExprType := FromNode.ForExprType;
AddChronologically(Result);
end;
var
Node: TAVLTreeNode;
begin
for Node in ExtList.FTree do
CopyNode(Node);
end;
function TFDHelpersList.CalcMemSize: PtrUInt;
var
Node: TAVLTreeNode;
begin
Result:=PtrUInt(InstanceSize)+PtrUInt(FTree.InstanceSize);
for Node in FTree do
Inc(Result, TFDHelpersListItem(Node.Data).CalcMemSize);
end;
procedure TFDHelpersList.WriteDebugReport;
var
Node: TAVLTreeNode;
Item: TFDHelpersListItem;
begin
debugln(['TFDHelpersList.WriteDebugReport ',dbgs(Kind),' Count=',FTree.Count]);
Node:=FTree.FindLowest;
while Node<>nil do begin
Item:=TFDHelpersListItem(Node.Data);
debugln([' ForExprType=[',ExprTypeToString(Item.ForExprType),']',
' Helper=[',FindContextToString(Item.HelperContext),']']);
Node:=FTree.FindSuccessor(Node);
end;
end;
procedure TFDHelpersList.AddChronologically(Item: TFDHelpersListItem);
begin
with Item.ForExprType.Context do begin
// Note: ObjCCategory allows multiple helpers for a class (here: ForExprType)
// => there can be multiple items with the same key in the tree which
// must be chronologically sorted
// -> append the new item rightmost by slightly increasing the key
Node:=TCodeTreeNode(Pointer(Node)-SizeOf(Pointer));
FTree.Add(Item);
Node:=TCodeTreeNode(Pointer(Node)+SizeOf(Pointer));
end;
end;
function TFDHelpersList.AddFromHelperNode(HelperNode: TCodeTreeNode;
Tool: TFindDeclarationTool; Replace: Boolean): TFDHelpersListItem;
var
OldKey: TAVLTreeNode;
ExprType: TExpressionType;
begin
//debugln(['TFDHelpersList.AddFromHelperNode Start ',Tool.CleanPosToStr(HelperNode.StartPos,true),' ',Tool.ExtractCode(HelperNode.StartPos,HelperNode.StartPos+20,[])]);
ExprType:=Tool.FindExtendedExprOfHelper(HelperNode);
//debugln(['TFDHelpersList.AddFromHelperNode ExprType=',ExprTypeToString(ExprType)]);
if ExprType.Desc in xtAllIdentTypes then
begin
if Kind=fdhlkDelphiHelper then begin
// class/type/record helpers only allow one helper per class
OldKey := FTree.FindKey(@ExprType, @CompareHelpersListExprType);
if OldKey <> nil then
begin
Result:=TFDHelpersListItem(OldKey.Data);
if Replace then begin
// keep AVLNode, it may be in use by the iterator of SearchInHelpers
Result.HelperContext.Node := HelperNode;
Result.HelperContext.Tool := Tool;
end;
exit;
end;
end;
Result := TFDHelpersListItem.Create;
Result.ForExprType := ExprType;
Result.HelperContext.Node := HelperNode;
Result.HelperContext.Tool := Tool;
AddChronologically(Result);
end else
Result := nil;
end;
procedure TFDHelpersList.Clear;
begin
FTree.FreeAndClear;
end;
function TFDHelpersList.Count: Integer;
begin
Result := FTree.Count;
end;
constructor TFDHelpersList.Create(aKind: TFDHelpersListKind);
begin
inherited Create;
FKind:=aKind;
FTree:=TAVLTree.Create(@CompareHelpersList);
end;
procedure TFDHelpersList.DeleteHelperNode(HelperNode: TCodeTreeNode;
Tool: TFindDeclarationTool);
var
OldKey: TAVLTreeNode;
ExprType: TExpressionType;
begin
ExprType:=Tool.FindExtendedExprOfHelper(HelperNode);
if ExprType.Desc in xtAllIdentTypes then
begin
OldKey := FTree.FindKey(@ExprType, @CompareHelpersListExprType);
if OldKey <> nil then
FTree.FreeAndDelete(OldKey);
end;
end;
destructor TFDHelpersList.Destroy;
begin
Clear;
FTree.Free;
inherited Destroy;
end;
function TFDHelpersList.IterateFromClassNode(ClassNode: TCodeTreeNode;
Tool: TFindDeclarationTool; out HelperContext: TFindContext; out
Iterator: TAVLTreeNode): boolean;
var
ExprType: TExpressionType;
begin
ExprType.Desc:=xtContext;
ExprType.Context.Node:=ClassNode;
ExprType.Context.Tool:=Tool;
Iterator := FTree.FindRightMostKey(@ExprType, @CompareHelpersListExprType);
if Iterator=nil then exit(false);
HelperContext:=TFDHelpersListItem(Iterator.Data).HelperContext;
Result:=true;
end;
function TFDHelpersList.GetNext(out HelperContext: TFindContext;
var Iterator: TAVLTreeNode): boolean;
var
NextNode: TAVLTreeNode;
begin
NextNode:=FTree.FindPrecessor(Iterator);
if (NextNode=nil) or (CompareHelpersList(NextNode.Data,Iterator.Data)<>0) then
exit(false);
// found an older compatible helper
Iterator:=NextNode;
HelperContext:=TFDHelpersListItem(Iterator.Data).HelperContext;
Result:=true;
end;
function TFDHelpersList.FindFromExprType(const ExprType: TExpressionType
): TFindContext;
var
Node: TAVLTreeNode;
begin
Node := FTree.FindRightMostKey(@ExprType, @CompareHelpersListExprType);
if Node<>nil then
Result := TFDHelpersListItem(Node.Data).HelperContext
else
Result := CleanFindContext;
end;
constructor TFindUsedUnitReferences.Create(Tool: TFindDeclarationTool; AContextNode: TCodeTreeNode);
begin
inherited Create;
Params:=TFindDeclarationParams.Create(Tool, AContextNode);
end;
destructor TFindUsedUnitReferences.Destroy;
begin
FreeAndNil(Params);
inherited Destroy;
end;
{ TFindDeclarationTool }
function TFindDeclarationTool.FindDeclaration(const CursorPos: TCodeXYPosition;
out NewPos: TCodeXYPosition; out NewTopLine: integer): boolean;
var
NewTool: TFindDeclarationTool;
NewNode: TCodeTreeNode;
begin
Result:=FindDeclaration(CursorPos,DefaultFindSmartFlags,NewTool,NewNode,
NewPos,NewTopLine);
end;
function TFindDeclarationTool.FindMainDeclaration(
const CursorPos: TCodeXYPosition; out NewPos: TCodeXYPosition; out
NewTopLine: integer): boolean;
var
NewTool: TFindDeclarationTool;
NewNode: TCodeTreeNode;
begin
Result:=FindDeclaration(CursorPos,[fsfFindMainDeclaration],NewTool,NewNode,
NewPos,NewTopLine);
end;
function TFindDeclarationTool.FindDeclarationOfIdentifier(
const CursorPos: TCodeXYPosition; Identifier: PChar;
out NewPos: TCodeXYPosition; out NewTopLine: integer): boolean;
var
CleanCursorPos: integer;
CursorNode: TCodeTreeNode;
Params: TFindDeclarationParams;
begin
Result:=false;
ActivateGlobalWriteLock;
Params:=nil;
try
// build code tree
{$IFDEF CTDEBUG}
DebugLn('TFindDeclarationTool.FindDeclarationOfIdentifier A CursorPos=X',dbgs(CursorPos.X),',Y',dbgs(CursorPos.Y));
{$ENDIF}
BuildTreeAndGetCleanPos(trTillCursor,lsrEnd,CursorPos,CleanCursorPos,
[btSetIgnoreErrorPos]);
{$IFDEF CTDEBUG}
DebugLn('TFindDeclarationTool.FindDeclarationOfIdentifier B CleanCursorPos=',dbgs(CleanCursorPos));
{$ENDIF}
// find CodeTreeNode at cursor
CursorNode:=BuildSubTreeAndFindDeepestNodeAtPos(CleanCursorPos,true);
// search
Params:=TFindDeclarationParams.Create(Self, CursorNode);
Params.SetIdentifier(Self,Identifier,nil);
Params.Flags:=[fdfSearchInParentNodes,fdfExceptionOnNotFound,
fdfExceptionOnPredefinedIdent,
fdfTopLvlResolving,fdfSearchInAncestors,fdfSearchInHelpers,
fdfIgnoreCurContextNode];
FindIdentifierInContext(Params);
// convert result to nice source position
Params.PrettifyResult;
Params.ConvertResultCleanPosToCaretPos;
NewPos:=Params.NewPos;
NewTopLine:=Params.NewTopLine;
Result:=true;
finally
Params.Free;
DeactivateGlobalWriteLock;
end;
end;
function TFindDeclarationTool.FindDeclaration(const CursorPos: TCodeXYPosition;
SearchSmartFlags: TFindSmartFlags; out NewExprType: TExpressionType; out
NewPos: TCodeXYPosition; out NewTopLine, BlockTopLine,
BlockBottomLine: integer): boolean;
var
CleanCursorPos: integer;
CursorNode, ClassNode: TCodeTreeNode;
DirectSearch, SkipChecks, SearchForward: boolean;
function CheckIfNodeIsForwardDefinedClass(ANode: TCodeTreeNode;
ATool: TFindDeclarationTool): Boolean;
var
TypeNode: TCodeTreeNode;
begin
Result := False;
if not (ANode.Desc in [ctnTypeDefinition,ctnGenericType]) then exit;
TypeNode:=ATool.FindTypeNodeOfDefinition(ANode);
if (TypeNode<>nil)
and (TypeNode.Desc in AllClasses)
and ((TypeNode.SubDesc and ctnsForwardDeclaration)>0)
then
Result := True;
end;
procedure CheckIfCursorOnAForwardDefinedClass;
begin
if SkipChecks then exit;
if CheckIfNodeIsForwardDefinedClass(CursorNode, Self) then
begin
DirectSearch:=true;
SearchForward:=true;
SkipChecks:=true;
end;
end;
procedure CheckIfCursorInClassNode;
begin
if SkipChecks then exit;
ClassNode:=CursorNode;
while (ClassNode<>nil)
and (not (ClassNode.Desc in AllClasses))
do
ClassNode:=ClassNode.Parent;
if ClassNode=nil then exit;
// cursor is in class/object/class interface definition
if (ClassNode.SubDesc and ctnsForwardDeclaration)>0 then exit;
// parse class and build CodeTreeNodes for all properties/methods
CursorNode:=FindDeepestNodeAtPos(ClassNode,CleanCursorPos,true);
if CursorNode.GetNodeOfType(ctnClassInheritance)=nil then exit;
// identifier is an ancestor/interface identifier
CursorNode:=ClassNode.Parent;
DirectSearch:=true;
SkipChecks:=true;
end;
procedure CheckIfCursorInProcNode;
var IsMethod: boolean;
begin
if SkipChecks then exit;
if CursorNode.Desc=ctnProcedureHead then
CursorNode:=CursorNode.Parent;
if CursorNode.Desc<>ctnProcedure then exit;
BuildSubTreeForProcHead(CursorNode);
CursorNode:=FindDeepestNodeAtPos(CursorNode,CleanCursorPos,true);
// check if cursor on proc name
if (CursorNode.Desc=ctnProcedureHead)
and (CleanCursorPos>=CursorNode.StartPos) then begin
MoveCursorToNodeStart(CursorNode);
ReadNextAtom;
IsMethod:=false;
if AtomIsIdentifier then begin
ReadNextAtom;
if AtomIsChar('.') then begin
ReadNextAtom;
ReadNextAtom;
IsMethod:=true;
end;
end;
if (CurPos.StartPos>CleanCursorPos) and (not IsMethod) then begin
// cursor on proc name
// -> ignore proc name and search overloaded identifier
DirectSearch:=true;
SkipChecks:=true;
end;
end;
if CursorNode.Desc=ctnProcedureHead then
CursorNode:=CursorNode.Parent;
end;
procedure CheckIfCursorInPropertyNode;
begin
if SkipChecks then exit;
if not (CursorNode.Desc in [ctnProperty,ctnGlobalProperty]) then exit;
MoveCursorToNodeStart(CursorNode);
if (CursorNode.Desc=ctnProperty) then begin
ReadNextAtom; // read 'property'
if UpAtomIs('CLASS') then ReadNextAtom;
end;
ReadNextAtom; // read property name
if CleanCursorPos<CurPos.EndPos then begin
DirectSearch:=true;
SkipChecks:=true;
end;
end;
function FindSourceName(ACode: TCodeBuffer): boolean;
var
NamePos: TAtomPosition;
begin
Result:=false;
NewExprType :=CleanExpressionType;
if Assigned(FOnGetCodeToolForBuffer) then
NewExprType.Context.Tool:=FOnGetCodeToolForBuffer(Self,ACode,false);
if NewExprType.Context.Tool=nil then exit;
NewExprType.Context.Tool.BuildTree(lsrSourceName);
if not NewExprType.Context.Tool.GetSourceNamePos(NamePos) then exit;
NewExprType.Context.Node:=NewExprType.Context.Tool.Tree.Root;
if not NewExprType.Context.Tool.JumpToCleanPos(NamePos.StartPos,NamePos.StartPos,
NamePos.StartPos,NewPos,NewTopLine,BlockTopLine,BlockBottomLine,false)
then exit;
Result:=true;
NewExprType.Desc:=xtContext;
end;
{$IFDEF VerboseFindDeclarationFail}
procedure WriteFailReport;
var
CodePos: integer;
LinkIndex: Integer;
Link: TSourceLink;
i: Integer;
SrcCodes: TAVLTree;
SrcNode: TAVLTreeNode;
begin
debugln(['TFindDeclarationTool.FindDeclaration failed',
' CursorPos=X=',CursorPos.X,',Y=',CursorPos.Y,
',File=',CursorPos.Code.Filename,
',LineCount=',CursorPos.Code.LineCount]);
if CursorPos.Y<=CursorPos.Code.LineCount then
debugln([' Line="',dbgstr(CursorPos.Code.GetLine(CursorPos.Y-1),1,CursorPos.X-1),'|',dbgstr(CursorPos.Code.GetLine(CursorPos.Y-1),CursorPos.X,1000),'"']);
if CleanCursorPos>0 then begin
debugln([ ' CleanCursorPos=',CleanCursorPos,' CleanCode="',dbgstr(Src,CleanCursorPos-40,40),'|',dbgstr(Src,CleanCursorPos,30),'"']);
end;
CursorPos.Code.LineColToPosition(CursorPos.Y,CursorPos.X,CodePos);
LinkIndex:=Scanner.LinkIndexAtCursorPos(CodePos,CursorPos.Code);
dbgout([' CodePos=',CodePos,' LinkIndex=',LinkIndex]);
if LinkIndex>=0 then begin
Link:=Scanner.Links[LinkIndex];
dbgout([',CleanedPos=',Link.CleanedPos,',Size=',Scanner.LinkSize(LinkIndex),',SrcPos=',Link.SrcPos,',Kind=',dbgs(Link.Kind),',CodeSame=',Link.Code=Pointer(CursorPos.Code)]);
end else begin
dbgout([' LinkCount=',Scanner.LinkCount]);
i:=0;
while (i<Scanner.LinkCount-1) do begin
Link:=Scanner.Links[i];
if Link.Code=Pointer(CursorPos.Code) then begin
if LinkIndex<0 then
dbgout([', First Link of Code: ID=',i,',CleanedPos=',Link.CleanedPos,',Size=',Scanner.LinkSize(i),',SrcPos=',Link.SrcPos,',Kind=',dbgs(Link.Kind)]);
LinkIndex:=i;
end;
inc(i);
end;
if LinkIndex>=0 then begin
Link:=Scanner.Links[LinkIndex];
dbgout([', Last Link of Code: ID=',LinkIndex,',CleanedPos=',Link.CleanedPos,',Size=',Scanner.LinkSize(i),',SrcPos=',Link.SrcPos,',Kind=',dbgs(Link.Kind)]);
end else begin
SrcCodes:=Scanner.CreateTreeOfSourceCodes;
try
for SrcNode in SrcCodes do begin
dbgout(',LinkFile="',TCodeBuffer(SrcNode.Data).Filename,'"');
end;
finally
SrcCodes.Free;
end;
end;
end;
debugln;
end;
{$ENDIF}
var
IdentStartPos: Integer;
function TrySkipClassForward(Params: TFindDeclarationParams): Boolean;
var
ForwardXY, NewSkipPos: TCodeXYPosition;
NewSkipExprType: TExpressionType;
NewSkipTopLine, NewSkipCleanPos, NewSkipBlockTopLine,
NewSkipBlockBottomLine: integer;
begin
// if we skip forward class definitions and we found one -> proceed search!
Result :=
(fsfSkipClassForward in SearchSmartFlags)
and CheckIfNodeIsForwardDefinedClass(Params.NewNode, Params.NewCodeTool)
and Params.NewCodeTool.CleanPosToCaret(Params.NewNode.StartPos, ForwardXY)
and Params.NewCodeTool.FindDeclaration(ForwardXY, SearchSmartFlags-[fsfSkipClassForward],
NewSkipExprType, NewSkipPos, NewSkipTopLine, NewSkipBlockTopLine, NewSkipBlockBottomLine);
if Result
and (NewSkipExprType.Desc=xtContext)
and (NewSkipExprType.Context.Tool=Self)
and (NewSkipExprType.Context.Tool.CaretToCleanPos(NewSkipPos, NewSkipCleanPos)=0)
and (IdentStartPos = GetIdentStartPosition(Src,NewSkipCleanPos))
then begin
// the old startpos and the skipclass startpos are the same -> we want to
// jump to the forward declaration because we jump from the actual one
Result := False;
end;
if Result then
begin
NewExprType := NewSkipExprType;
NewPos := NewSkipPos;
NewTopLine := NewSkipTopLine;
BlockTopLine := NewSkipBlockTopLine;
BlockBottomLine := NewSkipBlockBottomLine;
end;
end;
var
CleanPosInFront: integer;
CursorAtIdentifier: boolean;
IdentifierStart: PChar;
LineRange: TLineRange;
Params: TFindDeclarationParams;
begin
Result:=false;
NewExprType:=CleanExpressionType;
NewPos.X:=-1;
NewPos.Y:=-1;
SkipChecks:=false;
// check cursor in source
if (CursorPos.Y<1) or (CursorPos.Y>CursorPos.Code.LineCount)
or (CursorPos.X<1) then begin
{$IFDEF VerboseFindDeclarationFail}
debugln(['TFindDeclarationTool.FindDeclaration invalid CursorPos=X=',CursorPos.X,' Y=',CursorPos.Y,' File=',CursorPos.Code.Filename,' LineCount=',CursorPos.Code.LineCount]);
{$ENDIF}
exit;
end;
CursorPos.Code.GetLineRange(CursorPos.Y-1,LineRange);
if LineRange.EndPos-LineRange.StartPos+1<CursorPos.X then begin
// beyond end of line
{$IFDEF VerboseFindDeclarationFail}
debugln(['TFindDeclarationTool.FindDeclaration beyond end of line: CursorPos=X=',CursorPos.X,' Y=',CursorPos.Y,' File=',CursorPos.Code.Filename,' LineLen=',LineRange.EndPos-LineRange.StartPos]);
{$ENDIF}
exit;
end;
CleanCursorPos:=0;
ActivateGlobalWriteLock;
try
// build code tree
{$IFDEF CTDEBUG}
DebugLn('TFindDeclarationTool.FindDeclaration A CursorPos=X',dbgs(CursorPos.X),',Y',dbgs(CursorPos.Y),' ',CursorPos.Code.Filename);
debugln(['TFindDeclarationTool.FindDeclaration B ',dbgtext(copy(CursorPos.Code.GetLine(CursorPos.Y),1,CursorPos.X-1)),'|',dbgtext(copy(CursorPos.Code.GetLine(CursorPos.Y),CursorPos.X,120))]);
{$ENDIF}
BuildTreeAndGetCleanPos(trTillCursor,lsrEnd,CursorPos,CleanCursorPos,
[btSetIgnoreErrorPos,btCursorPosOutAllowed]);
{$IFDEF CTDEBUG}
debugLn('TFindDeclarationTool.FindDeclaration B CleanCursorPos=',dbgs(CleanCursorPos));
debugln(['TFindDeclarationTool.FindDeclaration C ',dbgtext(copy(Src,CleanCursorPos-30,30)),'|',dbgtext(copy(Src,CleanCursorPos,30))]);
{$ENDIF}
// find CodeTreeNode at cursor
if (Tree.Root<>nil) and (Tree.Root.StartPos<=CleanCursorPos) then begin
CursorNode:=BuildSubTreeAndFindDeepestNodeAtPos(CleanCursorPos,true);
if (fsfFindMainDeclaration in SearchSmartFlags)
and CleanPosIsDeclarationIdentifier(CleanCursorPos,CursorNode)
then begin
//DebugLn(['TFindDeclarationTool.FindDeclaration CleanPosIsDeclarationIdentifier']);
NewExprType.Desc:=xtContext;
NewExprType.Context.Tool:=Self;
NewExprType.Context.Node:=CursorNode;
CleanCursorPos:=GetIdentStartPosition(Src,CleanCursorPos);
if CursorNode.Desc=ctnVarDefinition then begin
// if this is a parameter, try to find the corresponding declaration
NewExprType.Context.Node:=FindCorrespondingProcParamNode(NewExprType.Context.Node);
if (NewExprType.Context.Node<>nil) and (NewExprType.Context.Node.StartPos<CursorNode.StartPos) then
CleanCursorPos:=NewExprType.Context.Node.StartPos
else
NewExprType.Context.Node:=CursorNode;
end;
if (CursorNode.Desc=ctnProcedureHead)
and (NodeIsMethodBody(CursorNode.Parent)) then begin
// if this is a procedure body, try to find the corresponding declaration
NewExprType.Context.Node:=FindCorrespondingProcNode(CursorNode.Parent);
if (NewExprType.Context.Node<>nil) and (NewExprType.Context.Node.Desc=ctnProcedure) then
NewExprType.Context.Node:=NewExprType.Context.Node.FirstChild;
if (NewExprType.Context.Node<>nil) and (NewExprType.Context.Node.StartPos<CursorNode.StartPos) then begin
CleanCursorPos:=NewExprType.Context.Node.StartPos;
end
else
NewExprType.Context.Node:=CursorNode;
end;
Result:=JumpToCleanPos(CleanCursorPos,CleanCursorPos,CleanCursorPos,
NewPos,NewTopLine,BlockTopLine,BlockBottomLine,false);
{$IFDEF VerboseFindDeclarationFail}
if not Result then begin
debugln(['TFindDeclarationTool.FindDeclaration cursor at declaration, but JumpToCleanPos failed']);
end;
{$ENDIF}
exit;
end;
CleanPosInFront:=CursorNode.StartPos;
end else begin
CleanPosInFront:=1;
CursorNode:=nil;
end;
if IsIncludeDirectiveAtPos(CleanCursorPos,CleanPosInFront,NewPos.Code)
then begin
// include directive
//DebugLn(['TFindDeclarationTool.FindDeclaration IsIncludeDirectiveAtPos']);
NewPos.X:=1;
NewPos.Y:=1;
NewTopLine:=1;
BlockTopLine:=NewPos.Y;
BlockBottomLine:=NewPos.Y;
NewExprType.Desc:=xtContext;
NewExprType.Context.Node:=nil;
NewExprType.Context.Tool:=Self;
Result:=(fsfIncludeDirective in SearchSmartFlags);
{$IFDEF VerboseFindDeclarationFail}
if not Result then begin
debugln(['TFindDeclarationTool.FindDeclaration cursor at include directive and fsfIncludeDirective not set']);
end;
{$ENDIF}
exit;
end;
if CursorNode=nil then begin
// raise exception
RaiseCursorOutsideCode(CursorPos);
end;
{$IFDEF CTDEBUG}
DbgOut(['TFindDeclarationTool.FindDeclaration D CursorNode=',NodeDescriptionAsString(CursorNode.Desc),' HasChildren=',dbgs(CursorNode.FirstChild<>nil)]);
if CursorNode.Parent<>nil then
DbgOut(' Parent="',CursorNode.Parent.DescAsString,'"');
Debugln;
{$ENDIF}
if (CursorNode.Desc = ctnUseUnitNamespace) then begin
NewExprType.Desc:=xtContext;
NewExprType.Context.Node:=CursorNode;
NewExprType.Context.Tool:=Self;
CleanPosToCaret(CursorNode.StartPos, NewPos);
NewTopLine := NewPos.Y;
BlockTopLine := NewTopLine;
CleanPosToCaret(CursorNode.EndPos, NewPos);
BlockBottomLine := NewPos.Y;
Result := True;
Exit;
end else
if (CursorNode.Desc in [ctnUsesSection,ctnUseUnitClearName]) then begin
// in uses section
//DebugLn(['TFindDeclarationTool.FindDeclaration IsUsesSection']);
Result:=FindDeclarationInUsesSection(CursorNode,CleanCursorPos,
NewPos,NewTopLine);
BlockTopLine:=NewPos.Y;
BlockBottomLine:=NewPos.Y;
NewExprType:=CleanExpressionType;
{$IFDEF VerboseFindDeclarationFail}
if not Result then begin
debugln(['TFindDeclarationTool.FindDeclaration cursor in uses and FindDeclarationInUsesSection failed']);
end;
{$ENDIF}
if Result and (fsfSearchSourceName in SearchSmartFlags) then begin
Result:=FindSourceName(NewPos.Code);
{$IFDEF VerboseFindDeclarationFail}
if not Result then begin
debugln(['TFindDeclarationTool.FindDeclaration cursor in uses and FindSourceName failed']);
end;
{$ENDIF}
end;
exit;
end;
DirectSearch:=false;
SearchForward:=false;
CheckIfCursorOnAForwardDefinedClass;
CheckIfCursorInClassNode;
CheckIfCursorInProcNode;
CheckIfCursorInPropertyNode;
// set cursor on identifier
MoveCursorToCleanPos(CleanCursorPos);
GetIdentStartEndAtPosition(Src,CleanCursorPos,
CurPos.StartPos,CurPos.EndPos);
IdentStartPos:=CurPos.StartPos;
CursorAtIdentifier:=CurPos.StartPos<CurPos.EndPos;
if CursorAtIdentifier then
IdentifierStart:=@Src[CurPos.StartPos]
else
IdentifierStart:=PChar(Src);
if CursorAtIdentifier then begin
// find declaration of identifier
Params:=TFindDeclarationParams.Create(Self, CursorNode);
try
Params.SetIdentifier(Self,IdentifierStart,@CheckSrcIdentifier);
Params.Flags:=[fdfSearchInParentNodes,fdfExceptionOnNotFound,
fdfExceptionOnPredefinedIdent,
fdfTopLvlResolving,fdfSearchInAncestors,fdfSearchInHelpers];
if fsfSkipClassForward in SearchSmartFlags then
Include(Params.Flags,fdfSkipClassForward);
if not DirectSearch then begin
Result:=FindDeclarationOfIdentAtParam(Params, NewExprType);
{$IFDEF VerboseFindDeclarationFail}
if not Result then begin
debugln(['TFindDeclarationTool.FindDeclaration FindDeclarationOfIdentAtParam failed']);
end;
{$ENDIF}
if Result and TrySkipClassForward(Params) then
Exit(True);
end else begin
Include(Params.Flags,fdfIgnoreCurContextNode);
if SearchForward then
Include(Params.Flags,fdfSearchForward);
//debugln(['TFindDeclarationTool.FindDeclaration Flags=',dbgs(Params.Flags),' FindIdentifierInContext ...']);
Result:=FindIdentifierInContext(Params);
if Result then
begin
if TrySkipClassForward(Params) then
Exit(True);
NewExprType.Desc:=xtContext;
NewExprType.Context.Node:=Params.NewNode;
NewExprType.Context.Tool:=Params.NewCodeTool;
end;
{$IFDEF VerboseFindDeclarationFail}
if not Result then begin
debugln(['TFindDeclarationTool.FindDeclaration FindIdentifierInContext failed']);
end;
{$ENDIF}
end;
if Result then begin
Params.PrettifyResult;
Params.ConvertResultCleanPosToCaretPos;
NewPos:=Params.NewPos;
NewTopLine:=Params.NewTopLine;
BlockTopLine:=NewPos.Y;
BlockBottomLine:=NewPos.Y;
if (NewExprType.Desc=xtContext) and
((NewPos.Code=nil) or (NewExprType.Context.Node=nil))
then begin
if Params.IdentifierTool.IsPCharInSrc(Params.Identifier) then
Params.IdentifierTool.MoveCursorToCleanPos(Params.Identifier)
else
MoveCursorToCleanPos(CleanCursorPos);
Params.IdentifierTool.RaiseExceptionFmt(20170421200024,ctsIdentifierNotFound,
[GetIdentifier(Params.Identifier)]);
end;
end;
finally
Params.Free;
end;
end else begin
// find declaration of non identifier, e.g. numeric label
{$IFDEF VerboseFindDeclarationFail}
if not Result then begin
debugln(['TFindDeclarationTool.FindDeclaration cursor at non identifier']);
end;
{$ENDIF}
end;
finally
ClearIgnoreErrorAfter;
DeactivateGlobalWriteLock;
{$IFDEF VerboseFindDeclarationFail}
WriteFailReport;
{$ENDIF}
end;
end;
function TFindDeclarationTool.FindDeclaration(const CursorPos: TCodeXYPosition;
SearchSmartFlags: TFindSmartFlags; out NewExprType: TExpressionType; out
NewPos: TCodeXYPosition; out NewTopLine: integer): boolean;
var
BlockTopLine, BlockBottomLine: integer;
begin
Result := FindDeclaration(CursorPos, SearchSmartFlags, NewExprType, NewPos,
NewTopLine, BlockTopLine, BlockBottomLine);
end;
function TFindDeclarationTool.FindDeclaration(const CursorPos: TCodeXYPosition;
SearchSmartFlags: TFindSmartFlags; out NewTool: TFindDeclarationTool; out
NewNode: TCodeTreeNode; out NewPos: TCodeXYPosition; out NewTopLine,
BlockTopLine, BlockBottomLine: integer): boolean;
var
ExprType: TExpressionType;
begin
Result := FindDeclaration(CursorPos, SearchSmartFlags, ExprType, NewPos, NewTopLine, BlockTopLine, BlockBottomLine) and
(NewPos.X >= 0) and (NewPos.Y >= 0);
if Result then begin
NewTool := ExprType.Context.Tool;
NewNode := ExprType.Context.Node;
end else begin
NewTool := nil;
NewNode := nil;
end;
end;
function TFindDeclarationTool.FindDeclaration(const CursorPos: TCodeXYPosition;
SearchSmartFlags: TFindSmartFlags; out NewTool: TFindDeclarationTool; out
NewNode: TCodeTreeNode; out NewPos: TCodeXYPosition; out NewTopLine: integer
): boolean;
var
BlockTopLine, BlockBottomLine: integer;
begin
Result := FindDeclaration(CursorPos, SearchSmartFlags, NewTool, NewNode, NewPos,
NewTopLine, BlockTopLine, BlockBottomLine);
end;
function TFindDeclarationTool.FindDeclarationInInterface(
const Identifier: string; out NewPos: TCodeXYPosition; out NewTopLine,
BlockTopLine, BlockBottomLine: integer): boolean;
var
Node: TCodeTreeNode;
begin
Result:=false;
if Identifier='' then exit;
Node:=FindDeclarationNodeInInterface(Identifier,true);
if Node<>nil then
Result:=JumpToNode(Node,NewPos,NewTopLine,BlockTopLine,BlockBottomLine,false);
end;
function TFindDeclarationTool.FindDeclarationWithMainUsesSection(
const Identifier: string; out NewPos: TCodeXYPosition; out NewTopLine: integer
): boolean;
var
UsesNode: TCodeTreeNode;
Params: TFindDeclarationParams;
begin
Result:=false;
if Identifier='' then exit;
BuildTree(lsrMainUsesSectionEnd);
UsesNode:=FindMainUsesNode;
if UsesNode=nil then exit;
Params:=TFindDeclarationParams.Create(Self, FindLastNode);
ActivateGlobalWriteLock;
try
Params.Flags:=[fdfExceptionOnNotFound];
Params.SetIdentifier(Self,PChar(Pointer(Identifier)),nil);
if FindIdentifierInUsesSection(UsesNode,Params,True) then begin
if Params.NewNode=nil then exit;
Result:=Params.NewCodeTool.JumpToNode(Params.NewNode,NewPos,
NewTopLine,false);
end;
finally
Params.Free;
DeactivateGlobalWriteLock;
end;
end;
function TFindDeclarationTool.FindDeclarationOfPropertyPath(
const PropertyPath: string; out NewContext: TFindContext;
IgnoreTypeLess: boolean): boolean;
// example: PropertyPath='TForm1.Font.Color'
var
StartPos: Integer;
function GetNextIdentifier: string;
var
EndPos: LongInt;
begin
EndPos:=StartPos;
while (EndPos<=length(PropertyPath)) and (IsIdentChar[PropertyPath[EndPos]])
do inc(EndPos);
if (EndPos<=length(PropertyPath)) and (PropertyPath[EndPos]<>'.') then
Result:=''
else begin
Result:=copy(PropertyPath,StartPos,EndPos-StartPos);
StartPos:=EndPos+1;
end;
end;
var
Params: TFindDeclarationParams;
Identifier: String;
IsLastProperty: Boolean;
Context: TFindContext;
IsTypeLess: Boolean;
Node: TCodeTreeNode;
begin
Result:=false;
NewContext:=CleanFindContext;
//DebugLn('TFindDeclarationTool.FindDeclarationOfPropertyPath ',MainFilename,' PropertyPath="',PropertyPath,'"');
if PropertyPath='' then exit;
ActivateGlobalWriteLock;
Params:=TFindDeclarationParams.Create(Self, FindLastNode);
try
BuildTree(lsrInitializationStart);
//DebugLn(['TFindDeclarationTool.FindDeclarationOfPropertyPath ',Src]);
// first search the class/variable in the interface
StartPos:=1;
Identifier:=GetNextIdentifier;
if Identifier='' then exit;
Context.Tool:=Self;
Context.Node:=FindDeclarationNodeInInterface(Identifier,true);
if Context.Node=nil then begin
DebugLn(['TFindDeclarationTool.FindDeclarationOfPropertyPath Identifier not found in interface ',Identifier]);
exit;
end;
Context:=FindBaseTypeOfNode(Params,Context.Node);
if Context.Node=nil then begin
DebugLn(['TFindDeclarationTool.FindDeclarationOfPropertyPath context not found']);
exit;
end;
// then search the properties
repeat
Identifier:=GetNextIdentifier;
IsLastProperty:=StartPos>length(PropertyPath);
//DebugLn('TFindDeclarationTool.FindDeclarationOfPropertyPath Context=',Context.Node.DescAsString,' Identifier=',Identifier);
if Identifier='' then begin
NewContext:=Context;
exit(true);
end;
if Context.Node.Desc=ctnSetType then begin
// set
if not IsLastProperty then exit;
Node:=Context.Node.FirstChild;
if (Node=nil) or (Node.Desc<>ctnIdentifier) then exit;
// search enum type
Params.Flags:=[fdfExceptionOnNotFound,fdfSearchInParentNodes,fdfFindChildren];
Params.SetIdentifier(Self,@Context.Tool.Src[Node.StartPos],nil);
Params.ContextNode:=Node;
if not Context.Tool.FindIdentifierInContext(Params) then exit;
Context.Tool:=Params.NewCodeTool;
Context.Node:=Params.NewNode;
// search enum base type
Context:=Context.Tool.FindBaseTypeOfNode(Params,Context.Node);
//debugln(['TFindDeclarationTool.FindDeclarationOfPropertyPath enum base type ',FindContextToString(Context)]);
if (Context.Node=nil) or (Context.Node.Desc<>ctnEnumerationType) then
exit;
// search enum
Node:=Context.Node.FirstChild;
while Node<>nil do begin
if CompareIdentifiers(PChar(Pointer(Identifier)),@Context.Tool.Src[Node.StartPos])=0
then begin
//debugln(['TFindDeclarationTool.FindDeclarationOfPropertyPath identifier=',Identifier]);
NewContext.Tool:=Context.Tool;
NewContext.Node:=Node;
//debugln(['TFindDeclarationTool.FindDeclarationOfPropertyPath FOUND ',FindContextToString(NewContext)]);
exit(true);
end;
Node:=Node.NextBrother;
end;
exit;
end;
if (not (Context.Node.Desc in AllClasses)) then begin
debugln(['TFindDeclarationTool.FindDeclarationOfPropertyPath failed Context=',Context.Node.DescAsString]);
exit;
end;
//DebugLn('TFindDeclarationTool.FindDeclarationOfPropertyPath Identifier="',identifier,'"');
Params.Flags:=[fdfExceptionOnNotFound,fdfSearchInAncestors,fdfSearchInHelpers];
Params.SetIdentifier(Self,PChar(Pointer(Identifier)),nil);
Params.ContextNode:=Context.Node;
if IsLastProperty then
Params.Flags:=Params.Flags+[fdfFindVariable]
else
Params.Flags:=Params.Flags-[fdfFindVariable]+[fdfFunctionResult,fdfFindChildren];
if not Context.Tool.FindIdentifierInContext(Params) then exit;
Context.Tool:=Params.NewCodeTool;
Context.Node:=Params.NewNode;
if Context.Node=nil then exit;
if IsLastProperty then begin
if IgnoreTypeLess then begin
repeat
IsTypeLess:=false;
if (Context.Node.Desc=ctnProperty)
and Context.Tool.PropNodeIsTypeLess(Context.Node) then
IsTypeLess:=true;
if not IsTypeLess then break;
//DebugLn(['TFindDeclarationTool.FindDeclarationOfPropertyPath has no type, searching next ...']);
Params.SetIdentifier(Self,PChar(Pointer(Identifier)),nil);
Params.ContextNode:=Context.Tool.FindClassOrInterfaceNode(Context.Node);
if Params.ContextNode=nil then
Params.ContextNode:=Context.Node;
Params.Flags:=[fdfExceptionOnNotFound,fdfSearchInAncestors,fdfSearchInHelpers,
fdfFindVariable,fdfIgnoreCurContextNode];
//DebugLn(['TFindDeclarationTool.FindDeclarationOfPropertyPath ',Context.Tool.MainFilename,' ',Params.ContextNode.DescAsString,' ',Context.Tool.CleanPosToStr(Params.ContextNode.StartPos)]);
if not Context.Tool.FindIdentifierInContext(Params) then exit;
Context.Tool:=Params.NewCodeTool;
Context.Node:=Params.NewNode;
if Context.Node=nil then exit;
until false;
end;
//DebugLn(['TFindDeclarationTool.FindDeclarationOfPropertyPath FOUND']);
NewContext:=Context;
Result:=true;
exit;
end else begin
Context:=Context.Tool.FindBaseTypeOfNode(Params,Context.Node);
if Context.Node=nil then exit;
end;
until false;
finally
Params.Free;
DeactivateGlobalWriteLock;
end;
end;
function TFindDeclarationTool.FindDeclarationOfPropertyPath(
const PropertyPath: string;
out NewPos: TCodeXYPosition; out NewTopLine: integer;
IgnoreTypeLess: boolean): boolean;
var
Context: TFindContext;
begin
Result:=FindDeclarationOfPropertyPath(PropertyPath,Context,IgnoreTypeLess);
if not Result then exit;
Result:=Context.Tool.JumpToNode(Context.Node,NewPos,NewTopLine,false);
end;
function TFindDeclarationTool.FindDeclarationNodeInInterface(
const Identifier: string; BuildTheTree: Boolean): TCodeTreeNode;
var
CacheEntry: PInterfaceIdentCacheEntry;
begin
Result:=nil;
if Identifier='' then exit;
if BuildTheTree and (not BuildInterfaceIdentifierCache(true)) then
exit;
CacheEntry:=FInterfaceIdentifierCache.FindIdentifier(PChar(Identifier));
if CacheEntry=nil then exit;
Result:=CacheEntry^.Node;
end;
function TFindDeclarationTool.FindDeclarationNodeInImplementation(
Identifier: string; BuildTheTree: Boolean): TCodeTreeNode;
begin
Result:=nil;
if Identifier='' then exit;
if BuildTheTree then
BuildTree(lsrInitializationStart);
Result:=FindSubDeclaration(Identifier,FindImplementationNode);
end;
function TFindDeclarationTool.FindSubDeclaration(Identifier: string;
ParentNode: TCodeTreeNode): TCodeTreeNode;
var
LastNode: TCodeTreeNode;
begin
Result:=nil;
if ParentNode=nil then exit;
if Identifier='' then exit;
Identifier:=UpperCaseStr(Identifier);
LastNode:=ParentNode.NextSkipChilds;
Result:=ParentNode.Next;
while Result<>LastNode do begin
// ToDo: check enums
if Result.Desc in AllIdentifierDefinitions then begin
if CompareNodeIdentChars(Result,Identifier)=0 then
exit;
Result:=Result.NextSkipChilds;
end else if Result.Desc=ctnProcedure then begin
if CompareIdentifiers(PChar(ExtractProcName(Result,[])),PChar(Pointer(Identifier)))=0 then
exit;
Result:=Result.NextSkipChilds;
end else
Result:=Result.Next;
end;
Result:=nil;
end;
function TFindDeclarationTool.FindNameInUsesSection(UsesNode: TCodeTreeNode;
const AUnitName: string): TCodeTreeNode;
var
CurUnitName: string;
begin
Result:=UsesNode.FirstChild;
while (Result<>nil) do begin
CurUnitName:=ExtractUsedUnitName(Result);
if CompareDottedIdentifiers(PChar(CurUnitName),PChar(AUnitName))=0 then exit;
Result:=Result.NextBrother;
end;
end;
function TFindDeclarationTool.FindUnitInUsesSection(UsesNode: TCodeTreeNode;
const AnUnitName: string; out NamePos, InPos: TAtomPosition): boolean;
var
CurUnitName: String;
StartPos: Integer;
begin
Result:=false;
NamePos:=CleanAtomPosition;
InPos:=CleanAtomPosition;
if (UsesNode=nil) or (not IsDottedIdentifier(AnUnitName))
or (UsesNode.Desc<>ctnUsesSection) then begin
DebugLn(['TFindDeclarationTool.FindUnitInUsesSection invalid AnUnitName']);
exit;
end;
MoveCursorToNodeStart(UsesNode);
ReadNextAtom; // read 'uses'
repeat
ReadNextAtom; // read name
if CurPos.Flag=cafSemicolon then break;
if (CurPos.StartPos>SrcLen) then break;
StartPos:=CurPos.StartPos;
CurUnitName:=ExtractUsedUnitNameAtCursor;
if CompareDottedIdentifiers(PChar(CurUnitName),PChar(AnUnitName))=0 then
begin
MoveCursorToCleanPos(StartPos);
ReadNextAtom;
ReadNextUsedUnit(NamePos,InPos);
Result:=true;
exit;
end;
if CurPos.Flag=cafSemicolon then break;
if CurPos.Flag<>cafComma then break;
until (CurPos.StartPos>SrcLen);
end;
function TFindDeclarationTool.FindUnitInAllUsesSections(
const AnUnitName: string; out NamePos, InPos: TAtomPosition): boolean;
procedure RaiseInvalidUnitName;
begin
raise Exception.Create('invalid unit name '+AnUnitName);
end;
function FindInSection(UsesNode: TCodeTreeNode): boolean;
begin
Result:=(UsesNode<>nil)
and FindUnitInUsesSection(UsesNode,AnUnitName,NamePos,InPos);
end;
begin
Result:=false;
NamePos.StartPos:=-1;
InPos.StartPos:=-1;
if not IsDottedIdentifier(AnUnitName) then
RaiseInvalidUnitName;
BuildTree(lsrImplementationUsesSectionEnd);
if FindInSection(FindMainUsesNode) then exit;
if FindInSection(FindImplementationUsesNode) then exit;
end;
function TFindDeclarationTool.GetUnitNameForUsesSection(
TargetTool: TFindDeclarationTool): string;
// if unit is already used return ''
// else return nice name
var
UsesNode: TCodeTreeNode;
Alternative: String;
begin
Result:='';
if (TargetTool=nil) or (TargetTool.MainFilename='') or (TargetTool=Self) then
exit;
Result:=ExtractFileNameOnly(TargetTool.MainFilename);
if Result='' then exit;
// check if system unit
if IsHiddenUsedUnit(PChar(Result)) then begin
Result:='';
exit;
end;
// check if already there
UsesNode:=FindMainUsesNode;
if (UsesNode<>nil) and (FindNameInUsesSection(UsesNode,Result)<>nil)
then begin
Result:='';
exit;
end;
UsesNode:=FindImplementationUsesNode;
if (UsesNode<>nil) and (FindNameInUsesSection(UsesNode,Result)<>nil)
then begin
Result:='';
exit;
end;
// beautify
if Result=lowercase(Result) then begin
Alternative:=TargetTool.GetSourceName(false);
if Alternative<>'' then
Result:=Alternative;
end;
end;
function TFindDeclarationTool.IsHiddenUsedUnit(TheUnitName: PChar): boolean;
var
HiddenUnits: String;
p: PChar;
begin
if TheUnitName=nil then exit(false);
HiddenUnits:=Scanner.GetHiddenUsedUnits;
if HiddenUnits<>'' then begin
p:=PChar(HiddenUnits);
while p^<>#0 do begin
if CompareDottedIdentifiers(TheUnitName,p)=0 then
exit(true);
while not (p^ in [',',#0]) do inc(p);
while p^=',' do inc(p);
end;
end;
Result:=false;
end;
function TFindDeclarationTool.FindDeclarationInUsesSection(
UsesNode: TCodeTreeNode; CleanPos: integer;
out NewPos: TCodeXYPosition; out NewTopLine: integer): boolean;
var AUnitName, UnitInFilename: string;
UnitNamePos, UnitInFilePos: TAtomPosition;
begin
Result:=false;
{$IFDEF ShowTriedContexts}
DebugLn('TFindDeclarationTool.FindDeclarationInUsesSection A');
{$ENDIF}
{$IFDEF CheckNodeTool}CheckNodeTool(UsesNode);{$ENDIF}
// reparse uses section, ignore errors after CleanPos
MoveCursorToNodeStart(UsesNode);
if (UsesNode.Desc=ctnUsesSection) then begin
ReadNextAtom;
if not UpAtomIs('USES') then
RaiseUsesExpected(20170421200506);
end else
if (UsesNode.Desc = ctnUseUnitClearName) then
MoveCursorToNodeStart(UsesNode.Parent);
repeat
ReadNextAtom; // read name
if CurPos.StartPos>CleanPos then break;
if CurPos.Flag=cafSemicolon then break;
ReadNextUsedUnit(UnitNamePos,UnitInFilePos);
if CleanPos<=CurPos.StartPos then begin
// cursor is on an used unit -> try to locate it
MoveCursorToCleanPos(UnitNamePos.StartPos);
ReadNextAtom;
AUnitName:=ExtractUsedUnitNameAtCursor(@UnitInFilename);
NewPos.Code:=FindUnitSource(AUnitName,UnitInFilename,true,UnitNamePos.StartPos);
NewPos.X:=1;
NewPos.Y:=1;
NewTopLine:=1;
Result:=true;
exit;
end;
if CurPos.Flag=cafSemicolon then break;
if CurPos.Flag<>cafComma then
RaiseExceptionFmt(20170421200032,ctsStrExpectedButAtomFound,[';',GetAtom])
until (CurPos.StartPos>SrcLen);
{$IFDEF ShowTriedContexts}
DebugLn('TFindDeclarationTool.FindDeclarationInUsesSection END cursor not on AUnitName');
{$ENDIF}
end;
function TFindDeclarationTool.FindUnitFileInUsesSection(
UsesNode: TCodeTreeNode; const AFilename: string): TCodeTreeNode;
var
TargetLoUnitName: string;
TargetLoShortFilename: string;
function CheckUseNode(Node: TCodeTreeNode): boolean;
var
Code: TCodeBuffer;
UnitInFilename: string;
AUnitName: string;
begin
Result:=false;
MoveCursorToNodeStart(Node);
ReadNextAtom;
AUnitName:=ExtractUsedUnitNameAtCursor(@UnitInFilename);
if AUnitName='' then exit;
// quick check: compare unitname
if UnitInFilename<>'' then begin
if lowercase(ExtractFilename(UnitInFilename))<>TargetLoShortFilename then
exit;
end else if LowerCase(AUnitName)<>TargetLoUnitName then
exit;
// search in search paths
Code:=FindUnitSource(AUnitName,UnitInFilename,false,Node.StartPos);
Result:=(Code<>nil) and (CompareFilenames(Code.Filename,AFilename)=0);
end;
begin
Result:=nil;
if (UsesNode=nil) or (UsesNode.Desc<>ctnUsesSection) then exit;
TargetLoUnitName:=LowerCase(ExtractFileNameOnly(AFilename));
TargetLoShortFilename:=LowerCase(ExtractFileName(AFilename));
if TargetLoShortFilename='' then exit;
Result:=UsesNode.LastChild;
while Result<>nil do begin
if CheckUseNode(Result) then exit;
Result:=Result.PriorBrother;
end;
end;
function TFindDeclarationTool.FindUnitFileInAllUsesSections(
const AFilename: string; CheckMain: boolean; CheckImplementation: boolean
): TCodeTreeNode;
begin
Result:=nil;
//debugln(['TFindDeclarationTool.FindUnitFileInAllUsesSections Self=',ExtractFilename(MainFilename),' Search=',ExtractFilename(AFilename)]);
if AFilename='' then exit;
if CheckMain then begin
Result:=FindUnitFileInUsesSection(FindMainUsesNode,AFilename);
//debugln(['TFindDeclarationTool.FindUnitFileInAllUsesSections Self=',ExtractFilename(MainFilename),' Search=',ExtractFilename(AFilename),' used in main uses=',Result<>nil]);
if Result<>nil then exit;
end;
if CheckImplementation then
Result:=FindUnitFileInUsesSection(FindImplementationUsesNode,AFilename);
end;
function TFindDeclarationTool.FindUnitSource(const AnUnitName,
AnUnitInFilename: string; ExceptionOnNotFound: boolean; ErrorPos: integer
): TCodeBuffer;
var
CompiledFilename: string;
AFilename: String;
NewUnitName: String;
NewInFilename: String;
NewCompiledUnitname: String;
ErrMsg: string;
begin
{$IF defined(ShowTriedFiles) or defined(ShowTriedUnits)}
DebugLn('TFindDeclarationTool.FindUnitSource Self="',MainFilename,'" AnUnitName="',AnUnitName,'" AnUnitInFilename="',AnUnitInFilename,'"');
{$ENDIF}
Result:=nil;
if (AnUnitName='') or (Scanner=nil) then
RaiseException(20171214184503,'TFindDeclarationTool.FindUnitSource Invalid Data');
if (Scanner.MainCode=nil) then
RaiseException(20171214184512,'TFindDeclarationTool.FindUnitSource Invalid Data');
if (not (TObject(Scanner.MainCode) is TCodeBuffer)) then
RaiseException(20171214184519,'TFindDeclarationTool.FindUnitSource Invalid Data');
if (Scanner.OnLoadSource=nil) then
RaiseException(20171214184527,'TFindDeclarationTool.FindUnitSource Invalid Data');
NewUnitName:=AnUnitName;
NewInFilename:=AnUnitInFilename;
AFilename:=DirectoryCache.FindUnitSourceInCompletePath(
NewUnitName,NewInFilename,false,false,AddedNameSpace);
Result:=TCodeBuffer(Scanner.OnLoadSource(Self,AFilename,true));
if (Result=nil) and Assigned(OnFindUsedUnit) then begin
// no unit found
Result:=OnFindUsedUnit(Self,AnUnitName,AnUnitInFilename);
end;
if Result=nil then begin
// search .ppu
NewCompiledUnitname:=AnUnitName+'.ppu';
CompiledFilename:=DirectoryCache.FindCompiledUnitInCompletePath(
NewCompiledUnitname,false);
//debugln(['TFindDeclarationTool.FindUnitSource UnitName=',NewUnitName,' ',NewCompiledUnitname,' CompiledFilename=',CompiledFilename]);
end else begin
CompiledFilename:='';
end;
if (Result=nil) and ExceptionOnNotFound then begin
ErrMsg:='';
if ErrorPos>0 then
MoveCursorToCleanPos(ErrorPos)
else if ErrorPos=0 then begin
CurPos.StartPos:=-1;
end else begin
CurPos.StartPos:=-1;
ErrMsg:=Format(ctsNeededByMode, [CompilerModeNames[Scanner.CompilerMode]]);
end;
if CompiledFilename<>'' then begin
// there is a compiled unit, only the source was not found
RaiseExceptionInstance(
ECodeToolUnitNotFound.Create(Self,20170421200052,
Format(ctsSourceNotFoundUnit+ErrMsg, [CompiledFilename]),
AnUnitName));
end else begin
// nothing found
RaiseExceptionInstance(
ECodeToolUnitNotFound.Create(Self,20170421200056,
Format(ctsUnitNotFound+ErrMsg,[AnUnitName]),
AnUnitInFilename));
end;
end;
end;
function TFindDeclarationTool.FindUnitCaseInsensitive(var AnUnitName,
AnUnitInFilename: string): string;
begin
Result:=DirectoryCache.FindUnitSourceInCompletePath(
AnUnitName,AnUnitInFilename,true,false,AddedNameSpace);
end;
procedure TFindDeclarationTool.GatherUnitAndSrcPath(var UnitPath,
CompleteSrcPath: string);
begin
UnitPath:='';
CompleteSrcPath:='';
UnitPath:=DirectoryCache.Strings[ctdcsUnitPath];
CompleteSrcPath:=DirectoryCache.Strings[ctdcsCompleteSrcPath];
//DebugLn('TFindDeclarationTool.GatherUnitAndSrcPath UnitPath="',UnitPath,'" CompleteSrcPath="',CompleteSrcPath,'"');
end;
function TFindDeclarationTool.SearchUnitInUnitSet(const TheUnitName: string): string;
begin
Result:=DirectoryCache.FindUnitInUnitSet(TheUnitName);
end;
function TFindDeclarationTool.GetNameSpaces: string;
begin
Result:=DirectoryCache.Strings[ctdcsNamespaces];
if AddedNameSpace<>'' then begin
if Result<>'' then Result:=';'+Result;
Result:=AddedNameSpace+Result;
end;
end;
function TFindDeclarationTool.FindSmartHint(const CursorPos: TCodeXYPosition;
Flags: TFindSmartFlags): string;
var
NewTool: TFindDeclarationTool;
NewNode: TCodeTreeNode;
NewPos: TCodeXYPosition;
NewTopLine: integer;
begin
Result:='';
if not FindDeclaration(CursorPos,Flags,NewTool,NewNode,NewPos,NewTopLine) then
begin
// identifier not found
exit;
end;
Result:=NewTool.GetSmartHint(NewNode,NewPos,true);
end;
function TFindDeclarationTool.GetSmartHint(Node: TCodeTreeNode;
XYPos: TCodeXYPosition; WithPosition: boolean; WithDefinition: boolean
): string;
function ReadIdentifierWithDots: String;
begin
Result := '';
repeat
ReadNextAtom;
Result := Result + GetAtom;
ReadNextAtom;
if CurPos.Flag = cafPoint then
Result := Result + '.'
else
break;
until false;
end;
function MoveToLastIdentifierThroughDots(ExtTool: TFindDeclarationTool): Boolean;
var
LastPos: TAtomPosition;
begin
LastPos := ExtTool.CurPos;
ExtTool.ReadNextAtom;
if ExtTool.CurPos.Flag = cafWord then
ExtTool.ReadNextAtom;
while ExtTool.CurPos.Flag = cafPoint do
begin
ExtTool.ReadNextAtom;
LastPos := ExtTool.CurPos;
ExtTool.ReadNextAtom;
end;
ExtTool.CurPos := LastPos;
Result := True;
end;
function ProceedWithSmartHint(ExtTool: TFindDeclarationTool): string;
var
CTExprType: TExpressionType;
CTXYPos: TCodeXYPosition;
CTTopLine: integer;
CTCursorPos: TCodeXYPosition;
begin
MoveToLastIdentifierThroughDots(ExtTool);
if ExtTool.CleanPosToCaret(ExtTool.CurPos.StartPos,CTCursorPos)
and ExtTool.FindDeclaration(CTCursorPos,
DefaultFindSmartHintFlags+[fsfSearchSourceName],CTExprType,CTXYPos,CTTopLine)
and not((CTExprType.Desc=xtContext) and (CTExprType.Context.Node=nil) and (CTExprType.Context.Tool=nil))
and not((CTExprType.Context.Tool=Self) and (CTXYPos.X=XYPos.X) and (CTXYPos.Y=XYPos.Y)) // prevent endless loop
then
Result := CTExprType.Context.Tool.GetSmartHint(CTExprType.Context.Node, CTXYPos, False, False)
else
Result := '';
end;
var
IdentNode, TypeNode, ANode: TCodeTreeNode;
ClassStr, NodeStr, SetStr: String;
Params: TFindDeclarationParams;
Tool: TFindDeclarationTool;
HelperForNode: TCodeTreeNode;
SubNode: TCodeTreeNode;
begin
Result:='';
{ Examples:
var i: integer
/home/.../codetools/finddeclarationtools.pas(1224,7)
}
// identifier category and identifier
if Node<>nil then begin
// class visibility
if Node.Parent<>nil then begin
ANode:=Node.Parent;
while ANode<>nil do begin
case ANode.Desc of
ctnClassPrivate:
Result+='private ';
ctnClassProtected:
Result+='protected ';
ctnClassPublic:
Result+='public ';
ctnClassPublished:
Result+='published ';
ctnClassClassVar:
Result+='class ';
else
break;
end;
ANode:=ANode.Parent;
end;
end;
if Node.Desc = ctnGenericName then
Node := Node.Parent;
case Node.Desc of
ctnIdentifier:
if Assigned(Node.Parent) and (Node.Parent.Desc = ctnProcedureHead) then
// function result
Result := 'var Result: ' + ExtractNode(Node, []);
ctnVarDefinition, ctnTypeDefinition, ctnConstDefinition,
ctnEnumIdentifier, ctnLabel, ctnGenericType:
begin
case Node.Desc of
ctnVarDefinition: Result+='var ';
ctnTypeDefinition: Result+='type ';
ctnConstDefinition: Result+='const ';
ctnEnumIdentifier: Result+='enum ';
ctnLabel: Result+='label ';
ctnGenericType: Result+='generic type ';
end;
// add class name
ClassStr := ExtractClassPath(Node.Parent);
if ClassStr <> '' then Result += ClassStr + '.';
Result:=Result+ExtractDefinitionName(Node);
TypeNode:=FindTypeNodeOfDefinition(Node);
if not WithDefinition then Result := '';
if TypeNode<>nil then begin
case Node.Desc of
ctnTypeDefinition, ctnGenericType:
Result+=' = ';
ctnConstDefinition:
if TypeNode.Desc = ctnConstant then
Result += ' = '
else
Result += ': ';
ctnEnumIdentifier,ctnLabel: ;
else
Result += ': ';
end;
case TypeNode.Desc of
ctnSetType:
begin
Result += ExtractNode(TypeNode, [phpCommentsToSpace]);
MoveCursorToNodeStart(TypeNode);
ReadNextAtom;
if ReadNextUpAtomIs('OF') then
begin
if (Length(Result) > 0) and (Result[Length(Result)] = ';') then//delete last ";" from set
Delete(Result, Length(Result), 1);
ReadNextAtom;
SetStr := ProceedWithSmartHint(Self);
if (Length(SetStr) > 2) and (SetStr[2] = '=') then
SetStr := Copy(SetStr, 4, High(Integer));
if (SetStr <> '') then
Result += ' = ['+SetStr+']';
end;
end;
ctnIdentifier, ctnSpecialize, ctnSpecializeType,
ctnPointerType, ctnRangeType, ctnFileType, ctnClassOfType:
begin
Result += ExtractNode(TypeNode, [phpCommentsToSpace]);
MoveCursorToNodeStart(TypeNode);
Result += ProceedWithSmartHint(Self);
end;
ctnClass, ctnClassInterface, ctnDispinterface,
ctnClassHelper, ctnTypeHelper, ctnRecordHelper,
ctnObject, ctnRangedArrayType, ctnOpenArrayType,
ctnObjCClass, ctnObjCCategory, ctnObjCProtocol, ctnCPPClass:
begin
MoveCursorToNodeStart(TypeNode);
case TypeNode.Desc of
ctnClass: Result:=Result+'class';
ctnClassHelper: Result:=Result+'class helper';
ctnRecordHelper: Result:=Result+'record helper';
ctnTypeHelper: Result:=Result+'type helper';
ctnObject: Result:=Result+'object';
ctnObjCClass: Result:=Result+'objcclass';
ctnObjCCategory: Result:=Result+'objccategory';
ctnCPPClass: Result:=Result+'cppclass';
ctnClassInterface: Result:=Result+'interface';
ctnObjCProtocol: Result:=Result+'objcprotocol';
ctnDispinterface: Result:=Result+'dispinterface';
ctnRangedArrayType, ctnOpenArrayType: Result:=Result+'array';
end;
try
BuildSubTree(TypeNode);
except
on ECodeToolError do ;
end;
SubNode:=FindInheritanceNode(TypeNode);
if SubNode<>nil then
Result:=Result+ExtractNode(SubNode,[]);
if TypeNode.Desc in [ctnClassHelper, ctnRecordHelper, ctnTypeHelper] then
HelperForNode := FindHelperForNode(TypeNode)
else
HelperForNode := nil;
if HelperForNode<>nil then
Result:=Result+' '+ExtractNode(HelperForNode,[]);
end;
ctnRecordType:
Result:=Result+'record';
ctnTypeType:
begin
Result:=Result+'type';
if TypeNode.FirstChild <> nil then
Result:=Result+' '+ExtractNode(TypeNode.FirstChild,[]);
end;
ctnConstant:
begin
NodeStr:=ExtractNode(TypeNode,[phpCommentsToSpace]);
Result+=copy(NodeStr,1,50);
end;
ctnEnumerationType:
begin
if Assigned(Node.FirstChild) then
begin
NodeStr:=ExtractCode(Node.FirstChild.StartPos,Node.FirstChild.EndPos,[phpCommentsToSpace]);
if Length(NodeStr) > 50 then
NodeStr:=Copy(NodeStr, 1, 50) + ' ...';
Result += NodeStr;
end else
Result += 'enum';
end;
end;
end else begin
case Node.Desc of
ctnConstDefinition:
begin
DebugLn('TFindDeclarationTool.GetSmartHint const without subnode "',ExtractNode(Node,[]),'"');
NodeStr:=ExtractCode(Node.StartPos
+GetIdentLen(@Src[Node.StartPos]),
Node.EndPos,[phpCommentsToSpace]);
Result+=copy(NodeStr,1,50);
end;
end;
end;
end;
ctnProcedure,ctnProcedureHead:
begin
// ToDo: ppu, dcu files
Result+=ExtractProcHead(Node,
[phpAddClassName,phpWithStart,phpWithVarModifiers,phpWithParameterNames,
phpWithDefaultValues,phpWithResultType,phpWithOfObject,phpCommentsToSpace]);
end;
ctnProperty,ctnGlobalProperty:
begin
IdentNode:=Node;
// ToDo: ppu, dcu files
Result+='property ';
MoveCursorToNodeStart(IdentNode);
ReadNextAtom;
if Node.Desc = ctnProperty then begin
// e.g. property Caption: string;
// skip keyword
ReadNextAtom;
// add class name
ClassStr := ExtractClassName(Node, False, True);
if ClassStr <> '' then Result += ClassStr + '.';
end else begin
// global property starts with identifier
end;
// add name
Result+=GetAtom;
Tool:=Self;
while (Node.Desc=ctnProperty)
and not Tool.MoveCursorToPropType(Node) do begin
// property without type
// -> search ancestor property
if not Tool.MoveCursorToPropName(Node) then break;
Params:=TFindDeclarationParams.Create(Tool, Node);
try
Params.SetIdentifier(Tool,@Tool.Src[Tool.CurPos.StartPos],nil);
Params.Flags:=[fdfSearchInAncestors,fdfSearchInHelpers];
if not FindIdentifierInAncestors(Node.Parent.Parent,Params) then break;
Tool:=Params.NewCodeTool;
Node:=Params.NewNode;
finally
Params.Free;
end;
end;
if (Node<>nil) then begin
if (Node.Desc in [ctnProperty,ctnGlobalProperty]) then begin
Result += Tool.ExtractProperty(Node,
[phpWithoutName,phpWithParameterNames,phpWithResultType]);
end;
if Tool.MoveCursorToPropType(Node) then
Result += ProceedWithSmartHint(Tool);
end;
end;
ctnProgram,ctnUnit,ctnPackage,ctnLibrary:
begin
IdentNode:=Node;
// ToDo: ppu, dcu files
MoveCursorToNodeStart(IdentNode);
ReadNextAtom;
if (IdentNode.Desc=ctnProgram) and not UpAtomIs('PROGRAM') then begin
// program without source name
Result:='program '+ExtractFileNameOnly(MainFilename)+' ';
end else begin
Result+=GetAtom+' '; // keyword
Result := Result + ReadIdentifierWithDots + ' ';
end;
end;
ctnUseUnitNamespace:
begin
// hint for unit namespace in "uses" section
Result += 'namespace ';
MoveCursorToNodeStart(Node);
ReadNextAtom;
Result := Result + GetAtom;
end;
ctnUseUnitClearName:
begin
// hint for unit in "uses" section
Result += 'unit ';
MoveCursorToNodeStart(Node.Parent);
Result := Result + ReadIdentifierWithDots;
end
else
DebugLn('ToDo: TFindDeclarationTool.GetSmartHint ',Node.DescAsString);
end;
end;
if WithPosition then begin
// filename
if Result<>'' then Result:=Result+LineEnding;
if XYPos.Code=nil then
CleanPosToCaret(Node.StartPos,XYPos);
Result+=XYPos.Code.Filename;
// file position
if XYPos.Y>=1 then begin
Result+='('+IntToStr(XYPos.Y);
if XYPos.X>=1 then begin
Result+=','+IntToStr(XYPos.X);
end;
Result+=')';
end;
end;
end;
function TFindDeclarationTool.BaseTypeOfNodeHasSubIdents(ANode: TCodeTreeNode
): boolean;
var
FindContext: TFindContext;
Params: TFindDeclarationParams;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(ANode);{$ENDIF}
Result:=false;
if (ANode=nil) then exit;
ActivateGlobalWriteLock;
Params:=TFindDeclarationParams.Create(Self, ANode);
try
Params.Flags:=Params.Flags+[fdfFunctionResult,fdfFindChildren];
FindContext:=FindBaseTypeOfNode(Params,ANode);
if (FindContext.Node<>nil)
and ((FindContext.Node.Desc in ([ctnEnumerationType]+AllClasses)))
and (FindContext.Node.FirstChild<>nil)
then
Result:=true;
finally
Params.Free;
DeactivateGlobalWriteLock;
end;
end;
function TFindDeclarationTool.IsIncludeDirectiveAtPos(CleanPos,
CleanCodePosInFront: integer; out IncludeCode: TCodeBuffer): boolean;
var LinkIndex, CommentStart, CommentEnd: integer;
SrcLink: TSourceLink;
begin
Result:=false;
IncludeCode:=nil;
if (Scanner=nil) then exit;
LinkIndex:=Scanner.LinkIndexAtCleanPos(CleanPos);
if (LinkIndex<0) or (LinkIndex>=Scanner.LinkCount-1) then exit;
SrcLink:=Scanner.Links[LinkIndex+1];
if (SrcLink.Code=nil) or (SrcLink.Code=Scanner.Links[LinkIndex].Code) then
exit;
//DebugLn(['TFindDeclarationTool.IsIncludeDirectiveAtPos CleanPos=',CleanPos,' CleanCodePosInFront=',CleanCodePosInFront,' ',copy(Src,CleanCodePosInFront,10)]);
if CleanPosIsInComment(CleanPos,CleanCodePosInFront,CommentStart,CommentEnd)
and (CommentEnd=SrcLink.CleanedPos) then begin
//DebugLn(['TFindDeclarationTool.IsIncludeDirectiveAtPos CommentStart=',CommentStart,' CommentEnd=',CommentEnd,' ',copy(Src,CommentStart,CommentEnd-CommentStart)]);
IncludeCode:=TCodeBuffer(SrcLink.Code);
Result:=true;
exit;
end;
end;
function TFindDeclarationTool.FindFileAtCursor(
const CursorPos: TCodeXYPosition; out Found: TFindFileAtCursorFlag; out
FoundFilename: string; SearchFor: TFindFileAtCursorFlags;
StartPos: PCodeXYPosition): boolean;
var
CleanPos: integer;
function CheckComment(CommentStart, CommentEnd: integer; Enabled: boolean): boolean;
var
DirectiveName, Param: string;
NewCode: TCodeBuffer;
MissingIncludeFile: TMissingIncludeFile;
NewCodePtr: Pointer;
begin
Result:=false;
// cursor in comment in parsed code
{$IFDEF VerboseFindFileAtCursor}
debugln(['TFindDeclarationTool.FindFileAtCursor.CheckComment']);
{$ENDIF}
if CommentStart=CommentEnd then exit;
if ExtractLongParamDirective(Src,CommentStart,DirectiveName,Param) then begin
DirectiveName:=lowercase(DirectiveName);
if ((Enabled and (ffatIncludeFile in SearchFor))
or (not Enabled and (ffatDisabledIncludeFile in SearchFor)))
and (DirectiveName='i') or (DirectiveName='include')
then begin
// include directive
if (Param<>'') and (Param[1]<>'%') then begin
// include file directive
Result:=true;
if Enabled then
Found:=ffatIncludeFile
else
Found:=ffatDisabledIncludeFile;
if Enabled and IsIncludeDirectiveAtPos(CleanPos,CommentStart,NewCode) then
begin
FoundFilename:=NewCode.Filename;
end else begin
FoundFilename:=ResolveDots(GetForcedPathDelims(Param));
// search include file
MissingIncludeFile:=nil;
if Scanner.SearchIncludeFile(FoundFilename,NewCodePtr,
MissingIncludeFile)
then
FoundFilename:=TCodeBuffer(NewCodePtr).Filename;
end;
exit;
end;
end else if ((Enabled and (ffatResource in SearchFor))
or (not Enabled and (ffatDisabledResource in SearchFor)))
and ((DirectiveName='r') or (DirectiveName='resource'))
then begin
// resource directive
Result:=true;
if Enabled then
Found:=ffatResource
else
Found:=ffatDisabledResource;
FoundFilename:=ResolveDots(GetForcedPathDelims(Param));
if (FoundFilename<>'') and (copy(FoundFilename,1,2)='*.') then begin
Delete(FoundFilename,1,1);
FoundFilename:=ChangeFileExt(MainFilename,FoundFilename);
end else if not FilenameIsAbsolute(FoundFilename) then begin
FoundFilename:=ResolveDots(ExtractFilePath(MainFilename)+FoundFilename);
end;
exit;
end;
end;
end;
function CheckPlainComments(Source: string; CurAbsPos: integer): boolean;
var
Filename: String;
p, EndPos, FileStartPos, FileEndPos, MinPos, MaxPos: Integer;
begin
// check if cursor in a comment (ignoring directives)
Result:=false;
CursorPos.Code.LineColToPosition(CursorPos.Y,CursorPos.X,CurAbsPos);
Source:=CursorPos.Code.Source;
if (CurAbsPos<1) or (CurAbsPos>length(Source)) then exit;
p:=1;
repeat
p:=FindNextComment(Source,p);
if p>CurAbsPos then break;
EndPos:=FindCommentEnd(Source,p,Scanner.NestedComments);
if EndPos>CurAbsPos then begin
// cursor in comment
MinPos:=p+1;
MaxPos:=EndPos-1;
if Source[p]<>'{' then begin
inc(MinPos);
dec(MaxPos);
end;
FileStartPos:=CurAbsPos;
while (FileStartPos>MinPos) and not (Source[FileStartPos-1] in [#0..#32]) do
dec(FileStartPos);
FileEndPos:=CurAbsPos;
while (FileEndPos<MaxPos) and not (Source[FileEndPos] in [#0..#32]) do
inc(FileEndPos);
Filename:=TrimFilename(copy(Source,FileStartPos,FileEndPos-FileStartPos));
if not FilenameIsAbsolute(Filename) then
Filename:=ResolveDots(ExtractFilePath(MainFilename)+Filename);
if Scanner.OnLoadSource(Scanner,Filename,false)<>nil then begin
Found:=ffatComment;
FoundFilename:=Filename;
exit(true);
end;
exit;
end;
p:=EndPos;
until false;
end;
function CheckUnitByWordAtCursor(Source: string; CurAbsPos: integer): boolean;
// e.g. 'Sy|sUtils.CompareText'
var
AnUnitName: String;
Code: TCodeBuffer;
p: Integer;
begin
Result:=false;
p:=FindStartOfAtom(Source,CurAbsPos);
if p<1 then exit;
AnUnitName:=GetIdentifier(@Source[p]);
Code:=FindUnitSource(AnUnitName,'',false);
if Code=nil then exit;
Found:=ffatUnit;
FoundFilename:=Code.Filename;
Result:=true;
end;
var
CommentStart, CommentEnd, Col, StartCol, CurAbsPos: integer;
Node: TCodeTreeNode;
aUnitName, UnitInFilename, Line, Literal, aSource: string;
NewCode: TCodeBuffer;
p, StartP: PChar;
begin
{$IFDEF VerboseFindFileAtCursor}
debugln(['TFindDeclarationTool.FindFileAtCursor START']);
{$ENDIF}
Result:=false;
Found:=ffatNone;
FoundFilename:='';
if StartPos<>nil then
StartPos^:=CleanCodeXYPosition;
if CursorPos.Code.LineColIsOutside(CursorPos.Y,CursorPos.X) then begin
{$IFDEF VerboseFindFileAtCursor}
debugln(['TFindDeclarationTool.FindFileAtCursor LineColIsOutside ',dbgs(CursorPos)]);
{$ENDIF}
exit;
end;
if CursorPos.Code.LineColIsSpace(CursorPos.Y,CursorPos.X) then begin
{$IFDEF VerboseFindFileAtCursor}
debugln(['TFindDeclarationTool.FindFileAtCursor LineColIsSpace ',dbgs(CursorPos)]);
{$ENDIF}
exit;
end;
if (CursorPos.Y<1) or (CursorPos.Y>CursorPos.Code.LineCount) then begin
{$IFDEF VerboseFindFileAtCursor}
debugln(['TFindDeclarationTool.FindFileAtCursor outside Line ',dbgs(CursorPos)]);
{$ENDIF}
exit;
end;
if [ffatUsedUnit,ffatIncludeFile,ffatDisabledIncludeFile]*SearchFor<>[]
then begin
try
{$IFDEF VerboseFindFileAtCursor}
debugln(['TFindDeclarationTool.FindFileAtCursor search in nodes']);
{$ENDIF}
BuildTreeAndGetCleanPos(trTillCursor,lsrEnd,CursorPos,CleanPos,
[btSetIgnoreErrorPos,btCursorPosOutAllowed]);
Node:=FindDeepestNodeAtPos(CleanPos,false);
{$IFDEF VerboseFindFileAtCursor}
debugln(['TFindDeclarationTool.FindFileAtCursor has node: ',Node<>nil]);
{$ENDIF}
if Node<>nil then begin
{$IFDEF VerboseFindFileAtCursor}
debugln(['TFindDeclarationTool.FindFileAtCursor in node "',Node.DescAsString,'"']);
{$ENDIF}
// cursor in parsed code
if CleanPosIsInComment(CleanPos,Node.StartPos,CommentStart,CommentEnd,true)
then begin
//debugln(['TFindDeclarationTool.FindFileAtCursor Comment="',copy(Src,CommentStart,CommentEnd-CommentStart),'"']);
if (CommentEnd-CommentStart>4)
and (Src[CommentStart]='{') and (Src[CommentStart+1]=#3) then begin
// cursor in disabled code
if CleanPosIsInComment(CleanPos,CommentStart+2,CommentStart,CommentEnd,true)
then begin
// cursor in disabled comment
if CheckComment(CommentStart,CommentEnd,false) then
exit(true);
end;
end else begin
// cursor in enabled comment
if CheckComment(CommentStart,CommentEnd,true) then
exit(true);
end;
end else begin
{$IFDEF VerboseFindFileAtCursor}
debugln(['TFindDeclarationTool.FindFileAtCursor in parsed code, not in comment Node=',Node.DescAsString]);
{$ENDIF}
if Node.Desc in [ctnUseUnitClearName,ctnUseUnitNamespace] then begin
Node:=Node.Parent;
{$IFDEF VerboseFindFileAtCursor}
debugln(['TFindDeclarationTool.FindFileAtCursor node="',Node.DescAsString,'"']);
{$ENDIF}
end;
if Node.Desc=ctnUseUnit then begin
{$IFDEF VerboseFindFileAtCursor}
debugln(['TFindDeclarationTool.FindFileAtCursor in use unit CleanPos=',CleanPos,' Node=',Node.StartPos,'-',Node.EndPos]);
{$ENDIF}
if (CleanPos>=Node.StartPos) and (CleanPos<Node.EndPos) then begin
// cursor on used unit
Found:=ffatUsedUnit;
if StartPos<>nil then
CleanPosToCaret(Node.StartPos,StartPos^);
MoveCursorToNodeStart(Node);
ReadNextAtom;
aUnitName:=ExtractUsedUnitNameAtCursor(@UnitInFilename);
NewCode:=FindUnitSource(aUnitName,UnitInFilename,false);
{$IFDEF VerboseFindFileAtCursor}
debugln(['TFindDeclarationTool.FindFileAtCursor cursor on used unit "',aUnitName,'" in "',UnitInFilename,'" Found=',NewCode<>nil]);
{$ENDIF}
if NewCode<>nil then begin
FoundFilename:=NewCode.Filename;
Result:=true;
end else begin
FoundFilename:=UnitInFilename;
Result:=false;
end;
exit;
end;
end;
end;
end;
except
on ELinkScannerError do ;
on ECodeToolError do ;
end;
end;
// fallback: ignore parsed code and read the line at cursor directly
if (CursorPos.Y<1) or (CursorPos.Y>CursorPos.Code.LineCount) then exit;
Line:=CursorPos.Code.GetLine(CursorPos.Y-1,false);
{$IFDEF VerboseFindFileAtCursor}
debugln(['TFindDeclarationTool.FindFileAtCursor Line="',copy(Line,1,CursorPos.X-1),'|',copy(Line,CursorPos.X,200),'"']);
{$ENDIF}
if CursorPos.X>length(Line) then exit;
if ffatLiteral in SearchFor then begin
// check literal
p:=PChar(Line);
repeat
case p^ of
#0:
break;
'''':
begin
StartCol:=p-PChar(Line)+1;
inc(p);
StartP:=p;
repeat
case p^ of
#0,'''': break;
else inc(p);
end;
until false;
Col:=p-PChar(Line)+1;
//debugln(['TFindDeclarationTool.FindFileAtCursor Col=',Col,' CursorCol=',CursorPos.X,' Literal=',copy(Line,StartCol+1,p-StartP)]);
if (p>StartP) and (CursorPos.X>=StartCol) and (CursorPos.X<=Col) then begin
Literal:=copy(Line,StartCol+1,p-StartP);
if not FilenameIsAbsolute(Literal) then
Literal:=TrimFilename(ExtractFilePath(Scanner.MainFilename)+Literal);
Found:=ffatLiteral;
FoundFilename:=Literal;
exit(true);
end;
if p^=#0 then break;
// p is now on the ending '
end;
end;
inc(p);
inc(Col);
until false;
end;
// search without node tree with basic tools
CursorPos.Code.LineColToPosition(CursorPos.Y,CursorPos.X,CurAbsPos);
aSource:=CursorPos.Code.Source;
if (CurAbsPos<1) or (CurAbsPos>length(aSource)) then exit;
if ffatComment in SearchFor then begin
// ignore syntax and only read comments
if CheckPlainComments(aSource,CurAbsPos) then exit(true);
end;
if ffatUnit in SearchFor then begin
if CheckUnitByWordAtCursor(aSource,CurAbsPos) then exit(true);
end;
end;
function TFindDeclarationTool.FindDeclarationOfIdentAtParam(
Params: TFindDeclarationParams): boolean;
var
ExprType: TExpressionType;
begin
Result := FindDeclarationOfIdentAtParam(Params, ExprType) and (Params.NewNode<>nil);
end;
function TFindDeclarationTool.FindDeclarationOfIdentAtParam(
Params: TFindDeclarationParams; out ExprType: TExpressionType): boolean;
{ searches an identifier in clean code, parses code in front and after the
identifier
Params:
Identifier in clean source
ContextNode // = DeepestNode at Cursor
Result:
true, if found
Examples:
A^.B().C[].Identifier
inherited Identifier(p1,p2)
'Hello'.identifier
}
var
StartPos, EndPos: integer;
SkipForward: boolean;
begin
{$IFDEF CTDEBUG}
DebugLn('[TFindDeclarationTool.FindDeclarationOfIdentAtParam] Identifier=',
'"',GetIdentifier(Params.Identifier),'"',
' ContextNode=',NodeDescriptionAsString(Params.ContextNode.Desc),
' "',dbgstr(copy(Src,Params.ContextNode.StartPos,20)),'"');
{$ENDIF}
Result:=false;
// search in cleaned source
MoveCursorToCleanPos(Params.Identifier);
StartPos:=FindStartOfTerm(CurPos.StartPos,NodeTermInType(Params.ContextNode));
MoveCursorToCleanPos(Params.Identifier);
ReadNextAtom;
EndPos:=CurPos.EndPos;
if (Params.ContextNode.Desc=ctnIdentifier)
and (Params.ContextNode.Parent.Desc=ctnAttribParam) then begin
// parameters don't matter for the attribute name
end else begin
ReadNextAtom;
if CurPos.Flag=cafRoundBracketOpen then begin
ReadTilBracketClose(true);
EndPos:=CurPos.EndPos;
end;
end;
{$IFDEF ShowExprEval}
debugln(['TFindDeclarationTool.FindDeclarationOfIdentAtParam Term=',dbgstr(Src,StartPos,EndPos-StartPos)]);
{$ENDIF}
SkipForward:=fdfSkipClassForward in Params.Flags;
Include(Params.Flags,fdfFindVariable);
ExprType:=FindExpressionTypeOfTerm(StartPos,EndPos,Params,false);
if (ExprType.Desc=xtContext) then
Params.SetResult(ExprType.Context)
else
Params.SetResult(CleanFindContext);
if SkipForward and (Params.NewNode<>nil) then
Params.NewCodeTool.FindNonForwardClass(Params);
{$IFDEF ShowExprEval}
DbgOut('[TFindDeclarationTool.FindDeclarationOfIdentAtParam] Ident=',
'"',GetIdentifier(Params.Identifier),'" ');
if Params.NewNode<>nil then
DebugLn('Node=',Params.NewNode.DescAsString,' ',Params.NewCodeTool.MainFilename)
else
DebugLn('NOT FOUND');
{$ENDIF}
Result:=ExprType.Desc<>xtNone;
end;
function TFindDeclarationTool.IdentifierIsDefined(const IdentAtom: TAtomPosition;
ContextNode: TCodeTreeNode; Params: TFindDeclarationParams): boolean;
var
Identifier: PChar;
Node: TCodeTreeNode;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(ContextNode);{$ENDIF}
// find declaration of identifier
Identifier:=@Src[IdentAtom.StartPos];
//DebugLn(['TFindDeclarationTool.IdentifierIsDefined BEGIN Params IdentAtom.StartPos=',IdentAtom.StartPos,'=',GetIdentifier(Identifier),', ContextNode.StartPos=',ContextNode.StartPos,'=',ContextNode.DescAsString,' "',ExtractNode(ContextNode,[]),'"']);
if (CompareIdentifiers(Identifier,'Self')=0) then begin
Node:=ContextNode;
while (Node<>nil) do begin
if NodeIsMethodBody(Node) then
exit(true);
Node:=Node.Parent;
end;
end;
if (cmsResult in FLastCompilerModeSwitches)
and (CompareIdentifiers(Identifier,'Result')=0) then begin
Node:=ContextNode;
while (Node<>nil) do begin
if NodeIsFunction(Node) then
exit(true);
Node:=Node.Parent;
end;
end;
Params.ContextNode:=ContextNode;
Params.SetIdentifier(Self,Identifier,nil);
Params.Flags:=[fdfSearchInParentNodes,fdfSearchInAncestors,fdfSearchInHelpers,
fdfTopLvlResolving,fdfFindVariable,fdfIgnoreCurContextNode];
Result:=FindIdentifierInContext(Params);
//DebugLn(['TFindDeclarationTool.IdentifierIsDefined END Result=',Result]);
end;
function TFindDeclarationTool.FindIdentifierInContext(
Params: TFindDeclarationParams; var IdentFoundResult: TIdentifierFoundResult
): boolean;
{ searches an identifier in context node
It does not care about code in front of the identifier like 'a.Identifier'.
Params:
Identifier
ContextNode // = DeepestNode at Cursor
Result:
true, if NewPos+NewTopLine valid
}
var
LastContextNode, StartContextNode, FirstSearchedNode, LastSearchedNode,
ContextNode: TCodeTreeNode;
IsForward: boolean;
IdentifierFoundResult: TIdentifierFoundResult;
LastNodeCache: TCodeTreeNodeCache;
LastCacheEntry: PCodeTreeNodeCacheEntry;
SearchRangeFlags: TNodeCacheEntryFlags;
NodeCacheEntryFlags: TNodeCacheEntryFlags;
Flags: TFindDeclarationFlags;
OldFlags: TFindDeclarationFlags;
SearchInHelpersInTheEnd: Boolean;
procedure InitNodesAndCacheAccess;
procedure RaiseInternalError;
begin
RaiseException(20170421200059,'[TFindDeclarationTool.FindIdentifierInContext] '
+' internal error: Params.ContextNode=nil');
end;
begin
ContextNode:=Params.ContextNode;
if ContextNode=nil then RaiseInternalError;
{$IFDEF CheckNodeTool}
CheckNodeTool(ContextNode);
{$ENDIF}
StartContextNode:=ContextNode;
FirstSearchedNode:=nil;
LastSearchedNode:=nil;
SearchRangeFlags:=[];
Flags:=Params.Flags;
if fdfSearchInParentNodes in Flags then
Include(SearchRangeFlags,ncefSearchedInParents);
if fdfSearchInAncestors in Flags then
Include(SearchRangeFlags,ncefSearchedInAncestors);
LastNodeCache:=nil;
LastCacheEntry:=nil;
NodeCacheEntryFlags:=[];
if fdfSearchInParentNodes in Flags then
Include(NodeCacheEntryFlags,ncefSearchedInParents);
if fdfSearchInAncestors in Flags then
Include(NodeCacheEntryFlags,ncefSearchedInAncestors);
end;
function FindInNodeCache: boolean;
var
NodeCache: TCodeTreeNodeCache;
begin
Result:=false;
// the node cache is identifier based
if ([fdfCollect,fdfExtractOperand]*Flags<>[]) then exit;
NodeCache:=GetNodeCache(ContextNode,false);
if (NodeCache<>LastNodeCache) then begin
// NodeCache changed -> search nearest cache entry for the identifier
LastNodeCache:=NodeCache;
if NodeCache<>nil then begin
LastCacheEntry:=NodeCache.FindNearest(Params.Identifier,
ContextNode.StartPos,ContextNode.EndPos,
not (fdfSearchForward in Flags));
end else
LastCacheEntry:=nil;
end;
if (LastCacheEntry<>nil)
and (LastCacheEntry^.CleanStartPos<=ContextNode.StartPos)
and (LastCacheEntry^.CleanEndPos>=ContextNode.EndPos)
and ((NodeCacheEntryFlags-LastCacheEntry^.Flags)=[])
then begin
// cached result found
Params.SetResult(LastCacheEntry);
{$IFDEF ShowNodeCache}
DbgOut(':::: TFindDeclarationTool.FindIdentifierInContext.FindInNodeCache');
DebugLn(' Ident=',GetIdentifier(Params.Identifier),
' Wanted=[',NodeCacheEntryFlagsAsString(NodeCacheEntryFlags),']',
' Cache=[',NodeCacheEntryFlagsAsString(LastCacheEntry^.Flags),']'
);
DebugLn(' ContextNode=',ContextNode.DescAsString,
' StartPos=',DbgS(ContextNode.StartPos),
' EndPos=',DbgS(ContextNode.EndPos),
' Self=',MainFilename);
DebugLn(' LastCacheEntry(Pos=',DbgS(LastCacheEntry^.CleanStartPos),
'-',DbgS(LastCacheEntry^.CleanEndPos),')');
if (Params.NewNode<>nil) then
DebugLn(' NewTool=',Params.NewCodeTool.MainFilename,
' NewNode=',Params.NewNode.DescAsString)
else
DebugLn(' cache says: identifier does NOT exist');
if CompareSrcIdentifiers(Params.Identifier,'TDefineAction') then begin
NodeCache.WriteDebugReport('NANUNANA: ');
end;
{$ENDIF}
Result:=true;
end;
end;
procedure CacheResult(Found: boolean; EndNode: TCodeTreeNode);
begin
if not Found then exit;
FindIdentifierInContext:=true;
{$IFDEF ShowCollect}
if fdfCollect in Flags then
raise Exception.Create('fdfCollect must never return true');
{$ENDIF}
{$IFDEF ShowFoundIdentifier}
debugln(['CacheResult FOUND ',GetIdentifier(Params.Identifier)]);
Params.WriteDebugReport;
{$ENDIF}
if (FirstSearchedNode=nil) then exit;
if ([fdfDoNotCache,fdfCollect,fdfExtractOperand]*Flags<>[]) then exit;
if ([fodDoNotCache]*Params.NewFlags<>[]) then exit;
if (Params.OnIdentifierFound<>@CheckSrcIdentifier) then exit;
if (Params.FoundProc<>nil) then exit; // do not cache proc searches
// cache result
if (Params.NewNode<>nil) and (Params.NewNode.Desc=ctnProcedure) then begin
DebugLn('NOTE: TFindDeclarationTool.FindIdentifierInContext.CacheResult Node is proc');
// ToDo:
// The search range is from start to end of search.
// This does not work for overloaded procs.
// -> do not cache
exit;
end;
AddResultToNodeCaches(FirstSearchedNode,EndNode,
fdfSearchForward in Flags,Params,SearchRangeFlags);
end;
function CheckResult(NewResult, CallOnIdentifierFound: boolean): boolean;
// returns: true to stop search
// false if search should continue
procedure RaiseNotFound;
var
Identifier: string;
begin
Identifier:=GetIdentifier(Params.Identifier);
if (Identifier='') and (Params.Identifier<>nil)
and (Params.Identifier[0]<>#0) then begin
Identifier:=Params.Identifier[0];
if Identifier='[' then begin
Params.IdentifierTool.RaiseException(20170421200103,ctsDefaultPropertyNotFound);
end;
end;
Params.IdentifierTool.RaiseExceptionFmt(20170421200105,ctsIdentifierNotFound,
[Identifier]);
end;
begin
Result:=true;
FindIdentifierInContext:=NewResult and (not (fdfCollect in Flags));
{$IFDEF ShowCollect}
if fdfCollect in Flags then begin
DebugLn('[TFindDeclarationTool.FindIdentifierInContext.CheckResult] COLLECT CheckResult Ident=',
'"',GetIdentifier(Params.Identifier),'"',
' File="',ExtractFilename(MainFilename)+'"',
' Flags=[',dbgs(Flags)+']',
' NewResult=',DbgS(NewResult),
' CallOnIdentifierFound=',DbgS(CallOnIdentifierFound));
end;
{$ENDIF}
if NewResult then begin
// identifier found
{$IFDEF ShowFoundIdentifier}
debugln(['CheckResult FOUND ',GetIdentifier(Params.Identifier)]);
Params.WriteDebugReport;
{$ENDIF}
if fdfExtractOperand in Flags then
case Params.NewNode.Desc of
ctnVarDefinition, ctnConstDefinition:
with Params do
AddOperandPart(GetIdentifier(@NewCodeTool.Src[NewNode.StartPos]));
ctnProperty,ctnGlobalProperty:
begin
if fdfPropertyResolving in Flags then begin
if not PropNodeIsTypeLess(Params.NewNode)
and ReadTilGetterOfProperty(Params.NewNode) then begin
// continue searching of getter
Params.Identifier := @Src[CurPos.StartPos];
end;
ContextNode := Params.NewNode;
Exit(False);
end else
Params.AddOperandPart(GetIdentifier(Params.Identifier));
end;
ctnProcedure:
begin
Params.AddOperandPart(ExtractProcName(Params.NewNode,[]));
// ToDo: add default parameters
end;
end;
if CallOnIdentifierFound then begin
{debugln(['[TFindDeclarationTool.FindIdentifierInContext.CheckResult] CallOnIdentifierFound Ident=',
'"',GetIdentifier(Params.Identifier),'"',
' StartContext="',StartContextNode.DescAsString,'" "',copy(Src,StartContextNode.StartPos,20),'"',
' File="',ExtractFilename(MainFilename)+'"',
' Flags=[',dbgs(Flags),']'
]);}
IdentFoundResult:=Params.NewCodeTool.DoOnIdentifierFound(Params,
Params.NewNode);
{$IFDEF ShowProcSearch}
DebugLn(['[TFindDeclarationTool.FindIdentifierInContext.CheckResult] DoOnIdentifierFound=',IdentifierFoundResultNames[IdentFoundResult]]);
{$ENDIF}
if (IdentFoundResult=ifrSuccess) then
CacheResult(true,ContextNode);
Result:=IdentFoundResult<>ifrProceedSearch;
if IdentFoundResult<>ifrAbortSearch then exit;
end else begin
if fdfCollect in Flags then
Result:=false;
CacheResult(true,ContextNode);
exit;
end;
end;
if Params.FoundProc<>nil then begin
// there was a proc,
// either the search for the overloaded proc was unsuccessful
// or the searched proc was found in a recursive sub search
// -> return the found proc
if Params.FoundProc^.CacheValid
and (Params.FoundProc^.ProcCompatibility=tcExact) then begin
// stop the search
Result:=true;
end;
FindIdentifierInContext:=true;
{$IFDEF ShowCollect}
if fdfCollect in Flags then
raise Exception.Create('fdfCollect must never return true');
{$ENDIF}
Params.SetResult(Params.FoundProc^.Context.Tool,
Params.FoundProc^.Context.Node);
{$IF defined(ShowProcSearch) or defined(ShowFoundIdentifier)}
DebugLn('[TFindDeclarationTool.FindIdentifierInContext] PROC Search ended with only one proc (normal when searching every used unit):');
Params.WriteDebugReport;
{$ENDIF}
exit;
end;
// identifier was not found
if not (fdfExceptionOnNotFound in Flags) then exit;
if (Params.Identifier<>nil)
and not (fdfExceptionOnPredefinedIdent in Flags)
and WordIsPredefinedIdentifier.DoItCaseInsensitive(Params.Identifier)
then begin
Params.SetResult(nil,nil);
exit;
end;
// identifier was not found and exception is wanted
// -> raise exception
if Params.IdentifierTool.IsPCharInSrc(Params.Identifier) then
Params.IdentifierTool.MoveCursorToCleanPos(Params.Identifier);
RaiseNotFound;
end;
procedure MoveContextNodeToChildren;
begin
if (ContextNode.LastChild<>nil) then begin
if not (fdfSearchForward in Flags) then begin
RaiseLastErrorIfInFrontOfCleanedPos(ContextNode.EndPos);
ContextNode:=ContextNode.LastChild;
end else
ContextNode:=ContextNode.FirstChild;
end;
end;
function SearchInGenericParams(GenParamsNode: TCodeTreeNode): boolean;
var
Node: TCodeTreeNode;
begin
Result:=false;
if (GenParamsNode=nil) or (GenParamsNode.Desc<>ctnGenericParams) then exit;
Node:=GenParamsNode.FirstChild;
while Node<>nil do begin
if (fdfCollect in Flags)
or CompareSrcIdentifiers(Node.StartPos,Params.Identifier)
then begin
{$IFDEF ShowTriedIdentifiers}
DebugLn(' SearchInGenericParams Identifier found="',GetIdentifier(@Src[Node.StartPos]),'" at '+CleanPosToStr(Node.StartPos));
{$ENDIF}
// identifier found
Params.SetResult(Self,Node);
Result:=CheckResult(true,true);
if not (fdfCollect in Flags) then
exit;
end;
Node:=Node.NextBrother;
end;
end;
function SearchInTypeVarConstGlobPropDefinition: boolean;
// returns: true if ok to exit
// false if search should continue
var
NameNode: TCodeTreeNode;
begin
Result:=false;
NameNode:=ContextNode;
if ContextNode.Desc=ctnGenericType then begin
NameNode:=ContextNode.FirstChild;
if NameNode=nil then exit;
end;
if (fdfCollect in Flags)
or CompareSrcIdentifiers(NameNode.StartPos,Params.Identifier)
then begin
{$IFDEF ShowTriedIdentifiers}
DebugLn(' Definition Identifier found="',GetIdentifier(Params.Identifier),'"');
{$ENDIF}
// identifier found
Params.SetResult(Self,ContextNode);
Result:=CheckResult(true,true);
if not (fdfCollect in Flags) then begin
if (fdfSkipClassForward in Flags)
and (ContextNode.FirstChild<>nil)
and (ContextNode.FirstChild.Desc in AllClasses)
and ((ctnsForwardDeclaration and ContextNode.FirstChild.SubDesc)<>0)
then begin
FindNonForwardClass(Params);
end;
exit;
end;
end;
// search for enums
Params.ContextNode:=ContextNode;
if FindEnumInContext(Params) then begin
Result:=CheckResult(true,false);
end;
end;
function SearchInGenericType: boolean;
// returns: true if ok to exit
// false if search should continue
var
NameNode: TCodeTreeNode;
begin
Result:=false;
NameNode:=ContextNode.FirstChild;
if NameNode=nil then exit;
// try type name
if (fdfCollect in Flags)
or CompareSrcIdentifiers(NameNode.StartPos,Params.Identifier)
then begin
{$IFDEF ShowTriedIdentifiers}
DebugLn(' Definition Identifier found="',GetIdentifier(Params.Identifier),'"');
{$ENDIF}
// identifier found
Params.SetResult(Self,ContextNode);
Result:=CheckResult(true,true);
if not (fdfCollect in Flags) then begin
if (fdfSkipClassForward in Flags)
and (ContextNode.LastChild.Desc in AllClasses)
and ((ctnsForwardDeclaration and ContextNode.LastChild.SubDesc)<>0)
then begin
FindNonForwardClass(Params);
end;
exit;
end;
end;
// search for enums
Params.ContextNode:=ContextNode;
if FindEnumInContext(Params) then begin
Result:=CheckResult(true,false);
end;
end;
function SearchInTypeOfVarConst: boolean;
// returns: true if ok to exit
// false if search should continue
begin
Result:=false;
//debugln(['SearchInTypeOfVarConst ',ContextNode.Parent.DescAsString]);
if (ContextNode.Parent.Desc in [ctnConstDefinition,ctnVarDefinition])
and (Src[ContextNode.StartPos]='(') then
begin
if FindIdentifierInTypeOfConstant(ContextNode.Parent,Params) then begin
Result:=CheckResult(true,false);
end;
end;
end;
function SearchInEnumLabelDefinition: boolean;
// returns: true if ok to exit
// false if search should continue
begin
Result:=false;
if (fdfCollect in Flags)
or CompareSrcIdentifiers(ContextNode.StartPos,Params.Identifier)
then begin
{$IFDEF ShowTriedIdentifiers}
DebugLn(' Enum/Label Identifier found="',GetIdentifier(Params.Identifier),'"');
{$ENDIF}
// identifier found
Params.SetResult(Self,ContextNode);
Result:=CheckResult(true,true);
if not (fdfCollect in Flags) then begin
exit;
end;
end;
end;
function SearchInOnBlockDefinition: boolean;
begin
Result:=false;
if ContextNode.FirstChild=nil then exit;
//debugln('SearchInOnBlockDefinition B ',GetIdentifier(@Src[ContextNode.StartPos]));
if (fdfCollect in Flags)
or CompareSrcIdentifiers(ContextNode.FirstChild.StartPos,Params.Identifier)
then begin
{$IFDEF ShowTriedIdentifiers}
DebugLn(' ON Identifier found="',GetIdentifier(Params.Identifier),'"');
{$ENDIF}
// identifier found
Params.SetResult(Self,ContextNode.FirstChild);
Result:=CheckResult(true,true);
if not (fdfCollect in Flags) then
exit;
end;
end;
function SearchInSourceName: boolean;
// returns: true if ok to exit
// false if search should continue
var
SrcNode: TCodeTreeNode;
begin
Result:=false;
SrcNode:=Tree.Root;
MoveCursorToNodeStart(SrcNode);
ReadNextAtom; // read keyword
if (SrcNode.Desc=ctnProgram) and (not UpAtomIs('PROGRAM')) then exit;
ReadNextAtom; // read name
if (fdfCollect in Flags)
or CompareSrcIdentifiers(CurPos.StartPos,Params.Identifier) then
begin
// identifier found
{$IFDEF ShowTriedIdentifiers}
if not (fdfCollect in Flags) then
DebugLn(' Source Name Identifier found="',GetIdentifier(Params.Identifier),'"');
{$ENDIF}
Params.SetResult(Self,SrcNode,CurPos.StartPos);
Result:=CheckResult(true,true);
if not (fdfCollect in Flags) then
exit;
end;
end;
function SearchDefault: boolean;
begin
Result:=false;
if SearchInSourceName then
exit(true);
if (not (fdfIgnoreUsedUnits in Flags))
and FindIdentifierInHiddenUsedUnits(Params) then begin
Result:=CheckResult(true,false);
end;
end;
function SearchInProperty: boolean;
// search in ctnProperty, not ctnGlobalProperty
// returns: true if ok to exit
// false if search should continue
begin
Result:=false;
if (fdfCollect in Flags)
or (Params.Identifier[0]<>'[') then begin
MoveCursorToNodeStart(ContextNode);
ReadNextAtom; // read keyword 'property'
if UpAtomIs('CLASS') then ReadNextAtom;
ReadNextAtom; // read name
if (fdfCollect in Flags)
or CompareSrcIdentifiers(CurPos.StartPos,Params.Identifier) then begin
// identifier found
{$IFDEF ShowTriedIdentifiers}
DebugLn(' Property Identifier found="',GetIdentifier(Params.Identifier),'"');
{$ENDIF}
Params.SetResult(Self,ContextNode,CurPos.StartPos);
Result:=CheckResult(true,true);
end;
end else begin
// the default property is searched
if PropertyIsDefault(ContextNode) then begin
Params.SetResult(Self,ContextNode);
Result:=CheckResult(true,true);
end;
end;
end;
function LeavingContextIsPermitted: boolean;
begin
Result:=true;
if (not ContextNode.HasAsParent(StartContextNode)) then begin
// searching in a prior node, will leave the start context
if (not (fdfSearchInParentNodes in Flags)) then begin
// searching in any parent context is not permitted
if not ((fdfSearchInAncestors in Flags)
and (ContextNode.Desc in AllClasses)) then begin
// even searching in ancestors contexts is not permitted
// -> there is no prior context accessible any more
// -> identifier not found
{$IFDEF ShowTriedContexts}
DebugLn('[TFindDeclarationTool.FindIdentifierInContext] no prior node accessible ',
' ContextNode=',ContextNode.DescAsString,
' "',StringToPascalConst(copy(Src,ContextNode.StartPos,15)),'"'
);
{$ENDIF}
ContextNode:=nil;
Result:=false;
end;
end;
end;
end;
function SearchInHelpers: Boolean;
var
HelperContext: TFindContext;
Helpers: TFDHelpersList;
HelperKind: TFDHelpersListKind;
HelperIterator: TAVLTreeNode;
begin
Result := False;
SearchInHelpersInTheEnd := False;
if StartContextNode.Desc=ctnObjCClass then
HelperKind:=fdhlkObjCCategory
else
HelperKind:=fdhlkDelphiHelper;
Helpers:=Params.GetHelpers(HelperKind);
if Helpers=nil then exit;
if not Helpers.IterateFromClassNode(StartContextNode,Self,
HelperContext,HelperIterator) then exit;
//debugln(['SearchInHelpers START at least one helper found, iterating...']);
//Helpers.WriteDebugReport;
repeat
//debugln(['SearchInHelpers searching in Helper=',FindContextToString(HelperContext),'...']);
OldFlags := Params.Flags;
try
Params.Flags:=Params.Flags
-[fdfExceptionOnNotFound,fdfIgnoreCurContextNode,fdfSearchInHelpers]
+[fdfIgnoreUsedUnits];
Params.ContextNode := HelperContext.Node;
if HelperContext.Tool.FindIdentifierInContext(Params, IdentFoundResult) then
begin
if (IdentFoundResult = ifrAbortSearch)
or ((IdentFoundResult = ifrSuccess) and CheckResult(true,False))
then
Result := True;
end;
finally
Params.Flags := OldFlags;
end;
until (HelperKind=fdhlkDelphiHelper) or (not Helpers.GetNext(HelperContext,HelperIterator));
//debugln(['SearchInHelpers END']);
end;
function SearchInNamespaces(SourceNamespaceNode: TCodeTreeNode): Boolean;
// SourceNamespaceNode.Desc = ctnUseUnitNamespace
// search all use-unit nodes with the same namespace prefix as SourceNamespaceNode
var
UnitNode, ThisNamespaceNode, TargetNamespaceNode, UsesNode: TCodeTreeNode;
Level, CurLevel: Integer;
InFilename, AnUnitName, FoundNames, FoundName: String;
NewCodeTool: TFindDeclarationTool;
begin
Result := False;
if SourceNamespaceNode.Desc<>ctnUseUnitNamespace then
RaiseException(20170426102058,'');
//debugln(['SearchInNamespaces ',ExtractNode(SourceNamespaceNode.Parent,[]),' ',fdfCollect in Flags]);
if not (fdfCollect in Flags) then begin
// search a specific identifier within a use-unit name
if (SourceNamespaceNode.NextBrother<>nil)
and (
(Params.Identifier=nil) or
CompareSrcIdentifiers(SourceNamespaceNode.NextBrother.StartPos,Params.Identifier))
then begin
Params.SetResult(Self,SourceNamespaceNode.NextBrother);
Result:=CheckResult(true,true);
end;
exit;
end;
// collect all uses-units with same namespace
UsesNode:=SourceNamespaceNode.Parent.Parent;
Level:=1;
while SourceNamespaceNode.PriorBrother<>nil do begin
inc(Level);
SourceNamespaceNode:=SourceNamespaceNode.PriorBrother;
end;
FoundNames:='';
UnitNode := UsesNode.LastChild;
while UnitNode<>nil do
begin
ThisNamespaceNode := SourceNamespaceNode;
TargetNamespaceNode := UnitNode.FirstChild;
CurLevel:=0;
while (ThisNamespaceNode<>nil) and (TargetNamespaceNode<>nil) do
begin
if CompareIdentifierPtrs(
@Src[ThisNamespaceNode.StartPos],
@Src[TargetNamespaceNode.StartPos]) <> 0
then Break;
inc(CurLevel);
if CurLevel=Level then break;
ThisNamespaceNode := ThisNamespaceNode.NextBrother;
TargetNamespaceNode := TargetNamespaceNode.NextBrother;
end;
if CurLevel=Level then
begin
// namespace paths match
//debugln(['SearchInNamespaces Match ',ExtractNode(TargetNamespaceNode.Parent,[])]);
if (TargetNamespaceNode.NextBrother<>nil) then begin
// prefix matches
FoundName:='('+GetIdentifier(@Src[TargetNamespaceNode.NextBrother.StartPos])+')';
if (Pos(FoundName,FoundNames)<1)
and ((Params.Identifier=nil)
or CompareSrcIdentifiers(TargetNamespaceNode.NextBrother.StartPos,Params.Identifier))
then begin
FoundNames:=FoundNames+FoundName;
Params.SetResult(Self,TargetNamespaceNode.NextBrother);
Result:=CheckResult(true,true);
end;
end else begin
// whole unit name matches -> list all interface identifiers
AnUnitName:=ExtractUsedUnitName(UnitNode,@InFilename);
NewCodeTool:=FindCodeToolForUsedUnit(AnUnitName,InFilename,true);
NewCodeTool.FindIdentifierInInterface(Params.IdentifierTool,Params);
end;
end;
if UnitNode.PriorBrother<>nil then
UnitNode := UnitNode.PriorBrother
else if UnitNode.Parent.Desc=ctnImplementation then begin
UnitNode:=FindMainUsesNode;
if UnitNode=nil then break;
UnitNode:=UnitNode.LastChild;
end else
break;
end;
end;
function SearchNextNode: boolean;
const
AbortNoCacheResult = false;
Proceed = true;
begin
repeat
// search for prior node
{$IFDEF ShowTriedIdentifiers}
DebugLn('[TFindDeclarationTool.FindIdentifierInContext.SearchNextNode] Searching prior node of ',ContextNode.DescAsString,' ',dbgstr(copy(Src,ContextNode.StartPos,ContextNode.EndPos-ContextNode.StartPos)));
{$ENDIF}
LastSearchedNode:=ContextNode;
if (ContextNode.Desc in AllClasses) then begin
// after searching in a class definition ...
if (ContextNode.PriorBrother<>nil) and (ContextNode.PriorBrother.Desc=ctnGenericParams)
then begin
// before searching in the ancestors, search in the generic parameters
if SearchInGenericParams(ContextNode.PriorBrother) then begin
FindIdentifierInContext:=true;
{$IFDEF ShowCollect}
if fdfCollect in Flags then
raise Exception.Create('fdfCollect must never return true');
{$ENDIF}
exit(AbortNoCacheResult);
end;
end;
//allow ctnRecordType and ctnTypeTypeBeforeHelper: they can have helpers!
if (fdfSearchInAncestors in Flags) then begin
// after searching in a class definition, search in its ancestors
// ToDo: check for cycles in ancestors
OldFlags := Params.Flags;
Params.Flags:=Params.Flags-[fdfExceptionOnNotFound,fdfSearchInHelpersInTheEnd];
// leaving current class -> check if search in helpers in the end
if SearchInHelpersInTheEnd then
begin
Result := SearchInHelpers;
Params.Flags := OldFlags;
if Result then
begin
FindIdentifierInContext:=true;
Exit(AbortNoCacheResult);
end;
end;
Exclude(Params.Flags,fdfExceptionOnNotFound);
Result:=FindIdentifierInAncestors(ContextNode,Params,IdentFoundResult);
Params.Flags := OldFlags;
if Result then begin
FindIdentifierInContext:=true;
{$IFDEF ShowCollect}
if fdfCollect in Flags then
raise Exception.Create('fdfCollect must never return true');
{$ENDIF}
exit(AbortNoCacheResult);
end;
end;
// if this was a nested class, the identifier can be in the ancestors
// of the enclosing class
Flags:=Flags+[fdfSearchInAncestors];
end else if ContextNode.Desc=ctnClassInheritance then begin
if (StartContextNode=ContextNode)
or StartContextNode.HasAsParent(ContextNode) then
// searching an ancestor => don't search within ancestors
Exclude(Flags,fdfSearchInAncestors);
end;
if (ContextNode=StartContextNode)
and (not (fdfSearchInParentNodes in Flags)) then begin
// startcontext completed => not searching in parents or ancestors
ContextNode:=nil;
exit(Proceed);
end;
if ((not (fdfSearchForward in Flags))
and (ContextNode.PriorBrother<>nil))
or ((fdfSearchForward in Flags)
and (ContextNode.NextBrother<>nil)
and (ContextNode.NextBrother.Desc<>ctnImplementation)) then
begin
// search next in prior/next brother
if not (fdfSearchForward in Flags) then
ContextNode:=ContextNode.PriorBrother
else begin
RaiseLastErrorIfInFrontOfCleanedPos(ContextNode.NextBrother.EndPos);
ContextNode:=ContextNode.NextBrother;
end;
{$IFDEF ShowTriedIdentifiers}
DebugLn('[TFindDeclarationTool.FindIdentifierInContext] Searching in Brother ContextNode=',ContextNode.DescAsString);
{$ENDIF}
// it is not always allowed to search in every node on the same lvl:
// -> test if class visibility valid
if ContextNode.Desc in AllClassSections then
break
else if ContextNode.Desc=ctnWithVariable then begin
{ check if StartContextNode is covered by the ContextNode
a WithVariable ranges from the start of its expression
to the end of the with statement
for example:
will be skipped:
with ContextNode do ;
with B do StartContextNode;
will be searched:
with ContextNode, StartContextNode do ;
}
{$IFDEF ShowExprEval}
DebugLn('SearchNextNode WithVar StartContextNode.StartPos=',dbgs(StartContextNode.StartPos),
' ContextNode=',dbgs(ContextNode.StartPos),'-',dbgs(ContextNode.EndPos),
' WithStart=',StringToPascalConst(
copy(copy(Src,ContextNode.StartPos,ContextNode.EndPos-ContextNode.StartPos),1,50)));
{$ENDIF}
if (StartContextNode.StartPos>=ContextNode.StartPos)
and (StartContextNode.StartPos<ContextNode.EndPos) then begin
{$IFDEF ShowExprEval}
debugln(['SearchNextNode WithVar covers startcontext']);
{$ENDIF}
// for example: with ContextNode, StartContextNode do ;
break;
end else begin
// this with statement does not cover the startcontext. For instance:
// with ContextNode do ;
// with B do StartContextNode;
// -> skip it
end;
end else if ContextNode.Desc=ctnOnBlock then begin
// the ctnOnIdentifier is only valid within the ctnOnStatement
// => skip
end else begin
break;
end;
end else if (ContextNode.Parent<>nil)
and ((fdfSearchInParentNodes in Flags)
or (ContextNode.HasAsParent(StartContextNode))) then
begin
// search next in parent
{$IFDEF ShowTriedParentContexts}
DebugLn('[TFindDeclarationTool.FindIdentifierInContext] Searching in Parent ',
' old ContextNode=',ContextNode.DescAsString,
' new ContextNode=',ContextNode.Parent.DescAsString
);
{$ENDIF}
ContextNode:=ContextNode.Parent;
case ContextNode.Desc of
ctnTypeSection, ctnVarSection, ctnConstSection, ctnResStrSection,
ctnLabelSection, ctnPropertySection,
ctnInterface, ctnImplementation, ctnProgram, ctnLibrary,
ctnClassPublished,ctnClassPublic,ctnClassProtected,ctnClassPrivate,
ctnClassClassVar,
ctnRecordVariant,
ctnProcedureHead, ctnParameterList,
ctnClassInheritance,ctnHelperFor:
// these codetreenodes build a parent-child-relationship, but
// for pascal it is only a range, hence after searching in the
// children of the last node, search must continue in the children
// of the prior node
;
ctnClass, ctnClassInterface, ctnDispinterface, ctnObject,
ctnObjCClass, ctnObjCCategory, ctnObjCProtocol, ctnCPPClass,
ctnRecordType, ctnRecordCase,
ctnClassHelper, ctnRecordHelper, ctnTypeHelper,
ctnEnumerationType:
// do not search again in this node, go on ...
;
ctnVarDefinition, ctnConstDefinition:
if (ContextNode.Parent<>nil)
and (ContextNode.Parent.Desc=ctnParameterList) then begin
// pascal allows declarations like: 'var a: a;' in parameters
// -> skip variable and search in next context node
;
end else begin
break;
end;
ctnProcedure:
begin
Result:=FindIdentifierInClassOfMethod(ContextNode,Params);
if Result then begin
FindIdentifierInContext:=true;
{$IFDEF ShowCollect}
if fdfCollect in Flags then
raise Exception.Create('fdfCollect must never return true');
{$ENDIF}
exit(AbortNoCacheResult);
end;
end;
else
break;
end;
end else begin
ContextNode:=nil;
break;
end;
until false;
Result:=Proceed;
end;
begin
Result:=false;
InitNodesAndCacheAccess;
{$IFDEF ShowTriedContexts}
DebugLn('[TFindDeclarationTool.FindIdentifierInContext] Start Ident=',
'"'+GetIdentifier(Params.Identifier)+'"',
' Context="'+ContextNode.DescAsString+'" "'+StringToPascalConst(copy(Src,ContextNode.StartPos,20)),'"',
' at '+CleanPosToStr(ContextNode.StartPos,true),
' Flags=['+dbgs(Flags)+']'
);
{$ELSE}
{$IFDEF ShowCollect}
if fdfCollect in Flags then begin
DebugLn(['[TFindDeclarationTool.FindIdentifierInContext] COLLECT Start Ident=',
'"',GetIdentifier(Params.Identifier),'"',
' Context="',ContextNode.DescAsString,'" "',copy(Src,ContextNode.StartPos,20),'"',
' at '+CleanPosToStr(ContextNode.StartPos,true),
' Flags=[',dbgs(Flags),']'
]);
end;
{$ENDIF}
{$ENDIF}
if (ContextNode.Desc=ctnInterface)
and (fdfIgnoreUsedUnits in Flags) then begin
{$IFDEF ShowTriedContexts}
DebugLn(['TFindDeclarationTool.FindIdentifierInContext searching in interface of ',MainFilename]);
{$ENDIF}
Result:=FindIdentifierInInterface(Params.IdentifierTool,Params);
CheckResult(Result,false);
exit;
end;
if (ContextNode.Desc=ctnUseUnitNamespace) then
begin
//search in namespaces
//debugln(['TFindDeclarationTool.FindIdentifierInContext NameSpace ',GetIdentifier(Params.Identifier),' ',ExtractNode(ContextNode,[])]);
if SearchInNamespaces(ContextNode) then exit;
Exit;
end;
// find class helper functions
SearchInHelpersInTheEnd := False;
if (fdfSearchInHelpers in Flags)
and (ContextNode.Desc in [ctnClass,ctnRecordType,ctnTypeType,ctnObjCClass,ctnEnumerationType,ctnRangedArrayType,ctnOpenArrayType])
and (ContextNode.Parent<>nil) and (ContextNode.Parent.Desc = ctnTypeDefinition)
then begin
if (fdfSearchInHelpersInTheEnd in Flags) then
SearchInHelpersInTheEnd := True
else begin
if SearchInHelpers then Exit;
end;
end;
//try
// search in the Tree of this tool
repeat
{$IFDEF ShowTriedIdentifiers}
DebugLn('[TFindDeclarationTool.FindIdentifierInContext] Loop Ident=',
'"',GetIdentifier(Params.Identifier),'"',
' Context="',ContextNode.DescAsString,'" "',copy(Src,ContextNode.StartPos,20),'"',
' Flags=[',dbgs(Flags),']'
);
{$ELSE}
{$IFDEF ShowCollect}
if fdfCollect in Flags then begin
DebugLn('[TFindDeclarationTool.FindIdentifierInContext] COLLECT Loop Ident=',
'"',GetIdentifier(Params.Identifier),'"',
' Context="',ContextNode.DescAsString,'" "',copy(Src,ContextNode.StartPos,20),'"',
' Flags=[',dbgs(Flags),']'
);
end;
{$ENDIF}
{$ENDIF}
// search identifier in current context
LastContextNode:=ContextNode;
if not (fdfIgnoreCurContextNode in Flags) then begin
// search in cache
if FindInNodeCache then begin
if CheckResult(Params.NewNode<>nil,Params.NewNode<>nil) then
exit;
end;
if FirstSearchedNode=nil then FirstSearchedNode:=ContextNode;
LastSearchedNode:=ContextNode;
case ContextNode.Desc of
ctnTypeSection, ctnVarSection, ctnConstSection, ctnResStrSection,
ctnLabelSection, ctnPropertySection,
ctnInterface, ctnImplementation,
ctnProgram, ctnLibrary,
ctnClassPublic, ctnClassPrivate, ctnClassProtected, ctnClassPublished,
ctnClassClassVar,
ctnClass, ctnClassInterface, ctnDispinterface, ctnObject,
ctnObjCClass, ctnObjCCategory, ctnObjCProtocol, ctnCPPClass,
ctnRecordType, ctnRecordVariant,
ctnClassHelper, ctnRecordHelper, ctnTypeHelper,
ctnEnumerationType,
ctnParameterList:
// these nodes build a parent-child relationship. But in pascal
// they just define a range and not a context.
// -> search in all children
MoveContextNodeToChildren;
ctnTypeDefinition, ctnVarDefinition, ctnConstDefinition,
ctnGlobalProperty:
if SearchInTypeVarConstGlobPropDefinition then exit;
ctnGenericType:
if SearchInGenericType then exit;
// ctnGenericParams: skip here, it was searched before searching the ancestors
ctnIdentifier:
if (ContextNode.Parent.Desc in [ctnConstDefinition,ctnVarDefinition])
and (ContextNode=ContextNode.Parent.LastChild)
and SearchInTypeOfVarConst then exit;
ctnEnumIdentifier,ctnLabel:
if SearchInEnumLabelDefinition then exit;
ctnProcedure:
begin
IdentifierFoundResult:=
FindIdentifierInProcContext(ContextNode,Params);
if IdentifierFoundResult in [ifrAbortSearch,ifrSuccess] then begin
if CheckResult(IdentifierFoundResult=ifrSuccess,true) then begin
{$IFDEF ShowProcSearch}
DebugLn(['TFindDeclarationTool.FindIdentifierInContext ctnProcedure FOUND, stopping']);
{$ENDIF}
exit;
end;
{$IFDEF ShowProcSearch}
DebugLn(['TFindDeclarationTool.FindIdentifierInContext ctnProcedure FOUND, continue']);
{$ENDIF}
end;
end;
ctnProcedureHead:
begin
BuildSubTreeForProcHead(ContextNode);
if ContextNode.FirstChild<>nil then
ContextNode:=ContextNode.FirstChild; // the ctnParameterList
end;
ctnProperty:
if SearchInProperty then exit;
ctnUsesSection:
begin
if FindIdentifierInUsesSection(ContextNode,Params,True)
and CheckResult(true,false) then
exit;
end;
ctnWithVariable:
begin
if FindIdentifierInWithVarContext(ContextNode,Params)
and CheckResult(true,false) then
exit;
end;
ctnOnBlock:
if SearchInOnBlockDefinition then exit;
ctnPointerType,ctnClassOfType:
begin
// pointer and class-of can be forward definitions
// -> search in both directions
Params.ContextNode:=ContextNode.Parent;
if CheckResult(FindForwardIdentifier(Params,IsForward),false) then
exit;
end;
ctnRecordCase:
begin
// search in variable and variants
MoveContextNodeToChildren;
end;
end;
end else begin
Exclude(Params.Flags,fdfIgnoreCurContextNode);
Exclude(Flags,fdfIgnoreCurContextNode);
{$IFDEF ShowTriedContexts}
DebugLn('[TFindDeclarationTool.FindIdentifierInContext] IgnoreCurContext ');
{$ENDIF}
end;
if LastContextNode=ContextNode then begin
// no special context switch => search next node
if not LeavingContextIsPermitted then break;
if not SearchNextNode then exit;
end;
until ContextNode=nil;
if SearchInHelpersInTheEnd then
begin
if SearchInHelpers then Exit;
end;
if LastSearchedNode=Tree.Root then begin
if SearchDefault then exit;
end;
{except
// unexpected exception
on E: Exception do begin
DebugLn('*** Unexpected Exception during find declaration: ',
E.ClassName,': ',E.Message);
DebugLn(' MainFilename=',MainFilename);
raise;
end;
end;}
// if we are here, the identifier was not found and there was no error
if (FirstSearchedNode<>nil) and (Params.FoundProc=nil)
and ([fdfCollect,fdfExtractOperand]*Flags=[]) then begin
// add result to cache
Params.NewNode:=nil;
Params.NewCodeTool:=nil;
AddResultToNodeCaches(FirstSearchedNode,LastSearchedNode,
fdfSearchForward in Flags,Params,SearchRangeFlags);
end;
CheckResult(false,false);
end;
function TFindDeclarationTool.FindEnumInContext(
Params: TFindDeclarationParams): boolean;
{ search all subnodes for ctnEnumIdentifier
Params:
Identifier
ContextNode // = DeepestNode at Cursor
Result:
true, if enum found
}
var OldContextNode, CurContextNode: TCodeTreeNode;
CollectResult: TIdentifierFoundResult;
SearchEnumIdentifiers: Boolean;
begin
Result:=false;
CurContextNode:=Params.ContextNode;
if CurContextNode=nil then exit;
if CurContextNode.Desc=ctnEnumerationType then
SearchEnumIdentifiers := not (Scanner.GetDirectiveValueAt(sdScopedEnums, CurContextNode.StartPos) = '1')
else
SearchEnumIdentifiers := False;
CurContextNode:=CurContextNode.FirstChild;
while CurContextNode<>nil do begin
if SearchEnumIdentifiers and (CurContextNode.Desc=ctnEnumIdentifier) then begin
if (fdfCollect in Params.Flags) then begin
//debugln('TFindDeclarationTool.FindEnumInContext ',GetIdentifier(@Src[CurContextNode.StartPos]));
CollectResult:=DoOnIdentifierFound(Params,CurContextNode);
if CollectResult=ifrAbortSearch then begin
Result:=false;
exit;
end else if CollectResult=ifrSuccess then begin
Result:=true;
Params.SetResult(Self,CurContextNode);
exit;
end;
end else if CompareSrcIdentifiers(CurContextNode.StartPos,Params.Identifier)
then begin
// identifier found
Result:=true;
Params.SetResult(Self,CurContextNode);
exit;
end;
end;
if CurContextNode.FirstChild<>nil then begin
OldContextNode:=Params.ContextNode;
Params.ContextNode:=CurContextNode;
Result:=FindEnumInContext(Params);
Params.ContextNode:=OldContextNode;
if Result then exit;
end;
CurContextNode:=CurContextNode.NextBrother;
end;
end;
function TFindDeclarationTool.FindContextNodeAtCursor(
Params: TFindDeclarationParams): TFindContext;
{ searches for the context node at a specific cursor pos
Params.Context should contain the deepest node at cursor
if there is no special context, then result is equal to Params.Context }
var
EndPos: integer;
ExprType: TExpressionType;
OldFlags: TFindDeclarationFlags;
begin
EndPos:=CurPos.StartPos;
OldFlags:=Params.Flags;
Params.Flags:=Params.Flags-[fdfFindVariable];
ExprType:=FindExpressionTypeOfTerm(-1,EndPos,Params,false);
Params.Flags:=OldFlags;
if (ExprType.Desc=xtContext) then
Result:=ExprType.Context
else begin
Result:=CleanFindContext;
if fdfExceptionOnNotFound in Params.Flags then begin
MoveCursorToCleanPos(EndPos);
RaiseException(20170421200111,ctsNoContextNodeFoundAtCursor);
end;
end;
end;
function TFindDeclarationTool.FindBaseTypeOfNode(
Params: TFindDeclarationParams; Node: TCodeTreeNode; AliasType: PFindContext;
NodeStack: PCodeTreeNodeStack): TFindContext;
var
MyNodeStack: TCodeTreeNodeStack;
procedure RaiseForwardClassNameLess;
begin
RaiseException(20170421200114,'[TFindDeclarationTool.FindBaseTypeOfNode] '
+'forward class node without name');
end;
procedure RaiseCircleDefs;
begin
Params.NewCodeTool.RaiseException(20170421200117,ctsCircleInDefinitions
+' ('+ctsIdentifier+'='+GetIdentifier(Params.Identifier)+')');
end;
procedure RaiseInternalError;
begin
Params.IdentifierTool.RaiseException(20170421200121,
'[TFindDeclarationTool.FindBaseTypeOfNode]'
+' internal error: not IsPCharInSrc(Params.Identifier) '
+' Params.IdentifierTool.='
+TCodeBuffer(Params.IdentifierTool.Scanner.MainCode).Filename
+' Ident="'+GetIdentifier(Params.Identifier)+'"');
end;
procedure RaiseBaseTypeOfNotFound;
begin
RaiseExceptionFmt(20170421200124,ctsBaseTypeOfNotFound,[GetIdentifier(Params.Identifier)]);
end;
procedure RaiseClassOfWithoutIdentifier;
begin
RaiseExceptionFmt(20170421200133,ctsBaseTypeOfNotFound+' ("class of")',
[GetIdentifier(Params.Identifier)]);
end;
procedure RaiseForwardNotResolved(ClassIdentNode: TCodeTreeNode);
begin
RaiseExceptionFmt(20170421200136,ctsForwardClassDefinitionNotResolved,
[copy(Src,ClassIdentNode.StartPos,
ClassIdentNode.EndPos-ClassIdentNode.StartPos)]);
end;
procedure RaiseClassOfNotResolved(ClassIdentNode: TCodeTreeNode);
begin
MoveCursorToNodeStart(ClassIdentNode);
RaiseExceptionFmt(20170421200141,ctsClassOfDefinitionNotResolved,
[copy(Src,ClassIdentNode.StartPos,
ClassIdentNode.EndPos-ClassIdentNode.StartPos)]);
end;
procedure SearchIdentifier(StartNode: TCodeTreeNode; CleanPos: integer;
out IsPredefined: boolean; var Context: TFindContext);
var
TypeFound: Boolean;
TestContext: TFindContext;
IdentStart: LongInt;
SubParams: TFindDeclarationParams;
ExprType: TExpressionType;
begin
IsPredefined:=false;
SubParams:=TFindDeclarationParams.Create(Params);
try
SubParams.GenParams := Params.GenParams;
IdentStart:=CleanPos;
{$IFDEF ShowTriedBaseContexts}
debugln(['TFindDeclarationTool.FindBaseTypeOfNode.SearchIdentifier Identifier=',GetIdentifier(@Src[IdentStart])]);
{$ENDIF}
SubParams.Flags:=[fdfSearchInParentNodes,fdfExceptionOnNotFound]
+(fdfGlobals*SubParams.Flags);
SubParams.ContextNode:=StartNode.Parent;
if (SubParams.ContextNode.Desc in (AllIdentifierDefinitions))
then begin
// pascal allows things like 'var a: a;' -> skip var definition
Include(SubParams.Flags,fdfIgnoreCurContextNode);
end;
if SubParams.ContextNode.Desc=ctnParameterList then
// skip search in parameter list
SubParams.ContextNode:=SubParams.ContextNode.Parent;
if SubParams.ContextNode.Desc=ctnProcedureHead then
// skip search in proc parameters
SubParams.ContextNode:=SubParams.ContextNode.Parent;
MoveCursorToCleanPos(CleanPos);
ReadNextAtom;
ReadNextAtom;
if (CurPos.Flag=cafPoint) or AtomIsChar('<') then begin
// this is an expression, e.g. A.B or A<B>
Include(SubParams.Flags,fdfFindVariable);
ExprType:=FindExpressionTypeOfTerm(CleanPos,-1,SubParams,false);
if ExprType.Desc=xtContext then begin
if not (ExprType.Context.Node.Desc in [ctnTypeDefinition,ctnGenericType,ctnGenericParameter]) then
begin
// not a type
{$IFDEF ShowTriedBaseContexts}
debugln(['TFindDeclarationTool.FindBaseTypeOfNode.SearchIdentifier expression: type expected but found ',ExprTypeToString(ExprType)]);
{$ENDIF}
MoveCursorToCleanPos(IdentStart);
ReadNextAtom;
RaiseExceptionFmt(20170421200144,ctsStrExpectedButAtomFound,
[ctsTypeIdentifier,GetAtom]);
end;
Context:=ExprType.Context;
end else begin
IsPredefined:=true;
end;
exit;
end;
SubParams.SetIdentifier(Self,@Src[IdentStart],nil);
TypeFound:=FindIdentifierInContext(SubParams);
if TypeFound and (SubParams.NewNode.Desc in [ctnUnit,ctnLibrary,ctnPackage])
then begin
// identifier is a unit
// => type expected
MoveCursorToCleanPos(IdentStart);
ReadNextAtom; // read AUnitName
SaveRaiseCharExpectedButAtomFound(20170421200146,'.');
end;
if TypeFound and (SubParams.NewNode.Desc=ctnGenericParameter) then begin
TypeFound:=SubParams.FindGenericParamType;
end;
if TypeFound then begin
// only types allowed here
TestContext.Tool:=SubParams.NewCodeTool;
TestContext.Node:=SubParams.NewNode;
if not (TestContext.Node.Desc in [ctnTypeDefinition,ctnGenericType,ctnGenericParameter]) then
begin
// not a type
{$IFDEF ShowTriedBaseContexts}
debugln(['TFindDeclarationTool.FindBaseTypeOfNode.SearchIdentifier expected type but found ',TestContext.Node.DescAsString]);
{$ENDIF}
MoveCursorToCleanPos(IdentStart);
ReadNextAtom;
RaiseExceptionFmt(20170421200149,ctsStrExpectedButAtomFound,
[ctsTypeIdentifier,GetAtom]);
end;
Context:=TestContext;
{$IFDEF ShowTriedBaseContexts}
debugln(['TFindDeclarationTool.FindBaseTypeOfNode.SearchIdentifier found ',GetIdentifier(@Src[IdentStart]),' Node=',Context.Node.DescAsString,' ',Context.Tool.CleanPosToStr(Context.Node.StartPos,true)]);
{$ENDIF}
end else begin
// predefined identifier
IsPredefined:=true;
end;
finally
SubParams.Free;
end;
end;
procedure CheckResult(var Context: TFindContext);
var
ResultNode: TCodeTreeNode;
OldFlags: TFindDeclarationFlags;
AliasContext: TFindContext;
Cache: TBaseTypeCache;
begin
if (NodeStack<>nil) and (NodeStack<>@MyNodeStack) then exit; // will be handled by caller
if (Context.Node<>nil) and (Context.Node.Desc in [ctnProcedure,ctnProcedureHead])
and (fdfFunctionResult in Params.Flags) then begin
// Note: do not resolve a constructor here
// because TMyClass.Create should return TMyClass
// and not TObject, where the Create is defined
// a proc -> if this is a function then return the Context type
//debugln(['TFindDeclarationTool.FindBaseTypeOfNode checking function Context: ',Context.Tool.ExtractNode(Context.Node,[])]);
Context.Tool.BuildSubTreeForProcHead(Context.Node,ResultNode);
if (ResultNode<>nil) then begin
// a function or an overloaded operator
// search further for the base type of the function Context type
OldFlags:=Params.Flags;
Exclude(Params.Flags,fdfFunctionResult);
//debugln(['TFindDeclarationTool.FindBaseTypeOfNode searching for function Context type: ',Context.Tool.ExtractNode(DummyNode,[])]);
Context:=Context.Tool.FindBaseTypeOfNode(Params,ResultNode,AliasType);
AliasType:=nil; // aliasing has been done
Params.Flags:=OldFlags;
exit;
end;
end;
if (Context.Node=nil) and (fdfExceptionOnNotFound in Params.Flags) then begin
if (Context.Tool<>nil) and (Params.Identifier<>nil) then begin
// ToDo ppu, dcu
if (not Params.IdentifierTool.IsPCharInSrc(Params.Identifier)) then
RaiseInternalError;
Params.IdentifierTool.MoveCursorToCleanPos(Params.Identifier);
end;
RaiseBaseTypeOfNotFound;
end;
if AliasType<>nil then begin
// follow the base type chain to the first type
// for example: var d: TDateTime; use TDateTime, instead of Double.
AliasContext.Node:=Node;
AliasContext.Tool:=Self;
while AliasContext.Node<>nil do begin
if AliasContext.Node.Desc in [ctnTypeDefinition,ctnGenericType] then begin
{$IF defined(ShowExprEval) or defined(ShowTriedBaseContexts)}
debugln(['TFindDeclarationTool.FindBaseTypeOfNode.CheckResult using alias ',AliasContext.Tool.ExtractDefinitionName(AliasContext.Node),' instead of base type ',Context.Node.DescAsString]);
{$ENDIF}
AliasType^:=AliasContext;
exit;
end;
if AliasContext.Node.Cache is TBaseTypeCache then begin
Cache:=TBaseTypeCache(AliasContext.Node.Cache);
if AliasContext.Node=Cache.NextNode then break;
AliasContext.Node:=Cache.NextNode;
AliasContext.Tool:=TFindDeclarationTool(Cache.NextTool);
end else
break;
end;
end;
end;
var
OldInput: TFindDeclarationInput;
ClassIdentNode: TCodeTreeNode;
TestContext: TFindContext;
OldPos: integer;
SpecializeNode: TCodeTreeNode;
NameNode: TCodeTreeNode;
IsPredefined: boolean;
OldStartFlags: TFindDeclarationFlags;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(Node);{$ENDIF}
//debugln(['TFindDeclarationTool.FindBaseTypeOfNode Flags=[',dbgs(Params.Flags),'] CacheValid=',Node.Cache is TBaseTypeCache]);
if (Node<>nil) and (Node.Cache is TBaseTypeCache) then begin
// base type already cached
Result:=CreateFindContext(TBaseTypeCache(Node.Cache));
CheckResult(Result);
exit;
end;
Result.Node:=Node;
Result.Tool:=Self;
OldStartFlags:=Params.Flags;
Exclude(Params.Flags,fdfTopLvlResolving);
if NodeStack=nil then begin
NodeStack:=@MyNodeStack;
InitializeNodeStack(NodeStack);
end;
try
while (Result.Node<>nil) do begin
if (Result.Node.Cache is TBaseTypeCache) then begin
// base type already cached
if NodeStack^.StackPtr>=0 then
AddNodeToStack(NodeStack,Result.Tool,Result.Node);
Result:=CreateFindContext(TBaseTypeCache(Result.Node.Cache));
break;
end;
{$IFDEF ShowTriedBaseContexts}
DebugLn('[TFindDeclarationTool.FindBaseTypeOfNode] LOOP Result=',Result.Node.DescAsString,' ',Result.Tool.CleanPosToStr(Result.Node.StartPos,true),' Flags=[',dbgs(Params.Flags),']');
{$ENDIF}
if NodeExistsInStack(NodeStack,Result.Node) then begin
// cycle detected
Result.Tool.MoveCursorToNodeStart(Result.Node);
Result.Tool.RaiseException(20170421200151,ctsCircleInDefinitions);
end;
{$IFDEF CheckNodeTool}Result.Tool.CheckNodeTool(Result.Node);{$ENDIF}
if Result.Tool<>Self then begin
{$IFDEF ShowTriedBaseContexts}
DebugLn(['[TFindDeclarationTool.FindBaseTypeOfNode] continuing in ',Result.Tool.MainFilename]);
{$ENDIF}
Result:=Result.Tool.FindBaseTypeOfNode(Params,Result.Node,AliasType,NodeStack);
break;
end;
AddNodeToStack(NodeStack,Result.Tool,Result.Node);
if (Result.Node.Desc in (AllSimpleIdentifierDefinitions+[ctnGenericType]))
then begin
// instead of variable/const/type definition, return the type
TestContext.Node:=FindTypeNodeOfDefinition(Result.Node);
if TestContext.Node=nil then
// some constants and variants do not have a type
break;
Result.Node:=TestContext.Node;
end else
if (Result.Node.Desc in AllClasses)
and ((Result.Node.SubDesc and ctnsForwardDeclaration)>0) then
begin
// this is a forward defined class
// -> search the real class
{$IFDEF ShowTriedBaseContexts}
DebugLn('[TFindDeclarationTool.FindBaseTypeOfNode] Class is forward');
{$ENDIF}
// ToDo: check for cycles in ancestor chain
ClassIdentNode:=Result.Node.Parent;
if (ClassIdentNode=nil)
or (not (ClassIdentNode.Desc in [ctnTypeDefinition,ctnGenericType]))
then begin
MoveCursorToCleanPos(Result.Node.StartPos);
RaiseForwardClassNameLess;
end;
Params.Save(OldInput);
Params.SetIdentifier(Self,@Src[ClassIdentNode.StartPos],
@CheckSrcIdentifier);
Params.Flags:=[fdfSearchInParentNodes,fdfSearchForward,
fdfIgnoreUsedUnits,fdfExceptionOnNotFound,
fdfIgnoreCurContextNode]
+(fdfGlobals*Params.Flags);
Params.ContextNode:=ClassIdentNode;
FindIdentifierInContext(Params);
if (not (Params.NewNode.Desc in [ctnTypeDefinition,ctnGenericType]))
or (Params.NewCodeTool<>Self) then begin
MoveCursorToCleanPos(Result.Node.StartPos);
RaiseForwardNotResolved(ClassIdentNode);
end;
Result.Tool:=Params.NewCodeTool;
Result.Node:=Params.NewNode;
Params.Load(OldInput,true);
end else
if (Result.Node.Desc=ctnClassOfType) and (fdfFindChildren in Params.Flags)
then begin
// this is a 'class of' type
// -> search the real class
{$IFDEF ShowTriedBaseContexts}
DebugLn('[TFindDeclarationTool.FindBaseTypeOfNode] "Class Of"');
{$ENDIF}
// ToDo: check for cycles in ancestor chain
ClassIdentNode:=Result.Node.FirstChild;
if (ClassIdentNode=nil) or (not (ClassIdentNode.Desc=ctnIdentifier))
then begin
MoveCursorToCleanPos(Result.Node.StartPos);
RaiseClassOfWithoutIdentifier;
end;
Params.Save(OldInput);
// first search backwards
Params.SetIdentifier(Self,@Src[ClassIdentNode.StartPos],
@CheckSrcIdentifier);
Params.Flags:=[fdfSearchInParentNodes,
fdfIgnoreCurContextNode]
+(fdfGlobals*Params.Flags)-[fdfExceptionOnNotFound];
Params.ContextNode:=Result.Node.Parent;
if not FindIdentifierInContext(Params) then begin
// then search forwards
Params.Load(OldInput,false);
Params.SetIdentifier(Self,@Src[ClassIdentNode.StartPos],
@CheckSrcIdentifier);
Params.Flags:=[fdfSearchInParentNodes,fdfExceptionOnNotFound,
fdfIgnoreCurContextNode,fdfSearchForward]
+(fdfGlobals*Params.Flags);
Params.ContextNode:=Result.Node.Parent;
FindIdentifierInContext(Params);
end;
if not (Params.NewNode.Desc in [ctnTypeDefinition,ctnGenericType]) then
begin
MoveCursorToCleanPos(Result.Node.StartPos);
RaiseClassOfNotResolved(ClassIdentNode);
end;
Result.Tool:=Params.NewCodeTool;
Result.Node:=Params.NewNode;
Params.Load(OldInput,true);
end else
if (Result.Node.Desc=ctnOnIdentifier) and (Result.Node.PriorBrother=nil)
then begin
// this is the ON variable node, the type comes right behind
Result.Node:=Result.Node.NextBrother;
end else if Result.Node.Desc=ctnSrcName then begin
break;
end else if (Result.Node.Desc=ctnIdentifier)
and (Result.Node.Parent.Desc=ctnSrcName) then begin
if (Result.Node.NextBrother=nil) then
Result.Node:=Result.Node.Parent;
break;
end else
if (Result.Node.Desc in [ctnIdentifier,ctnOnIdentifier])
then begin
// this type is just an alias for another type
// -> search the basic type
if Result.Node.Parent=nil then
break;
SearchIdentifier(Result.Node,Result.Node.StartPos,IsPredefined,Result);
if IsPredefined then break;
end else
if (Result.Node.Desc=ctnProperty)
or (Result.Node.Desc=ctnGlobalProperty) then begin
// this is a property -> search the type definition of the property
if MoveCursorToPropType(Result.Node) then begin
// property has a type
SearchIdentifier(Result.Node,CurPos.StartPos,IsPredefined,Result);
if IsPredefined then break;
end else if (Result.Node.Desc=ctnProperty) then begin
// property has no type
// -> search ancestor property
Params.Save(OldInput);
if not MoveCursorToPropName(Result.Node) then break;
OldPos:=CurPos.StartPos;
Params.SetIdentifier(Self,@Src[CurPos.StartPos],nil);
Params.Flags:=[fdfExceptionOnNotFound,fdfSearchInAncestors,fdfSearchInHelpers]
+(fdfGlobalsSameIdent*Params.Flags);
FindIdentifierInAncestors(Result.Node.Parent.Parent,Params);
TestContext.Tool:=Params.NewCodeTool;
TestContext.Node:=Params.NewNode;
Params.Load(OldInput,true);
if Params.NewNode.Desc<>ctnProperty then begin
// ancestor is not a property
MoveCursorToCleanPos(OldPos);
RaiseException(20170421200153,ctsAncestorIsNotProperty);
end;
Result:=TestContext;
end else
break;
end else
if Result.Node.Desc=ctnProcedure then begin
Result.Node:=Result.Node.FirstChild;
break;
end else
if Result.Node.Desc=ctnProcedureHead then begin
break;
end else
if (Result.Node.Desc=ctnTypeType) then begin
if fdfTypeType in Params.Flags then
break; // the type node is wanted, not its real type
// a TypeType is for example 'MyInt = type integer;'
// the context is not the 'type' keyword, but the identifier after it.
Result.Node:=Result.Node.FirstChild;
end else
if (Result.Node.Desc=ctnEnumIdentifier) then begin
// an enum identifier
if fdfEnumIdentifier in Params.Flags then
break; // the enum is wanted, not its type
// an enum identifier, the base type is the enumeration
Result.Node:=Result.Node.Parent;
end else
if (Result.Node.Desc=ctnSpecialize) then begin
// go to the type name of the specialisation
SpecializeNode:=Result.Node;
NameNode:=SpecializeNode.FirstChild;
Result.Node:=NameNode;
if Result.Node=nil then break;
Params.SetGenericParamValues(Self, SpecializeNode);
SearchIdentifier(SpecializeNode,NameNode.StartPos,IsPredefined,Result);
if (Result.Node=nil) or (Result.Node.Desc<>ctnGenericType) then begin
// not a generic
MoveCursorToNodeStart(NameNode);
ReadNextAtom;
RaiseExceptionFmt(20170421200156,ctsStrExpectedButAtomFound,
[ctsGenericIdentifier,GetAtom]);
end;
end else
break;
end;
Params.Flags:=OldStartFlags;
finally
if NodeStack=@MyNodeStack then begin
// cache the result in all nodes
// do not cache the result of generic type
if not Assigned(Params.GenParams.ParamValuesTool) then
CreateBaseTypeCaches(NodeStack,Result);
// free node stack
FinalizeNodeStack(NodeStack);
end;
end;
CheckResult(Result);
{$IFDEF ShowFoundIdentifier}
Debugln(['[TFindDeclarationTool.FindBaseTypeOfNode] END Node=',Node.DescAsString,' Result=',Result.Node.DescAsString]);
{$ENDIF}
end;
function TFindDeclarationTool.FindIdentifierInBasicTypeHelpers(
ExprType: TExpressionTypeDesc; Params: TFindDeclarationParams): Boolean;
var
OldFlags: TFindDeclarationFlags;
FullExprType: TExpressionType;
CHContext: TFindContext;
Helpers: TFDHelpersList;
begin
Helpers:=Params.GetHelpers(fdhlkDelphiHelper);
if Helpers=nil then exit(false);
FullExprType := CleanExpressionType;
FullExprType.Desc := ExprType;
case FullExprType.Desc of
xtConstString: FullExprType.Desc:=GetDefaultStringType;
xtConstOrdInteger: FullExprType.Desc:=xtLongint;
xtConstBoolean: FullExprType.Desc:=xtBoolean;
xtConstReal: FullExprType.Desc:=xtDouble;
end;
//debugln(['TFindDeclarationTool.FindIdentifierInBasicTypeHelpers ',ExprTypeToString(FullExprType)]);
// find class helper functions
CHContext := Helpers.FindFromExprType(FullExprType);
if Assigned(CHContext.Node) and Assigned(CHContext.Tool) then
begin
OldFlags := Params.Flags;
try
Exclude(Params.Flags, fdfExceptionOnNotFound);
Exclude(Params.Flags, fdfIgnoreCurContextNode);
Include(Params.Flags, fdfIgnoreUsedUnits);
Params.ContextNode := CHContext.Node;
Result := CHContext.Tool.FindIdentifierInContext(Params);
finally
Params.Flags := OldFlags;
end;
end else
Result := False;
end;
function TFindDeclarationTool.FindDeclarationAndOverload(
const CursorPos: TCodeXYPosition; out ListOfPCodeXYPosition: TFPList;
Flags: TFindDeclarationListFlags): boolean;
var
CurCursorPos: TCodeXYPosition;
NewTool: TFindDeclarationTool;
NewNode: TCodeTreeNode;
NewPos: TCodeXYPosition;
NewTopLine: integer;
CurTool: TFindDeclarationTool;
OldPositions: TFPList;
NodeList: TFPList;
CleanPos: integer;
AtDefinition: Boolean;
procedure AddPos;
begin
AddCodePosition(OldPositions,NewPos);
if (NodeList.IndexOf(NewNode)>=0) then begin
{$IFDEF VerboseFindDeclarationAndOverload}
debugln(['AddPos skip, because Node already in NodList']);
{$ENDIF}
exit;
end;
if (fdlfOneOverloadPerUnit in Flags)
and (NodeList.Count>0)
and (TCodeTreeNode(NodeList[NodeList.Count-1]).GetRoot=NewTool.Tree.Root)
then begin
{$IFDEF VerboseFindDeclarationAndOverload}
debugln(['AddPos skip, because in same unit']);
{$ENDIF}
exit;
end;
NodeList.Add(NewNode);
if (fdlfWithoutEmptyProperties in Flags)
and (NewNode.Desc=ctnProperty)
and (NewTool.PropNodeIsTypeLess(NewNode)) then begin
{$IFDEF VerboseFindDeclarationAndOverload}
debugln(['AddPos skip, because property has no type']);
{$ENDIF}
exit;
end;
if (fdlfWithoutForwards in Flags) then begin
if (NewNode.Desc in [ctnTypeDefinition,ctnGenericType])
and NewTool.NodeIsForwardDeclaration(NewNode) then begin
{$IFDEF VerboseFindDeclarationAndOverload}
debugln(['AddPos skip, because type is forward']);
{$ENDIF}
exit;
end;
if (NewNode.Desc=ctnProcedure)
and ((NewNode.SubDesc and ctnsForwardDeclaration)>0)
and (not NewNode.HasParentOfType(ctnInterface)) then begin
{$IFDEF VerboseFindDeclarationAndOverload}
debugln(['AddPos skip, because proc is forward']);
{$ENDIF}
exit;
end;
end;
AddCodePosition(ListOfPCodeXYPosition,NewPos);
end;
function StartPositionAtDefinition: boolean;
begin
if (NewNode.Desc in AllIdentifierDefinitions)
and (PositionInDefinitionName(NewNode,CleanPos)) then
Result:=true
else if (NewNode.Desc in [ctnProcedure,ctnProcedureHead])
and (PositionInProcName(NewNode,false,CleanPos)) then
Result:=true
else if (NewNode.Desc in [ctnProperty,ctnGlobalProperty])
and (PositionInPropertyName(NewNode,CleanPos)) then
Result:=true
else if (NewNode.Desc in AllSourceTypes)
and (PositionInSourceName(CleanPos)) then
Result:=true
else
Result:=false;
end;
function StartPositionAtFunctionResult: boolean;
var
Node: TCodeTreeNode;
begin
Result:=false;
if (NewNode.Desc in [ctnProcedureHead,ctnIdentifier])
and PositionInFuncResultName(NewNode,CleanPos) then begin
Node:=NewNode;
if Node.Desc=ctnProcedureHead then begin
Node:=Node.FirstChild;
if Node=nil then exit;
if Node.Desc=ctnParameterList then Node:=Node.NextBrother;
if Node=nil then exit;
end;
if Node.Desc in [ctnVarDefinition,ctnIdentifier] then begin
// return the function result type or the operator variable name
NewNode:=Node;
Result:=true;
end;
end;
end;
begin
{$IFDEF VerboseFindDeclarationAndOverload}
debugln(['TFindDeclarationTool.FindDeclarationAndOverload START']);
{$ENDIF}
Result:=true;
ListOfPCodeXYPosition:=nil;
NewTool:=nil;
NewNode:=nil;
OldPositions:=nil;
NodeList:=nil;
ActivateGlobalWriteLock;
try
BuildTreeAndGetCleanPos(trTillCursorSection,lsrEnd,CursorPos,CleanPos,[]);
NodeList:=TFPList.Create;
NewTool:=Self;
NewNode:=BuildSubTreeAndFindDeepestNodeAtPos(CleanPos,true);
NewPos:=CursorPos;
AtDefinition:=StartPositionAtDefinition;
if AtDefinition then begin
AddPos;
if fdlfIfStartIsDefinitionStop in Flags then begin
{$IFDEF VerboseFindDeclarationAndOverload}
debugln(['TFindDeclarationTool.FindDeclarationAndOverload AtDefiniton and fdlfIfStartIsDefinitionStop in Flags']);
{$ENDIF}
exit;
end;
end;
if StartPositionAtFunctionResult then begin
AddPos;
// the function result has no overloads => stop search
{$IFDEF VerboseFindDeclarationAndOverload}
debugln(['TFindDeclarationTool.FindDeclarationAndOverload function result has no overloads']);
{$ENDIF}
exit;
end;
if NewNode.Desc in AllSourceTypes then begin
// the unit name has no overloads => stop search
{$IFDEF VerboseFindDeclarationAndOverload}
debugln(['TFindDeclarationTool.FindDeclarationAndOverload unit name has no overload']);
{$ENDIF}
exit;
end;
CurCursorPos:=CursorPos;
CurTool:=Self;
try
while CurTool.FindDeclaration(CurCursorPos,DefaultFindSmartFlags
+[fsfSearchSourceName],
NewTool,NewNode,NewPos,NewTopLine) do
begin
if IndexOfCodePosition(OldPositions,@NewPos)>=0 then break;
AddPos;
CurCursorPos:=NewPos;
CurTool:=NewTool;
{$IFDEF VerboseFindDeclarationAndOverload}
debugln('TFindDeclarationTool.FindDeclarationAndOverload Self="',MainFilename,'" ');
if CurCursorPos.Code<>nil then
debugln(' CurCursorPos=',CurCursorPos.Code.Filename,' ',dbgs(CurCursorPos.X),',',dbgs(CurCursorPos.Y));
if CurTool<>nil then
debugln(' CurTool=',CurTool.MainFilename);
{$ENDIF}
if (CurTool=nil) then exit;
end;
except
// ignore normal errors
on E: ECodeToolError do ;
on E: ELinkScannerError do ;
end;
finally
FreeListOfPCodeXYPosition(OldPositions);
NodeList.Free;
DeactivateGlobalWriteLock;
end;
end;
function TFindDeclarationTool.FindIdentifierContextsAtStatement(CleanPos: integer;
out IsSubIdentifier: boolean; out ListOfPFindContext: TFPList): boolean;
var
Params: TFindDeclarationParams;
CursorNode: TCodeTreeNode;
Node: TCodeTreeNode;
Context: TFindContext;
WithNode: TCodeTreeNode;
ExprType: TExpressionType;
begin
Result:=false;
IsSubIdentifier:=false;
ListOfPFindContext:=nil;
CursorNode:=FindDeepestNodeAtPos(CleanPos,true);
if not (CursorNode.Desc in AllPascalStatements) then begin
debugln(['TFindDeclarationTool.FindIdentifierContextsAtStatement CursorNode.Desc=',CursorNode.DescAsString]);
exit;
end;
// check expression in front
MoveCursorToCleanPos(CleanPos);
ReadPriorAtom;
if CurPos.Flag=cafPoint then begin
// sub identifier
// for example A.Identifier
IsSubIdentifier:=true;
// search the context of A and add it to the ListOfPFindContext
Params:=TFindDeclarationParams.Create(Self, CursorNode);
try
Params.ContextNode:=CursorNode;
Params.Flags:=[fdfSearchInParentNodes,fdfSearchInAncestors,fdfSearchInHelpers,
fdfTopLvlResolving,fdfFunctionResult];
ExprType:=FindExpressionTypeOfTerm(-1,CleanPos,Params,false);
finally
Params.Free;
end;
if ExprType.Desc=xtContext then
AddFindContext(ListOfPFindContext,ExprType.Context);
end else begin
// not a sub identifier
BuildSubTree(CursorNode);
CursorNode:=FindDeepestNodeAtPos(CursorNode,CleanPos,true);
Node:=CursorNode;
while Node<>nil do begin
case Node.Desc of
ctnWithStatement:
begin
// add all With contexts
WithNode:=Node.Parent;
while WithNode<>nil do begin
if WithNode.Desc<>ctnWithVariable then break;
Params:=TFindDeclarationParams.Create(Self, WithNode);
try
Params.ContextNode:=WithNode;
Params.Flags:=[fdfExceptionOnNotFound,fdfSearchInAncestors,fdfSearchInHelpers,
fdfSearchInParentNodes,fdfFunctionResult,fdfIgnoreCurContextNode,
fdfFindChildren];
ExprType:=FindExpressionResultType(Params,WithNode.StartPos,-1);
if ExprType.Desc=xtContext then
AddFindContext(ListOfPFindContext,ExprType.Context);
finally
Params.Free;
end;
WithNode:=WithNode.PriorBrother;
end;
end;
ctnProcedure:
begin
// add procedure context
Context.Node:=Node;
Context.Tool:=Self;
AddFindContext(ListOfPFindContext,Context);
if NodeIsMethodBody(Node) then begin
// add class context
Context.Node:=FindClassNodeForMethodBody(Node,true,false);
if Context.Node<>nil then begin
Context.Tool:=Self;
AddFindContext(ListOfPFindContext,Context);
end;
end;
end;
ctnImplementation:
begin
Context.Node:=Node;
Context.Tool:=Self;
AddFindContext(ListOfPFindContext,Context);
end;
end;
Node:=Node.Parent;
end;
end;
Result:=true;
end;
function TFindDeclarationTool.FindIdentifierInAncestors(
ClassNode: TCodeTreeNode; Params: TFindDeclarationParams): boolean;
var
IdentFoundResult: TIdentifierFoundResult;
begin
Result := FindIdentifierInAncestors(ClassNode, Params, IdentFoundResult{%H-});
end;
function TFindDeclarationTool.FindClassAndAncestors(ClassNode: TCodeTreeNode;
var ListOfPFindContext: TFPList; ExceptionOnNotFound: boolean): boolean;
var
Params: TFindDeclarationParams;
function Search: boolean;
var
CurTool: TFindDeclarationTool;
FoundContext: TFindContext;
begin
CurTool:=Self;
while CurTool.FindAncestorOfClass(ClassNode,Params,true) do begin
if (Params.NewCodeTool=nil) then break;
FoundContext.Tool:=Params.NewCodeTool;
FoundContext.Node:=Params.NewNode;
if IndexOfFindContext(ListOfPFindContext,@FoundContext)>=0 then break;
AddFindContext(ListOfPFindContext,FoundContext);
//debugln('TFindDeclarationTool.FindClassAndAncestors FoundContext=',DbgsFC(FoundContext));
CurTool:=Params.NewCodeTool;
ClassNode:=Params.NewNode;
if (ClassNode=nil)
or (not (ClassNode.Desc in AllClasses)) then
break;
end;
Result:=true;
end;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(ClassNode);{$ENDIF}
Result:=false;
if (ClassNode=nil) or (not (ClassNode.Desc in AllClasses))
or (ClassNode.Parent=nil)
or (not (ClassNode.Parent.Desc in [ctnTypeDefinition,ctnGenericType])) then
exit;
AddFindContext(ListOfPFindContext,CreateFindContext(Self,ClassNode));
Params:=TFindDeclarationParams.Create;
ActivateGlobalWriteLock;
try
if ExceptionOnNotFound then
Result:=Search
else begin
try
Result:=Search;
except
// catch syntax errors
on E: ECodeToolError do ;
on E: ELinkScannerError do ;
end;
end;
finally
DeactivateGlobalWriteLock;
Params.Free;
end;
end;
procedure TFindDeclarationTool.FindHelpersInContext(
Params: TFindDeclarationParams);
var
Node: TCodeTreeNode;
begin
Node:=Params.StartNode;
Params.FNeedHelpers:=false;
while Node<>nil do
begin
case Node.Desc of
ctnClassHelper, ctnRecordHelper, ctnTypeHelper:
if (Node.Parent.Desc = ctnTypeDefinition) then
Params.GetHelpers(fdhlkDelphiHelper,true).AddFromHelperNode(Node, Self,
False{ keep last found Helper }
);
ctnObjCCategory:
if (Node.Parent.Desc = ctnTypeDefinition) then
Params.GetHelpers(fdhlkObjCCategory,true).AddFromHelperNode(Node, Self, False);
ctnUsesSection:
FindHelpersInUsesSection(Node, Params);
end;
Node := Node.Prior;
end;
end;
procedure TFindDeclarationTool.FindHelpersInInterface(
AskingTool: TFindDeclarationTool; Params: TFindDeclarationParams);
var
HelperKind: TFDHelpersListKind;
Cache: TFDHelpersList;
begin
// build tree for pascal source
if not BuildInterfaceIdentifierCache(true) then exit;
if (AskingTool<>Self) and (AskingTool<>nil) then
begin
AskingTool.AddToolDependency(Self);
for HelperKind in TFDHelpersListKind do begin
Cache:=FInterfaceHelperCache[HelperKind];
if (Cache<>nil) and (Cache.Count>0) then
Params.GetHelpers(HelperKind,true).AddFromList(FInterfaceHelperCache[HelperKind]);
end;
end;
end;
procedure TFindDeclarationTool.FindHelpersInUsesSection(
UsesNode: TCodeTreeNode; Params: TFindDeclarationParams);
var
NewCodeTool: TFindDeclarationTool;
Node: TCodeTreeNode;
AnUnitName: string;
InFilename: string;
begin
// search in units
//debugln(['TFindDeclarationTool.FindHelpersInUsesSection START ',CleanPosToStr(UsesNode.StartPos,true),' Main=',MainFilename]);
Node:=UsesNode.LastChild;
while Node<>nil do begin
AnUnitName:=ExtractUsedUnitName(Node,@InFilename);
if AnUnitName<>'' then begin
//debugln(['TFindDeclarationTool.FindHelpersInUsesSection ',CleanPosToStr(Node.StartPos),' AnUnitName="',AnUnitName,'" in "',InFilename,'"']);
NewCodeTool:=FindCodeToolForUsedUnit(AnUnitName,InFilename,false);
if NewCodeTool<>nil then begin
// search the identifier in the interface of the used unit
NewCodeTool.FindHelpersInInterface(Self,Params);
end;
end;
Node:=Node.PriorBrother;
end;
end;
function TFindDeclarationTool.FindContextClassAndAncestorsAndExtendedClassOfHelper
(const CursorPos: TCodeXYPosition; var ListOfPFindContext: TFPList): boolean;
// returns a list of nodes of AllClasses (ctnClass, ...)
var
CleanCursorPos: integer;
ANode: TCodeTreeNode;
ClassNode: TCodeTreeNode;
ExtendedClassExpr: TExpressionType;
begin
Result:=false;
ListOfPFindContext:=nil;
ActivateGlobalWriteLock;
try
BuildTreeAndGetCleanPos(trTillCursor,lsrEnd,CursorPos,CleanCursorPos,
[btSetIgnoreErrorPos]);
// find class node
ANode:=FindDeepestNodeAtPos(CleanCursorPos,true);
if (ANode.GetNodeOfType(ctnClassInheritance)<>nil) then
exit;
ClassNode:=FindClassNode(ANode);
if (ClassNode=nil) or (ClassNode.Parent=nil)
or (not (ClassNode.Parent.Desc in [ctnTypeDefinition,ctnGenericType])) then
exit;
//debugln('TFindDeclarationTool.FindContextClassAndAncestors A ClassName=',ExtractClassName(ClassNode,false));
// add class and ancestors type definition to ListOfPCodeXYPosition
if not FindClassAndAncestors(ClassNode,ListOfPFindContext,true)
then exit;
//find extended class node
ExtendedClassExpr := FindExtendedExprOfHelper(ClassNode);
if ((ExtendedClassExpr.Desc=xtContext) and (ExtendedClassExpr.Context.Tool<>nil) and
(ExtendedClassExpr.Context.Node<>nil) and (ExtendedClassExpr.Context.Node.Desc=ctnClass)) then
begin
if not ExtendedClassExpr.Context.Tool.FindClassAndAncestors(ExtendedClassExpr.Context.Node,ListOfPFindContext,true)
then exit;
end;
//debugln('TFindDeclarationTool.FindContextClassAndAncestors List: ',ListOfPFindContextToStr(ListOfPFindContext));
finally
DeactivateGlobalWriteLock;
end;
Result:=true;
end;
function TFindDeclarationTool.FindDefaultAncestorOfClass(
ClassNode: TCodeTreeNode; Params: TFindDeclarationParams;
FindClassContext: boolean): boolean;
var
OldInput: TFindDeclarationInput;
AncestorNode, ClassIdentNode: TCodeTreeNode;
AncestorContext: TFindContext;
BaseClassName: PChar;
procedure RaiseBaseClassNotFound;
begin
MoveCursorToNodeStart(ClassNode);
if BaseClassName='TObject' then
RaiseException(20170421200159,ctsDefaultClassAncestorTObjectNotFound)
else if BaseClassName='IInterface' then
RaiseException(20170421200202,ctsDefaultInterfaceAncestorIInterfaceNotFound)
else if BaseClassName='IDispatch' then
RaiseException(20170421200205,ctsDefaultDispinterfaceAncestorIDispatchNotFound)
else if BaseClassName='JLObject' then
RaiseException(20170421200207,ctsDefaultJavaClassAncestorJLObjectNotFound)
else
RaiseExceptionFmt(20170421200210,ctsDefaultAncestorNotFound, [BaseClassName]);
end;
begin
//debugln(['TFindDeclarationTool.FindAncestorOfClass ',CleanPosToStr(ClassNode.StartPos,true)]);
{$IFDEF CheckNodeTool}CheckNodeTool(ClassNode);{$ENDIF}
if (ClassNode=nil) or (not (ClassNode.Desc in AllClasses))
then
RaiseException(20170421200213,'[TFindDeclarationTool.FindDefaultAncestorOfClass] '
+' invalid classnode');
Result:=false;
// ToDo: ppu, dcu
// no ancestor class specified
ClassIdentNode:=ClassNode.Parent;
// check class name
if (ClassIdentNode<>nil)
and (not (ClassIdentNode.Desc in [ctnTypeDefinition,ctnGenericType])) then
begin
debugln(['TFindDeclarationTool.FindDefaultAncestorOfClass not a type']);
exit;
end;
BaseClassName:=nil;
case ClassNode.Desc of
ctnClass:
if Scanner.Values.IsDefined('CPUJVM') then
BaseClassName:='JLObject'
else if (Scanner.PascalCompiler=pcPas2js)
and (FindClassExternalNode(ClassNode)<>nil) then
exit // external root class has no ancestor
else
BaseClassName:='TObject';
ctnDispinterface:
// default interface is IDispatch
BaseClassName:='IDispatch';
ctnClassInterface:
begin
if Scanner.Values.IsDefined('CPUJVM') then
exit; // JVM has no default interface
// Delphi has as default interface IInterface
// FPC has as default interface IUnknown and an alias IInterface = IUnknown
if CompareSrcIdentifiers(ClassIdentNode.StartPos,'IUnknown') then exit;
BaseClassName:='IInterface';
end
else
exit; // has no default ancestor (e.g. record)
end;
if CompareSrcIdentifiers(ClassIdentNode.StartPos,BaseClassName) then
exit; // this is already the base class
{$IFDEF ShowTriedContexts}
DebugLn('[TFindDeclarationTool.FindAncestorOfClass] ',
' search default ancestor class '+BaseClassName);
{$ENDIF}
// search default ancestor
Params.Save(OldInput);
Params.Flags:=[fdfSearchInParentNodes,fdfIgnoreCurContextNode,
fdfExceptionOnNotFound]
+(fdfGlobals*Params.Flags)
-[fdfTopLvlResolving];
Params.SetIdentifier(Self,BaseClassName,nil);
Params.ContextNode:=ClassNode;
if not FindIdentifierInContext(Params) then
RaiseBaseClassNotFound;
// check result
if not (Params.NewNode.Desc in [ctnTypeDefinition,ctnGenericType]) then
RaiseBaseClassNotFound;
// search ancestor class context
if FindClassContext then begin
AncestorNode:=Params.NewNode;
Params.Flags:=Params.Flags+[fdfFindChildren];
AncestorContext:=Params.NewCodeTool.FindBaseTypeOfNode(Params,
AncestorNode);
Params.SetResult(AncestorContext);
// check result
if Params.NewNode.Desc<>ClassNode.Desc then
RaiseBaseClassNotFound;
end;
Result:=true;
Params.Load(OldInput,true);
end;
{-------------------------------------------------------------------------------
function TFindDeclarationTool.FindReferences(const CursorPos: TCodeXYPosition;
SkipComments: boolean; var ListOfPCodeXYPosition: TFPList): boolean;
Search for all identifiers in current unit, referring to the declaration
at CursorPos.
-------------------------------------------------------------------------------}
function TFindDeclarationTool.FindReferences(const CursorPos: TCodeXYPosition;
SkipComments: boolean; out ListOfPCodeXYPosition: TFPList): boolean;
var
DeclarationFound: boolean;
Identifier: string;
CleanDeclCursorPos: integer;
DeclarationTool: TFindDeclarationTool;
DeclarationNode: TCodeTreeNode;
AliasDeclarationNode: TCodeTreeNode; // if exists: always in front of DeclarationNode
Params: TFindDeclarationParams;
PosTree: TAVLTree; // tree of PChar positions in Src
ReferencePos: TCodeXYPosition;
MinPos, MaxPos: Integer;
CursorNode: TCodeTreeNode;
UnitStartFound, Found: Boolean;
StartPos: integer; // keep this here, it is modified at several places
procedure AddReference(ACleanPos: integer);
var
p: PChar;
begin
if PosTree=nil then
PosTree:=TAVLTree.Create;
p:=@Src[ACleanPos];
//debugln('TFindDeclarationTool.FindReferences.AddReference ',CleanPosToStr(ACleanPos),' ',dbgs(PosTree.Find(p)=nil),' Code=',dbgstr(copy(Src,ACleanPos-8,8)+'|'+dbgstr(copy(Src,ACleanPos,5))));
if PosTree.Find(p)=nil then
PosTree.Add(p);
end;
procedure AddNodeReference(Node: TCodeTreeNode);
var
p: LongInt;
begin
p:=Node.StartPos;
if Node.Desc in [ctnProcedure,ctnProcedureHead] then begin
MoveCursorToProcName(Node,true);
p:=CurPos.StartPos;
end else if Node.Desc in [ctnProperty,ctnGlobalProperty] then begin
MoveCursorToPropName(Node);
p:=CurPos.StartPos;
end;
AddReference(p);
end;
procedure UseProcHead(var Node: TCodeTreeNode);
begin
if Node=nil then exit;
if (Node.Desc=ctnProcedure)
and (Node.FirstChild<>nil)
and (Node.FirstChild.Desc=ctnProcedureHead) then
Node:=Node.FirstChild;
end;
procedure ReadIdentifier(IsComment: boolean);
var
IdentStartPos: Integer;
IdentEndPos: integer;
begin
if (not IsComment) then
UnitStartFound:=true;
IdentStartPos:=StartPos;
IdentEndPos:=IdentStartPos;
while (IdentEndPos<=MaxPos) and (IsIdentChar[Src[IdentEndPos]]) do
inc(IdentEndPos);
StartPos:=IdentEndPos;
//debugln(['ReadIdentifier ',CleanPosToStr(IdentStartPos,true),' ',copy(Src,IdentStartPos,IdentEndPos-IdentStartPos),' ',CompareIdentifiers(PChar(Pointer(Identifier)),@Src[IdentStartPos])]);
if IdentEndPos-IdentStartPos<>length(Identifier) then exit;
if CompareIdentifiers(PChar(Pointer(Identifier)),@Src[IdentStartPos])<>0 then exit;
if IsComment and (SkipComments or (not UnitStartFound)) then exit;
{debugln(['Identifier with same name found at: ',
IdentStartPos,'=',CleanPosToStr(StartPos),' ',GetIdentifier(@Src[IdentStartPos]),
' CleanDeclCursorPos=',CleanDeclCursorPos,
' MaxPos=',MaxPos,
' IsComment=',IsComment,
' SkipComments=',SkipComments,
' UnitStartFound=',UnitStartFound
]);}
CursorNode:=BuildSubTreeAndFindDeepestNodeAtPos(IdentStartPos,true);
//debugln(' CursorNode=',CursorNode.DescAsString,' Forward=',dbgs(CursorNode.SubDesc and ctnsForwardDeclaration));
if (DeclarationTool=Self)
and ((IdentStartPos=CleanDeclCursorPos) or (CursorNode=AliasDeclarationNode))
then begin
// declaration itself found
//debugln(['ReadIdentifier declaration itself found, adding ...']);
AddReference(IdentStartPos)
end
else if CleanPosIsDeclarationIdentifier(IdentStartPos,CursorNode) then
// this identifier is another declaration with the same name
else begin
// find declaration
if Params=nil then
Params:=TFindDeclarationParams.Create(Self, CursorNode)
else
Params.Clear;
Params.Flags:=[fdfSearchInParentNodes,fdfSearchInAncestors,fdfSearchInHelpers,
fdfIgnoreCurContextNode];
Params.ContextNode:=CursorNode;
//debugln(copy(Src,Params.ContextNode.StartPos,200));
Params.SetIdentifier(Self,@Src[IdentStartPos],@CheckSrcIdentifier);
// search identifier in comment -> if not found, this is no bug
// => silently ignore
try
Found:=FindDeclarationOfIdentAtParam(Params);
except
on E: ECodeToolError do begin
if E.Sender<>Self then begin
// there is an error in another unit, which prevents searching
// stop further searching in this unit
raise;
end;
// continue
end;
on E: Exception do
raise;
end;
//debugln(' Found=',dbgs(Found));
if Found and (Params.NewNode<>nil) then begin
UseProcHead(Params.NewNode);
//debugln('Context=',Params.NewNode.DescAsString,' ',dbgs(Params.NewNode.StartPos),' ',dbgs(DeclarationNode.StartPos));
if (Params.NewNode=DeclarationNode)
or (Params.NewNode=AliasDeclarationNode) then begin
//debugln(['ReadIdentifier reference found, adding ...']);
AddReference(IdentStartPos);
end;
end;
end;
end;
procedure SearchIdentifiers;
var
CommentLvl: Integer;
InStrConst: Boolean;
begin
StartPos:=MinPos;
UnitStartFound:=false;
while StartPos<=MaxPos do begin
case Src[StartPos] of
'{':
begin
inc(StartPos);
if (StartPos<=MaxPos) and (Src[StartPos]=#3) then begin
// codetools skip comment {#3 #3}
inc(StartPos);
while (StartPos<=MaxPos) do begin
if (Src[StartPos]=#3) and (StartPos<MaxPos) and (Src[StartPos+1]='}')
then begin
inc(StartPos,2);
break;
end;
inc(StartPos);
end;
end else begin
// pascal comment {}
CommentLvl:=1;
InStrConst:=false;
while StartPos<=MaxPos do begin
case Src[StartPos] of
'{': if Scanner.NestedComments then inc(CommentLvl);
'}':
begin
dec(CommentLvl);
if CommentLvl=0 then break;
end;
'a'..'z','A'..'Z','_':
if not InStrConst then begin
ReadIdentifier(true);
dec(StartPos);
end;
'''':
InStrConst:=not InStrConst;
#10,#13:
InStrConst:=false;
end;
inc(StartPos);
end;
inc(StartPos);
//debugln(StartPos,' ',copy(Src,CommentStart,StartPos-CommentStart));
end;
end;
'/': // Delphi comment
if (Src[StartPos+1]<>'/') then begin
inc(StartPos);
end else begin
inc(StartPos,2);
InStrConst:=false;
while (StartPos<=MaxPos) do begin
case Src[StartPos] of
#10,#13:
break;
'a'..'z','A'..'Z','_':
if not InStrConst then begin
ReadIdentifier(true);
dec(StartPos);
end;
'''':
InStrConst:=not InStrConst;
end;
inc(StartPos);
end;
inc(StartPos);
if (StartPos<=MaxPos) and (Src[StartPos] in [#10,#13])
and (Src[StartPos-1]<>Src[StartPos]) then
inc(StartPos);
end;
'(': // turbo pascal comment
if (Src[StartPos+1]<>'*') then begin
inc(StartPos);
end else begin
inc(StartPos,3);
InStrConst:=false;
while (StartPos<=MaxPos) do begin
case Src[StartPos] of
')':
if Src[StartPos-1]='*' then break;
'a'..'z','A'..'Z','_':
if not InStrConst then begin
ReadIdentifier(true);
dec(StartPos);
end;
'''':
InStrConst:=not InStrConst;
#10,#13:
InStrConst:=false;
end;
inc(StartPos);
end;
inc(StartPos);
end;
'a'..'z','A'..'Z','_':
ReadIdentifier(false);
'''':
begin
// skip string constant
inc(StartPos);
while (StartPos<=MaxPos) do begin
if (not (Src[StartPos] in ['''',#10,#13])) then
inc(StartPos)
else begin
inc(StartPos);
break;
end;
end;
end;
else
inc(StartPos);
end;
end;
end;
function GetDeclarationTool: boolean;
begin
Result:=false;
DeclarationTool:=nil;
if Assigned(FOnGetCodeToolForBuffer) then
DeclarationTool:=FOnGetCodeToolForBuffer(Self,CursorPos.Code,true)
else if CursorPos.Code=TObject(Scanner.MainCode) then
DeclarationTool:=Self;
if DeclarationTool=nil then begin
debugln('WARNING: TFindDeclarationTool.FindReferences DeclarationTool=nil');
exit;
end;
Result:=true;
end;
function FindDeclarationNode: boolean;
const
ProcAttr = [phpInUpperCase,phpAddClassName,phpWithVarModifiers];
var
Node: TCodeTreeNode;
CommentStart: integer;
CommentEnd: integer;
p: LongInt;
begin
if DeclarationFound then exit(true);
Result:=false;
// find the main declaration node and identifier
DeclarationTool.BuildTreeAndGetCleanPos(CursorPos,CleanDeclCursorPos);
DeclarationNode:=DeclarationTool.BuildSubTreeAndFindDeepestNodeAtPos(
CleanDeclCursorPos,true);
Identifier:=DeclarationTool.ExtractIdentifier(CleanDeclCursorPos);
if Identifier='' then begin
//debugln('FindDeclarationNode Identifier="',Identifier,'"');
exit;
end;
UseProcHead(DeclarationNode);
if DeclarationTool=Self then begin
//debugln(['FindDeclarationNode adding DeclarationNode ...']);
AddNodeReference(DeclarationNode);
end;
// find alias declaration node
//debugln('FindDeclarationNode DeclarationNode=',DeclarationNode.DescAsString);
AliasDeclarationNode:=nil;
case DeclarationNode.Desc of
ctnProcedure,ctnProcedureHead:
begin
Node:=DeclarationNode;
if DeclarationNode.Desc=ctnProcedureHead then
Node:=Node.Parent;
AliasDeclarationNode:=DeclarationTool.FindCorrespondingProcNode(
Node,ProcAttr);
end;
ctnVarDefinition:
if DeclarationNode.HasParentOfType(ctnProcedureHead) then begin
AliasDeclarationNode:=FindCorrespondingProcParamNode(DeclarationNode,ProcAttr);
end;
ctnTypeDefinition:
if NodeIsForwardType(DeclarationNode) then
AliasDeclarationNode:=DeclarationTool.FindTypeOfForwardNode(DeclarationNode)
else
AliasDeclarationNode:=DeclarationTool.FindForwardTypeNode(DeclarationNode,true);
end;
if AliasDeclarationNode=DeclarationNode then
AliasDeclarationNode:=nil;
if AliasDeclarationNode<>nil then begin
UseProcHead(AliasDeclarationNode);
if DeclarationTool=Self then begin
//debugln(['FindDeclarationNode adding alias node ...']);
AddNodeReference(AliasDeclarationNode);
end;
if AliasDeclarationNode.StartPos>DeclarationNode.StartPos then begin
Node:=AliasDeclarationNode;
AliasDeclarationNode:=DeclarationNode;
DeclarationNode:=Node;
end;
//debugln('FindDeclarationNode AliasDeclarationNode=',AliasDeclarationNode.DescAsString,' ',DeclarationTool.CleanPosToStr(AliasDeclarationNode.StartPos,DeclarationTool<>Self));
end;
// search comment in front of declaration
//debugln(['FindDeclarationNode search comment in front: ',DeclarationTool=Self,' SkipComments=',SkipComments,' Identifier=',Identifier]);
if (DeclarationTool=Self)
and (not SkipComments)
and FindCommentInFront(DeclarationNode.StartPos,Identifier,
true,false,false,true,true,CommentStart,CommentEnd)
then begin
//debugln(['FindDeclarationNode Comment="',dbgstr(copy(Src,CommentStart,CommentEnd)),'"']);
p:=CommentStart;
if (Src[p]='{') then begin
inc(p);
while (p<=SrcLen) and IsSpaceChar[Src[p]] do inc(p);
if (p<=SrcLen) and (CompareIdentifiers(@Src[p],PChar(Identifier))=0)
then begin
//debugln(['FindDeclarationNode comment in front']);
AddReference(p);
end;
end;
end;
DeclarationFound:=true;
Result:=true;
end;
procedure LimitScope(UseNode: TCodeTreeNode);
var
Node: TCodeTreeNode;
StartNode: TCodeTreeNode;
begin
MinPos:=Tree.FindFirstPosition;
MaxPos:=Tree.FindLastPosition;
if MaxPos>SrcLen then MaxPos:=SrcLen;
if DeclarationTool<>Self then begin
MinPos:=UseNode.Parent.EndPos;
exit;
end;
StartNode:=DeclarationNode;
if (AliasDeclarationNode<>nil) then
StartNode:=AliasDeclarationNode;
Node:=StartNode;
while Node<>nil do begin
case Node.Desc of
ctnImplementation:
// only search in implementation
if MinPos<Node.StartPos then MinPos:=Node.StartPos;
ctnTypeDefinition:
begin
// Note: types can be used before declaration
end;
ctnVarDefinition,ctnConstDefinition,ctnEnumIdentifier,ctnLabel:
begin
// only search behind variable
if MinPos<Node.StartPos then MinPos:=Node.StartPos;
end;
ctnProcedureHead:
MinPos:=Node.StartPos;
ctnProcedure:
begin
if (FindProcBody(Node)<>nil) and (StartNode<>Node.FirstChild) then
begin
// DeclarationNode is a local identifier
// limit scope to procedure
//debugln(['LimitScope ProcNode=',CleanPosToStr(Node.StartPos),'..',CleanPosToStr(Node.EndPos)]);
if MinPos<Node.FirstChild.EndPos then
MinPos:=Node.FirstChild.EndPos;
if MaxPos>Node.EndPos then
MaxPos:=Node.EndPos;
end;
end;
ctnOnBlock:
begin
// a declaration in an on block is only accessible in the on block
if MinPos<Node.StartPos then
MinPos:=Node.StartPos;
if MaxPos>Node.EndPos then
MaxPos:=Node.EndPos;
end;
end;
//debugln(['scope limited to node: ',Node.DescAsString,' ',CleanPosToStr(MinPos),'..',CleanPosToStr(MaxPos),': ',dbgstr(copy(Src,MinPos,20)),'..',dbgstr(copy(Src,MaxPos-20,20))]);
Node:=Node.Parent;
end;
//debugln(['LimitScope ',CleanPosToStr(MinPos),'..',CleanPosToStr(MaxPos),': ',dbgstr(copy(Src,MinPos,20)),'..',dbgstr(copy(Src,MaxPos-20,20))]);
end;
var
UseNode: TCodeTreeNode;
AVLNode: TAVLTreeNode;
begin
Result:=false;
//debugln('FindReferences ',MainFilename,' CursorPos=',CursorPos.Code.Filename,' x=',dbgs(CursorPos.X),' y=',dbgs(CursorPos.Y),' SkipComments=',dbgs(SkipComments));
ListOfPCodeXYPosition:=nil;
Params:=nil;
PosTree:=nil;
DeclarationFound:=false;
ActivateGlobalWriteLock;
try
// get the tool of the declaration
if not GetDeclarationTool then exit;
// check if this unit uses the declaration unit
UseNode:=nil;
if Self<>DeclarationTool then begin
BuildTree(lsrImplementationUsesSectionEnd);
UseNode:=FindUnitFileInAllUsesSections(DeclarationTool.MainFilename);
if UseNode=nil then
exit(true); // the declaration unit is not used
end;
// find declaration nodes and identifier
BuildTree(lsrEnd);
if not FindDeclarationNode then exit;
// search identifiers
LimitScope(UseNode);
//debugln('FindReferences MinPos=',CleanPosToStr(MinPos),' MaxPos=',CleanPosToStr(MaxPos));
SearchIdentifiers;
// create the reference list
if PosTree<>nil then begin
AVLNode:=PosTree.FindHighest;
while AVLNode<>nil do begin
StartPos:=PChar(AVLNode.Data)-PChar(Pointer(Src))+1;
// Note: if an include file is included twice a code position could be duplicated
if CleanPosToCaret(StartPos,ReferencePos) then
AddCodePosition(ListOfPCodeXYPosition,ReferencePos);
AVLNode:=PosTree.FindPrecessor(AVLNode);
end;
end;
finally
Params.Free;
PosTree.Free;
DeactivateGlobalWriteLock;
end;
Result:=true;
end;
function TFindDeclarationTool.FindUnitReferences(UnitCode: TCodeBuffer;
SkipComments: boolean; out ListOfPCodeXYPosition: TFPList): boolean;
var
AUnitName, UpperUnitName: String;
function CheckUsesSection(UsesNode: TCodeTreeNode; out Found: boolean): boolean;
var
ReferencePos: TCodeXYPosition;
begin
Result:=true;
Found:=false;
if UsesNode=nil then exit;
//DebugLn(['CheckUsesSection ']);
MoveCursorToNodeStart(UsesNode);
if (UsesNode.Desc=ctnUsesSection) then begin
ReadNextAtom;
if not UpAtomIs('USES') then
RaiseUsesExpected(20170421200509);
end;
repeat
ReadNextAtom; // read name
if CurPos.StartPos>SrcLen then break;
if AtomIsChar(';') then break;
AtomIsIdentifierE;
//DebugLn(['CheckUsesSection ',GetAtom,' ',AUnitName]);
if UpAtomIs(UpperUnitName) then begin // compare case insensitive
if CleanPosToCaret(CurPos.StartPos,ReferencePos) then begin
//DebugLn(['CheckUsesSection found in uses section: ',Dbgs(ReferencePos)]);
Found:=true;
AddCodePosition(ListOfPCodeXYPosition,ReferencePos);
end;
end;
ReadNextAtom;
if UpAtomIs('IN') then begin
ReadNextAtom;
if not AtomIsStringConstant then RaiseStrConstExpected(20170421200522);
ReadNextAtom;
end;
if AtomIsChar(';') then break;
if not AtomIsChar(',') then
RaiseExceptionFmt(20170421200217,ctsStrExpectedButAtomFound,[';',GetAtom])
until (CurPos.StartPos>SrcLen);
end;
function CheckSource(StartPos: integer): boolean;
var
ReferencePos: TCodeXYPosition;
begin
MoveCursorToCleanPos(StartPos);
repeat
ReadNextAtom;
if not SkipComments then
; // ToDo
if UpAtomIs(UpperUnitName)
and not LastAtomIs(0,'.') then begin
if CleanPosToCaret(CurPos.StartPos,ReferencePos) then begin
//DebugLn(['CheckSource found: ',Dbgs(ReferencePos)]);
AddCodePosition(ListOfPCodeXYPosition,ReferencePos);
end;
end;
until CurPos.StartPos>SrcLen;
Result:=true;
end;
var
InterfaceUsesNode: TCodeTreeNode;
ImplementationUsesNode: TCodeTreeNode;
Found: boolean;
StartPos: Integer;
begin
Result:=false;
//debugln('FindUnitReferences UnitCode=',UnitCode.Filename,' SkipComments=',dbgs(SkipComments),' ',MainFilename);
AUnitName:=ExtractFileNameOnly(UnitCode.Filename);
UpperUnitName:=UpperCaseStr(AUnitName);
ListOfPCodeXYPosition:=nil;
ActivateGlobalWriteLock;
try
BuildTree(lsrEnd);
InterfaceUsesNode:=FindMainUsesNode;
if not CheckUsesSection(InterfaceUsesNode,Found) then exit;
StartPos:=-1;
if Found then begin
StartPos:=InterfaceUsesNode.EndPos;
end else begin
ImplementationUsesNode:=FindImplementationUsesNode;
if not CheckUsesSection(ImplementationUsesNode,Found) then exit;
if Found then
StartPos:=ImplementationUsesNode.EndPos;
end;
// find unit reference in source
if StartPos>0 then begin
if not CheckSource(StartPos) then exit;
end;
finally
DeactivateGlobalWriteLock;
end;
Result:=true;
end;
procedure TFindDeclarationTool.FindUsedUnitReferences(
const CursorPos: TCodeXYPosition; SkipComments: boolean; out
UsedUnitFilename: string; out ListOfPCodeXYPosition: TFPList);
var
CleanPos: integer;
Node: TCodeTreeNode;
UnitInFilename: string;
AnUnitName: String;
TargetCode: TCodeBuffer;
TargetTool: TFindDeclarationTool;
begin
//debugln(['TFindDeclarationTool.FindUsedUnitReferences ',dbgs(CursorPos)]);
UsedUnitFilename:='';
ListOfPCodeXYPosition:=nil;
BuildTreeAndGetCleanPos(CursorPos,CleanPos);
Node:=FindDeepestNodeAtPos(CleanPos,true);
if Node.Desc in [ctnUseUnitNamespace,ctnUseUnitClearName] then
Node:=Node.Parent;
if Node.Desc<>ctnUseUnit then
RaiseException(20170421200221,'This function needs the cursor at a unit in a uses clause');
// cursor is on an used unit -> try to locate it
MoveCursorToCleanPos(Node.StartPos);
ReadNextAtom;
AnUnitName:=ExtractUsedUnitNameAtCursor(@UnitInFilename);
//debugln(['TFindDeclarationTool.FindUsedUnitReferences Used Unit=',AnUnitName,' in "',UnitInFilename,'"']);
TargetCode:=FindUnitSource(AnUnitName,UnitInFilename,true,Node.StartPos);
UsedUnitFilename:=TargetCode.Filename;
//debugln(['TFindDeclarationTool.FindUsedUnitReferences TargetCode=',TargetCode.Filename]);
TargetTool:=FOnGetCodeToolForBuffer(Self,TargetCode,false);
FindUsedUnitReferences(TargetTool,SkipComments,ListOfPCodeXYPosition);
end;
procedure TFindDeclarationTool.FindUsedUnitReferences(
TargetTool: TFindDeclarationTool; SkipComments: boolean; out
ListOfPCodeXYPosition: TFPList);
var
refs: TFindUsedUnitReferences;
begin
ListOfPCodeXYPosition:=TFPList.Create;
if TargetTool=nil then
RaiseException(20170421200226,'TargetTool=nil');
TargetTool.BuildInterfaceIdentifierCache(true);
refs:=TFindUsedUnitReferences.Create(Self, FindLastNode);
try
refs.TargetTool:=TargetTool;
refs.TargetUnitName:=TargetTool.GetSourceName(false);
refs.ListOfPCodeXYPosition:=ListOfPCodeXYPosition;
ForEachIdentifier(SkipComments,@OnFindUsedUnitIdentifier,refs);
finally
refs.Free;
end;
end;
{-------------------------------------------------------------------------------
function TFindDeclarationTool.CleanPosIsDeclarationIdentifier(CleanPos: integer;
Node: TCodeTreeNode): boolean;
Node should be the deepest node at CleanPos, and all sub trees built.
See BuildSubTree
-------------------------------------------------------------------------------}
function TFindDeclarationTool.CleanPosIsDeclarationIdentifier(CleanPos: integer;
Node: TCodeTreeNode): boolean;
function InNodeIdentifier(NodeIdentStartPos: Integer): boolean;
var
IdentStartPos, IdentEndPos: integer;
begin
GetIdentStartEndAtPosition(Src,CleanPos,IdentStartPos,IdentEndPos);
Result:=(IdentEndPos>IdentStartPos) and (IdentStartPos=NodeIdentStartPos);
end;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(Node);{$ENDIF}
Result:=false;
if Node=nil then exit;
case Node.Desc of
ctnTypeDefinition,ctnVarDefinition,ctnConstDefinition,ctnEnumIdentifier,ctnLabel:
begin
if NodeIsForwardDeclaration(Node) then exit;
Result:=InNodeIdentifier(Node.StartPos);
end;
ctnGenericType:
begin
if (Node.FirstChild=nil) or NodeIsForwardDeclaration(Node) then exit;
Result:=InNodeIdentifier(Node.FirstChild.StartPos);
end;
ctnProcedure:
begin
if (Node.FirstChild<>nil)
and ((Node.FirstChild.SubDesc and ctnsForwardDeclaration)>0) then
RaiseException(20170421200230,'TFindDeclarationTool.CleanPosIsDeclarationIdentifier Node not expanded');
MoveCursorToProcName(Node,true);
Result:=InNodeIdentifier(CurPos.StartPos);
end;
ctnProcedureHead:
begin
MoveCursorToProcName(Node,true);
Result:=InNodeIdentifier(CurPos.StartPos);
end;
ctnProperty, ctnGlobalProperty:
begin
if not MoveCursorToPropName(Node) then exit;
Result:=InNodeIdentifier(CurPos.StartPos);
end;
ctnUnit:
Result:=PositionInSourceName(CleanPos);
end;
end;
function TFindDeclarationTool.JumpToNode(ANode: TCodeTreeNode; out
NewPos: TCodeXYPosition; out NewTopLine, BlockTopLine,
BlockBottomLine: integer; IsCodeBlock: boolean): boolean;
var
JumpPos: LongInt;
Caret: TCodeXYPosition;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(ANode);{$ENDIF}
Result:=false;
if (ANode=nil) or (ANode.StartPos<1) then exit;
JumpPos:=ANode.StartPos;
if ANode.Desc in [ctnProperty,ctnGlobalProperty] then begin
MoveCursorToPropName(ANode);
JumpPos:=CurPos.StartPos;
end;
Result:=JumpToCleanPos(JumpPos,JumpPos,ANode.EndPos,
NewPos,NewTopLine,BlockTopLine,BlockBottomLine,IsCodeBlock);
if CleanPosToCaret(ANode.StartPos, Caret) then
BlockTopLine := Caret.Y
else
BlockTopLine := -1;
if CleanPosToCaret(ANode.EndPos, Caret) then
BlockBottomLine := Caret.Y
else
BlockBottomLine := -1;
end;
function TFindDeclarationTool.JumpToNode(ANode: TCodeTreeNode; out
NewPos: TCodeXYPosition; out NewTopLine: integer; IsCodeBlock: boolean
): boolean;
var
BlockTopLine, BlockBottomLine: integer;
begin
Result := JumpToNode(ANode, NewPos, NewTopLine, BlockTopLine, BlockBottomLine, IsCodeBlock);
end;
function TFindDeclarationTool.JumpToCleanPos(NewCleanPos, NewTopLineCleanPos,
NewBottomLineCleanPos: integer; out NewPos: TCodeXYPosition; out NewTopLine,
BlockTopLine, BlockBottomLine: integer; IsCodeBlock: boolean): boolean;
var
NewTopLinePos: TCodeXYPosition;
NewBottomLinePos: TCodeXYPosition;
JumpPos: Integer;
begin
Result:=false;
// convert clean position to line, column and code
if not CleanPosToCaret(NewCleanPos,NewPos) then exit;
NewTopLine:=NewPos.Y;
if AdjustTopLineDueToComment then begin
// if there is a comment in front of the top position, it probably belongs
// to the destination code
// -> adjust the topline position, so that the comment is visible
NewTopLineCleanPos:=FindLineEndOrCodeInFrontOfPosition(NewTopLineCleanPos,
false);
if (NewTopLineCleanPos>=1) and (Src[NewTopLineCleanPos] in [#13,#10])
then begin
inc(NewTopLineCleanPos);
if (Src[NewTopLineCleanPos] in [#10,#13])
and (Src[NewTopLineCleanPos]<>Src[NewTopLineCleanPos-1]) then
inc(NewTopLineCleanPos);
end;
end;
// convert clean top line position to line, column and code
if not CleanPosToCaret(NewTopLineCleanPos,NewTopLinePos) then exit;
BlockTopLine := NewTopLinePos.Y;
// convert clean bottom line position to line, column and code
NewBottomLinePos:=NewPos;
if (NewBottomLineCleanPos>NewCleanPos)
and (not CleanPosToCaret(NewBottomLineCleanPos,NewBottomLinePos)) then exit;
BlockBottomLine := NewBottomLinePos.Y;
if NewTopLinePos.Code=NewPos.Code then begin
// center the destination position in the source editor
if IsCodeBlock and (JumpCodeBlockPos>0) then
JumpPos := JumpCodeBlockPos
else
if not IsCodeBlock and (JumpSingleLinePos>0) then
JumpPos := JumpSingleLinePos
else
JumpPos := 0;
if JumpPos>0 then
NewTopLine:=NewTopLinePos.Y-((VisibleEditorLines-(NewBottomLinePos.Y-NewTopLinePos.Y))*JumpPos div 100)
else
NewTopLine:=High(NewTopLine);
if NewTopLine>NewTopLinePos.Y then
NewTopLine:=NewTopLinePos.Y;
// NewTopLine not above first line of code
if NewTopLine<1 then NewTopLine:=1;
// make NewTopLine visible
if NewTopLine<=NewPos.Y-VisibleEditorLines then begin
// NewTopLine is not visible
// center or align to bottom
if (NewBottomLineCleanPos>NewCleanPos)
and (NewBottomLinePos.Y<NewPos.Y+(VisibleEditorLines div 2))
then begin
// align to bottom
NewTopLine:=NewBottomLinePos.Y-VisibleEditorLines+1;
end else begin
// center
NewTopLine:=NewPos.Y-(VisibleEditorLines*JumpSingleLinePos div 100);
end;
if NewTopLine<1 then NewTopLine:=1;
end;
end else
NewTopLine:=1;
Result:=true;
end;
function TFindDeclarationTool.JumpToCleanPos(NewCleanPos, NewTopLineCleanPos,
NewBottomLineCleanPos: integer; out NewPos: TCodeXYPosition; out
NewTopLine: integer; IsCodeBlock: boolean): boolean;
var
BlockTopLine, BlockBottomLine: integer;
begin
Result := JumpToCleanPos(NewCleanPos, NewTopLineCleanPos, NewBottomLineCleanPos,
NewPos, NewTopLine, BlockTopLine, BlockBottomLine, IsCodeBlock);
end;
function TFindDeclarationTool.NodeIsForwardDeclaration(Node: TCodeTreeNode
): boolean;
var
TypeNode: TCodeTreeNode;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(Node);{$ENDIF}
Result:=false;
if (Node=nil) or (not (Node.Desc in [ctnTypeDefinition,ctnGenericType])) then
exit;
TypeNode:=FindTypeNodeOfDefinition(Node);
if TypeNode=nil then exit;
if TypeNode.Desc in AllClasses then begin
if (TypeNode.SubDesc and ctnsForwardDeclaration)>0 then begin
Result:=true;
exit;
end;
end;
end;
function TFindDeclarationTool.GetExpandedOperand(const CursorPos: TCodeXYPosition;
out Operand: string; ResolveProperty: Boolean): Boolean;
var
CursorNode: TCodeTreeNode;
CleanCursorPos: integer;
Params: TFindDeclarationParams;
Identifier: PChar;
LineRange: TLineRange;
begin
Result := False;
Operand := '';
if (CursorPos.Y<1) or (CursorPos.Y>CursorPos.Code.LineCount)
or (CursorPos.X<1) then Exit;
CursorPos.Code.GetLineRange(CursorPos.Y-1,LineRange);
if LineRange.EndPos-LineRange.StartPos+1<CursorPos.X then Exit;
ActivateGlobalWriteLock;
try
// build code tree
BuildTreeAndGetCleanPos(trTillCursor,lsrEnd,CursorPos,CleanCursorPos,
[btSetIgnoreErrorPos,btCursorPosOutAllowed]);
// find CodeTreeNode at cursor
if (Tree.Root<>nil) and (Tree.Root.StartPos<=CleanCursorPos) then
CursorNode := BuildSubTreeAndFindDeepestNodeAtPos(CleanCursorPos, True)
else
CursorNode := nil;
if CursorNode = nil then begin
// raise exception
CursorNode := FindDeepestNodeAtPos(CleanCursorPos, True);
end;
if CursorNode.Desc = ctnBeginBlock then begin
BuildSubTreeForBeginBlock(CursorNode);
CursorNode := FindDeepestNodeAtPos(CursorNode, CleanCursorPos, True);
end;
// set cursor on identifier
MoveCursorToCleanPos(CleanCursorPos);
GetIdentStartEndAtPosition(Src,CleanCursorPos,
CurPos.StartPos,CurPos.EndPos);
if CurPos.StartPos >= CurPos.EndPos then Exit;
Identifier := @Src[CurPos.StartPos];
// find declaration of identifier
Params := TFindDeclarationParams.Create;
try
Params.ContextNode := CursorNode;
Params.SetIdentifier(Self, Identifier, nil);
Params.Flags := [fdfSearchInParentNodes, fdfTopLvlResolving,
fdfSearchInAncestors, fdfSkipClassForward,
fdfExtractOperand];
if ResolveProperty then
Include(Params.Flags, fdfPropertyResolving);
if FindDeclarationOfIdentAtParam(Params) then
begin
Operand := Params.ExtractedOperand;
Result := Operand <> '';
end;
finally
Params.Free;
end;
finally
ClearIgnoreErrorAfter;
DeactivateGlobalWriteLock;
end;
end;
function TFindDeclarationTool.FindIdentifierInProcContext(
ProcContextNode: TCodeTreeNode;
Params: TFindDeclarationParams): TIdentifierFoundResult;
{ this function is internally used by FindIdentifierInContext
}
var
NameAtom: TAtomPosition;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(ProcContextNode);{$ENDIF}
Result:=ifrProceedSearch;
// if proc is a method body, search in class
// -> find class name
if ProcContextNode.FirstChild=nil then
exit(ifrProceedSearch);
MoveCursorToNodeStart(ProcContextNode.FirstChild);
ReadNextAtom; // read name
if not AtomIsIdentifier then exit; // ignore operator procs
NameAtom:=CurPos;
ReadNextAtom;
if AtomIsChar('.') then begin
// proc is a method body (not a declaration).
// -> proceed the search normally ...
end else begin
// proc is a proc declaration
if ((fdfCollect in Params.Flags)
or CompareSrcIdentifiers(NameAtom.StartPos,Params.Identifier)) then begin
// proc identifier found
// the parameters will be checked by the caller
{$IFDEF ShowTriedContexts}
DebugLn('[TFindDeclarationTool.FindIdentifierInProcContext] Proc-Identifier found="',GetIdentifier(@Src[NameAtom.StartPos]),'"');
{$ENDIF}
Params.SetResult(Self,ProcContextNode,NameAtom.StartPos);
Result:=ifrSuccess;
end else begin
// proceed the search normally ...
end;
end;
end;
function TFindDeclarationTool.FindIdentifierInClassOfMethod(
ProcContextNode: TCodeTreeNode; Params: TFindDeclarationParams): boolean;
{ this function is internally used by FindIdentifierInContext
}
var
ClassNameAtom: TAtomPosition;
OldFlags: TFindDeclarationFlags;
IdentFoundResult: TIdentifierFoundResult;
CurClassNode: TCodeTreeNode;
ForExprType: TExpressionType;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(ProcContextNode);{$ENDIF}
Result:=false;
// if proc is a method, search in class
// -> find class name
MoveCursorToNodeStart(ProcContextNode);
ReadNextAtom; // read keyword
if UpAtomIs('CLASS') then
ReadNextAtom;
ReadNextAtom; // read classname
ClassNameAtom:=CurPos;
ReadNextAtom;
if AtomIsChar('.') then begin
// proc is a method
if CompareSrcIdentifiers(ClassNameAtom.StartPos,Params.Identifier) then
begin
// the class itself is searched
// -> proceed the search normally ...
end else begin
// search the identifier in the class first
// search the class in the same unit
CurClassNode:=FindClassOfMethod(ProcContextNode,true,true);
repeat
// search identifier in class
OldFlags := Params.Flags;
Params.Flags:=[fdfSearchInAncestors]
+(fdfGlobalsSameIdent*Params.Flags)
-[fdfExceptionOnNotFound];
Params.ContextNode:=CurClassNode;
{$IFDEF ShowTriedContexts}
DebugLn('[TFindDeclarationTool.FindIdentifierInClassOfMethod] searching identifier in class of method Identifier=',GetIdentifier(Params.Identifier));
{$ENDIF}
if (fdfSearchInHelpers in Params.Flags)
and (CurClassNode.Desc in [ctnClassHelper,ctnRecordHelper])
and (Params.GetHelpers(fdhlkDelphiHelper)<>nil)
then begin
// override current helper for the type and search in that type
ForExprType := Params.GetHelpers(fdhlkDelphiHelper).AddFromHelperNode(CurClassNode, Self, True).ForExprType;
if (ForExprType.Desc = xtContext) and (ForExprType.Context.Node<>nil)
then begin
Params.ContextNode:=ForExprType.Context.Node;
Result:=ForExprType.Context.Tool.FindIdentifierInContext(Params);
end;
end else
Result:=FindIdentifierInContext(Params);
Params.Flags := OldFlags;
if Result and Params.IsFoundProcFinal then exit;
// in a nested class, continue search in enclosing class
repeat
CurClassNode:=CurClassNode.Parent;
until (CurClassNode=nil) or (CurClassNode.Desc in AllClassObjects);
until CurClassNode=nil;
end;
end else begin
// proc is not a method
if (fdfCollect in Params.Flags)
or CompareSrcIdentifiers(ClassNameAtom.StartPos,Params.Identifier) then
begin
// proc identifier found
{$IFDEF ShowTriedContexts}
DebugLn('[TFindDeclarationTool.FindIdentifierInClassOfMethod] Proc Identifier found="',GetIdentifier(Params.Identifier),'"');
{$ENDIF}
Params.SetResult(Self,ProcContextNode,ClassNameAtom.StartPos);
IdentFoundResult:=Params.NewCodeTool.DoOnIdentifierFound(Params,
Params.NewNode);
Result:=IdentFoundResult=ifrSuccess;
exit;
end else begin
// proceed the search normally ...
end;
end;
end;
function TFindDeclarationTool.FindIdentifierInContext(
Params: TFindDeclarationParams): boolean;
var
IdentFoundResult: TIdentifierFoundResult;
begin
Result := FindIdentifierInContext(Params, IdentFoundResult{%H-});
end;
function TFindDeclarationTool.FindClassOfMethod(ProcNode: TCodeTreeNode;
FindClassContext, ExceptionOnNotFound: boolean): TCodeTreeNode;
var
ClassNameAtom: TAtomPosition;
Node: TCodeTreeNode;
TypeNode: TCodeTreeNode;
NextNameAtom: TAtomPosition;
CurClassName: PChar;
CurClassNode: TCodeTreeNode;
procedure RaiseClassNotFound;
begin
MoveCursorToAtomPos(ClassNameAtom);
RaiseExceptionFmt(20170421200233,'Class %s not found',[GetAtom]);
end;
procedure RaiseNotAClass;
begin
MoveCursorToAtomPos(ClassNameAtom);
RaiseExceptionFmt(20170421200237,'Class expected, but %s found',[GetAtom]);
end;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(ProcNode);{$ENDIF}
{$IFDEF ShowTriedContexts}
DebugLn('[TFindDeclarationTool.FindClassOfMethod] A ');
{$ENDIF}
Result:=nil;
if ProcNode.Desc=ctnProcedureHead then
ProcNode:=ProcNode.Parent;
if (ProcNode.Parent<>nil) and (ProcNode.Parent.Desc in AllClassSections) then begin
CurClassNode:=ProcNode.Parent.Parent;
if FindClassContext then begin
// return the class node
exit(CurClassNode);
end else begin
// return the type identifier node
exit(CurClassNode.Parent);
end;
end;
MoveCursorToNodeStart(ProcNode);
ReadNextAtom; // read keyword
if UpAtomIs('CLASS') then ReadNextAtom;
ReadNextAtom; // read classname
ClassNameAtom:=CurPos;
if CurPos.Flag<>cafWord then begin
if not ExceptionOnNotFound then exit;
RaiseNotAClass;
end;
CurClassName:=@Src[ClassNameAtom.StartPos];
ReadNextAtom;
if CurPos.Flag<>cafPoint then begin
// not a method
if not ExceptionOnNotFound then exit;
RaiseNotAClass;
end;
ReadNextAtom;
NextNameAtom:=CurPos;
//debugln(['TFindDeclarationTool.FindClassOfMethod ClassName="',GetAtom(ClassNameAtom),'"']);
// proc is a method
// -> search the class
Node:=ProcNode;
repeat
if Node.Desc=ctnTypeSection then begin
TypeNode:=Node.LastChild;
while TypeNode<>nil do begin
{$IFDEF ShowTriedIdentifiers}
debugln(['TFindDeclarationTool.FindClassOfMethod ',TypeNode.DescAsString,' ',dbgstr(ExtractNode(TypeNode,[]),1,40)]);
{$ENDIF}
if ((TypeNode.Desc=ctnTypeDefinition)
and (CompareIdentifierPtrs(CurClassName,@Src[TypeNode.StartPos])=0))
or ((TypeNode.Desc=ctnGenericType)
and (TypeNode.FirstChild<>nil)
and (CompareIdentifierPtrs(CurClassName,@Src[TypeNode.FirstChild.StartPos])=0))
then begin
repeat
// type with same name found
//debugln(['TFindDeclarationTool.FindClassOfMethod type found ',ExtractDefinitionName(TypeNode)]);
CurClassNode:=FindTypeNodeOfDefinition(TypeNode);
if (CurClassNode=nil) then begin
if not ExceptionOnNotFound then exit;
RaiseClassNotFound;
end;
if (not (CurClassNode.Desc in AllClassObjects))
or ((ctnsForwardDeclaration and Node.SubDesc)<>0)
then begin
if not ExceptionOnNotFound then exit;
RaiseNotAClass;
end;
//debugln(['TFindDeclarationTool.FindClassOfMethod class found, NextNameAtom=',GetAtom(NextNameAtom)]);
// class found
if NextNameAtom.Flag=cafWord then begin
MoveCursorToAtomPos(NextNameAtom);
ReadNextAtom;
if CurPos.Flag<>cafPoint then begin
if FindClassContext then begin
// return the class node
exit(CurClassNode);
end else begin
// return the type identifier node
exit(TypeNode);
end;
end;
ReadNextAtom;
ClassNameAtom:=NextNameAtom;
NextNameAtom:=CurPos;
CurClassName:=@Src[ClassNameAtom.StartPos];
end else begin
// operator or missing sub identifier
if FindClassContext then begin
// return the class node
exit(CurClassNode);
end else begin
// return the type identifier node
exit(TypeNode);
end;
end;
// search sub class
//debugln(['TFindDeclarationTool.FindClassOfMethod searching sub class "',GetIdentifier(CurClassName),'"']);
Node:=FindClassMember(CurClassNode,CurClassName);
if Node=nil then begin
if not ExceptionOnNotFound then exit;
RaiseClassNotFound;
end;
if not (Node.Desc in [ctnTypeDefinition,ctnGenericType]) then begin
if not ExceptionOnNotFound then exit;
RaiseNotAClass;
end;
TypeNode:=Node;
until false;
end;
TypeNode:=TypeNode.PriorBrother;
end;
end;
// next
if Node.PriorBrother<>nil then
Node:=Node.PriorBrother
else begin
Node:=Node.Parent;
if (Node=nil) or (Node.Desc<>ctnImplementation) then break;
Node:=Node.PriorBrother;
if (Node=nil) or (Node.Desc<>ctnInterface) then break;
Node:=Node.LastChild;
if Node=nil then break;
end;
until false;
if ExceptionOnNotFound then
RaiseClassNotFound;
end;
function TFindDeclarationTool.FindClassMember(aClassNode: TCodeTreeNode;
Identifier: PChar): TCodeTreeNode;
var
Node: TCodeTreeNode;
CurIdentifier: PChar;
begin
Result:=nil;
if GetIdentLen(Identifier)=0 then exit;
if aClassNode=nil then exit;
Node:=aClassNode.LastChild;
while Node<>nil do begin
if (Node.Desc in AllClassSections)
and (Node.FirstChild<>nil) then begin
Node:=Node.LastChild;
continue;
end
else if Node.Desc in AllSimpleIdentifierDefinitions then begin
if CompareIdentifierPtrs(@Src[Node.StartPos],Identifier)=0 then
exit(Node);
end else if Node.Desc=ctnProperty then begin
CurIdentifier:=GetPropertyNameIdentifier(Node);
if CompareIdentifierPtrs(CurIdentifier,Identifier)=0 then
exit(Node);
end else if Node.Desc=ctnProcedure then begin
CurIdentifier:=GetProcNameIdentifier(Node);
if CompareIdentifierPtrs(CurIdentifier,Identifier)=0 then
exit(Node);
end;
// next
if Node.PriorBrother<>nil then
Node:=Node.PriorBrother
else begin
repeat
Node:=Node.Parent;
if Node=aClassNode then exit;
until Node.PriorBrother<>nil;
Node:=Node.PriorBrother;
end;
end;
end;
function TFindDeclarationTool.FindClassMember(aClassNode: TCodeTreeNode;
const Identifier: String; SearchInAncestors: boolean): TFindContext;
var
Params: TFindDeclarationParams;
begin
Result.Tool:=Self;
Result.Node:=FindClassMember(aClassNode,PChar(Identifier));
if Result.Node<>nil then exit;
if not SearchInAncestors then begin
Result:=CleanFindContext;
exit;
end;
Params:=TFindDeclarationParams.Create;
try
while Result.Tool.FindAncestorOfClass(aClassNode,Params,True) do begin
Result.Tool:=Params.NewCodeTool;
aClassNode:=Params.NewNode;
Result.Node:=Result.Tool.FindClassMember(aClassNode,PChar(Identifier));
if Result.Node<>nil then exit;
end;
Result:=CleanFindContext;
finally
Params.Free;
end;
end;
function TFindDeclarationTool.FindAncestorOfClass(ClassNode: TCodeTreeNode;
Params: TFindDeclarationParams; FindClassContext: boolean): boolean;
var
InheritanceNode: TCodeTreeNode;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(ClassNode);{$ENDIF}
if (ClassNode=nil) or (not (ClassNode.Desc in AllClasses)) then
RaiseException(20170421200240,'[TFindDeclarationTool.FindAncestorOfClass] invalid classnode');
Result:=false;
// ToDo: ppu, dcu
InheritanceNode:=FindInheritanceNode(ClassNode);
if (InheritanceNode<>nil)
and (InheritanceNode.FirstChild<>nil) then begin
Result:=FindAncestorOfClassInheritance(InheritanceNode.FirstChild,
Params,FindClassContext);
end else begin
Result:=FindDefaultAncestorOfClass(ClassNode,Params,FindClassContext);
end;
end;
function TFindDeclarationTool.FindAncestorOfClassInheritance(
IdentifierNode: TCodeTreeNode; ResultParams: TFindDeclarationParams;
FindClassContext: boolean): boolean;
var
InheritanceNode: TCodeTreeNode;
ClassNode: TCodeTreeNode;
AncestorContext: TFindContext;
AncestorStartPos: LongInt;
ExprType: TExpressionType;
Params: TFindDeclarationParams;
procedure RaiseExpected(const Expected: string);
begin
MoveCursorToCleanPos(AncestorStartPos);
ReadNextAtom;
RaiseExceptionFmt(20170421200243,ctsStrExpectedButAtomFound,[Expected,ExtractNode(IdentifierNode,[])]);
end;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(IdentifierNode);{$ENDIF}
if (IdentifierNode=nil)
or (not (IdentifierNode.Desc in [ctnIdentifier,ctnSpecialize]))
or (IdentifierNode.Parent=nil)
or (IdentifierNode.Parent.Desc<>ctnClassInheritance)
then
RaiseException(20170421200245,'[TFindDeclarationTool.FindAncestorOfClass] '
+' not an inheritance node');
Result:=false;
InheritanceNode:=IdentifierNode.Parent;
ClassNode:=InheritanceNode.Parent;
if IdentifierNode.Desc=ctnSpecialize then begin
if (IdentifierNode.FirstChild=nil) then begin
MoveCursorToCleanPos(IdentifierNode.StartPos);
ReadNextAtom;
if UpAtomIs('SPECIALIZE') then
ReadNextAtom;
RaiseStringExpectedButAtomFound(20170421200248,'class type');
end;
MoveCursorToCleanPos(IdentifierNode.FirstChild.StartPos);
end else
MoveCursorToCleanPos(IdentifierNode.StartPos);
ReadNextAtom;
AtomIsIdentifierE;
AncestorStartPos:=CurPos.StartPos;
ReadNextAtom;
Params:=TFindDeclarationParams.Create;
try
Params.Flags:=fdfDefaultForExpressions;
Params.ContextNode:=IdentifierNode;
if CurPos.Flag=cafPoint then begin
// complex identifier
{$IFDEF ShowTriedContexts}
DebugLn(['[TFindDeclarationTool.FindAncestorOfClass] ',
' search complex ancestor class = "',ExtractNode(IdentifierNode,[]),'" for class "',ExtractClassName(ClassNode,false),'"']);
{$ENDIF}
if not FindClassContext then
Params.Flags:=Params.Flags+[fdfFindVariable];
ExprType:=FindExpressionTypeOfTerm(IdentifierNode.StartPos,IdentifierNode.EndPos,Params,false);
if ExprType.Desc<>xtContext then
RaiseExpected('type');
AncestorContext:=ExprType.Context
end else begin
// simple identifier
{$IFDEF ShowTriedContexts}
DebugLn('[TFindDeclarationTool.FindAncestorOfClass] ',
' search ancestor class="',GetIdentifier(@Src[AncestorStartPos]),'" for class "',ExtractClassName(ClassNode,false),'"');
{$ENDIF}
Params.SetIdentifier(Self,@Src[AncestorStartPos],nil);
if not FindIdentifierInContext(Params) then
exit;
AncestorContext.Tool:=Params.NewCodeTool;
AncestorContext.Node:=Params.NewNode;
end;
finally
Params.Free;
end;
if FindClassContext then begin
// search ancestor class context
if (AncestorContext.Node.Desc in [ctnTypeDefinition,ctnGenericType]) then
begin
Params:=TFindDeclarationParams.Create;
try
Params.Flags:=fdfDefaultForExpressions+[fdfFindChildren];
AncestorContext:=AncestorContext.Tool.FindBaseTypeOfNode(Params,AncestorContext.Node);
finally
Params.Free;
end;
end;
// check result
if not (AncestorContext.Node.Desc in AllClasses) then
RaiseExpected('class');
if AncestorContext.Node=ClassNode then begin
MoveCursorToCleanPos(AncestorStartPos);
ReadNextAtom;
RaiseException(20170421200252,'cycle detected');
end;
end else begin
// check if class identifier
if (not (AncestorContext.Node.Desc in [ctnTypeDefinition,ctnGenericType])) then
RaiseExpected('type');
end;
ResultParams.SetResult(AncestorContext);
Result:=true;
end;
function TFindDeclarationTool.FindAncestorsOfClass(ClassNode: TCodeTreeNode;
var ListOfPFindContext: TFPList;
Params: TFindDeclarationParams; FindClassContext: boolean;
ExceptionOnNotFound: boolean): boolean;
var
Node: TCodeTreeNode;
Context: TFindContext;
InheritanceNode: TCodeTreeNode;
begin
Result:=false;
InheritanceNode:=FindInheritanceNode(ClassNode);
if (InheritanceNode=nil) then
exit(true);
Node:=InheritanceNode.FirstChild;
if Node=nil then begin
try
if not FindAncestorOfClass(ClassNode,Params,FindClassContext) then begin
exit(true); // this is TObject or IInterface, IUnknown
end else begin
Context:=CreateFindContext(Params);
end;
AddFindContext(ListOfPFindContext,Context);
Result:=Context.Node<>nil;
except
if ExceptionOnNotFound then raise;
end;
end else begin
while Node<>nil do begin
try
if FindAncestorOfClassInheritance(Node,Params,FindClassContext) then
begin
Context:=CreateFindContext(Params);
AddFindContext(ListOfPFindContext,Context);
end;
except
if ExceptionOnNotFound then raise;
end;
Node:=Node.NextBrother;
end;
end;
Result:=true;
end;
function TFindDeclarationTool.FindForwardIdentifier(
Params: TFindDeclarationParams; out IsForward: boolean): boolean;
{ first search the identifier in the normal way via FindIdentifierInContext
then search the other direction }
var
OldInput: TFindDeclarationInput;
begin
Params.Save(OldInput);
Exclude(Params.Flags,fdfExceptionOnNotFound);
Result:=FindIdentifierInContext(Params);
if not Result then begin
Params.Load(OldInput,false);
Params.Flags:=Params.Flags+[fdfSearchForward,fdfIgnoreCurContextNode];
Result:=FindIdentifierInContext(Params);
IsForward:=true;
end else begin
IsForward:=false;
end;
Params.Load(OldInput,true);
end;
function TFindDeclarationTool.FindNonForwardClass(ForwardNode: TCodeTreeNode
): TCodeTreeNode;
var
Node: TCodeTreeNode;
Identifier: PChar;
begin
Result:=nil;
Node:=ForwardNode;
if Node.Desc=ctnGenericType then begin
Node:=Node.FirstChild;
if Node=nil then exit;
end else if Node.Desc<>ctnTypeDefinition then
exit;
Node:=Node.FirstChild;
if Node=nil then
Exit;
Identifier:=@Src[Node.StartPos];
if (Node=nil)
or (not (Node.Desc in AllClasses))
or ((ctnsForwardDeclaration and Node.SubDesc)=0) then
exit;
Node:=ForwardNode;
repeat
//DebugLn(['TFindDeclarationTool.FindNonForwardClass Node=',dbgstr(copy(Src,Node.StartPos,20))]);
if Node.NextBrother<>nil then
Node:=Node.NextBrother
else if (Node.Parent=nil)
or (not (Node.Parent.Desc in AllDefinitionSections)) then
break
else begin
Node:=Node.Parent.NextBrother;
while (Node<>nil)
and ((Node.FirstChild=nil) or (not (Node.Desc in AllDefinitionSections)))
do
Node:=Node.NextBrother;
if Node=nil then break;
Node:=Node.FirstChild;
end;
if CompareSrcIdentifiers(Node.StartPos,Identifier) then begin
Result:=Node;
exit;
end;
until false;
end;
function TFindDeclarationTool.FindNonForwardClass(Params: TFindDeclarationParams
): boolean;
var
Node: TCodeTreeNode;
begin
Node:=FindNonForwardClass(Params.NewNode);
if Node<>nil then begin
Params.SetResult(Self,Node,Node.StartPos);
Result:=true;
end else begin
Result:=false;
end;
end;
function TFindDeclarationTool.FindIdentifierInWithVarContext(
WithVarNode: TCodeTreeNode; Params: TFindDeclarationParams): boolean;
{ this function is internally used by FindIdentifierInContext }
var
WithVarExpr: TExpressionType;
OldInput: TFindDeclarationInput;
OldExtractedOperand, NewExtractedOperand: string;
begin
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.FindIdentifierInWithVarContext] Ident=',
'"',GetIdentifier(Params.Identifier),'"',
' WithStart=',StringToPascalConst(copy(Src,WithVarNode.StartPos,15))
);
{$ENDIF}
{$IFDEF CheckNodeTool}CheckNodeTool(WithVarNode);{$ENDIF}
Result:=false;
// find the base type of the with variable
// move cursor to end of with-variable
Params.Save(OldInput);
Params.ContextNode:=WithVarNode;
Params.Flags:=Params.Flags*fdfGlobals
+[fdfExceptionOnNotFound,fdfFunctionResult,fdfFindChildren];
OldExtractedOperand:=Params.ExtractedOperand;
WithVarExpr:=FindExpressionTypeOfTerm(WithVarNode.StartPos,-1,Params,true);
if fdfExtractOperand in Params.Flags then
NewExtractedOperand:=Params.ExtractedOperand+'.'
else
NewExtractedOperand:='';
if (WithVarExpr.Desc<>xtContext)
or (WithVarExpr.Context.Node=nil)
or (WithVarExpr.Context.Node=OldInput.ContextNode)
or (not (WithVarExpr.Context.Node.Desc in (AllClasses+[ctnEnumerationType])))
then begin
MoveCursorToCleanPos(WithVarNode.StartPos);
RaiseException(20170421200254,ctsExprTypeMustBeClassOrRecord);
end;
// search identifier in 'with' context
// Note: do not search in parent nodes (e.g. with ListBox1 do Items)
Params.Load(OldInput,false);
Params.Flags:=Params.Flags-[fdfExceptionOnNotFound,fdfSearchInParentNodes];
Params.ContextNode:=WithVarExpr.Context.Node;
Result:=WithVarExpr.Context.Tool.FindIdentifierInContext(Params);
Params.Load(OldInput,true);
if fdfExtractOperand in Params.Flags then
if Result then
Params.FExtractedOperand:=NewExtractedOperand
else
Params.FExtractedOperand:=OldExtractedOperand;
end;
function TFindDeclarationTool.FindIdentifierInAncestors(
ClassNode: TCodeTreeNode; Params: TFindDeclarationParams;
var IdentFoundResult: TIdentifierFoundResult): boolean;
{ this function is internally used by FindIdentifierInContext
and FindBaseTypeOfNode
}
function Search(AncestorTool: TFindDeclarationTool;
AncestorClassNode: TCodeTreeNode): boolean;
var
OldFlags: TFindDeclarationFlags;
begin
OldFlags := Params.Flags;
Params.ContextNode:=AncestorClassNode;
Params.Flags:=Params.Flags
-[fdfIgnoreCurContextNode,fdfSearchInParentNodes]
+[fdfSearchInAncestors];
Result:=AncestorTool.FindIdentifierInContext(Params,IdentFoundResult);
Params.Flags := OldFlags;
end;
var
InheritanceNode: TCodeTreeNode;
Node: TCodeTreeNode;
SearchDefaultAncestor: Boolean;
begin
Result:=false;
if not (fdfSearchInAncestors in Params.Flags) then exit;
SearchDefaultAncestor:=true;
InheritanceNode:=FindInheritanceNode(ClassNode);
if (InheritanceNode<>nil) then begin
Node:=InheritanceNode.FirstChild;
while Node<>nil do begin
if not FindAncestorOfClassInheritance(Node,Params,true) then exit;
SearchDefaultAncestor:=false;
if Search(Params.NewCodeTool,Params.NewNode) then exit(true);
Node:=Node.NextBrother;
end;
end;
//debugln(['TFindDeclarationTool.FindIdentifierInAncestors SearchDefaultAncestor=',SearchDefaultAncestor,' ',CleanPosToStr(ClassNode.StartPos,true)]);
if SearchDefaultAncestor then begin
if not FindDefaultAncestorOfClass(ClassNode,Params,true) then exit;
//debugln(['TFindDeclarationTool.FindIdentifierInAncestors search in default ancestor ',FindContextToString(CreateFindContext(Params.NewCodeTool,Params.NewNode))]);
Result:=Search(Params.NewCodeTool,Params.NewNode);
end;
end;
{$IFDEF DebugPrefix}
procedure TFindDeclarationTool.DecPrefix;
begin
DebugPrefix:=copy(DebugPrefix,1,length(DebugPrefix)-2);
end;
procedure TFindDeclarationTool.IncPrefix;
begin
DebugPrefix:=DebugPrefix+' ';
end;
{$ENDIF}
function TFindDeclarationTool.FindExpressionResultType(
Params: TFindDeclarationParams; StartPos, EndPos: integer;
AliasType: PFindContext): TExpressionType;
{
- operators
- mixing ansistring and shortstring gives ansistring
- Pointer +,- Pointer gives Pointer
- Sets:
[enum1] gives set of enumeration type
set *,-,+ set gives set of same type
set <>,=,<,> set gives boolean
- precedence rules table:
1. brackets
2. not @ sign
3. * / div mod and shl shr as
4. + - or xor
5. < <> > <= >= in is
- nil is compatible to pointers and classes
- operator overloading?
- internal types. e.g. string[], ansistring[], shortstring[], pchar[] to char
- the type of a subrange is the type of the first constant/enum/number/char
- predefined types:
ordinal:
int64, cardinal, QWord, boolean, bytebool, wordbool, qwordbool, longbool, char
real:
real, single, double, extended, cextended, comp, currency
- predefined functions:
function pred(ordinal type): ordinal constant of same type;
function succ(ordinal type): ordinal constant of same type;
function ord(ordinal type): ordinal type;
val?
function low(array): type of leftmost index type in the array;
function high(array): type of leftmost index type in the array;
procedure dec(ordinal var);
procedure dec(ordinal var; ordinal type);
procedure dec(pointer var);
procedure dec(pointer var; ordinal type);
procedure inc(ordinal var);
procedure inc(ordinal var; ordinal type);
procedure inc(pointer var);
procedure inc(pointer var; ordinal type);
procedure write(...);
procedure writeln(...);
function SizeOf(type): ordinal constant;
typeinfo?
uniquestring?
procedure include(set type,enum identifier);
procedure exclude(set type,enum identifier);
function objcselector(string): sel;
}
type
TOperandAndOperator = record
Operand: TOperand;
theOperator: TAtomPosition;
OperatorLvl: integer;
end;
POperandAndOperator = ^TOperandAndOperator;
TExprStack = array[0..4] of TOperandAndOperator;
var
CurExprType: TExpressionType;
CurAliasType: PFindContext;
AliasTypeStorage: TFindContext;
ExprStack: TExprStack;
StackPtr: integer;
procedure ExecuteStack(Complete: boolean);
{ Executes the operand+operator stack
Examples:
Position Operand Operator
0 AWord *
1 AByte +
Because * has higher predence than + the stack is executed:
AWord*AByte gives an integer. New stack
Position Operand Operator
0 Integer +
}
var
NewOperand: TOperand;
LastPos: TAtomPosition;
begin
if StackPtr<=0 then begin
// only one element -> nothing to do
exit;
end;
LastPos:=CurPos;
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.FindExpressionResultType.ExecuteStack] ',
' StackPtr=',dbgs(StackPtr),
' Lvl=',dbgs(ExprStack[StackPtr].OperatorLvl),
' Complete=',dbgs(Complete));
{$ENDIF}
while (StackPtr>0)
and (Complete
or (ExprStack[StackPtr-1].OperatorLvl<=ExprStack[StackPtr].OperatorLvl)) do
begin
// next operand has a higher or equal precedence
// (lower is computed before higher)
// -> calculate last two operands
NewOperand:=CalculateBinaryOperator(ExprStack[StackPtr-1].Operand,
ExprStack[StackPtr].Operand,ExprStack[StackPtr-1].theOperator,
Params);
// put result on stack
ExprStack[StackPtr-1]:=ExprStack[StackPtr];
dec(StackPtr);
ExprStack[StackPtr].Operand:=NewOperand;
end;
MoveCursorToAtomPos(LastPos);
end;
procedure RaiseBinaryOperatorNotFound;
begin
RaiseExceptionFmt(20170421200256,ctsStrExpectedButAtomFound,[ctsBinaryOperator,GetAtom]);
end;
procedure RaiseInternalError;
begin
RaiseException(20170421200300,'[TFindDeclarationTool.FindExpressionResultType]'
+' internal error: unknown precedence lvl for operator '+GetAtom);
end;
procedure RaiseInternalErrorStack;
begin
RaiseException(20170421200303,'[TFindDeclarationTool.FindExpressionResultType]'
+' internal error: stackptr too big ');
end;
var
OldFlags: TFindDeclarationFlags;
StackEntry: POperandAndOperator;
IsEnd, IsBinOpError: Boolean;
begin
{$IFDEF ShowExprEval}
DebugLn(['[TFindDeclarationTool.FindExpressionResultType] Start',
' Pos=',StartPos,'-',EndPos,
'="',dbgstr(Src,StartPos,EndPos-StartPos),'" Context=',Params.ContextNode.DescAsString,' Alias=',AliasType<>nil]);
{$ENDIF}
Result:=CleanExpressionType;
if (AliasType<>nil) and (AliasType^.Node=nil) then begin
AliasTypeStorage:=CleanFindContext;
CurAliasType:=@AliasTypeStorage;
end else
CurAliasType:=nil;
OldFlags:=Params.Flags;
Exclude(Params.Flags,fdfFindVariable);
// read the expression from left to right and calculate the type
StackPtr:=-1;
MoveCursorToCleanPos(StartPos);
repeat
// read operand
CurExprType:=ReadOperandTypeAtCursor(Params,EndPos,CurAliasType);
{$IFDEF ShowExprEval}
DebugLn(['[TFindDeclarationTool.FindExpressionResultType] Operand: ',
ExprTypeToString(CurExprType),' Alias=',FindContextToString(CurAliasType)]);
{$ENDIF}
// put operand on stack
inc(StackPtr);
if StackPtr>High(ExprStack) then
RaiseInternalErrorStack;
StackEntry:=@ExprStack[StackPtr];
StackEntry^.Operand.Expr:=CurExprType;
if CurAliasType<>nil then
StackEntry^.Operand.AliasType:=CurAliasType^
else
StackEntry^.Operand.AliasType:=CleanFindContext;
StackEntry^.theOperator.StartPos:=-1;
StackEntry^.OperatorLvl:=5;
// read operator
ReadNextAtom;
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.FindExpressionResultType] Operator: ',
GetAtom,' CurPos.EndPos=',dbgs(CurPos.EndPos),' EndPos=',dbgs(EndPos));
{$ENDIF}
IsEnd := (CurPos.EndPos>EndPos) or (CurExprType.Desc=xtNone);
if not IsEnd then
IsBinOpError := not WordIsBinaryOperator.DoItCaseInsensitive(Src,CurPos.StartPos,
CurPos.EndPos-CurPos.StartPos)
else
IsBinOpError := False;
// check if expression is completely parsed
if IsEnd or (IsBinOpError and (fdfIgnoreOperatorError in Params.Flags)) then
begin
// -> execute complete stack
ExecuteStack(true);
Result:=ExprStack[StackPtr].Operand.Expr;
if CurAliasType<>nil then
AliasType^:=ExprStack[StackPtr].Operand.AliasType;
Params.Flags:=OldFlags;
exit;
end;
if IsBinOpError then
RaiseBinaryOperatorNotFound;
// put operator on stack
ExprStack[StackPtr].theOperator:=CurPos;
// find operator precendence level
if WordIsLvl1Operator.DoItCaseInsensitive(Src,CurPos.StartPos,
CurPos.EndPos-CurPos.StartPos)
then
ExprStack[StackPtr].OperatorLvl:=1
else if WordIsLvl2Operator.DoItCaseInsensitive(Src,CurPos.StartPos,
CurPos.EndPos-CurPos.StartPos)
then
ExprStack[StackPtr].OperatorLvl:=2
else if WordIsLvl3Operator.DoItCaseInsensitive(Src,CurPos.StartPos,
CurPos.EndPos-CurPos.StartPos)
then
ExprStack[StackPtr].OperatorLvl:=3
else if WordIsLvl4Operator.DoItCaseInsensitive(Src,CurPos.StartPos,
CurPos.EndPos-CurPos.StartPos)
then
ExprStack[StackPtr].OperatorLvl:=4
else
RaiseInternalError;
// execute stack if possible
ExecuteStack(false);
// move cursor to next atom (= next operand start)
ReadNextAtom;
until false;
end;
function TFindDeclarationTool.FindIdentifierInUsesSection(
UsesNode: TCodeTreeNode; Params: TFindDeclarationParams;
FindMissingFPCUnits: Boolean): boolean;
{ this function is internally used by FindIdentifierInContext
search backwards through the uses section
compare first all unit names, then load the units and search there
}
var
NewCodeTool: TFindDeclarationTool;
OldFlags: TFindDeclarationFlags;
Node: TCodeTreeNode;
CollectResult: TIdentifierFoundResult;
MissingUnit: TCodeTreeNode;
procedure RaiseUnitNotFound;
var
AnUnitName: String;
InFilename: String;
begin
AnUnitName:=ExtractUsedUnitName(MissingUnit,@InFilename);
RaiseExceptionInstance(
ECodeToolUnitNotFound.Create(Self,20170421200312,
Format(ctsUnitNotFound,[AnUnitName]),InFilename));
end;
var
AnUnitName: string;
InFilename: string;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(UsesNode);{$ENDIF}
{$IFDEF ShowTriedParentContexts}
DebugLn(['TFindDeclarationTool.FindIdentifierInUsesSection ',MainFilename,' fdfIgnoreUsedUnits=',fdfIgnoreUsedUnits in Params.Flags]);
{$ENDIF}
Result:=false;
// first search the identifier in the uses section (not in the interfaces of the units)
if (Params.IdentifierTool=Self) then begin
Node:=UsesNode.LastChild;
while Node<>nil do begin
if (fdfCollect in Params.Flags) then begin
CollectResult:=DoOnIdentifierFound(Params,Node.FirstChild);
if CollectResult=ifrAbortSearch then begin
Result:=false;
exit;
end else if CollectResult=ifrSuccess then begin
Result:=true;
Params.SetResult(Self,Node.FirstChild);
exit;
end;
end else if CompareSrcIdentifiers(Node.StartPos,Params.Identifier) then begin
// the searched identifier was a uses AUnitName, point to the identifier in
// the uses section
// if the unit name has a namespace defined point to the namespace
Params.SetResult(Self,Node.FirstChild);
Result:=true;
exit;
end;
Node:=Node.PriorBrother;
end;
end;
if not (fdfIgnoreUsedUnits in Params.Flags) then begin
MissingUnit:=nil;
// search in units
Node:=UsesNode.LastChild;
while Node<>nil do begin
AnUnitName:=ExtractUsedUnitName(Node,@InFilename);
if AnUnitName<>'' then begin
NewCodeTool:=FindCodeToolForUsedUnit(AnUnitName,InFilename,false);
if NewCodeTool<>nil then begin
// search the identifier in the interface of the used unit
OldFlags:=Params.Flags;
Params.Flags:=[fdfIgnoreUsedUnits]+(fdfGlobalsSameIdent*Params.Flags)
-[fdfExceptionOnNotFound];
Result:=NewCodeTool.FindIdentifierInInterface(Self,Params);
Params.Flags:=OldFlags;
if Result and Params.IsFoundProcFinal then exit;
end else if MissingUnit=nil then begin
MissingUnit:=Node;
end;
{$IFDEF ShowTriedParentContexts}
DebugLn(['TFindDeclarationTool.FindIdentifierInUsesSection ',AnUnitName,' Result=',Result]);
{$ENDIF}
end;
Node:=Node.PriorBrother;
end;
if (not Result) and (MissingUnit<>nil) then begin
// identifier not found and there is a missing unit
if FindMissingFPCUnits and Assigned(FOnRescanFPCDirectoryCache) then
begin
AnUnitName := LowerCase(AnUnitName);
if FFindMissingFPCUnits=nil then
FFindMissingFPCUnits := TFindIdentifierInUsesSection_FindMissingFPCUnit.Create;
if not FFindMissingFPCUnits.IsInResults(AnUnitName) // don't rescan twice
and FFindMissingFPCUnits.Find(AnUnitName, DirectoryCache) then
begin
FOnRescanFPCDirectoryCache(Self);
Result := FindIdentifierInUsesSection(UsesNode, Params, False);
end else
RaiseUnitNotFound;
end else
RaiseUnitNotFound;
end;
end;
end;
function TFindDeclarationTool.FindCodeToolForUsedUnit(const AnUnitName,
AnUnitInFilename: string; ExceptionOnNotFound: boolean): TFindDeclarationTool;
var
NewCode: TCodeBuffer;
begin
Result:=nil;
NewCode:=FindUnitSource(AnUnitName,AnUnitInFilename,ExceptionOnNotFound);
if (NewCode=nil) then begin
// no source found
if ExceptionOnNotFound then
RaiseException(20170421200315,'unit '+AnUnitName+' not found');
end else begin
// source found -> get codetool for it
{$IF defined(ShowTriedFiles) or defined(ShowTriedUnits)}
DebugLn('[TFindDeclarationTool.FindCodeToolForUsedUnit] ',
' This source is=',TCodeBuffer(Scanner.MainCode).Filename,
' NewCode=',NewCode.Filename);
{$ENDIF}
if Assigned(FOnGetCodeToolForBuffer) then
Result:=FOnGetCodeToolForBuffer(Self,NewCode,false)
else if NewCode=TCodeBuffer(Scanner.MainCode) then
Result:=Self;
end;
end;
function TFindDeclarationTool.FindIdentifierInInterface(
AskingTool: TFindDeclarationTool; Params: TFindDeclarationParams): boolean;
function CheckEntry(Entry: PInterfaceIdentCacheEntry): TIdentifierFoundResult;
begin
while Entry<>nil do begin
Params.SetResult(Self,Entry^.Node,Entry^.CleanPos);
Result:=DoOnIdentifierFound(Params,Params.NewNode);
if Result in [ifrSuccess,ifrAbortSearch] then
exit;
// proceed
Entry:=Entry^.Overloaded;
end;
Result:=ifrProceedSearch;
end;
var
CacheEntry: PInterfaceIdentCacheEntry;
AVLNode: TAVLTreeNode;
begin
Result:=false;
// build code tree
{$IFDEF ShowTriedContexts}
DebugLn({$IFDEF DebugPrefix}DebugPrefix,{$ENDIF}
'TFindDeclarationTool.FindIdentifierInInterface',
' Ident="',GetIdentifier(Params.Identifier),'"',
' IgnoreUsedUnits=',dbgs(fdfIgnoreUsedUnits in Params.Flags),
' Self=',TCodeBuffer(Scanner.MainCode).Filename
);
{$ENDIF}
// ToDo: build codetree for ppu, dcu files
// build tree for pascal source
if not BuildInterfaceIdentifierCache(true) then exit(false);
if (AskingTool<>Self) and (AskingTool<>nil) then
AskingTool.AddToolDependency(Self);
// search identifier in cache
if fdfCollect in Params.Flags then begin
AVLNode:=FInterfaceIdentifierCache.Items.FindLowest;
while AVLNode<>nil do begin
CacheEntry:=PInterfaceIdentCacheEntry(AVLNode.Data);
//DebugLn(['TFindDeclarationTool.FindIdentifierInInterface ',CacheEntry^.Identifier]);
case CheckEntry(CacheEntry) of
ifrSuccess: exit(true);
ifrAbortSearch: exit(false);
end;
AVLNode:=FInterfaceIdentifierCache.Items.FindSuccessor(AVLNode);
end;
end else begin
CacheEntry:=FInterfaceIdentifierCache.FindIdentifier(Params.Identifier);
if CacheEntry=nil then
exit(false);
case CheckEntry(CacheEntry) of
ifrSuccess: exit(true);
ifrAbortSearch: exit(false);
end;
end;
// proceed search
Result:=false;
end;
function TFindDeclarationTool.BuildInterfaceIdentifierCache(
ExceptionOnNotUnit: boolean): boolean;
procedure ScanForEnums(ParentNode: TCodeTreeNode);
var
Node: TCodeTreeNode;
begin
Node:=ParentNode.FirstChild;
if (Node=nil) or (Scanner.GetDirectiveValueAt(sdScopedEnums, Node.StartPos) = '1') then
Exit;
while Node<>nil do begin
if Node.Desc=ctnEnumIdentifier then
FInterfaceIdentifierCache.Add(@Src[Node.StartPos],Node,Node.StartPos);
if Node.FirstChild<>nil then
Node:=Node.FirstChild
else begin
while Node.NextBrother=nil do begin
Node:=Node.Parent;
if Node=ParentNode then exit;
end;
Node:=Node.NextBrother;
end;
end;
end;
procedure ScanChildren(ParentNode: TCodeTreeNode); forward;
procedure ScanNode(Node: TCodeTreeNode);
var
FirstChild: TCodeTreeNode;
begin
case Node.Desc of
ctnTypeSection,ctnConstSection,ctnVarSection,ctnResStrSection,ctnPropertySection:
ScanChildren(Node);
ctnVarDefinition,ctnConstDefinition,ctnTypeDefinition,ctnGlobalProperty:
begin
FInterfaceIdentifierCache.Add(@Src[Node.StartPos],Node,Node.StartPos);
ScanForEnums(Node);
FirstChild:=Node.FirstChild;
if (Node.Desc = ctnTypeDefinition) and (FirstChild<>nil) then begin
case FirstChild.Desc of
ctnClassHelper, ctnRecordHelper, ctnTypeHelper:
FInterfaceHelperCache[fdhlkDelphiHelper].AddFromHelperNode(FirstChild, Self,
True{ use last found helper}
);
ctnObjCCategory:
FInterfaceHelperCache[fdhlkObjCCategory].AddFromHelperNode(FirstChild, Self, false);
end;
end;
end;
ctnGenericType:
if Node.FirstChild<>nil then begin
FInterfaceIdentifierCache.Add(@Src[Node.FirstChild.StartPos],Node,Node.StartPos);
ScanForEnums(Node);
end;
ctnProperty:
begin
MoveCursorToPropName(Node);
FInterfaceIdentifierCache.Add(@Src[CurPos.StartPos],Node,Node.StartPos);
end;
ctnProcedure:
if (Node.FirstChild<>nil) and (not NodeIsOperator(Node)) then
FInterfaceIdentifierCache.Add(@Src[Node.FirstChild.StartPos],Node,
Node.FirstChild.StartPos);
end;
end;
procedure ScanChildren(ParentNode: TCodeTreeNode);
var
Node: TCodeTreeNode;
begin
Node:=ParentNode.FirstChild;
while Node<>nil do begin
ScanNode(Node);
Node:=Node.NextBrother;
end;
end;
var
InterfaceNode: TCodeTreeNode;
Node: TCodeTreeNode;
HelperKind: TFDHelpersListKind;
begin
// build tree for pascal source
//debugln(['TFindDeclarationTool.BuildInterfaceIdentifierCache BEFORE ',MainFilename]);
BuildTree(lsrImplementationStart);
//debugln(['TFindDeclarationTool.BuildInterfaceIdentifierCache AFTER ',MainFilename]);
if Tree.Root=nil then exit(false);
// search interface section
InterfaceNode:=FindInterfaceNode;
if InterfaceNode=nil then begin
// check source type
if ExceptionOnNotUnit then begin
MoveCursorToNodeStart(Tree.Root);
ReadNextAtom; // read keyword for source type, e.g. 'unit'
if not UpAtomIs('UNIT') then
RaiseException(20170421200317,ctsSourceIsNotUnit);
RaiseException(20170421200319,ctsInterfaceSectionNotFound);
end;
end;
// create tree
if (FInterfaceIdentifierCache<>nil) and FInterfaceIdentifierCache.Complete then
exit(true);
if FInterfaceIdentifierCache=nil then
FInterfaceIdentifierCache:=TInterfaceIdentifierCache.Create(Self)
else
FInterfaceIdentifierCache.Clear;
FInterfaceIdentifierCache.Complete:=true;
for HelperKind in TFDHelpersListKind do
if FInterfaceHelperCache[HelperKind]=nil then
FInterfaceHelperCache[HelperKind]:=TFDHelpersList.Create(HelperKind)
else
FInterfaceHelperCache[HelperKind].Clear;
// add unit node
MoveCursorToNodeStart(Tree.Root);
ReadNextAtom; // keyword unit
ReadNextAtom;
FInterfaceIdentifierCache.Add(@Src[CurPos.StartPos],Tree.Root,CurPos.StartPos);
// create nodes
if InterfaceNode<>nil then
// scan interface
ScanChildren(InterfaceNode)
else begin
// scan program
Node:=Tree.Root;
while Node<>nil do begin
ScanNode(Node);
Node:=Node.NextBrother;
end;
end;
//DebugLn(['TFindDeclarationTool.BuildInterfaceIdentifierCache ',MainFilename,' ',FInterfaceIdentifierCache.Items.Count,' ',GlobalIdentifierTree.Count]);
Result:=true;
end;
function TFindDeclarationTool.CompareNodeIdentifier(Node: TCodeTreeNode;
Params: TFindDeclarationParams): boolean;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(Node);{$ENDIF}
Result:=false;
if Node=nil then exit;
if Node.Desc in AllSourceTypes then begin
MoveCursorToNodeStart(Node);
ReadNextAtom;
if (Node.Desc=ctnProgram) and not UpAtomIs('PROGRAM') then exit;
ReadNextAtom;
Result:=CompareSrcIdentifiers(CurPos.StartPos,Params.Identifier);
end else if (Node.Desc in AllSimpleIdentifierDefinitions)
or (Node.Desc in [ctnIdentifier,ctnGenericName]) then begin
Result:=CompareSrcIdentifiers(Node.StartPos,Params.Identifier);
end else if Node.Desc=ctnGenericType then begin
if Node.FirstChild<>nil then
Result:=CompareSrcIdentifiers(Node.FirstChild.StartPos,Params.Identifier);
end;
end;
function TFindDeclarationTool.GetInterfaceNode: TCodeTreeNode;
begin
Result:=Tree.Root;
if Result=nil then begin
CurPos.StartPos:=-1;
RaiseException(20170421200323,'[TFindDeclarationTool.GetInterfaceNode] no code tree found');
end;
if not (Tree.Root.Desc in AllUsableSourceTypes) then begin
CurPos.StartPos:=-1;
RaiseException(20170421200325,ctsUsedUnitIsNotAPascalUnit);
end;
Result:=FindInterfaceNode;
if Result=nil then begin
CurPos.StartPos:=-1;
RaiseException(20170421200327,ctsInterfaceSectionNotFound);
end;
end;
function TFindDeclarationTool.FindIdentifierInUsedUnit(
const AnUnitName: string; Params: TFindDeclarationParams; ErrorPos: integer
): boolean;
{ Note: this function is internally used by FindIdentifierInHiddenUsedUnits
for hidden used units, like the system unit or the objpas unit
}
var
NewCode: TCodeBuffer;
NewCodeTool: TFindDeclarationTool;
OldFlags: TFindDeclarationFlags;
begin
Result:=false;
// open the unit and search the identifier in the interface
NewCode:=FindUnitSource(AnUnitName,'',true,ErrorPos);
if NewCode=TCodeBuffer(Scanner.MainCode) then begin
// Searching again in hidden unit
DebugLn('WARNING: Searching again in hidden unit: "',NewCode.Filename,'" identifier=',GetIdentifier(Params.Identifier));
NewCodeTool:=Self;
MoveCursorToCleanPos(ErrorPos);
RaiseExceptionFmt(20170421200330,ctsIllegalCircleInUsedUnits,[AnUnitName]);
end else begin
// source found -> get codetool for it
{$IF defined(ShowTriedContexts) or defined(ShowTriedUnits)}
DebugLn('[TFindDeclarationTool.FindIdentifierInUsedUnit] ',
' This source is=',TCodeBuffer(Scanner.MainCode).Filename,
' NewCode=',NewCode.Filename,' IgnoreUsedUnits=',dbgs(fdfIgnoreUsedUnits in Params.Flags));
{$ENDIF}
NewCodeTool:=nil;
if not Assigned(FOnGetCodeToolForBuffer) then begin
MoveCursorToCleanPos(ErrorPos);
RaiseExceptionFmt(20170421200333,
'Unable to create codetool for "%s", need OnGetCodeToolForBuffer',
[NewCode.Filename]);
end;
NewCodeTool:=FOnGetCodeToolForBuffer(Self,NewCode,false);
if NewCodeTool=nil then begin
MoveCursorToCleanPos(ErrorPos);
RaiseExceptionFmt(20170421200346,'Unable to create codetool for "%s"',[NewCode.Filename]);
end;
// search the identifier in the interface of the used unit
OldFlags:=Params.Flags;
Params.Flags:=[fdfIgnoreUsedUnits]+(fdfGlobalsSameIdent*Params.Flags)
-[fdfExceptionOnNotFound];
Result:=NewCodeTool.FindIdentifierInInterface(Self,Params);
Params.Flags:=OldFlags;
end;
end;
function TFindDeclarationTool.FindIdentifierInTypeOfConstant(
VarConstNode: TCodeTreeNode; Params: TFindDeclarationParams): boolean;
{ const a: atype = context;
for example: const p: TPoint = (x:0; y:0);
}
var
TypeNode: TCodeTreeNode;
ExprType: TExpressionType;
TypeParams: TFindDeclarationParams;
OldInput: TFindDeclarationInput;
begin
Result:=false;
//debugln(['TFindDeclarationTool.FindIdentifierInTypeOfConstant ',VarConstNode.DescAsString]);
TypeNode:=VarConstNode.FirstChild;
if TypeNode=nil then exit;
if TypeNode.Desc=ctnIdentifier then begin
// resolve type
//debugln(['TFindDeclarationTool.FindIdentifierInTypeOfConstant ']);
TypeParams:=TFindDeclarationParams.Create(Params);
try
TypeParams.ContextNode:=TypeNode;
TypeParams.SetIdentifier(Self,nil,nil);
TypeParams.Flags:=fdfDefaultForExpressions;
ExprType:=FindExpressionTypeOfTerm(TypeNode.StartPos,-1,TypeParams,false);
//debugln(['TFindDeclarationTool.FindIdentifierInTypeOfConstant ExprType=',ExprTypeToString(ExprType)]);
finally
TypeParams.Free;
end;
if ExprType.Desc=xtContext then begin
if ExprType.Context.Node.Parent=nil then exit;
if not (ExprType.Context.Node.Parent.Desc in [ctnTypeDefinition,ctnGenericType])
then
exit;
// search identifier in type
Params.Save(OldInput);
Params.ContextNode:=ExprType.Context.Node;
Params.Flags:=Params.Flags-[fdfIgnoreCurContextNode,fdfSearchInParentNodes];
Result:=ExprType.Context.Tool.FindIdentifierInContext(Params);
Params.Load(OldInput,true);
end;
end;
end;
procedure TFindDeclarationTool.RaiseUsesExpected(id: int64);
begin
RaiseExceptionFmt(id,ctsStrExpectedButAtomFound,['"uses"',GetAtom]);
end;
procedure TFindDeclarationTool.RaiseStrConstExpected(id: int64);
begin
RaiseExceptionFmt(id,ctsStrExpectedButAtomFound,[ctsStringConstant,GetAtom]);
end;
procedure TFindDeclarationTool.BeginParsing(Range: TLinkScannerRange);
begin
// scan code and init parser
inherited BeginParsing(Range);
// now the scanner knows, which compiler mode is needed
// -> setup compiler dependent tables
case Scanner.PascalCompiler of
pcDelphi: WordIsPredefinedIdentifier:=WordIsPredefinedDelphiIdentifier;
pcPas2js: WordIsPredefinedIdentifier:=WordIsPredefinedPas2jsIdentifier;
else
WordIsPredefinedIdentifier:=WordIsPredefinedFPCIdentifier;
end;
end;
function TFindDeclarationTool.FindIdentifierInHiddenUsedUnits(
Params: TFindDeclarationParams): boolean;
var
HiddenUnits: String;
p: Integer;
AnUnitName: String;
begin
Result:=false;
{$IFDEF ShowTriedContexts}
DebugLn('[TFindDeclarationTool.FindIdentifierInHiddenUsedUnits] ',
'"',GetIdentifier(Params.Identifier),'" IgnoreUsedUnits=',dbgs(fdfIgnoreUsedUnits in Params.Flags));
{$ENDIF}
if (Tree.Root<>nil) and (not (fdfIgnoreUsedUnits in Params.Flags)) then begin
HiddenUnits:=Scanner.GetHiddenUsedUnits;
{$IFDEF ShowTriedContexts}
debugln(['TFindDeclarationTool.FindIdentifierInHiddenUsedUnits Identifier=',GetIdentifier(Params.Identifier),' ',Scanner.MainFilename,' SourceName=',Scanner.SourceName,' HiddenUnits=',HiddenUnits]);
{$ENDIF}
p:=length(HiddenUnits);
while p>=1 do begin
while (p>1) and (HiddenUnits[p-1]<>',') do dec(p);
AnUnitName:=GetDottedIdentifier(@HiddenUnits[p]);
if AnUnitName<>'' then begin
// try hidden used unit
Result:=FindIdentifierInUsedUnit(AnUnitName,Params,0);
if Result and Params.IsFoundProcFinal then exit;
end;
dec(p);
end;
end;
end;
function TFindDeclarationTool.FindEndOfTerm(
StartPos: integer; ExceptionIfNoVariableStart, WithAsOperator: boolean
): integer;
{ ExceptionIfNoVariableStart: if false allow starting in the middle of a term
a variable can have the form:
A
A.B()^.C()[]^^.D
(A).B
inherited A
A as B
}
procedure RaiseIdentNotFound;
begin
RaiseExceptionFmt(20170421200525,ctsIdentExpectedButAtomFound,[GetAtom]);
end;
var
FirstIdentifier: boolean;
procedure StartVar;
begin
ReadNextAtom;
if UpAtomIs('INHERITED') then
ReadNextAtom;
if UpAtomIs('ARRAY') then
begin
ReadNextAtom;
if UpAtomIs('OF') then
ReadNextAtom;
end;
FirstIdentifier:=true;
if not (CurPos.Flag in AllCommonAtomWords) then exit;
AtomIsIdentifierE;
FirstIdentifier:=false;
ReadNextAtom;
end;
begin
MoveCursorToCleanPos(StartPos);
StartVar;
repeat
case CurPos.Flag of
cafRoundBracketOpen:
begin
ReadTilBracketClose(true);
FirstIdentifier:=false;
end;
cafPoint:
begin
if FirstIdentifier and ExceptionIfNoVariableStart then
RaiseIdentNotFound;
ReadNextAtom;
AtomIsIdentifierE;
end;
cafEdgedBracketOpen:
begin
if FirstIdentifier and ExceptionIfNoVariableStart then
RaiseIdentNotFound;
ReadTilBracketClose(true);
end;
else
if AtomIsChar('^') then begin
if FirstIdentifier and ExceptionIfNoVariableStart then
RaiseIdentNotFound;
end else if UpAtomIs('AS') then begin
if not WithAsOperator then
break;
StartVar;
UndoReadNextAtom;
end else
break;
end;
ReadNextAtom;
until false;
if LastAtoms.HasPrior then
UndoReadNextAtom
else
MoveCursorToCleanPos(StartPos);
Result:=CurPos.EndPos;
end;
function TFindDeclarationTool.FindStartOfTerm(EndPos: integer; InType: boolean
): integer;
{ a variable can be combinations of
1. A.B
2. A().B
3. inherited A
4. A[].
5. A[].B
6. A^.
7. (A).
8. (A as B)
9. (@A)
10. A()[]
11. nothing (e.g. cursor behind semicolon, keyword or closing bracket)
12. 'A'.B (constant.B, type helpers)
}
procedure RaiseIdentNotFound;
begin
RaiseExceptionFmt(20170421200528,ctsIdentExpectedButAtomFound,[GetAtom]);
end;
var CurAtom, NextAtom: TAtomPosition;
NextAtomType, CurAtomType: TVariableAtomType;
StartPos: LongInt;
CurIsValue, NextIsValue: Boolean;
begin
StartPos:=FindStartOfAtom(Src,EndPos);
MoveCursorToCleanPos(StartPos);
NextAtom:=CurPos;
if not IsSpaceChar[Src[StartPos]] then
ReadNextAtom;
NextAtomType:=GetCurrentAtomType;
NextIsValue:=NextAtomType in [vatIdentifier,vatPreDefIdentifier,vatNumber,vatStringConstant];
repeat
ReadPriorAtom;
CurAtom:=CurPos;
CurAtomType:=GetCurrentAtomType;
if CurAtomType=vatNone then begin
Result:=NextAtom.StartPos;
exit;
end;
//DebugLn(['TFindDeclarationTool.FindStartOfTerm ',GetAtom,' Cur=',VariableAtomTypeNames[CurAtomType],' Next=',VariableAtomTypeNames[NextAtomType]]);
if CurAtomType in [vatRoundBracketClose,vatEdgedBracketClose] then begin
if NextAtomType in [vatRoundBracketOpen,vatRoundBracketClose,
vatEdgedBracketOpen,vatEdgedBracketClose,vatPoint,vatUp,
vatAS,vatNone,vatSpace]
then begin
ReadBackTilBracketOpen(true);
CurAtom.StartPos:=CurPos.StartPos;
end else begin
Result:=NextAtom.StartPos;
exit;
end;
end;
// check if CurAtom belongs to variable
if CurAtomType=vatINHERITED then begin
Result:=CurAtom.StartPos;
exit;
end;
if (CurAtomType in [vatAS,vatKeyword]) then begin
Result:=NextAtom.StartPos;
exit;
end;
if (CurAtomType=vatUp) and InType then begin
Result:=NextAtom.StartPos;
exit;
end;
CurIsValue:=CurAtomType in [vatIdentifier,vatPreDefIdentifier,vatNumber,vatStringConstant];
if (not (CurAtomType in [vatIdentifier,vatPreDefIdentifier,vatNumber,vatStringConstant,
vatPoint,vatUp,vatEdgedBracketClose,vatRoundBracketClose]))
or (CurIsValue and NextIsValue)
then begin
// boundary found between current and next
if NextAtom.StartPos>=EndPos then begin
// no token belongs to a variable (e.g. ; ;)
Result:=EndPos;
end else begin
// the next atom is the start of the variable
if (not (NextAtomType in [vatSpace,vatIdentifier,vatPreDefIdentifier,
vatRoundBracketClose,vatEdgedBracketClose,vatAddrOp])) then
begin
MoveCursorToCleanPos(NextAtom.StartPos);
ReadNextAtom;
RaiseIdentNotFound;
end;
Result:=NextAtom.StartPos;
end;
exit;
end;
NextAtom:=CurAtom;
NextAtomType:=CurAtomType;
NextIsValue:=CurIsValue;
until false;
end;
function TFindDeclarationTool.NodeTermInType(Node: TCodeTreeNode): boolean;
begin
if Node=nil then exit(false);
Result:=not (Node.Desc in AllPascalStatements);
end;
function TFindDeclarationTool.FindExpressionTypeOfTerm(StartPos,
EndPos: integer; Params: TFindDeclarationParams; WithAsOperator: boolean;
AliasType: PFindContext): TExpressionType;
{ examples
1. A.B
2. A().B
3. inherited A
4. A[]
5. A[].B
6. A^.
7. (A).
8. (A as B)
9. (@A)
10. A as B
}
type
TIsIdentEndOfVar = (iieovYes, iieovNo, iieovUnknown);
var
CurAtomType: TVariableAtomType;
NextAtomType: TVariableAtomType; // next, if CurAtomType is brackets then after the brackets
PrevAtomType: TVariableAtomType; // previous, start of brackets
CurAtom, NextAtom: TAtomPosition;
CurAtomBracketEndPos: integer;
StartNode: TCodeTreeNode;
OldInput: TFindDeclarationInput;
StartFlags: TFindDeclarationFlags;
IsIdentEndOfVar: TIsIdentEndOfVar;
FlagCanBeForwardDefined, FlagCanBeForwardDefinedValid: boolean;
ExprType: TExpressionType;
FirstParamStartPos: Integer;
FirstParamProcContext: TFindContext;
procedure RaiseIdentExpected;
begin
RaiseExceptionFmt(20170421200530,ctsStrExpectedButAtomFound,[ctsIdentifier,GetAtom]);
end;
procedure RaiseIdentNotFound;
begin
RaiseExceptionFmt(20170421200532,ctsIdentifierNotFound,[GetAtom]);
end;
procedure RaiseIllegalQualifierFound;
begin
RaiseExceptionFmt(20170421200535,ctsIllegalQualifier,[GetAtom]);
end;
procedure RaisePointNotFound;
begin
RaiseExceptionFmt(20170421200537,ctsStrExpectedButAtomFound,['.',GetAtom]);
end;
procedure RaiseClassDeclarationNotFound(Tool: TFindDeclarationTool);
begin
Tool.RaiseExceptionFmt(20170421200539,ctsClassSNotFound, [Tool.GetAtom]);
end;
function InitAtomQueue: boolean;
procedure RaiseInternalError;
begin
RaiseException(20170421200543,'internal codetool error: FindExpressionTypeOfVariable '
+' StartPos='+IntToStr(StartPos)+' EndPos='+IntToStr(EndPos));
end;
begin
Result:=false;
if StartPos<1 then
StartPos:=FindStartOfTerm(EndPos,NodeTermInType(Params.ContextNode))
else if EndPos<1 then
EndPos:=FindEndOfTerm(StartPos,true,WithAsOperator);
//DebugLn(['InitAtomQueue StartPos=',StartPos,'=',dbgstr(copy(Src,StartPos,10)),' EndPos=',dbgstr(copy(Src,EndPos,10))]);
if (StartPos<1) then
RaiseInternalError;
if StartPos>SrcLen then exit;
if StartPos=EndPos then begin
// e.g. cursor behind semicolon, keyword or closing bracket
exit;
end;
{$IFDEF ShowExprEval}
DebugLn([' FindExpressionTypeOfTerm InitAtomQueue StartPos=',StartPos,' EndPos=',EndPos,' Expr="',copy(Src,StartPos,EndPos-StartPos),'"']);
{$ENDIF}
PrevAtomType:=vatNone;
MoveCursorToCleanPos(StartPos);
ReadNextAtom;
if CurPos.StartPos>SrcLen then exit;
CurAtom:=CurPos;
CurAtomType:=GetCurrentAtomType;
if CurAtomType in [vatRoundBracketOpen,vatEdgedBracketOpen] then
ReadTilBracketClose(true);
CurAtomBracketEndPos:=CurPos.EndPos;
ReadNextAtom;
NextAtom:=CurPos;
if NextAtom.EndPos<=EndPos then
NextAtomType:=GetCurrentAtomType
else
NextAtomType:=vatSpace;
MoveCursorToCleanPos(CurAtom.StartPos);
IsIdentEndOfVar:=iieovUnknown;
FlagCanBeForwardDefinedValid:=false;
Result:=true;
end;
procedure ReadNextExpressionAtom;
begin
PrevAtomType:=CurAtomType;
CurAtom:=NextAtom;
CurAtomType:=NextAtomType;
MoveCursorToCleanPos(NextAtom.StartPos);
ReadNextAtom;
if CurAtomType in [vatRoundBracketOpen,vatEdgedBracketOpen] then
ReadTilBracketClose(true);
CurAtomBracketEndPos:=CurPos.EndPos;
ReadNextAtom;
NextAtom:=CurPos;
if NextAtom.EndPos<=EndPos then
NextAtomType:=GetCurrentAtomType
else
NextAtomType:=vatSpace;
MoveCursorToCleanPos(CurAtom.StartPos);
IsIdentEndOfVar:=iieovUnknown;
end;
function IsIdentifierEndOfVariable: boolean;
var BehindFuncAtomType: TVariableAtomType;
begin
if IsIdentEndOfVar=iieovUnknown then begin
if CurAtom.StartPos>=EndPos then begin
IsIdentEndOfVar:=iieovYes;
end else if CurAtom.Flag=cafWord then begin
ReadNextAtom;
if AtomIsChar('(') then begin
ReadTilBracketClose(true);
ReadNextAtom;
end;
if CurPos.StartPos<EndPos then begin
BehindFuncAtomType:=GetCurrentAtomType;
if (BehindFuncAtomType in [vatPoint,vatUP,
vatEdgedBracketOpen,vatRoundBracketOpen])
then
IsIdentEndOfVar:=iieovNo
else
IsIdentEndOfVar:=iieovYes;
end else begin
IsIdentEndOfVar:=iieovYes;
end;
end else begin
IsIdentEndOfVar:=iieovNo
end;
end;
Result:=(IsIdentEndOfVar=iieovYes);
end;
function CanBeForwardDefined: boolean;
var
Node: TCodeTreeNode;
begin
if not FlagCanBeForwardDefinedValid then begin
FlagCanBeForwardDefinedValid:=true;
FlagCanBeForwardDefined:=false;
Node:=StartNode;
while Node<>nil do begin
if Node.Desc in [ctnTypeDefinition,ctnGenericType] then begin
FlagCanBeForwardDefined:=true;
break;
end else if not (Node.Desc in AllPascalTypes) then
break;
Node:=Node.Parent;
end;
end;
Result:=FlagCanBeForwardDefined;
end;
procedure ResolveTypeLessProperty;
begin
if ExprType.Desc<>xtContext then exit;
with ExprType.Context do begin
if not (Node.Desc in [ctnProperty,ctnGlobalProperty]) then exit;
if Tool.PropNodeIsTypeLess(Node)
and Tool.MoveCursorToPropName(Node) then begin
// typeless property => search in ancestors: it can be property with parameters
Params.Save(OldInput);
Params.SetIdentifier(Tool,@Tool.Src[Tool.CurPos.StartPos],nil);
Params.Flags:=[fdfSearchInAncestors,fdfSearchInHelpers];
if Tool.FindIdentifierInAncestors(Node.Parent.Parent,Params) then begin
Tool:=Params.NewCodeTool;
Node:=Params.NewNode;
end;
Params.Load(OldInput,true);
end;
end;
end;
procedure ResolveStringFunctionParam;
var
FirstParamAlias: TFindContext;
FirstParamExprType: TExpressionType;
begin
MoveCursorToCleanPos(FirstParamStartPos);
ReadNextAtom;
if (CurPos.Flag=cafRoundBracketOpen) then
begin
ReadNextAtom;
FirstParamStartPos := CurPos.StartPos;
if CurPos.Flag<>cafRoundBracketClose then
begin
// read first expressions
// read til comma or bracket close
repeat
while not(AtomIsChar(',') or AtomIsChar('[') or AtomIsChar('(') or AtomIsChar(')')) do
ReadNextAtom;
if CurPos.Flag in [cafRoundBracketOpen,cafEdgedBracketOpen] then begin
ReadTilBracketClose(true);
ReadNextAtom;
end;
if (CurPos.StartPos>SrcLen)
or (CurPos.Flag in [cafRoundBracketClose,cafEdgedBracketClose,cafComma])
then
break;
until false;
// find expression type
Params.Flags:=Params.Flags-[fdfExceptionOnNotFound];
FillChar(FirstParamAlias{%H-}, SizeOf(FirstParamAlias), 0);
//DebugLn('TFindDeclarationTool.CreateParamExprListFromStatement CurIgnoreErrorAfterPos=',dbgs(CurIgnoreErrorAfterPos),' ExprStartPos=',dbgs(ExprStartPos));
FirstParamExprType:=FindExpressionResultType(Params,FirstParamStartPos,CurPos.StartPos,@FirstParamAlias);
if (FirstParamExprType.Desc in [xtAnsiString, xtString, xtShortString]) then
begin
ExprType := FirstParamExprType;
if AliasType<>nil then
AliasType^ := FirstParamAlias;
end;
end;
end;
end;
procedure ResolveBaseTypeOfIdentifier;
{ normally not the identifier is searched, but its type
but there is one exception:
if the identifier is a function and it is the end of the variable then
the decision is based on the fdfFunctionResult flag.
}
var
ProcNode, FuncResultNode, FirstParamNode: TCodeTreeNode;
AtEnd: Boolean;
CurAliasType: PFindContext;
Context: TFindContext;
FirstParamProcExpr: TExpressionType;
NewParams: TFindDeclarationParams;
begin
//DebugLn(['ResolveBaseTypeOfIdentifier ',ExprType.Context.Node<>nil]);
if ExprType.Desc=xtContext then
Context:=ExprType.Context
else
Context:=CreateFindContext(Self,StartNode);
if (Context.Node=nil) then exit;
AtEnd:=IsIdentifierEndOfVariable;
// check if at the end of the variable
if AtEnd and (fdfFindVariable in StartFlags) then begin
// the variable is wanted, not its type
exit;
end;
if (not AtEnd)
and (Context.Node.Desc in [ctnProperty,ctnGlobalProperty])
then begin
ResolveTypeLessProperty;
end;
CurAliasType:=nil;
if AtEnd then CurAliasType:=AliasType;
// find base type
Params.Flags:=Params.Flags+[fdfEnumIdentifier]-[fdfFunctionResult,fdfFindChildren];
{$IFDEF ShowExprEval}
DebugLn([' FindExpressionTypeOfTerm ResolveBaseTypeOfIdentifier BEFORE ExprType=',ExprTypeToString(ExprType),' Alias=',CurAliasType<>nil]);
{$ENDIF}
ExprType:=Context.Tool.ConvertNodeToExpressionType(
Context.Node,Params,CurAliasType);
{$IFDEF ShowExprEval}
DebugLn([' FindExpressionTypeOfTerm ResolveBaseTypeOfIdentifier AFTER ExprType=',ExprTypeToString(ExprType),' Alias=',FindContextToString(CurAliasType)]);
{$ENDIF}
if (ExprType.Desc=xtContext)
and (ExprType.Context.Node.Desc in [ctnProcedure,ctnProcedureHead]) then
begin
// check if this is a function
ProcNode:=ExprType.Context.Node;
if ProcNode.Desc=ctnProcedureHead then
ProcNode:=ProcNode.Parent;
ExprType.Context.Tool.BuildSubTreeForProcHead(ProcNode.FirstChild,
FuncResultNode);
{$IFDEF ShowExprEval}
DebugLn([' FindExpressionTypeOfTerm ResolveBaseTypeOfIdentifier IsFunction=',FuncResultNode<>nil,' IsIdentifierEndOfVariable=',IsIdentifierEndOfVariable,' fdfFunctionResult in StartFlags=',fdfFunctionResult in StartFlags]);
{$ENDIF}
if (FuncResultNode<>nil) then begin
// it is function
// -> use the result type instead of the function
if AtEnd then begin
// this function identifier is the end of the variable
if not (fdfFunctionResult in StartFlags) then
exit;
end;
Include(Params.Flags,fdfFunctionResult);
ExprType:=ExprType.Context.Tool.ConvertNodeToExpressionType(
ProcNode,Params,CurAliasType);
if (ExprType.Desc in [xtAnsiString, xtString, xtShortString])
and (FirstParamStartPos>0)
and (FirstParamProcContext.Node<>nil) then
begin
FirstParamNode := FirstParamProcContext.Node;
while (FirstParamNode<>nil) and (FirstParamNode.Desc in [ctnProcedure, ctnProcedureHead, ctnParameterList]) do
FirstParamNode := FirstParamNode.FirstChild;
if (FirstParamNode<>nil) and (FirstParamNode.Desc=ctnVarDefinition) then
begin
while FirstParamNode.NextBrother<>nil do
FirstParamNode := FirstParamNode.NextBrother;
FirstParamNode := FirstParamNode.FirstChild;
end;
if (FirstParamNode<>nil) and (FirstParamNode.Desc=ctnIdentifier) then
begin
NewParams := TFindDeclarationParams.Create(FirstParamProcContext.Tool, FirstParamProcContext.Node);
try
FirstParamProcExpr := FirstParamProcContext.Tool.FindExpressionResultType(NewParams, FirstParamNode.StartPos, FirstParamNode.EndPos);
finally
NewParams.Free;
end;
if FirstParamProcExpr.Desc in [xtAnsiString, xtString, xtShortString] then
ResolveStringFunctionParam;
end;
end;
end;
end;
end;
function ResolveUseUnit(StartUseUnitNode: TCodeTreeNode): TCodeTreeNode;
// IsStart=true, NextAtomType=vatPoint,
// StartUseUnitNameNode.Desc=ctnUseUnit
// -> Find the longest namespaced used unit (ctnUseUnitNamespace,ctnUseUnitClearName)
// or the source name (ctnIdentifier), that fits the start of the
// current identifier a.b.c...
//
function GetPrevUseUnit(UseUnitNode: TCodeTreeNode): TCodeTreeNode;
begin
if UseUnitNode.PriorBrother<>nil then
Result:=UseUnitNode.PriorBrother
else begin
if UseUnitNode.Parent.Parent.Desc=ctnImplementation then begin
Result:=FindMainUsesNode;
if Result<>nil then
Result:=Result.FirstChild;
end else
Result:=nil;
end;
end;
var
UseUnitNode, Node, BestNode: TCodeTreeNode;
HasNamespace: Boolean;
Count, Level, BestLevel: Integer;
p: PChar;
DottedIdentifier: String;
begin
Result:=StartUseUnitNode.FirstChild;
//debugln(['ResolveUsenit START ',NextAtomType,' ',StartUseUnitNode.DescAsString,' "',GetIdentifier(@Src[CurAtom.StartPos]),'"']);
// find all candidates
Count:=0;
HasNamespace:=false;
UseUnitNode:=StartUseUnitNode;
repeat
if (UseUnitNode.FirstChild<>nil)
and CompareSrcIdentifiers(CurAtom.StartPos,UseUnitNode.StartPos) then begin
// found candidate
inc(Count);
//debugln(['ResolveUsenit candidate found']);
if UseUnitNode.FirstChild.Desc=ctnUseUnitNamespace then begin
HasNamespace:=true;
end;
end;
UseUnitNode:=GetPrevUseUnit(UseUnitNode);
until UseUnitNode=nil;
//debugln(['ResolveUsenit CandidateCount=',Count,' HasNamespace=',HasNamespace]);
if not HasNamespace then exit;
// multiple uses start with this identifier -> collect candidates
//debugln(['ResolveUsenit collect candidates ...']);
// read a.b.c...
DottedIdentifier:=GetIdentifier(@Src[CurAtom.StartPos]);
MoveCursorToCleanPos(NextAtom.EndPos);
Level:=1;
repeat
ReadNextAtom;
if not AtomIsIdentifier then break;
inc(Level);
DottedIdentifier:=DottedIdentifier+'.'+GetAtom;
ReadNextAtom;
until CurPos.Flag<>cafPoint;
//debugln(['ResolveUsenit DottedIdentifier="',DottedIdentifier,'"']);
// find longest dotted unit name in uses and source name
UseUnitNode:=StartUseUnitNode;
BestNode:=nil;
BestLevel:=0;
repeat
Node:=UseUnitNode.FirstChild; // ctnUseUnitNamespace or ctnUseUnitClearName
UseUnitNode:=GetPrevUseUnit(UseUnitNode);
if (Node<>nil)
and CompareSrcIdentifiers(CurAtom.StartPos,Node.StartPos) then begin
// found candidate
//debugln(['ResolveUseUnit Candidate=',ExtractNode(Node,[])]);
Level:=1;
p:=PChar(DottedIdentifier);
repeat
inc(p,GetIdentLen(p));
if p^='.' then inc(p);
//debugln(['ResolveUseUnit p=',p,' NextBrother=',Node.NextBrother<>nil]);
if Node.NextBrother=nil then begin
// fits
if Level>BestLevel then begin
BestNode:=Node.Parent;
BestLevel:=Level;
end;
break;
end else if p^=#0 then begin
// unitname too long
break;
end else begin
Node:=Node.NextBrother;
//debugln(['ResolveUseUnit p=',p,' node=',GetIdentifier(@Src[Node.StartPos])]);
if not CompareSrcIdentifiers(Node.StartPos,p) then
break;
inc(Level);
end;
until false;
end;
until UseUnitNode=nil;
//debugln(['ResolveUseUnit collected candidates Best=',ExtractNode(BestNode,[])]);
//debugln(['ResolveUseUnit Src=',Tree.Root.DescAsString,' Name=',GetSourceName(false),' DottedIdentifier="',DottedIdentifier,'"']);
// check source name
if (Tree.Root.Desc in AllSourceTypes)
and (Tree.Root.FirstChild<>nil)
and (Tree.Root.FirstChild.Desc=ctnSrcName)
and CompareSrcIdentifiers(Tree.Root.FirstChild.StartPos,PChar(DottedIdentifier))
then begin
// found candidate
Level:=1;
Node:=Tree.Root.FirstChild.FirstChild;
//debugln(['ResolveUseUnit Candidate SrcName']);
p:=PChar(DottedIdentifier);
repeat
//debugln('ResolveUseUnit SrcName p=',p,' Node=',ExtractNode(Node,[]));
if (Node.FirstChild=nil) or (Node.NextBrother.Desc<>ctnIdentifier) then begin
// fits
//debugln(['ResolveUseUnit FITS Level=',Level,' Best=',BestLevel]);
if Level>BestLevel then begin
// source name fits best
Result:=Tree.Root.FirstChild.FirstChild;
// move cursor forward
while (Result.NextBrother<>nil)
and (NextAtom.EndPos<EndPos) do begin
if (Result.NextBrother=nil) then
exit(Tree.Root);
ReadNextExpressionAtom; // read point
ReadNextExpressionAtom; // read namespace/unitname
//debugln(['ResolveUseUnit Next ',GetAtom(CurAtom)]);
Result:=Result.NextBrother;
end;
//debugln(['ResolveUseUnit SrcName fits better']);
exit;
end;
break;
end else if p^=#0 then begin
// source name too long
break;
end else begin
Node:=Node.NextBrother;
inc(p,GetIdentLen(p));
if p^='.' then inc(p);
//debugln('ResolveUseUnit SrcName NEXT p=',p,' Node=',ExtractNode(Node,[]));
if not CompareSrcIdentifiers(Node.StartPos,p) then
break;
inc(Level);
end;
until false;
end;
Result:=BestNode;
if Result=nil then exit;
// Result is now a ctnUseUnit
Result:=Result.FirstChild;
// move cursor forward
while (Result.NextBrother<>nil) and (NextAtom.EndPos<EndPos) do begin
ReadNextExpressionAtom; // read point
ReadNextExpressionAtom; // read namespace/unitname
//debugln(['ResolveUseUnit Next ',GetAtom(CurAtom)]);
Result:=Result.NextBrother;
end;
end;
function ResolveAttribute(const Context: TFindContext): boolean;
var
Identifier: String;
l: Integer;
begin
Result:=false;
if CurAtom.Flag<>cafWord then exit;
Identifier:=GetAtom;
l:=length(Identifier)-length('attribute');
if (l>0) and (CompareIdentifiers(@Identifier[l+1],'attribute')=0) then
exit;
// auto append 'attribute' to typename
Identifier+='Attribute';
Params.SetIdentifier(Self,PChar(Identifier),@CheckSrcIdentifier);
if Context.Tool.FindIdentifierInContext(Params) then begin
ExprType.Desc:=xtContext;
ExprType.Context:=CreateFindContext(Params);
Params.Load(OldInput,true);
exit(true);
end;
Params.Load(OldInput,false);
Result:=false;
end;
procedure ResolveIdentifier;
var
ProcNode: TCodeTreeNode;
IdentFound: boolean;
OldFlags: TFindDeclarationFlags;
ResultNode: TCodeTreeNode;
IsStart: Boolean;
Context: TFindContext;
IsEnd: Boolean;
SearchForwardToo: Boolean;
begin
// for example 'AnObject[3]'
{$IFDEF ShowExprEval}
debugln(['ResolveIdentifier "',GetAtom(CurAtom),'"']);
{$ENDIF}
// check special identifiers 'Result' and 'Self'
IdentFound:=false;
IsStart:=ExprType.Desc=xtNone;
IsEnd:=IsIdentifierEndOfVariable;
if IsStart then begin
// start context
if (StartNode.Desc in AllPascalStatements) then begin
if CompareSrcIdentifiers(CurAtom.StartPos,'SELF') then begin
// SELF in a method is the object itself
// -> check if in a method or nested proc of a method
if fdfExtractOperand in Params.Flags then
Params.AddOperandPart('Self');
ProcNode:=StartNode;
while (ProcNode<>nil) do begin
if (ProcNode.Desc=ctnProcedure) and NodeIsMethodBody(ProcNode) then
begin
ResultNode:=FindClassOfMethod(ProcNode,True,
fdfExceptionOnNotFound in Params.Flags);
if (ResultNode<>nil) and
(ResultNode.Desc in [ctnClassHelper,ctnRecordHelper,ctnTypeHelper])
then//Self is helper -> return extended type
begin
ExprType := FindExtendedExprOfHelper(ResultNode);
ResultNode := ExprType.Context.Node;
end else
begin//Self is class/record
if (ResultNode<>nil) and (ResultNode.Parent<>nil) then
begin
ExprType.Desc:=xtContext;
ExprType.Context.Tool:=Self;
end else
ExprType := CleanExpressionType;
end;
if IsEnd and (ResultNode<>nil) then
ResultNode := ResultNode.Parent;
ExprType.Context.Node:=ResultNode;
IdentFound:=ExprType.Desc<>xtNone;
break;
end;
ProcNode:=ProcNode.Parent;
end;
end else if CompareSrcIdentifiers(CurAtom.StartPos,'RESULT')
and (cmsResult in Scanner.CompilerModeSwitches) then begin
// RESULT has a special meaning in a function
// -> check if in a function
if fdfExtractOperand in Params.Flags then
Params.AddOperandPart('Result');
ProcNode:=StartNode;
while (ProcNode<>nil) do begin
if (ProcNode.Desc=ctnProcedure)
and (NodeIsFunction(ProcNode) or NodeIsOperator(ProcNode)) then
break;
ProcNode:=ProcNode.Parent;
end;
if (ProcNode<>nil) then begin
if IsEnd and (fdfFindVariable in StartFlags) then begin
BuildSubTreeForProcHead(ProcNode);
ResultNode:=ProcNode.FirstChild.FirstChild;
while (ResultNode<>nil) do begin
if ResultNode.Desc in [ctnVarDefinition,ctnIdentifier] then begin
// procedure: none
// operator: ctnVarDefinition,ctnIdentifier
// function: ctnIdentifier
ExprType.Desc:=xtContext;
ExprType.Context.Node:=ResultNode;
ExprType.Context.Tool:=Self;
exit;
end;
ResultNode:=ResultNode.NextBrother;
end;
end else begin
OldFlags:=Params.Flags;
Params.Flags:=Params.Flags+[fdfFunctionResult,fdfFindChildren];
ExprType.Context:=FindBaseTypeOfNode(Params,ProcNode);
ExprType.Desc:=xtContext;
Params.Flags:=OldFlags;
exit;
end;
end;
end;
end;
end;
// find identifier
if not IdentFound then begin
if not (ExprType.Desc in [xtContext,xtNone]) then
begin
// find special sub identifier
if (ExprType.Desc in xtAllTypeHelperTypes) then
begin
// found predefined basic type (e.g. string) without a context!
// -> search in type helpers
Params.Save(OldInput);
// build new param flags for sub identifiers
Params.Flags:=[fdfSearchInAncestors,fdfExceptionOnNotFound,fdfSearchInHelpers]
+(fdfGlobals*Params.Flags);
Params.SetIdentifier(Self,@Src[CurAtom.StartPos],nil);
{$IFDEF ShowExprEval}
debugln(['ResolveIdentifier searching "',GetAtom(CurAtom),'" in helper of predefined type "',ExprTypeToString(ExprType),'"']);
{$ENDIF}
if FindIdentifierInBasicTypeHelpers(ExprType.Desc, Params) then
begin
ExprType.Desc:=xtContext;
ExprType.SubDesc:=xtNone;
ExprType.Context.Tool := Params.NewCodeTool;
ExprType.Context.Node := Params.NewNode;
{$IFDEF ShowExprEval}
debugln(['ResolveIdentifier "',GetAtom(CurAtom),'" Found In Helper: "',ExprTypeToString(ExprType),'"']);
{$ENDIF}
end else begin
{$IFDEF ShowExprEval}
debugln(['ResolveIdentifier "',GetAtom(CurAtom),'" NOT Found In Helper']);
{$ENDIF}
end;
Params.Load(OldInput,true);
end;
if ExprType.Desc in xtAllPredefinedTypes then begin
ExprType:=FindExpressionTypeOfPredefinedIdentifier(CurAtom.StartPos,
Params);
{$IFDEF CheckNodeTool}
if ExprType.Desc=xtContext then
ExprType.Context.Tool.CheckNodeTool(ExprType.Context.Node);
{$ENDIF}
{$IFDEF ShowExprEval}
debugln(['ResolveIdentifier Predefined "',GetAtom(CurAtom),'" : ',ExprType.Desc in xtAllTypeHelperTypes]);
{$ENDIF}
end;
end else
begin
// find identifier
if ExprType.Desc=xtContext then
Context:=ExprType.Context
else
Context:=CreateFindContext(Self,StartNode);
Params.Save(OldInput);
// build new param flags for sub identifiers
Params.Flags:=[fdfSearchInAncestors,fdfExceptionOnNotFound,fdfSearchInHelpers]
+(fdfGlobals*Params.Flags);
Params.ContextNode:=Context.Node;
SearchForwardToo:=false;
if Context.Node=StartNode then begin
// there is no special context -> search in parent contexts too
Params.Flags:=Params.Flags+[fdfSearchInParentNodes,fdfIgnoreCurContextNode];
// check if searching forward too
if CanBeForwardDefined then begin
SearchForwardToo:=true;
Params.Flags:=Params.Flags-[fdfExceptionOnNotFound];
end;
end else begin
// only search in special context
Params.Flags:=Params.Flags+[fdfIgnoreUsedUnits];
if Assigned(Context.Node) and (Context.Node.Desc=ctnImplementation) then
Params.Flags:=Params.Flags+[fdfSearchInParentNodes];
if Context.Node.Desc=ctnObjCClass then
Exclude(Params.Flags,fdfExceptionOnNotFound); // ObjCClass has predefined identifiers like 'alloc'
end;
// check identifier for overloaded procs
if (IsEnd and (fdfIgnoreOverloadedProcs in StartFlags))
then
Include(Params.Flags,fdfIgnoreOverloadedProcs);
//debugln(['ResolveIdentifier ',IsEnd,' ',GetAtom(CurAtom),' ',Context.Node.DescAsString,' ',Context.Node.Parent.DescAsString,' ']);
if IsEnd and (Context.Node.Desc=ctnIdentifier)
and (Context.Node.Parent.Desc=ctnAttribParam)
and ResolveAttribute(Context) then begin
exit;
end;
Params.SetIdentifier(Self,@Src[CurAtom.StartPos],@CheckSrcIdentifier);
// search ...
{$IFDEF ShowExprEval}
Debugln([' FindExpressionTypeOfTerm ResolveIdentifier "',GetIdentifier(Params.Identifier),'" backward ',BoolToStr(IsStart,'Main','Sub'),'Ident="',GetIdentifier(Params.Identifier),'" ContextNode="',Params.ContextNode.DescAsString,'" "',dbgstr(Context.Tool.Src,Params.ContextNode.StartPos,15),'" ',dbgs(Params.Flags)]);
{$ENDIF}
ExprType.Desc:=xtNone;
// first search backwards
if Context.Tool.FindIdentifierInContext(Params) then begin
ExprType.Desc:=xtContext;
end else if SearchForwardToo then begin
// then search forwards
Params.Load(OldInput,false);
Params.SetIdentifier(Self,@Src[CurAtom.StartPos],@CheckSrcIdentifier);
Params.Flags:=[fdfSearchInParentNodes,fdfExceptionOnNotFound,
fdfIgnoreCurContextNode,fdfSearchForward]
+(fdfGlobals*Params.Flags);
Params.ContextNode:=Context.Node;
{$IFDEF ShowExprEval}
DebugLn([' FindExpressionTypeOfTerm ResolveIdentifier "',GetAtom(CurAtom),'" forward SubIdent="',GetIdentifier(Params.Identifier),'" ContextNode="',Params.ContextNode.DescAsString,'" "',dbgstr(Context.Tool.Src,Params.ContextNode.StartPos,15),'" ',dbgs(Params.Flags)]);
{$ENDIF}
if FindIdentifierInContext(Params) then begin
ExprType.Desc:=xtContext;
end;
end;
if ExprType.Desc=xtContext then begin
// identifier found
if Params.NewCodeTool.NodeIsConstructor(Params.NewNode) then begin
// identifier is a constructor
if (Context.Node.Desc in AllClassObjects) then begin
if (not IsEnd) or (not (fdfFindVariable in StartFlags)) then begin
// examples:
// TMyClass.Create.
// :=TMyClass.Create;
// use this class (the constructor can be defined in the ancestor)
ExprType.Context:=Context;
Params.Load(OldInput,true);
exit;
end;
end;
end;
if IsStart and (NextAtomType=vatPoint)
and (Params.NewCodeTool=Self)
and (Params.NewNode.Desc in [ctnUseUnitClearName,ctnUseUnitNamespace])
then begin
// first identifier is a used unit -> find longest fitting unitname
//debugln(['ResolveIdentifier UseUnit FindLongest... ',Params.NewNode.DescAsString,' ',ExtractNode(Params.NewNode,[])]);
Params.NewNode:=ResolveUseUnit(Params.NewNode.Parent);
//debugln(['ResolveIdentifier UseUnit FoundLongest: ',Params.NewNode.DescAsString,' ',ExtractNode(Params.NewNode,[])]);
end;
ExprType.Context:=CreateFindContext(Params);
Params.Load(OldInput,true);
end else begin
// predefined identifier
if (Context.Node.Desc=ctnObjCClass)
and CompareSrcIdentifiers('alloc',@Src[CurAtom.StartPos])
then begin
// 'alloc' returns the class itself
ExprType.Context:=Context;
//debugln(['ResolveIdentifier ',ExprTypeToString(ExprType)]);
Params.Load(OldInput,true);
exit;
end;
Params.Load(OldInput,true);
if IsEnd then
ExprType:=FindExpressionTypeOfPredefinedIdentifier(CurAtom.StartPos,
Params,AliasType)
else
ExprType:=FindExpressionTypeOfPredefinedIdentifier(CurAtom.StartPos,
Params);
{$IFDEF CheckNodeTool}
if ExprType.Desc=xtContext then
ExprType.Context.Tool.CheckNodeTool(ExprType.Context.Node);
{$ENDIF}
end;
end;
{$IFDEF ShowExprEval}
DebugLn([' FindExpressionTypeOfTerm ResolveIdentifier END Ident="',dbgstr(Src,StartPos,CurAtom.EndPos-StartPos),'" Expr=',ExprTypeToString(ExprType)]);
{$ENDIF}
end;
end;
procedure ResolveConstant;
var
IsStart: Boolean;
begin
IsStart:=ExprType.Desc=xtNone;
if not IsStart then
RaiseExceptionFmt(20170421200546,ctsOperatorExpectedButAtomFound,[GetAtom]);
if AtomIsStringConstant then begin
// string or char constant
if AtomIsCharConstant then
ExprType.Desc:=xtChar
else
ExprType.Desc:=xtConstString;
MoveCursorToCleanPos(CurPos.StartPos);
end
else if AtomIsNumber then begin
// ordinal or real constant
if AtomIsRealNumber then
ExprType.Desc:=xtConstReal
else
ExprType.Desc:=xtConstOrdInteger;
MoveCursorToCleanPos(CurPos.EndPos);
end else
RaiseExceptionFmt(20170421200548,ctsOperatorExpectedButAtomFound,[GetAtom]);
end;
procedure ResolveUseUnit;
var
AnUnitName: string;
InFilename: string;
aTool: TFindDeclarationTool;
NewCodeTool: TFindDeclarationTool;
NewNode: TCodeTreeNode;
begin
aTool:=ExprType.Context.Tool;
{$IFDEF ShowExprEval}
debugln([' FindExpressionTypeOfTerm ResolveUseUnit used unit -> interface node ',dbgstr(ExprType.Context.Tool.ExtractNode(ExprType.Context.Node,[]))]);
{$ENDIF}
AnUnitName:=aTool.ExtractUsedUnitName(ExprType.Context.Node.Parent,@InFilename);
NewCodeTool:=aTool.FindCodeToolForUsedUnit(AnUnitName,InFilename,true);
NewCodeTool.BuildInterfaceIdentifierCache(true);
NewNode:=NewCodeTool.FindInterfaceNode;
ExprType.Context.Tool:=NewCodeTool;
ExprType.Context.Node:=NewNode;
end;
procedure ResolveChildren;
var
NewNode: TCodeTreeNode;
begin
if (ExprType.Context.Node=nil) then exit;
{$IFDEF ShowExprEval}
debugln([' FindExpressionTypeOfTerm ResolveChildren']);
{$ENDIF}
ResolveBaseTypeOfIdentifier;
{$IFDEF ShowExprEval}
debugln([' FindExpressionTypeOfTerm ResolveChildren ExprType=',ExprTypeToString(ExprType)]);
//debugln(['ResolveChildren xtContext=',(ExprType.Desc=xtContext),
// ' ctnPointerType=',(ExprType.Context.Node.Desc=ctnPointerType),
// ' Node=',(ExprType.Context.Node<>StartNode),
// ' cmsAutoderef=',(cmsAutoderef in Scanner.CompilerModeSwitches),
// ' ',CompilerModeNames[Scanner.CompilerMode]
// ]);
{$ENDIF}
NewNode:=ExprType.Context.Node;
if (NewNode=nil) then exit;
if (NewNode.Desc in AllUsableSourceTypes)
or (NewNode.Desc=ctnSrcName)
or ((NewNode.Desc=ctnIdentifier) and (NewNode.Parent.Desc=ctnSrcName)
and (NewNode.NextBrother=nil))
then begin
if ExprType.Context.Tool=Self then begin
// unit name of this unit => implementation
// Note: allowed for programs too
NewNode:=Tree.Root;
if NewNode.Desc=ctnUnit then begin
NewNode:=FindImplementationNode;
if NewNode=nil then
NewNode:=FindInterfaceNode;
end;
{$IFDEF ShowExprEval}
debugln([' FindExpressionTypeOfTerm ResolveChildren this unit -> ',NewNode.DescAsString]);
{$ENDIF}
ExprType.Context.Node:=NewNode;
end else begin
// unit name of another unit => interface
{$IFDEF ShowExprEval}
debugln([' FindExpressionTypeOfTerm ResolveChildren unit -> interface node']);
{$ENDIF}
ExprType.Context.Node:=ExprType.Context.Tool.GetInterfaceNode;
end;
end
else if (ExprType.Context.Node.Desc=ctnUseUnitClearName) then begin
// uses unit name => interface of used unit
ResolveUseUnit;
end
else if (ExprType.Context.Node.Desc=ctnClassOfType) then begin
// 'class of' => jump to the class
ExprType.Context:=ExprType.Context.Tool.FindBaseTypeOfNode(Params,ExprType.Context.Node.FirstChild);
end
else if (ExprType.Desc=xtContext)
and (ExprType.Context.Node.Desc=ctnPointerType)
and (ExprType.Context.Node<>StartNode)
and (cmsAutoderef in Scanner.CompilerModeSwitches) then begin
// Delphi knows . as shortcut for ^.
// -> check for pointer type
// left side of expression has defined a special context
// => this '.' is a dereference
ExprType.Context:=ExprType.Context.Tool.FindBaseTypeOfNode(Params,ExprType.Context.Node.FirstChild);
end;
end;
procedure ResolvePoint;
begin
// for example 'A.B'
if fdfExtractOperand in Params.Flags then
Params.AddOperandPart('.');
if (not (NextAtomType in [vatSpace,vatIdentifier,vatPreDefIdentifier])) then
begin
MoveCursorToCleanPos(NextAtom.StartPos);
ReadNextAtom;
RaiseIdentExpected;
end;
ResolveChildren;
if ExprType.Desc in xtAllTypeHelperTypes then begin
// Lazarus supports record helpers for basic types (string) as well (with TYPEHELPERS modeswitch!).
end else if (ExprType.Context.Node=nil) then begin
MoveCursorToCleanPos(CurAtom.StartPos);
ReadNextAtom;
RaiseIllegalQualifierFound;
end else if ExprType.Context.Node.Desc in AllPointContexts then begin
// ok, allowed
end else begin
// not allowed
//debugln(['ResolvePoint ',ExprTypeToString(ExprType)]);
MoveCursorToCleanPos(CurAtom.StartPos);
ReadNextAtom;
RaiseIllegalQualifierFound;
end;
end;
procedure ResolveAs;
begin
// for example 'A as B'
if (not (NextAtomType in [vatSpace,vatIdentifier,vatPreDefIdentifier])) then
begin
MoveCursorToCleanPos(NextAtom.StartPos);
ReadNextAtom;
RaiseIdentExpected;
end;
// 'as' is a type cast, so the left side is irrelevant
// -> context is default context
ExprType.Desc:=xtContext;
ExprType.Context.Tool:=Self;
ExprType.Context.Node:=StartNode;
end;
procedure ResolveUp;
begin
// for example:
// 1. 'PInt = ^integer' pointer type
// 2. a^ dereferencing
{$IFDEF ShowExprEval}
debugln([' FindExpressionTypeOfTerm ResolveUp']);
{$ENDIF}
if fdfExtractOperand in Params.Flags then
Params.AddOperandPart('^');
if (not (NextAtomType in [vatSpace,vatPoint,vatUp,vatAS,vatEdgedBracketOpen]))
or ((ExprType.Context.Node=nil) and (ExprType.Desc<>xtPointer))
then begin
MoveCursorToCleanPos(NextAtom.StartPos);
ReadNextAtom;
RaiseIllegalQualifierFound;
end;
ResolveBaseTypeOfIdentifier;
if (ExprType.Desc=xtPointer) then begin
// the compiler type 'Pointer'
exit;
end;
if (ExprType.Context.Node<>StartNode) then begin
// left side of expression has defined a special context
// => this '^' is a dereference
if (not
(NextAtomType in [vatSpace,vatPoint,vatAS,vatUP,vatEdgedBracketOpen]))
then begin
MoveCursorToCleanPos(NextAtom.StartPos);
ReadNextAtom;
RaisePointNotFound;
end;
if (ExprType.Context.Node=nil)
or (ExprType.Context.Node.Desc<>ctnPointerType) then begin
MoveCursorToCleanPos(CurAtom.StartPos);
RaiseExceptionFmt(20170421200550,ctsIllegalQualifier,['^']);
end;
ExprType.Desc:=xtContext;
ExprType.Context.Node:=ExprType.Context.Node.FirstChild;
end else if NodeHasParentOfType(ExprType.Context.Node,ctnPointerType) then
begin
// this is a pointer type definition
// -> the default context is ok
end;
end;
procedure ResolveEdgedBracketOpen;
{ for example: a[]
this could be:
1. ranged array e.g. array[1..2] of
2. dynamic array e.g. array of integer
3. variant array e.g. array of const
4. indexed pointer e.g. PInteger[1]
5. default property e.g. Items[Index: integer]
6. indexed property e.g. Items[Index: integer]
7. string character e.g. string[3]
}
procedure RaiseTypeIdentNotFound;
begin
ExprType.Context.Tool.RaiseExceptionFmt(20170421200553,ctsStrExpectedButAtomFound,
[ctsTypeIdentifier,ExprType.Context.Tool.GetAtom]);
end;
procedure RaiseIdentInCurContextNotFound;
begin
ExprType.Context.Tool.RaiseExceptionFmt(20170421200557,ctsStrExpectedButAtomFound,
[ctsIdentifier,GetAtom]);
end;
begin
{$IFDEF ShowExprEval}
debugln([' FindExpressionTypeOfTerm ResolveEdgedBracketOpen ',ExprTypeToString(ExprType)]);
{$ENDIF}
if fdfExtractOperand in Params.Flags then begin
// simple copying, todo: expand argument
Params.AddOperandPart(ExtractBrackets(CurPos.StartPos,[]));
end;
if (not (NextAtomType in [vatSpace,vatPoint,vatAs,vatUp,vatRoundBracketClose,
vatRoundBracketOpen,vatEdgedBracketClose,vatEdgedBracketOpen]))
then begin
MoveCursorToCleanPos(NextAtom.StartPos);
ReadNextAtom;
RaiseIllegalQualifierFound;
end;
if (ExprType.Desc=xtContext)
and (ExprType.Context.Node.Desc=ctnProperty) then begin
// [] behind a property
// -> Check if this property has parameters
ResolveTypeLessProperty;
if (ExprType.Desc=xtContext)
and (ExprType.Context.Node.Desc=ctnProperty)
and ExprType.Context.Tool.PropertyNodeHasParamList(ExprType.Context.Node)
then begin
// use the property type
ResolveChildren;
exit;
end;
end;
ResolveBaseTypeOfIdentifier;
if ExprType.Desc in xtAllStringTypes then begin
ExprType.Desc:=xtChar;
ExprType.Context.Node:=nil;
exit;
end;
if ExprType.Desc in xtAllWideStringTypes then begin
ExprType.Desc:=xtWideChar;
ExprType.Context.Node:=nil;
exit;
end;
if ExprType.Context.Node=nil then begin
MoveCursorToCleanPos(NextAtom.StartPos);
ReadNextAtom;
RaiseIllegalQualifierFound;
end;
if ExprType.Context.Node.Desc in [ctnRangedArrayType,ctnOpenArrayType] then
begin
MoveCursorToCleanPos(CurAtom.StartPos);
ReadNextAtom; // "["
ReadNextAtom;
repeat
case CurPos.Flag of
cafRoundBracketClose: SaveRaiseBracketCloseExpectedButAtomFound(20170425090717);
cafRoundBracketOpen,
cafEdgedBracketOpen: ReadTilBracketClose(true);
cafComma:
with ExprType, Context do begin
Context:=Tool.FindBaseTypeOfNode(Params,Node.LastChild);
if not (Node.Desc in [ctnRangedArrayType,ctnOpenArrayType]) then
RaiseIllegalQualifierFound;
end;
end;
ReadNextAtom;
until CurPos.Flag=cafEdgedBracketClose;
end;
{$IFDEF ShowExprEval}
DebugLn([' FindExpressionTypeOfTerm ResolveEdgedBracketOpen ExprType=',ExprTypeToString(ExprType)]);
{$ENDIF}
case ExprType.Context.Node.Desc of
ctnOpenArrayType,ctnRangedArrayType:
begin
// the array type is the last child node
//debugln('ResolveEdgedBracketOpen Open/RangedArray LastChild=',ExprType.Context.Node.LastChild.DescAsString);
if ExprType.Context.Node.LastChild.Desc=ctnOfConstType then begin
// 'array of const'; the array type is 'TVarRec'
// => search 'TVarRec'
Params.Save(OldInput);
Params.Flags:=[fdfSearchInParentNodes,fdfIgnoreCurContextNode,
fdfExceptionOnNotFound,fdfFindChildren];
// special identifier for TVarRec
Params.SetIdentifier(Self,'tvarrec',nil);
Params.ContextNode:=ExprType.Context.Node;
ExprType.Context.Tool.FindIdentifierInContext(Params);
ExprType.Context:=CreateFindContext(Params);
Params.Load(OldInput,true);
end else begin
ExprType.Context.Node:=ExprType.Context.Node.LastChild;
end;
end;
ctnPointerType:
// the pointer type is the only child node
ExprType.Context.Node:=ExprType.Context.Node.FirstChild;
ctnClass, ctnClassInterface, ctnDispinterface, ctnObject, ctnRecordType,
ctnClassHelper, ctnRecordHelper, ctnTypeHelper,
ctnObjCClass, ctnObjCCategory, ctnObjCProtocol, ctnCPPClass:
begin
// search default property of the class / interface
Params.Save(OldInput);
Params.Flags:=[fdfSearchInAncestors,fdfExceptionOnNotFound,fdfSearchInHelpers]
+fdfGlobals*Params.Flags;
// special identifier '[' for default property
Params.SetIdentifier(Self,@Src[CurAtom.StartPos],nil);
Params.ContextNode:=ExprType.Context.Node;
ExprType.Context.Tool.FindIdentifierInContext(Params);
ExprType.Context:=CreateFindContext(Params);
Params.Load(OldInput,true);
end;
ctnProperty, ctnGlobalProperty:
begin
if not ExprType.Context.Tool.PropertyNodeHasParamList(ExprType.Context.Node) then
RaiseIdentInCurContextNotFound;
end;
ctnIdentifier:
begin
MoveCursorToNodeStart(ExprType.Context.Node);
ReadNextAtom;
if UpAtomIs('STRING') or UpAtomIs('ANSISTRING')
or UpAtomIs('SHORTSTRING') then begin
ExprType.Desc:=xtChar;
ExprType.Context.Node:=nil;
exit;
end else if UpAtomIs('WIDESTRING') or UpAtomIs('UNICODESTRING') then begin
ExprType.Desc:=xtWideChar;
ExprType.Context.Node:=nil;
exit;
end else begin
MoveCursorToCleanPos(CurAtom.StartPos);
ReadNextAtom;
RaiseIllegalQualifierFound;
end;
end;
else
MoveCursorToCleanPos(CurAtom.StartPos);
ReadNextAtom;
RaiseIllegalQualifierFound;
end;
end;
procedure ResolveRoundBracketOpen;
begin
{ for example:
(a+b) expression bracket: the type is the result type of the
expression.
a() typecast or function
}
if not (NextAtomType in [vatSpace,vatPoint,vatAs,vatUp,vatRoundBracketClose,
vatRoundBracketOpen,vatEdgedBracketClose,vatEdgedBracketOpen]) then
begin
MoveCursorToCleanPos(NextAtom.StartPos);
ReadNextAtom;
RaiseIllegalQualifierFound;
end;
if PrevAtomType<>vatNone then begin
// typecast or function
{$IFDEF ShowExprEval}
debugln([' FindExpressionTypeOfTerm ResolveRoundBracketOpen skip typecast/paramlist="',dbgstr(Src,CurAtom.StartPos,CurAtomBracketEndPos-CurAtom.StartPos),'"']);
{$ENDIF}
if fdfExtractOperand in Params.Flags then begin
if (ExprType.Context.Node<>nil)
and (ExprType.Context.Node.Desc=ctnTypeDefinition) then begin
// typecast
with ExprType.Context do
Params.AddOperandPart(GetIdentifier(@Tool.Src[Node.StartPos]));
Params.AddOperandPart('(');
// assumption: one term in brakets
FindExpressionTypeOfTerm(CurAtom.StartPos+1,CurAtomBracketEndPos-1,
Params,false);
Params.AddOperandPart(')');
end;
end;
if fdfOverrideStringTypesWithFirstParamType in Params.Flags then begin
if (ExprType.Context.Node<>nil)
and (ExprType.Context.Node.Desc in [ctnProcedure, ctnProcedureHead])
and (FirstParamStartPos<0) then begin
FirstParamStartPos := CurAtom.StartPos;
FirstParamProcContext := ExprType.Context;
end;
end;
end else begin
// expression
{$IFDEF ShowExprEval}
debugln([' FindExpressionTypeOfTerm ResolveRoundBracketOpen subexpr="',dbgstr(Src,CurAtom.StartPos,CurAtomBracketEndPos-CurAtom.StartPos),'"']);
{$ENDIF}
ExprType:=FindExpressionResultType(Params,CurAtom.StartPos+1,
CurAtomBracketEndPos-1, AliasType);
end;
end;
procedure ResolveINHERITED;
// for example: inherited A; inherited;
// inherited skips the class and begins to search in the ancestor class
var
ProcNode: TCodeTreeNode;
ClassNodeOfMethod: TCodeTreeNode;
HasIdentifier: Boolean;
Context: TFindContext;
var
DefProcNode: TCodeTreeNode;
HelperForExpr: TExpressionType;
SearchInHelpersInTheEnd: Boolean;
begin
if ExprType.Desc=xtNone then
Context:=CreateFindContext(Self,StartNode)
else
Context:=ExprType.Context;
if (Context.Node<>StartNode) or (Context.Node=nil) then begin
MoveCursorToCleanPos(CurAtom.StartPos);
RaiseIllegalQualifierFound;
end;
ProcNode:=GetMethodOfBody(Context.Node);
if ProcNode=nil then begin
MoveCursorToCleanPos(CurAtom.StartPos);
RaiseException(20170421200601,ctsInheritedKeywordOnlyAllowedInMethods);
end;
HasIdentifier:=NextAtom.EndPos<=EndPos;
if HasIdentifier then begin
if (not (NextAtomType in [vatIdentifier,vatPreDefIdentifier])) then
begin
MoveCursorToCleanPos(NextAtom.StartPos);
ReadNextAtom;
RaiseIdentExpected;
end;
ReadNextExpressionAtom;
end;
{$IFDEF ShowExprEval}
DebugLn(' FindExpressionTypeOfTerm ResolveINHERITED CurAtomType=',
VariableAtomTypeNames[CurAtomType],
' CurAtom="',copy(Src,CurAtom.StartPos,CurAtom.EndPos-CurAtom.StartPos),'"');
{$ENDIF}
// find class of method
ClassNodeOfMethod:=FindClassOfMethod(ProcNode,true,true);
// find class ancestor
OldInput.Flags:=Params.Flags;
Params.Flags:=[fdfSearchInParentNodes,fdfExceptionOnNotFound]
+fdfGlobals*Params.Flags;
FindAncestorOfClass(ClassNodeOfMethod,Params,true);
Params.Flags:=OldInput.Flags;
ExprType.Desc:=xtContext;
ExprType.Context:=CreateFindContext(Params);
SearchInHelpersInTheEnd := False;
if ClassNodeOfMethod.Desc in [ctnClassHelper,ctnRecordHelper] then
begin
// helpers have different order in "inherited" call.
// -> first search in extended class and then in helper (applies only to inherited call)
if (ExprType.Context.Node<>nil) then//inherited helper found -> use it!
Params.GetHelpers(fdhlkDelphiHelper,true)
.AddFromHelperNode(ExprType.Context.Node, ExprType.Context.Tool, True)
else//inherited helper not found -> delete current
Params.GetHelpers(fdhlkDelphiHelper,true)
.DeleteHelperNode(ClassNodeOfMethod, Self);
HelperForExpr := FindExtendedExprOfHelper(ClassNodeOfMethod);
if HelperForExpr.Desc = xtContext then
begin
ExprType.Context := HelperForExpr.Context;
SearchInHelpersInTheEnd := True;
end;
end;
if (not HasIdentifier) then begin
// the keyword 'inherited' is the last atom
if StartFlags*[fdfFindChildren,fdfFindVariable]=[fdfFindVariable] then begin
// for example: inherited; search the method, not the context
DefProcNode:=FindCorrespondingProcNode(ProcNode);
if DefProcNode=nil then begin
MoveCursorToProcName(ProcNode,true);
RaiseExceptionFmt(20170421200604,ctsMethodSignatureSNotFoundInClass, [GetAtom]);
end;
MoveCursorToProcName(DefProcNode,true);
end else begin
// for example: inherited |
// return the ancestor class context
exit;
end;
end else
MoveCursorToCleanPos(CurAtom.StartPos);
// search identifier only in class ancestor
if SearchInHelpersInTheEnd then
Params.Flags := Params.Flags + [fdfSearchInHelpersInTheEnd];
Params.Save(OldInput);
Params.SetIdentifier(Self,@Src[CurPos.StartPos],@CheckSrcIdentifier);
Params.ContextNode:=ExprType.Context.Node;
Params.Flags:=Params.Flags-[fdfSearchInParentNodes]
+[fdfExceptionOnNotFound,fdfSearchInAncestors];
ExprType.Context.Tool.FindIdentifierInContext(Params);
ExprType.Context:=CreateFindContext(Params);
Params.Load(OldInput,true);
Params.Flags := Params.Flags - [fdfSearchInHelpersInTheEnd];
end;
begin
Result:=CleanExpressionType;
FirstParamStartPos := -1;
FirstParamProcContext := CleanFindContext;
StartFlags:=Params.Flags;
StartNode:=Params.ContextNode;
{$IFDEF ShowExprEval}
DebugLn(['[TFindDeclarationTool.FindExpressionTypeOfTerm] START',
' Flags=[',dbgs(Params.Flags),']',
' StartContext=',StartNode.DescAsString,'=',dbgstr(Src,StartNode.StartPos,15),
' Alias=',AliasType<>nil]
);
{$ENDIF}
{$IFDEF CheckNodeTool}
CheckNodeTool(StartNode);
{$ENDIF}
if not InitAtomQueue then exit;
ExprType:=CleanExpressionType;
repeat
{$IFDEF ShowExprEval}
DebugLn([' FindExpressionTypeOfTerm ATOM',
' CurAtomType=',VariableAtomTypeNames[CurAtomType],
' CurAtom="',GetAtom(CurAtom),'"',
' ExprType=',ExprTypeToString(ExprType)]);
{$ENDIF}
case CurAtomType of
vatIdentifier, vatPreDefIdentifier: ResolveIdentifier;
vatStringConstant,vatNumber: ResolveConstant;
vatPoint: ResolvePoint;
vatAS: ResolveAs;
vatUP: ResolveUp;
vatEdgedBracketOpen: ResolveEdgedBracketOpen;
vatRoundBracketOpen: ResolveRoundBracketOpen;
vatINHERITED: ResolveINHERITED;
end;
ReadNextExpressionAtom;
until CurAtom.EndPos>EndPos;
if fdfFunctionResult in StartFlags then
ResolveChildren;
Result:=ExprType;
if (Result.Desc=xtContext) and (not (fdfFindVariable in StartFlags)) then
Result:=Result.Context.Tool.ConvertNodeToExpressionType(
Result.Context.Node,Params);
{$IFDEF ShowExprEval}
DebugLn(' FindExpressionTypeOfTerm Result=',ExprTypeToString(Result));
{$ENDIF}
end;
function TFindDeclarationTool.FindEndOfExpression(StartPos: integer): integer;
var
First: Integer;
begin
MoveCursorToCleanPos(StartPos);
Result:=CurPos.StartPos;
First:=0;
repeat
ReadNextAtom;
if First=0 then begin
First:=CurPos.StartPos;
if UpAtomIs('INHERITED') then begin
Result:=CurPos.EndPos;
ReadNextAtom;
end;
end;
// read till statement end
if (CurPos.StartPos>SrcLen)
or (CurPos.Flag in [cafSemicolon,cafComma,cafEnd,
cafRoundBracketClose,cafEdgedBracketClose])
or (AtomIsKeyWord
and not IsKeyWordInConstAllowed.DoItCaseInsensitive(Src,
CurPos.StartPos,CurPos.EndPos-CurPos.StartPos))
then begin
break;
end
else if CurPos.Flag in [cafRoundBracketOpen,cafEdgedBracketOpen] then begin
ReadTilBracketClose(true);
end;
Result:=CurPos.EndPos;
until false;
end;
function TFindDeclarationTool.ConvertNodeToExpressionType(Node: TCodeTreeNode;
Params: TFindDeclarationParams; AliasType: PFindContext): TExpressionType;
procedure ConvertIdentifierAtCursor(Tool: TFindDeclarationTool);
begin
if WordIsPredefinedIdentifier.DoItCaseInsensitive(Tool.Src,Tool.CurPos.StartPos,
Tool.CurPos.EndPos-Tool.CurPos.StartPos) then
begin
// predefined identifiers
ConvertNodeToExpressionType:=Tool.FindExpressionTypeOfPredefinedIdentifier(
Tool.CurPos.StartPos,Params);
end;
end;
var
BaseContext: TFindContext;
OldInput: TFindDeclarationInput;
Tool: TFindDeclarationTool;
CurAliasType: PFindContext;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(Node);{$ENDIF}
{$IFDEF ShowExprEval}
DebugLn(['[TFindDeclarationTool.ConvertNodeToExpressionType] A',
' Node=',Node.DescAsString,' "',dbgstr(copy(ExtractNode(Node,[]),1,30)),'" Flags=[',dbgs(Params.Flags),'] Alias=',AliasType<>nil]);
{$ENDIF}
BaseContext:=FindBaseTypeOfNode(Params,Node,AliasType);
Node:=BaseContext.Node;
Tool:=BaseContext.Tool;
Result:=CleanExpressionType;
Result.Desc:=xtContext;
Result.Context:=BaseContext;
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.ConvertNodeToExpressionType] B',
' Expr=',ExprTypeToString(Result),' Alias=',FindContextToString(AliasType));
{$ENDIF}
if (AliasType<>nil) and (AliasType^.Node=nil) then
CurAliasType:=AliasType
else
CurAliasType:=nil;
case Node.Desc of
ctnRangeType:
begin
// range type -> convert to special expression type
// for example: type c = 1..3;
// ToDo: ppu, dcu files
Tool.MoveCursorToNodeStart(Node);
// ToDo: check for cycles
Params.Save(OldInput);
Params.ContextNode:=Node;
Result:=Tool.ReadOperandTypeAtCursor(Params,-1,CurAliasType);
Params.Load(OldInput,true);
Result.Context:=CreateFindContext(Tool,Node);
end;
ctnConstDefinition:
begin
// const -> convert to special expression type
// for example: const a: integer = 3;
// ToDo: ppu, dcu files
Tool.MoveCursorToNodeStart(Node);
Tool.ReadNextAtom;
if not Tool.AtomIsIdentifier then exit;
Tool.ReadNextAtom;
if not (CurPos.Flag in [cafEqual,cafColon]) then exit;
Tool.ReadNextAtom;
// ToDo: check for cycles
Params.Save(OldInput);
Params.ContextNode:=Node;
Result:=Tool.ReadOperandTypeAtCursor(Params,-1,CurAliasType);
Params.Load(OldInput,true);
Result.Context:=CreateFindContext(Tool,Node);
end;
ctnIdentifier:
begin
// ToDo: ppu, dcu files
Tool.MoveCursorToNodeStart(Node);
Tool.ReadNextAtom;
ConvertIdentifierAtCursor(Tool);
end;
ctnProperty,ctnGlobalProperty:
begin
// ToDo: ppu, dcu files
if Tool.MoveCursorToPropType(Node) then
ConvertIdentifierAtCursor(Tool);
end;
ctnConstant:
begin
// for example: const a = 3;
// ToDo: ppu, dcu files
Tool.MoveCursorToNodeStart(Node);
Params.Save(OldInput);
Params.ContextNode:=Node;
Result:=Tool.ReadOperandTypeAtCursor(Params,-1,CurAliasType);
Params.Load(OldInput,true);
Result.Context:=CreateFindContext(Tool,Node);
end;
end;
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.ConvertNodeToExpressionType] END',
' Expr=',ExprTypeToString(Result),' Alias=',FindContextToString(AliasType));
{$ENDIF}
end;
function TFindDeclarationTool.ReadOperandTypeAtCursor(
Params: TFindDeclarationParams; MaxEndPos: integer; AliasType: PFindContext
): TExpressionType;
{ internally used by FindExpressionResultType
after reading, the cursor will be on the next atom
}
var EndPos, SubStartPos: integer;
procedure ReadEdgedBracketOperand;
procedure RaiseConstExpected;
begin
RaiseExceptionFmt(20170421200607,ctsStrExpectedButAtomFound,[ctsConstant,GetAtom]);
end;
begin
// 'set' constant
SubStartPos:=CurPos.StartPos;
ReadNextAtom;
if not AtomIsChar(']') then begin
Result:=ReadOperandTypeAtCursor(Params);
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.ReadOperandTypeAtCursor] Set of ',
ExpressionTypeDescNames[Result.Desc]);
if Result.Desc=xtContext then
DebugLn(' Result.Context.Node=',Result.Context.Node.DescAsString);
{$ENDIF}
end else begin
// empty set '[]'
Result.Desc:=xtNone;
end;
Result.SubDesc:=Result.Desc;
Result.Desc:=xtConstSet;
MoveCursorToCleanPos(SubStartPos);
ReadNextAtom;
ReadTilBracketClose(true);
MoveCursorToCleanPos(CurPos.EndPos);
end;
procedure RaiseIdentExpected;
begin
RaiseExceptionFmt(20170421200609,ctsStrExpectedButAtomFound,[ctsIdentifier,GetAtom]);
end;
var
OldFlags: TFindDeclarationFlags;
begin
Result:=CleanExpressionType;
if AliasType<>nil then
AliasType^:=CleanFindContext;
if CurPos.StartPos=CurPos.EndPos then ReadNextAtom;
// read unary operators which have no effect on the type: +, -, not
while AtomIsChar('+') or AtomIsChar('-') or UpAtomIs('NOT') do
ReadNextAtom;
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.ReadOperandTypeAtCursor] A Atom=',GetAtom);
debugln(['TFindDeclarationTool.ReadOperandTypeAtCursor StartContext=',Params.ContextNode.DescAsString,'="',dbgstr(Src,Params.ContextNode.StartPos,15),'"']);
{$ENDIF}
if (AtomIsIdentifier)
or (CurPos.Flag=cafRoundBracketOpen)
or UpAtomIs('INHERITED')
or UpAtomIs('ARRAY')
then begin
// read variable
SubStartPos:=CurPos.StartPos;
EndPos:=FindEndOfTerm(SubStartPos,false,true);
if EndPos>MaxEndPos then
EndPos:=MaxEndPos;
OldFlags:=Params.Flags;
Params.Flags:=(Params.Flags*fdfGlobals)+[fdfFunctionResult];
Result:=FindExpressionTypeOfTerm(SubStartPos,EndPos,Params,true,AliasType);
Params.Flags:=OldFlags;
MoveCursorToCleanPos(EndPos);
end
else if UpAtomIs('NIL') then begin
Result.Desc:=xtNil;
ReadNextAtom;
end
else if AtomIsChar('[') then begin
ReadEdgedBracketOperand;
end
else if AtomIsStringConstant then begin
// string or char constant
if AtomIsCharConstant then
Result.Desc:=xtChar
else
Result.Desc:=xtConstString;
MoveCursorToCleanPos(CurPos.StartPos);
ReadAsStringConstant;
end
else if AtomIsNumber then begin
// ordinal or real constant
if AtomIsRealNumber then
Result.Desc:=xtConstReal
else
Result.Desc:=xtConstOrdInteger;
MoveCursorToCleanPos(CurPos.EndPos);
end
else if AtomIsChar('@') then begin
// a simple pointer or a PChar or an event
ReadNextAtom;
if CurPos.Flag=cafWord then begin
SubStartPos:=CurPos.StartPos;
EndPos:=FindEndOfTerm(SubStartPos,false,true);
if EndPos>MaxEndPos then
EndPos:=MaxEndPos;
OldFlags:=Params.Flags;
Params.Flags:=(Params.Flags*fdfGlobals)-[fdfFunctionResult];
Result:=FindExpressionTypeOfTerm(SubStartPos,EndPos,Params,true,AliasType);
Params.Flags:=OldFlags;
MoveCursorToCleanPos(EndPos);
end else begin
MoveCursorToCleanPos(CurPos.StartPos);
Result:=ReadOperandTypeAtCursor(Params);
end;
if (Result.Desc=xtContext)
or ((Result.Context.Node<>nil) and (Result.Context.Node.Desc=ctnProcedure))
then begin
Result.SubDesc:=Result.Desc;
Result.Desc:=xtPointer;
end else if (Result.Desc=xtChar) then begin
Result.SubDesc:=xtNone;
Result.Desc:=xtPChar
end else begin
Result.SubDesc:=xtNone;
Result.Context:=CleanFindContext;
Result.Desc:=xtPointer;
end;
end
else
RaiseIdentExpected;
{$IFDEF ShowExprEval}
DbgOut('[TFindDeclarationTool.ReadOperandTypeAtCursor] END ',
ExpressionTypeDescNames[Result.Desc]);
if Result.Context.Node<>nil then
DbgOut(' Context.Node=',Result.Context.Node.DescAsString)
else
DbgOut(' Context.Node=nil');
if AliasType<>nil then
DbgOut(' Alias=',FindContextToString(AliasType));
DebugLn('');
{$ENDIF}
end;
function TFindDeclarationTool.FindExpressionTypeOfPredefinedIdentifier(
StartPos: integer; Params: TFindDeclarationParams; AliasType: PFindContext
): TExpressionType;
var
IdentPos: PChar;
ParamList: TExprTypeList;
ParamNode: TCodeTreeNode;
SubParams: TFindDeclarationParams;
NewTool: TFindDeclarationTool;
begin
Result:=CleanExpressionType;
IdentPos:=@Src[StartPos];
Result.Desc:=PredefinedIdentToExprTypeDesc(IdentPos,Scanner.PascalCompiler);
{$IFDEF ShowExprEval}
debugln('TFindDeclarationTool.FindExpressionTypeOfPredefinedIdentifier "',GetIdentifier(IdentPos),'" ',
ExpressionTypeDescNames[Result.Desc]);
if Result.desc=xtNone then begin
//CTDumpStack;
//IsWordBuiltInFunc.WriteDebugListing;
end;
{$ENDIF}
ParamList:=nil;
try
case Result.Desc of
xtCompilerFunc:
begin
if not (Params.ContextNode.Desc in (AllPascalStatements+[ctnConstant])) then begin
{$IFDEF ShowExprEval}
debugln(['TFindDeclarationTool.FindExpressionTypeOfPredefinedIdentifier Skipping non expr parent ContextNode=',Params.ContextNode.DescAsString]);
{$ENDIF}
exit;
end;
MoveCursorToCleanPos(StartPos);
ReadNextAtom;
ReadNextAtom;
if not AtomIsChar('(') then
exit;
ParamList:=CreateParamExprListFromStatement(CurPos.StartPos,Params,true);
if (CompareIdentifiers(IdentPos,'PRED')=0)
or (CompareIdentifiers(IdentPos,'SUCC')=0)
or (CompareIdentifiers(IdentPos,'DEFAULT')=0)
then begin
// the DEFAULT, PRED and SUCC of a expression has the same type as the expression
if ParamList.Count<>1 then exit;
Result:=ParamList.Items[0];
if AliasType<>nil then
AliasType^:=ParamList.AliasTypes[0];
//debugln(['TFindDeclarationTool.FindExpressionTypeOfPredefinedIdentifier ',ExprTypeToString(Result)]);
end
else if (CompareIdentifiers(IdentPos,'LOW')=0)
or (CompareIdentifiers(IdentPos,'HIGH')=0) then
begin
{$IFDEF ShowExprEval}
debugln('TFindDeclarationTool.FindExpressionTypeOfPredefinedIdentifier Ident=',GetIdentifier(IdentPos));
{$ENDIF}
{ examples:
Low(ordinal type) is the ordinal type
Low(array) has type of the array items
Low(set) has type of the enums
}
if ParamList.Count<>1 then exit;
Result:=ParamList.Items[0];
if Result.Desc<>xtContext then exit;
ParamNode:=Result.Context.Node;
case ParamNode.Desc of
ctnEnumerationType:
// Low(enum) has the type of the enum
if (ParamNode.Parent<>nil)
and (ParamNode.Parent.Desc=ctnTypeDefinition) then
Result.Context.Node:=ParamNode.Parent;
ctnOpenArrayType:
// array without explicit range -> open array
// Low(Open array) is ordinal integer
begin
Result.Desc:=xtConstOrdInteger;
Result.Context:=CleanFindContext;
end;
ctnRangedArrayType:
begin
// array with explicit range
// Low(array[SubRange]) has the type of the subrange
Result.Context.Tool.MoveCursorToNodeStart(ParamNode.FirstChild);
SubParams:=TFindDeclarationParams.Create(Params);
try
SubParams.Flags:=fdfDefaultForExpressions;
SubParams.ContextNode:=ParamNode;
Result:=Result.Context.Tool.ReadOperandTypeAtCursor(SubParams);
finally
SubParams.Free;
end;
end;
else
DebugLn('NOTE: unimplemented Low(type) type=',ParamNode.DescAsString);
end;
end
else if (CompareIdentifiers(IdentPos,'LENGTH')=0) then
begin
if ParamList.Count<>1 then exit;
Result.Desc:=xtConstOrdInteger;
end
else if (CompareIdentifiers(IdentPos,'COPY')=0) then
begin
if (ParamList.Count<1) or (ParamList.Count>3) or (Scanner.Values.IsDefined('VER1_0')) then
exit;
Result:=ParamList.Items[0]; // Copy sets the result based on the first
// parameter (can be any kind of string or array)
end
else if (CompareIdentifiers(IdentPos,'GET_FRAME')=0) then
begin
if ParamList.Count<>1 then exit;
Result.Desc:=xtPointer;
end
else if (CompareIdentifiers(IdentPos,'OBJCSELECTOR')=0) then
begin
// return type is System.SEL
NewTool:=FindCodeToolForUsedUnit('system','',true);
if NewTool=nil then exit;
SubParams:=TFindDeclarationParams.Create(Params);
try
SubParams.Identifier:='SEL'#0;
if (not NewTool.FindIdentifierInInterface(Self,SubParams))
or (SubParams.NewNode=nil) then exit;
Result.Desc:=xtContext;
Result.Context.Node:=SubParams.NewNode;
Result.Context.Tool:=SubParams.NewCodeTool;
finally
SubParams.Free;
end;
end;
end;
xtString:
Result.Desc:=GetDefaultStringType;
end;
finally
ParamList.Free;
end;
end;
function TFindDeclarationTool.FindExpressionTypeOfConstSet(Node: TCodeTreeNode
): TExpressionType;
var
AliasType: TFindContext;
Params: TFindDeclarationParams;
begin
Result:=CleanExpressionType;
if Node=nil then
RaiseException(20170421212058,'TFindDeclarationTool.FindExpressionTypeOfConstSet Node=nil');
{$IFDEF CheckNodeTool}
CheckNodeTool(Node);
{$ENDIF}
MoveCursorToNodeStart(Node);
ReadNextAtom;
if CurPos.Flag<>cafEdgedBracketOpen then
RaiseStringExpectedButAtomFound(20170421212227,'[');
ReadNextAtom;
Params:=TFindDeclarationParams.Create(Self,Node);
try
Params.Flags:=fdfDefaultForExpressions+[fdfFunctionResult];
AliasType:=CleanFindContext;
Result:=FindExpressionTypeOfTerm(CurPos.StartPos,-1,Params,false,@AliasType);
//debugln(['TFindDeclarationTool.FindExpressionTypeOfConstSet ',ExprTypeToString(Result)]);
finally
Params.Free;
end;
end;
function TFindDeclarationTool.GetDefaultStringType: TExpressionTypeDesc;
begin
if cmsDefault_unicodestring in Scanner.CompilerModeSwitches then
Result:=xtUnicodeString
else if (Scanner.PascalCompiler=pcDelphi)
or ((Scanner.CompilerMode=cmDELPHI)
or (Scanner.Values['LONGSTRINGS']='1')) then
Result:=xtAnsiString
else
Result:=xtString;
end;
function TFindDeclarationTool.CalculateBinaryOperator(LeftOperand,
RightOperand: TOperand; BinaryOperator: TAtomPosition;
Params: TFindDeclarationParams): TOperand;
begin
Result.Expr:=CleanExpressionType;
Result.AliasType:=CleanFindContext;
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.CalculateBinaryOperator] A',
' LeftOperand=',ExprTypeToString(LeftOperand.Expr),
' Operator=',GetAtom(BinaryOperator),
' RightOperand=',ExprTypeToString(RightOperand.Expr)
);
{$ENDIF}
// convert Left and RightOperand contexts to expressiontype
if LeftOperand.Expr.Desc=xtContext then begin
LeftOperand.Expr:=LeftOperand.Expr.Context.Tool.ConvertNodeToExpressionType(
LeftOperand.Expr.Context.Node,Params);
end;
if RightOperand.Expr.Desc=xtContext then begin
RightOperand.Expr:=RightOperand.Expr.Context.Tool.ConvertNodeToExpressionType(
RightOperand.Expr.Context.Node,Params);
end;
// ToDo: search for an overloaded operator
if WordIsBooleanOperator.DoItCaseInsensitive(Src,BinaryOperator.StartPos,
BinaryOperator.EndPos-BinaryOperator.StartPos)
then begin
// Boolean operators
// < > <= >= <> in is
Result.Expr.Desc:=xtBoolean;
end
else if (BinaryOperator.EndPos-BinaryOperator.StartPos=1)
and (Src[BinaryOperator.StartPos]='/') then begin
// real division /
Result:=RealTypesOrderList.Compare(LeftOperand, RightOperand, Self, BinaryOperator.EndPos);
if not(Result.Expr.Desc in xtAllRealTypes) then
begin
Result.Expr.Desc:=xtConstReal;
Result.AliasType:=CleanFindContext;
end;
end
else if WordIsOrdNumberOperator.DoItCaseInsensitive(Src,BinaryOperator.StartPos,
BinaryOperator.EndPos-BinaryOperator.StartPos)
then begin
// ordinal number operator
// or xor and mod div shl shr
if LeftOperand.Expr.Desc in xtAllBooleanTypes then
Result:=BooleanTypesOrderList.Compare(LeftOperand, RightOperand, Self, BinaryOperator.EndPos)
else
Result:=IntegerTypesOrderList.Compare(LeftOperand, RightOperand, Self, BinaryOperator.EndPos);
end
else if WordIsNumberOperator.DoItCaseInsensitive(Src,BinaryOperator.StartPos,
BinaryOperator.EndPos-BinaryOperator.StartPos)
then begin
// number operator (or string concatenating or set cut)
// + - *
if (Src[BinaryOperator.StartPos]='+')
and (LeftOperand.Expr.Desc in xtAllStringCompatibleTypes)
then begin
// string/char '+'
if (RightOperand.Expr.Desc in xtAllStringCompatibleTypes)
then
begin
Result:=StringTypesOrderList.Compare(LeftOperand, RightOperand, Self, BinaryOperator.EndPos);
if not(Result.Expr.Desc in xtAllStringTypes) then
begin
Result.Expr.Desc:=xtConstString;
Result.AliasType:=CleanFindContext;
end;
end else begin
MoveCursorToCleanPos(BinaryOperator.EndPos);
ReadNextAtom;
RaiseExceptionFmt(20170421200612,ctsIncompatibleTypesGotExpected,
['char',ExpressionTypeDescNames[RightOperand.Expr.Desc]]);
end;
end else if (Src[BinaryOperator.StartPos] in ['+','-','*'])
and (LeftOperand.Expr.Desc=xtContext)
and (LeftOperand.Expr.Context.Node<>nil)
and (LeftOperand.Expr.Context.Node.Desc=ctnSetType)
then begin
Result:=LeftOperand;
end else begin
if (LeftOperand.Expr.Desc in xtAllRealTypes)
or (RightOperand.Expr.Desc in xtAllRealTypes) then
Result:=RealTypesOrderList.Compare(LeftOperand, RightOperand, Self, BinaryOperator.EndPos)
else if (LeftOperand.Expr.Desc=xtPointer)
or (RightOperand.Expr.Desc=xtPointer)
or ((LeftOperand.Expr.Desc=xtContext)
and (LeftOperand.Expr.Context.Node.Desc=ctnPointerType))
or ((RightOperand.Expr.Desc=xtContext)
and (RightOperand.Expr.Context.Node.Desc=ctnPointerType))
then
Result.Expr.Desc:=xtPointer
else
Result:=IntegerTypesOrderList.Compare(LeftOperand, RightOperand, Self, BinaryOperator.EndPos);
end;
end else begin
// ???
{$IFDEF ShowExprEval}
debugln(['TFindDeclarationTool.CalculateBinaryOperator unknown operator: ',GetAtom(BinaryOperator)]);
{$ENDIF}
Result:=RightOperand;
end;
end;
function TFindDeclarationTool.IsParamExprListCompatibleToNodeList(
FirstTargetParameterNode: TCodeTreeNode;
SourceExprParamList: TExprTypeList; IgnoreMissingParameters: boolean;
Params: TFindDeclarationParams;
CompatibilityList: TTypeCompatibilityList): TTypeCompatibility;
// tests if SourceExprParamList fits into the TargetFirstParameterNode
var
ParamNode: TCodeTreeNode;
i, MinParamCnt, MaxParamCnt: integer;
ParamCompatibility: TTypeCompatibility;
CompatibilityListCount: LongInt;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(FirstTargetParameterNode);{$ENDIF}
// quick check: parameter count
ParamNode:=FirstTargetParameterNode;
MinParamCnt:=0;
while (ParamNode<>nil)
and ((ParamNode.SubDesc and ctnsHasDefaultValue)=0) do begin
ParamNode:=ParamNode.NextBrother;
inc(MinParamCnt);
end;
MaxParamCnt:=MinParamCnt;
while (ParamNode<>nil) do begin
ParamNode:=ParamNode.NextBrother;
inc(MaxParamCnt);
end;
{$IF defined(ShowExprEval) or defined(ShowProcSearch)}
DebugLn('[TFindDeclarationTool.IsParamExprListCompatibleToNodeList] ',
' ExprParamList.Count=',dbgs(SourceExprParamList.Count),
' MinParamCnt=',dbgs(MinParamCnt),' MaxParamCnt=',dbgs(MaxParamCnt)
);
try
{$ENDIF}
Result:=tcExact;
if (SourceExprParamlist.Count>MaxParamCnt)
or ((not IgnoreMissingParameters) and (SourceExprParamList.Count<MinParamCnt))
then begin
Result:=tcIncompatible;
exit;
end;
// check each parameter for compatibility
ParamNode:=FirstTargetParameterNode;
i:=0;
CompatibilityListCount:=SourceExprParamList.Count;
while (ParamNode<>nil) and (i<CompatibilityListCount) do begin
ParamCompatibility:=IsCompatible(ParamNode,SourceExprParamList.Items[i],
Params);
{$IF defined(ShowExprEval) or defined(ShowProcSearch)}
DebugLn(['[TFindDeclarationTool.IsParamExprListCompatibleToNodeList] SourceParam=',ExprTypeToString(SourceExprParamList.Items[i]),' TargetParam=',ExtractNode(ParamNode,[]),' ',TypeCompatibilityNames[ParamCompatibility]]);
{$ENDIF}
if CompatibilityList<>nil then
CompatibilityList[i]:=ParamCompatibility;
if (ParamCompatibility=tcIncompatible)
or ((ParamCompatibility=tcCompatible)
and MoveCursorToParameterSpecifier(ParamNode)
and (UpAtomIs('VAR') or UpAtomIs('CONSTREF')
or (UpAtomIs('OUT') and (cmsOut in Scanner.CompilerModeSwitches))))
then begin
Result:=tcIncompatible;
exit;
end;
if ParamCompatibility=tcCompatible then
Result:=tcCompatible;
ParamNode:=ParamNode.NextBrother;
inc(i);
end;
if (i<SourceExprParamList.Count) then begin
// there are more expressions, then the param list has variables
Result:=tcIncompatible;
end else if (ParamNode<>nil) then begin
// there are not enough expressions for the param list
// -> check if missing variables have default variables
if (ParamNode.SubDesc and ctnsHasDefaultValue)>0 then begin
// the rest params have default values
if CompatibilityList<>nil then begin
while (ParamNode<>nil) and (i<CompatibilityListCount) do begin
CompatibilityList[i]:=tcExact;
ParamNode:=ParamNode.NextBrother;
inc(i);
end;
end;
end else if not IgnoreMissingParameters then begin
// not enough expression for param list
// -> incompatible
Result:=tcIncompatible;
end;
end;
{$IF defined(ShowExprEval) or defined(ShowProcSearch)}
finally
DebugLn('[TFindDeclarationTool.IsParamExprListCompatibleToNodeList] END ',
' Result=',TypeCompatibilityNames[Result],' ! ONLY VALID if no error !'
);
end;
{$ENDIF}
end;
function TFindDeclarationTool.IsParamNodeListCompatibleToExprList(
TargetExprParamList: TExprTypeList; FirstSourceParameterNode: TCodeTreeNode;
Params: TFindDeclarationParams;
CompatibilityList: TTypeCompatibilityList): TTypeCompatibility;
// tests if FirstSourceParameterNode fits (i.e. can be assigned) into
// the TargetExprParamList
var
ParamNode: TCodeTreeNode;
i, MinParamCnt, MaxParamCnt: integer;
ParamCompatibility: TTypeCompatibility;
SourceExprType: TExpressionType;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(FirstSourceParameterNode);{$ENDIF}
// quick check: parameter count
MinParamCnt:=0;
ParamNode:=FirstSourceParameterNode;
while (ParamNode<>nil) do begin
ParamNode:=ParamNode.NextBrother;
inc(MinParamCnt);
end;
MaxParamCnt:=MinParamCnt;
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.IsParamNodeListCompatibleToExprList] ',
' ExprParamList.Count=',dbgs(TargetExprParamList.Count),' ',
' MinParamCnt=',dbgs(MinParamCnt),' MaxParamCnt=',dbgs(MaxParamCnt)
);
try
{$ENDIF}
Result:=tcExact;
if (TargetExprParamList.Count<>MaxParamCnt) then begin
Result:=tcIncompatible;
exit;
end;
// check each parameter for compatibility
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.IsParamNodeListCompatibleToExprList] ',
' ExprParamList=[',TargetExprParamList.AsString,']');
{$ENDIF}
ParamNode:=FirstSourceParameterNode;
i:=0;
while (ParamNode<>nil) and (i<TargetExprParamList.Count) do begin
SourceExprType:=ConvertNodeToExpressionType(ParamNode,Params);
ParamCompatibility:=IsCompatible(TargetExprParamList.Items[i],
SourceExprType,Params);
{$IFDEF ShowExprEval}
DebugLn(['[TFindDeclarationTool.IsParamNodeListCompatibleToExprList] B ',i,' Source=[',ExprTypeToString(SourceExprType),'] Target=[',ExprTypeToString(TargetExprParamList.Items[i]),'] Result=',TypeCompatibilityNames[ParamCompatibility]]);
{$ENDIF}
if CompatibilityList<>nil then
CompatibilityList[i]:=ParamCompatibility;
if ParamCompatibility=tcIncompatible then begin
Result:=tcIncompatible;
exit;
end else if ParamCompatibility=tcCompatible then begin
Result:=tcCompatible;
end;
ParamNode:=ParamNode.NextBrother;
inc(i);
end;
if (ParamNode<>nil) or (i<TargetExprParamList.Count) then
RaiseException(20170421200618,'Internal Error: one param list has changed');
{$IFDEF ShowExprEval}
finally
DebugLn('[TFindDeclarationTool.IsParamNodeListCompatibleToExprList] END ',
' Result=',TypeCompatibilityNames[Result],' ! ONLY VALID if no error !'
);
end;
{$ENDIF}
end;
function TFindDeclarationTool.IsParamNodeListCompatibleToParamNodeList(
FirstTargetParameterNode, FirstSourceParameterNode: TCodeTreeNode;
Params: TFindDeclarationParams;
CompatibilityList: TTypeCompatibilityList): TTypeCompatibility;
var
CurParamNode1, CurParamNode2: TCodeTreeNode;
ParamCompatibility: TTypeCompatibility;
SourceExprType, TargetExprType: TExpressionType;
OldFlags: TFindDeclarationFlags;
i: integer;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(FirstTargetParameterNode);{$ENDIF}
// quick check: parameter count
CurParamNode1:=FirstTargetParameterNode;
CurParamNode2:=FirstSourceParameterNode;
while (CurParamNode1<>nil) and (CurParamNode2<>nil) do begin
CurParamNode1:=CurParamNode1.NextBrother;
CurParamNode2:=CurParamNode2.NextBrother;
end;
if (CurParamNode1<>nil) or (CurParamNode2<>nil) then begin
Result:=tcIncompatible;
exit;
end;
// check each parameter
OldFlags:=Params.Flags;
Params.Flags:=Params.Flags-[fdfFindVariable]+[fdfIgnoreOverloadedProcs];
CurParamNode1:=FirstTargetParameterNode;
CurParamNode2:=FirstSourceParameterNode;
Result:=tcExact;
i:=0;
while (CurParamNode1<>nil) and (CurParamNode2<>nil) do begin
TargetExprType:=ConvertNodeToExpressionType(CurParamNode1,Params);
SourceExprType:=ConvertNodeToExpressionType(CurParamNode2,Params);
ParamCompatibility:=IsBaseCompatible(TargetExprType,SourceExprType,Params);
if CompatibilityList<>nil then
CompatibilityList[i]:=ParamCompatibility;
if ParamCompatibility=tcIncompatible then begin
Result:=tcIncompatible;
exit;
end else if ParamCompatibility=tcCompatible then begin
Result:=tcCompatible;
end;
CurParamNode1:=CurParamNode1.NextBrother;
CurParamNode2:=CurParamNode2.NextBrother;
inc(i);
end;
Params.Flags:=OldFlags;
end;
function TFindDeclarationTool.GetParameterNode(Node: TCodeTreeNode
): TCodeTreeNode;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(Node);{$ENDIF}
Result:=Node;
if Result=nil then exit;
if Result.Desc=ctnReferenceTo then begin
Result:=Result.FirstChild;
if Result=nil then exit;
end;
if (Result.Desc in [ctnProperty,ctnGlobalProperty]) then
Result:=Result.FirstChild
else if Result.Desc in [ctnProcedure,ctnProcedureHead,ctnProcedureType] then begin
BuildSubTreeForProcHead(Result);
if Result.Desc in [ctnProcedure,ctnProcedureType] then
Result:=Result.FirstChild;
if Result.Desc=ctnProcedureHead then
Result:=Result.FirstChild;
end;
end;
function TFindDeclarationTool.GetFirstParameterNode(Node: TCodeTreeNode
): TCodeTreeNode;
begin
Result:=GetParameterNode(Node);
if Result<>nil then Result:=Result.FirstChild;
end;
function TFindDeclarationTool.CheckSrcIdentifier(
Params: TFindDeclarationParams;
const FoundContext: TFindContext): TIdentifierFoundResult;
// this is a TOnIdentifierFound function
// if identifier found is a proc then it searches for the best overloaded proc
function CallHasEmptyParamsAndFoundProcFits: boolean;
var
FirstParameterNode: TCodeTreeNode;
TargetTool: TFindDeclarationTool;
begin
Result:=false;
FirstParameterNode:=FoundContext.Tool.GetFirstParameterNode(
FoundContext.Node);
if (FirstParameterNode<>nil)
and ((FirstParameterNode.SubDesc and ctnsHasDefaultValue)=0) then begin
// found proc needs at least one parameter
exit;
end;
// FoundContext is a proc with no or only default params
TargetTool:=Params.IdentifierTool;
TargetTool.MoveCursorToCleanPos(Params.Identifier);
TargetTool.ReadNextAtom; // read identifier
TargetTool.ReadNextAtom; // read bracket
if TargetTool.CurPos.Flag<>cafRoundBracketOpen then exit;
TargetTool.ReadNextAtom; // read bracket close
if TargetTool.CurPos.Flag<>cafRoundBracketClose then exit;
Result:=true;
end;
var
FirstParameterNode, StartContextNode: TCodeTreeNode;
ParamCompatibility: TTypeCompatibility;
OldInput: TFindDeclarationInput;
CurCompatibilityList: TTypeCompatibilityList;
CompListSize: integer;
NewExprInputList: TExprTypeList;
begin
// the search has found an identifier with the right name
{$IFDEF ShowFoundIdentifier}
DebugLn('[TFindDeclarationTool.CheckSrcIdentifier]',
' Ident=',GetIdentifier(Params.Identifier),
' FoundContext=',FoundContext.Node.DescAsString,
' Flags=[',dbgs(Params.Flags),']'
);
{$ENDIF}
if FoundContext.Node.Desc=ctnProcedure then begin
// the found node is a proc
// 1. the current identifier cache is blind for parameter lists
// => proc identifiers can not be identified by the name alone
// -> do not cache
// 2. Even if there is only one proc. With different search flags,
// different routes will be searched and then there can be another proc.
// The only solution is to store the param expression list and all flags
// in the cache. This is a ToDo
Include(Params.Flags,fdfDoNotCache);
Include(Params.NewFlags,fodDoNotCache);
if (fdfIgnoreOverloadedProcs in Params.Flags) then begin
// do not check for overloaded procs -> ident found
Result:=ifrSuccess;
exit;
end;
// Procs can be overloaded, that means there can be several procs with the
// same name, but with different param lists.
// The search must go on, and the most compatible proc is returned.
if not Params.IdentifierTool.IsPCharInSrc(Params.Identifier) then begin
// Params.Identifier is not in the source of the start tool
// => impossible to check param list, because the context is unknown
// -> identifier found
{$IFDEF ShowProcSearch}
DebugLn('[TFindDeclarationTool.CheckSrcIdentifier]',
' Ident=',GetIdentifier(Params.Identifier),
' NO SOURCE to check params'
);
{$ENDIF}
Result:=ifrSuccess;
exit;
end;
if FoundContext.Tool.NodeIsClassConstructorOrDestructor(FoundContext.Node) then
begin
Result:=ifrProceedSearch;
Exit;
end;
if (not (fdfCollect in Params.Flags))
and CallHasEmptyParamsAndFoundProcFits then begin
// call has brackets without params (e.g. writeln() )
// and found proc fits exactly
// => stop search
{$IF defined(ShowFoundIdentifier) or defined(ShowProcSearch)}
debugln(['TFindDeclarationTool.CheckSrcIdentifier call is () and found proc fits exactly',
' Ident=',GetIdentifier(Params.Identifier),
' ',FoundContext.Tool.CleanPosToStr(FoundContext.Node.StartPos)
]);
{$ENDIF}
Params.SetResult(FoundContext);
Result:=ifrSuccess;
exit;
end;
Result:=ifrProceedSearch;
if (Params.FoundProc=nil) then begin
// this is the first proc found
// -> save it and proceed the search to find all overloadeded procs
{$IF defined(ShowFoundIdentifier) or defined(ShowProcSearch)}
DebugLn('[TFindDeclarationTool.CheckSrcIdentifier]',
' Ident=',GetIdentifier(Params.Identifier),
' ',FoundContext.Tool.CleanPosToStr(FoundContext.Node.StartPos),
' FIRST PROC searching for overloads ...'
);
{$ENDIF}
Params.SetFoundProc(FoundContext);
exit;
end;
// -> check which one is more compatible
// create the input expression list
// (the expressions in the brackets are parsed and converted to types)
if Params.FoundProc^.ExprInputList=nil then begin
{$IF defined(ShowFoundIdentifier) or defined(ShowProcSearch)}
DebugLn('[TFindDeclarationTool.CheckSrcIdentifier]',
' Ident=',GetIdentifier(Params.Identifier),
' Creating Input Expression List ...'
);
{$ENDIF}
if Params.IdentifierTool.IsPCharInSrc(Params.Identifier) then begin
Params.IdentifierTool.MoveCursorToCleanPos(Params.Identifier);
StartContextNode:=Params.IdentifierTool.FindDeepestNodeAtPos(
Params.IdentifierTool.CurPos.StartPos,true);
if (StartContextNode<>nil) then begin
if (StartContextNode.Desc in AllPascalStatements) then begin
{$IFDEF ShowProcSearch}
DebugLn('[TFindDeclarationTool.CheckSrcIdentifier]',
' Ident=',GetIdentifier(Params.Identifier),
' Creating Input Expression List for statement ...'
);
{$ENDIF}
Params.Save(OldInput);
Params.IdentifierTool.MoveCursorToCleanPos(Params.Identifier);
Params.Flags:=fdfDefaultForExpressions+Params.Flags*fdfGlobals;
Params.ContextNode:=StartContextNode;
Params.OnIdentifierFound:=@Params.IdentifierTool.CheckSrcIdentifier;
Params.IdentifierTool.ReadNextAtom;
NewExprInputList:=
Params.IdentifierTool.CreateParamExprListFromStatement(
Params.IdentifierTool.CurPos.EndPos,Params);
{$IFDEF ShowProcSearch}
debugln(['TFindDeclarationTool.CheckSrcIdentifier Params: ',NewExprInputList.AsString]);
{$ENDIF}
Params.Load(OldInput,true);
FreeAndNil(Params.FoundProc^.ExprInputList);
Params.FoundProc^.ExprInputList:=NewExprInputList;
end
else if (StartContextNode.Desc in [ctnProcedureHead,ctnProcedure])
then begin
{$IFDEF ShowProcSearch}
DebugLn('[TFindDeclarationTool.CheckSrcIdentifier]',
' Ident=',GetIdentifier(Params.Identifier),
' Creating Input Expression List for proc node ...'
);
{$ENDIF}
NewExprInputList:=
Params.IdentifierTool.CreateParamExprListFromProcNode(
StartContextNode,Params);
{$IFDEF ShowProcSearch}
debugln(['TFindDeclarationTool.CheckSrcIdentifier Params: ',NewExprInputList.AsString]);
{$ENDIF}
FreeAndNil(Params.FoundProc^.ExprInputList);
Params.FoundProc^.ExprInputList:=NewExprInputList;
end;
end;
end;
if Params.FoundProc^.ExprInputList=nil then begin
// create expression list without params
Params.FoundProc^.ExprInputList:=TExprTypeList.Create;
end;
end;
// create compatibility lists for params
// (each parameter is checked for compatibility)
CompListSize:=SizeOf(TTypeCompatibility)
*Params.FoundProc^.ExprInputList.Count;
if (CompListSize>0)
and (Params.FoundProc^.ParamCompatibilityList=nil) then begin
GetMem(Params.FoundProc^.ParamCompatibilityList,CompListSize);
//DebugLn(['TFindDeclarationTool.CheckSrcIdentifier FoundProc=',dbgs(Params.FoundProc),' New ParamCompatibilityList=',dbgs(Params.FoundProc^.ParamCompatibilityList),' CompListSize=',CompListSize]);
end else begin
//DebugLn(['TFindDeclarationTool.CheckSrcIdentifier FoundProc=',dbgs(Params.FoundProc),' Old ParamCompatibilityList=',dbgs(Params.FoundProc^.ParamCompatibilityList),' CompListSize=',CompListSize]);
end;
// check the first found proc for compatibility
// (compare the expression list with the proc param list)
if not Params.FoundProc^.CacheValid then begin
{$IF defined(ShowFoundIdentifier) or defined(ShowProcSearch)}
DebugLn('[TFindDeclarationTool.CheckSrcIdentifier]',
' Ident=',GetIdentifier(Params.Identifier),
' Check the first found proc for compatibility ...'
);
{$ENDIF}
FirstParameterNode:=Params.FoundProc^.Context.Tool.GetFirstParameterNode(
Params.FoundProc^.Context.Node);
ParamCompatibility:=
Params.FoundProc^.Context.Tool.IsParamExprListCompatibleToNodeList(
FirstParameterNode,
Params.FoundProc^.ExprInputList,
fdfIgnoreMissingParams in Params.Flags,
Params,Params.FoundProc^.ParamCompatibilityList);
Params.FoundProc^.ProcCompatibility:=ParamCompatibility;
Params.FoundProc^.CacheValid:=true;
if ParamCompatibility=tcExact then begin
Params.SetResult(Params.FoundProc^.Context.Tool,
Params.FoundProc^.Context.Node.FirstChild);
end;
end;
if Params.FoundProc^.ProcCompatibility=tcExact then begin
{$IF defined(ShowFoundIdentifier) or defined(ShowProcSearch)}
DebugLn('[TFindDeclarationTool.CheckSrcIdentifier]',
' Ident=',GetIdentifier(Params.Identifier),
' First Proc ParamCompatibility=',TypeCompatibilityNames[Params.FoundProc^.ProcCompatibility]
);
{$ENDIF}
// the first proc fits exactly -> stop the search
Result:=ifrSuccess;
exit;
end;
// check the current proc for compatibility
// (compare the expression list with the proc param list)
{$IF defined(ShowFoundIdentifier) or defined(ShowProcSearch)}
DebugLn('[TFindDeclarationTool.CheckSrcIdentifier]',
' Ident=',GetIdentifier(Params.Identifier),
' Check the current found proc for compatibility ...'
);
{$ENDIF}
if CompListSize>0 then begin
GetMem(CurCompatibilityList,CompListSize);
//DebugLn(['TFindDeclarationTool.CheckSrcIdentifier create temp CurCompatibilityList=',dbgs(CurCompatibilityList),' CompListSize=',CompListSize]);
end else begin
CurCompatibilityList:=nil;
end;
try
FirstParameterNode:=
FoundContext.Tool.GetFirstParameterNode(FoundContext.Node);
ParamCompatibility:=
FoundContext.Tool.IsParamExprListCompatibleToNodeList(
FirstParameterNode,
Params.FoundProc^.ExprInputList,
fdfIgnoreMissingParams in Params.Flags,
Params,CurCompatibilityList);
{$IF defined(ShowFoundIdentifier) or defined(ShowProcSearch)}
DebugLn('[TFindDeclarationTool.CheckSrcIdentifier]',
' Ident=',GetIdentifier(Params.Identifier),
' Current Proc ParamCompatibility=',TypeCompatibilityNames[ParamCompatibility]
);
{$ENDIF}
if ParamCompatibility=tcExact then begin
// the current proc fits exactly -> stop the search
Params.ChangeFoundProc(FoundContext,ParamCompatibility,
CurCompatibilityList);
CurCompatibilityList:=nil; // set to nil, so that it will not be freed
Params.SetResult(FoundContext.Tool,FoundContext.Node.FirstChild);
Result:=ifrSuccess;
end else if ParamCompatibility=tcCompatible then begin
// the proc fits not exactly, but is compatible
if (Params.FoundProc^.ProcCompatibility=tcInCompatible)
or CompatibilityList1IsBetter(CurCompatibilityList,
Params.FoundProc^.ParamCompatibilityList,
Params.FoundProc^.ExprInputList.Count) then
begin
// the new proc fits better
Params.ChangeFoundProc(FoundContext,ParamCompatibility,CurCompatibilityList);
CurCompatibilityList:=nil; // set to nil, so that it will not be freed
end;
end;
finally
// end overloaded proc search
if CurCompatibilityList<>nil then begin
//DebugLn(['TFindDeclarationTool.CheckSrcIdentifier free CurCompatibilityList=',dbgs(CurCompatibilityList)]);
FreeMem(CurCompatibilityList);
end;
end;
end else
if (FoundContext.Node.Desc=ctnVarDefinition) then begin
if not (fdfIgnoreClassVisibility in Params.Flags)
and (FoundContext.Tool<>Params.IdentifierTool)
and (GetClassVisibility(FoundContext.Node)=ctnClassPrivate) then
Result:=ifrProceedSearch
else
Result:=ifrSuccess;
end else begin
Result:=ifrSuccess;
end;
end;
function TFindDeclarationTool.DoOnIdentifierFound(
Params: TFindDeclarationParams;
FoundNode: TCodeTreeNode): TIdentifierFoundResult;
// this internal function is called, whenever an identifier is found
var IsTopLvlIdent: boolean;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(FoundNode);{$ENDIF}
IsTopLvlIdent:=(fdfTopLvlResolving in Params.Flags);
if Assigned(Params.OnIdentifierFound) then
Result:=Params.OnIdentifierFound(Params,CreateFindContext(Self,FoundNode))
else
Result:=ifrSuccess;
if (Result=ifrSuccess) and IsTopLvlIdent
and Assigned(Params.OnTopLvlIdentifierFound) then
Params.OnTopLvlIdentifierFound(Params,CreateFindContext(Self,FoundNode));
end;
function TFindDeclarationTool.IsCompatible(TargetNode: TCodeTreeNode;
const ExpressionType: TExpressionType;
Params: TFindDeclarationParams): TTypeCompatibility;
var TargetContext: TFindContext;
OldInput: TFindDeclarationInput;
NodeExprType: TExpressionType;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(TargetNode);{$ENDIF}
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.IsCompatible] A Node=',TargetNode.DescAsString,
' ExpressionType=',ExpressionTypeDescNames[ExpressionType.Desc]);
{$ENDIF}
Result:=tcIncompatible;
// find base type of node
OldInput.Flags:=Params.Flags;
Include(Params.Flags,fdfExceptionOnNotFound);
TargetContext:=FindBaseTypeOfNode(Params,TargetNode);
Params.Flags:=OldInput.Flags;
// compare node base type and ExpressionType
if (ExpressionType.Context.Node<>nil)
and (ExpressionType.Context.Node=TargetContext.Node) then begin
// same base type
Result:=tcExact;
end
else if (TargetContext.Node.Desc=ctnGenericParameter)
or ((ExpressionType.Desc=xtContext)
and (ExpressionType.Context.Node.Desc=ctnGenericParameter))
then begin
// generic type is always preferred
Result:=tcExact;
end
else if (TargetContext.Node.Desc=ctnSetType) then begin
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.IsCompatible] TargetContext.Node.Desc=ctnSetType',
' "',copy(TargetContext.Tool.Src,TargetContext.Node.Parent.StartPos,20),'"');
{$ENDIF}
if (ExpressionType.Desc=xtConstSet) then begin
// both are sets, compare type of sets
if (ExpressionType.SubDesc<>xtNone) then begin
// ToDo: check if enums of expression fits into enums of target
// ToDo: ppu, dcu
Result:=tcCompatible;
end else
// the empty set is compatible to all kinds of sets
Result:=tcExact;
end else begin
end;
end else begin
NodeExprType:=CleanExpressionType;
NodeExprType.Desc:=xtContext;
NodeExprType.Context:=CreateFindContext(Self,TargetNode);
Result:=IsCompatible(NodeExprType,ExpressionType,Params);
end;
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.IsCompatible] END',
' BaseNode=',TargetContext.Node.DescAsString,
' ExpressionType=',ExpressionTypeDescNames[ExpressionType.Desc],
' Result=',TypeCompatibilityNames[Result]
);
{$ENDIF}
end;
function TFindDeclarationTool.IsCompatible(TargetType,
ExpressionType: TExpressionType; Params: TFindDeclarationParams
): TTypeCompatibility;
begin
if TargetType.Desc=xtContext then begin
if TargetType.Context.Node.Desc=ctnGenericParameter then
exit(tcExact);
TargetType:=TargetType.Context.Tool.ConvertNodeToExpressionType(
TargetType.Context.Node,Params);
end;
if ExpressionType.Desc=xtContext then begin
if ExpressionType.Context.Node.Desc=ctnGenericParameter then
exit(tcExact);
ExpressionType:=ExpressionType.Context.Tool.ConvertNodeToExpressionType(
ExpressionType.Context.Node,Params);
end;
Result:=IsBaseCompatible(TargetType,ExpressionType,Params);
end;
function TFindDeclarationTool.GetCurrentAtomType: TVariableAtomType;
var
Node: TCodeTreeNode;
c: Char;
begin
//debugln(['TFindDeclarationTool.GetCurrentAtomType ',CurPos.StartPos,' ',CurPos.EndPos,' ',SrcLen,' ',GetAtom]);
if (CurPos.StartPos=CurPos.EndPos) then
exit(vatSpace)
else if (CurPos.StartPos<1) or (CurPos.StartPos>SrcLen) then
exit(vatNone);
c:=Src[CurPos.StartPos];
if IsIdentStartChar[c] then begin
if WordIsPredefinedIdentifier.DoItCaseInsensitive(Src,CurPos.StartPos,
CurPos.EndPos-CurPos.StartPos) then
exit(vatPreDefIdentifier)
else if UpAtomIs('INHERITED') then
exit(vatINHERITED)
else if UpAtomIs('AS') then
exit(vatAS)
else if WordIsKeyWord.DoItCaseInsensitive(Src,CurPos.StartPos,
CurPos.EndPos-CurPos.StartPos) then
exit(vatKeyWord)
else if UpAtomIs('PROPERTY') then begin
Node:=FindDeepestNodeAtPos(CurPos.StartPos,false);
if (Node<>nil) and (Node.Desc in [ctnProperty,ctnPropertySection]) then
exit(vatKeyword)
else
exit(vatIdentifier);
end else
exit(vatIdentifier);
end else if (CurPos.StartPos=CurPos.EndPos-1) then begin
case c of
'.': exit(vatPoint);
'^': exit(vatUp);
'(': exit(vatRoundBracketOpen);
')': exit(vatRoundBracketClose);
'[': exit(vatEdgedBracketOpen);
']': exit(vatEdgedBracketClose);
'@': exit(vatAddrOp);
else exit(vatNone);
end;
end
else begin
case c of
'''','#': exit(vatStringConstant);
'&':
begin
if (CurPos.StartPos+1=CurPos.EndPos) then exit(vatNone);
c:=Src[CurPos.StartPos+1];
if IsIdentStartChar[c] then begin
// &keyword
exit(vatIdentifier);
end else if IsNumberChar[c] then
exit(vatNumber) // octal
else exit(vatNone);
end;
else exit(vatNone);
end;
end;
end;
function TFindDeclarationTool.CreateParamExprListFromStatement(
StartPos: integer; Params: TFindDeclarationParams; GetAlias: boolean
): TExprTypeList;
var ExprType: TExpressionType;
BracketClose: char;
ExprStartPos, ExprEndPos: integer;
CurIgnoreErrorAfterPos: Integer;
OldFlags: TFindDeclarationFlags;
ok: Boolean;
AliasType: TFindContext;
procedure RaiseBracketNotFound;
begin
RaiseExceptionFmt(20170421200621,ctsStrExpectedButAtomFound,[BracketClose,GetAtom]);
end;
begin
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.CreateParamExprListFromStatement] ',
'"',copy(Src,StartPos,40),'" Context=',Params.ContextNode.DescAsString);
{$ENDIF}
Result:=TExprTypeList.Create;
ok:=false;
try
MoveCursorToCleanPos(StartPos);
ReadNextAtom; // reads first atom after proc name
if AtomIsChar('(') then
BracketClose:=')'
else if AtomIsChar('[') then
BracketClose:=']'
else
BracketClose:=#0;
if IgnoreErrorAfterValid then
CurIgnoreErrorAfterPos:=IgnoreErrorAfterCleanedPos
else
CurIgnoreErrorAfterPos:=-1;
OldFlags:=Params.Flags;
if BracketClose<>#0 then begin
// read parameter list
ReadNextAtom;
if not AtomIsChar(BracketClose) then begin
// read all expressions
while true do begin
ExprStartPos:=CurPos.StartPos;
// read til comma or bracket close
repeat
if CurPos.Flag in [cafRoundBracketOpen,cafEdgedBracketOpen] then begin
ReadTilBracketClose(true);
end;
ReadNextAtom;
if (CurPos.StartPos>SrcLen)
or (CurPos.Flag in [cafRoundBracketClose,cafEdgedBracketClose,cafComma])
then
break;
until false;
ExprEndPos:=CurPos.StartPos;
// find expression type
if (CurIgnoreErrorAfterPos>=ExprStartPos) then
Params.Flags:=Params.Flags-[fdfExceptionOnNotFound];
//DebugLn('TFindDeclarationTool.CreateParamExprListFromStatement CurIgnoreErrorAfterPos=',dbgs(CurIgnoreErrorAfterPos),' ExprStartPos=',dbgs(ExprStartPos));
if GetAlias then begin
AliasType:=CleanFindContext;
ExprType:=FindExpressionResultType(Params,ExprStartPos,ExprEndPos,@AliasType);
Result.Add(ExprType,AliasType);
end else begin
ExprType:=FindExpressionResultType(Params,ExprStartPos,ExprEndPos);
Result.Add(ExprType);
end;
MoveCursorToCleanPos(ExprEndPos);
ReadNextAtom;
if AtomIsChar(BracketClose) then break;
if not AtomIsChar(',') then
RaiseBracketNotFound;
ReadNextAtom;
end;
end;
end;
Params.Flags:=OldFlags;
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.CreateParamExprListFromStatement] END ',
'ParamCount=',dbgs(Result.Count),' "',copy(Src,StartPos,40),'"');
DebugLn(' ExprList=[',Result.AsString,']');
{$ENDIF}
Ok:=true;
finally
if not Ok then Result.Free;
end;
end;
function TFindDeclarationTool.CreateParamExprListFromProcNode(
ProcNode: TCodeTreeNode; Params: TFindDeclarationParams): TExprTypeList;
var
ExprType: TExpressionType;
ParamNode: TCodeTreeNode;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(ProcNode);{$ENDIF}
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.CreateParamExprListFromProcNode] ',
'"',copy(Src,ProcNode.StartPos,40),'" Context=',ProcNode.DescAsString);
{$ENDIF}
Result:=TExprTypeList.Create;
ParamNode:=GetFirstParameterNode(ProcNode);
while ParamNode<>nil do begin
// find expression type
ExprType:=ConvertNodeToExpressionType(ParamNode,Params);
// add expression type to list
Result.Add(ExprType);
ParamNode:=ParamNode.NextBrother;
end;
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.CreateParamExprListFromProcNode] END ',
'ParamCount=',dbgs(Result.Count),' "',copy(Src,ProcNode.StartPos,40),'"');
DebugLn(' ExprList=[',Result.AsString,']');
{$ENDIF}
end;
function TFindDeclarationTool.CompatibilityList1IsBetter( List1,
List2: TTypeCompatibilityList; ListCount: integer): boolean;
// List1 and List2 should only contain tcCompatible and tcExact values
var i: integer;
begin
// search first difference, start at end
i:=ListCount-1;
while (i>=0) and (List1[i]=List2[i]) do dec(i);
// List1 is better, if first difference is better for List1
Result:=(i>=0) and (List1[i]=tcExact);
{$IFDEF ShowFoundIdentifier}
DebugLn('[TFindDeclarationTool.CompatibilityList1IsBetter] END i=',dbgs(i));
{$ENDIF}
end;
function TFindDeclarationTool.ContextIsDescendOf(const DescendContext,
AncestorContext: TFindContext; Params: TFindDeclarationParams): boolean;
procedure RaiseInternalError;
begin
RaiseException(20170421200624,'[TFindDeclarationTool.ContextIsDescendOf] '
+' internal error: DescendContext.Desc<>ctnClass');
end;
var CurContext: TFindContext;
OldInput: TFindDeclarationInput;
begin
if not (DescendContext.Node.Desc in AllClasses) then
RaiseInternalError;
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.ContextIsDescendOf] ',
' DescendContext="',copy(DescendContext.Tool.Src,DescendContext.Node.Parent.StartPos,15),'"');
{$ENDIF}
CurContext:=DescendContext;
Params.Save(OldInput);
repeat
Result:=CurContext.Tool.FindAncestorOfClass(CurContext.Node,Params,true);
if Result then begin
CurContext:=CreateFindContext(Params);
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.ContextIsDescendOf] B ',
' CurContext="',copy(CurContext.Tool.Src,CurContext.Node.Parent.StartPos,15),'"');
{$ENDIF}
Result:=FindContextAreEqual(CurContext,AncestorContext);
if Result then exit;
end else
break;
until false;
Result:=false;
end;
function TFindDeclarationTool.IsBaseCompatible(const TargetType,
ExpressionType: TExpressionType; Params: TFindDeclarationParams
): TTypeCompatibility;
// test if ExpressionType can be assigned to TargetType
// both expression types must be base types
var TargetNode, ExprNode: TCodeTreeNode;
begin
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.IsBaseCompatible] START ',
' TargetType=',ExprTypeToString(TargetType),
' ExpressionType=',ExprTypeToString(ExpressionType));
{$ENDIF}
Result:=tcIncompatible;
if (TargetType.Desc=xtContext)
and (TargetType.Context.Node.Desc=ctnGenericParameter) then
exit(tcExact);
if (ExpressionType.Desc=xtContext)
and (ExpressionType.Context.Node.Desc=ctnGenericParameter) then
exit(tcExact);
if (TargetType.Desc=ExpressionType.Desc) then begin
case TargetType.Desc of
xtNone: ;
xtContext:
begin
TargetNode:=TargetType.Context.Node;
ExprNode:=ExpressionType.Context.Node;
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.IsBaseCompatible] C ',
' TargetContext="',copy(TargetType.Context.Tool.Src,TargetType.Context.Node.StartPos,20),'"',
' ExpressionContext="',copy(ExpressionType.Context.Tool.Src,ExpressionType.Context.Node.StartPos,20),'"'
);
{$ENDIF}
if TargetNode=ExprNode then
Result:=tcExact
else
if ExprNode.Desc=TargetNode.Desc then begin
// same context type
case ExprNode.Desc of
ctnClass, ctnClassInterface, ctnDispinterface, ctnObject, ctnRecordType,
ctnClassHelper, ctnRecordHelper, ctnTypeHelper,
ctnObjCClass, ctnObjCCategory, ctnObjCProtocol, ctnCPPClass:
// check, if ExpressionType.Context descends from TargetContext
if ContextIsDescendOf(ExpressionType.Context,
TargetType.Context,Params)
then
Result:=tcExact;
ctnRangedArrayType,ctnOpenArrayType:
// ToDo: check range and type of arrayfields
begin
Result:=tcCompatible;
end;
end;
end else begin
// different context type
end;
end;
else
Result:=tcExact;
end;
end else if ((TargetType.Desc=xtPointer)
and (ExpressionType.Desc=xtContext)
and (ExpressionType.Context.Node.Desc in AllClasses))
then begin
// assigning a class to a pointer
Result:=tcExact;
end else begin
// check, if ExpressionType can be auto converted into TargetType
if ((TargetType.Desc in xtAllRealTypes)
and (ExpressionType.Desc in xtAllRealConvertibles))
or ((TargetType.Desc in xtAllStringTypes)
and (ExpressionType.Desc in xtAllStringConvertibles))
or ((TargetType.Desc in xtAllWideStringTypes)
and (ExpressionType.Desc in xtAllWideStringCompatibleTypes))
or ((TargetType.Desc in xtAllIntegerTypes)
and (ExpressionType.Desc in xtAllIntegerConvertibles))
or ((TargetType.Desc in xtAllBooleanTypes)
and (ExpressionType.Desc in xtAllBooleanConvertibles))
or ((TargetType.Desc in xtAllPointerTypes)
and (ExpressionType.Desc in xtAllPointerConvertibles))
or (TargetType.Desc=xtJSValue)
then
Result:=tcCompatible
else if (TargetType.Desc=xtContext) then begin
TargetNode:=TargetType.Context.Node;
if ((TargetNode.Desc in (AllClasses+[ctnProcedure]))
and (ExpressionType.Desc=xtNil))
or ((TargetNode.Desc in [ctnOpenArrayType,ctnRangedArrayType])
and (TargetNode.LastChild<>nil)
and (TargetNode.LastChild.Desc=ctnOfConstType)
and (ExpressionType.Desc=xtConstSet))
then
Result:=tcCompatible
end
else if (ExpressionType.Desc=xtContext) then begin
ExprNode:=ExpressionType.Context.Node;
if (TargetType.Desc=xtFile) and (ExprNode.Desc=ctnFileType)
then
Result:=tcCompatible
end;
end;
{$IFDEF ShowExprEval}
DebugLn('[TFindDeclarationTool.IsBaseCompatible] END ',
' TargetType=',ExpressionTypeDescNames[TargetType.Desc],
' ExpressionType=',ExpressionTypeDescNames[ExpressionType.Desc],
' Result=',TypeCompatibilityNames[Result]
);
{$ENDIF}
end;
function TFindDeclarationTool.CheckParameterSyntax(StartPos,
CleanCursorPos: integer; out ParameterAtom, ProcNameAtom: TAtomPosition; out
ParameterIndex: integer): boolean;
// check for Identifier(expr,expr,...,expr,VarName
// or Identifier[expr,expr,...,expr,VarName
// ParameterIndex is 0 based
{off $DEFINE VerboseCPS}
procedure RaiseBracketNotOpened;
begin
if CurPos.Flag=cafRoundBracketClose then
RaiseExceptionFmt(20170421200628,ctsBracketNotFound,['('])
else
RaiseExceptionFmt(20170421200630,ctsBracketNotFound,['[']);
end;
function CheckIdentifierAndParameterList: boolean; forward;
function CheckBrackets: boolean;
{ check simple brackets (no identifier in front of brackets)
}
var
BracketAtom: TAtomPosition;
begin
BracketAtom:=CurPos;
{$IFDEF VerboseCPS}DebugLn('CheckBrackets "',GetAtom,'" BracketAtom=',dbgs(BracketAtom));{$ENDIF}
repeat
ReadNextAtom;
if CurPos.Flag in [cafRoundBracketOpen,cafEdgedBracketOpen] then begin
if (LastAtoms.GetPriorAtom.Flag=cafWord) then begin
{$IFDEF VerboseCPS}DebugLn('CheckBrackets check word+bracket open');{$ENDIF}
UndoReadNextAtom;
if CheckIdentifierAndParameterList() then exit(true);
end else begin
{$IFDEF VerboseCPS}DebugLn('CheckBrackets check bracket open');{$ENDIF}
if CheckBrackets() then exit(true);
end;
end else if CurPos.Flag in [cafRoundBracketClose,cafEdgedBracketClose]
then begin
if (BracketAtom.Flag=cafRoundBracketOpen)
=(CurPos.Flag=cafRoundBracketClose)
then begin
// closing bracket found, but the variable was not in them
{$IFDEF VerboseCPS}DebugLn('CheckBrackets bracket closed');{$ENDIF}
exit(false);
end else begin
// invalid closing bracket found
RaiseBracketNotOpened;
end;
end;
until (CurPos.EndPos>CleanCursorPos);
Result:=false;
end;
function CheckIdentifierAndParameterList: boolean;
{ when called: CursorPos is at an identifier followed by a ( or [
}
var
BracketAtom: TAtomPosition;
CurProcNameAtom: TAtomPosition;
CurParameterIndex: Integer;
ParameterStart: integer;
begin
Result:=false;
if CurPos.Flag<>cafWord then exit;
CurProcNameAtom:=CurPos;
CurParameterIndex:=0;
{$IFDEF VerboseCPS}DebugLn('CheckIdentifierAndParameterList START "',GetAtom,'" ',dbgs(CurProcNameAtom));{$ENDIF}
ReadNextAtom;
if not (CurPos.Flag in [cafRoundBracketOpen,cafEdgedBracketOpen]) then exit;
BracketAtom:=CurPos;
ParameterStart:=CurPos.EndPos;
{$IFDEF VerboseCPS}DebugLn('CheckIdentifierAndParameterList Bracket="',GetAtom,'"');{$ENDIF}
repeat
ReadNextAtom;
{$IFDEF VerboseCPS}DebugLn('CheckIdentifierAndParameterList Atom="',GetAtom,'"');{$ENDIF}
if (CurPos.EndPos>CleanCursorPos)
or ((CurPos.EndPos=CleanCursorPos)
and ((CurPos.Flag=cafWord) or AtomIsChar('@')))
then begin
// parameter found => search parameter expression bounds e.g. ', parameter ,'
// important: this function should work, even if the code
// behind CleanCursorPos has syntax errors
{$IFDEF VerboseCPS}DebugLn('CheckIdentifierAndParameterList Parameter found, search range ...');{$ENDIF}
ProcNameAtom:=CurProcNameAtom;
ParameterIndex:=CurParameterIndex;
ParameterAtom.StartPos:=ParameterStart;
ParameterAtom.EndPos:=ParameterStart;
MoveCursorToCleanPos(ParameterStart);
repeat
ReadNextAtom;
{$IFDEF VerboseCPS}DebugLn('CheckIdentifierAndParameterList parameter atom "',GetAtom,'"');{$ENDIF}
if (CurPos.Flag in [cafRoundBracketOpen,cafEdgedBracketOpen]) then
begin
// atom belongs to the parameter expression
if ParameterAtom.StartPos=ParameterAtom.EndPos then
ParameterAtom.StartPos:=CurPos.StartPos;
ReadTilBracketClose(false);
ParameterAtom.EndPos:=CurPos.EndPos;
end
else
if (CurPos.StartPos>SrcLen)
or (CurPos.Flag in [cafComma,cafSemicolon,cafEnd,
cafRoundBracketClose,cafEdgedBracketClose])
or ((CurPos.Flag=cafWord)
and (LastAtoms.GetPriorAtom.Flag=cafWord)
and (not LastUpAtomIs(0,'INHERITED'))) then
begin
// end of parameter expression found
{$IFDEF VerboseCPS}DebugLn('CheckIdentifierAndParameterList end of parameter found "',GetAtom,'" Parameter="',dbgstr(Src,ParameterAtom.StartPos,ParameterAtom.EndPos-ParameterAtom.StartPos),'"');{$ENDIF}
exit(true);
end else begin
// atom belongs to the parameter expression
if ParameterAtom.StartPos=ParameterAtom.EndPos then
ParameterAtom.StartPos:=CurPos.StartPos;
ParameterAtom.EndPos:=CurPos.EndPos;
end;
until false;
end;
if (CurPos.Flag in [cafRoundBracketOpen,cafEdgedBracketOpen]) then begin
if (LastAtoms.GetPriorAtom.Flag=cafWord) then begin
{$IFDEF VerboseCPS}DebugLn('CheckIdentifierAndParameterList check word+bracket open');{$ENDIF}
UndoReadNextAtom;
if CheckIdentifierAndParameterList() then exit(true);
end else begin
{$IFDEF VerboseCPS}DebugLn('CheckIdentifierAndParameterList check bracket open');{$ENDIF}
if CheckBrackets then exit(true);
end;
end
else if CurPos.Flag in [cafRoundBracketClose,cafEdgedBracketClose] then
begin
{$IFDEF VerboseCPS}DebugLn('CheckIdentifierAndParameterList check bracket close');{$ENDIF}
if (BracketAtom.Flag=cafRoundBracketOpen)
=(CurPos.Flag=cafRoundBracketClose)
then begin
// parameter list ended in front of Variable => continue search
{$IFDEF VerboseCPS}DebugLn('CheckIdentifierAndParameterList parameter list ended in front of cursor');{$ENDIF}
if CurPos.Flag=cafEdgedBracketClose then begin
ReadNextAtom;
if CurPos.Flag=cafEdgedBracketOpen then begin
// [][] is equal to [,]
ParameterStart:=CurPos.EndPos;
inc(CurParameterIndex);
continue;
end else
UndoReadNextAtom;
end;
exit;
end else begin
// invalid closing bracket found
RaiseBracketNotOpened;
end;
end;
// finally after checking the expression: count commas
if CurPos.Flag=cafComma then begin
ParameterStart:=CurPos.EndPos;
inc(CurParameterIndex);
end;
{$IFDEF VerboseCPS}DebugLn('CheckIdentifierAndParameterList After parsing atom. atom="',GetAtom,'"');{$ENDIF}
until (CurPos.EndPos>CleanCursorPos);
end;
var
CommentStart: integer;
CommentEnd: integer;
CleanPosInFront: Integer;
begin
Result:=false;
ParameterAtom:=CleanAtomPosition;
ProcNameAtom:=CleanAtomPosition;
ParameterIndex:=0;
//DebugLn('TFindDeclarationTool.CheckParameterSyntax START');
if StartPos<1 then exit;
// read code in front to find ProcName and check the syntax
MoveCursorToCleanPos(StartPos);
repeat
ReadNextAtom;
{$IFDEF VerboseCPS}
DebugLn('TFindDeclarationTool.CheckParameterSyntax ',GetAtom,' at ',CleanPosToStr(CurPos.StartPos),' ',dbgs(CurPos.EndPos),'<',dbgs(CleanCursorPos));
{$ENDIF}
if CurPos.EndPos>CleanCursorPos then begin
if not LastAtoms.HasPrior then exit;
CleanPosInFront:=LastAtoms.GetPriorAtom.EndPos;
//debugln(['TFindDeclarationTool.CheckParameterSyntax Cur="',GetAtom,'" Last="',GetAtom(LastAtoms.GetValueAt(0)),'"']);
if not CleanPosIsInComment(CleanCursorPos,CleanPosInFront,
CommentStart,CommentEnd,false) then exit;
// cursor in a comment
// => parse within the comment
MoveCursorToCleanPos(CommentStart);
end else if (CurPos.Flag in [cafRoundBracketOpen,cafEdgedBracketOpen])
and (LastAtoms.GetPriorAtom.Flag=cafWord) then begin
UndoReadNextAtom;
if CheckIdentifierAndParameterList then exit(true);
if CurPos.EndPos>CleanCursorPos then exit;
end;
until false;
end;
procedure TFindDeclarationTool.OnFindUsedUnitIdentifier(
Sender: TPascalParserTool; IdentifierCleanPos: integer; Range: TEPRIRange;
Node: TCodeTreeNode; Data: Pointer; var Abort: boolean);
var
Identifier: PChar;
CacheEntry: PInterfaceIdentCacheEntry;
refs: TFindUsedUnitReferences;
Found: Boolean;
ReferencePos: TCodeXYPosition;
begin
if Range=epriInDirective then exit;
if not (Node.Desc in (AllPascalTypes+AllPascalStatements)) then exit;
Identifier:=@Src[IdentifierCleanPos];
refs:=TFindUsedUnitReferences(Data);
CacheEntry:=refs.TargetTool.FInterfaceIdentifierCache.FindIdentifier(Identifier);
//debugln(['TFindUsedUnitReferences.OnIdentifier Identifier=',GetIdentifier(Identifier),' Found=',CacheEntry<>nil]);
if (CacheEntry=nil)
and (CompareIdentifiers(Identifier,PChar(refs.TargetUnitName))<>0) then
exit;
Sender.MoveCursorToCleanPos(IdentifierCleanPos);
Sender.ReadPriorAtom;
if (Sender.CurPos.Flag=cafPoint) or (Sender.UpAtomIs('inherited')) then exit;
//debugln(['TFindUsedUnitReferences.OnIdentifier Identifier=',GetIdentifier(Identifier),' at begin of term']);
// find declaration
refs.Params.Clear;
refs.Params.Flags:=[fdfSearchInParentNodes,fdfSearchInAncestors,
fdfIgnoreCurContextNode];
refs.Params.ContextNode:=Node;
//debugln(copy(Src,Params.ContextNode.StartPos,200));
refs.Params.SetIdentifier(Self,Identifier,@CheckSrcIdentifier);
if Range=epriInCode then begin
// search identifier in code
Found:=FindDeclarationOfIdentAtParam(refs.Params);
end else begin
// search identifier in comment -> if not found, this is no problem
// => silently ignore
try
Found:=FindDeclarationOfIdentAtParam(refs.Params);
except
on E: ECodeToolError do begin
// continue
end;
on E: Exception do
raise;
end;
end;
//debugln(['TFindUsedUnitReferences.OnIdentifier Identifier=',GetIdentifier(Identifier),' found=',Found]);
if not Found then exit;
if CleanPosToCaret(IdentifierCleanPos,ReferencePos) then
AddCodePosition(refs.ListOfPCodeXYPosition,ReferencePos);
end;
function TFindDeclarationTool.FindNthParameterNode(Node: TCodeTreeNode;
ParameterIndex: integer): TCodeTreeNode;
var
ProcNode, FunctionNode: TCodeTreeNode;
ProcHeadNode: TCodeTreeNode;
ParameterNode: TCodeTreeNode;
i: Integer;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(Node);{$ENDIF}
Result:=nil;
if Node=nil then exit;
if Node.Desc=ctnReferenceTo then begin
Node:=Node.FirstChild;
if Node=nil then exit;
end;
if Node.Desc in [ctnProcedure,ctnProcedureType] then begin
ProcNode:=Node;
//DebugLn(' FindNthParameterNode ProcNode="',copy(Params.NewCodeTool.Src,ProcNode.StartPos,ProcNode.EndPos-ProcNode.StartPos),'"');
FunctionNode:=nil;
BuildSubTreeForProcHead(ProcNode,FunctionNode);
// find procedure head
ProcHeadNode:=ProcNode.FirstChild;
if (ProcHeadNode=nil) or (ProcHeadNode.Desc<>ctnProcedureHead) then begin
DebugLn(' FindNthParameterNode Procedure has no parameter list');
exit;
end;
// find parameter list
ParameterNode:=ProcHeadNode.FirstChild;
if (ParameterNode=nil) or (ParameterNode.Desc<>ctnParameterList)
then begin
DebugLn(' FindNthParameterNode Procedure has no parameter list');
exit;
end;
// find parameter
ParameterNode:=ParameterNode.FirstChild;
i:=0;
while (i<ParameterIndex) and (ParameterNode<>nil) do begin
//DebugLn(' FindNthParameterNode ',ParameterNode.DescAsString);
ParameterNode:=ParameterNode.NextBrother;
inc(i);
end;
Result:=ParameterNode;
end;
end;
constructor TFindDeclarationTool.Create;
begin
inherited Create;
FSourcesChangeStep:=CTInvalidChangeStamp64;
FFilesChangeStep:=CTInvalidChangeStamp64;
FInitValuesChangeStep:=CTInvalidChangeStamp;
end;
procedure TFindDeclarationTool.DoDeleteNodes(StartNode: TCodeTreeNode);
var
HelperKind: TFDHelpersListKind;
begin
ClearNodeCaches;
if FInterfaceIdentifierCache<>nil then begin
FInterfaceIdentifierCache.Clear;
FInterfaceIdentifierCache.Complete:=false;
end;
for HelperKind in TFDHelpersListKind do
if FInterfaceHelperCache[HelperKind]<>nil then
FInterfaceHelperCache[HelperKind].Clear;
inherited DoDeleteNodes(StartNode);
end;
function TFindDeclarationTool.CheckDependsOnNodeCaches(
CheckedTools: TAVLTree = nil): boolean;
var
ANode: TAVLTreeNode;
ATool: TFindDeclarationTool;
FreeCheckedTools: Boolean;
SourcesChangeStep, FilesChangeStep: int64;
InitValuesChangeStep: integer;
begin
Result:=false;
//debugln(['TFindDeclarationTool.CheckDependsOnNodeCaches ',MainFilename,' FDependsOnCodeTools=',FDependsOnCodeTools]);
if (FDependsOnCodeTools=nil) or FCheckingNodeCacheDependencies then exit;
if Scanner=nil then exit;
if Assigned(Scanner.OnGetGlobalChangeSteps) then begin
// check if any sources or values have changed
Scanner.OnGetGlobalChangeSteps(SourcesChangeStep,FilesChangeStep,
InitValuesChangeStep);
if (SourcesChangeStep=FSourcesChangeStep)
and (FilesChangeStep=FFilesChangeStep)
and (InitValuesChangeStep=FInitValuesChangeStep) then
// all sources and values are the same
exit;
FSourcesChangeStep:=SourcesChangeStep;
FFilesChangeStep:=FilesChangeStep;
FInitValuesChangeStep:=InitValuesChangeStep;
end;
if (CheckedTools<>nil) and (CheckedTools.Find(Self)<>nil) then exit;
{$IFDEF ShowCacheDependencies}
DebugLn(['[TFindDeclarationTool.CheckDependsOnNodeCaches] START DependsOn=',FDependsOnCodeTools.Count,' ',MainFilename]);
{$ENDIF}
FCheckingNodeCacheDependencies:=true;
FreeCheckedTools:=false;
if CheckedTools=nil then begin
FreeCheckedTools:=true;
CheckedTools:=TAVLTree.Create;
end;
try
CheckedTools.Add(Self);
ANode:=FDependsOnCodeTools.FindLowest;
while ANode<>nil do begin
ATool:=TFindDeclarationTool(ANode.Data);
Result:=ATool.UpdateNeeded(lsrImplementationStart)
or ATool.CheckDependsOnNodeCaches(CheckedTools);
if Result then exit;
ANode:=FDependsOnCodeTools.FindSuccessor(ANode);
end;
Result:=false;
finally
{$IFDEF ShowCacheDependencies}
DebugLn('[TFindDeclarationTool.CheckDependsOnNodeCaches] Result=',DbgS(Result),' ',MainFilename);
{$ENDIF}
FCheckingNodeCacheDependencies:=false;
if FreeCheckedTools then FreeAndNil(CheckedTools);
if Result then ClearNodeCaches;
end;
end;
destructor TFindDeclarationTool.Destroy;
var
HelperKind: TFDHelpersListKind;
begin
FreeAndNil(FInterfaceIdentifierCache);
for HelperKind in TFDHelpersListKind do
FreeAndNil(FInterfaceHelperCache[HelperKind]);
FreeAndNil(FDependsOnCodeTools);
FreeAndNil(FDependentCodeTools);
if FDirectoryCache<>nil then begin
FDirectoryCache.Release;
FDirectoryCache:=nil;
end;
FFindMissingFPCUnits.Free;
inherited Destroy;
end;
procedure TFindDeclarationTool.ClearNodeCaches;
var
NodeCache: TCodeTreeNodeCache;
BaseTypeCache: TBaseTypeCache;
begin
// check if there is something in cache to delete
if (FFirstNodeCache=nil) and (FFirstBaseTypeCache=nil)
and (FRootNodeCache=nil)
and ((FDependentCodeTools=nil) or (FDependentCodeTools.Count=0))
and ((FDependsOnCodeTools=nil) or (FDependsOnCodeTools.Count=0)) then
exit;
{$IFDEF ShowCacheDependencies}
DebugLn('[TFindDeclarationTool.ClearNodeCaches] Force=',
DbgS(Force),' ',MainFilename);
{$ENDIF}
// clear node caches
while FFirstNodeCache<>nil do begin
NodeCache:=FFirstNodeCache;
FFirstNodeCache:=NodeCache.Next;
NodeCacheMemManager.DisposeNodeCache(NodeCache);
end;
while FFirstBaseTypeCache<>nil do begin
BaseTypeCache:=FFirstBaseTypeCache;
FFirstBaseTypeCache:=BaseTypeCache.NextCache;
BaseTypeCacheMemManager.DisposeBaseTypeCache(BaseTypeCache);
end;
if FRootNodeCache<>nil then begin
NodeCacheMemManager.DisposeNodeCache(FRootNodeCache);
FRootNodeCache:=nil;
end;
// clear dependent codetools
ClearDependentNodeCaches;
ClearDependsOnToolRelationships;
end;
procedure TFindDeclarationTool.ClearDependentNodeCaches;
var
ANode: TAVLTreeNode;
DependentTool: TFindDeclarationTool;
begin
if (FDependentCodeTools=nil) or (FDependentCodeTools.Count=0)
or FClearingDependentNodeCaches then exit;
FClearingDependentNodeCaches:=true;
{$IFDEF ShowCacheDependencies}
DebugLn('[TFindDeclarationTool.ClearDependentNodeCaches] ',MainFilename);
{$ENDIF}
try
ANode:=FDependentCodeTools.FindLowest;
while ANode<>nil do begin
DependentTool:=TFindDeclarationTool(ANode.Data);
DependentTool.ClearNodeCaches;
ANode:=FDependentCodeTools.FindSuccessor(ANode);
end;
FDependentCodeTools.Clear;
finally
FClearingDependentNodeCaches:=false;
end;
end;
procedure TFindDeclarationTool.ClearDependsOnToolRelationships;
var
ANode: TAVLTreeNode;
DependOnTool: TFindDeclarationTool;
begin
if (FDependsOnCodeTools=nil) or (FDependsOnCodeTools.Count=0) then exit;
{$IFDEF ShowCacheDependencies}
DebugLn('[TFindDeclarationTool.ClearDependsOnToolRelationships] ',MainFilename);
{$ENDIF}
ANode:=FDependsOnCodeTools.FindLowest;
while ANode<>nil do begin
DependOnTool:=TFindDeclarationTool(ANode.Data);
if not DependOnTool.FClearingDependentNodeCaches then
DependOnTool.FDependentCodeTools.Remove(Self);
ANode:=FDependsOnCodeTools.FindSuccessor(ANode);
end;
FDependsOnCodeTools.Clear;
end;
procedure TFindDeclarationTool.AddToolDependency(
DependOnTool: TFindDeclarationTool);
// build a relationship: this tool depends on DependOnTool
{$IFDEF DebugAddToolDependency}
var
AVLNode: TAVLTreeNode;
Tool: TFindDeclarationTool;
{$ENDIF}
begin
{$IFDEF ShowCacheDependencies}
DebugLn('[TFindDeclarationTool.AddToolDependency] "',MainFilename,'" depends on "',DependOnTool.MainFilename,'"');
{$ENDIF}
if DependOnTool.FDependentCodeTools=nil then
DependOnTool.FDependentCodeTools:=TAVLTree.Create;
if DependOnTool.FDependentCodeTools.Find(Self)=nil then
DependOnTool.FDependentCodeTools.Add(Self);
if FDependsOnCodeTools=nil then
FDependsOnCodeTools:=TAVLTree.Create;
if FDependsOnCodeTools.Find(DependOnTool)=nil then begin
{$IFDEF DebugAddToolDependency}
AVLNode:=FDependsOnCodeTools.FindLowest;
while AVLNode<>nil do begin
Tool:=TFindDeclarationTool(AVLNode.Data);
if CompareFilenames(ExtractFilename(Tool.MainFilename),ExtractFilename(DependOnTool.MainFilename))=0 then begin
DebugLn(['TFindDeclarationTool.AddToolDependency inconsistency: ',Tool.MainFilename,' ',DependOnTool.MainFilename]);
end;
AVLNode:=FDependsOnCodeTools.FindSuccessor(AVLNode);
end;
{$ENDIF}
FDependsOnCodeTools.Add(DependOnTool);
end;
end;
procedure TFindDeclarationTool.ConsistencyCheck;
var ANodeCache: TCodeTreeNodeCache;
begin
inherited ConsistencyCheck;
if FInterfaceIdentifierCache<>nil then
FInterfaceIdentifierCache.ConsistencyCheck;
ANodeCache:=FFirstNodeCache;
while ANodeCache<>nil do begin
ANodeCache.ConsistencyCheck;
ANodeCache:=ANodeCache.Next;
end;
if FDependentCodeTools<>nil then
FDependentCodeTools.ConsistencyCheck;
if FDependsOnCodeTools<>nil then
FDependsOnCodeTools.ConsistencyCheck;
end;
procedure TFindDeclarationTool.CalcMemSize(Stats: TCTMemStats);
var
NodeCache: TCodeTreeNodeCache;
TypeCache: TBaseTypeCache;
m: PtrUInt;
HelperKind: TFDHelpersListKind;
begin
inherited CalcMemSize(Stats);
if FInterfaceIdentifierCache<>nil then
Stats.Add('TFindDeclarationTool.FInterfaceIdentifierCache',
FInterfaceIdentifierCache.CalcMemSize);
for HelperKind in TFDHelpersListKind do
if FInterfaceHelperCache[HelperKind]<>nil then
Stats.Add('TFindDeclarationTool.FInterfaceHelperCache[]',
FInterfaceHelperCache[HelperKind].CalcMemSize);
if FFirstNodeCache<>nil then begin
m:=0;
NodeCache:=FFirstNodeCache;
while NodeCache<>nil do begin
inc(m,NodeCache.CalcMemSize);
NodeCache:=NodeCache.Next;
end;
Stats.Add('TFindDeclarationTool.NodeCache',m);
end;
if FFirstBaseTypeCache<>nil then begin
m:=0;
TypeCache:=FFirstBaseTypeCache;
while TypeCache<>nil do begin
inc(m,TypeCache.CalcMemSize);
TypeCache:=TypeCache.NextCache;
end;
Stats.Add('TFindDeclarationTool.TypeCache',m);
end;
if FDependentCodeTools<>nil then
Stats.Add('TFindDeclarationTool.FDependentCodeTools',
FDependentCodeTools.Count*SizeOf(TAVLTreeNode));
if FDependsOnCodeTools<>nil then
Stats.Add('TFindDeclarationTool.FDependsOnCodeTools',
FDependsOnCodeTools.Count*SizeOf(TAVLTreeNode));
end;
procedure TFindDeclarationTool.ValidateToolDependencies;
begin
//debugln(['TFindDeclarationTool.ValidateToolDependencies ',MainFilename]);
inherited ValidateToolDependencies;
CheckDependsOnNodeCaches;
end;
function TFindDeclarationTool.GetNodeCache(Node: TCodeTreeNode;
CreateIfNotExists: boolean): TCodeTreeNodeCache;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(Node);{$ENDIF}
while (Node<>nil) and (not (Node.Desc in AllNodeCacheDescs)) do
Node:=Node.Parent;
if Node<>nil then begin
if (Node.Cache=nil) and CreateIfNotExists then
CreateNewNodeCache(Node);
if (Node.Cache is TCodeTreeNodeCache) then
Result:=TCodeTreeNodeCache(Node.Cache)
else
Result:=nil;
end else begin
if (FRootNodeCache=nil) and CreateIfNotExists then
FRootNodeCache:=CreateNewNodeCache(nil);
Result:=FRootNodeCache;
end;
end;
procedure TFindDeclarationTool.AddResultToNodeCaches(
StartNode, EndNode: TCodeTreeNode; SearchedForward: boolean;
Params: TFindDeclarationParams; SearchRangeFlags: TNodeCacheEntryFlags);
var Node: TCodeTreeNode;
CurNodeCache, LastNodeCache: TCodeTreeNodeCache;
CleanStartPos, CleanEndPos: integer;
NewNode: TCodeTreeNode;
NewTool: TPascalParserTool;
NewCleanPos: integer;
{$IFDEF ShowNodeCache}
BeVerbose: boolean;
NodeOwner: TObject;
function WriteSrcPos(t: TPascalParserTool; p: integer): string;
begin
Result:=StringToPascalConst(copy(t.Src,p-10,10)+'|'+copy(t.Src,p,15)+'"');
end;
function NodeOwnerAsString(ANodeOwner: TObject): string;
begin
if ANodeOwner=nil then
Result:='nil'
else if ANodeOwner is TPascalParserTool then
Result:=ExtractFileName(TPascalParserTool(ANodeOwner).MainFilename)
else
Result:='?'+ANodeOwner.ClassName+'?';
end;
{$ENDIF}
begin
{$IFDEF CheckNodeTool}CheckNodeTool(StartNode);{$ENDIF}
if StartNode=nil then exit;
if EndNode=nil then EndNode:=StartNode;
if Params.NewNode<>nil then begin
// identifier found
NewNode:=Params.NewNode;
NewTool:=Params.NewCodeTool;
NewCleanPos:=Params.NewCleanPos;
end else begin
// identifier not found
NewNode:=nil;
NewTool:=nil;
NewCleanPos:=-1;
end;
// calculate search range
if EndNode<>nil then begin
if SearchedForward then begin
CleanStartPos:=StartNode.StartPos;
CleanEndPos:=EndNode.EndPos;
end else begin
CleanStartPos:=EndNode.StartPos;
CleanEndPos:=StartNode.EndPos;
end;
end else begin
// searched till start or end of source
if not SearchedForward then begin
CleanStartPos:=1;
CleanEndPos:=StartNode.StartPos;
end else begin
CleanStartPos:=StartNode.StartPos;
CleanEndPos:=SrcLen+1;
end;
end;
{$IFDEF ShowNodeCache}
beVerbose:=true; //CompareSrcIdentifiers(Params.Identifier,'InitDecompressor');
if beVerbose then begin
DebugLn('(((((((((((((((((((((((((((==================');
DbgOut('TFindDeclarationTool.AddResultToNodeCaches ',
' Ident=',GetIdentifier(Params.Identifier));
DbgOut(' SearchedForward=',DbgS(SearchedForward));
DbgOut(' Flags=[');
if ncefSearchedInParents in SearchRangeFlags then DbgOut('Parents');
if ncefSearchedInAncestors in SearchRangeFlags then DbgOut(',Ancestors');
DebugLn(']');
DbgOut(' StartNode=',StartNode.DescAsString,
'('+DbgS(StartNode.StartPos),'-',DbgS(StartNode.EndPos)+')=',
WriteSrcPos(Self,StartNode.StartPos));
NodeOwner:=FindOwnerOfCodeTreeNode(StartNode);
if NodeOwner<>Self then DbgOut(' StartNodeOwner=',NodeOwnerAsString(NodeOwner));
DebugLn('');
if EndNode<>nil then
DbgOut(' EndNode=',EndNode.DescAsString,
'('+DbgS(EndNode.StartPos),'-',DbgS(EndNode.EndPos)+')=',
WriteSrcPos(Self,EndNode.StartPos))
else
DbgOut(' EndNode=nil');
NodeOwner:=FindOwnerOfCodeTreeNode(EndNode);
if NodeOwner<>Self then DbgOut(' EndNodeOwner=',NodeOwnerAsString(NodeOwner));
DebugLn('');
DebugLn(' Self=',ExtractFileName(MainFilename));
if NewNode<>nil then begin
DebugLn(' NewNode=',NewNode.DescAsString,
'(',DbgS(NewNode.StartPos),'-',DbgS(NewNode.EndPos),')=',
WriteSrcPos(NewTool,NewNode.StartPos),
' NewTool=',ExtractFileName(NewTool.MainFilename));
end else begin
DebugLn(' NOT FOUND');
//RaiseCatchableException('');
end;
DebugLn(' CleanStartPos=',DbgS(CleanStartPos),' ',WriteSrcPos(Self,CleanStartPos));
DebugLn(' CleanEndPos=',DbgS(CleanEndPos),' ',WriteSrcPos(Self,CleanEndPos));
end;
{$ENDIF}
LastNodeCache:=nil;
// start with parent of deepest node and end parent of highest
Node:=StartNode;
repeat
if (Node.Desc in AllNodeCacheDescs) then begin
if (Node.Cache=nil) then
CreateNewNodeCache(Node);
if (Node.Cache is TCodeTreeNodeCache) then begin
CurNodeCache:=TCodeTreeNodeCache(Node.Cache);
if LastNodeCache<>CurNodeCache then begin
{$IFDEF ShowNodeCache}
if BeVerbose then begin
CurNodeCache.WriteDebugReport(' BEFORE NODECACHE REPORT: ');
end;
{$ENDIF}
CurNodeCache.Add(Params.Identifier,
Self,CleanStartPos,CleanEndPos,
NewNode,NewTool,NewCleanPos,SearchRangeFlags);
{$IFDEF ShowNodeCache}
if BeVerbose then begin
CurNodeCache.WriteDebugReport(' AFTER NODECACHE REPORT: ');
end;
{$ENDIF}
LastNodeCache:=CurNodeCache;
end;
end;
end;
Node:=Node.Parent;
until (Node=nil) or (EndNode=Node) or EndNode.HasAsParent(Node);
{$IFDEF ShowNodeCache}
if BeVerbose then begin
DebugLn('=========================))))))))))))))))))))))))))))))))');
end;
{$ENDIF}
end;
function TFindDeclarationTool.CreateNewNodeCache(
Node: TCodeTreeNode): TCodeTreeNodeCache;
begin
{$IFDEF CheckNodeTool}CheckNodeTool(Node);{$ENDIF}
Result:=NodeCacheMemManager.NewNodeCache(Node);
Result.Next:=FFirstNodeCache;
FFirstNodeCache:=Result;
end;
function TFindDeclarationTool.CreateNewBaseTypeCache(
Tool: TFindDeclarationTool; Node: TCodeTreeNode): TBaseTypeCache;
begin
{$IFDEF CheckNodeTool}Tool.CheckNodeTool(Node);{$ENDIF}
Result:=BaseTypeCacheMemManager.NewBaseTypeCache(Node);
Result.NextCache:=Tool.FFirstBaseTypeCache;
Tool.FFirstBaseTypeCache:=Result;
end;
procedure TFindDeclarationTool.CreateBaseTypeCaches(
NodeStack: PCodeTreeNodeStack; const Result: TFindContext);
var i: integer;
Entry: PCodeTreeNodeStackEntry;
BaseTypeCache: TBaseTypeCache;
NextEntry: PCodeTreeNodeStackEntry;
begin
{$IFDEF ShowBaseTypeCache}
DbgOut('[TFindDeclarationTool.CreateBaseTypeCaches] ',
' StackPtr=',DbgS(NodeStack^.StackPtr));
DebugLn(' Self=',MainFilename);
if Result.Node<>nil then
DbgOut(' Result='+Result.Node.DescAsString,
' Start='+DbgS(Result.Node.StartPos),
' End='+DbgS(Result.Node.EndPos),
' "'+copy(Result.Tool.Src,Result.Node.StartPos,15)+'" ',Result.Tool.MainFilename)
else
DbgOut(' Result=nil');
DebugLn('');
{$ENDIF}
for i:=0 to NodeStack^.StackPtr do begin
Entry:=GetNodeStackEntry(NodeStack,i);
if Entry^.Node.Cache=nil then begin
{$IFDEF ShowBaseTypeCache}
DebugLn(' i=',DbgS(i),' Node=',Entry^.Node.DescAsString,' "',copy(Entry^.Tool.Src,Entry^.Node.StartPos,15),'"');
{$ENDIF}
BaseTypeCache:=
CreateNewBaseTypeCache(TFindDeclarationTool(Entry^.Tool),Entry^.Node);
if BaseTypeCache<>nil then begin
BaseTypeCache.BaseNode:=Result.Node;
BaseTypeCache.BaseTool:=Result.Tool;
if i<NodeStack^.StackPtr then begin
NextEntry:=GetNodeStackEntry(NodeStack,i+1);
BaseTypeCache.NextNode:=NextEntry^.Node;
BaseTypeCache.NextTool:=NextEntry^.Tool;
end else begin
BaseTypeCache.NextNode:=Result.Node;
BaseTypeCache.NextTool:=Result.Tool;
end;
end;
end;
end;
end;
function TFindDeclarationTool.GetExpressionTypeOfTypeIdentifier(
Params: TFindDeclarationParams): TExpressionType;
var
OldFlags: TFindDeclarationFlags;
begin
OldFlags:=Params.Flags;
if FindIdentifierInContext(Params) then begin
Params.Flags:=OldFlags;
Result:=Params.NewCodeTool.ConvertNodeToExpressionType(Params.NewNode,Params);
end else begin
// predefined identifier
Params.Flags:=OldFlags;
Result:=CleanExpressionType;
Result.Desc:=PredefinedIdentToExprTypeDesc(Params.Identifier,Scanner.PascalCompiler);
end;
end;
function TFindDeclarationTool.FindTermTypeAsString(TermPos: TAtomPosition;
Params: TFindDeclarationParams;
out ExprType: TExpressionType): string;
var
EdgedBracketsStartPos: integer;
SetNode: TCodeTreeNode;
SetTool: TFindDeclarationTool;
AliasType: TFindContext;
begin
//debugln(['TFindDeclarationTool.FindTermTypeAsString START']);
{$IFDEF CheckNodeTool}CheckNodeTool(Params.ContextNode);{$ENDIF}
Result:='';
AliasType:=CleanFindContext;
if IsTermEdgedBracket(TermPos,EdgedBracketsStartPos) then begin
// check for constant sets: [enum]
MoveCursorToCleanPos(EdgedBracketsStartPos);
ReadNextAtom;
ReadNextAtom;
if CurPos.Flag=cafWord then begin
{$IFDEF ShowExprEval}
debugln(['TFindDeclarationTool.FindTermTypeAsString "[name" : check for enumeration type ...']);
debugln(['TFindDeclarationTool.FindTermTypeAsString StartContext=',Params.ContextNode.DescAsString,'=',dbgstr(Src,Params.ContextNode.StartPos,15),'"']);
{$ENDIF}
ExprType:=FindExpressionResultType(Params,EdgedBracketsStartPos+1,-1);
{$IFDEF ShowExprEval}
debugln(['TFindDeclarationTool.FindTermTypeAsString "[name" : ',ExprTypeToString(ExprType)]);
{$ENDIF}
if (ExprType.Desc=xtContext)
and (ExprType.Context.Node.Desc in [ctnEnumerationType,ctnEnumIdentifier])
then begin
SetTool:=ExprType.Context.Tool;
SetNode:=SetTool.FindSetOfEnumerationType(ExprType.Context.Node);
if SetNode<>nil then begin
ExprType:=CleanExpressionType;
ExprType.Desc:=xtContext;
ExprType.SubDesc:=xtNone;
ExprType.Context.Tool:=SetTool;
ExprType.Context.Node:=SetNode;
Result:=SetTool.ExtractDefinitionName(SetNode);
exit;
end;
end;
end;
end;
// check if TermPos is @Name and a pointer (= ^Name) can be found
if IsTermNamedPointer(TermPos,ExprType) then begin
// pointer type
end else begin
ExprType:=CleanExpressionType;
Params.Flags:=[fdfSearchInParentNodes,fdfSearchInAncestors,fdfSearchInHelpers,
fdfTopLvlResolving,fdfFunctionResult,fdfIgnoreOperatorError]
+Params.Flags*[fdfOverrideStringTypesWithFirstParamType];
ExprType:=FindExpressionResultType(Params,TermPos.StartPos,TermPos.EndPos,
@AliasType);
end;
if AliasType.Node<>nil then begin
ExprType:=CleanExpressionType;
ExprType.Desc:=xtContext;
ExprType.Context:=AliasType;
end;
Result:=FindExprTypeAsString(ExprType,TermPos.StartPos);
end;
function TFindDeclarationTool.FindForInTypeAsString(TermPos: TAtomPosition;
CursorNode: TCodeTreeNode; Params: TFindDeclarationParams; out
ExprType: TExpressionType): string;
procedure RaiseTermHasNoIterator(id: int64; TermExprType: TExpressionType);
begin
if TermPos.StartPos<1 then
TermPos.StartPos:=1;
MoveCursorToCleanPos(TermPos.StartPos);
debugln(['TFindDeclarationTool.FindForInTypeAsString TermExprType=',ExprTypeToString(TermExprType)]);
RaiseException(id,'Can not find an enumerator for '''+TrimCodeSpace(GetAtom(TermPos))+'''');
end;
procedure ResolveExpr(SubExprType: TExpressionType);
var
AliasType: TFindContext;
Node: TCodeTreeNode;
begin
{$IFDEF ShowForInEval}
debugln([' ResolveExpr ',ExprTypeToString(SubExprType)]);
{$ENDIF}
// use default enumerators
case SubExprType.Desc of
xtContext:
begin
case SubExprType.Context.Node.Desc of
ctnClass, ctnRecordType, ctnClassHelper, ctnRecordHelper, ctnTypeHelper:
begin
AliasType:=CleanFindContext;
if not SubExprType.Context.Tool.FindEnumeratorOfClass(
SubExprType.Context.Node,true,ExprType,@AliasType, Params)
then
RaiseTermHasNoIterator(20170421211210,SubExprType);
Result:=FindExprTypeAsString(ExprType,TermPos.StartPos,@AliasType);
end;
ctnEnumerationType:
begin
Node:=SubExprType.Context.Node.Parent;
if Node.Desc=ctnTypeDefinition then
Result:=SubExprType.Context.Tool.ExtractIdentifier(Node.StartPos);
end;
ctnSetType:
if SubExprType.Context.Tool.FindEnumerationTypeOfSetType(
SubExprType.Context.Node,ExprType.Context)
then begin
ExprType.Desc:=xtContext;
Result:=FindExprTypeAsString(ExprType,TermPos.StartPos);
end;
ctnRangedArrayType,ctnOpenArrayType:
begin
AliasType:=CleanFindContext;
if SubExprType.Context.Tool.FindElementTypeOfArrayType(
SubExprType.Context.Node,ExprType,@AliasType)
then begin
Result:=FindExprTypeAsString(ExprType,TermPos.StartPos,@AliasType);
end;
end;
else
RaiseTermHasNoIterator(20170421211213,SubExprType);
end;
end;
xtChar,
xtSmallInt,
xtShortInt,
xtByte,
xtWord,
xtBoolean,
xtByteBool,
xtWordBool,
xtLongBool,
xtQWordBool,
xtNativeInt,
xtNativeUInt:
Result:=ExpressionTypeDescNames[SubExprType.Desc];
xtNone,
xtWideChar,
xtReal,
xtSingle,
xtDouble,
xtExtended,
xtCExtended,
xtCurrency,
xtComp,
xtInt64,
xtCardinal,
xtQWord,
xtPointer,
xtFile,
xtText,
xtConstOrdInteger,
xtConstReal,
xtConstBoolean,
xtLongint,
xtLongWord,
xtCompilerFunc,
xtVariant,
xtJSValue,
xtNil:
RaiseTermHasNoIterator(20170421211217,SubExprType);
xtString,
xtAnsiString,
xtShortString,
xtPChar,
xtConstString:
begin
ExprType.Desc:=xtChar;
Result:=ExpressionTypeDescNames[ExprType.Desc];
end;
xtWideString,
xtUnicodeString:
begin
ExprType.Desc:=xtWideChar;
Result:=ExpressionTypeDescNames[ExprType.Desc];
end;
xtConstSet:
begin
if SubExprType.Context.Node=nil then
RaiseTermHasNoIterator(20170421211222,SubExprType);
SubExprType:=SubExprType.Context.Tool.FindExpressionTypeOfConstSet(SubExprType.Context.Node);
{$IFDEF ShowForInEval}
debugln([' ResolveExpr ConstSet Element: ',ExprTypeToString(SubExprType)]);
{$ENDIF}
if SubExprType.Desc=xtConstSet then
RaiseTermHasNoIterator(20170421211222,SubExprType);
ResolveExpr(SubExprType);
end;
else
DebugLn('TFindDeclarationTool.FindForInTypeAsString.ResolveExpr TermExprType=',
ExprTypeToString(SubExprType));
RaiseTermHasNoIterator(20170421211225,SubExprType);
end;
end;
var
TermExprType: TExpressionType;
OperatorExprType: TExpressionType;
begin
Result:='';
ExprType:=CleanExpressionType;
TermExprType:=CleanExpressionType;
Params.ContextNode:=CursorNode;
Params.Flags:=[fdfSearchInParentNodes,fdfSearchInAncestors,fdfSearchInHelpers,
fdfTopLvlResolving,fdfFunctionResult];
TermExprType:=FindExpressionResultType(Params,TermPos.StartPos,TermPos.EndPos);
{$IFDEF ShowForInEval}
DebugLn('TFindDeclarationTool.FindForInTypeAsString TermExprType=',
ExprTypeToString(TermExprType));
{$ENDIF}
// search operator enumerator
if FindOperatorEnumerator(CursorNode,TermExprType,foeEnumeratorCurrentExprType,
OperatorExprType)
then begin
{$IFDEF ShowForInEval}
DebugLn(['TFindDeclarationTool.FindForInTypeAsString Operator=',ExprTypeToString(OperatorExprType)]);
{$ENDIF}
ExprType:=OperatorExprType;
Result:=FindExprTypeAsString(ExprType,TermPos.StartPos);
exit;
end;
// convert to string
ResolveExpr(TermExprType);
{$IFDEF ShowExprEval}
DebugLn('TFindDeclarationTool.FindForInTypeAsString Result=',Result);
{$ENDIF}
end;
function TFindDeclarationTool.FindEnumeratorOfClass(ClassNode: TCodeTreeNode;
ExceptionOnNotFound: boolean; out ExprType: TExpressionType;
AliasType: PFindContext; ParentParams: TFindDeclarationParams): boolean;
var
Params: TFindDeclarationParams;
ProcTool: TFindDeclarationTool;
ProcNode: TCodeTreeNode;
EnumeratorContext: TFindContext;
PropTool: TFindDeclarationTool;
PropNode: TCodeTreeNode;
CurrentContext: TFindContext;
begin
Result:=false;
if AliasType<>nil then
AliasType^:=CleanFindContext;
ExprType:=CleanExpressionType;
Params:=TFindDeclarationParams.Create(ParentParams);
try
// search function 'GetEnumerator'
Params.ContextNode:=ClassNode;
Params.Flags:=[fdfSearchInAncestors,fdfSearchInHelpers];
Params.SetIdentifier(Self,'GetEnumerator',nil);
{$IFDEF ShowForInEval}
DebugLn(['TFindDeclarationTool.FindEnumeratorOfClass searching GetEnumerator for ',ExtractClassName(ClassNode,false),' ...']);
{$ENDIF}
if not FindIdentifierInContext(Params) then begin
if ExceptionOnNotFound then begin
MoveCursorToCleanPos(ClassNode.StartPos);
RaiseException(20170421200638,ctsFunctionGetEnumeratorNotFoundInThisClass);
end else begin
{$IFDEF ShowForInEval}
debugln(['TFindDeclarationTool.FindEnumeratorOfClass GetEnumerator not found for ',ExtractClassName(ClassNode,false)]);
{$ENDIF}
exit;
end;
end;
ProcTool:=Params.NewCodeTool;
ProcNode:=Params.NewNode;
//DebugLn(['TFindDeclarationTool.FindEnumeratorOfClass Proc']);
if (ProcNode=nil) or (ProcNode.Desc<>ctnProcedure) then begin
if ExceptionOnNotFound then begin
MoveCursorToCleanPos(ClassNode.StartPos);
RaiseException(20170421200640,ctsFunctionGetEnumeratorNotFoundInThisClass2);
end else begin
{$IFDEF ShowForInEval}
debugln(['TFindDeclarationTool.FindEnumeratorOfClass GetEnumerator is not a proc, class=',ExtractClassName(ClassNode,false)]);
{$ENDIF}
exit;
end;
end;
// search function type
Params.Clear;
Include(Params.Flags,fdfFunctionResult);
EnumeratorContext:=ProcTool.FindBaseTypeOfNode(Params,ProcNode);
{$IFDEF ShowForInEval}
DebugLn(['TFindDeclarationTool.FindEnumeratorOfClass EnumeratorContext=',FindContextToString(EnumeratorContext)]);
{$ENDIF}
if (EnumeratorContext.Node=nil)
or not (EnumeratorContext.Node.Desc in [ctnClass,ctnClassInterface,ctnRecordType])
then begin
if ExceptionOnNotFound then begin
ProcTool.MoveCursorToCleanPos(ProcNode.StartPos);
ProcTool.RaiseException(20170421200642,ctsResultTypeOfFunctionGetEnumeratorNotFound);
end else
exit;
end;
// search 'Current' in enumerator class
Params.Clear;
Params.ContextNode:=EnumeratorContext.Node;
Params.Flags:=[fdfSearchInAncestors];
if ExceptionOnNotFound then
Include(Params.Flags,fdfExceptionOnNotFound);
Params.SetIdentifier(EnumeratorContext.Tool,'Current',nil);
//DebugLn(['TFindDeclarationTool.FindEnumeratorOfClass search current ...']);
if not EnumeratorContext.Tool.FindIdentifierInContext(Params) then begin
{$IFDEF ShowForInEval}
DebugLn(['TFindDeclarationTool.FindEnumeratorOfClass missing "current" in ',EnumeratorContext.Tool.ExtractClassName(EnumeratorContext.Node,false)]);
{$ENDIF}
exit;
end;
// check if "current" is a property
PropTool:=Params.NewCodeTool;
PropNode:=Params.NewNode;
//DebugLn(['TFindDeclarationTool.FindEnumeratorOfClass PropNode=',PropNode.DescAsString]);
if (PropNode=nil) or (PropNode.Desc<>ctnProperty) then begin
if ExceptionOnNotFound then begin
EnumeratorContext.Tool.MoveCursorToCleanPos(EnumeratorContext.Node.StartPos);
RaiseException(20170421200644,ctsPropertyCurrentNotFound);
end else begin
{$IFDEF ShowForInEval}
DebugLn(['TFindDeclarationTool.FindEnumeratorOfClass "current" is not a property']);
{$ENDIF}
exit;
end;
end;
// search type of Current
Params.Clear;
if ExceptionOnNotFound then
Include(Params.Flags,fdfExceptionOnNotFound);
//DebugLn(['TFindDeclarationTool.FindEnumeratorOfClass searching property type ...']);
CurrentContext:=PropTool.FindBaseTypeOfNode(Params,PropNode,AliasType);
ExprType:=CurrentContext.Tool.ConvertNodeToExpressionType(
CurrentContext.Node,Params,AliasType);
{$IFDEF ShowForInEval}
DebugLn(['TFindDeclarationTool.FindEnumeratorOfClass exprtype of CURRENT: ExprType=',ExprTypeToString(ExprType),' Alias=',FindContextToString(AliasType)]);
{$ENDIF}
Result:=ExprType.Desc<>xtNone;
finally
Params.Free;
end;
end;
function TFindDeclarationTool.FindOperatorEnumerator(Node: TCodeTreeNode;
ExprType: TExpressionType; Need: TFindOperatorEnumerator; out
ResultExprType: TExpressionType): boolean;
// find a compatible operator overload for 'enumerator' with a parameter
// compatible to ExprType
// for example:
// operator enumerator (AList: TMyList): TMyListEnumerator;
var
Params: TFindDeclarationParams;
OperatorTool: TFindDeclarationTool;
OperatorNode: TCodeTreeNode;
ClassContext: TFindContext;
EnumeratorCurrentTool: TFindDeclarationTool;
EnumeratorCurrentNode: TCodeTreeNode;
begin
Result:=false;
ResultExprType:=CleanExpressionType;
Params:=TFindDeclarationParams.Create;
try
// search compatible operator enumerator
Params.ContextNode:=Node;
Params.Flags:=[fdfSearchInParentNodes];
Params.Data:=@ExprType;
Params.SetIdentifier(Self,'Enumerator',@CheckOperatorEnumerator);
{$IFDEF ShowForInEval}
DebugLn(['TFindDeclarationTool.FindOperatorEnumerator searching operator enumerator ...']);
{$ENDIF}
if not FindIdentifierInContext(Params) then begin
{$IFDEF ShowForInEval}
DebugLn(['TFindDeclarationTool.FindOperatorEnumerator operator enumerator not found']);
{$ENDIF}
exit;
end;
// operator found
// now check if it is valid
OperatorTool:=Params.NewCodeTool;
OperatorNode:=Params.NewNode;
{$IFDEF ShowForInEval}
DebugLn(['TFindDeclarationTool.FindOperatorEnumerator Operator="',OperatorTool.ExtractNode(OperatorNode,[]),'"']);
{$ENDIF}
if Need=foeProcNode then begin
ResultExprType.Desc:=xtContext;
ResultExprType.Context.Tool:=OperatorTool;
ResultExprType.Context.Node:=OperatorNode;
exit(true);
end;
// search class node
Params.Clear;
Params.Flags:=[fdfFunctionResult];
{$IFDEF ShowForInEval}
DebugLn(['TFindDeclarationTool.FindOperatorEnumerator searching operator result object ...']);
{$ENDIF}
ClassContext:=OperatorTool.FindBaseTypeOfNode(Params,OperatorNode);
{$IFDEF ShowForInEval}
DebugLn(['TFindDeclarationTool.FindOperatorEnumerator ClassContext=',FindContextToString(ClassContext)]);
{$ENDIF}
case ClassContext.Node.Desc of
ctnClass,ctnObject,ctnRecordType,ctnClassInterface,ctnDispinterface: ;
else
OperatorTool.MoveCursorToNodeStart(OperatorNode);
OperatorTool.RaiseException(20170421200650,'operator enumerator result type is not object');
end;
if Need=foeResultClassNode then begin
ResultExprType.Desc:=xtContext;
ResultExprType.Context:=ClassContext;
exit(true);
end;
// search property with modifier enumerator Current
Params.Clear;
Params.ContextNode:=ClassContext.Node;
Params.Flags:=[fdfSearchInAncestors,fdfCollect];
Params.SetIdentifier(Self,'',@CheckModifierEnumeratorCurrent);
{$IFDEF ShowForInEval}
DebugLn(['TFindDeclarationTool.FindOperatorEnumerator searching enumerator current ...']);
{$ENDIF}
if not ClassContext.Tool.FindIdentifierInContext(Params) then begin
ClassContext.Tool.MoveCursorToNodeStart(ClassContext.Node);
ClassContext.Tool.RaiseException(20170421200654,'enumerator ''current'' not found');
end;
EnumeratorCurrentTool:=Params.NewCodeTool;
EnumeratorCurrentNode:=Params.NewNode;
if Need=foeEnumeratorCurrentNode then begin
ResultExprType.Desc:=xtContext;
ResultExprType.Context.Tool:=EnumeratorCurrentTool;
ResultExprType.Context.Node:=EnumeratorCurrentNode;
exit(true);
end;
// search expression type of 'enumerator current'
Params.Clear;
Params.Flags:=[fdfFunctionResult];
{$IFDEF ShowForInEval}
DebugLn(['TFindDeclarationTool.FindOperatorEnumerator searching enumerator current result ...']);
{$ENDIF}
ResultExprType:=EnumeratorCurrentTool.ConvertNodeToExpressionType(
EnumeratorCurrentNode,Params);
{$IFDEF ShowForInEval}
DebugLn(['TFindDeclarationTool.FindOperatorEnumerator enumerator current result=',ExprTypeToString(ResultExprType)]);
{$ENDIF}
Result:=true;
finally
Params.Free;
end;
end;
function TFindDeclarationTool.FindEnumerationTypeOfSetType(
SetTypeNode: TCodeTreeNode; out Context: TFindContext): boolean;
var
Params: TFindDeclarationParams;
p: LongInt;
begin
Result:=false;
if (SetTypeNode=nil) or (SetTypeNode.Desc<>ctnSetType) then exit;
MoveCursorToNodeStart(SetTypeNode);
ReadNextAtom; // set
if not UpAtomIs('SET') then exit;
ReadNextAtom; // of
if not UpAtomIs('OF') then exit;
ReadNextAtom;
if not IsIdentStartChar[Src[CurPos.StartPos]] then
// set of ()
exit;
Params:=TFindDeclarationParams.Create;
try
Params.Flags:=fdfDefaultForExpressions;
Params.ContextNode:=SetTypeNode;
p:=CurPos.StartPos;
Params.SetIdentifier(Self,@Src[p],nil);
if not FindIdentifierInContext(Params) then exit;
if (Params.NewNode=nil)
or (Params.NewNode.Desc<>ctnTypeDefinition)
or (Params.NewNode.FirstChild=nil)
or (Params.NewNode.FirstChild.Desc<>ctnEnumerationType) then begin
MoveCursorToCleanPos(p);
ReadNextAtom;
RaiseStringExpectedButAtomFound(20170421200656,ctsEnumerationType);
end;
Context.Tool:=Params.NewCodeTool;
Context.Node:=Params.NewNode;
Result:=true;
finally
Params.Free;
end;
end;
function TFindDeclarationTool.FindElementTypeOfArrayType(
ArrayNode: TCodeTreeNode; out ExprType: TExpressionType;
AliasType: PFindContext): boolean;
var
Params: TFindDeclarationParams;
p: LongInt;
begin
Result:=false;
ExprType:=CleanExpressionType;
AliasType^:=CleanFindContext;
if (ArrayNode=nil) then exit;
if (ArrayNode.Desc<>ctnOpenArrayType) and (ArrayNode.Desc<>ctnRangedArrayType)
then exit;
MoveCursorToNodeStart(ArrayNode);
ReadNextAtom; // array
if not UpAtomIs('ARRAY') then exit;
ReadNextAtom; // of
if CurPos.Flag=cafEdgedBracketOpen then begin
ReadTilBracketClose(true);
ReadNextAtom;
end;
if not UpAtomIs('OF') then exit;
ReadNextAtom;
if not AtomIsIdentifier then exit;
Params:=TFindDeclarationParams.Create;
try
Params.Flags:=fdfDefaultForExpressions;
Params.ContextNode:=ArrayNode;
p:=CurPos.StartPos;
Params.SetIdentifier(Self,@Src[p],nil);
ExprType:=FindExpressionResultType(Params,p,-1,AliasType);
Result:=true;
finally
Params.Free;
end;
end;
function TFindDeclarationTool.CheckOperatorEnumerator(
Params: TFindDeclarationParams; const FoundContext: TFindContext
): TIdentifierFoundResult;
var
Node: TCodeTreeNode;
ExprType: TExpressionType;
Params2: TFindDeclarationParams;
begin
Result:=ifrProceedSearch;
{$IFDEF ShowExprEval}
DebugLn(['TFindDeclarationTool.CheckOperatorEnumerator ',FindContextToString(FoundContext)]);
{$ENDIF}
if not FoundContext.Tool.NodeIsOperator(FoundContext.Node) then exit;
FoundContext.Tool.BuildSubTreeForProcHead(FoundContext.Node);
Node:=FoundContext.Node.FirstChild;
if (Node=nil) or (Node.Desc<>ctnProcedureHead) then exit;
Node:=Node.FirstChild;
if (Node=nil) or (Node.Desc<>ctnParameterList) then exit;
Node:=Node.FirstChild;
if (Node=nil) then exit;
if Node.NextBrother<>nil then exit;
ExprType:=PExpressionType(Params.Data)^;
Params2:=TFindDeclarationParams.Create;
try
if IsCompatible(Node,ExprType,Params2)=tcIncompatible then exit;
finally
Params2.Free;
end;
{$IFDEF ShowExprEval}
DebugLn(['TFindDeclarationTool.CheckOperatorEnumerator FOUND ',FoundContext.Tool.ExtractNode(FoundContext.Node,[])]);
{$ENDIF}
Result:=ifrSuccess;
end;
function TFindDeclarationTool.CheckModifierEnumeratorCurrent(
Params: TFindDeclarationParams; const FoundContext: TFindContext
): TIdentifierFoundResult;
begin
Result:=ifrProceedSearch;
//DebugLn(['TFindDeclarationTool.CheckModifierEnumeratorCurrent ',FindContextToString(FoundContext)]);
case FoundContext.Node.Desc of
ctnProperty:
begin
if FoundContext.Tool.PropertyHasSpecifier(FoundContext.Node,'Enumerator',false)
then begin
FoundContext.Tool.ReadNextAtom;
if FoundContext.Tool.UpAtomIs('CURRENT') then
Result:=ifrSuccess;
end;
end;
end;
end;
function TFindDeclarationTool.IsTermEdgedBracket(TermPos: TAtomPosition; out
EdgedBracketsStartPos: integer): boolean;
{ allowed:
- at least one edged brackets
- identifiers
- functions
- operators: + and -
[a,b]+[c]-D()*inherited E
not allowed:
[]<>[]
}
var
Lvl: Integer;
EndPos: LongInt;
begin
Result:=false;
EdgedBracketsStartPos:=0;
EndPos:=TermPos.EndPos;
if EndPos>SrcLen then
EndPos:=SrcLen;
MoveCursorToCleanPos(TermPos.StartPos);
Lvl:=0;
repeat
ReadNextAtom;
if (CurPos.StartPos>=EndPos) then
break;
case CurPos.Flag of
cafRoundBracketOpen: ReadTilBracketClose(false);
cafEdgedBracketOpen:
begin
inc(Lvl);
if (Lvl=1) and (EdgedBracketsStartPos<1) then begin
if (not LastAtoms.HasPrior)
or LastAtomIs(-1,'+') or LastAtomIs(-1,'-') or LastAtomIs(-1,'*')
then
EdgedBracketsStartPos:=CurPos.StartPos;
end;
end;
cafEdgedBracketClose:
dec(Lvl);
cafWord:
;
cafComma:
if Lvl<1 then
break
else if Lvl>1 then
exit;
else
if AtomIsChar('+') or AtomIsChar('-') then begin
// allowed
end else begin
// not allowed
exit;
end;
end;
until false;
Result:=EdgedBracketsStartPos>0;
end;
function TFindDeclarationTool.IsTermNamedPointer(TermPos: TAtomPosition; out
ExprType: TExpressionType): boolean;
// check if TermPos is @Name and a pointer (= ^Name) can be found
var
SubExprType: TExpressionType;
Node: TCodeTreeNode;
PointerTool: TFindDeclarationTool;
Params: TFindDeclarationParams;
PointerNode: TCodeTreeNode;
begin
//debugln(['TFindDeclarationTool.IsTermNamedPointer ',CleanPosToStr(TermPos.StartPos,true),' Term={',copy(Src,TermPos.StartPos,TermPos.EndPos-TermPos.StartPos),'}']);
Result:=false;
MoveCursorToCleanPos(TermPos.StartPos);
ReadNextAtom;
if not AtomIsChar('@') then exit;
// a pointer
ExprType:=CleanExpressionType;
ExprType.Desc:=xtPointer;
Result:=true;
// try to find a name
ReadNextAtom;
if CurPos.StartPos>SrcLen then exit;
Node := FindDeepestNodeAtPos(CurPos.StartPos,true);
Params:=TFindDeclarationParams.Create(Self, Node);
try
SubExprType:=FindExpressionResultType(Params,CurPos.StartPos,-1);
finally
Params.Free;
end;
//debugln(['TFindDeclarationTool.IsTermNamedPointer SubExprType=',ExprTypeToString(SubExprType)]);
if SubExprType.Desc in xtAllPredefinedTypes then begin
ExprType.SubDesc:=SubExprType.Desc;
exit(true);
end else if (SubExprType.Desc=xtContext) then begin
Node:=SubExprType.Context.Node;
if (not (Node.Desc in AllIdentifierDefinitions))
and (Node.Parent<>nil) and (Node.Parent.Desc in AllIdentifierDefinitions) then
Node:=Node.Parent;
if (Node.Desc in AllIdentifierDefinitions) then begin
PointerTool:=SubExprType.Context.Tool;
PointerNode:=PointerTool.FindPointerOfIdentifier(Node);
if PointerNode<>nil then begin
ExprType:=CleanExpressionType;
ExprType.Desc:=xtContext;
ExprType.SubDesc:=xtNone;
ExprType.Context.Tool:=PointerTool;
ExprType.Context.Node:=PointerNode;
exit(true);
end;
end;
end;
end;
function TFindDeclarationTool.FindSetOfEnumerationType(EnumNode: TCodeTreeNode
): TCodeTreeNode;
// search in the same type section for a 'set of ' node
var
p: PChar;
function IsSetOfEnum(Node: TCodeTreeNode): boolean;
begin
Result:=false;
if (Node.Desc<>ctnTypeDefinition)
or (Node.FirstChild=nil)
or (Node.FirstChild.Desc<>ctnSetType) then exit;
MoveCursorToNodeStart(Node.FirstChild);
ReadNextAtom; // read set
if not UpAtomIs('SET') then exit;
ReadNextAtom; // read of
if not UpAtomIs('OF') then exit;
ReadNextAtom; // read of
if CurPos.Flag<>cafWord then exit;
Result:=CompareSrcIdentifiers(CurPos.StartPos,p);
end;
begin
{$IFDEF ShowExprEval}
debugln(['TFindDeclarationTool.FindSetOfEnumerationType ',EnumNode.DescAsString]);
{$ENDIF}
if EnumNode.Desc=ctnEnumIdentifier then EnumNode:=EnumNode.Parent;
if EnumNode.Desc=ctnEnumerationType then EnumNode:=EnumNode.Parent;
p:=@Src[EnumNode.StartPos];
Result:=EnumNode.Parent.FirstChild;
while Result<>nil do begin
if IsSetOfEnum(Result) then exit;
Result:=Result.NextBrother;
end;
end;
function TFindDeclarationTool.FindPointerOfIdentifier(
TypeNode: TCodeTreeNode): TCodeTreeNode;
// search in the same type section for a '^identifier' node
var
p: PChar;
function IsPointerOf(Node: TCodeTreeNode): boolean;
begin
Result:=false;
if (Node.Desc<>ctnTypeDefinition)
or (Node.FirstChild=nil)
or (Node.FirstChild.Desc<>ctnPointerType) then exit;
MoveCursorToNodeStart(Node.FirstChild);
ReadNextAtom; // read ^
if not AtomIsChar('^') then exit;
ReadNextAtom; // read identifier
if not AtomIsIdentifier then exit;
Result:=CompareSrcIdentifiers(CurPos.StartPos,p);
end;
begin
if TypeNode.Desc<>ctnTypeDefinition then exit(nil);
p:=@Src[TypeNode.StartPos];
Result:=TypeNode.Parent.FirstChild;
while Result<>nil do begin
if IsPointerOf(Result) then exit;
Result:=Result.NextBrother;
end;
end;
function TFindDeclarationTool.FindExprTypeAsString(
const ExprType: TExpressionType; TermCleanPos: integer;
AliasType: PFindContext): string;
procedure RaiseTermNotSimple(id: int64);
begin
if TermCleanPos<1 then
TermCleanPos:=1;
MoveCursorToCleanPos(TermCleanPos);
RaiseException(id,ctsTermNotSimple);
end;
var
FindContext: TFindContext;
ANode: TCodeTreeNode;
begin
{$IFDEF ShowExprEval}
DebugLn('TFindDeclarationTool.FindExprTypeAsString ExprType=',
ExprTypeToString(ExprType),' Alias=',FindContextToString(AliasType));
{$ENDIF}
Result:='';
if (AliasType<>nil) and (AliasType^.Node<>nil) then begin
case AliasType^.Node.Desc of
ctnTypeDefinition:
Result:=GetIdentifier(@AliasType^.Tool.Src[AliasType^.Node.StartPos]);
end;
if Result<>'' then exit;
end;
case ExprType.Desc of
xtNone:
RaiseTermNotSimple(20170421204649);
xtContext:
begin
FindContext:=ExprType.Context;
// ToDo: PPU, DCU
if FindContext.Node.Parent.Desc=ctnTypeDefinition then
FindContext.Node:=FindContext.Node.Parent;
case FindContext.Node.Desc of
ctnTypeDefinition:
Result:=GetIdentifier(
@FindContext.Tool.Src[FindContext.Node.StartPos]);
ctnVarDefinition,ctnConstDefinition:
begin
ANode:=FindContext.Tool.FindTypeNodeOfDefinition(FindContext.Node);
if (ANode=nil) or (ANode.Desc<>ctnIdentifier) then
RaiseTermNotSimple(20170421204653);
Result:=GetIdentifier(@FindContext.Tool.Src[ANode.StartPos]);
end;
ctnClass, ctnClassInterface, ctnDispinterface, ctnObject, ctnRecordType,
ctnClassHelper, ctnRecordHelper, ctnTypeHelper,
ctnObjCClass, ctnObjCCategory, ctnObjCProtocol, ctnCPPClass:
if (FindContext.Node.Parent<>nil)
and (FindContext.Node.Parent.Desc in [ctnTypeDefinition,ctnGenericType])
then
Result:=GetIdentifier(
@FindContext.Tool.Src[FindContext.Node.Parent.StartPos]);
ctnEnumIdentifier:
if (FindContext.Node.Parent<>nil)
and (FindContext.Node.Parent.Desc=ctnEnumerationType)
and (FindContext.Node.Parent.Parent<>nil)
and (FindContext.Node.Parent.Parent.Desc=ctnTypeDefinition)
then
Result:=GetIdentifier(
@FindContext.Tool.Src[FindContext.Node.Parent.Parent.StartPos]);
ctnEnumerationType:
if (FindContext.Node.Parent<>nil)
and (FindContext.Node.Parent.Desc=ctnTypeDefinition)
then
Result:=GetIdentifier(
@FindContext.Tool.Src[FindContext.Node.Parent.StartPos]);
ctnProperty,ctnGlobalProperty:
begin
FindContext.Tool.MoveCursorToPropType(FindContext.Node);
Result:=FindContext.Tool.GetAtom;
end;
ctnIdentifier:
begin
Result:=GetIdentifier(
@FindContext.Tool.Src[FindContext.Node.StartPos]);
end;
ctnProcedureHead:
begin
ANode:=GetProcResultNode(FindContext.Node);
if ANode<>nil then
Result:=FindContext.Tool.ExtractNode(ANode,[]);
end;
end;
if Result='' then begin
DebugLn('TFindDeclarationTool.FindExprTypeAsString ContextNode=',
FindContext.Node.DescAsString,' ',dbgsFC(FindContext));
RaiseTermNotSimple(20170421204655);
end;
end;
xtChar,
xtWideChar,
xtReal,
xtSingle,
xtDouble,
xtExtended,
xtCExtended,
xtCurrency,
xtComp,
xtInt64,
xtCardinal,
xtQWord,
xtPChar:
Result:=ExpressionTypeDescNames[ExprType.Desc];
xtPointer:
begin
case ExprType.SubDesc of
xtChar,
xtWideChar,
xtReal,
xtSingle,
xtDouble,
xtExtended,
xtCExtended,
xtCurrency,
xtComp,
xtInt64,
xtCardinal,
xtQWord,
xtBoolean,
xtByteBool,
xtWordBool,
xtLongBool,
xtQWordBool,
xtString,
xtAnsiString,
xtShortString,
xtWideString,
xtUnicodeString,
xtLongint,
xtLongWord,
xtWord,
xtSmallInt,
xtShortInt,
xtByte,
xtNativeInt,
xtNativeUInt:
Result:='P'+ExpressionTypeDescNames[ExprType.SubDesc];
else
Result:=ExpressionTypeDescNames[xtPointer];
end;
end;
xtFile,
xtText,
xtLongint,
xtLongWord,
xtSmallInt,
xtWord,
xtShortInt,
xtByte,
xtNativeInt,
xtNativeUInt:
Result:=ExpressionTypeDescNames[ExprType.Desc];
xtBoolean,
xtByteBool,
xtWordBool,
xtLongBool,
xtQWordBool:
Result:=ExpressionTypeDescNames[xtBoolean];
xtString,
xtAnsiString,
xtShortString:
Result:=ExpressionTypeDescNames[xtString];
xtWideString, xtUnicodeString:
Result:=ExpressionTypeDescNames[ExprType.Desc];
xtConstOrdInteger:
Result:='Integer';
xtConstString:
Result:=ExpressionTypeDescNames[xtString];
xtConstReal:
Result:=ExpressionTypeDescNames[xtExtended];
xtConstSet:
begin
// eventually try to find the 'set of ' type
RaiseTermNotSimple(20170421204658);
end;
xtConstBoolean:
Result:=ExpressionTypeDescNames[xtBoolean];
xtJSValue:
Result:=ExpressionTypeDescNames[ExprType.Desc];
xtNil:
RaiseTermNotSimple(20170421204702);
else
DebugLn('TCodeCompletionCodeTool.FindExprTypeAsString ExprType=',
ExprTypeToString(ExprType),' Alias=',FindContextToString(AliasType));
RaiseTermNotSimple(20170421204705);
end;
end;
function TFindDeclarationTool.FindExtendedExprOfHelper(HelperNode: TCodeTreeNode
): TExpressionType;
// returns the expression type of the extended class/type of a "helper for"
var
ForNode: TCodeTreeNode;
Params: TFindDeclarationParams;
begin
case HelperNode.Desc of
ctnClassHelper,ctnRecordHelper,ctnTypeHelper:
ForNode:=FindHelperForNode(HelperNode);
ctnObjCCategory:
ForNode:=FindInheritanceNode(HelperNode);
else
exit(CleanExpressionType);
end;
if Assigned(ForNode) and Assigned(ForNode.FirstChild) then
begin
Params:=TFindDeclarationParams.Create;
try
Params.Flags:=fdfDefaultForExpressions-[fdfSearchInHelpers,fdfSearchInAncestors]+[fdfTypeType];
Params.ContextNode:=ForNode;
Result:=FindExpressionTypeOfTerm(ForNode.FirstChild.StartPos,ForNode.FirstChild.EndPos,Params,false);
finally
Params.Free;
end;
end else
Result := CleanExpressionType;
end;
{ TFindDeclarationParams }
procedure TFindDeclarationParams.ClearFoundProc;
begin
if FoundProc=nil then exit;
//DebugLn(['TFindDeclarationParams.ClearFoundProc ',dbgs(FoundProc),' Saved=',FoundProc^.Owner<>nil]);
if FoundProc^.Owner=nil then
// the FoundProc is not saved
FreeFoundProc(FoundProc,true)
else if FoundProc^.Next<>nil then
// the FoundProc is saved (release the later FoundProcs,
// which are not needed any more)
FreeFoundProc(FoundProc^.Next,true)
else begin
// the FoundProc is owned, that means someo other function is reponsible for freeing it
end;
FoundProc:=nil;
end;
procedure TFindDeclarationParams.FreeFoundProc(aFoundProc: PFoundProc; FreeNext: boolean);
var
Next: PFoundProc;
begin
//DebugLn(['TFindDeclarationParams.FreeFoundProc ',dbgs(aFoundProc)]);
while aFoundProc<>nil do begin
if (aFoundProc^.Owner<>Self)
and ((FFoundProcStackFirst=aFoundProc)
or (aFoundProc^.Prior<>nil) or (aFoundProc^.Next<>nil))
then
raise Exception.Create('FoundProc is in list, but not owned');
if FreeNext then
Next:=aFoundProc^.Next
else
Next:=nil;
RemoveFoundProcFromList(aFoundProc);
with aFoundProc^ do begin
//DebugLn(['TFindDeclarationParams.FreeFoundProc ExprInputList=',dbgs(ExprInputList)]);
if ExprInputList<>nil then
FreeAndNil(ExprInputList);
//DebugLn(['TFindDeclarationParams.FreeFoundProc ParamCompatibilityList=',dbgs(ParamCompatibilityList)]);
if ParamCompatibilityList<>nil then begin
FreeMem(ParamCompatibilityList);
ParamCompatibilityList:=nil;
end;
CacheValid:=false;
end;
//DebugLn(['TFindDeclarationParams.FreeFoundProc Dispose ',dbgs(aFoundProc)]);
Dispose(aFoundProc);
aFoundProc:=Next;
end;
end;
procedure TFindDeclarationParams.RemoveFoundProcFromList(aFoundProc: PFoundProc);
begin
//DebugLn(['TFindDeclarationParams.RemoveFoundProcFromList ',dbgs(aFoundProc)]);
if aFoundProc^.Owner<>Self then exit;
if FFoundProcStackFirst=aFoundProc then
FFoundProcStackFirst:=aFoundProc^.Next;
if FFoundProcStackLast=aFoundProc then
FFoundProcStackLast:=aFoundProc^.Next;
with aFoundProc^ do begin
if Next<>nil then
Next^.Prior:=Prior;
if Prior<>nil then
Prior^.Next:=Next;
Prior:=nil;
Next:=nil;
Owner:=nil;
end;
end;
constructor TFindDeclarationParams.Create(ParentParams: TFindDeclarationParams);
begin
inherited Create;
Clear;
Parent:=ParentParams;
end;
constructor TFindDeclarationParams.Create(Tool: TFindDeclarationTool;
AContextNode: TCodeTreeNode);
begin
Create(nil);//helper list will be created
StartTool := Tool;
StartNode := AContextNode;
ContextNode := AContextNode;
{$IFDEF CheckNodeTool}
if (StartNode<>nil) and (StartNode.GetRoot<>StartTool.Tree.Root) then begin
debugln(['TFindDeclarationParams.Create Inconsistency']);
CTDumpStack;
raise Exception.Create('TFindDeclarationParams.Create StartNode does not belong to StartTool');
end;
{$ENDIF}
if (StartTool<>nil) and (StartNode<>nil) then
FNeedHelpers:=true;
end;
destructor TFindDeclarationParams.Destroy;
var
HelperKind: TFDHelpersListKind;
begin
Clear;
FreeFoundProc(FFoundProcStackFirst,true);
for HelperKind in TFDHelpersListKind do
if FFreeHelpers[HelperKind] then
FreeAndNil(FHelpers[HelperKind]);
inherited Destroy;
end;
procedure TFindDeclarationParams.Clear;
begin
ClearInput;
ClearFoundProc;
ClearResult(false);
OnTopLvlIdentifierFound:=nil;
end;
procedure TFindDeclarationParams.Save(out Input: TFindDeclarationInput);
begin
Input.Flags:=Flags;
Input.Identifier:=Identifier;
Input.ContextNode:=ContextNode;
Input.OnIdentifierFound:=OnIdentifierFound;
Input.IdentifierTool:=IdentifierTool;
Input.FoundProc:=FoundProc;
if (FoundProc<>nil) and (FoundProc^.Owner=nil) then begin
// add to list of saved FoundProcs
//DebugLn(['TFindDeclarationParams.Save ',dbgs(FoundProc)]);
FoundProc^.Prior:=FFoundProcStackLast;
if FFoundProcStackLast<>nil then
FFoundProcStackLast^.Next:=FoundProc;
FFoundProcStackLast:=FoundProc;
if FFoundProcStackFirst=nil then
FFoundProcStackFirst:=FoundProc;
FoundProc^.Owner:=Self;
end;
end;
procedure TFindDeclarationParams.Load(Input: TFindDeclarationInput;
FreeInput: boolean);
// set FreeInput to true, if the Input is not needed anymore and the dynamic
// data can be freed.
begin
Flags:=Input.Flags;
Identifier:=Input.Identifier;
ContextNode:=Input.ContextNode;
OnIdentifierFound:=Input.OnIdentifierFound;
IdentifierTool:=Input.IdentifierTool;
if FoundProc<>Input.FoundProc then begin
// clear current FoundProc
if FoundProc<>nil then
ClearFoundProc;
// use saved FoundProc
FoundProc:=Input.FoundProc;
// free all FoundProcs, that were saved later
if (FoundProc<>nil) then begin
FreeFoundProc(FoundProc^.Next,true);
if FreeInput then begin
Input.FoundProc:=nil;
RemoveFoundProcFromList(FoundProc);
end;
end;
end;
end;
procedure TFindDeclarationParams.ClearResult(CopyCacheFlags: boolean);
begin
NewPos.Code:=nil;
NewPos.X:=-1;
NewPos.Y:=-1;
NewTopLine:=-1;
NewNode:=nil;
NewCleanPos:=-1;
NewCodeTool:=nil;
NewFlags:=[];
if CopyCacheFlags and (fdfDoNotCache in Flags) then
Include(NewFlags,fodDoNotCache);
end;
procedure TFindDeclarationParams.SetResult(const AFindContext: TFindContext);
begin
ClearResult(true);
NewCodeTool:=AFindContext.Tool;
NewNode:=AFindContext.Node;
end;
procedure TFindDeclarationParams.SetResult(ANewCodeTool: TFindDeclarationTool;
ANewNode: TCodeTreeNode);
begin
ClearResult(true);
NewCodeTool:=ANewCodeTool;
NewNode:=ANewNode;
{$IFDEF CheckNodeTool}if NewCodeTool<>nil then NewCodeTool.CheckNodeTool(NewNode);{$ENDIF}
end;
procedure TFindDeclarationParams.SetResult(ANewCodeTool: TFindDeclarationTool;
ANewNode: TCodeTreeNode; ANewCleanPos: integer);
begin
ClearResult(true);
NewCodeTool:=ANewCodeTool;
NewNode:=ANewNode;
NewCleanPos:=ANewCleanPos;
{$IFDEF CheckNodeTool}if NewCodeTool<>nil then NewCodeTool.CheckNodeTool(NewNode);{$ENDIF}
end;
procedure TFindDeclarationParams.ConvertResultCleanPosToCaretPos;
begin
NewPos.Code:=nil;
if NewCodeTool<>nil then begin
if (NewCleanPos>=1) then
NewCodeTool.CleanPosToCaretAndTopLine(NewCleanPos,NewPos,NewTopLine)
else if (NewNode<>nil) then
NewCodeTool.CleanPosToCaretAndTopLine(NewNode.StartPos,NewPos,NewTopLine);
end;
end;
procedure TFindDeclarationParams.ClearInput;
begin
Flags:=[];
Identifier:=nil;
ContextNode:=nil;
OnIdentifierFound:=nil;
IdentifierTool:=nil;
end;
procedure TFindDeclarationParams.WriteDebugReport;
begin
DebugLn('TFindDeclarationParams.WriteDebugReport Self=',DbgS(Self));
// input parameters:
DebugLn(' Flags=',dbgs(Flags));
DebugLn(' Identifier=',GetIdentifier(Identifier));
if ContextNode<>nil then
DebugLn(' ContextNode=',ContextNode.DescAsString)
else
DebugLn(' ContextNode=nil');
if OnIdentifierFound<>nil then
DebugLn(' OnIdentifierFound=',TFindDeclarationTool(TMethod(OnIdentifierFound).Data).MainFilename);
if IdentifierTool<>nil then
DebugLn(' IdentifierTool=',IdentifierTool.MainFilename)
else
DebugLn(' IdentifierTool=nil');
if FoundProc<>nil then begin
if FoundProc^.Context.Node<>nil then
DebugLn(' FoundProc=',FoundProc^.Context.Tool.CleanPosToStr(FoundProc^.Context.Node.StartPos,true))
else
DebugLn(' FoundProc<>nil');
end;
// global params
if OnTopLvlIdentifierFound<>nil then
DebugLn(' OnTopLvlIdentifierFound=',TFindDeclarationTool(TMethod(OnTopLvlIdentifierFound).Code).MainFilename);
// results:
if NewNode<>nil then
DebugLn(' NewNode=',NewNode.DescAsString)
else
DebugLn(' NewNode=nil');
DebugLn(' NewCleanPos=',dbgs(NewCleanPos));
if NewCodeTool<>nil then begin
DebugLn(' NewCodeTool=',NewCodeTool.MainFilename,' at ',NewCodeTool.CleanPosToStr(NewCleanPos,false))
end else begin
DebugLn([' NewCodeTool=nil NewCleanPos=',NewCleanPos]);
end;
if NewPos.Code<>nil then
DebugLn([' NewPos=',NewPos.Code.Filename,' x=',NewPos.X,' y=',NewPos.Y,' topline=',NewTopLine])
else
DebugLn(' NewPos=nil');
DebugLn(' NewFlags=',dbgs(NewFlags));
DebugLn('');
end;
function TFindDeclarationParams.GetHelpers(HelperKind: TFDHelpersListKind;
CreateIfNotExists: boolean): TFDHelpersList;
begin
if Parent<>nil then
exit(Parent.GetHelpers(HelperKind,CreateIfNotExists));
if FNeedHelpers then
StartTool.FindHelpersInContext(Self); // beware: this calls GetHelpers
Result:=FHelpers[HelperKind];
if (Result=nil) and CreateIfNotExists then begin
Result:=TFDHelpersList.Create(HelperKind);
FHelpers[HelperKind]:=Result;
FFreeHelpers[HelperKind]:=true;
//if HelperKind=fdhlkDelphiHelper then
// debugln(['TFindDeclarationParams.GetHelpers Self=',dbgs(Pointer(Self)),' Helper=',dbgs(Pointer(FHelpers[HelperKind]))]);
end;
end;
procedure TFindDeclarationParams.SetIdentifier(
NewIdentifierTool: TFindDeclarationTool; NewIdentifier: PChar;
NewOnIdentifierFound: TOnIdentifierFound);
begin
Identifier:=NewIdentifier;
IdentifierTool:=NewIdentifierTool;
OnIdentifierFound:=NewOnIdentifierFound;
ClearFoundProc;
end;
procedure TFindDeclarationParams.SetFoundProc(
const ProcContext: TFindContext);
begin
//DebugLn(['TFindDeclarationParams.SetFirstFoundProc Old=',dbgs(FoundProc)]);
if FoundProc<>nil then
ClearFoundProc;
New(FoundProc);
//DebugLn(['TFindDeclarationParams.SetFirstFoundProc New=',dbgs(FoundProc)]);
FillChar(FoundProc^,SizeOf(TFoundProc),0);
FoundProc^.Context:=ProcContext;
end;
procedure TFindDeclarationParams.SetGenericParamValues(
SpecializeParamsTool: TFindDeclarationTool;
SpecializeNode: TCodeTreeNode);
begin
GenParams.ParamValuesTool := SpecializeParamsTool;
GenParams.SpecializeParamsNode := SpecializeNode.FirstChild.NextBrother;
end;
function TFindDeclarationParams.FindGenericParamType: Boolean;
var
i, n: integer;
GenParamType: TCodeTreeNode;
begin
// NewCodeTool, NewNode=GenericParamType
if not Assigned(NewCodeTool) or not Assigned(NewNode)
or not Assigned(GenParams.ParamValuesTool)
or not Assigned(GenParams.SpecializeParamsNode) then exit(false);
n:=0;
GenParamType:=NewNode;
while GenParamType<>nil do begin
GenParamType:=GenParamType.PriorBrother;
inc(n);
end;
with GenParams.ParamValuesTool do begin
MoveCursorToNodeStart(GenParams.SpecializeParamsNode);
ReadNextAtom;
// maybe all this syntax check is redundant
if not AtomIsChar('<') then
RaiseExceptionFmt(20170421200701,ctsStrExpectedButAtomFound,['<']);
ReadNextAtom;
if CurPos.Flag<>cafWord then
RaiseExceptionFmt(20170421200703,ctsIdentExpectedButAtomFound,[GetAtom]);
for i:=2 to n do begin
ReadNextAtom;
if AtomIsChar('>') then
RaiseException(20170421200705,ctsNotEnoughGenParams);
if not AtomIsChar(',') then
RaiseExceptionFmt(20170421200707,ctsStrExpectedButAtomFound,['>']);
ReadNextAtom;
if CurPos.Flag<>cafWord then
RaiseExceptionFmt(20170421200710,ctsIdentExpectedButAtomFound,[GetAtom]);
end;
Identifier:=@Src[CurPos.StartPos];
IdentifierTool:=GenParams.ParamValuesTool;
ContextNode:=GenParams.SpecializeParamsNode;
Result:=FindIdentifierInContext(Self);
end;
end;
procedure TFindDeclarationParams.AddOperandPart(aPart: string);
begin
FExtractedOperand := FExtractedOperand + aPart;
end;
procedure TFindDeclarationParams.ChangeFoundProc(
const ProcContext: TFindContext;
ProcCompatibility: TTypeCompatibility;
ParamCompatibilityList: TTypeCompatibilityList);
begin
FoundProc^.Context:=ProcContext;
FoundProc^.ProcCompatibility:=ProcCompatibility;
if (FoundProc^.ParamCompatibilityList<>ParamCompatibilityList) then begin
//DebugLn(['TFindDeclarationParams.ChangeFoundProc Old ParamCompatibilityList=',dbgs(FoundProc^.ParamCompatibilityList)]);
if (FoundProc^.ParamCompatibilityList<>nil) then
FreeMem(FoundProc^.ParamCompatibilityList);
FoundProc^.ParamCompatibilityList:=ParamCompatibilityList;
//DebugLn(['TFindDeclarationParams.ChangeFoundProc New ParamCompatibilityList=',dbgs(FoundProc^.ParamCompatibilityList)]);
end;
end;
function TFindDeclarationParams.IsFoundProcFinal: boolean;
begin
Result:=(FoundProc=nil)
or (FoundProc^.CacheValid and (FoundProc^.ProcCompatibility=tcExact));
end;
procedure TFindDeclarationParams.PrettifyResult;
begin
// adjust result for nicer position
if (NewNode<>nil) then begin
{$IFDEF CheckNodeTool}
if NewCodeTool<>nil then
NewCodeTool.CheckNodeTool(NewNode);
{$ENDIF}
case NewNode.Desc of
ctnProcedure:
if (NewNode.FirstChild<>nil)
and (NewNode.FirstChild.Desc=ctnProcedureHead) then begin
// Instead of jumping to the procedure keyword,
// jump to the procedure name
NewNode:=NewNode.FirstChild;
NewCleanPos:=NewNode.StartPos;
end;
ctnGenericType:
if (NewNode.FirstChild<>nil) then begin
// Instead of jumping to the generic keyword,
// jump to the name
NewNode:=NewNode.FirstChild;
NewCleanPos:=NewNode.StartPos;
end;
ctnProperty:
// jump to the name of the property
if NewCodeTool.MoveCursorToPropName(NewNode) then
NewCleanPos:=NewCodeTool.CurPos.StartPos;
end;
end;
end;
procedure TFindDeclarationParams.SetResult(
NodeCacheEntry: PCodeTreeNodeCacheEntry);
begin
ClearResult(true);
NewCodeTool:=TFindDeclarationTool(NodeCacheEntry^.NewTool);
NewNode:=NodeCacheEntry^.NewNode;
NewCleanPos:=NodeCacheEntry^.NewCleanPos;
end;
{ TExprTypeList }
destructor TExprTypeList.Destroy;
begin
if Items<>nil then begin
FreeMem(Items);
Freemem(AliasTypes);
end;
end;
function TExprTypeList.AsString: string;
var i: integer;
begin
Result:='';
for i:=0 to Count-1 do begin
Result:=Result+'{'+IntToStr(i)+'/'+IntToStr(Count)+':'+ExprTypeToString(Items[i])+'}'+LineEnding;
end;
end;
function TExprTypeList.CalcMemSize: PtrUInt;
begin
Result:=PtrUInt(InstanceSize)
+PtrUInt(FCapacity)*SizeOf(TExpressionType);
end;
procedure TExprTypeList.SetCapacity(const AValue: integer);
var NewSize, NewAliasSize: integer;
begin
if FCapacity=AValue then exit;
FCapacity:=AValue;
NewSize:=FCapacity*SizeOf(TExpressionType);
NewAliasSize:=FCapacity*SizeOf(TFindContext);
if Items=nil then begin
GetMem(Items,NewSize);
GetMem(AliasTypes,NewAliasSize);
end
else begin
ReAllocMem(Items,NewSize);
ReAllocMem(AliasTypes,NewAliasSize);
end;
if Count>Capacity then Count:=Capacity;
end;
procedure TExprTypeList.Grow;
begin
Capacity:=Capacity*2+4;
end;
procedure TExprTypeList.Add(const ExprType: TExpressionType);
begin
inc(Count);
if Count>Capacity then Grow;
Items[Count-1]:=ExprType;
AliasTypes[Count-1]:=CleanFindContext;
end;
procedure TExprTypeList.Add(const ExprType: TExpressionType;
const AliasType: TFindContext);
begin
inc(Count);
if Count>Capacity then Grow;
Items[Count-1]:=ExprType;
AliasTypes[Count-1]:=AliasType;
end;
procedure TExprTypeList.AddFirst(const ExprType: TExpressionType);
begin
inc(Count);
if Count>Capacity then Grow;
if Count>1 then
Move(Items[0],Items[1],SizeOf(TExpressionType)*(Count-1));
Items[0]:=ExprType;
end;
finalization
FreeAndNil(FBooleanTypesOrderList);
FreeAndNil(FIntegerTypesOrderList);
FreeAndNil(FRealTypesOrderList);
FreeAndNil(FStringTypesOrderList);
end.
|