lua_environment.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. /*
  2. * Copyright (c) 2012-2021 Daniele Bartolini et al.
  3. * License: https://github.com/dbartolini/crown/blob/master/LICENSE
  4. */
  5. #include "config.h"
  6. #include "core/error/error.h"
  7. #include "core/json/json_object.inl"
  8. #include "core/json/sjson.h"
  9. #include "core/memory/temp_allocator.inl"
  10. #include "core/strings/dynamic_string.inl"
  11. #include "core/strings/string_stream.inl"
  12. #include "device/device.h"
  13. #include "device/log.h"
  14. #include "lua/lua_environment.h"
  15. #include "lua/lua_stack.inl"
  16. #include "resource/lua_resource.h"
  17. #include "resource/resource_manager.h"
  18. #include <lua.hpp>
  19. #include <stdarg.h>
  20. LOG_SYSTEM(LUA, "lua")
  21. namespace crown
  22. {
  23. extern void load_api(LuaEnvironment& env);
  24. static int luaB_print(lua_State* L)
  25. {
  26. TempAllocator2048 ta;
  27. StringStream ss(ta);
  28. int n = lua_gettop(L); /* number of arguments */
  29. lua_getglobal(L, "tostring");
  30. for (int i = 1; i <= n; ++i)
  31. {
  32. const char *s;
  33. lua_pushvalue(L, -1); /* function to be called */
  34. lua_pushvalue(L, i); /* value to print */
  35. lua_call(L, 1, 1);
  36. s = lua_tostring(L, -1); /* get result */
  37. if (s == NULL)
  38. return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print"));
  39. if (i > 1)
  40. ss << "\t";
  41. ss << s;
  42. lua_pop(L, 1); /* pop result */
  43. }
  44. logi(LUA, string_stream::c_str(ss));
  45. return 0;
  46. }
  47. static int msghandler(lua_State* L) {
  48. const char *msg = lua_tostring(L, 1);
  49. if (msg == NULL) { /* is error object not a string? */
  50. if (luaL_callmeta(L, 1, "__tostring") && /* does it have a metamethod */
  51. lua_type(L, -1) == LUA_TSTRING) /* that produces a string? */
  52. return 1; /* that is the message */
  53. else
  54. msg = lua_pushfstring(L, "(error object is a %s value)",
  55. luaL_typename(L, 1));
  56. }
  57. luaL_traceback(L, L, msg, 1); /* append a standard traceback */
  58. return 1; /* return the traceback */
  59. }
  60. /*
  61. ** Prints (calling the Lua 'print' function) any values on the stack
  62. */
  63. static void l_print (lua_State *L) {
  64. int n = lua_gettop(L);
  65. if (n > 0) { /* any result to be printed? */
  66. luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
  67. lua_getglobal(L, "print");
  68. lua_insert(L, 1);
  69. if (lua_pcall(L, n, 0, 0) != LUA_OK)
  70. loge(LUA, lua_pushfstring(L, "error calling 'print' (%s)", lua_tostring(L, -1)));
  71. }
  72. }
  73. /*
  74. ** Try to compile line on the stack as 'return <line>;'; on return, stack
  75. ** has either compiled chunk or original line (if compilation failed).
  76. */
  77. static int addreturn (lua_State *L) {
  78. const char *line = lua_tostring(L, -1); /* original line */
  79. const char *retline = lua_pushfstring(L, "return %s;", line);
  80. int status = luaL_loadbuffer(L, retline, strlen(retline), "=stdin");
  81. if (status == LUA_OK)
  82. lua_remove(L, -2); /* remove modified line */
  83. else
  84. lua_pop(L, 2); /* pop result from 'luaL_loadbuffer' and modified line */
  85. return status;
  86. }
  87. /*
  88. ** Read a line and try to load (compile) it first as an expression (by
  89. ** adding "return " in front of it) and second as a statement. Return
  90. ** the final status of load/call with the resulting function (if any)
  91. ** in the top of the stack.
  92. */
  93. static int loadline (lua_State *L) {
  94. int status;
  95. if ((status = addreturn(L)) != LUA_OK) { /* 'return ...' did not work? */
  96. // status = multiline(L); /* try as command, maybe with continuation lines */
  97. size_t len;
  98. const char *line = lua_tolstring(L, 1, &len); /* get what it has */
  99. status = luaL_loadbuffer(L, line, len, "=stdin"); /* try it */
  100. }
  101. lua_remove(L, 1); /* remove line from the stack */
  102. lua_assert(lua_gettop(L) == 1);
  103. return status;
  104. }
  105. /*
  106. ** Check whether 'status' is not OK and, if so, prints the error
  107. ** message on the top of the stack. It assumes that the error object
  108. ** is a string, as it was either generated by Lua or by 'msghandler'.
  109. */
  110. int report (lua_State *L, int status) {
  111. if (status != LUA_OK) {
  112. const char *msg = lua_tostring(L, -1);
  113. loge(LUA, msg);
  114. lua_pop(L, 1); /* remove message */
  115. }
  116. return status;
  117. }
  118. static int loader(lua_State* L)
  119. {
  120. LuaStack stack(L);
  121. int status;
  122. const LuaResource* lr = (LuaResource*)device()->_resource_manager->get(RESOURCE_TYPE_SCRIPT, stack.get_resource_name(1));
  123. status = luaL_loadbuffer(L, lua_resource::program(lr), lr->size, "");
  124. if (status != LUA_OK)
  125. {
  126. report(L, status);
  127. device()->pause();
  128. }
  129. return 1;
  130. }
  131. #if CROWN_DEBUG
  132. static int require_internal(lua_State* L)
  133. {
  134. const char* module_name = lua_tostring(L, 1);
  135. bool already_loaded = false;
  136. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  137. lua_getfield(L, -1, module_name);
  138. already_loaded = lua_toboolean(L, -1);
  139. lua_pop(L, 2);
  140. lua_getglobal(L, "original_require");
  141. lua_pushvalue(L, -2);
  142. lua_remove(L, -3);
  143. lua_call(L, 1, 1);
  144. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  145. lua_getfield(L, 2, module_name);
  146. if (lua_toboolean(L, -1) && !already_loaded)
  147. {
  148. lua_pop(L, 2);
  149. lua_getglobal(L, "package");
  150. lua_getfield(L, -1, "load_order");
  151. lua_pushstring(L, module_name);
  152. lua_rawseti(L, -2, int(lua_objlen(L, -2) + 1));
  153. lua_pop(L, 2); // Pop "package.load_order" and "package"
  154. }
  155. return 1;
  156. }
  157. #endif
  158. LuaEnvironment::LuaEnvironment()
  159. : L(NULL)
  160. , _num_vec3(0)
  161. , _num_quat(0)
  162. , _num_mat4(0)
  163. #if CROWN_DEBUG
  164. , _vec3_marker(0)
  165. , _quat_marker(0)
  166. , _mat4_marker(0)
  167. , _random(0)
  168. #endif
  169. {
  170. #if CROWN_DEBUG
  171. // Initialize temporaries markers with random values.
  172. _random._seed = (s32)guid::new_guid().data1;
  173. reset_temporaries();
  174. #endif
  175. L = luaL_newstate();
  176. CE_ASSERT(L, "Unable to create lua state");
  177. }
  178. LuaEnvironment::~LuaEnvironment()
  179. {
  180. lua_close(L);
  181. }
  182. void LuaEnvironment::load_libs()
  183. {
  184. lua_gc(L, LUA_GCSTOP, 0);
  185. // Open default libraries
  186. lua_pushcfunction(L, luaopen_base);
  187. lua_pushstring(L, "");
  188. lua_call(L, 1, 0);
  189. lua_pushcfunction(L, luaopen_package);
  190. lua_pushstring(L, LUA_LOADLIBNAME);
  191. lua_call(L, 1, 0);
  192. lua_pushcfunction(L, luaopen_table);
  193. lua_pushstring(L, LUA_TABLIBNAME);
  194. lua_call(L, 1, 0);
  195. lua_pushcfunction(L, luaopen_string);
  196. lua_pushstring(L, LUA_STRLIBNAME);
  197. lua_call(L, 1, 0);
  198. lua_pushcfunction(L, luaopen_math);
  199. lua_pushstring(L, LUA_MATHLIBNAME);
  200. lua_call(L, 1, 0);
  201. lua_pushcfunction(L, luaopen_debug);
  202. lua_pushstring(L, LUA_DBLIBNAME);
  203. lua_call(L, 1, 0);
  204. lua_pushcfunction(L, luaopen_bit);
  205. lua_pushstring(L, LUA_BITLIBNAME);
  206. lua_call(L, 1, 0);
  207. lua_pushcfunction(L, luaopen_jit);
  208. lua_pushstring(L, LUA_JITLIBNAME);
  209. lua_call(L, 1, 0);
  210. // Override print to redirect output to logging system
  211. add_module_function("_G", "print", luaB_print);
  212. // Register crown libraries
  213. load_api(*this);
  214. // Register custom loader
  215. lua_getglobal(L, "package");
  216. lua_getfield(L, -1, "loaders");
  217. lua_pushcfunction(L, loader);
  218. lua_rawseti(L, -2, 1); // package.loaders[1] = loader
  219. lua_pushnil(L);
  220. lua_rawseti(L, -2, 2); // package.loaders[2] = nil
  221. lua_pushnil(L);
  222. lua_rawseti(L, -2, 3); // package.loaders[3] = nil
  223. lua_pushnil(L);
  224. lua_rawseti(L, -2, 4); // package.loaders[4] = nil
  225. lua_pop(L, 1); // pop "package.loaders"
  226. #if CROWN_DEBUG
  227. // Create new empty table to store package load order
  228. lua_newtable(L);
  229. lua_setfield(L, -2, "load_order"); // package.load_order = {}
  230. // Override require() to keep track of libraries' load order
  231. lua_getglobal(L, "require");
  232. lua_setglobal(L, "original_require");
  233. lua_pushcclosure(L, require_internal, 0); // pass original require() to new require as upvalue
  234. lua_setglobal(L, "require");
  235. #endif
  236. lua_pop(L, 1); // pop "package"
  237. // Create metatable for lightuserdata
  238. lua_pushlightuserdata(L, 0);
  239. lua_getfield(L, LUA_REGISTRYINDEX, "Lightuserdata_mt");
  240. lua_setmetatable(L, -2);
  241. lua_pop(L, 1);
  242. // Ensure stack is clean
  243. CE_ASSERT(lua_gettop(L) == 0, "Stack not clean");
  244. lua_gc(L, LUA_GCRESTART, 0);
  245. }
  246. void LuaEnvironment::do_file(const char* name)
  247. {
  248. lua_getglobal(L, "dofile");
  249. lua_pushstring(L, name);
  250. this->call(1, 0);
  251. }
  252. void LuaEnvironment::require(const char* name)
  253. {
  254. lua_getglobal(L, "require");
  255. lua_pushstring(L, name);
  256. this->call(1, 0);
  257. }
  258. LuaStack LuaEnvironment::execute(const LuaResource* lr, int nres)
  259. {
  260. LuaStack stack(L);
  261. int status;
  262. status = luaL_loadbuffer(L, lua_resource::program(lr), lr->size, "<unknown>");
  263. if (status == LUA_OK)
  264. status = this->call(0, nres);
  265. if (status != LUA_OK)
  266. {
  267. report(L, status);
  268. device()->pause();
  269. }
  270. return stack;
  271. }
  272. LuaStack LuaEnvironment::execute_string(const char* s)
  273. {
  274. LuaStack stack(L);
  275. int status;
  276. status = luaL_loadstring(L, s);
  277. if (status == LUA_OK)
  278. status = this->call(0, 0);
  279. if (status != LUA_OK)
  280. {
  281. report(L, status);
  282. device()->pause();
  283. }
  284. CE_ASSERT(lua_gettop(L) == 0, "Stack not clean");
  285. return stack;
  286. }
  287. void LuaEnvironment::add_module_function(const char* module, const char* name, const lua_CFunction func)
  288. {
  289. luaL_Reg entry[2];
  290. entry[0].name = name;
  291. entry[0].func = func;
  292. entry[1].name = NULL;
  293. entry[1].func = NULL;
  294. luaL_register(L, module, entry);
  295. lua_pop(L, 1);
  296. }
  297. void LuaEnvironment::add_module_function(const char* module, const char* name, const char* func)
  298. {
  299. // Create module if it does not exist
  300. luaL_Reg entry;
  301. entry.name = NULL;
  302. entry.func = NULL;
  303. luaL_register(L, module, &entry);
  304. lua_pop(L, 1);
  305. lua_getglobal(L, module);
  306. lua_getglobal(L, func);
  307. lua_setfield(L, -2, name);
  308. lua_setglobal(L, module);
  309. }
  310. void LuaEnvironment::add_module_metafunction(const char* module, const char* name, const lua_CFunction func)
  311. {
  312. // Create module if it does not exist
  313. luaL_Reg entry[2];
  314. entry[0].name = NULL;
  315. entry[0].func = NULL;
  316. luaL_register(L, module, entry);
  317. lua_pop(L, 1);
  318. luaL_newmetatable(L, module);
  319. if (func)
  320. {
  321. entry[0].name = name;
  322. entry[0].func = func;
  323. entry[1].name = NULL;
  324. entry[1].func = NULL;
  325. luaL_register(L, NULL, entry);
  326. }
  327. else
  328. {
  329. lua_pushstring(L, name);
  330. lua_pushvalue(L, -2);
  331. lua_settable(L, -3);
  332. }
  333. lua_getglobal(L, module);
  334. lua_pushvalue(L, -2);
  335. lua_setmetatable(L, -2);
  336. lua_pop(L, -1);
  337. }
  338. int LuaEnvironment::call(int narg, int nres)
  339. {
  340. int status;
  341. int base = lua_gettop(L) - narg; /* function index */
  342. lua_pushcfunction(L, msghandler); /* push message handler */
  343. lua_insert(L, base); /* put it under function and args */
  344. status = lua_pcall(L, narg, nres, base);
  345. lua_remove(L, base); /* remove message handler from the stack */
  346. return status;
  347. }
  348. void LuaEnvironment::call_global(const char* func, int narg, int nres)
  349. {
  350. int status;
  351. CE_ENSURE(NULL != func);
  352. lua_getglobal(L, func);
  353. lua_insert(L, 1); // Move func to the top of stack
  354. status = call(narg, nres);
  355. if (status != LUA_OK)
  356. {
  357. report(L, status);
  358. device()->pause();
  359. }
  360. CE_ASSERT(lua_gettop(L) == 0, "Stack not clean");
  361. }
  362. LuaStack LuaEnvironment::get_global(const char* global)
  363. {
  364. LuaStack stack(L);
  365. lua_getglobal(L, global);
  366. return stack;
  367. }
  368. Vector3* LuaEnvironment::next_vector3(const Vector3& v)
  369. {
  370. CE_ASSERT(_num_vec3 < LUA_MAX_VECTOR3, "Maximum number of Vector3 reached");
  371. Vector3* vec3 = &(_vec3[_num_vec3++] = v);
  372. uintptr_t ptr = (uintptr_t)(void*)vec3;
  373. #if CROWN_DEBUG
  374. ptr |= _vec3_marker;
  375. #endif
  376. return (Vector3*)ptr;
  377. }
  378. Quaternion* LuaEnvironment::next_quaternion(const Quaternion& q)
  379. {
  380. CE_ASSERT(_num_quat < LUA_MAX_QUATERNION, "Maximum number of Quaternion reached");
  381. Quaternion* quat = &(_quat[_num_quat++] = q);
  382. uintptr_t ptr = (uintptr_t)(void*)quat;
  383. #if CROWN_DEBUG
  384. ptr |= _quat_marker;
  385. #endif
  386. return (Quaternion*)ptr;
  387. }
  388. Matrix4x4* LuaEnvironment::next_matrix4x4(const Matrix4x4& m)
  389. {
  390. CE_ASSERT(_num_mat4 < LUA_MAX_MATRIX4X4, "Maximum number of Matrix4x4 reached");
  391. Matrix4x4* mat4 = &(_mat4[_num_mat4++] = m);
  392. uintptr_t ptr = (uintptr_t)(void*)mat4;
  393. #if CROWN_DEBUG
  394. ptr |= _mat4_marker;
  395. #endif
  396. return (Matrix4x4*)ptr;
  397. }
  398. bool LuaEnvironment::is_vector3(const void* ptr)
  399. {
  400. return ptr >= &_vec3[0]
  401. && ptr <= &_vec3[LUA_MAX_VECTOR3 - 1];
  402. }
  403. bool LuaEnvironment::is_quaternion(const void* ptr)
  404. {
  405. return ptr >= &_quat[0]
  406. && ptr <= &_quat[LUA_MAX_QUATERNION - 1];
  407. }
  408. bool LuaEnvironment::is_matrix4x4(const void* ptr)
  409. {
  410. return ptr >= &_mat4[0]
  411. && ptr <= &_mat4[LUA_MAX_MATRIX4X4 - 1];
  412. }
  413. #if CROWN_DEBUG
  414. Vector3* LuaEnvironment::check_valid(const Vector3* ptr)
  415. {
  416. LUA_ASSERT(((uintptr_t)ptr & LUA_VECTOR3_MARKER_MASK) >> LUA_VECTOR3_MARKER_SHIFT == _vec3_marker
  417. , LuaStack(L)
  418. , "Stale Vector3 ptr: %p, expected marker: %p"
  419. , ptr
  420. , _vec3_marker
  421. );
  422. return (Vector3*)(uintptr_t(ptr) & ~LUA_VECTOR3_MARKER_MASK);
  423. }
  424. Quaternion* LuaEnvironment::check_valid(const Quaternion* ptr)
  425. {
  426. LUA_ASSERT(((uintptr_t)ptr & LUA_QUATERNION_MARKER_MASK) >> LUA_QUATERNION_MARKER_SHIFT == _quat_marker
  427. , LuaStack(L)
  428. , "Stale Quaternion ptr: %p, expected marker: %p"
  429. , ptr
  430. , _quat_marker
  431. );
  432. return (Quaternion*)(uintptr_t(ptr) & ~LUA_QUATERNION_MARKER_MASK);
  433. }
  434. Matrix4x4* LuaEnvironment::check_valid(const Matrix4x4* ptr)
  435. {
  436. LUA_ASSERT(((uintptr_t)ptr & LUA_MATRIX4X4_MARKER_MASK) >> LUA_MATRIX4X4_MARKER_SHIFT == _mat4_marker
  437. , LuaStack(L)
  438. , "Stale Matrix4x4 ptr: %p, expected marker: %p"
  439. , ptr
  440. , _mat4_marker
  441. );
  442. return (Matrix4x4*)(uintptr_t(ptr) & ~LUA_MATRIX4X4_MARKER_MASK);
  443. }
  444. #endif // CROWN_DEBUG
  445. void LuaEnvironment::reload()
  446. {
  447. lua_getglobal(L, "package");
  448. lua_getfield(L, -1, "load_order");
  449. for (size_t i = 1, n = lua_objlen(L, -1); i < n+1; ++i)
  450. {
  451. lua_rawgeti(L, -1, (int)i);
  452. logi(LUA, "reloading: %s", lua_tostring(L, -1));
  453. LuaStack stack(L);
  454. StringId64 name = stack.get_resource_name(-1);
  455. this->execute((const LuaResource*)device()->_resource_manager->get(RESOURCE_TYPE_SCRIPT, name), 0);
  456. lua_pop(L, 1);
  457. }
  458. lua_pop(L, 2);
  459. }
  460. void LuaEnvironment::temp_count(u32& num_vec3, u32& num_quat, u32& num_mat4)
  461. {
  462. num_vec3 = _num_vec3;
  463. num_quat = _num_quat;
  464. num_mat4 = _num_mat4;
  465. }
  466. void LuaEnvironment::set_temp_count(u32 num_vec3, u32 num_quat, u32 num_mat4)
  467. {
  468. _num_vec3 = num_vec3;
  469. _num_quat = num_quat;
  470. _num_mat4 = num_mat4;
  471. }
  472. void LuaEnvironment::reset_temporaries()
  473. {
  474. _num_vec3 = 0;
  475. _num_quat = 0;
  476. _num_mat4 = 0;
  477. #if CROWN_DEBUG
  478. _vec3_marker = (uintptr_t)_random.integer(1 + LUA_VECTOR3_MARKER_MASK);
  479. _quat_marker = (uintptr_t)_random.integer(1 + LUA_QUATERNION_MARKER_MASK);
  480. _mat4_marker = (uintptr_t)_random.integer(1 + LUA_MATRIX4X4_MARKER_MASK);
  481. #endif
  482. }
  483. static void console_command_script(ConsoleServer& /*cs*/, u32 /*client_id*/, const char* json, void* user_data)
  484. {
  485. TempAllocator4096 ta;
  486. JsonObject obj(ta);
  487. DynamicString script(ta);
  488. sjson::parse(obj, json);
  489. sjson::parse_string(script, obj["script"]);
  490. ((LuaEnvironment*)user_data)->execute_string(script.c_str());
  491. }
  492. static void do_REPL(LuaEnvironment* env, const char* lua)
  493. {
  494. lua_State* L = env->L;
  495. int status;
  496. lua_settop(L, 0);
  497. lua_pushstring(L, lua);
  498. if ((status = loadline(L)) != -1) // This is never -1
  499. {
  500. if (status == LUA_OK)
  501. {
  502. status = env->call(0, LUA_MULTRET);
  503. }
  504. if (status == LUA_OK)
  505. l_print(L);
  506. else
  507. report(L, status);
  508. }
  509. lua_settop(L, 0); /* clear stack */
  510. return;
  511. }
  512. static void console_command_REPL(ConsoleServer& /*cs*/, u32 /*client_id*/, const char* json, void* user_data)
  513. {
  514. TempAllocator4096 ta;
  515. JsonObject obj(ta);
  516. DynamicString script(ta);
  517. sjson::parse(obj, json);
  518. sjson::parse_string(script, obj["repl"]);
  519. do_REPL((LuaEnvironment*)user_data, script.c_str());
  520. }
  521. void LuaEnvironment::register_console_commands(ConsoleServer& cs)
  522. {
  523. cs.register_message_type("script", console_command_script, this);
  524. cs.register_message_type("repl", console_command_REPL, this);
  525. }
  526. } // namespace crown