as_module.cpp 36 KB

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