Script.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Addons.h"
  24. #include "Context.h"
  25. #include "Log.h"
  26. #include "Profiler.h"
  27. #include "Scene.h"
  28. #include "Script.h"
  29. #include "ScriptFile.h"
  30. #include "ScriptInstance.h"
  31. #include <angelscript.h>
  32. #include "DebugNew.h"
  33. namespace Urho3D
  34. {
  35. /// %Object property info for scripting API dump.
  36. struct PropertyInfo
  37. {
  38. /// Construct.
  39. PropertyInfo() :
  40. read_(false),
  41. write_(false),
  42. indexed_(false)
  43. {
  44. }
  45. /// Property name.
  46. String name_;
  47. /// Property data type.
  48. String type_;
  49. /// Reading supported flag.
  50. bool read_;
  51. /// Writing supported flag.
  52. bool write_;
  53. /// Indexed flag.
  54. bool indexed_;
  55. };
  56. void ExtractPropertyInfo(const String& functionName, const String& declaration, Vector<PropertyInfo>& propertyInfos)
  57. {
  58. String propertyName = functionName.Substring(4);
  59. PropertyInfo* info = 0;
  60. for (unsigned k = 0; k < propertyInfos.Size(); ++k)
  61. {
  62. if (propertyInfos[k].name_ == propertyName)
  63. {
  64. info = &propertyInfos[k];
  65. break;
  66. }
  67. }
  68. if (!info)
  69. {
  70. propertyInfos.Resize(propertyInfos.Size() + 1);
  71. info = &propertyInfos.Back();
  72. info->name_ = propertyName;
  73. }
  74. if (functionName.Contains("get_"))
  75. {
  76. info->read_ = true;
  77. // Extract type from the return value
  78. Vector<String> parts = declaration.Split(' ');
  79. if (parts.Size())
  80. {
  81. if (parts[0] != "const")
  82. info->type_ = parts[0];
  83. else if (parts.Size() > 1)
  84. info->type_ = parts[1];
  85. }
  86. // If get method has parameters, it is indexed
  87. if (!declaration.Contains("()"))
  88. {
  89. info->indexed_ = true;
  90. info->type_ += "[]";
  91. }
  92. // Sanitate the reference operator away
  93. info->type_.Replace("&", "");
  94. }
  95. if (functionName.Contains("set_"))
  96. {
  97. info->write_ = true;
  98. if (info->type_.Empty())
  99. {
  100. // Extract type from parameters
  101. unsigned begin = declaration.Find(',');
  102. if (begin == String::NPOS)
  103. begin = declaration.Find('(');
  104. else
  105. info->indexed_ = true;
  106. if (begin != String::NPOS)
  107. {
  108. ++begin;
  109. unsigned end = declaration.Find(')');
  110. if (end != String::NPOS)
  111. {
  112. info->type_ = declaration.Substring(begin, end - begin);
  113. // Sanitate const & reference operator away
  114. info->type_.Replace("const ", "");
  115. info->type_.Replace("&in", "");
  116. info->type_.Replace("&", "");
  117. }
  118. }
  119. }
  120. }
  121. }
  122. OBJECTTYPESTATIC(Script);
  123. Script::Script(Context* context) :
  124. Object(context),
  125. scriptEngine_(0),
  126. immediateContext_(0),
  127. logMode_(LOGMODE_IMMEDIATE),
  128. scriptNestingLevel_(0)
  129. {
  130. scriptEngine_ = asCreateScriptEngine(ANGELSCRIPT_VERSION);
  131. if (!scriptEngine_)
  132. {
  133. LOGERROR("Could not create AngelScript engine");
  134. return;
  135. }
  136. scriptEngine_->SetUserData(this);
  137. scriptEngine_->SetEngineProperty(asEP_USE_CHARACTER_LITERALS, true);
  138. scriptEngine_->SetEngineProperty(asEP_ALLOW_UNSAFE_REFERENCES, true);
  139. scriptEngine_->SetEngineProperty(asEP_ALLOW_IMPLICIT_HANDLE_TYPES, true);
  140. scriptEngine_->SetEngineProperty(asEP_BUILD_WITHOUT_LINE_CUES, true);
  141. scriptEngine_->SetMessageCallback(asMETHOD(Script, MessageCallback), this, asCALL_THISCALL);
  142. // Create the context for immediate execution
  143. immediateContext_ = scriptEngine_->CreateContext();
  144. immediateContext_->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  145. // Register the Array & String types
  146. RegisterArray(scriptEngine_);
  147. RegisterString(scriptEngine_);
  148. }
  149. Script::~Script()
  150. {
  151. if (immediateContext_)
  152. {
  153. immediateContext_->Release();
  154. immediateContext_ = 0;
  155. }
  156. for (unsigned i = 0 ; i < scriptFileContexts_.Size(); ++i)
  157. scriptFileContexts_[i]->Release();
  158. if (scriptEngine_)
  159. {
  160. scriptEngine_->Release();
  161. scriptEngine_ = 0;
  162. }
  163. }
  164. bool Script::Execute(const String& line)
  165. {
  166. // Note: compiling code each time is slow. Not to be used for performance-critical or repeating activity
  167. PROFILE(ExecuteImmediate);
  168. ClearObjectTypeCache();
  169. String wrappedLine = "void f(){\n" + line + ";\n}";
  170. // If no immediate mode script file set, create a dummy module for compiling the line
  171. asIScriptModule* module = 0;
  172. if (defaultScriptFile_)
  173. module = defaultScriptFile_->GetScriptModule();
  174. if (!module)
  175. module = scriptEngine_->GetModule("ExecuteImmediate", asGM_CREATE_IF_NOT_EXISTS);
  176. if (!module)
  177. return false;
  178. asIScriptFunction *function = 0;
  179. if (module->CompileFunction("", wrappedLine.CString(), -1, 0, &function) < 0)
  180. return false;
  181. if (immediateContext_->Prepare(function) < 0)
  182. {
  183. function->Release();
  184. return false;
  185. }
  186. bool success = immediateContext_->Execute() >= 0;
  187. immediateContext_->Unprepare();
  188. function->Release();
  189. return success;
  190. }
  191. void Script::SetDefaultScriptFile(ScriptFile* file)
  192. {
  193. defaultScriptFile_ = file;
  194. }
  195. void Script::SetDefaultScene(Scene* scene)
  196. {
  197. defaultScene_ = scene;
  198. }
  199. void Script::SetLogMode(ScriptLogMode mode)
  200. {
  201. logMode_ = mode;
  202. }
  203. void Script::ClearLogMessages()
  204. {
  205. logMessages_.Clear();
  206. }
  207. void Script::DumpAPI()
  208. {
  209. // Does not use LOGRAW macro here to ensure the messages are always dumped regarless of ENABLE_LOGGING compiler directive and of Log subsystem availability
  210. Log::WriteRaw("namespace Urho3D\n{\n\n/**\n\\page ScriptAPI Scripting API\n\n");
  211. Vector<PropertyInfo> globalPropertyInfos;
  212. Vector<String> globalFunctions;
  213. unsigned functions = scriptEngine_->GetGlobalFunctionCount();
  214. for (unsigned i = 0; i < functions; ++i)
  215. {
  216. asIScriptFunction* function = scriptEngine_->GetGlobalFunctionByIndex(i);
  217. String functionName(function->GetName());
  218. String declaration(function->GetDeclaration());
  219. if (functionName.Contains("set_") || functionName.Contains("get_"))
  220. ExtractPropertyInfo(functionName, declaration, globalPropertyInfos);
  221. else
  222. globalFunctions.Push(declaration);
  223. }
  224. Log::WriteRaw("\\section ScriptAPI_GlobalFunctions Global functions\n");
  225. for (unsigned i = 0; i < globalFunctions.Size(); ++i)
  226. OutputAPIRow(globalFunctions[i]);
  227. Log::WriteRaw("\\section ScriptAPI_GlobalProperties Global properties\n");
  228. for (unsigned i = 0; i < globalPropertyInfos.Size(); ++i)
  229. OutputAPIRow(globalPropertyInfos[i].type_ + " " + globalPropertyInfos[i].name_, true);
  230. Log::WriteRaw("\\section ScriptAPI_GlobalConstants Global constants\n");
  231. unsigned properties = scriptEngine_->GetGlobalPropertyCount();
  232. for (unsigned i = 0; i < properties; ++i)
  233. {
  234. const char* propertyName;
  235. const char* propertyDeclaration;
  236. int typeId;
  237. scriptEngine_->GetGlobalPropertyByIndex(i, &propertyName, 0, &typeId);
  238. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  239. String type(propertyDeclaration);
  240. OutputAPIRow(type + " " + String(propertyName), true);
  241. }
  242. Log::WriteRaw("\\section ScriptAPI_Classes Classes\n");
  243. unsigned types = scriptEngine_->GetObjectTypeCount();
  244. for (unsigned i = 0; i < types; ++i)
  245. {
  246. asIObjectType* type = scriptEngine_->GetObjectTypeByIndex(i);
  247. if (type)
  248. {
  249. String typeName(type->GetName());
  250. Vector<String> methodDeclarations;
  251. Vector<PropertyInfo> propertyInfos;
  252. Log::WriteRaw("\n" + typeName + "\n");
  253. unsigned methods = type->GetMethodCount();
  254. for (unsigned j = 0; j < methods; ++j)
  255. {
  256. asIScriptFunction* method = type->GetMethodByIndex(j);
  257. String methodName(method->GetName());
  258. String declaration(method->GetDeclaration());
  259. if (methodName.Contains("get_") || methodName.Contains("set_"))
  260. ExtractPropertyInfo(methodName, declaration, propertyInfos);
  261. else
  262. {
  263. // Sanitate the method name. \todo For now, skip the operators
  264. if (!declaration.Contains("::op"))
  265. {
  266. String prefix(typeName + "::");
  267. declaration.Replace(prefix, "");
  268. methodDeclarations.Push(declaration);
  269. }
  270. }
  271. }
  272. // Assume that the same property is never both an accessor property, and a direct one
  273. unsigned properties = type->GetPropertyCount();
  274. for (unsigned j = 0; j < properties; ++j)
  275. {
  276. const char* propertyName;
  277. const char* propertyDeclaration;
  278. int typeId;
  279. type->GetProperty(j, &propertyName, &typeId);
  280. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  281. PropertyInfo newInfo;
  282. newInfo.name_ = String(propertyName);
  283. newInfo.type_ = String(propertyDeclaration);
  284. newInfo.read_ = newInfo.write_ = true;
  285. propertyInfos.Push(newInfo);
  286. }
  287. if (!methodDeclarations.Empty())
  288. {
  289. Log::WriteRaw("\nMethods:<br>\n");
  290. for (unsigned j = 0; j < methodDeclarations.Size(); ++j)
  291. OutputAPIRow(methodDeclarations[j]);
  292. }
  293. if (!propertyInfos.Empty())
  294. {
  295. Log::WriteRaw("\nProperties:<br>\n");
  296. for (unsigned j = 0; j < propertyInfos.Size(); ++j)
  297. {
  298. String remark;
  299. if (!propertyInfos[j].write_)
  300. remark = " (readonly)";
  301. else if (!propertyInfos[j].read_)
  302. remark = " (writeonly)";
  303. OutputAPIRow(propertyInfos[j].type_ + " " + propertyInfos[j].name_ + remark);
  304. }
  305. }
  306. Log::WriteRaw("\n");
  307. }
  308. }
  309. Log::WriteRaw("*/\n\n}\n");
  310. }
  311. void Script::MessageCallback(const asSMessageInfo* msg)
  312. {
  313. String message = String(msg->section) + " (" + String(msg->row) + "," + String(msg->col) + ") " +
  314. String(msg->message);
  315. if (logMode_ == LOGMODE_IMMEDIATE)
  316. {
  317. switch (msg->type)
  318. {
  319. case asMSGTYPE_ERROR:
  320. LOGERROR(message);
  321. break;
  322. case asMSGTYPE_WARNING:
  323. LOGWARNING(message);
  324. break;
  325. default:
  326. LOGINFO(message);
  327. break;
  328. }
  329. }
  330. else
  331. {
  332. // Ignore info messages in retained mode
  333. if (msg->type == asMSGTYPE_ERROR || msg->type == asMSGTYPE_WARNING)
  334. logMessages_ += message + "\n";
  335. }
  336. }
  337. void Script::ExceptionCallback(asIScriptContext* context)
  338. {
  339. asIScriptFunction *function = context->GetExceptionFunction();
  340. String message = "Exception '" + String(context->GetExceptionString()) + "' in '" +
  341. String(function->GetDeclaration()) + "'\n";
  342. message += GetCallStack(context);
  343. asSMessageInfo msg;
  344. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  345. msg.type = asMSGTYPE_ERROR;
  346. msg.message = message.CString();
  347. MessageCallback(&msg);
  348. }
  349. String Script::GetCallStack(asIScriptContext* context)
  350. {
  351. String str("AngelScript callstack:\n");
  352. // Append the call stack
  353. for (asUINT i = 0; i < context->GetCallstackSize(); i++)
  354. {
  355. asIScriptFunction* func;
  356. const char* scriptSection;
  357. int line, column;
  358. func = context->GetFunction(i);
  359. line = context->GetLineNumber(i, &column, &scriptSection);
  360. str.AppendWithFormat("\t%s:%s:%d,%d\n", scriptSection, func->GetDeclaration(), line, column);
  361. }
  362. return str;
  363. }
  364. ScriptFile* Script::GetDefaultScriptFile() const
  365. {
  366. return defaultScriptFile_;
  367. }
  368. Scene* Script::GetDefaultScene() const
  369. {
  370. return defaultScene_;
  371. }
  372. void Script::ClearObjectTypeCache()
  373. {
  374. objectTypes_.Clear();
  375. }
  376. asIObjectType* Script::GetObjectType(const char* declaration)
  377. {
  378. HashMap<const char*, asIObjectType*>::ConstIterator i = objectTypes_.Find(declaration);
  379. if (i != objectTypes_.End())
  380. return i->second_;
  381. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  382. objectTypes_[declaration] = type;
  383. return type;
  384. }
  385. asIScriptContext* Script::GetScriptFileContext()
  386. {
  387. while (scriptNestingLevel_ >= scriptFileContexts_.Size())
  388. {
  389. asIScriptContext* newContext = scriptEngine_->CreateContext();
  390. newContext->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  391. scriptFileContexts_.Push(newContext);
  392. }
  393. return scriptFileContexts_[scriptNestingLevel_];
  394. }
  395. void Script::OutputAPIRow(const String& row, bool removeReference)
  396. {
  397. String out = row;
  398. ///\todo We need Regex capability in String class to handle whole-word replacement correctly.
  399. // Temporary fix to prevent property name like 'doubleClickInterval' from being wrongly replaced.
  400. // Fortunately, there is no occurence of type 'double' in the API at the moment.
  401. //out.Replace("double", "float");
  402. out.Replace("&in", "&");
  403. out.Replace("&out", "&");
  404. if (removeReference)
  405. out.Replace("&", "");
  406. Log::WriteRaw("- " + out + "\n");
  407. }
  408. void RegisterScriptLibrary(Context* context)
  409. {
  410. ScriptFile::RegisterObject(context);
  411. ScriptInstance::RegisterObject(context);
  412. }
  413. }