as_module.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424
  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. // For object variables it's necessary to dereference the pointer to get the address of the value
  470. if( scriptGlobals[index]->type.IsObject() &&
  471. (!scriptGlobals[index]->type.IsObjectHandle() ||
  472. (scriptGlobals[index]->type.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  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. asUINT asCModule::GetObjectTypeCount() const
  504. {
  505. return (asUINT)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. asUINT asCModule::GetEnumCount() const
  526. {
  527. return (asUINT)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. asUINT asCModule::GetTypedefCount() const
  562. {
  563. return (asUINT)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. // TODO: multithread: This will break if one thread if freeing a module, while another is being compiled
  578. if( engine->freeImportedFunctionIdxs.GetLength() )
  579. return FUNC_IMPORTED | (asUINT)engine->freeImportedFunctionIdxs[engine->freeImportedFunctionIdxs.GetLength()-1];
  580. return FUNC_IMPORTED | (asUINT)engine->importedFunctions.GetLength();
  581. }
  582. // internal
  583. 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)
  584. {
  585. asASSERT(id >= 0);
  586. // Store the function information
  587. asCScriptFunction *func = asNEW(asCScriptFunction)(engine, this, isInterface ? asFUNC_INTERFACE : asFUNC_SCRIPT);
  588. func->name = name;
  589. func->id = id;
  590. func->returnType = returnType;
  591. func->scriptSectionIdx = sectionIdx;
  592. for( int n = 0; n < paramCount; n++ )
  593. {
  594. func->parameterTypes.PushLast(params[n]);
  595. func->inOutFlags.PushLast(inOutFlags[n]);
  596. func->defaultArgs.PushLast(defaultArgs[n]);
  597. }
  598. func->objectType = objType;
  599. func->isReadOnly = isConstMethod;
  600. func->isPrivate = isPrivate;
  601. // The script function's refCount was initialized to 1
  602. scriptFunctions.PushLast(func);
  603. engine->SetScriptFunction(func);
  604. // Compute the signature id
  605. if( objType )
  606. func->ComputeSignatureId();
  607. // Add reference
  608. if( isGlobalFunction )
  609. {
  610. globalFunctions.PushLast(func);
  611. func->AddRef();
  612. }
  613. return 0;
  614. }
  615. // internal
  616. int asCModule::AddScriptFunction(asCScriptFunction *func)
  617. {
  618. scriptFunctions.PushLast(func);
  619. func->AddRef();
  620. engine->SetScriptFunction(func);
  621. return 0;
  622. }
  623. // internal
  624. int asCModule::AddImportedFunction(int id, const char *name, const asCDataType &returnType, asCDataType *params, asETypeModifiers *inOutFlags, int paramCount, const asCString &moduleName)
  625. {
  626. asASSERT(id >= 0);
  627. // Store the function information
  628. asCScriptFunction *func = asNEW(asCScriptFunction)(engine, this, asFUNC_IMPORTED);
  629. func->name = name;
  630. func->id = id;
  631. func->returnType = returnType;
  632. for( int n = 0; n < paramCount; n++ )
  633. {
  634. func->parameterTypes.PushLast(params[n]);
  635. func->inOutFlags.PushLast(inOutFlags[n]);
  636. }
  637. func->objectType = 0;
  638. sBindInfo *info = asNEW(sBindInfo);
  639. info->importedFunctionSignature = func;
  640. info->boundFunctionId = -1;
  641. info->importFromModule = moduleName;
  642. bindInformations.PushLast(info);
  643. // Add the info to the array in the engine
  644. if( engine->freeImportedFunctionIdxs.GetLength() )
  645. engine->importedFunctions[engine->freeImportedFunctionIdxs.PopLast()] = info;
  646. else
  647. engine->importedFunctions.PushLast(info);
  648. return 0;
  649. }
  650. // internal
  651. asCScriptFunction *asCModule::GetImportedFunction(int index) const
  652. {
  653. return bindInformations[index]->importedFunctionSignature;
  654. }
  655. // interface
  656. int asCModule::BindImportedFunction(asUINT index, int sourceId)
  657. {
  658. // First unbind the old function
  659. int r = UnbindImportedFunction(index);
  660. if( r < 0 ) return r;
  661. // Must verify that the interfaces are equal
  662. asCScriptFunction *dst = GetImportedFunction(index);
  663. if( dst == 0 ) return asNO_FUNCTION;
  664. asCScriptFunction *src = engine->GetScriptFunction(sourceId);
  665. if( src == 0 )
  666. return asNO_FUNCTION;
  667. // Verify return type
  668. if( dst->returnType != src->returnType )
  669. return asINVALID_INTERFACE;
  670. if( dst->parameterTypes.GetLength() != src->parameterTypes.GetLength() )
  671. return asINVALID_INTERFACE;
  672. for( size_t n = 0; n < dst->parameterTypes.GetLength(); ++n )
  673. {
  674. if( dst->parameterTypes[n] != src->parameterTypes[n] )
  675. return asINVALID_INTERFACE;
  676. }
  677. bindInformations[index]->boundFunctionId = sourceId;
  678. engine->scriptFunctions[sourceId]->AddRef();
  679. return asSUCCESS;
  680. }
  681. // interface
  682. int asCModule::UnbindImportedFunction(asUINT index)
  683. {
  684. if( index >= bindInformations.GetLength() )
  685. return asINVALID_ARG;
  686. // Remove reference to old module
  687. int oldFuncID = bindInformations[index]->boundFunctionId;
  688. if( oldFuncID != -1 )
  689. {
  690. bindInformations[index]->boundFunctionId = -1;
  691. engine->scriptFunctions[oldFuncID]->Release();
  692. }
  693. return asSUCCESS;
  694. }
  695. // interface
  696. const char *asCModule::GetImportedFunctionDeclaration(asUINT index) const
  697. {
  698. asCScriptFunction *func = GetImportedFunction(index);
  699. if( func == 0 ) return 0;
  700. asASSERT(threadManager);
  701. asCString *tempString = &threadManager->GetLocalData()->string;
  702. *tempString = func->GetDeclarationStr();
  703. return tempString->AddressOf();
  704. }
  705. // interface
  706. const char *asCModule::GetImportedFunctionSourceModule(asUINT index) const
  707. {
  708. if( index >= bindInformations.GetLength() )
  709. return 0;
  710. return bindInformations[index]->importFromModule.AddressOf();
  711. }
  712. // inteface
  713. int asCModule::BindAllImportedFunctions()
  714. {
  715. bool notAllFunctionsWereBound = false;
  716. // Bind imported functions
  717. int c = GetImportedFunctionCount();
  718. for( int n = 0; n < c; ++n )
  719. {
  720. asCScriptFunction *func = GetImportedFunction(n);
  721. if( func == 0 ) return asERROR;
  722. asCString str = func->GetDeclarationStr();
  723. // Get module name from where the function should be imported
  724. const char *moduleName = GetImportedFunctionSourceModule(n);
  725. if( moduleName == 0 ) return asERROR;
  726. asCModule *srcMod = engine->GetModule(moduleName, false);
  727. int funcId = -1;
  728. if( srcMod )
  729. funcId = srcMod->GetFunctionIdByDecl(str.AddressOf());
  730. if( funcId < 0 )
  731. notAllFunctionsWereBound = true;
  732. else
  733. {
  734. if( BindImportedFunction(n, funcId) < 0 )
  735. notAllFunctionsWereBound = true;
  736. }
  737. }
  738. if( notAllFunctionsWereBound )
  739. return asCANT_BIND_ALL_FUNCTIONS;
  740. return asSUCCESS;
  741. }
  742. // interface
  743. int asCModule::UnbindAllImportedFunctions()
  744. {
  745. asUINT c = GetImportedFunctionCount();
  746. for( asUINT n = 0; n < c; ++n )
  747. UnbindImportedFunction(n);
  748. return asSUCCESS;
  749. }
  750. // internal
  751. asCObjectType *asCModule::GetObjectType(const char *type)
  752. {
  753. size_t n;
  754. // TODO: optimize: Improve linear search
  755. for( n = 0; n < classTypes.GetLength(); n++ )
  756. if( classTypes[n]->name == type )
  757. return classTypes[n];
  758. for( n = 0; n < enumTypes.GetLength(); n++ )
  759. if( enumTypes[n]->name == type )
  760. return enumTypes[n];
  761. for( n = 0; n < typeDefs.GetLength(); n++ )
  762. if( typeDefs[n]->name == type )
  763. return typeDefs[n];
  764. return 0;
  765. }
  766. // internal
  767. asCGlobalProperty *asCModule::AllocateGlobalProperty(const char *name, const asCDataType &dt)
  768. {
  769. asCGlobalProperty *prop = engine->AllocateGlobalProperty();
  770. prop->name = name;
  771. // Allocate the memory for this property based on its type
  772. prop->type = dt;
  773. prop->AllocateMemory();
  774. // Store the variable in the module scope (the reference count is already set to 1)
  775. scriptGlobals.PushLast(prop);
  776. return prop;
  777. }
  778. // internal
  779. void asCModule::ResolveInterfaceIds(asCArray<void*> *substitutions)
  780. {
  781. // For each of the interfaces declared in the script find identical interface in the engine.
  782. // If an identical interface was found then substitute the current id for the identical interface's id,
  783. // then remove this interface declaration. If an interface was modified by the declaration, then
  784. // retry the detection of identical interface for it since it may now match another.
  785. // For an interface to be equal to another the name and methods must match. If the interface
  786. // references another interface, then that must be checked as well, which can lead to circular references.
  787. // Example:
  788. //
  789. // interface A { void f(B@); }
  790. // interface B { void f(A@); void f(C@); }
  791. // interface C { void f(A@); }
  792. //
  793. // A1 equals A2 if and only if B1 equals B2
  794. // B1 equals B2 if and only if A1 equals A2 and C1 equals C2
  795. // C1 equals C2 if and only if A1 equals A2
  796. unsigned int i;
  797. // The interface can only be equal to interfaces declared in other modules.
  798. // Interfaces registered by the application will conflict with this one if it has the same name.
  799. // This means that we only need to look for the interfaces in the engine->classTypes, but not in engine->objectTypes.
  800. asCArray<sObjectTypePair> equals;
  801. for( i = 0; i < classTypes.GetLength(); i++ )
  802. {
  803. asCObjectType *intf1 = classTypes[i];
  804. if( !intf1->IsInterface() )
  805. continue;
  806. // The interface may have been determined to be equal to another already
  807. bool found = false;
  808. for( unsigned int e = 0; e < equals.GetLength(); e++ )
  809. {
  810. if( equals[e].a == intf1 )
  811. {
  812. found = true;
  813. break;
  814. }
  815. }
  816. if( found )
  817. continue;
  818. for( unsigned int n = 0; n < engine->classTypes.GetLength(); n++ )
  819. {
  820. // Don't compare against self
  821. if( engine->classTypes[n] == intf1 )
  822. continue;
  823. asCObjectType *intf2 = engine->classTypes[n];
  824. // Assume the interface are equal, then validate this
  825. sObjectTypePair pair = {intf1,intf2};
  826. equals.PushLast(pair);
  827. if( AreInterfacesEqual(intf1, intf2, equals) )
  828. break;
  829. // Since they are not equal, remove them from the list again
  830. equals.PopLast();
  831. }
  832. }
  833. // For each of the interfaces that have been found to be equal we need to
  834. // remove the new declaration and instead have the module use the existing one.
  835. for( i = 0; i < equals.GetLength(); i++ )
  836. {
  837. // Substitute the old object type from the module's class types
  838. unsigned int c;
  839. for( c = 0; c < classTypes.GetLength(); c++ )
  840. {
  841. if( classTypes[c] == equals[i].a )
  842. {
  843. if( substitutions )
  844. {
  845. substitutions->PushLast(equals[i].a);
  846. substitutions->PushLast(equals[i].b);
  847. }
  848. classTypes[c] = equals[i].b;
  849. equals[i].b->AddRef();
  850. break;
  851. }
  852. }
  853. // Remove the old object type from the engine's class types
  854. engine->classTypes.RemoveValue(equals[i].a);
  855. // Substitute all uses of this object type
  856. // Only interfaces in the module is using the type so far
  857. for( c = 0; c < classTypes.GetLength(); c++ )
  858. {
  859. if( classTypes[c]->IsInterface() )
  860. {
  861. asCObjectType *intf = classTypes[c];
  862. for( asUINT m = 0; m < intf->GetMethodCount(); m++ )
  863. {
  864. asCScriptFunction *func = engine->GetScriptFunction(intf->methods[m]);
  865. if( func )
  866. {
  867. if( func->returnType.GetObjectType() == equals[i].a )
  868. func->returnType.SetObjectType(equals[i].b);
  869. for( asUINT p = 0; p < func->GetParamCount(); p++ )
  870. {
  871. if( func->parameterTypes[p].GetObjectType() == equals[i].a )
  872. func->parameterTypes[p].SetObjectType(equals[i].b);
  873. }
  874. }
  875. }
  876. }
  877. }
  878. // Substitute all interface methods in the module. Delete all methods for the old interface
  879. for( unsigned int m = 0; m < equals[i].a->methods.GetLength(); m++ )
  880. {
  881. for( c = 0; c < scriptFunctions.GetLength(); c++ )
  882. {
  883. if( scriptFunctions[c]->id == equals[i].a->methods[m] )
  884. {
  885. if( substitutions )
  886. substitutions->PushLast(scriptFunctions[c]);
  887. scriptFunctions[c]->Release();
  888. scriptFunctions[c] = engine->GetScriptFunction(equals[i].b->methods[m]);
  889. scriptFunctions[c]->AddRef();
  890. if( substitutions )
  891. substitutions->PushLast(scriptFunctions[c]);
  892. }
  893. }
  894. }
  895. // Deallocate the object type
  896. asDELETE(equals[i].a, asCObjectType);
  897. }
  898. }
  899. // internal
  900. bool asCModule::AreInterfacesEqual(asCObjectType *a, asCObjectType *b, asCArray<sObjectTypePair> &equals)
  901. {
  902. // An interface is considered equal to another if the following criterias apply:
  903. //
  904. // - The interface names are equal
  905. // - The number of methods is equal
  906. // - All the methods are equal
  907. // - The order of the methods is equal
  908. // - If a method returns or takes an interface by handle or reference, both interfaces must be equal
  909. // ------------
  910. // TODO: Study the possiblity of allowing interfaces where methods are declared in different orders to
  911. // be considered equal. The compiler and VM can handle this, but it complicates the comparison of interfaces
  912. // where multiple methods take different interfaces as parameters (or return values). Example:
  913. //
  914. // interface A
  915. // {
  916. // void f(B, C);
  917. // void f(B);
  918. // void f(C);
  919. // }
  920. //
  921. // If 'void f(B)' in module A is compared against 'void f(C)' in module B, then the code will assume
  922. // interface B in module A equals interface C in module B. Thus 'void f(B, C)' in module A won't match
  923. // 'void f(C, B)' in module B.
  924. // ------------
  925. // Are both interfaces?
  926. if( !a->IsInterface() || !b->IsInterface() )
  927. return false;
  928. // Are the names equal?
  929. if( a->name != b->name )
  930. return false;
  931. // Are the number of methods equal?
  932. if( a->methods.GetLength() != b->methods.GetLength() )
  933. return false;
  934. // Keep the number of equals in the list so we can restore it later if necessary
  935. int prevEquals = (int)equals.GetLength();
  936. // Are the methods equal to each other?
  937. bool match = true;
  938. for( unsigned int n = 0; n < a->methods.GetLength(); n++ )
  939. {
  940. match = false;
  941. asCScriptFunction *funcA = (asCScriptFunction*)engine->GetFunctionDescriptorById(a->methods[n]);
  942. asCScriptFunction *funcB = (asCScriptFunction*)engine->GetFunctionDescriptorById(b->methods[n]);
  943. // funcB can be null if the module that created the interface has been
  944. // discarded but the type has not yet been released by the engine.
  945. if( funcB == 0 )
  946. break;
  947. // The methods must have the same name and the same number of parameters
  948. if( funcA->name != funcB->name ||
  949. funcA->parameterTypes.GetLength() != funcB->parameterTypes.GetLength() )
  950. break;
  951. // The return types must be equal. If the return type is an interface the interfaces must match.
  952. if( !AreTypesEqual(funcA->returnType, funcB->returnType, equals) )
  953. break;
  954. match = true;
  955. for( unsigned int p = 0; p < funcA->parameterTypes.GetLength(); p++ )
  956. {
  957. if( !AreTypesEqual(funcA->parameterTypes[p], funcB->parameterTypes[p], equals) ||
  958. funcA->inOutFlags[p] != funcB->inOutFlags[p] )
  959. {
  960. match = false;
  961. break;
  962. }
  963. }
  964. if( !match )
  965. break;
  966. }
  967. // For each of the new interfaces that we're assuming to be equal, we need to validate this
  968. if( match )
  969. {
  970. for( unsigned int n = prevEquals; n < equals.GetLength(); n++ )
  971. {
  972. if( !AreInterfacesEqual(equals[n].a, equals[n].b, equals) )
  973. {
  974. match = false;
  975. break;
  976. }
  977. }
  978. }
  979. if( !match )
  980. {
  981. // The interfaces doesn't match.
  982. // Restore the list of previous equals before we go on, so
  983. // the caller can continue comparing with another interface
  984. equals.SetLength(prevEquals);
  985. }
  986. return match;
  987. }
  988. // internal
  989. bool asCModule::AreTypesEqual(const asCDataType &a, const asCDataType &b, asCArray<sObjectTypePair> &equals)
  990. {
  991. if( !a.IsEqualExceptInterfaceType(b) )
  992. return false;
  993. asCObjectType *ai = a.GetObjectType();
  994. asCObjectType *bi = b.GetObjectType();
  995. if( ai && ai->IsInterface() )
  996. {
  997. // If the interface is in the equals list, then the pair must match the pair in the list
  998. bool found = false;
  999. unsigned int e;
  1000. for( e = 0; e < equals.GetLength(); e++ )
  1001. {
  1002. if( equals[e].a == ai )
  1003. {
  1004. found = true;
  1005. break;
  1006. }
  1007. }
  1008. if( found )
  1009. {
  1010. // Do the pairs match?
  1011. if( equals[e].b != bi )
  1012. return false;
  1013. }
  1014. else
  1015. {
  1016. // Assume they are equal from now on
  1017. sObjectTypePair pair = {ai, bi};
  1018. equals.PushLast(pair);
  1019. }
  1020. }
  1021. return true;
  1022. }
  1023. // interface
  1024. int asCModule::SaveByteCode(asIBinaryStream *out) const
  1025. {
  1026. if( out == 0 ) return asINVALID_ARG;
  1027. asCRestore rest(const_cast<asCModule*>(this), out, engine);
  1028. return rest.Save();
  1029. }
  1030. // interface
  1031. int asCModule::LoadByteCode(asIBinaryStream *in)
  1032. {
  1033. if( in == 0 ) return asINVALID_ARG;
  1034. // Only permit loading bytecode if no other thread is currently compiling
  1035. // TODO: It should be possible to have multiple threads perform compilations
  1036. int r = engine->RequestBuild();
  1037. if( r < 0 )
  1038. return r;
  1039. asCRestore rest(this, in, engine);
  1040. r = rest.Restore();
  1041. JITCompile();
  1042. engine->BuildCompleted();
  1043. return r;
  1044. }
  1045. // interface
  1046. int asCModule::CompileGlobalVar(const char *sectionName, const char *code, int lineOffset)
  1047. {
  1048. // Validate arguments
  1049. if( code == 0 )
  1050. return asINVALID_ARG;
  1051. // Only one thread may build at one time
  1052. // TODO: It should be possible to have multiple threads perform compilations
  1053. int r = engine->RequestBuild();
  1054. if( r < 0 )
  1055. return r;
  1056. // Prepare the engine
  1057. engine->PrepareEngine();
  1058. if( engine->configFailed )
  1059. {
  1060. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_INVALID_CONFIGURATION);
  1061. engine->BuildCompleted();
  1062. return asINVALID_CONFIGURATION;
  1063. }
  1064. // Compile the global variable and add it to the module scope
  1065. asCBuilder builder(engine, this);
  1066. asCString str = code;
  1067. r = builder.CompileGlobalVar(sectionName, str.AddressOf(), lineOffset);
  1068. engine->BuildCompleted();
  1069. // Initialize the variable
  1070. if( r >= 0 && engine->ep.initGlobalVarsAfterBuild )
  1071. {
  1072. // Clear the memory
  1073. asCGlobalProperty *prop = scriptGlobals[scriptGlobals.GetLength()-1];
  1074. memset(prop->GetAddressOfValue(), 0, sizeof(asDWORD)*prop->type.GetSizeOnStackDWords());
  1075. if( prop->GetInitFunc() )
  1076. {
  1077. // Call the init function for the global variable
  1078. asIScriptContext *ctx = 0;
  1079. int r = engine->CreateContext(&ctx, true);
  1080. if( r < 0 )
  1081. return r;
  1082. r = ctx->Prepare(prop->GetInitFunc()->id);
  1083. if( r >= 0 )
  1084. r = ctx->Execute();
  1085. ctx->Release();
  1086. }
  1087. }
  1088. return r;
  1089. }
  1090. // interface
  1091. int asCModule::CompileFunction(const char *sectionName, const char *code, int lineOffset, asDWORD compileFlags, asIScriptFunction **outFunc)
  1092. {
  1093. asASSERT(outFunc == 0 || *outFunc == 0);
  1094. // Validate arguments
  1095. if( code == 0 ||
  1096. (compileFlags != 0 && compileFlags != asCOMP_ADD_TO_MODULE) )
  1097. return asINVALID_ARG;
  1098. // Only one thread may build at one time
  1099. // TODO: It should be possible to have multiple threads perform compilations
  1100. int r = engine->RequestBuild();
  1101. if( r < 0 )
  1102. return r;
  1103. // Prepare the engine
  1104. engine->PrepareEngine();
  1105. if( engine->configFailed )
  1106. {
  1107. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_INVALID_CONFIGURATION);
  1108. engine->BuildCompleted();
  1109. return asINVALID_CONFIGURATION;
  1110. }
  1111. // Compile the single function
  1112. asCBuilder builder(engine, this);
  1113. asCString str = code;
  1114. asCScriptFunction *func = 0;
  1115. r = builder.CompileFunction(sectionName, str.AddressOf(), lineOffset, compileFlags, &func);
  1116. engine->BuildCompleted();
  1117. if( r >= 0 && outFunc )
  1118. {
  1119. // Return the function to the caller
  1120. *outFunc = func;
  1121. func->AddRef();
  1122. }
  1123. // Release our reference to the function
  1124. if( func )
  1125. func->Release();
  1126. return r;
  1127. }
  1128. // interface
  1129. int asCModule::RemoveFunction(int funcId)
  1130. {
  1131. // Find the global function
  1132. for( asUINT n = 0; n < globalFunctions.GetLength(); n++ )
  1133. {
  1134. if( globalFunctions[n] && globalFunctions[n]->id == funcId )
  1135. {
  1136. asCScriptFunction *func = globalFunctions[n];
  1137. globalFunctions.RemoveIndex(n);
  1138. func->Release();
  1139. scriptFunctions.RemoveValue(func);
  1140. func->Release();
  1141. return 0;
  1142. }
  1143. }
  1144. return asNO_FUNCTION;
  1145. }
  1146. // internal
  1147. int asCModule::AddFuncDef(const char *name)
  1148. {
  1149. asCScriptFunction *func = asNEW(asCScriptFunction)(engine, 0, asFUNC_FUNCDEF);
  1150. func->name = name;
  1151. funcDefs.PushLast(func);
  1152. engine->funcDefs.PushLast(func);
  1153. func->id = engine->GetNextScriptFunctionId();
  1154. engine->SetScriptFunction(func);
  1155. return (int)funcDefs.GetLength()-1;
  1156. }
  1157. END_AS_NAMESPACE