2
0

as_scriptfunction.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2020 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. return module->GetName();
  489. return 0;
  490. }
  491. // interface
  492. asIScriptModule *asCScriptFunction::GetModule() const
  493. {
  494. return module;
  495. }
  496. // interface
  497. asITypeInfo *asCScriptFunction::GetObjectType() const
  498. {
  499. return objectType;
  500. }
  501. // interface
  502. const char *asCScriptFunction::GetObjectName() const
  503. {
  504. if( objectType )
  505. return objectType->GetName();
  506. return 0;
  507. }
  508. // interface
  509. const char *asCScriptFunction::GetName() const
  510. {
  511. return name.AddressOf();
  512. }
  513. // interface
  514. const char *asCScriptFunction::GetNamespace() const
  515. {
  516. if (nameSpace)
  517. return nameSpace->name.AddressOf();
  518. return 0;
  519. }
  520. // interface
  521. bool asCScriptFunction::IsReadOnly() const
  522. {
  523. return traits.GetTrait(asTRAIT_CONST);
  524. }
  525. // interface
  526. bool asCScriptFunction::IsPrivate() const
  527. {
  528. return traits.GetTrait(asTRAIT_PRIVATE);
  529. }
  530. // interface
  531. bool asCScriptFunction::IsProtected() const
  532. {
  533. return traits.GetTrait(asTRAIT_PROTECTED);
  534. }
  535. // internal
  536. int asCScriptFunction::GetSpaceNeededForArguments()
  537. {
  538. // We need to check the size for each type
  539. int s = 0;
  540. for( asUINT n = 0; n < parameterTypes.GetLength(); n++ )
  541. s += parameterTypes[n].GetSizeOnStackDWords();
  542. return s;
  543. }
  544. // internal
  545. int asCScriptFunction::GetSpaceNeededForReturnValue()
  546. {
  547. return returnType.GetSizeOnStackDWords();
  548. }
  549. // internal
  550. bool asCScriptFunction::DoesReturnOnStack() const
  551. {
  552. if( returnType.GetTypeInfo() &&
  553. (returnType.GetTypeInfo()->flags & asOBJ_VALUE) &&
  554. !returnType.IsReference() )
  555. return true;
  556. return false;
  557. }
  558. // internal
  559. asCString asCScriptFunction::GetDeclarationStr(bool includeObjectName, bool includeNamespace, bool includeParamNames) const
  560. {
  561. asCString str;
  562. // TODO: default arg: Make the declaration with the default args an option
  563. // Don't add the return type for constructors and destructors
  564. if( !(returnType.GetTokenType() == ttVoid &&
  565. objectType &&
  566. (name == objectType->name || (name.GetLength() > 0 && name[0] == '~') ||
  567. name == "$beh0" || name == "$beh2")) )
  568. {
  569. str = returnType.Format(nameSpace, includeNamespace);
  570. str += " ";
  571. }
  572. if( objectType && includeObjectName )
  573. {
  574. if( includeNamespace && objectType->nameSpace->name != "" )
  575. str += objectType->nameSpace->name + "::";
  576. if( objectType->name != "" )
  577. str += objectType->name + "::";
  578. else
  579. str += "_unnamed_type_::";
  580. }
  581. else if (funcdefType && funcdefType->parentClass && includeObjectName)
  582. {
  583. if (includeNamespace && funcdefType->parentClass->nameSpace->name != "")
  584. str += funcdefType->parentClass->nameSpace->name + "::";
  585. if (funcdefType->parentClass->name != "")
  586. str += funcdefType->parentClass->name + "::";
  587. else
  588. str += "_unnamed_type_::";
  589. }
  590. else if( includeNamespace && nameSpace->name != "" && !objectType )
  591. {
  592. str += nameSpace->name + "::";
  593. }
  594. if( name == "" )
  595. str += "_unnamed_function_(";
  596. else if( name.SubString(0,4) == "$beh" && name.GetLength() == 5 )
  597. {
  598. if( name[4] == '0' + asBEHAVE_CONSTRUCT )
  599. str += objectType->name + "(";
  600. else if( name[4] == '0' + asBEHAVE_FACTORY )
  601. str += returnType.GetTypeInfo()->name + "(";
  602. else if( name[4] == '0' + asBEHAVE_DESTRUCT )
  603. str += "~" + objectType->name + "(";
  604. else
  605. str += name + "(";
  606. }
  607. else
  608. str += name + "(";
  609. if( parameterTypes.GetLength() > 0 )
  610. {
  611. asUINT n;
  612. for( n = 0; n < parameterTypes.GetLength() - 1; n++ )
  613. {
  614. str += parameterTypes[n].Format(nameSpace, includeNamespace);
  615. if( parameterTypes[n].IsReference() && inOutFlags.GetLength() > n )
  616. {
  617. if( inOutFlags[n] == asTM_INREF ) str += "in";
  618. else if( inOutFlags[n] == asTM_OUTREF ) str += "out";
  619. else if( inOutFlags[n] == asTM_INOUTREF ) str += "inout";
  620. }
  621. if( includeParamNames && n < parameterNames.GetLength() && parameterNames[n].GetLength() != 0 )
  622. {
  623. str += " ";
  624. str += parameterNames[n];
  625. }
  626. if( defaultArgs.GetLength() > n && defaultArgs[n] )
  627. {
  628. asCString tmp;
  629. tmp.Format(" = %s", defaultArgs[n]->AddressOf());
  630. str += tmp;
  631. }
  632. str += ", ";
  633. }
  634. // Add the last parameter
  635. str += parameterTypes[n].Format(nameSpace, includeNamespace);
  636. if( parameterTypes[n].IsReference() && inOutFlags.GetLength() > n )
  637. {
  638. if( inOutFlags[n] == asTM_INREF ) str += "in";
  639. else if( inOutFlags[n] == asTM_OUTREF ) str += "out";
  640. else if( inOutFlags[n] == asTM_INOUTREF ) str += "inout";
  641. }
  642. if( includeParamNames && n < parameterNames.GetLength() && parameterNames[n].GetLength() != 0 )
  643. {
  644. str += " ";
  645. str += parameterNames[n];
  646. }
  647. if( defaultArgs.GetLength() > n && defaultArgs[n] )
  648. {
  649. asCString tmp;
  650. tmp.Format(" = %s", defaultArgs[n]->AddressOf());
  651. str += tmp;
  652. }
  653. }
  654. str += ")";
  655. if( IsReadOnly() )
  656. str += " const";
  657. // Add the declaration of the list pattern
  658. if( listPattern )
  659. {
  660. asSListPatternNode *n = listPattern;
  661. bool first = true;
  662. while( n )
  663. {
  664. if( n->type == asLPT_START )
  665. {
  666. str += " {";
  667. first = true;
  668. }
  669. else if( n->type == asLPT_END )
  670. {
  671. str += " }";
  672. first = false;
  673. }
  674. else if( n->type == asLPT_REPEAT )
  675. str += " repeat";
  676. else if( n->type == asLPT_REPEAT_SAME )
  677. str += " repeat_same";
  678. else if( n->type == asLPT_TYPE )
  679. {
  680. if( first )
  681. {
  682. str += " ";
  683. first = false;
  684. }
  685. else
  686. str += ", ";
  687. str += reinterpret_cast<asSListPatternDataTypeNode*>(n)->dataType.Format(nameSpace, includeNamespace);
  688. }
  689. n = n->next;
  690. }
  691. }
  692. return str;
  693. }
  694. // interface
  695. int asCScriptFunction::FindNextLineWithCode(int line) const
  696. {
  697. if( scriptData == 0 ) return -1;
  698. if( scriptData->lineNumbers.GetLength() == 0 ) return -1;
  699. // The line numbers for constructors are not in order due to the way
  700. // class members can be initialized directly in the declaration
  701. if( objectType && objectType->name == name )
  702. {
  703. // Sort all line numbers before looking for the next
  704. asCArray<int> lineNbrs;
  705. for( asUINT n = 1; n < scriptData->lineNumbers.GetLength(); n += 2 )
  706. lineNbrs.PushLast(scriptData->lineNumbers[n]&0xFFFFF);
  707. struct C
  708. {
  709. static int cmp(const void *a, const void *b) { return *(int*)a - *(int*)b; }
  710. };
  711. std::qsort(&lineNbrs[0], lineNbrs.GetLength(), sizeof(int), C::cmp);
  712. if( line < lineNbrs[0] && line < (scriptData->declaredAt&0xFFFFF)) return -1;
  713. if( line > lineNbrs[lineNbrs.GetLength()-1] ) return -1;
  714. // Find the line with code on or right after the input line
  715. // TODO: optimize: Do binary search
  716. for( asUINT n = 0; n < lineNbrs.GetLength(); n++ )
  717. if( line <= lineNbrs[n] )
  718. return lineNbrs[n];
  719. }
  720. else
  721. {
  722. // Check if given line is outside function
  723. if( line < (scriptData->declaredAt&0xFFFFF) ) return -1;
  724. if( line > (scriptData->lineNumbers[scriptData->lineNumbers.GetLength()-1]&0xFFFFF) ) return -1;
  725. // Find the line with code on or right after the input line
  726. // TODO: optimize: Do binary search instead
  727. for( asUINT n = 1; n < scriptData->lineNumbers.GetLength(); n += 2 )
  728. {
  729. if( line <= (scriptData->lineNumbers[n]&0xFFFFF) )
  730. return (scriptData->lineNumbers[n]&0xFFFFF);
  731. }
  732. }
  733. return -1;
  734. }
  735. // internal
  736. int asCScriptFunction::GetLineNumber(int programPosition, int *sectionIdx)
  737. {
  738. asASSERT( scriptData );
  739. if( sectionIdx ) *sectionIdx = scriptData->scriptSectionIdx;
  740. if( scriptData->lineNumbers.GetLength() == 0 ) return 0;
  741. if( sectionIdx )
  742. {
  743. // Find the correct section index if the function is compiled from multiple sections
  744. // This array will be empty most of the time so we don't need a sofisticated algorithm to search it
  745. for( asUINT n = 0; n < scriptData->sectionIdxs.GetLength(); n += 2 )
  746. {
  747. if( scriptData->sectionIdxs[n] <= programPosition )
  748. *sectionIdx = scriptData->sectionIdxs[n+1];
  749. }
  750. }
  751. // Do a binary search in the buffer
  752. int max = (int)scriptData->lineNumbers.GetLength()/2 - 1;
  753. int min = 0;
  754. int i = max/2;
  755. for(;;)
  756. {
  757. if( scriptData->lineNumbers[i*2] < programPosition )
  758. {
  759. // Have we found the largest number < programPosition?
  760. if( max == i ) return scriptData->lineNumbers[i*2+1];
  761. if( scriptData->lineNumbers[i*2+2] > programPosition ) return scriptData->lineNumbers[i*2+1];
  762. min = i + 1;
  763. i = (max + min)/2;
  764. }
  765. else if( scriptData->lineNumbers[i*2] > programPosition )
  766. {
  767. // Have we found the smallest number > programPosition?
  768. if( min == i ) return scriptData->lineNumbers[i*2+1];
  769. max = i - 1;
  770. i = (max + min)/2;
  771. }
  772. else
  773. {
  774. // We found the exact position
  775. return scriptData->lineNumbers[i*2+1];
  776. }
  777. }
  778. }
  779. // interface
  780. asEFuncType asCScriptFunction::GetFuncType() const
  781. {
  782. return funcType;
  783. }
  784. // interface
  785. asUINT asCScriptFunction::GetVarCount() const
  786. {
  787. if( scriptData )
  788. return asUINT(scriptData->variables.GetLength());
  789. return 0;
  790. }
  791. // interface
  792. int asCScriptFunction::GetVar(asUINT index, const char **out_name, int *out_typeId) const
  793. {
  794. if( scriptData == 0 )
  795. return asNOT_SUPPORTED;
  796. if( index >= scriptData->variables.GetLength() )
  797. return asINVALID_ARG;
  798. if( out_name )
  799. *out_name = scriptData->variables[index]->name.AddressOf();
  800. if( out_typeId )
  801. *out_typeId = engine->GetTypeIdFromDataType(scriptData->variables[index]->type);
  802. return asSUCCESS;
  803. }
  804. // interface
  805. const char *asCScriptFunction::GetVarDecl(asUINT index, bool includeNamespace) const
  806. {
  807. if( scriptData == 0 || index >= scriptData->variables.GetLength() )
  808. return 0;
  809. asCString *tempString = &asCThreadManager::GetLocalData()->string;
  810. *tempString = scriptData->variables[index]->type.Format(nameSpace, includeNamespace);
  811. *tempString += " " + scriptData->variables[index]->name;
  812. return tempString->AddressOf();
  813. }
  814. // internal
  815. void asCScriptFunction::AddVariable(asCString &in_name, asCDataType &in_type, int in_stackOffset)
  816. {
  817. asASSERT( scriptData );
  818. asSScriptVariable *var = asNEW(asSScriptVariable);
  819. if( var == 0 )
  820. {
  821. // Out of memory
  822. return;
  823. }
  824. var->name = in_name;
  825. var->type = in_type;
  826. var->stackOffset = in_stackOffset;
  827. var->declaredAtProgramPos = 0;
  828. scriptData->variables.PushLast(var);
  829. }
  830. // internal
  831. asCTypeInfo *asCScriptFunction::GetTypeInfoOfLocalVar(short varOffset)
  832. {
  833. asASSERT( scriptData );
  834. for( asUINT n = 0; n < scriptData->objVariablePos.GetLength(); n++ )
  835. {
  836. if( scriptData->objVariablePos[n] == varOffset )
  837. return scriptData->objVariableTypes[n];
  838. }
  839. return 0;
  840. }
  841. // internal
  842. void asCScriptFunction::ComputeSignatureId()
  843. {
  844. // This function will compute the signatureId based on the
  845. // function name, return type, and parameter types. The object
  846. // type for methods is not used, so that class methods and
  847. // interface methods match each other.
  848. for( asUINT n = 0; n < engine->signatureIds.GetLength(); n++ )
  849. {
  850. if( !IsSignatureEqual(engine->signatureIds[n]) ) continue;
  851. // We don't need to increment the reference counter here, because
  852. // asCScriptEngine::FreeScriptFunctionId will maintain the signature
  853. // id as the function is freed.
  854. signatureId = engine->signatureIds[n]->signatureId;
  855. return;
  856. }
  857. signatureId = id;
  858. engine->signatureIds.PushLast(this);
  859. }
  860. // internal
  861. bool asCScriptFunction::IsSignatureEqual(const asCScriptFunction *func) const
  862. {
  863. if( name != func->name || !IsSignatureExceptNameEqual(func) ) return false;
  864. return true;
  865. }
  866. // internal
  867. bool asCScriptFunction::IsSignatureExceptNameEqual(const asCScriptFunction *func) const
  868. {
  869. return IsSignatureExceptNameEqual(func->returnType, func->parameterTypes, func->inOutFlags, func->objectType, func->IsReadOnly());
  870. }
  871. // internal
  872. bool asCScriptFunction::IsSignatureExceptNameEqual(const asCDataType &retType, const asCArray<asCDataType> &paramTypes, const asCArray<asETypeModifiers> &paramInOut, const asCObjectType *objType, bool readOnly) const
  873. {
  874. if( this->returnType != retType ) return false;
  875. return IsSignatureExceptNameAndReturnTypeEqual(paramTypes, paramInOut, objType, readOnly);
  876. }
  877. // internal
  878. bool asCScriptFunction::IsSignatureExceptNameAndObjectTypeEqual(const asCScriptFunction *func) const
  879. {
  880. return IsSignatureExceptNameEqual(func->returnType, func->parameterTypes, func->inOutFlags, objectType, IsReadOnly());
  881. }
  882. // internal
  883. bool asCScriptFunction::IsSignatureExceptNameAndReturnTypeEqual(const asCScriptFunction *func) const
  884. {
  885. return IsSignatureExceptNameAndReturnTypeEqual(func->parameterTypes, func->inOutFlags, func->objectType, func->IsReadOnly());
  886. }
  887. // internal
  888. bool asCScriptFunction::IsSignatureExceptNameAndReturnTypeEqual(const asCArray<asCDataType> &paramTypes, const asCArray<asETypeModifiers> &paramInOut, const asCObjectType *objType, bool readOnly) const
  889. {
  890. if( this->IsReadOnly() != readOnly ) return false;
  891. if( (this->objectType != 0) != (objType != 0) ) return false;
  892. if( this->inOutFlags != paramInOut ) return false;
  893. if( this->parameterTypes != paramTypes ) return false;
  894. return true;
  895. }
  896. // internal
  897. void asCScriptFunction::AddReferences()
  898. {
  899. // This array will be used to make sure we only add the reference to the same resource once
  900. // This is especially important for global variables, as it expects the initialization function
  901. // to hold only one reference to the variable. However, if the variable is initialized through
  902. // the default constructor followed by the assignment operator we will have two references to
  903. // the variable in the function.
  904. asCArray<void*> ptrs;
  905. // Only count references if there is any bytecode
  906. if( scriptData && scriptData->byteCode.GetLength() )
  907. {
  908. if( returnType.GetTypeInfo() )
  909. {
  910. returnType.GetTypeInfo()->AddRefInternal();
  911. asCConfigGroup *group = engine->FindConfigGroupForTypeInfo(returnType.GetTypeInfo());
  912. if( group != 0 ) group->AddRef();
  913. }
  914. for( asUINT p = 0; p < parameterTypes.GetLength(); p++ )
  915. if( parameterTypes[p].GetTypeInfo() )
  916. {
  917. parameterTypes[p].GetTypeInfo()->AddRefInternal();
  918. asCConfigGroup *group = engine->FindConfigGroupForTypeInfo(parameterTypes[p].GetTypeInfo());
  919. if( group != 0 ) group->AddRef();
  920. }
  921. for( asUINT v = 0; v < scriptData->objVariableTypes.GetLength(); v++ )
  922. if( scriptData->objVariableTypes[v] ) // The null handle is also stored, but it doesn't have an object type
  923. {
  924. scriptData->objVariableTypes[v]->AddRefInternal();
  925. asCConfigGroup *group = engine->FindConfigGroupForTypeInfo(scriptData->objVariableTypes[v]);
  926. if( group != 0 ) group->AddRef();
  927. }
  928. // Go through the byte code and add references to all resources used by the function
  929. asCArray<asDWORD> &bc = scriptData->byteCode;
  930. for( asUINT n = 0; n < bc.GetLength(); n += asBCTypeSize[asBCInfo[*(asBYTE*)&bc[n]].type] )
  931. {
  932. switch( *(asBYTE*)&bc[n] )
  933. {
  934. // Object types
  935. case asBC_OBJTYPE:
  936. case asBC_FREE:
  937. case asBC_REFCPY:
  938. case asBC_RefCpyV:
  939. {
  940. asCObjectType *objType = (asCObjectType*)asBC_PTRARG(&bc[n]);
  941. asASSERT( objType );
  942. if( objType )
  943. objType->AddRefInternal();
  944. }
  945. break;
  946. // Object type and function
  947. case asBC_ALLOC:
  948. {
  949. asCObjectType *objType = (asCObjectType*)asBC_PTRARG(&bc[n]);
  950. asASSERT( objType );
  951. if( objType )
  952. objType->AddRefInternal();
  953. int funcId = asBC_INTARG(&bc[n]+AS_PTR_SIZE);
  954. if( funcId )
  955. engine->scriptFunctions[funcId]->AddRefInternal();
  956. }
  957. break;
  958. // Global variables
  959. case asBC_PGA:
  960. case asBC_PshGPtr:
  961. case asBC_LDG:
  962. case asBC_PshG4:
  963. case asBC_LdGRdR4:
  964. case asBC_CpyGtoV4:
  965. case asBC_CpyVtoG4:
  966. case asBC_SetG4:
  967. // Need to increase the reference for each global variable
  968. {
  969. void *gvarPtr = (void*)asBC_PTRARG(&bc[n]);
  970. if( !gvarPtr ) break;
  971. asCGlobalProperty *prop = GetPropertyByGlobalVarPtr(gvarPtr);
  972. if (!prop)
  973. {
  974. // The pointer is a string constant. In order to make sure the correct resource
  975. // management is maintained we request a new string constant here, so the compiler
  976. // or bytecode loader can release its copy afterwards.
  977. asCString str;
  978. asUINT length;
  979. int r = engine->stringFactory->GetRawStringData(gvarPtr, 0, &length);
  980. if (r >= 0)
  981. {
  982. str.SetLength(length);
  983. engine->stringFactory->GetRawStringData(gvarPtr, str.AddressOf(), &length);
  984. // Get a new pointer (depending on the string factory implementation it may actually be the same)
  985. gvarPtr = const_cast<void*>(engine->stringFactory->GetStringConstant(str.AddressOf(), length));
  986. asBC_PTRARG(&bc[n]) = (asPWORD)gvarPtr;
  987. }
  988. // If we get an error from the string factory there is not
  989. // anything we can do about it, except report a message.
  990. // TODO: NEWSTRING: Write a message and then exit gracefully
  991. asASSERT(r >= 0);
  992. break;
  993. }
  994. // Only addref the properties once
  995. if( !ptrs.Exists(gvarPtr) )
  996. {
  997. prop->AddRef();
  998. ptrs.PushLast(gvarPtr);
  999. }
  1000. asCConfigGroup *group = engine->FindConfigGroupForGlobalVar(prop->id);
  1001. if( group != 0 ) group->AddRef();
  1002. }
  1003. break;
  1004. // System functions
  1005. case asBC_CALLSYS:
  1006. {
  1007. int funcId = asBC_INTARG(&bc[n]);
  1008. asCConfigGroup *group = engine->FindConfigGroupForFunction(funcId);
  1009. if( group != 0 ) group->AddRef();
  1010. asASSERT( funcId > 0 );
  1011. if( funcId > 0 )
  1012. engine->scriptFunctions[funcId]->AddRefInternal();
  1013. }
  1014. break;
  1015. // Functions
  1016. case asBC_CALL:
  1017. case asBC_CALLINTF:
  1018. {
  1019. int funcId = asBC_INTARG(&bc[n]);
  1020. asASSERT( funcId > 0 );
  1021. if( funcId > 0 )
  1022. engine->scriptFunctions[funcId]->AddRefInternal();
  1023. }
  1024. break;
  1025. // Function pointers
  1026. case asBC_FuncPtr:
  1027. {
  1028. asCScriptFunction *func = (asCScriptFunction*)asBC_PTRARG(&bc[n]);
  1029. asASSERT( func );
  1030. if( func )
  1031. func->AddRefInternal();
  1032. }
  1033. break;
  1034. }
  1035. }
  1036. }
  1037. }
  1038. // internal
  1039. void asCScriptFunction::ReleaseReferences()
  1040. {
  1041. asCArray<void*> ptrs;
  1042. // Only count references if there is any bytecode
  1043. if( scriptData && scriptData->byteCode.GetLength() )
  1044. {
  1045. if( returnType.GetTypeInfo() )
  1046. {
  1047. returnType.GetTypeInfo()->ReleaseInternal();
  1048. asCConfigGroup *group = engine->FindConfigGroupForTypeInfo(returnType.GetTypeInfo());
  1049. if( group != 0 ) group->Release();
  1050. }
  1051. for( asUINT p = 0; p < parameterTypes.GetLength(); p++ )
  1052. if( parameterTypes[p].GetTypeInfo() )
  1053. {
  1054. parameterTypes[p].GetTypeInfo()->ReleaseInternal();
  1055. asCConfigGroup *group = engine->FindConfigGroupForTypeInfo(parameterTypes[p].GetTypeInfo());
  1056. if( group != 0 ) group->Release();
  1057. }
  1058. for( asUINT v = 0; v < scriptData->objVariableTypes.GetLength(); v++ )
  1059. if( scriptData->objVariableTypes[v] ) // The null handle is also stored, but it doesn't have an object type
  1060. {
  1061. scriptData->objVariableTypes[v]->ReleaseInternal();
  1062. asCConfigGroup *group = engine->FindConfigGroupForTypeInfo(scriptData->objVariableTypes[v]);
  1063. if( group != 0 ) group->Release();
  1064. }
  1065. // Go through the byte code and release references to all resources used by the function
  1066. asCArray<asDWORD> &bc = scriptData->byteCode;
  1067. for( asUINT n = 0; n < bc.GetLength(); n += asBCTypeSize[asBCInfo[*(asBYTE*)&bc[n]].type] )
  1068. {
  1069. switch( *(asBYTE*)&bc[n] )
  1070. {
  1071. // Object types
  1072. case asBC_OBJTYPE:
  1073. case asBC_FREE:
  1074. case asBC_REFCPY:
  1075. case asBC_RefCpyV:
  1076. {
  1077. asCObjectType *objType = (asCObjectType*)asBC_PTRARG(&bc[n]);
  1078. if( objType )
  1079. objType->ReleaseInternal();
  1080. }
  1081. break;
  1082. // Object type and function
  1083. case asBC_ALLOC:
  1084. {
  1085. asCObjectType *objType = (asCObjectType*)asBC_PTRARG(&bc[n]);
  1086. if( objType )
  1087. objType->ReleaseInternal();
  1088. int funcId = asBC_INTARG(&bc[n]+AS_PTR_SIZE);
  1089. if( funcId > 0 )
  1090. {
  1091. asCScriptFunction *fptr = engine->scriptFunctions[funcId];
  1092. if( fptr )
  1093. fptr->ReleaseInternal();
  1094. // The engine may have been forced to destroy the function internals early
  1095. // and this may will make it impossible to find the function by id anymore.
  1096. // This should only happen if the engine is released while the application
  1097. // is still keeping functions alive.
  1098. // TODO: Fix this possible memory leak
  1099. }
  1100. }
  1101. break;
  1102. // Global variables
  1103. case asBC_PGA:
  1104. case asBC_PshGPtr:
  1105. case asBC_LDG:
  1106. case asBC_PshG4:
  1107. case asBC_LdGRdR4:
  1108. case asBC_CpyGtoV4:
  1109. case asBC_CpyVtoG4:
  1110. case asBC_SetG4:
  1111. // Need to increase the reference for each global variable
  1112. {
  1113. void *gvarPtr = (void*)asBC_PTRARG(&bc[n]);
  1114. if( !gvarPtr ) break;
  1115. asCGlobalProperty *prop = GetPropertyByGlobalVarPtr(gvarPtr);
  1116. if (!prop)
  1117. {
  1118. // The pointer is a string constant, so it needs to be released by the string factory
  1119. int r = engine->stringFactory->ReleaseStringConstant(gvarPtr);
  1120. UNUSED_VAR(r);
  1121. // If we get an error from the string factory there is not
  1122. // anything we can do about it, except report a message.
  1123. // TODO: Write a message showing that the string couldn't be
  1124. // released. Include the first 10 characters and the length
  1125. // to make it easier to identify which string it was
  1126. asASSERT(r >= 0);
  1127. break;
  1128. }
  1129. // Only release the properties once
  1130. if( !ptrs.Exists(gvarPtr) )
  1131. {
  1132. prop->Release();
  1133. ptrs.PushLast(gvarPtr);
  1134. }
  1135. asCConfigGroup *group = engine->FindConfigGroupForGlobalVar(prop->id);
  1136. if( group != 0 ) group->Release();
  1137. }
  1138. break;
  1139. // System functions
  1140. case asBC_CALLSYS:
  1141. {
  1142. int funcId = asBC_INTARG(&bc[n]);
  1143. asCConfigGroup *group = engine->FindConfigGroupForFunction(funcId);
  1144. if( group != 0 ) group->Release();
  1145. if( funcId )
  1146. {
  1147. asCScriptFunction *fptr = engine->scriptFunctions[funcId];
  1148. if( fptr )
  1149. fptr->ReleaseInternal();
  1150. }
  1151. }
  1152. break;
  1153. // Functions
  1154. case asBC_CALL:
  1155. case asBC_CALLINTF:
  1156. {
  1157. int funcId = asBC_INTARG(&bc[n]);
  1158. if( funcId )
  1159. {
  1160. asCScriptFunction *fptr = engine->scriptFunctions[funcId];
  1161. if( fptr )
  1162. fptr->ReleaseInternal();
  1163. // The engine may have been forced to destroy the function internals early
  1164. // and this may will make it impossible to find the function by id anymore.
  1165. // This should only happen if the engine is released while the application
  1166. // is still keeping functions alive.
  1167. // TODO: Fix this possible memory leak
  1168. }
  1169. }
  1170. break;
  1171. // Function pointers
  1172. case asBC_FuncPtr:
  1173. {
  1174. asCScriptFunction *func = (asCScriptFunction*)asBC_PTRARG(&bc[n]);
  1175. if( func )
  1176. func->ReleaseInternal();
  1177. }
  1178. break;
  1179. }
  1180. }
  1181. // Release the jit compiled function
  1182. if( scriptData->jitFunction )
  1183. engine->jitCompiler->ReleaseJITFunction(scriptData->jitFunction);
  1184. scriptData->jitFunction = 0;
  1185. }
  1186. // Delegate
  1187. if( objForDelegate )
  1188. engine->ReleaseScriptObject(objForDelegate, funcForDelegate->GetObjectType());
  1189. objForDelegate = 0;
  1190. if( funcForDelegate )
  1191. funcForDelegate->Release();
  1192. funcForDelegate = 0;
  1193. }
  1194. // interface
  1195. int asCScriptFunction::GetReturnTypeId(asDWORD *flags) const
  1196. {
  1197. if( flags )
  1198. {
  1199. if( returnType.IsReference() )
  1200. {
  1201. *flags = asTM_INOUTREF;
  1202. *flags |= returnType.IsReadOnly() ? asTM_CONST : 0;
  1203. }
  1204. else
  1205. *flags = asTM_NONE;
  1206. }
  1207. return engine->GetTypeIdFromDataType(returnType);
  1208. }
  1209. // interface
  1210. asUINT asCScriptFunction::GetParamCount() const
  1211. {
  1212. return (asUINT)parameterTypes.GetLength();
  1213. }
  1214. // interface
  1215. int asCScriptFunction::GetParam(asUINT index, int *out_typeId, asDWORD *out_flags, const char **out_name, const char **out_defaultArg) const
  1216. {
  1217. if( index >= parameterTypes.GetLength() )
  1218. return asINVALID_ARG;
  1219. if( out_typeId )
  1220. *out_typeId = engine->GetTypeIdFromDataType(parameterTypes[index]);
  1221. if( out_flags )
  1222. {
  1223. *out_flags = inOutFlags[index];
  1224. *out_flags |= parameterTypes[index].IsReadOnly() ? asTM_CONST : 0;
  1225. }
  1226. if( out_name )
  1227. {
  1228. // The parameter names are not stored if loading from bytecode without debug information
  1229. if( index < parameterNames.GetLength() )
  1230. *out_name = parameterNames[index].AddressOf();
  1231. else
  1232. *out_name = 0;
  1233. }
  1234. if( out_defaultArg )
  1235. {
  1236. if( index < defaultArgs.GetLength() && defaultArgs[index] )
  1237. *out_defaultArg = defaultArgs[index]->AddressOf();
  1238. else
  1239. *out_defaultArg = 0;
  1240. }
  1241. return asSUCCESS;
  1242. }
  1243. // interface
  1244. asIScriptEngine *asCScriptFunction::GetEngine() const
  1245. {
  1246. return engine;
  1247. }
  1248. // interface
  1249. const char *asCScriptFunction::GetDeclaration(bool includeObjectName, bool includeNamespace, bool includeParamNames) const
  1250. {
  1251. asCString *tempString = &asCThreadManager::GetLocalData()->string;
  1252. *tempString = GetDeclarationStr(includeObjectName, includeNamespace, includeParamNames);
  1253. return tempString->AddressOf();
  1254. }
  1255. // interface
  1256. const char *asCScriptFunction::GetScriptSectionName() const
  1257. {
  1258. if( scriptData && scriptData->scriptSectionIdx >= 0 )
  1259. return engine->scriptSectionNames[scriptData->scriptSectionIdx]->AddressOf();
  1260. return 0;
  1261. }
  1262. // interface
  1263. const char *asCScriptFunction::GetConfigGroup() const
  1264. {
  1265. asCConfigGroup *group = 0;
  1266. if( funcType != asFUNC_FUNCDEF )
  1267. group = engine->FindConfigGroupForFunction(id);
  1268. else
  1269. group = engine->FindConfigGroupForFuncDef(this->funcdefType);
  1270. if( group == 0 )
  1271. return 0;
  1272. return group->groupName.AddressOf();
  1273. }
  1274. // interface
  1275. asDWORD asCScriptFunction::GetAccessMask() const
  1276. {
  1277. return accessMask;
  1278. }
  1279. // internal
  1280. void asCScriptFunction::JITCompile()
  1281. {
  1282. if( funcType != asFUNC_SCRIPT )
  1283. return;
  1284. asASSERT( scriptData );
  1285. asIJITCompiler *jit = engine->GetJITCompiler();
  1286. if( !jit )
  1287. return;
  1288. // Make sure the function has been compiled with JitEntry instructions
  1289. // For functions that has JitEntry this will be a quick test
  1290. asUINT length;
  1291. asDWORD *byteCode = GetByteCode(&length);
  1292. asDWORD *end = byteCode + length;
  1293. bool foundJitEntry = false;
  1294. while( byteCode < end )
  1295. {
  1296. // Determine the instruction
  1297. asEBCInstr op = asEBCInstr(*(asBYTE*)byteCode);
  1298. if( op == asBC_JitEntry )
  1299. {
  1300. foundJitEntry = true;
  1301. break;
  1302. }
  1303. // Move to next instruction
  1304. byteCode += asBCTypeSize[asBCInfo[op].type];
  1305. }
  1306. if( !foundJitEntry )
  1307. {
  1308. asCString msg;
  1309. msg.Format(TXT_NO_JIT_IN_FUNC_s, GetDeclaration());
  1310. engine->WriteMessage("", 0, 0, asMSGTYPE_WARNING, msg.AddressOf());
  1311. }
  1312. // Release the previous function, if any
  1313. if( scriptData->jitFunction )
  1314. {
  1315. engine->jitCompiler->ReleaseJITFunction(scriptData->jitFunction);
  1316. scriptData->jitFunction = 0;
  1317. }
  1318. // Compile for native system
  1319. int r = jit->CompileFunction(this, &scriptData->jitFunction);
  1320. if( r < 0 )
  1321. asASSERT( scriptData->jitFunction == 0 );
  1322. }
  1323. // interface
  1324. asDWORD *asCScriptFunction::GetByteCode(asUINT *length)
  1325. {
  1326. if( scriptData == 0 ) return 0;
  1327. if( length )
  1328. *length = (asUINT)scriptData->byteCode.GetLength();
  1329. if( scriptData->byteCode.GetLength() )
  1330. return scriptData->byteCode.AddressOf();
  1331. return 0;
  1332. }
  1333. // interface
  1334. void *asCScriptFunction::SetUserData(void *data, asPWORD type)
  1335. {
  1336. // As a thread might add a new new user data at the same time as another
  1337. // it is necessary to protect both read and write access to the userData member
  1338. ACQUIREEXCLUSIVE(engine->engineRWLock);
  1339. // It is not intended to store a lot of different types of userdata,
  1340. // so a more complex structure like a associative map would just have
  1341. // more overhead than a simple array.
  1342. for( asUINT n = 0; n < userData.GetLength(); n += 2 )
  1343. {
  1344. if( userData[n] == type )
  1345. {
  1346. void *oldData = reinterpret_cast<void*>(userData[n+1]);
  1347. userData[n+1] = reinterpret_cast<asPWORD>(data);
  1348. RELEASEEXCLUSIVE(engine->engineRWLock);
  1349. return oldData;
  1350. }
  1351. }
  1352. userData.PushLast(type);
  1353. userData.PushLast(reinterpret_cast<asPWORD>(data));
  1354. RELEASEEXCLUSIVE(engine->engineRWLock);
  1355. return 0;
  1356. }
  1357. // interface
  1358. void *asCScriptFunction::GetUserData(asPWORD type) const
  1359. {
  1360. // There may be multiple threads reading, but when
  1361. // setting the user data nobody must be reading.
  1362. ACQUIRESHARED(engine->engineRWLock);
  1363. for( asUINT n = 0; n < userData.GetLength(); n += 2 )
  1364. {
  1365. if( userData[n] == type )
  1366. {
  1367. RELEASESHARED(engine->engineRWLock);
  1368. return reinterpret_cast<void*>(userData[n+1]);
  1369. }
  1370. }
  1371. RELEASESHARED(engine->engineRWLock);
  1372. return 0;
  1373. }
  1374. // internal
  1375. // TODO: cleanup: This method should probably be a member of the engine
  1376. asCGlobalProperty *asCScriptFunction::GetPropertyByGlobalVarPtr(void *gvarPtr)
  1377. {
  1378. asSMapNode<void*, asCGlobalProperty*> *node;
  1379. if( engine->varAddressMap.MoveTo(&node, gvarPtr) )
  1380. {
  1381. asASSERT(gvarPtr == node->value->GetAddressOfValue());
  1382. return node->value;
  1383. }
  1384. return 0;
  1385. }
  1386. // internal
  1387. int asCScriptFunction::GetRefCount()
  1388. {
  1389. asASSERT( funcType == asFUNC_DELEGATE );
  1390. return externalRefCount.get();
  1391. }
  1392. // internal
  1393. void asCScriptFunction::SetFlag()
  1394. {
  1395. gcFlag = true;
  1396. }
  1397. // internal
  1398. bool asCScriptFunction::GetFlag()
  1399. {
  1400. return gcFlag;
  1401. }
  1402. // internal
  1403. void asCScriptFunction::EnumReferences(asIScriptEngine *)
  1404. {
  1405. asASSERT( funcType == asFUNC_DELEGATE );
  1406. // Delegate
  1407. if( objForDelegate )
  1408. engine->GCEnumCallback(objForDelegate);
  1409. }
  1410. // internal
  1411. void asCScriptFunction::ReleaseAllHandles(asIScriptEngine *)
  1412. {
  1413. asASSERT( funcType == asFUNC_DELEGATE );
  1414. // Release paramaters
  1415. // Delegate
  1416. if( objForDelegate )
  1417. engine->ReleaseScriptObject(objForDelegate, funcForDelegate->GetObjectType());
  1418. objForDelegate = 0;
  1419. }
  1420. // interface
  1421. bool asCScriptFunction::IsShared() const
  1422. {
  1423. // All system functions are shared
  1424. if( funcType == asFUNC_SYSTEM ) return true;
  1425. // All class methods for shared classes are also shared
  1426. asASSERT( objectType == 0 || objectType->engine == engine || objectType->engine == 0 );
  1427. if( objectType && (objectType->flags & asOBJ_SHARED) ) return true;
  1428. // funcdefs that are registered by the application are shared
  1429. if (funcType == asFUNC_FUNCDEF && module == 0) return true;
  1430. // Functions that have been specifically marked as shared are shared
  1431. return traits.GetTrait(asTRAIT_SHARED);
  1432. }
  1433. // interface
  1434. bool asCScriptFunction::IsFinal() const
  1435. {
  1436. return traits.GetTrait(asTRAIT_FINAL);
  1437. }
  1438. // interface
  1439. bool asCScriptFunction::IsOverride() const
  1440. {
  1441. return traits.GetTrait(asTRAIT_OVERRIDE);
  1442. }
  1443. // interface
  1444. bool asCScriptFunction::IsExplicit() const
  1445. {
  1446. return traits.GetTrait(asTRAIT_EXPLICIT);
  1447. }
  1448. // interface
  1449. bool asCScriptFunction::IsProperty() const
  1450. {
  1451. return traits.GetTrait(asTRAIT_PROPERTY);
  1452. }
  1453. END_AS_NAMESPACE