as_scriptfunction.cpp 47 KB

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