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
|
/*
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_builder.cpp
//
// This is the class that manages the compilation of the scripts
//
#include "as_config.h"
#include "as_builder.h"
#include "as_parser.h"
#include "as_compiler.h"
#include "as_tokendef.h"
#include "as_string_util.h"
#include "as_outputbuffer.h"
#include "as_texts.h"
#include "as_scriptobject.h"
#include "as_debug.h"
BEGIN_AS_NAMESPACE
#ifndef AS_NO_COMPILER
// asCSymbolTable template specializations for sGlobalVariableDescription entries
template<>
void asCSymbolTable<sGlobalVariableDescription>::GetKey(const sGlobalVariableDescription *entry, asSNameSpaceNamePair &key) const {
asSNameSpace *ns = entry->ns;
asCString name = entry->name;
key = asSNameSpaceNamePair(ns, name);
}
// Comparator for exact variable search
class asCCompGlobVarType : public asIFilter {
public:
const asCDataType &m_type;
asCCompGlobVarType(const asCDataType &type) : m_type(type) {}
bool operator()(const void *p) const {
const sGlobalVariableDescription *desc = reinterpret_cast<const sGlobalVariableDescription *>(p);
return desc->datatype == m_type;
}
private:
// The assignment operator is required for MSVC9, otherwise it will complain that it is not possible to auto generate the operator
asCCompGlobVarType &operator=(const asCCompGlobVarType &) {
return *this;
}
};
#endif
asCBuilder::asCBuilder(asCScriptEngine *_engine, asCModule *_module) {
this->engine = _engine;
this->module = _module;
silent = false;
}
asCBuilder::~asCBuilder() {
#ifndef AS_NO_COMPILER
asUINT n;
// Free all functions
for (n = 0; n < functions.GetLength(); n++) {
if (functions[n]) {
if (functions[n]->node)
functions[n]->node->Destroy(engine);
asDELETE(functions[n], sFunctionDescription);
}
functions[n] = 0;
}
// Free all global variables
CleanupEnumValues();
asCSymbolTable<sGlobalVariableDescription>::iterator it = globVariables.List();
while (it) {
if ((*it)->declaredAtNode)
(*it)->declaredAtNode->Destroy(engine);
if ((*it)->initializationNode)
(*it)->initializationNode->Destroy(engine);
asDELETE((*it), sGlobalVariableDescription);
it++;
}
globVariables.Clear();
// Free all the loaded files
for (n = 0; n < scripts.GetLength(); n++) {
if (scripts[n])
asDELETE(scripts[n], asCScriptCode);
scripts[n] = 0;
}
// Free all class declarations
for (n = 0; n < classDeclarations.GetLength(); n++) {
if (classDeclarations[n]) {
if (classDeclarations[n]->node)
classDeclarations[n]->node->Destroy(engine);
asDELETE(classDeclarations[n], sClassDeclaration);
classDeclarations[n] = 0;
}
}
for (n = 0; n < interfaceDeclarations.GetLength(); n++) {
if (interfaceDeclarations[n]) {
if (interfaceDeclarations[n]->node)
interfaceDeclarations[n]->node->Destroy(engine);
asDELETE(interfaceDeclarations[n], sClassDeclaration);
interfaceDeclarations[n] = 0;
}
}
for (n = 0; n < namedTypeDeclarations.GetLength(); n++) {
if (namedTypeDeclarations[n]) {
if (namedTypeDeclarations[n]->node)
namedTypeDeclarations[n]->node->Destroy(engine);
asDELETE(namedTypeDeclarations[n], sClassDeclaration);
namedTypeDeclarations[n] = 0;
}
}
for (n = 0; n < funcDefs.GetLength(); n++) {
if (funcDefs[n]) {
if (funcDefs[n]->node)
funcDefs[n]->node->Destroy(engine);
asDELETE(funcDefs[n], sFuncDef);
funcDefs[n] = 0;
}
}
for (n = 0; n < mixinClasses.GetLength(); n++) {
if (mixinClasses[n]) {
if (mixinClasses[n]->node)
mixinClasses[n]->node->Destroy(engine);
asDELETE(mixinClasses[n], sMixinClass);
mixinClasses[n] = 0;
}
}
#endif // AS_NO_COMPILER
}
void asCBuilder::Reset() {
numErrors = 0;
numWarnings = 0;
engine->preMessage.isSet = false;
#ifndef AS_NO_COMPILER
// Clear the cache of known types
hasCachedKnownTypes = false;
knownTypes.EraseAll();
#endif
}
#ifndef AS_NO_COMPILER
int asCBuilder::AddCode(const char *name, const char *code, int codeLength, int lineOffset, int sectionIdx, bool makeCopy) {
asCScriptCode *script = asNEW(asCScriptCode);
if (script == 0)
return asOUT_OF_MEMORY;
int r = script->SetCode(name, code, codeLength, makeCopy);
if (r < 0) {
asDELETE(script, asCScriptCode);
return r;
}
script->lineOffset = lineOffset;
script->idx = sectionIdx;
scripts.PushLast(script);
return 0;
}
asCScriptCode *asCBuilder::FindOrAddCode(const char *name, const char *code, size_t length) {
for (asUINT n = 0; n < scripts.GetLength(); n++)
if (scripts[n]->name == name && scripts[n]->codeLength == length && memcmp(scripts[n]->code, code, length) == 0)
return scripts[n];
asCScriptCode *script = asNEW(asCScriptCode);
if (script == 0)
return 0;
int r = script->SetCode(name, code, length, true);
if (r < 0) {
asDELETE(script, asCScriptCode);
return 0;
}
script->idx = engine->GetScriptSectionNameIndex(name);
scripts.PushLast(script);
return script;
}
void asCBuilder::EvaluateTemplateInstances(asUINT startIdx, bool keepSilent) {
// Backup the original message stream
bool msgCallback = engine->msgCallback;
asSSystemFunctionInterface msgCallbackFunc = engine->msgCallbackFunc;
void *msgCallbackObj = engine->msgCallbackObj;
// Set the new temporary message stream
asCOutputBuffer outBuffer;
if (keepSilent)
engine->SetMessageCallback(asFUNCTION(asCOutputBuffer::CDeclCallback), &outBuffer, asCALL_CDECL_OBJLAST);
// Evaluate each of the template instances that have been created since the start of the build
// TODO: This is not exactly correct, since another thread may have created template instances in parallel
for (asUINT n = startIdx; n < engine->templateInstanceTypes.GetLength(); n++) {
bool dontGarbageCollect = false;
asCObjectType *tmpl = engine->templateInstanceTypes[n];
asCScriptFunction *callback = engine->scriptFunctions[tmpl->beh.templateCallback];
if (callback && !engine->CallGlobalFunctionRetBool(tmpl, &dontGarbageCollect, callback->sysFuncIntf, callback)) {
asCString sub = tmpl->templateSubTypes[0].Format(engine->nameSpaces[0]);
for (asUINT m = 1; m < tmpl->templateSubTypes.GetLength(); m++) {
sub += ",";
sub += tmpl->templateSubTypes[m].Format(engine->nameSpaces[0]);
}
asCString str;
str.Format(TXT_INSTANCING_INVLD_TMPL_TYPE_s_s, tmpl->name.AddressOf(), sub.AddressOf());
WriteError(tmpl->scriptSectionIdx >= 0 ? engine->scriptSectionNames[tmpl->scriptSectionIdx]->AddressOf() : "", str, tmpl->declaredAt & 0xFFFFF, (tmpl->declaredAt >> 20) & 0xFFF);
} else {
// If the callback said this template instance won't be garbage collected then remove the flag
if (dontGarbageCollect)
tmpl->flags &= ~asOBJ_GC;
}
}
// Restore message callback
if (keepSilent) {
engine->msgCallback = msgCallback;
engine->msgCallbackFunc = msgCallbackFunc;
engine->msgCallbackObj = msgCallbackObj;
}
}
int asCBuilder::Build() {
Reset();
// The template callbacks must only be called after the subtypes have a known structure,
// otherwise the callback may think it is not possible to create the template instance,
// even though it is.
// TODO: This flag shouldn't be set globally in the engine, as it would mean that another
// thread requesting a template instance in parallel to the compilation wouldn't
// evaluate the template instance.
engine->deferValidationOfTemplateTypes = true;
asUINT numTempl = (asUINT)engine->templateInstanceTypes.GetLength();
ParseScripts();
if (numErrors > 0)
return asERROR;
// Compile the types first
CompileInterfaces();
CompileClasses(numTempl);
// Evaluate the template instances one last time, this time with error messages, as we know
// all classes have been fully built and it is known which ones will need garbage collection.
EvaluateTemplateInstances(numTempl, false);
engine->deferValidationOfTemplateTypes = false;
if (numErrors > 0)
return asERROR;
// Then the global variables. Here the variables declared with auto
// will be resolved, so they can be accessed properly in the functions
CompileGlobalVariables();
// Finally the global functions and class methods
CompileFunctions();
// TODO: Attempt to reorder the initialization of global variables so that
// they do not access other uninitialized global variables out-of-order
// The builder needs to check for each of the global variable, what functions
// that are accessed, and what global variables are access by these functions.
if (numWarnings > 0 && engine->ep.compilerWarnings == 2)
WriteError(TXT_WARNINGS_TREATED_AS_ERROR, 0, 0);
if (numErrors > 0)
return asERROR;
// Make sure something was compiled, otherwise return an error
if (module->IsEmpty()) {
WriteError(TXT_NOTHING_WAS_BUILT, 0, 0);
return asERROR;
}
return asSUCCESS;
}
int asCBuilder::CompileGlobalVar(const char *sectionName, const char *code, int lineOffset) {
Reset();
// Add the string to the script code
asCScriptCode *script = asNEW(asCScriptCode);
if (script == 0)
return asOUT_OF_MEMORY;
script->SetCode(sectionName, code, true);
script->lineOffset = lineOffset;
script->idx = engine->GetScriptSectionNameIndex(sectionName ? sectionName : "");
scripts.PushLast(script);
// Parse the string
asCParser parser(this);
if (parser.ParseScript(scripts[0]) < 0)
return asERROR;
asCScriptNode *node = parser.GetScriptNode();
// Make sure there is nothing else than the global variable in the script code
if (node == 0 ||
node->firstChild == 0 ||
node->firstChild != node->lastChild ||
node->firstChild->nodeType != snDeclaration) {
WriteError(TXT_ONLY_ONE_VARIABLE_ALLOWED, script, 0);
return asERROR;
}
node = node->firstChild;
node->DisconnectParent();
RegisterGlobalVar(node, script, module->m_defaultNamespace);
CompileGlobalVariables();
// It is possible that the global variable initialization included anonymous functions that must be compiled too
for (asUINT n = 0; n < functions.GetLength(); n++) {
asCCompiler compiler(engine);
asCScriptFunction *func = engine->scriptFunctions[functions[n]->funcId];
int r = compiler.CompileFunction(this, functions[n]->script, func->parameterNames, functions[n]->node, func, 0);
if (r < 0)
break;
}
if (numWarnings > 0 && engine->ep.compilerWarnings == 2)
WriteError(TXT_WARNINGS_TREATED_AS_ERROR, 0, 0);
// None of the functions should be added to the module if any error occurred,
// or it was requested that the functions wouldn't be added to the scope
if (numErrors > 0) {
for (asUINT n = 0; n < functions.GetLength(); n++) {
asCScriptFunction *func = engine->scriptFunctions[functions[n]->funcId];
if (module->m_globalFunctions.GetIndex(func) >= 0) {
module->m_globalFunctions.Erase(module->m_globalFunctions.GetIndex(func));
module->m_scriptFunctions.RemoveValue(func);
func->ReleaseInternal();
}
}
}
if (numErrors > 0) {
// Remove the variable from the module, if it was registered
if (globVariables.GetSize() > 0)
module->RemoveGlobalVar(module->GetGlobalVarCount() - 1);
return asERROR;
}
return 0;
}
#endif
int asCBuilder::ValidateDefaultArgs(asCScriptCode *script, asCScriptNode *node, asCScriptFunction *func) {
int firstArgWithDefaultValue = -1;
for (asUINT n = 0; n < func->defaultArgs.GetLength(); n++) {
if (func->defaultArgs[n])
firstArgWithDefaultValue = n;
else if (firstArgWithDefaultValue >= 0) {
asCString str;
str.Format(TXT_DEF_ARG_MISSING_IN_FUNC_s, func->GetDeclaration());
WriteError(str, script, node);
return asINVALID_DECLARATION;
}
}
return 0;
}
#ifndef AS_NO_COMPILER
// This function will verify if the newly created function will conflict another overload due to having
// identical function arguments that are not default args, e.g: foo(int) and foo(int, int=0)
int asCBuilder::CheckForConflictsDueToDefaultArgs(asCScriptCode *script, asCScriptNode *node, asCScriptFunction *func, asCObjectType *objType) {
// TODO: Implement for global functions too
if (func->objectType == 0 || objType == 0) return 0;
asCArray<int> funcs;
GetObjectMethodDescriptions(func->name.AddressOf(), objType, funcs, false);
for (asUINT n = 0; n < funcs.GetLength(); n++) {
asCScriptFunction *func2 = engine->scriptFunctions[funcs[n]];
if (func == func2)
continue;
if (func->IsReadOnly() != func2->IsReadOnly())
continue;
bool match = true;
asUINT p = 0;
for (; p < func->parameterTypes.GetLength() && p < func2->parameterTypes.GetLength(); p++) {
// Only verify until the first argument with default args
if ((func->defaultArgs.GetLength() > p && func->defaultArgs[p]) ||
(func2->defaultArgs.GetLength() > p && func2->defaultArgs[p]))
break;
if (func->parameterTypes[p] != func2->parameterTypes[p] ||
func->inOutFlags[p] != func2->inOutFlags[p]) {
match = false;
break;
}
}
if (match) {
if (!((p >= func->parameterTypes.GetLength() && p < func2->defaultArgs.GetLength() && func2->defaultArgs[p]) ||
(p >= func2->parameterTypes.GetLength() && p < func->defaultArgs.GetLength() && func->defaultArgs[p]))) {
// The argument lists match for the full length of the shorter, but the next
// argument on the longer does not have a default arg so there is no conflict
match = false;
}
}
if (match) {
WriteWarning(TXT_OVERLOAD_CONFLICTS_DUE_TO_DEFAULT_ARGS, script, node);
WriteInfo(func->GetDeclaration(), script, node);
WriteInfo(func2->GetDeclaration(), script, node);
break;
}
}
return 0;
}
int asCBuilder::CompileFunction(const char *sectionName, const char *code, int lineOffset, asDWORD compileFlags, asCScriptFunction **outFunc) {
asASSERT(outFunc != 0);
Reset();
// Add the string to the script code
asCScriptCode *script = asNEW(asCScriptCode);
if (script == 0)
return asOUT_OF_MEMORY;
script->SetCode(sectionName, code, true);
script->lineOffset = lineOffset;
script->idx = engine->GetScriptSectionNameIndex(sectionName ? sectionName : "");
scripts.PushLast(script);
// Parse the string
asCParser parser(this);
if (parser.ParseScript(scripts[0]) < 0)
return asERROR;
asCScriptNode *node = parser.GetScriptNode();
// Make sure there is nothing else than the function in the script code
if (node == 0 ||
node->firstChild == 0 ||
node->firstChild != node->lastChild ||
node->firstChild->nodeType != snFunction) {
WriteError(TXT_ONLY_ONE_FUNCTION_ALLOWED, script, 0);
return asERROR;
}
// Find the function node
node = node->firstChild;
// Create the function
asSFunctionTraits funcTraits;
asCScriptFunction *func = asNEW(asCScriptFunction)(engine, compileFlags & asCOMP_ADD_TO_MODULE ? module : 0, asFUNC_SCRIPT);
if (func == 0)
return asOUT_OF_MEMORY;
GetParsedFunctionDetails(node, scripts[0], 0, func->name, func->returnType, func->parameterNames, func->parameterTypes, func->inOutFlags, func->defaultArgs, funcTraits, module->m_defaultNamespace);
func->id = engine->GetNextScriptFunctionId();
func->scriptData->scriptSectionIdx = engine->GetScriptSectionNameIndex(sectionName ? sectionName : "");
int row, col;
scripts[0]->ConvertPosToRowCol(node->tokenPos, &row, &col);
func->scriptData->declaredAt = (row & 0xFFFFF) | ((col & 0xFFF) << 20);
func->nameSpace = module->m_defaultNamespace;
// Make sure the default args are declared correctly
int r = ValidateDefaultArgs(script, node, func);
if (r < 0) {
func->ReleaseInternal();
return asERROR;
}
// Tell the engine that the function exists already so the compiler can access it
if (compileFlags & asCOMP_ADD_TO_MODULE) {
r = CheckNameConflict(func->name.AddressOf(), node, scripts[0], module->m_defaultNamespace, false, false);
if (r < 0) {
func->ReleaseInternal();
return asERROR;
}
module->m_globalFunctions.Put(func);
module->AddScriptFunction(func);
} else
engine->AddScriptFunction(func);
// Fill in the function info for the builder too
node->DisconnectParent();
sFunctionDescription *funcDesc = asNEW(sFunctionDescription);
if (funcDesc == 0) {
func->ReleaseInternal();
return asOUT_OF_MEMORY;
}
functions.PushLast(funcDesc);
funcDesc->script = scripts[0];
funcDesc->node = node;
funcDesc->name = func->name;
funcDesc->funcId = func->id;
funcDesc->paramNames = func->parameterNames;
funcDesc->isExistingShared = false;
// This must be done in a loop, as it is possible that additional functions get declared as lambda's in the code
for (asUINT n = 0; n < functions.GetLength(); n++) {
asCCompiler compiler(engine);
asCScriptFunction *f = engine->scriptFunctions[functions[n]->funcId];
r = compiler.CompileFunction(this, functions[n]->script, f->parameterNames, functions[n]->node, f, 0);
if (r < 0)
break;
}
if (numWarnings > 0 && engine->ep.compilerWarnings == 2)
WriteError(TXT_WARNINGS_TREATED_AS_ERROR, 0, 0);
// None of the functions should be added to the module if any error occurred,
// or it was requested that the functions wouldn't be added to the scope
if (!(compileFlags & asCOMP_ADD_TO_MODULE) || numErrors > 0) {
for (asUINT n = 0; n < functions.GetLength(); n++) {
asCScriptFunction *f = engine->scriptFunctions[functions[n]->funcId];
if (module->m_globalFunctions.GetIndex(f) >= 0) {
module->m_globalFunctions.Erase(module->m_globalFunctions.GetIndex(f));
module->m_scriptFunctions.RemoveValue(f);
f->ReleaseInternal();
}
}
}
if (numErrors > 0) {
// Release the function pointer that would otherwise be returned if no errors occured
func->ReleaseInternal();
return asERROR;
}
// Return the function
*outFunc = func;
return asSUCCESS;
}
void asCBuilder::ParseScripts() {
TimeIt("asCBuilder::ParseScripts");
asCArray<asCParser *> parsers((int)scripts.GetLength());
// Parse all the files as if they were one
asUINT n = 0;
for (n = 0; n < scripts.GetLength(); n++) {
asCParser *parser = asNEW(asCParser)(this);
if (parser != 0) {
parsers.PushLast(parser);
// Parse the script file
parser->ParseScript(scripts[n]);
}
}
if (numErrors == 0) {
// Find all type declarations
for (n = 0; n < scripts.GetLength(); n++) {
asCScriptNode *node = parsers[n]->GetScriptNode();
RegisterTypesFromScript(node, scripts[n], engine->nameSpaces[0]);
}
// Before moving forward the builder must establish the relationship between types
// so that a derived type can see the child types of the parent type.
DetermineTypeRelations();
// Complete function definitions (defining returntype and parameters)
for (n = 0; n < funcDefs.GetLength(); n++)
CompleteFuncDef(funcDefs[n]);
// Find other global nodes
for (n = 0; n < scripts.GetLength(); n++) {
// Find other global nodes
asCScriptNode *node = parsers[n]->GetScriptNode();
RegisterNonTypesFromScript(node, scripts[n], engine->nameSpaces[0]);
}
// Register script methods found in the interfaces
for (n = 0; n < interfaceDeclarations.GetLength(); n++) {
sClassDeclaration *decl = interfaceDeclarations[n];
asCScriptNode *node = decl->node->firstChild->next;
// Skip list of inherited interfaces
while (node && node->nodeType == snIdentifier)
node = node->next;
while (node) {
asCScriptNode *next = node->next;
if (node->nodeType == snFunction) {
node->DisconnectParent();
RegisterScriptFunctionFromNode(node, decl->script, CastToObjectType(decl->typeInfo), true, false, 0, decl->isExistingShared);
} else if (node->nodeType == snVirtualProperty) {
node->DisconnectParent();
RegisterVirtualProperty(node, decl->script, CastToObjectType(decl->typeInfo), true, false, 0, decl->isExistingShared);
}
node = next;
}
}
// Register script methods found in the classes
for (n = 0; n < classDeclarations.GetLength(); n++) {
sClassDeclaration *decl = classDeclarations[n];
asCScriptNode *node = decl->node->firstChild->next;
// Skip list of classes and interfaces
while (node && node->nodeType == snIdentifier)
node = node->next;
while (node) {
asCScriptNode *next = node->next;
if (node->nodeType == snFunction) {
node->DisconnectParent();
RegisterScriptFunctionFromNode(node, decl->script, CastToObjectType(decl->typeInfo), false, false, 0, decl->isExistingShared);
} else if (node->nodeType == snVirtualProperty) {
node->DisconnectParent();
RegisterVirtualProperty(node, decl->script, CastToObjectType(decl->typeInfo), false, false, 0, decl->isExistingShared);
}
node = next;
}
// Make sure the default factory & constructor exists for classes
asCObjectType *ot = CastToObjectType(decl->typeInfo);
if (ot->beh.construct == engine->scriptTypeBehaviours.beh.construct) {
if (ot->beh.constructors.GetLength() == 1 || engine->ep.alwaysImplDefaultConstruct) {
AddDefaultConstructor(ot, decl->script);
} else {
// As the class has another constructor we shouldn't provide the default constructor
if (ot->beh.construct) {
engine->scriptFunctions[ot->beh.construct]->ReleaseInternal();
ot->beh.construct = 0;
ot->beh.constructors.RemoveIndex(0);
}
if (ot->beh.factory) {
engine->scriptFunctions[ot->beh.factory]->ReleaseInternal();
ot->beh.factory = 0;
ot->beh.factories.RemoveIndex(0);
}
// Only remove the opAssign method if the script hasn't provided one
if (ot->beh.copy == engine->scriptTypeBehaviours.beh.copy) {
engine->scriptFunctions[ot->beh.copy]->ReleaseInternal();
ot->beh.copy = 0;
}
}
}
}
}
for (n = 0; n < parsers.GetLength(); n++) {
asDELETE(parsers[n], asCParser);
}
}
void asCBuilder::RegisterTypesFromScript(asCScriptNode *node, asCScriptCode *script, asSNameSpace *ns) {
asASSERT(node->nodeType == snScript);
// Find structure definitions first
node = node->firstChild;
while (node) {
asCScriptNode *next = node->next;
if (node->nodeType == snNamespace) {
// Recursively register the entities defined in the namespace
asCString nsName;
nsName.Assign(&script->code[node->firstChild->tokenPos], node->firstChild->tokenLength);
if (ns->name != "")
nsName = ns->name + "::" + nsName;
asSNameSpace *nsChild = engine->AddNameSpace(nsName.AddressOf());
RegisterTypesFromScript(node->lastChild, script, nsChild);
} else {
if (node->nodeType == snClass) {
node->DisconnectParent();
RegisterClass(node, script, ns);
} else if (node->nodeType == snInterface) {
node->DisconnectParent();
RegisterInterface(node, script, ns);
} else if (node->nodeType == snEnum) {
node->DisconnectParent();
RegisterEnum(node, script, ns);
} else if (node->nodeType == snTypedef) {
node->DisconnectParent();
RegisterTypedef(node, script, ns);
} else if (node->nodeType == snFuncDef) {
node->DisconnectParent();
RegisterFuncDef(node, script, ns, 0);
} else if (node->nodeType == snMixin) {
node->DisconnectParent();
RegisterMixinClass(node, script, ns);
}
}
node = next;
}
}
void asCBuilder::RegisterNonTypesFromScript(asCScriptNode *node, asCScriptCode *script, asSNameSpace *ns) {
node = node->firstChild;
while (node) {
asCScriptNode *next = node->next;
if (node->nodeType == snNamespace) {
// Determine the name of the namespace
asCString nsName;
nsName.Assign(&script->code[node->firstChild->tokenPos], node->firstChild->tokenLength);
if (ns->name != "")
nsName = ns->name + "::" + nsName;
// Declare the namespace, then add the entities
asSNameSpace *nsChild = engine->AddNameSpace(nsName.AddressOf());
RegisterNonTypesFromScript(node->lastChild, script, nsChild);
} else {
node->DisconnectParent();
if (node->nodeType == snFunction)
RegisterScriptFunctionFromNode(node, script, 0, false, true, ns);
else if (node->nodeType == snDeclaration)
RegisterGlobalVar(node, script, ns);
else if (node->nodeType == snVirtualProperty)
RegisterVirtualProperty(node, script, 0, false, true, ns);
else if (node->nodeType == snImport)
RegisterImportedFunction(module->GetNextImportedFunctionId(), node, script, ns);
else {
// Unused script node
int r, c;
script->ConvertPosToRowCol(node->tokenPos, &r, &c);
WriteWarning(script->name, TXT_UNUSED_SCRIPT_NODE, r, c);
node->Destroy(engine);
}
}
node = next;
}
}
void asCBuilder::CompileFunctions() {
// Compile each function
for (asUINT n = 0; n < functions.GetLength(); n++) {
sFunctionDescription *current = functions[n];
if (current == 0) continue;
// Don't compile the function again if it was an existing shared function
if (current->isExistingShared) continue;
// Don't compile if there is no statement block
if (current->node && !(current->node->nodeType == snStatementBlock || current->node->lastChild->nodeType == snStatementBlock))
continue;
asCCompiler compiler(engine);
asCScriptFunction *func = engine->scriptFunctions[current->funcId];
// Find the class declaration for constructors
sClassDeclaration *classDecl = 0;
if (current->objType && current->name == current->objType->name) {
for (asUINT c = 0; c < classDeclarations.GetLength(); c++) {
if (classDeclarations[c]->typeInfo == current->objType) {
classDecl = classDeclarations[c];
break;
}
}
asASSERT(classDecl);
}
if (current->node) {
int r, c;
current->script->ConvertPosToRowCol(current->node->tokenPos, &r, &c);
asCString str = func->GetDeclarationStr();
str.Format(TXT_COMPILING_s, str.AddressOf());
WriteInfo(current->script->name, str, r, c, true);
// When compiling a constructor need to pass the class declaration for member initializations
compiler.CompileFunction(this, current->script, current->paramNames, current->node, func, classDecl);
engine->preMessage.isSet = false;
} else if (current->objType && current->name == current->objType->name) {
asCScriptNode *node = classDecl->node;
int r = 0, c = 0;
if (node)
current->script->ConvertPosToRowCol(node->tokenPos, &r, &c);
asCString str = func->GetDeclarationStr();
str.Format(TXT_COMPILING_s, str.AddressOf());
WriteInfo(current->script->name, str, r, c, true);
// This is the default constructor that is generated
// automatically if not implemented by the user.
compiler.CompileDefaultConstructor(this, current->script, node, func, classDecl);
engine->preMessage.isSet = false;
} else {
asASSERT(false);
}
}
}
#endif
// Called from module and engine
int asCBuilder::ParseDataType(const char *datatype, asCDataType *result, asSNameSpace *implicitNamespace, bool isReturnType) {
Reset();
asCScriptCode source;
source.SetCode("", datatype, true);
asCParser parser(this);
int r = parser.ParseDataType(&source, isReturnType);
if (r < 0)
return asINVALID_TYPE;
// Get data type and property name
asCScriptNode *dataType = parser.GetScriptNode()->firstChild;
*result = CreateDataTypeFromNode(dataType, &source, implicitNamespace, true);
if (isReturnType)
*result = ModifyDataTypeFromNode(*result, dataType->next, &source, 0, 0);
if (numErrors > 0)
return asINVALID_TYPE;
return asSUCCESS;
}
int asCBuilder::ParseTemplateDecl(const char *decl, asCString *name, asCArray<asCString> &subtypeNames) {
Reset();
asCScriptCode source;
source.SetCode("", decl, true);
asCParser parser(this);
int r = parser.ParseTemplateDecl(&source);
if (r < 0)
return asINVALID_TYPE;
// Get the template name and subtype names
asCScriptNode *node = parser.GetScriptNode()->firstChild;
name->Assign(&decl[node->tokenPos], node->tokenLength);
while ((node = node->next) != 0) {
asCString subtypeName;
subtypeName.Assign(&decl[node->tokenPos], node->tokenLength);
subtypeNames.PushLast(subtypeName);
}
// TODO: template: check for name conflicts
if (numErrors > 0)
return asINVALID_DECLARATION;
return asSUCCESS;
}
int asCBuilder::VerifyProperty(asCDataType *dt, const char *decl, asCString &name, asCDataType &type, asSNameSpace *ns) {
// Either datatype or namespace must be informed
asASSERT(dt || ns);
Reset();
if (dt) {
// Verify that the object type exist
if (CastToObjectType(dt->GetTypeInfo()) == 0)
return asINVALID_OBJECT;
}
// Check property declaration and type
asCScriptCode source;
source.SetCode(TXT_PROPERTY, decl, true);
asCParser parser(this);
int r = parser.ParsePropertyDeclaration(&source);
if (r < 0)
return asINVALID_DECLARATION;
// Get data type
asCScriptNode *dataType = parser.GetScriptNode()->firstChild;
// Check if the property is declared 'by reference'
bool isReference = (dataType->next->tokenType == ttAmp);
// Get the name of the property
asCScriptNode *nameNode = isReference ? dataType->next->next : dataType->next;
// If an object property is registered, then use the
// object's namespace, otherwise use the specified namespace
type = CreateDataTypeFromNode(dataType, &source, dt ? dt->GetTypeInfo()->nameSpace : ns);
name.Assign(&decl[nameNode->tokenPos], nameNode->tokenLength);
type.MakeReference(isReference);
// Validate that the type really can be a registered property
// We cannot use CanBeInstantiated, as it is allowed to register
// properties of type that cannot otherwise be instantiated
if (type.IsFuncdef() && !type.IsObjectHandle()) {
// Function definitions must always be handles
return asINVALID_DECLARATION;
}
// Verify property name
if (dt) {
if (CheckNameConflictMember(dt->GetTypeInfo(), name.AddressOf(), nameNode, &source, true, false) < 0)
return asNAME_TAKEN;
} else {
if (CheckNameConflict(name.AddressOf(), nameNode, &source, ns, true, false) < 0)
return asNAME_TAKEN;
}
if (numErrors > 0)
return asINVALID_DECLARATION;
return asSUCCESS;
}
#ifndef AS_NO_COMPILER
asCObjectProperty *asCBuilder::GetObjectProperty(asCDataType &obj, const char *prop) {
asASSERT(CastToObjectType(obj.GetTypeInfo()) != 0);
// TODO: optimize: Improve linear search
asCArray<asCObjectProperty *> &props = CastToObjectType(obj.GetTypeInfo())->properties;
for (asUINT n = 0; n < props.GetLength(); n++) {
if (props[n]->name == prop) {
if (module->m_accessMask & props[n]->accessMask)
return props[n];
else
return 0;
}
}
return 0;
}
#endif
bool asCBuilder::DoesGlobalPropertyExist(const char *prop, asSNameSpace *ns, asCGlobalProperty **outProp, sGlobalVariableDescription **outDesc, bool *isAppProp) {
if (outProp) *outProp = 0;
if (outDesc) *outDesc = 0;
if (isAppProp) *isAppProp = false;
// Check application registered properties
asCString name(prop);
asCGlobalProperty *globProp = engine->registeredGlobalProps.GetFirst(ns, name);
if (globProp) {
if (isAppProp) *isAppProp = true;
if (outProp) *outProp = globProp;
return true;
}
#ifndef AS_NO_COMPILER
// Check properties being compiled now
sGlobalVariableDescription *desc = globVariables.GetFirst(ns, prop);
if (desc && !desc->isEnumValue) {
if (outProp) *outProp = desc->property;
if (outDesc) *outDesc = desc;
return true;
}
#endif
// Check previously compiled global variables
if (module) {
globProp = module->m_scriptGlobals.GetFirst(ns, prop);
if (globProp) {
if (outProp) *outProp = globProp;
return true;
}
}
return false;
}
asCGlobalProperty *asCBuilder::GetGlobalProperty(const char *prop, asSNameSpace *ns, bool *isCompiled, bool *isPureConstant, asQWORD *constantValue, bool *isAppProp) {
if (isCompiled) *isCompiled = true;
if (isPureConstant) *isPureConstant = false;
if (isAppProp) *isAppProp = false;
if (constantValue) *constantValue = 0;
asCGlobalProperty *globProp = 0;
sGlobalVariableDescription *globDesc = 0;
if (DoesGlobalPropertyExist(prop, ns, &globProp, &globDesc, isAppProp)) {
#ifndef AS_NO_COMPILER
if (globDesc) {
// The property was declared in this build call, check if it has been compiled successfully already
if (isCompiled) *isCompiled = globDesc->isCompiled;
if (isPureConstant) *isPureConstant = globDesc->isPureConstant;
if (constantValue) *constantValue = globDesc->constantValue;
} else
#endif
if (isAppProp) {
// Don't return the property if the module doesn't have access to it
if (!(module->m_accessMask & globProp->accessMask))
globProp = 0;
}
return globProp;
}
return 0;
}
int asCBuilder::ParseFunctionDeclaration(asCObjectType *objType, const char *decl, asCScriptFunction *func, bool isSystemFunction, asCArray<bool> *paramAutoHandles, bool *returnAutoHandle, asSNameSpace *ns, asCScriptNode **listPattern, asCObjectType **outParentClass) {
asASSERT(objType || ns);
if (listPattern)
*listPattern = 0;
if (outParentClass)
*outParentClass = 0;
// TODO: Can't we use GetParsedFunctionDetails to do most of what is done in this function?
Reset();
asCScriptCode source;
source.SetCode(TXT_SYSTEM_FUNCTION, decl, true);
asCParser parser(this);
int r = parser.ParseFunctionDefinition(&source, listPattern != 0);
if (r < 0)
return asINVALID_DECLARATION;
asCScriptNode *node = parser.GetScriptNode();
// Determine scope
asCScriptNode *n = node->firstChild->next->next;
asCObjectType *parentClass = 0;
func->nameSpace = GetNameSpaceFromNode(n, &source, ns, &n, &parentClass);
if (func->nameSpace == 0 && parentClass == 0)
return asINVALID_DECLARATION;
if (parentClass && func->funcType != asFUNC_FUNCDEF)
return asINVALID_DECLARATION;
if (outParentClass)
*outParentClass = parentClass;
// Find name
func->name.Assign(&source.code[n->tokenPos], n->tokenLength);
// Initialize a script function object for registration
bool autoHandle;
// Scoped reference types are allowed to use handle when returned from application functions
func->returnType = CreateDataTypeFromNode(node->firstChild, &source, objType ? objType->nameSpace : ns, true, parentClass ? parentClass : objType);
func->returnType = ModifyDataTypeFromNode(func->returnType, node->firstChild->next, &source, 0, &autoHandle);
if (autoHandle && (!func->returnType.IsObjectHandle() || func->returnType.IsReference()))
return asINVALID_DECLARATION;
if (returnAutoHandle) *returnAutoHandle = autoHandle;
// Reference types cannot be returned by value from system functions
if (isSystemFunction &&
(func->returnType.GetTypeInfo() &&
(func->returnType.GetTypeInfo()->flags & asOBJ_REF)) &&
!(func->returnType.IsReference() ||
func->returnType.IsObjectHandle()))
return asINVALID_DECLARATION;
// Count number of parameters
int paramCount = 0;
asCScriptNode *paramList = n->next;
n = paramList->firstChild;
while (n) {
paramCount++;
n = n->next->next;
if (n && n->nodeType == snIdentifier)
n = n->next;
if (n && n->nodeType == snExpression)
n = n->next;
}
// Preallocate memory
func->parameterTypes.Allocate(paramCount, false);
func->parameterNames.SetLength(paramCount);
func->inOutFlags.Allocate(paramCount, false);
func->defaultArgs.Allocate(paramCount, false);
if (paramAutoHandles) paramAutoHandles->Allocate(paramCount, false);
n = paramList->firstChild;
asUINT index = 0;
while (n) {
asETypeModifiers inOutFlags;
asCDataType type = CreateDataTypeFromNode(n, &source, objType ? objType->nameSpace : ns, false, parentClass ? parentClass : objType);
type = ModifyDataTypeFromNode(type, n->next, &source, &inOutFlags, &autoHandle);
// Reference types cannot be passed by value to system functions
if (isSystemFunction &&
(type.GetTypeInfo() &&
(type.GetTypeInfo()->flags & asOBJ_REF)) &&
!(type.IsReference() ||
type.IsObjectHandle()))
return asINVALID_DECLARATION;
// Store the parameter type
func->parameterTypes.PushLast(type);
func->inOutFlags.PushLast(inOutFlags);
// Don't permit void parameters
if (type.GetTokenType() == ttVoid)
return asINVALID_DECLARATION;
if (autoHandle && (!type.IsObjectHandle() || type.IsReference()))
return asINVALID_DECLARATION;
if (paramAutoHandles) paramAutoHandles->PushLast(autoHandle);
// Make sure that var type parameters are references
if (type.GetTokenType() == ttQuestion &&
!type.IsReference())
return asINVALID_DECLARATION;
// Move to next parameter
n = n->next->next;
if (n && n->nodeType == snIdentifier) {
func->parameterNames[index] = asCString(&source.code[n->tokenPos], n->tokenLength);
n = n->next;
}
++index;
if (n && n->nodeType == snExpression) {
// Strip out white space and comments to better share the string
asCString *defaultArgStr = asNEW(asCString);
if (defaultArgStr) {
*defaultArgStr = GetCleanExpressionString(n, &source);
func->defaultArgs.PushLast(defaultArgStr);
}
n = n->next;
} else
func->defaultArgs.PushLast(0);
}
// Set the read-only flag if const is declared after parameter list
n = paramList->next;
if (n && n->nodeType == snUndefined && n->tokenType == ttConst) {
if (objType == 0)
return asINVALID_DECLARATION;
func->SetReadOnly(true);
n = n->next;
} else
func->SetReadOnly(false);
// Check for additional function traits
while (n && n->nodeType == snIdentifier) {
if (source.TokenEquals(n->tokenPos, n->tokenLength, EXPLICIT_TOKEN))
func->SetExplicit(true);
else if (source.TokenEquals(n->tokenPos, n->tokenLength, PROPERTY_TOKEN))
func->SetProperty(true);
else
return asINVALID_DECLARATION;
n = n->next;
}
// If the caller expects a list pattern, check for the existence, else report an error if not
if (listPattern) {
if (n == 0 || n->nodeType != snListPattern)
return asINVALID_DECLARATION;
else {
*listPattern = n;
n->DisconnectParent();
}
} else {
if (n)
return asINVALID_DECLARATION;
}
// Make sure the default args are declared correctly
ValidateDefaultArgs(&source, node, func);
if (numErrors > 0 || numWarnings > 0)
return asINVALID_DECLARATION;
return 0;
}
int asCBuilder::ParseVariableDeclaration(const char *decl, asSNameSpace *implicitNamespace, asCString &outName, asSNameSpace *&outNamespace, asCDataType &outDt) {
Reset();
asCScriptCode source;
source.SetCode(TXT_VARIABLE_DECL, decl, true);
asCParser parser(this);
int r = parser.ParsePropertyDeclaration(&source);
if (r < 0)
return asINVALID_DECLARATION;
asCScriptNode *node = parser.GetScriptNode();
// Determine the scope from declaration
asCScriptNode *n = node->firstChild->next;
// TODO: child funcdef: The parentType will be set if the scope is actually a type rather than a namespace
outNamespace = GetNameSpaceFromNode(n, &source, implicitNamespace, &n);
if (outNamespace == 0)
return asINVALID_DECLARATION;
// Find name
outName.Assign(&source.code[n->tokenPos], n->tokenLength);
// Initialize a script variable object for registration
outDt = CreateDataTypeFromNode(node->firstChild, &source, implicitNamespace);
if (numErrors > 0 || numWarnings > 0)
return asINVALID_DECLARATION;
return 0;
}
// TODO: This should use SymbolLookupMember, which should be available in the TypeInfo class
int asCBuilder::CheckNameConflictMember(asCTypeInfo *t, const char *name, asCScriptNode *node, asCScriptCode *code, bool isProperty, bool isVirtualProperty) {
// It's not necessary to check against object types
asCObjectType *ot = CastToObjectType(t);
if (!ot)
return 0;
// Check against properties
// TODO: optimize: Improve linear search
// Properties are allowed to have the same name as virtual properties
if (!isVirtualProperty) {
asCArray<asCObjectProperty *> &props = ot->properties;
for (asUINT n = 0; n < props.GetLength(); n++) {
if (props[n]->name == name) {
if (code) {
asCString str;
str.Format(TXT_NAME_CONFLICT_s_OBJ_PROPERTY, name);
WriteError(str, code, node);
}
return -1;
}
}
}
// Check against virtual properties
// Don't do this when the check is for a virtual property, as it is allowed to have multiple overloads for virtual properties
// Properties are allowed to have the same name as virtual properties
if (!isProperty && !isVirtualProperty) {
asCArray<int> methods = ot->methods;
for (asUINT n = 0; n < methods.GetLength(); n++) {
asCScriptFunction *func = engine->scriptFunctions[methods[n]];
if (func->IsProperty() && func->name.SubString(4) == name) {
if (code) {
asCString str;
str.Format(TXT_NAME_CONFLICT_s_OBJ_PROPERTY, name);
WriteError(str, code, node);
}
return -1;
}
}
}
// Check against child types
asCArray<asCFuncdefType *> &funcdefs = ot->childFuncDefs;
for (asUINT n = 0; n < funcdefs.GetLength(); n++) {
if (funcdefs[n]->name == name) {
if (code) {
asCString str;
str.Format(TXT_NAME_CONFLICT_s_IS_FUNCDEF, name);
WriteError(str, code, node);
}
return -1;
}
}
// Property names must be checked against method names
if (isProperty) {
asCArray<int> methods = ot->methods;
for (asUINT n = 0; n < methods.GetLength(); n++) {
if (engine->scriptFunctions[methods[n]]->name == name) {
if (code) {
asCString str;
str.Format(TXT_NAME_CONFLICT_s_METHOD, name);
WriteError(str, code, node);
}
return -1;
}
}
}
// If there is a namespace at the same level with the same name as the class, then need to check for conflicts with symbols in that namespace too
// TODO: When classes can have static members, the code should change so that class name cannot be the same as a namespace
asCString scope;
if (ot->nameSpace->name != "")
scope = ot->nameSpace->name + "::" + ot->name;
else
scope = ot->name;
asSNameSpace *ns = engine->FindNameSpace(scope.AddressOf());
if (ns) {
// Check as if not a function as it doesn't matter the function signature
return CheckNameConflict(name, node, code, ns, true, isVirtualProperty);
}
return 0;
}
// TODO: This should use SymbolLookup
int asCBuilder::CheckNameConflict(const char *name, asCScriptNode *node, asCScriptCode *code, asSNameSpace *ns, bool isProperty, bool isVirtualProperty) {
// Check against registered object types
if (engine->GetRegisteredType(name, ns) != 0) {
if (code) {
asCString str;
if (ns->name != "")
str = ns->name + "::" + name;
else
str = name;
str.Format(TXT_NAME_CONFLICT_s_EXTENDED_TYPE, str.AddressOf());
WriteError(str, code, node);
}
return -1;
}
// Check against global properties
// Virtual properties are allowed to have the same name as a real property
if (!isVirtualProperty && DoesGlobalPropertyExist(name, ns)) {
if (code) {
asCString str;
if (ns->name != "")
str = ns->name + "::" + name;
else
str = name;
str.Format(TXT_NAME_CONFLICT_s_GLOBAL_PROPERTY, str.AddressOf());
WriteError(str, code, node);
}
return -1;
}
// Check against registered global virtual properties
// Don't do this when the check is for a virtual property, as it is allowed to have multiple overloads for virtual properties
if (!isProperty || !isVirtualProperty) {
for (asUINT n = 0; n < engine->registeredGlobalFuncs.GetSize(); n++) {
asCScriptFunction *func = engine->registeredGlobalFuncs.Get(n);
if (func->IsProperty() &&
func->nameSpace == ns &&
func->name.SubString(4) == name) {
if (code) {
asCString str;
if (ns->name != "")
str = ns->name + "::" + name;
else
str = name;
str.Format(TXT_NAME_CONFLICT_s_IS_VIRTPROP, str.AddressOf());
WriteError(str, code, node);
}
return -1;
}
}
}
// Property names must be checked against function names
if (isProperty) {
for (asUINT n = 0; n < engine->registeredGlobalFuncs.GetSize(); n++) {
if (engine->registeredGlobalFuncs.Get(n)->name == name &&
engine->registeredGlobalFuncs.Get(n)->nameSpace == ns) {
if (code) {
asCString str;
if (ns->name != "")
str = ns->name + "::" + name;
else
str = name;
str.Format(TXT_NAME_CONFLICT_s_IS_FUNCTION, str.AddressOf());
WriteError(str, code, node);
}
return -1;
}
}
}
#ifndef AS_NO_COMPILER
// Check against interface types
asUINT n;
for (n = 0; n < interfaceDeclarations.GetLength(); n++) {
if (interfaceDeclarations[n]->name == name &&
interfaceDeclarations[n]->typeInfo->nameSpace == ns) {
if (code) {
asCString str;
if (ns->name != "")
str = ns->name + "::" + name;
else
str = name;
str.Format(TXT_NAME_CONFLICT_s_INTF, str.AddressOf());
WriteError(str, code, node);
}
return -1;
}
}
// Check against class types
for (n = 0; n < classDeclarations.GetLength(); n++) {
if (classDeclarations[n]->name == name &&
classDeclarations[n]->typeInfo->nameSpace == ns) {
if (code) {
asCString str;
if (ns->name != "")
str = ns->name + "::" + name;
else
str = name;
str.Format(TXT_NAME_CONFLICT_s_STRUCT, str.AddressOf());
WriteError(str, code, node);
}
return -1;
}
}
// Check against named types
for (n = 0; n < namedTypeDeclarations.GetLength(); n++) {
if (namedTypeDeclarations[n]->name == name &&
namedTypeDeclarations[n]->typeInfo->nameSpace == ns) {
if (code) {
asCString str;
if (ns->name != "")
str = ns->name + "::" + name;
else
str = name;
str.Format(TXT_NAME_CONFLICT_s_IS_NAMED_TYPE, str.AddressOf());
WriteError(str, code, node);
}
return -1;
}
}
// Must check for name conflicts with funcdefs
for (n = 0; n < funcDefs.GetLength(); n++) {
if (funcDefs[n]->name == name &&
module->m_funcDefs[funcDefs[n]->idx]->nameSpace == ns) {
if (code) {
asCString str;
if (ns->name != "")
str = ns->name + "::" + name;
else
str = name;
str.Format(TXT_NAME_CONFLICT_s_IS_FUNCDEF, str.AddressOf());
WriteError(str, code, node);
}
return -1;
}
}
// Check against mixin classes
if (GetMixinClass(name, ns)) {
if (code) {
asCString str;
if (ns->name != "")
str = ns->name + "::" + name;
else
str = name;
str.Format(TXT_NAME_CONFLICT_s_IS_MIXIN, str.AddressOf());
WriteError(str, code, node);
}
return -1;
}
// Check against virtual properties
// Don't do this when the check is for a virtual property, as it is allowed to have multiple overloads for virtual properties
if (!isProperty && !isVirtualProperty) {
for (n = 0; n < functions.GetLength(); n++) {
asCScriptFunction *func = engine->scriptFunctions[functions[n] ? functions[n]->funcId : 0];
if (func &&
func->IsProperty() &&
func->objectType == 0 &&
func->nameSpace == ns &&
func->name.SubString(4) == name) {
if (code) {
asCString str;
if (ns->name != "")
str = ns->name + "::" + name;
else
str = name;
str.Format(TXT_NAME_CONFLICT_s_IS_VIRTPROP, str.AddressOf());
WriteError(str, code, node);
}
return -1;
}
}
}
// Property names must be checked against function names
if (isProperty) {
for (n = 0; n < functions.GetLength(); n++) {
if (functions[n] &&
functions[n]->objType == 0 &&
functions[n]->name == name &&
engine->scriptFunctions[functions[n]->funcId]->nameSpace == ns) {
if (code) {
asCString str;
if (ns->name != "")
str = ns->name + "::" + name;
else
str = name;
str.Format(TXT_NAME_CONFLICT_s_IS_FUNCTION, str.AddressOf());
WriteError(str, code, node);
}
return -1;
}
}
}
#endif
return 0;
}
// Returns a negative value on invalid property
// -2 incorrect prefix
// -3 invalid signature
// -4 mismatching type for get/set
// -5 name conflict
int asCBuilder::ValidateVirtualProperty(asCScriptFunction *func) {
asASSERT(func->IsProperty());
// A virtual property must have the prefix "get_" or "set_"
asCString prefix = func->name.SubString(0, 4);
if (prefix != "get_" && prefix != "set_")
return -2;
// A getter must return a non-void type and have at most 1 argument (indexed property)
if (prefix == "get_" && (func->returnType == asCDataType::CreatePrimitive(ttVoid, false) || func->parameterTypes.GetLength() > 1))
return -3;
// A setter must return a void and have 1 or 2 arguments (indexed property)
if (prefix == "set_" && (func->returnType != asCDataType::CreatePrimitive(ttVoid, false) || func->parameterTypes.GetLength() < 1 || func->parameterTypes.GetLength() > 2))
return -3;
// Check matching getter/setter
asCDataType getType, setType;
bool found = false;
if (prefix == "get_") {
getType = func->returnType;
// Find if there is a set accessor in the same scope, and then validate the type of it
// TODO: optimize search
asCString setName = "set_" + func->name.SubString(4);
for (asUINT n = 0; n < engine->scriptFunctions.GetLength(); n++) {
asCScriptFunction *setFunc = engine->scriptFunctions[n];
if (setFunc == 0 || setFunc->name != setName || !setFunc->IsProperty())
continue;
// Is it the same scope?
if (func->module != setFunc->module || func->nameSpace != setFunc->nameSpace || func->objectType != setFunc->objectType)
continue;
setType = setFunc->parameterTypes[setFunc->parameterTypes.GetLength() - 1];
found = true;
break;
}
} else {
setType = func->parameterTypes[func->parameterTypes.GetLength() - 1];
// Find if there is a get accessor in the same scope and then validate the type of it
// TODO: optimize search
asCString getName = "get_" + func->name.SubString(4);
for (asUINT n = 0; n < engine->scriptFunctions.GetLength(); n++) {
asCScriptFunction *getFunc = engine->scriptFunctions[n];
if (getFunc == 0 || getFunc->name != getName || !getFunc->IsProperty())
continue;
// Is it the same scope?
if (func->module != getFunc->module || func->nameSpace != getFunc->nameSpace || func->objectType != getFunc->objectType)
continue;
getType = getFunc->returnType;
found = true;
break;
}
}
if (found) {
// Check that the type matches
// It is permitted for a getter to return a handle and the setter to take a reference
if (!getType.IsEqualExceptRefAndConst(setType) &&
!((getType.IsObjectHandle() && !setType.IsObjectHandle()) &&
(getType.GetTypeInfo() == setType.GetTypeInfo()))) {
return -4;
}
}
// Check name conflict with other entities in the same scope
// It is allowed to have a real property of the same name, in which case the virtual property hides the real one.
int r;
if (func->objectType)
r = CheckNameConflictMember(func->objectType, func->name.SubString(4).AddressOf(), 0, 0, true, true);
else
r = CheckNameConflict(func->name.SubString(4).AddressOf(), 0, 0, func->nameSpace, true, true);
if (r < 0)
return -5;
// Everything is OK
return 0;
}
#ifndef AS_NO_COMPILER
sMixinClass *asCBuilder::GetMixinClass(const char *name, asSNameSpace *ns) {
for (asUINT n = 0; n < mixinClasses.GetLength(); n++)
if (mixinClasses[n]->name == name &&
mixinClasses[n]->ns == ns)
return mixinClasses[n];
return 0;
}
int asCBuilder::RegisterFuncDef(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns, asCObjectType *parent) {
// namespace and parent are exclusively mutual
asASSERT((ns == 0 && parent) || (ns && parent == 0));
// Skip leading 'shared' and 'external' keywords
asCScriptNode *n = node->firstChild;
while (n->nodeType == snIdentifier)
n = n->next;
// Find the name
asASSERT(n->nodeType == snDataType);
n = n->next->next;
asCString name;
name.Assign(&file->code[n->tokenPos], n->tokenLength);
// Check for name conflict with other types
if (ns) {
int r = CheckNameConflict(name.AddressOf(), node, file, ns, true, false);
if (asSUCCESS != r) {
node->Destroy(engine);
return r;
}
} else {
int r = CheckNameConflictMember(parent, name.AddressOf(), node, file, false, false);
if (asSUCCESS != r) {
node->Destroy(engine);
return r;
}
}
// The function definition should be stored as a asCScriptFunction so that the application
// can use the asIScriptFunction interface to enumerate the return type and parameters
// The return type and parameter types aren't determined in this function. A second pass is
// necessary after all type declarations have been identified. The second pass is implemented
// in CompleteFuncDef().
sFuncDef *fd = asNEW(sFuncDef);
if (fd == 0) {
node->Destroy(engine);
return asOUT_OF_MEMORY;
}
fd->name = name;
fd->node = node;
fd->script = file;
fd->idx = module->AddFuncDef(name, ns, parent);
funcDefs.PushLast(fd);
return 0;
}
void asCBuilder::CompleteFuncDef(sFuncDef *funcDef) {
asCArray<asCString *> defaultArgs;
asSFunctionTraits funcTraits;
asCFuncdefType *fdt = module->m_funcDefs[funcDef->idx];
asASSERT(fdt);
asCScriptFunction *func = fdt->funcdef;
asSNameSpace *implicitNs = func->nameSpace ? func->nameSpace : fdt->parentClass->nameSpace;
GetParsedFunctionDetails(funcDef->node, funcDef->script, fdt->parentClass, funcDef->name, func->returnType, func->parameterNames, func->parameterTypes, func->inOutFlags, defaultArgs, funcTraits, implicitNs);
// There should not be any defaultArgs, but if there are any we need to delete them to avoid leaks
for (asUINT n = 0; n < defaultArgs.GetLength(); n++)
if (defaultArgs[n])
asDELETE(defaultArgs[n], asCString);
// All funcdefs are shared, unless one of the parameter types or return type is not shared
bool declaredShared = funcTraits.GetTrait(asTRAIT_SHARED);
funcTraits.SetTrait(asTRAIT_SHARED, true);
if (func->returnType.GetTypeInfo() && !func->returnType.GetTypeInfo()->IsShared()) {
if (declaredShared) {
asCString s;
s.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, func->returnType.GetTypeInfo()->name.AddressOf());
WriteError(s.AddressOf(), funcDef->script, funcDef->node);
}
funcTraits.SetTrait(asTRAIT_SHARED, false);
}
for (asUINT n = 0; funcTraits.GetTrait(asTRAIT_SHARED) && n < func->parameterTypes.GetLength(); n++)
if (func->parameterTypes[n].GetTypeInfo() && !func->parameterTypes[n].GetTypeInfo()->IsShared()) {
if (declaredShared) {
asCString s;
s.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, func->parameterTypes[n].GetTypeInfo()->name.AddressOf());
WriteError(s.AddressOf(), funcDef->script, funcDef->node);
}
funcTraits.SetTrait(asTRAIT_SHARED, false);
}
func->SetShared(funcTraits.GetTrait(asTRAIT_SHARED));
// Check if there is another identical funcdef from another module and if so reuse that instead
bool found = false;
if (func->IsShared()) {
for (asUINT n = 0; n < engine->funcDefs.GetLength(); n++) {
asCFuncdefType *fdt2 = engine->funcDefs[n];
if (fdt2 == 0 || fdt == fdt2)
continue;
if (!fdt2->funcdef->IsShared())
continue;
if (fdt2->name == fdt->name &&
fdt2->nameSpace == fdt->nameSpace &&
fdt2->funcdef->IsSignatureExceptNameEqual(func)) {
// Replace our funcdef for the existing one
funcDef->idx = fdt2->funcdef->id;
module->ReplaceFuncDef(fdt, fdt2);
fdt2->AddRefInternal();
engine->funcDefs.RemoveValue(fdt);
fdt->ReleaseInternal();
found = true;
break;
}
}
}
// If the funcdef was declared as external then the existing shared declaration must have been found
if (funcTraits.GetTrait(asTRAIT_EXTERNAL) && !found) {
asCString str;
str.Format(TXT_EXTERNAL_SHARED_s_NOT_FOUND, funcDef->name.AddressOf());
WriteError(str, funcDef->script, funcDef->node);
}
// Remember if the type was declared as external so the saved bytecode can be flagged accordingly
if (funcTraits.GetTrait(asTRAIT_EXTERNAL) && found)
module->m_externalTypes.PushLast(engine->scriptFunctions[funcDef->idx]->funcdefType);
}
int asCBuilder::RegisterGlobalVar(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns) {
// Has the application disabled global vars?
if (engine->ep.disallowGlobalVars)
WriteError(TXT_GLOBAL_VARS_NOT_ALLOWED, file, node);
// What data type is it?
asCDataType type = CreateDataTypeFromNode(node->firstChild, file, ns);
if (!type.CanBeInstantiated()) {
asCString str;
if (type.IsAbstractClass())
str.Format(TXT_ABSTRACT_CLASS_s_CANNOT_BE_INSTANTIATED, type.Format(ns).AddressOf());
else if (type.IsInterface())
str.Format(TXT_INTERFACE_s_CANNOT_BE_INSTANTIATED, type.Format(ns).AddressOf());
else
// TODO: Improve error message to explain why
str.Format(TXT_DATA_TYPE_CANT_BE_s, type.Format(ns).AddressOf());
WriteError(str, file, node);
}
asCScriptNode *n = node->firstChild->next;
while (n) {
// Verify that the name isn't taken
asCString name(&file->code[n->tokenPos], n->tokenLength);
CheckNameConflict(name.AddressOf(), n, file, ns, true, false);
// Register the global variable
sGlobalVariableDescription *gvar = asNEW(sGlobalVariableDescription);
if (gvar == 0) {
node->Destroy(engine);
return asOUT_OF_MEMORY;
}
gvar->script = file;
gvar->name = name;
gvar->isCompiled = false;
gvar->datatype = type;
gvar->isEnumValue = false;
gvar->ns = ns;
// TODO: Give error message if wrong
asASSERT(!gvar->datatype.IsReference());
// Allocation is done when the variable is compiled, to allow for autos
gvar->property = 0;
gvar->index = 0;
globVariables.Put(gvar);
gvar->declaredAtNode = n;
n = n->next;
gvar->declaredAtNode->DisconnectParent();
gvar->initializationNode = 0;
if (n &&
(n->nodeType == snAssignment ||
n->nodeType == snArgList ||
n->nodeType == snInitList)) {
gvar->initializationNode = n;
n = n->next;
gvar->initializationNode->DisconnectParent();
}
}
node->Destroy(engine);
return 0;
}
int asCBuilder::RegisterMixinClass(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns) {
asCScriptNode *cl = node->firstChild;
asASSERT(cl->nodeType == snClass);
asCScriptNode *n = cl->firstChild;
// Skip potential decorator tokens
while (n->tokenType == ttIdentifier &&
(file->TokenEquals(n->tokenPos, n->tokenLength, FINAL_TOKEN) ||
file->TokenEquals(n->tokenPos, n->tokenLength, SHARED_TOKEN) ||
file->TokenEquals(n->tokenPos, n->tokenLength, ABSTRACT_TOKEN) ||
file->TokenEquals(n->tokenPos, n->tokenLength, EXTERNAL_TOKEN))) {
// Report error, because mixin class cannot be final or shared
asCString msg;
msg.Format(TXT_MIXIN_CANNOT_BE_DECLARED_AS_s, asCString(&file->code[n->tokenPos], n->tokenLength).AddressOf());
WriteError(msg, file, n);
asCScriptNode *tmp = n;
n = n->next;
// Remove the invalid node, so compilation can continue as if it wasn't there
tmp->DisconnectParent();
tmp->Destroy(engine);
}
asCString name(&file->code[n->tokenPos], n->tokenLength);
int r, c;
file->ConvertPosToRowCol(n->tokenPos, &r, &c);
CheckNameConflict(name.AddressOf(), n, file, ns, true, false);
sMixinClass *decl = asNEW(sMixinClass);
if (decl == 0) {
node->Destroy(engine);
return asOUT_OF_MEMORY;
}
mixinClasses.PushLast(decl);
decl->name = name;
decl->ns = ns;
decl->node = cl;
decl->script = file;
// Clean up memory
cl->DisconnectParent();
node->Destroy(engine);
// Check that the mixin class doesn't contain any child types
// TODO: Add support for child types in mixin classes
n = cl->firstChild;
while (n) {
if (n->nodeType == snFuncDef) {
WriteError(TXT_MIXIN_CANNOT_HAVE_CHILD_TYPES, file, n);
break;
}
n = n->next;
}
return 0;
}
int asCBuilder::RegisterClass(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns) {
asCScriptNode *n = node->firstChild;
bool isFinal = false;
bool isShared = false;
bool isAbstract = false;
bool isExternal = false;
// Check the class modifiers
while (n->tokenType == ttIdentifier) {
if (file->TokenEquals(n->tokenPos, n->tokenLength, FINAL_TOKEN)) {
if (isAbstract)
WriteError(TXT_CLASS_CANT_BE_FINAL_AND_ABSTRACT, file, n);
else {
if (isFinal) {
asCString msg;
msg.Format(TXT_ATTR_s_INFORMED_MULTIPLE_TIMES, asCString(&file->code[n->tokenPos], n->tokenLength).AddressOf());
WriteWarning(msg, file, n);
}
isFinal = true;
}
} else if (file->TokenEquals(n->tokenPos, n->tokenLength, SHARED_TOKEN)) {
if (isShared) {
asCString msg;
msg.Format(TXT_ATTR_s_INFORMED_MULTIPLE_TIMES, asCString(&file->code[n->tokenPos], n->tokenLength).AddressOf());
WriteWarning(msg, file, n);
}
isShared = true;
} else if (file->TokenEquals(n->tokenPos, n->tokenLength, EXTERNAL_TOKEN)) {
if (isExternal) {
asCString msg;
msg.Format(TXT_ATTR_s_INFORMED_MULTIPLE_TIMES, asCString(&file->code[n->tokenPos], n->tokenLength).AddressOf());
WriteWarning(msg, file, n);
}
isExternal = true;
} else if (file->TokenEquals(n->tokenPos, n->tokenLength, ABSTRACT_TOKEN)) {
if (isFinal)
WriteError(TXT_CLASS_CANT_BE_FINAL_AND_ABSTRACT, file, n);
else {
if (isAbstract) {
asCString msg;
msg.Format(TXT_ATTR_s_INFORMED_MULTIPLE_TIMES, asCString(&file->code[n->tokenPos], n->tokenLength).AddressOf());
WriteWarning(msg, file, n);
}
isAbstract = true;
}
} else {
// This is the name of the class
break;
}
n = n->next;
}
asCString name(&file->code[n->tokenPos], n->tokenLength);
int r, c;
file->ConvertPosToRowCol(n->tokenPos, &r, &c);
CheckNameConflict(name.AddressOf(), n, file, ns, true, false);
sClassDeclaration *decl = asNEW(sClassDeclaration);
if (decl == 0) {
node->Destroy(engine);
return asOUT_OF_MEMORY;
}
classDeclarations.PushLast(decl);
decl->name = name;
decl->script = file;
decl->node = node;
// External shared interfaces must not try to redefine the interface
if (isExternal && (n->next == 0 || n->next->tokenType != ttEndStatement)) {
asCString str;
str.Format(TXT_EXTERNAL_SHARED_s_CANNOT_REDEF, name.AddressOf());
WriteError(str, file, n);
} else if (!isExternal && n->next && n->next->tokenType == ttEndStatement) {
asCString str;
str.Format(TXT_MISSING_DEFINITION_OF_s, name.AddressOf());
WriteError(str, file, n);
}
// If this type is shared and there already exist another shared
// type of the same name, then that one should be used instead of
// creating a new one.
asCObjectType *st = 0;
if (isShared) {
for (asUINT i = 0; i < engine->sharedScriptTypes.GetLength(); i++) {
st = CastToObjectType(engine->sharedScriptTypes[i]);
if (st &&
st->IsShared() &&
st->name == name &&
st->nameSpace == ns &&
!st->IsInterface()) {
// We'll use the existing type
decl->isExistingShared = true;
decl->typeInfo = st;
module->AddClassType(st);
st->AddRefInternal();
break;
}
}
}
// If the class was declared as external then it must have been compiled in a different module first
if (isExternal && decl->typeInfo == 0) {
asCString str;
str.Format(TXT_EXTERNAL_SHARED_s_NOT_FOUND, name.AddressOf());
WriteError(str, file, n);
}
// Remember if the class was declared as external so the saved bytecode can be flagged accordingly
if (isExternal)
module->m_externalTypes.PushLast(st);
if (!decl->isExistingShared) {
// Create a new object type for this class
st = asNEW(asCObjectType)(engine);
if (st == 0)
return asOUT_OF_MEMORY;
// By default all script classes are marked as garbage collected.
// Only after the complete structure and relationship between classes
// is known, can the flag be cleared for those objects that truly cannot
// form circular references. This is important because a template
// callback may be called with a script class before the compilation
// completes, and until it is known, the callback must assume the class
// is garbage collected.
st->flags = asOBJ_REF | asOBJ_SCRIPT_OBJECT | asOBJ_GC;
if (isShared)
st->flags |= asOBJ_SHARED;
if (isFinal)
st->flags |= asOBJ_NOINHERIT;
if (isAbstract)
st->flags |= asOBJ_ABSTRACT;
if (node->tokenType == ttHandle)
st->flags |= asOBJ_IMPLICIT_HANDLE;
st->size = sizeof(asCScriptObject);
st->name = name;
st->nameSpace = ns;
st->module = module;
module->AddClassType(st);
if (isShared) {
engine->sharedScriptTypes.PushLast(st);
st->AddRefInternal();
}
decl->typeInfo = st;
// Use the default script class behaviours
st->beh = engine->scriptTypeBehaviours.beh;
// TODO: Move this to asCObjectType so that the asCRestore can reuse it
engine->scriptFunctions[st->beh.addref]->AddRefInternal();
engine->scriptFunctions[st->beh.release]->AddRefInternal();
engine->scriptFunctions[st->beh.gcEnumReferences]->AddRefInternal();
engine->scriptFunctions[st->beh.gcGetFlag]->AddRefInternal();
engine->scriptFunctions[st->beh.gcGetRefCount]->AddRefInternal();
engine->scriptFunctions[st->beh.gcReleaseAllReferences]->AddRefInternal();
engine->scriptFunctions[st->beh.gcSetFlag]->AddRefInternal();
engine->scriptFunctions[st->beh.copy]->AddRefInternal();
engine->scriptFunctions[st->beh.factory]->AddRefInternal();
engine->scriptFunctions[st->beh.construct]->AddRefInternal();
// TODO: weak: Should not do this if the class has been declared with noweak
engine->scriptFunctions[st->beh.getWeakRefFlag]->AddRefInternal();
// Skip to the content of the class
while (n && n->nodeType == snIdentifier)
n = n->next;
}
// Register possible child types
while (n) {
node = n->next;
if (n->nodeType == snFuncDef) {
n->DisconnectParent();
if (!decl->isExistingShared)
RegisterFuncDef(n, file, 0, st);
else {
// Destroy the node, since it won't be used
// TODO: Should verify that the funcdef is identical to the one in the existing shared class
n->Destroy(engine);
}
}
n = node;
}
return 0;
}
int asCBuilder::RegisterInterface(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns) {
asCScriptNode *n = node->firstChild;
bool isShared = false;
bool isExternal = false;
while (n->nodeType == snIdentifier) {
if (file->TokenEquals(n->tokenPos, n->tokenLength, SHARED_TOKEN))
isShared = true;
else if (file->TokenEquals(n->tokenPos, n->tokenLength, EXTERNAL_TOKEN))
isExternal = true;
else
break;
n = n->next;
}
int r, c;
file->ConvertPosToRowCol(n->tokenPos, &r, &c);
asCString name;
name.Assign(&file->code[n->tokenPos], n->tokenLength);
CheckNameConflict(name.AddressOf(), n, file, ns, true, false);
sClassDeclaration *decl = asNEW(sClassDeclaration);
if (decl == 0) {
node->Destroy(engine);
return asOUT_OF_MEMORY;
}
interfaceDeclarations.PushLast(decl);
decl->name = name;
decl->script = file;
decl->node = node;
// External shared interfaces must not try to redefine the interface
if (isExternal && (n->next == 0 || n->next->tokenType != ttEndStatement)) {
asCString str;
str.Format(TXT_EXTERNAL_SHARED_s_CANNOT_REDEF, name.AddressOf());
WriteError(str, file, n);
} else if (!isExternal && n->next && n->next->tokenType == ttEndStatement) {
asCString str;
str.Format(TXT_MISSING_DEFINITION_OF_s, name.AddressOf());
WriteError(str, file, n);
}
// If this type is shared and there already exist another shared
// type of the same name, then that one should be used instead of
// creating a new one.
if (isShared) {
for (asUINT i = 0; i < engine->sharedScriptTypes.GetLength(); i++) {
asCObjectType *st = CastToObjectType(engine->sharedScriptTypes[i]);
if (st &&
st->IsShared() &&
st->name == name &&
st->nameSpace == ns &&
st->IsInterface()) {
// We'll use the existing type
decl->isExistingShared = true;
decl->typeInfo = st;
module->AddClassType(st);
st->AddRefInternal();
// Remember if the interface was declared as external so the saved bytecode can be flagged accordingly
if (isExternal)
module->m_externalTypes.PushLast(st);
return 0;
}
}
}
// If the interface was declared as external then it must have been compiled in a different module first
if (isExternal) {
asCString str;
str.Format(TXT_EXTERNAL_SHARED_s_NOT_FOUND, name.AddressOf());
WriteError(str, file, n);
}
// Register the object type for the interface
asCObjectType *st = asNEW(asCObjectType)(engine);
if (st == 0)
return asOUT_OF_MEMORY;
st->flags = asOBJ_REF | asOBJ_SCRIPT_OBJECT;
if (isShared)
st->flags |= asOBJ_SHARED;
st->size = 0; // Cannot be instantiated
st->name = name;
st->nameSpace = ns;
st->module = module;
module->AddClassType(st);
if (isShared) {
engine->sharedScriptTypes.PushLast(st);
st->AddRefInternal();
}
decl->typeInfo = st;
// Use the default script class behaviours
st->beh.construct = 0;
st->beh.addref = engine->scriptTypeBehaviours.beh.addref;
engine->scriptFunctions[st->beh.addref]->AddRefInternal();
st->beh.release = engine->scriptTypeBehaviours.beh.release;
engine->scriptFunctions[st->beh.release]->AddRefInternal();
st->beh.copy = 0;
return 0;
}
void asCBuilder::CompileGlobalVariables() {
bool compileSucceeded = true;
// Store state of compilation (errors, warning, output)
int currNumErrors = numErrors;
int currNumWarnings = numWarnings;
// Backup the original message stream
bool msgCallback = engine->msgCallback;
asSSystemFunctionInterface msgCallbackFunc = engine->msgCallbackFunc;
void *msgCallbackObj = engine->msgCallbackObj;
// Set the new temporary message stream
asCOutputBuffer outBuffer;
engine->SetMessageCallback(asFUNCTION(asCOutputBuffer::CDeclCallback), &outBuffer, asCALL_CDECL_OBJLAST);
asCOutputBuffer finalOutput;
asCScriptFunction *initFunc = 0;
asCSymbolTable<asCGlobalProperty> initOrder;
// We first try to compile all the primitive global variables, and only after that
// compile the non-primitive global variables. This permits the constructors
// for the complex types to use the already initialized variables of primitive
// type. Note, we currently don't know which global variables are used in the
// constructors, so we cannot guarantee that variables of complex types are
// initialized in the correct order, so we won't reorder those.
bool compilingPrimitives = true;
// Compile each global variable
while (compileSucceeded) {
compileSucceeded = false;
int accumErrors = 0;
int accumWarnings = 0;
// Restore state of compilation
finalOutput.Clear();
asCSymbolTable<sGlobalVariableDescription>::iterator it = globVariables.List();
for (; it; it++) {
sGlobalVariableDescription *gvar = *it;
if (gvar->isCompiled)
continue;
asCByteCode init(engine);
numWarnings = 0;
numErrors = 0;
outBuffer.Clear();
// Skip this for now if we're not compiling complex types yet
if (compilingPrimitives && !gvar->datatype.IsPrimitive())
continue;
if (gvar->declaredAtNode) {
int r, c;
gvar->script->ConvertPosToRowCol(gvar->declaredAtNode->tokenPos, &r, &c);
asCString str = gvar->datatype.Format(gvar->ns);
str += " " + gvar->name;
str.Format(TXT_COMPILING_s, str.AddressOf());
WriteInfo(gvar->script->name, str, r, c, true);
}
if (gvar->isEnumValue) {
int r;
if (gvar->initializationNode) {
asCCompiler comp(engine);
asCScriptFunction func(engine, module, asFUNC_SCRIPT);
// Set the namespace that should be used during the compilation
func.nameSpace = gvar->datatype.GetTypeInfo()->nameSpace;
// Temporarily switch the type of the variable to int so it can be compiled properly
asCDataType saveType;
saveType = gvar->datatype;
gvar->datatype = asCDataType::CreatePrimitive(ttInt, true);
r = comp.CompileGlobalVariable(this, gvar->script, gvar->initializationNode, gvar, &func);
gvar->datatype = saveType;
// Make the function a dummy so it doesn't try to release objects while destroying the function
func.funcType = asFUNC_DUMMY;
} else {
r = 0;
// When there is no assignment the value is the last + 1
int enumVal = 0;
asCSymbolTable<sGlobalVariableDescription>::iterator prev_it = it;
prev_it--;
if (prev_it) {
sGlobalVariableDescription *gvar2 = *prev_it;
if (gvar2->datatype == gvar->datatype) {
enumVal = int(gvar2->constantValue) + 1;
if (!gvar2->isCompiled) {
int row, col;
gvar->script->ConvertPosToRowCol(gvar->declaredAtNode->tokenPos, &row, &col);
asCString str = gvar->datatype.Format(gvar->ns);
str += " " + gvar->name;
str.Format(TXT_COMPILING_s, str.AddressOf());
WriteInfo(gvar->script->name, str, row, col, true);
str.Format(TXT_UNINITIALIZED_GLOBAL_VAR_s, gvar2->name.AddressOf());
WriteError(gvar->script->name, str, row, col);
r = -1;
}
}
}
gvar->constantValue = enumVal;
}
if (r >= 0) {
// Set the value as compiled
gvar->isCompiled = true;
compileSucceeded = true;
}
} else {
// Compile the global variable
initFunc = asNEW(asCScriptFunction)(engine, module, asFUNC_SCRIPT);
if (initFunc == 0) {
// Out of memory
return;
}
// Set the namespace that should be used for this function
initFunc->nameSpace = gvar->ns;
asCCompiler comp(engine);
int r = comp.CompileGlobalVariable(this, gvar->script, gvar->initializationNode, gvar, initFunc);
if (r >= 0) {
// Compilation succeeded
gvar->isCompiled = true;
compileSucceeded = true;
} else {
// Compilation failed
initFunc->funcType = asFUNC_DUMMY;
asDELETE(initFunc, asCScriptFunction);
initFunc = 0;
}
}
if (gvar->isCompiled) {
// Add warnings for this constant to the total build
if (numWarnings) {
currNumWarnings += numWarnings;
if (msgCallback)
outBuffer.SendToCallback(engine, &msgCallbackFunc, msgCallbackObj);
}
// Determine order of variable initializations
if (gvar->property && !gvar->isEnumValue)
initOrder.Put(gvar->property);
// Does the function contain more than just a SUSPEND followed by a RET instruction?
if (initFunc && initFunc->scriptData->byteCode.GetLength() > 2) {
// Create the init function for this variable
initFunc->id = engine->GetNextScriptFunctionId();
engine->AddScriptFunction(initFunc);
// Finalize the init function for this variable
initFunc->returnType = asCDataType::CreatePrimitive(ttVoid, false);
initFunc->scriptData->scriptSectionIdx = engine->GetScriptSectionNameIndex(gvar->script->name.AddressOf());
if (gvar->declaredAtNode) {
int row, col;
gvar->script->ConvertPosToRowCol(gvar->declaredAtNode->tokenPos, &row, &col);
initFunc->scriptData->declaredAt = (row & 0xFFFFF) | ((col & 0xFFF) << 20);
}
gvar->property->SetInitFunc(initFunc);
initFunc->ReleaseInternal();
initFunc = 0;
} else if (initFunc) {
// Destroy the function as it won't be used
initFunc->funcType = asFUNC_DUMMY;
asDELETE(initFunc, asCScriptFunction);
initFunc = 0;
}
// Convert enums to true enum values, so subsequent compilations can access it as an enum
if (gvar->isEnumValue) {
asCEnumType *enumType = CastToEnumType(gvar->datatype.GetTypeInfo());
asASSERT(NULL != enumType);
asSEnumValue *e = asNEW(asSEnumValue);
if (e == 0) {
// Out of memory
numErrors++;
return;
}
e->name = gvar->name;
e->value = int(gvar->constantValue);
enumType->enumValues.PushLast(e);
}
} else {
// Add output to final output
finalOutput.Append(outBuffer);
accumErrors += numErrors;
accumWarnings += numWarnings;
}
engine->preMessage.isSet = false;
}
if (!compileSucceeded) {
if (compilingPrimitives) {
// No more primitives could be compiled, so
// switch to compiling the complex variables
compilingPrimitives = false;
compileSucceeded = true;
} else {
// No more variables can be compiled
// Add errors and warnings to total build
currNumWarnings += accumWarnings;
currNumErrors += accumErrors;
if (msgCallback)
finalOutput.SendToCallback(engine, &msgCallbackFunc, msgCallbackObj);
}
}
}
// Restore states
engine->msgCallback = msgCallback;
engine->msgCallbackFunc = msgCallbackFunc;
engine->msgCallbackObj = msgCallbackObj;
numWarnings = currNumWarnings;
numErrors = currNumErrors;
// Set the correct order of initialization
if (numErrors == 0) {
// If the length of the arrays are not the same, then this is the compilation
// of a single variable, in which case the initialization order of the previous
// variables must be preserved.
if (module->m_scriptGlobals.GetSize() == initOrder.GetSize())
module->m_scriptGlobals.SwapWith(initOrder);
}
CleanupEnumValues();
}
void asCBuilder::CleanupEnumValues() {
// Delete the enum expressions
asCSymbolTableIterator<sGlobalVariableDescription> it = globVariables.List();
while (it) {
sGlobalVariableDescription *gvar = *it;
if (gvar->isEnumValue) {
// Remove from symboltable. This has to be done prior to freeing the memeory
globVariables.Erase(it.GetIndex());
// Destroy the gvar property
if (gvar->declaredAtNode) {
gvar->declaredAtNode->Destroy(engine);
gvar->declaredAtNode = 0;
}
if (gvar->initializationNode) {
gvar->initializationNode->Destroy(engine);
gvar->initializationNode = 0;
}
if (gvar->property) {
asDELETE(gvar->property, asCGlobalProperty);
gvar->property = 0;
}
asDELETE(gvar, sGlobalVariableDescription);
} else
it++;
}
}
int asCBuilder::GetNamespaceAndNameFromNode(asCScriptNode *n, asCScriptCode *script, asSNameSpace *implicitNs, asSNameSpace *&outNs, asCString &outName) {
// TODO: child funcdef: The node might be a snScope now
asASSERT(n->nodeType == snIdentifier);
// Get the optional scope from the node
// TODO: child funcdef: The parentType will be set if the scope is actually a type rather than a namespace
asSNameSpace *ns = GetNameSpaceFromNode(n->firstChild, script, implicitNs, 0);
if (ns == 0)
return -1;
// Get the name
asCString name(&script->code[n->lastChild->tokenPos], n->lastChild->tokenLength);
outNs = ns;
outName = name;
return 0;
}
void asCBuilder::AddInterfaceFromMixinToClass(sClassDeclaration *decl, asCScriptNode *errNode, sMixinClass *mixin) {
// Determine what interfaces that the mixin implements
asCScriptNode *node = mixin->node;
asASSERT(node->nodeType == snClass);
// Skip the name of the mixin
node = node->firstChild->next;
while (node && node->nodeType == snIdentifier) {
bool ok = true;
asSNameSpace *ns;
asCString name;
if (GetNamespaceAndNameFromNode(node, mixin->script, mixin->ns, ns, name) < 0)
ok = false;
else {
// Find the object type for the interface
asCObjectType *objType = GetObjectType(name.AddressOf(), ns);
// Check that the object type is an interface
if (objType && objType->IsInterface()) {
// Only add the interface if the class doesn't already implement it
if (!decl->typeInfo->Implements(objType))
AddInterfaceToClass(decl, errNode, objType);
} else {
WriteError(TXT_MIXIN_CLASS_CANNOT_INHERIT, mixin->script, node);
ok = false;
}
}
if (!ok) {
// Remove this node so the error isn't reported again
asCScriptNode *delNode = node;
node = node->prev;
delNode->DisconnectParent();
delNode->Destroy(engine);
}
node = node->next;
}
}
void asCBuilder::AddInterfaceToClass(sClassDeclaration *decl, asCScriptNode *errNode, asCObjectType *intfType) {
// A shared type may only implement from shared interfaces
if (decl->typeInfo->IsShared() && !intfType->IsShared()) {
asCString msg;
msg.Format(TXT_SHARED_CANNOT_IMPLEMENT_NON_SHARED_s, intfType->name.AddressOf());
WriteError(msg, decl->script, errNode);
return;
}
if (decl->isExistingShared) {
// If the class is an existing shared class, then just check if the
// interface exists in the original declaration too
if (!decl->typeInfo->Implements(intfType)) {
asCString str;
str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, decl->typeInfo->GetName());
WriteError(str, decl->script, errNode);
return;
}
} else {
// If the interface is already in the class then don't add it again
if (decl->typeInfo->Implements(intfType))
return;
// Add the interface to the class
CastToObjectType(decl->typeInfo)->interfaces.PushLast(intfType);
// Add the inherited interfaces too
// For interfaces this will be done outside to handle out-of-order declarations
if (!CastToObjectType(decl->typeInfo)->IsInterface()) {
for (asUINT n = 0; n < intfType->interfaces.GetLength(); n++)
AddInterfaceToClass(decl, errNode, intfType->interfaces[n]);
}
}
}
void asCBuilder::CompileInterfaces() {
asUINT n;
// Order the interfaces with inheritances so that the inherited
// of inherited interfaces can be added properly
for (n = 0; n < interfaceDeclarations.GetLength(); n++) {
sClassDeclaration *intfDecl = interfaceDeclarations[n];
asCObjectType *intfType = CastToObjectType(intfDecl->typeInfo);
if (intfType->interfaces.GetLength() == 0) continue;
// If any of the derived interfaces are found after this interface, then move this to the end of the list
for (asUINT m = n + 1; m < interfaceDeclarations.GetLength(); m++) {
if (intfType != interfaceDeclarations[m]->typeInfo &&
intfType->Implements(interfaceDeclarations[m]->typeInfo)) {
interfaceDeclarations.RemoveIndex(n);
interfaceDeclarations.PushLast(intfDecl);
// Decrease index so that we don't skip an entry
n--;
break;
}
}
}
// Now recursively add the additional inherited interfaces
for (n = 0; n < interfaceDeclarations.GetLength(); n++) {
sClassDeclaration *intfDecl = interfaceDeclarations[n];
if (intfDecl->isExistingShared) {
// Set the declaration as validated already, so that other
// types that contain this will accept this type
intfDecl->validState = 1;
continue;
}
asCObjectType *intfType = CastToObjectType(intfDecl->typeInfo);
// TODO: Is this really at the correct place? Hasn't the vfTableIdx already been set here?
// Co-opt the vfTableIdx value in our own methods to indicate the
// index the function should have in the table chunk for this interface.
for (asUINT d = 0; d < intfType->methods.GetLength(); d++) {
asCScriptFunction *func = GetFunctionDescription(intfType->methods[d]);
func->vfTableIdx = d;
asASSERT(func->objectType == intfType);
}
// As new interfaces will be added to the end of the list, all
// interfaces will be traversed the same as recursively
for (asUINT m = 0; m < intfType->interfaces.GetLength(); m++) {
asCObjectType *base = intfType->interfaces[m];
// Add any interfaces not already implemented
for (asUINT l = 0; l < base->interfaces.GetLength(); l++)
AddInterfaceToClass(intfDecl, intfDecl->node, base->interfaces[l]);
// Add the methods from the implemented interface
for (asUINT l = 0; l < base->methods.GetLength(); l++) {
// If the derived interface implements the same method, then don't add the base interface' method
asCScriptFunction *baseFunc = GetFunctionDescription(base->methods[l]);
asCScriptFunction *derivedFunc = 0;
bool found = false;
for (asUINT d = 0; d < intfType->methods.GetLength(); d++) {
derivedFunc = GetFunctionDescription(intfType->methods[d]);
if (derivedFunc->IsSignatureEqual(baseFunc)) {
found = true;
break;
}
}
if (!found) {
// Add the method
intfType->methods.PushLast(baseFunc->id);
baseFunc->AddRefInternal();
}
}
}
}
}
void asCBuilder::DetermineTypeRelations() {
// Determine inheritance between interfaces
for (asUINT n = 0; n < interfaceDeclarations.GetLength(); n++) {
sClassDeclaration *intfDecl = interfaceDeclarations[n];
asCObjectType *intfType = CastToObjectType(intfDecl->typeInfo);
asCScriptNode *node = intfDecl->node;
asASSERT(node && node->nodeType == snInterface);
node = node->firstChild;
// Skip the 'shared' & 'external' keywords
while (node->nodeType == snIdentifier &&
(intfDecl->script->TokenEquals(node->tokenPos, node->tokenLength, SHARED_TOKEN) ||
intfDecl->script->TokenEquals(node->tokenPos, node->tokenLength, EXTERNAL_TOKEN)))
node = node->next;
// Skip the name
node = node->next;
// Verify the inherited interfaces
while (node && node->nodeType == snIdentifier) {
asSNameSpace *ns;
asCString name;
if (GetNamespaceAndNameFromNode(node, intfDecl->script, intfType->nameSpace, ns, name) < 0) {
node = node->next;
continue;
}
// Find the object type for the interface
asCObjectType *objType = 0;
while (ns) {
objType = GetObjectType(name.AddressOf(), ns);
if (objType) break;
ns = engine->GetParentNameSpace(ns);
}
// Check that the object type is an interface
bool ok = true;
if (objType && objType->IsInterface()) {
// Check that the implemented interface is shared if the base interface is shared
if (intfType->IsShared() && !objType->IsShared()) {
asCString str;
str.Format(TXT_SHARED_CANNOT_IMPLEMENT_NON_SHARED_s, objType->GetName());
WriteError(str, intfDecl->script, node);
ok = false;
}
} else {
WriteError(TXT_INTERFACE_CAN_ONLY_IMPLEMENT_INTERFACE, intfDecl->script, node);
ok = false;
}
if (ok) {
// Make sure none of the implemented interfaces implement from this one
asCObjectType *base = objType;
while (base != 0) {
if (base == intfType) {
WriteError(TXT_CANNOT_IMPLEMENT_SELF, intfDecl->script, node);
ok = false;
break;
}
// At this point there is at most one implemented interface
if (base->interfaces.GetLength())
base = base->interfaces[0];
else
break;
}
}
if (ok)
AddInterfaceToClass(intfDecl, node, objType);
// Remove the nodes so they aren't parsed again
asCScriptNode *delNode = node;
node = node->next;
delNode->DisconnectParent();
delNode->Destroy(engine);
}
}
// Determine class inheritances and interfaces
for (asUINT n = 0; n < classDeclarations.GetLength(); n++) {
sClassDeclaration *decl = classDeclarations[n];
asCScriptCode *file = decl->script;
// Find the base class that this class inherits from
bool multipleInheritance = false;
asCScriptNode *node = decl->node->firstChild;
while (file->TokenEquals(node->tokenPos, node->tokenLength, FINAL_TOKEN) ||
file->TokenEquals(node->tokenPos, node->tokenLength, SHARED_TOKEN) ||
file->TokenEquals(node->tokenPos, node->tokenLength, ABSTRACT_TOKEN) ||
file->TokenEquals(node->tokenPos, node->tokenLength, EXTERNAL_TOKEN)) {
node = node->next;
}
// Skip the name of the class
asASSERT(node->tokenType == ttIdentifier);
node = node->next;
while (node && node->nodeType == snIdentifier) {
asSNameSpace *ns;
asCString name;
if (GetNamespaceAndNameFromNode(node, file, decl->typeInfo->nameSpace, ns, name) < 0) {
node = node->next;
continue;
}
// Find the object type for the interface
asCObjectType *objType = 0;
sMixinClass *mixin = 0;
asSNameSpace *origNs = ns;
while (ns) {
objType = GetObjectType(name.AddressOf(), ns);
if (objType == 0)
mixin = GetMixinClass(name.AddressOf(), ns);
if (objType || mixin)
break;
ns = engine->GetParentNameSpace(ns);
}
if (objType == 0 && mixin == 0) {
asCString str;
if (origNs->name == "")
str.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE_IN_GLOBAL_NS, name.AddressOf());
else
str.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE_IN_NS_s, name.AddressOf(), origNs->name.AddressOf());
WriteError(str, file, node);
} else if (mixin) {
AddInterfaceFromMixinToClass(decl, node, mixin);
} else if (!(objType->flags & asOBJ_SCRIPT_OBJECT) ||
(objType->flags & asOBJ_NOINHERIT)) {
// Either the class is not a script class or interface
// or the class has been declared as 'final'
asCString str;
str.Format(TXT_CANNOT_INHERIT_FROM_s_FINAL, objType->name.AddressOf());
WriteError(str, file, node);
} else if (objType->size != 0) {
// The class inherits from another script class
if (!decl->isExistingShared && CastToObjectType(decl->typeInfo)->derivedFrom != 0) {
if (!multipleInheritance) {
WriteError(TXT_CANNOT_INHERIT_FROM_MULTIPLE_CLASSES, file, node);
multipleInheritance = true;
}
} else {
// Make sure none of the base classes inherit from this one
asCObjectType *base = objType;
bool error = false;
while (base != 0) {
if (base == decl->typeInfo) {
WriteError(TXT_CANNOT_INHERIT_FROM_SELF, file, node);
error = true;
break;
}
base = base->derivedFrom;
}
if (!error) {
// A shared type may only inherit from other shared types
if ((decl->typeInfo->IsShared()) && !(objType->IsShared())) {
asCString msg;
msg.Format(TXT_SHARED_CANNOT_INHERIT_FROM_NON_SHARED_s, objType->name.AddressOf());
WriteError(msg, file, node);
error = true;
}
}
if (!error) {
if (decl->isExistingShared) {
// Verify that the base class is the same as the original shared type
if (CastToObjectType(decl->typeInfo)->derivedFrom != objType) {
asCString str;
str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, decl->typeInfo->GetName());
WriteError(str, file, node);
}
} else {
// Set the base class
CastToObjectType(decl->typeInfo)->derivedFrom = objType;
objType->AddRefInternal();
}
}
}
} else {
// The class implements an interface
AddInterfaceToClass(decl, node, objType);
}
node = node->next;
}
}
}
// numTempl is the number of template instances that existed in the engine before the build begun
void asCBuilder::CompileClasses(asUINT numTempl) {
asUINT n;
asCArray<sClassDeclaration *> toValidate((int)classDeclarations.GetLength());
// Order class declarations so that base classes are compiled before derived classes.
// This will allow the derived classes to copy properties and methods in the next step.
for (n = 0; n < classDeclarations.GetLength(); n++) {
sClassDeclaration *decl = classDeclarations[n];
asCObjectType *derived = CastToObjectType(decl->typeInfo);
asCObjectType *base = derived->derivedFrom;
if (base == 0) continue;
// If the base class is found after the derived class, then move the derived class to the end of the list
for (asUINT m = n + 1; m < classDeclarations.GetLength(); m++) {
sClassDeclaration *declBase = classDeclarations[m];
if (base == declBase->typeInfo) {
classDeclarations.RemoveIndex(n);
classDeclarations.PushLast(decl);
// Decrease index so that we don't skip an entry
n--;
break;
}
}
}
// Go through each of the classes and register the object type descriptions
for (n = 0; n < classDeclarations.GetLength(); n++) {
sClassDeclaration *decl = classDeclarations[n];
asCObjectType *ot = CastToObjectType(decl->typeInfo);
if (decl->isExistingShared) {
// Set the declaration as validated already, so that other
// types that contain this will accept this type
decl->validState = 1;
// We'll still validate the declaration to make sure nothing new is
// added to the shared class that wasn't there in the previous
// compilation. We do not care if something that is there in the previous
// declaration is not included in the new declaration though.
asASSERT(ot->interfaces.GetLength() == ot->interfaceVFTOffsets.GetLength());
}
// Methods included from mixin classes should take precedence over inherited methods
IncludeMethodsFromMixins(decl);
// Add all properties and methods from the base class
if (!decl->isExistingShared && ot->derivedFrom) {
asCObjectType *baseType = ot->derivedFrom;
// The derived class inherits all interfaces from the base class
for (unsigned int m = 0; m < baseType->interfaces.GetLength(); m++) {
if (!ot->Implements(baseType->interfaces[m]))
ot->interfaces.PushLast(baseType->interfaces[m]);
}
// TODO: Need to check for name conflict with new class methods
// Copy properties from base class to derived class
for (asUINT p = 0; p < baseType->properties.GetLength(); p++) {
asCObjectProperty *prop = AddPropertyToClass(decl, baseType->properties[p]->name, baseType->properties[p]->type, baseType->properties[p]->isPrivate, baseType->properties[p]->isProtected, true);
// The properties must maintain the same offset
asASSERT(prop && prop->byteOffset == baseType->properties[p]->byteOffset);
UNUSED_VAR(prop);
}
// Copy methods from base class to derived class
for (asUINT m = 0; m < baseType->methods.GetLength(); m++) {
// If the derived class implements the same method, then don't add the base class' method
asCScriptFunction *baseFunc = GetFunctionDescription(baseType->methods[m]);
asCScriptFunction *derivedFunc = 0;
bool found = false;
for (asUINT d = 0; d < ot->methods.GetLength(); d++) {
derivedFunc = GetFunctionDescription(ot->methods[d]);
if (baseFunc->name == "opConv" || baseFunc->name == "opImplConv" ||
baseFunc->name == "opCast" || baseFunc->name == "opImplCast") {
// For the opConv and opCast methods, the return type can differ if they are different methods
if (derivedFunc->name == baseFunc->name &&
derivedFunc->IsSignatureExceptNameEqual(baseFunc)) {
if (baseFunc->IsFinal()) {
asCString msg;
msg.Format(TXT_METHOD_CANNOT_OVERRIDE_s, baseFunc->GetDeclaration());
WriteError(msg, decl->script, decl->node);
}
// Move the function from the methods array to the virtualFunctionTable
ot->methods.RemoveIndex(d);
ot->virtualFunctionTable.PushLast(derivedFunc);
found = true;
break;
}
} else {
if (derivedFunc->name == baseFunc->name &&
derivedFunc->IsSignatureExceptNameAndReturnTypeEqual(baseFunc)) {
if (baseFunc->returnType != derivedFunc->returnType) {
asCString msg;
msg.Format(TXT_DERIVED_METHOD_MUST_HAVE_SAME_RETTYPE_s, baseFunc->GetDeclaration());
WriteError(msg, decl->script, decl->node);
}
if (baseFunc->IsFinal()) {
asCString msg;
msg.Format(TXT_METHOD_CANNOT_OVERRIDE_s, baseFunc->GetDeclaration());
WriteError(msg, decl->script, decl->node);
}
// Move the function from the methods array to the virtualFunctionTable
ot->methods.RemoveIndex(d);
ot->virtualFunctionTable.PushLast(derivedFunc);
found = true;
break;
}
}
}
if (!found) {
// Push the base class function on the virtual function table
ot->virtualFunctionTable.PushLast(baseType->virtualFunctionTable[m]);
baseType->virtualFunctionTable[m]->AddRefInternal();
CheckForConflictsDueToDefaultArgs(decl->script, decl->node, baseType->virtualFunctionTable[m], ot);
}
ot->methods.PushLast(baseType->methods[m]);
engine->scriptFunctions[baseType->methods[m]]->AddRefInternal();
}
}
if (!decl->isExistingShared) {
// Move this class' methods into the virtual function table
for (asUINT m = 0; m < ot->methods.GetLength(); m++) {
asCScriptFunction *func = GetFunctionDescription(ot->methods[m]);
if (func->funcType != asFUNC_VIRTUAL) {
// Move the reference from the method list to the virtual function list
ot->methods.RemoveIndex(m);
ot->virtualFunctionTable.PushLast(func);
// Substitute the function description in the method list for a virtual method
// Make sure the methods are in the same order as the virtual function table
ot->methods.PushLast(CreateVirtualFunction(func, (int)ot->virtualFunctionTable.GetLength() - 1));
m--;
}
}
// Make virtual function table chunks for each implemented interface
for (asUINT m = 0; m < ot->interfaces.GetLength(); m++) {
asCObjectType *intf = ot->interfaces[m];
// Add all the interface's functions to the virtual function table
asUINT offset = asUINT(ot->virtualFunctionTable.GetLength());
ot->interfaceVFTOffsets.PushLast(offset);
for (asUINT j = 0; j < intf->methods.GetLength(); j++) {
asCScriptFunction *intfFunc = GetFunctionDescription(intf->methods[j]);
// Only create the table for functions that are explicitly from this interface,
// inherited interface methods will be put in that interface's table.
if (intfFunc->objectType != intf)
continue;
asASSERT((asUINT)intfFunc->vfTableIdx == j);
//Find the interface function in the list of methods
asCScriptFunction *realFunc = 0;
for (asUINT p = 0; p < ot->methods.GetLength(); p++) {
asCScriptFunction *func = GetFunctionDescription(ot->methods[p]);
if (func->signatureId == intfFunc->signatureId) {
if (func->funcType == asFUNC_VIRTUAL) {
realFunc = ot->virtualFunctionTable[func->vfTableIdx];
} else {
// This should not happen, all methods were moved into the virtual table
asASSERT(false);
}
break;
}
}
// If realFunc is still null, the interface was not
// implemented and we error out later in the checks.
ot->virtualFunctionTable.PushLast(realFunc);
if (realFunc)
realFunc->AddRefInternal();
}
}
}
// Enumerate each of the declared properties
asCScriptNode *node = decl->node->firstChild->next;
// Skip list of classes and interfaces
while (node && node->nodeType == snIdentifier)
node = node->next;
while (node && node->nodeType == snDeclaration) {
asCScriptNode *nd = node->firstChild;
// Is the property declared as private or protected?
bool isPrivate = false, isProtected = false;
if (nd && nd->tokenType == ttPrivate) {
isPrivate = true;
nd = nd->next;
} else if (nd && nd->tokenType == ttProtected) {
isProtected = true;
nd = nd->next;
}
// Determine the type of the property
asCScriptCode *file = decl->script;
asCDataType dt = CreateDataTypeFromNode(nd, file, ot->nameSpace, false, ot);
if (ot->IsShared() && dt.GetTypeInfo() && !dt.GetTypeInfo()->IsShared()) {
asCString msg;
msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, dt.GetTypeInfo()->name.AddressOf());
WriteError(msg, file, node);
}
if (dt.IsReadOnly())
WriteError(TXT_PROPERTY_CANT_BE_CONST, file, node);
// Multiple properties can be declared separated by ,
nd = nd->next;
while (nd) {
asCString name(&file->code[nd->tokenPos], nd->tokenLength);
if (!decl->isExistingShared) {
CheckNameConflictMember(ot, name.AddressOf(), nd, file, true, false);
AddPropertyToClass(decl, name, dt, isPrivate, isProtected, false, file, nd);
} else {
// Verify that the property exists in the original declaration
bool found = false;
for (asUINT p = 0; p < ot->properties.GetLength(); p++) {
asCObjectProperty *prop = ot->properties[p];
if (prop->isPrivate == isPrivate &&
prop->isProtected == isProtected &&
prop->name == name &&
prop->type.IsEqualExceptRef(dt)) {
found = true;
break;
}
}
if (!found) {
asCString str;
str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, ot->GetName());
WriteError(str, file, nd);
}
}
// Skip the initialization node
if (nd->next && nd->next->nodeType != snIdentifier)
nd = nd->next;
nd = nd->next;
}
node = node->next;
}
// Add properties from included mixin classes that don't conflict with existing properties
IncludePropertiesFromMixins(decl);
if (!decl->isExistingShared)
toValidate.PushLast(decl);
asASSERT(ot->interfaces.GetLength() == ot->interfaceVFTOffsets.GetLength());
}
// TODO: Warn if a method overrides a base method without marking it as 'override'.
// It must be possible to turn off this warning through engine property.
// TODO: A base class should be able to mark a method as 'abstract'. This will
// allow a base class to provide a partial implementation, but still force
// derived classes to implement specific methods.
// Verify that all interface methods are implemented in the classes
// We do this here so the base class' methods have already been inherited
for (n = 0; n < classDeclarations.GetLength(); n++) {
sClassDeclaration *decl = classDeclarations[n];
if (decl->isExistingShared) continue;
asCObjectType *ot = CastToObjectType(decl->typeInfo);
asCArray<bool> overrideValidations(ot->GetMethodCount());
for (asUINT k = 0; k < ot->methods.GetLength(); k++)
overrideValidations.PushLast(!static_cast<asCScriptFunction *>(ot->GetMethodByIndex(k, false))->IsOverride());
for (asUINT m = 0; m < ot->interfaces.GetLength(); m++) {
asCObjectType *objType = ot->interfaces[m];
for (asUINT i = 0; i < objType->methods.GetLength(); i++) {
// Only check the interface methods that was explicitly declared in this interface
// Methods that was inherited from other interfaces will be checked in those interfaces
if (objType != engine->scriptFunctions[objType->methods[i]]->objectType)
continue;
asUINT overrideIndex;
if (!DoesMethodExist(ot, objType->methods[i], &overrideIndex)) {
asCString str;
str.Format(TXT_MISSING_IMPLEMENTATION_OF_s,
engine->GetFunctionDeclaration(objType->methods[i]).AddressOf());
WriteError(str, decl->script, decl->node);
} else
overrideValidations[overrideIndex] = true;
}
}
bool hasBaseClass = ot->derivedFrom != 0;
for (asUINT j = 0; j < overrideValidations.GetLength(); j++) {
if (!overrideValidations[j] && (!hasBaseClass || !DoesMethodExist(ot->derivedFrom, ot->methods[j]))) {
asCString msg;
msg.Format(TXT_METHOD_s_DOES_NOT_OVERRIDE, ot->GetMethodByIndex(j, false)->GetDeclaration());
WriteError(msg, decl->script, decl->node);
}
}
}
// Verify that the declared structures are valid, e.g. that the structure
// doesn't contain a member of its own type directly or indirectly
while (toValidate.GetLength() > 0) {
asUINT numClasses = (asUINT)toValidate.GetLength();
asCArray<sClassDeclaration *> toValidateNext((int)toValidate.GetLength());
while (toValidate.GetLength() > 0) {
sClassDeclaration *decl = toValidate[toValidate.GetLength() - 1];
asCObjectType *ot = CastToObjectType(decl->typeInfo);
int validState = 1;
for (n = 0; n < ot->properties.GetLength(); n++) {
// A valid structure is one that uses only primitives or other valid objects
asCObjectProperty *prop = ot->properties[n];
asCDataType dt = prop->type;
// TODO: Add this check again, once solving the issues commented below
/*
if( dt.IsTemplate() )
{
// TODO: This must verify all sub types, not just the first one
// TODO: Just because the subtype is not a handle doesn't mean the template will actually instance the object
// this it shouldn't automatically raise an error for this, e.g. weakref<Object> should be legal as member
// of the Object class
asCDataType sub = dt;
while( sub.IsTemplate() && !sub.IsObjectHandle() )
sub = sub.GetSubType();
dt = sub;
}
*/
if (dt.IsObject() && !dt.IsObjectHandle()) {
// Find the class declaration
sClassDeclaration *pdecl = 0;
for (asUINT p = 0; p < classDeclarations.GetLength(); p++) {
if (classDeclarations[p]->typeInfo == dt.GetTypeInfo()) {
pdecl = classDeclarations[p];
break;
}
}
if (pdecl) {
if (pdecl->typeInfo == decl->typeInfo) {
WriteError(TXT_ILLEGAL_MEMBER_TYPE, decl->script, decl->node);
validState = 2;
break;
} else if (pdecl->validState != 1) {
validState = pdecl->validState;
break;
}
}
}
}
if (validState == 1) {
decl->validState = 1;
toValidate.PopLast();
} else if (validState == 2) {
decl->validState = 2;
toValidate.PopLast();
} else {
toValidateNext.PushLast(toValidate.PopLast());
}
}
toValidate = toValidateNext;
toValidateNext.SetLength(0);
if (numClasses == toValidate.GetLength()) {
WriteError(TXT_ILLEGAL_MEMBER_TYPE, toValidate[0]->script, toValidate[0]->node);
break;
}
}
if (numErrors > 0) return;
// Verify which script classes can really form circular references, and mark only those as garbage collected.
// This must be done in the correct order, so that a class that contains another class isn't needlessly marked
// as garbage collected, just because the contained class was evaluated afterwards.
// TODO: runtime optimize: This algorithm can be further improved by checking the types that inherits from
// a base class. If the base class is not shared all the classes that derive from it
// are known at compile time, and can thus be checked for potential circular references too.
//
// Observe, that doing this would conflict with another potential future feature, which is to
// allow incremental builds, i.e. allow application to add or replace classes in an
// existing module. However, the applications that want to use that should use a special
// build flag to not finalize the module.
asCArray<asCObjectType *> typesToValidate;
for (n = 0; n < classDeclarations.GetLength(); n++) {
// Existing shared classes won't need evaluating, nor interfaces
sClassDeclaration *decl = classDeclarations[n];
if (decl->isExistingShared) continue;
asCObjectType *ot = CastToObjectType(decl->typeInfo);
if (ot->IsInterface()) continue;
typesToValidate.PushLast(ot);
}
asUINT numReevaluations = 0;
while (typesToValidate.GetLength()) {
if (numReevaluations > typesToValidate.GetLength()) {
// No types could be completely evaluated in the last iteration so
// we consider the remaining types in the array as garbage collected
break;
}
asCObjectType *type = typesToValidate[0];
typesToValidate.RemoveIndex(0);
// If the type inherits from another type that is yet to be validated, then reinsert it at the end
if (type->derivedFrom && typesToValidate.Exists(type->derivedFrom)) {
typesToValidate.PushLast(type);
numReevaluations++;
continue;
}
// If the type inherits from a known garbage collected type, then this type must also be garbage collected
if (type->derivedFrom && (type->derivedFrom->flags & asOBJ_GC)) {
type->flags |= asOBJ_GC;
continue;
}
// Evaluate template instances (silently) before verifying each of the classes, since it is possible that
// a class will be marked as non-garbage collected, which in turn will mark the template instance that uses
// it as non-garbage collected, which in turn means the class that contains the array also do not have to be
// garbage collected
EvaluateTemplateInstances(numTempl, true);
// Is there some path in which this structure is involved in circular references?
// If the type contains a member of a type that is yet to be validated, then reinsert it at the end
bool mustReevaluate = false;
bool gc = false;
for (asUINT p = 0; p < type->properties.GetLength(); p++) {
asCDataType dt = type->properties[p]->type;
if (dt.IsFuncdef()) {
// If a class holds a function pointer as member then the class must be garbage collected as the
// function pointer can form circular references with the class through use of a delegate. Example:
//
// class A { B @b; void f(); }
// class B { F @f; }
// funcdef void F();
//
// A a;
// @a.b = B(); // instance of A refers to instance of B
// @a.b.f = F(a.f); // instance of B refers to delegate that refers to instance of A
//
gc = true;
break;
}
if (!dt.IsObject())
continue;
if (typesToValidate.Exists(CastToObjectType(dt.GetTypeInfo())))
mustReevaluate = true;
else {
if (dt.IsTemplate()) {
// Check if any of the subtypes are yet to be evaluated
bool skip = false;
for (asUINT s = 0; s < dt.GetTypeInfo()->GetSubTypeCount(); s++) {
asCObjectType *t = reinterpret_cast<asCObjectType *>(dt.GetTypeInfo()->GetSubType(s));
if (typesToValidate.Exists(t)) {
mustReevaluate = true;
skip = true;
break;
}
}
if (skip)
continue;
}
if (dt.IsObjectHandle()) {
// If it is known that the handle can't be involved in a circular reference
// then this object doesn't need to be marked as garbage collected.
asCObjectType *prop = CastToObjectType(dt.GetTypeInfo());
if (prop->flags & asOBJ_SCRIPT_OBJECT) {
// For script objects, treat non-final classes as if they can contain references
// as it is not known what derived classes might do. For final types, check all
// properties to determine if any of those can cause a circular reference with this
// class.
if (prop->flags & asOBJ_NOINHERIT) {
for (asUINT sp = 0; sp < prop->properties.GetLength(); sp++) {
asCDataType sdt = prop->properties[sp]->type;
if (sdt.IsObject()) {
if (sdt.IsObjectHandle()) {
// TODO: runtime optimize: If the handle is again to a final class, then we can recursively check if the circular reference can occur
if (sdt.GetTypeInfo()->flags & (asOBJ_SCRIPT_OBJECT | asOBJ_GC)) {
gc = true;
break;
}
} else if (sdt.GetTypeInfo()->flags & asOBJ_GC) {
// TODO: runtime optimize: Just because the member type is a potential circle doesn't mean that this one is.
// Only if the object is of a type that can reference this type, either directly or indirectly
gc = true;
break;
}
}
}
if (gc)
break;
} else {
// Assume it is garbage collected as it is not known at compile time what might inherit from this type
gc = true;
break;
}
} else if (prop->flags & asOBJ_GC) {
// If a type is not a script object, adopt its GC flag
// TODO: runtime optimize: Just because an application registered class is garbage collected, doesn't mean it
// can form a circular reference with this script class. Perhaps need a flag to tell
// if the script classes that contains the type should be garbage collected or not.
gc = true;
break;
}
} else if (dt.GetTypeInfo()->flags & asOBJ_GC) {
// TODO: runtime optimize: Just because the member type is a potential circle doesn't mean that this one is.
// Only if the object is of a type that can reference this type, either directly or indirectly
gc = true;
break;
}
}
}
// If the class wasn't found to require garbage collection, but it
// contains another type that has yet to be evaluated then it must be
// re-evaluated.
if (!gc && mustReevaluate) {
typesToValidate.PushLast(type);
numReevaluations++;
continue;
}
// Update the flag in the object type
if (gc)
type->flags |= asOBJ_GC;
else
type->flags &= ~asOBJ_GC;
// Reset the counter
numReevaluations = 0;
}
}
void asCBuilder::IncludeMethodsFromMixins(sClassDeclaration *decl) {
asCScriptNode *node = decl->node->firstChild;
// Skip the class attributes
while (node->nodeType == snIdentifier &&
!decl->script->TokenEquals(node->tokenPos, node->tokenLength, decl->name.AddressOf()))
node = node->next;
// Skip the name of the class
node = node->next;
// Find the included mixin classes
while (node && node->nodeType == snIdentifier) {
asSNameSpace *ns;
asCString name;
if (GetNamespaceAndNameFromNode(node, decl->script, decl->typeInfo->nameSpace, ns, name) < 0) {
node = node->next;
continue;
}
sMixinClass *mixin = 0;
while (ns) {
// Need to make sure the name is not an object type
asCObjectType *objType = GetObjectType(name.AddressOf(), ns);
if (objType == 0)
mixin = GetMixinClass(name.AddressOf(), ns);
if (objType || mixin)
break;
ns = engine->GetParentNameSpace(ns);
}
if (mixin) {
// Find methods from mixin declaration
asCScriptNode *n = mixin->node->firstChild;
// Skip to the member declarations
// Possible keywords 'final' and 'shared' are removed in RegisterMixinClass so we don't need to worry about those here
while (n && n->nodeType == snIdentifier)
n = n->next;
// Add methods from the mixin that are not already existing in the class
while (n) {
if (n->nodeType == snFunction) {
// Instead of disconnecting the node, we need to clone it, otherwise other
// classes that include the same mixin will not see the methods
asCScriptNode *copy = n->CreateCopy(engine);
// Register the method, but only if it doesn't already exist in the class
RegisterScriptFunctionFromNode(copy, mixin->script, CastToObjectType(decl->typeInfo), false, false, mixin->ns, false, true);
} else if (n->nodeType == snVirtualProperty) {
// TODO: mixin: Support virtual properties too
WriteError("The virtual property syntax is currently not supported for mixin classes", mixin->script, n);
//RegisterVirtualProperty(node, decl->script, decl->objType, false, false);
}
n = n->next;
}
}
node = node->next;
}
}
void asCBuilder::IncludePropertiesFromMixins(sClassDeclaration *decl) {
asCScriptNode *node = decl->node->firstChild;
// Skip the class attributes
while (node->nodeType == snIdentifier &&
!decl->script->TokenEquals(node->tokenPos, node->tokenLength, decl->name.AddressOf()))
node = node->next;
// Skip the name of the class
node = node->next;
// Find the included mixin classes
while (node && node->nodeType == snIdentifier) {
asSNameSpace *ns;
asCString name;
if (GetNamespaceAndNameFromNode(node, decl->script, decl->typeInfo->nameSpace, ns, name) < 0) {
node = node->next;
continue;
}
sMixinClass *mixin = 0;
while (ns) {
// Need to make sure the name is not an object type
asCObjectType *objType = GetObjectType(name.AddressOf(), ns);
if (objType == 0)
mixin = GetMixinClass(name.AddressOf(), ns);
if (objType || mixin)
break;
ns = engine->GetParentNameSpace(ns);
}
if (mixin) {
// Find properties from mixin declaration
asCScriptNode *n = mixin->node->firstChild;
// Skip to the member declarations
// Possible keywords 'final' and 'shared' are removed in RegisterMixinClass so we don't need to worry about those here
while (n && n->nodeType == snIdentifier)
n = n->next;
// Add properties from the mixin that are not already existing in the class
while (n) {
if (n->nodeType == snDeclaration) {
asCScriptNode *n2 = n->firstChild;
bool isPrivate = false, isProtected = false;
if (n2 && n2->tokenType == ttPrivate) {
isPrivate = true;
n2 = n2->next;
} else if (n2 && n2->tokenType == ttProtected) {
isProtected = true;
n2 = n2->next;
}
asCScriptCode *file = mixin->script;
asCDataType dt = CreateDataTypeFromNode(n2, file, mixin->ns);
if (decl->typeInfo->IsShared() && dt.GetTypeInfo() && !dt.GetTypeInfo()->IsShared()) {
asCString msg;
msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, dt.GetTypeInfo()->name.AddressOf());
WriteError(msg, file, n);
WriteInfo(TXT_WHILE_INCLUDING_MIXIN, decl->script, node);
}
if (dt.IsReadOnly())
WriteError(TXT_PROPERTY_CANT_BE_CONST, file, n);
n2 = n2->next;
while (n2) {
name.Assign(&file->code[n2->tokenPos], n2->tokenLength);
// Add the property only if it doesn't already exist in the class
bool exists = false;
asCObjectType *ot = CastToObjectType(decl->typeInfo);
for (asUINT p = 0; p < ot->properties.GetLength(); p++)
if (ot->properties[p]->name == name) {
exists = true;
break;
}
if (!exists) {
if (!decl->isExistingShared) {
// It must not conflict with the name of methods
int r = CheckNameConflictMember(ot, name.AddressOf(), n2, file, true, false);
if (r < 0)
WriteInfo(TXT_WHILE_INCLUDING_MIXIN, decl->script, node);
AddPropertyToClass(decl, name, dt, isPrivate, isProtected, false, file, n2);
} else {
// Verify that the property exists in the original declaration
bool found = false;
for (asUINT p = 0; p < ot->properties.GetLength(); p++) {
asCObjectProperty *prop = ot->properties[p];
if (prop->isPrivate == isPrivate &&
prop->isProtected == isProtected &&
prop->name == name &&
prop->type == dt) {
found = true;
break;
}
}
if (!found) {
asCString str;
str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, ot->GetName());
WriteError(str, decl->script, decl->node);
WriteInfo(TXT_WHILE_INCLUDING_MIXIN, decl->script, node);
}
}
}
// Skip the initialization expression
if (n2->next && n2->next->nodeType != snIdentifier)
n2 = n2->next;
n2 = n2->next;
}
}
n = n->next;
}
}
node = node->next;
}
}
int asCBuilder::CreateVirtualFunction(asCScriptFunction *func, int idx) {
asCScriptFunction *vf = asNEW(asCScriptFunction)(engine, module, asFUNC_VIRTUAL);
if (vf == 0)
return asOUT_OF_MEMORY;
vf->name = func->name;
vf->nameSpace = func->nameSpace;
vf->returnType = func->returnType;
vf->parameterTypes = func->parameterTypes;
vf->inOutFlags = func->inOutFlags;
vf->id = engine->GetNextScriptFunctionId();
vf->objectType = func->objectType;
vf->objectType->AddRefInternal();
vf->signatureId = func->signatureId;
vf->vfTableIdx = idx;
vf->traits = func->traits;
// Clear the shared trait since the virtual function should not have that
vf->SetShared(false);
// It is not necessary to copy the default args, as they have no meaning in the virtual function
module->AddScriptFunction(vf);
// Add a dummy to the builder so that it doesn't mix up function ids
functions.PushLast(0);
return vf->id;
}
asCObjectProperty *asCBuilder::AddPropertyToClass(sClassDeclaration *decl, const asCString &name, const asCDataType &dt, bool isPrivate, bool isProtected, bool isInherited, asCScriptCode *file, asCScriptNode *node) {
if (node) {
asASSERT(!isInherited);
// Check if the property is allowed
if (!dt.CanBeInstantiated()) {
if (file && node) {
asCString str;
if (dt.IsAbstractClass())
str.Format(TXT_ABSTRACT_CLASS_s_CANNOT_BE_INSTANTIATED, dt.Format(decl->typeInfo->nameSpace).AddressOf());
else if (dt.IsInterface())
str.Format(TXT_INTERFACE_s_CANNOT_BE_INSTANTIATED, dt.Format(decl->typeInfo->nameSpace).AddressOf());
else
// TODO: Improve error message to explain why
str.Format(TXT_DATA_TYPE_CANT_BE_s, dt.Format(decl->typeInfo->nameSpace).AddressOf());
WriteError(str, file, node);
}
return 0;
}
// Register the initialization expression (if any) to be compiled later
asCScriptNode *declNode = node;
asCScriptNode *initNode = 0;
if (node->next && node->next->nodeType != snIdentifier) {
asASSERT(node->next->nodeType == snAssignment);
initNode = node->next;
}
sPropertyInitializer p(name, declNode, initNode, file);
decl->propInits.PushLast(p);
} else {
// If the declaration node is not given, then
// this property is inherited from a base class
asASSERT(isInherited);
}
// Add the property to the object type
return CastToObjectType(decl->typeInfo)->AddPropertyToClass(name, dt, isPrivate, isProtected, isInherited);
}
bool asCBuilder::DoesMethodExist(asCObjectType *objType, int methodId, asUINT *methodIndex) {
asCScriptFunction *method = GetFunctionDescription(methodId);
for (asUINT n = 0; n < objType->methods.GetLength(); n++) {
asCScriptFunction *m = GetFunctionDescription(objType->methods[n]);
if (m->name != method->name) continue;
if (m->returnType != method->returnType) continue;
if (m->IsReadOnly() != method->IsReadOnly()) continue;
if (m->parameterTypes != method->parameterTypes) continue;
if (m->inOutFlags != method->inOutFlags) continue;
if (methodIndex)
*methodIndex = n;
return true;
}
return false;
}
void asCBuilder::AddDefaultConstructor(asCObjectType *objType, asCScriptCode *file) {
int funcId = engine->GetNextScriptFunctionId();
asCDataType returnType = asCDataType::CreatePrimitive(ttVoid, false);
asCArray<asCDataType> parameterTypes;
asCArray<asETypeModifiers> inOutFlags;
asCArray<asCString *> defaultArgs;
asCArray<asCString> parameterNames;
// Add the script function
// TODO: declaredAt should be set to where the class has been declared
module->AddScriptFunction(file->idx, 0, funcId, objType->name, returnType, parameterTypes, parameterNames, inOutFlags, defaultArgs, false, objType, false, asSFunctionTraits(), objType->nameSpace);
// Set it as default constructor
if (objType->beh.construct)
engine->scriptFunctions[objType->beh.construct]->ReleaseInternal();
objType->beh.construct = funcId;
objType->beh.constructors[0] = funcId;
engine->scriptFunctions[funcId]->AddRefInternal();
// The bytecode for the default constructor will be generated
// only after the potential inheritance has been established
sFunctionDescription *func = asNEW(sFunctionDescription);
if (func == 0) {
// Out of memory
return;
}
functions.PushLast(func);
func->script = file;
func->node = 0;
func->name = objType->name;
func->objType = objType;
func->funcId = funcId;
func->isExistingShared = false;
// Add a default factory as well
funcId = engine->GetNextScriptFunctionId();
if (objType->beh.factory)
engine->scriptFunctions[objType->beh.factory]->ReleaseInternal();
objType->beh.factory = funcId;
objType->beh.factories[0] = funcId;
returnType = asCDataType::CreateObjectHandle(objType, false);
// TODO: should be the same as the constructor
module->AddScriptFunction(file->idx, 0, funcId, objType->name, returnType, parameterTypes, parameterNames, inOutFlags, defaultArgs, false);
functions.PushLast(0);
asCCompiler compiler(engine);
compiler.CompileFactory(this, file, engine->scriptFunctions[funcId]);
engine->scriptFunctions[funcId]->AddRefInternal();
// If the object is shared, then the factory must also be marked as shared
if (objType->flags & asOBJ_SHARED)
engine->scriptFunctions[funcId]->SetShared(true);
}
int asCBuilder::RegisterEnum(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns) {
// Is it a shared enum?
bool isShared = false;
bool isExternal = false;
asCEnumType *existingSharedType = 0;
asCScriptNode *tmp = node->firstChild;
while (tmp->nodeType == snIdentifier) {
if (file->TokenEquals(tmp->tokenPos, tmp->tokenLength, SHARED_TOKEN))
isShared = true;
else if (file->TokenEquals(tmp->tokenPos, tmp->tokenLength, EXTERNAL_TOKEN))
isExternal = true;
else
break;
tmp = tmp->next;
}
// Grab the name of the enumeration
asCString name;
asASSERT(snDataType == tmp->nodeType);
asASSERT(snIdentifier == tmp->firstChild->nodeType);
name.Assign(&file->code[tmp->firstChild->tokenPos], tmp->firstChild->tokenLength);
if (isShared) {
// Look for a pre-existing shared enum with the same signature
for (asUINT n = 0; n < engine->sharedScriptTypes.GetLength(); n++) {
asCTypeInfo *o = engine->sharedScriptTypes[n];
if (o &&
o->IsShared() &&
(o->flags & asOBJ_ENUM) &&
o->name == name &&
o->nameSpace == ns) {
existingSharedType = CastToEnumType(o);
break;
}
}
}
// If the enum was declared as external then it must have been compiled in a different module first
if (isExternal && existingSharedType == 0) {
asCString str;
str.Format(TXT_EXTERNAL_SHARED_s_NOT_FOUND, name.AddressOf());
WriteError(str, file, tmp);
}
// Remember if the type was declared as external so the saved bytecode can be flagged accordingly
if (isExternal && existingSharedType)
module->m_externalTypes.PushLast(existingSharedType);
// Check the name and add the enum
int r = CheckNameConflict(name.AddressOf(), tmp->firstChild, file, ns, true, false);
if (asSUCCESS == r) {
asCEnumType *st;
if (existingSharedType) {
st = existingSharedType;
st->AddRefInternal();
} else {
st = asNEW(asCEnumType)(engine);
if (st == 0)
return asOUT_OF_MEMORY;
st->flags = asOBJ_ENUM;
if (isShared)
st->flags |= asOBJ_SHARED;
st->size = 4;
st->name = name;
st->nameSpace = ns;
st->module = module;
}
module->AddEnumType(st);
if (!existingSharedType && isShared) {
engine->sharedScriptTypes.PushLast(st);
st->AddRefInternal();
}
// Store the location of this declaration for reference in name collisions
sClassDeclaration *decl = asNEW(sClassDeclaration);
if (decl == 0)
return asOUT_OF_MEMORY;
decl->name = name;
decl->script = file;
decl->typeInfo = st;
namedTypeDeclarations.PushLast(decl);
asCDataType type = CreateDataTypeFromNode(tmp, file, ns);
asASSERT(!type.IsReference());
// External shared enums must not redeclare the enum values
if (isExternal && (tmp->next == 0 || tmp->next->tokenType != ttEndStatement)) {
asCString str;
str.Format(TXT_EXTERNAL_SHARED_s_CANNOT_REDEF, name.AddressOf());
WriteError(str, file, tmp);
} else if (!isExternal && tmp->next && tmp->next->tokenType == ttEndStatement) {
asCString str;
str.Format(TXT_MISSING_DEFINITION_OF_s, name.AddressOf());
WriteError(str, file, tmp);
}
// Register the enum values
tmp = tmp->next;
while (tmp && tmp->nodeType == snIdentifier) {
name.Assign(&file->code[tmp->tokenPos], tmp->tokenLength);
if (existingSharedType) {
// If this is a pre-existent shared enum, then just double check
// that the value is already defined in the original declaration
bool found = false;
for (asUINT n = 0; n < st->enumValues.GetLength(); n++)
if (st->enumValues[n]->name == name) {
found = true;
break;
}
if (!found) {
asCString str;
str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, st->GetName());
WriteError(str, file, tmp);
break;
}
tmp = tmp->next;
if (tmp && tmp->nodeType == snAssignment)
tmp = tmp->next;
continue;
} else {
// Check for name conflict errors with other values in the enum
if (globVariables.GetFirst(ns, name, asCCompGlobVarType(type))) {
asCString str;
str.Format(TXT_NAME_CONFLICT_s_ALREADY_USED, name.AddressOf());
WriteError(str, file, tmp);
tmp = tmp->next;
if (tmp && tmp->nodeType == snAssignment)
tmp = tmp->next;
continue;
}
// Check for assignment
asCScriptNode *asnNode = tmp->next;
if (asnNode && snAssignment == asnNode->nodeType)
asnNode->DisconnectParent();
else
asnNode = 0;
// Create the global variable description so the enum value can be evaluated
sGlobalVariableDescription *gvar = asNEW(sGlobalVariableDescription);
if (gvar == 0)
return asOUT_OF_MEMORY;
gvar->script = file;
gvar->declaredAtNode = tmp;
tmp = tmp->next;
gvar->declaredAtNode->DisconnectParent();
gvar->initializationNode = asnNode;
gvar->name = name;
gvar->datatype = type;
gvar->ns = ns;
// No need to allocate space on the global memory stack since the values are stored in the asCObjectType
// Set the index to a negative to allow compiler to diferentiate from ordinary global var when compiling the initialization
gvar->index = -1;
gvar->isCompiled = false;
gvar->isPureConstant = true;
gvar->isEnumValue = true;
gvar->constantValue = 0xdeadbeef;
// Allocate dummy property so we can compile the value.
// This will be removed later on so we don't add it to the engine.
gvar->property = asNEW(asCGlobalProperty);
if (gvar->property == 0)
return asOUT_OF_MEMORY;
gvar->property->name = name;
gvar->property->nameSpace = ns;
gvar->property->type = gvar->datatype;
gvar->property->id = 0;
globVariables.Put(gvar);
}
}
}
node->Destroy(engine);
return r;
}
int asCBuilder::RegisterTypedef(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns) {
// Get the native data type
asCScriptNode *tmp = node->firstChild;
asASSERT(NULL != tmp && snDataType == tmp->nodeType);
asCDataType dataType;
dataType.CreatePrimitive(tmp->tokenType, false);
dataType.SetTokenType(tmp->tokenType);
tmp = tmp->next;
// Grab the name of the typedef
asASSERT(NULL != tmp && NULL == tmp->next);
asCString name;
name.Assign(&file->code[tmp->tokenPos], tmp->tokenLength);
// If the name is not already in use add it
int r = CheckNameConflict(name.AddressOf(), tmp, file, ns, true, false);
asCTypedefType *st = 0;
if (asSUCCESS == r) {
// Create the new type
st = asNEW(asCTypedefType)(engine);
if (st == 0)
r = asOUT_OF_MEMORY;
}
if (asSUCCESS == r) {
st->flags = asOBJ_TYPEDEF;
st->size = dataType.GetSizeInMemoryBytes();
st->name = name;
st->nameSpace = ns;
st->aliasForType = dataType;
st->module = module;
module->AddTypeDef(st);
// Store the location of this declaration for reference in name collisions
sClassDeclaration *decl = asNEW(sClassDeclaration);
if (decl == 0)
r = asOUT_OF_MEMORY;
else {
decl->name = name;
decl->script = file;
decl->typeInfo = st;
namedTypeDeclarations.PushLast(decl);
}
}
node->Destroy(engine);
return r;
}
void asCBuilder::GetParsedFunctionDetails(asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, asCString &name, asCDataType &returnType, asCArray<asCString> ¶meterNames, asCArray<asCDataType> ¶meterTypes, asCArray<asETypeModifiers> &inOutFlags, asCArray<asCString *> &defaultArgs, asSFunctionTraits &funcTraits, asSNameSpace *implicitNamespace) {
node = node->firstChild;
// Is the function shared?
funcTraits.SetTrait(asTRAIT_SHARED, false);
funcTraits.SetTrait(asTRAIT_EXTERNAL, false);
while (node->tokenType == ttIdentifier) {
if (file->TokenEquals(node->tokenPos, node->tokenLength, SHARED_TOKEN))
funcTraits.SetTrait(asTRAIT_SHARED, true);
else if (file->TokenEquals(node->tokenPos, node->tokenLength, EXTERNAL_TOKEN))
funcTraits.SetTrait(asTRAIT_EXTERNAL, true);
else
break;
node = node->next;
}
// Is the function a private or protected class method?
funcTraits.SetTrait(asTRAIT_PRIVATE, false);
funcTraits.SetTrait(asTRAIT_PROTECTED, false);
if (node->tokenType == ttPrivate) {
funcTraits.SetTrait(asTRAIT_PRIVATE, true);
node = node->next;
} else if (node->tokenType == ttProtected) {
funcTraits.SetTrait(asTRAIT_PROTECTED, true);
node = node->next;
}
// Find the name
funcTraits.SetTrait(asTRAIT_CONSTRUCTOR, false);
funcTraits.SetTrait(asTRAIT_DESTRUCTOR, false);
asCScriptNode *n = 0;
if (node->nodeType == snDataType)
n = node->next->next;
else {
// If the first node is a ~ token, then we know it is a destructor
if (node->tokenType == ttBitNot) {
n = node->next;
funcTraits.SetTrait(asTRAIT_DESTRUCTOR, true);
} else {
n = node;
funcTraits.SetTrait(asTRAIT_CONSTRUCTOR, true);
}
}
name.Assign(&file->code[n->tokenPos], n->tokenLength);
if (!funcTraits.GetTrait(asTRAIT_CONSTRUCTOR) && !funcTraits.GetTrait(asTRAIT_DESTRUCTOR)) {
returnType = CreateDataTypeFromNode(node, file, implicitNamespace, false, objType);
returnType = ModifyDataTypeFromNode(returnType, node->next, file, 0, 0);
if (engine->ep.disallowValueAssignForRefType &&
returnType.GetTypeInfo() &&
(returnType.GetTypeInfo()->flags & asOBJ_REF) &&
!(returnType.GetTypeInfo()->flags & asOBJ_SCOPED) &&
!returnType.IsReference() &&
!returnType.IsObjectHandle()) {
WriteError(TXT_REF_TYPE_CANT_BE_RETURNED_BY_VAL, file, node);
}
} else
returnType = asCDataType::CreatePrimitive(ttVoid, false);
funcTraits.SetTrait(asTRAIT_CONST, false);
funcTraits.SetTrait(asTRAIT_FINAL, false);
funcTraits.SetTrait(asTRAIT_OVERRIDE, false);
funcTraits.SetTrait(asTRAIT_EXPLICIT, false);
funcTraits.SetTrait(asTRAIT_PROPERTY, false);
if (n->next->next) {
asCScriptNode *decorator = n->next->next;
// Is this a const method?
if (objType && decorator->tokenType == ttConst) {
funcTraits.SetTrait(asTRAIT_CONST, true);
decorator = decorator->next;
}
while (decorator && decorator->tokenType == ttIdentifier) {
if (objType && file->TokenEquals(decorator->tokenPos, decorator->tokenLength, FINAL_TOKEN))
funcTraits.SetTrait(asTRAIT_FINAL, true);
else if (objType && file->TokenEquals(decorator->tokenPos, decorator->tokenLength, OVERRIDE_TOKEN))
funcTraits.SetTrait(asTRAIT_OVERRIDE, true);
else if (objType && file->TokenEquals(decorator->tokenPos, decorator->tokenLength, EXPLICIT_TOKEN))
funcTraits.SetTrait(asTRAIT_EXPLICIT, true);
else if (file->TokenEquals(decorator->tokenPos, decorator->tokenLength, PROPERTY_TOKEN))
funcTraits.SetTrait(asTRAIT_PROPERTY, true);
else {
asCString msg(&file->code[decorator->tokenPos], decorator->tokenLength);
msg.Format(TXT_UNEXPECTED_TOKEN_s, msg.AddressOf());
WriteError(msg.AddressOf(), file, decorator);
}
decorator = decorator->next;
}
}
// Count the number of parameters
int count = 0;
asCScriptNode *c = n->next->firstChild;
while (c) {
count++;
c = c->next->next;
if (c && c->nodeType == snIdentifier)
c = c->next;
if (c && c->nodeType == snExpression)
c = c->next;
}
// Get the parameter types
parameterNames.Allocate(count, false);
parameterTypes.Allocate(count, false);
inOutFlags.Allocate(count, false);
defaultArgs.Allocate(count, false);
n = n->next->firstChild;
while (n) {
asETypeModifiers inOutFlag;
asCDataType type = CreateDataTypeFromNode(n, file, implicitNamespace, false, objType);
type = ModifyDataTypeFromNode(type, n->next, file, &inOutFlag, 0);
if (engine->ep.disallowValueAssignForRefType &&
type.GetTypeInfo() &&
(type.GetTypeInfo()->flags & asOBJ_REF) &&
!(type.GetTypeInfo()->flags & asOBJ_SCOPED) &&
!type.IsReference() &&
!type.IsObjectHandle()) {
WriteError(TXT_REF_TYPE_CANT_BE_PASSED_BY_VAL, file, node);
}
// Store the parameter type
parameterTypes.PushLast(type);
inOutFlags.PushLast(inOutFlag);
// Move to next parameter
n = n->next->next;
if (n && n->nodeType == snIdentifier) {
asCString paramName(&file->code[n->tokenPos], n->tokenLength);
parameterNames.PushLast(paramName);
n = n->next;
} else {
// No name was given for the parameter
parameterNames.PushLast(asCString());
}
if (n && n->nodeType == snExpression) {
// Strip out white space and comments to better share the string
asCString *defaultArgStr = asNEW(asCString);
if (defaultArgStr)
*defaultArgStr = GetCleanExpressionString(n, file);
defaultArgs.PushLast(defaultArgStr);
n = n->next;
} else
defaultArgs.PushLast(0);
}
}
#endif
asCString asCBuilder::GetCleanExpressionString(asCScriptNode *node, asCScriptCode *file) {
asASSERT(node && node->nodeType == snExpression);
asCString str;
str.Assign(file->code + node->tokenPos, node->tokenLength);
asCString cleanStr;
for (asUINT n = 0; n < str.GetLength();) {
asUINT len = 0;
asETokenClass tok = engine->ParseToken(str.AddressOf() + n, str.GetLength() - n, &len);
if (tok != asTC_COMMENT && tok != asTC_WHITESPACE) {
if (cleanStr.GetLength()) cleanStr += " ";
cleanStr.Concatenate(str.AddressOf() + n, len);
}
n += len;
}
return cleanStr;
}
#ifndef AS_NO_COMPILER
int asCBuilder::RegisterScriptFunctionFromNode(asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, bool isInterface, bool isGlobalFunction, asSNameSpace *ns, bool isExistingShared, bool isMixin) {
asCString name;
asCDataType returnType;
asCArray<asCString> parameterNames;
asCArray<asCDataType> parameterTypes;
asCArray<asETypeModifiers> inOutFlags;
asCArray<asCString *> defaultArgs;
asSFunctionTraits funcTraits;
asASSERT((objType && ns == 0) || isGlobalFunction || isMixin);
// Set the default namespace
if (ns == 0) {
if (objType)
ns = objType->nameSpace;
else
ns = engine->nameSpaces[0];
}
GetParsedFunctionDetails(node, file, objType, name, returnType, parameterNames, parameterTypes, inOutFlags, defaultArgs, funcTraits, ns);
return RegisterScriptFunction(node, file, objType, isInterface, isGlobalFunction, ns, isExistingShared, isMixin, name, returnType, parameterNames, parameterTypes, inOutFlags, defaultArgs, funcTraits);
}
asCScriptFunction *asCBuilder::RegisterLambda(asCScriptNode *node, asCScriptCode *file, asCScriptFunction *funcDef, const asCString &name, asSNameSpace *ns, bool isShared) {
// Get the parameter names from the node
asCArray<asCString> parameterNames;
asCArray<asCString *> defaultArgs;
asCScriptNode *args = node->firstChild;
while (args && args->nodeType != snStatementBlock) {
if (args->nodeType == snIdentifier) {
asCString argName;
argName.Assign(&file->code[args->tokenPos], args->tokenLength);
parameterNames.PushLast(argName);
defaultArgs.PushLast(0);
}
args = args->next;
}
// The statement block for the function must be disconnected, as the builder is going to be the owner of it
args->DisconnectParent();
// Get the return and parameter types from the funcDef
asCString funcName = name;
asSFunctionTraits traits;
traits.SetTrait(asTRAIT_SHARED, isShared);
int r = RegisterScriptFunction(args, file, 0, 0, true, ns, false, false, funcName, funcDef->returnType, parameterNames, funcDef->parameterTypes, funcDef->inOutFlags, defaultArgs, traits);
if (r < 0)
return 0;
// Return the function that was just created (but that will be compiled later)
return engine->scriptFunctions[functions[functions.GetLength() - 1]->funcId];
}
int asCBuilder::RegisterScriptFunction(asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, bool isInterface, bool isGlobalFunction, asSNameSpace *ns, bool isExistingShared, bool isMixin, asCString &name, asCDataType &returnType, asCArray<asCString> ¶meterNames, asCArray<asCDataType> ¶meterTypes, asCArray<asETypeModifiers> &inOutFlags, asCArray<asCString *> &defaultArgs, asSFunctionTraits funcTraits) {
// Determine default namespace if not specified
if (ns == 0) {
if (objType)
ns = objType->nameSpace;
else
ns = engine->nameSpaces[0];
}
if (isExistingShared) {
asASSERT(objType);
// Should validate that the function really exists in the class/interface
bool found = false;
if (funcTraits.GetTrait(asTRAIT_CONSTRUCTOR) || funcTraits.GetTrait(asTRAIT_DESTRUCTOR)) {
// TODO: shared: Should check the existance of these too
found = true;
} else {
for (asUINT n = 0; n < objType->methods.GetLength(); n++) {
asCScriptFunction *func = engine->scriptFunctions[objType->methods[n]];
if (func->name == name &&
func->IsSignatureExceptNameEqual(returnType, parameterTypes, inOutFlags, objType, funcTraits.GetTrait(asTRAIT_CONST))) {
// Add the shared function in this module too
module->AddScriptFunction(func);
found = true;
break;
}
}
}
if (!found) {
asCString str;
str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, objType->GetName());
WriteError(str, file, node);
}
// Free the default args
for (asUINT n = 0; n < defaultArgs.GetLength(); n++)
if (defaultArgs[n])
asDELETE(defaultArgs[n], asCString);
node->Destroy(engine);
return 0;
}
// Check for name conflicts
if (!funcTraits.GetTrait(asTRAIT_CONSTRUCTOR) && !funcTraits.GetTrait(asTRAIT_DESTRUCTOR)) {
if (objType) {
CheckNameConflictMember(objType, name.AddressOf(), node, file, false, false);
if (name == objType->name)
WriteError(TXT_METHOD_CANT_HAVE_NAME_OF_CLASS, file, node);
} else
CheckNameConflict(name.AddressOf(), node, file, ns, false, false);
} else {
if (isMixin) {
// Mixins cannot implement constructors/destructors
WriteError(TXT_MIXIN_CANNOT_HAVE_CONSTRUCTOR, file, node);
// Free the default args
for (asUINT n = 0; n < defaultArgs.GetLength(); n++)
if (defaultArgs[n])
asDELETE(defaultArgs[n], asCString);
node->Destroy(engine);
return 0;
}
// Verify that the name of the constructor/destructor is the same as the class
if (name != objType->name) {
asCString str;
if (funcTraits.GetTrait(asTRAIT_DESTRUCTOR))
str.Format(TXT_DESTRUCTOR_s_s_NAME_ERROR, objType->name.AddressOf(), name.AddressOf());
else
str.Format(TXT_METHOD_s_s_HAS_NO_RETURN_TYPE, objType->name.AddressOf(), name.AddressOf());
WriteError(str, file, node);
}
if (funcTraits.GetTrait(asTRAIT_DESTRUCTOR))
name = "~" + name;
}
// Validate virtual properties signature
if (funcTraits.GetTrait(asTRAIT_PROPERTY)) {
asCScriptFunction func(engine, module, asFUNC_SCRIPT);
func.name = name;
func.nameSpace = ns;
func.objectType = objType;
if (objType)
objType->AddRefInternal();
func.traits = funcTraits;
func.returnType = returnType;
func.parameterTypes = parameterTypes;
int r = ValidateVirtualProperty(&func);
if (r < 0) {
asCString str;
if (r == -2 || r == -3)
str.Format(TXT_INVALID_SIG_FOR_VIRTPROP);
else if (r == -4)
str.Format(TXT_GET_SET_ACCESSOR_TYPE_MISMATCH_FOR_s, name.SubString(4).AddressOf());
else if (r == -5)
str.Format(TXT_NAME_CONFLICT_s_ALREADY_USED, name.SubString(4).AddressOf());
WriteError(str, file, node);
}
func.funcType = asFUNC_DUMMY;
}
isExistingShared = false;
int funcId = engine->GetNextScriptFunctionId();
if (!isInterface) {
sFunctionDescription *func = asNEW(sFunctionDescription);
if (func == 0) {
// Free the default args
for (asUINT n = 0; n < defaultArgs.GetLength(); n++)
if (defaultArgs[n])
asDELETE(defaultArgs[n], asCString);
return asOUT_OF_MEMORY;
}
functions.PushLast(func);
func->script = file;
func->node = node;
func->name = name;
func->objType = objType;
func->funcId = funcId;
func->isExistingShared = false;
func->paramNames = parameterNames;
if (funcTraits.GetTrait(asTRAIT_SHARED)) {
// Look for a pre-existing shared function with the same signature
for (asUINT n = 0; n < engine->scriptFunctions.GetLength(); n++) {
asCScriptFunction *f = engine->scriptFunctions[n];
if (f &&
f->IsShared() &&
f->name == name &&
f->nameSpace == ns &&
f->objectType == objType &&
f->IsSignatureExceptNameEqual(returnType, parameterTypes, inOutFlags, 0, false)) {
funcId = func->funcId = f->id;
isExistingShared = func->isExistingShared = true;
break;
}
}
}
// Remember if the function was declared as external so the saved bytecode can be flagged accordingly
if (funcTraits.GetTrait(asTRAIT_EXTERNAL) && func->isExistingShared)
module->m_externalFunctions.PushLast(engine->scriptFunctions[func->funcId]);
if (funcTraits.GetTrait(asTRAIT_EXTERNAL) && !func->isExistingShared) {
// Mark it as existing shared to avoid compiling it
func->isExistingShared = true;
asCString str;
str.Format(TXT_EXTERNAL_SHARED_s_NOT_FOUND, name.AddressOf());
WriteError(str, file, node);
}
// External shared function must not try to redefine the interface
if (funcTraits.GetTrait(asTRAIT_EXTERNAL) && !(node->tokenType == ttEndStatement || node->lastChild->tokenType == ttEndStatement)) {
asCString str;
str.Format(TXT_EXTERNAL_SHARED_s_CANNOT_REDEF, name.AddressOf());
WriteError(str, file, node);
} else if (!funcTraits.GetTrait(asTRAIT_EXTERNAL) && !(node->nodeType == snStatementBlock || node->lastChild->nodeType == snStatementBlock)) {
asCString str;
str.Format(TXT_MISSING_DEFINITION_OF_s, name.AddressOf());
WriteError(str, file, node);
}
}
// Destructors may not have any parameters
if (funcTraits.GetTrait(asTRAIT_DESTRUCTOR) && parameterTypes.GetLength() > 0)
WriteError(TXT_DESTRUCTOR_MAY_NOT_HAVE_PARM, file, node);
// If a function, class, or interface is shared then only shared types may be used in the signature
if ((objType && objType->IsShared()) || funcTraits.GetTrait(asTRAIT_SHARED)) {
asCTypeInfo *ti = returnType.GetTypeInfo();
if (ti && !ti->IsShared()) {
asCString msg;
msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, ti->name.AddressOf());
WriteError(msg, file, node);
}
for (asUINT p = 0; p < parameterTypes.GetLength(); ++p) {
ti = parameterTypes[p].GetTypeInfo();
if (ti && !ti->IsShared()) {
asCString msg;
msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, ti->name.AddressOf());
WriteError(msg, file, node);
}
}
}
// Check that the same function hasn't been registered already in the namespace
asCArray<int> funcs;
if (objType)
GetObjectMethodDescriptions(name.AddressOf(), objType, funcs, false);
else
GetFunctionDescriptions(name.AddressOf(), funcs, ns);
if (objType && (name == "opConv" || name == "opImplConv" || name == "opCast" || name == "opImplCast") && parameterTypes.GetLength() == 0) {
// opConv and opCast are special methods used for type casts
for (asUINT n = 0; n < funcs.GetLength(); ++n) {
asCScriptFunction *func = GetFunctionDescription(funcs[n]);
if (func->IsSignatureExceptNameEqual(returnType, parameterTypes, inOutFlags, objType, funcTraits.GetTrait(asTRAIT_CONST))) {
// TODO: clean up: Reuse the same error handling for both opConv and normal methods
if (isMixin) {
// Clean up the memory, as the function will not be registered
if (node)
node->Destroy(engine);
sFunctionDescription *funcDesc = functions.PopLast();
asDELETE(funcDesc, sFunctionDescription);
// Free the default args
for (n = 0; n < defaultArgs.GetLength(); n++)
if (defaultArgs[n])
asDELETE(defaultArgs[n], asCString);
return 0;
}
WriteError(TXT_FUNCTION_ALREADY_EXIST, file, node);
break;
}
}
} else {
for (asUINT n = 0; n < funcs.GetLength(); ++n) {
asCScriptFunction *func = GetFunctionDescription(funcs[n]);
if (func->IsSignatureExceptNameAndReturnTypeEqual(parameterTypes, inOutFlags, objType, funcTraits.GetTrait(asTRAIT_CONST))) {
if (isMixin) {
// Clean up the memory, as the function will not be registered
if (node)
node->Destroy(engine);
sFunctionDescription *funcDesc = functions.PopLast();
asDELETE(funcDesc, sFunctionDescription);
// Free the default args
for (n = 0; n < defaultArgs.GetLength(); n++)
if (defaultArgs[n])
asDELETE(defaultArgs[n], asCString);
return 0;
}
WriteError(TXT_FUNCTION_ALREADY_EXIST, file, node);
break;
}
}
}
// Register the function
if (isExistingShared) {
// Delete the default args as they won't be used anymore
for (asUINT n = 0; n < defaultArgs.GetLength(); n++)
if (defaultArgs[n])
asDELETE(defaultArgs[n], asCString);
asCScriptFunction *f = engine->scriptFunctions[funcId];
module->AddScriptFunction(f);
// TODO: clean up: This should be done by AddScriptFunction() itself
module->m_globalFunctions.Put(f);
} else {
int row = 0, col = 0;
if (node)
file->ConvertPosToRowCol(node->tokenPos, &row, &col);
module->AddScriptFunction(file->idx, (row & 0xFFFFF) | ((col & 0xFFF) << 20), funcId, name, returnType, parameterTypes, parameterNames, inOutFlags, defaultArgs, isInterface, objType, isGlobalFunction, funcTraits, ns);
}
// Make sure the default args are declared correctly
ValidateDefaultArgs(file, node, engine->scriptFunctions[funcId]);
CheckForConflictsDueToDefaultArgs(file, node, engine->scriptFunctions[funcId], objType);
if (objType) {
asASSERT(!isExistingShared);
engine->scriptFunctions[funcId]->AddRefInternal();
if (funcTraits.GetTrait(asTRAIT_CONSTRUCTOR)) {
int factoryId = engine->GetNextScriptFunctionId();
if (parameterTypes.GetLength() == 0) {
// Overload the default constructor
engine->scriptFunctions[objType->beh.construct]->ReleaseInternal();
objType->beh.construct = funcId;
objType->beh.constructors[0] = funcId;
// Register the default factory as well
engine->scriptFunctions[objType->beh.factory]->ReleaseInternal();
objType->beh.factory = factoryId;
objType->beh.factories[0] = factoryId;
} else {
// The copy constructor needs to be marked for easy finding
if (parameterTypes.GetLength() == 1 &&
parameterTypes[0].GetTypeInfo() == objType &&
(parameterTypes[0].IsReference() || parameterTypes[0].IsObjectHandle())) {
// Verify that there are not multiple options matching the copy constructor
// TODO: Need a better message, since the parameters can be slightly different, e.g. & vs @
if (objType->beh.copyconstruct)
WriteError(TXT_FUNCTION_ALREADY_EXIST, file, node);
objType->beh.copyconstruct = funcId;
objType->beh.copyfactory = factoryId;
}
// Register as a normal constructor
objType->beh.constructors.PushLast(funcId);
// Register the factory as well
objType->beh.factories.PushLast(factoryId);
}
// We must copy the default arg strings to avoid deleting the same object multiple times
for (asUINT n = 0; n < defaultArgs.GetLength(); n++)
if (defaultArgs[n])
defaultArgs[n] = asNEW(asCString)(*defaultArgs[n]);
asCDataType dt = asCDataType::CreateObjectHandle(objType, false);
module->AddScriptFunction(file->idx, engine->scriptFunctions[funcId]->scriptData->declaredAt, factoryId, name, dt, parameterTypes, parameterNames, inOutFlags, defaultArgs, false, 0, false, funcTraits);
// If the object is shared, then the factory must also be marked as shared
if (objType->flags & asOBJ_SHARED)
engine->scriptFunctions[factoryId]->SetShared(true);
// Add a dummy function to the builder so that it doesn't mix up the fund Ids
functions.PushLast(0);
// Compile the factory immediately
asCCompiler compiler(engine);
compiler.CompileFactory(this, file, engine->scriptFunctions[factoryId]);
engine->scriptFunctions[factoryId]->AddRefInternal();
} else if (funcTraits.GetTrait(asTRAIT_DESTRUCTOR))
objType->beh.destruct = funcId;
else {
// If the method is the assignment operator we need to replace the default implementation
asCScriptFunction *f = engine->scriptFunctions[funcId];
if (f->name == "opAssign" && f->parameterTypes.GetLength() == 1 &&
f->parameterTypes[0].GetTypeInfo() == f->objectType &&
(f->inOutFlags[0] & asTM_INREF)) {
engine->scriptFunctions[objType->beh.copy]->ReleaseInternal();
objType->beh.copy = funcId;
f->AddRefInternal();
}
objType->methods.PushLast(funcId);
}
}
// We need to delete the node already if this is an interface method
if (isInterface && node)
node->Destroy(engine);
return 0;
}
int asCBuilder::RegisterVirtualProperty(asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, bool isInterface, bool isGlobalFunction, asSNameSpace *ns, bool isExistingShared) {
if (engine->ep.propertyAccessorMode < 2) {
WriteError(TXT_PROPERTY_ACCESSOR_DISABLED, file, node);
node->Destroy(engine);
return 0;
}
asASSERT((objType && ns == 0) || isGlobalFunction);
if (ns == 0) {
if (objType)
ns = objType->nameSpace;
else
ns = engine->nameSpaces[0];
}
bool isPrivate = false, isProtected = false;
asCString emulatedName;
asCDataType emulatedType;
asCScriptNode *mainNode = node;
node = node->firstChild;
if (!isGlobalFunction && node->tokenType == ttPrivate) {
isPrivate = true;
node = node->next;
} else if (!isGlobalFunction && node->tokenType == ttProtected) {
isProtected = true;
node = node->next;
}
emulatedType = CreateDataTypeFromNode(node, file, ns);
emulatedType = ModifyDataTypeFromNode(emulatedType, node->next, file, 0, 0);
node = node->next->next;
emulatedName.Assign(&file->code[node->tokenPos], node->tokenLength);
if (node->next == 0)
WriteError(TXT_PROPERTY_WITHOUT_ACCESSOR, file, node);
node = node->next;
while (node) {
asCScriptNode *next = node->next;
asCScriptNode *funcNode = 0;
bool success = false;
asSFunctionTraits funcTraits;
asCDataType returnType;
asCArray<asCString> paramNames;
asCArray<asCDataType> paramTypes;
asCArray<asETypeModifiers> paramModifiers;
asCArray<asCString *> defaultArgs;
asCString name;
funcTraits.SetTrait(asTRAIT_PRIVATE, isPrivate);
funcTraits.SetTrait(asTRAIT_PROTECTED, isProtected);
funcTraits.SetTrait(asTRAIT_PROPERTY, true);
if (node->firstChild->nodeType == snIdentifier && file->TokenEquals(node->firstChild->tokenPos, node->firstChild->tokenLength, GET_TOKEN))
name = "get_";
else if (node->firstChild->nodeType == snIdentifier && file->TokenEquals(node->firstChild->tokenPos, node->firstChild->tokenLength, SET_TOKEN))
name = "set_";
else
WriteError(TXT_UNRECOGNIZED_VIRTUAL_PROPERTY_NODE, file, node);
if (name != "") {
success = true;
funcNode = node->firstChild->next;
if (funcNode && funcNode->tokenType == ttConst) {
funcTraits.SetTrait(asTRAIT_CONST, true);
funcNode = funcNode->next;
}
while (funcNode && funcNode->nodeType != snStatementBlock) {
if (funcNode->tokenType == ttIdentifier && file->TokenEquals(funcNode->tokenPos, funcNode->tokenLength, FINAL_TOKEN))
funcTraits.SetTrait(asTRAIT_FINAL, true);
else if (funcNode->tokenType == ttIdentifier && file->TokenEquals(funcNode->tokenPos, funcNode->tokenLength, OVERRIDE_TOKEN))
funcTraits.SetTrait(asTRAIT_OVERRIDE, true);
else {
asCString msg(&file->code[funcNode->tokenPos], funcNode->tokenLength);
msg.Format(TXT_UNEXPECTED_TOKEN_s, msg.AddressOf());
WriteError(msg.AddressOf(), file, node);
}
funcNode = funcNode->next;
}
if (funcNode)
funcNode->DisconnectParent();
if (funcNode == 0 && (objType == 0 || !objType->IsInterface())) {
// TODO: getset: If no implementation is supplied the builder should provide an automatically generated implementation
// The compiler needs to be able to handle the different types, primitive, value type, and handle
// The code is also different for global property accessors
WriteError(TXT_PROPERTY_ACCESSOR_MUST_BE_IMPLEMENTED, file, node);
}
if (name == "get_") {
// Setup the signature for the get accessor method
returnType = emulatedType;
name = "get_" + emulatedName;
} else if (name == "set_") {
// Setup the signature for the set accessor method
returnType = asCDataType::CreatePrimitive(ttVoid, false);
paramModifiers.PushLast(asTM_NONE);
paramNames.PushLast("value");
paramTypes.PushLast(emulatedType);
defaultArgs.PushLast(0);
name = "set_" + emulatedName;
}
}
if (success) {
if (!isExistingShared)
RegisterScriptFunction(funcNode, file, objType, isInterface, isGlobalFunction, ns, false, false, name, returnType, paramNames, paramTypes, paramModifiers, defaultArgs, funcTraits);
else {
// Free the funcNode as it won't be used
if (funcNode) funcNode->Destroy(engine);
// Should validate that the function really exists in the class/interface
bool found = false;
for (asUINT n = 0; n < objType->methods.GetLength(); n++) {
asCScriptFunction *func = engine->scriptFunctions[objType->methods[n]];
if (func->name == name &&
func->IsSignatureExceptNameEqual(returnType, paramTypes, paramModifiers, objType, funcTraits.GetTrait(asTRAIT_CONST))) {
found = true;
break;
}
}
if (!found) {
asCString str;
str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, objType->GetName());
WriteError(str, file, node);
}
}
}
node = next;
};
mainNode->Destroy(engine);
return 0;
}
int asCBuilder::RegisterImportedFunction(int importID, asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns) {
asCString name;
asCDataType returnType;
asCArray<asCString> parameterNames;
asCArray<asCDataType> parameterTypes;
asCArray<asETypeModifiers> inOutFlags;
asCArray<asCString *> defaultArgs;
asSFunctionTraits funcTraits;
if (ns == 0)
ns = engine->nameSpaces[0];
GetParsedFunctionDetails(node->firstChild, file, 0, name, returnType, parameterNames, parameterTypes, inOutFlags, defaultArgs, funcTraits, ns);
CheckNameConflict(name.AddressOf(), node, file, ns, false, false);
// Check that the same function hasn't been registered already in the namespace
asCArray<int> funcs;
GetFunctionDescriptions(name.AddressOf(), funcs, ns);
for (asUINT n = 0; n < funcs.GetLength(); ++n) {
asCScriptFunction *func = GetFunctionDescription(funcs[n]);
if (func->IsSignatureExceptNameAndReturnTypeEqual(parameterTypes, inOutFlags, 0, false)) {
WriteError(TXT_FUNCTION_ALREADY_EXIST, file, node);
break;
}
}
// Read the module name as well
asCScriptNode *nd = node->lastChild;
asASSERT(nd->nodeType == snConstant && nd->tokenType == ttStringConstant);
asCString moduleName;
moduleName.Assign(&file->code[nd->tokenPos + 1], nd->tokenLength - 2);
node->Destroy(engine);
// Register the function
module->AddImportedFunction(importID, name, returnType, parameterTypes, inOutFlags, defaultArgs, funcTraits, ns, moduleName);
return 0;
}
asCScriptFunction *asCBuilder::GetFunctionDescription(int id) {
// TODO: import: This should be improved when the imported functions are removed
// Get the description from the engine
if ((id & FUNC_IMPORTED) == 0)
return engine->scriptFunctions[id];
else
return engine->importedFunctions[id & ~FUNC_IMPORTED]->importedFunctionSignature;
}
void asCBuilder::GetFunctionDescriptions(const char *name, asCArray<int> &funcs, asSNameSpace *ns) {
asUINT n;
// Get the script declared global functions
const asCArray<unsigned int> &idxs = module->m_globalFunctions.GetIndexes(ns, name);
for (n = 0; n < idxs.GetLength(); n++) {
const asCScriptFunction *f = module->m_globalFunctions.Get(idxs[n]);
asASSERT(f->objectType == 0);
funcs.PushLast(f->id);
}
// Add the imported functions
// TODO: optimize: Linear search: This is probably not that critial. Also bindInformation will probably be removed in near future
for (n = 0; n < module->m_bindInformations.GetLength(); n++) {
if (module->m_bindInformations[n]->importedFunctionSignature->name == name &&
module->m_bindInformations[n]->importedFunctionSignature->nameSpace == ns)
funcs.PushLast(module->m_bindInformations[n]->importedFunctionSignature->id);
}
// Add the registered global functions
const asCArray<unsigned int> &idxs2 = engine->registeredGlobalFuncs.GetIndexes(ns, name);
for (n = 0; n < idxs2.GetLength(); n++) {
asCScriptFunction *f = engine->registeredGlobalFuncs.Get(idxs2[n]);
// Verify if the module has access to the function
if (module->m_accessMask & f->accessMask) {
funcs.PushLast(f->id);
}
}
}
// scope is only informed when looking for a base class' method
void asCBuilder::GetObjectMethodDescriptions(const char *name, asCObjectType *objectType, asCArray<int> &methods, bool objIsConst, const asCString &scope, asCScriptNode *errNode, asCScriptCode *script) {
asASSERT(objectType);
if (scope != "") {
// If searching with a scope informed, then the node and script must also be informed for potential error reporting
asASSERT(errNode && script);
// If the scope contains ::identifier, then use the last identifier as the class name and the rest of it as the namespace
// TODO: child funcdef: A scope can include a template type, e.g. array<ns::type>
int n = scope.FindLast("::");
asCString className = n >= 0 ? scope.SubString(n + 2) : scope;
asCString nsName = n >= 0 ? scope.SubString(0, n) : asCString("");
// If a namespace was specifically defined, then this must be used
asSNameSpace *ns = 0;
if (n >= 0) {
if (nsName == "")
ns = engine->nameSpaces[0];
else
ns = GetNameSpaceByString(nsName, objectType->nameSpace, errNode, script, 0, false);
// If the namespace isn't found return silently and let the calling
// function report the error if it cannot resolve the symbol
if (ns == 0)
return;
}
// Find the base class with the specified scope
while (objectType) {
// If the name and namespace matches it is the correct class. If no
// specific namespace was given, then don't compare the namespace
if (objectType->name == className && (ns == 0 || objectType->nameSpace == ns))
break;
objectType = objectType->derivedFrom;
}
// If the scope is not any of the base classes, then return no methods
if (objectType == 0)
return;
}
// Find the methods in the object that match the name
// TODO: optimize: Improve linear search
for (asUINT n = 0; n < objectType->methods.GetLength(); n++) {
asCScriptFunction *func = engine->scriptFunctions[objectType->methods[n]];
if (func->name == name &&
(!objIsConst || func->IsReadOnly()) &&
(func->accessMask & module->m_accessMask)) {
// When the scope is defined the returned methods should be the true methods, not the virtual method stubs
if (scope == "")
methods.PushLast(engine->scriptFunctions[objectType->methods[n]]->id);
else {
asCScriptFunction *f = engine->scriptFunctions[objectType->methods[n]];
if (f && f->funcType == asFUNC_VIRTUAL)
f = objectType->virtualFunctionTable[f->vfTableIdx];
methods.PushLast(f->id);
}
}
}
}
#endif
void asCBuilder::WriteInfo(const asCString &scriptname, const asCString &message, int r, int c, bool pre) {
// Need to store the pre message in a structure
if (pre) {
engine->preMessage.isSet = true;
engine->preMessage.c = c;
engine->preMessage.r = r;
engine->preMessage.message = message;
engine->preMessage.scriptname = scriptname;
} else {
engine->preMessage.isSet = false;
if (!silent)
engine->WriteMessage(scriptname.AddressOf(), r, c, asMSGTYPE_INFORMATION, message.AddressOf());
}
}
void asCBuilder::WriteInfo(const asCString &message, asCScriptCode *file, asCScriptNode *node) {
int r = 0, c = 0;
if (node)
file->ConvertPosToRowCol(node->tokenPos, &r, &c);
WriteInfo(file->name, message, r, c, false);
}
void asCBuilder::WriteError(const asCString &message, asCScriptCode *file, asCScriptNode *node) {
int r = 0, c = 0;
if (node && file)
file->ConvertPosToRowCol(node->tokenPos, &r, &c);
WriteError(file ? file->name : asCString(""), message, r, c);
}
void asCBuilder::WriteError(const asCString &scriptname, const asCString &message, int r, int c) {
numErrors++;
if (!silent)
engine->WriteMessage(scriptname.AddressOf(), r, c, asMSGTYPE_ERROR, message.AddressOf());
}
void asCBuilder::WriteWarning(const asCString &scriptname, const asCString &message, int r, int c) {
if (engine->ep.compilerWarnings) {
numWarnings++;
if (!silent)
engine->WriteMessage(scriptname.AddressOf(), r, c, asMSGTYPE_WARNING, message.AddressOf());
}
}
void asCBuilder::WriteWarning(const asCString &message, asCScriptCode *file, asCScriptNode *node) {
int r = 0, c = 0;
if (node && file)
file->ConvertPosToRowCol(node->tokenPos, &r, &c);
WriteWarning(file ? file->name : asCString(""), message, r, c);
}
// TODO: child funcdef: Should try to eliminate this function. GetNameSpaceFromNode is more complete
asCString asCBuilder::GetScopeFromNode(asCScriptNode *node, asCScriptCode *script, asCScriptNode **next) {
if (node->nodeType != snScope) {
if (next)
*next = node;
return "";
}
asCString scope;
asCScriptNode *sn = node->firstChild;
if (sn->tokenType == ttScope) {
scope = "::";
sn = sn->next;
}
// TODO: child funcdef: A scope can have a template type as the innermost
while (sn && sn->next && sn->next->tokenType == ttScope) {
asCString tmp;
tmp.Assign(&script->code[sn->tokenPos], sn->tokenLength);
if (scope != "" && scope != "::")
scope += "::";
scope += tmp;
sn = sn->next->next;
}
if (next)
*next = node->next;
return scope;
}
asSNameSpace *asCBuilder::GetNameSpaceFromNode(asCScriptNode *node, asCScriptCode *script, asSNameSpace *implicitNs, asCScriptNode **next, asCObjectType **objType) {
if (objType)
*objType = 0;
// If no scope has been informed, then return the implicit namespace
if (node->nodeType != snScope) {
if (next)
*next = node;
return implicitNs ? implicitNs : engine->nameSpaces[0];
}
if (next)
*next = node->next;
asCString scope;
asCScriptNode *sn = node->firstChild;
if (sn && sn->tokenType == ttScope) {
scope = "::";
sn = sn->next;
}
while (sn) {
if (sn->next->tokenType == ttScope) {
asCString tmp;
tmp.Assign(&script->code[sn->tokenPos], sn->tokenLength);
if (scope != "" && scope != "::")
scope += "::";
scope += tmp;
sn = sn->next->next;
} else {
// This is a template type
asASSERT(sn->next->nodeType == snDataType);
asSNameSpace *ns = implicitNs;
if (scope != "")
ns = engine->FindNameSpace(scope.AddressOf());
asCString templateName(&script->code[sn->tokenPos], sn->tokenLength);
asCObjectType *templateType = GetObjectType(templateName.AddressOf(), ns);
if (templateType == 0 || (templateType->flags & asOBJ_TEMPLATE) == 0) {
// TODO: child funcdef: Report error
return ns;
}
if (objType)
*objType = GetTemplateInstanceFromNode(sn, script, templateType, implicitNs, 0);
// Return no namespace, since this is an object type
return 0;
}
}
asCTypeInfo *ti = 0;
asSNameSpace *ns = GetNameSpaceByString(scope, implicitNs ? implicitNs : engine->nameSpaces[0], node, script, &ti);
if (ti && objType)
*objType = CastToObjectType(ti);
return ns;
}
asSNameSpace *asCBuilder::GetNameSpaceByString(const asCString &nsName, asSNameSpace *implicitNs, asCScriptNode *errNode, asCScriptCode *script, asCTypeInfo **scopeType, bool isRequired) {
if (scopeType)
*scopeType = 0;
asSNameSpace *ns = implicitNs;
if (nsName == "::")
ns = engine->nameSpaces[0];
else if (nsName != "") {
ns = engine->FindNameSpace(nsName.AddressOf());
if (ns == 0 && scopeType) {
asCString typeName;
asCString searchNs;
// Split the scope with at the inner most ::
int pos = nsName.FindLast("::");
bool recursive = false;
if (pos >= 0) {
// Fully qualified namespace
typeName = nsName.SubString(pos + 2);
searchNs = nsName.SubString(0, pos);
} else {
// Partially qualified, use the implicit namespace and then search recursively for the type
typeName = nsName;
searchNs = implicitNs->name;
recursive = true;
}
asSNameSpace *nsTmp = searchNs == "::" ? engine->nameSpaces[0] : engine->FindNameSpace(searchNs.AddressOf());
asCTypeInfo *ti = 0;
while (!ti && nsTmp) {
// Check if the typeName is an existing type in the namespace
ti = GetType(typeName.AddressOf(), nsTmp, 0);
if (ti) {
// The informed scope is not a namespace, but it does match a type
*scopeType = ti;
return 0;
}
nsTmp = recursive ? engine->GetParentNameSpace(nsTmp) : 0;
}
}
if (ns == 0 && isRequired) {
asCString msg;
msg.Format(TXT_NAMESPACE_s_DOESNT_EXIST, nsName.AddressOf());
WriteError(msg, script, errNode);
}
}
return ns;
}
asCDataType asCBuilder::CreateDataTypeFromNode(asCScriptNode *node, asCScriptCode *file, asSNameSpace *implicitNamespace, bool acceptHandleForScope, asCObjectType *currentType, bool reportError, bool *isValid) {
asASSERT(node->nodeType == snDataType || node->nodeType == snIdentifier || node->nodeType == snScope);
asCDataType dt;
asCScriptNode *n = node->firstChild;
if (isValid)
*isValid = true;
// If the informed node is an identifier or scope, then the
// datatype should be identified directly from that
if (node->nodeType != snDataType)
n = node;
bool isConst = false;
bool isImplicitHandle = false;
if (n->tokenType == ttConst) {
isConst = true;
n = n->next;
}
// Determine namespace (or parent type) to search for the data type in
asCObjectType *parentType = 0;
asSNameSpace *ns = GetNameSpaceFromNode(n, file, implicitNamespace, &n, &parentType);
if (ns == 0 && parentType == 0) {
// The namespace and parent type doesn't exist. Return a dummy type instead.
dt = asCDataType::CreatePrimitive(ttInt, false);
if (isValid)
*isValid = false;
return dt;
}
if (n->tokenType == ttIdentifier) {
bool found = false;
asCString str;
str.Assign(&file->code[n->tokenPos], n->tokenLength);
// Recursively search parent namespaces for matching type
asSNameSpace *origNs = ns;
asCObjectType *origParentType = parentType;
while ((ns || parentType) && !found) {
asCTypeInfo *ti = 0;
if (currentType) {
// If this is for a template type, then we must first determine if the
// identifier matches any of the template subtypes
if (currentType->flags & asOBJ_TEMPLATE) {
for (asUINT subtypeIndex = 0; subtypeIndex < currentType->templateSubTypes.GetLength(); subtypeIndex++) {
asCTypeInfo *type = currentType->templateSubTypes[subtypeIndex].GetTypeInfo();
if (type && str == type->name) {
ti = type;
break;
}
}
}
if (ti == 0) {
// Check if the type is a child type of the current type
ti = GetFuncDef(str.AddressOf(), 0, currentType);
if (ti) {
dt = asCDataType::CreateType(ti, false);
found = true;
}
}
}
if (ti == 0)
ti = GetType(str.AddressOf(), ns, parentType);
if (ti == 0 && !module && currentType)
ti = GetTypeFromTypesKnownByObject(str.AddressOf(), currentType);
if (ti && !found) {
found = true;
if (ti->flags & asOBJ_IMPLICIT_HANDLE)
isImplicitHandle = true;
// Make sure the module has access to the object type
if (!module || (module->m_accessMask & ti->accessMask)) {
if (asOBJ_TYPEDEF == (ti->flags & asOBJ_TYPEDEF)) {
// TODO: typedef: A typedef should be considered different from the original type (though with implicit conversions between the two)
// Create primitive data type based on object flags
dt = CastToTypedefType(ti)->aliasForType;
dt.MakeReadOnly(isConst);
} else {
if (ti->flags & asOBJ_TEMPLATE) {
ti = GetTemplateInstanceFromNode(n, file, CastToObjectType(ti), implicitNamespace, currentType, &n);
if (ti == 0) {
if (isValid)
*isValid = false;
// Return a dummy
return asCDataType::CreatePrimitive(ttInt, false);
}
} else if (n && n->next && n->next->nodeType == snDataType) {
if (reportError) {
asCString msg;
msg.Format(TXT_TYPE_s_NOT_TEMPLATE, ti->name.AddressOf());
WriteError(msg, file, n);
}
if (isValid)
*isValid = false;
}
// Create object data type
if (ti)
dt = asCDataType::CreateType(ti, isConst);
else
dt = asCDataType::CreatePrimitive(ttInt, isConst);
}
} else {
if (reportError) {
asCString msg;
msg.Format(TXT_TYPE_s_NOT_AVAILABLE_FOR_MODULE, (const char *)str.AddressOf());
WriteError(msg, file, n);
}
dt.SetTokenType(ttInt);
if (isValid)
*isValid = false;
}
}
if (!found) {
// Try to find it in the parent namespace
if (ns)
ns = engine->GetParentNameSpace(ns);
if (parentType)
parentType = 0;
}
}
if (!found) {
if (reportError) {
asCString msg;
if (origNs && origNs->name == "")
msg.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE_IN_GLOBAL_NS, str.AddressOf());
else if (origNs)
msg.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE_IN_NS_s, str.AddressOf(), origNs->name.AddressOf());
else {
// TODO: child funcdef: Message should explain that the identifier is not a type of the parent type
asCDataType pt = asCDataType::CreateType(origParentType, false);
msg.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE_IN_NS_s, str.AddressOf(), pt.Format(origParentType->nameSpace, false).AddressOf());
}
WriteError(msg, file, n);
}
dt = asCDataType::CreatePrimitive(ttInt, isConst);
if (isValid)
*isValid = false;
return dt;
}
} else if (n->tokenType == ttAuto) {
dt = asCDataType::CreateAuto(isConst);
} else {
// Create primitive data type
dt = asCDataType::CreatePrimitive(n->tokenType, isConst);
}
// Determine array dimensions and object handles
n = n->next;
while (n && (n->tokenType == ttOpenBracket || n->tokenType == ttHandle)) {
if (n->tokenType == ttOpenBracket) {
if (isImplicitHandle) {
// Make the type a handle
if (dt.MakeHandle(true, acceptHandleForScope) < 0) {
if (reportError)
WriteError(TXT_OBJECT_HANDLE_NOT_SUPPORTED, file, n);
if (isValid)
*isValid = false;
}
isImplicitHandle = false;
}
// Make sure the sub type can be instantiated
if (!dt.CanBeInstantiated()) {
if (reportError) {
asCString str;
if (dt.IsAbstractClass())
str.Format(TXT_ABSTRACT_CLASS_s_CANNOT_BE_INSTANTIATED, dt.Format(ns).AddressOf());
else if (dt.IsInterface())
str.Format(TXT_INTERFACE_s_CANNOT_BE_INSTANTIATED, dt.Format(ns).AddressOf());
else
// TODO: Improve error message to explain why
str.Format(TXT_DATA_TYPE_CANT_BE_s, dt.Format(ns).AddressOf());
WriteError(str, file, n);
}
if (isValid)
*isValid = false;
}
// Make the type an array (or multidimensional array)
if (dt.MakeArray(engine, module) < 0) {
if (reportError)
WriteError(TXT_NO_DEFAULT_ARRAY_TYPE, file, n);
if (isValid)
*isValid = false;
break;
}
} else {
// Make the type a handle
if (dt.IsObjectHandle()) {
if (reportError)
WriteError(TXT_HANDLE_OF_HANDLE_IS_NOT_ALLOWED, file, n);
if (isValid)
*isValid = false;
break;
} else {
if (dt.MakeHandle(true, acceptHandleForScope) < 0) {
if (reportError)
WriteError(TXT_OBJECT_HANDLE_NOT_SUPPORTED, file, n);
if (isValid)
*isValid = false;
break;
}
// Check if the handle should be read-only
if (n && n->next && n->next->tokenType == ttConst)
dt.MakeReadOnly(true);
}
}
n = n->next;
}
if (isImplicitHandle) {
// Make the type a handle
if (dt.MakeHandle(true, acceptHandleForScope) < 0) {
if (reportError)
WriteError(TXT_OBJECT_HANDLE_NOT_SUPPORTED, file, n);
if (isValid)
*isValid = false;
}
}
return dt;
}
asCObjectType *asCBuilder::GetTemplateInstanceFromNode(asCScriptNode *node, asCScriptCode *file, asCObjectType *templateType, asSNameSpace *implicitNamespace, asCObjectType *currentType, asCScriptNode **next) {
// Check if the subtype is a type or the template's subtype
// if it is the template's subtype then this is the actual template type,
// orderwise it is a template instance.
// Only do this for application registered interface, as the
// scripts cannot implement templates.
asCArray<asCDataType> subTypes;
asUINT subtypeIndex;
asCScriptNode *n = node;
while (n && n->next && n->next->nodeType == snDataType) {
n = n->next;
// When parsing function definitions for template registrations (currentType != 0) it is necessary
// to pass in the current template type to the recursive call since it is this ones sub-template types
// that should be allowed.
asCDataType subType = CreateDataTypeFromNode(n, file, implicitNamespace, false, module ? 0 : (currentType ? currentType : templateType));
subTypes.PushLast(subType);
if (subType.IsReadOnly()) {
asCString msg;
msg.Format(TXT_TMPL_SUBTYPE_MUST_NOT_BE_READ_ONLY);
WriteError(msg, file, n);
// Return a dummy
return 0;
}
}
if (next)
*next = n;
if (subTypes.GetLength() != templateType->templateSubTypes.GetLength()) {
asCString msg;
msg.Format(TXT_TMPL_s_EXPECTS_d_SUBTYPES, templateType->name.AddressOf(), int(templateType->templateSubTypes.GetLength()));
WriteError(msg, file, node);
// Return a dummy
return 0;
}
// Check if any of the given subtypes are different from the template's declared subtypes
bool isDifferent = false;
for (subtypeIndex = 0; subtypeIndex < subTypes.GetLength(); subtypeIndex++) {
if (subTypes[subtypeIndex].GetTypeInfo() != templateType->templateSubTypes[subtypeIndex].GetTypeInfo()) {
isDifferent = true;
break;
}
}
if (isDifferent) {
// This is a template instance
// Need to find the correct object type
asCObjectType *otInstance = engine->GetTemplateInstanceType(templateType, subTypes, module);
if (otInstance && otInstance->scriptSectionIdx < 0) {
// If this is the first time the template instance is used, store where it was declared from
otInstance->scriptSectionIdx = engine->GetScriptSectionNameIndex(file->name.AddressOf());
int row, column;
file->ConvertPosToRowCol(n->tokenPos, &row, &column);
otInstance->declaredAt = (row & 0xFFFFF) | (column << 20);
}
if (!otInstance) {
asCString sub = subTypes[0].Format(templateType->nameSpace);
for (asUINT s = 1; s < subTypes.GetLength(); s++) {
sub += ",";
sub += subTypes[s].Format(templateType->nameSpace);
}
asCString msg;
msg.Format(TXT_INSTANCING_INVLD_TMPL_TYPE_s_s, templateType->name.AddressOf(), sub.AddressOf());
WriteError(msg, file, n);
}
return otInstance;
}
return templateType;
}
asCDataType asCBuilder::ModifyDataTypeFromNode(const asCDataType &type, asCScriptNode *node, asCScriptCode *file, asETypeModifiers *inOutFlags, bool *autoHandle) {
asCDataType dt = type;
if (inOutFlags) *inOutFlags = asTM_NONE;
// Is the argument sent by reference?
asCScriptNode *n = node->firstChild;
if (n && n->tokenType == ttAmp) {
if (dt.GetTokenType() == ttVoid) {
asCString msg;
msg.Format(TXT_TYPE_s_CANNOT_BE_REFERENCE, type.Format(0).AddressOf());
WriteError(msg, file, node->firstChild);
return dt;
}
dt.MakeReference(true);
n = n->next;
if (n) {
if (inOutFlags) {
if (n->tokenType == ttIn)
*inOutFlags = asTM_INREF;
else if (n->tokenType == ttOut)
*inOutFlags = asTM_OUTREF;
else if (n->tokenType == ttInOut)
*inOutFlags = asTM_INOUTREF;
else
asASSERT(false);
}
n = n->next;
} else {
if (inOutFlags)
*inOutFlags = asTM_INOUTREF; // ttInOut
}
if (!engine->ep.allowUnsafeReferences &&
inOutFlags && *inOutFlags == asTM_INOUTREF &&
!(dt.GetTypeInfo() && (dt.GetTypeInfo()->flags & asOBJ_TEMPLATE_SUBTYPE))) {
// Verify that the base type support &inout parameter types
if (!dt.IsObject() || dt.IsObjectHandle() ||
!((dt.GetTypeInfo()->flags & asOBJ_NOCOUNT) || (CastToObjectType(dt.GetTypeInfo())->beh.addref && CastToObjectType(dt.GetTypeInfo())->beh.release)))
WriteError(TXT_ONLY_OBJECTS_MAY_USE_REF_INOUT, file, node->firstChild);
}
}
if (autoHandle) *autoHandle = false;
if (n && n->tokenType == ttPlus) {
// Autohandles are not supported for types with NOCOUNT
// If the type is not a handle then there was an error with building the type, but
// this error would already have been reported so no need to report another error here
if (dt.IsObjectHandle() && (dt.GetTypeInfo()->flags & asOBJ_NOCOUNT))
WriteError(TXT_AUTOHANDLE_CANNOT_BE_USED_FOR_NOCOUNT, file, node->firstChild);
if (autoHandle) *autoHandle = true;
}
if (n && n->tokenType == ttIdentifier) {
asCString str;
str.Assign(&file->code[n->tokenPos], n->tokenLength);
if (str == IF_HANDLE_TOKEN)
dt.SetIfHandleThenConst(true);
else {
// TODO: Should give error if not currently parsing template registration
asCString msg;
msg.Format(TXT_UNEXPECTED_TOKEN_s, str.AddressOf());
WriteError(msg, file, node->firstChild);
}
}
return dt;
}
asCTypeInfo *asCBuilder::GetType(const char *type, asSNameSpace *ns, asCObjectType *parentType) {
asASSERT((ns == 0 && parentType) || (ns && parentType == 0));
if (ns) {
asCTypeInfo *ti = engine->GetRegisteredType(type, ns);
if (!ti && module)
ti = module->GetType(type, ns);
return ti;
} else {
// Recursively check base classes
asCObjectType *currType = parentType;
while (currType) {
for (asUINT n = 0; n < currType->childFuncDefs.GetLength(); n++) {
asCFuncdefType *funcDef = currType->childFuncDefs[n];
if (funcDef && funcDef->name == type)
return funcDef;
}
currType = currType->derivedFrom;
}
}
return 0;
}
asCObjectType *asCBuilder::GetObjectType(const char *type, asSNameSpace *ns) {
return CastToObjectType(GetType(type, ns, 0));
}
#ifndef AS_NO_COMPILER
// This function will return true if there are any types in the engine or module
// with the given name. The namespace is ignored in this verification.
bool asCBuilder::DoesTypeExist(const asCString &type) {
asUINT n;
// This function is only used when parsing expressions for building bytecode
// and this is only done after all types are known. For this reason the types
// can be safely cached in a map for quick lookup. Once the builder is released
// the cache will also be destroyed thus avoiding unnecessary memory consumption.
if (!hasCachedKnownTypes) {
// Only do this once
hasCachedKnownTypes = true;
// Add registered types
asSMapNode<asSNameSpaceNamePair, asCTypeInfo *> *cursor;
engine->allRegisteredTypes.MoveFirst(&cursor);
while (cursor) {
if (!knownTypes.MoveTo(0, cursor->key.name))
knownTypes.Insert(cursor->key.name, true);
engine->allRegisteredTypes.MoveNext(&cursor, cursor);
}
if (module) {
// Add script classes and interfaces
for (n = 0; n < module->m_classTypes.GetLength(); n++)
if (!knownTypes.MoveTo(0, module->m_classTypes[n]->name))
knownTypes.Insert(module->m_classTypes[n]->name, true);
// Add script enums
for (n = 0; n < module->m_enumTypes.GetLength(); n++)
if (!knownTypes.MoveTo(0, module->m_enumTypes[n]->name))
knownTypes.Insert(module->m_enumTypes[n]->name, true);
// Add script typedefs
for (n = 0; n < module->m_typeDefs.GetLength(); n++)
if (!knownTypes.MoveTo(0, module->m_typeDefs[n]->name))
knownTypes.Insert(module->m_typeDefs[n]->name, true);
// Add script funcdefs
for (n = 0; n < module->m_funcDefs.GetLength(); n++)
if (!knownTypes.MoveTo(0, module->m_funcDefs[n]->name))
knownTypes.Insert(module->m_funcDefs[n]->name, true);
}
}
// Check if the type is known
return knownTypes.MoveTo(0, type);
}
#endif
asCTypeInfo *asCBuilder::GetTypeFromTypesKnownByObject(const char *type, asCObjectType *currentType) {
if (currentType->name == type)
return currentType;
asUINT n;
asCTypeInfo *found = 0;
for (n = 0; found == 0 && n < currentType->properties.GetLength(); n++)
if (currentType->properties[n]->type.GetTypeInfo() &&
currentType->properties[n]->type.GetTypeInfo()->name == type)
found = currentType->properties[n]->type.GetTypeInfo();
for (n = 0; found == 0 && n < currentType->methods.GetLength(); n++) {
asCScriptFunction *func = engine->scriptFunctions[currentType->methods[n]];
if (func->returnType.GetTypeInfo() &&
func->returnType.GetTypeInfo()->name == type)
found = func->returnType.GetTypeInfo();
for (asUINT f = 0; found == 0 && f < func->parameterTypes.GetLength(); f++)
if (func->parameterTypes[f].GetTypeInfo() &&
func->parameterTypes[f].GetTypeInfo()->name == type)
found = func->parameterTypes[f].GetTypeInfo();
}
if (found) {
// In case we find a template instance it mustn't be returned
// because it is not known if the subtype is really matching
if (found->flags & asOBJ_TEMPLATE)
return 0;
}
return found;
}
asCFuncdefType *asCBuilder::GetFuncDef(const char *type, asSNameSpace *ns, asCObjectType *parentType) {
asASSERT((ns == 0 && parentType) || (ns && parentType == 0));
if (ns) {
for (asUINT n = 0; n < engine->registeredFuncDefs.GetLength(); n++) {
asCFuncdefType *funcDef = engine->registeredFuncDefs[n];
// TODO: access: Only return the definitions that the module has access to
if (funcDef && funcDef->nameSpace == ns && funcDef->name == type)
return funcDef;
}
if (module) {
for (asUINT n = 0; n < module->m_funcDefs.GetLength(); n++) {
asCFuncdefType *funcDef = module->m_funcDefs[n];
if (funcDef && funcDef->nameSpace == ns && funcDef->name == type)
return funcDef;
}
}
} else {
// Recursively check base classes
asCObjectType *currType = parentType;
while (currType) {
for (asUINT n = 0; n < currType->childFuncDefs.GetLength(); n++) {
asCFuncdefType *funcDef = currType->childFuncDefs[n];
if (funcDef && funcDef->name == type)
return funcDef;
}
currType = currType->derivedFrom;
}
}
return 0;
}
#ifndef AS_NO_COMPILER
int asCBuilder::GetEnumValueFromType(asCEnumType *type, const char *name, asCDataType &outDt, asDWORD &outValue) {
if (!type || !(type->flags & asOBJ_ENUM))
return 0;
for (asUINT n = 0; n < type->enumValues.GetLength(); ++n) {
if (type->enumValues[n]->name == name) {
outDt = asCDataType::CreateType(type, true);
outValue = type->enumValues[n]->value;
return 1;
}
}
return 0;
}
int asCBuilder::GetEnumValue(const char *name, asCDataType &outDt, asDWORD &outValue, asSNameSpace *ns) {
bool found = false;
// Search all available enum types
asUINT t;
for (t = 0; t < engine->registeredEnums.GetLength(); t++) {
asCEnumType *et = engine->registeredEnums[t];
if (ns != et->nameSpace) continue;
// Don't bother with types the module doesn't have access to
if ((et->accessMask & module->m_accessMask) == 0)
continue;
if (GetEnumValueFromType(et, name, outDt, outValue)) {
if (!found)
found = true;
else {
// Found more than one value in different enum types
return 2;
}
}
}
for (t = 0; t < module->m_enumTypes.GetLength(); t++) {
asCEnumType *et = module->m_enumTypes[t];
if (ns != et->nameSpace) continue;
if (GetEnumValueFromType(et, name, outDt, outValue)) {
if (!found)
found = true;
else {
// Found more than one value in different enum types
return 2;
}
}
}
if (found)
return 1;
// Didn't find any value
return 0;
}
#endif // AS_NO_COMPILER
END_AS_NAMESPACE
|