as_scriptengine.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2014 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_scriptengine.h
  25. //
  26. // The implementation of the script engine interface
  27. //
  28. #ifndef AS_SCRIPTENGINE_H
  29. #define AS_SCRIPTENGINE_H
  30. #include "as_config.h"
  31. #include "as_atomic.h"
  32. #include "as_scriptfunction.h"
  33. #include "as_array.h"
  34. #include "as_datatype.h"
  35. #include "as_objecttype.h"
  36. #include "as_module.h"
  37. #include "as_callfunc.h"
  38. #include "as_configgroup.h"
  39. #include "as_memory.h"
  40. #include "as_gc.h"
  41. #include "as_tokenizer.h"
  42. BEGIN_AS_NAMESPACE
  43. class asCBuilder;
  44. class asCContext;
  45. // TODO: import: Remove this when import is removed
  46. struct sBindInfo;
  47. class asCScriptEngine : public asIScriptEngine
  48. {
  49. //=============================================================
  50. // From asIScriptEngine
  51. //=============================================================
  52. public:
  53. // Memory management
  54. virtual int AddRef() const;
  55. virtual int Release() const;
  56. // Engine properties
  57. virtual int SetEngineProperty(asEEngineProp property, asPWORD value);
  58. virtual asPWORD GetEngineProperty(asEEngineProp property) const;
  59. // Compiler messages
  60. virtual int SetMessageCallback(const asSFuncPtr &callback, void *obj, asDWORD callConv);
  61. virtual int ClearMessageCallback();
  62. virtual int WriteMessage(const char *section, int row, int col, asEMsgType type, const char *message);
  63. // JIT Compiler
  64. virtual int SetJITCompiler(asIJITCompiler *compiler);
  65. virtual asIJITCompiler *GetJITCompiler() const;
  66. // Global functions
  67. virtual int RegisterGlobalFunction(const char *declaration, const asSFuncPtr &funcPointer, asDWORD callConv, void *objForThiscall = 0);
  68. virtual asUINT GetGlobalFunctionCount() const;
  69. virtual asIScriptFunction *GetGlobalFunctionByIndex(asUINT index) const;
  70. virtual asIScriptFunction *GetGlobalFunctionByDecl(const char *declaration) const;
  71. // Global properties
  72. virtual int RegisterGlobalProperty(const char *declaration, void *pointer);
  73. virtual asUINT GetGlobalPropertyCount() const;
  74. virtual int GetGlobalPropertyByIndex(asUINT index, const char **name, const char **nameSpace = 0, int *typeId = 0, bool *isConst = 0, const char **configGroup = 0, void **pointer = 0, asDWORD *accessMask = 0) const;
  75. virtual int GetGlobalPropertyIndexByName(const char *name) const;
  76. virtual int GetGlobalPropertyIndexByDecl(const char *decl) const;
  77. // Type registration
  78. virtual int RegisterObjectType(const char *obj, int byteSize, asDWORD flags);
  79. virtual int RegisterObjectProperty(const char *obj, const char *declaration, int byteOffset);
  80. virtual int RegisterObjectMethod(const char *obj, const char *declaration, const asSFuncPtr &funcPointer, asDWORD callConv, void *objForThiscall = 0);
  81. virtual int RegisterObjectBehaviour(const char *obj, asEBehaviours behaviour, const char *declaration, const asSFuncPtr &funcPointer, asDWORD callConv, void *objForThiscall = 0);
  82. virtual int RegisterInterface(const char *name);
  83. virtual int RegisterInterfaceMethod(const char *intf, const char *declaration);
  84. virtual asUINT GetObjectTypeCount() const;
  85. virtual asIObjectType *GetObjectTypeByIndex(asUINT index) const;
  86. virtual asIObjectType *GetObjectTypeByName(const char *name) const;
  87. virtual asIObjectType *GetObjectTypeByDecl(const char *decl) const;
  88. // String factory
  89. virtual int RegisterStringFactory(const char *datatype, const asSFuncPtr &factoryFunc, asDWORD callConv, void *objForThiscall = 0);
  90. virtual int GetStringFactoryReturnTypeId(asDWORD *flags) const;
  91. // Default array type
  92. virtual int RegisterDefaultArrayType(const char *type);
  93. virtual int GetDefaultArrayTypeId() const;
  94. // Enums
  95. virtual int RegisterEnum(const char *type);
  96. virtual int RegisterEnumValue(const char *type, const char *name, int value);
  97. virtual asUINT GetEnumCount() const;
  98. virtual const char *GetEnumByIndex(asUINT index, int *enumTypeId, const char **nameSpace, const char **configGroup = 0, asDWORD *accessMask = 0) const;
  99. virtual int GetEnumValueCount(int enumTypeId) const;
  100. virtual const char *GetEnumValueByIndex(int enumTypeId, asUINT index, int *outValue) const;
  101. // Funcdefs
  102. virtual int RegisterFuncdef(const char *decl);
  103. virtual asUINT GetFuncdefCount() const;
  104. virtual asIScriptFunction *GetFuncdefByIndex(asUINT index) const;
  105. // Typedefs
  106. // TODO: interface: Should perhaps rename this to Alias, since it doesn't really create a new type
  107. virtual int RegisterTypedef(const char *type, const char *decl);
  108. virtual asUINT GetTypedefCount() const;
  109. virtual const char *GetTypedefByIndex(asUINT index, int *typeId, const char **nameSpace, const char **configGroup = 0, asDWORD *accessMask = 0) const;
  110. // Configuration groups
  111. virtual int BeginConfigGroup(const char *groupName);
  112. virtual int EndConfigGroup();
  113. virtual int RemoveConfigGroup(const char *groupName);
  114. virtual asDWORD SetDefaultAccessMask(asDWORD defaultMask);
  115. virtual int SetDefaultNamespace(const char *nameSpace);
  116. virtual const char *GetDefaultNamespace() const;
  117. // Script modules
  118. virtual asIScriptModule *GetModule(const char *module, asEGMFlags flag);
  119. virtual int DiscardModule(const char *module);
  120. virtual asUINT GetModuleCount() const;
  121. virtual asIScriptModule *GetModuleByIndex(asUINT index) const;
  122. // Script functions
  123. virtual asIScriptFunction *GetFunctionById(int funcId) const;
  124. virtual asIScriptFunction *GetFuncDefFromTypeId(int typeId) const;
  125. // Type identification
  126. virtual asIObjectType *GetObjectTypeById(int typeId) const;
  127. virtual int GetTypeIdByDecl(const char *decl) const;
  128. virtual const char *GetTypeDeclaration(int typeId, bool includeNamespace = false) const;
  129. virtual int GetSizeOfPrimitiveType(int typeId) const;
  130. // Script execution
  131. virtual asIScriptContext *CreateContext();
  132. virtual void *CreateScriptObject(const asIObjectType *type);
  133. virtual void *CreateScriptObjectCopy(void *obj, const asIObjectType *type);
  134. virtual void *CreateUninitializedScriptObject(const asIObjectType *type);
  135. virtual asIScriptFunction *CreateDelegate(asIScriptFunction *func, void *obj);
  136. virtual void AssignScriptObject(void *dstObj, void *srcObj, const asIObjectType *type);
  137. virtual void ReleaseScriptObject(void *obj, const asIObjectType *type);
  138. virtual void AddRefScriptObject(void *obj, const asIObjectType *type);
  139. // TODO: interface: Should have a method void *CastObject(void *obj, asIObjectType *fromType, asIObjectType *toType);
  140. // For script objects it should simply check if the object implements or derives from the toType
  141. // For application objects it should look for ref cast behaviours and call the matching one
  142. // Once implemented the IsHandleCompatibleWithObject should be removed from the engine
  143. virtual bool IsHandleCompatibleWithObject(void *obj, int objTypeId, int handleTypeId) const;
  144. virtual asILockableSharedBool *GetWeakRefFlagOfScriptObject(void *obj, const asIObjectType *type) const;
  145. // Context pooling
  146. virtual asIScriptContext *RequestContext();
  147. virtual void ReturnContext(asIScriptContext *ctx);
  148. virtual int SetContextCallbacks(asREQUESTCONTEXTFUNC_t requestCtx, asRETURNCONTEXTFUNC_t returnCtx, void *param = 0);
  149. // String interpretation
  150. virtual asETokenClass ParseToken(const char *string, size_t stringLength = 0, int *tokenLength = 0) const;
  151. // Garbage collection
  152. virtual int GarbageCollect(asDWORD flags = asGC_FULL_CYCLE, asUINT numIterations = 1);
  153. virtual void GetGCStatistics(asUINT *currentSize, asUINT *totalDestroyed, asUINT *totalDetected, asUINT *newObjects, asUINT *totalNewDestroyed) const;
  154. virtual int NotifyGarbageCollectorOfNewObject(void *obj, asIObjectType *type);
  155. virtual int GetObjectInGC(asUINT idx, asUINT *seqNbr, void **obj = 0, asIObjectType **type = 0);
  156. virtual void GCEnumCallback(void *reference);
  157. // User data
  158. virtual void *SetUserData(void *data, asPWORD type);
  159. virtual void *GetUserData(asPWORD type) const;
  160. virtual void SetEngineUserDataCleanupCallback(asCLEANENGINEFUNC_t callback, asPWORD type);
  161. virtual void SetModuleUserDataCleanupCallback(asCLEANMODULEFUNC_t callback, asPWORD type);
  162. virtual void SetContextUserDataCleanupCallback(asCLEANCONTEXTFUNC_t callback, asPWORD type);
  163. virtual void SetFunctionUserDataCleanupCallback(asCLEANFUNCTIONFUNC_t callback, asPWORD type);
  164. virtual void SetObjectTypeUserDataCleanupCallback(asCLEANOBJECTTYPEFUNC_t callback, asPWORD type);
  165. //===========================================================
  166. // internal methods
  167. //===========================================================
  168. public:
  169. asCScriptEngine();
  170. virtual ~asCScriptEngine();
  171. //protected:
  172. friend class asCBuilder;
  173. friend class asCCompiler;
  174. friend class asCContext;
  175. friend class asCDataType;
  176. friend class asCModule;
  177. friend class asCRestore;
  178. friend class asCByteCode;
  179. friend int PrepareSystemFunction(asCScriptFunction *func, asSSystemFunctionInterface *internal, asCScriptEngine *engine);
  180. int RegisterMethodToObjectType(asCObjectType *objectType, const char *declaration, const asSFuncPtr &funcPointer, asDWORD callConv, void *objForThiscall = 0);
  181. int RegisterBehaviourToObjectType(asCObjectType *objectType, asEBehaviours behaviour, const char *decl, const asSFuncPtr &funcPointer, asDWORD callConv, void *objForThiscall);
  182. int VerifyVarTypeNotInFunction(asCScriptFunction *func);
  183. void *CallAlloc(const asCObjectType *objType) const;
  184. void CallFree(void *obj) const;
  185. void *CallGlobalFunctionRetPtr(int func) const;
  186. void *CallGlobalFunctionRetPtr(int func, void *param1) const;
  187. void *CallGlobalFunctionRetPtr(asSSystemFunctionInterface *func, asCScriptFunction *desc) const;
  188. void *CallGlobalFunctionRetPtr(asSSystemFunctionInterface *i, asCScriptFunction *s, void *param1) const;
  189. void CallObjectMethod(void *obj, int func) const;
  190. void CallObjectMethod(void *obj, void *param, int func) const;
  191. void CallObjectMethod(void *obj, asSSystemFunctionInterface *func, asCScriptFunction *desc) const;
  192. void CallObjectMethod(void *obj, void *param, asSSystemFunctionInterface *func, asCScriptFunction *desc) const;
  193. bool CallObjectMethodRetBool(void *obj, int func) const;
  194. int CallObjectMethodRetInt(void *obj, int func) const;
  195. void *CallObjectMethodRetPtr(void *obj, int func) const;
  196. void CallGlobalFunction(void *param1, void *param2, asSSystemFunctionInterface *func, asCScriptFunction *desc) const;
  197. bool CallGlobalFunctionRetBool(void *param1, void *param2, asSSystemFunctionInterface *func, asCScriptFunction *desc) const;
  198. void ConstructScriptObjectCopy(void *mem, void *obj, asCObjectType *type);
  199. void CleanupAfterDiscardModule();
  200. int ClearUnusedTypes();
  201. void RemoveTemplateInstanceType(asCObjectType *t);
  202. void RemoveTypeAndRelatedFromList(asCArray<asCObjectType*> &types, asCObjectType *ot);
  203. asCConfigGroup *FindConfigGroupForFunction(int funcId) const;
  204. asCConfigGroup *FindConfigGroupForGlobalVar(int gvarId) const;
  205. asCConfigGroup *FindConfigGroupForObjectType(const asCObjectType *type) const;
  206. asCConfigGroup *FindConfigGroupForFuncDef(const asCScriptFunction *funcDef) const;
  207. int RequestBuild();
  208. void BuildCompleted();
  209. void PrepareEngine();
  210. bool isPrepared;
  211. int CreateContext(asIScriptContext **context, bool isInternal);
  212. asCObjectType *GetRegisteredObjectType(const asCString &name, asSNameSpace *ns) const;
  213. asCObjectType *GetListPatternType(int listPatternFuncId);
  214. void DestroyList(asBYTE *buffer, const asCObjectType *listPatternType);
  215. void DestroySubList(asBYTE *&buffer, asSListPatternNode *&patternNode);
  216. int AddBehaviourFunction(asCScriptFunction &func, asSSystemFunctionInterface &internal);
  217. asCString GetFunctionDeclaration(int funcId);
  218. asCScriptFunction *GetScriptFunction(int funcId) const;
  219. asCModule *GetModule(const char *name, bool create);
  220. asCModule *GetModuleFromFuncId(int funcId);
  221. int GetMethodIdByDecl(const asCObjectType *ot, const char *decl, asCModule *mod);
  222. int GetFactoryIdByDecl(const asCObjectType *ot, const char *decl);
  223. int GetNextScriptFunctionId();
  224. void SetScriptFunction(asCScriptFunction *func);
  225. void FreeScriptFunctionId(int id);
  226. int ConfigError(int err, const char *funcName, const char *arg1, const char *arg2);
  227. int GetTypeIdFromDataType(const asCDataType &dt) const;
  228. asCDataType GetDataTypeFromTypeId(int typeId) const;
  229. asCObjectType *GetObjectTypeFromTypeId(int typeId) const;
  230. void RemoveFromTypeIdMap(asCObjectType *type);
  231. bool IsTemplateType(const char *name) const;
  232. asCObjectType *GetTemplateInstanceType(asCObjectType *templateType, asCArray<asCDataType> &subTypes);
  233. asCScriptFunction *GenerateTemplateFactoryStub(asCObjectType *templateType, asCObjectType *templateInstanceType, int origFactoryId);
  234. bool GenerateNewTemplateFunction(asCObjectType *templateType, asCObjectType *templateInstanceType, asCScriptFunction *templateFunc, asCScriptFunction **newFunc);
  235. void OrphanTemplateInstances(asCObjectType *subType);
  236. asCDataType DetermineTypeForTemplate(const asCDataType &orig, asCObjectType *tmpl, asCObjectType *ot);
  237. // String constants
  238. // TODO: Must free unused string constants, thus the ref count for each must be tracked
  239. int AddConstantString(const char *str, size_t length);
  240. const asCString &GetConstantString(int id);
  241. // Global property management
  242. asCGlobalProperty *AllocateGlobalProperty();
  243. void FreeUnusedGlobalProperties();
  244. int GetScriptSectionNameIndex(const char *name);
  245. // Namespace management
  246. asSNameSpace *AddNameSpace(const char *name);
  247. asSNameSpace *FindNameSpace(const char *name);
  248. //===========================================================
  249. // internal properties
  250. //===========================================================
  251. asCMemoryMgr memoryMgr;
  252. asUINT initialContextStackSize;
  253. asCObjectType *defaultArrayObjectType;
  254. asCObjectType scriptTypeBehaviours;
  255. asCObjectType functionBehaviours;
  256. asCObjectType objectTypeBehaviours;
  257. asCObjectType globalPropertyBehaviours;
  258. // Registered interface
  259. asCArray<asCObjectType *> registeredObjTypes;
  260. asCArray<asCObjectType *> registeredTypeDefs;
  261. asCArray<asCObjectType *> registeredEnums;
  262. asCSymbolTable<asCGlobalProperty> registeredGlobalProps; // TODO: memory savings: Since there can be only one property with the same name a simpler symbol table should be used
  263. asCSymbolTable<asCScriptFunction> registeredGlobalFuncs;
  264. asCArray<asCScriptFunction *> registeredFuncDefs;
  265. asCArray<asCObjectType *> registeredTemplateTypes;
  266. asCScriptFunction *stringFactory;
  267. bool configFailed;
  268. // Stores all registered types except funcdefs
  269. asCMap<asSNameSpaceNamePair, asCObjectType*> allRegisteredTypes;
  270. // Dummy types used to name the subtypes in the template objects
  271. asCArray<asCObjectType *> templateSubTypes;
  272. // Store information about template types
  273. // This list will contain all instances of templates, both registered specialized
  274. // types and those automacially instanciated from scripts
  275. asCArray<asCObjectType *> templateInstanceTypes;
  276. // Store information about list patterns
  277. asCArray<asCObjectType *> listPatternTypes;
  278. // Stores all global properties, both those registered by application, and those declared by scripts.
  279. // The id of a global property is the index in this array.
  280. asCArray<asCGlobalProperty *> globalProperties;
  281. // This map is used to quickly find a property by its memory address
  282. // It is used principally during building, cleanup, and garbage detection for script functions
  283. asCMap<void*, asCGlobalProperty*> varAddressMap;
  284. asCArray<int> freeGlobalPropertyIds;
  285. // Stores all functions, i.e. registered functions, script functions, class methods, behaviours, etc.
  286. asCArray<asCScriptFunction *> scriptFunctions;
  287. asCArray<int> freeScriptFunctionIds;
  288. asCArray<asCScriptFunction *> signatureIds;
  289. // An array with all module imported functions
  290. asCArray<sBindInfo *> importedFunctions;
  291. asCArray<int> freeImportedFunctionIdxs;
  292. // These resources must be protected for multiple accesses
  293. mutable asCAtomic refCount;
  294. asCArray<asCModule *> scriptModules;
  295. asCModule *lastModule;
  296. bool isBuilding;
  297. bool deferValidationOfTemplateTypes;
  298. // Tokenizer is instanciated once to share resources
  299. asCTokenizer tok;
  300. // Stores script declared object types
  301. asCArray<asCObjectType *> classTypes;
  302. // This array stores the template instances types that have been automatically generated from template types
  303. asCArray<asCObjectType *> generatedTemplateTypes;
  304. // Stores the funcdefs
  305. asCArray<asCScriptFunction *> funcDefs;
  306. // Stores the names of the script sections for debugging purposes
  307. asCArray<asCString *> scriptSectionNames;
  308. // Type identifiers
  309. mutable int typeIdSeqNbr;
  310. mutable asCMap<int, asCDataType*> mapTypeIdToDataType;
  311. // Garbage collector
  312. asCGarbageCollector gc;
  313. // Dynamic groups
  314. asCConfigGroup defaultGroup;
  315. asCArray<asCConfigGroup*> configGroups;
  316. asCConfigGroup *currentGroup;
  317. asDWORD defaultAccessMask;
  318. asSNameSpace *defaultNamespace;
  319. // Message callback
  320. bool msgCallback;
  321. asSSystemFunctionInterface msgCallbackFunc;
  322. void *msgCallbackObj;
  323. struct preMessage_t
  324. {
  325. preMessage_t() { isSet = false; }
  326. bool isSet;
  327. asCString message;
  328. asCString scriptname;
  329. int r;
  330. int c;
  331. } preMessage;
  332. // JIt compilation
  333. asIJITCompiler *jitCompiler;
  334. // Namespaces
  335. // These are shared between all entities and are
  336. // only deleted once the engine is destroyed
  337. asCArray<asSNameSpace*> nameSpaces;
  338. // String constants
  339. // These are shared between all scripts and are
  340. // only deleted once the engine is destroyed
  341. asCArray<asCString*> stringConstants;
  342. asCMap<asCStringPointer, int> stringToIdMap;
  343. // Callbacks for context pooling
  344. asREQUESTCONTEXTFUNC_t requestCtxFunc;
  345. asRETURNCONTEXTFUNC_t returnCtxFunc;
  346. void *ctxCallbackParam;
  347. // User data
  348. asCArray<asPWORD> userData;
  349. struct SEngineClean { asPWORD type; asCLEANENGINEFUNC_t cleanFunc; };
  350. asCArray<SEngineClean> cleanEngineFuncs;
  351. struct SModuleClean { asPWORD type; asCLEANMODULEFUNC_t cleanFunc; };
  352. asCArray<SModuleClean> cleanModuleFuncs;
  353. struct SContextClean { asPWORD type; asCLEANCONTEXTFUNC_t cleanFunc; };
  354. asCArray<SContextClean> cleanContextFuncs;
  355. struct SFunctionClean { asPWORD type; asCLEANFUNCTIONFUNC_t cleanFunc; };
  356. asCArray<SFunctionClean> cleanFunctionFuncs;
  357. struct SObjTypeClean { asPWORD type; asCLEANOBJECTTYPEFUNC_t cleanFunc; };
  358. asCArray<SObjTypeClean> cleanObjectTypeFuncs;
  359. // Synchronization for threads
  360. DECLAREREADWRITELOCK(mutable engineRWLock)
  361. // Engine properties
  362. struct
  363. {
  364. bool allowUnsafeReferences;
  365. bool optimizeByteCode;
  366. bool copyScriptSections;
  367. asUINT maximumContextStackSize;
  368. bool useCharacterLiterals;
  369. bool allowMultilineStrings;
  370. bool allowImplicitHandleTypes;
  371. bool buildWithoutLineCues;
  372. bool initGlobalVarsAfterBuild;
  373. bool requireEnumScope;
  374. int scanner;
  375. bool includeJitInstructions;
  376. int stringEncoding;
  377. int propertyAccessorMode;
  378. bool expandDefaultArrayToTemplate;
  379. bool autoGarbageCollect;
  380. bool disallowGlobalVars;
  381. bool alwaysImplDefaultConstruct;
  382. int compilerWarnings;
  383. bool disallowValueAssignForRefType;
  384. } ep;
  385. // This flag is to allow a quicker shutdown when releasing the engine
  386. bool shuttingDown;
  387. };
  388. END_AS_NAMESPACE
  389. #endif