as_scriptfunction.cpp 47 KB

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