as_scriptfunction.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2018 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_scriptfunction.cpp
  25. //
  26. // A container for a compiled script function
  27. //
  28. #include "as_config.h"
  29. #include "as_scriptfunction.h"
  30. #include "as_tokendef.h"
  31. #include "as_scriptengine.h"
  32. #include "as_callfunc.h"
  33. #include "as_bytecode.h"
  34. #include "as_texts.h"
  35. #include "as_scriptnode.h"
  36. #include "as_builder.h"
  37. #include "as_scriptcode.h"
  38. #include <cstdlib> // qsort
  39. BEGIN_AS_NAMESPACE
  40. #ifdef AS_MAX_PORTABILITY
  41. static void ScriptFunction_AddRef_Generic(asIScriptGeneric *gen)
  42. {
  43. asCScriptFunction *self = (asCScriptFunction*)gen->GetObject();
  44. self->AddRef();
  45. }
  46. static void ScriptFunction_Release_Generic(asIScriptGeneric *gen)
  47. {
  48. asCScriptFunction *self = (asCScriptFunction*)gen->GetObject();
  49. self->Release();
  50. }
  51. static void ScriptFunction_GetRefCount_Generic(asIScriptGeneric *gen)
  52. {
  53. asCScriptFunction *self = (asCScriptFunction*)gen->GetObject();
  54. *(int*)gen->GetAddressOfReturnLocation() = self->GetRefCount();
  55. }
  56. static void ScriptFunction_SetFlag_Generic(asIScriptGeneric *gen)
  57. {
  58. asCScriptFunction *self = (asCScriptFunction*)gen->GetObject();
  59. self->SetFlag();
  60. }
  61. static void ScriptFunction_GetFlag_Generic(asIScriptGeneric *gen)
  62. {
  63. asCScriptFunction *self = (asCScriptFunction*)gen->GetObject();
  64. *(bool*)gen->GetAddressOfReturnLocation() = self->GetFlag();
  65. }
  66. static void ScriptFunction_EnumReferences_Generic(asIScriptGeneric *gen)
  67. {
  68. asCScriptFunction *self = (asCScriptFunction*)gen->GetObject();
  69. asIScriptEngine *engine = *(asIScriptEngine**)gen->GetAddressOfArg(0);
  70. self->EnumReferences(engine);
  71. }
  72. static void ScriptFunction_ReleaseAllHandles_Generic(asIScriptGeneric *gen)
  73. {
  74. asCScriptFunction *self = (asCScriptFunction*)gen->GetObject();
  75. asIScriptEngine *engine = *(asIScriptEngine**)gen->GetAddressOfArg(0);
  76. self->ReleaseAllHandles(engine);
  77. }
  78. static void ScriptFunction_CreateDelegate_Generic(asIScriptGeneric *gen)
  79. {
  80. asCScriptFunction *func = (asCScriptFunction*)gen->GetArgAddress(0);
  81. void *obj = gen->GetArgAddress(1);
  82. gen->SetReturnAddress(CreateDelegate(func, obj));
  83. }
  84. // TODO: operator==
  85. /*static void ScriptFunction_opEquals_Generic(asIScriptGeneric *gen)
  86. {
  87. asCScriptFunction *funcSelf = (asCScriptFunction*)gen->GetObject();
  88. asCScriptFunction *funcOther = (asCScriptFunction*)gen->GetArgAddress(0);
  89. *(bool*)gen->GetAddressOfReturnLocation() = *funcSelf == *funcOther;
  90. }
  91. */
  92. #endif
  93. void RegisterScriptFunction(asCScriptEngine *engine)
  94. {
  95. // Register the gc behaviours for the script functions
  96. int r = 0;
  97. UNUSED_VAR(r); // It is only used in debug mode
  98. engine->functionBehaviours.engine = engine;
  99. engine->functionBehaviours.flags = asOBJ_REF | asOBJ_GC;
  100. engine->functionBehaviours.name = "$func";
  101. #ifndef AS_MAX_PORTABILITY
  102. r = engine->RegisterBehaviourToObjectType(&engine->functionBehaviours, asBEHAVE_ADDREF, "void f()", asMETHOD(asCScriptFunction,AddRef), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  103. r = engine->RegisterBehaviourToObjectType(&engine->functionBehaviours, asBEHAVE_RELEASE, "void f()", asMETHOD(asCScriptFunction,Release), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  104. r = engine->RegisterBehaviourToObjectType(&engine->functionBehaviours, asBEHAVE_GETREFCOUNT, "int f()", asMETHOD(asCScriptFunction,GetRefCount), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  105. r = engine->RegisterBehaviourToObjectType(&engine->functionBehaviours, asBEHAVE_SETGCFLAG, "void f()", asMETHOD(asCScriptFunction,SetFlag), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  106. r = engine->RegisterBehaviourToObjectType(&engine->functionBehaviours, asBEHAVE_GETGCFLAG, "bool f()", asMETHOD(asCScriptFunction,GetFlag), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  107. r = engine->RegisterBehaviourToObjectType(&engine->functionBehaviours, asBEHAVE_ENUMREFS, "void f(int&in)", asMETHOD(asCScriptFunction,EnumReferences), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  108. r = engine->RegisterBehaviourToObjectType(&engine->functionBehaviours, asBEHAVE_RELEASEREFS, "void f(int&in)", asMETHOD(asCScriptFunction,ReleaseAllHandles), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  109. // TODO: Need some way to allow the arg type to adapt when the funcdefs are instantiated
  110. // r = engine->RegisterMethodToObjectType(&engine->functionBehaviours, "bool opEquals(const int &in)", asMETHOD(asCScriptFunction,operator==), asCALL_THISCALL); asASSERT( r >= 0 );
  111. #else
  112. r = engine->RegisterBehaviourToObjectType(&engine->functionBehaviours, asBEHAVE_ADDREF, "void f()", asFUNCTION(ScriptFunction_AddRef_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  113. r = engine->RegisterBehaviourToObjectType(&engine->functionBehaviours, asBEHAVE_RELEASE, "void f()", asFUNCTION(ScriptFunction_Release_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  114. r = engine->RegisterBehaviourToObjectType(&engine->functionBehaviours, asBEHAVE_GETREFCOUNT, "int f()", asFUNCTION(ScriptFunction_GetRefCount_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  115. r = engine->RegisterBehaviourToObjectType(&engine->functionBehaviours, asBEHAVE_SETGCFLAG, "void f()", asFUNCTION(ScriptFunction_SetFlag_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  116. r = engine->RegisterBehaviourToObjectType(&engine->functionBehaviours, asBEHAVE_GETGCFLAG, "bool f()", asFUNCTION(ScriptFunction_GetFlag_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  117. r = engine->RegisterBehaviourToObjectType(&engine->functionBehaviours, asBEHAVE_ENUMREFS, "void f(int&in)", asFUNCTION(ScriptFunction_EnumReferences_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  118. r = engine->RegisterBehaviourToObjectType(&engine->functionBehaviours, asBEHAVE_RELEASEREFS, "void f(int&in)", asFUNCTION(ScriptFunction_ReleaseAllHandles_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  119. // r = engine->RegisterMethodToObjectType(&engine->functionBehaviours, "bool opEquals(const int &in)", asFUNCTION(ScriptFunction_opEquals_Generic), asCALL_GENERIC); asASSERT( r >= 0 );
  120. #endif
  121. // Register the builtin function for creating delegates
  122. // This function returns a handle to the delegate, but since the type is not known at this time it is
  123. // registered to return a void then the return type is changed manually to the builtin function type
  124. // The name of the function is an invalid identifier so it cannot be invoked accidentally from the script
  125. #ifndef AS_MAX_PORTABILITY
  126. r = engine->RegisterGlobalFunction("void f(int &in, int &in)", asFUNCTION(CreateDelegate), asCALL_CDECL); asASSERT( r >= 0 );
  127. #else
  128. r = engine->RegisterGlobalFunction("void f(int &in, int &in)", asFUNCTION(ScriptFunction_CreateDelegate_Generic), asCALL_GENERIC); asASSERT( r >= 0 );
  129. #endif
  130. // Rename the function so that it cannot be called manually by the script
  131. int idx = engine->registeredGlobalFuncs.GetIndex(engine->scriptFunctions[r]);
  132. engine->registeredGlobalFuncs.Erase(idx);
  133. engine->scriptFunctions[r]->name = DELEGATE_FACTORY;
  134. engine->registeredGlobalFuncs.Put(engine->scriptFunctions[r]);
  135. // Change the return type so the VM will know the function really returns a handle
  136. engine->scriptFunctions[r]->returnType = asCDataType::CreateType(&engine->functionBehaviours, false);
  137. engine->scriptFunctions[r]->returnType.MakeHandle(true);
  138. }
  139. asCScriptFunction *CreateDelegate(asCScriptFunction *func, void *obj)
  140. {
  141. if( func == 0 || obj == 0 )
  142. {
  143. // TODO: delegate: Should set script exception
  144. return 0;
  145. }
  146. // Create an instance of a asCScriptFunction with the type asFUNC_DELEGATE
  147. // The delegate shouldn't have a function id and is not added to the engine->scriptFunctions
  148. asCScriptFunction *delegate = asNEW(asCScriptFunction)(static_cast<asCScriptEngine*>(func->GetEngine()), 0, asFUNC_DELEGATE);
  149. if( delegate )
  150. delegate->MakeDelegate(func, obj);
  151. return delegate;
  152. }
  153. // internal
  154. void asCScriptFunction::MakeDelegate(asCScriptFunction *func, void *obj)
  155. {
  156. // Increase the reference of the function and object
  157. func->AddRef();
  158. funcForDelegate = func;
  159. func->GetEngine()->AddRefScriptObject(obj, func->GetObjectType());
  160. objForDelegate = obj;
  161. // The return type and parameters are copied from the delegated method to this object
  162. // TODO: optimize: Do we really need to copy? Whenever requested the delegate can simply return the delegated methods' info directly
  163. parameterTypes = func->parameterTypes;
  164. returnType = func->returnType;
  165. inOutFlags = func->inOutFlags;
  166. // The delegate doesn't own the parameters as it will only forward them to the real method
  167. // so the exception handler must not clean up the parameters for the delegate
  168. dontCleanUpOnException = true;
  169. }
  170. // interface
  171. void *asCScriptFunction::GetAuxiliary() const
  172. {
  173. if (sysFuncIntf)
  174. return sysFuncIntf->auxiliary;
  175. return 0;
  176. }
  177. // interface
  178. void *asCScriptFunction::GetDelegateObject() const
  179. {
  180. return objForDelegate;
  181. }
  182. // interface
  183. asITypeInfo *asCScriptFunction::GetDelegateObjectType() const
  184. {
  185. if( objForDelegate == 0 || funcForDelegate == 0 )
  186. return 0;
  187. return funcForDelegate->objectType;
  188. }
  189. // interface
  190. asIScriptFunction *asCScriptFunction::GetDelegateFunction() const
  191. {
  192. return funcForDelegate;
  193. }
  194. // TODO: operator==
  195. /*
  196. // internal
  197. bool asCScriptFunction::operator==(const asCScriptFunction &other) const
  198. {
  199. if( this == &other ) return true;
  200. if( this->funcType == asFUNC_DELEGATE && other.funcType == asFUNC_DELEGATE )
  201. {
  202. if( this->objForDelegate == other.objForDelegate &&
  203. this->funcForDelegate == other.funcForDelegate )
  204. return true;
  205. }
  206. return false;
  207. }
  208. */
  209. // internal
  210. int asCScriptFunction::RegisterListPattern(const char *decl, asCScriptNode *listNodes)
  211. {
  212. if( listNodes == 0 )
  213. return asINVALID_ARG;
  214. // Build the representation of the list pattern from the script nodes
  215. asSListPatternNode *node;
  216. listPattern = asNEW(asSListPatternNode)(asLPT_START);
  217. node = listPattern;
  218. // Recursively parse the child
  219. int r = ParseListPattern(node, decl, listNodes);
  220. node->next = asNEW(asSListPatternNode)(asLPT_END);
  221. return r;
  222. }
  223. // internal
  224. int asCScriptFunction::ParseListPattern(asSListPatternNode *&target, const char *decl, asCScriptNode *listNodes)
  225. {
  226. asSListPatternNode *node = target;
  227. listNodes = listNodes->firstChild;
  228. while( listNodes )
  229. {
  230. if( listNodes->nodeType == snIdentifier )
  231. {
  232. asCString token(&decl[listNodes->tokenPos], listNodes->tokenLength);
  233. if( token == "repeat" )
  234. {
  235. node->next = asNEW(asSListPatternNode)(asLPT_REPEAT);
  236. node = node->next;
  237. }
  238. else if( token == "repeat_same" )
  239. {
  240. // TODO: list: Should make sure this is a sub-list
  241. node->next = asNEW(asSListPatternNode)(asLPT_REPEAT_SAME);
  242. node = node->next;
  243. }
  244. else
  245. {
  246. // Shouldn't happen as the parser already reported the error
  247. asASSERT(false);
  248. }
  249. }
  250. else if( listNodes->nodeType == snDataType )
  251. {
  252. asCDataType dt;
  253. asCBuilder builder(engine, 0);
  254. asCScriptCode code;
  255. code.SetCode("", decl, 0, false);
  256. dt = builder.CreateDataTypeFromNode(listNodes, &code, engine->defaultNamespace, false, CastToObjectType(returnType.GetTypeInfo()));
  257. node->next = asNEW(asSListPatternDataTypeNode)(dt);
  258. node = node->next;
  259. }
  260. else if( listNodes->nodeType == snListPattern )
  261. {
  262. node->next = asNEW(asSListPatternNode)(asLPT_START);
  263. node = node->next;
  264. // Recursively parse the child
  265. int r = ParseListPattern(node, decl, listNodes);
  266. if( r < 0 )
  267. return r;
  268. node->next = asNEW(asSListPatternNode)(asLPT_END);
  269. node = node->next;
  270. }
  271. else
  272. {
  273. // Unexpected token in the list, the parser shouldn't have allowed
  274. asASSERT( false );
  275. return -1;
  276. }
  277. listNodes = listNodes->next;
  278. }
  279. target = node;
  280. return 0;
  281. }
  282. // internal
  283. asCScriptFunction::asCScriptFunction(asCScriptEngine *engine, asCModule *mod, asEFuncType _funcType)
  284. {
  285. funcType = _funcType;
  286. if( funcType == asFUNC_DELEGATE )
  287. {
  288. // Delegates behave like object instances, rather than script code
  289. externalRefCount.set(1);
  290. internalRefCount.set(0);
  291. }
  292. else
  293. {
  294. internalRefCount.set(1);
  295. externalRefCount.set(0);
  296. }
  297. this->engine = engine;
  298. this->scriptData = 0;
  299. module = mod;
  300. objectType = 0;
  301. name = "";
  302. sysFuncIntf = 0;
  303. signatureId = 0;
  304. dontCleanUpOnException = false;
  305. vfTableIdx = -1;
  306. gcFlag = false;
  307. userData = 0;
  308. id = 0;
  309. accessMask = 0xFFFFFFFF;
  310. nameSpace = engine->nameSpaces[0];
  311. objForDelegate = 0;
  312. funcForDelegate = 0;
  313. listPattern = 0;
  314. funcdefType = 0;
  315. if( funcType == asFUNC_SCRIPT )
  316. AllocateScriptFunctionData();
  317. // Notify the GC of delegates
  318. if( funcType == asFUNC_DELEGATE )
  319. engine->gc.AddScriptObjectToGC(this, &engine->functionBehaviours);
  320. }
  321. void asCScriptFunction::AllocateScriptFunctionData()
  322. {
  323. if( scriptData ) return;
  324. scriptData = asNEW(ScriptFunctionData);
  325. scriptData->stackNeeded = 0;
  326. scriptData->variableSpace = 0;
  327. scriptData->scriptSectionIdx = -1;
  328. scriptData->declaredAt = 0;
  329. scriptData->jitFunction = 0;
  330. }
  331. void asCScriptFunction::DeallocateScriptFunctionData()
  332. {
  333. if( !scriptData ) return;
  334. for( asUINT n = 0; n < scriptData->variables.GetLength(); n++ )
  335. asDELETE(scriptData->variables[n],asSScriptVariable);
  336. scriptData->variables.SetLength(0);
  337. asDELETE(scriptData, ScriptFunctionData);
  338. scriptData = 0;
  339. }
  340. // internal
  341. asCScriptFunction::~asCScriptFunction()
  342. {
  343. // Dummy functions that are allocated on the stack are not reference counted
  344. asASSERT( funcType == asFUNC_DUMMY ||
  345. (externalRefCount.get() == 0 && internalRefCount.get() == 0) );
  346. // Remove the script function from the engine's scriptFunctions array here
  347. // Don't remove it before, because there may still be functions referring to it
  348. // by index until now. If it was removed in DestroyInternal, those would not
  349. // be able to release the refcount, thus causing memory leak.
  350. if( engine && id != 0 && funcType != asFUNC_DUMMY )
  351. engine->RemoveScriptFunction(this);
  352. // If the engine pointer is 0, then DestroyInternal has already been called and there is nothing more to do
  353. if( engine == 0 ) return;
  354. DestroyInternal();
  355. // Finally set the engine pointer to 0 because it must not be accessed again
  356. engine = 0;
  357. }
  358. // internal
  359. void asCScriptFunction::DestroyHalfCreated()
  360. {
  361. asASSERT( externalRefCount.get() == 0 && internalRefCount.get() == 1 );
  362. // Set the funcType to dummy so the destructor won't complain
  363. funcType = asFUNC_DUMMY;
  364. // If the bytecode exist remove it before destroying, otherwise it
  365. // will fail when the destructor releases the references as the bytecode
  366. // is not fully constructed.
  367. if( scriptData )
  368. scriptData->byteCode.SetLength(0);
  369. asDELETE(this, asCScriptFunction);
  370. }
  371. // internal
  372. void asCScriptFunction::DestroyInternal()
  373. {
  374. // Clean up user data
  375. for( asUINT n = 0; n < userData.GetLength(); n += 2 )
  376. {
  377. if( userData[n+1] )
  378. {
  379. for( asUINT c = 0; c < engine->cleanFunctionFuncs.GetLength(); c++ )
  380. if( engine->cleanFunctionFuncs[c].type == userData[n] )
  381. engine->cleanFunctionFuncs[c].cleanFunc(this);
  382. }
  383. }
  384. userData.SetLength(0);
  385. // Release all references the function holds to other objects
  386. ReleaseReferences();
  387. parameterTypes.SetLength(0);
  388. returnType = asCDataType::CreatePrimitive(ttVoid, false);
  389. for( asUINT p = 0; p < defaultArgs.GetLength(); p++ )
  390. if( defaultArgs[p] )
  391. asDELETE(defaultArgs[p], asCString);
  392. defaultArgs.SetLength(0);
  393. if( sysFuncIntf )
  394. asDELETE(sysFuncIntf,asSSystemFunctionInterface);
  395. sysFuncIntf = 0;
  396. if( objectType )
  397. {
  398. objectType->ReleaseInternal();
  399. objectType = 0;
  400. }
  401. DeallocateScriptFunctionData();
  402. // Deallocate list pattern data
  403. while( listPattern )
  404. {
  405. asSListPatternNode *n = listPattern->next;
  406. asDELETE(listPattern, asSListPatternNode);
  407. listPattern = n;
  408. }
  409. }
  410. // interface
  411. int asCScriptFunction::GetId() const
  412. {
  413. return id;
  414. }
  415. // interface
  416. int asCScriptFunction::AddRef() const
  417. {
  418. gcFlag = false;
  419. return externalRefCount.atomicInc();
  420. }
  421. // interface
  422. int asCScriptFunction::Release() const
  423. {
  424. gcFlag = false;
  425. int r = externalRefCount.atomicDec();
  426. if( r == 0 &&
  427. funcType != asFUNC_DUMMY ) // Dummy functions are allocated on the stack and cannot be deleted
  428. {
  429. // There are no more external references, if there are also no
  430. // internal references then it is time to delete the function
  431. if( internalRefCount.get() == 0 )
  432. {
  433. // If there are no internal references, then no module is owning the function
  434. // For example if the function was dynamically compiled without adding it to the scope of the module
  435. asASSERT( module == 0 );
  436. asDELETE(const_cast<asCScriptFunction*>(this),asCScriptFunction);
  437. }
  438. }
  439. return r;
  440. }
  441. // internal
  442. int asCScriptFunction::AddRefInternal()
  443. {
  444. return internalRefCount.atomicInc();
  445. }
  446. // internal
  447. int asCScriptFunction::ReleaseInternal()
  448. {
  449. int r = internalRefCount.atomicDec();
  450. if( r == 0 &&
  451. funcType != asFUNC_DUMMY )
  452. {
  453. // There are no more internal references, if there are also no
  454. // external references then it is time to delete the function
  455. if( externalRefCount.get() == 0 )
  456. {
  457. asDELETE(const_cast<asCScriptFunction*>(this),asCScriptFunction);
  458. }
  459. }
  460. return r;
  461. }
  462. // interface
  463. int asCScriptFunction::GetTypeId() const
  464. {
  465. // This const cast is ok, the object won't be modified
  466. asCDataType dt = asCDataType::CreateType(engine->FindMatchingFuncdef(const_cast<asCScriptFunction*>(this), 0), false);
  467. return engine->GetTypeIdFromDataType(dt);
  468. }
  469. // interface
  470. bool asCScriptFunction::IsCompatibleWithTypeId(int typeId) const
  471. {
  472. asCDataType dt = engine->GetDataTypeFromTypeId(typeId);
  473. // Make sure the type is a function
  474. if (!dt.IsFuncdef())
  475. return false;
  476. asCScriptFunction *func = CastToFuncdefType(dt.GetTypeInfo())->funcdef;
  477. if( !IsSignatureExceptNameEqual(func) )
  478. return false;
  479. // If this is a class method, then only return true if the object type is the same
  480. if( objectType != func->objectType )
  481. return false;
  482. return true;
  483. }
  484. // interface
  485. const char *asCScriptFunction::GetModuleName() const
  486. {
  487. if( module )
  488. {
  489. return module->name.AddressOf();
  490. }
  491. return 0;
  492. }
  493. // interface
  494. asIScriptModule *asCScriptFunction::GetModule() const
  495. {
  496. return module;
  497. }
  498. // interface
  499. asITypeInfo *asCScriptFunction::GetObjectType() const
  500. {
  501. return objectType;
  502. }
  503. // interface
  504. const char *asCScriptFunction::GetObjectName() const
  505. {
  506. if( objectType )
  507. return objectType->GetName();
  508. return 0;
  509. }
  510. // interface
  511. const char *asCScriptFunction::GetName() const
  512. {
  513. return name.AddressOf();
  514. }
  515. // interface
  516. const char *asCScriptFunction::GetNamespace() const
  517. {
  518. if (nameSpace)
  519. return nameSpace->name.AddressOf();
  520. return 0;
  521. }
  522. // interface
  523. bool asCScriptFunction::IsReadOnly() const
  524. {
  525. return traits.GetTrait(asTRAIT_CONST);
  526. }
  527. // interface
  528. bool asCScriptFunction::IsPrivate() const
  529. {
  530. return traits.GetTrait(asTRAIT_PRIVATE);
  531. }
  532. // interface
  533. bool asCScriptFunction::IsProtected() const
  534. {
  535. return traits.GetTrait(asTRAIT_PROTECTED);
  536. }
  537. // internal
  538. int asCScriptFunction::GetSpaceNeededForArguments()
  539. {
  540. // We need to check the size for each type
  541. int s = 0;
  542. for( asUINT n = 0; n < parameterTypes.GetLength(); n++ )
  543. s += parameterTypes[n].GetSizeOnStackDWords();
  544. return s;
  545. }
  546. // internal
  547. int asCScriptFunction::GetSpaceNeededForReturnValue()
  548. {
  549. return returnType.GetSizeOnStackDWords();
  550. }
  551. // internal
  552. bool asCScriptFunction::DoesReturnOnStack() const
  553. {
  554. if( returnType.GetTypeInfo() &&
  555. (returnType.GetTypeInfo()->flags & asOBJ_VALUE) &&
  556. !returnType.IsReference() )
  557. return true;
  558. return false;
  559. }
  560. // internal
  561. asCString asCScriptFunction::GetDeclarationStr(bool includeObjectName, bool includeNamespace, bool includeParamNames) const
  562. {
  563. asCString str;
  564. // TODO: default arg: Make the declaration with the default args an option
  565. // Don't add the return type for constructors and destructors
  566. if( !(returnType.GetTokenType() == ttVoid &&
  567. objectType &&
  568. (name == objectType->name || (name.GetLength() > 0 && name[0] == '~') ||
  569. name == "$beh0" || name == "$beh2")) )
  570. {
  571. str = returnType.Format(nameSpace, includeNamespace);
  572. str += " ";
  573. }
  574. if( objectType && includeObjectName )
  575. {
  576. if( includeNamespace && objectType->nameSpace->name != "" )
  577. str += objectType->nameSpace->name + "::";
  578. if( objectType->name != "" )
  579. str += objectType->name + "::";
  580. else
  581. str += "_unnamed_type_::";
  582. }
  583. else if (funcdefType && funcdefType->parentClass && includeObjectName)
  584. {
  585. if (includeNamespace && funcdefType->parentClass->nameSpace->name != "")
  586. str += funcdefType->parentClass->nameSpace->name + "::";
  587. if (funcdefType->parentClass->name != "")
  588. str += funcdefType->parentClass->name + "::";
  589. else
  590. str += "_unnamed_type_::";
  591. }
  592. else if( includeNamespace && nameSpace->name != "" && !objectType )
  593. {
  594. str += nameSpace->name + "::";
  595. }
  596. if( name == "" )
  597. str += "_unnamed_function_(";
  598. else if( name.SubString(0,4) == "$beh" && name.GetLength() == 5 )
  599. {
  600. if( name[4] == '0' + asBEHAVE_CONSTRUCT )
  601. str += objectType->name + "(";
  602. else if( name[4] == '0' + asBEHAVE_FACTORY )
  603. str += returnType.GetTypeInfo()->name + "(";
  604. else if( name[4] == '0' + asBEHAVE_DESTRUCT )
  605. str += "~" + objectType->name + "(";
  606. else
  607. str += name + "(";
  608. }
  609. else
  610. str += name + "(";
  611. if( parameterTypes.GetLength() > 0 )
  612. {
  613. asUINT n;
  614. for( n = 0; n < parameterTypes.GetLength() - 1; n++ )
  615. {
  616. str += parameterTypes[n].Format(nameSpace, includeNamespace);
  617. if( parameterTypes[n].IsReference() && inOutFlags.GetLength() > n )
  618. {
  619. if( inOutFlags[n] == asTM_INREF ) str += "in";
  620. else if( inOutFlags[n] == asTM_OUTREF ) str += "out";
  621. else if( inOutFlags[n] == asTM_INOUTREF ) str += "inout";
  622. }
  623. if( includeParamNames && n < parameterNames.GetLength() && parameterNames[n].GetLength() != 0 )
  624. {
  625. str += " ";
  626. str += parameterNames[n];
  627. }
  628. if( defaultArgs.GetLength() > n && defaultArgs[n] )
  629. {
  630. asCString tmp;
  631. tmp.Format(" = %s", defaultArgs[n]->AddressOf());
  632. str += tmp;
  633. }
  634. str += ", ";
  635. }
  636. // Add the last parameter
  637. str += parameterTypes[n].Format(nameSpace, includeNamespace);
  638. if( parameterTypes[n].IsReference() && inOutFlags.GetLength() > n )
  639. {
  640. if( inOutFlags[n] == asTM_INREF ) str += "in";
  641. else if( inOutFlags[n] == asTM_OUTREF ) str += "out";
  642. else if( inOutFlags[n] == asTM_INOUTREF ) str += "inout";
  643. }
  644. if( includeParamNames && n < parameterNames.GetLength() && parameterNames[n].GetLength() != 0 )
  645. {
  646. str += " ";
  647. str += parameterNames[n];
  648. }
  649. if( defaultArgs.GetLength() > n && defaultArgs[n] )
  650. {
  651. asCString tmp;
  652. tmp.Format(" = %s", defaultArgs[n]->AddressOf());
  653. str += tmp;
  654. }
  655. }
  656. str += ")";
  657. if( IsReadOnly() )
  658. str += " const";
  659. // Add the declaration of the list pattern
  660. if( listPattern )
  661. {
  662. asSListPatternNode *n = listPattern;
  663. bool first = true;
  664. while( n )
  665. {
  666. if( n->type == asLPT_START )
  667. {
  668. str += " {";
  669. first = true;
  670. }
  671. else if( n->type == asLPT_END )
  672. {
  673. str += " }";
  674. first = false;
  675. }
  676. else if( n->type == asLPT_REPEAT )
  677. str += " repeat";
  678. else if( n->type == asLPT_REPEAT_SAME )
  679. str += " repeat_same";
  680. else if( n->type == asLPT_TYPE )
  681. {
  682. if( first )
  683. {
  684. str += " ";
  685. first = false;
  686. }
  687. else
  688. str += ", ";
  689. str += reinterpret_cast<asSListPatternDataTypeNode*>(n)->dataType.Format(nameSpace, includeNamespace);
  690. }
  691. n = n->next;
  692. }
  693. }
  694. return str;
  695. }
  696. // interface
  697. int asCScriptFunction::FindNextLineWithCode(int line) const
  698. {
  699. if( scriptData == 0 ) return -1;
  700. if( scriptData->lineNumbers.GetLength() == 0 ) return -1;
  701. // The line numbers for constructors are not in order due to the way
  702. // class members can be initialized directly in the declaration
  703. if( objectType && objectType->name == name )
  704. {
  705. // Sort all line numbers before looking for the next
  706. asCArray<int> lineNbrs;
  707. for( asUINT n = 1; n < scriptData->lineNumbers.GetLength(); n += 2 )
  708. lineNbrs.PushLast(scriptData->lineNumbers[n]&0xFFFFF);
  709. struct C
  710. {
  711. static int cmp(const void *a, const void *b) { return *(int*)a - *(int*)b; }
  712. };
  713. std::qsort(&lineNbrs[0], lineNbrs.GetLength(), sizeof(int), C::cmp);
  714. if( line < lineNbrs[0] && line < (scriptData->declaredAt&0xFFFFF)) return -1;
  715. if( line > lineNbrs[lineNbrs.GetLength()-1] ) return -1;
  716. // Find the line with code on or right after the input line
  717. // TODO: optimize: Do binary search
  718. for( asUINT n = 0; n < lineNbrs.GetLength(); n++ )
  719. if( line <= lineNbrs[n] )
  720. return lineNbrs[n];
  721. }
  722. else
  723. {
  724. // Check if given line is outside function
  725. if( line < (scriptData->declaredAt&0xFFFFF) ) return -1;
  726. if( line > (scriptData->lineNumbers[scriptData->lineNumbers.GetLength()-1]&0xFFFFF) ) return -1;
  727. // Find the line with code on or right after the input line
  728. // TODO: optimize: Do binary search instead
  729. for( asUINT n = 1; n < scriptData->lineNumbers.GetLength(); n += 2 )
  730. {
  731. if( line <= (scriptData->lineNumbers[n]&0xFFFFF) )
  732. return (scriptData->lineNumbers[n]&0xFFFFF);
  733. }
  734. }
  735. return -1;
  736. }
  737. // internal
  738. int asCScriptFunction::GetLineNumber(int programPosition, int *sectionIdx)
  739. {
  740. asASSERT( scriptData );
  741. if( sectionIdx ) *sectionIdx = scriptData->scriptSectionIdx;
  742. if( scriptData->lineNumbers.GetLength() == 0 ) return 0;
  743. if( sectionIdx )
  744. {
  745. // Find the correct section index if the function is compiled from multiple sections
  746. // This array will be empty most of the time so we don't need a sofisticated algorithm to search it
  747. for( asUINT n = 0; n < scriptData->sectionIdxs.GetLength(); n += 2 )
  748. {
  749. if( scriptData->sectionIdxs[n] <= programPosition )
  750. *sectionIdx = scriptData->sectionIdxs[n+1];
  751. }
  752. }
  753. // Do a binary search in the buffer
  754. int max = (int)scriptData->lineNumbers.GetLength()/2 - 1;
  755. int min = 0;
  756. int i = max/2;
  757. for(;;)
  758. {
  759. if( scriptData->lineNumbers[i*2] < programPosition )
  760. {
  761. // Have we found the largest number < programPosition?
  762. if( max == i ) return scriptData->lineNumbers[i*2+1];
  763. if( scriptData->lineNumbers[i*2+2] > programPosition ) return scriptData->lineNumbers[i*2+1];
  764. min = i + 1;
  765. i = (max + min)/2;
  766. }
  767. else if( scriptData->lineNumbers[i*2] > programPosition )
  768. {
  769. // Have we found the smallest number > programPosition?
  770. if( min == i ) return scriptData->lineNumbers[i*2+1];
  771. max = i - 1;
  772. i = (max + min)/2;
  773. }
  774. else
  775. {
  776. // We found the exact position
  777. return scriptData->lineNumbers[i*2+1];
  778. }
  779. }
  780. }
  781. // interface
  782. asEFuncType asCScriptFunction::GetFuncType() const
  783. {
  784. return funcType;
  785. }
  786. // interface
  787. asUINT asCScriptFunction::GetVarCount() const
  788. {
  789. if( scriptData )
  790. return asUINT(scriptData->variables.GetLength());
  791. return 0;
  792. }
  793. // interface
  794. int asCScriptFunction::GetVar(asUINT index, const char **out_name, int *out_typeId) const
  795. {
  796. if( scriptData == 0 )
  797. return asNOT_SUPPORTED;
  798. if( index >= scriptData->variables.GetLength() )
  799. return asINVALID_ARG;
  800. if( out_name )
  801. *out_name = scriptData->variables[index]->name.AddressOf();
  802. if( out_typeId )
  803. *out_typeId = engine->GetTypeIdFromDataType(scriptData->variables[index]->type);
  804. return asSUCCESS;
  805. }
  806. // interface
  807. const char *asCScriptFunction::GetVarDecl(asUINT index, bool includeNamespace) const
  808. {
  809. if( scriptData == 0 || index >= scriptData->variables.GetLength() )
  810. return 0;
  811. asCString *tempString = &asCThreadManager::GetLocalData()->string;
  812. *tempString = scriptData->variables[index]->type.Format(nameSpace, includeNamespace);
  813. *tempString += " " + scriptData->variables[index]->name;
  814. return tempString->AddressOf();
  815. }
  816. // internal
  817. void asCScriptFunction::AddVariable(asCString &in_name, asCDataType &in_type, int in_stackOffset)
  818. {
  819. asASSERT( scriptData );
  820. asSScriptVariable *var = asNEW(asSScriptVariable);
  821. if( var == 0 )
  822. {
  823. // Out of memory
  824. return;
  825. }
  826. var->name = in_name;
  827. var->type = in_type;
  828. var->stackOffset = in_stackOffset;
  829. var->declaredAtProgramPos = 0;
  830. scriptData->variables.PushLast(var);
  831. }
  832. // internal
  833. asCTypeInfo *asCScriptFunction::GetTypeInfoOfLocalVar(short varOffset)
  834. {
  835. asASSERT( scriptData );
  836. for( asUINT n = 0; n < scriptData->objVariablePos.GetLength(); n++ )
  837. {
  838. if( scriptData->objVariablePos[n] == varOffset )
  839. return scriptData->objVariableTypes[n];
  840. }
  841. return 0;
  842. }
  843. // internal
  844. void asCScriptFunction::ComputeSignatureId()
  845. {
  846. // This function will compute the signatureId based on the
  847. // function name, return type, and parameter types. The object
  848. // type for methods is not used, so that class methods and
  849. // interface methods match each other.
  850. for( asUINT n = 0; n < engine->signatureIds.GetLength(); n++ )
  851. {
  852. if( !IsSignatureEqual(engine->signatureIds[n]) ) continue;
  853. // We don't need to increment the reference counter here, because
  854. // asCScriptEngine::FreeScriptFunctionId will maintain the signature
  855. // id as the function is freed.
  856. signatureId = engine->signatureIds[n]->signatureId;
  857. return;
  858. }
  859. signatureId = id;
  860. engine->signatureIds.PushLast(this);
  861. }
  862. // internal
  863. bool asCScriptFunction::IsSignatureEqual(const asCScriptFunction *func) const
  864. {
  865. if( name != func->name || !IsSignatureExceptNameEqual(func) ) return false;
  866. return true;
  867. }
  868. // internal
  869. bool asCScriptFunction::IsSignatureExceptNameEqual(const asCScriptFunction *func) const
  870. {
  871. return IsSignatureExceptNameEqual(func->returnType, func->parameterTypes, func->inOutFlags, func->objectType, func->IsReadOnly());
  872. }
  873. // internal
  874. bool asCScriptFunction::IsSignatureExceptNameEqual(const asCDataType &retType, const asCArray<asCDataType> &paramTypes, const asCArray<asETypeModifiers> &paramInOut, const asCObjectType *objType, bool readOnly) const
  875. {
  876. if( this->returnType != retType ) return false;
  877. return IsSignatureExceptNameAndReturnTypeEqual(paramTypes, paramInOut, objType, readOnly);
  878. }
  879. // internal
  880. bool asCScriptFunction::IsSignatureExceptNameAndObjectTypeEqual(const asCScriptFunction *func) const
  881. {
  882. return IsSignatureExceptNameEqual(func->returnType, func->parameterTypes, func->inOutFlags, objectType, IsReadOnly());
  883. }
  884. // internal
  885. bool asCScriptFunction::IsSignatureExceptNameAndReturnTypeEqual(const asCScriptFunction *func) const
  886. {
  887. return IsSignatureExceptNameAndReturnTypeEqual(func->parameterTypes, func->inOutFlags, func->objectType, func->IsReadOnly());
  888. }
  889. // internal
  890. bool asCScriptFunction::IsSignatureExceptNameAndReturnTypeEqual(const asCArray<asCDataType> &paramTypes, const asCArray<asETypeModifiers> &paramInOut, const asCObjectType *objType, bool readOnly) const
  891. {
  892. if( this->IsReadOnly() != readOnly ) return false;
  893. if( (this->objectType != 0) != (objType != 0) ) return false;
  894. if( this->inOutFlags != paramInOut ) return false;
  895. if( this->parameterTypes != paramTypes ) return false;
  896. return true;
  897. }
  898. // internal
  899. void asCScriptFunction::AddReferences()
  900. {
  901. // This array will be used to make sure we only add the reference to the same resource once
  902. // This is especially important for global variables, as it expects the initialization function
  903. // to hold only one reference to the variable. However, if the variable is initialized through
  904. // the default constructor followed by the assignment operator we will have two references to
  905. // the variable in the function.
  906. asCArray<void*> ptrs;
  907. // Only count references if there is any bytecode
  908. if( scriptData && scriptData->byteCode.GetLength() )
  909. {
  910. if( returnType.GetTypeInfo() )
  911. {
  912. returnType.GetTypeInfo()->AddRefInternal();
  913. asCConfigGroup *group = engine->FindConfigGroupForTypeInfo(returnType.GetTypeInfo());
  914. if( group != 0 ) group->AddRef();
  915. }
  916. for( asUINT p = 0; p < parameterTypes.GetLength(); p++ )
  917. if( parameterTypes[p].GetTypeInfo() )
  918. {
  919. parameterTypes[p].GetTypeInfo()->AddRefInternal();
  920. asCConfigGroup *group = engine->FindConfigGroupForTypeInfo(parameterTypes[p].GetTypeInfo());
  921. if( group != 0 ) group->AddRef();
  922. }
  923. for( asUINT v = 0; v < scriptData->objVariableTypes.GetLength(); v++ )
  924. if( scriptData->objVariableTypes[v] ) // The null handle is also stored, but it doesn't have an object type
  925. {
  926. scriptData->objVariableTypes[v]->AddRefInternal();
  927. asCConfigGroup *group = engine->FindConfigGroupForTypeInfo(scriptData->objVariableTypes[v]);
  928. if( group != 0 ) group->AddRef();
  929. }
  930. // Go through the byte code and add references to all resources used by the function
  931. asCArray<asDWORD> &bc = scriptData->byteCode;
  932. for( asUINT n = 0; n < bc.GetLength(); n += asBCTypeSize[asBCInfo[*(asBYTE*)&bc[n]].type] )
  933. {
  934. switch( *(asBYTE*)&bc[n] )
  935. {
  936. // Object types
  937. case asBC_OBJTYPE:
  938. case asBC_FREE:
  939. case asBC_REFCPY:
  940. case asBC_RefCpyV:
  941. {
  942. asCObjectType *objType = (asCObjectType*)asBC_PTRARG(&bc[n]);
  943. asASSERT( objType );
  944. if( objType )
  945. objType->AddRefInternal();
  946. }
  947. break;
  948. // Object type and function
  949. case asBC_ALLOC:
  950. {
  951. asCObjectType *objType = (asCObjectType*)asBC_PTRARG(&bc[n]);
  952. asASSERT( objType );
  953. if( objType )
  954. objType->AddRefInternal();
  955. int funcId = asBC_INTARG(&bc[n]+AS_PTR_SIZE);
  956. if( funcId )
  957. engine->scriptFunctions[funcId]->AddRefInternal();
  958. }
  959. break;
  960. // Global variables
  961. case asBC_PGA:
  962. case asBC_PshGPtr:
  963. case asBC_LDG:
  964. case asBC_PshG4:
  965. case asBC_LdGRdR4:
  966. case asBC_CpyGtoV4:
  967. case asBC_CpyVtoG4:
  968. case asBC_SetG4:
  969. // Need to increase the reference for each global variable
  970. {
  971. void *gvarPtr = (void*)asBC_PTRARG(&bc[n]);
  972. if( !gvarPtr ) break;
  973. asCGlobalProperty *prop = GetPropertyByGlobalVarPtr(gvarPtr);
  974. if (!prop)
  975. {
  976. // The pointer is a string constant. In order to make sure the correct resource
  977. // management is maintained we request a new string constant here, so the compiler
  978. // or bytecode loader can release its copy afterwards.
  979. asCString str;
  980. asUINT length;
  981. int r = engine->stringFactory->GetRawStringData(gvarPtr, 0, &length);
  982. if (r >= 0)
  983. {
  984. str.SetLength(length);
  985. engine->stringFactory->GetRawStringData(gvarPtr, str.AddressOf(), &length);
  986. // Get a new pointer (depending on the string factory implementation it may actually be the same)
  987. gvarPtr = const_cast<void*>(engine->stringFactory->GetStringConstant(str.AddressOf(), length));
  988. asBC_PTRARG(&bc[n]) = (asPWORD)gvarPtr;
  989. }
  990. // If we get an error from the string factory there is not
  991. // anything we can do about it, except report a message.
  992. // TODO: NEWSTRING: Write a message and then exit gracefully
  993. asASSERT(r >= 0);
  994. break;
  995. }
  996. // Only addref the properties once
  997. if( !ptrs.Exists(gvarPtr) )
  998. {
  999. prop->AddRef();
  1000. ptrs.PushLast(gvarPtr);
  1001. }
  1002. asCConfigGroup *group = engine->FindConfigGroupForGlobalVar(prop->id);
  1003. if( group != 0 ) group->AddRef();
  1004. }
  1005. break;
  1006. // System functions
  1007. case asBC_CALLSYS:
  1008. {
  1009. int funcId = asBC_INTARG(&bc[n]);
  1010. asCConfigGroup *group = engine->FindConfigGroupForFunction(funcId);
  1011. if( group != 0 ) group->AddRef();
  1012. asASSERT( funcId > 0 );
  1013. if( funcId > 0 )
  1014. engine->scriptFunctions[funcId]->AddRefInternal();
  1015. }
  1016. break;
  1017. // Functions
  1018. case asBC_CALL:
  1019. case asBC_CALLINTF:
  1020. {
  1021. int funcId = asBC_INTARG(&bc[n]);
  1022. asASSERT( funcId > 0 );
  1023. if( funcId > 0 )
  1024. engine->scriptFunctions[funcId]->AddRefInternal();
  1025. }
  1026. break;
  1027. // Function pointers
  1028. case asBC_FuncPtr:
  1029. {
  1030. asCScriptFunction *func = (asCScriptFunction*)asBC_PTRARG(&bc[n]);
  1031. asASSERT( func );
  1032. if( func )
  1033. func->AddRefInternal();
  1034. }
  1035. break;
  1036. }
  1037. }
  1038. }
  1039. }
  1040. // internal
  1041. void asCScriptFunction::ReleaseReferences()
  1042. {
  1043. asCArray<void*> ptrs;
  1044. // Only count references if there is any bytecode
  1045. if( scriptData && scriptData->byteCode.GetLength() )
  1046. {
  1047. if( returnType.GetTypeInfo() )
  1048. {
  1049. returnType.GetTypeInfo()->ReleaseInternal();
  1050. asCConfigGroup *group = engine->FindConfigGroupForTypeInfo(returnType.GetTypeInfo());
  1051. if( group != 0 ) group->Release();
  1052. }
  1053. for( asUINT p = 0; p < parameterTypes.GetLength(); p++ )
  1054. if( parameterTypes[p].GetTypeInfo() )
  1055. {
  1056. parameterTypes[p].GetTypeInfo()->ReleaseInternal();
  1057. asCConfigGroup *group = engine->FindConfigGroupForTypeInfo(parameterTypes[p].GetTypeInfo());
  1058. if( group != 0 ) group->Release();
  1059. }
  1060. for( asUINT v = 0; v < scriptData->objVariableTypes.GetLength(); v++ )
  1061. if( scriptData->objVariableTypes[v] ) // The null handle is also stored, but it doesn't have an object type
  1062. {
  1063. scriptData->objVariableTypes[v]->ReleaseInternal();
  1064. asCConfigGroup *group = engine->FindConfigGroupForTypeInfo(scriptData->objVariableTypes[v]);
  1065. if( group != 0 ) group->Release();
  1066. }
  1067. // Go through the byte code and release references to all resources used by the function
  1068. asCArray<asDWORD> &bc = scriptData->byteCode;
  1069. for( asUINT n = 0; n < bc.GetLength(); n += asBCTypeSize[asBCInfo[*(asBYTE*)&bc[n]].type] )
  1070. {
  1071. switch( *(asBYTE*)&bc[n] )
  1072. {
  1073. // Object types
  1074. case asBC_OBJTYPE:
  1075. case asBC_FREE:
  1076. case asBC_REFCPY:
  1077. case asBC_RefCpyV:
  1078. {
  1079. asCObjectType *objType = (asCObjectType*)asBC_PTRARG(&bc[n]);
  1080. if( objType )
  1081. objType->ReleaseInternal();
  1082. }
  1083. break;
  1084. // Object type and function
  1085. case asBC_ALLOC:
  1086. {
  1087. asCObjectType *objType = (asCObjectType*)asBC_PTRARG(&bc[n]);
  1088. if( objType )
  1089. objType->ReleaseInternal();
  1090. int funcId = asBC_INTARG(&bc[n]+AS_PTR_SIZE);
  1091. if( funcId > 0 )
  1092. {
  1093. asCScriptFunction *fptr = engine->scriptFunctions[funcId];
  1094. if( fptr )
  1095. fptr->ReleaseInternal();
  1096. // The engine may have been forced to destroy the function internals early
  1097. // and this may will make it impossible to find the function by id anymore.
  1098. // This should only happen if the engine is released while the application
  1099. // is still keeping functions alive.
  1100. // TODO: Fix this possible memory leak
  1101. }
  1102. }
  1103. break;
  1104. // Global variables
  1105. case asBC_PGA:
  1106. case asBC_PshGPtr:
  1107. case asBC_LDG:
  1108. case asBC_PshG4:
  1109. case asBC_LdGRdR4:
  1110. case asBC_CpyGtoV4:
  1111. case asBC_CpyVtoG4:
  1112. case asBC_SetG4:
  1113. // Need to increase the reference for each global variable
  1114. {
  1115. void *gvarPtr = (void*)asBC_PTRARG(&bc[n]);
  1116. if( !gvarPtr ) break;
  1117. asCGlobalProperty *prop = GetPropertyByGlobalVarPtr(gvarPtr);
  1118. if (!prop)
  1119. {
  1120. // The pointer is a string constant, so it needs to be released by the string factory
  1121. int r = engine->stringFactory->ReleaseStringConstant(gvarPtr);
  1122. UNUSED_VAR(r);
  1123. // If we get an error from the string factory there is not
  1124. // anything we can do about it, except report a message.
  1125. // TODO: Write a message showing that the string couldn't be
  1126. // released. Include the first 10 characters and the length
  1127. // to make it easier to identify which string it was
  1128. asASSERT(r >= 0);
  1129. break;
  1130. }
  1131. // Only release the properties once
  1132. if( !ptrs.Exists(gvarPtr) )
  1133. {
  1134. prop->Release();
  1135. ptrs.PushLast(gvarPtr);
  1136. }
  1137. asCConfigGroup *group = engine->FindConfigGroupForGlobalVar(prop->id);
  1138. if( group != 0 ) group->Release();
  1139. }
  1140. break;
  1141. // System functions
  1142. case asBC_CALLSYS:
  1143. {
  1144. int funcId = asBC_INTARG(&bc[n]);
  1145. asCConfigGroup *group = engine->FindConfigGroupForFunction(funcId);
  1146. if( group != 0 ) group->Release();
  1147. if( funcId )
  1148. {
  1149. asCScriptFunction *fptr = engine->scriptFunctions[funcId];
  1150. if( fptr )
  1151. fptr->ReleaseInternal();
  1152. }
  1153. }
  1154. break;
  1155. // Functions
  1156. case asBC_CALL:
  1157. case asBC_CALLINTF:
  1158. {
  1159. int funcId = asBC_INTARG(&bc[n]);
  1160. if( funcId )
  1161. {
  1162. asCScriptFunction *fptr = engine->scriptFunctions[funcId];
  1163. if( fptr )
  1164. fptr->ReleaseInternal();
  1165. // The engine may have been forced to destroy the function internals early
  1166. // and this may will make it impossible to find the function by id anymore.
  1167. // This should only happen if the engine is released while the application
  1168. // is still keeping functions alive.
  1169. // TODO: Fix this possible memory leak
  1170. }
  1171. }
  1172. break;
  1173. // Function pointers
  1174. case asBC_FuncPtr:
  1175. {
  1176. asCScriptFunction *func = (asCScriptFunction*)asBC_PTRARG(&bc[n]);
  1177. if( func )
  1178. func->ReleaseInternal();
  1179. }
  1180. break;
  1181. }
  1182. }
  1183. // Release the jit compiled function
  1184. if( scriptData->jitFunction )
  1185. engine->jitCompiler->ReleaseJITFunction(scriptData->jitFunction);
  1186. scriptData->jitFunction = 0;
  1187. }
  1188. // Delegate
  1189. if( objForDelegate )
  1190. engine->ReleaseScriptObject(objForDelegate, funcForDelegate->GetObjectType());
  1191. objForDelegate = 0;
  1192. if( funcForDelegate )
  1193. funcForDelegate->Release();
  1194. funcForDelegate = 0;
  1195. }
  1196. // interface
  1197. int asCScriptFunction::GetReturnTypeId(asDWORD *flags) const
  1198. {
  1199. if( flags )
  1200. {
  1201. if( returnType.IsReference() )
  1202. {
  1203. *flags = asTM_INOUTREF;
  1204. *flags |= returnType.IsReadOnly() ? asTM_CONST : 0;
  1205. }
  1206. else
  1207. *flags = asTM_NONE;
  1208. }
  1209. return engine->GetTypeIdFromDataType(returnType);
  1210. }
  1211. // interface
  1212. asUINT asCScriptFunction::GetParamCount() const
  1213. {
  1214. return (asUINT)parameterTypes.GetLength();
  1215. }
  1216. // interface
  1217. int asCScriptFunction::GetParam(asUINT index, int *out_typeId, asDWORD *out_flags, const char **out_name, const char **out_defaultArg) const
  1218. {
  1219. if( index >= parameterTypes.GetLength() )
  1220. return asINVALID_ARG;
  1221. if( out_typeId )
  1222. *out_typeId = engine->GetTypeIdFromDataType(parameterTypes[index]);
  1223. if( out_flags )
  1224. {
  1225. *out_flags = inOutFlags[index];
  1226. *out_flags |= parameterTypes[index].IsReadOnly() ? asTM_CONST : 0;
  1227. }
  1228. if( out_name )
  1229. {
  1230. // The parameter names are not stored if loading from bytecode without debug information
  1231. if( index < parameterNames.GetLength() )
  1232. *out_name = parameterNames[index].AddressOf();
  1233. else
  1234. *out_name = 0;
  1235. }
  1236. if( out_defaultArg )
  1237. {
  1238. if( index < defaultArgs.GetLength() && defaultArgs[index] )
  1239. *out_defaultArg = defaultArgs[index]->AddressOf();
  1240. else
  1241. *out_defaultArg = 0;
  1242. }
  1243. return asSUCCESS;
  1244. }
  1245. // interface
  1246. asIScriptEngine *asCScriptFunction::GetEngine() const
  1247. {
  1248. return engine;
  1249. }
  1250. // interface
  1251. const char *asCScriptFunction::GetDeclaration(bool includeObjectName, bool includeNamespace, bool includeParamNames) const
  1252. {
  1253. asCString *tempString = &asCThreadManager::GetLocalData()->string;
  1254. *tempString = GetDeclarationStr(includeObjectName, includeNamespace, includeParamNames);
  1255. return tempString->AddressOf();
  1256. }
  1257. // interface
  1258. const char *asCScriptFunction::GetScriptSectionName() const
  1259. {
  1260. if( scriptData && scriptData->scriptSectionIdx >= 0 )
  1261. return engine->scriptSectionNames[scriptData->scriptSectionIdx]->AddressOf();
  1262. return 0;
  1263. }
  1264. // interface
  1265. const char *asCScriptFunction::GetConfigGroup() const
  1266. {
  1267. asCConfigGroup *group = 0;
  1268. if( funcType != asFUNC_FUNCDEF )
  1269. group = engine->FindConfigGroupForFunction(id);
  1270. else
  1271. group = engine->FindConfigGroupForFuncDef(this->funcdefType);
  1272. if( group == 0 )
  1273. return 0;
  1274. return group->groupName.AddressOf();
  1275. }
  1276. // interface
  1277. asDWORD asCScriptFunction::GetAccessMask() const
  1278. {
  1279. return accessMask;
  1280. }
  1281. // internal
  1282. void asCScriptFunction::JITCompile()
  1283. {
  1284. if( funcType != asFUNC_SCRIPT )
  1285. return;
  1286. asASSERT( scriptData );
  1287. asIJITCompiler *jit = engine->GetJITCompiler();
  1288. if( !jit )
  1289. return;
  1290. // Make sure the function has been compiled with JitEntry instructions
  1291. // For functions that has JitEntry this will be a quick test
  1292. asUINT length;
  1293. asDWORD *byteCode = GetByteCode(&length);
  1294. asDWORD *end = byteCode + length;
  1295. bool foundJitEntry = false;
  1296. while( byteCode < end )
  1297. {
  1298. // Determine the instruction
  1299. asEBCInstr op = asEBCInstr(*(asBYTE*)byteCode);
  1300. if( op == asBC_JitEntry )
  1301. {
  1302. foundJitEntry = true;
  1303. break;
  1304. }
  1305. // Move to next instruction
  1306. byteCode += asBCTypeSize[asBCInfo[op].type];
  1307. }
  1308. if( !foundJitEntry )
  1309. {
  1310. asCString msg;
  1311. msg.Format(TXT_NO_JIT_IN_FUNC_s, GetDeclaration());
  1312. engine->WriteMessage("", 0, 0, asMSGTYPE_WARNING, msg.AddressOf());
  1313. }
  1314. // Release the previous function, if any
  1315. if( scriptData->jitFunction )
  1316. {
  1317. engine->jitCompiler->ReleaseJITFunction(scriptData->jitFunction);
  1318. scriptData->jitFunction = 0;
  1319. }
  1320. // Compile for native system
  1321. int r = jit->CompileFunction(this, &scriptData->jitFunction);
  1322. if( r < 0 )
  1323. asASSERT( scriptData->jitFunction == 0 );
  1324. }
  1325. // interface
  1326. asDWORD *asCScriptFunction::GetByteCode(asUINT *length)
  1327. {
  1328. if( scriptData == 0 ) return 0;
  1329. if( length )
  1330. *length = (asUINT)scriptData->byteCode.GetLength();
  1331. if( scriptData->byteCode.GetLength() )
  1332. return scriptData->byteCode.AddressOf();
  1333. return 0;
  1334. }
  1335. // interface
  1336. void *asCScriptFunction::SetUserData(void *data, asPWORD type)
  1337. {
  1338. // As a thread might add a new new user data at the same time as another
  1339. // it is necessary to protect both read and write access to the userData member
  1340. ACQUIREEXCLUSIVE(engine->engineRWLock);
  1341. // It is not intended to store a lot of different types of userdata,
  1342. // so a more complex structure like a associative map would just have
  1343. // more overhead than a simple array.
  1344. for( asUINT n = 0; n < userData.GetLength(); n += 2 )
  1345. {
  1346. if( userData[n] == type )
  1347. {
  1348. void *oldData = reinterpret_cast<void*>(userData[n+1]);
  1349. userData[n+1] = reinterpret_cast<asPWORD>(data);
  1350. RELEASEEXCLUSIVE(engine->engineRWLock);
  1351. return oldData;
  1352. }
  1353. }
  1354. userData.PushLast(type);
  1355. userData.PushLast(reinterpret_cast<asPWORD>(data));
  1356. RELEASEEXCLUSIVE(engine->engineRWLock);
  1357. return 0;
  1358. }
  1359. // interface
  1360. void *asCScriptFunction::GetUserData(asPWORD type) const
  1361. {
  1362. // There may be multiple threads reading, but when
  1363. // setting the user data nobody must be reading.
  1364. ACQUIRESHARED(engine->engineRWLock);
  1365. for( asUINT n = 0; n < userData.GetLength(); n += 2 )
  1366. {
  1367. if( userData[n] == type )
  1368. {
  1369. RELEASESHARED(engine->engineRWLock);
  1370. return reinterpret_cast<void*>(userData[n+1]);
  1371. }
  1372. }
  1373. RELEASESHARED(engine->engineRWLock);
  1374. return 0;
  1375. }
  1376. // internal
  1377. // TODO: cleanup: This method should probably be a member of the engine
  1378. asCGlobalProperty *asCScriptFunction::GetPropertyByGlobalVarPtr(void *gvarPtr)
  1379. {
  1380. asSMapNode<void*, asCGlobalProperty*> *node;
  1381. if( engine->varAddressMap.MoveTo(&node, gvarPtr) )
  1382. {
  1383. asASSERT(gvarPtr == node->value->GetAddressOfValue());
  1384. return node->value;
  1385. }
  1386. return 0;
  1387. }
  1388. // internal
  1389. int asCScriptFunction::GetRefCount()
  1390. {
  1391. asASSERT( funcType == asFUNC_DELEGATE );
  1392. return externalRefCount.get();
  1393. }
  1394. // internal
  1395. void asCScriptFunction::SetFlag()
  1396. {
  1397. gcFlag = true;
  1398. }
  1399. // internal
  1400. bool asCScriptFunction::GetFlag()
  1401. {
  1402. return gcFlag;
  1403. }
  1404. // internal
  1405. void asCScriptFunction::EnumReferences(asIScriptEngine *)
  1406. {
  1407. asASSERT( funcType == asFUNC_DELEGATE );
  1408. // Delegate
  1409. if( objForDelegate )
  1410. engine->GCEnumCallback(objForDelegate);
  1411. }
  1412. // internal
  1413. void asCScriptFunction::ReleaseAllHandles(asIScriptEngine *)
  1414. {
  1415. asASSERT( funcType == asFUNC_DELEGATE );
  1416. // Release paramaters
  1417. // Delegate
  1418. if( objForDelegate )
  1419. engine->ReleaseScriptObject(objForDelegate, funcForDelegate->GetObjectType());
  1420. objForDelegate = 0;
  1421. }
  1422. // interface
  1423. bool asCScriptFunction::IsShared() const
  1424. {
  1425. // All system functions are shared
  1426. if( funcType == asFUNC_SYSTEM ) return true;
  1427. // All class methods for shared classes are also shared
  1428. asASSERT( objectType == 0 || objectType->engine == engine || objectType->engine == 0 );
  1429. if( objectType && (objectType->flags & asOBJ_SHARED) ) return true;
  1430. // funcdefs that are registered by the application are shared
  1431. if (funcType == asFUNC_FUNCDEF && module == 0) return true;
  1432. // Functions that have been specifically marked as shared are shared
  1433. return traits.GetTrait(asTRAIT_SHARED);
  1434. }
  1435. // interface
  1436. bool asCScriptFunction::IsFinal() const
  1437. {
  1438. return traits.GetTrait(asTRAIT_FINAL);
  1439. }
  1440. // interface
  1441. bool asCScriptFunction::IsOverride() const
  1442. {
  1443. return traits.GetTrait(asTRAIT_OVERRIDE);
  1444. }
  1445. // interface
  1446. bool asCScriptFunction::IsExplicit() const
  1447. {
  1448. return traits.GetTrait(asTRAIT_EXPLICIT);
  1449. }
  1450. END_AS_NAMESPACE