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
|
/*
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_module.cpp
//
// A class that holds a script module
//
#include "as_config.h"
#include "as_module.h"
#include "as_builder.h"
#include "as_context.h"
#include "as_texts.h"
#include "as_debug.h"
#include "as_restore.h"
BEGIN_AS_NAMESPACE
// internal
asCModule::asCModule(const char *name, asCScriptEngine *engine) {
m_name = name;
m_engine = engine;
m_userData = 0;
m_builder = 0;
m_isGlobalVarInitialized = false;
m_accessMask = 1;
m_defaultNamespace = engine->nameSpaces[0];
}
// internal
asCModule::~asCModule() {
InternalReset();
// The builder is not removed by InternalReset because it holds the script
// sections that will be built, so we need to explictly remove it now if it exists
if (m_builder) {
asDELETE(m_builder, asCBuilder);
m_builder = 0;
}
if (m_engine) {
// Clean the user data
for (asUINT n = 0; n < m_userData.GetLength(); n += 2) {
if (m_userData[n + 1]) {
for (asUINT c = 0; c < m_engine->cleanModuleFuncs.GetLength(); c++)
if (m_engine->cleanModuleFuncs[c].type == m_userData[n])
m_engine->cleanModuleFuncs[c].cleanFunc(this);
}
}
// Remove the module from the engine
ACQUIREEXCLUSIVE(m_engine->engineRWLock);
// The module must have been discarded before it is deleted
asASSERT(!m_engine->scriptModules.Exists(this));
m_engine->discardedModules.RemoveValue(this);
RELEASEEXCLUSIVE(m_engine->engineRWLock);
}
}
// interface
void asCModule::Discard() {
// Reset the global variables already so that no object in the global variables keep the module alive forever.
// If any live object tries to access the global variables during clean up they will fail with a script exception,
// so the application must keep that in mind before discarding a module.
CallExit();
// Keep a local copy of the engine pointer, because once the module is moved do the discarded
// pile, it is possible that another thread might discard it while we are still in here. So no
// further access to members may be done after that
asCScriptEngine *engine = m_engine;
// Instead of deleting the module immediately, move it to the discarded pile
// This will turn it invisible to the application, yet keep it alive until all
// external references to its entities have been released.
ACQUIREEXCLUSIVE(engine->engineRWLock);
if (engine->lastModule == this)
engine->lastModule = 0;
engine->scriptModules.RemoveValue(this);
engine->discardedModules.PushLast(this);
RELEASEEXCLUSIVE(engine->engineRWLock);
// Allow the engine to go over the list of discarded modules to see what can be cleaned up at this moment.
// Don't do this if the engine is already shutting down, as it will be done explicitly by the engine itself with error reporting
if (!engine->shuttingDown) {
if (engine->ep.autoGarbageCollect)
engine->GarbageCollect();
else {
// GarbageCollect calls DeleteDiscardedModules, so no need
// to call it again if we already called GarbageCollect
engine->DeleteDiscardedModules();
}
}
}
// interface
void *asCModule::SetUserData(void *data, asPWORD type) {
// As a thread might add a new new user data at the same time as another
// it is necessary to protect both read and write access to the userData member
ACQUIREEXCLUSIVE(m_engine->engineRWLock);
// It is not intended to store a lot of different types of userdata,
// so a more complex structure like a associative map would just have
// more overhead than a simple array.
for (asUINT n = 0; n < m_userData.GetLength(); n += 2) {
if (m_userData[n] == type) {
void *oldData = reinterpret_cast<void *>(m_userData[n + 1]);
m_userData[n + 1] = reinterpret_cast<asPWORD>(data);
RELEASEEXCLUSIVE(m_engine->engineRWLock);
return oldData;
}
}
m_userData.PushLast(type);
m_userData.PushLast(reinterpret_cast<asPWORD>(data));
RELEASEEXCLUSIVE(m_engine->engineRWLock);
return 0;
}
// interface
void *asCModule::GetUserData(asPWORD type) const {
// There may be multiple threads reading, but when
// setting the user data nobody must be reading.
ACQUIRESHARED(m_engine->engineRWLock);
for (asUINT n = 0; n < m_userData.GetLength(); n += 2) {
if (m_userData[n] == type) {
void *ud = reinterpret_cast<void *>(m_userData[n + 1]);
RELEASESHARED(m_engine->engineRWLock);
return ud;
}
}
RELEASESHARED(m_engine->engineRWLock);
return 0;
}
// interface
asIScriptEngine *asCModule::GetEngine() const {
return m_engine;
}
// interface
void asCModule::SetName(const char *in_name) {
m_name = in_name;
}
// interface
const char *asCModule::GetName() const {
return m_name.AddressOf();
}
// interface
const char *asCModule::GetDefaultNamespace() const {
return m_defaultNamespace->name.AddressOf();
}
// interface
int asCModule::SetDefaultNamespace(const char *nameSpace) {
// TODO: cleanup: This function is similar to asCScriptEngine::SetDefaultNamespace. Can we reuse the code?
if (nameSpace == 0)
return asINVALID_ARG;
asCString ns = nameSpace;
if (ns != "") {
// Make sure the namespace is composed of alternating identifier and ::
size_t pos = 0;
bool expectIdentifier = true;
size_t len;
eTokenType t = ttIdentifier;
for (; pos < ns.GetLength(); pos += len) {
t = m_engine->tok.GetToken(ns.AddressOf() + pos, ns.GetLength() - pos, &len);
if ((expectIdentifier && t != ttIdentifier) || (!expectIdentifier && t != ttScope))
return asINVALID_DECLARATION;
expectIdentifier = !expectIdentifier;
}
// If the namespace ends with :: then strip it off
if (t == ttScope)
ns.SetLength(ns.GetLength() - 2);
}
m_defaultNamespace = m_engine->AddNameSpace(ns.AddressOf());
return 0;
}
// interface
int asCModule::AddScriptSection(const char *in_name, const char *in_code, size_t in_codeLength, int in_lineOffset) {
#ifdef AS_NO_COMPILER
UNUSED_VAR(in_name);
UNUSED_VAR(in_code);
UNUSED_VAR(in_codeLength);
UNUSED_VAR(in_lineOffset);
return asNOT_SUPPORTED;
#else
if (!m_builder) {
m_builder = asNEW(asCBuilder)(m_engine, this);
if (m_builder == 0)
return asOUT_OF_MEMORY;
}
return m_builder->AddCode(in_name, in_code, (int)in_codeLength, in_lineOffset, (int)m_engine->GetScriptSectionNameIndex(in_name ? in_name : ""), m_engine->ep.copyScriptSections);
#endif
}
// internal
void asCModule::JITCompile() {
asIJITCompiler *jit = m_engine->GetJITCompiler();
if (!jit)
return;
for (unsigned int i = 0; i < m_scriptFunctions.GetLength(); i++)
m_scriptFunctions[i]->JITCompile();
}
// interface
int asCModule::Build() {
#ifdef AS_NO_COMPILER
return asNOT_SUPPORTED;
#else
TimeIt("asCModule::Build");
// Don't allow the module to be rebuilt if there are still
// external references that will need the previous code
// TODO: interface: The asIScriptModule must have a method for querying if the module is used
if (HasExternalReferences(false)) {
m_engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_MODULE_IS_IN_USE);
return asMODULE_IS_IN_USE;
}
// Only one thread may build at one time
// TODO: It should be possible to have multiple threads perform compilations
int r = m_engine->RequestBuild();
if (r < 0)
return r;
m_engine->PrepareEngine();
if (m_engine->configFailed) {
m_engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_INVALID_CONFIGURATION);
m_engine->BuildCompleted();
return asINVALID_CONFIGURATION;
}
InternalReset();
if (!m_builder) {
m_engine->BuildCompleted();
return asSUCCESS;
}
// Compile the script
r = m_builder->Build();
asDELETE(m_builder, asCBuilder);
m_builder = 0;
if (r < 0) {
// Reset module again
InternalReset();
m_engine->BuildCompleted();
return r;
}
JITCompile();
m_engine->PrepareEngine();
#ifdef AS_DEBUG
// Verify that there are no unwanted gaps in the scriptFunctions array.
for (asUINT n = 1; n < m_engine->scriptFunctions.GetLength(); n++) {
int id = n;
if (m_engine->scriptFunctions[n] == 0 && !m_engine->freeScriptFunctionIds.Exists(id))
asASSERT(false);
}
#endif
m_engine->BuildCompleted();
// Initialize global variables
if (r >= 0 && m_engine->ep.initGlobalVarsAfterBuild)
r = ResetGlobalVars(0);
return r;
#endif
}
// interface
int asCModule::ResetGlobalVars(asIScriptContext *ctx) {
if (m_isGlobalVarInitialized)
CallExit();
return CallInit(ctx);
}
// interface
asIScriptFunction *asCModule::GetFunctionByIndex(asUINT index) const {
return const_cast<asCScriptFunction *>(m_globalFunctions.Get(index));
}
// internal
int asCModule::CallInit(asIScriptContext *myCtx) {
if (m_isGlobalVarInitialized)
return asERROR;
// Each global variable needs to be cleared individually
asCSymbolTableIterator<asCGlobalProperty> it = m_scriptGlobals.List();
while (it) {
asCGlobalProperty *desc = *it;
memset(desc->GetAddressOfValue(), 0, sizeof(asDWORD)*desc->type.GetSizeOnStackDWords());
it++;
}
// Call the init function for each of the global variables
asIScriptContext *ctx = myCtx;
int r = asEXECUTION_FINISHED;
it = m_scriptGlobals.List();
while (it && r == asEXECUTION_FINISHED) {
asCGlobalProperty *desc = *it;
it++;
if (desc->GetInitFunc()) {
if (ctx == 0) {
ctx = m_engine->RequestContext();
if (ctx == 0)
break;
}
r = InitGlobalProp(desc, ctx);
}
}
if (ctx && !myCtx) {
m_engine->ReturnContext(ctx);
ctx = 0;
}
// Even if the initialization failed we need to set the
// flag that the variables have been initialized, otherwise
// the module won't free those variables that really were
// initialized.
m_isGlobalVarInitialized = true;
if (r != asEXECUTION_FINISHED)
return asINIT_GLOBAL_VARS_FAILED;
return asSUCCESS;
}
// internal
// This function assumes the memory for the global property is already cleared
int asCModule::InitGlobalProp(asCGlobalProperty *prop, asIScriptContext *myCtx) {
// Call the init function for each of the global variables
asIScriptContext *ctx = myCtx;
int r = asEXECUTION_FINISHED;
if (prop->GetInitFunc()) {
if (ctx == 0) {
ctx = m_engine->RequestContext();
if (ctx == 0)
return asERROR;
}
r = ctx->Prepare(prop->GetInitFunc());
if (r >= 0) {
r = ctx->Execute();
if (r != asEXECUTION_FINISHED) {
asCString msg;
msg.Format(TXT_FAILED_TO_INITIALIZE_s, prop->name.AddressOf());
asCScriptFunction *func = prop->GetInitFunc();
m_engine->WriteMessage(func->scriptData->scriptSectionIdx >= 0 ? m_engine->scriptSectionNames[func->scriptData->scriptSectionIdx]->AddressOf() : "",
func->GetLineNumber(0, 0) & 0xFFFFF,
func->GetLineNumber(0, 0) >> 20,
asMSGTYPE_ERROR,
msg.AddressOf());
if (r == asEXECUTION_EXCEPTION) {
const asIScriptFunction *function = ctx->GetExceptionFunction();
msg.Format(TXT_EXCEPTION_s_IN_s, ctx->GetExceptionString(), function->GetDeclaration());
m_engine->WriteMessage(function->GetScriptSectionName(),
ctx->GetExceptionLineNumber(),
0,
asMSGTYPE_INFORMATION,
msg.AddressOf());
}
}
}
}
if (ctx && !myCtx) {
m_engine->ReturnContext(ctx);
ctx = 0;
}
// Even if the initialization failed we need to set the
// flag that the variables have been initialized, otherwise
// the module won't free those variables that really were
// initialized.
m_isGlobalVarInitialized = true;
if (r != asEXECUTION_FINISHED)
return asINIT_GLOBAL_VARS_FAILED;
return asSUCCESS;
}
// internal
void asCModule::UninitializeGlobalProp(asCGlobalProperty *prop) {
if (prop == 0)
return;
if (prop->type.IsObject()) {
void **obj = (void **)prop->GetAddressOfValue();
if (*obj) {
asCObjectType *ot = CastToObjectType(prop->type.GetTypeInfo());
if (ot->flags & asOBJ_REF) {
asASSERT((ot->flags & asOBJ_NOCOUNT) || ot->beh.release);
if (ot->beh.release)
m_engine->CallObjectMethod(*obj, ot->beh.release);
} else {
if (ot->beh.destruct)
m_engine->CallObjectMethod(*obj, ot->beh.destruct);
m_engine->CallFree(*obj);
}
// Set the address to 0 as someone might try to access the variable afterwards
*obj = 0;
}
} else if (prop->type.IsFuncdef()) {
asCScriptFunction **func = (asCScriptFunction **)prop->GetAddressOfValue();
if (*func) {
(*func)->Release();
*func = 0;
}
}
}
// internal
void asCModule::CallExit() {
if (!m_isGlobalVarInitialized) return;
asCSymbolTableIterator<asCGlobalProperty> it = m_scriptGlobals.List();
while (it) {
UninitializeGlobalProp(*it);
it++;
}
m_isGlobalVarInitialized = false;
}
// internal
bool asCModule::HasExternalReferences(bool shuttingDown) {
// Check all entities in the module for any external references.
// If there are any external references the module cannot be deleted yet.
asCSymbolTableIterator<asCGlobalProperty> it = m_scriptGlobals.List();
while (it) {
asCGlobalProperty *desc = *it;
if (desc->GetInitFunc() && desc->GetInitFunc()->externalRefCount.get()) {
if (!shuttingDown)
return true;
else {
asCString msg;
msg.Format(TXT_EXTRNL_REF_TO_MODULE_s, m_name.AddressOf());
m_engine->WriteMessage("", 0, 0, asMSGTYPE_WARNING, msg.AddressOf());
// TODO: Use a better error message
asCString tmpName = "init " + desc->name;
msg.Format(TXT_PREV_FUNC_IS_NAMED_s_TYPE_IS_d, tmpName.AddressOf(), desc->GetInitFunc()->GetFuncType());
m_engine->WriteMessage("", 0, 0, asMSGTYPE_INFORMATION, msg.AddressOf());
}
}
it++;
}
for (asUINT n = 0; n < m_scriptFunctions.GetLength(); n++) {
asCScriptFunction *func = m_scriptFunctions[n];
if (func && func->externalRefCount.get()) {
// If the func is shared and can be moved to another module then this is not a reason to keep the module alive
if (func->IsShared() && m_engine->FindNewOwnerForSharedFunc(func, this) != this)
continue;
if (!shuttingDown)
return true;
else {
asCString msg;
msg.Format(TXT_EXTRNL_REF_TO_MODULE_s, m_name.AddressOf());
m_engine->WriteMessage("", 0, 0, asMSGTYPE_WARNING, msg.AddressOf());
msg.Format(TXT_PREV_FUNC_IS_NAMED_s_TYPE_IS_d, m_scriptFunctions[n]->GetName(), m_scriptFunctions[n]->GetFuncType());
m_engine->WriteMessage("", 0, 0, asMSGTYPE_INFORMATION, msg.AddressOf());
}
}
}
for (asUINT n = 0; n < m_classTypes.GetLength(); n++) {
asCObjectType *obj = m_classTypes[n];
if (obj && obj->externalRefCount.get()) {
// If the obj is shared and can be moved to another module then this is not a reason to keep the module alive
if (obj->IsShared() && m_engine->FindNewOwnerForSharedType(obj, this) != this)
continue;
if (!shuttingDown)
return true;
else {
asCString msg;
msg.Format(TXT_EXTRNL_REF_TO_MODULE_s, m_name.AddressOf());
m_engine->WriteMessage("", 0, 0, asMSGTYPE_WARNING, msg.AddressOf());
msg.Format(TXT_PREV_TYPE_IS_NAMED_s, m_classTypes[n]->GetName());
m_engine->WriteMessage("", 0, 0, asMSGTYPE_INFORMATION, msg.AddressOf());
}
}
}
for (asUINT n = 0; n < m_funcDefs.GetLength(); n++) {
asCFuncdefType *func = m_funcDefs[n];
if (func && func->externalRefCount.get()) {
// If the funcdef is shared and can be moved to another module then this is not a reason to keep the module alive
if (func->IsShared() && m_engine->FindNewOwnerForSharedType(func, this) != this)
continue;
if (!shuttingDown)
return true;
else {
asCString msg;
msg.Format(TXT_EXTRNL_REF_TO_MODULE_s, m_name.AddressOf());
m_engine->WriteMessage("", 0, 0, asMSGTYPE_WARNING, msg.AddressOf());
msg.Format(TXT_PREV_FUNC_IS_NAMED_s_TYPE_IS_d, m_funcDefs[n]->GetName(), m_funcDefs[n]->funcdef->GetFuncType());
m_engine->WriteMessage("", 0, 0, asMSGTYPE_INFORMATION, msg.AddressOf());
}
}
}
for (asUINT n = 0; n < m_templateInstances.GetLength(); n++) {
asCObjectType *obj = m_templateInstances[n];
if (obj && obj->externalRefCount.get()) {
// If the template can be moved to another module then this is not a reason to keep the module alive
if (obj->IsShared() && m_engine->FindNewOwnerForSharedType(obj, this) != this)
continue;
if (!shuttingDown)
return true;
else {
asCString msg;
msg.Format(TXT_EXTRNL_REF_TO_MODULE_s, m_name.AddressOf());
m_engine->WriteMessage("", 0, 0, asMSGTYPE_WARNING, msg.AddressOf());
msg.Format(TXT_PREV_TYPE_IS_NAMED_s, m_templateInstances[n]->GetName());
m_engine->WriteMessage("", 0, 0, asMSGTYPE_INFORMATION, msg.AddressOf());
}
}
}
return false;
}
// internal
void asCModule::InternalReset() {
CallExit();
asUINT n;
// Remove all global functions
m_globalFunctions.Clear();
// Destroy the internals of the global properties here, but do not yet remove them from the
// engine, because functions need the engine's varAddressMap to get to the property. If the
// property is removed already, it may leak as the refCount doesn't reach 0.
asCSymbolTableIterator<asCGlobalProperty> globIt = m_scriptGlobals.List();
while (globIt) {
(*globIt)->DestroyInternal();
globIt++;
}
UnbindAllImportedFunctions();
// Free bind information
for (n = 0; n < m_bindInformations.GetLength(); n++) {
if (m_bindInformations[n]) {
m_bindInformations[n]->importedFunctionSignature->ReleaseInternal();
asDELETE(m_bindInformations[n], sBindInfo);
}
}
m_bindInformations.SetLength(0);
// Free declared types, including classes, typedefs, and enums
for (n = 0; n < m_templateInstances.GetLength(); n++) {
asCObjectType *type = m_templateInstances[n];
if (m_engine->FindNewOwnerForSharedType(type, this) != this) {
// The type is owned by another module, just release our reference
type->ReleaseInternal();
continue;
}
// Orphan the template instance
type->module = 0;
// No other module is holding the template type
m_engine->RemoveTemplateInstanceType(type);
type->ReleaseInternal();
}
m_templateInstances.SetLength(0);
for (n = 0; n < m_classTypes.GetLength(); n++) {
asCObjectType *type = m_classTypes[n];
if (type->IsShared()) {
// The type is shared, so transfer ownership to another module that also uses it
if (m_engine->FindNewOwnerForSharedType(type, this) != this) {
// The type is owned by another module, just release our reference
type->ReleaseInternal();
continue;
}
}
// The type should be destroyed now
type->DestroyInternal();
// Remove the type from the engine
if (type->IsShared()) {
m_engine->sharedScriptTypes.RemoveValue(type);
type->ReleaseInternal();
}
// Release it from the module
type->module = 0;
type->ReleaseInternal();
}
m_classTypes.SetLength(0);
for (n = 0; n < m_enumTypes.GetLength(); n++) {
asCEnumType *type = m_enumTypes[n];
if (type->IsShared()) {
// The type is shared, so transfer ownership to another module that also uses it
if (m_engine->FindNewOwnerForSharedType(type, this) != this) {
// The type is owned by another module, just release our reference
type->ReleaseInternal();
continue;
}
}
// Remove the type from the engine
if (type->IsShared()) {
m_engine->sharedScriptTypes.RemoveValue(type);
type->ReleaseInternal();
}
// Release it from the module
type->module = 0;
type->ReleaseInternal();
}
m_enumTypes.SetLength(0);
for (n = 0; n < m_typeDefs.GetLength(); n++) {
asCTypedefType *type = m_typeDefs[n];
// The type should be destroyed now
type->DestroyInternal();
// Release it from the module
type->module = 0;
type->ReleaseInternal();
}
m_typeDefs.SetLength(0);
// Free funcdefs
for (n = 0; n < m_funcDefs.GetLength(); n++) {
asCFuncdefType *func = m_funcDefs[n];
asASSERT(func);
if (func->funcdef && func->funcdef->IsShared()) {
// The funcdef is shared, so transfer ownership to another module that also uses it
if (m_engine->FindNewOwnerForSharedType(func, this) != this) {
// The funcdef is owned by another module, just release our reference
func->ReleaseInternal();
continue;
}
}
func->DestroyInternal();
m_engine->RemoveFuncdef(func);
func->module = 0;
func->ReleaseInternal();
}
m_funcDefs.SetLength(0);
// Then release the functions
for (n = 0; n < m_scriptFunctions.GetLength(); n++) {
asCScriptFunction *func = m_scriptFunctions[n];
if (func->IsShared()) {
// The func is shared, so transfer ownership to another module that also uses it
if (m_engine->FindNewOwnerForSharedFunc(func, this) != this) {
// The func is owned by another module, just release our reference
func->ReleaseInternal();
continue;
}
}
func->DestroyInternal();
func->module = 0;
func->ReleaseInternal();
}
m_scriptFunctions.SetLength(0);
// Now remove and release the global properties as there are no more references to them
globIt = m_scriptGlobals.List();
while (globIt) {
m_engine->RemoveGlobalProperty(*globIt);
asASSERT((*globIt)->refCount.get() == 1);
(*globIt)->Release();
globIt++;
}
m_scriptGlobals.Clear();
// Clear the type lookup
// The references were already released as the types were removed from the respective arrays
m_typeLookup.EraseAll();
asASSERT(IsEmpty());
}
// interface
asIScriptFunction *asCModule::GetFunctionByName(const char *in_name) const {
asCString name;
asSNameSpace *ns = 0;
if (m_engine->DetermineNameAndNamespace(in_name, m_defaultNamespace, name, ns) < 0)
return 0;
// Search recursively in the given namespace, moving up to parent namespace until the function is found
while (ns) {
const asCArray<unsigned int> &idxs = m_globalFunctions.GetIndexes(ns, name);
if (idxs.GetLength() != 1)
return 0;
const asIScriptFunction *func = m_globalFunctions.Get(idxs[0]);
if (func)
return const_cast<asIScriptFunction *>(func);
// Recursively search parent namespaces
ns = m_engine->GetParentNameSpace(ns);
}
return 0;
}
// interface
asUINT asCModule::GetImportedFunctionCount() const {
return (asUINT)m_bindInformations.GetLength();
}
// interface
int asCModule::GetImportedFunctionIndexByDecl(const char *decl) const {
asCBuilder bld(m_engine, const_cast<asCModule *>(this));
// Don't write parser errors to the message callback
bld.silent = true;
asCScriptFunction func(m_engine, const_cast<asCModule *>(this), asFUNC_DUMMY);
bld.ParseFunctionDeclaration(0, decl, &func, false, 0, 0, m_defaultNamespace);
// TODO: optimize: Improve linear search
// Search script functions for matching interface
int id = -1;
for (asUINT n = 0; n < m_bindInformations.GetLength(); ++n) {
if (func.name == m_bindInformations[n]->importedFunctionSignature->name &&
func.returnType == m_bindInformations[n]->importedFunctionSignature->returnType &&
func.parameterTypes.GetLength() == m_bindInformations[n]->importedFunctionSignature->parameterTypes.GetLength()) {
bool match = true;
for (asUINT p = 0; p < func.parameterTypes.GetLength(); ++p) {
if (func.parameterTypes[p] != m_bindInformations[n]->importedFunctionSignature->parameterTypes[p]) {
match = false;
break;
}
}
if (match) {
if (id == -1)
id = n;
else
return asMULTIPLE_FUNCTIONS;
}
}
}
if (id == -1) return asNO_FUNCTION;
return id;
}
// interface
asUINT asCModule::GetFunctionCount() const {
return (asUINT)m_globalFunctions.GetSize();
}
// interface
asIScriptFunction *asCModule::GetFunctionByDecl(const char *decl) const {
asCBuilder bld(m_engine, const_cast<asCModule *>(this));
// Don't write parser errors to the message callback
bld.silent = true;
asCScriptFunction func(m_engine, const_cast<asCModule *>(this), asFUNC_DUMMY);
int r = bld.ParseFunctionDeclaration(0, decl, &func, false, 0, 0, m_defaultNamespace);
if (r < 0) {
// Invalid declaration
// TODO: Write error to message stream
return 0;
}
// Use the defaultNamespace implicitly unless an explicit namespace has been provided
asSNameSpace *ns = func.nameSpace == m_engine->nameSpaces[0] ? m_defaultNamespace : func.nameSpace;
// Search script functions for matching interface
while (ns) {
asIScriptFunction *f = 0;
const asCArray<unsigned int> &idxs = m_globalFunctions.GetIndexes(ns, func.name);
for (unsigned int n = 0; n < idxs.GetLength(); n++) {
const asCScriptFunction *funcPtr = m_globalFunctions.Get(idxs[n]);
if (funcPtr->objectType == 0 &&
func.returnType == funcPtr->returnType &&
func.parameterTypes.GetLength() == funcPtr->parameterTypes.GetLength()
) {
bool match = true;
for (asUINT p = 0; p < func.parameterTypes.GetLength(); ++p) {
if (func.parameterTypes[p] != funcPtr->parameterTypes[p]) {
match = false;
break;
}
}
if (match) {
if (f == 0)
f = const_cast<asCScriptFunction *>(funcPtr);
else
// Multiple functions
return 0;
}
}
}
if (f)
return f;
else {
// Search for matching functions in the parent namespace
ns = m_engine->GetParentNameSpace(ns);
}
}
return 0;
}
// interface
asUINT asCModule::GetGlobalVarCount() const {
return (asUINT)m_scriptGlobals.GetSize();
}
// interface
int asCModule::GetGlobalVarIndexByName(const char *in_name) const {
asCString name;
asSNameSpace *ns = 0;
if (m_engine->DetermineNameAndNamespace(in_name, m_defaultNamespace, name, ns) < 0)
return asINVALID_ARG;
// Find the global var id
while (ns) {
int id = m_scriptGlobals.GetFirstIndex(ns, name);
if (id >= 0) return id;
// Recursively search parent namespaces
ns = m_engine->GetParentNameSpace(ns);
}
return asNO_GLOBAL_VAR;
}
// interface
int asCModule::RemoveGlobalVar(asUINT index) {
asCGlobalProperty *prop = m_scriptGlobals.Get(index);
if (!prop)
return asINVALID_ARG;
// If the global variables have already been initialized
// then uninitialize the variable before it is removed
if (m_isGlobalVarInitialized)
UninitializeGlobalProp(prop);
// Destroy the internal of the global variable (removes the initialization function)
prop->DestroyInternal();
// Check if the module is the only one referring to the property, if so remove it from the engine too
// If the property is not removed now, it will be removed later when the module is discarded
if (prop->refCount.get() == 2)
m_engine->RemoveGlobalProperty(prop);
// Remove the global variable from the module
m_scriptGlobals.Erase(index);
prop->Release();
return 0;
}
// interface
int asCModule::GetGlobalVarIndexByDecl(const char *decl) const {
asCBuilder bld(m_engine, const_cast<asCModule *>(this));
// Don't write parser errors to the message callback
bld.silent = true;
asCString declName;
asSNameSpace *nameSpace;
asCDataType dt;
int r = bld.ParseVariableDeclaration(decl, m_defaultNamespace, declName, nameSpace, dt);
if (r < 0)
return r;
// Search global variables for a match
while (nameSpace) {
int id = m_scriptGlobals.GetFirstIndex(nameSpace, declName, asCCompGlobPropType(dt));
if (id != -1)
return id;
// Recursively search parent namespace
nameSpace = m_engine->GetParentNameSpace(nameSpace);
}
return asNO_GLOBAL_VAR;
}
// interface
void *asCModule::GetAddressOfGlobalVar(asUINT index) {
asCGlobalProperty *prop = m_scriptGlobals.Get(index);
if (!prop)
return 0;
// For object variables it's necessary to dereference the pointer to get the address of the value
if (prop->type.IsObject() &&
!prop->type.IsObjectHandle())
return *(void **)(prop->GetAddressOfValue());
return (void *)(prop->GetAddressOfValue());
}
// interface
const char *asCModule::GetGlobalVarDeclaration(asUINT index, bool includeNamespace) const {
const asCGlobalProperty *prop = m_scriptGlobals.Get(index);
if (!prop) return 0;
asCString *tempString = &asCThreadManager::GetLocalData()->string;
*tempString = prop->type.Format(m_defaultNamespace);
*tempString += " ";
if (includeNamespace && prop->nameSpace->name != "")
*tempString += prop->nameSpace->name + "::";
*tempString += prop->name;
return tempString->AddressOf();
}
// interface
int asCModule::GetGlobalVar(asUINT index, const char **out_name, const char **out_nameSpace, int *out_typeId, bool *out_isConst) const {
const asCGlobalProperty *prop = m_scriptGlobals.Get(index);
if (!prop) return asINVALID_ARG;
if (out_name)
*out_name = prop->name.AddressOf();
if (out_nameSpace)
*out_nameSpace = prop->nameSpace->name.AddressOf();
if (out_typeId)
*out_typeId = m_engine->GetTypeIdFromDataType(prop->type);
if (out_isConst)
*out_isConst = prop->type.IsReadOnly();
return asSUCCESS;
}
// interface
asUINT asCModule::GetObjectTypeCount() const {
return (asUINT)m_classTypes.GetLength();
}
// interface
asITypeInfo *asCModule::GetObjectTypeByIndex(asUINT index) const {
if (index >= m_classTypes.GetLength())
return 0;
return m_classTypes[index];
}
// interface
asITypeInfo *asCModule::GetTypeInfoByName(const char *in_name) const {
asCString name;
asSNameSpace *ns = 0;
if (m_engine->DetermineNameAndNamespace(in_name, m_defaultNamespace, name, ns) < 0)
return 0;
while (ns) {
asITypeInfo *info = GetType(name, ns);
if (info) {
return info;
}
// Recursively search parent namespace
ns = m_engine->GetParentNameSpace(ns);
}
return 0;
}
// interface
int asCModule::GetTypeIdByDecl(const char *decl) const {
asCDataType dt;
// This const cast is safe since we know the engine won't be modified
asCBuilder bld(m_engine, const_cast<asCModule *>(this));
// Don't write parser errors to the message callback
bld.silent = true;
int r = bld.ParseDataType(decl, &dt, m_defaultNamespace);
if (r < 0)
return asINVALID_TYPE;
return m_engine->GetTypeIdFromDataType(dt);
}
// interface
asITypeInfo *asCModule::GetTypeInfoByDecl(const char *decl) const {
asCDataType dt;
// This const cast is safe since we know the engine won't be modified
asCBuilder bld(m_engine, const_cast<asCModule *>(this));
// Don't write parser errors to the message callback
bld.silent = true;
int r = bld.ParseDataType(decl, &dt, m_defaultNamespace);
if (r < 0)
return 0;
return dt.GetTypeInfo();
}
// interface
asUINT asCModule::GetEnumCount() const {
return m_enumTypes.GetLength();
}
// interface
asITypeInfo *asCModule::GetEnumByIndex(asUINT index) const {
if (index >= m_enumTypes.GetLength())
return 0;
return m_enumTypes[index];
}
// interface
asUINT asCModule::GetTypedefCount() const {
return (asUINT)m_typeDefs.GetLength();
}
// interface
asITypeInfo *asCModule::GetTypedefByIndex(asUINT index) const {
if (index >= m_typeDefs.GetLength())
return 0;
return m_typeDefs[index];
}
// internal
int asCModule::GetNextImportedFunctionId() {
// TODO: multithread: This will break if one thread if freeing a module, while another is being compiled
if (m_engine->freeImportedFunctionIdxs.GetLength())
return FUNC_IMPORTED | (asUINT)m_engine->freeImportedFunctionIdxs[m_engine->freeImportedFunctionIdxs.GetLength() - 1];
return FUNC_IMPORTED | (asUINT)m_engine->importedFunctions.GetLength();
}
#ifndef AS_NO_COMPILER
// internal
int asCModule::AddScriptFunction(int sectionIdx, int declaredAt, int id, const asCString &funcName, const asCDataType &returnType, const asCArray<asCDataType> ¶ms, const asCArray<asCString> ¶mNames, const asCArray<asETypeModifiers> &inOutFlags, const asCArray<asCString *> &defaultArgs, bool isInterface, asCObjectType *objType, bool isGlobalFunction, asSFunctionTraits funcTraits, asSNameSpace *ns) {
asASSERT(id >= 0);
// Store the function information
asCScriptFunction *func = asNEW(asCScriptFunction)(m_engine, this, isInterface ? asFUNC_INTERFACE : asFUNC_SCRIPT);
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;
}
if (ns == 0)
ns = m_engine->nameSpaces[0];
// All methods of shared objects are also shared
if (objType && objType->IsShared())
funcTraits.SetTrait(asTRAIT_SHARED, true);
func->name = funcName;
func->nameSpace = ns;
func->id = id;
func->returnType = returnType;
if (func->funcType == asFUNC_SCRIPT) {
func->scriptData->scriptSectionIdx = sectionIdx;
func->scriptData->declaredAt = declaredAt;
}
func->parameterTypes = params;
func->parameterNames = paramNames;
func->inOutFlags = inOutFlags;
func->defaultArgs = defaultArgs;
func->objectType = objType;
if (objType)
objType->AddRefInternal();
func->traits = funcTraits;
asASSERT(params.GetLength() == inOutFlags.GetLength() && params.GetLength() == defaultArgs.GetLength());
// Verify that we are not assigning either the final or override specifier(s) if we are registering a non-member function
asASSERT(!(!objType && funcTraits.GetTrait(asTRAIT_FINAL)));
asASSERT(!(!objType && funcTraits.GetTrait(asTRAIT_OVERRIDE)));
// The internal ref count was already set by the constructor
m_scriptFunctions.PushLast(func);
m_engine->AddScriptFunction(func);
// Compute the signature id
if (objType)
func->ComputeSignatureId();
// Add reference
if (isGlobalFunction)
m_globalFunctions.Put(func);
return 0;
}
// internal
int asCModule::AddScriptFunction(asCScriptFunction *func) {
m_scriptFunctions.PushLast(func);
func->AddRefInternal();
m_engine->AddScriptFunction(func);
// If the function that is being added is an already compiled shared function
// then it is necessary to look for anonymous functions that may be declared
// within it and add those as well
if (func->IsShared() && func->funcType == asFUNC_SCRIPT) {
// Loop through the byte code and check all the
// asBC_FuncPtr instructions for anonymous functions
asDWORD *bc = func->scriptData->byteCode.AddressOf();
asUINT bcLength = (asUINT)func->scriptData->byteCode.GetLength();
for (asUINT n = 0; n < bcLength;) {
int c = *(asBYTE *)&bc[n];
if (c == asBC_FuncPtr) {
asCScriptFunction *f = reinterpret_cast<asCScriptFunction *>(asBC_PTRARG(&bc[n]));
// Anonymous functions start with $
// There are never two equal anonymous functions so it is not necessary to look for duplicates
if (f && f->name[0] == '$') {
AddScriptFunction(f);
m_globalFunctions.Put(f);
}
}
n += asBCTypeSize[asBCInfo[c].type];
}
}
return 0;
}
// internal
int asCModule::AddImportedFunction(int id, const asCString &funcName, const asCDataType &returnType, const asCArray<asCDataType> ¶ms, const asCArray<asETypeModifiers> &inOutFlags, const asCArray<asCString *> &defaultArgs, asSFunctionTraits funcTraits, asSNameSpace *ns, const asCString &moduleName) {
asASSERT(id >= 0);
// Store the function information
asCScriptFunction *func = asNEW(asCScriptFunction)(m_engine, this, asFUNC_IMPORTED);
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;
}
func->name = funcName;
func->id = id;
func->returnType = returnType;
func->nameSpace = ns;
func->parameterTypes = params;
func->inOutFlags = inOutFlags;
func->defaultArgs = defaultArgs;
func->objectType = 0;
func->traits = funcTraits;
sBindInfo *info = asNEW(sBindInfo);
if (info == 0) {
asDELETE(func, asCScriptFunction);
return asOUT_OF_MEMORY;
}
info->importedFunctionSignature = func;
info->boundFunctionId = -1;
info->importFromModule = moduleName;
m_bindInformations.PushLast(info);
// Add the info to the array in the engine
if (m_engine->freeImportedFunctionIdxs.GetLength())
m_engine->importedFunctions[m_engine->freeImportedFunctionIdxs.PopLast()] = info;
else
m_engine->importedFunctions.PushLast(info);
return 0;
}
#endif
// internal
asCScriptFunction *asCModule::GetImportedFunction(int index) const {
return m_bindInformations[index]->importedFunctionSignature;
}
// interface
int asCModule::BindImportedFunction(asUINT index, asIScriptFunction *func) {
// First unbind the old function
int r = UnbindImportedFunction(index);
if (r < 0) return r;
// Must verify that the interfaces are equal
asCScriptFunction *dst = GetImportedFunction(index);
if (dst == 0) return asNO_FUNCTION;
if (func == 0)
return asINVALID_ARG;
asCScriptFunction *src = m_engine->GetScriptFunction(func->GetId());
if (src == 0)
return asNO_FUNCTION;
// Verify return type
if (dst->returnType != src->returnType)
return asINVALID_INTERFACE;
if (dst->parameterTypes.GetLength() != src->parameterTypes.GetLength())
return asINVALID_INTERFACE;
for (asUINT n = 0; n < dst->parameterTypes.GetLength(); ++n) {
if (dst->parameterTypes[n] != src->parameterTypes[n])
return asINVALID_INTERFACE;
}
m_bindInformations[index]->boundFunctionId = src->GetId();
src->AddRefInternal();
return asSUCCESS;
}
// interface
int asCModule::UnbindImportedFunction(asUINT index) {
if (index >= m_bindInformations.GetLength())
return asINVALID_ARG;
// Remove reference to old module
if (m_bindInformations[index]) {
int oldFuncID = m_bindInformations[index]->boundFunctionId;
if (oldFuncID != -1) {
m_bindInformations[index]->boundFunctionId = -1;
m_engine->scriptFunctions[oldFuncID]->ReleaseInternal();
}
}
return asSUCCESS;
}
// interface
const char *asCModule::GetImportedFunctionDeclaration(asUINT index) const {
asCScriptFunction *func = GetImportedFunction(index);
if (func == 0) return 0;
asCString *tempString = &asCThreadManager::GetLocalData()->string;
// TODO: Allow the application to decide if the parameter name should be included or not (requires change in the interface)
*tempString = func->GetDeclarationStr(true, true, false);
return tempString->AddressOf();
}
// interface
const char *asCModule::GetImportedFunctionSourceModule(asUINT index) const {
if (index >= m_bindInformations.GetLength())
return 0;
return m_bindInformations[index]->importFromModule.AddressOf();
}
// inteface
int asCModule::BindAllImportedFunctions() {
bool notAllFunctionsWereBound = false;
// Bind imported functions
int c = GetImportedFunctionCount();
for (int n = 0; n < c; ++n) {
asCScriptFunction *importFunc = GetImportedFunction(n);
if (importFunc == 0) return asERROR;
asCString str = importFunc->GetDeclarationStr(false, true);
// Get module name from where the function should be imported
const char *moduleName = GetImportedFunctionSourceModule(n);
if (moduleName == 0) return asERROR;
asCModule *srcMod = m_engine->GetModule(moduleName, false);
asIScriptFunction *func = 0;
if (srcMod)
func = srcMod->GetFunctionByDecl(str.AddressOf());
if (func == 0)
notAllFunctionsWereBound = true;
else {
if (BindImportedFunction(n, func) < 0)
notAllFunctionsWereBound = true;
}
}
if (notAllFunctionsWereBound)
return asCANT_BIND_ALL_FUNCTIONS;
return asSUCCESS;
}
// interface
int asCModule::UnbindAllImportedFunctions() {
asUINT c = GetImportedFunctionCount();
for (asUINT n = 0; n < c; ++n)
UnbindImportedFunction(n);
return asSUCCESS;
}
// internal
void asCModule::AddClassType(asCObjectType *type) {
m_classTypes.PushLast(type);
m_typeLookup.Insert(asSNameSpaceNamePair(type->nameSpace, type->name), type);
}
// internal
void asCModule::AddEnumType(asCEnumType *type) {
m_enumTypes.PushLast(type);
m_typeLookup.Insert(asSNameSpaceNamePair(type->nameSpace, type->name), type);
}
// internal
void asCModule::AddTypeDef(asCTypedefType *type) {
m_typeDefs.PushLast(type);
m_typeLookup.Insert(asSNameSpaceNamePair(type->nameSpace, type->name), type);
}
// internal
void asCModule::AddFuncDef(asCFuncdefType *type) {
m_funcDefs.PushLast(type);
m_typeLookup.Insert(asSNameSpaceNamePair(type->nameSpace, type->name), type);
}
// internal
void asCModule::ReplaceFuncDef(asCFuncdefType *type, asCFuncdefType *newType) {
int i = m_funcDefs.IndexOf(type);
if (i >= 0) {
m_funcDefs[i] = newType;
// Replace it in the lookup map too
asSMapNode<asSNameSpaceNamePair, asCTypeInfo *> *result = 0;
if (m_typeLookup.MoveTo(&result, asSNameSpaceNamePair(type->nameSpace, type->name))) {
asASSERT(result->value == type);
result->value = newType;
}
}
}
// internal
asCTypeInfo *asCModule::GetType(const asCString &type, asSNameSpace *ns) const {
asSMapNode<asSNameSpaceNamePair, asCTypeInfo *> *result = 0;
if (m_typeLookup.MoveTo(&result, asSNameSpaceNamePair(ns, type))) {
return result->value;
}
return 0;
}
// internal
asCObjectType *asCModule::GetObjectType(const char *type, asSNameSpace *ns) const {
asSMapNode<asSNameSpaceNamePair, asCTypeInfo *> *result = 0;
if (m_typeLookup.MoveTo(&result, asSNameSpaceNamePair(ns, type))) {
return CastToObjectType(result->value);
}
return 0;
}
// internal
asCGlobalProperty *asCModule::AllocateGlobalProperty(const char *propName, const asCDataType &dt, asSNameSpace *ns) {
asCGlobalProperty *prop = m_engine->AllocateGlobalProperty();
prop->name = propName;
prop->nameSpace = ns;
// Allocate the memory for this property based on its type
prop->type = dt;
prop->AllocateMemory();
// Make an entry in the address to variable map
m_engine->varAddressMap.Insert(prop->GetAddressOfValue(), prop);
// Store the variable in the module scope
m_scriptGlobals.Put(prop);
prop->AddRef();
return prop;
}
// internal
bool asCModule::IsEmpty() const {
if (m_scriptFunctions.GetLength()) return false;
if (m_globalFunctions.GetSize()) return false;
if (m_bindInformations.GetLength()) return false;
if (m_scriptGlobals.GetSize()) return false;
if (m_classTypes.GetLength()) return false;
if (m_enumTypes.GetLength()) return false;
if (m_typeDefs.GetLength()) return false;
if (m_funcDefs.GetLength()) return false;
return true;
}
// interface
int asCModule::SaveByteCode(asIBinaryStream *out, bool stripDebugInfo) const {
#ifdef AS_NO_COMPILER
UNUSED_VAR(out);
UNUSED_VAR(stripDebugInfo);
return asNOT_SUPPORTED;
#else
if (out == 0) return asINVALID_ARG;
// Make sure there is actually something to save
if (IsEmpty())
return asERROR;
asCWriter write(const_cast<asCModule *>(this), out, m_engine, stripDebugInfo);
return write.Write();
#endif
}
// interface
int asCModule::LoadByteCode(asIBinaryStream *in, bool *wasDebugInfoStripped) {
if (in == 0) return asINVALID_ARG;
// Don't allow the module to be rebuilt if there are still
// external references that will need the previous code
if (HasExternalReferences(false)) {
m_engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_MODULE_IS_IN_USE);
return asMODULE_IS_IN_USE;
}
// Only permit loading bytecode if no other thread is currently compiling
// TODO: It should be possible to have multiple threads perform compilations
int r = m_engine->RequestBuild();
if (r < 0)
return r;
asCReader read(this, in, m_engine);
r = read.Read(wasDebugInfoStripped);
if (r < 0) {
m_engine->BuildCompleted();
return r;
}
JITCompile();
#ifdef AS_DEBUG
// Verify that there are no unwanted gaps in the scriptFunctions array.
for (asUINT n = 1; n < m_engine->scriptFunctions.GetLength(); n++) {
int id = n;
if (m_engine->scriptFunctions[n] == 0 && !m_engine->freeScriptFunctionIds.Exists(id))
asASSERT(false);
}
#endif
m_engine->BuildCompleted();
return r;
}
// interface
int asCModule::CompileGlobalVar(const char *sectionName, const char *code, int lineOffset) {
#ifdef AS_NO_COMPILER
UNUSED_VAR(sectionName);
UNUSED_VAR(code);
UNUSED_VAR(lineOffset);
return asNOT_SUPPORTED;
#else
// Validate arguments
if (code == 0)
return asINVALID_ARG;
// Only one thread may build at one time
// TODO: It should be possible to have multiple threads perform compilations
int r = m_engine->RequestBuild();
if (r < 0)
return r;
// Prepare the engine
m_engine->PrepareEngine();
if (m_engine->configFailed) {
m_engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_INVALID_CONFIGURATION);
m_engine->BuildCompleted();
return asINVALID_CONFIGURATION;
}
// Compile the global variable and add it to the module scope
asCBuilder varBuilder(m_engine, this);
asCString str = code;
r = varBuilder.CompileGlobalVar(sectionName, str.AddressOf(), lineOffset);
m_engine->BuildCompleted();
// Initialize the variable
if (r >= 0) {
// Clear the memory
asCGlobalProperty *prop = m_scriptGlobals.GetLast();
if (prop) {
memset(prop->GetAddressOfValue(), 0, sizeof(asDWORD)*prop->type.GetSizeOnStackDWords());
}
if (prop && m_engine->ep.initGlobalVarsAfterBuild) {
// Flag that there are initialized global variables
m_isGlobalVarInitialized = true;
r = InitGlobalProp(prop, 0);
}
}
return r;
#endif
}
// interface
int asCModule::CompileFunction(const char *sectionName, const char *code, int lineOffset, asDWORD compileFlags, asIScriptFunction **outFunc) {
// Make sure the outFunc is null if the function fails, so the
// application doesn't attempt to release a non-existent function
if (outFunc)
*outFunc = 0;
#ifdef AS_NO_COMPILER
UNUSED_VAR(sectionName);
UNUSED_VAR(code);
UNUSED_VAR(lineOffset);
UNUSED_VAR(compileFlags);
return asNOT_SUPPORTED;
#else
// Validate arguments
if (code == 0 ||
(compileFlags != 0 && compileFlags != asCOMP_ADD_TO_MODULE))
return asINVALID_ARG;
// Only one thread may build at one time
// TODO: It should be possible to have multiple threads perform compilations
int r = m_engine->RequestBuild();
if (r < 0)
return r;
// Prepare the engine
m_engine->PrepareEngine();
if (m_engine->configFailed) {
m_engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_INVALID_CONFIGURATION);
m_engine->BuildCompleted();
return asINVALID_CONFIGURATION;
}
// Compile the single function
asCBuilder funcBuilder(m_engine, this);
asCString str = code;
asCScriptFunction *func = 0;
r = funcBuilder.CompileFunction(sectionName, str.AddressOf(), lineOffset, compileFlags, &func);
if (r >= 0) {
// Invoke the JIT compiler if it has been set
asIJITCompiler *jit = m_engine->GetJITCompiler();
if (jit) {
func->JITCompile();
}
}
m_engine->BuildCompleted();
if (r >= 0 && outFunc && func) {
// Return the function to the caller and add an external reference
*outFunc = func;
func->AddRef();
}
// Release our reference to the function
if (func)
func->ReleaseInternal();
return r;
#endif
}
// interface
int asCModule::RemoveFunction(asIScriptFunction *func) {
// Find the global function
asCScriptFunction *f = static_cast<asCScriptFunction *>(func);
int idx = m_globalFunctions.GetIndex(f);
if (idx >= 0) {
m_globalFunctions.Erase(idx);
m_scriptFunctions.RemoveValue(f);
f->ReleaseInternal();
return 0;
}
return asNO_FUNCTION;
}
#ifndef AS_NO_COMPILER
// internal
int asCModule::AddFuncDef(const asCString &funcName, asSNameSpace *ns, asCObjectType *parent) {
// namespace and parent are mutually exclusive
asASSERT((ns == 0 && parent) || (ns && parent == 0));
asCScriptFunction *func = asNEW(asCScriptFunction)(m_engine, 0, asFUNC_FUNCDEF);
if (func == 0)
return asOUT_OF_MEMORY;
func->name = funcName;
func->nameSpace = ns;
func->module = this;
asCFuncdefType *fdt = asNEW(asCFuncdefType)(m_engine, func);
AddFuncDef(fdt); // The constructor set the refcount to 1
m_engine->funcDefs.PushLast(fdt); // doesn't increase refcount
func->id = m_engine->GetNextScriptFunctionId();
m_engine->AddScriptFunction(func);
if (parent) {
parent->childFuncDefs.PushLast(fdt);
fdt->parentClass = parent;
}
return (int)m_funcDefs.GetLength() - 1;
}
#endif
// interface
asDWORD asCModule::SetAccessMask(asDWORD mask) {
asDWORD old = m_accessMask;
m_accessMask = mask;
return old;
}
END_AS_NAMESPACE
|