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