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
|
/*
FALCON - The Falcon Programming Language.
FILE: vm.cpp
Implementation of virtual machine - non main loop
-------------------------------------------------------------------
Author: Giancarlo Niccolai
Begin: 2004-09-08
-------------------------------------------------------------------
(C) Copyright 2004: the FALCON developers (see list in AUTHORS file)
See LICENSE file for licensing details.
*/
#include <falcon/item.h>
#include <falcon/vm.h>
#include <falcon/pcodes.h>
#include <falcon/runtime.h>
#include <falcon/vmcontext.h>
#include <falcon/sys.h>
#include <falcon/coreobject.h>
#include <falcon/cclass.h>
#include <falcon/corefunc.h>
#include <falcon/symlist.h>
#include <falcon/proptable.h>
#include <falcon/memory.h>
#include <falcon/stream.h>
#include <falcon/core_ext.h>
#include <falcon/stdstreams.h>
#include <falcon/traits.h>
#include <falcon/fassert.h>
#include <falcon/format.h>
#include <falcon/vm_sys.h>
#include <falcon/flexymodule.h>
#include <falcon/mt.h>
#include <falcon/vmmsg.h>
#include <falcon/livemodule.h>
#include <falcon/vmevent.h>
#include <falcon/lineardict.h>
#include <string.h>
namespace Falcon {
static ThreadSpecific s_currentVM;
VMachine *VMachine::getCurrent()
{
return (VMachine *) s_currentVM.get();
}
VMachine::VMachine():
m_services( &traits::t_string(), &traits::t_voidp() ),
m_systemData( this ),
m_slots( &traits::t_string(), &traits::t_coreslotptr() ),
m_nextVM(0),
m_prevVM(0),
m_idleNext( 0 ),
m_idlePrev( 0 ),
m_baton( this ),
m_msg_head(0),
m_msg_tail(0),
m_refcount(1),
m_break(false)
{
internal_construct();
init();
}
VMachine::VMachine( bool initItems ):
m_services( &traits::t_string(), &traits::t_voidp() ),
m_systemData( this ),
m_slots( &traits::t_string(), &traits::t_coreslotptr() ),
m_nextVM(0),
m_prevVM(0),
m_idleNext( 0 ),
m_idlePrev( 0 ),
m_baton( this ),
m_msg_head(0),
m_msg_tail(0),
m_refcount(1),
m_break(false)
{
internal_construct();
if ( initItems )
init();
}
void VMachine::incref()
{
atomicInc( m_refcount );
}
void VMachine::decref()
{
if( atomicDec( m_refcount ) == 0 )
{
delete this;
}
}
void VMachine::setCurrent() const
{
s_currentVM.set( (void*) this );
}
void VMachine::internal_construct()
{
// use a ring for lock items.
m_onFinalize = 0;
m_userData = 0;
m_bhasStandardStreams = false;
m_loopsGC = FALCON_VM_DFAULT_CHECK_LOOPS;
m_loopsContext = FALCON_VM_DFAULT_CHECK_LOOPS;
m_loopsCallback = 0;
m_opLimit = 0;
m_generation = 0;
m_bSingleStep = false;
m_stdIn = 0;
m_stdOut = 0;
m_stdErr = 0;
m_launchAtLink = true;
m_bGcEnabled = true;
m_bWaitForCollect = false;
m_bPirorityGC = false;
resetCounters();
// this initialization must be performed by all vms.
m_mainModule = 0;
m_allowYield = true;
m_opCount = 0;
// This vectror has also context ownership -- when we remove a context here, it's dead
m_contexts.deletor( ContextList_deletor );
// finally we create the context (and the stack)
m_currentContext = new VMContext;
// saving also the first context for accounting reasons.
m_contexts.pushBack( m_currentContext );
m_opHandlers = (tOpcodeHandler *) memAlloc( FLC_PCODE_COUNT * sizeof( tOpcodeHandler ) );
m_metaClasses = (CoreClass**) memAlloc( FLC_ITEM_COUNT * sizeof(CoreClass*) );
memset( m_metaClasses, 0, FLC_ITEM_COUNT * sizeof(CoreClass*) );
// Search path
appSearchPath( Engine::getSearchPath() );
// This code is actually here for debug reasons. Opcode management should
// be performed via a swtich in the end, but until the beta version, this
// method allows to have a stack trace telling immediately which opcode
// were served in case a problem arises.
m_opHandlers[ P_END ] = opcodeHandler_END ;
m_opHandlers[ P_NOP ] = opcodeHandler_NOP ;
m_opHandlers[ P_PSHN] = opcodeHandler_PSHN;
m_opHandlers[ P_RET ] = opcodeHandler_RET ;
m_opHandlers[ P_RETA] = opcodeHandler_RETA;
// Range 2: one parameter ops
m_opHandlers[ P_PTRY] = opcodeHandler_PTRY;
m_opHandlers[ P_LNIL] = opcodeHandler_LNIL;
m_opHandlers[ P_RETV] = opcodeHandler_RETV;
m_opHandlers[ P_FORK] = opcodeHandler_FORK;
m_opHandlers[ P_BOOL] = opcodeHandler_BOOL;
m_opHandlers[ P_GENA] = opcodeHandler_GENA;
m_opHandlers[ P_GEND] = opcodeHandler_GEND;
m_opHandlers[ P_PUSH] = opcodeHandler_PUSH;
m_opHandlers[ P_PSHR] = opcodeHandler_PSHR;
m_opHandlers[ P_POP ] = opcodeHandler_POP ;
m_opHandlers[ P_JMP ] = opcodeHandler_JMP ;
m_opHandlers[ P_INC ] = opcodeHandler_INC ;
m_opHandlers[ P_DEC ] = opcodeHandler_DEC ;
m_opHandlers[ P_NEG ] = opcodeHandler_NEG ;
m_opHandlers[ P_NOT ] = opcodeHandler_NOT ;
m_opHandlers[ P_TRAL] = opcodeHandler_TRAL;
m_opHandlers[ P_IPOP] = opcodeHandler_IPOP;
m_opHandlers[ P_XPOP] = opcodeHandler_XPOP;
m_opHandlers[ P_GEOR] = opcodeHandler_GEOR;
m_opHandlers[ P_TRY ] = opcodeHandler_TRY ;
m_opHandlers[ P_JTRY] = opcodeHandler_JTRY;
m_opHandlers[ P_RIS ] = opcodeHandler_RIS ;
m_opHandlers[ P_BNOT] = opcodeHandler_BNOT;
m_opHandlers[ P_NOTS] = opcodeHandler_NOTS;
m_opHandlers[ P_PEEK] = opcodeHandler_PEEK;
// Range3: Double parameter ops
m_opHandlers[ P_LD ] = opcodeHandler_LD ;
m_opHandlers[ P_LDRF] = opcodeHandler_LDRF;
m_opHandlers[ P_ADD ] = opcodeHandler_ADD ;
m_opHandlers[ P_SUB ] = opcodeHandler_SUB ;
m_opHandlers[ P_MUL ] = opcodeHandler_MUL ;
m_opHandlers[ P_DIV ] = opcodeHandler_DIV ;
m_opHandlers[ P_MOD ] = opcodeHandler_MOD ;
m_opHandlers[ P_POW ] = opcodeHandler_POW ;
m_opHandlers[ P_ADDS] = opcodeHandler_ADDS;
m_opHandlers[ P_SUBS] = opcodeHandler_SUBS;
m_opHandlers[ P_MULS] = opcodeHandler_MULS;
m_opHandlers[ P_DIVS] = opcodeHandler_DIVS;
m_opHandlers[ P_MODS] = opcodeHandler_MODS;
m_opHandlers[ P_POWS] = opcodeHandler_POWS;
m_opHandlers[ P_BAND] = opcodeHandler_BAND;
m_opHandlers[ P_BOR ] = opcodeHandler_BOR ;
m_opHandlers[ P_BXOR] = opcodeHandler_BXOR;
m_opHandlers[ P_ANDS] = opcodeHandler_ANDS;
m_opHandlers[ P_ORS ] = opcodeHandler_ORS ;
m_opHandlers[ P_XORS] = opcodeHandler_XORS;
m_opHandlers[ P_GENR] = opcodeHandler_GENR;
m_opHandlers[ P_EQ ] = opcodeHandler_EQ ;
m_opHandlers[ P_NEQ ] = opcodeHandler_NEQ ;
m_opHandlers[ P_GT ] = opcodeHandler_GT ;
m_opHandlers[ P_GE ] = opcodeHandler_GE ;
m_opHandlers[ P_LT ] = opcodeHandler_LT ;
m_opHandlers[ P_LE ] = opcodeHandler_LE ;
m_opHandlers[ P_IFT ] = opcodeHandler_IFT ;
m_opHandlers[ P_IFF ] = opcodeHandler_IFF ;
m_opHandlers[ P_CALL] = opcodeHandler_CALL;
m_opHandlers[ P_INST] = opcodeHandler_INST;
m_opHandlers[ P_ONCE] = opcodeHandler_ONCE;
m_opHandlers[ P_LDV ] = opcodeHandler_LDV ;
m_opHandlers[ P_LDP ] = opcodeHandler_LDP ;
m_opHandlers[ P_TRAN] = opcodeHandler_TRAN;
m_opHandlers[ P_LDAS] = opcodeHandler_LDAS;
m_opHandlers[ P_SWCH] = opcodeHandler_SWCH;
m_opHandlers[ P_IN ] = opcodeHandler_IN ;
m_opHandlers[ P_NOIN] = opcodeHandler_NOIN;
m_opHandlers[ P_PROV] = opcodeHandler_PROV;
m_opHandlers[ P_STPS] = opcodeHandler_STPS;
m_opHandlers[ P_STVS] = opcodeHandler_STVS;
m_opHandlers[ P_AND ] = opcodeHandler_AND;
m_opHandlers[ P_OR ] = opcodeHandler_OR;
// Range 4: ternary opcodes
m_opHandlers[ P_STP ] = opcodeHandler_STP ;
m_opHandlers[ P_STV ] = opcodeHandler_STV ;
m_opHandlers[ P_LDVT] = opcodeHandler_LDVT;
m_opHandlers[ P_LDPT] = opcodeHandler_LDPT;
m_opHandlers[ P_STPR] = opcodeHandler_STPR;
m_opHandlers[ P_STVR] = opcodeHandler_STVR;
m_opHandlers[ P_TRAV] = opcodeHandler_TRAV;
m_opHandlers[ P_INCP] = opcodeHandler_INCP;
m_opHandlers[ P_DECP] = opcodeHandler_DECP;
m_opHandlers[ P_SHL ] = opcodeHandler_SHL;
m_opHandlers[ P_SHR ] = opcodeHandler_SHR;
m_opHandlers[ P_SHLS] = opcodeHandler_SHLS;
m_opHandlers[ P_SHRS] = opcodeHandler_SHRS;
m_opHandlers[ P_LSB ] = opcodeHandler_LSB;
m_opHandlers[ P_SELE ] = opcodeHandler_SELE;
m_opHandlers[ P_INDI ] = opcodeHandler_INDI;
m_opHandlers[ P_STEX ] = opcodeHandler_STEX;
m_opHandlers[ P_TRAC ] = opcodeHandler_TRAC;
m_opHandlers[ P_WRT ] = opcodeHandler_WRT;
m_opHandlers[ P_STO ] = opcodeHandler_STO;
m_opHandlers[ P_FORB ] = opcodeHandler_FORB;
m_opHandlers[ P_EVAL ] = opcodeHandler_EVAL;
m_opHandlers[ P_CLOS ] = opcodeHandler_CLOS;
m_opHandlers[ P_PSHL ] = opcodeHandler_PSHL;
m_opHandlers[ P_OOB ] = opcodeHandler_OOB;
m_opHandlers[ P_TRDN ] = opcodeHandler_TRDN;
m_opHandlers[ P_EXEQ ] = opcodeHandler_EXEQ;
// Finally, register to the GC system
memPool->registerVM( this );
}
void VMachine::init()
{
//================================
// Preparing minimal input/output
if ( m_stdIn == 0 )
m_stdIn = stdInputStream();
if ( m_stdOut == 0 )
m_stdOut = stdOutputStream();
if ( m_stdErr == 0 )
m_stdErr = stdErrorStream();
}
void VMachine::finalize()
{
// we should have at least 2 refcounts here: one is from the caller and one in the GC.
fassert( m_refcount >= 2 );
/*
* We are destroying the VM, so disable any things
* that may access it when it's being freed.
*/
m_systemData.earlyCleanup();
// disengage from mempool
if ( memPool != 0 )
{
memPool->unregisterVM( this );
}
if ( m_onFinalize != 0 )
m_onFinalize( this );
decref();
}
VMachine::~VMachine()
{
// Free generic tables (quite safe)
memFree( m_opHandlers );
memFree( m_metaClasses );
// and finally, the streams.
delete m_stdErr;
delete m_stdIn;
delete m_stdOut;
// clear now the global maps
// this also decrefs the modules and destroys the globals.
// Notice that this would be done automatically also at destructor exit.
m_liveModules.clear();
}
LiveModule* VMachine::link( Runtime *rt )
{
fassert(rt);
// link all the modules in the runtime from first to last.
// FIFO order is important.
uint32 listSize = rt->moduleVector()->size();
LiveModule** lmodList = new LiveModule*[listSize];
LiveModule* lmod = 0;
//Make sure we catch falcon errors to delete lmodList afterwards.
try {
uint32 iter;
for( iter = 0; iter < listSize; ++iter )
{
ModuleDep *md = rt->moduleVector()->moduleDepAt( iter );
if ( (lmod = prelink( md->module(),
rt->hasMainModule() && (iter + 1 == listSize),
md->isPrivate() ) ) == 0
)
{
delete [] lmodList;
return 0;
}
// use the temporary storage.
lmodList[ iter ] = lmod;
}
// now again, do the complete phase.
for( iter = 0; iter < listSize; ++iter )
{
if ( ! completeModLink( lmodList[ iter ] ) )
{
delete [] lmodList;
return 0;
}
}
// returns the topmost livemodule
delete [] lmodList;
}
catch( Error *err )
{
delete [] lmodList;
throw err;
}
return lmod;
}
LiveModule *VMachine::link( Module *mod, bool isMainModule, bool bPrivate )
{
// Ok, the module is now in.
// We can now increment reference count and add it to ourselves
LiveModule *livemod = prelink( mod, isMainModule, bPrivate );
if ( livemod && completeModLink( livemod ) )
{
return livemod;
}
return 0;
}
LiveModule *VMachine::prelink( Module *mod, bool isMainModule, bool bPrivate )
{
// See if we have a module with the same name
LiveModule *oldMod = findModule( mod->name() );
if ( oldMod != 0 )
{
// if the publish policy is changed, allow this
if( oldMod->isPrivate() && ! bPrivate )
{
// try to export all
if ( ! exportAllSymbols( oldMod ) )
{
return 0;
}
// success; change official policy and return the livemod
oldMod->setPrivate( false );
}
return oldMod;
}
// Ok, the module is now in.
// We can now increment reference count and add it to ourselves
LiveModule *livemod = new LiveModule( mod, bPrivate );
// set this as the main module if required.
if ( isMainModule )
m_mainModule = livemod;
// then we always need the symbol table.
const SymbolTable *symtab = &livemod->module()->symbolTable();
// A shortcut
ItemArray& globs = livemod->globals();
// resize() creates a series of NIL items.
globs.resize( symtab->size()+1 );
bool success = true;
// now, the symbol table must be traversed.
MapIterator iter = symtab->map().begin();
while( iter.hasCurrent() )
{
Symbol *sym = *(Symbol **) iter.currentValue();
if ( ! sym->isUndefined() )
{
if ( ! linkDefinedSymbol( sym, livemod ) )
{
// but continue to expose other errors as well.
success = false;
}
}
// next symbol
iter.next();
}
// return zero and dispose of the module if not succesful.
if ( ! success )
{
// no need to free on failure: livemod are garbaged
livemod->mark( 0 );
// LiveModule is garbageable, cannot be destroyed.
return 0;
}
// We can now add the module to our list of available modules.
m_liveModules.insert( &livemod->name(), livemod );
livemod->initialized( LiveModule::init_complete );
return livemod;
}
bool VMachine::completeModLink( LiveModule *livemod )
{
// we need to record the classes in the module as they have to be evaluated last.
SymbolList modClasses;
SymbolList modObjects;
// then we always need the symbol table.
const SymbolTable *symtab = &livemod->module()->symbolTable();
// we won't be preemptible during link
bool atomic = m_currentContext->atomicMode();
m_currentContext->atomicMode(true);
bool success = true;
// now, the symbol table must be traversed.
MapIterator iter = symtab->map().begin();
while( iter.hasCurrent() )
{
Symbol *sym = *(Symbol **) iter.currentValue();
if ( sym->isUndefined() )
{
if (! linkUndefinedSymbol( sym, livemod ) )
success = false;
}
else
{
// save classes and objects for later linking.
if( sym->type() == Symbol::tclass )
modClasses.pushBack( sym );
else if ( sym->type() == Symbol::tinst )
modObjects.pushBack( sym );
}
// next symbol
iter.next();
}
// now that the symbols in the module have been linked, link the classes.
ListElement *cls_iter = modClasses.begin();
while( cls_iter != 0 )
{
Symbol *sym = (Symbol *) cls_iter->data();
fassert( sym->isClass() );
// on error, report failure but proceed.
if ( ! linkClassSymbol( sym, livemod ) )
success = false;
cls_iter = cls_iter->next();
}
// then, prepare the instances of standalone objects
ListElement *obj_iter = modObjects.begin();
while( obj_iter != 0 )
{
Symbol *obj = (Symbol *) obj_iter->data();
fassert( obj->isInstance() );
// on error, report failure but proceed.
if ( ! linkInstanceSymbol( obj, livemod ) )
success = false;
obj_iter = obj_iter->next();
}
if ( success )
{
// eventually, call the constructors declared by the instances
obj_iter = modObjects.begin();
// In case we have some objects to link - and while we have no errors,
// -- we can't afford calling constructors if everything is not ok.
while( success && obj_iter != 0 )
{
Symbol *obj = (Symbol *) obj_iter->data();
initializeInstance( obj, livemod );
obj_iter = obj_iter->next();
}
}
// Initializations of module objects is complete; return to non-atomic mode
m_currentContext->atomicMode( atomic );
// return zero and dispose of the module if not succesful.
if ( ! success )
{
// LiveModule is garbageable, cannot be destroyed.
return false;
}
// and for last, export all the services.
MapIterator svmap_iter = livemod->module()->getServiceMap().begin();
while( svmap_iter.hasCurrent() )
{
// throws on error.
publishService( *(Service ** ) svmap_iter.currentValue() );
svmap_iter.next();
}
// execute the main code, if we have one
// -- but only if this is NOT the main module
if ( m_launchAtLink && m_mainModule != livemod )
{
Item *mainItem = livemod->findModuleItem( "__main__" );
if( mainItem != 0 )
{
callItem( *mainItem, 0 );
}
}
return true;
}
// Link a single symbol
bool VMachine::linkSymbol( const Symbol *sym, LiveModule *livemod )
{
if ( sym->isUndefined() )
{
return linkUndefinedSymbol( sym, livemod );
}
return linkDefinedSymbol( sym, livemod );
}
bool VMachine::linkDefinedSymbol( const Symbol *sym, LiveModule *livemod )
{
// A shortcut
ItemArray& globs = livemod->globals();
// Ok, the symbol is defined here. Link (record) it.
// create an appropriate item here.
// NOTE: Classes and instances are handled separately.
switch( sym->type() )
{
case Symbol::tfunc:
case Symbol::textfunc:
globs[ sym->itemId() ].setFunction( new CoreFunc( sym, livemod ) );
break;
case Symbol::tvar:
case Symbol::tconst:
{
Item& itm = globs[ sym->itemId() ];
VarDef *vd = sym->getVarDef();
switch( vd->type() ) {
case VarDef::t_bool: itm.setBoolean( vd->asBool() ); break;
case VarDef::t_int: itm.setInteger( vd->asInteger() ); break;
case VarDef::t_num: itm.setNumeric( vd->asNumeric() ); break;
case VarDef::t_string:
{
itm.setString( new CoreString( *vd->asString() ) );
}
break;
default:
break;
}
}
break;
// nil when we don't know what it is.
default:
globs[ sym->itemId() ].setNil();
}
// see if the symbol needs exportation and eventually do that.
if ( ! exportSymbol( sym, livemod ) )
return false;
return true;
}
bool VMachine::linkUndefinedSymbol( const Symbol *sym, LiveModule *livemod )
{
// A shortcut
ItemArray& globs = livemod->globals();
const Module *mod = livemod->module();
// is the symbol name-spaced?
uint32 dotPos;
String localSymName;
ModuleDepData *depData;
LiveModule *lmod = 0;
if ( ( dotPos = sym->name().rfind( "." ) ) != String::npos && sym->imported() )
{
String nameSpace = sym->name().subString( 0, dotPos );
// get the module name for the given module
depData = mod->dependencies().findModule( nameSpace );
// if we linked it, it must exist
// -- but in some cases, the compiler may generate a dotted symbol loaded from external sources
// -- this is usually an error, so let the undefined error to be declared.
if ( depData != 0 )
{
// ... then find the module in the item
String absName;
Module::absoluteName(
depData->isFile() ? nameSpace: depData->moduleName(),
mod->name(), absName );
lmod = findModule( absName );
// we must convert the name if it contains self or if it starts with "."
if ( lmod != 0 )
localSymName = sym->name().subString( dotPos + 1 );
}
}
else if ( sym->isImportAlias() )
{
depData = mod->dependencies().findModule( sym->getImportAlias()->origModule() );
// if we linked it, it must exist
fassert( depData != 0 );
// ... then find the module in the item
String absName;
Module::absoluteName( depData->moduleName(), mod->name(), absName );
lmod = findModule( absName );
if( lmod != 0 )
localSymName = sym->getImportAlias()->name();
}
// If we found it...
if ( lmod != 0 )
{
Symbol *localSym = lmod->module()->findGlobalSymbol( localSymName );
if ( localSym != 0 )
{
referenceItem( globs[ sym->itemId() ],
lmod->globals()[ localSym->itemId() ] );
return true;
}
// last chance: if the module is flexy, we may ask it do dynload it.
if( lmod->module()->isFlexy() )
{
// Destroy also constness; flexy modules love to be abused.
FlexyModule *fmod = (FlexyModule *)( lmod->module() );
Symbol *newsym = fmod->onSymbolRequest( localSymName );
// Found -- great, link it and if all it's fine, link again this symbol.
if ( newsym != 0 )
{
// be sure to allocate enough space in the module global table.
if ( newsym->itemId() >= lmod->globals().length() )
{
lmod->globals().resize( newsym->itemId()+1 );
}
// now we have space to link it.
if ( linkCompleteSymbol( newsym, lmod ) )
{
referenceItem( globs[ sym->itemId() ], lmod->globals()[newsym->itemId()] );
return true;
}
else {
// we found the symbol, but it was flacky. We must have raised an error,
// and so we should return now.
// Notice that there is no need to free the symbol.
return false;
}
}
}
// ... otherwise, the symbol is undefined.
}
else {
// try to find the imported symbol.
SymModule *sm = (SymModule *) m_globalSyms.find( &sym->name() );
if( sm != 0 )
{
// link successful, we must set the current item as a reference of the original
referenceItem( globs[ sym->itemId() ], *sm->item() );
return true;
}
}
// try to dynamically load the symbol from flexy modules.
SymModule symmod;
if ( linkSymbolDynamic( sym->name(), symmod ) )
{
referenceItem( globs[ sym->itemId() ], *symmod.item() );
return true;
}
// We failed every try; raise undefined symbol.
throw new CodeError(
ErrorParam( e_undef_sym, sym->declaredAt() ).origin( e_orig_vm ).
module( mod->name() ).
extra( sym->name() )
);
}
bool VMachine::exportAllSymbols( LiveModule *livemod )
{
bool success = true;
// now, the symbol table must be traversed.
const SymbolTable *symtab = &livemod->module()->symbolTable();
MapIterator iter = symtab->map().begin();
while( iter.hasCurrent() )
{
Symbol *sym = *(Symbol **) iter.currentValue();
if ( ! exportSymbol( sym, livemod ) )
{
// but continue to expose other errors as well.
success = false;
}
// next symbol
iter.next();
}
return success;
}
bool VMachine::exportSymbol( const Symbol *sym, LiveModule *livemod )
{
// A shortcut
ItemArray& globs = livemod->globals();
const Module *mod = livemod->module();
// Is this symbol exported?
if ( ! livemod->isPrivate() && sym->exported() && sym->name().getCharAt(0) != '_' )
{
// as long as the module is referenced, the symbols are alive, and as we
// hold a reference to the module, we are sure that symbols are alive here.
// also, in case an entry already exists, the previous item is just overwritten.
if ( m_globalSyms.find( &sym->name() ) != 0 )
{
throw new CodeError( ErrorParam( e_already_def, sym->declaredAt() ).origin( e_orig_vm ).
module( mod->name() ).
symbol( sym->name() ) );
}
SymModule tmp( &globs[ sym->itemId() ], livemod, sym );
m_globalSyms.insert( &sym->name(), &tmp );
// export also the instance, if it is not already exported.
if ( sym->isInstance() )
{
Symbol* tsym = sym->getInstance();
if ( ! tsym->exported() ) {
SymModule tmp( &globs[ tsym->itemId() ], livemod, tsym );
m_globalSyms.insert( &tsym->name(), &tmp );
}
}
}
// Is this symbol a well known item?
if ( sym->isWKS() )
{
if ( m_wellKnownSyms.find( &sym->name() ) != 0 )
{
throw
new CodeError( ErrorParam( e_already_def, sym->declaredAt() ).origin( e_orig_vm ).
module( mod->name() ).
symbol( sym->name() ).
extra( "Well Known Item" )
);
}
SymModule tmp( livemod->wkitems().length(), livemod, sym );
m_wellKnownSyms.insert( &sym->name(), &tmp );
// and don't forget to add a copy of the item
livemod->wkitems().append( globs[ sym->itemId() ] );
}
return true;
}
bool VMachine::linkSymbolDynamic( const String &name, SymModule &symdata )
{
// For now, the thing is very unoptimized; we'll traverse all the live modules,
// and see which of them is flexy.
MapIterator iter = m_liveModules.begin();
while( iter.hasCurrent() )
{
LiveModule *lmod = *(LiveModule **)(iter.currentValue());
if( lmod->module()->isFlexy() )
{
// Destroy also constness; flexy modules love to be abused.
FlexyModule *fmod = (FlexyModule *)( lmod->module() );
Symbol *newsym = fmod->onSymbolRequest( name );
// Found -- great, link it and if all it's fine, link again this symbol.
if ( newsym != 0 )
{
// be sure to allocate enough space in the module global table.
if ( newsym->itemId() >= lmod->globals().length() )
{
lmod->globals().resize( newsym->itemId()+1 );
}
// now we have space to link it.
if ( linkCompleteSymbol( newsym, lmod ) )
{
symdata = SymModule( &lmod->globals()[ newsym->itemId() ], lmod, newsym );
return true;
}
else {
// we found the symbol, but it was flacky. We must have raised an error,
// and so we should return now.
// Notice that there is no need to free the symbol.
return false;
}
}
// otherwise, go on
}
iter.next();
}
// sorry, not found.
return false;
}
bool VMachine::linkClassSymbol( const Symbol *sym, LiveModule *livemod )
{
// shortcut
ItemArray& globs = livemod->globals();
CoreClass *cc = linkClass( livemod, sym );
if ( cc == 0 )
return false;
// we need to add it anyhow to the GC to provoke its destruction at VM end.
// and hey, you could always destroy symbols if your mood is so from falcon ;-)
// dereference as other classes may have referenced this item1
globs[ cc->symbol()->itemId() ].dereference()->setClass( cc );
// if this class was a WKI, we must also set the relevant exported symbol
if ( sym->isWKS() )
{
SymModule *tmp = (SymModule *) m_wellKnownSyms.find( &sym->name() );
fassert( tmp != 0 ); // we just added it
tmp->liveModule()->wkitems()[ tmp->wkiid() ] = cc;
}
if ( sym->getClassDef()->isMetaclassFor() >= 0 )
{
m_metaClasses[ sym->getClassDef()->isMetaclassFor() ] = cc;
}
return true;
}
bool VMachine::linkInstanceSymbol( const Symbol *obj, LiveModule *livemod )
{
// shortcut
ItemArray& globs = livemod->globals();
Symbol *cls = obj->getInstance();
Item *clsItem = globs[ cls->itemId() ].dereference();
if ( clsItem == 0 || ! clsItem->isClass() ) {
new CodeError( ErrorParam( e_no_cls_inst, obj->declaredAt() ).origin( e_orig_vm ).
symbol( obj->name() ).
module( obj->module()->name() )
);
return false;
}
else {
CoreObject *co = clsItem->asClass()->createInstance();
globs[ obj->itemId() ].dereference()->setObject( co );
// if this class was a WKI, we must also set the relevant exported symbol
if ( obj->isWKS() )
{
SymModule *tmp = (SymModule *) m_wellKnownSyms.find( &obj->name() );
fassert ( tmp != 0 );
tmp->liveModule()->wkitems()[ tmp->wkiid() ] = co;
}
}
return true;
}
void VMachine::initializeInstance( const Symbol *obj, LiveModule *livemod )
{
ItemArray& globs = livemod->globals();
Symbol *cls = obj->getInstance();
if ( cls->getClassDef()->constructor() != 0 )
{
Item ctor = *globs[cls->getClassDef()->constructor()->itemId() ].dereference();
ctor.methodize( *globs[ obj->itemId() ].dereference() );
// If we can't call, we have a wrong init.
callItemAtomic( ctor, 0 );
}
CoreObject* cobj = globs[ obj->itemId() ].dereference()->asObject();
if( cobj->generator()->initState() != 0 )
{
cobj->setState( "init", cobj->generator()->initState() );
// If we can't call, we have a wrong init.
Item enterItem;
if( cobj->getMethod("__enter", enterItem ) )
{
pushParam(Item());
callItemAtomic( enterItem, 1 );
}
}
}
bool VMachine::linkCompleteSymbol( const Symbol *sym, LiveModule *livemod )
{
// try a pre-link
bool bSuccess = linkSymbol( sym, livemod );
// Proceed anyhow, even on failure, for classes and instance symbols
if( sym->type() == Symbol::tclass )
{
if ( ! linkClassSymbol( sym, livemod ) )
bSuccess = false;
}
else if ( sym->type() == Symbol::tinst )
{
fassert( sym->getInstance() != 0 );
// we can't try to call the initialization method
// if the creation of the symbol fails.
if ( linkClassSymbol( sym->getInstance(), livemod ) &&
linkInstanceSymbol( sym, livemod )
)
{
initializeInstance( sym, livemod );
}
else
bSuccess = false;
}
return bSuccess;
}
bool VMachine::linkCompleteSymbol( Symbol *sym, const String &moduleName )
{
LiveModule *lm = findModule( moduleName );
if ( lm != 0 )
return linkCompleteSymbol( sym, lm );
return false;
}
PropertyTable *VMachine::createClassTemplate( LiveModule *lmod, const Map &pt )
{
MapIterator iter = pt.begin();
PropertyTable *table = new PropertyTable( pt.size() );
bool bHasSetGet = false;
while( iter.hasCurrent() )
{
VarDefMod *vdmod = *(VarDefMod **) iter.currentValue();
VarDef *vd = vdmod->vd;
String *key = *(String **) iter.currentKey();
PropEntry &e = table->appendSafe( key );
e.m_bReadOnly = vd->isReadOnly();
// configure the element
if ( vd->isReflective() )
{
e.m_eReflectMode = vd->asReflecMode();
// we must keep this information for later.
if ( e.m_eReflectMode == e_reflectSetGet )
bHasSetGet = true;
else
e.m_reflection.offset = vd->asReflecOffset();
}
else if ( vd->isReflectFunc() )
{
e.m_eReflectMode = e_reflectFunc;
e.m_reflection.rfunc.to = vd->asReflectFuncTo();
e.m_reflection.rfunc.from = vd->asReflectFuncFrom();
e.reflect_data = vd->asReflectFuncData();
// just to be paranoid
if( e.m_reflection.rfunc.to == 0 )
e.m_bReadOnly = true;
}
// create the instance
switch( vd->type() )
{
case VarDef::t_nil:
e.m_value.setNil();
break;
case VarDef::t_bool:
e.m_value.setBoolean( vd->asBool() );
break;
case VarDef::t_int:
e.m_value.setInteger( vd->asInteger() );
break;
case VarDef::t_num:
e.m_value.setNumeric( vd->asNumeric() );
break;
case VarDef::t_string:
{
e.m_value.setString( new CoreString( *vd->asString() ) );
}
break;
case VarDef::t_base:
e.m_bReadOnly = true;
case VarDef::t_reference:
{
const Symbol *sym = vd->asSymbol();
referenceItem( e.m_value, vdmod->lmod->globals()[ sym->itemId() ] );
}
break;
case VarDef::t_symbol:
{
Symbol *sym = const_cast< Symbol *>( vd->asSymbol() );
// may be a function or an extfunc
fassert( sym->isExtFunc() || sym->isFunction() );
if ( sym->isExtFunc() || sym->isFunction() )
{
e.m_value.setFunction( new CoreFunc( sym, vdmod->lmod ) );
}
}
break;
default:
break; // compiler warning no-op
}
iter.next();
}
// complete setter/getter
if( bHasSetGet )
{
for( uint32 pp = 0; pp < table->added(); ++pp )
{
PropEntry& pe = table->getEntry(pp);
if( pe.m_eReflectMode == e_reflectSetGet )
{
uint32 pos;
if( table->findKey(String("__set_") + *pe.m_name, pos ) )
{
pe.m_reflection.gs.m_setterId = pos;
}
else
{
pe.m_reflection.gs.m_setterId = PropEntry::NO_OFFSET;
pe.m_bReadOnly = true;
}
if( table->findKey(String("__get_") + *pe.m_name, pos ) )
{
pe.m_reflection.gs.m_getterId = pos;
}
else
{
pe.m_reflection.gs.m_getterId = PropEntry::NO_OFFSET;
}
}
}
}
table->checkProperties();
return table;
}
CoreClass *VMachine::linkClass( LiveModule *lmod, const Symbol *clssym )
{
Map props( &traits::t_stringptr(), &traits::t_voidp() );
Map states( &traits::t_stringptr(), &traits::t_voidp() );
ObjectFactory factory = 0;
if( ! linkSubClass( lmod, clssym, props, states, &factory ) )
return 0;
CoreClass *cc = new CoreClass( clssym, lmod, createClassTemplate( lmod, props ) );
Symbol *ctor = clssym->getClassDef()->constructor();
if ( ctor != 0 ) {
cc->constructor().setFunction( new CoreFunc( ctor, lmod ) );
}
// destroy the temporary vardef we have created
MapIterator iter = props.begin();
while( iter.hasCurrent() )
{
VarDefMod *value = *(VarDefMod **) iter.currentValue();
delete value;
iter.next();
}
// apply the state map
if( ! states.empty() )
{
MapIterator siter = states.begin();
ItemDict* dict = new LinearDict;
ItemDict* initState = 0;
while ( siter.hasCurrent() )
{
const String* sname = *(String**) siter.currentKey();
const Map* sd = *(Map**) siter.currentValue();
ItemDict *sdict = new LinearDict(sd->size());
MapIterator fiter = sd->begin();
while( fiter.hasCurrent() )
{
const String* fname = *(String**) fiter.currentKey();
CoreFunc* sfunc = *(CoreFunc**) fiter.currentValue();
sdict->put(
new CoreString( *fname ), sfunc );
fiter.next();
}
delete sd;
// TODO: See if we can use the const String* form sd->name() here
dict->put( new CoreString( *sname ), new CoreDict(sdict) );
if( *sname == "init" )
initState = sdict;
siter.next();
}
cc->states( dict, initState );
}
// ok, now determine the default object factory, if not provided.
if( factory != 0 )
{
cc->factory( factory );
}
else
{
// use one of our standard factories.
if ( ! cc->properties().isReflective() )
{
// a standard falcon object
cc->factory( FalconObjectFactory );
}
else
{
if ( cc->properties().isStatic() )
{
// A fully reflective class.
cc->factory( ReflectFalconFactory );
}
else
{
// a partially reflective class.
cc->factory( CRFalconFactory );
}
}
}
return cc;
}
bool VMachine::linkSubClass( LiveModule *lmod, const Symbol *clssym,
Map &props, Map &states, ObjectFactory *factory )
{
// first sub-instantiates all the inheritances.
ClassDef *cd = clssym->getClassDef();
ListElement *from_iter = cd->inheritance().begin();
const Module *class_module = clssym->module();
// If the class is final, we're doomed, as this is called on subclasses
if( cd->isFinal() )
{
throw new CodeError( ErrorParam( e_final_inherit, clssym->declaredAt() ).origin( e_orig_vm ).
symbol( clssym->name() ).
module( class_module->name() ) );
}
if( *factory != 0 && cd->factory() != 0 )
{
// raise an error for duplicated object manager.
throw new CodeError( ErrorParam( e_inv_inherit2, clssym->declaredAt() ).origin( e_orig_vm ).
symbol( clssym->name() ).
module( class_module->name() )
);
}
ObjectFactory subFactory = 0;
while( from_iter != 0 )
{
const InheritDef *def = (const InheritDef *) from_iter->data();
const Symbol *parent = def->base();
// iterates in the parent. Where is it?
// 1) in the same module or 2) in the global modules.
if( parent->isClass() )
{
// do we have some circular inheritance
if ( parent->getClassDef()->checkCircularInheritance( clssym ) )
throw new CodeError( ErrorParam( e_circular_inh, __LINE__ )
.origin( e_orig_vm )
.extra( clssym->name() ) );
// we create the item anew instead of relying on the already linked item.
LiveModule *parmod = findModule( parent->module()->name() );
if ( ! linkSubClass( parmod, parent, props, states, &subFactory ) )
return false;
}
else if ( parent->isUndefined() )
{
// we have already linked the symbol for sure.
Item *icls = lmod->globals()[ parent->itemId() ].dereference();
if ( ! icls->isClass() )
{
throw new CodeError( ErrorParam( e_inv_inherit, clssym->declaredAt() ).origin( e_orig_vm ).
symbol( clssym->name() ).
module( class_module->name() )
);
}
parent = icls->asClass()->symbol();
if ( parent->getClassDef()->checkCircularInheritance( clssym ) )
throw new CodeError( ErrorParam( e_circular_inh, __LINE__ )
.origin( e_orig_vm )
.extra( clssym->name() ) );
LiveModule *parmod = findModule( parent->module()->name() );
if ( ! linkSubClass( parmod, parent, props, states, &subFactory ) )
return false;
}
else
{
throw new CodeError( ErrorParam( e_inv_inherit, clssym->declaredAt() ).origin( e_orig_vm ).
symbol( clssym->name() ).
module( class_module->name() ) );
}
from_iter = from_iter->next();
}
// assign our manager
if ( cd->factory() != 0 )
*factory = cd->factory();
else
*factory = subFactory;
// then copies the vardefs declared in this class.
MapIterator iter = cd->properties().begin();
while( iter.hasCurrent() )
{
String *key = *(String **) iter.currentKey();
VarDefMod *value = new VarDefMod;
value->vd = *(VarDef **) iter.currentValue();
value->lmod = lmod;
// TODO: define vardefvalue traits
VarDefMod **oldValue = (VarDefMod **) props.find( key );
if ( oldValue != 0 )
delete *oldValue;
//==========================
props.insert( key, value );
iter.next();
}
// and the same for the states.
MapIterator siter = cd->states().begin();
while( siter.hasCurrent() )
{
String *stateName = *(String **) siter.currentKey();
StateDef* sd = *(StateDef **) siter.currentValue();
Map* sfuncs = new Map( &traits::t_stringptr(), &traits::t_voidp() );
MapIterator fiter = sd->functions().begin();
while( fiter.hasCurrent() )
{
const String* fname = *(String**) fiter.currentKey();
const Symbol* fsym = *(Symbol**) fiter.currentValue();
CoreFunc* sfunc = new CoreFunc( fsym, lmod );
CoreFunc **oldFunc = (CoreFunc **) sfuncs->find( fname );
if ( oldFunc != 0 )
{
delete *oldFunc;
*oldFunc = sfunc;
}
else {
sfuncs->insert( fname, sfunc );
}
fiter.next();
}
//==========================
Map** oldFuncs =(Map**) states.find( stateName );
if( oldFuncs != 0 )
{
delete *oldFuncs;
*oldFuncs = sfuncs;
}
else
{
states.insert( stateName, sfuncs );
}
siter.next();
}
return true;
}
void VMachine::reset()
{
// first, the trivial resets.
// reset counters
resetCounters();
// clear the accounting of sleeping contexts.
m_sleepingContexts.clear();
if ( m_contexts.size() > 1 )
{
// clear the contexts
m_contexts.clear();
// as our frame, stack and tryframe were in one of the contexts,
// they have been destroyed.
m_currentContext = new VMContext;
// saving also the first context for accounting reasons.
m_contexts.pushBack( m_currentContext );
}
else
{
m_currentContext->resetFrames();
}
}
const SymModule *VMachine::findGlobalSymbol( const String &name ) const
{
return (SymModule *) m_globalSyms.find( &name );
}
bool VMachine::getCaller( const Symbol *&sym, const Module *&module)
{
StackFrame* frame = currentFrame();
if( frame == 0 || frame->m_module == 0 )
return false;
sym = frame->m_symbol;
module = frame->m_module->module();
return sym != 0 && module != 0;
}
bool VMachine::getCallerItem( Item &caller, uint32 level )
{
StackFrame* frame = currentFrame();
while( (frame != 0 && frame->m_symbol != 0 ) && level > 0 )
{
frame = frame->prev();
level--;
}
if ( frame == 0 || frame->m_symbol == 0 )
return false;
const Symbol* sym = frame->m_symbol;
const LiveModule* module = frame->m_module;
caller = module->globals()[ sym->itemId() ];
if ( ! caller.isFunction() )
return false;
// was it a method ?
if ( ! frame->m_self.isNil() )
{
caller.methodize( frame->m_self );
}
return true;
}
void VMachine::fillErrorContext( Error *err, bool filltb )
{
if( currentSymbol() != 0 )
{
if ( err->module().size() == 0 )
err->module( currentModule()->name() );
if ( err->symbol().size() == 0 )
err->symbol( currentSymbol()->name() );
if( currentSymbol()->isFunction() )
err->line( currentModule()->getLineAt( currentSymbol()->getFuncDef()->basePC() + programCounter() ) );
err->pcounter( programCounter() );
}
if ( filltb )
fillErrorTraceback( *err );
}
void VMachine::callFrameNow( ext_func_frame_t callbackFunc )
{
currentFrame()->m_endFrameFunc = callbackFunc;
switch( m_currentContext->pc() )
{
case i_pc_call_external_ctor:
m_currentContext->pc_next() = i_pc_call_external_ctor_return;
break;
case i_pc_call_external:
m_currentContext->pc_next() = i_pc_call_external_return;
break;
default:
m_currentContext->pc_next() = m_currentContext->pc();
}
}
void VMachine::callItemAtomic(const Item &callable, int32 paramCount )
{
bool oldAtomic = m_currentContext->atomicMode();
m_currentContext->atomicMode( true );
callFrame( callable, paramCount );
execFrame();
m_currentContext->atomicMode( oldAtomic );
}
void VMachine::yield( numeric secs )
{
if ( m_currentContext->atomicMode() )
{
throw new InterruptedError( ErrorParam( e_wait_in_atomic, __LINE__ )
.origin( e_orig_vm )
.symbol( "yield" )
.module( "core.vm" )
.hard() );
}
// be sure to allow yelding.
m_allowYield = true;
// a pure sleep time can never be < 0.
if( secs < 0.0 )
secs = 0.0;
m_currentContext->scheduleAfter( secs );
rotateContext();
}
void VMachine::putAtSleep( VMContext *ctx )
{
// consider the special case of a context not willing to be awaken
if( ctx->isWaitingForever() )
{
m_sleepingContexts.pushBack( ctx );
return;
}
ListElement *iter = m_sleepingContexts.begin();
while( iter != 0 ) {
VMContext *curctx = (VMContext *) iter->data();
if ( ctx->schedule() < curctx->schedule() || curctx->schedule() < 0.0 ) {
m_sleepingContexts.insertBefore( iter, ctx );
return;
}
iter = iter->next();
}
// can't find it anywhere?
m_sleepingContexts.pushBack( ctx );
}
void VMachine::reschedule( VMContext *ctx )
{
ListElement *iter = m_sleepingContexts.begin();
bool bPlaced = false;
bool bRemoved = false;
while( iter != 0 )
{
VMContext *curctx = (VMContext *) iter->data();
// if the rescheduled context is in sleeping context,
// signal we've found it.
if ( curctx == ctx )
{
ListElement *old = iter;
iter = iter->next();
m_sleepingContexts.erase( old );
// -- did we find the position where to place it, we did it all.
// -- go away.
if ( bPlaced )
return;
// but if item was not placed because it has an endless sleep, we have
// no gain in scanning more than this. So just place at the end
// (by breaking)
if( ctx->schedule() < 0.0 )
break;
// otherwise, continue working
bRemoved = true;
continue;
}
// avoid to place twice
if ( ! bPlaced &&
( ctx->schedule() < curctx->schedule() || curctx->schedule() < 0.0 )
)
{
m_sleepingContexts.insertBefore( iter, ctx );
// if we have also already removed the previous position, we did all
if( bRemoved )
return;
bPlaced = true;
}
iter = iter->next();
}
// can't find any place to store it?
if ( ! bPlaced )
m_sleepingContexts.pushBack( ctx );
}
void VMachine::rotateContext()
{
putAtSleep( m_currentContext );
electContext();
}
void VMachine::electContext()
{
// if there is some sleeping context...
if ( ! m_sleepingContexts.empty() )
{
bool bInterrupted = false;
while( true )
{
VMContext *elect = (VMContext *) m_sleepingContexts.front();
m_sleepingContexts.popFront();
// change the context to the first ready to run.
m_currentContext = elect;
// we must move to the next instruction after the context was swapped.
m_currentContext->pc() = m_currentContext->pc_next();
numeric tgtTime = elect->schedule();
// Is the most ready context willing to sleep?
if( tgtTime < 0.0 || (tgtTime -= Sys::_seconds()) > 0.0 )
{
// If we're here after being interrupted, it means we didn't find
// a suitable runnable context after an interruption.
/*if( bInterrupted )
{
// Then this is a real interruption, and we got to die.
throw new InterruptedError(
ErrorParam( e_interrupted ).origin( e_orig_vm ).
symbol( currentSymbol()->name() ).
module( currentModule()->name() )
);
}*/
// This may wait forever (with a tgtime < 0);
// in this case the function may throw a deadlock error
bInterrupted = replaceMe_onIdleTime( tgtTime );
// very probably, the context we selected is not ready to run.
// Try again selecting a new context that another thread may have
// inserted in the meanwhile.
if( bInterrupted )
{
putAtSleep( m_currentContext );
continue;
}
}
// tell the context that it is not waiting anymore, if it was.
m_currentContext->wakeup( false );
m_opCount = 0;
break;
}
}
}
void VMachine::terminateCurrentContext()
{
// don't destroy this context if it's the last one.
// inspectors outside this VM may want to check it.
if ( ! m_contexts.empty() && m_contexts.begin()->next() != 0 )
{
// scan the contexts and remove the current one.
ListElement *iter = m_contexts.begin();
while( iter != 0 ) {
if( iter->data() == m_currentContext ) {
m_contexts.erase( iter );
m_currentContext = 0;
break;
}
iter = iter->next();
}
// there must be something sleeping
fassert( ! m_sleepingContexts.empty() );
electContext();
}
else {
// we're done
throw VMEventQuit();
}
}
void VMachine::itemToString( String &target, const Item *itm, const String &format )
{
if( itm->isObject() )
{
Item propString;
if( itm->asObjectSafe()->getMethod( "toString", propString ) )
{
if ( propString.type() == FLC_ITEM_STRING )
target = *propString.asString();
else
{
Item old = self();
// eventually push parameters if format is required
int params = 0;
if( format.size() != 0 )
{
pushParam( new CoreString(format) );
params = 1;
}
// atomically call the item
callItemAtomic( propString, params );
self() = old;
// if regA is already a string, it's a quite light operation.
regA().toString( target );
}
}
else
itm->toString( target );
}
else
itm->toString( target );
}
bool VMachine::seekInteger( int64 value, byte *base, uint16 size, uint32 &landing ) const
{
#undef SEEK_STEP
#define SEEK_STEP (sizeof(int64) + sizeof(int32))
fassert( size > 0 ); // should be granted before call
int32 higher = size-1;
byte *pos;
int32 lower = 0;
int32 point = higher / 2;
while ( lower < higher - 1 )
{
pos = base + point * SEEK_STEP;
if ( loadInt64( pos ) == value )
{
landing = *reinterpret_cast< uint32 *>( pos + sizeof(int64) );
return true;
}
if ( value > loadInt64( pos ) )
lower = point;
else
higher = point;
point = ( lower + higher ) / 2;
}
// see if it was in the last loop
if ( loadInt64( base + lower * SEEK_STEP ) == value )
{
landing = *reinterpret_cast< uint32 *>( base + lower * SEEK_STEP + sizeof( int64 ) );
return true;
}
if ( lower != higher && loadInt64( base + higher * SEEK_STEP ) == value )
{
// YATTA, we found it at last
landing = *reinterpret_cast< uint32 *>( base + higher * SEEK_STEP + sizeof( int64 ) );
return true;
}
return false;
}
bool VMachine::seekInRange( int64 numLong, byte *base, uint16 size, uint32 &landing ) const
{
#undef SEEK_STEP
#define SEEK_STEP (sizeof(int32) + sizeof(int32) + sizeof(int32))
fassert( size > 0 ); // should be granted before call
int32 higher = size-1;
byte *pos;
int32 value = (int32) numLong;
int32 lower = 0;
int32 point = higher / 2;
while ( lower < higher - 1 )
{
pos = base + point * SEEK_STEP;
if ( *reinterpret_cast< int32 *>( pos ) <= value &&
*reinterpret_cast< int32 *>( pos + sizeof( int32 ) ) >= value)
{
landing = *reinterpret_cast< int32 *>( pos + sizeof( int32 ) + sizeof( int32 ) );
return true;
}
if ( value > *reinterpret_cast< int32 *>( pos ) )
lower = point;
else
higher = point;
point = ( lower + higher ) / 2;
}
// see if it was in the last loop
pos = base + lower * SEEK_STEP;
if ( *reinterpret_cast< int32 *>( pos ) <= value &&
*reinterpret_cast< int32 *>( pos + sizeof( int32 ) ) >= value )
{
landing = *reinterpret_cast< uint32 *>( pos + sizeof( int32 ) + sizeof( int32 ) );
return true;
}
if( lower != higher )
{
pos = base + higher * SEEK_STEP;
if ( *reinterpret_cast< int32 *>( pos ) <= value &&
*reinterpret_cast< int32 *>( pos + sizeof( int32 ) ) >= value )
{
// YATTA, we found it at last
landing = *reinterpret_cast< uint32 *>( pos + sizeof( int32 ) + sizeof( int32 ) );
return true;
}
}
return false;
}
bool VMachine::seekString( const String *value, byte *base, uint16 size, uint32 &landing ) const
{
#undef SEEK_STEP
#define SEEK_STEP (sizeof(int32) + sizeof(int32))
fassert( size > 0 ); // should be granted before call
int32 higher = size-1;
byte *pos;
int32 lower = 0;
int32 point = higher / 2;
const String *paragon;
while ( lower < higher - 1 )
{
pos = base + point * SEEK_STEP;
paragon = currentModule()->getString( *reinterpret_cast< int32 *>( pos ) );
fassert( paragon != 0 );
if ( paragon == 0 )
return false;
if ( *paragon == *value )
{
landing = *reinterpret_cast< int32 *>( pos + sizeof(int32) );
return true;
}
if ( *value > *paragon )
lower = point;
else
higher = point;
point = ( lower + higher ) / 2;
}
// see if it was in the last loop
paragon = currentModule()->getString( *reinterpret_cast< uint32 *>( base + lower * SEEK_STEP ) );
if ( paragon != 0 && *paragon == *value )
{
landing = *reinterpret_cast< uint32 *>( base + lower * SEEK_STEP + sizeof( int32 ) );
return true;
}
if ( lower != higher )
{
paragon = currentModule()->getString( *reinterpret_cast< uint32 *>( base + higher * SEEK_STEP ) );
if ( paragon != 0 && *paragon == *value )
{
// YATTA, we found it at last
landing = *reinterpret_cast< uint32 *>( base + higher * SEEK_STEP + sizeof( int32 ) );
return true;
}
}
return false;
}
bool VMachine::seekItem( const Item *item, byte *base, uint16 size, uint32 &landing )
{
#undef SEEK_STEP
#define SEEK_STEP (sizeof(int32) + sizeof(int32))
byte *target = base + size *SEEK_STEP;
while ( base < target )
{
Symbol *sym = currentModule()->getSymbol( *reinterpret_cast< int32 *>( base ) );
fassert( sym );
if ( sym == 0 )
return false;
switch( sym->type() )
{
case Symbol::tlocal:
if( *local( sym->itemId() )->dereference() == *item )
goto success;
break;
case Symbol::tparam:
if( *param( sym->itemId() )->dereference() == *item )
goto success;
break;
default:
if( *moduleItem( sym->itemId() ).dereference() == *item )
goto success;
}
base += SEEK_STEP;
}
return false;
success:
landing = *reinterpret_cast< uint32 *>( base + sizeof(int32) );
return true;
}
bool VMachine::seekItemClass( const Item *itm, byte *base, uint16 size, uint32 &landing ) const
{
#undef SEEK_STEP
#define SEEK_STEP (sizeof(int32) + sizeof(int32))
byte *target = base + size *SEEK_STEP;
while ( base < target )
{
Symbol *sym = currentModule()->getSymbol( *reinterpret_cast< uint32 *>( base ) );
fassert( sym );
if ( sym == 0 )
return false;
const Item *cfr;
if ( sym->isLocal() )
{
cfr = local( sym->itemId() )->dereference();
}
else if ( sym->isParam() )
{
cfr = param( sym->itemId() );
}
else
{
cfr = moduleItem( sym->itemId() ).dereference();
}
switch( cfr->type() )
{
case FLC_ITEM_CLASS:
if ( itm->isObject() )
{
const CoreObject *obj = itm->asObjectSafe();
if ( obj->derivedFrom( cfr->asClass()->symbol()->name() ) )
goto success;
}
else if (itm->isClass() && itm->asClass()->derivedFrom( cfr->asClass()->symbol() ) )
{
goto success;
}
break;
case FLC_ITEM_OBJECT:
if ( itm->isObject() )
{
if( itm->asObject() == cfr->asObjectSafe() )
goto success;
}
break;
case FLC_ITEM_INT:
if ( cfr->asInteger() == itm->type() )
{
goto success;
}
break;
case FLC_ITEM_STRING:
if ( itm->isObject() && itm->asObjectSafe()->derivedFrom( *cfr->asString() ) )
goto success;
break;
}
base += SEEK_STEP;
}
return false;
success:
landing = *reinterpret_cast< uint32 *>( base + sizeof(int32) );
return true;
}
void VMachine::publishService( Service *svr )
{
Service **srv = (Service **) m_services.find( &svr->getServiceName() );
if ( srv == 0 )
{
m_services.insert( &svr->getServiceName(), svr );
}
else {
throw new CodeError(
ErrorParam( e_service_adef ).origin( e_orig_vm ).
extra( svr->getServiceName() ).
symbol( "publishService" ).
module( "core.vm" ) );
}
}
Service *VMachine::getService( const String &name )
{
Service **srv = (Service **) m_services.find( &name );
if ( srv == 0 )
return 0;
return *srv;
}
void VMachine::stdIn( Stream *nstream )
{
delete m_stdIn;
m_stdIn = nstream;
}
void VMachine::stdOut( Stream *nstream )
{
delete m_stdOut;
m_stdOut = nstream;
}
void VMachine::stdErr( Stream *nstream )
{
delete m_stdErr;
m_stdErr = nstream;
}
void ContextList_deletor( void *data )
{
VMContext *vmc = (VMContext *) data;
delete vmc;
}
const String &VMachine::moduleString( uint32 stringId ) const
{
static String empty;
if ( currentModule() == 0 )
return empty;
const String *str = currentModule()->getString( stringId );
if( str != 0 )
return *str;
return empty;
}
void VMachine::resetCounters()
{
m_opCount = 0;
m_opNextGC = m_loopsGC;
m_opNextContext = m_loopsContext;
m_opNextCallback = m_loopsCallback;
m_opNextCheck = m_loopsGC < m_loopsContext ? m_loopsGC : m_loopsContext;
if ( m_opNextCallback != 0 && m_opNextCallback < m_opNextCheck )
{
m_opNextCheck = m_opNextCallback;
}
}
// basic implementation does nothing.
void VMachine::periodicCallback()
{}
// TODO move elsewhere
inline bool vmIsWhiteSpace( uint32 chr )
{
return chr == ' ' || chr == '\t' || chr == '\n' || chr == '\r';
}
inline bool vmIsTokenChr( uint32 chr )
{
return chr >= 'A' || (chr >= '0' && chr <= '9') || chr == '_';
}
Item *VMachine::findLocalSymbolItem( const String &symName ) const
{
// parse self and sender
if( symName == "self" )
{
return const_cast<Item *>(&self());
}
// find the symbol
const Symbol *sym = currentSymbol();
if ( sym != 0 )
{
// get the relevant symbol table.
const SymbolTable *symtab;
switch( sym->type() )
{
case Symbol::tclass:
symtab = &sym->getClassDef()->symtab();
break;
case Symbol::tfunc:
symtab = &sym->getFuncDef()->symtab();
break;
case Symbol::textfunc:
symtab = sym->getExtFuncDef()->parameters();
break;
default:
symtab = 0;
}
if ( symtab != 0 )
sym = symtab->findByName( symName );
else
sym = 0; // try again
}
// -- not a local symbol? -- try the global module table.
if( sym == 0 )
{
sym = currentModule()->findGlobalSymbol( symName );
// still zero? Let's try the global symbol table.
if( sym == 0 )
{
Item *itm = findGlobalItem( symName );
if ( itm != 0 )
return itm->dereference();
}
}
Item *itm = 0;
if ( sym != 0 )
{
if ( sym->isLocal() )
{
itm = const_cast<VMachine *>(this)->local( sym->getItemId() )->dereference();
}
else if ( sym->isParam() )
{
itm = const_cast<VMachine *>(this)->param( sym->getItemId() )->dereference();
}
else {
itm = const_cast<VMachine *>(this)->moduleItem( sym->getItemId() ).dereference();
}
}
// if the item is zero, we didn't found it
return itm;
}
bool VMachine::findLocalVariable( const String &name, Item &itm ) const
{
// item to be returned.
String sItemName;
uint32 squareLevel = 0;
uint32 len = name.length();
typedef enum {
initial,
firstToken,
interToken,
dotAccessor,
dotArrayAccessor,
dotDictAccessor,
squareAccessor,
postSquareAccessor,
singleQuote,
doubleQuote,
strEscapeSingle,
strEscapeDouble
} t_state;
t_state state = initial;
uint32 pos = 0;
while( pos <= len )
{
// little trick: force a ' ' at len
uint32 chr;
if( pos == len )
chr = ' ';
else
chr = name.getCharAt( pos );
switch( state )
{
case initial:
if( vmIsWhiteSpace( chr ) )
{
pos++;
continue;
}
if( chr < 'A' )
return false;
state = firstToken;
sItemName.append( chr );
break;
//===================================================
// Parse first token. It must be a valid local symbol
case firstToken:
if ( vmIsWhiteSpace( chr ) || chr == '.' || chr == '[' )
{
Item *lsi = findLocalSymbolItem( sItemName );
// item not found?
if( lsi == 0 )
return false;
itm = *lsi;
// set state accordingly to chr.
goto resetState;
}
else if ( vmIsTokenChr( chr ) )
{
sItemName.append( chr );
}
else {
// invalid format
return false;
}
break;
//===================================================
// Parse a dot accessor.
//
case dotAccessor:
// wating for a complete token.
if ( vmIsWhiteSpace( chr ) || chr == '.' || chr == '[' )
{
// ignore leading ws.
if( sItemName.size() == 0 && vmIsWhiteSpace( chr ) )
break;
// access the item. We know it's an object or class or we wouldn't be in this state.
// also, notice that we change the item itself.
Item prop;
if( itm.isClass() )
{
const Falcon::Item* requested = itm.asClass()->properties().getValue( sItemName );
if( requested == 0 )
return false;
prop = *requested;
}
else if ( !itm.asObjectSafe()->getProperty( sItemName, prop ) )
return false;
prop.methodize( itm );
itm = prop;
// set state accordingly to chr.
goto resetState;
}
else if ( vmIsTokenChr( chr ) )
{
sItemName.append( chr );
}
else
return false;
break;
case dotArrayAccessor:
// wating for a complete token.
if ( vmIsWhiteSpace( chr ) || chr == '.' || chr == '[' )
{
// ignore leading ws.
if( sItemName.size() == 0 && vmIsWhiteSpace( chr ) )
break;
// access the item. We know it's an object or we wouldn't be in this state.
// also, notice that we change the item itself.
Item *tmp;
if ( ( tmp = itm.asArray()->getProperty( sItemName ) ) == 0 )
return false;
if ( tmp->isFunction() )
tmp->setMethod( itm, tmp->asFunction() );
itm = *tmp;
// set state accordingly to chr.
goto resetState;
}
else if ( vmIsTokenChr( chr ) )
{
sItemName.append( chr );
}
else
return false;
break;
case dotDictAccessor:
// wating for a complete token.
if ( vmIsWhiteSpace( chr ) || chr == '.' || chr == '[' )
{
// ignore leading ws.
if( sItemName.size() == 0 && vmIsWhiteSpace( chr ) )
break;
// access the item. We know it's an object or we wouldn't be in this state.
// also, notice that we change the item itself.
Item *tmp;
if ( ( tmp = itm.asDict()->find( sItemName ) ) == 0 )
return false;
if ( tmp->isFunction() )
tmp->setMethod( itm, tmp->asFunction() );
itm = *tmp;
// set state accordingly to chr.
goto resetState;
}
else if ( vmIsTokenChr( chr ) )
{
sItemName.append( chr );
}
else
return false;
break;
//===================================================
// Parse the square accessor; from [ to matching ]
case squareAccessor:
// wating for complete square token.
switch( chr )
{
case '[':
squareLevel++;
sItemName.append( chr );
break;
case ']':
if( --squareLevel == 0 )
{
Item *lsi = parseSquareAccessor( itm, sItemName );
if( lsi == 0 )
return false;
itm = *lsi;
goto resetState;
}
else
sItemName.append( chr );
break;
case '\'':
sItemName.append( chr );
state = singleQuote;
break;
case '"':
sItemName.append( chr );
state = doubleQuote;
break;
default:
sItemName.append( chr );
}
break;
case postSquareAccessor:
// wating for complete square token.
if( chr == ']' )
{
if( --squareLevel == 0 )
{
Item *lsi = parseSquareAccessor( itm, sItemName );
if( lsi == 0 )
return false;
itm = *lsi;
goto resetState;
}
else
sItemName.append( chr );
}
else if( ! vmIsWhiteSpace( chr ) )
{
return false;
}
break;
//===================================================
// Parse the double quote inside suqare accessor
case doubleQuote:
switch( chr )
{
case '\\': state = strEscapeDouble; break;
case '"': state = postSquareAccessor; // do not break
default:
sItemName.append( chr );
}
break;
//===================================================
// Parse the single quote inside suqare accessor
case singleQuote:
switch( chr )
{
case '\\': state = strEscapeSingle; break;
case '\'': state = squareAccessor; // do not break
default:
sItemName.append( chr );
}
break;
//===================================================
// Parse the double quote inside suqare accessor
case strEscapeDouble:
sItemName.append( chr );
state = doubleQuote;
break;
//===================================================
// Parse the single quote inside suqare accessor
case strEscapeSingle:
sItemName.append( chr );
state = singleQuote;
break;
//===================================================
// Parse the space between tokens.
case interToken:
switch( chr ) {
case '.':
if( itm.isObject() )
state = dotAccessor;
else if( itm.isArray() )
state = dotArrayAccessor;
else if( itm.isDict() && itm.asDict()->isBlessed() )
state = dotDictAccessor;
else
return false;
break;
case '[':
if( ! itm.isDict() && ! itm.isArray() )
return false;
state = squareAccessor;
squareLevel = 1;
break;
default:
if( ! vmIsWhiteSpace( chr ) )
return false;
}
break;
}
// end the loop here
pos++;
continue;
// state reset area.
resetState:
sItemName.size(0); // clear sItemName.
switch( chr ) {
case '.':
if( itm.isObject() || itm.isClass() )
state = dotAccessor;
else if ( itm.isArray() )
state = dotArrayAccessor;
else if ( itm.isDict() && itm.asDict()->isBlessed() )
state = dotDictAccessor;
else
return false;
break;
case '[':
if( ! itm.isDict() && ! itm.isArray() )
return false;
state = squareAccessor;
squareLevel = 1;
break;
default:
state = interToken;
}
// end of loop, increment pos.
pos++;
}
// if the state is not "interToken" we have an incomplete parse
if( state != interToken )
return false;
// Success
return true;
}
Item *VMachine::parseSquareAccessor( const Item &accessed, String &accessor ) const
{
accessor.trim();
// empty accessor? -- can't access!
if( accessor.length() == 0)
return 0;
// what's the first character of the accessor?
uint32 firstChar = accessor.getCharAt( 0 );
// parse the accessor.
Item acc;
String da;
if( firstChar >= '0' && firstChar <= '9' )
{
// try to parse a number.
int64 num;
if( accessor.parseInt( num ) )
acc.setInteger( num );
else
return 0;
}
else if( firstChar == '\'' || firstChar == '"' )
{
// arrays cannot be accessed by strings.
if( accessed.isArray() )
return 0;
da = accessor.subString( 1, accessor.length() - 1 );
acc.setString( &da );
}
else {
// reparse the accessor as a token
if( ! findLocalVariable( accessor, acc ) )
return 0;
}
// what's the accessed item?
if ( accessed.isDict() )
{
// find the accessor
return accessed.asDict()->find( acc );
}
else if( accessed.isArray() )
{
// for arrays, only nubmbers and reaccessed items are
if( !acc.isOrdinal() )
return 0;
uint32 pos = (uint32) acc.forceInteger();
if( pos >= accessed.asArray()->length() )
return 0;
return &accessed.asArray()->at( pos );
}
return 0;
}
VMachine::returnCode VMachine::expandString( const String &src, String &target )
{
uint32 pos0 = 0;
uint32 pos1 = src.find( "$" );
uint32 len = src.length();
while( pos1 != String::npos )
{
target.append( src.subString( pos0, pos1 ) );
pos1++;
if( pos1 == len )
{
return return_error_string;
}
typedef enum {
none,
token,
open,
singleQuote,
doubleQuote,
escapeSingle,
escapeDouble,
complete,
complete1,
noAction,
fail
}
t_state;
t_state state = none;
pos0 = pos1;
uint32 chr = 0;
while( pos1 < len && state != fail && state != complete && state != complete1 && state != noAction )
{
chr = src.getCharAt( pos1 );
switch( state )
{
case none:
if( chr == '$' )
{
target.append( '$' );
state = noAction;
break;
}
else if ( chr == '(' )
{
// scan for balanced ')'
pos0 = pos1+1;
state = open;
}
else if ( chr < '@' )
{
state = fail;
}
else {
state = token;
}
break;
case token:
// allow also ':' and '|'
if( (( chr < '0' && chr != '.' && chr != '%' ) || ( chr > ':' && chr <= '@' ))
&& chr != '|' && chr != '[' && chr != ']' )
{
state = complete;
pos1--;
// else we do this below.
}
break;
case open:
if( chr == ')' )
state = complete1;
else if ( chr == '\'' )
state = singleQuote;
else if ( chr == '\"' )
state = doubleQuote;
// else just continue
break;
case singleQuote:
if( chr == '\'' )
state = open;
else if ( chr == '\\' )
state = escapeSingle;
// else just continue
break;
case doubleQuote:
if( chr == '\"' )
state = open;
else if ( chr == '\\' )
state = escapeDouble;
// else just continue
break;
case escapeSingle:
state = singleQuote;
break;
case escapeDouble:
state = escapeDouble;
break;
default: // compiler warning no-op
break;
}
++pos1;
}
// parse the result in to the target.
switch( state )
{
case token:
case complete:
case complete1:
{
uint32 pos2 = pos1;
if( state == complete1 )
{
pos2--;
}
// todo: record this while scanning
uint32 posColon = src.find( ":", pos0, pos2 );
uint32 posPipe = src.find( "|", pos0, pos2 );
uint32 posEnd;
Item itm;
if( posColon != String::npos ) {
posEnd = posColon;
}
else if( posPipe != String::npos )
{
posEnd = posPipe;
}
else {
posEnd = pos2;
}
if ( ! findLocalVariable( src.subString( pos0, posEnd ), itm ) )
{
return return_error_parse;
}
String temp;
// do we have a format?
if( posColon != String::npos )
{
Format fmt( src.subString( posColon+1, pos2 ) );
if( ! fmt.isValid() )
{
return return_error_parse_fmt;
}
if( ! fmt.format( this, *itm.dereference(), temp ) ) {
return return_error_parse_fmt;
}
}
// do we have a toString parameter?
else if( posPipe != String::npos )
{
itemToString( temp, &itm, src.subString( posPipe+1, pos2 ) );
}
else {
// otherwise, add the toString version (todo format)
// append to target.
itemToString( temp, &itm );
}
target.append( temp );
}
break;
case noAction:
break;
default:
return return_error_string;
}
pos0 = pos1;
pos1 = src.find( "$", pos1 );
}
// add the last segment
if( pos0 != pos1 )
{
target.append( src.subString( pos0, pos1 ) );
}
return return_ok;
}
void VMachine::referenceItem( Item &target, Item &source )
{
if( source.isReference() ) {
target.setReference( source.asReference() );
}
else {
GarbageItem *itm = new GarbageItem( source );
source.setReference( itm );
target.setReference( itm );
}
}
static bool vm_func_eval( VMachine *vm )
{
CoreArray *arr = vm->local( 0 )->asArray();
uint32 count = (uint32) vm->local( 1 )->asInteger();
// interrupt functional sequence request?
if ( vm->regA().isOob() && vm->regA().isInteger() )
{
int64 val = vm->regA().asInteger();
if ( val == 1 || val == 0 )
return false;
}
// let's push other function's return value
if ( vm->regA().isLBind() )
{
if ( vm->regA().isFutureBind() )
{
vm->regBind().flagsOn( 0xF0 );
}
else {
String *binding = vm->regA().asLBind();
Item *bind = vm->getBinding( *binding );
if ( bind == 0 )
{
vm->regA().setReference( new GarbageItem( Item() ) );
vm->setBinding( *binding, vm->regA() );
}
else {
//fassert( bind->isReference() );
vm->regA() = *bind;
}
}
}
vm->pushParam( vm->regA() );
// fake a call return
while ( count < arr->length() )
{
*vm->local( 1 ) = (int64) count+1;
if ( vm->functionalEval( arr->at(count) ) )
{
return true;
}
vm->pushParam( vm->regA() );
++count;
}
// done? -- have we to perform a last reduction call?
if( count > 0 && vm->local( 2 )->isCallable() )
{
vm->returnHandler(0);
vm->callFrame( *vm->local( 2 ), count - 1 );
return true;
}
// if the first element is not callable, generate an array
CoreArray *array = new CoreArray( count );
Item *data = array->items().elements();
int32 base = vm->stack().length() - count;
memcpy( data, &vm->stack()[base],array->items().esize( count ) );
array->length( count );
vm->regA() = array;
vm->stack().resize( base );
return false;
}
bool VMachine::functionalEval( const Item &itm, uint32 paramCount, bool retArray )
{
// An array
switch( itm.type() )
{
case FLC_ITEM_ARRAY:
{
CoreArray *arr = itm.asArray();
// prepare for parametric evaluation
for( uint32 pi = 1; pi <= paramCount; ++pi )
{
String s;
s.writeNumber( (int64) pi );
arr->setProperty(s, stack()[ stack().length() - pi] );
}
createFrame(0);
if ( regBind().isNil() )
regBind() = arr->makeBindings();
// great. Then recursively evaluate the parameters.
uint32 count = arr->length();
if ( count > 0 )
{
// if the first element is an ETA function, just call it as frame and return.
if ( (*arr)[0].isFunction() && (*arr)[0].asFunction()->symbol()->isEta() )
{
callFrame( arr, 0 );
return true;
}
// create two locals; we may need it
addLocals( 2 );
// time to install our handleres
returnHandler( vm_func_eval );
*local(0) = itm;
*local(1) = (int64)0;
for ( uint32 l = 0; l < count; l ++ )
{
const Item &citem = (*arr)[l];
*local(1) = (int64)l+1;
if ( functionalEval( citem ) )
{
return true;
}
if ( regA().isFutureBind() )
{
// with this marker, the next call operation will search its parameters.
// Let's consider this a temporary (but legitimate) hack.
regBind().flags( 0xF0 );
}
pushParam( regA() );
}
// we got nowere to go
returnHandler( 0 );
// is there anything to call? -- is the first element an atom?
// local 2 is the first element we have pushed
if( local(2)->isCallable() )
{
callFrame( *local(2), count-1 );
return true;
}
}
// if the first element is not callable, generate an array
if( retArray )
{
CoreArray *array = new CoreArray( count );
Item *data = array->items().elements();
int32 base = stack().length() - count;
memcpy( data, &stack()[base], array->items().esize( count ) );
array->length( count );
regA() = array;
}
else {
regA().setNil();
}
callReturn();
}
break;
case FLC_ITEM_LBIND:
if ( ! itm.isFutureBind() )
{
if ( regBind().isDict() )
{
Item *bind = getBinding( *itm.asLBind() );
if ( bind == 0 )
{
regA().setReference( new GarbageItem( Item() ) );
setBinding( *itm.asLBind(), regA() );
}
else {
//fassert( bind->isReference() );
regA() = *bind;
}
}
else
regA().setNil();
break;
}
// fallback
default:
regA() = itm;
}
return false;
}
Item *VMachine::findGlobalItem( const String &name ) const
{
const SymModule *sm = findGlobalSymbol( name );
if ( sm == 0 ) return 0;
return sm->item()->dereference();
}
LiveModule *VMachine::findModule( const String &name )
{
LiveModule **lm =(LiveModule **) m_liveModules.find( &name );
if ( lm != 0 )
return *lm;
return 0;
}
Item *VMachine::findWKI( const String &name ) const
{
const SymModule *sm = (SymModule *) m_wellKnownSyms.find( &name );
if ( sm == 0 ) return 0;
return &sm->liveModule()->wkitems()[ sm->wkiid() ];
}
bool VMachine::unlink( const Runtime *rt )
{
for( uint32 iter = 0; iter < rt->moduleVector()->size(); ++iter )
{
if (! unlink( rt->moduleVector()->moduleAt( iter ) ) )
return false;
}
return true;
}
bool VMachine::unlink( const Module *module )
{
MapIterator iter;
if ( !m_liveModules.find( &module->name(), iter ) )
return false;
// get the thing
LiveModule *lm = *(LiveModule **) iter.currentValue();
// ensure this module is not the active one
if ( currentLiveModule() == lm )
{
return false;
}
// delete all the exported and well known symbols
MapIterator stiter = lm->module()->symbolTable().map().begin();
while( stiter.hasCurrent() )
{
Symbol *sym = *(Symbol **) stiter.currentValue();
if ( sym->isWKS() )
m_wellKnownSyms.erase( &sym->name() );
else if ( sym->exported() )
m_globalSyms.erase( &sym->name() );
stiter.next();
}
// delete the iterator from the map
m_liveModules.erase( iter );
//detach the object, so it becomes an invalid callable reference
lm->detachModule();
// delete the key, which will detach the module, if found.
return true;
}
bool VMachine::interrupted( bool raise, bool reset, bool dontCheck )
{
if( dontCheck || m_systemData.interrupted() )
{
if( reset )
m_systemData.resetInterrupt();
if ( raise )
{
uint32 line = currentSymbol()->isFunction() ?
currentModule()->getLineAt( currentSymbol()->getFuncDef()->basePC() + programCounter() )
: 0;
throw new InterruptedError(
ErrorParam( e_interrupted ).origin( e_orig_vm ).
symbol( currentSymbol()->name() ).
module( currentModule()->name() ).
line( line ) );
}
return true;
}
return false;
}
Item *VMachine::getBinding( const String &bind ) const
{
if ( ! regBind().isDict() )
return 0;
return regBind().asDict()->find( bind );
}
Item *VMachine::getSafeBinding( const String &bind )
{
if ( ! regBind().isDict() )
return 0;
Item *found = regBind().asDict()->find( bind );
if ( found == 0 )
{
regBind().asDict()->put( new CoreString( bind ), Item() );
found = regBind().asDict()->find( bind );
found->setReference( new GarbageItem( Item() ) );
}
return found;
}
bool VMachine::setBinding( const String &bind, const Item &value )
{
if ( ! regBind().isDict() )
return false;
regBind().asDict()->put( new CoreString(bind), value );
return true;
}
CoreSlot* VMachine::getSlot( const String& slotName, bool create )
{
m_slot_mtx.lock();
MapIterator iter;
if ( ! m_slots.find( &slotName, iter ) )
{
if ( create )
{
CoreSlot* cs = new CoreSlot( slotName );
m_slots.insert( &slotName, cs );
m_slot_mtx.unlock();
return cs;
}
m_slot_mtx.unlock();
return 0;
}
// get the thing
CoreSlot *cs = *(CoreSlot **) iter.currentValue();
m_slot_mtx.unlock();
return cs;
}
void VMachine::removeSlot( const String& slotName )
{
MapIterator iter;
m_slot_mtx.lock();
if ( m_slots.find( &slotName, iter ) )
{
m_slots.erase( iter );
// erase will decrefc, because of item traits in m_slots
}
m_slot_mtx.unlock();
}
void VMachine::markSlots( uint32 mark )
{
MapIterator iter = m_slots.begin();
m_slot_mtx.lock();
while( iter.hasCurrent() )
{
(*(CoreSlot**) iter.currentValue() )->gcMark( mark );
iter.next();
}
m_slot_mtx.unlock();
}
bool VMachine::consumeSignal()
{
StackFrame* frame = currentFrame();
while( frame != 0 )
{
if( frame->m_endFrameFunc == coreslot_broadcast_internal )
{
frame->m_endFrameFunc = 0;
const Item& msgItem = frame->localItem(4); // local(4)
if( msgItem.isInteger() )
{
VMMessage* msg = (VMMessage*) msgItem.asInteger();
msg->onMsgComplete( true );
delete msg;
}
return true;
}
frame = frame->prev();
}
return false;
}
void VMachine::gcEnable( bool mode )
{
m_bGcEnabled = mode;
}
bool VMachine::isGcEnabled() const
{
return m_bGcEnabled;
}
VMContext* VMachine::coPrepare( int32 pSize )
{
// create a new context
VMContext *ctx = new VMContext( *m_currentContext );
// if there are some parameters...
if ( pSize > 0 )
{
// avoid reallocation afterwards.
ctx->stack().reserve( pSize );
// copy flat
for( int32 i = 0; i < pSize; i++ )
{
ctx->stack().append( stack()[ stack().length() - pSize + i ] );
}
stack().resize( stack().length() - pSize );
}
// rotate the context
m_contexts.pushBack( ctx );
return ctx;
}
bool VMachine::callCoroFrame( const Item &callable, int32 pSize )
{
if ( ! callable.isCallable() )
return false;
// rotate the context
putAtSleep( m_currentContext );
m_currentContext = coPrepare( pSize );
// fake the frame as a pure return value; this will force this coroutine to terminate
// without peeking any code in the module.
m_currentContext->pc_next() = i_pc_call_external_return;
callFrame( callable, pSize );
return true;
}
//=====================================================================================
// messages
//
void VMachine::postMessage( VMMessage *msg )
{
// ok, we can't do it now; post the message
m_mtx_mesasges.lock();
if ( m_msg_head == 0 )
{
m_msg_head = msg;
}
else {
m_msg_tail->append( msg );
}
// reach the end of the msg list and set the new tail
while( msg->next() != 0 )
msg = msg->next();
m_msg_tail = msg;
// also, ask for early checks.
// We're really not concerned about spurious reads here or in the other thread,
// everything would be ok even without this operation. It's just ok if some of
// the two threads sync on this asap.
m_opNextCheck = m_opCount;
m_mtx_mesasges.unlock();
// can we process the message now?
if( m_baton.tryAcquire() )
{
// this doesn't actually process data,
// it just prepares coroutines to process them. -- so it can't throw.
processPendingMessages();
m_baton.release();
// wake up the vm, if it was sleeping.
m_systemData.interrupt();
}
}
void VMachine::processMessage( VMMessage *msg )
{
// find the slot
CoreSlot* slot = getSlot( msg->name(), false );
if ( slot == 0 || slot->empty() )
{
msg->onMsgComplete( false );
delete msg;
return;
}
// create the coroutine, whose first operation will be
// to call our external return frame.
VMContext* sleepCtx = coPrepare(0);
// force the sleeping context to call the return frame immediately
sleepCtx->pc_next() = i_pc_call_external_return;
sleepCtx->pc() = i_pc_call_external_return;
// prepare the broadcast in the frame.
slot->prepareBroadcast( sleepCtx, 0, 0, msg );
// force immediate context rotation
/* putAtSleep( m_currentContext );
m_currentContext = sleepCtx;*/
putAtSleep( sleepCtx );
}
void VMachine::performGC( bool bWaitForCollect )
{
m_bWaitForCollect = bWaitForCollect;
memPool->idleVM( this, true );
m_eGCPerformed.wait();
}
void VMachine::prepareFrame( CoreFunc* target, uint32 paramCount )
{
// eventually check for named parameters
if ( this->regBind().flags() == 0xF0 )
{
const SymbolTable *symtab;
if( target->symbol()->isFunction() )
symtab = &target->symbol()->getFuncDef()->symtab();
else
symtab = target->symbol()->getExtFuncDef()->parameters();
this->regBind().flags(0);
// We know we have (probably) a named parameter.
uint32 size = this->stack().length();
uint32 paramBase = size - paramCount;
ItemArray iv(8);
uint32 pid = 0;
// first step; identify future binds and pack parameters.
while( paramBase+pid < size )
{
Item &item = this->stack()[ paramBase+pid ];
if ( item.isFutureBind() )
{
// we must move the parameter into the right position
iv.append( item );
for( uint32 pos = paramBase + pid + 1; pos < size; pos ++ )
{
this->stack()[ pos - 1 ] = this->stack()[ pos ];
}
this->stack()[ size-1 ].setNil();
size--;
paramCount--;
}
else
pid++;
}
this->stack().resize( size );
// second step: apply future binds.
for( uint32 i = 0; i < iv.length(); i ++ )
{
Item &item = iv[i];
// try to find the parameter
const String *pname = item.asLBind();
Symbol *param = symtab == 0 ? 0 : symtab->findByName( *pname );
if ( param == 0 || ! param->isParam( ) ) {
throw new CodeError( ErrorParam( e_undef_param, __LINE__ ).extra(*pname) );
}
// place it in the stack; if the stack is not big enough, resize it.
if ( this->stack().length() <= param->itemId() + paramBase )
{
paramCount = param->itemId()+1;
this->stack().resize( paramCount + paramBase );
}
this->stack()[ param->itemId() + paramBase ] = item.asFBind()->origin();
}
}
// ensure against optional parameters.
if( target->symbol()->isFunction() )
{
FuncDef *tg_def = target->symbol()->getFuncDef();
if( paramCount < tg_def->params() )
{
this->stack().resize( this->stack().length() + tg_def->params() - paramCount );
paramCount = tg_def->params();
}
this->createFrame( paramCount );
// space for locals
if ( tg_def->locals() > 0 )
{
this->currentFrame()->resizeStack( tg_def->locals() );
// are part of this locals closed?
if( target->closure() != 0 ) {
fassert( target->closure()->length() <= tg_def->locals() );
this->stack().copyOnto( 0, *target->closure() );
}
}
this->m_currentContext->lmodule( target->liveModule() );
this->m_currentContext->symbol( target->symbol() );
//jump
this->m_currentContext->pc_next() = 0;
}
else
{
this->createFrame( paramCount );
// so we can have adequate tracebacks.
this->m_currentContext->lmodule( target->liveModule() );
this->m_currentContext->symbol( target->symbol() );
this->m_currentContext->pc_next() = VMachine::i_pc_call_external;
}
}
void VMachine::prepareFrame( CoreArray* arr, uint32 paramCount )
{
fassert( arr->length() > 0 && arr->at(0).isCallable() );
Item& carr = (*arr)[0];
uint32 arraySize = arr->length();
uint32 sizeNow = this->stack().length();
CoreDict* bindings = arr->bindings();
bool hasFuture = false;
// move parameters beyond array parameters
arraySize -- ; // first element is the callable item.
if ( arraySize > 0 )
{
// first array element is the called item.
this->stack().resize( sizeNow + arraySize );
sizeNow -= paramCount;
for ( uint32 j = sizeNow + paramCount; j > sizeNow; j -- )
{
this->stack()[ j-1 + arraySize ] = this->stack()[ j-1 ];
}
// push array paramers
for ( uint32 i = 0; i < arraySize; i ++ )
{
Item &itm = (*arr)[i + 1];
if( itm.isLBind() )
{
if ( itm.asFBind() == 0 )
{
if ( this->regBind().isNil() && bindings == 0 )
{
// we must create bindings for this array.
bindings = arr->makeBindings();
}
if ( bindings != 0 )
{
// have we got this binding?
Item *bound = bindings->find( *itm.asLBind() );
if ( ! bound )
{
arr->setProperty( *itm.asLBind(), Item() );
bound = bindings->find( *itm.asLBind() );
}
this->stack()[ i + sizeNow ] = *bound;
}
else
{
// fall back to currently provided bindings
this->stack()[ i + sizeNow ] = *this->getSafeBinding( *itm.asLBind() );
}
}
else {
// treat as a future binding
hasFuture = true;
this->stack()[ i + sizeNow ] = itm;
}
}
else {
// just transfer the parameters
this->stack()[ i + sizeNow ] = itm;
}
}
}
// inform the called about future state
if( hasFuture )
this->regBind().flagsOn( 0xF0 );
carr.readyFrame( this, arraySize + paramCount );
// change the bindings now, before the VM runs this frame.
if ( this->regBind().isNil() && arr->bindings() != 0 )
{
this->regBind() = arr->bindings();
}
}
uint32 VMachine::generation() const
{
return m_generation;
}
void VMachine::setupScript( int argc, char** argv )
{
if ( m_mainModule != 0 )
{
Item *scriptName = findGlobalItem( "scriptName" );
if ( scriptName != 0 )
*scriptName = new CoreString( m_mainModule->module()->name() );
Item *scriptPath = findGlobalItem( "scriptPath" );
if ( scriptPath != 0 )
*scriptPath = new Falcon::CoreString( m_mainModule->module()->name() );
}
Falcon::Item *args = findGlobalItem( "args" );
if ( args != 0 )
{
// create the arguments.
// It is correct to pass an empty array if we haven't any argument to pass.
Falcon::CoreArray *argsArray = new Falcon::CoreArray;
for( int i = 0; i < argc; i ++ )
{
argsArray->append( new Falcon::CoreString( argv[i] ) );
}
*args = argsArray;
}
}
void VMachine::onIdleTime( numeric seconds )
{
}
bool VMachine::replaceMe_onIdleTime( numeric seconds )
{
if ( seconds < 0.0 )
{
throw new CodeError(
ErrorParam( e_deadlock ).origin( e_orig_vm ).
symbol( currentSymbol()->name() ).
module( currentModule()->name() )
);
}
idle();
bool complete = m_systemData.sleep( seconds );
unidle();
if ( ! complete )
{
m_systemData.resetInterrupt();
return true;
}
return false;
}
void VMachine::handleRaisedItem( Item& value )
{
Error* err = 0;
if ( value.isObject() && value.isOfClass( "Error" ) )
{
err = static_cast<core::ErrorObject *>(value.asObjectSafe())->getError();
if( ! err->hasTraceback() )
fillErrorContext(err, true);
}
// can someone get it?
if( currentContext()->tryFrame() == 0 ) // uncaught error raised from scripts...
{
// create the error that the external application will see.
if ( err != 0 )
{
// in case of an error of class Error, we have already a good error inside of it.
err->incref();
}
else {
// else incapsulate the item in an error.
err = new GenericError( ErrorParam( e_uncaught ).origin( e_orig_vm ) );
err->raised( value );
}
throw err;
}
// Enter the stack frame that should handle the error (or raise to the top if uncaught)
while( currentFrame()->m_try_base == i_noTryFrame )
{
// neutralize post-processors
// currentFrame()->m_endFrameFunc = 0; -- done by currentContext()->callReturn();
m_break = currentContext()->callReturn();
// let the VM deal with returns
if ( m_break )
{
m_break = false;
throw value;
}
}
regB() = value;
// We are in the frame that should handle the error, in one way or another
// should we catch it?
popTry( true );
}
void VMachine::handleRaisedError( Error* err )
{
if( ! err->hasTraceback() )
fillErrorContext( err, true );
// catch it if possible
if( err->catchable() && currentContext()->tryFrame() != 0 )
{
// Enter the stack frame that should handle the error (or raise to the top if uncaught)
while( currentFrame() != currentContext()->tryFrame() )
{
// neutralize post-processors
// currentFrame()->m_endFrameFunc = 0; -- done by currentFrame()->callReturn();
m_break = currentContext()->callReturn();
// let the VM deal with returns
if ( m_break )
{
m_break = false;
throw err;
}
}
CoreObject *obj = err->scriptize( this );
if ( obj != 0 )
{
err->decref();
regB() = obj;
// We are in the frame that should handle the error, in one way or another
// should we catch it?
popTry( true );
}
else {
// Panic. Should not happen -- scriptize has raised a symbol not found error
// describing the missing error class; we must tell the user so that the module
// not declaring the correct error class, or failing to export it, can be
// fixed.
fassert( false );
throw err;
}
}
// we couldn't catch the error (this also means we're at stackBase() zero)
// we should handle it then exit
else {
// we should manage the error; if we're here, stackBase() is zero,
// so we are the last in charge
throw err;
}
}
void VMachine::periodicChecks()
{
// pulse VM idle
if( m_bGcEnabled )
m_baton.checkBlock();
if ( m_opLimit > 0 )
{
// Bail out???
if ( m_opCount > m_opLimit )
return;
else
if ( m_opNextCheck > m_opLimit )
m_opNextCheck = m_opLimit;
}
if( ! m_currentContext->atomicMode() )
{
if( m_allowYield && ! m_sleepingContexts.empty() && m_opCount > m_opNextContext ) {
rotateContext();
m_opNextContext = m_opCount + m_loopsContext;
if( m_opNextContext < m_opNextCheck )
m_opNextCheck = m_opNextContext;
}
// Periodic Callback
if( m_loopsCallback > 0 && m_opCount > m_opNextCallback )
{
periodicCallback();
m_opNextCallback = m_opCount + m_loopsCallback;
if( m_opNextCallback < m_opNextCheck )
m_opNextCheck = m_opNextCallback;
}
// in case of single step:
if( m_bSingleStep )
{
// stop also next op
m_opNextCheck = m_opCount + 1;
return; // maintain the event we have, but exit now.
}
// perform messages
processPendingMessages();
}
}
void VMachine::processPendingMessages()
{
m_mtx_mesasges.lock();
while( m_msg_head != 0 )
{
VMMessage* msg = m_msg_head;
m_msg_head = msg->next();
if( m_msg_head == 0 )
m_msg_tail = 0;
// it is ok if m_msg_tail is left dangling.
m_mtx_mesasges.unlock();
processMessage( msg ); // do not delete msg
m_mtx_mesasges.lock();
}
m_mtx_mesasges.unlock();
}
void VMachine::raiseHardError( int code, const String &expl, int32 line )
{
Error *err = new CodeError(
ErrorParam( code, line ).origin( e_orig_vm )
.hard()
.extra( expl )
);
// of course, if we're not executing, there nothing to raise
if( currentSymbol() != 0 )
{
fillErrorContext( err );
}
throw err;
}
void VMachine::launch( const String &startSym, uint32 paramCount )
{
Item* lItem = 0;
if( m_mainModule != 0 ) {
lItem = m_mainModule->findModuleItem( startSym );
}
if ( lItem == 0 )
{
lItem = findGlobalItem( startSym );
if( lItem == 0 ) {
throw new CodeError(
ErrorParam( e_undef_sym, __LINE__ ).origin( e_orig_vm ).extra( startSym ).
symbol( "launch" ).
module( "core.vm" ) );
}
}
/** \todo allow to call classes at startup. Something like "all-classes" a-la-java */
if ( ! lItem->isCallable() ) {
throw new CodeError(
ErrorParam( e_non_callable, __LINE__ ).origin( e_orig_vm ).
extra( startSym ).
symbol( "launch" ).
module( "core.vm" ) );
}
// be sure to pass a clean env.
try
{
reset();
callItem( *lItem, paramCount );
}
catch( VMEventQuit& )
{
}
}
void VMachine::bindItem( const String& name, const Item &tgt )
{
if ( ! regBind().isDict() )
{
regBind() = new CoreDict(new LinearDict() );
}
CoreDict* cd = regBind().asDict();
cd->put( Item( new CoreString( name ) ), tgt );
}
void VMachine::unbindItem( const String& name, Item &tgt ) const
{
fassert( name.size() > 0 );
if ( name[0] == '.' )
{
tgt.setLBind( new CoreString( name, 1 ) );
}
else {
if ( regBind().isDict() )
{
if( regBind().asDict()->find( Item( const_cast<String*>(&name) ), tgt ) )
return;
}
// create the lbind.
tgt.setLBind( new CoreString( name ) );
}
}
void VMachine::expandTRAV( uint32 count, Iterator& iter )
{
// we work a bit differently for dictionaries and normal sequences.
if ( iter.sequence()->isDictionary() )
{
if( count == 1 )
{
// if we have one variable, we must create a pair holding key and value
CoreArray* ca = new CoreArray(2);
ca->items()[0] = iter.getCurrentKey();
ca->items()[1] = iter.getCurrent();
ca->length(2);
*getNextTravVar() = ca;
}
else if ( count != 2 )
{
throw
new AccessError( ErrorParam( e_unpack_size ).origin( e_orig_vm ).extra( "TR*" ) );
}
else {
// we have two vars to decode
Item* k = getNextTravVar();
Item* v = getNextTravVar();
*k = iter.getCurrentKey();
*v = iter.getCurrent();
}
}
else {
// for all the other cases, when we have 1 variable we must just set it inside...
if( count == 1 )
{
*getNextTravVar() = iter.getCurrent();
}
else {
// otherwise, we must match the number of variables with the count of sub-variables.
const Item& current = iter.getCurrent();
if( ! current.isArray() || current.asArray()->length() != count )
{
throw
new AccessError( ErrorParam( e_unpack_size ).origin( e_orig_vm ).extra( "TR*" ) );
}
CoreArray* source = current.asArray();
for( uint32 p = 0; p < count; p++ )
{
*getNextTravVar() = source->items()[p];
}
}
}
}
Item* VMachine::getNextTravVar()
{
fassert( m_currentContext->pc_next() % 4 == 0 );
byte* code = m_currentContext->code();
fassert( code[ m_currentContext->pc_next() ] == P_NOP );
int32 type = int( code[ m_currentContext->pc_next()+1 ] );
m_currentContext->pc_next()+=sizeof( int32 );
int32 id = *reinterpret_cast< int32 * >( code + m_currentContext->pc_next() );
m_currentContext->pc_next()+=sizeof( int32 );
switch( type )
{
case P_PARAM_GLOBID:
return &moduleItem( id );
case P_PARAM_LOCID:
return local( id );
case P_PARAM_PARID:
return param( id );
}
// shall never be here.
fassert( false );
return 0;
}
//=====================================================================================
// baton
//
void VMBaton::release()
{
Baton::release();
// See if the memPool has anything interesting for us.
memPool->idleVM( m_owner );
}
void VMBaton::releaseNotIdle()
{
Baton::release();
}
void VMBaton::onBlockedAcquire()
{
// See if the memPool has anything interesting for us.
memPool->idleVM( m_owner );
}
}
/* end of vm.cpp */
|