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
|
/*
* ERMInterpreter.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "ERMInterpreter.h"
#include <cctype>
#include "../../lib/mapObjects/CObjectHandler.h"
#include "../../lib/mapObjects/MapObjects.h"
#include "../../lib/CHeroHandler.h"
#include "../../lib/CCreatureHandler.h"
#include "../../lib/VCMIDirs.h"
#include "../../lib/IGameCallback.h"
#include "../../lib/mapObjects/CGHeroInstance.h"
#include "../../lib/mapObjects/MiscObjects.h"
namespace spirit = boost::spirit;
using namespace VERMInterpreter;
typedef int TUnusedType;
ERMInterpreter *erm;
Environment *topDyn;
namespace ERMPrinter
{
//console printer
using namespace ERM;
struct VarPrinterVisitor : boost::static_visitor<>
{
void operator()(TVarExpNotMacro const& val) const
{
logGlobal->debug(val.varsym);
if(val.val.is_initialized())
{
logGlobal->debug("%d", val.val.get());
}
}
void operator()(TMacroUsage const& val) const
{
logGlobal->debug("$%s$", val.macro);
}
};
void varPrinter(const TVarExp & var)
{
boost::apply_visitor(VarPrinterVisitor(), var);
}
struct IExpPrinterVisitor : boost::static_visitor<>
{
void operator()(int const & constant) const
{
logGlobal->debug("%d", constant);
}
void operator()(TVarExp const & var) const
{
varPrinter(var);
}
};
void iexpPrinter(const TIexp & exp)
{
boost::apply_visitor(IExpPrinterVisitor(), exp);
}
struct IdentifierPrinterVisitor : boost::static_visitor<>
{
void operator()(TIexp const& iexp) const
{
iexpPrinter(iexp);
}
void operator()(TArithmeticOp const& arop) const
{
iexpPrinter(arop.lhs);
logGlobal->debug(" %s ", arop.opcode);
iexpPrinter(arop.rhs);
}
};
void identifierPrinter(const boost::optional<Tidentifier> & id)
{
if(id.is_initialized())
{
logGlobal->debug("identifier: ");
for (auto x : id.get())
{
logGlobal->debug("#");
boost::apply_visitor(IdentifierPrinterVisitor(), x);
}
}
}
struct ConditionCondPrinterVisitor : boost::static_visitor<>
{
void operator()(TComparison const& cmp) const
{
iexpPrinter(cmp.lhs);
logGlobal->debug(" %s ", cmp.compSign);
iexpPrinter(cmp.rhs);
}
void operator()(int const& flag) const
{
logGlobal->debug("condflag %d", flag);
}
};
void conditionPrinter(const boost::optional<Tcondition> & cond)
{
if(cond.is_initialized())
{
Tcondition condp = cond.get();
logGlobal->debug(" condition: ");
boost::apply_visitor(ConditionCondPrinterVisitor(), condp.cond);
logGlobal->debug(" cond type: %s", condp.ctype);
//recursive call
if(condp.rhs.is_initialized())
{
logGlobal->debug("rhs: ");
boost::optional<Tcondition> rhsc = condp.rhs.get().get();
conditionPrinter(rhsc);
}
else
{
logGlobal->debug("no rhs; ");
}
}
}
struct BodyVarpPrinterVisitor : boost::static_visitor<>
{
void operator()(TVarExpNotMacro const& cmp) const
{
if(cmp.questionMark.is_initialized())
{
logGlobal->debug("%s", cmp.questionMark.get());
}
if(cmp.val.is_initialized())
{
logGlobal->debug("val:%d",cmp.val.get());
}
logGlobal->debug("varsym: |%s|",cmp.varsym);
}
void operator()(TMacroUsage const& cmp) const
{
logGlobal->debug("???$$%s$$", cmp.macro);
}
};
struct BodyOptionItemPrinterVisitor : boost::static_visitor<>
{
void operator()(TVarConcatString const& cmp) const
{
logGlobal->debug("+concat\"");
varPrinter(cmp.var);
logGlobal->debug(" with %s", cmp.string.str);
}
void operator()(TStringConstant const& cmp) const
{
logGlobal->debug(" \"%s\" ", cmp.str);
}
void operator()(TCurriedString const& cmp) const
{
logGlobal->debug("cs: ");
iexpPrinter(cmp.iexp);
logGlobal->debug(" '%s' ", cmp.string.str);
}
void operator()(TSemiCompare const& cmp) const
{
logGlobal->debug("%s; rhs: ", cmp.compSign);
iexpPrinter(cmp.rhs);
}
void operator()(TMacroUsage const& cmp) const
{
logGlobal->debug("$$%s$$", cmp.macro);
}
void operator()(TMacroDef const& cmp) const
{
logGlobal->debug("@@%s@@", cmp.macro);
}
void operator()(TIexp const& cmp) const
{
iexpPrinter(cmp);
}
void operator()(TVarpExp const& cmp) const
{
logGlobal->debug("varp");
boost::apply_visitor(BodyVarpPrinterVisitor(), cmp.var);
}
void operator()(spirit::unused_type const& cmp) const
{
logGlobal->debug("nothing");
}
};
struct BodyOptionVisitor : boost::static_visitor<>
{
void operator()(TVRLogic const& cmp) const
{
logGlobal->debug("%s ", cmp.opcode);
iexpPrinter(cmp.var);
}
void operator()(TVRArithmetic const& cmp) const
{
logGlobal->debug("%s ", cmp.opcode);
iexpPrinter(cmp.rhs);
}
void operator()(TNormalBodyOption const& cmp) const
{
logGlobal->debug("%s~",cmp.optionCode);
for (auto optList : cmp.params)
{
boost::apply_visitor(BodyOptionItemPrinterVisitor(), optList);
}
}
};
void bodyPrinter(const Tbody & body)
{
logGlobal->debug(" body items: ");
for (auto bi: body)
{
logGlobal->debug(" (");
apply_visitor(BodyOptionVisitor(), bi);
logGlobal->debug(") ");
}
}
struct CommandPrinterVisitor : boost::static_visitor<>
{
void operator()(Ttrigger const& trig) const
{
logGlobal->debug("trigger: %s ", trig.name);
identifierPrinter(trig.identifier);
conditionPrinter(trig.condition);
}
void operator()(Tinstruction const& trig) const
{
logGlobal->debug("instruction: %s", trig.name);
identifierPrinter(trig.identifier);
conditionPrinter(trig.condition);
bodyPrinter(trig.body);
}
void operator()(Treceiver const& trig) const
{
logGlobal->debug("receiver: %s ", trig.name);
identifierPrinter(trig.identifier);
conditionPrinter(trig.condition);
if(trig.body.is_initialized())
bodyPrinter(trig.body.get());
}
void operator()(TPostTrigger const& trig) const
{
logGlobal->debug("post trigger: %s ", trig.name);
identifierPrinter(trig.identifier);
conditionPrinter(trig.condition);
}
};
struct LinePrinterVisitor : boost::static_visitor<>
{
void operator()(Tcommand const& cmd) const
{
CommandPrinterVisitor un;
boost::apply_visitor(un, cmd.cmd);
logGlobal->debug("Line comment: %s", cmd.comment);
}
void operator()(std::string const& comment) const
{
}
void operator()(spirit::unused_type const& nothing) const
{
}
};
void printERM(const TERMline & ast)
{
logGlobal->debug("");
boost::apply_visitor(LinePrinterVisitor(), ast);
}
void printTVExp(const TVExp & exp);
struct VOptionPrinterVisitor : boost::static_visitor<>
{
void operator()(TVExp const& cmd) const
{
printTVExp(cmd);
}
void operator()(TSymbol const& cmd) const
{
for(auto mod : cmd.symModifier)
{
logGlobal->debug(mod);
}
logGlobal->debug(cmd.sym);
}
void operator()(char const& cmd) const
{
logGlobal->debug("'%s'", cmd);
}
void operator()(int const& cmd) const
{
logGlobal->debug("%d", cmd);
}
void operator()(double const& cmd) const
{
logGlobal->debug("%f", cmd);
}
void operator()(TERMline const& cmd) const
{
printERM(cmd);
}
void operator()(TStringConstant const& cmd) const
{
logGlobal->debug("^%s^", cmd.str);
}
};
void printTVExp(const TVExp & exp)
{
for (auto mod: exp.modifier)
{
logGlobal->debug("%s ", mod);
}
logGlobal->debug("[ ");
for (auto opt: exp.children)
{
boost::apply_visitor(VOptionPrinterVisitor(), opt);
logGlobal->debug(" ");
}
logGlobal->debug("]");
}
struct TLPrinterVisitor : boost::static_visitor<>
{
void operator()(TVExp const& cmd) const
{
printTVExp(cmd);
}
void operator()(TERMline const& cmd) const
{
printERM(cmd);
}
};
void printAST(const TLine & ast)
{
boost::apply_visitor(TLPrinterVisitor(), ast);
}
}
void ERMInterpreter::scanForScripts()
{
using namespace boost::filesystem;
//parser checking
const path dataPath = VCMIDirs::get().dataPaths().back() / "Data" / "s";
if(!exists(dataPath))
{
logGlobal->warn("Warning: Folder %s doesn't exist!", dataPath.string());
return;
}
directory_iterator enddir;
for (directory_iterator dir(dataPath); dir!=enddir; dir++)
{
if(is_regular(dir->status()))
{
const std::string ext = boost::to_upper_copy(dir->path().extension().string());
if (ext == ".ERM" || ext == ".VERM")
{
ERMParser ep(dir->path().string());
FileInfo * finfo = new FileInfo();
finfo->filename = dir->path().string();
std::vector<LineInfo> buf = ep.parseFile();
finfo->length = buf.size();
files.push_back(finfo);
for(int g=0; g<buf.size(); ++g)
{
scripts[LinePointer(finfo, g, buf[g].realLineNum)] = buf[g].tl;
}
}
}
}
}
void ERMInterpreter::printScripts(EPrintMode mode)
{
std::map< LinePointer, ERM::TLine >::const_iterator prevIt;
for(std::map< LinePointer, ERM::TLine >::const_iterator it = scripts.begin(); it != scripts.end(); ++it)
{
if(it == scripts.begin() || it->first.file != prevIt->first.file)
{
logGlobal->debug("----------------- script %s ------------------", it->first.file->filename);
}
logGlobal->debug("%d", it->first.realLineNum);
ERMPrinter::printAST(it->second);
prevIt = it;
}
}
struct ScriptScanner : boost::static_visitor<>
{
ERMInterpreter * interpreter;
LinePointer lp;
ScriptScanner(ERMInterpreter * interpr, const LinePointer & _lp) : interpreter(interpr), lp(_lp)
{}
void operator()(TVExp const& cmd) const
{
//
}
void operator()(TERMline const& cmd) const
{
if(cmd.which() == 0) //TCommand
{
Tcommand tcmd = boost::get<Tcommand>(cmd);
switch (tcmd.cmd.which())
{
case 0: //trigger
{
Trigger trig;
trig.line = lp;
interpreter->triggers[ TriggerType(boost::get<ERM::Ttrigger>(tcmd.cmd).name) ].push_back(trig);
}
break;
case 3: //post trigger
{
Trigger trig;
trig.line = lp;
interpreter->postTriggers[ TriggerType(boost::get<ERM::TPostTrigger>(tcmd.cmd).name) ].push_back(trig);
}
break;
default:
break;
}
}
}
};
void ERMInterpreter::scanScripts()
{
for(std::map< LinePointer, ERM::TLine >::const_iterator it = scripts.begin(); it != scripts.end(); ++it)
{
boost::apply_visitor(ScriptScanner(this, it->first), it->second);
}
}
ERMInterpreter::ERMInterpreter()
{
erm = this;
curFunc = nullptr;
curTrigger = nullptr;
globalEnv = new Environment();
topDyn = globalEnv;
}
void ERMInterpreter::executeTrigger(VERMInterpreter::Trigger & trig, int funNum, std::vector<int> funParams)
{
//function-related logic
if(funNum != -1)
{
curFunc = getFuncVars(funNum);
for(int g=1; g<=FunctionLocalVars::NUM_PARAMETERS; ++g)
{
curFunc->getParam(g) = g-1 < funParams.size() ? funParams[g-1] : 0;
}
}
else
curFunc = getFuncVars(0);
//skip the first line
LinePointer lp = trig.line;
++lp;
for(; lp.isValid(); ++lp)
{
ERM::TLine curLine = retrieveLine(lp);
if(isATrigger(curLine))
break;
executeLine(lp);
}
curFunc = nullptr;
}
bool ERMInterpreter::isATrigger( const ERM::TLine & line )
{
switch(line.which())
{
case 0: //v-exp
{
TVExp vexp = boost::get<TVExp>(line);
if(vexp.children.size() == 0)
return false;
switch (getExpType(vexp.children[0]))
{
case SYMBOL:
{
//TODO: what about sym modifiers?
//TOOD: macros?
ERM::TSymbol sym = boost::get<ERM::TSymbol>(vexp.children[0]);
return sym.sym == triggerSymbol || sym.sym == postTriggerSymbol;
}
break;
case TCMD:
return isCMDATrigger( boost::get<ERM::Tcommand>(vexp.children[0]) );
break;
default:
return false;
break;
}
}
break;
case 1: //erm
{
TERMline ermline = boost::get<TERMline>(line);
switch(ermline.which())
{
case 0: //tcmd
return isCMDATrigger( boost::get<ERM::Tcommand>(ermline) );
break;
default:
return false;
break;
}
}
break;
default:
assert(0); //it should never happen
break;
}
assert(0);
return false;
}
ERM::EVOtions ERMInterpreter::getExpType( const ERM::TVOption & opt )
{
//MAINTENANCE: keep it correct!
return static_cast<ERM::EVOtions>(opt.which());
}
bool ERMInterpreter::isCMDATrigger( const ERM::Tcommand & cmd )
{
switch (cmd.cmd.which())
{
case 0: //trigger
case 3: //post trigger
return true;
break;
default:
return false;
break;
}
}
ERM::TLine &ERMInterpreter::retrieveLine( LinePointer linePtr )
{
return scripts.find(linePtr)->second;
}
/////////
//code execution
template<typename OwnerType>
struct StandardBodyOptionItemVisitor : boost::static_visitor<>
{
typedef OwnerType TReceiverType;
OwnerType & owner;
explicit StandardBodyOptionItemVisitor(OwnerType & _owner) : owner(_owner)
{}
virtual void operator()(TVarConcatString const& cmp) const
{
throw EScriptExecError("String concatenation not allowed in this receiver");
}
virtual void operator()(TStringConstant const& cmp) const
{
throw EScriptExecError("String constant not allowed in this receiver");
}
virtual void operator()(TCurriedString const& cmp) const
{
throw EScriptExecError("Curried string not allowed in this receiver");
}
virtual void operator()(TSemiCompare const& cmp) const
{
throw EScriptExecError("Semi comparison not allowed in this receiver");
}
// virtual void operator()(TMacroUsage const& cmp) const
// {
// throw EScriptExecError("Macro usage not allowed in this receiver");
// }
virtual void operator()(TMacroDef const& cmp) const
{
throw EScriptExecError("Macro definition not allowed in this receiver");
}
virtual void operator()(TIexp const& cmp) const
{
throw EScriptExecError("i-expression not allowed in this receiver");
}
virtual void operator()(TVarpExp const& cmp) const
{
throw EScriptExecError("Varp expression not allowed in this receiver");
}
virtual void operator()(spirit::unused_type const& cmp) const
{
throw EScriptExecError("\'Nothing\' not allowed in this receiver");
}
};
template<typename T>
struct StandardReceiverVisitor : boost::static_visitor<>
{
ERMInterpreter * interp;
T identifier;
StandardReceiverVisitor(ERMInterpreter * _interpr, T ident) : interp(_interpr), identifier(ident)
{}
virtual void operator()(TVRLogic const& trig) const
{
throw EScriptExecError("VR logic not allowed in this receiver!");
}
virtual void operator()(TVRArithmetic const& trig) const
{
throw EScriptExecError("VR arithmetic not allowed in this receiver!");
}
virtual void operator()(TNormalBodyOption const& trig) const = 0;
template<typename OptionPerformer>
void performOptionTakingOneParamter(const ERM::TNormalBodyOptionList & params) const
{
if(params.size() == 1)
{
ERM::TBodyOptionItem boi = params[0];
boost::apply_visitor(
OptionPerformer(*const_cast<typename OptionPerformer::TReceiverType*>(static_cast<const typename OptionPerformer::TReceiverType*>(this))), boi);
}
else
throw EScriptExecError("This receiver option takes exactly 1 parameter!");
}
template<template <int opcode> class OptionPerformer>
void performOptionTakingOneParamterWithIntDispatcher(const ERM::TNormalBodyOptionList & params) const
{
if(params.size() == 2)
{
int optNum = erm->getIexp(params[0]).getInt();
ERM::TBodyOptionItem boi = params[1];
switch(optNum)
{
case 0:
boost::apply_visitor(
OptionPerformer<0>(*const_cast<typename OptionPerformer<0>::TReceiverType*>(static_cast<const typename OptionPerformer<0>::TReceiverType*>(this))), boi);
break;
default:
throw EScriptExecError("Wrong number of option code!");
break;
}
}
else
throw EScriptExecError("This receiver option takes exactly 2 parameters!");
}
};
////HE
struct HEPerformer;
template<int opcode>
struct HE_BPerformer : StandardBodyOptionItemVisitor<HEPerformer>
{
explicit HE_BPerformer(HEPerformer & _owner) : StandardBodyOptionItemVisitor<HEPerformer>(_owner)
{}
using StandardBodyOptionItemVisitor<HEPerformer>::operator();
void operator()(TIexp const& cmp) const override;
void operator()(TVarpExp const& cmp) const override;
};
template<int opcode>
void HE_BPerformer<opcode>::operator()( TIexp const& cmp ) const
{
throw EScriptExecError("Setting hero name is not implemented!");
}
template<int opcode>
struct HE_CPerformer : StandardBodyOptionItemVisitor<HEPerformer>
{
explicit HE_CPerformer(HEPerformer & _owner) : StandardBodyOptionItemVisitor<HEPerformer>(_owner)
{}
using StandardBodyOptionItemVisitor<HEPerformer>::operator();
void operator()(TIexp const& cmp) const override;
void operator()(TVarpExp const& cmp) const override;
};
template<int opcode>
void HE_CPerformer<opcode>::operator()( TIexp const& cmp ) const
{
throw EScriptExecError("Setting hero army is not implemented!");
}
struct HEPerformer : StandardReceiverVisitor<const CGHeroInstance *>
{
HEPerformer(ERMInterpreter * _interpr, const CGHeroInstance * hero) : StandardReceiverVisitor<const CGHeroInstance *>(_interpr, hero)
{}
using StandardReceiverVisitor<const CGHeroInstance *>::operator();
void operator()(TNormalBodyOption const& trig) const override
{
switch(trig.optionCode)
{
case 'B':
{
performOptionTakingOneParamterWithIntDispatcher<HE_BPerformer>(trig.params);
}
break;
case 'C':
{
const ERM::TNormalBodyOptionList & params = trig.params;
if(params.size() == 4)
{
if(erm->getIexp(params[0]).getInt() == 0)
{
SlotID slot = SlotID(erm->getIexp(params[1]).getInt());
const CStackInstance *stack = identifier->getStackPtr(slot);
if(params[2].which() == 6) //varp
{
IexpValStr lhs = erm->getIexp(boost::get<ERM::TVarpExp>(params[2]));
if(stack)
lhs.setTo(stack->getCreatureID());
else
lhs.setTo(-1);
}
else
throw EScriptExecError("Setting stack creature type is not implemented!");
if(params[3].which() == 6) //varp
{
erm->getIexp(boost::get<ERM::TVarpExp>(params[3])).setTo(identifier->getStackCount(SlotID(slot)));
}
else
throw EScriptExecError("Setting stack count is not implemented!");
}
else
throw EScriptExecError("Slot number must be an evaluable i-exp");
}
//todo else if(14 params)
else
throw EScriptExecError("Slot number must be an evaluable i-exp");
}
break;
case 'E':
break;
case 'N':
break;
default:
break;
}
}
};
struct IFPerformer;
struct IF_MPerformer : StandardBodyOptionItemVisitor<IFPerformer>
{
explicit IF_MPerformer(IFPerformer & _owner) : StandardBodyOptionItemVisitor<IFPerformer>(_owner){}
using StandardBodyOptionItemVisitor<IFPerformer>::operator();
void operator()(TStringConstant const& cmp) const override;
};
//according to the ERM help:
//"%%" -> "%"
//"%V#" -> current value of # flag.
//"%Vf"..."%Vt" -> current value of corresponding variable.
//"%W1"..."%W100" -> current value of corresponding hero variable.
//"%X1"..."%X16" -> current value of corresponding function parameter.
//"%Y1"..."%Y100" -> current value of corresponding local variable.
//"%Z1"..."%Z500" -> current value of corresponding string variable.
//"%$macro$" -> macro name of corresponding variable
//"%Dd" -> current day of week
//"%Dw" -> current week
//"%Dm" -> current month
//"%Da" -> current day from beginning of the game
//"%Gc" -> the color of current gamer in text
struct StringFormatter
{
int pos;
int tokenLength;
size_t percentPos;
int charsToReplace;
std::string &msg;
StringFormatter(std::string &MSG) : pos(0), msg(MSG) {}
static void format(std::string &msg)
{
StringFormatter sf(msg);
sf.format();
}
// startpos is the first digit
// digits will be converted to number and returned
// ADDITIVE on digitsUsed
int getNum()
{
int toAdd = 0;
int numStart = percentPos + 2;
size_t numEnd = msg.find_first_not_of("1234567890", numStart);
if(numEnd == std::string::npos)
toAdd = msg.size() - numStart;
else
toAdd = numEnd - numStart;
charsToReplace += toAdd;
return boost::lexical_cast<int>(msg.substr(numStart, toAdd));
}
void format()
{
while(pos < msg.size())
{
percentPos = msg.find_first_of('%', pos);
charsToReplace = 1; //at least the same '%' needs to be replaced
std::ostringstream replaceWithWhat;
if(percentPos == std::string::npos) //processing done?
break;
if(percentPos + 1 >= msg.size()) //at least one character after % is required
throw EScriptExecError("Formatting error: % at the end of string!");
charsToReplace++; //the sign after % is consumed
switch(msg[percentPos+1])
{
case '%':
replaceWithWhat << '%';
break;
case 'F':
replaceWithWhat << erm->ermGlobalEnv->getFlag(getNum());
break;
case 'V':
if(std::isdigit(msg[percentPos + 2]))
replaceWithWhat << erm->ermGlobalEnv->getStandardVar(getNum());
else
{
charsToReplace++;
replaceWithWhat << erm->ermGlobalEnv->getQuickVar(msg[percentPos+2]);
}
break;
case 'X':
replaceWithWhat << erm->getVar("x", getNum()).getInt();
break;
case 'Z':
replaceWithWhat << erm->ermGlobalEnv->getZVar(getNum());
break;
default:
throw EScriptExecError("Formatting error: unrecognized token indicator after %!");
}
msg.replace(percentPos, charsToReplace, replaceWithWhat.str());
pos = percentPos + 1;
}
}
};
struct IFPerformer : StandardReceiverVisitor<TUnusedType>
{
IFPerformer(ERMInterpreter * _interpr) : StandardReceiverVisitor<TUnusedType>(_interpr, 0)
{}
using StandardReceiverVisitor<TUnusedType>::operator();
void operator()(TNormalBodyOption const& trig) const override
{
switch(trig.optionCode)
{
case 'M': //Show the message (Text) or contents of z$ variable on the screen immediately.
performOptionTakingOneParamter<IF_MPerformer>(trig.params);
break;
default:
break;
}
}
void showMessage(const std::string &msg)
{
std::string msgToFormat = msg;
StringFormatter::format(msgToFormat);
acb->showInfoDialog(msgToFormat, icb->getLocalPlayer());
}
};
void IF_MPerformer::operator()(TStringConstant const& cmp) const
{
owner.showMessage(cmp.str);
}
template<int opcode>
void HE_BPerformer<opcode>::operator()( TVarpExp const& cmp ) const
{
erm->getIexp(cmp).setTo(owner.identifier->name);
}
template<int opcode>
void HE_CPerformer<opcode>::operator()( TVarpExp const& cmp ) const
{
erm->getIexp(cmp).setTo(owner.identifier->name);
}
////MA
struct MAPerformer;
struct MA_PPerformer : StandardBodyOptionItemVisitor<MAPerformer>
{
explicit MA_PPerformer(MAPerformer & _owner);
using StandardBodyOptionItemVisitor<MAPerformer>::operator();
void operator()(TIexp const& cmp) const override;
void operator()(TVarpExp const& cmp) const override;
};
struct MAPerformer : StandardReceiverVisitor<TUnusedType>
{
MAPerformer(ERMInterpreter * _interpr) : StandardReceiverVisitor<TUnusedType>(_interpr, 0)
{}
using StandardReceiverVisitor<TUnusedType>::operator();
void operator()(TNormalBodyOption const& trig) const override
{
switch(trig.optionCode)
{
case 'A': //sgc monster attack
break;
case 'B': //spell?
break;
case 'P': //hit points
{
//TODO
}
break;
default:
break;
}
}
};
void MA_PPerformer::operator()( TIexp const& cmp ) const
{
}
void MA_PPerformer::operator()( TVarpExp const& cmp ) const
{
}
////MO
struct MOPerformer;
struct MO_GPerformer : StandardBodyOptionItemVisitor<MOPerformer>
{
explicit MO_GPerformer(MOPerformer & _owner) : StandardBodyOptionItemVisitor<MOPerformer>(_owner)
{}
using StandardBodyOptionItemVisitor<MOPerformer>::operator();
void operator()(TVarpExp const& cmp) const override;
void operator()(TIexp const& cmp) const override;
};
struct MOPerformer: StandardReceiverVisitor<int3>
{
MOPerformer(ERMInterpreter * _interpr, int3 pos) : StandardReceiverVisitor<int3>(_interpr, pos)
{}
using StandardReceiverVisitor<int3>::operator();
void operator()(TNormalBodyOption const& trig) const override
{
switch(trig.optionCode)
{
case 'G':
{
performOptionTakingOneParamter<MO_GPerformer>(trig.params);
}
break;
default:
break;
}
}
};
void MO_GPerformer::operator()( TIexp const& cmp ) const
{
throw EScriptExecError("Setting monster count is not implemented yet!");
}
void MO_GPerformer::operator()( TVarpExp const& cmp ) const
{
const CGCreature *cre = erm->getObjFromAs<CGCreature>(owner.identifier);
erm->getIexp(cmp).setTo(cre->getStackCount(SlotID(0)));
}
struct ConditionDisemboweler;
//OB
struct OBPerformer;
struct OB_UPerformer : StandardBodyOptionItemVisitor<OBPerformer>
{
explicit OB_UPerformer(OBPerformer & owner) : StandardBodyOptionItemVisitor<OBPerformer>(owner)
{}
using StandardBodyOptionItemVisitor<OBPerformer>::operator();
virtual void operator()(TIexp const& cmp) const;
virtual void operator()(TVarpExp const& cmp) const;
};
struct OBPerformer : StandardReceiverVisitor<int3>
{
OBPerformer(ERMInterpreter * _interpr, int3 objPos) : StandardReceiverVisitor<int3>(_interpr, objPos)
{}
using StandardReceiverVisitor<int3>::operator(); //it removes compilation error... not sure why it *must* be here
void operator()(TNormalBodyOption const& trig) const
{
switch(trig.optionCode)
{
case 'B': //removes description hint
{
//TODO
}
break;
case 'C': //sgc of control word of object
{
//TODO
}
break;
case 'D': //disable gamer to use object
{
//TODO
}
break;
case 'E': //enable gamer to use object
{
//TODO
}
break;
case 'H': //replace hint for object
{
//TODO
}
break;
case 'M': //disabling messages and questions
{
//TODO
}
break;
case 'R': //enable all gamers to use object
{
//TODO
}
break;
case 'S': //disable all gamers to use object
{
//TODO
}
break;
case 'T': //sgc of obj type
{
//TODO
}
break;
case 'U': //sgc of obj subtype
{
performOptionTakingOneParamter<OB_UPerformer>(trig.params);
}
break;
default:
throw EScriptExecError("Wrong OB receiver option!");
break;
}
}
};
void OB_UPerformer::operator()( TIexp const& cmp ) const
{
IexpValStr val = owner.interp->getIexp(cmp);
throw EScriptExecError("Setting subID is not implemented yet!");
}
void OB_UPerformer::operator()( TVarpExp const& cmp ) const
{
IexpValStr val = owner.interp->getIexp(cmp);
val.setTo(erm->getObjFrom(owner.identifier)->subID);
}
/////VR
struct VRPerformer;
struct VR_SPerformer : StandardBodyOptionItemVisitor<VRPerformer>
{
explicit VR_SPerformer(VRPerformer & _owner);
using StandardBodyOptionItemVisitor<VRPerformer>::operator();
void operator()(TStringConstant const& cmp) const override;
void operator()(TIexp const& cmp) const override;
};
struct VRPerformer : StandardReceiverVisitor<IexpValStr>
{
VRPerformer(ERMInterpreter * _interpr, IexpValStr ident) : StandardReceiverVisitor<IexpValStr>(_interpr, ident)
{}
void operator()(TVRLogic const& trig) const override
{
int valr = interp->getIexp(trig.var).getInt();
switch (trig.opcode)
{
case '&':
const_cast<VRPerformer*>(this)->identifier.setTo(identifier.getInt() & valr);
break;
case '|':
const_cast<VRPerformer*>(this)->identifier.setTo(identifier.getInt() | valr);
break;
case 'X':
const_cast<VRPerformer*>(this)->identifier.setTo(identifier.getInt() ^ valr);
break;
default:
throw EInterpreterError("Wrong opcode in VR logic expression!");
break;
}
}
void operator()(TVRArithmetic const& trig) const override
{
IexpValStr rhs = interp->getIexp(trig.rhs);
switch (trig.opcode)
{
case '+':
const_cast<VRPerformer*>(this)->identifier += rhs;
break;
case '-':
const_cast<VRPerformer*>(this)->identifier -= rhs;
break;
case '*':
const_cast<VRPerformer*>(this)->identifier *= rhs;
break;
case ':':
const_cast<VRPerformer*>(this)->identifier /= rhs;
break;
case '%':
const_cast<VRPerformer*>(this)->identifier %= rhs;
break;
default:
throw EInterpreterError("Wrong opcode in VR arithmetic!");
break;
}
}
void operator()(TNormalBodyOption const& trig) const override
{
switch(trig.optionCode)
{
case 'C': //setting/checking v vars
{
//TODO
}
break;
case 'H': //checking if string is empty
{
//TODO
}
break;
case 'M': //string operations
{
//TODO
}
break;
case 'R': //random variables
{
//TODO
}
break;
case 'S': //setting variable
{
performOptionTakingOneParamter<VR_SPerformer>(trig.params);
}
break;
case 'T': //random variables
{
//TODO
}
break;
case 'U': //search for a substring
{
//TODO
}
break;
case 'V': //convert string to value
{
//TODO
}
break;
default:
throw EScriptExecError("Wrong VR receiver option!");
break;
}
}
};
VR_SPerformer::VR_SPerformer(VRPerformer & _owner) : StandardBodyOptionItemVisitor<VRPerformer>(_owner)
{}
void VR_SPerformer::operator()(ERM::TIexp const& trig) const
{
owner.identifier.setTo(owner.interp->getIexp(trig));
}
void VR_SPerformer::operator()(TStringConstant const& cmp) const
{
owner.identifier.setTo(cmp.str);
}
/////
struct ERMExpDispatch : boost::static_visitor<>
{
struct HLP
{
int3 getPosFromIdentifier(ERM::Tidentifier tid, bool allowDummyFourth)
{
switch(tid.size())
{
case 1:
{
int num = erm->getIexp(tid[0]).getInt();
return int3(erm->ermGlobalEnv->getStandardVar(num),
erm->ermGlobalEnv->getStandardVar(num+1),
erm->ermGlobalEnv->getStandardVar(num+2));
}
break;
case 3:
case 4:
if(tid.size() == 4 && !allowDummyFourth)
throw EScriptExecError("4 items in identifier are not allowed for this receiver!");
return int3(erm->getIexp(tid[0]).getInt(),
erm->getIexp(tid[1]).getInt(),
erm->getIexp(tid[2]).getInt());
break;
default:
throw EScriptExecError("This receiver takes 1 or 3 items in identifier!");
break;
}
}
template <typename Visitor>
void performBody(const boost::optional<ERM::Tbody> & body, const Visitor& visitor)
{
if(body.is_initialized())
{
ERM::Tbody bo = body.get();
for(int g=0; g<bo.size(); ++g)
{
boost::apply_visitor(visitor, bo[g]);
}
}
}
};
void operator()(Ttrigger const& trig) const
{
throw EInterpreterError("Triggers cannot be executed!");
}
void operator()(Tinstruction const& trig) const
{
}
void operator()(Treceiver const& trig) const
{
HLP helper;
//check condition
if(trig.condition.is_initialized())
{
if( !erm->checkCondition(trig.condition.get()) )
return;
}
if(trig.name == "VR")
{
//perform operations
if(trig.identifier.is_initialized())
{
ERM::Tidentifier ident = trig.identifier.get();
if(ident.size() == 1)
{
IexpValStr ievs = erm->getIexp(ident[0]);
//see body
helper.performBody(trig.body, VRPerformer(erm, ievs));
}
else
throw EScriptExecError("VR receiver must be used with exactly one identifier item!");
}
else
throw EScriptExecError("VR receiver must be used with an identifier!");
}
else if(trig.name == "DO")
{
//perform operations
if(trig.identifier.is_initialized())
{
ERM::Tidentifier tid = trig.identifier.get();
if(tid.size() != 4)
{
throw EScriptExecError("DO receiver takes exactly 4 arguments");
}
int funNum = erm->getIexp(tid[0]).getInt(),
startVal = erm->getIexp(tid[1]).getInt(),
stopVal = erm->getIexp(tid[2]).getInt(),
increment = erm->getIexp(tid[3]).getInt();
for(int it = startVal; it < stopVal; it += increment)
{
std::vector<int> params(FunctionLocalVars::NUM_PARAMETERS, 0);
params.back() = it;
//owner->getFuncVars(funNum)->getParam(16) = it;
std::vector<int> v1;
v1.push_back(funNum);
ERMInterpreter::TIDPattern tip = {{v1.size(), v1}};
erm->executeTriggerType(TriggerType("FU"), true, tip, params);
it = erm->getFuncVars(funNum)->getParam(16);
}
}
}
else if(trig.name == "MA")
{
if(trig.identifier.is_initialized())
{
throw EScriptExecError("MA receiver doesn't take the identifier!");
}
helper.performBody(trig.body, MAPerformer(erm));
}
else if(trig.name == "MO")
{
int3 objPos;
if(trig.identifier.is_initialized())
{
ERM::Tidentifier tid = trig.identifier.get();
objPos = HLP().getPosFromIdentifier(tid, true);
helper.performBody(trig.body, MOPerformer(erm, objPos));
}
else
throw EScriptExecError("MO receiver must have an identifier!");
}
else if(trig.name == "OB")
{
int3 objPos;
if(trig.identifier.is_initialized())
{
ERM::Tidentifier tid = trig.identifier.get();
objPos = HLP().getPosFromIdentifier(tid, false);
helper.performBody(trig.body, OBPerformer(erm, objPos));
}
else
throw EScriptExecError("OB receiver must have an identifier!");
}
else if(trig.name == "HE")
{
if(trig.identifier.is_initialized())
{
const CGHeroInstance * hero = nullptr;
ERM::Tidentifier tid = trig.identifier.get();
switch(tid.size())
{
case 1:
{
int heroNum = erm->getIexp(tid[0]).getInt();
if(heroNum == -1)
assert(false); //FIXME: use new hero selection mechanics
else
hero = icb->getHeroWithSubid(heroNum);
}
break;
case 3:
{
int3 pos = helper.getPosFromIdentifier(tid, false);
hero = erm->getObjFromAs<CGHeroInstance>(pos);
}
break;
default:
throw EScriptExecError("HE receiver takes 1 or 3 items in identifier");
break;
}
helper.performBody(trig.body, HEPerformer(erm, hero));
}
else
throw EScriptExecError("HE receiver must have an identifier!");
}
else if(trig.name == "IF")
{
helper.performBody(trig.body, IFPerformer(erm));
}
else
{
logGlobal->warn("%s receiver is not supported yet, doing nothing...", trig.name);
//not supported or invalid trigger
}
}
void operator()(TPostTrigger const& trig) const
{
throw EInterpreterError("Post-triggers cannot be executed!");
}
};
struct CommandExec : boost::static_visitor<>
{
void operator()(Tcommand const& cmd) const
{
boost::apply_visitor(ERMExpDispatch(), cmd.cmd);
logGlobal->debug("Line comment: %s", cmd.comment);
}
void operator()(std::string const& comment) const
{
//comment - do nothing
}
void operator()(spirit::unused_type const& nothing) const
{
//nothing - do nothing
}
};
struct LineExec : boost::static_visitor<>
{
void operator()(TVExp const& cmd) const
{
VNode line(cmd);
erm->eval(line);
}
void operator()(TERMline const& cmd) const
{
boost::apply_visitor(CommandExec(), cmd);
}
};
/////////
void ERMInterpreter::executeLine( const LinePointer & lp )
{
logGlobal->debug("Executing line %d (internal %d) from %s", getRealLine(lp), lp.lineNum, lp.file->filename);
executeLine(scripts[lp]);
}
void ERMInterpreter::executeLine(const ERM::TLine &line)
{
boost::apply_visitor(LineExec(), line);
}
IexpValStr ERMInterpreter::getVar(std::string toFollow, boost::optional<int> initVal) const
{
IexpValStr ret;
ret.type = IexpValStr::WRONGVAL;
int initV=0;
bool hasInit = false;
if(initVal.is_initialized())
{
initV = initVal.get();
hasInit = true;
}
int endNum = 0;
if(toFollow[0] == 'd')
{
endNum = 1;
//TODO: support
}
if(toFollow.size() == 0)
{
if(hasInit)
ret = IexpValStr(initV);
else
throw EIexpProblem("No input to getVar!");
return ret;
}
//now we have at least one element in toFollow
for(int b=toFollow.size()-1; b>=endNum; --b)
{
bool retIt = b == endNum/*+1*/; //if we should return the value are currently at
char cr = toFollow[b];
if(cr == 'c')//write number of current day
{
//TODO
}
else if(cr == 'd') //info for external env - add i/o set
{
throw EIexpProblem("d inside i-expression not allowed!");
}
else if(cr == 'e')
{
if(hasInit)
{
if(retIt)
{
//these C-style cast is here just to shut up compiler errors
if(initV > 0 && initV <= FunctionLocalVars::NUM_FLOATINGS)
{
if(curFunc)
ret = IexpValStr(&curFunc->getFloat(initV));
else
throw EIexpProblem("Function context not available!");
}
else if(initV < 0 && initV >= -TriggerLocalVars::EVAR_NUM)
{
if(curTrigger)
ret = IexpValStr(&curTrigger->ermLocalVars.getEvar(initV));
else
throw EIexpProblem("No trigger context available!");
}
else
throw EIexpProblem("index " + boost::lexical_cast<std::string>(initV) + " not allowed for e array");
}
else
throw EIexpProblem("e variables cannot appear in this context");
}
else
throw EIexpProblem("e variables cannot appear in this context");
}
else if(cr >= 'f' && cr <= 't')
{
if(retIt)
ret = IexpValStr(&ermGlobalEnv->getQuickVar(cr));
else
{
if(hasInit)
throw EIexpProblem("quick variables cannot be used in this context");
else
{
initV = ermGlobalEnv->getQuickVar(cr);
hasInit = true;
}
}
}
else if(cr == 'v') //standard variables
{
if(hasInit)
{
if(retIt)
ret = IexpValStr(&ermGlobalEnv->getStandardVar(initV));
else
initV = ermGlobalEnv->getStandardVar(initV);
}
else
throw EIexpProblem("standard variable cannot be used in this context!");
}
else if(cr == 'w') //local hero variables
{
//TODO
}
else if(cr == 'x') //function parameters
{
if(hasInit)
{
if(curFunc)
{
if(retIt)
ret = IexpValStr(&curFunc->getParam(initV));
else
initV = curFunc->getParam(initV);
}
else throw EIexpProblem("Function parameters cannot be used outside a function!");
}
else
throw EIexpProblem("Specify which function parameter should be used");
}
else if(cr == 'y')
{
if(hasInit)
{
if(initV > 0 && initV <= FunctionLocalVars::NUM_LOCALS)
{
int &valPtr = curFunc ? curFunc->getLocal(initV) : const_cast<ERMInterpreter&>(*this).getFuncVars(0)->getLocal(initV); //retrieve local var if in function or use global set otherwise
if(retIt)
ret = IexpValStr(&valPtr);
else
initV = curFunc->getLocal(initV);
}
else if(initV < 0 && initV >= -TriggerLocalVars::YVAR_NUM)
{
if(curTrigger)
{
if(retIt)
ret = IexpValStr(&curTrigger->ermLocalVars.getYvar(initV));
else
initV = curTrigger->ermLocalVars.getYvar(initV);
}
else
throw EIexpProblem("Trigger local variables cannot be used outside triggers!");
}
else
throw EIexpProblem("Wrong argument for function local variable!");
}
else
throw EIexpProblem("y variable cannot be used in this context!");
}
else if(cr == 'z')
{
if(hasInit)
{
if(retIt)
{
//these C-style casts are here just to shut up compiler errors
if(initV > 0 )
ret = IexpValStr(&ermGlobalEnv->getZVar(initV));
else if(initV < 0)
{
if(curFunc)
ret = IexpValStr(&curFunc->getString(initV));
else
throw EIexpProblem("Function local string variables cannot be used outside functions!");
}
else
throw EIexpProblem("Wrong parameter for string variable!");
}
else
throw EIexpProblem("String variables can only be returned!");
}
else
throw EIexpProblem("String variables cannot be used in this context!");
}
else
{
throw EIexpProblem(std::string("Symbol ") + cr + " is not allowed in this context!");
}
}
ret.name = toFollow;
if(initVal.is_initialized())
{
ret.name += boost::lexical_cast<std::string>(initVal.get());
}
return ret;
}
namespace IexpDisemboweler
{
enum EDir{GET, SET};
}
struct LVL2IexpDisemboweler : boost::static_visitor<IexpValStr>
{
/*const*/ ERMInterpreter * env;
IexpDisemboweler::EDir dir;
LVL2IexpDisemboweler(/*const*/ ERMInterpreter * _env, IexpDisemboweler::EDir _dir)
: env(_env), dir(_dir) //writes value to given var
{}
IexpValStr processNotMacro(const TVarExpNotMacro & val) const
{
if(val.questionMark.is_initialized())
throw EIexpProblem("Question marks ('?') are not allowed in getter i-expressions");
//const-cast just to do some code-reuse...
return env->getVar(val.varsym, val.val);
}
IexpValStr operator()(TVarExpNotMacro const& val) const
{
return processNotMacro(val);
}
IexpValStr operator()(TMacroUsage const& val) const
{
return env->getIexp(val);
}
};
struct LVL1IexpDisemboweler : boost::static_visitor<IexpValStr>
{
/*const*/ ERMInterpreter * env;
IexpDisemboweler::EDir dir;
LVL1IexpDisemboweler(/*const*/ ERMInterpreter * _env, IexpDisemboweler::EDir _dir)
: env(_env), dir(_dir) //writes value to given var
{}
IexpValStr operator()(int const & constant) const
{
if(dir == IexpDisemboweler::GET)
{
return IexpValStr(constant);
}
else
{
throw EIexpProblem("Cannot set a constant!");
}
}
IexpValStr operator()(TVarExp const & var) const
{
return boost::apply_visitor(LVL2IexpDisemboweler(env, dir), var);
}
};
IexpValStr ERMInterpreter::getIexp( const ERM::TIexp & iexp ) const
{
return boost::apply_visitor(LVL1IexpDisemboweler(const_cast<ERMInterpreter*>(this), IexpDisemboweler::GET), iexp);
}
IexpValStr ERMInterpreter::getIexp( const ERM::TMacroUsage & macro ) const
{
std::map<std::string, ERM::TVarExpNotMacro>::const_iterator it =
ermGlobalEnv->macroBindings.find(macro.macro);
if(it == ermGlobalEnv->macroBindings.end())
throw EUsageOfUndefinedMacro(macro.macro);
return getVar(it->second.varsym, it->second.val);
}
IexpValStr ERMInterpreter::getIexp( const ERM::TIdentifierInternal & tid ) const
{
if(tid.which() == 0)
{
return getIexp(boost::get<ERM::TIexp>(tid));
}
else
throw EScriptExecError("Identifier must be a valid i-expression to perform this operation!");
}
IexpValStr ERMInterpreter::getIexp( const ERM::TVarpExp & tid ) const
{
return boost::apply_visitor(LVL2IexpDisemboweler(const_cast<ERMInterpreter*>(this), IexpDisemboweler::GET), tid.var);
}
struct LVL3BodyOptionItemVisitor : StandardBodyOptionItemVisitor<IexpValStr>
{
explicit LVL3BodyOptionItemVisitor(IexpValStr & _owner) : StandardBodyOptionItemVisitor<IexpValStr>(_owner)
{}
using StandardBodyOptionItemVisitor<IexpValStr>::operator();
void operator()(TIexp const& cmp) const override
{
owner = erm->getIexp(cmp);
}
void operator()(TVarpExp const& cmp) const override
{
owner = erm->getIexp(cmp);
}
};
IexpValStr ERMInterpreter::getIexp( const ERM::TBodyOptionItem & opit ) const
{
IexpValStr ret;
boost::apply_visitor(LVL3BodyOptionItemVisitor(ret), opit);
return ret;
}
void ERMInterpreter::executeTriggerType(VERMInterpreter::TriggerType tt, bool pre, const TIDPattern & identifier, const std::vector<int> &funParams)
{
struct HLP
{
static int calcFunNum(VERMInterpreter::TriggerType tt, const TIDPattern & identifier)
{
if(tt.type != VERMInterpreter::TriggerType::FU)
return -1;
return identifier.begin()->second[0];
}
};
TtriggerListType & triggerList = pre ? triggers : postTriggers;
TriggerIdentifierMatch tim;
tim.allowNoIdetifier = true;
tim.ermEnv = this;
tim.matchToIt = identifier;
std::vector<Trigger> & triggersToTry = triggerList[tt];
for(int g=0; g<triggersToTry.size(); ++g)
{
if(tim.tryMatch(&triggersToTry[g]))
{
curTrigger = &triggersToTry[g];
executeTrigger(triggersToTry[g], HLP::calcFunNum(tt, identifier), funParams);
}
}
}
void ERMInterpreter::executeTriggerType(const char *trigger, int id)
{
TIDPattern tip;
tip[0] = std::vector<int>(1, id);
executeTriggerType(VERMInterpreter::TriggerType(trigger), true, tip);
}
void ERMInterpreter::executeTriggerType(const char *trigger)
{
executeTriggerType(VERMInterpreter::TriggerType(trigger), true, TIDPattern());
}
ERM::TTriggerBase & ERMInterpreter::retrieveTrigger( ERM::TLine &line )
{
if(line.which() == 1)
{
ERM::TERMline &tl = boost::get<ERM::TERMline>(line);
if(tl.which() == 0)
{
ERM::Tcommand &tcm = boost::get<ERM::Tcommand>(tl);
if(tcm.cmd.which() == 0)
{
return boost::get<ERM::Ttrigger>(tcm.cmd);
}
else if(tcm.cmd.which() == 3)
{
return boost::get<ERM::TPostTrigger>(tcm.cmd);
}
throw ELineProblem("Given line is not a trigger!");
}
throw ELineProblem("Given line is not a command!");
}
throw ELineProblem("Given line is not an ERM trigger!");
}
template<typename T>
bool compareExp(const T & lhs, const T & rhs, std::string op)
{
if(op == "<")
{
return lhs < rhs;
}
else if(op == ">")
{
return lhs > rhs;
}
else if(op == ">=" || op == "=>")
{
return lhs >= rhs;
}
else if(op == "<=" || op == "=<")
{
return lhs <= rhs;
}
else if(op == "==")
{
return lhs == rhs;
}
else if(op == "<>" || op == "><")
{
return lhs != rhs;
}
else
throw EScriptExecError(std::string("Wrong comparison sign: ") + op);
}
struct ConditionDisemboweler : boost::static_visitor<bool>
{
ConditionDisemboweler(ERMInterpreter * _ei) : ei(_ei)
{}
bool operator()(TComparison const & cmp) const
{
IexpValStr lhs = ei->getIexp(cmp.lhs),
rhs = ei->getIexp(cmp.rhs);
switch (lhs.type)
{
case IexpValStr::FLOATVAR:
switch (rhs.type)
{
case IexpValStr::FLOATVAR:
return compareExp(lhs.getFloat(), rhs.getFloat(), cmp.compSign);
break;
default:
throw EScriptExecError("Incompatible types for comparison");
}
break;
case IexpValStr::INT:
case IexpValStr::INTVAR:
switch (rhs.type)
{
case IexpValStr::INT:
case IexpValStr::INTVAR:
return compareExp(lhs.getInt(), rhs.getInt(), cmp.compSign);
break;
default:
throw EScriptExecError("Incompatible types for comparison");
}
break;
case IexpValStr::STRINGVAR:
switch (rhs.type)
{
case IexpValStr::STRINGVAR:
return compareExp(lhs.getString(), rhs.getString(), cmp.compSign);
break;
default:
throw EScriptExecError("Incompatible types for comparison");
}
break;
default:
throw EScriptExecError("Wrong type of left iexp!");
}
return false;//we should never reach this place
}
bool operator()(int const & flag) const
{
return ei->ermGlobalEnv->getFlag(flag);
}
private:
ERMInterpreter * ei;
};
bool ERMInterpreter::checkCondition( ERM::Tcondition cond )
{
bool ret = boost::apply_visitor(ConditionDisemboweler(this), cond.cond);
if(cond.rhs.is_initialized())
{ //taking care of rhs expression
bool rhs = checkCondition(cond.rhs.get().get());
switch (cond.ctype)
{
case '&':
ret &= rhs;
break;
case '|':
ret |= rhs;
break;
case 'X':
ret ^= rhs;
break;
default:
throw EInterpreterProblem(std::string("Strange - wrong condition connection (") + cond.ctype + ") !");
break;
}
}
return ret;
}
FunctionLocalVars * ERMInterpreter::getFuncVars( int funNum )
{
if(funNum >= ARRAY_COUNT(funcVars) || funNum < 0)
throw EScriptExecError("Attempt of accessing variables of function with index out of boundaries!");
return funcVars + funNum;
}
void ERMInterpreter::executeInstructions()
{
//TODO implement me
}
int ERMInterpreter::getRealLine(const LinePointer &lp)
{
for(std::map<VERMInterpreter::LinePointer, ERM::TLine>::const_iterator i = scripts.begin(); i != scripts.end(); i++)
if(i->first.lineNum == lp.lineNum && i->first.file->filename == lp.file->filename)
return i->first.realLineNum;
return -1;
}
void ERMInterpreter::setCurrentlyVisitedObj( int3 pos )
{
ermGlobalEnv->getStandardVar(998) = pos.x;
ermGlobalEnv->getStandardVar(999) = pos.y;
ermGlobalEnv->getStandardVar(1000) = pos.z;
}
const std::string ERMInterpreter::triggerSymbol = "trigger";
const std::string ERMInterpreter::postTriggerSymbol = "postTrigger";
const std::string ERMInterpreter::defunSymbol = "defun";
struct TriggerIdMatchHelper : boost::static_visitor<>
{
int & ret;
ERMInterpreter * interpreter;
Trigger * trig;
TriggerIdMatchHelper(int & b, ERMInterpreter * ermint, Trigger * _trig)
: ret(b), interpreter(ermint), trig(_trig)
{}
void operator()(TIexp const& iexp) const
{
IexpValStr val = interpreter->getIexp(iexp);
switch(val.type)
{
case IexpValStr::INT:
case IexpValStr::INTVAR:
ret = val.getInt();
break;
default:
throw EScriptExecError("Incompatible i-exp type!");
break;
}
}
void operator()(TArithmeticOp const& arop) const
{
//error?!?
}
};
bool TriggerIdentifierMatch::tryMatch( Trigger * interptrig ) const
{
bool ret = true;
const ERM::TTriggerBase & trig = ERMInterpreter::retrieveTrigger(ermEnv->retrieveLine(interptrig->line));
if(trig.identifier.is_initialized())
{
ERM::Tidentifier tid = trig.identifier.get();
std::map< int, std::vector<int> >::const_iterator it = matchToIt.find(tid.size());
if(it == matchToIt.end())
ret = false;
else
{
const std::vector<int> & pattern = it->second;
for(int g=0; g<pattern.size(); ++g)
{
int val = -1;
boost::apply_visitor(TriggerIdMatchHelper(val, ermEnv, interptrig), tid[g]);
if(pattern[g] != val)
{
ret = false;
}
}
}
}
else
{
ret = allowNoIdetifier;
}
//check condition
if(ret)
{
if(trig.condition.is_initialized())
{
return ermEnv->checkCondition(trig.condition.get());
}
else //no condition
return true;
}
else
return false;
}
VERMInterpreter::ERMEnvironment::ERMEnvironment()
{
for(int g=0; g<NUM_QUICKS; ++g)
quickVars[g] = 0;
for(int g=0; g<NUM_STANDARDS; ++g)
standardVars[g] = 0;
//string should be automatically initialized to ""
for(int g=0; g<NUM_FLAGS; ++g)
flags[g] = false;
}
int & VERMInterpreter::ERMEnvironment::getQuickVar( const char letter )
{
assert(letter >= 'f' && letter <= 't'); //it should be check by another function, just making sure here
return quickVars[letter - 'f'];
}
int & VERMInterpreter::ERMEnvironment::getStandardVar( int num )
{
if(num < 1 || num > NUM_STANDARDS)
throw EScriptExecError("Number of standard variable out of bounds");
return standardVars[num-1];
}
std::string & VERMInterpreter::ERMEnvironment::getZVar( int num )
{
if(num < 1 || num > NUM_STRINGS)
throw EScriptExecError("Number of string variable out of bounds");
return strings[num-1];
}
bool & VERMInterpreter::ERMEnvironment::getFlag( int num )
{
if(num < 1 || num > NUM_FLAGS)
throw EScriptExecError("Number of flag out of bounds");
return flags[num-1];
}
VERMInterpreter::TriggerLocalVars::TriggerLocalVars()
{
for(int g=0; g<EVAR_NUM; ++g)
evar[g] = 0.0;
for(int g=0; g<YVAR_NUM; ++g)
yvar[g] = 0;
}
double & VERMInterpreter::TriggerLocalVars::getEvar( int num )
{
num = -num;
if(num < 1 || num > EVAR_NUM)
throw EScriptExecError("Number of trigger local floating point variable out of bounds");
return evar[num-1];
}
int & VERMInterpreter::TriggerLocalVars::getYvar( int num )
{
num = -num; //we handle negative indices
if(num < 1 || num > YVAR_NUM)
throw EScriptExecError("Number of trigger local variable out of bounds");
return yvar[num-1];
}
bool VERMInterpreter::Environment::isBound( const std::string & name, EIsBoundMode mode ) const
{
std::map<std::string, VOption>::const_iterator it = symbols.find(name);
if(mode == LOCAL_ONLY)
{
return it != symbols.end();
}
if(mode == GLOBAL_ONLY && parent)
{
return parent->isBound(name, mode);
}
//we have it; if globalOnly is true, lexical parent is false here so we are global env
if(it != symbols.end())
return true;
//here, we don;t have it; but parent can have
if(parent)
return parent->isBound(name, mode);
return false;
}
VOption & VERMInterpreter::Environment::retrieveValue( const std::string & name )
{
std::map<std::string, VOption>::iterator it = symbols.find(name);
if(it == symbols.end())
{
if(parent)
{
return parent->retrieveValue(name);
}
throw ESymbolNotFound(name);
}
return it->second;
}
bool VERMInterpreter::Environment::unbind( const std::string & name, EUnbindMode mode )
{
if(isBound(name, ANYWHERE))
{
if(symbols.find(name) != symbols.end()) //result of isBound could be from higher lexical env
symbols.erase(symbols.find(name));
if(mode == FULLY_RECURSIVE && parent)
parent->unbind(name, mode);
return true;
}
if(parent && (mode == RECURSIVE_UNTIL_HIT || mode == FULLY_RECURSIVE))
return parent->unbind(name, mode);
//neither bound nor have lexical parent
return false;
}
void VERMInterpreter::Environment::localBind( std::string name, const VOption & sym )
{
symbols[name] = sym;
}
void VERMInterpreter::Environment::setPatent( Environment * _parent )
{
parent = _parent;
}
Environment * VERMInterpreter::Environment::getPatent() const
{
return parent;
}
void VERMInterpreter::Environment::bindAtFirstHit( std::string name, const VOption & sym )
{
if(isBound(name, Environment::LOCAL_ONLY) || !parent)
localBind(name, sym);
else
parent->bindAtFirstHit(name, sym);
}
int & VERMInterpreter::FunctionLocalVars::getParam( int num )
{
if(num < 1 || num > NUM_PARAMETERS)
throw EScriptExecError("Number of parameter out of bounds");
return params[num-1];
}
int & VERMInterpreter::FunctionLocalVars::getLocal( int num )
{
if(num < 1 || num > NUM_LOCALS)
throw EScriptExecError("Number of local variable out of bounds");
return locals[num-1];
}
std::string & VERMInterpreter::FunctionLocalVars::getString( int num )
{
num = -num; //we deal with negative indices
if(num < 1 || num > NUM_PARAMETERS)
throw EScriptExecError("Number of function local string variable out of bounds");
return strings[num-1];
}
double & VERMInterpreter::FunctionLocalVars::getFloat( int num )
{
if(num < 1 || num > NUM_FLOATINGS)
throw EScriptExecError("Number of float var out of bounds");
return floats[num-1];
}
void VERMInterpreter::FunctionLocalVars::reset()
{
for(int g=0; g<ARRAY_COUNT(params); ++g)
params[g] = 0;
for(int g=0; g<ARRAY_COUNT(locals); ++g)
locals[g] = 0;
for(int g=0; g<ARRAY_COUNT(strings); ++g)
strings[g] = "";
for(int g=0; g<ARRAY_COUNT(floats); ++g)
floats[g] = 0.0;
}
void IexpValStr::setTo( const IexpValStr & second )
{
logGlobal->trace("setting %s to %s", getName(), second.getName());
switch(type)
{
case IexpValStr::FLOATVAR:
*val.flvar = second.getFloat();
break;
case IexpValStr::INT:
throw EScriptExecError("VR S: value not assignable!");
break;
case IexpValStr::INTVAR:
*val.integervar = second.getInt();
break;
case IexpValStr::STRINGVAR:
*val.stringvar = second.getString();
break;
default:
throw EScriptExecError("Wrong type of identifier iexp!");
}
}
void IexpValStr::setTo( int val )
{
logGlobal->trace("setting %s to %d", getName(), val);
switch(type)
{
case INTVAR:
*this->val.integervar = val;
break;
default:
throw EIexpProblem("Incompatible type!");
break;
}
}
void IexpValStr::setTo( double val )
{
logGlobal->trace("setting %s to %f", getName(), val);
switch(type)
{
case FLOATVAR:
*this->val.flvar = val;
break;
default:
throw EIexpProblem("Incompatible type!");
break;
}
}
void IexpValStr::setTo( const std::string & val )
{
logGlobal->trace("setting %s to %s", getName(), val);
switch(type)
{
case STRINGVAR:
*this->val.stringvar = val;
break;
default:
throw EIexpProblem("Incompatible type!");
break;
}
}
int IexpValStr::getInt() const
{
switch(type)
{
case IexpValStr::INT:
return val.val;
break;
case IexpValStr::INTVAR:
return *val.integervar;
break;
default:
throw EIexpProblem("Cannot get iexp as int!");
break;
}
}
double IexpValStr::getFloat() const
{
switch(type)
{
case IexpValStr::FLOATVAR:
return *val.flvar;
break;
default:
throw EIexpProblem("Cannot get iexp as float!");
break;
}
}
std::string IexpValStr::getString() const
{
switch(type)
{
case IexpValStr::STRINGVAR:
return *val.stringvar;
break;
default:
throw EScriptExecError("Cannot get iexp as string!");
break;
}
}
std::string IexpValStr::getName() const
{
if(name.size())
{
return name;
}
else if(type == IexpValStr::INT)
{
return "Literal " + boost::lexical_cast<std::string>(getInt());
}
else
return "Unknown variable";
}
void ERMInterpreter::init()
{
ermGlobalEnv = new ERMEnvironment();
globalEnv = new Environment();
//TODO: reset?
for(int g = 0; g < ARRAY_COUNT(funcVars); ++g)
funcVars[g].reset();
scanForScripts();
scanScripts();
executeInstructions();
executeTriggerType("PI");
}
void ERMInterpreter::heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start)
{
if(!visitedObj)
return;
setCurrentlyVisitedObj(visitedObj->pos);
TIDPattern tip;
tip[1] = {visitedObj->ID};
tip[2] = {visitedObj->ID, visitedObj->subID};
tip[3] = {visitedObj->pos.x, visitedObj->pos.y, visitedObj->pos.z};
executeTriggerType(VERMInterpreter::TriggerType("OB"), start, tip);
}
void ERMInterpreter::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
{
executeTriggerType("BA", 0);
executeTriggerType("BR", -1);
executeTriggerType("BF", 0);
//TODO tactics or not
}
const CGObjectInstance * ERMInterpreter::getObjFrom( int3 pos )
{
std::vector<const CGObjectInstance * > objs = icb->getVisitableObjs(pos);
if(!objs.size())
throw EScriptExecError("Attempt to obtain access to nonexistent object!");
return objs.back();
}
struct VOptionPrinter : boost::static_visitor<>
{
void operator()(VNIL const& opt) const
{
logGlobal->error("VNIL");
}
void operator()(VNode const& opt) const
{
logGlobal->error("--vnode (will be supported in future versions)--");
}
void operator()(VSymbol const& opt) const
{
logGlobal->error(opt.text);
}
void operator()(TLiteral const& opt) const
{
logGlobal->error(boost::to_string(opt));
}
void operator()(ERM::Tcommand const& opt) const
{
logGlobal->error("--erm command (will be supported in future versions)--");
}
void operator()(VFunc const& opt) const
{
logGlobal->error("function");
}
};
struct _SbackquoteEval : boost::static_visitor<VOption>
{
VOption operator()(VNIL const& opt) const
{
return opt;
}
VOption operator()(VNode const& opt) const
{
VNode ret = opt;
if(opt.children.size() == 2)
{
VOption fo = opt.children[0];
if(isA<VSymbol>(fo))
{
if(getAs<VSymbol>(fo).text == "comma")
{
return erm->eval(opt.children[1]);
}
}
}
for(int g=0; g<opt.children.size(); ++g)
{
ret.children[g] = boost::apply_visitor(_SbackquoteEval(), ret.children[g]);
}
return ret;
}
VOption operator()(VSymbol const& opt) const
{
return opt;
}
VOption operator()(TLiteral const& opt) const
{
return opt;
}
VOption operator()(ERM::Tcommand const& opt) const
{
boost::apply_visitor(ERMExpDispatch(), opt.cmd);
return opt;
}
VOption operator()(VFunc const& opt) const
{
return opt;
}
};
struct VNodeEvaluator : boost::static_visitor<VOption>
{
Environment & env;
VNode & exp;
VNodeEvaluator(Environment & _env, VNode & _exp) : env(_env), exp(_exp)
{}
VOption operator()(VNIL const& opt) const
{
throw EVermScriptExecError("Nil does not evaluate to a function");
}
VOption operator()(VNode const& opt) const
{
//otherwise...
VNode tmpn(exp);
tmpn.children.car() = erm->eval(opt);
VFunc fun = getAs<VFunc>(tmpn.children.car().getAsItem());
return fun(tmpn.children.cdr());
}
VOption operator()(VSymbol const& opt) const
{
std::map<std::string, VFunc::Eopt> symToFunc =
{
{"<", VFunc::LT},{"<=", VFunc::LE},{">", VFunc::GT},{">=", VFunc::GE},{"=", VFunc::EQ},{"+", VFunc::ADD},{"-", VFunc::SUB},
{"*", VFunc::MULT},{"/", VFunc::DIV},{"%", VFunc::MOD}
};
//check keywords
if(opt.text == "quote")
{
if(exp.children.size() == 2)
return exp.children[1];
else
throw EVermScriptExecError("quote special form takes only one argument");
}
else if(opt.text == "backquote")
{
if(exp.children.size() == 2)
return boost::apply_visitor(_SbackquoteEval(), exp.children[1]);
else
throw EVermScriptExecError("backquote special form takes only one argument");
}
else if(opt.text == "if")
{
if(exp.children.size() > 4)
throw EVermScriptExecError("if statement takes no more than three arguments");
if( !isA<VNIL>(erm->eval(exp.children[1]) ) )
{
if(exp.children.size() > 2)
return erm->eval(exp.children[2]);
else
throw EVermScriptExecError("this if form needs at least two arguments");
}
else
{
if(exp.children.size() > 3)
return erm->eval(exp.children[3]);
else
throw EVermScriptExecError("this if form needs at least three arguments");
}
}
else if(opt.text == "lambda")
{
if(exp.children.size() <= 2)
{
throw EVermScriptExecError("Too few arguments for lambda special form");
}
VFunc ret(exp.children.cdr().getAsCDR().getAsList());
VNode arglist = getAs<VNode>(exp.children[1]);
for(int g=0; g<arglist.children.size(); ++g)
{
ret.args.push_back(getAs<VSymbol>(arglist.children[g]));
}
return ret;
}
else if(opt.text == "print")
{
if(exp.children.size() == 2)
{
VOption printed = erm->eval(exp.children[1]);
boost::apply_visitor(VOptionPrinter(), printed);
return printed;
}
else
throw EVermScriptExecError("print special form takes only one argument");
}
else if(opt.text == "setq")
{
if(exp.children.size() != 3)
throw EVermScriptExecError("setq special form takes exactly 2 arguments");
env.bindAtFirstHit( getAs<VSymbol>(exp.children[1]).text, erm->eval(exp.children[2]));
return getAs<VSymbol>(exp.children[1]);
}
else if(opt.text == "defun")
{
if(exp.children.size() < 4)
{
throw EVermScriptExecError("defun special form takes at least 3 arguments");
}
VFunc f(exp.children.cdr().getAsCDR().getAsCDR().getAsList());
VNode arglist = getAs<VNode>(exp.children[2]);
for(int g=0; g<arglist.children.size(); ++g)
{
f.args.push_back(getAs<VSymbol>(arglist.children[g]));
}
env.localBind(getAs<VSymbol>(exp.children[1]).text, f);
return f;
}
else if(opt.text == "defmacro")
{
if(exp.children.size() < 4)
{
throw EVermScriptExecError("defmacro special form takes at least 3 arguments");
}
VFunc f(exp.children.cdr().getAsCDR().getAsCDR().getAsList(), true);
VNode arglist = getAs<VNode>(exp.children[2]);
for(int g=0; g<arglist.children.size(); ++g)
{
f.args.push_back(getAs<VSymbol>(arglist.children[g]));
}
env.localBind(getAs<VSymbol>(exp.children[1]).text, f);
return f;
}
else if(opt.text == "progn")
{
for(int g=1; g<exp.children.size(); ++g)
{
if(g < exp.children.size()-1)
erm->eval(exp.children[g]);
else
return erm->eval(exp.children[g]);
}
return VNIL();
}
else if(opt.text == "do") //evaluates second argument as long first evaluates to non-nil
{
if(exp.children.size() != 3)
{
throw EVermScriptExecError("do special form takes exactly 2 arguments");
}
while(!isA<VNIL>(erm->eval(exp.children[1])))
{
erm->eval(exp.children[2]);
}
return VNIL();
}
//"apply" part of eval, a bit blurred in this implementation but this way it looks good too
else if(symToFunc.find(opt.text) != symToFunc.end())
{
VFunc f(symToFunc[opt.text]);
if(f.macro)
{
return f(exp.children.cdr());
}
else
{
VOptionList ls = erm->evalEach(exp.children.cdr());
return f(VermTreeIterator(ls));
}
}
else if(topDyn->isBound(opt.text, Environment::ANYWHERE))
{
VOption & bValue = topDyn->retrieveValue(opt.text);
if(!isA<VFunc>(bValue))
{
throw EVermScriptExecError("This value does not evaluate to a function!");
}
VFunc f = getAs<VFunc>(bValue);
VOptionList ls = f.macro ? exp.children.cdr().getAsList() : erm->evalEach(exp.children.cdr());
return f(VermTreeIterator(ls));
}
logGlobal->error("Cannot evaluate:");
printVOption(exp);
throw EVermScriptExecError("Cannot evaluate given expression");
}
VOption operator()(TLiteral const& opt) const
{
throw EVermScriptExecError("String literal does not evaluate to a function");
}
VOption operator()(ERM::Tcommand const& opt) const
{
throw EVermScriptExecError("ERM command does not evaluate to a function");
}
VOption operator()(VFunc const& opt) const
{
return opt;
}
};
struct VEvaluator : boost::static_visitor<VOption>
{
Environment & env;
VEvaluator(Environment & _env) : env(_env)
{}
VOption operator()(VNIL const& opt) const
{
return opt;
}
VOption operator()(VNode const& opt) const
{
if(opt.children.size() == 0)
return VNIL();
else
{
VOption & car = const_cast<VNode&>(opt).children.car().getAsItem();
return boost::apply_visitor(VNodeEvaluator(env, const_cast<VNode&>(opt)), car);
}
}
VOption operator()(VSymbol const& opt) const
{
return env.retrieveValue(opt.text);
}
VOption operator()(TLiteral const& opt) const
{
return opt;
}
VOption operator()(ERM::Tcommand const& opt) const
{
return VNIL();
}
VOption operator()(VFunc const& opt) const
{
return opt;
}
};
VOption ERMInterpreter::eval(VOption line, Environment * env)
{
// if(line.children.isNil())
// return;
//
// VOption & car = line.children.car().getAsItem();
logGlobal->trace("\tevaluating ");
printVOption(line);
return boost::apply_visitor(VEvaluator(env ? *env : *topDyn), line);
}
VOptionList ERMInterpreter::evalEach(VermTreeIterator list, Environment * env)
{
VOptionList ret;
for(int g=0; g<list.size(); ++g)
{
ret.push_back(eval(list.getIth(g), env));
}
return ret;
}
void ERMInterpreter::executeUserCommand(const std::string &cmd)
{
logGlobal->trace("ERM here: received command: %s", cmd);
if(cmd.size() < 3)
{
logGlobal->error("That can't be a valid command: %s", cmd);
return;
}
try
{
if(cmd[0] == '!') //should be a neat (V)ERM command
{
ERM::TLine line = ERMParser::parseLine(cmd);
executeLine(line);
}
}
catch(std::exception &e)
{
logGlobal->error("Failed executing user command! Exception info: %s", e.what());
}
}
void ERMInterpreter::giveInfoCB(CPrivilegedInfoCallback *cb)
{
icb = cb;
}
void ERMInterpreter::giveActionCB(IGameEventRealizer *cb)
{
acb = cb;
}
namespace VERMInterpreter
{
VOption convertToVOption(const ERM::TVOption & tvo)
{
return boost::apply_visitor(OptionConverterVisitor(), tvo);
}
VNode::VNode( const ERM::TVExp & exp )
{
for(int i=0; i<exp.children.size(); ++i)
{
children.push_back(convertToVOption(exp.children[i]));
}
processModifierList(exp.modifier, false);
}
VNode::VNode( const VOption & first, const VOptionList & rest ) /*merges given arguments into [a, rest] */
{
setVnode(first, rest);
}
VNode::VNode( const VOptionList & cdren ) : children(cdren)
{}
VNode::VNode( const ERM::TSymbol & sym )
{
children.car() = VSymbol(sym.sym);
processModifierList(sym.symModifier, true);
}
void VNode::setVnode( const VOption & first, const VOptionList & rest )
{
children.car() = first;
children.cdr() = rest;
}
void VNode::processModifierList( const std::vector<TVModifier> & modifierList, bool asSymbol )
{
for(int g=0; g<modifierList.size(); ++g)
{
if(asSymbol)
{
children.resize(children.size()+1);
for(int i=children.size()-1; i >0; i--)
{
children[i] = children[i-1];
}
}
else
{
children.cdr() = VNode(children);
}
if(modifierList[g] == "`")
{
children.car() = VSymbol("backquote");
}
else if(modifierList[g] == ",!")
{
children.car() = VSymbol("comma-unlist");
}
else if(modifierList[g] == ",")
{
children.car() = VSymbol("comma");
}
else if(modifierList[g] == "#'")
{
children.car() = VSymbol("get-func");
}
else if(modifierList[g] == "'")
{
children.car() = VSymbol("quote");
}
else
throw EInterpreterError("Incorrect value of modifier!");
}
}
VermTreeIterator & VermTreeIterator::operator=( const VOption & opt )
{
switch (state)
{
case CAR:
if(parent->size() <= basePos)
parent->push_back(opt);
else
(*parent)[basePos] = opt;
break;
case NORM:
parent->resize(basePos+1);
(*parent)[basePos] = opt;
break;
default://should never happen
break;
}
return *this;
}
VermTreeIterator & VermTreeIterator::operator=( const std::vector<VOption> & opt )
{
switch (state)
{
case CAR:
//TODO: implement me
break;
case NORM:
parent->resize(basePos+1);
parent->insert(parent->begin()+basePos, opt.begin(), opt.end());
break;
default://should never happen
break;
}
return *this;
}
VermTreeIterator & VermTreeIterator::operator=( const VOptionList & opt )
{
return *this = opt;
}
VOption & VermTreeIterator::getAsItem()
{
if(state == CAR)
return (*parent)[basePos];
else
throw EInterpreterError("iterator is not in car state, cannot get as list");
}
VermTreeIterator VermTreeIterator::getAsCDR()
{
VermTreeIterator ret = *this;
ret.basePos++;
return ret;
}
VOption & VermTreeIterator::getIth( int i )
{
return (*parent)[basePos + i];
}
size_t VermTreeIterator::size() const
{
return parent->size() - basePos;
}
VERMInterpreter::VOptionList VermTreeIterator::getAsList()
{
VOptionList ret;
for(int g = basePos; g<parent->size(); ++g)
{
ret.push_back((*parent)[g]);
}
return ret;
}
VOption OptionConverterVisitor::operator()( ERM::TVExp const& cmd ) const
{
return VNode(cmd);
}
VOption OptionConverterVisitor::operator()( ERM::TSymbol const& cmd ) const
{
if(cmd.symModifier.size() == 0)
return VSymbol(cmd.sym);
else
return VNode(cmd);
}
VOption OptionConverterVisitor::operator()( char const& cmd ) const
{
return TLiteral(cmd);
}
VOption OptionConverterVisitor::operator()( double const& cmd ) const
{
return TLiteral(cmd);
}
VOption OptionConverterVisitor::operator()(int const& cmd) const
{
return TLiteral(cmd);
}
VOption OptionConverterVisitor::operator()(ERM::Tcommand const& cmd) const
{
return cmd;
}
VOption OptionConverterVisitor::operator()( ERM::TStringConstant const& cmd ) const
{
return TLiteral(cmd.str);
}
bool VOptionList::isNil() const
{
return size() == 0;
}
VermTreeIterator VOptionList::cdr()
{
VermTreeIterator ret(*this);
ret.basePos = 1;
return ret;
}
VermTreeIterator VOptionList::car()
{
VermTreeIterator ret(*this);
ret.state = VermTreeIterator::CAR;
return ret;
}
VERMInterpreter::VOption VFunc::operator()( VermTreeIterator params )
{
switch(option)
{
case DEFAULT:
{
if(params.size() != args.size())
{
throw EVermScriptExecError("Expected " + boost::lexical_cast<std::string>(args.size()) + " arguments!");
}
IntroduceDynamicEnv dyn;
for(int i=0; i<args.size(); ++i)
{
if(macro)
topDyn->localBind(args[i].text, params.getIth(i));
else
topDyn->localBind(args[i].text, erm->eval(params.getIth(i)));
}
//execute
VOptionList toEval = body;
if(macro)
{
//first evaluation (in place of definition)
toEval = erm->evalEach(toEval);
}
//second evaluation for macros/evaluation of funcs
VOptionList ret = erm->evalEach(toEval);
return ret[ret.size()-1];
}
break;
case LT:
{
if(params.size() != 2)
throw EVermScriptExecError("< special function takes exactly 2 arguments");
TLiteral lhs = getAs<TLiteral>(params.getIth(0)),
rhs = getAs<TLiteral>(params.getIth(1));
if(lhs < rhs)
return lhs;
else
return VNIL();
}
break;
case LE:
{
if(params.size() != 2)
throw EVermScriptExecError("<= special function takes exactly 2 arguments");
TLiteral lhs = getAs<TLiteral>(params.getIth(0)),
rhs = getAs<TLiteral>(params.getIth(1));
if(lhs <= rhs)
return lhs;
else
return VNIL();
}
break;
case GT:
{
if(params.size() != 2)
throw EVermScriptExecError("> special function takes exactly 2 arguments");
TLiteral lhs = getAs<TLiteral>(params.getIth(0)),
rhs = getAs<TLiteral>(params.getIth(1));
if(lhs >= rhs)
return lhs;
else
return VNIL();
}
break;
case GE:
{
if(params.size() != 2)
throw EVermScriptExecError(">= special function takes exactly 2 arguments");
TLiteral lhs = getAs<TLiteral>(params.getIth(0)),
rhs = getAs<TLiteral>(params.getIth(1));
if(lhs >= rhs)
return lhs;
else
return VNIL();
}
break;
case EQ:
{
if(params.size() != 2)
throw EVermScriptExecError("= special function takes exactly 2 arguments");
printVOption(params.getIth(0));
printVOption(params.getIth(1));
TLiteral lhs = getAs<TLiteral>(params.getIth(0)),
rhs = getAs<TLiteral>(params.getIth(1));
if(lhs.type() == rhs.type())
{
if(boost::apply_visitor(_opEQvis(lhs), rhs))
return lhs;
else
return VNIL();
}
else
throw EVermScriptExecError("Incompatible types in = special function");
}
break;
case ADD:
{
if(params.size() == 0)
throw EVermScriptExecError("+ special function takes at least 1 argument");
TLiteral par1 = getAs<TLiteral>(params.getIth(0));
int retI = 0;
double retD = 0.0;
int used = isA<int>(par1) ? 0 : 1;
for(int i=0; i<params.size(); ++i)
{
if(used == 0)
retI += getAs<int>(getAs<TLiteral>(params.getIth(i)));
else
retD += getAs<double>(getAs<TLiteral>(params.getIth(i)));
}
if(used == 0)
return retI;
else
return retD;
}
break;
case SUB:
{
if(params.size() != 2)
throw EVermScriptExecError("- special function takes at least 2 argument");
TLiteral par1 = getAs<TLiteral>(params.getIth(0));
int used = isA<int>(par1) ? 0 : 1;
if(used == 0)
return getAs<int>(getAs<TLiteral>(params.getIth(0))) - getAs<int>(getAs<TLiteral>(params.getIth(1)));
else
return getAs<double>(getAs<TLiteral>(params.getIth(1))) - getAs<double>(getAs<TLiteral>(params.getIth(1)));
}
break;
case MULT:
{
if(params.size() == 0)
throw EVermScriptExecError("* special function takes at least 1 argument");
TLiteral par1 = getAs<TLiteral>(params.getIth(0));
int retI = 1;
double retD = 1.0;
int used = isA<int>(par1) ? 0 : 1;
for(int i=0; i<params.size(); ++i)
{
if(used == 0)
retI *= getAs<int>(getAs<TLiteral>(params.getIth(i)));
else
retD *= getAs<double>(getAs<TLiteral>(params.getIth(i)));
}
if(used == 0)
return retI;
else
return retD;
}
break;
case DIV:
{
if(params.size() != 2)
throw EVermScriptExecError("/ special function takes at least 2 argument");
TLiteral par1 = getAs<TLiteral>(params.getIth(0));
int used = isA<int>(par1) ? 0 : 1;
if(used == 0)
return getAs<int>(getAs<TLiteral>(params.getIth(0))) / getAs<int>(getAs<TLiteral>(params.getIth(1)));
else
return getAs<double>(getAs<TLiteral>(params.getIth(1))) / getAs<double>(getAs<TLiteral>(params.getIth(1)));
}
break;
case MOD:
{
if(params.size() != 2)
throw EVermScriptExecError("% special function takes at least 2 argument");
return getAs<int>(getAs<TLiteral>(params.getIth(0))) % getAs<int>(getAs<TLiteral>(params.getIth(1)));
}
break;
default:
throw EInterpreterError("VFunc in forbidden mode!");
break;
}
}
IntroduceDynamicEnv::IntroduceDynamicEnv()
{
Environment * nen = new Environment();
nen->setPatent(topDyn);
topDyn = nen;
}
IntroduceDynamicEnv::~IntroduceDynamicEnv()
{
topDyn->setPatent(topDyn->getPatent());
}
bool operator<=(const TLiteral & t1, const TLiteral & t2)
{
if(t1.type() == t2.type())
{
return boost::apply_visitor(_opLEvis(t1), t2);
}
throw EVermScriptExecError("These types are incomparable!");
}
bool operator>(const TLiteral & t1, const TLiteral & t2)
{
if(t1.type() == t2.type())
{
return boost::apply_visitor(_opGTvis(t1), t2);
}
throw EVermScriptExecError("These types are incomparable!");
}
bool operator>=(const TLiteral & t1, const TLiteral & t2)
{
if(t1.type() == t2.type())
{
return boost::apply_visitor(_opGEvis(t1), t2);
}
throw EVermScriptExecError("These types are incomparable!");
}
struct _VLITPrinter : boost::static_visitor<void>
{
void operator()(const std::string & par) const
{
logGlobal->debug("^%s^", par);
}
template<typename T>
void operator()(const T & par) const
{
logGlobal->debug(boost::to_string(par));
}
};
struct _VOPTPrinter : boost::static_visitor<void>
{
void operator()(VNIL const& opt) const
{
logGlobal->debug("[]");
}
void operator()(VNode const& opt) const
{
logGlobal->debug("[");
for(int g=0; g<opt.children.size(); ++g)
{
boost::apply_visitor(_VOPTPrinter(), opt.children[g]);
logGlobal->debug(" ");
}
logGlobal->debug("]");
}
void operator()(VSymbol const& opt) const
{
logGlobal->debug(opt.text);
}
void operator()(TLiteral const& opt) const
{
boost::apply_visitor(_VLITPrinter(), opt);
}
void operator()(ERM::Tcommand const& opt) const
{
logGlobal->debug("--erm--");
}
void operator()(VFunc const& opt) const
{
logGlobal->debug("function");
}
};
void printVOption(const VOption & opt)
{
boost::apply_visitor(_VOPTPrinter(), opt);
}
}
|