1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925
|
/*
AngelCode Scripting Library
Copyright (c) 2003-2021 Andreas Jonsson
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
The original version of this library can be located at:
http://www.angelcode.com/angelscript/
Andreas Jonsson
andreas@angelcode.com
*/
//
// as_scriptengine.cpp
//
// The implementation of the script engine interface
//
#include <stdlib.h>
#include "as_config.h"
#include "as_scriptengine.h"
#include "as_builder.h"
#include "as_context.h"
#include "as_string_util.h"
#include "as_tokenizer.h"
#include "as_texts.h"
#include "as_module.h"
#include "as_callfunc.h"
#include "as_generic.h"
#include "as_scriptobject.h"
#include "as_compiler.h"
#include "as_bytecode.h"
#include "as_debug.h"
BEGIN_AS_NAMESPACE
#ifdef AS_PROFILE
// Instantiate the profiler once
CProfiler g_profiler;
#endif
extern "C"
{
AS_API const char *asGetLibraryVersion() {
#ifdef _DEBUG
return ANGELSCRIPT_VERSION_STRING " DEBUG";
#else
return ANGELSCRIPT_VERSION_STRING;
#endif
}
AS_API const char *asGetLibraryOptions() {
const char *string = " "
// Options
#ifdef AS_MAX_PORTABILITY
"AS_MAX_PORTABILITY "
#endif
#ifdef AS_DEBUG
"AS_DEBUG "
#endif
#ifdef AS_NO_CLASS_METHODS
"AS_NO_CLASS_METHODS "
#endif
#ifdef AS_USE_DOUBLE_AS_FLOAT
"AS_USE_DOUBLE_AS_FLOAT "
#endif
#ifdef AS_64BIT_PTR
"AS_64BIT_PTR "
#endif
#ifdef AS_NO_THREADS
"AS_NO_THREADS "
#endif
#ifdef AS_NO_ATOMIC
"AS_NO_ATOMIC "
#endif
#ifdef AS_NO_COMPILER
"AS_NO_COMPILER "
#endif
#ifdef AS_NO_MEMBER_INIT
"AS_NO_MEMBER_INIT "
#endif
#ifdef AS_NO_THISCALL_FUNCTOR_METHOD
"AS_NO_THISCALL_FUNCTOR_METHOD "
#endif
#ifdef AS_NO_EXCEPTIONS
"AS_NO_EXCEPTIONS "
#endif
#ifdef WIP_16BYTE_ALIGN
"WIP_16BYTE_ALIGN "
#endif
#ifdef AS_BIG_ENDIAN
"AS_BIG_ENDIAN "
#endif
// Target system
#ifdef AS_WIN
"AS_WIN "
#endif
#ifdef AS_LINUX
"AS_LINUX "
#endif
#ifdef AS_MAC
"AS_MAC "
#endif
#ifdef AS_SUN
"AS_SUN "
#endif
#ifdef AS_BSD
"AS_BSD "
#endif
#ifdef AS_XBOX
"AS_XBOX "
#endif
#ifdef AS_XBOX360
"AS_XBOX360 "
#endif
#ifdef AS_PSP
"AS_PSP "
#endif
#ifdef AS_PS2
"AS_PS2 "
#endif
#ifdef AS_PS3
"AS_PS3 "
#endif
#ifdef AS_PSVITA
"AS_PSVITA "
#endif
#ifdef AS_DC
"AS_DC "
#endif
#ifdef AS_GC
"AS_GC "
#endif
#ifdef AS_WII
"AS_WII "
#endif
#ifdef AS_WIIU
"AS_WIIU "
#endif
#ifdef AS_IPHONE
"AS_IPHONE "
#endif
#ifdef AS_ANDROID
"AS_ANDROID "
#endif
#ifdef AS_HAIKU
"AS_HAIKU "
#endif
#ifdef AS_ILLUMOS
"AS_ILLUMOS "
#endif
#ifdef AS_MARMALADE
"AS_MARMALADE "
#endif
// CPU family
#ifdef AS_PPC
"AS_PPC "
#endif
#ifdef AS_PPC_64
"AS_PPC_64 "
#endif
#ifdef AS_X86
"AS_X86 "
#endif
#ifdef AS_MIPS
"AS_MIPS "
#endif
#ifdef AS_SH4
"AS_SH4 "
#endif
#ifdef AS_XENON
"AS_XENON "
#endif
#ifdef AS_ARM
"AS_ARM "
#endif
#ifdef AS_SOFTFP
"AS_SOFTFP "
#endif
#ifdef AS_X64_GCC
"AS_X64_GCC "
#endif
#ifdef AS_X64_MSVC
"AS_X64_MSVC "
#endif
#ifdef AS_SPARC
"AS_SPARC "
#endif
#ifdef AS_ARM64
"AS_ARM64 "
#endif
;
return string;
}
AS_API asIScriptEngine *asCreateScriptEngine(asDWORD version) {
// Verify the version that the application expects
if ((version / 10000) != (ANGELSCRIPT_VERSION / 10000))
return 0;
if ((version / 100) % 100 != (ANGELSCRIPT_VERSION / 100) % 100)
return 0;
if ((version % 100) > (ANGELSCRIPT_VERSION % 100))
return 0;
// Verify the size of the types
asASSERT(sizeof(asBYTE) == 1);
asASSERT(sizeof(asWORD) == 2);
asASSERT(sizeof(asDWORD) == 4);
asASSERT(sizeof(asQWORD) == 8);
asASSERT(sizeof(asPWORD) == sizeof(void *));
// Verify the boolean type
asASSERT(sizeof(bool) == AS_SIZEOF_BOOL);
asASSERT(true == VALUE_OF_BOOLEAN_TRUE);
// Verify endianess
#ifdef AS_BIG_ENDIAN
asDWORD dw = 0x00010203;
asQWORD qw = ((asQWORD(0x00010203) << 32) | asQWORD(0x04050607));
#else
asDWORD dw = 0x03020100;
// C++ didn't have a standard way of declaring 64bit literal constants until C++11, so
// I'm forced to do it like this to avoid compilers warnings when compiling with the full
// C++ compliance.
asQWORD qw = ((asQWORD(0x07060504) << 32) | asQWORD(0x03020100));
#endif
asASSERT(memcmp("\x00\x01\x02\x03", &dw, 4) == 0);
asASSERT(memcmp("\x00\x01\x02\x03\x04\x05\x06\x07", &qw, 8) == 0);
UNUSED_VAR(dw);
UNUSED_VAR(qw);
return asNEW(asCScriptEngine)();
}
} // extern "C"
// interface
int asCScriptEngine::SetEngineProperty(asEEngineProp property, asPWORD value) {
switch (property) {
case asEP_ALLOW_UNSAFE_REFERENCES:
ep.allowUnsafeReferences = value ? true : false;
break;
case asEP_OPTIMIZE_BYTECODE:
ep.optimizeByteCode = value ? true : false;
break;
case asEP_COPY_SCRIPT_SECTIONS:
ep.copyScriptSections = value ? true : false;
break;
case asEP_MAX_STACK_SIZE:
if (value == 0) {
// Restore default: no limit and initially size 4KB
ep.maximumContextStackSize = 0;
} else {
// The size is given in bytes, but we only store dwords
ep.maximumContextStackSize = (asUINT)value / 4;
}
break;
case asEP_INIT_STACK_SIZE:
if (value < 4) {
// At least one dword
ep.initContextStackSize = 1;
} else {
// The size is given in bytes, but we only store dwords
ep.initContextStackSize = (asUINT)value / 4;
}
break;
case asEP_USE_CHARACTER_LITERALS:
ep.useCharacterLiterals = value ? true : false;
break;
case asEP_ALLOW_MULTILINE_STRINGS:
ep.allowMultilineStrings = value ? true : false;
break;
case asEP_ALLOW_IMPLICIT_HANDLE_TYPES:
ep.allowImplicitHandleTypes = value ? true : false;
break;
case asEP_BUILD_WITHOUT_LINE_CUES:
ep.buildWithoutLineCues = value ? true : false;
break;
case asEP_INIT_GLOBAL_VARS_AFTER_BUILD:
ep.initGlobalVarsAfterBuild = value ? true : false;
break;
case asEP_REQUIRE_ENUM_SCOPE:
ep.requireEnumScope = value ? true : false;
break;
case asEP_SCRIPT_SCANNER:
if (value <= 1)
ep.scanner = (int)value;
else
return asINVALID_ARG;
break;
case asEP_INCLUDE_JIT_INSTRUCTIONS:
ep.includeJitInstructions = value ? true : false;
break;
case asEP_STRING_ENCODING:
if (value <= 1)
ep.stringEncoding = (int)value;
else
return asINVALID_ARG;
break;
case asEP_PROPERTY_ACCESSOR_MODE:
if (value <= 3)
ep.propertyAccessorMode = (int)value;
else
return asINVALID_ARG;
break;
case asEP_EXPAND_DEF_ARRAY_TO_TMPL:
ep.expandDefaultArrayToTemplate = value ? true : false;
break;
case asEP_AUTO_GARBAGE_COLLECT:
ep.autoGarbageCollect = value ? true : false;
break;
case asEP_DISALLOW_GLOBAL_VARS:
ep.disallowGlobalVars = value ? true : false;
break;
case asEP_ALWAYS_IMPL_DEFAULT_CONSTRUCT:
ep.alwaysImplDefaultConstruct = value ? true : false;
break;
case asEP_COMPILER_WARNINGS:
if (value <= 2)
ep.compilerWarnings = (int)value;
else
return asINVALID_ARG;
break;
case asEP_DISALLOW_VALUE_ASSIGN_FOR_REF_TYPE:
ep.disallowValueAssignForRefType = value ? true : false;
break;
case asEP_ALTER_SYNTAX_NAMED_ARGS:
if (value <= 2)
ep.alterSyntaxNamedArgs = (int)value;
else
return asINVALID_ARG;
break;
case asEP_DISABLE_INTEGER_DIVISION:
ep.disableIntegerDivision = value ? true : false;
break;
case asEP_DISALLOW_EMPTY_LIST_ELEMENTS:
ep.disallowEmptyListElements = value ? true : false;
break;
case asEP_PRIVATE_PROP_AS_PROTECTED:
ep.privatePropAsProtected = value ? true : false;
break;
case asEP_ALLOW_UNICODE_IDENTIFIERS:
ep.allowUnicodeIdentifiers = value ? true : false;
break;
case asEP_HEREDOC_TRIM_MODE:
if (value <= 2)
ep.heredocTrimMode = (int)value;
else
return asINVALID_ARG;
break;
case asEP_MAX_NESTED_CALLS:
if (value > 0xFFFFFFFF)
ep.maxNestedCalls = 0xFFFFFFFF;
else
ep.maxNestedCalls = (asUINT)value;
break;
case asEP_GENERIC_CALL_MODE:
if (value > 1)
ep.genericCallMode = 1;
else
ep.genericCallMode = (asUINT)value;
break;
case asEP_INIT_CALL_STACK_SIZE:
ep.initCallStackSize = (asUINT)value;
break;
case asEP_MAX_CALL_STACK_SIZE:
ep.maxCallStackSize = (asUINT)value;
break;
default:
return asINVALID_ARG;
}
return asSUCCESS;
}
// interface
asPWORD asCScriptEngine::GetEngineProperty(asEEngineProp property) const {
switch (property) {
case asEP_ALLOW_UNSAFE_REFERENCES:
return ep.allowUnsafeReferences;
case asEP_OPTIMIZE_BYTECODE:
return ep.optimizeByteCode;
case asEP_COPY_SCRIPT_SECTIONS:
return ep.copyScriptSections;
case asEP_MAX_STACK_SIZE:
return ep.maximumContextStackSize * 4;
case asEP_INIT_STACK_SIZE:
return ep.initContextStackSize * 4;
case asEP_USE_CHARACTER_LITERALS:
return ep.useCharacterLiterals;
case asEP_ALLOW_MULTILINE_STRINGS:
return ep.allowMultilineStrings;
case asEP_ALLOW_IMPLICIT_HANDLE_TYPES:
return ep.allowImplicitHandleTypes;
case asEP_BUILD_WITHOUT_LINE_CUES:
return ep.buildWithoutLineCues;
case asEP_INIT_GLOBAL_VARS_AFTER_BUILD:
return ep.initGlobalVarsAfterBuild;
case asEP_REQUIRE_ENUM_SCOPE:
return ep.requireEnumScope;
case asEP_SCRIPT_SCANNER:
return ep.scanner;
case asEP_INCLUDE_JIT_INSTRUCTIONS:
return ep.includeJitInstructions;
case asEP_STRING_ENCODING:
return ep.stringEncoding;
case asEP_PROPERTY_ACCESSOR_MODE:
return ep.propertyAccessorMode;
case asEP_EXPAND_DEF_ARRAY_TO_TMPL:
return ep.expandDefaultArrayToTemplate;
case asEP_AUTO_GARBAGE_COLLECT:
return ep.autoGarbageCollect;
case asEP_DISALLOW_GLOBAL_VARS:
return ep.disallowGlobalVars;
case asEP_ALWAYS_IMPL_DEFAULT_CONSTRUCT:
return ep.alwaysImplDefaultConstruct;
case asEP_COMPILER_WARNINGS:
return ep.compilerWarnings;
case asEP_DISALLOW_VALUE_ASSIGN_FOR_REF_TYPE:
return ep.disallowValueAssignForRefType;
case asEP_ALTER_SYNTAX_NAMED_ARGS:
return ep.alterSyntaxNamedArgs;
case asEP_DISABLE_INTEGER_DIVISION:
return ep.disableIntegerDivision;
case asEP_DISALLOW_EMPTY_LIST_ELEMENTS:
return ep.disallowEmptyListElements;
case asEP_PRIVATE_PROP_AS_PROTECTED:
return ep.privatePropAsProtected;
case asEP_ALLOW_UNICODE_IDENTIFIERS:
return ep.allowUnicodeIdentifiers;
case asEP_HEREDOC_TRIM_MODE:
return ep.heredocTrimMode;
case asEP_MAX_NESTED_CALLS:
return ep.maxNestedCalls;
case asEP_GENERIC_CALL_MODE:
return ep.genericCallMode;
case asEP_INIT_CALL_STACK_SIZE:
return ep.initCallStackSize;
case asEP_MAX_CALL_STACK_SIZE:
return ep.maxCallStackSize;
default:
return 0;
}
UNREACHABLE_RETURN;
}
// interface
asIScriptFunction *asCScriptEngine::CreateDelegate(asIScriptFunction *func, void *obj) {
if (func == 0 || obj == 0)
return 0;
// The function must be a class method
asITypeInfo *type = func->GetObjectType();
if (type == 0)
return 0;
// The object type must allow handles
if ((type->GetFlags() & asOBJ_REF) == 0 || (type->GetFlags() & (asOBJ_SCOPED | asOBJ_NOHANDLE)))
return 0;
// Create the delegate the same way it would be created by the scripts
return AS_NAMESPACE_QUALIFIER CreateDelegate(reinterpret_cast<asCScriptFunction *>(func), obj);
}
asCScriptEngine::asCScriptEngine() {
asCThreadManager::Prepare(0);
shuttingDown = false;
inDestructor = false;
// Engine properties
{
ep.allowUnsafeReferences = false;
ep.optimizeByteCode = true;
ep.copyScriptSections = true;
ep.maximumContextStackSize = 0; // no limit
ep.initContextStackSize = 1024; // 4KB default init stack size
ep.useCharacterLiterals = false;
ep.allowMultilineStrings = false;
ep.allowImplicitHandleTypes = false;
// TODO: optimize: Maybe this should be turned off by default? If a debugger is not used
// then this is just slowing down the execution.
ep.buildWithoutLineCues = false;
ep.initGlobalVarsAfterBuild = true;
ep.requireEnumScope = false;
ep.scanner = 1; // utf8. 0 = ascii
ep.includeJitInstructions = false;
ep.stringEncoding = 0; // utf8. 1 = utf16
ep.propertyAccessorMode = 3; // 0 = disable, 1 = app registered only, 2 = app and script created, 3 = flag with 'property'
ep.expandDefaultArrayToTemplate = false;
ep.autoGarbageCollect = true;
ep.disallowGlobalVars = false;
ep.alwaysImplDefaultConstruct = false;
ep.compilerWarnings = 1; // 0 = no warnings, 1 = warning, 2 = treat as error
// TODO: 3.0.0: disallowValueAssignForRefType should be true by default
ep.disallowValueAssignForRefType = false;
ep.alterSyntaxNamedArgs = 0; // 0 = no alternate syntax, 1 = accept alternate syntax but warn, 2 = accept without warning
ep.disableIntegerDivision = false;
ep.disallowEmptyListElements = false;
ep.privatePropAsProtected = false;
ep.allowUnicodeIdentifiers = false;
ep.heredocTrimMode = 1; // 0 = never trim, 1 = don't trim on single line, 2 = trim initial and final empty line
ep.maxNestedCalls = 100;
ep.genericCallMode = 1; // 0 = old (pre 2.33.0) behavior where generic ignored auto handles, 1 = treat handles like in native call
ep.initCallStackSize = 10; // 10 levels of calls
ep.maxCallStackSize = 0; // 0 = no limit
}
gc.engine = this;
tok.engine = this;
refCount.set(1);
stringFactory = 0;
configFailed = false;
isPrepared = false;
isBuilding = false;
deferValidationOfTemplateTypes = false;
lastModule = 0;
typeIdSeqNbr = 0;
currentGroup = &defaultGroup;
defaultAccessMask = 0xFFFFFFFF; // All bits set so that built-in functions/types will be available to all modules
msgCallback = 0;
jitCompiler = 0;
// Create the global namespace
defaultNamespace = AddNameSpace("");
requestCtxFunc = 0;
returnCtxFunc = 0;
ctxCallbackParam = 0;
// We must set the namespace in the built-in types explicitly as
// this wasn't done by the default constructor. If we do not do
// this we will get null pointer access in other parts of the code
scriptTypeBehaviours.nameSpace = defaultNamespace;
functionBehaviours.nameSpace = defaultNamespace;
// Reserve function id 0 for no function
scriptFunctions.PushLast(0);
// Reserve the first typeIds for the primitive types
typeIdSeqNbr = asTYPEID_DOUBLE + 1;
// Make sure typeId for the built-in primitives are defined according to asETypeIdFlags
asASSERT(GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttVoid, false)) == asTYPEID_VOID);
asASSERT(GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttBool, false)) == asTYPEID_BOOL);
asASSERT(GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttInt8, false)) == asTYPEID_INT8);
asASSERT(GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttInt16, false)) == asTYPEID_INT16);
asASSERT(GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttInt, false)) == asTYPEID_INT32);
asASSERT(GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttInt64, false)) == asTYPEID_INT64);
asASSERT(GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttUInt8, false)) == asTYPEID_UINT8);
asASSERT(GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttUInt16, false)) == asTYPEID_UINT16);
asASSERT(GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttUInt, false)) == asTYPEID_UINT32);
asASSERT(GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttUInt64, false)) == asTYPEID_UINT64);
asASSERT(GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttFloat, false)) == asTYPEID_FLOAT);
asASSERT(GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttDouble, false)) == asTYPEID_DOUBLE);
defaultArrayObjectType = 0;
RegisterScriptObject(this);
RegisterScriptFunction(this);
#ifndef AS_NO_EXCEPTIONS
translateExceptionCallback = false;
#endif
}
void asCScriptEngine::DeleteDiscardedModules() {
// TODO: redesign: Prevent more than one thread from entering this function at the same time.
// If a thread is already doing the work for the clean-up the other thread should
// simply return, as the first thread will continue.
ACQUIRESHARED(engineRWLock);
asUINT maxCount = discardedModules.GetLength();
RELEASESHARED(engineRWLock);
for (asUINT n = 0; n < maxCount; n++) {
ACQUIRESHARED(engineRWLock);
asCModule *mod = discardedModules[n];
RELEASESHARED(engineRWLock);
if (!mod->HasExternalReferences(shuttingDown)) {
asDELETE(mod, asCModule);
n--;
}
ACQUIRESHARED(engineRWLock);
// Determine the max count again, since another module may have been discarded during the processing
maxCount = discardedModules.GetLength();
RELEASESHARED(engineRWLock);
}
// Go over the list of global properties, to see if it is possible to clean
// up some variables that are no longer referred to by any functions
for (asUINT n = 0; n < globalProperties.GetLength(); n++) {
asCGlobalProperty *prop = globalProperties[n];
if (prop && prop->refCount.get() == 1)
RemoveGlobalProperty(prop);
}
}
asCScriptEngine::~asCScriptEngine() {
// TODO: clean-up: Clean up redundant code
inDestructor = true;
asASSERT(refCount.get() == 0);
// If ShutDown hasn't been called yet do it now
if (!shuttingDown) {
AddRef();
ShutDownAndRelease();
}
// Unravel the registered interface
if (defaultArrayObjectType) {
defaultArrayObjectType->ReleaseInternal();
defaultArrayObjectType = 0;
}
// Delete the functions for generated template types that may references object types
for (asUINT n = 0; n < generatedTemplateTypes.GetLength(); n++) {
asCObjectType *templateType = generatedTemplateTypes[n];
if (templateType)
templateType->DestroyInternal();
}
for (asUINT n = 0; n < listPatternTypes.GetLength(); n++) {
asCObjectType *type = listPatternTypes[n];
if (type)
type->ReleaseInternal();
}
listPatternTypes.SetLength(0);
// No script types must have survived
asASSERT(sharedScriptTypes.GetLength() == 0);
// It is allowed to create new references to the engine temporarily while destroying objects
// but these references must be release immediately or else something is can go wrong later on
if (refCount.get() > 0)
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ENGINE_REF_COUNT_ERROR_DURING_SHUTDOWN);
mapTypeIdToTypeInfo.EraseAll();
// First remove what is not used, so that other groups can be deleted safely
defaultGroup.RemoveConfiguration(this, true);
while (configGroups.GetLength()) {
// Delete config groups in the right order
asCConfigGroup *grp = configGroups.PopLast();
if (grp) {
grp->RemoveConfiguration(this);
asDELETE(grp, asCConfigGroup);
}
}
// Remove what is remaining
defaultGroup.RemoveConfiguration(this);
// Any remaining objects in templateInstanceTypes is from generated template instances
for (asUINT n = 0; n < templateInstanceTypes.GetLength(); n++) {
asCObjectType *templateType = templateInstanceTypes[n];
if (templateInstanceTypes[n])
templateType->ReleaseInternal();
}
templateInstanceTypes.SetLength(0);
asCSymbolTable<asCGlobalProperty>::iterator it = registeredGlobalProps.List();
for (; it; it++) {
RemoveGlobalProperty(*it);
(*it)->Release();
}
registeredGlobalProps.Clear();
for (asUINT n = 0; n < templateSubTypes.GetLength(); n++) {
if (templateSubTypes[n]) {
templateSubTypes[n]->DestroyInternal();
templateSubTypes[n]->ReleaseInternal();
}
}
templateSubTypes.SetLength(0);
registeredTypeDefs.SetLength(0);
registeredEnums.SetLength(0);
registeredObjTypes.SetLength(0);
asCSymbolTable<asCScriptFunction>::iterator funcIt = registeredGlobalFuncs.List();
for (; funcIt; funcIt++)
(*funcIt)->ReleaseInternal();
registeredGlobalFuncs.Clear();
scriptTypeBehaviours.ReleaseAllFunctions();
functionBehaviours.ReleaseAllFunctions();
for (asUINT n = 0; n < scriptFunctions.GetLength(); n++)
if (scriptFunctions[n]) {
scriptFunctions[n]->DestroyInternal();
// Set the engine pointer to null to signal that the function is no longer part of the engine
scriptFunctions[n]->engine = 0;
}
scriptFunctions.SetLength(0);
// Increase the internal ref count for these builtin object types, so the destructor is not called incorrectly
scriptTypeBehaviours.AddRefInternal();
functionBehaviours.AddRefInternal();
// Destroy the funcdefs
// As funcdefs are shared between modules it shouldn't be a problem to keep the objects until the engine is released
for (asUINT n = 0; n < funcDefs.GetLength(); n++)
if (funcDefs[n]) {
funcDefs[n]->DestroyInternal();
funcDefs[n]->ReleaseInternal();
}
funcDefs.SetLength(0);
// Free the global properties
for (asUINT n = 0; n < globalProperties.GetLength(); n++) {
asCGlobalProperty *prop = globalProperties[n];
if (prop) {
asASSERT(prop->refCount.get() == 1);
RemoveGlobalProperty(prop);
}
}
// Free the script section names
for (asUINT n = 0; n < scriptSectionNames.GetLength(); n++)
asDELETE(scriptSectionNames[n], asCString);
scriptSectionNames.SetLength(0);
// Clean the user data
for (asUINT n = 0; n < userData.GetLength(); n += 2) {
if (userData[n + 1]) {
for (asUINT c = 0; c < cleanEngineFuncs.GetLength(); c++)
if (cleanEngineFuncs[c].type == userData[n])
cleanEngineFuncs[c].cleanFunc(this);
}
}
// Free namespaces
for (asUINT n = 0; n < nameSpaces.GetLength(); n++)
asDELETE(nameSpaces[n], asSNameSpace);
nameSpaces.SetLength(0);
asCThreadManager::Unprepare();
}
// interface
int asCScriptEngine::SetContextCallbacks(asREQUESTCONTEXTFUNC_t requestCtx, asRETURNCONTEXTFUNC_t returnCtx, void *param) {
// Both callbacks or neither must be set
if ((requestCtx == 0 && returnCtx != 0) || (requestCtx != 0 && returnCtx == 0))
return asINVALID_ARG;
requestCtxFunc = requestCtx;
returnCtxFunc = returnCtx;
ctxCallbackParam = param;
return 0;
}
// interface
asIScriptContext *asCScriptEngine::RequestContext() {
if (requestCtxFunc) {
// The return callback must also exist
asASSERT(returnCtxFunc);
asIScriptContext *ctx = requestCtxFunc(this, ctxCallbackParam);
return ctx;
}
// As fallback we create a new context
return CreateContext();
}
// internal
asCModule *asCScriptEngine::FindNewOwnerForSharedType(asCTypeInfo *in_type, asCModule *in_mod) {
asASSERT(in_type->IsShared());
if (in_type->module != in_mod)
return in_type->module;
for (asUINT n = 0; n < scriptModules.GetLength(); n++) {
// TODO: optimize: If the modules already stored the shared types separately, this would be quicker
int foundIdx = -1;
asCModule *mod = scriptModules[n];
if (mod == in_type->module) continue;
if (in_type->flags & asOBJ_ENUM)
foundIdx = mod->m_enumTypes.IndexOf(CastToEnumType(in_type));
else if (in_type->flags & asOBJ_TYPEDEF)
foundIdx = mod->m_typeDefs.IndexOf(CastToTypedefType(in_type));
else if (in_type->flags & asOBJ_FUNCDEF)
foundIdx = mod->m_funcDefs.IndexOf(CastToFuncdefType(in_type));
else if (in_type->flags & asOBJ_TEMPLATE)
foundIdx = mod->m_templateInstances.IndexOf(CastToObjectType(in_type));
else
foundIdx = mod->m_classTypes.IndexOf(CastToObjectType(in_type));
if (foundIdx >= 0) {
in_type->module = mod;
break;
}
}
return in_type->module;
}
// internal
asCModule *asCScriptEngine::FindNewOwnerForSharedFunc(asCScriptFunction *in_func, asCModule *in_mod) {
asASSERT(in_func->IsShared());
asASSERT(!(in_func->funcType & asFUNC_FUNCDEF));
if (in_func->module != in_mod)
return in_func->module;
// Check if this is a class method or class factory for a type that has already been moved to a different module
if ((in_func->objectType && in_func->objectType->module && in_func->objectType->module != in_func->module) ||
(in_func->IsFactory() && in_func->returnType.GetTypeInfo()->module && in_func->returnType.GetTypeInfo()->module != in_func->module)) {
// The object type for the method has already been transferred to
// another module, so transfer the method to the same module
if (in_func->objectType)
in_func->module = in_func->objectType->module;
else
in_func->module = in_func->returnType.GetTypeInfo()->module;
// Make sure the function is listed in the module
// The compiler may not have done this earlier, since the object
// type is shared and originally compiled from another module
if (in_func->module->m_scriptFunctions.IndexOf(in_func) < 0) {
in_func->module->m_scriptFunctions.PushLast(in_func);
in_func->AddRefInternal();
}
}
for (asUINT n = 0; n < scriptModules.GetLength(); n++) {
// TODO: optimize: If the modules already stored the shared types separately, this would be quicker
int foundIdx = -1;
asCModule *mod = scriptModules[n];
if (mod == in_func->module) continue;
foundIdx = mod->m_scriptFunctions.IndexOf(in_func);
if (foundIdx >= 0) {
in_func->module = mod;
break;
}
}
return in_func->module;
}
// interface
void asCScriptEngine::ReturnContext(asIScriptContext *ctx) {
if (returnCtxFunc) {
returnCtxFunc(this, ctx, ctxCallbackParam);
return;
}
// As fallback we just release the context
if (ctx)
ctx->Release();
}
// interface
int asCScriptEngine::AddRef() const {
asASSERT(refCount.get() > 0 || inDestructor);
return refCount.atomicInc();
}
// interface
int asCScriptEngine::Release() const {
int r = refCount.atomicDec();
if (r == 0) {
// It is possible that some function will temporarily increment the engine ref count
// during clean-up for example while destroying the objects in the garbage collector.
if (!inDestructor)
asDELETE(const_cast<asCScriptEngine *>(this), asCScriptEngine);
return 0;
}
return r;
}
// interface
int asCScriptEngine::ShutDownAndRelease() {
// Do a full garbage collection cycle to clean up any object that may still hold on to the engine
GarbageCollect();
// Set the flag that the engine is being shutdown now. This will speed up
// the process, and will also allow the engine to warn about invalid calls
shuttingDown = true;
// Clear the context callbacks. If new context's are needed for the clean-up the engine will take care of this itself.
// Context callbacks are normally used for pooling contexts, and if we allow new contexts to be created without being
// immediately destroyed afterwards it means the engine's refcount will increase. This is turn may cause memory access
// violations later on when the pool releases its contexts.
SetContextCallbacks(0, 0, 0);
// The modules must be deleted first, as they may use
// object types from the config groups
for (asUINT n = (asUINT)scriptModules.GetLength(); n-- > 0;)
if (scriptModules[n])
scriptModules[n]->Discard();
scriptModules.SetLength(0);
// Do another full garbage collection to destroy the object types/functions
// that may have been placed in the gc when destroying the modules
GarbageCollect();
// Do another sweep to delete discarded modules, that may not have
// been deleted earlier due to still having external references
DeleteDiscardedModules();
// If the application hasn't registered GC behaviours for all types
// that can form circular references with script types, then there
// may still be objects in the GC.
gc.ReportAndReleaseUndestroyedObjects();
// Release the engine reference
return Release();
}
// internal
asSNameSpace *asCScriptEngine::AddNameSpace(const char *name) {
// First check if it doesn't exist already
asSNameSpace *ns = FindNameSpace(name);
if (ns) return ns;
ns = asNEW(asSNameSpace);
if (ns == 0) {
// Out of memory
return 0;
}
ns->name = name;
nameSpaces.PushLast(ns);
return ns;
}
// internal
asSNameSpace *asCScriptEngine::FindNameSpace(const char *name) const {
// TODO: optimize: Improve linear search
for (asUINT n = 0; n < nameSpaces.GetLength(); n++)
if (nameSpaces[n]->name == name)
return nameSpaces[n];
return 0;
}
// interface
const char *asCScriptEngine::GetDefaultNamespace() const {
return defaultNamespace->name.AddressOf();
}
// interface
int asCScriptEngine::SetDefaultNamespace(const char *nameSpace) {
if (nameSpace == 0)
return ConfigError(asINVALID_ARG, "SetDefaultNamespace", nameSpace, 0);
asCString ns = nameSpace;
if (ns != "") {
// Make sure the namespace is composed of alternating identifier and ::
size_t pos = 0;
bool expectIdentifier = true;
size_t len;
eTokenType t = ttIdentifier;
for (; pos < ns.GetLength(); pos += len) {
t = tok.GetToken(ns.AddressOf() + pos, ns.GetLength() - pos, &len);
if ((expectIdentifier && t != ttIdentifier) || (!expectIdentifier && t != ttScope))
return ConfigError(asINVALID_DECLARATION, "SetDefaultNamespace", nameSpace, 0);
// Make sure parent namespaces are registred in case of nested namespaces
if (expectIdentifier)
AddNameSpace(ns.SubString(0, pos + len).AddressOf());
expectIdentifier = !expectIdentifier;
}
// If the namespace ends with :: then strip it off
if (t == ttScope)
ns.SetLength(ns.GetLength() - 2);
}
defaultNamespace = AddNameSpace(ns.AddressOf());
return 0;
}
// interface
void *asCScriptEngine::SetUserData(void *data, asPWORD type) {
// As a thread might add a new new user data at the same time as another
// it is necessary to protect both read and write access to the userData member
ACQUIREEXCLUSIVE(engineRWLock);
// It is not intended to store a lot of different types of userdata,
// so a more complex structure like a associative map would just have
// more overhead than a simple array.
for (asUINT n = 0; n < userData.GetLength(); n += 2) {
if (userData[n] == type) {
void *oldData = reinterpret_cast<void *>(userData[n + 1]);
userData[n + 1] = reinterpret_cast<asPWORD>(data);
RELEASEEXCLUSIVE(engineRWLock);
return oldData;
}
}
userData.PushLast(type);
userData.PushLast(reinterpret_cast<asPWORD>(data));
RELEASEEXCLUSIVE(engineRWLock);
return 0;
}
// interface
void *asCScriptEngine::GetUserData(asPWORD type) const {
// There may be multiple threads reading, but when
// setting the user data nobody must be reading.
ACQUIRESHARED(engineRWLock);
for (asUINT n = 0; n < userData.GetLength(); n += 2) {
if (userData[n] == type) {
RELEASESHARED(engineRWLock);
return reinterpret_cast<void *>(userData[n + 1]);
}
}
RELEASESHARED(engineRWLock);
return 0;
}
// interface
int asCScriptEngine::SetMessageCallback(const asSFuncPtr &callback, void *obj, asDWORD callConv) {
msgCallback = true;
msgCallbackObj = obj;
bool isObj = false;
if ((unsigned)callConv == asCALL_GENERIC || (unsigned)callConv == asCALL_THISCALL_OBJFIRST || (unsigned)callConv == asCALL_THISCALL_OBJLAST) {
msgCallback = false;
return asNOT_SUPPORTED;
}
if ((unsigned)callConv >= asCALL_THISCALL) {
isObj = true;
if (obj == 0) {
msgCallback = false;
return asINVALID_ARG;
}
}
int r = DetectCallingConvention(isObj, callback, callConv, 0, &msgCallbackFunc);
if (r < 0) msgCallback = false;
return r;
}
// interface
int asCScriptEngine::ClearMessageCallback() {
msgCallback = false;
return 0;
}
// interface
int asCScriptEngine::WriteMessage(const char *section, int row, int col, asEMsgType type, const char *message) {
// Validate input parameters
if (section == 0 ||
message == 0)
return asINVALID_ARG;
// If there is no callback then there's nothing to do
if (!msgCallback)
return 0;
// If a pre-message has been set, then write that first
if (preMessage.isSet) {
asSMessageInfo msg;
msg.section = preMessage.scriptname.AddressOf();
msg.row = preMessage.r;
msg.col = preMessage.c;
msg.type = asMSGTYPE_INFORMATION;
msg.message = preMessage.message.AddressOf();
if (msgCallbackFunc.callConv < ICC_THISCALL)
CallGlobalFunction(&msg, msgCallbackObj, &msgCallbackFunc, 0);
else
CallObjectMethod(msgCallbackObj, &msg, &msgCallbackFunc, 0);
preMessage.isSet = false;
}
// Write the message to the callback
asSMessageInfo msg;
msg.section = section;
msg.row = row;
msg.col = col;
msg.type = type;
msg.message = message;
if (msgCallbackFunc.callConv < ICC_THISCALL)
CallGlobalFunction(&msg, msgCallbackObj, &msgCallbackFunc, 0);
else
CallObjectMethod(msgCallbackObj, &msg, &msgCallbackFunc, 0);
return 0;
}
int asCScriptEngine::SetJITCompiler(asIJITCompiler *compiler) {
jitCompiler = compiler;
return asSUCCESS;
}
asIJITCompiler *asCScriptEngine::GetJITCompiler() const {
return jitCompiler;
}
// interface
asETokenClass asCScriptEngine::ParseToken(const char *string, size_t stringLength, asUINT *tokenLength) const {
if (stringLength == 0)
stringLength = strlen(string);
size_t len;
asETokenClass tc;
tok.GetToken(string, stringLength, &len, &tc);
if (tokenLength)
*tokenLength = (asUINT)len;
return tc;
}
// interface
asIScriptModule *asCScriptEngine::GetModule(const char *module, asEGMFlags flag) {
asCModule *mod = GetModule(module, false);
if (flag == asGM_ALWAYS_CREATE) {
if (mod != 0)
mod->Discard();
return GetModule(module, true);
}
if (mod == 0 && flag == asGM_CREATE_IF_NOT_EXISTS)
return GetModule(module, true);
return mod;
}
// interface
int asCScriptEngine::DiscardModule(const char *module) {
asCModule *mod = GetModule(module, false);
if (mod == 0) return asNO_MODULE;
mod->Discard();
return 0;
}
// interface
asUINT asCScriptEngine::GetModuleCount() const {
ACQUIRESHARED(engineRWLock);
asUINT length = asUINT(scriptModules.GetLength());
RELEASESHARED(engineRWLock);
return length;
}
// interface
asIScriptModule *asCScriptEngine::GetModuleByIndex(asUINT index) const {
asIScriptModule *mod = 0;
ACQUIRESHARED(engineRWLock);
if (index < scriptModules.GetLength())
mod = scriptModules[index];
RELEASESHARED(engineRWLock);
return mod;
}
// internal
int asCScriptEngine::GetFactoryIdByDecl(const asCObjectType *ot, const char *decl) {
asCModule *mod = 0;
// Is this a script class?
if ((ot->flags & asOBJ_SCRIPT_OBJECT) && ot->size > 0)
mod = scriptFunctions[ot->beh.factories[0]]->module;
asCBuilder bld(this, mod);
// Don't write parser errors to the message callback
bld.silent = true;
asCScriptFunction func(this, mod, asFUNC_DUMMY);
int r = bld.ParseFunctionDeclaration(0, decl, &func, false, 0, 0, defaultNamespace);
if (r < 0)
return asINVALID_DECLARATION;
// Search for matching factory function
int id = -1;
for (asUINT n = 0; n < ot->beh.factories.GetLength(); n++) {
asCScriptFunction *f = scriptFunctions[ot->beh.factories[n]];
// We don't really care if the name of the function is correct
if (f->IsSignatureExceptNameEqual(&func)) {
id = ot->beh.factories[n];
break;
}
}
if (id == -1) return asNO_FUNCTION;
return id;
}
// internal
int asCScriptEngine::GetMethodIdByDecl(const asCObjectType *ot, const char *decl, asCModule *mod) {
asCBuilder bld(this, mod);
// Don't write parser errors to the message callback
bld.silent = true;
asCScriptFunction func(this, mod, asFUNC_DUMMY);
// Set the object type so that the signature can be properly compared
// This cast is OK, it will only be used for comparison
func.objectType = const_cast<asCObjectType *>(ot);
func.objectType->AddRefInternal();
int r = bld.ParseFunctionDeclaration(func.objectType, decl, &func, false);
if (r < 0)
return asINVALID_DECLARATION;
// Search script functions for matching interface
int id = -1;
for (asUINT n = 0; n < ot->methods.GetLength(); ++n) {
if (func.IsSignatureEqual(scriptFunctions[ot->methods[n]])) {
if (id == -1)
id = ot->methods[n];
else
return asMULTIPLE_FUNCTIONS;
}
}
if (id == -1) return asNO_FUNCTION;
return id;
}
// internal
asCString asCScriptEngine::GetFunctionDeclaration(int funcId) {
asCString str;
asCScriptFunction *func = GetScriptFunction(funcId);
if (func)
str = func->GetDeclarationStr();
return str;
}
// internal
asCScriptFunction *asCScriptEngine::GetScriptFunction(int funcId) const {
if (funcId < 0 || funcId >= (int)scriptFunctions.GetLength())
return 0;
return scriptFunctions[funcId];
}
// interface
asIScriptContext *asCScriptEngine::CreateContext() {
asIScriptContext *ctx = 0;
CreateContext(&ctx, false);
return ctx;
}
// internal
int asCScriptEngine::CreateContext(asIScriptContext **context, bool isInternal) {
*context = asNEW(asCContext)(this, !isInternal);
if (*context == 0)
return asOUT_OF_MEMORY;
// We need to make sure the engine has been
// prepared before any context is executed
PrepareEngine();
return 0;
}
// interface
int asCScriptEngine::RegisterObjectProperty(const char *obj, const char *declaration, int byteOffset, int compositeOffset, bool isCompositeIndirect) {
int r;
asCDataType dt;
asCBuilder bld(this, 0);
r = bld.ParseDataType(obj, &dt, defaultNamespace);
if (r < 0)
return ConfigError(r, "RegisterObjectProperty", obj, declaration);
if (dt.GetTypeInfo() == 0 || (dt.IsObjectHandle() && !(dt.GetTypeInfo()->GetFlags() & asOBJ_IMPLICIT_HANDLE)))
return ConfigError(asINVALID_OBJECT, "RegisterObjectProperty", obj, declaration);
// Don't allow modifying generated template instances
if (dt.GetTypeInfo() && (dt.GetTypeInfo()->flags & asOBJ_TEMPLATE) && generatedTemplateTypes.Exists(CastToObjectType(dt.GetTypeInfo())))
return ConfigError(asINVALID_TYPE, "RegisterObjectProperty", obj, declaration);
// Verify that the correct config group is used
if (currentGroup->FindType(dt.GetTypeInfo()->name.AddressOf()) == 0)
return ConfigError(asWRONG_CONFIG_GROUP, "RegisterObjectProperty", obj, declaration);
asCDataType type;
asCString name;
if ((r = bld.VerifyProperty(&dt, declaration, name, type, 0)) < 0)
return ConfigError(r, "RegisterObjectProperty", obj, declaration);
// The VM currently only supports 16bit offsets
// TODO: The VM needs to have support for 32bit offsets. Probably with a second ADDSi instruction
// However, when implementing this it is necessary for the bytecode serialization to support
// the switch between the instructions upon loading bytecode as the offset may not be the
// same on all platforms
if (byteOffset > 32767 || byteOffset < -32768)
return ConfigError(asINVALID_ARG, "RegisterObjectProperty", obj, declaration);
// The composite offset must also obey the ADDSi restriction
if (compositeOffset > 32767 || compositeOffset < -32768)
return ConfigError(asINVALID_ARG, "RegisterObjectProperty", obj, declaration);
asCObjectProperty *prop = asNEW(asCObjectProperty);
if (prop == 0)
return ConfigError(asOUT_OF_MEMORY, "RegisterObjectProperty", obj, declaration);
prop->name = name;
prop->type = type;
prop->byteOffset = byteOffset;
prop->isPrivate = false;
prop->isProtected = false;
prop->compositeOffset = compositeOffset;
prop->isCompositeIndirect = isCompositeIndirect;
prop->accessMask = defaultAccessMask;
asCObjectType *ot = CastToObjectType(dt.GetTypeInfo());
asUINT idx = ot->properties.GetLength();
ot->properties.PushLast(prop);
// Add references to types so they are not released too early
if (type.GetTypeInfo()) {
type.GetTypeInfo()->AddRefInternal();
// Add template instances to the config group
if ((type.GetTypeInfo()->flags & asOBJ_TEMPLATE) && !currentGroup->types.Exists(type.GetTypeInfo()))
currentGroup->types.PushLast(type.GetTypeInfo());
}
currentGroup->AddReferencesForType(this, type.GetTypeInfo());
// Return the index of the property to signal success
return idx;
}
// interface
int asCScriptEngine::RegisterInterface(const char *name) {
if (name == 0) return ConfigError(asINVALID_NAME, "RegisterInterface", 0, 0);
// Verify if the name has been registered as a type already
if (GetRegisteredType(name, defaultNamespace))
return asALREADY_REGISTERED;
// Use builder to parse the datatype
asCDataType dt;
asCBuilder bld(this, 0);
bool oldMsgCallback = msgCallback;
msgCallback = false;
int r = bld.ParseDataType(name, &dt, defaultNamespace);
msgCallback = oldMsgCallback;
if (r >= 0) {
// If it is not in the defaultNamespace then the type was successfully parsed because
// it is declared in a parent namespace which shouldn't be treated as an error
if (dt.GetTypeInfo() && dt.GetTypeInfo()->nameSpace == defaultNamespace)
return ConfigError(asERROR, "RegisterInterface", name, 0);
}
// Make sure the name is not a reserved keyword
size_t tokenLen;
int token = tok.GetToken(name, strlen(name), &tokenLen);
if (token != ttIdentifier || strlen(name) != tokenLen)
return ConfigError(asINVALID_NAME, "RegisterInterface", name, 0);
r = bld.CheckNameConflict(name, 0, 0, defaultNamespace, true, false);
if (r < 0)
return ConfigError(asNAME_TAKEN, "RegisterInterface", name, 0);
// Don't have to check against members of object
// types as they are allowed to use the names
// Register the object type for the interface
asCObjectType *st = asNEW(asCObjectType)(this);
if (st == 0)
return ConfigError(asOUT_OF_MEMORY, "RegisterInterface", name, 0);
st->flags = asOBJ_REF | asOBJ_SCRIPT_OBJECT | asOBJ_SHARED;
st->size = 0; // Cannot be instantiated
st->name = name;
st->nameSpace = defaultNamespace;
// Use the default script class behaviours
st->beh.factory = 0;
st->beh.addref = scriptTypeBehaviours.beh.addref;
scriptFunctions[st->beh.addref]->AddRefInternal();
st->beh.release = scriptTypeBehaviours.beh.release;
scriptFunctions[st->beh.release]->AddRefInternal();
st->beh.copy = 0;
allRegisteredTypes.Insert(asSNameSpaceNamePair(st->nameSpace, st->name), st);
registeredObjTypes.PushLast(st);
currentGroup->types.PushLast(st);
return GetTypeIdByDecl(name);
}
// interface
int asCScriptEngine::RegisterInterfaceMethod(const char *intf, const char *declaration) {
// Verify that the correct config group is set.
if (currentGroup->FindType(intf) == 0)
return ConfigError(asWRONG_CONFIG_GROUP, "RegisterInterfaceMethod", intf, declaration);
asCDataType dt;
asCBuilder bld(this, 0);
int r = bld.ParseDataType(intf, &dt, defaultNamespace);
if (r < 0)
return ConfigError(r, "RegisterInterfaceMethod", intf, declaration);
asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_INTERFACE);
if (func == 0)
return ConfigError(asOUT_OF_MEMORY, "RegisterInterfaceMethod", intf, declaration);
func->objectType = CastToObjectType(dt.GetTypeInfo());
func->objectType->AddRefInternal();
r = bld.ParseFunctionDeclaration(func->objectType, declaration, func, false);
if (r < 0) {
func->funcType = asFUNC_DUMMY;
asDELETE(func, asCScriptFunction);
return ConfigError(asINVALID_DECLARATION, "RegisterInterfaceMethod", intf, declaration);
}
// Check name conflicts
r = bld.CheckNameConflictMember(dt.GetTypeInfo(), func->name.AddressOf(), 0, 0, false, false);
if (r < 0) {
func->funcType = asFUNC_DUMMY;
asDELETE(func, asCScriptFunction);
return ConfigError(asNAME_TAKEN, "RegisterInterfaceMethod", intf, declaration);
}
func->id = GetNextScriptFunctionId();
AddScriptFunction(func);
// The index into the interface's vftable chunk should be
// its index in the methods array.
func->vfTableIdx = int(func->objectType->methods.GetLength());
func->objectType->methods.PushLast(func->id);
func->ComputeSignatureId();
currentGroup->AddReferencesForFunc(this, func);
// Return function id as success
return func->id;
}
int asCScriptEngine::RegisterObjectType(const char *name, int byteSize, asDWORD flags) {
int r;
isPrepared = false;
// Verify flags
// Must have either asOBJ_REF or asOBJ_VALUE
if (flags & asOBJ_REF) {
// Can optionally have the asOBJ_GC, asOBJ_NOHANDLE, asOBJ_SCOPED, or asOBJ_TEMPLATE flag set, but nothing else
if (flags & ~(asOBJ_REF | asOBJ_GC | asOBJ_NOHANDLE | asOBJ_SCOPED | asOBJ_TEMPLATE | asOBJ_NOCOUNT | asOBJ_IMPLICIT_HANDLE))
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
// flags are exclusive
if ((flags & asOBJ_GC) && (flags & (asOBJ_NOHANDLE | asOBJ_SCOPED | asOBJ_NOCOUNT)))
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
if ((flags & asOBJ_NOHANDLE) && (flags & (asOBJ_GC | asOBJ_SCOPED | asOBJ_NOCOUNT | asOBJ_IMPLICIT_HANDLE)))
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
if ((flags & asOBJ_SCOPED) && (flags & (asOBJ_GC | asOBJ_NOHANDLE | asOBJ_NOCOUNT | asOBJ_IMPLICIT_HANDLE)))
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
if ((flags & asOBJ_NOCOUNT) && (flags & (asOBJ_GC | asOBJ_NOHANDLE | asOBJ_SCOPED)))
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
// Implicit handle is only allowed if the engine property for this is turned on
if (!ep.allowImplicitHandleTypes && (flags & asOBJ_IMPLICIT_HANDLE))
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
} else if (flags & asOBJ_VALUE) {
// Cannot use reference flags
if (flags & (asOBJ_REF | asOBJ_NOHANDLE | asOBJ_SCOPED | asOBJ_NOCOUNT | asOBJ_IMPLICIT_HANDLE))
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
// Flags are exclusive
if ((flags & asOBJ_POD) && (flags & (asOBJ_ASHANDLE | asOBJ_TEMPLATE)))
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
// If the app type is given, we must validate the flags
if (flags & asOBJ_APP_CLASS) {
// Must not set the primitive or float flag
if (flags & (asOBJ_APP_PRIMITIVE | asOBJ_APP_FLOAT | asOBJ_APP_ARRAY))
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
} else {
// Must not set the class properties, without the class flag
if (flags & (asOBJ_APP_CLASS_CONSTRUCTOR |
asOBJ_APP_CLASS_DESTRUCTOR |
asOBJ_APP_CLASS_ASSIGNMENT |
asOBJ_APP_CLASS_COPY_CONSTRUCTOR |
asOBJ_APP_CLASS_ALLINTS |
asOBJ_APP_CLASS_ALLFLOATS)) {
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
}
}
if (flags & asOBJ_APP_PRIMITIVE) {
if (flags & (asOBJ_APP_CLASS |
asOBJ_APP_FLOAT |
asOBJ_APP_ARRAY))
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
} else if (flags & asOBJ_APP_FLOAT) {
if (flags & (asOBJ_APP_CLASS |
asOBJ_APP_PRIMITIVE |
asOBJ_APP_ARRAY))
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
} else if (flags & asOBJ_APP_ARRAY) {
if (flags & (asOBJ_APP_CLASS |
asOBJ_APP_PRIMITIVE |
asOBJ_APP_FLOAT))
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
}
} else
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
// Don't allow anything else than the defined flags
#ifndef WIP_16BYTE_ALIGN
if (flags - (flags & asOBJ_MASK_VALID_FLAGS))
#else
if (flags - (flags & (asOBJ_MASK_VALID_FLAGS | asOBJ_APP_ALIGN16)))
#endif
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
// Value types must have a defined size
if ((flags & asOBJ_VALUE) && byteSize == 0) {
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_VALUE_TYPE_MUST_HAVE_SIZE);
return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
}
// Verify type name
if (name == 0)
return ConfigError(asINVALID_NAME, "RegisterObjectType", name, 0);
asCString typeName;
asCBuilder bld(this, 0);
if (flags & asOBJ_TEMPLATE) {
asCArray<asCString> subtypeNames;
r = bld.ParseTemplateDecl(name, &typeName, subtypeNames);
if (r < 0)
return ConfigError(r, "RegisterObjectType", name, 0);
// Verify that the template name hasn't been registered as a type already
if (GetRegisteredType(typeName, defaultNamespace))
// This is not an irrepairable error, as it may just be that the same type is registered twice
return asALREADY_REGISTERED;
asCObjectType *type = asNEW(asCObjectType)(this);
if (type == 0)
return ConfigError(asOUT_OF_MEMORY, "RegisterObjectType", name, 0);
type->name = typeName;
type->nameSpace = defaultNamespace;
type->size = byteSize;
#ifdef WIP_16BYTE_ALIGN
// TODO: Types smaller than 4 don't need to be aligned to 4 byte boundaries
type->alignment = (flags & asOBJ_APP_ALIGN16) ? 16 : 4;
#endif
type->flags = flags;
type->accessMask = defaultAccessMask;
// Store it in the object types
allRegisteredTypes.Insert(asSNameSpaceNamePair(type->nameSpace, type->name), type);
currentGroup->types.PushLast(type);
registeredObjTypes.PushLast(type);
registeredTemplateTypes.PushLast(type);
// Define the template subtypes
for (asUINT subTypeIdx = 0; subTypeIdx < subtypeNames.GetLength(); subTypeIdx++) {
asCTypeInfo *subtype = 0;
for (asUINT n = 0; n < templateSubTypes.GetLength(); n++) {
if (templateSubTypes[n]->name == subtypeNames[subTypeIdx]) {
subtype = templateSubTypes[n];
break;
}
}
if (subtype == 0) {
// Create the new subtype if not already existing
subtype = asNEW(asCTypeInfo)(this);
if (subtype == 0)
return ConfigError(asOUT_OF_MEMORY, "RegisterObjectType", name, 0);
subtype->name = subtypeNames[subTypeIdx];
subtype->size = 0;
subtype->flags = asOBJ_TEMPLATE_SUBTYPE;
templateSubTypes.PushLast(subtype);
}
type->templateSubTypes.PushLast(asCDataType::CreateType(subtype, false));
subtype->AddRefInternal();
}
} else {
typeName = name;
// Verify if the name has been registered as a type already
if (GetRegisteredType(typeName, defaultNamespace))
// This is not an irrepairable error, as it may just be that the same type is registered twice
return asALREADY_REGISTERED;
// Keep the most recent template generated instance type, so we know what it was before parsing the datatype
asCObjectType *mostRecentTemplateInstanceType = 0;
asUINT originalSizeOfGeneratedTemplateTypes = (asUINT)generatedTemplateTypes.GetLength();
if (originalSizeOfGeneratedTemplateTypes)
mostRecentTemplateInstanceType = generatedTemplateTypes[originalSizeOfGeneratedTemplateTypes - 1];
// Use builder to parse the datatype
asCDataType dt;
bool oldMsgCallback = msgCallback;
msgCallback = false;
r = bld.ParseDataType(name, &dt, defaultNamespace);
msgCallback = oldMsgCallback;
// If the builder fails or the namespace is different than the default
// namespace, then the type name is new and it should be registered
if (r < 0 || dt.GetTypeInfo()->nameSpace != defaultNamespace) {
// Make sure the name is not a reserved keyword
size_t tokenLen;
int token = tok.GetToken(name, typeName.GetLength(), &tokenLen);
if (token != ttIdentifier || typeName.GetLength() != tokenLen)
return ConfigError(asINVALID_NAME, "RegisterObjectType", name, 0);
r = bld.CheckNameConflict(name, 0, 0, defaultNamespace, true, false);
if (r < 0)
return ConfigError(asNAME_TAKEN, "RegisterObjectType", name, 0);
// Don't have to check against members of object
// types as they are allowed to use the names
// Put the data type in the list
asCObjectType *type = asNEW(asCObjectType)(this);
if (type == 0)
return ConfigError(asOUT_OF_MEMORY, "RegisterObjectType", name, 0);
type->name = typeName;
type->nameSpace = defaultNamespace;
type->size = byteSize;
#ifdef WIP_16BYTE_ALIGN
// TODO: Types smaller than 4 don't need to be aligned to 4 byte boundaries
type->alignment = (flags & asOBJ_APP_ALIGN16) ? 16 : 4;
#endif
type->flags = flags;
type->accessMask = defaultAccessMask;
allRegisteredTypes.Insert(asSNameSpaceNamePair(type->nameSpace, type->name), type);
registeredObjTypes.PushLast(type);
currentGroup->types.PushLast(type);
} else {
// The application is registering a template specialization so we
// need to replace the template instance type with the new type.
// TODO: Template: We don't require the lower dimensions to be registered first for registered template types
// int[][] must not be allowed to be registered
// if int[] hasn't been registered first
if (dt.GetSubType().IsTemplate())
return ConfigError(asLOWER_ARRAY_DIMENSION_NOT_REGISTERED, "RegisterObjectType", name, 0);
if (dt.IsReadOnly() ||
dt.IsReference())
return ConfigError(asINVALID_TYPE, "RegisterObjectType", name, 0);
// Was the template instance type generated before?
if (generatedTemplateTypes.Exists(CastToObjectType(dt.GetTypeInfo())) &&
generatedTemplateTypes[generatedTemplateTypes.GetLength() - 1] == mostRecentTemplateInstanceType) {
asCString str;
str.Format(TXT_TEMPLATE_s_ALREADY_GENERATED_CANT_REGISTER, typeName.AddressOf());
WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
return ConfigError(asNOT_SUPPORTED, "RegisterObjectType", name, 0);
}
// If this is not a generated template instance type, then it means it is an
// already registered template specialization
if (!generatedTemplateTypes.Exists(CastToObjectType(dt.GetTypeInfo())))
return ConfigError(asALREADY_REGISTERED, "RegisterObjectType", name, 0);
// TODO: Add this again. The type is used by the factory stubs so we need to discount that
// Is the template instance type already being used?
// if( dt.GetTypeInfo()->GetRefCount() > 1 )
// return ConfigError(asNOT_SUPPORTED, "RegisterObjectType", name, 0);
// Put the data type in the list
asCObjectType *type = asNEW(asCObjectType)(this);
if (type == 0)
return ConfigError(asOUT_OF_MEMORY, "RegisterObjectType", name, 0);
type->name = dt.GetTypeInfo()->name;
// The namespace will be the same as the original template type
type->nameSpace = dt.GetTypeInfo()->nameSpace;
type->templateSubTypes.PushLast(dt.GetSubType());
for (asUINT s = 0; s < type->templateSubTypes.GetLength(); s++)
if (type->templateSubTypes[s].GetTypeInfo())
type->templateSubTypes[s].GetTypeInfo()->AddRefInternal();
type->size = byteSize;
#ifdef WIP_16BYTE_ALIGN
// TODO: Types smaller than 4 don't need to be aligned to 4 byte boundaries
type->alignment = (flags & asOBJ_APP_ALIGN16) ? 16 : 4;
#endif
type->flags = flags;
type->accessMask = defaultAccessMask;
templateInstanceTypes.PushLast(type);
currentGroup->types.PushLast(type);
// Remove the template instance type, which will no longer be used.
// It is possible that multiple template instances are generated if
// they have any relationship, so all of them must be removed
while (generatedTemplateTypes.GetLength() > originalSizeOfGeneratedTemplateTypes)
RemoveTemplateInstanceType(generatedTemplateTypes[generatedTemplateTypes.GetLength() - 1]);
}
}
// Return the type id as the success (except for template types)
if (flags & asOBJ_TEMPLATE)
return asSUCCESS;
return GetTypeIdByDecl(name);
}
// interface
int asCScriptEngine::RegisterObjectBehaviour(const char *datatype, asEBehaviours behaviour, const char *decl, const asSFuncPtr &funcPointer, asDWORD callConv, void *auxiliary, int compositeOffset, bool isCompositeIndirect) {
if (datatype == 0) return ConfigError(asINVALID_ARG, "RegisterObjectBehaviour", datatype, decl);
// Determine the object type
asCBuilder bld(this, 0);
asCDataType type;
int r = bld.ParseDataType(datatype, &type, defaultNamespace);
if (r < 0)
return ConfigError(r, "RegisterObjectBehaviour", datatype, decl);
if (type.GetTypeInfo() == 0 || (type.IsObjectHandle() && !(type.GetTypeInfo()->GetFlags() & asOBJ_IMPLICIT_HANDLE)))
return ConfigError(asINVALID_TYPE, "RegisterObjectBehaviour", datatype, decl);
// Don't allow application to modify built-in types
if (type.GetTypeInfo() == &functionBehaviours ||
type.GetTypeInfo() == &scriptTypeBehaviours)
return ConfigError(asINVALID_TYPE, "RegisterObjectBehaviour", datatype, decl);
if (type.IsReadOnly() || type.IsReference())
return ConfigError(asINVALID_TYPE, "RegisterObjectBehaviour", datatype, decl);
// Don't allow modifying generated template instances
if (type.GetTypeInfo() && (type.GetTypeInfo()->flags & asOBJ_TEMPLATE) && generatedTemplateTypes.Exists(CastToObjectType(type.GetTypeInfo())))
return ConfigError(asINVALID_TYPE, "RegisterObjectBehaviour", datatype, decl);
return RegisterBehaviourToObjectType(CastToObjectType(type.GetTypeInfo()), behaviour, decl, funcPointer, callConv, auxiliary, compositeOffset, isCompositeIndirect);
}
// internal
int asCScriptEngine::RegisterBehaviourToObjectType(asCObjectType *objectType, asEBehaviours behaviour, const char *decl, const asSFuncPtr &funcPointer, asDWORD callConv, void *auxiliary, int compositeOffset, bool isCompositeIndirect) {
#ifdef AS_MAX_PORTABILITY
if (callConv != asCALL_GENERIC)
return ConfigError(asNOT_SUPPORTED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
#endif
asSSystemFunctionInterface internal;
bool isMethod = !(behaviour == asBEHAVE_FACTORY ||
behaviour == asBEHAVE_LIST_FACTORY ||
behaviour == asBEHAVE_TEMPLATE_CALLBACK);
int r = DetectCallingConvention(isMethod, funcPointer, callConv, auxiliary, &internal);
if (r < 0)
return ConfigError(r, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
internal.compositeOffset = compositeOffset;
internal.isCompositeIndirect = isCompositeIndirect;
if ((compositeOffset || isCompositeIndirect) && callConv != asCALL_THISCALL)
return ConfigError(asINVALID_ARG, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
// TODO: cleanup: This is identical to what is in RegisterMethodToObjectType
// If the object type is a template, make sure there are no generated instances already
if (objectType->flags & asOBJ_TEMPLATE) {
for (asUINT n = 0; n < generatedTemplateTypes.GetLength(); n++) {
asCObjectType *tmpl = generatedTemplateTypes[n];
if (tmpl->name == objectType->name &&
tmpl->nameSpace == objectType->nameSpace &&
!(tmpl->templateSubTypes[0].GetTypeInfo() && (tmpl->templateSubTypes[0].GetTypeInfo()->flags & asOBJ_TEMPLATE_SUBTYPE))) {
asCString msg;
msg.Format(TXT_TEMPLATE_s_ALREADY_GENERATED_CANT_REGISTER, asCDataType::CreateType(tmpl, false).Format(tmpl->nameSpace).AddressOf());
WriteMessage("", 0, 0, asMSGTYPE_ERROR, msg.AddressOf());
return ConfigError(asERROR, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
}
}
isPrepared = false;
asSTypeBehaviour *beh = &objectType->beh;
// Verify function declaration
asCScriptFunction func(this, 0, asFUNC_DUMMY);
bool expectListPattern = behaviour == asBEHAVE_LIST_FACTORY || behaviour == asBEHAVE_LIST_CONSTRUCT;
asCScriptNode *listPattern = 0;
asCBuilder bld(this, 0);
r = bld.ParseFunctionDeclaration(objectType, decl, &func, true, &internal.paramAutoHandles, &internal.returnAutoHandle, 0, expectListPattern ? &listPattern : 0);
if (r < 0) {
if (listPattern)
listPattern->Destroy(this);
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
func.name.Format("$beh%d", behaviour);
if (behaviour != asBEHAVE_FACTORY && behaviour != asBEHAVE_LIST_FACTORY) {
func.objectType = objectType;
func.objectType->AddRefInternal();
}
// Check if the method restricts that use of the template to value types or reference types
if (objectType->flags & asOBJ_TEMPLATE) {
r = SetTemplateRestrictions(objectType, &func, "RegisterObjectBehaviour", decl);
if (r < 0)
return r;
}
if (behaviour == asBEHAVE_CONSTRUCT) {
// Verify that the return type is void
if (func.returnType != asCDataType::CreatePrimitive(ttVoid, false))
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
if (objectType->flags & asOBJ_SCRIPT_OBJECT) {
// The script object is a special case
asASSERT(func.parameterTypes.GetLength() == 1);
beh->construct = AddBehaviourFunction(func, internal);
beh->factory = beh->construct;
scriptFunctions[beh->factory]->AddRefInternal();
beh->constructors.PushLast(beh->construct);
beh->factories.PushLast(beh->factory);
func.id = beh->construct;
} else {
// Verify that it is a value type
if (!(func.objectType->flags & asOBJ_VALUE)) {
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
// The templates take a hidden parameter with the object type
if ((objectType->flags & asOBJ_TEMPLATE) &&
(func.parameterTypes.GetLength() == 0 ||
!func.parameterTypes[0].IsReference())) {
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_FIRST_PARAM_MUST_BE_REF_FOR_TEMPLATE_FACTORY);
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
// TODO: Verify that the same constructor hasn't been registered already
// Store all constructors in a list
func.id = AddBehaviourFunction(func, internal);
beh->constructors.PushLast(func.id);
if (func.parameterTypes.GetLength() == 0 ||
(func.parameterTypes.GetLength() == 1 && (objectType->flags & asOBJ_TEMPLATE))) {
beh->construct = func.id;
} else if (func.parameterTypes.GetLength() == 1) {
// Is this the copy constructor?
asCDataType paramType = func.parameterTypes[0];
// If the parameter is object, and const reference for input or inout,
// and same type as this class, then this is a copy constructor.
if (paramType.IsObject() && paramType.IsReference() && paramType.IsReadOnly() &&
(func.inOutFlags[0] & asTM_INREF) && paramType.GetTypeInfo() == objectType)
beh->copyconstruct = func.id;
}
}
} else if (behaviour == asBEHAVE_DESTRUCT) {
// Must be a value type
if (!(func.objectType->flags & asOBJ_VALUE)) {
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
if (beh->destruct)
return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
// Verify that the return type is void
if (func.returnType != asCDataType::CreatePrimitive(ttVoid, false))
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
// Verify that there are no parameters
if (func.parameterTypes.GetLength() > 0)
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
func.id = beh->destruct = AddBehaviourFunction(func, internal);
} else if (behaviour == asBEHAVE_LIST_CONSTRUCT) {
func.name = "$list";
// Verify that the return type is void
if (func.returnType != asCDataType::CreatePrimitive(ttVoid, false)) {
if (listPattern)
listPattern->Destroy(this);
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
// Verify that it is a value type
if (!(func.objectType->flags & asOBJ_VALUE)) {
if (listPattern)
listPattern->Destroy(this);
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
// Verify the parameters
// The templates take a hidden parameter with the object type
if ((!(objectType->flags & asOBJ_TEMPLATE) && (func.parameterTypes.GetLength() != 1 || !func.parameterTypes[0].IsReference())) ||
((objectType->flags & asOBJ_TEMPLATE) && (func.parameterTypes.GetLength() != 2 || !func.parameterTypes[0].IsReference() || !func.parameterTypes[1].IsReference()))) {
if (listPattern)
listPattern->Destroy(this);
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_LIST_FACTORY_EXPECTS_1_REF_PARAM);
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
// Don't accept duplicates
if (beh->listFactory) {
if (listPattern)
listPattern->Destroy(this);
return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
// Add the function
func.id = AddBehaviourFunction(func, internal);
// Re-use the listFactory member, as it is not possible to have both anyway
beh->listFactory = func.id;
// Store the list pattern for this function
r = scriptFunctions[func.id]->RegisterListPattern(decl, listPattern);
if (listPattern)
listPattern->Destroy(this);
if (r < 0)
return ConfigError(r, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
} else if (behaviour == asBEHAVE_FACTORY || behaviour == asBEHAVE_LIST_FACTORY) {
if (behaviour == asBEHAVE_LIST_FACTORY)
func.name = "$list";
// Must be a ref type and must not have asOBJ_NOHANDLE
if (!(objectType->flags & asOBJ_REF) || (objectType->flags & asOBJ_NOHANDLE)) {
if (listPattern)
listPattern->Destroy(this);
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
// Verify that the return type is a handle to the type
if (func.returnType != asCDataType::CreateObjectHandle(objectType, false)) {
if (listPattern)
listPattern->Destroy(this);
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
// The templates take a hidden parameter with the object type
if ((objectType->flags & asOBJ_TEMPLATE) &&
(func.parameterTypes.GetLength() == 0 ||
!func.parameterTypes[0].IsReference())) {
if (listPattern)
listPattern->Destroy(this);
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_FIRST_PARAM_MUST_BE_REF_FOR_TEMPLATE_FACTORY);
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
if (behaviour == asBEHAVE_LIST_FACTORY) {
// Make sure the factory takes a reference as its last parameter
if (objectType->flags & asOBJ_TEMPLATE) {
if (func.parameterTypes.GetLength() != 2 || !func.parameterTypes[1].IsReference()) {
if (listPattern)
listPattern->Destroy(this);
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_TEMPLATE_LIST_FACTORY_EXPECTS_2_REF_PARAMS);
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
} else {
if (func.parameterTypes.GetLength() != 1 || !func.parameterTypes[0].IsReference()) {
if (listPattern)
listPattern->Destroy(this);
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_LIST_FACTORY_EXPECTS_1_REF_PARAM);
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
}
}
// TODO: Verify that the same factory function hasn't been registered already
// Don't accept duplicates
if (behaviour == asBEHAVE_LIST_FACTORY && beh->listFactory) {
if (listPattern)
listPattern->Destroy(this);
return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
// Store all factory functions in a list
func.id = AddBehaviourFunction(func, internal);
// The list factory is a special factory and isn't stored together with the rest
if (behaviour != asBEHAVE_LIST_FACTORY)
beh->factories.PushLast(func.id);
if ((func.parameterTypes.GetLength() == 0) ||
(func.parameterTypes.GetLength() == 1 && (objectType->flags & asOBJ_TEMPLATE))) {
beh->factory = func.id;
} else if ((func.parameterTypes.GetLength() == 1) ||
(func.parameterTypes.GetLength() == 2 && (objectType->flags & asOBJ_TEMPLATE))) {
if (behaviour == asBEHAVE_LIST_FACTORY) {
beh->listFactory = func.id;
// Store the list pattern for this function
r = scriptFunctions[func.id]->RegisterListPattern(decl, listPattern);
if (listPattern)
listPattern->Destroy(this);
if (r < 0)
return ConfigError(r, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
} else {
// Is this the copy factory?
asCDataType paramType = func.parameterTypes[func.parameterTypes.GetLength() - 1];
// If the parameter is object, and const reference for input,
// and same type as this class, then this is a copy constructor.
if (paramType.IsObject() && paramType.IsReference() && paramType.IsReadOnly() && func.inOutFlags[func.parameterTypes.GetLength() - 1] == asTM_INREF && paramType.GetTypeInfo() == objectType)
beh->copyfactory = func.id;
}
}
} else if (behaviour == asBEHAVE_ADDREF) {
// Must be a ref type and must not have asOBJ_NOHANDLE, nor asOBJ_SCOPED
if (!(func.objectType->flags & asOBJ_REF) ||
(func.objectType->flags & asOBJ_NOHANDLE) ||
(func.objectType->flags & asOBJ_SCOPED) ||
(func.objectType->flags & asOBJ_NOCOUNT)) {
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
if (beh->addref)
return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
// Verify that the return type is void
if (func.returnType != asCDataType::CreatePrimitive(ttVoid, false))
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
// Verify that there are no parameters
if (func.parameterTypes.GetLength() > 0)
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
func.id = beh->addref = AddBehaviourFunction(func, internal);
} else if (behaviour == asBEHAVE_RELEASE) {
// Must be a ref type and must not have asOBJ_NOHANDLE
if (!(func.objectType->flags & asOBJ_REF) ||
(func.objectType->flags & asOBJ_NOHANDLE) ||
(func.objectType->flags & asOBJ_NOCOUNT)) {
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
if (beh->release)
return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
// Verify that the return type is void
if (func.returnType != asCDataType::CreatePrimitive(ttVoid, false))
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
// Verify that there are no parameters
if (func.parameterTypes.GetLength() > 0)
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
func.id = beh->release = AddBehaviourFunction(func, internal);
} else if (behaviour == asBEHAVE_TEMPLATE_CALLBACK) {
// Must be a template type
if (!(func.objectType->flags & asOBJ_TEMPLATE)) {
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
if (beh->templateCallback)
return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
// Verify that the return type is bool
if (func.returnType != asCDataType::CreatePrimitive(ttBool, false))
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
// Verify that there are two parameters
if (func.parameterTypes.GetLength() != 2)
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
// The first parameter must be an inref (to receive the object type), and
// the second must be a bool out ref (to return if the type should or shouldn't be garbage collected)
if (func.inOutFlags[0] != asTM_INREF || func.inOutFlags[1] != asTM_OUTREF || !func.parameterTypes[1].IsEqualExceptRef(asCDataType::CreatePrimitive(ttBool, false)))
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
func.id = beh->templateCallback = AddBehaviourFunction(func, internal);
} else if (behaviour >= asBEHAVE_FIRST_GC &&
behaviour <= asBEHAVE_LAST_GC) {
// Only allow GC behaviours for types registered to be garbage collected
if (!(func.objectType->flags & asOBJ_GC)) {
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
// Verify parameter count
if ((behaviour == asBEHAVE_GETREFCOUNT ||
behaviour == asBEHAVE_SETGCFLAG ||
behaviour == asBEHAVE_GETGCFLAG) &&
func.parameterTypes.GetLength() != 0)
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
if ((behaviour == asBEHAVE_ENUMREFS ||
behaviour == asBEHAVE_RELEASEREFS) &&
func.parameterTypes.GetLength() != 1)
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
// Verify return type
if (behaviour == asBEHAVE_GETREFCOUNT &&
func.returnType != asCDataType::CreatePrimitive(ttInt, false))
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
if (behaviour == asBEHAVE_GETGCFLAG &&
func.returnType != asCDataType::CreatePrimitive(ttBool, false))
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
if ((behaviour == asBEHAVE_SETGCFLAG ||
behaviour == asBEHAVE_ENUMREFS ||
behaviour == asBEHAVE_RELEASEREFS) &&
func.returnType != asCDataType::CreatePrimitive(ttVoid, false))
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
if (behaviour == asBEHAVE_GETREFCOUNT)
func.id = beh->gcGetRefCount = AddBehaviourFunction(func, internal);
else if (behaviour == asBEHAVE_SETGCFLAG)
func.id = beh->gcSetFlag = AddBehaviourFunction(func, internal);
else if (behaviour == asBEHAVE_GETGCFLAG)
func.id = beh->gcGetFlag = AddBehaviourFunction(func, internal);
else if (behaviour == asBEHAVE_ENUMREFS)
func.id = beh->gcEnumReferences = AddBehaviourFunction(func, internal);
else if (behaviour == asBEHAVE_RELEASEREFS)
func.id = beh->gcReleaseAllReferences = AddBehaviourFunction(func, internal);
} else if (behaviour == asBEHAVE_GET_WEAKREF_FLAG) {
// This behaviour is only allowed for reference types
if (!(func.objectType->flags & asOBJ_REF)) {
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
// Don't allow it if the type is registered with nohandle or scoped
if (func.objectType->flags & (asOBJ_NOHANDLE | asOBJ_SCOPED)) {
WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
// Verify that the return type is a reference since it needs to return a pointer to an asISharedBool
if (!func.returnType.IsReference())
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
// Verify that there are no parameters
if (func.parameterTypes.GetLength() != 0)
return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
if (beh->getWeakRefFlag)
return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
func.id = beh->getWeakRefFlag = AddBehaviourFunction(func, internal);
} else {
asASSERT(false);
return ConfigError(asINVALID_ARG, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
}
if (func.id < 0)
return ConfigError(func.id, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
// Return function id as success
return func.id;
}
int asCScriptEngine::SetTemplateRestrictions(asCObjectType *templateType, asCScriptFunction *func, const char *caller, const char *decl) {
asASSERT(templateType->flags & asOBJ_TEMPLATE);
for (asUINT subTypeIdx = 0; subTypeIdx < templateType->templateSubTypes.GetLength(); subTypeIdx++) {
if (func->returnType.GetTypeInfo() == templateType->templateSubTypes[subTypeIdx].GetTypeInfo()) {
if (func->returnType.IsObjectHandle())
templateType->acceptValueSubType = false;
else if (!func->returnType.IsReference())
templateType->acceptRefSubType = false;
// Can't support template subtypes by value, since each type is treated differently in the ABI
if (!func->returnType.IsObjectHandle() && !func->returnType.IsReference())
return ConfigError(asNOT_SUPPORTED, caller, templateType->name.AddressOf(), decl);
}
for (asUINT n = 0; n < func->parameterTypes.GetLength(); n++) {
if (func->parameterTypes[n].GetTypeInfo() == templateType->templateSubTypes[subTypeIdx].GetTypeInfo()) {
if (func->parameterTypes[n].IsObjectHandle() ||
(!ep.allowUnsafeReferences && func->parameterTypes[n].IsReference() && func->inOutFlags[n] == asTM_INOUTREF))
templateType->acceptValueSubType = false;
else if (!func->parameterTypes[n].IsReference())
templateType->acceptRefSubType = false;
// Can't support template subtypes by value, since each type is treated differently in the ABI
if (!func->parameterTypes[n].IsObjectHandle() && !func->parameterTypes[n].IsReference())
return ConfigError(asNOT_SUPPORTED, caller, templateType->name.AddressOf(), decl);
}
}
}
return asSUCCESS;
}
int asCScriptEngine::VerifyVarTypeNotInFunction(asCScriptFunction *func) {
// Don't allow var type in this function
if (func->returnType.GetTokenType() == ttQuestion)
return asINVALID_DECLARATION;
for (unsigned int n = 0; n < func->parameterTypes.GetLength(); n++)
if (func->parameterTypes[n].GetTokenType() == ttQuestion)
return asINVALID_DECLARATION;
return 0;
}
int asCScriptEngine::AddBehaviourFunction(asCScriptFunction &func, asSSystemFunctionInterface &internal) {
asUINT n;
int id = GetNextScriptFunctionId();
asSSystemFunctionInterface *newInterface = asNEW(asSSystemFunctionInterface)(internal);
if (newInterface == 0)
return asOUT_OF_MEMORY;
asCScriptFunction *f = asNEW(asCScriptFunction)(this, 0, asFUNC_SYSTEM);
if (f == 0) {
asDELETE(newInterface, asSSystemFunctionInterface);
return asOUT_OF_MEMORY;
}
asASSERT(func.name != "" && func.name != "f");
f->name = func.name;
f->sysFuncIntf = newInterface;
f->returnType = func.returnType;
f->objectType = func.objectType;
if (f->objectType)
f->objectType->AddRefInternal();
f->id = id;
f->SetReadOnly(func.IsReadOnly());
f->accessMask = defaultAccessMask;
f->parameterTypes = func.parameterTypes;
f->parameterNames = func.parameterNames;
f->inOutFlags = func.inOutFlags;
f->traits = func.traits;
for (n = 0; n < func.defaultArgs.GetLength(); n++)
if (func.defaultArgs[n])
f->defaultArgs.PushLast(asNEW(asCString)(*func.defaultArgs[n]));
else
f->defaultArgs.PushLast(0);
AddScriptFunction(f);
// If parameter type from other groups are used, add references
currentGroup->AddReferencesForFunc(this, f);
return id;
}
// interface
int asCScriptEngine::RegisterGlobalProperty(const char *declaration, void *pointer) {
// Don't accept a null pointer
if (pointer == 0)
return ConfigError(asINVALID_ARG, "RegisterGlobalProperty", declaration, 0);
asCDataType type;
asCString name;
int r;
asCBuilder bld(this, 0);
if ((r = bld.VerifyProperty(0, declaration, name, type, defaultNamespace)) < 0)
return ConfigError(r, "RegisterGlobalProperty", declaration, 0);
// Don't allow registering references as global properties
if (type.IsReference())
return ConfigError(asINVALID_TYPE, "RegisterGlobalProperty", declaration, 0);
// Store the property info
asCGlobalProperty *prop = AllocateGlobalProperty();
prop->name = name;
prop->nameSpace = defaultNamespace;
prop->type = type;
prop->accessMask = defaultAccessMask;
prop->SetRegisteredAddress(pointer);
varAddressMap.Insert(prop->GetAddressOfValue(), prop);
asUINT idx = registeredGlobalProps.Put(prop);
prop->AddRef();
currentGroup->globalProps.PushLast(prop);
currentGroup->AddReferencesForType(this, type.GetTypeInfo());
// Return the index of the property to signal success
return int(idx);
}
// internal
asCGlobalProperty *asCScriptEngine::AllocateGlobalProperty() {
asCGlobalProperty *prop = asNEW(asCGlobalProperty);
if (prop == 0) {
// Out of memory
return 0;
}
// First check the availability of a free slot
if (freeGlobalPropertyIds.GetLength()) {
prop->id = freeGlobalPropertyIds.PopLast();
globalProperties[prop->id] = prop;
return prop;
}
prop->id = (asUINT)globalProperties.GetLength();
globalProperties.PushLast(prop);
return prop;
}
// internal
void asCScriptEngine::RemoveGlobalProperty(asCGlobalProperty *prop) {
int index = globalProperties.IndexOf(prop);
if (index >= 0) {
freeGlobalPropertyIds.PushLast(index);
globalProperties[index] = 0;
asSMapNode<void *, asCGlobalProperty *> *node;
varAddressMap.MoveTo(&node, prop->GetAddressOfValue());
asASSERT(node);
if (node)
varAddressMap.Erase(node);
prop->Release();
}
}
// interface
asUINT asCScriptEngine::GetGlobalPropertyCount() const {
return asUINT(registeredGlobalProps.GetSize());
}
// interface
// TODO: If the typeId ever encodes the const flag, then the isConst parameter should be removed
int asCScriptEngine::GetGlobalPropertyByIndex(asUINT index, const char **name, const char **nameSpace, int *typeId, bool *isConst, const char **configGroup, void **pointer, asDWORD *accessMask) const {
const asCGlobalProperty *prop = registeredGlobalProps.Get(index);
if (!prop)
return asINVALID_ARG;
if (name) *name = prop->name.AddressOf();
if (nameSpace) *nameSpace = prop->nameSpace->name.AddressOf();
if (typeId) *typeId = GetTypeIdFromDataType(prop->type);
if (isConst) *isConst = prop->type.IsReadOnly();
if (pointer) *pointer = prop->GetRegisteredAddress();
if (accessMask) *accessMask = prop->accessMask;
if (configGroup) {
asCConfigGroup *group = FindConfigGroupForGlobalVar(index);
if (group)
*configGroup = group->groupName.AddressOf();
else
*configGroup = 0;
}
return asSUCCESS;
}
// interface
int asCScriptEngine::GetGlobalPropertyIndexByName(const char *in_name) const {
asCString name;
asSNameSpace *ns = 0;
if (DetermineNameAndNamespace(in_name, defaultNamespace, name, ns) < 0)
return asINVALID_ARG;
// Find the global var id
while (ns) {
int id = registeredGlobalProps.GetFirstIndex(ns, name);
if (id >= 0)
return id;
// Recursively search parent namespace
ns = GetParentNameSpace(ns);
}
return asNO_GLOBAL_VAR;
}
// interface
int asCScriptEngine::GetGlobalPropertyIndexByDecl(const char *decl) const {
// This const cast is OK. The builder won't modify the engine
asCBuilder bld(const_cast<asCScriptEngine *>(this), 0);
// Don't write parser errors to the message callback
bld.silent = true;
asCString name;
asSNameSpace *ns;
asCDataType dt;
int r = bld.ParseVariableDeclaration(decl, defaultNamespace, name, ns, dt);
if (r < 0)
return r;
// Search for a match
while (ns) {
int id = registeredGlobalProps.GetFirstIndex(ns, name, asCCompGlobPropType(dt));
if (id >= 0)
return id;
ns = GetParentNameSpace(ns);
}
return asNO_GLOBAL_VAR;
}
// interface
int asCScriptEngine::RegisterObjectMethod(const char *obj, const char *declaration, const asSFuncPtr &funcPointer, asDWORD callConv, void *auxiliary, int compositeOffset, bool isCompositeIndirect) {
if (obj == 0)
return ConfigError(asINVALID_ARG, "RegisterObjectMethod", obj, declaration);
// Determine the object type
asCDataType dt;
asCBuilder bld(this, 0);
int r = bld.ParseDataType(obj, &dt, defaultNamespace);
if (r < 0)
return ConfigError(r, "RegisterObjectMethod", obj, declaration);
// Don't allow application to modify primitives or handles
if (dt.GetTypeInfo() == 0 || (dt.IsObjectHandle() && !(dt.GetTypeInfo()->GetFlags() & asOBJ_IMPLICIT_HANDLE)))
return ConfigError(asINVALID_ARG, "RegisterObjectMethod", obj, declaration);
// Don't allow application to modify built-in types or funcdefs
if (dt.GetTypeInfo() == &functionBehaviours ||
dt.GetTypeInfo() == &scriptTypeBehaviours ||
CastToFuncdefType(dt.GetTypeInfo()))
return ConfigError(asINVALID_ARG, "RegisterObjectMethod", obj, declaration);
// Don't allow modifying generated template instances
if (dt.GetTypeInfo() && (dt.GetTypeInfo()->flags & asOBJ_TEMPLATE) && generatedTemplateTypes.Exists(CastToObjectType(dt.GetTypeInfo())))
return ConfigError(asINVALID_TYPE, "RegisterObjectMethod", obj, declaration);
return RegisterMethodToObjectType(CastToObjectType(dt.GetTypeInfo()), declaration, funcPointer, callConv, auxiliary, compositeOffset, isCompositeIndirect);
}
// internal
int asCScriptEngine::RegisterMethodToObjectType(asCObjectType *objectType, const char *declaration, const asSFuncPtr &funcPointer, asDWORD callConv, void *auxiliary, int compositeOffset, bool isCompositeIndirect) {
#ifdef AS_MAX_PORTABILITY
if (callConv != asCALL_GENERIC)
return ConfigError(asNOT_SUPPORTED, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
#endif
asSSystemFunctionInterface internal;
int r = DetectCallingConvention(true, funcPointer, callConv, auxiliary, &internal);
if (r < 0)
return ConfigError(r, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
internal.compositeOffset = compositeOffset;
internal.isCompositeIndirect = isCompositeIndirect;
if ((compositeOffset || isCompositeIndirect) && callConv != asCALL_THISCALL)
return ConfigError(asINVALID_ARG, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
// TODO: cleanup: This is identical to what is in RegisterMethodToObjectType
// If the object type is a template, make sure there are no generated instances already
if (objectType->flags & asOBJ_TEMPLATE) {
for (asUINT n = 0; n < generatedTemplateTypes.GetLength(); n++) {
asCObjectType *tmpl = generatedTemplateTypes[n];
if (tmpl->name == objectType->name &&
tmpl->nameSpace == objectType->nameSpace &&
!(tmpl->templateSubTypes[0].GetTypeInfo() && (tmpl->templateSubTypes[0].GetTypeInfo()->flags & asOBJ_TEMPLATE_SUBTYPE))) {
asCString msg;
msg.Format(TXT_TEMPLATE_s_ALREADY_GENERATED_CANT_REGISTER, asCDataType::CreateType(tmpl, false).Format(tmpl->nameSpace).AddressOf());
WriteMessage("", 0, 0, asMSGTYPE_ERROR, msg.AddressOf());
return ConfigError(asERROR, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
}
}
}
isPrepared = false;
// Put the system function in the list of system functions
asSSystemFunctionInterface *newInterface = asNEW(asSSystemFunctionInterface)(internal);
if (newInterface == 0)
return ConfigError(asOUT_OF_MEMORY, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_SYSTEM);
if (func == 0) {
asDELETE(newInterface, asSSystemFunctionInterface);
return ConfigError(asOUT_OF_MEMORY, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
}
func->sysFuncIntf = newInterface;
func->objectType = objectType;
func->objectType->AddRefInternal();
asCBuilder bld(this, 0);
r = bld.ParseFunctionDeclaration(func->objectType, declaration, func, true, &newInterface->paramAutoHandles, &newInterface->returnAutoHandle);
if (r < 0) {
// Set as dummy function before deleting
func->funcType = asFUNC_DUMMY;
asDELETE(func, asCScriptFunction);
return ConfigError(asINVALID_DECLARATION, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
}
// Check name conflicts
r = bld.CheckNameConflictMember(objectType, func->name.AddressOf(), 0, 0, false, false);
if (r < 0) {
func->funcType = asFUNC_DUMMY;
asDELETE(func, asCScriptFunction);
return ConfigError(asNAME_TAKEN, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
}
// Validate property signature
if (func->IsProperty() && (r = bld.ValidateVirtualProperty(func)) < 0) {
// Set as dummy function before deleting
func->funcType = asFUNC_DUMMY;
asDELETE(func, asCScriptFunction);
if (r == -5)
return ConfigError(asNAME_TAKEN, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
else
return ConfigError(asINVALID_DECLARATION, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
}
// Check against duplicate methods
if (func->name == "opConv" || func->name == "opImplConv" || func->name == "opCast" || func->name == "opImplCast") {
// opConv and opCast are special methods that the compiler differentiates between by the return type
for (asUINT n = 0; n < func->objectType->methods.GetLength(); n++) {
asCScriptFunction *f = scriptFunctions[func->objectType->methods[n]];
if (f->name == func->name &&
f->IsSignatureExceptNameEqual(func)) {
func->funcType = asFUNC_DUMMY;
asDELETE(func, asCScriptFunction);
return ConfigError(asALREADY_REGISTERED, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
}
}
} else {
for (asUINT n = 0; n < func->objectType->methods.GetLength(); n++) {
asCScriptFunction *f = scriptFunctions[func->objectType->methods[n]];
if (f->name == func->name &&
f->IsSignatureExceptNameAndReturnTypeEqual(func)) {
func->funcType = asFUNC_DUMMY;
asDELETE(func, asCScriptFunction);
return ConfigError(asALREADY_REGISTERED, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
}
}
}
func->id = GetNextScriptFunctionId();
func->objectType->methods.PushLast(func->id);
func->accessMask = defaultAccessMask;
AddScriptFunction(func);
// If parameter type from other groups are used, add references
currentGroup->AddReferencesForFunc(this, func);
// Check if the method restricts that use of the template to value types or reference types
if (func->objectType->flags & asOBJ_TEMPLATE) {
r = SetTemplateRestrictions(func->objectType, func, "RegisterObjectMethod", declaration);
if (r < 0)
return r;
}
// TODO: beh.copy member will be removed, so this is not necessary
// Is this the default copy behaviour?
if (func->name == "opAssign" && func->parameterTypes.GetLength() == 1 && !func->IsReadOnly() &&
((objectType->flags & asOBJ_SCRIPT_OBJECT) || func->parameterTypes[0].IsEqualExceptRefAndConst(asCDataType::CreateType(func->objectType, false)))) {
if (func->objectType->beh.copy != 0)
return ConfigError(asALREADY_REGISTERED, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
func->objectType->beh.copy = func->id;
func->AddRefInternal();
}
// Return the function id as success
return func->id;
}
// interface
int asCScriptEngine::RegisterGlobalFunction(const char *declaration, const asSFuncPtr &funcPointer, asDWORD callConv, void *auxiliary) {
#ifdef AS_MAX_PORTABILITY
if (callConv != asCALL_GENERIC)
return ConfigError(asNOT_SUPPORTED, "RegisterGlobalFunction", declaration, 0);
#endif
asSSystemFunctionInterface internal;
int r = DetectCallingConvention(false, funcPointer, callConv, auxiliary, &internal);
if (r < 0)
return ConfigError(r, "RegisterGlobalFunction", declaration, 0);
isPrepared = false;
// Put the system function in the list of system functions
asSSystemFunctionInterface *newInterface = asNEW(asSSystemFunctionInterface)(internal);
if (newInterface == 0)
return ConfigError(asOUT_OF_MEMORY, "RegisterGlobalFunction", declaration, 0);
asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_SYSTEM);
if (func == 0) {
asDELETE(newInterface, asSSystemFunctionInterface);
return ConfigError(asOUT_OF_MEMORY, "RegisterGlobalFunction", declaration, 0);
}
func->sysFuncIntf = newInterface;
asCBuilder bld(this, 0);
r = bld.ParseFunctionDeclaration(0, declaration, func, true, &newInterface->paramAutoHandles, &newInterface->returnAutoHandle, defaultNamespace);
if (r < 0) {
// Set as dummy function before deleting
func->funcType = asFUNC_DUMMY;
asDELETE(func, asCScriptFunction);
return ConfigError(asINVALID_DECLARATION, "RegisterGlobalFunction", declaration, 0);
}
// TODO: namespace: What if the declaration defined an explicit namespace?
func->nameSpace = defaultNamespace;
// Check name conflicts
r = bld.CheckNameConflict(func->name.AddressOf(), 0, 0, defaultNamespace, false, false);
if (r < 0) {
// Set as dummy function before deleting
func->funcType = asFUNC_DUMMY;
asDELETE(func, asCScriptFunction);
return ConfigError(asNAME_TAKEN, "RegisterGlobalFunction", declaration, 0);
}
// Validate property signature
if (func->IsProperty() && (r = bld.ValidateVirtualProperty(func)) < 0) {
// Set as dummy function before deleting
func->funcType = asFUNC_DUMMY;
asDELETE(func, asCScriptFunction);
if (r == -5)
return ConfigError(asNAME_TAKEN, "RegisterGlobalFunction", declaration, 0);
else
return ConfigError(asINVALID_DECLARATION, "RegisterGlobalFunction", declaration, 0);
}
// Make sure the function is not identical to a previously registered function
asUINT n;
const asCArray<unsigned int> &idxs = registeredGlobalFuncs.GetIndexes(func->nameSpace, func->name);
for (n = 0; n < idxs.GetLength(); n++) {
asCScriptFunction *f = registeredGlobalFuncs.Get(idxs[n]);
if (f->IsSignatureExceptNameAndReturnTypeEqual(func)) {
func->funcType = asFUNC_DUMMY;
asDELETE(func, asCScriptFunction);
return ConfigError(asALREADY_REGISTERED, "RegisterGlobalFunction", declaration, 0);
}
}
func->id = GetNextScriptFunctionId();
AddScriptFunction(func);
currentGroup->scriptFunctions.PushLast(func);
func->accessMask = defaultAccessMask;
registeredGlobalFuncs.Put(func);
// If parameter type from other groups are used, add references
currentGroup->AddReferencesForFunc(this, func);
// Return the function id as success
return func->id;
}
// interface
asUINT asCScriptEngine::GetGlobalFunctionCount() const {
// Don't count the builtin delegate factory
return asUINT(registeredGlobalFuncs.GetSize() - 1);
}
// interface
asIScriptFunction *asCScriptEngine::GetGlobalFunctionByIndex(asUINT index) const {
// Don't count the builtin delegate factory
index++;
if (index >= registeredGlobalFuncs.GetSize())
return 0;
return static_cast<asIScriptFunction *>(const_cast<asCScriptFunction *>(registeredGlobalFuncs.Get(index)));
}
// interface
asIScriptFunction *asCScriptEngine::GetGlobalFunctionByDecl(const char *decl) const {
asCBuilder bld(const_cast<asCScriptEngine *>(this), 0);
// Don't write parser errors to the message callback
bld.silent = true;
asCScriptFunction func(const_cast<asCScriptEngine *>(this), 0, asFUNC_DUMMY);
int r = bld.ParseFunctionDeclaration(0, decl, &func, false, 0, 0, defaultNamespace);
if (r < 0)
return 0;
asSNameSpace *ns = defaultNamespace;
// Search script functions for matching interface
while (ns) {
asIScriptFunction *f = 0;
const asCArray<unsigned int> &idxs = registeredGlobalFuncs.GetIndexes(ns, func.name);
for (unsigned int n = 0; n < idxs.GetLength(); n++) {
const asCScriptFunction *funcPtr = registeredGlobalFuncs.Get(idxs[n]);
if (funcPtr->objectType == 0 &&
func.returnType == funcPtr->returnType &&
func.parameterTypes.GetLength() == funcPtr->parameterTypes.GetLength()
) {
bool match = true;
for (asUINT p = 0; p < func.parameterTypes.GetLength(); ++p) {
if (func.parameterTypes[p] != funcPtr->parameterTypes[p]) {
match = false;
break;
}
}
if (match) {
if (f == 0)
f = const_cast<asCScriptFunction *>(funcPtr);
else
// Multiple functions
return 0;
}
}
}
if (f)
return f;
// Recursively search parent namespaces
ns = GetParentNameSpace(ns);
}
return 0;
}
asCTypeInfo *asCScriptEngine::GetRegisteredType(const asCString &type, asSNameSpace *ns) const {
asSMapNode<asSNameSpaceNamePair, asCTypeInfo *> *cursor;
if (allRegisteredTypes.MoveTo(&cursor, asSNameSpaceNamePair(ns, type)))
return cursor->value;
return 0;
}
void asCScriptEngine::PrepareEngine() {
if (isPrepared) return;
if (configFailed) return;
asUINT n;
for (n = 0; n < scriptFunctions.GetLength(); n++) {
// Determine the host application interface
if (scriptFunctions[n] && scriptFunctions[n]->funcType == asFUNC_SYSTEM) {
if (scriptFunctions[n]->sysFuncIntf->callConv == ICC_GENERIC_FUNC ||
scriptFunctions[n]->sysFuncIntf->callConv == ICC_GENERIC_METHOD)
PrepareSystemFunctionGeneric(scriptFunctions[n], scriptFunctions[n]->sysFuncIntf, this);
else
PrepareSystemFunction(scriptFunctions[n], scriptFunctions[n]->sysFuncIntf, this);
}
}
// Validate object type registrations
for (n = 0; n < registeredObjTypes.GetLength(); n++) {
asCObjectType *type = registeredObjTypes[n];
if (type && !(type->flags & asOBJ_SCRIPT_OBJECT)) {
bool missingBehaviour = false;
const char *infoMsg = 0;
// Verify that GC types have all behaviours
if (type->flags & asOBJ_GC) {
if (type->flags & asOBJ_REF) {
if (type->beh.addref == 0 ||
type->beh.release == 0 ||
type->beh.gcGetRefCount == 0 ||
type->beh.gcSetFlag == 0 ||
type->beh.gcGetFlag == 0 ||
type->beh.gcEnumReferences == 0 ||
type->beh.gcReleaseAllReferences == 0) {
infoMsg = TXT_GC_REQUIRE_ADD_REL_GC_BEHAVIOUR;
missingBehaviour = true;
}
} else {
if (type->beh.gcEnumReferences == 0) {
infoMsg = TXT_VALUE_GC_REQUIRE_GC_BEHAVIOUR;
missingBehaviour = true;
}
}
}
// Verify that scoped ref types have the release behaviour
if (type->flags & asOBJ_SCOPED) {
if (type->beh.release == 0) {
infoMsg = TXT_SCOPE_REQUIRE_REL_BEHAVIOUR;
missingBehaviour = true;
}
}
// Verify that ref types have add ref and release behaviours
if ((type->flags & asOBJ_REF) &&
!(type->flags & asOBJ_SCOPED) &&
!(type->flags & asOBJ_NOHANDLE) &&
!(type->flags & asOBJ_NOCOUNT)) {
if (type->beh.addref == 0 ||
type->beh.release == 0) {
infoMsg = TXT_REF_REQUIRE_ADD_REL_BEHAVIOUR;
missingBehaviour = true;
}
}
// Verify that non-pod value types have the constructor and destructor registered
if ((type->flags & asOBJ_VALUE) &&
!(type->flags & asOBJ_POD)) {
if (type->beh.constructors.GetLength() == 0 ||
type->beh.destruct == 0) {
infoMsg = TXT_NON_POD_REQUIRE_CONSTR_DESTR_BEHAVIOUR;
missingBehaviour = true;
}
}
if (missingBehaviour) {
asCString str;
str.Format(TXT_TYPE_s_IS_MISSING_BEHAVIOURS, type->name.AddressOf());
WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
WriteMessage("", 0, 0, asMSGTYPE_INFORMATION, infoMsg);
ConfigError(asINVALID_CONFIGURATION, 0, 0, 0);
}
}
}
isPrepared = true;
}
int asCScriptEngine::ConfigError(int err, const char *funcName, const char *arg1, const char *arg2) {
configFailed = true;
if (funcName) {
asCString str;
if (arg1) {
if (arg2)
str.Format(TXT_FAILED_IN_FUNC_s_WITH_s_AND_s_s_d, funcName, arg1, arg2, errorNames[-err], err);
else
str.Format(TXT_FAILED_IN_FUNC_s_WITH_s_s_d, funcName, arg1, errorNames[-err], err);
} else
str.Format(TXT_FAILED_IN_FUNC_s_s_d, funcName, errorNames[-err], err);
WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
}
return err;
}
// interface
int asCScriptEngine::RegisterDefaultArrayType(const char *type) {
asCBuilder bld(this, 0);
asCDataType dt;
int r = bld.ParseDataType(type, &dt, defaultNamespace);
if (r < 0) return r;
if (dt.GetTypeInfo() == 0 ||
!(dt.GetTypeInfo()->GetFlags() & asOBJ_TEMPLATE))
return asINVALID_TYPE;
defaultArrayObjectType = CastToObjectType(dt.GetTypeInfo());
defaultArrayObjectType->AddRefInternal();
return 0;
}
// interface
int asCScriptEngine::GetDefaultArrayTypeId() const {
if (defaultArrayObjectType)
return GetTypeIdFromDataType(asCDataType::CreateType(defaultArrayObjectType, false));
return asINVALID_TYPE;
}
// interface
int asCScriptEngine::RegisterStringFactory(const char *datatype, asIStringFactory *factory) {
if (factory == 0)
return ConfigError(asINVALID_ARG, "RegisterStringFactory", datatype, 0);
// Parse the data type
asCBuilder bld(this, 0);
asCDataType dt;
int r = bld.ParseDataType(datatype, &dt, defaultNamespace, true);
if (r < 0)
return ConfigError(asINVALID_TYPE, "RegisterStringFactory", datatype, 0);
// Validate the type. It must not be reference or handle
if (dt.IsReference() || dt.IsObjectHandle())
return ConfigError(asINVALID_TYPE, "RegisterStringFactory", datatype, 0);
// All string literals will be treated as const
dt.MakeReadOnly(true);
stringType = dt;
stringFactory = factory;
return asSUCCESS;
}
// interface
int asCScriptEngine::GetStringFactoryReturnTypeId(asDWORD *flags) const {
if (stringFactory == 0)
return asNO_FUNCTION;
if (flags)
*flags = 0;
return GetTypeIdFromDataType(stringType);
}
// internal
asCModule *asCScriptEngine::GetModule(const char *name, bool create) {
// Accept null as well as zero-length string
if (name == 0) name = "";
asCModule *retModule = 0;
ACQUIRESHARED(engineRWLock);
if (lastModule && lastModule->m_name == name)
retModule = lastModule;
else {
// TODO: optimize: Improve linear search
for (asUINT n = 0; n < scriptModules.GetLength(); ++n)
if (scriptModules[n] && scriptModules[n]->m_name == name) {
retModule = scriptModules[n];
break;
}
}
RELEASESHARED(engineRWLock);
if (retModule) {
ACQUIREEXCLUSIVE(engineRWLock);
lastModule = retModule;
RELEASEEXCLUSIVE(engineRWLock);
return retModule;
}
if (create) {
retModule = asNEW(asCModule)(name, this);
if (retModule == 0) {
// Out of memory
return 0;
}
ACQUIREEXCLUSIVE(engineRWLock);
scriptModules.PushLast(retModule);
lastModule = retModule;
RELEASEEXCLUSIVE(engineRWLock);
}
return retModule;
}
asCModule *asCScriptEngine::GetModuleFromFuncId(int id) {
if (id < 0) return 0;
if (id >= (int)scriptFunctions.GetLength()) return 0;
asCScriptFunction *func = scriptFunctions[id];
if (func == 0) return 0;
return func->module;
}
// internal
int asCScriptEngine::RequestBuild() {
ACQUIREEXCLUSIVE(engineRWLock);
if (isBuilding) {
RELEASEEXCLUSIVE(engineRWLock);
return asBUILD_IN_PROGRESS;
}
isBuilding = true;
RELEASEEXCLUSIVE(engineRWLock);
return 0;
}
// internal
void asCScriptEngine::BuildCompleted() {
// Always free up pooled memory after a completed build
memoryMgr.FreeUnusedMemory();
isBuilding = false;
}
void asCScriptEngine::RemoveTemplateInstanceType(asCObjectType *t) {
// If there is a module that still owns the generated type, then don't remove it
if (t->module)
return;
// Don't remove it if there are external refernces
if (t->externalRefCount.get())
return;
// Only remove the template instance type if no config group is using it
if (defaultGroup.generatedTemplateInstances.Exists(t))
return;
for (asUINT n = 0; n < configGroups.GetLength(); n++)
if (configGroups[n]->generatedTemplateInstances.Exists(t))
return;
t->DestroyInternal();
templateInstanceTypes.RemoveValue(t);
generatedTemplateTypes.RemoveValue(t);
t->ReleaseInternal();
}
// internal
asCObjectType *asCScriptEngine::GetTemplateInstanceType(asCObjectType *templateType, asCArray<asCDataType> &subTypes, asCModule *requestingModule) {
asUINT n;
// Is there any template instance type or template specialization already with this subtype?
for (n = 0; n < templateInstanceTypes.GetLength(); n++) {
asCObjectType *type = templateInstanceTypes[n];
if (type &&
type->name == templateType->name &&
type->nameSpace == templateType->nameSpace &&
type->templateSubTypes == subTypes) {
// If the template instance is generated, then the module should hold a reference
// to it so the config group can determine see that the template type is in use.
// Template specializations will be treated as normal types
if (requestingModule && generatedTemplateTypes.Exists(type)) {
if (type->module == 0) {
// Set the ownership of this template type
// It may be without ownership if it was previously created from application with for example GetTypeInfoByDecl
type->module = requestingModule;
}
if (!requestingModule->m_templateInstances.Exists(type)) {
requestingModule->m_templateInstances.PushLast(type);
type->AddRefInternal();
}
}
return templateInstanceTypes[n];
}
}
// No previous template instance exists
// Make sure this template supports the subtype
for (n = 0; n < subTypes.GetLength(); n++) {
if (!templateType->acceptValueSubType && (subTypes[n].IsPrimitive() || (subTypes[n].GetTypeInfo()->flags & asOBJ_VALUE)))
return 0;
if (!templateType->acceptRefSubType && (subTypes[n].IsObject() && (subTypes[n].GetTypeInfo()->flags & asOBJ_REF)))
return 0;
}
// Create a new template instance type based on the templateType
asCObjectType *ot = asNEW(asCObjectType)(this);
if (ot == 0) {
// Out of memory
return 0;
}
ot->templateSubTypes = subTypes;
ot->flags = templateType->flags;
ot->size = templateType->size;
ot->name = templateType->name;
ot->nameSpace = templateType->nameSpace;
// If the template is being requested from a module, then the module should hold a reference to the type
if (requestingModule) {
// Set the ownership of this template type
ot->module = requestingModule;
requestingModule->m_templateInstances.PushLast(ot);
ot->AddRefInternal();
} else {
// If the template type is not requested directly from a module, then set the ownership
// of it to the same module as one of the subtypes. If none of the subtypes are owned by]
// any module, the template instance will be without ownership and can be removed from the
// engine at any time (unless the application holds an external reference).
for (n = 0; n < subTypes.GetLength(); n++) {
if (subTypes[n].GetTypeInfo()) {
ot->module = subTypes[n].GetTypeInfo()->module;
if (ot->module) {
ot->module->m_templateInstances.PushLast(ot);
ot->AddRefInternal();
break;
}
}
}
}
// Before filling in the methods, call the template instance callback behaviour to validate the type
if (templateType->beh.templateCallback) {
// If the validation is deferred then the validation will be done later,
// so it is necessary to continue the preparation of the template instance type
if (!deferValidationOfTemplateTypes) {
asCScriptFunction *callback = scriptFunctions[templateType->beh.templateCallback];
bool dontGarbageCollect = false;
if (!CallGlobalFunctionRetBool(ot, &dontGarbageCollect, callback->sysFuncIntf, callback)) {
// The type cannot be instantiated
ot->templateSubTypes.SetLength(0);
if (ot->module) {
ot->module->m_templateInstances.RemoveValue(ot);
ot->ReleaseInternal();
}
ot->ReleaseInternal();
return 0;
}
// If the callback said this template instance won't be garbage collected then remove the flag
if (dontGarbageCollect)
ot->flags &= ~asOBJ_GC;
}
ot->beh.templateCallback = templateType->beh.templateCallback;
scriptFunctions[ot->beh.templateCallback]->AddRefInternal();
}
ot->methods = templateType->methods;
for (n = 0; n < ot->methods.GetLength(); n++)
scriptFunctions[ot->methods[n]]->AddRefInternal();
if (templateType->flags & asOBJ_REF) {
// Store the real factory in the constructor. This is used by the CreateScriptObject function.
// Otherwise it wouldn't be necessary to store the real factory ids.
ot->beh.construct = templateType->beh.factory;
ot->beh.constructors = templateType->beh.factories;
} else {
ot->beh.construct = templateType->beh.construct;
ot->beh.constructors = templateType->beh.constructors;
}
for (n = 0; n < ot->beh.constructors.GetLength(); n++)
scriptFunctions[ot->beh.constructors[n]]->AddRefInternal();
// Before proceeding with the generation of the template functions for the template instance it is necessary
// to include the new template instance type in the list of known types, otherwise it is possible that we get
// a infinite recursive loop as the template instance type is requested again during the generation of the
// template functions.
templateInstanceTypes.PushLast(ot);
// Store the template instance types that have been created automatically by the engine from a template type
// The object types in templateInstanceTypes that are not also in generatedTemplateTypes are registered template specializations
generatedTemplateTypes.PushLast(ot);
// Any child funcdefs must be copied to the template instance (with adjustments in case of template subtypes)
// This must be done before resolving other methods, to make sure the other methods that may refer to the
// templated funcdef will resolve to the new funcdef
for (n = 0; n < templateType->childFuncDefs.GetLength(); n++) {
asCFuncdefType *funcdef = GenerateNewTemplateFuncdef(templateType, ot, templateType->childFuncDefs[n]);
funcdef->parentClass = ot;
ot->childFuncDefs.PushLast(funcdef);
}
// As the new template type is instantiated the engine should
// generate new functions to substitute the ones with the template subtype.
for (n = 0; n < ot->beh.constructors.GetLength(); n++) {
int funcId = ot->beh.constructors[n];
asCScriptFunction *func = scriptFunctions[funcId];
if (GenerateNewTemplateFunction(templateType, ot, func, &func)) {
// Release the old function, the new one already has its ref count set to 1
scriptFunctions[funcId]->ReleaseInternal();
ot->beh.constructors[n] = func->id;
if (ot->beh.construct == funcId)
ot->beh.construct = func->id;
}
}
ot->beh.factory = 0;
if (templateType->flags & asOBJ_REF) {
// Generate factory stubs for each of the factories
for (n = 0; n < ot->beh.constructors.GetLength(); n++) {
asCScriptFunction *func = GenerateTemplateFactoryStub(templateType, ot, ot->beh.constructors[n]);
ot->beh.factories.PushLast(func->id);
// Set the default factory as well
if (ot->beh.constructors[n] == ot->beh.construct)
ot->beh.factory = func->id;
}
} else {
// Generate factory stubs for each of the constructors
for (n = 0; n < ot->beh.constructors.GetLength(); n++) {
asCScriptFunction *func = GenerateTemplateFactoryStub(templateType, ot, ot->beh.constructors[n]);
if (ot->beh.constructors[n] == ot->beh.construct)
ot->beh.construct = func->id;
// Release previous constructor
scriptFunctions[ot->beh.constructors[n]]->ReleaseInternal();
ot->beh.constructors[n] = func->id;
}
}
// Generate stub for the list factory as well
if (templateType->beh.listFactory) {
asCScriptFunction *func = GenerateTemplateFactoryStub(templateType, ot, templateType->beh.listFactory);
// Rename the function to easily identify it in LoadByteCode
func->name = "$list";
ot->beh.listFactory = func->id;
}
ot->beh.addref = templateType->beh.addref;
if (scriptFunctions[ot->beh.addref]) scriptFunctions[ot->beh.addref]->AddRefInternal();
ot->beh.release = templateType->beh.release;
if (scriptFunctions[ot->beh.release]) scriptFunctions[ot->beh.release]->AddRefInternal();
ot->beh.destruct = templateType->beh.destruct;
if (scriptFunctions[ot->beh.destruct]) scriptFunctions[ot->beh.destruct]->AddRefInternal();
ot->beh.copy = templateType->beh.copy;
if (scriptFunctions[ot->beh.copy]) scriptFunctions[ot->beh.copy]->AddRefInternal();
ot->beh.gcGetRefCount = templateType->beh.gcGetRefCount;
if (scriptFunctions[ot->beh.gcGetRefCount]) scriptFunctions[ot->beh.gcGetRefCount]->AddRefInternal();
ot->beh.gcSetFlag = templateType->beh.gcSetFlag;
if (scriptFunctions[ot->beh.gcSetFlag]) scriptFunctions[ot->beh.gcSetFlag]->AddRefInternal();
ot->beh.gcGetFlag = templateType->beh.gcGetFlag;
if (scriptFunctions[ot->beh.gcGetFlag]) scriptFunctions[ot->beh.gcGetFlag]->AddRefInternal();
ot->beh.gcEnumReferences = templateType->beh.gcEnumReferences;
if (scriptFunctions[ot->beh.gcEnumReferences]) scriptFunctions[ot->beh.gcEnumReferences]->AddRefInternal();
ot->beh.gcReleaseAllReferences = templateType->beh.gcReleaseAllReferences;
if (scriptFunctions[ot->beh.gcReleaseAllReferences]) scriptFunctions[ot->beh.gcReleaseAllReferences]->AddRefInternal();
ot->beh.getWeakRefFlag = templateType->beh.getWeakRefFlag;
if (scriptFunctions[ot->beh.getWeakRefFlag]) scriptFunctions[ot->beh.getWeakRefFlag]->AddRefInternal();
// As the new template type is instantiated, the engine should
// generate new functions to substitute the ones with the template subtype.
for (n = 0; n < ot->methods.GetLength(); n++) {
int funcId = ot->methods[n];
asCScriptFunction *func = scriptFunctions[funcId];
if (GenerateNewTemplateFunction(templateType, ot, func, &func)) {
// Release the old function, the new one already has its ref count set to 1
scriptFunctions[funcId]->ReleaseInternal();
ot->methods[n] = func->id;
}
}
// Increase ref counter for sub type if it is an object type
for (n = 0; n < ot->templateSubTypes.GetLength(); n++)
if (ot->templateSubTypes[n].GetTypeInfo())
ot->templateSubTypes[n].GetTypeInfo()->AddRefInternal();
// Copy the properties to the template instance
for (n = 0; n < templateType->properties.GetLength(); n++) {
asCObjectProperty *prop = templateType->properties[n];
ot->properties.PushLast(asNEW(asCObjectProperty)(*prop));
if (prop->type.GetTypeInfo())
prop->type.GetTypeInfo()->AddRefInternal();
}
return ot;
}
// interface
asILockableSharedBool *asCScriptEngine::GetWeakRefFlagOfScriptObject(void *obj, const asITypeInfo *type) const {
// Make sure it is not a null pointer
if (obj == 0 || type == 0) return 0;
const asCObjectType *objType = static_cast<const asCObjectType *>(type);
asILockableSharedBool *dest = 0;
if (objType->beh.getWeakRefFlag) {
// Call the getweakrefflag behaviour
dest = reinterpret_cast<asILockableSharedBool *>(CallObjectMethodRetPtr(obj, objType->beh.getWeakRefFlag));
}
return dest;
}
// internal
// orig is the parameter type that is to be replaced
// tmpl is the registered template. Used to find which subtype is being replaced
// ot is the new template instance that is being created. Used to find the target type
asCDataType asCScriptEngine::DetermineTypeForTemplate(const asCDataType &orig, asCObjectType *tmpl, asCObjectType *ot) {
asCDataType dt;
if (orig.GetTypeInfo() && (orig.GetTypeInfo()->flags & asOBJ_TEMPLATE_SUBTYPE)) {
bool found = false;
for (asUINT n = 0; n < tmpl->templateSubTypes.GetLength(); n++) {
if (orig.GetTypeInfo() == tmpl->templateSubTypes[n].GetTypeInfo()) {
found = true;
dt = ot->templateSubTypes[n];
if (orig.IsObjectHandle() && !ot->templateSubTypes[n].IsObjectHandle()) {
dt.MakeHandle(true, true);
asASSERT(dt.IsObjectHandle());
if (orig.IsHandleToConst())
dt.MakeHandleToConst(true);
dt.MakeReference(orig.IsReference());
dt.MakeReadOnly(orig.IsReadOnly());
} else {
// The target type is a handle, then check if the application
// wants this handle to be to a const object. This is done by
// flagging the type with 'if_handle_then_const' in the declaration.
if (dt.IsObjectHandle() && orig.HasIfHandleThenConst())
dt.MakeHandleToConst(true);
dt.MakeReference(orig.IsReference());
dt.MakeReadOnly(ot->templateSubTypes[n].IsReadOnly() || orig.IsReadOnly());
// If the target is a @& then don't make the handle const,
// as it is not possible to declare functions with @const &
if (orig.IsReference() && dt.IsObjectHandle())
dt.MakeReadOnly(false);
}
break;
}
}
asASSERT(found);
UNUSED_VAR(found);
} else if (orig.GetTypeInfo() == tmpl) {
if (orig.IsObjectHandle())
dt = asCDataType::CreateObjectHandle(ot, false);
else
dt = asCDataType::CreateType(ot, false);
dt.MakeReference(orig.IsReference());
dt.MakeReadOnly(orig.IsReadOnly());
} else if (orig.GetTypeInfo() && (orig.GetTypeInfo()->flags & asOBJ_TEMPLATE)) {
// The type is itself a template, so it is necessary to find the correct template instance type
asCArray<asCDataType> tmplSubTypes;
asCObjectType *origType = CastToObjectType(orig.GetTypeInfo());
bool needInstance = true;
// Find the matching replacements for the subtypes
for (asUINT n = 0; n < origType->templateSubTypes.GetLength(); n++) {
if (origType->templateSubTypes[n].GetTypeInfo() == 0 ||
!(origType->templateSubTypes[n].GetTypeInfo()->flags & asOBJ_TEMPLATE_SUBTYPE)) {
// The template is already an instance so we shouldn't attempt to create another instance
needInstance = false;
break;
}
for (asUINT m = 0; m < tmpl->templateSubTypes.GetLength(); m++)
if (origType->templateSubTypes[n].GetTypeInfo() == tmpl->templateSubTypes[m].GetTypeInfo())
tmplSubTypes.PushLast(ot->templateSubTypes[m]);
if (tmplSubTypes.GetLength() != n + 1) {
asASSERT(false);
return orig;
}
}
asCObjectType *ntype = origType;
if (needInstance) {
// Always find the original template type when creating a new template instance otherwise the
// generation will fail since it will attempt to create factory stubs when they already exists, etc
for (asUINT n = 0; n < registeredTemplateTypes.GetLength(); n++)
if (registeredTemplateTypes[n]->name == origType->name &&
registeredTemplateTypes[n]->nameSpace == origType->nameSpace) {
origType = registeredTemplateTypes[n];
break;
}
ntype = GetTemplateInstanceType(origType, tmplSubTypes, ot->module);
if (ntype == 0) {
// It not possible to instantiate the subtype
asASSERT(false);
ntype = tmpl;
}
}
if (orig.IsObjectHandle())
dt = asCDataType::CreateObjectHandle(ntype, false);
else
dt = asCDataType::CreateType(ntype, false);
dt.MakeReference(orig.IsReference());
dt.MakeReadOnly(orig.IsReadOnly());
} else if (orig.GetTypeInfo() && (orig.GetTypeInfo()->flags & asOBJ_FUNCDEF) && CastToFuncdefType(orig.GetTypeInfo())->parentClass == tmpl) {
// The type is a child funcdef. Find the corresponding child funcdef in the template instance
for (asUINT n = 0; n < ot->childFuncDefs.GetLength(); n++) {
if (ot->childFuncDefs[n]->name == orig.GetTypeInfo()->name) {
dt = orig;
dt.SetTypeInfo(ot->childFuncDefs[n]);
}
}
} else
dt = orig;
return dt;
}
// internal
asCScriptFunction *asCScriptEngine::GenerateTemplateFactoryStub(asCObjectType *templateType, asCObjectType *ot, int factoryId) {
asCScriptFunction *factory = scriptFunctions[factoryId];
// By first instantiating the function as a dummy and then changing it to be a script function
// I avoid having it added to the garbage collector. As it is known that this object will stay
// alive until the template instance is no longer used there is no need to have the GC check
// this function all the time.
asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_DUMMY);
if (func == 0) {
// Out of memory
return 0;
}
func->funcType = asFUNC_SCRIPT;
func->AllocateScriptFunctionData();
func->id = GetNextScriptFunctionId();
AddScriptFunction(func);
func->traits = factory->traits;
func->SetShared(true);
if (templateType->flags & asOBJ_REF) {
func->name = "$fact";
func->returnType = asCDataType::CreateObjectHandle(ot, false);
} else {
func->name = "$beh0";
func->returnType = factory->returnType; // constructors return nothing
func->objectType = ot;
func->objectType->AddRefInternal();
}
// Skip the first parameter as this is the object type pointer that the stub will add
func->parameterTypes.SetLength(factory->parameterTypes.GetLength() - 1);
func->parameterNames.SetLength(factory->parameterNames.GetLength() - 1);
func->inOutFlags.SetLength(factory->inOutFlags.GetLength() - 1);
func->defaultArgs.SetLength(factory->defaultArgs.GetLength() - 1);
for (asUINT p = 1; p < factory->parameterTypes.GetLength(); p++) {
func->parameterTypes[p - 1] = factory->parameterTypes[p];
func->parameterNames[p - 1] = factory->parameterNames[p];
func->inOutFlags[p - 1] = factory->inOutFlags[p];
func->defaultArgs[p - 1] = factory->defaultArgs[p] ? asNEW(asCString)(*factory->defaultArgs[p]) : 0;
}
func->scriptData->objVariablesOnHeap = 0;
// Generate the bytecode for the factory stub
asUINT bcLength = asBCTypeSize[asBCInfo[asBC_OBJTYPE].type] +
asBCTypeSize[asBCInfo[asBC_CALLSYS].type] +
asBCTypeSize[asBCInfo[asBC_RET].type];
if (ep.includeJitInstructions)
bcLength += asBCTypeSize[asBCInfo[asBC_JitEntry].type];
if (templateType->flags & asOBJ_VALUE)
bcLength += asBCTypeSize[asBCInfo[asBC_SwapPtr].type];
func->scriptData->byteCode.SetLength(bcLength);
asDWORD *bc = func->scriptData->byteCode.AddressOf();
if (ep.includeJitInstructions) {
*(asBYTE *)bc = asBC_JitEntry;
*(asPWORD *)(bc + 1) = 0;
bc += asBCTypeSize[asBCInfo[asBC_JitEntry].type];
}
*(asBYTE *)bc = asBC_OBJTYPE;
*(asPWORD *)(bc + 1) = (asPWORD)ot;
bc += asBCTypeSize[asBCInfo[asBC_OBJTYPE].type];
if (templateType->flags & asOBJ_VALUE) {
// Swap the object pointer with the object type
*(asBYTE *)bc = asBC_SwapPtr;
bc += asBCTypeSize[asBCInfo[asBC_SwapPtr].type];
}
*(asBYTE *)bc = asBC_CALLSYS;
*(asDWORD *)(bc + 1) = factoryId;
bc += asBCTypeSize[asBCInfo[asBC_CALLSYS].type];
*(asBYTE *)bc = asBC_RET;
*(((asWORD *)bc) + 1) = (asWORD)func->GetSpaceNeededForArguments() + (func->objectType ? AS_PTR_SIZE : 0);
func->AddReferences();
func->scriptData->stackNeeded = AS_PTR_SIZE;
// Tell the virtual machine not to clean up the object on exception
func->dontCleanUpOnException = true;
func->JITCompile();
// Need to translate the list pattern too so the VM and compiler will know the correct type of the members
if (factory->listPattern) {
asSListPatternNode *n = factory->listPattern;
asSListPatternNode *last = 0;
while (n) {
asSListPatternNode *newNode = n->Duplicate();
if (newNode->type == asLPT_TYPE) {
asSListPatternDataTypeNode *typeNode = reinterpret_cast<asSListPatternDataTypeNode *>(newNode);
typeNode->dataType = DetermineTypeForTemplate(typeNode->dataType, templateType, ot);
}
if (last)
last->next = newNode;
else
func->listPattern = newNode;
last = newNode;
n = n->next;
}
}
return func;
}
bool asCScriptEngine::RequireTypeReplacement(asCDataType &type, asCObjectType *templateType) {
if (type.GetTypeInfo() == templateType) return true;
if (type.GetTypeInfo() && (type.GetTypeInfo()->flags & asOBJ_TEMPLATE_SUBTYPE)) return true;
if (type.GetTypeInfo() && (type.GetTypeInfo()->flags & asOBJ_TEMPLATE)) {
asCObjectType *ot = CastToObjectType(type.GetTypeInfo());
for (asUINT n = 0; n < ot->templateSubTypes.GetLength(); n++)
if (ot->templateSubTypes[n].GetTypeInfo() &&
ot->templateSubTypes[n].GetTypeInfo()->flags & asOBJ_TEMPLATE_SUBTYPE)
return true;
}
if (type.GetTypeInfo() && (type.GetTypeInfo()->flags & asOBJ_FUNCDEF) && CastToFuncdefType(type.GetTypeInfo())->parentClass == templateType)
return true;
return false;
}
bool asCScriptEngine::GenerateNewTemplateFunction(asCObjectType *templateType, asCObjectType *ot, asCScriptFunction *func, asCScriptFunction **newFunc) {
// Due to the objectType it is always required to generate a new function,
// even if none of the function arguments needs to be changed.
/*
// TODO: Can we store the new function in some other optimized way to avoid
// duplicating all information just because of the different objectType member?
bool needNewFunc = false;
if( RequireTypeReplacement(func->returnType, templateType) )
needNewFunc = true;
else
{
for( asUINT p = 0; p < func->parameterTypes.GetLength(); p++ )
{
if( RequireTypeReplacement(func->parameterTypes[p], templateType) )
{
needNewFunc = true;
break;
}
}
}
if( !needNewFunc )
return false;
*/
asCScriptFunction *func2 = asNEW(asCScriptFunction)(this, 0, func->funcType);
if (func2 == 0) {
// Out of memory
return false;
}
func2->name = func->name;
func2->returnType = DetermineTypeForTemplate(func->returnType, templateType, ot);
func2->parameterTypes.SetLength(func->parameterTypes.GetLength());
for (asUINT p = 0; p < func->parameterTypes.GetLength(); p++)
func2->parameterTypes[p] = DetermineTypeForTemplate(func->parameterTypes[p], templateType, ot);
for (asUINT n = 0; n < func->defaultArgs.GetLength(); n++)
if (func->defaultArgs[n])
func2->defaultArgs.PushLast(asNEW(asCString)(*func->defaultArgs[n]));
else
func2->defaultArgs.PushLast(0);
// TODO: template: Must be careful when instantiating templates for garbage collected types
// If the template hasn't been registered with the behaviours, it shouldn't
// permit instantiation of garbage collected types that in turn may refer to
// this instance.
func2->parameterNames = func->parameterNames;
func2->inOutFlags = func->inOutFlags;
func2->traits = func->traits;
func2->SetReadOnly(func->IsReadOnly());
func2->objectType = ot;
func2->objectType->AddRefInternal();
func2->sysFuncIntf = asNEW(asSSystemFunctionInterface)(*func->sysFuncIntf);
// Adjust the clean up instructions
if (func2->sysFuncIntf->callConv == ICC_GENERIC_FUNC ||
func2->sysFuncIntf->callConv == ICC_GENERIC_METHOD)
PrepareSystemFunctionGeneric(func2, func2->sysFuncIntf, this);
else
PrepareSystemFunction(func2, func2->sysFuncIntf, this);
func2->id = GetNextScriptFunctionId();
AddScriptFunction(func2);
// Return the new function
*newFunc = func2;
return true;
}
asCFuncdefType *asCScriptEngine::GenerateNewTemplateFuncdef(asCObjectType *templateType, asCObjectType *ot, asCFuncdefType *func) {
// TODO: Only generate the new funcdef if it used the template subtypes.
// Remember to also update the clean up in asCObjectType::DestroyInternal so it doesn't delete
// child funcdefs that have not been created specificially for the template instance.
// Perhaps a new funcdef is always needed, since the funcdef will have a reference to the
// parent class (in this case the template instance).
asCScriptFunction *func2 = asNEW(asCScriptFunction)(this, 0, func->funcdef->funcType);
if (func2 == 0) {
// Out of memory
return 0;
}
func2->name = func->name;
func2->returnType = DetermineTypeForTemplate(func->funcdef->returnType, templateType, ot);
func2->parameterTypes.SetLength(func->funcdef->parameterTypes.GetLength());
for (asUINT p = 0; p < func->funcdef->parameterTypes.GetLength(); p++)
func2->parameterTypes[p] = DetermineTypeForTemplate(func->funcdef->parameterTypes[p], templateType, ot);
// TODO: template: Must be careful when instantiating templates for garbage collected types
// If the template hasn't been registered with the behaviours, it shouldn't
// permit instantiation of garbage collected types that in turn may refer to
// this instance.
func2->inOutFlags = func->funcdef->inOutFlags;
func2->SetReadOnly(func->funcdef->IsReadOnly());
asASSERT(func->funcdef->objectType == 0);
asASSERT(func->funcdef->sysFuncIntf == 0);
func2->id = GetNextScriptFunctionId();
AddScriptFunction(func2);
asCFuncdefType *fdt2 = asNEW(asCFuncdefType)(this, func2);
funcDefs.PushLast(fdt2); // don't increase refCount as the constructor already set it to 1
// Return the new function
return fdt2;
}
void asCScriptEngine::CallObjectMethod(void *obj, int func) const {
asCScriptFunction *s = scriptFunctions[func];
asASSERT(s != 0);
CallObjectMethod(obj, s->sysFuncIntf, s);
}
void asCScriptEngine::CallObjectMethod(void *obj, asSSystemFunctionInterface *i, asCScriptFunction *s) const {
#if defined(__GNUC__) || defined(AS_PSVITA)
if (i->callConv == ICC_GENERIC_METHOD) {
asCGeneric gen(const_cast<asCScriptEngine *>(this), s, obj, 0);
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
}
#ifndef AS_NO_CLASS_METHODS
else if (i->callConv == ICC_THISCALL || i->callConv == ICC_VIRTUAL_THISCALL) {
// For virtual thiscalls we must call the method as a true class method
// so that the compiler will lookup the function address in the vftable
union {
asSIMPLEMETHOD_t mthd;
struct {
asFUNCTION_t func;
asPWORD baseOffset; // Same size as the pointer
} f;
} p;
obj = (void *)((char *)obj + i->compositeOffset);
if (i->isCompositeIndirect)
obj = *((void **)obj);
p.f.func = (asFUNCTION_t)(i->func);
p.f.baseOffset = asPWORD(i->baseOffset);
void (asCSimpleDummy::*f)() = p.mthd;
(((asCSimpleDummy *)obj)->*f)();
}
#endif
else { /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
void (*f)(void *) = (void (*)(void *))(i->func);
f(obj);
}
#else
#ifndef AS_NO_CLASS_METHODS
if (i->callConv == ICC_THISCALL) {
union {
asSIMPLEMETHOD_t mthd;
asFUNCTION_t func;
} p;
p.func = (asFUNCTION_t)(i->func);
void (asCSimpleDummy::*f)() = p.mthd;
obj = (void *)((char *) obj + i->compositeOffset);
if (i->isCompositeIndirect)
obj = *((void **)obj);
obj = (void *)(asPWORD(obj) + i->baseOffset);
(((asCSimpleDummy *)obj)->*f)();
} else
#endif
if (i->callConv == ICC_GENERIC_METHOD) {
asCGeneric gen(const_cast<asCScriptEngine *>(this), s, obj, 0);
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
} else { /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
void (*f)(void *) = (void (*)(void *))(i->func);
f(obj);
}
#endif
}
bool asCScriptEngine::CallObjectMethodRetBool(void *obj, int func) const {
asCScriptFunction *s = scriptFunctions[func];
asASSERT(s != 0);
asSSystemFunctionInterface *i = s->sysFuncIntf;
#if defined(__GNUC__) || defined(AS_PSVITA)
if (i->callConv == ICC_GENERIC_METHOD) {
asCGeneric gen(const_cast<asCScriptEngine *>(this), s, obj, 0);
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
return *(bool *)gen.GetReturnPointer();
}
#ifndef AS_NO_CLASS_METHODS
else if (i->callConv == ICC_THISCALL || i->callConv == ICC_VIRTUAL_THISCALL) {
// For virtual thiscalls we must call the method as a true class method so that the compiler will lookup the function address in the vftable
union {
asSIMPLEMETHOD_t mthd;
struct {
asFUNCTION_t func;
asPWORD baseOffset;
} f;
} p;
obj = (void *)((char *)obj + i->compositeOffset);
if (i->isCompositeIndirect)
obj = *((void **)obj);
p.f.func = (asFUNCTION_t)(i->func);
p.f.baseOffset = asPWORD(i->baseOffset);
bool (asCSimpleDummy::*f)() = (bool(asCSimpleDummy::*)())(p.mthd);
return (((asCSimpleDummy *)obj)->*f)();
}
#endif
else { /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
bool (*f)(void *) = (bool (*)(void *))(i->func);
return f(obj);
}
#else
#ifndef AS_NO_CLASS_METHODS
if (i->callConv == ICC_THISCALL) {
union {
asSIMPLEMETHOD_t mthd;
asFUNCTION_t func;
} p;
p.func = (asFUNCTION_t)(i->func);
bool (asCSimpleDummy::*f)() = (bool (asCSimpleDummy::*)())p.mthd;
obj = (void *)((char *) obj + i->compositeOffset);
if (i->isCompositeIndirect)
obj = *((void **)obj);
obj = (void *)(asPWORD(obj) + i->baseOffset);
return (((asCSimpleDummy *)obj)->*f)();
} else
#endif
if (i->callConv == ICC_GENERIC_METHOD) {
asCGeneric gen(const_cast<asCScriptEngine *>(this), s, obj, 0);
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
return *(bool *)gen.GetReturnPointer();
} else { /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
bool (*f)(void *) = (bool (*)(void *))(i->func);
return f(obj);
}
#endif
}
int asCScriptEngine::CallObjectMethodRetInt(void *obj, int func) const {
asCScriptFunction *s = scriptFunctions[func];
asASSERT(s != 0);
asSSystemFunctionInterface *i = s->sysFuncIntf;
#if defined(__GNUC__) || defined(AS_PSVITA)
if (i->callConv == ICC_GENERIC_METHOD) {
asCGeneric gen(const_cast<asCScriptEngine *>(this), s, obj, 0);
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
return *(int *)gen.GetReturnPointer();
}
#ifndef AS_NO_CLASS_METHODS
else if (i->callConv == ICC_THISCALL || i->callConv == ICC_VIRTUAL_THISCALL) {
// For virtual thiscalls we must call the method as a true class method so that the compiler will lookup the function address in the vftable
union {
asSIMPLEMETHOD_t mthd;
struct {
asFUNCTION_t func;
asPWORD baseOffset;
} f;
} p;
p.f.func = (asFUNCTION_t)(i->func);
p.f.baseOffset = asPWORD(i->baseOffset);
obj = (void *)((char *)obj + i->compositeOffset);
if (i->isCompositeIndirect)
obj = *((void **)obj);
int (asCSimpleDummy::*f)() = (int(asCSimpleDummy::*)())(p.mthd);
return (((asCSimpleDummy *)obj)->*f)();
}
#endif
else { /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
int (*f)(void *) = (int (*)(void *))(i->func);
return f(obj);
}
#else
#ifndef AS_NO_CLASS_METHODS
if (i->callConv == ICC_THISCALL) {
union {
asSIMPLEMETHOD_t mthd;
asFUNCTION_t func;
} p;
p.func = (asFUNCTION_t)(i->func);
int (asCSimpleDummy::*f)() = (int (asCSimpleDummy::*)())p.mthd;
obj = (void *)((char *) obj + i->compositeOffset);
if (i->isCompositeIndirect)
obj = *((void **)obj);
obj = (void *)(asPWORD(obj) + i->baseOffset);
return (((asCSimpleDummy *)obj)->*f)();
} else
#endif
if (i->callConv == ICC_GENERIC_METHOD) {
asCGeneric gen(const_cast<asCScriptEngine *>(this), s, obj, 0);
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
return *(int *)gen.GetReturnPointer();
} else { /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
int (*f)(void *) = (int (*)(void *))(i->func);
return f(obj);
}
#endif
}
void *asCScriptEngine::CallObjectMethodRetPtr(void *obj, int func) const {
asCScriptFunction *s = scriptFunctions[func];
asASSERT(s != 0);
asSSystemFunctionInterface *i = s->sysFuncIntf;
#if defined(__GNUC__) || defined(AS_PSVITA)
if (i->callConv == ICC_GENERIC_METHOD) {
asCGeneric gen(const_cast<asCScriptEngine *>(this), s, obj, 0);
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
return *(void **)gen.GetReturnPointer();
}
#ifndef AS_NO_CLASS_METHODS
else if (i->callConv == ICC_THISCALL || i->callConv == ICC_VIRTUAL_THISCALL) {
// For virtual thiscalls we must call the method as a true class method so that the compiler will lookup the function address in the vftable
union {
asSIMPLEMETHOD_t mthd;
struct {
asFUNCTION_t func;
asPWORD baseOffset;
} f;
} p;
p.f.func = (asFUNCTION_t)(i->func);
p.f.baseOffset = asPWORD(i->baseOffset);
obj = (void *)((char *)obj + i->compositeOffset);
if (i->isCompositeIndirect)
obj = *((void **)obj);
void *(asCSimpleDummy::*f)() = (void *(asCSimpleDummy::*)())(p.mthd);
return (((asCSimpleDummy *)obj)->*f)();
}
#endif
else { /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
void *(*f)(void *) = (void *(*)(void *))(i->func);
return f(obj);
}
#else
#ifndef AS_NO_CLASS_METHODS
if (i->callConv == ICC_THISCALL) {
union {
asSIMPLEMETHOD_t mthd;
asFUNCTION_t func;
} p;
p.func = (asFUNCTION_t)(i->func);
void *(asCSimpleDummy::*f)() = (void *(asCSimpleDummy::*)())p.mthd;
obj = (void *)((char *) obj + i->compositeOffset);
if (i->isCompositeIndirect)
obj = *((void **)obj);
obj = (void *)(asPWORD(obj) + i->baseOffset);
return (((asCSimpleDummy *)obj)->*f)();
} else
#endif
if (i->callConv == ICC_GENERIC_METHOD) {
asCGeneric gen(const_cast<asCScriptEngine *>(this), s, obj, 0);
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
return *(void **)gen.GetReturnPointer();
} else { /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
void *(*f)(void *) = (void *(*)(void *))(i->func);
return f(obj);
}
#endif
}
void *asCScriptEngine::CallObjectMethodRetPtr(void *obj, int param1, asCScriptFunction *func) const {
asASSERT(obj != 0);
asASSERT(func != 0);
asSSystemFunctionInterface *i = func->sysFuncIntf;
#ifndef AS_NO_CLASS_METHODS
if (i->callConv == ICC_THISCALL || i->callConv == ICC_VIRTUAL_THISCALL) {
#if defined(__GNUC__) || defined(AS_PSVITA)
// For virtual thiscalls we must call the method as a true class method so that the compiler will lookup the function address in the vftable
union {
asSIMPLEMETHOD_t mthd;
struct {
asFUNCTION_t func;
asPWORD baseOffset;
} f;
} p;
p.f.func = (asFUNCTION_t)(i->func);
p.f.baseOffset = asPWORD(i->baseOffset);
obj = (void *)((char *) obj + i->compositeOffset);
if (i->isCompositeIndirect)
obj = *((void **)obj);
void *(asCSimpleDummy::*f)(int) = (void *(asCSimpleDummy::*)(int))(p.mthd);
return (((asCSimpleDummy *)obj)->*f)(param1);
#else
union {
asSIMPLEMETHOD_t mthd;
asFUNCTION_t func;
} p;
p.func = (asFUNCTION_t)(i->func);
void *(asCSimpleDummy::*f)(int) = (void *(asCSimpleDummy::*)(int))p.mthd;
obj = (void *)((char *) obj + i->compositeOffset);
if (i->isCompositeIndirect)
obj = *((void **)obj);
obj = (void *)(asPWORD(obj) + i->baseOffset);
return (((asCSimpleDummy *)obj)->*f)(param1);
#endif
} else
#endif
if (i->callConv == ICC_GENERIC_METHOD) {
asCGeneric gen(const_cast<asCScriptEngine *>(this), func, obj, reinterpret_cast<asDWORD *>(¶m1));
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
return *(void **)gen.GetReturnPointer();
} else if (i->callConv == ICC_CDECL_OBJLAST) {
void *(*f)(int, void *) = (void *(*)(int, void *))(i->func);
return f(param1, obj);
} else { /*if( i->callConv == ICC_CDECL_OBJFIRST )*/
void *(*f)(void *, int) = (void *(*)(void *, int))(i->func);
return f(obj, param1);
}
}
void *asCScriptEngine::CallGlobalFunctionRetPtr(int func) const {
asCScriptFunction *s = scriptFunctions[func];
asASSERT(s != 0);
return CallGlobalFunctionRetPtr(s->sysFuncIntf, s);
}
void *asCScriptEngine::CallGlobalFunctionRetPtr(int func, void *param1) const {
asCScriptFunction *s = scriptFunctions[func];
asASSERT(s != 0);
return CallGlobalFunctionRetPtr(s->sysFuncIntf, s, param1);
}
void *asCScriptEngine::CallGlobalFunctionRetPtr(asSSystemFunctionInterface *i, asCScriptFunction *s) const {
if (i->callConv == ICC_CDECL) {
void *(*f)() = (void *(*)())(i->func);
return f();
} else if (i->callConv == ICC_STDCALL) {
typedef void *(STDCALL * func_t)();
func_t f = (func_t)(i->func);
return f();
} else {
asCGeneric gen(const_cast<asCScriptEngine *>(this), s, 0, 0);
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
return *(void **)gen.GetReturnPointer();
}
}
void *asCScriptEngine::CallGlobalFunctionRetPtr(asSSystemFunctionInterface *i, asCScriptFunction *s, void *param1) const {
if (i->callConv == ICC_CDECL) {
void *(*f)(void *) = (void *(*)(void *))(i->func);
return f(param1);
} else if (i->callConv == ICC_STDCALL) {
typedef void *(STDCALL * func_t)(void *);
func_t f = (func_t)(i->func);
return f(param1);
} else {
asCGeneric gen(const_cast<asCScriptEngine *>(this), s, 0, (asDWORD *)¶m1);
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
return *(void **)gen.GetReturnPointer();
}
}
void asCScriptEngine::CallObjectMethod(void *obj, void *param, int func) const {
asCScriptFunction *s = scriptFunctions[func];
asASSERT(s != 0);
CallObjectMethod(obj, param, s->sysFuncIntf, s);
}
void asCScriptEngine::CallObjectMethod(void *obj, void *param, asSSystemFunctionInterface *i, asCScriptFunction *s) const {
#if defined(__GNUC__) || defined(AS_PSVITA)
if (i->callConv == ICC_CDECL_OBJLAST) {
void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
f(param, obj);
} else if (i->callConv == ICC_GENERIC_METHOD) {
asCGeneric gen(const_cast<asCScriptEngine *>(this), s, obj, (asDWORD *)¶m);
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
}
#ifndef AS_NO_CLASS_METHODS
else if (i->callConv == ICC_VIRTUAL_THISCALL || i->callConv == ICC_THISCALL) {
// For virtual thiscalls we must call the method as a true class method
// so that the compiler will lookup the function address in the vftable
union {
asSIMPLEMETHOD_t mthd;
struct {
asFUNCTION_t func;
asPWORD baseOffset; // Same size as the pointer
} f;
} p;
p.f.func = (asFUNCTION_t)(i->func);
p.f.baseOffset = asPWORD(i->baseOffset);
obj = (void *)((char *)obj + i->compositeOffset);
if (i->isCompositeIndirect)
obj = *((void **)obj);
void (asCSimpleDummy::*f)(void *) = (void(asCSimpleDummy::*)(void *))(p.mthd);
(((asCSimpleDummy *)obj)->*f)(param);
}
#endif
else { /*if( i->callConv == ICC_CDECL_OBJFIRST */
void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
f(obj, param);
}
#else
#ifndef AS_NO_CLASS_METHODS
if (i->callConv == ICC_THISCALL) {
union {
asSIMPLEMETHOD_t mthd;
asFUNCTION_t func;
} p;
p.func = (asFUNCTION_t)(i->func);
void (asCSimpleDummy::*f)(void *) = (void (asCSimpleDummy::*)(void *))(p.mthd);
obj = (void *)((char *) obj + i->compositeOffset);
if (i->isCompositeIndirect)
obj = *((void **)obj);
obj = (void *)(asPWORD(obj) + i->baseOffset);
(((asCSimpleDummy *)obj)->*f)(param);
} else
#endif
if (i->callConv == ICC_CDECL_OBJLAST) {
void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
f(param, obj);
} else if (i->callConv == ICC_GENERIC_METHOD) {
asCGeneric gen(const_cast<asCScriptEngine *>(this), s, obj, (asDWORD *)¶m);
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
} else { /*if( i->callConv == ICC_CDECL_OBJFIRST )*/
void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
f(obj, param);
}
#endif
}
void asCScriptEngine::CallGlobalFunction(void *param1, void *param2, asSSystemFunctionInterface *i, asCScriptFunction *s) const {
if (i->callConv == ICC_CDECL) {
void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
f(param1, param2);
} else if (i->callConv == ICC_STDCALL) {
typedef void (STDCALL * func_t)(void *, void *);
func_t f = (func_t)(i->func);
f(param1, param2);
} else {
// We must guarantee the order of the arguments which is why we copy them to this
// array. Otherwise the compiler may put them anywhere it likes, or even keep them
// in the registers which causes problem.
void *params[2] = {param1, param2};
asCGeneric gen(const_cast<asCScriptEngine *>(this), s, 0, (asDWORD *)¶ms);
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
}
}
bool asCScriptEngine::CallGlobalFunctionRetBool(void *param1, void *param2, asSSystemFunctionInterface *i, asCScriptFunction *s) const {
if (i->callConv == ICC_CDECL) {
bool (*f)(void *, void *) = (bool (*)(void *, void *))(i->func);
return f(param1, param2);
} else if (i->callConv == ICC_STDCALL) {
typedef bool (STDCALL * func_t)(void *, void *);
func_t f = (func_t)(i->func);
return f(param1, param2);
} else {
// TODO: When simulating a 64bit environment by defining AS_64BIT_PTR on a 32bit platform this code
// fails, because the stack given to asCGeneric is not prepared with two 64bit arguments.
// We must guarantee the order of the arguments which is why we copy them to this
// array. Otherwise the compiler may put them anywhere it likes, or even keep them
// in the registers which causes problem.
void *params[2] = {param1, param2};
asCGeneric gen(const_cast<asCScriptEngine *>(this), s, 0, (asDWORD *)params);
void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
f(&gen);
return *(bool *)gen.GetReturnPointer();
}
}
void *asCScriptEngine::CallAlloc(const asCObjectType *type) const {
// Allocate 4 bytes as the smallest size. Otherwise CallSystemFunction may try to
// copy a DWORD onto a smaller memory block, in case the object type is return in registers.
// Pad to the next even 4 bytes to avoid asBC_CPY writing outside of allocated buffer for registered POD types
asUINT size = type->size;
if (size & 0x3)
size += 4 - (size & 0x3);
#ifndef WIP_16BYTE_ALIGN
#if defined(AS_DEBUG)
return ((asALLOCFUNCDEBUG_t)userAlloc)(size, __FILE__, __LINE__);
#else
return userAlloc(size);
#endif
#else
#if defined(AS_DEBUG)
return ((asALLOCALIGNEDFUNCDEBUG_t)userAllocAligned)(size, type->alignment, __FILE__, __LINE__);
#else
return userAllocAligned(size, type->alignment);
#endif
#endif
}
void asCScriptEngine::CallFree(void *obj) const {
#ifndef WIP_16BYTE_ALIGN
userFree(obj);
#else
userFreeAligned(obj);
#endif
}
// interface
int asCScriptEngine::NotifyGarbageCollectorOfNewObject(void *obj, asITypeInfo *type) {
return gc.AddScriptObjectToGC(obj, static_cast<asCObjectType *>(type));
}
// interface
int asCScriptEngine::GetObjectInGC(asUINT idx, asUINT *seqNbr, void **obj, asITypeInfo **type) {
return gc.GetObjectInGC(idx, seqNbr, obj, type);
}
// interface
int asCScriptEngine::GarbageCollect(asDWORD flags, asUINT iterations) {
int r = gc.GarbageCollect(flags, iterations);
if (r == 0) {
// Delete any modules that have been discarded previously but not
// removed due to being referred to by objects in the garbage collector
DeleteDiscardedModules();
}
return r;
}
// interface
void asCScriptEngine::GetGCStatistics(asUINT *currentSize, asUINT *totalDestroyed, asUINT *totalDetected, asUINT *newObjects, asUINT *totalNewDestroyed) const {
gc.GetStatistics(currentSize, totalDestroyed, totalDetected, newObjects, totalNewDestroyed);
}
// interface
void asCScriptEngine::GCEnumCallback(void *reference) {
gc.GCEnumCallback(reference);
}
// interface
void asCScriptEngine::ForwardGCEnumReferences(void *ref, asITypeInfo *type) {
asCTypeInfo *t = reinterpret_cast<asCTypeInfo *>(type);
if ((t->flags & asOBJ_VALUE) && (t->flags & asOBJ_GC)) {
CallObjectMethod(ref, this, CastToObjectType(t)->beh.gcEnumReferences);
}
}
// interface
void asCScriptEngine::ForwardGCReleaseReferences(void *ref, asITypeInfo *type) {
asCTypeInfo *t = reinterpret_cast<asCTypeInfo *>(type);
if ((t->flags & asOBJ_VALUE) && (t->flags & asOBJ_GC)) {
CallObjectMethod(ref, this, CastToObjectType(t)->beh.gcReleaseAllReferences);
}
}
// interface
void asCScriptEngine::SetCircularRefDetectedCallback(asCIRCULARREFFUNC_t callback, void *param) {
gc.circularRefDetectCallbackFunc = callback;
gc.circularRefDetectCallbackParam = param;
}
int asCScriptEngine::GetTypeIdFromDataType(const asCDataType &dtIn) const {
if (dtIn.IsNullHandle()) return asTYPEID_VOID;
if (dtIn.GetTypeInfo() == 0) {
// Primitives have pre-fixed typeIds
switch (dtIn.GetTokenType()) {
case ttVoid:
return asTYPEID_VOID;
case ttBool:
return asTYPEID_BOOL;
case ttInt8:
return asTYPEID_INT8;
case ttInt16:
return asTYPEID_INT16;
case ttInt:
return asTYPEID_INT32;
case ttInt64:
return asTYPEID_INT64;
case ttUInt8:
return asTYPEID_UINT8;
case ttUInt16:
return asTYPEID_UINT16;
case ttUInt:
return asTYPEID_UINT32;
case ttUInt64:
return asTYPEID_UINT64;
case ttFloat:
return asTYPEID_FLOAT;
case ttDouble:
return asTYPEID_DOUBLE;
default:
// All types should be covered by the above. The variable type is not really a type
asASSERT(dtIn.GetTokenType() == ttQuestion);
return -1;
}
}
int typeId = -1;
asCTypeInfo *ot = dtIn.GetTypeInfo();
asASSERT(ot != &functionBehaviours);
// Object's hold the typeId themselves
typeId = ot->typeId;
if (typeId == -1) {
ACQUIREEXCLUSIVE(engineRWLock);
// Make sure another thread didn't determine the typeId while we were waiting for the lock
if (ot->typeId == -1) {
typeId = typeIdSeqNbr++;
if (ot->flags & asOBJ_SCRIPT_OBJECT) typeId |= asTYPEID_SCRIPTOBJECT;
else if (ot->flags & asOBJ_TEMPLATE) typeId |= asTYPEID_TEMPLATE;
else if (ot->flags & asOBJ_ENUM) {} // TODO: Should we have a specific bit for this?
else typeId |= asTYPEID_APPOBJECT;
ot->typeId = typeId;
mapTypeIdToTypeInfo.Insert(typeId, ot);
}
RELEASEEXCLUSIVE(engineRWLock);
}
// Add flags according to the requested type
if (dtIn.GetTypeInfo() && !(dtIn.GetTypeInfo()->flags & asOBJ_ASHANDLE)) {
// The ASHANDLE types behave like handles, but are really
// value types so the typeId is never returned as a handle
if (dtIn.IsObjectHandle())
typeId |= asTYPEID_OBJHANDLE;
if (dtIn.IsHandleToConst())
typeId |= asTYPEID_HANDLETOCONST;
}
return typeId;
}
asCDataType asCScriptEngine::GetDataTypeFromTypeId(int typeId) const {
int baseId = typeId & (asTYPEID_MASK_OBJECT | asTYPEID_MASK_SEQNBR);
if (typeId <= asTYPEID_DOUBLE) {
eTokenType type[] = {ttVoid, ttBool, ttInt8, ttInt16, ttInt, ttInt64, ttUInt8, ttUInt16, ttUInt, ttUInt64, ttFloat, ttDouble};
return asCDataType::CreatePrimitive(type[typeId], false);
}
// First check if the typeId is an object type
asCTypeInfo *ot = 0;
ACQUIRESHARED(engineRWLock);
asSMapNode<int, asCTypeInfo *> *cursor = 0;
if (mapTypeIdToTypeInfo.MoveTo(&cursor, baseId))
ot = mapTypeIdToTypeInfo.GetValue(cursor);
RELEASESHARED(engineRWLock);
if (ot) {
asCDataType dt = asCDataType::CreateType(ot, false);
if (typeId & asTYPEID_OBJHANDLE)
dt.MakeHandle(true, true);
if (typeId & asTYPEID_HANDLETOCONST)
dt.MakeHandleToConst(true);
return dt;
}
return asCDataType();
}
asCObjectType *asCScriptEngine::GetObjectTypeFromTypeId(int typeId) const {
asCDataType dt = GetDataTypeFromTypeId(typeId);
return CastToObjectType(dt.GetTypeInfo());
}
void asCScriptEngine::RemoveFromTypeIdMap(asCTypeInfo *type) {
ACQUIREEXCLUSIVE(engineRWLock);
asSMapNode<int, asCTypeInfo *> *cursor = 0;
mapTypeIdToTypeInfo.MoveFirst(&cursor);
while (cursor) {
if (mapTypeIdToTypeInfo.GetValue(cursor) == type) {
mapTypeIdToTypeInfo.Erase(cursor);
break;
}
mapTypeIdToTypeInfo.MoveNext(&cursor, cursor);
}
RELEASEEXCLUSIVE(engineRWLock);
}
// interface
asITypeInfo *asCScriptEngine::GetTypeInfoByDecl(const char *decl) const {
asCDataType dt;
// This cast is ok, because we are not changing anything in the engine
asCBuilder bld(const_cast<asCScriptEngine *>(this), 0);
// Don't write parser errors to the message callback
bld.silent = true;
int r = bld.ParseDataType(decl, &dt, defaultNamespace);
if (r < 0)
return 0;
return dt.GetTypeInfo();
}
// interface
int asCScriptEngine::GetTypeIdByDecl(const char *decl) const {
asCDataType dt;
// This cast is ok, because we are not changing anything in the engine
asCBuilder bld(const_cast<asCScriptEngine *>(this), 0);
// Don't write parser errors to the message callback
bld.silent = true;
int r = bld.ParseDataType(decl, &dt, defaultNamespace);
if (r < 0)
return asINVALID_TYPE;
return GetTypeIdFromDataType(dt);
}
// interface
const char *asCScriptEngine::GetTypeDeclaration(int typeId, bool includeNamespace) const {
asCDataType dt = GetDataTypeFromTypeId(typeId);
asCString *tempString = &asCThreadManager::GetLocalData()->string;
*tempString = dt.Format(defaultNamespace, includeNamespace);
return tempString->AddressOf();
}
// interface
int asCScriptEngine::GetSizeOfPrimitiveType(int typeId) const {
asCDataType dt = GetDataTypeFromTypeId(typeId);
if (!dt.IsPrimitive()) return 0;
return dt.GetSizeInMemoryBytes();
}
// interface
int asCScriptEngine::RefCastObject(void *obj, asITypeInfo *fromType, asITypeInfo *toType, void **newPtr, bool useOnlyImplicitCast) {
if (newPtr == 0) return asINVALID_ARG;
*newPtr = 0;
if (fromType == 0 || toType == 0) return asINVALID_ARG;
// A null-pointer can always be cast to another type, so it will always be successful
if (obj == 0)
return asSUCCESS;
if (fromType == toType) {
*newPtr = obj;
AddRefScriptObject(*newPtr, toType);
return asSUCCESS;
}
// Check for funcdefs
if ((fromType->GetFlags() & asOBJ_FUNCDEF) && (toType->GetFlags() & asOBJ_FUNCDEF)) {
asCFuncdefType *fromFunc = CastToFuncdefType(reinterpret_cast<asCTypeInfo *>(fromType));
asCFuncdefType *toFunc = CastToFuncdefType(reinterpret_cast<asCTypeInfo *>(toType));
if (fromFunc && toFunc && fromFunc->funcdef->IsSignatureExceptNameEqual(toFunc->funcdef)) {
*newPtr = obj;
AddRefScriptObject(*newPtr, toType);
return asSUCCESS;
}
return asSUCCESS;
}
// Look for ref cast behaviours
asCScriptFunction *universalCastFunc = 0;
asCObjectType *from = CastToObjectType(reinterpret_cast< asCTypeInfo *>(fromType));
if (from == 0) return asINVALID_ARG;
for (asUINT n = 0; n < from->methods.GetLength(); n++) {
asCScriptFunction *func = scriptFunctions[from->methods[n]];
if (func->name == "opImplCast" ||
(!useOnlyImplicitCast && func->name == "opCast")) {
if (func->returnType.GetTypeInfo() == toType) {
*newPtr = CallObjectMethodRetPtr(obj, func->id);
// The ref cast behaviour returns a handle with incremented
// ref counter, so there is no need to call AddRef explicitly
// unless the function is registered with autohandle
if (func->sysFuncIntf->returnAutoHandle)
AddRefScriptObject(*newPtr, toType);
return asSUCCESS;
} else if (func->returnType.GetTokenType() == ttVoid &&
func->parameterTypes.GetLength() == 1 &&
func->parameterTypes[0].GetTokenType() == ttQuestion) {
universalCastFunc = func;
}
}
}
// One last chance if the object has a void opCast(?&out) behaviour
if (universalCastFunc) {
// TODO: Add proper error handling
asIScriptContext *ctx = RequestContext();
ctx->Prepare(universalCastFunc);
ctx->SetObject(obj);
ctx->SetArgVarType(0, newPtr, toType->GetTypeId() | asTYPEID_OBJHANDLE);
ctx->Execute();
ReturnContext(ctx);
// The opCast(?&out) method already incremented the
// refCount so there is no need to do it manually
return asSUCCESS;
}
// For script classes and interfaces there is a quick route
if ((fromType->GetFlags() & asOBJ_SCRIPT_OBJECT) && (toType->GetFlags() & asOBJ_SCRIPT_OBJECT)) {
if (fromType == toType) {
*newPtr = obj;
reinterpret_cast<asCScriptObject *>(*newPtr)->AddRef();
return asSUCCESS;
}
// Up casts to base class or interface can be done implicitly
if (fromType->DerivesFrom(toType) ||
fromType->Implements(toType)) {
*newPtr = obj;
reinterpret_cast<asCScriptObject *>(*newPtr)->AddRef();
return asSUCCESS;
}
// Down casts to derived class or from interface can only be done explicitly
if (!useOnlyImplicitCast) {
// Get the true type of the object so the explicit cast can evaluate all possibilities
asITypeInfo *trueType = reinterpret_cast<asCScriptObject *>(obj)->GetObjectType();
if (trueType->DerivesFrom(toType) ||
trueType->Implements(toType)) {
*newPtr = obj;
reinterpret_cast<asCScriptObject *>(*newPtr)->AddRef();
return asSUCCESS;
}
}
}
// The cast is not available, but it is still a success
return asSUCCESS;
}
// interface
void *asCScriptEngine::CreateScriptObject(const asITypeInfo *type) {
if (type == 0) return 0;
asCObjectType *objType = CastToObjectType(const_cast<asCTypeInfo *>(reinterpret_cast<const asCTypeInfo *>(type)));
if (objType == 0) return 0;
void *ptr = 0;
// Check that there is a default factory for ref types
if (objType->beh.factory == 0 && (objType->flags & asOBJ_REF)) {
// TODO: How to report the reason the object couldn't be created, without writing to the message callback? optional argument with return code?
// TODO: Warn about the invalid call to message callback. Make it an optional, so the warning can be turned off
// asCString str;
// str.Format(TXT_FAILED_IN_FUNC_s_s_d, "CreateScriptObject", errorNames[-asNO_FUNCTION], asNO_FUNCTION);
// WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
return 0;
}
// Construct the object
if (objType->flags & asOBJ_SCRIPT_OBJECT) {
// Call the script class' default factory with a context
ptr = ScriptObjectFactory(objType, this);
} else if ((objType->flags & asOBJ_TEMPLATE) && (objType->flags & asOBJ_REF)) {
// The registered factory that takes the object type is moved
// to the construct behaviour when the type is instantiated
#ifdef AS_NO_EXCEPTIONS
ptr = CallGlobalFunctionRetPtr(objType->beh.construct, objType);
#else
try {
ptr = CallGlobalFunctionRetPtr(objType->beh.construct, objType);
} catch (...) {
asCContext *ctx = reinterpret_cast<asCContext *>(asGetActiveContext());
if (ctx)
ctx->HandleAppException();
}
#endif
} else if (objType->flags & asOBJ_REF) {
// Call the default factory directly
#ifdef AS_NO_EXCEPTIONS
ptr = CallGlobalFunctionRetPtr(objType->beh.factory);
#else
try {
ptr = CallGlobalFunctionRetPtr(objType->beh.factory);
} catch (...) {
asCContext *ctx = reinterpret_cast<asCContext *>(asGetActiveContext());
if (ctx)
ctx->HandleAppException();
}
#endif
} else {
// Make sure there is a default constructor or that it is a POD type
if (objType->beh.construct == 0 && !(objType->flags & asOBJ_POD)) {
// TODO: How to report the reason the object couldn't be created, without writing to the message callback? optional argument with return code?
// TODO: Warn about the invalid call to message callback. Make it an optional, so the warning can be turned off
// asCString str;
// str.Format(TXT_FAILED_IN_FUNC_s_s_d, "CreateScriptObject", errorNames[-asNO_FUNCTION], asNO_FUNCTION);
// WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
return 0;
}
// Manually allocate the memory, then call the default constructor
ptr = CallAlloc(objType);
int funcIndex = objType->beh.construct;
if (funcIndex) {
if (objType->flags & asOBJ_TEMPLATE) {
// Templates of value types create script functions as the constructors
CallScriptObjectMethod(ptr, funcIndex);
} else {
#ifdef AS_NO_EXCEPTIONS
CallObjectMethod(ptr, funcIndex);
#else
try {
CallObjectMethod(ptr, funcIndex);
} catch (...) {
asCContext *ctx = reinterpret_cast<asCContext *>(asGetActiveContext());
if (ctx)
ctx->HandleAppException();
// Free the memory
CallFree(ptr);
ptr = 0;
}
#endif
}
}
}
return ptr;
}
// internal
int asCScriptEngine::CallScriptObjectMethod(void *obj, int funcId) {
asIScriptContext *ctx = 0;
int r = 0;
bool isNested = false;
// Use nested call in the context if there is an active context
ctx = asGetActiveContext();
if (ctx) {
// It may not always be possible to reuse the current context,
// in which case we'll have to create a new one any way.
if (ctx->GetEngine() == this && ctx->PushState() == asSUCCESS)
isNested = true;
else
ctx = 0;
}
if (ctx == 0) {
// Request a context from the engine
ctx = RequestContext();
if (ctx == 0) {
// TODO: How to best report this failure?
return asERROR;
}
}
r = ctx->Prepare(scriptFunctions[funcId]);
if (r < 0) {
if (isNested)
ctx->PopState();
else
ReturnContext(ctx);
// TODO: How to best report this failure?
return asERROR;
}
// Set the object
ctx->SetObject(obj);
for (;;) {
r = ctx->Execute();
// We can't allow this execution to be suspended
// so resume the execution immediately
if (r != asEXECUTION_SUSPENDED)
break;
}
if (r != asEXECUTION_FINISHED) {
if (isNested) {
ctx->PopState();
// If the execution was aborted or an exception occurred,
// then we should forward that to the outer execution.
if (r == asEXECUTION_EXCEPTION) {
// TODO: How to improve this exception
ctx->SetException(TXT_EXCEPTION_IN_NESTED_CALL);
} else if (r == asEXECUTION_ABORTED)
ctx->Abort();
} else
ReturnContext(ctx);
// TODO: How to best report the error?
return asERROR;
}
if (isNested)
ctx->PopState();
else
ReturnContext(ctx);
return asSUCCESS;
}
// interface
void *asCScriptEngine::CreateUninitializedScriptObject(const asITypeInfo *type) {
// This function only works for script classes. Registered types cannot be created this way.
if (type == 0 || !(type->GetFlags() & asOBJ_SCRIPT_OBJECT))
return 0;
asCObjectType *objType = CastToObjectType(const_cast<asCTypeInfo *>(reinterpret_cast<const asCTypeInfo *>(type)));
if (objType == 0)
return 0;
// Construct the object, but do not call the actual constructor that initializes the members
// The initialization will be done by the application afterwards, e.g. through serialization.
asCScriptObject *obj = reinterpret_cast<asCScriptObject *>(CallAlloc(objType));
// Pre-initialize the memory so there are no invalid pointers
ScriptObject_ConstructUnitialized(objType, obj);
return obj;
}
// interface
void *asCScriptEngine::CreateScriptObjectCopy(void *origObj, const asITypeInfo *type) {
if (origObj == 0 || type == 0) return 0;
const asCObjectType *ot = CastToObjectType(const_cast<asCTypeInfo *>(reinterpret_cast<const asCTypeInfo *>(type)));
if (ot == 0) return 0;
void *newObj = 0;
if ((ot->flags & asOBJ_SCRIPT_OBJECT) && ot->beh.copyfactory) {
// Call the script class' default factory with a context
newObj = ScriptObjectCopyFactory(ot, origObj, this);
} else if (ot->beh.copyfactory) {
// Call the copy factory which will allocate the memory then copy the original object
#ifdef AS_NO_EXCEPTIONS
newObj = CallGlobalFunctionRetPtr(ot->beh.copyfactory, origObj);
#else
try {
newObj = CallGlobalFunctionRetPtr(ot->beh.copyfactory, origObj);
} catch (...) {
asCContext *ctx = reinterpret_cast<asCContext *>(asGetActiveContext());
if (ctx)
ctx->HandleAppException();
}
#endif
} else if (ot->beh.copyconstruct) {
// Manually allocate the memory, then call the copy constructor
newObj = CallAlloc(ot);
#ifdef AS_NO_EXCEPTIONS
CallObjectMethod(newObj, origObj, ot->beh.copyconstruct);
#else
try {
CallObjectMethod(newObj, origObj, ot->beh.copyconstruct);
} catch (...) {
asCContext *ctx = reinterpret_cast<asCContext *>(asGetActiveContext());
if (ctx)
ctx->HandleAppException();
// Free the memory
CallFree(newObj);
newObj = 0;
}
#endif
} else {
// Allocate the object and then do a value assign
newObj = CreateScriptObject(type);
if (newObj == 0) return 0;
AssignScriptObject(newObj, origObj, type);
}
return newObj;
}
// internal
void asCScriptEngine::ConstructScriptObjectCopy(void *mem, void *obj, asCObjectType *type) {
if (type == 0 || mem == 0 || obj == 0) return;
// This function is only meant to be used for value types
asASSERT(type->flags & asOBJ_VALUE);
// Call the copy constructor if available, else call the default constructor followed by the opAssign
int funcIndex = type->beh.copyconstruct;
if (funcIndex) {
CallObjectMethod(mem, obj, funcIndex);
} else {
funcIndex = type->beh.construct;
if (funcIndex)
CallObjectMethod(mem, funcIndex);
AssignScriptObject(mem, obj, type);
}
}
// interface
int asCScriptEngine::AssignScriptObject(void *dstObj, void *srcObj, const asITypeInfo *type) {
// TODO: Warn about invalid call in message stream (make it optional)
if (type == 0 || dstObj == 0 || srcObj == 0) return asINVALID_ARG;
const asCObjectType *objType = CastToObjectType(const_cast<asCTypeInfo *>(reinterpret_cast<const asCTypeInfo *>(type)));
if (objType == 0) return asINVALID_ARG;
// If value assign for ref types has been disabled, then don't do anything if the type is a ref type
if (ep.disallowValueAssignForRefType && (objType->flags & asOBJ_REF) && !(objType->flags & asOBJ_SCOPED)) {
asIScriptContext *ctx = asGetActiveContext();
if (ctx)
ctx->SetException("Cannot do value assignment");
return asNOT_SUPPORTED;
}
// Must not copy if the opAssign is not available and the object is not a POD object
if (objType->beh.copy) {
asCScriptFunction *func = scriptFunctions[objType->beh.copy];
if (func->funcType == asFUNC_SYSTEM)
CallObjectMethod(dstObj, srcObj, objType->beh.copy);
else {
// Call the script class' opAssign method
asASSERT(objType->flags & asOBJ_SCRIPT_OBJECT);
reinterpret_cast<asCScriptObject *>(dstObj)->CopyFrom(reinterpret_cast<asCScriptObject *>(srcObj));
}
} else if (objType->size && (objType->flags & asOBJ_POD)) {
memcpy(dstObj, srcObj, objType->size);
}
return asSUCCESS;
}
// interface
void asCScriptEngine::AddRefScriptObject(void *obj, const asITypeInfo *type) {
// Make sure it is not a null pointer
if (obj == 0 || type == 0) return;
const asCTypeInfo *ti = reinterpret_cast<const asCTypeInfo *>(type);
if (ti->flags & asOBJ_FUNCDEF) {
CallObjectMethod(obj, functionBehaviours.beh.addref);
} else {
asCObjectType *objType = CastToObjectType(const_cast<asCTypeInfo *>(ti));
if (objType && objType->beh.addref) {
// Call the addref behaviour
CallObjectMethod(obj, objType->beh.addref);
}
}
}
// interface
void asCScriptEngine::ReleaseScriptObject(void *obj, const asITypeInfo *type) {
// Make sure it is not a null pointer
if (obj == 0 || type == 0) return;
const asCTypeInfo *ti = reinterpret_cast<const asCTypeInfo *>(type);
if (ti->flags & asOBJ_FUNCDEF) {
CallObjectMethod(obj, functionBehaviours.beh.release);
} else {
asCObjectType *objType = CastToObjectType(const_cast<asCTypeInfo *>(ti));
if (objType && objType->flags & asOBJ_REF) {
asASSERT((objType->flags & asOBJ_NOCOUNT) || objType->beh.release);
if (objType->beh.release) {
// Call the release behaviour
CallObjectMethod(obj, objType->beh.release);
}
} else if (objType) {
// Call the destructor
if (objType->beh.destruct)
CallObjectMethod(obj, objType->beh.destruct);
else if (objType->flags & asOBJ_LIST_PATTERN)
DestroyList((asBYTE *)obj, objType);
// We'll have to trust that the memory for the object was allocated with CallAlloc.
// This is true if the object was created in the context, or with CreateScriptObject.
// Then free the memory
CallFree(obj);
}
}
}
// interface
int asCScriptEngine::BeginConfigGroup(const char *groupName) {
// Make sure the group name doesn't already exist
for (asUINT n = 0; n < configGroups.GetLength(); n++) {
if (configGroups[n]->groupName == groupName)
return asNAME_TAKEN;
}
if (currentGroup != &defaultGroup)
return asNOT_SUPPORTED;
asCConfigGroup *group = asNEW(asCConfigGroup)();
if (group == 0)
return asOUT_OF_MEMORY;
group->groupName = groupName;
configGroups.PushLast(group);
currentGroup = group;
return 0;
}
// interface
int asCScriptEngine::EndConfigGroup() {
// Raise error if trying to end the default config
if (currentGroup == &defaultGroup)
return asERROR;
currentGroup = &defaultGroup;
return 0;
}
// interface
int asCScriptEngine::RemoveConfigGroup(const char *groupName) {
// It is not allowed to remove a group that is still in use.
// It would be possible to change the code in such a way that
// the group could be removed even though it was still in use,
// but that would cause severe negative impact on runtime
// performance, since the VM would then have to be able handle
// situations where the types, functions, and global variables
// can be removed at any time.
for (asUINT n = 0; n < configGroups.GetLength(); n++) {
if (configGroups[n]->groupName == groupName) {
asCConfigGroup *group = configGroups[n];
// Remove any unused generated template instances
// before verifying if the config group is still in use.
// RemoveTemplateInstanceType() checks if the instance is in use
for (asUINT g = generatedTemplateTypes.GetLength(); g-- > 0;)
RemoveTemplateInstanceType(generatedTemplateTypes[g]);
// Make sure the group isn't referenced by anyone
if (group->refCount > 0)
return asCONFIG_GROUP_IS_IN_USE;
// Verify if any objects registered in this group is still alive
if (group->HasLiveObjects())
return asCONFIG_GROUP_IS_IN_USE;
// Remove the group from the list
if (n == configGroups.GetLength() - 1)
configGroups.PopLast();
else
configGroups[n] = configGroups.PopLast();
// Remove the configurations registered with this group
group->RemoveConfiguration(this);
asDELETE(group, asCConfigGroup);
}
}
return 0;
}
asCConfigGroup *asCScriptEngine::FindConfigGroupForFunction(int funcId) const {
for (asUINT n = 0; n < configGroups.GetLength(); n++) {
// Check global functions
asUINT m;
for (m = 0; m < configGroups[n]->scriptFunctions.GetLength(); m++) {
if (configGroups[n]->scriptFunctions[m]->id == funcId)
return configGroups[n];
}
}
return 0;
}
asCConfigGroup *asCScriptEngine::FindConfigGroupForGlobalVar(int gvarId) const {
for (asUINT n = 0; n < configGroups.GetLength(); n++) {
for (asUINT m = 0; m < configGroups[n]->globalProps.GetLength(); m++) {
if (int(configGroups[n]->globalProps[m]->id) == gvarId)
return configGroups[n];
}
}
return 0;
}
asCConfigGroup *asCScriptEngine::FindConfigGroupForTypeInfo(const asCTypeInfo *objType) const {
for (asUINT n = 0; n < configGroups.GetLength(); n++) {
for (asUINT m = 0; m < configGroups[n]->types.GetLength(); m++) {
if (configGroups[n]->types[m] == objType)
return configGroups[n];
}
}
return 0;
}
asCConfigGroup *asCScriptEngine::FindConfigGroupForFuncDef(const asCFuncdefType *funcDef) const {
for (asUINT n = 0; n < configGroups.GetLength(); n++) {
asCFuncdefType *f = const_cast<asCFuncdefType *>(funcDef);
if (configGroups[n]->types.Exists(f))
return configGroups[n];
}
return 0;
}
// interface
asDWORD asCScriptEngine::SetDefaultAccessMask(asDWORD defaultMask) {
asDWORD old = defaultAccessMask;
defaultAccessMask = defaultMask;
return old;
}
int asCScriptEngine::GetNextScriptFunctionId() {
// This function only returns the next function id that
// should be used. It doesn't update the internal arrays.
if (freeScriptFunctionIds.GetLength())
return freeScriptFunctionIds[freeScriptFunctionIds.GetLength() - 1];
return (int)scriptFunctions.GetLength();
}
void asCScriptEngine::AddScriptFunction(asCScriptFunction *func) {
// Update the internal arrays with the function id that is now used
if (freeScriptFunctionIds.GetLength() && freeScriptFunctionIds[freeScriptFunctionIds.GetLength() - 1] == func->id)
freeScriptFunctionIds.PopLast();
if (asUINT(func->id) == scriptFunctions.GetLength())
scriptFunctions.PushLast(func);
else {
// The slot should be empty or already set with the function, which happens if an existing shared function is reused
asASSERT(scriptFunctions[func->id] == 0 || scriptFunctions[func->id] == func);
scriptFunctions[func->id] = func;
}
}
void asCScriptEngine::RemoveScriptFunction(asCScriptFunction *func) {
if (func == 0 || func->id < 0) return;
int id = func->id & ~FUNC_IMPORTED;
if (func->funcType == asFUNC_IMPORTED) {
if (id >= (int)importedFunctions.GetLength()) return;
if (importedFunctions[id]) {
// Remove the function from the list of script functions
if (id == (int)importedFunctions.GetLength() - 1) {
importedFunctions.PopLast();
} else {
importedFunctions[id] = 0;
freeImportedFunctionIdxs.PushLast(id);
}
}
} else {
if (id >= (int)scriptFunctions.GetLength()) return;
asASSERT(func == scriptFunctions[id]);
if (scriptFunctions[id]) {
// Remove the function from the list of script functions
if (id == (int)scriptFunctions.GetLength() - 1) {
scriptFunctions.PopLast();
} else {
scriptFunctions[id] = 0;
freeScriptFunctionIds.PushLast(id);
}
// Is the function used as signature id?
if (func->signatureId == id) {
// Remove the signature id
signatureIds.RemoveValue(func);
// Update all functions using the signature id
int newSigId = 0;
for (asUINT n = 0; n < scriptFunctions.GetLength(); n++) {
if (scriptFunctions[n] && scriptFunctions[n]->signatureId == id) {
if (newSigId == 0) {
newSigId = scriptFunctions[n]->id;
signatureIds.PushLast(scriptFunctions[n]);
}
scriptFunctions[n]->signatureId = newSigId;
}
}
}
}
}
}
// internal
void asCScriptEngine::RemoveFuncdef(asCFuncdefType *funcdef) {
funcDefs.RemoveValue(funcdef);
}
// interface
int asCScriptEngine::RegisterFuncdef(const char *decl) {
if (decl == 0) return ConfigError(asINVALID_ARG, "RegisterFuncdef", decl, 0);
// Parse the function declaration
asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_FUNCDEF);
if (func == 0)
return ConfigError(asOUT_OF_MEMORY, "RegisterFuncdef", decl, 0);
asCBuilder bld(this, 0);
asCObjectType *parentClass = 0;
int r = bld.ParseFunctionDeclaration(0, decl, func, false, 0, 0, defaultNamespace, 0, &parentClass);
if (r < 0) {
// Set as dummy function before deleting
func->funcType = asFUNC_DUMMY;
asDELETE(func, asCScriptFunction);
return ConfigError(asINVALID_DECLARATION, "RegisterFuncdef", decl, 0);
}
// Check name conflicts
r = bld.CheckNameConflict(func->name.AddressOf(), 0, 0, defaultNamespace, true, false);
if (r < 0) {
asDELETE(func, asCScriptFunction);
return ConfigError(asNAME_TAKEN, "RegisterFuncdef", decl, 0);
}
func->id = GetNextScriptFunctionId();
AddScriptFunction(func);
asCFuncdefType *fdt = asNEW(asCFuncdefType)(this, func);
funcDefs.PushLast(fdt); // doesn't increase refcount
registeredFuncDefs.PushLast(fdt); // doesn't increase refcount
allRegisteredTypes.Insert(asSNameSpaceNamePair(fdt->nameSpace, fdt->name), fdt); // constructor already set the ref count to 1
currentGroup->types.PushLast(fdt);
if (parentClass) {
parentClass->childFuncDefs.PushLast(fdt);
fdt->parentClass = parentClass;
// Check if the method restricts that use of the template to value types or reference types
if (parentClass->flags & asOBJ_TEMPLATE) {
r = SetTemplateRestrictions(parentClass, func, "RegisterFuncdef", decl);
if (r < 0)
return r;
}
}
// If parameter type from other groups are used, add references
currentGroup->AddReferencesForFunc(this, func);
// Return the type id as success
return GetTypeIdFromDataType(asCDataType::CreateType(fdt, false));
}
// interface
asUINT asCScriptEngine::GetFuncdefCount() const {
return asUINT(registeredFuncDefs.GetLength());
}
// interface
asITypeInfo *asCScriptEngine::GetFuncdefByIndex(asUINT index) const {
if (index >= registeredFuncDefs.GetLength())
return 0;
return registeredFuncDefs[index];
}
// internal
asCFuncdefType *asCScriptEngine::FindMatchingFuncdef(asCScriptFunction *func, asCModule *module) {
asCFuncdefType *funcDef = func->funcdefType;
if (funcDef == 0) {
// Check if there is any matching funcdefs already in the engine that can be reused
for (asUINT n = 0; n < funcDefs.GetLength(); n++) {
if (funcDefs[n]->funcdef->IsSignatureExceptNameEqual(func)) {
if (func->IsShared() && !funcDefs[n]->funcdef->IsShared())
continue;
funcDef = funcDefs[n];
break;
}
}
}
if (funcDef == 0) {
// Create a matching funcdef
asCScriptFunction *fd = asNEW(asCScriptFunction)(this, 0, asFUNC_FUNCDEF);
fd->name = func->name;
fd->nameSpace = func->nameSpace;
fd->SetShared(func->IsShared());
fd->returnType = func->returnType;
fd->parameterTypes = func->parameterTypes;
fd->inOutFlags = func->inOutFlags;
funcDef = asNEW(asCFuncdefType)(this, fd);
funcDefs.PushLast(funcDef); // doesn't increase the refCount
fd->id = GetNextScriptFunctionId();
AddScriptFunction(fd);
if (module) {
// Add the new funcdef to the module so it will
// be available when saving the bytecode
funcDef->module = module;
module->AddFuncDef(funcDef); // the refCount was already accounted for in the constructor
}
// Observe, if the funcdef is created without informing a module a reference will be stored in the
// engine's funcDefs array, but it will not be owned by any module. This means that it will live on
// until the engine is released.
}
if (funcDef && module && funcDef->module && funcDef->module != module) {
// Unless this is a registered funcDef the returned funcDef must
// be stored as part of the module for saving/loading bytecode
if (!module->m_funcDefs.Exists(funcDef)) {
module->AddFuncDef(funcDef);
funcDef->AddRefInternal();
} else {
asASSERT(funcDef->IsShared());
}
}
return funcDef;
}
// interface
// TODO: typedef: Accept complex types for the typedefs
int asCScriptEngine::RegisterTypedef(const char *type, const char *decl) {
if (type == 0) return ConfigError(asINVALID_NAME, "RegisterTypedef", type, decl);
// Verify if the name has been registered as a type already
// TODO: Must check against registered funcdefs too
if (GetRegisteredType(type, defaultNamespace))
// Let the application recover from this error, for example if the same typedef is registered twice
return asALREADY_REGISTERED;
// Grab the data type
size_t tokenLen;
eTokenType token;
asCDataType dataType;
// Create the data type
token = tok.GetToken(decl, strlen(decl), &tokenLen);
switch (token) {
case ttBool:
case ttInt:
case ttInt8:
case ttInt16:
case ttInt64:
case ttUInt:
case ttUInt8:
case ttUInt16:
case ttUInt64:
case ttFloat:
case ttDouble:
if (strlen(decl) != tokenLen) {
return ConfigError(asINVALID_TYPE, "RegisterTypedef", type, decl);
}
break;
default:
return ConfigError(asINVALID_TYPE, "RegisterTypedef", type, decl);
}
dataType = asCDataType::CreatePrimitive(token, false);
// Make sure the name is not a reserved keyword
token = tok.GetToken(type, strlen(type), &tokenLen);
if (token != ttIdentifier || strlen(type) != tokenLen)
return ConfigError(asINVALID_NAME, "RegisterTypedef", type, decl);
asCBuilder bld(this, 0);
int r = bld.CheckNameConflict(type, 0, 0, defaultNamespace, true, false);
if (r < 0)
return ConfigError(asNAME_TAKEN, "RegisterTypedef", type, decl);
// Don't have to check against members of object
// types as they are allowed to use the names
// Put the data type in the list
asCTypedefType *td = asNEW(asCTypedefType)(this);
if (td == 0)
return ConfigError(asOUT_OF_MEMORY, "RegisterTypedef", type, decl);
td->flags = asOBJ_TYPEDEF;
td->size = dataType.GetSizeInMemoryBytes();
td->name = type;
td->nameSpace = defaultNamespace;
td->aliasForType = dataType;
allRegisteredTypes.Insert(asSNameSpaceNamePair(td->nameSpace, td->name), td);
registeredTypeDefs.PushLast(td);
currentGroup->types.PushLast(td);
return GetTypeIdByDecl(type);
}
// interface
asUINT asCScriptEngine::GetTypedefCount() const {
return asUINT(registeredTypeDefs.GetLength());
}
// interface
asITypeInfo *asCScriptEngine::GetTypedefByIndex(asUINT index) const {
if (index >= registeredTypeDefs.GetLength())
return 0;
return registeredTypeDefs[index];
}
// interface
int asCScriptEngine::RegisterEnum(const char *name) {
// Check the name
if (NULL == name)
return ConfigError(asINVALID_NAME, "RegisterEnum", name, 0);
// Verify if the name has been registered as a type already
if (GetRegisteredType(name, defaultNamespace))
return asALREADY_REGISTERED;
// Use builder to parse the datatype
asCDataType dt;
asCBuilder bld(this, 0);
bool oldMsgCallback = msgCallback;
msgCallback = false;
int r = bld.ParseDataType(name, &dt, defaultNamespace);
msgCallback = oldMsgCallback;
if (r >= 0) {
// If it is not in the defaultNamespace then the type was successfully parsed because
// it is declared in a parent namespace which shouldn't be treated as an error
if (dt.GetTypeInfo() && dt.GetTypeInfo()->nameSpace == defaultNamespace)
return ConfigError(asERROR, "RegisterEnum", name, 0);
}
// Make sure the name is not a reserved keyword
size_t tokenLen;
int token = tok.GetToken(name, strlen(name), &tokenLen);
if (token != ttIdentifier || strlen(name) != tokenLen)
return ConfigError(asINVALID_NAME, "RegisterEnum", name, 0);
r = bld.CheckNameConflict(name, 0, 0, defaultNamespace, true, false);
if (r < 0)
return ConfigError(asNAME_TAKEN, "RegisterEnum", name, 0);
asCEnumType *st = asNEW(asCEnumType)(this);
if (st == 0)
return ConfigError(asOUT_OF_MEMORY, "RegisterEnum", name, 0);
asCDataType dataType;
dataType.CreatePrimitive(ttInt, false);
st->flags = asOBJ_ENUM | asOBJ_SHARED;
st->size = 4;
st->name = name;
st->nameSpace = defaultNamespace;
allRegisteredTypes.Insert(asSNameSpaceNamePair(st->nameSpace, st->name), st);
registeredEnums.PushLast(st);
currentGroup->types.PushLast(st);
return GetTypeIdByDecl(name);
}
// interface
int asCScriptEngine::RegisterEnumValue(const char *typeName, const char *valueName, int value) {
// Verify that the correct config group is used
if (currentGroup->FindType(typeName) == 0)
return ConfigError(asWRONG_CONFIG_GROUP, "RegisterEnumValue", typeName, valueName);
asCDataType dt;
int r;
asCBuilder bld(this, 0);
r = bld.ParseDataType(typeName, &dt, defaultNamespace);
if (r < 0)
return ConfigError(r, "RegisterEnumValue", typeName, valueName);
// Store the enum value
asCEnumType *ot = CastToEnumType(dt.GetTypeInfo());
if (ot == 0)
return ConfigError(asINVALID_TYPE, "RegisterEnumValue", typeName, valueName);
if (NULL == valueName)
return ConfigError(asINVALID_NAME, "RegisterEnumValue", typeName, valueName);
asUINT tokenLen = 0;
asETokenClass tokenClass = ParseToken(valueName, 0, &tokenLen);
if (tokenClass != asTC_IDENTIFIER || tokenLen != strlen(valueName))
return ConfigError(asINVALID_NAME, "RegisterEnumValue", typeName, valueName);
for (unsigned int n = 0; n < ot->enumValues.GetLength(); n++) {
if (ot->enumValues[n]->name == valueName)
return ConfigError(asALREADY_REGISTERED, "RegisterEnumValue", typeName, valueName);
}
asSEnumValue *e = asNEW(asSEnumValue);
if (e == 0)
return ConfigError(asOUT_OF_MEMORY, "RegisterEnumValue", typeName, valueName);
e->name = valueName;
e->value = value;
ot->enumValues.PushLast(e);
return asSUCCESS;
}
// interface
asUINT asCScriptEngine::GetEnumCount() const {
return registeredEnums.GetLength();
}
// interface
asITypeInfo *asCScriptEngine::GetEnumByIndex(asUINT index) const {
if (index >= registeredEnums.GetLength())
return 0;
return registeredEnums[index];
}
// interface
asUINT asCScriptEngine::GetObjectTypeCount() const {
return asUINT(registeredObjTypes.GetLength());
}
// interface
asITypeInfo *asCScriptEngine::GetObjectTypeByIndex(asUINT index) const {
if (index >= registeredObjTypes.GetLength())
return 0;
return registeredObjTypes[index];
}
// interface
asITypeInfo *asCScriptEngine::GetTypeInfoByName(const char *in_name) const {
asCString name;
asSNameSpace *ns = 0;
if (DetermineNameAndNamespace(in_name, defaultNamespace, name, ns) < 0)
return 0;
while (ns) {
// Check the object types
for (asUINT n = 0; n < registeredObjTypes.GetLength(); n++) {
if (registeredObjTypes[n]->name == name &&
registeredObjTypes[n]->nameSpace == ns)
return registeredObjTypes[n];
}
// Perhaps it is a template type? In this case
// the returned type will be the generic type
for (asUINT n = 0; n < registeredTemplateTypes.GetLength(); n++) {
if (registeredTemplateTypes[n]->name == name &&
registeredTemplateTypes[n]->nameSpace == ns)
return registeredTemplateTypes[n];
}
// Check the enum types
for (asUINT n = 0; n < registeredEnums.GetLength(); n++) {
if (registeredEnums[n]->name == name &&
registeredEnums[n]->nameSpace == ns)
return registeredEnums[n];
}
// Check the typedefs
for (asUINT n = 0; n < registeredTypeDefs.GetLength(); n++) {
if (registeredTypeDefs[n]->name == name &&
registeredTypeDefs[n]->nameSpace == ns)
return registeredTypeDefs[n];
}
// Recursively search parent namespace
ns = GetParentNameSpace(ns);
}
return 0;
}
// internal
int asCScriptEngine::DetermineNameAndNamespace(const char *in_name, asSNameSpace *implicitNs, asCString &out_name, asSNameSpace *&out_ns) const {
if (in_name == 0)
return asINVALID_ARG;
asCString name = in_name;
asCString scope;
asSNameSpace *ns = implicitNs;
// Check if the given name contains a scope
int pos = name.FindLast("::");
if (pos >= 0) {
scope = name.SubString(0, pos);
name = name.SubString(pos + 2);
if (pos == 0) {
// The scope is '::' so the search must start in the global namespace
ns = nameSpaces[0];
} else if (scope.SubString(0, 2) == "::") {
// The scope starts with '::' so the given scope is fully qualified
ns = FindNameSpace(scope.SubString(2).AddressOf());
} else {
// The scope doesn't start with '::' so it is relative to the current namespace
if (implicitNs->name == "")
ns = FindNameSpace(scope.AddressOf());
else
ns = FindNameSpace((implicitNs->name + "::" + scope).AddressOf());
}
}
out_name = name;
out_ns = ns;
return 0;
}
// interface
asITypeInfo *asCScriptEngine::GetTypeInfoById(int typeId) const {
asCDataType dt = GetDataTypeFromTypeId(typeId);
// Is the type id valid?
if (!dt.IsValid()) return 0;
return dt.GetTypeInfo();
}
// interface
asIScriptFunction *asCScriptEngine::GetFunctionById(int funcId) const {
return GetScriptFunction(funcId);
}
// internal
bool asCScriptEngine::IsTemplateType(const char *name) const {
// Only look in the list of template types (not instance types)
for (unsigned int n = 0; n < registeredTemplateTypes.GetLength(); n++) {
asCObjectType *type = registeredTemplateTypes[n];
if (type && type->name == name)
return true;
}
return false;
}
// internal
int asCScriptEngine::GetScriptSectionNameIndex(const char *name) {
ACQUIREEXCLUSIVE(engineRWLock);
// TODO: These names are only released when the engine is freed. The assumption is that
// the same script section names will be reused instead of there always being new
// names. Is this assumption valid? Do we need to add reference counting?
// Store the script section names for future reference
for (asUINT n = 0; n < scriptSectionNames.GetLength(); n++) {
if (scriptSectionNames[n]->Compare(name) == 0) {
RELEASEEXCLUSIVE(engineRWLock);
return n;
}
}
asCString *str = asNEW(asCString)(name);
if (str)
scriptSectionNames.PushLast(str);
int r = int(scriptSectionNames.GetLength() - 1);
RELEASEEXCLUSIVE(engineRWLock);
return r;
}
// interface
void asCScriptEngine::SetEngineUserDataCleanupCallback(asCLEANENGINEFUNC_t callback, asPWORD type) {
ACQUIREEXCLUSIVE(engineRWLock);
for (asUINT n = 0; n < cleanEngineFuncs.GetLength(); n++) {
if (cleanEngineFuncs[n].type == type) {
cleanEngineFuncs[n].cleanFunc = callback;
RELEASEEXCLUSIVE(engineRWLock);
return;
}
}
SEngineClean otc = {type, callback};
cleanEngineFuncs.PushLast(otc);
RELEASEEXCLUSIVE(engineRWLock);
}
// interface
void asCScriptEngine::SetModuleUserDataCleanupCallback(asCLEANMODULEFUNC_t callback, asPWORD type) {
ACQUIREEXCLUSIVE(engineRWLock);
for (asUINT n = 0; n < cleanModuleFuncs.GetLength(); n++) {
if (cleanModuleFuncs[n].type == type) {
cleanModuleFuncs[n].cleanFunc = callback;
RELEASEEXCLUSIVE(engineRWLock);
return;
}
}
SModuleClean otc = {type, callback};
cleanModuleFuncs.PushLast(otc);
RELEASEEXCLUSIVE(engineRWLock);
}
// interface
void asCScriptEngine::SetContextUserDataCleanupCallback(asCLEANCONTEXTFUNC_t callback, asPWORD type) {
ACQUIREEXCLUSIVE(engineRWLock);
for (asUINT n = 0; n < cleanContextFuncs.GetLength(); n++) {
if (cleanContextFuncs[n].type == type) {
cleanContextFuncs[n].cleanFunc = callback;
RELEASEEXCLUSIVE(engineRWLock);
return;
}
}
SContextClean otc = {type, callback};
cleanContextFuncs.PushLast(otc);
RELEASEEXCLUSIVE(engineRWLock);
}
// interface
void asCScriptEngine::SetFunctionUserDataCleanupCallback(asCLEANFUNCTIONFUNC_t callback, asPWORD type) {
ACQUIREEXCLUSIVE(engineRWLock);
for (asUINT n = 0; n < cleanFunctionFuncs.GetLength(); n++) {
if (cleanFunctionFuncs[n].type == type) {
cleanFunctionFuncs[n].cleanFunc = callback;
RELEASEEXCLUSIVE(engineRWLock);
return;
}
}
SFunctionClean otc = {type, callback};
cleanFunctionFuncs.PushLast(otc);
RELEASEEXCLUSIVE(engineRWLock);
}
// interface
void asCScriptEngine::SetTypeInfoUserDataCleanupCallback(asCLEANTYPEINFOFUNC_t callback, asPWORD type) {
ACQUIREEXCLUSIVE(engineRWLock);
for (asUINT n = 0; n < cleanTypeInfoFuncs.GetLength(); n++) {
if (cleanTypeInfoFuncs[n].type == type) {
cleanTypeInfoFuncs[n].cleanFunc = callback;
RELEASEEXCLUSIVE(engineRWLock);
return;
}
}
STypeInfoClean otc = {type, callback};
cleanTypeInfoFuncs.PushLast(otc);
RELEASEEXCLUSIVE(engineRWLock);
}
// interface
void asCScriptEngine::SetScriptObjectUserDataCleanupCallback(asCLEANSCRIPTOBJECTFUNC_t callback, asPWORD type) {
ACQUIREEXCLUSIVE(engineRWLock);
for (asUINT n = 0; n < cleanScriptObjectFuncs.GetLength(); n++) {
if (cleanScriptObjectFuncs[n].type == type) {
cleanScriptObjectFuncs[n].cleanFunc = callback;
RELEASEEXCLUSIVE(engineRWLock);
return;
}
}
SScriptObjClean soc = {type, callback};
cleanScriptObjectFuncs.PushLast(soc);
RELEASEEXCLUSIVE(engineRWLock);
}
// interface
int asCScriptEngine::SetTranslateAppExceptionCallback(asSFuncPtr callback, void *param, int callConv) {
#ifdef AS_NO_EXCEPTIONS
return asNOT_SUPPORTED;
#else
if (callback.ptr.f.func == 0) {
// Clear the callback
translateExceptionCallback = false;
return asSUCCESS;
}
// Detect the new callback
translateExceptionCallback = true;
translateExceptionCallbackObj = param;
bool isObj = false;
if ((unsigned)callConv == asCALL_GENERIC || (unsigned)callConv == asCALL_THISCALL_OBJFIRST || (unsigned)callConv == asCALL_THISCALL_OBJLAST)
return asNOT_SUPPORTED;
if ((unsigned)callConv >= asCALL_THISCALL) {
isObj = true;
if (param == 0) {
translateExceptionCallback = false;
return asINVALID_ARG;
}
}
int r = DetectCallingConvention(isObj, callback, callConv, 0, &translateExceptionCallbackFunc);
if (r < 0)
translateExceptionCallback = false;
return r;
#endif
}
// internal
asCObjectType *asCScriptEngine::GetListPatternType(int listPatternFuncId) {
// Get the object type either from the constructor's object for value types
// or from the factory's return type for reference types
asCObjectType *ot = scriptFunctions[listPatternFuncId]->objectType;
if (ot == 0)
ot = CastToObjectType(scriptFunctions[listPatternFuncId]->returnType.GetTypeInfo());
asASSERT(ot);
// Check if this object type already has a list pattern type
for (asUINT n = 0; n < listPatternTypes.GetLength(); n++) {
if (listPatternTypes[n]->templateSubTypes[0].GetTypeInfo() == ot)
return listPatternTypes[n];
}
// Create a new list pattern type for the given object type
asCObjectType *lpt = asNEW(asCObjectType)(this);
lpt->templateSubTypes.PushLast(asCDataType::CreateType(ot, false));
lpt->flags = asOBJ_LIST_PATTERN;
listPatternTypes.PushLast(lpt);
return lpt;
}
// internal
void asCScriptEngine::DestroyList(asBYTE *buffer, const asCObjectType *listPatternType) {
asASSERT(listPatternType && (listPatternType->flags & asOBJ_LIST_PATTERN));
// Get the list pattern from the listFactory function
// TODO: runtime optimize: Store the used list factory in the listPatternType itself
// TODO: runtime optimize: Keep a flag to indicate if there is really a need to free anything
asCObjectType *ot = CastToObjectType(listPatternType->templateSubTypes[0].GetTypeInfo());
asCScriptFunction *listFactory = scriptFunctions[ot->beh.listFactory];
asASSERT(listFactory);
asSListPatternNode *node = listFactory->listPattern;
DestroySubList(buffer, node);
asASSERT(node->type == asLPT_END);
}
// internal
void asCScriptEngine::DestroySubList(asBYTE *&buffer, asSListPatternNode *&node) {
asASSERT(node->type == asLPT_START);
int count = 0;
node = node->next;
while (node) {
if (node->type == asLPT_REPEAT || node->type == asLPT_REPEAT_SAME) {
// Align the offset to 4 bytes boundary
if ((asPWORD(buffer) & 0x3))
buffer += 4 - (asPWORD(buffer) & 0x3);
// Determine how many times the pattern repeat
count = *(asUINT *)buffer;
buffer += 4;
if (count == 0) {
// Skip the sub pattern that was expected to be repeated, otherwise
// we'll try to delete things that don't exist in the buffer
node = node->next;
if (node->type == asLPT_START) {
int subCount = 1;
do {
node = node->next;
if (node->type == asLPT_START)
subCount++;
else if (node->type == asLPT_END)
subCount--;
} while (subCount > 0);
return;
}
}
} else if (node->type == asLPT_TYPE) {
// If we're not in a repeat iteration, then only 1 value should be destroyed
if (count <= 0)
count = 1;
asCDataType dt = reinterpret_cast<asSListPatternDataTypeNode *>(node)->dataType;
bool isVarType = dt.GetTokenType() == ttQuestion;
while (count--) {
if (isVarType) {
// Align the offset to 4 bytes boundary
if ((asPWORD(buffer) & 0x3))
buffer += 4 - (asPWORD(buffer) & 0x3);
int typeId = *(int *)buffer;
buffer += 4;
dt = GetDataTypeFromTypeId(typeId);
}
asCTypeInfo *ti = dt.GetTypeInfo();
if (ti && (ti->flags & asOBJ_ENUM) == 0) {
// Free all instances of this type
if (ti->flags & asOBJ_VALUE) {
asUINT size = ti->GetSize();
// Align the offset to 4 bytes boundary
if (size >= 4 && (asPWORD(buffer) & 0x3))
buffer += 4 - (asPWORD(buffer) & 0x3);
asCObjectType *ot = CastToObjectType(ti);
if (ot && ot->beh.destruct) {
// Only call the destructor if the object has been created
// We'll assume the object has been created if any byte in
// the memory is different from 0.
// TODO: This is not really correct, as bytes may have been
// modified by the constructor, but then an exception
// thrown aborting the initialization. The engine
// really should be keeping track of which objects has
// been successfully initialized.
for (asUINT n = 0; n < size; n++) {
if (buffer[n] != 0) {
void *ptr = (void *)buffer;
CallObjectMethod(ptr, ot->beh.destruct);
break;
}
}
}
// Advance the pointer in the buffer
buffer += size;
} else {
// Align the offset to 4 bytes boundary
if (asPWORD(buffer) & 0x3)
buffer += 4 - (asPWORD(buffer) & 0x3);
// Call the release behaviour
void *ptr = *(void **)buffer;
if (ptr)
ReleaseScriptObject(ptr, ti);
buffer += AS_PTR_SIZE * 4;
}
} else {
asUINT size = dt.GetSizeInMemoryBytes();
// Align the offset to 4 bytes boundary
if (size >= 4 && (asPWORD(buffer) & 0x3))
buffer += 4 - (asPWORD(buffer) & 0x3);
// Advance the buffer
buffer += size;
}
}
} else if (node->type == asLPT_START) {
// If we're not in a repeat iteration, then only 1 value should be destroyed
if (count <= 0)
count = 1;
while (count--) {
asSListPatternNode *subList = node;
DestroySubList(buffer, subList);
asASSERT(subList->type == asLPT_END);
if (count == 0)
node = subList;
}
} else if (node->type == asLPT_END) {
return;
} else {
asASSERT(false);
}
node = node->next;
}
}
// internal
asSNameSpace *asCScriptEngine::GetParentNameSpace(asSNameSpace *ns) const {
if (ns == 0) return 0;
if (ns == nameSpaces[0]) return 0;
asCString scope = ns->name;
int pos = scope.FindLast("::");
if (pos >= 0) {
scope = scope.SubString(0, pos);
return FindNameSpace(scope.AddressOf());
}
return nameSpaces[0];
}
END_AS_NAMESPACE
|