as_module.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2011 Andreas Jonsson
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any
  6. damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any
  8. purpose, including commercial applications, and to alter it and
  9. redistribute it freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you
  11. must not claim that you wrote the original software. If you use
  12. this software in a product, an acknowledgment in the product
  13. documentation would be appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and
  15. must not be misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. The original version of this library can be located at:
  19. http://www.angelcode.com/angelscript/
  20. Andreas Jonsson
  21. [email protected]
  22. */
  23. //
  24. // as_module.cpp
  25. //
  26. // A class that holds a script module
  27. //
  28. #include "as_config.h"
  29. #include "as_module.h"
  30. #include "as_builder.h"
  31. #include "as_context.h"
  32. #include "as_texts.h"
  33. BEGIN_AS_NAMESPACE
  34. // internal
  35. asCModule::asCModule(const char *name, asCScriptEngine *engine)
  36. {
  37. this->name = name;
  38. this->engine = engine;
  39. builder = 0;
  40. isGlobalVarInitialized = false;
  41. }
  42. // internal
  43. asCModule::~asCModule()
  44. {
  45. InternalReset();
  46. if( builder )
  47. {
  48. asDELETE(builder,asCBuilder);
  49. builder = 0;
  50. }
  51. // Remove the module from the engine
  52. if( engine )
  53. {
  54. if( engine->lastModule == this )
  55. engine->lastModule = 0;
  56. engine->scriptModules.RemoveValue(this);
  57. }
  58. }
  59. // interface
  60. asIScriptEngine *asCModule::GetEngine() const
  61. {
  62. return engine;
  63. }
  64. // interface
  65. void asCModule::SetName(const char *name)
  66. {
  67. this->name = name;
  68. }
  69. // interface
  70. const char *asCModule::GetName() const
  71. {
  72. return name.AddressOf();
  73. }
  74. // interface
  75. int asCModule::AddScriptSection(const char *name, const char *code, size_t codeLength, int lineOffset)
  76. {
  77. if( !builder )
  78. builder = asNEW(asCBuilder)(engine, this);
  79. return builder->AddCode(name, code, (int)codeLength, lineOffset, (int)engine->GetScriptSectionNameIndex(name ? name : ""), engine->ep.copyScriptSections);
  80. }
  81. // internal
  82. void asCModule::JITCompile()
  83. {
  84. for (unsigned int i = 0; i < scriptFunctions.GetLength(); i++)
  85. {
  86. scriptFunctions[i]->JITCompile();
  87. }
  88. }
  89. // interface
  90. int asCModule::Build()
  91. {
  92. // Only one thread may build at one time
  93. // TODO: It should be possible to have multiple threads perform compilations
  94. int r = engine->RequestBuild();
  95. if( r < 0 )
  96. return r;
  97. engine->PrepareEngine();
  98. if( engine->configFailed )
  99. {
  100. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_INVALID_CONFIGURATION);
  101. engine->BuildCompleted();
  102. return asINVALID_CONFIGURATION;
  103. }
  104. InternalReset();
  105. if( !builder )
  106. {
  107. engine->BuildCompleted();
  108. return asSUCCESS;
  109. }
  110. // Compile the script
  111. r = builder->Build();
  112. asDELETE(builder,asCBuilder);
  113. builder = 0;
  114. if( r < 0 )
  115. {
  116. // Reset module again
  117. InternalReset();
  118. engine->BuildCompleted();
  119. return r;
  120. }
  121. JITCompile();
  122. engine->PrepareEngine();
  123. engine->BuildCompleted();
  124. // Initialize global variables
  125. if( r >= 0 && engine->ep.initGlobalVarsAfterBuild )
  126. r = ResetGlobalVars();
  127. return r;
  128. }
  129. // interface
  130. int asCModule::ResetGlobalVars()
  131. {
  132. if( isGlobalVarInitialized )
  133. CallExit();
  134. // TODO: The application really should do this manually through a context
  135. // otherwise it cannot properly handle script exceptions that may be
  136. // thrown by object initializations.
  137. return CallInit();
  138. }
  139. // interface
  140. int asCModule::GetFunctionIdByIndex(int index) const
  141. {
  142. if( index < 0 || index >= (int)globalFunctions.GetLength() )
  143. return asNO_FUNCTION;
  144. return globalFunctions[index]->id;
  145. }
  146. // internal
  147. int asCModule::CallInit()
  148. {
  149. if( isGlobalVarInitialized )
  150. return asERROR;
  151. // Each global variable needs to be cleared individually
  152. asUINT n;
  153. for( n = 0; n < scriptGlobals.GetLength(); n++ )
  154. {
  155. if( scriptGlobals[n] )
  156. {
  157. memset(scriptGlobals[n]->GetAddressOfValue(), 0, sizeof(asDWORD)*scriptGlobals[n]->type.GetSizeOnStackDWords());
  158. }
  159. }
  160. // Call the init function for each of the global variables
  161. asIScriptContext *ctx = 0;
  162. int r = asEXECUTION_FINISHED;
  163. for( n = 0; n < scriptGlobals.GetLength() && r == asEXECUTION_FINISHED; n++ )
  164. {
  165. if( scriptGlobals[n]->GetInitFunc() )
  166. {
  167. if( ctx == 0 )
  168. {
  169. r = engine->CreateContext(&ctx, true);
  170. if( r < 0 )
  171. break;
  172. }
  173. r = ctx->Prepare(scriptGlobals[n]->GetInitFunc()->id);
  174. if( r >= 0 )
  175. {
  176. r = ctx->Execute();
  177. if( r != asEXECUTION_FINISHED )
  178. {
  179. asCString msg;
  180. msg.Format(TXT_FAILED_TO_INITIALIZE_s, scriptGlobals[n]->name.AddressOf());
  181. asCScriptFunction *func = scriptGlobals[n]->GetInitFunc();
  182. engine->WriteMessage(func->scriptSectionIdx >= 0 ? engine->scriptSectionNames[func->scriptSectionIdx]->AddressOf() : "",
  183. func->GetLineNumber(0) & 0xFFFFF,
  184. func->GetLineNumber(0) >> 20,
  185. asMSGTYPE_ERROR,
  186. msg.AddressOf());
  187. if( r == asEXECUTION_EXCEPTION )
  188. {
  189. int funcId = ctx->GetExceptionFunction();
  190. const asIScriptFunction *function = engine->GetFunctionDescriptorById(funcId);
  191. msg.Format(TXT_EXCEPTION_s_IN_s, ctx->GetExceptionString(), function->GetDeclaration());
  192. engine->WriteMessage(function->GetScriptSectionName(),
  193. ctx->GetExceptionLineNumber(),
  194. 0,
  195. asMSGTYPE_INFORMATION,
  196. msg.AddressOf());
  197. }
  198. }
  199. }
  200. }
  201. }
  202. if( ctx )
  203. {
  204. ctx->Release();
  205. ctx = 0;
  206. }
  207. // Even if the initialization failed we need to set the
  208. // flag that the variables have been initialized, otherwise
  209. // the module won't free those variables that really were
  210. // initialized.
  211. isGlobalVarInitialized = true;
  212. if( r != asEXECUTION_FINISHED )
  213. return asINIT_GLOBAL_VARS_FAILED;
  214. return asSUCCESS;
  215. }
  216. // internal
  217. void asCModule::CallExit()
  218. {
  219. if( !isGlobalVarInitialized ) return;
  220. for( size_t n = 0; n < scriptGlobals.GetLength(); n++ )
  221. {
  222. if( scriptGlobals[n]->type.IsObject() )
  223. {
  224. void **obj = (void**)scriptGlobals[n]->GetAddressOfValue();
  225. if( *obj )
  226. {
  227. asCObjectType *ot = scriptGlobals[n]->type.GetObjectType();
  228. if( ot->beh.release )
  229. engine->CallObjectMethod(*obj, ot->beh.release);
  230. else
  231. {
  232. if( ot->beh.destruct )
  233. engine->CallObjectMethod(*obj, ot->beh.destruct);
  234. engine->CallFree(*obj);
  235. }
  236. // Set the address to 0 as someone might try to access the variable afterwards
  237. *obj = 0;
  238. }
  239. }
  240. }
  241. isGlobalVarInitialized = false;
  242. }
  243. // internal
  244. void asCModule::InternalReset()
  245. {
  246. CallExit();
  247. size_t n;
  248. // Release all global functions
  249. for( n = 0; n < globalFunctions.GetLength(); n++ )
  250. {
  251. if( globalFunctions[n] )
  252. globalFunctions[n]->Release();
  253. }
  254. globalFunctions.SetLength(0);
  255. // First release all compiled functions
  256. for( n = 0; n < scriptFunctions.GetLength(); n++ )
  257. {
  258. if( scriptFunctions[n] )
  259. {
  260. // Remove the module reference in the functions
  261. scriptFunctions[n]->module = 0;
  262. scriptFunctions[n]->Release();
  263. }
  264. }
  265. scriptFunctions.SetLength(0);
  266. // Release the global properties declared in the module
  267. for( n = 0; n < scriptGlobals.GetLength(); n++ )
  268. scriptGlobals[n]->Release();
  269. scriptGlobals.SetLength(0);
  270. UnbindAllImportedFunctions();
  271. // Free bind information
  272. for( n = 0; n < bindInformations.GetLength(); n++ )
  273. {
  274. engine->importedFunctions[bindInformations[n]->importedFunctionSignature->id & 0xFFFF] = 0 ;
  275. asDELETE(bindInformations[n]->importedFunctionSignature, asCScriptFunction);
  276. asDELETE(bindInformations[n], sBindInfo);
  277. }
  278. bindInformations.SetLength(0);
  279. // Free declared types, including classes, typedefs, and enums
  280. for( n = 0; n < classTypes.GetLength(); n++ )
  281. classTypes[n]->Release();
  282. classTypes.SetLength(0);
  283. for( n = 0; n < enumTypes.GetLength(); n++ )
  284. enumTypes[n]->Release();
  285. enumTypes.SetLength(0);
  286. for( n = 0; n < typeDefs.GetLength(); n++ )
  287. typeDefs[n]->Release();
  288. typeDefs.SetLength(0);
  289. // Free funcdefs
  290. for( n = 0; n < funcDefs.GetLength(); n++ )
  291. {
  292. // TODO: funcdefs: These may be shared between modules, so we can't just remove them
  293. engine->funcDefs.RemoveValue(funcDefs[n]);
  294. funcDefs[n]->Release();
  295. }
  296. funcDefs.SetLength(0);
  297. }
  298. // interface
  299. int asCModule::GetFunctionIdByName(const char *name) const
  300. {
  301. // TODO: optimize: Improve linear search
  302. // Find the function id
  303. int id = -1;
  304. for( size_t n = 0; n < globalFunctions.GetLength(); n++ )
  305. {
  306. if( globalFunctions[n]->name == name )
  307. {
  308. if( id == -1 )
  309. id = globalFunctions[n]->id;
  310. else
  311. return asMULTIPLE_FUNCTIONS;
  312. }
  313. }
  314. if( id == -1 ) return asNO_FUNCTION;
  315. return id;
  316. }
  317. // interface
  318. int asCModule::GetImportedFunctionCount() const
  319. {
  320. return (int)bindInformations.GetLength();
  321. }
  322. // interface
  323. int asCModule::GetImportedFunctionIndexByDecl(const char *decl) const
  324. {
  325. asCBuilder bld(engine, const_cast<asCModule*>(this));
  326. asCScriptFunction func(engine, const_cast<asCModule*>(this), asFUNC_DUMMY);
  327. bld.ParseFunctionDeclaration(0, decl, &func, false);
  328. // TODO: optimize: Improve linear search
  329. // Search script functions for matching interface
  330. int id = -1;
  331. for( asUINT n = 0; n < bindInformations.GetLength(); ++n )
  332. {
  333. if( func.name == bindInformations[n]->importedFunctionSignature->name &&
  334. func.returnType == bindInformations[n]->importedFunctionSignature->returnType &&
  335. func.parameterTypes.GetLength() == bindInformations[n]->importedFunctionSignature->parameterTypes.GetLength() )
  336. {
  337. bool match = true;
  338. for( asUINT p = 0; p < func.parameterTypes.GetLength(); ++p )
  339. {
  340. if( func.parameterTypes[p] != bindInformations[n]->importedFunctionSignature->parameterTypes[p] )
  341. {
  342. match = false;
  343. break;
  344. }
  345. }
  346. if( match )
  347. {
  348. if( id == -1 )
  349. id = n;
  350. else
  351. return asMULTIPLE_FUNCTIONS;
  352. }
  353. }
  354. }
  355. if( id == -1 ) return asNO_FUNCTION;
  356. return id;
  357. }
  358. // interface
  359. int asCModule::GetFunctionCount() const
  360. {
  361. return (int)globalFunctions.GetLength();
  362. }
  363. // interface
  364. int asCModule::GetFunctionIdByDecl(const char *decl) const
  365. {
  366. asCBuilder bld(engine, const_cast<asCModule*>(this));
  367. asCScriptFunction func(engine, const_cast<asCModule*>(this), asFUNC_DUMMY);
  368. int r = bld.ParseFunctionDeclaration(0, decl, &func, false);
  369. if( r < 0 )
  370. return asINVALID_DECLARATION;
  371. // TODO: optimize: Improve linear search
  372. // Search script functions for matching interface
  373. int id = -1;
  374. for( size_t n = 0; n < globalFunctions.GetLength(); ++n )
  375. {
  376. if( globalFunctions[n]->objectType == 0 &&
  377. func.name == globalFunctions[n]->name &&
  378. func.returnType == globalFunctions[n]->returnType &&
  379. func.parameterTypes.GetLength() == globalFunctions[n]->parameterTypes.GetLength() )
  380. {
  381. bool match = true;
  382. for( size_t p = 0; p < func.parameterTypes.GetLength(); ++p )
  383. {
  384. if( func.parameterTypes[p] != globalFunctions[n]->parameterTypes[p] )
  385. {
  386. match = false;
  387. break;
  388. }
  389. }
  390. if( match )
  391. {
  392. if( id == -1 )
  393. id = globalFunctions[n]->id;
  394. else
  395. return asMULTIPLE_FUNCTIONS;
  396. }
  397. }
  398. }
  399. if( id == -1 ) return asNO_FUNCTION;
  400. return id;
  401. }
  402. // interface
  403. int asCModule::GetGlobalVarCount() const
  404. {
  405. return (int)scriptGlobals.GetLength();
  406. }
  407. // interface
  408. int asCModule::GetGlobalVarIndexByName(const char *name) const
  409. {
  410. // Find the global var id
  411. int id = -1;
  412. for( size_t n = 0; n < scriptGlobals.GetLength(); n++ )
  413. {
  414. if( scriptGlobals[n]->name == name )
  415. {
  416. id = (int)n;
  417. break;
  418. }
  419. }
  420. if( id == -1 ) return asNO_GLOBAL_VAR;
  421. return id;
  422. }
  423. // interface
  424. int asCModule::RemoveGlobalVar(asUINT index)
  425. {
  426. if( index >= scriptGlobals.GetLength() )
  427. return asINVALID_ARG;
  428. scriptGlobals[index]->Release();
  429. scriptGlobals.RemoveIndex(index);
  430. return 0;
  431. }
  432. // interface
  433. asIScriptFunction *asCModule::GetFunctionDescriptorByIndex(int index) const
  434. {
  435. if( index < 0 || index >= (int)globalFunctions.GetLength() )
  436. return 0;
  437. return globalFunctions[index];
  438. }
  439. // interface
  440. asIScriptFunction *asCModule::GetFunctionDescriptorById(int funcId) const
  441. {
  442. return engine->GetFunctionDescriptorById(funcId);
  443. }
  444. // interface
  445. int asCModule::GetGlobalVarIndexByDecl(const char *decl) const
  446. {
  447. asCBuilder bld(engine, const_cast<asCModule*>(this));
  448. asCObjectProperty gvar;
  449. bld.ParseVariableDeclaration(decl, &gvar);
  450. // TODO: optimize: Improve linear search
  451. // Search script functions for matching interface
  452. int id = -1;
  453. for( size_t n = 0; n < scriptGlobals.GetLength(); ++n )
  454. {
  455. if( gvar.name == scriptGlobals[n]->name &&
  456. gvar.type == scriptGlobals[n]->type )
  457. {
  458. id = (int)n;
  459. break;
  460. }
  461. }
  462. if( id == -1 ) return asNO_GLOBAL_VAR;
  463. return id;
  464. }
  465. // interface
  466. void *asCModule::GetAddressOfGlobalVar(asUINT index)
  467. {
  468. if( index >= scriptGlobals.GetLength() )
  469. return 0;
  470. // TODO: value types shouldn't need dereferencing
  471. // For object variables it's necessary to dereference the pointer to get the address of the value
  472. if( scriptGlobals[index]->type.IsObject() && !scriptGlobals[index]->type.IsObjectHandle() )
  473. return *(void**)(scriptGlobals[index]->GetAddressOfValue());
  474. return (void*)(scriptGlobals[index]->GetAddressOfValue());
  475. }
  476. // interface
  477. const char *asCModule::GetGlobalVarDeclaration(asUINT index) const
  478. {
  479. if( index >= scriptGlobals.GetLength() )
  480. return 0;
  481. asCGlobalProperty *prop = scriptGlobals[index];
  482. asASSERT(threadManager);
  483. asCString *tempString = &threadManager->GetLocalData()->string;
  484. *tempString = prop->type.Format();
  485. *tempString += " " + prop->name;
  486. return tempString->AddressOf();
  487. }
  488. // interface
  489. int asCModule::GetGlobalVar(asUINT index, const char **name, int *typeId, bool *isConst) const
  490. {
  491. if( index >= scriptGlobals.GetLength() )
  492. return asINVALID_ARG;
  493. asCGlobalProperty *prop = scriptGlobals[index];
  494. if( name )
  495. *name = prop->name.AddressOf();
  496. if( typeId )
  497. *typeId = engine->GetTypeIdFromDataType(prop->type);
  498. if( isConst )
  499. *isConst = prop->type.IsReadOnly();
  500. return asSUCCESS;
  501. }
  502. // interface
  503. int asCModule::GetObjectTypeCount() const
  504. {
  505. return (int)classTypes.GetLength();
  506. }
  507. // interface
  508. asIObjectType *asCModule::GetObjectTypeByIndex(asUINT index) const
  509. {
  510. if( index >= classTypes.GetLength() )
  511. return 0;
  512. return classTypes[index];
  513. }
  514. // interface
  515. int asCModule::GetTypeIdByDecl(const char *decl) const
  516. {
  517. asCDataType dt;
  518. asCBuilder bld(engine, const_cast<asCModule*>(this));
  519. int r = bld.ParseDataType(decl, &dt);
  520. if( r < 0 )
  521. return asINVALID_TYPE;
  522. return engine->GetTypeIdFromDataType(dt);
  523. }
  524. // interface
  525. int asCModule::GetEnumCount() const
  526. {
  527. return (int)enumTypes.GetLength();
  528. }
  529. // interface
  530. const char *asCModule::GetEnumByIndex(asUINT index, int *enumTypeId) const
  531. {
  532. if( index >= enumTypes.GetLength() )
  533. return 0;
  534. if( enumTypeId )
  535. *enumTypeId = GetTypeIdByDecl(enumTypes[index]->name.AddressOf());
  536. return enumTypes[index]->name.AddressOf();
  537. }
  538. // interface
  539. int asCModule::GetEnumValueCount(int enumTypeId) const
  540. {
  541. const asCDataType *dt = engine->GetDataTypeFromTypeId(enumTypeId);
  542. asCObjectType *t = dt->GetObjectType();
  543. if( t == 0 || !(t->GetFlags() & asOBJ_ENUM) )
  544. return asINVALID_TYPE;
  545. return (int)t->enumValues.GetLength();
  546. }
  547. // interface
  548. const char *asCModule::GetEnumValueByIndex(int enumTypeId, asUINT index, int *outValue) const
  549. {
  550. const asCDataType *dt = engine->GetDataTypeFromTypeId(enumTypeId);
  551. asCObjectType *t = dt->GetObjectType();
  552. if( t == 0 || !(t->GetFlags() & asOBJ_ENUM) )
  553. return 0;
  554. if( index >= t->enumValues.GetLength() )
  555. return 0;
  556. if( outValue )
  557. *outValue = t->enumValues[index]->value;
  558. return t->enumValues[index]->name.AddressOf();
  559. }
  560. // interface
  561. int asCModule::GetTypedefCount() const
  562. {
  563. return (int)typeDefs.GetLength();
  564. }
  565. // interface
  566. const char *asCModule::GetTypedefByIndex(asUINT index, int *typeId) const
  567. {
  568. if( index >= typeDefs.GetLength() )
  569. return 0;
  570. if( typeId )
  571. *typeId = GetTypeIdByDecl(typeDefs[index]->name.AddressOf());
  572. return typeDefs[index]->name.AddressOf();
  573. }
  574. // internal
  575. int asCModule::GetNextImportedFunctionId()
  576. {
  577. return FUNC_IMPORTED | (asUINT)engine->importedFunctions.GetLength();
  578. }
  579. // internal
  580. int asCModule::AddScriptFunction(int sectionIdx, int id, const char *name, const asCDataType &returnType, asCDataType *params, asETypeModifiers *inOutFlags, asCString **defaultArgs, int paramCount, bool isInterface, asCObjectType *objType, bool isConstMethod, bool isGlobalFunction, bool isPrivate)
  581. {
  582. asASSERT(id >= 0);
  583. // Store the function information
  584. asCScriptFunction *func = asNEW(asCScriptFunction)(engine, this, isInterface ? asFUNC_INTERFACE : asFUNC_SCRIPT);
  585. func->name = name;
  586. func->id = id;
  587. func->returnType = returnType;
  588. func->scriptSectionIdx = sectionIdx;
  589. for( int n = 0; n < paramCount; n++ )
  590. {
  591. func->parameterTypes.PushLast(params[n]);
  592. func->inOutFlags.PushLast(inOutFlags[n]);
  593. func->defaultArgs.PushLast(defaultArgs[n]);
  594. }
  595. func->objectType = objType;
  596. func->isReadOnly = isConstMethod;
  597. func->isPrivate = isPrivate;
  598. // The script function's refCount was initialized to 1
  599. scriptFunctions.PushLast(func);
  600. engine->SetScriptFunction(func);
  601. // Compute the signature id
  602. if( objType )
  603. func->ComputeSignatureId();
  604. // Add reference
  605. if( isGlobalFunction )
  606. {
  607. globalFunctions.PushLast(func);
  608. func->AddRef();
  609. }
  610. return 0;
  611. }
  612. // internal
  613. int asCModule::AddScriptFunction(asCScriptFunction *func)
  614. {
  615. scriptFunctions.PushLast(func);
  616. func->AddRef();
  617. engine->SetScriptFunction(func);
  618. return 0;
  619. }
  620. // internal
  621. int asCModule::AddImportedFunction(int id, const char *name, const asCDataType &returnType, asCDataType *params, asETypeModifiers *inOutFlags, int paramCount, const asCString &moduleName)
  622. {
  623. asASSERT(id >= 0);
  624. // Store the function information
  625. asCScriptFunction *func = asNEW(asCScriptFunction)(engine, this, asFUNC_IMPORTED);
  626. func->name = name;
  627. func->id = id;
  628. func->returnType = returnType;
  629. for( int n = 0; n < paramCount; n++ )
  630. {
  631. func->parameterTypes.PushLast(params[n]);
  632. func->inOutFlags.PushLast(inOutFlags[n]);
  633. }
  634. func->objectType = 0;
  635. sBindInfo *info = asNEW(sBindInfo);
  636. info->importedFunctionSignature = func;
  637. info->boundFunctionId = -1;
  638. info->importFromModule = moduleName;
  639. bindInformations.PushLast(info);
  640. // Add the info to the array in the engine
  641. engine->importedFunctions.PushLast(info);
  642. return 0;
  643. }
  644. // internal
  645. asCScriptFunction *asCModule::GetImportedFunction(int index) const
  646. {
  647. return bindInformations[index]->importedFunctionSignature;
  648. }
  649. // interface
  650. int asCModule::BindImportedFunction(int index, int sourceId)
  651. {
  652. // First unbind the old function
  653. int r = UnbindImportedFunction(index);
  654. if( r < 0 ) return r;
  655. // Must verify that the interfaces are equal
  656. asCScriptFunction *dst = GetImportedFunction(index);
  657. if( dst == 0 ) return asNO_FUNCTION;
  658. asCScriptFunction *src = engine->GetScriptFunction(sourceId);
  659. if( src == 0 )
  660. return asNO_FUNCTION;
  661. // Verify return type
  662. if( dst->returnType != src->returnType )
  663. return asINVALID_INTERFACE;
  664. if( dst->parameterTypes.GetLength() != src->parameterTypes.GetLength() )
  665. return asINVALID_INTERFACE;
  666. for( size_t n = 0; n < dst->parameterTypes.GetLength(); ++n )
  667. {
  668. if( dst->parameterTypes[n] != src->parameterTypes[n] )
  669. return asINVALID_INTERFACE;
  670. }
  671. bindInformations[index]->boundFunctionId = sourceId;
  672. engine->scriptFunctions[sourceId]->AddRef();
  673. return asSUCCESS;
  674. }
  675. // interface
  676. int asCModule::UnbindImportedFunction(int index)
  677. {
  678. if( index < 0 || index > (int)bindInformations.GetLength() )
  679. return asINVALID_ARG;
  680. // Remove reference to old module
  681. int oldFuncID = bindInformations[index]->boundFunctionId;
  682. if( oldFuncID != -1 )
  683. {
  684. bindInformations[index]->boundFunctionId = -1;
  685. engine->scriptFunctions[oldFuncID]->Release();
  686. }
  687. return asSUCCESS;
  688. }
  689. // interface
  690. const char *asCModule::GetImportedFunctionDeclaration(int index) const
  691. {
  692. asCScriptFunction *func = GetImportedFunction(index);
  693. if( func == 0 ) return 0;
  694. asASSERT(threadManager);
  695. asCString *tempString = &threadManager->GetLocalData()->string;
  696. *tempString = func->GetDeclarationStr();
  697. return tempString->AddressOf();
  698. }
  699. // interface
  700. const char *asCModule::GetImportedFunctionSourceModule(int index) const
  701. {
  702. if( index >= (int)bindInformations.GetLength() )
  703. return 0;
  704. return bindInformations[index]->importFromModule.AddressOf();
  705. }
  706. // inteface
  707. int asCModule::BindAllImportedFunctions()
  708. {
  709. bool notAllFunctionsWereBound = false;
  710. // Bind imported functions
  711. int c = GetImportedFunctionCount();
  712. for( int n = 0; n < c; ++n )
  713. {
  714. asCScriptFunction *func = GetImportedFunction(n);
  715. if( func == 0 ) return asERROR;
  716. asCString str = func->GetDeclarationStr();
  717. // Get module name from where the function should be imported
  718. const char *moduleName = GetImportedFunctionSourceModule(n);
  719. if( moduleName == 0 ) return asERROR;
  720. asCModule *srcMod = engine->GetModule(moduleName, false);
  721. int funcId = -1;
  722. if( srcMod )
  723. funcId = srcMod->GetFunctionIdByDecl(str.AddressOf());
  724. if( funcId < 0 )
  725. notAllFunctionsWereBound = true;
  726. else
  727. {
  728. if( BindImportedFunction(n, funcId) < 0 )
  729. notAllFunctionsWereBound = true;
  730. }
  731. }
  732. if( notAllFunctionsWereBound )
  733. return asCANT_BIND_ALL_FUNCTIONS;
  734. return asSUCCESS;
  735. }
  736. // interface
  737. int asCModule::UnbindAllImportedFunctions()
  738. {
  739. int c = GetImportedFunctionCount();
  740. for( int n = 0; n < c; ++n )
  741. UnbindImportedFunction(n);
  742. return asSUCCESS;
  743. }
  744. // internal
  745. asCObjectType *asCModule::GetObjectType(const char *type)
  746. {
  747. size_t n;
  748. // TODO: optimize: Improve linear search
  749. for( n = 0; n < classTypes.GetLength(); n++ )
  750. if( classTypes[n]->name == type )
  751. return classTypes[n];
  752. for( n = 0; n < enumTypes.GetLength(); n++ )
  753. if( enumTypes[n]->name == type )
  754. return enumTypes[n];
  755. for( n = 0; n < typeDefs.GetLength(); n++ )
  756. if( typeDefs[n]->name == type )
  757. return typeDefs[n];
  758. return 0;
  759. }
  760. // internal
  761. asCGlobalProperty *asCModule::AllocateGlobalProperty(const char *name, const asCDataType &dt)
  762. {
  763. asCGlobalProperty *prop = engine->AllocateGlobalProperty();
  764. prop->name = name;
  765. // Allocate the memory for this property based on its type
  766. prop->type = dt;
  767. prop->AllocateMemory();
  768. // Store the variable in the module scope (the reference count is already set to 1)
  769. scriptGlobals.PushLast(prop);
  770. return prop;
  771. }
  772. // internal
  773. void asCModule::ResolveInterfaceIds(asCArray<void*> *substitutions)
  774. {
  775. // For each of the interfaces declared in the script find identical interface in the engine.
  776. // If an identical interface was found then substitute the current id for the identical interface's id,
  777. // then remove this interface declaration. If an interface was modified by the declaration, then
  778. // retry the detection of identical interface for it since it may now match another.
  779. // For an interface to be equal to another the name and methods must match. If the interface
  780. // references another interface, then that must be checked as well, which can lead to circular references.
  781. // Example:
  782. //
  783. // interface A { void f(B@); }
  784. // interface B { void f(A@); void f(C@); }
  785. // interface C { void f(A@); }
  786. //
  787. // A1 equals A2 if and only if B1 equals B2
  788. // B1 equals B2 if and only if A1 equals A2 and C1 equals C2
  789. // C1 equals C2 if and only if A1 equals A2
  790. unsigned int i;
  791. // The interface can only be equal to interfaces declared in other modules.
  792. // Interfaces registered by the application will conflict with this one if it has the same name.
  793. // This means that we only need to look for the interfaces in the engine->classTypes, but not in engine->objectTypes.
  794. asCArray<sObjectTypePair> equals;
  795. for( i = 0; i < classTypes.GetLength(); i++ )
  796. {
  797. asCObjectType *intf1 = classTypes[i];
  798. if( !intf1->IsInterface() )
  799. continue;
  800. // The interface may have been determined to be equal to another already
  801. bool found = false;
  802. for( unsigned int e = 0; e < equals.GetLength(); e++ )
  803. {
  804. if( equals[e].a == intf1 )
  805. {
  806. found = true;
  807. break;
  808. }
  809. }
  810. if( found )
  811. continue;
  812. for( unsigned int n = 0; n < engine->classTypes.GetLength(); n++ )
  813. {
  814. // Don't compare against self
  815. if( engine->classTypes[n] == intf1 )
  816. continue;
  817. asCObjectType *intf2 = engine->classTypes[n];
  818. // Assume the interface are equal, then validate this
  819. sObjectTypePair pair = {intf1,intf2};
  820. equals.PushLast(pair);
  821. if( AreInterfacesEqual(intf1, intf2, equals) )
  822. break;
  823. // Since they are not equal, remove them from the list again
  824. equals.PopLast();
  825. }
  826. }
  827. // For each of the interfaces that have been found to be equal we need to
  828. // remove the new declaration and instead have the module use the existing one.
  829. for( i = 0; i < equals.GetLength(); i++ )
  830. {
  831. // Substitute the old object type from the module's class types
  832. unsigned int c;
  833. for( c = 0; c < classTypes.GetLength(); c++ )
  834. {
  835. if( classTypes[c] == equals[i].a )
  836. {
  837. if( substitutions )
  838. {
  839. substitutions->PushLast(equals[i].a);
  840. substitutions->PushLast(equals[i].b);
  841. }
  842. classTypes[c] = equals[i].b;
  843. equals[i].b->AddRef();
  844. break;
  845. }
  846. }
  847. // Remove the old object type from the engine's class types
  848. engine->classTypes.RemoveValue(equals[i].a);
  849. // Substitute all uses of this object type
  850. // Only interfaces in the module is using the type so far
  851. for( c = 0; c < classTypes.GetLength(); c++ )
  852. {
  853. if( classTypes[c]->IsInterface() )
  854. {
  855. asCObjectType *intf = classTypes[c];
  856. for( int m = 0; m < intf->GetMethodCount(); m++ )
  857. {
  858. asCScriptFunction *func = engine->GetScriptFunction(intf->methods[m]);
  859. if( func )
  860. {
  861. if( func->returnType.GetObjectType() == equals[i].a )
  862. func->returnType.SetObjectType(equals[i].b);
  863. for( int p = 0; p < func->GetParamCount(); p++ )
  864. {
  865. if( func->parameterTypes[p].GetObjectType() == equals[i].a )
  866. func->parameterTypes[p].SetObjectType(equals[i].b);
  867. }
  868. }
  869. }
  870. }
  871. }
  872. // Substitute all interface methods in the module. Delete all methods for the old interface
  873. for( unsigned int m = 0; m < equals[i].a->methods.GetLength(); m++ )
  874. {
  875. for( c = 0; c < scriptFunctions.GetLength(); c++ )
  876. {
  877. if( scriptFunctions[c]->id == equals[i].a->methods[m] )
  878. {
  879. if( substitutions )
  880. substitutions->PushLast(scriptFunctions[c]);
  881. scriptFunctions[c]->Release();
  882. scriptFunctions[c] = engine->GetScriptFunction(equals[i].b->methods[m]);
  883. scriptFunctions[c]->AddRef();
  884. if( substitutions )
  885. substitutions->PushLast(scriptFunctions[c]);
  886. }
  887. }
  888. }
  889. // Deallocate the object type
  890. asDELETE(equals[i].a, asCObjectType);
  891. }
  892. }
  893. // internal
  894. bool asCModule::AreInterfacesEqual(asCObjectType *a, asCObjectType *b, asCArray<sObjectTypePair> &equals)
  895. {
  896. // An interface is considered equal to another if the following criterias apply:
  897. //
  898. // - The interface names are equal
  899. // - The number of methods is equal
  900. // - All the methods are equal
  901. // - The order of the methods is equal
  902. // - If a method returns or takes an interface by handle or reference, both interfaces must be equal
  903. // ------------
  904. // TODO: Study the possiblity of allowing interfaces where methods are declared in different orders to
  905. // be considered equal. The compiler and VM can handle this, but it complicates the comparison of interfaces
  906. // where multiple methods take different interfaces as parameters (or return values). Example:
  907. //
  908. // interface A
  909. // {
  910. // void f(B, C);
  911. // void f(B);
  912. // void f(C);
  913. // }
  914. //
  915. // If 'void f(B)' in module A is compared against 'void f(C)' in module B, then the code will assume
  916. // interface B in module A equals interface C in module B. Thus 'void f(B, C)' in module A won't match
  917. // 'void f(C, B)' in module B.
  918. // ------------
  919. // Are both interfaces?
  920. if( !a->IsInterface() || !b->IsInterface() )
  921. return false;
  922. // Are the names equal?
  923. if( a->name != b->name )
  924. return false;
  925. // Are the number of methods equal?
  926. if( a->methods.GetLength() != b->methods.GetLength() )
  927. return false;
  928. // Keep the number of equals in the list so we can restore it later if necessary
  929. int prevEquals = (int)equals.GetLength();
  930. // Are the methods equal to each other?
  931. bool match = true;
  932. for( unsigned int n = 0; n < a->methods.GetLength(); n++ )
  933. {
  934. match = false;
  935. asCScriptFunction *funcA = (asCScriptFunction*)engine->GetFunctionDescriptorById(a->methods[n]);
  936. asCScriptFunction *funcB = (asCScriptFunction*)engine->GetFunctionDescriptorById(b->methods[n]);
  937. // funcB can be null if the module that created the interface has been
  938. // discarded but the type has not yet been released by the engine.
  939. if( funcB == 0 )
  940. break;
  941. // The methods must have the same name and the same number of parameters
  942. if( funcA->name != funcB->name ||
  943. funcA->parameterTypes.GetLength() != funcB->parameterTypes.GetLength() )
  944. break;
  945. // The return types must be equal. If the return type is an interface the interfaces must match.
  946. if( !AreTypesEqual(funcA->returnType, funcB->returnType, equals) )
  947. break;
  948. match = true;
  949. for( unsigned int p = 0; p < funcA->parameterTypes.GetLength(); p++ )
  950. {
  951. if( !AreTypesEqual(funcA->parameterTypes[p], funcB->parameterTypes[p], equals) ||
  952. funcA->inOutFlags[p] != funcB->inOutFlags[p] )
  953. {
  954. match = false;
  955. break;
  956. }
  957. }
  958. if( !match )
  959. break;
  960. }
  961. // For each of the new interfaces that we're assuming to be equal, we need to validate this
  962. if( match )
  963. {
  964. for( unsigned int n = prevEquals; n < equals.GetLength(); n++ )
  965. {
  966. if( !AreInterfacesEqual(equals[n].a, equals[n].b, equals) )
  967. {
  968. match = false;
  969. break;
  970. }
  971. }
  972. }
  973. if( !match )
  974. {
  975. // The interfaces doesn't match.
  976. // Restore the list of previous equals before we go on, so
  977. // the caller can continue comparing with another interface
  978. equals.SetLength(prevEquals);
  979. }
  980. return match;
  981. }
  982. // internal
  983. bool asCModule::AreTypesEqual(const asCDataType &a, const asCDataType &b, asCArray<sObjectTypePair> &equals)
  984. {
  985. if( !a.IsEqualExceptInterfaceType(b) )
  986. return false;
  987. asCObjectType *ai = a.GetObjectType();
  988. asCObjectType *bi = b.GetObjectType();
  989. if( ai && ai->IsInterface() )
  990. {
  991. // If the interface is in the equals list, then the pair must match the pair in the list
  992. bool found = false;
  993. unsigned int e;
  994. for( e = 0; e < equals.GetLength(); e++ )
  995. {
  996. if( equals[e].a == ai )
  997. {
  998. found = true;
  999. break;
  1000. }
  1001. }
  1002. if( found )
  1003. {
  1004. // Do the pairs match?
  1005. if( equals[e].b != bi )
  1006. return false;
  1007. }
  1008. else
  1009. {
  1010. // Assume they are equal from now on
  1011. sObjectTypePair pair = {ai, bi};
  1012. equals.PushLast(pair);
  1013. }
  1014. }
  1015. return true;
  1016. }
  1017. // interface
  1018. int asCModule::SaveByteCode(asIBinaryStream *out) const
  1019. {
  1020. if( out == 0 ) return asINVALID_ARG;
  1021. asCRestore rest(const_cast<asCModule*>(this), out, engine);
  1022. return rest.Save();
  1023. }
  1024. // interface
  1025. int asCModule::LoadByteCode(asIBinaryStream *in)
  1026. {
  1027. if( in == 0 ) return asINVALID_ARG;
  1028. // Only permit loading bytecode if no other thread is currently compiling
  1029. // TODO: It should be possible to have multiple threads perform compilations
  1030. int r = engine->RequestBuild();
  1031. if( r < 0 )
  1032. return r;
  1033. asCRestore rest(this, in, engine);
  1034. r = rest.Restore();
  1035. JITCompile();
  1036. engine->BuildCompleted();
  1037. return r;
  1038. }
  1039. // interface
  1040. int asCModule::CompileGlobalVar(const char *sectionName, const char *code, int lineOffset)
  1041. {
  1042. // Validate arguments
  1043. if( code == 0 )
  1044. return asINVALID_ARG;
  1045. // Only one thread may build at one time
  1046. // TODO: It should be possible to have multiple threads perform compilations
  1047. int r = engine->RequestBuild();
  1048. if( r < 0 )
  1049. return r;
  1050. // Prepare the engine
  1051. engine->PrepareEngine();
  1052. if( engine->configFailed )
  1053. {
  1054. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_INVALID_CONFIGURATION);
  1055. engine->BuildCompleted();
  1056. return asINVALID_CONFIGURATION;
  1057. }
  1058. // Compile the global variable and add it to the module scope
  1059. asCBuilder builder(engine, this);
  1060. asCString str = code;
  1061. r = builder.CompileGlobalVar(sectionName, str.AddressOf(), lineOffset);
  1062. engine->BuildCompleted();
  1063. // Initialize the variable
  1064. if( r >= 0 && engine->ep.initGlobalVarsAfterBuild )
  1065. {
  1066. // Clear the memory
  1067. asCGlobalProperty *prop = scriptGlobals[scriptGlobals.GetLength()-1];
  1068. memset(prop->GetAddressOfValue(), 0, sizeof(asDWORD)*prop->type.GetSizeOnStackDWords());
  1069. if( prop->GetInitFunc() )
  1070. {
  1071. // Call the init function for the global variable
  1072. asIScriptContext *ctx = 0;
  1073. int r = engine->CreateContext(&ctx, true);
  1074. if( r < 0 )
  1075. return r;
  1076. r = ctx->Prepare(prop->GetInitFunc()->id);
  1077. if( r >= 0 )
  1078. r = ctx->Execute();
  1079. ctx->Release();
  1080. }
  1081. }
  1082. return r;
  1083. }
  1084. // interface
  1085. int asCModule::CompileFunction(const char *sectionName, const char *code, int lineOffset, asDWORD compileFlags, asIScriptFunction **outFunc)
  1086. {
  1087. asASSERT(outFunc == 0 || *outFunc == 0);
  1088. // Validate arguments
  1089. if( code == 0 ||
  1090. (compileFlags != 0 && compileFlags != asCOMP_ADD_TO_MODULE) )
  1091. return asINVALID_ARG;
  1092. // Only one thread may build at one time
  1093. // TODO: It should be possible to have multiple threads perform compilations
  1094. int r = engine->RequestBuild();
  1095. if( r < 0 )
  1096. return r;
  1097. // Prepare the engine
  1098. engine->PrepareEngine();
  1099. if( engine->configFailed )
  1100. {
  1101. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_INVALID_CONFIGURATION);
  1102. engine->BuildCompleted();
  1103. return asINVALID_CONFIGURATION;
  1104. }
  1105. // Compile the single function
  1106. asCBuilder builder(engine, this);
  1107. asCString str = code;
  1108. asCScriptFunction *func = 0;
  1109. r = builder.CompileFunction(sectionName, str.AddressOf(), lineOffset, compileFlags, &func);
  1110. engine->BuildCompleted();
  1111. if( r >= 0 && outFunc )
  1112. {
  1113. // Return the function to the caller
  1114. *outFunc = func;
  1115. func->AddRef();
  1116. }
  1117. // Release our reference to the function
  1118. if( func )
  1119. func->Release();
  1120. return r;
  1121. }
  1122. // interface
  1123. int asCModule::RemoveFunction(int funcId)
  1124. {
  1125. // Find the global function
  1126. for( asUINT n = 0; n < globalFunctions.GetLength(); n++ )
  1127. {
  1128. if( globalFunctions[n] && globalFunctions[n]->id == funcId )
  1129. {
  1130. asCScriptFunction *func = globalFunctions[n];
  1131. globalFunctions.RemoveIndex(n);
  1132. func->Release();
  1133. scriptFunctions.RemoveValue(func);
  1134. func->Release();
  1135. return 0;
  1136. }
  1137. }
  1138. return asNO_FUNCTION;
  1139. }
  1140. // internal
  1141. int asCModule::AddFuncDef(const char *name)
  1142. {
  1143. asCScriptFunction *func = asNEW(asCScriptFunction)(engine, 0, asFUNC_FUNCDEF);
  1144. func->name = name;
  1145. funcDefs.PushLast(func);
  1146. engine->funcDefs.PushLast(func);
  1147. func->id = engine->GetNextScriptFunctionId();
  1148. engine->SetScriptFunction(func);
  1149. return (int)funcDefs.GetLength()-1;
  1150. }
  1151. END_AS_NAMESPACE