lua_bridge.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. #include "lua_bridge.hpp"
  2. namespace pkpy{
  3. static lua_State* _L;
  4. static void lua_push_from_python(VM*, PyVar);
  5. static PyVar lua_popx_to_python(VM*);
  6. template<typename T>
  7. static void table_apply(VM* vm, T f){
  8. PK_ASSERT(lua_istable(_L, -1));
  9. lua_pushnil(_L); // [key]
  10. while(lua_next(_L, -2) != 0){ // [key, val]
  11. lua_pushvalue(_L, -2); // [key, val, key]
  12. PyVar key = lua_popx_to_python(vm);
  13. PyVar val = lua_popx_to_python(vm);
  14. f(key, val); // [key]
  15. }
  16. lua_pop(_L, 1); // []
  17. }
  18. struct LuaExceptionGuard{
  19. int base_size;
  20. LuaExceptionGuard(){ base_size = lua_gettop(_L); }
  21. ~LuaExceptionGuard(){
  22. int delta = lua_gettop(_L) - base_size;
  23. if(delta > 0) lua_pop(_L, delta);
  24. }
  25. };
  26. #define LUA_PROTECTED(__B) { LuaExceptionGuard __guard; __B; }
  27. struct PyLuaObject{
  28. PK_ALWAYS_PASS_BY_POINTER(PyLuaObject)
  29. int r;
  30. PyLuaObject(){ r = luaL_ref(_L, LUA_REGISTRYINDEX); }
  31. ~PyLuaObject(){ luaL_unref(_L, LUA_REGISTRYINDEX, r); }
  32. };
  33. struct PyLuaTable: PyLuaObject{
  34. static void _register(VM* vm, PyVar mod, PyVar type){
  35. Type t = PK_OBJ_GET(Type, type);
  36. PyTypeInfo* ti = &vm->_all_types[t];
  37. ti->subclass_enabled = false;
  38. ti->m__getattr__ = [](VM* vm, PyVar obj, StrName name){
  39. const PyLuaTable& self = _CAST(PyLuaTable&, obj);
  40. LUA_PROTECTED(
  41. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  42. std::string_view name_sv = name.sv();
  43. lua_pushlstring(_L, name_sv.data(), name_sv.size());
  44. lua_gettable(_L, -2);
  45. PyVar ret = lua_popx_to_python(vm);
  46. lua_pop(_L, 1);
  47. return ret;
  48. )
  49. };
  50. ti->m__setattr__ = [](VM* vm, PyVar obj, StrName name, PyVar val){
  51. const PyLuaTable& self = _CAST(PyLuaTable&, obj);
  52. LUA_PROTECTED(
  53. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  54. std::string_view name_sv = name.sv();
  55. lua_pushlstring(_L, name_sv.data(), name_sv.size());
  56. lua_push_from_python(vm, val);
  57. lua_settable(_L, -3);
  58. lua_pop(_L, 1);
  59. )
  60. };
  61. ti->m__delattr__ = [](VM* vm, PyVar obj, StrName name){
  62. const PyLuaTable& self = _CAST(PyLuaTable&, obj);
  63. LUA_PROTECTED(
  64. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  65. std::string_view name_sv = name.sv();
  66. lua_pushlstring(_L, name_sv.data(), name_sv.size());
  67. lua_pushnil(_L);
  68. lua_settable(_L, -3);
  69. lua_pop(_L, 1);
  70. )
  71. return true;
  72. };
  73. vm->bind_func(type, __new__, 1, [](VM* vm, ArgsView args){
  74. lua_newtable(_L); // push an empty table onto the stack
  75. PyVar obj = vm->heap.gcnew<PyLuaTable>(PK_OBJ_GET(Type, args[0]));
  76. return obj;
  77. });
  78. vm->bind__len__(t, [](VM* vm, PyVar obj){
  79. const PyLuaTable& self = _CAST(PyLuaTable&, obj);
  80. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  81. i64 len = 0;
  82. lua_pushnil(_L);
  83. while(lua_next(_L, -2) != 0){ len += 1; lua_pop(_L, 1); }
  84. lua_pop(_L, 1);
  85. return len;
  86. });
  87. vm->bind__getitem__(t, [](VM* vm, PyVar obj, PyVar key){
  88. const PyLuaTable& self = _CAST(PyLuaTable&, obj);
  89. LUA_PROTECTED(
  90. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  91. lua_push_from_python(vm, key);
  92. lua_gettable(_L, -2);
  93. PyVar ret = lua_popx_to_python(vm);
  94. lua_pop(_L, 1);
  95. return ret;
  96. )
  97. });
  98. vm->bind__setitem__(t, [](VM* vm, PyVar obj, PyVar key, PyVar val){
  99. const PyLuaTable& self = _CAST(PyLuaTable&, obj);
  100. LUA_PROTECTED(
  101. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  102. lua_push_from_python(vm, key);
  103. lua_push_from_python(vm, val);
  104. lua_settable(_L, -3);
  105. lua_pop(_L, 1);
  106. )
  107. });
  108. vm->bind__delitem__(t, [](VM* vm, PyVar obj, PyVar key){
  109. const PyLuaTable& self = _CAST(PyLuaTable&, obj);
  110. LUA_PROTECTED(
  111. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  112. lua_push_from_python(vm, key);
  113. lua_pushnil(_L);
  114. lua_settable(_L, -3);
  115. lua_pop(_L, 1);
  116. )
  117. });
  118. vm->bind__contains__(t, [](VM* vm, PyVar obj, PyVar key){
  119. const PyLuaTable& self = _CAST(PyLuaTable&, obj);
  120. LUA_PROTECTED(
  121. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  122. lua_push_from_python(vm, key);
  123. lua_gettable(_L, -2);
  124. bool ret = lua_isnil(_L, -1) == 0;
  125. lua_pop(_L, 2);
  126. return ret ? vm->True : vm->False;
  127. )
  128. });
  129. vm->bind(type, "keys(self) -> list", [](VM* vm, ArgsView args){
  130. const PyLuaTable& self = _CAST(PyLuaTable&, args[0]);
  131. LUA_PROTECTED(
  132. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  133. List ret;
  134. table_apply(vm, [&](PyVar key, PyVar val){ ret.push_back(key); });
  135. lua_pop(_L, 1);
  136. return VAR(std::move(ret));
  137. )
  138. });
  139. vm->bind(type, "values(self) -> list", [](VM* vm, ArgsView args){
  140. const PyLuaTable& self = _CAST(PyLuaTable&, args[0]);
  141. LUA_PROTECTED(
  142. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  143. List ret;
  144. table_apply(vm, [&](PyVar key, PyVar val){ ret.push_back(val); });
  145. lua_pop(_L, 1);
  146. return VAR(std::move(ret));
  147. )
  148. });
  149. vm->bind(type, "items(self) -> list[tuple]", [](VM* vm, ArgsView args){
  150. const PyLuaTable& self = _CAST(PyLuaTable&, args[0]);
  151. LUA_PROTECTED(
  152. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  153. List ret;
  154. table_apply(vm, [&](PyVar key, PyVar val){
  155. PyVar item = VAR(Tuple(key, val));
  156. ret.push_back(item);
  157. });
  158. lua_pop(_L, 1);
  159. return VAR(std::move(ret));
  160. )
  161. });
  162. }
  163. };
  164. static PyVar lua_popx_multi_to_python(VM* vm, int count){
  165. if(count == 0){
  166. return vm->None;
  167. }else if(count == 1){
  168. return lua_popx_to_python(vm);
  169. }else if(count > 1){
  170. Tuple ret(count);
  171. for(int i=0; i<count; i++){
  172. ret[i] = lua_popx_to_python(vm);
  173. }
  174. return VAR(std::move(ret));
  175. }
  176. PK_FATAL_ERROR()
  177. }
  178. struct PyLuaFunction: PyLuaObject{
  179. static void _register(VM* vm, PyVar mod, PyVar type){
  180. vm->bind_func(type, __call__, -1, [](VM* vm, ArgsView args){
  181. if(args.size() < 1) vm->TypeError("__call__ takes at least 1 argument");
  182. const PyLuaFunction& self = _CAST(PyLuaFunction&, args[0]);
  183. int base_size = lua_gettop(_L);
  184. LUA_PROTECTED(
  185. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  186. for(int i=1; i<args.size(); i++){
  187. lua_push_from_python(vm, args[i]);
  188. }
  189. if(lua_pcall(_L, args.size()-1, LUA_MULTRET, 0)){
  190. const char* error = lua_tostring(_L, -1);
  191. lua_pop(_L, 1);
  192. vm->RuntimeError(error);
  193. }
  194. return lua_popx_multi_to_python(vm, lua_gettop(_L) - base_size);
  195. )
  196. });
  197. }
  198. };
  199. void lua_push_from_python(VM* vm, PyVar val){
  200. if(val == vm->None){
  201. lua_pushnil(_L);
  202. return;
  203. }
  204. Type t = vm->_tp(val);
  205. switch(t.index){
  206. case VM::tp_bool.index:
  207. lua_pushboolean(_L, val == vm->True);
  208. return;
  209. case VM::tp_int.index:
  210. lua_pushinteger(_L, _CAST(i64, val));
  211. return;
  212. case VM::tp_float.index:
  213. lua_pushnumber(_L, _CAST(f64, val));
  214. return;
  215. case VM::tp_str.index: {
  216. std::string_view sv = _CAST(Str, val).sv();
  217. lua_pushlstring(_L, sv.data(), sv.size());
  218. return;
  219. }
  220. case VM::tp_tuple.index: {
  221. lua_newtable(_L);
  222. int i = 1;
  223. for(PyVar obj: PK_OBJ_GET(Tuple, val)){
  224. lua_push_from_python(vm, obj);
  225. lua_rawseti(_L, -2, i++);
  226. }
  227. return;
  228. }
  229. case VM::tp_list.index: {
  230. lua_newtable(_L);
  231. int i = 1;
  232. for(PyVar obj: PK_OBJ_GET(List, val)){
  233. lua_push_from_python(vm, obj);
  234. lua_rawseti(_L, -2, i++);
  235. }
  236. return;
  237. }
  238. case VM::tp_dict.index: {
  239. lua_newtable(_L);
  240. PK_OBJ_GET(Dict, val).apply([&](PyVar key, PyVar val){
  241. lua_push_from_python(vm, key);
  242. lua_push_from_python(vm, val);
  243. lua_settable(_L, -3);
  244. });
  245. return;
  246. }
  247. }
  248. if(vm->is_user_type<PyLuaTable>(val)){
  249. const PyLuaTable& table = _CAST(PyLuaTable&, val);
  250. lua_rawgeti(_L, LUA_REGISTRYINDEX, table.r);
  251. return;
  252. }
  253. if(vm->is_user_type<PyLuaFunction>(val)){
  254. const PyLuaFunction& func = _CAST(PyLuaFunction&, val);
  255. lua_rawgeti(_L, LUA_REGISTRYINDEX, func.r);
  256. return;
  257. }
  258. vm->RuntimeError(_S("unsupported python type: ", _type_name(vm, t).escape()));
  259. }
  260. PyVar lua_popx_to_python(VM* vm) {
  261. int type = lua_type(_L, -1);
  262. switch (type) {
  263. case LUA_TNIL: {
  264. lua_pop(_L, 1);
  265. return vm->None;
  266. }
  267. case LUA_TBOOLEAN: {
  268. bool val = lua_toboolean(_L, -1);
  269. lua_pop(_L, 1);
  270. return val ? vm->True : vm->False;
  271. }
  272. case LUA_TNUMBER: {
  273. double val = lua_tonumber(_L, -1);
  274. lua_pop(_L, 1);
  275. return VAR(val);
  276. }
  277. case LUA_TSTRING: {
  278. const char* val = lua_tostring(_L, -1);
  279. lua_pop(_L, 1);
  280. return VAR(val);
  281. }
  282. case LUA_TTABLE: {
  283. PyVar obj = vm->new_user_object<PyLuaTable>();
  284. return obj;
  285. }
  286. case LUA_TFUNCTION: {
  287. PyVar obj = vm->new_user_object<PyLuaFunction>();
  288. return obj;
  289. }
  290. default: {
  291. const char* type_name = lua_typename(_L, type);
  292. lua_pop(_L, 1);
  293. vm->RuntimeError(_S("unsupported lua type: '", type_name, "'"));
  294. }
  295. }
  296. PK_UNREACHABLE()
  297. }
  298. void initialize_lua_bridge(VM* vm, lua_State* newL){
  299. PyVar mod = vm->new_module("lua");
  300. if(_L != nullptr){
  301. throw std::runtime_error("lua bridge already initialized");
  302. }
  303. _L = newL;
  304. vm->register_user_class<PyLuaTable>(mod, "Table");
  305. vm->register_user_class<PyLuaFunction>(mod, "Function");
  306. vm->bind(mod, "dostring(__source: str)", [](VM* vm, ArgsView args){
  307. const char* source = CAST(CString, args[0]);
  308. int base_size = lua_gettop(_L);
  309. if (luaL_dostring(_L, source)) {
  310. const char* error = lua_tostring(_L, -1);
  311. lua_pop(_L, 1); // pop error message from the stack
  312. vm->RuntimeError(error);
  313. }
  314. return lua_popx_multi_to_python(vm, lua_gettop(_L) - base_size);
  315. });
  316. }
  317. } // namespace pkpy