lua_bridge.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. 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, PyObject* mod, PyObject* type){
  35. Type t = type->as<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. return vm->new_object<PyLuaTable>(PK_OBJ_GET(Type, args[0]));
  76. });
  77. vm->bind__len__(t, [](VM* vm, PyVar obj){
  78. const PyLuaTable& self = _CAST(PyLuaTable&, obj);
  79. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  80. i64 len = 0;
  81. lua_pushnil(_L);
  82. while(lua_next(_L, -2) != 0){ len += 1; lua_pop(_L, 1); }
  83. lua_pop(_L, 1);
  84. return len;
  85. });
  86. vm->bind__getitem__(t, [](VM* vm, PyVar obj, PyVar key){
  87. const PyLuaTable& self = _CAST(PyLuaTable&, obj);
  88. LUA_PROTECTED(
  89. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  90. lua_push_from_python(vm, key);
  91. lua_gettable(_L, -2);
  92. PyVar ret = lua_popx_to_python(vm);
  93. lua_pop(_L, 1);
  94. return ret;
  95. )
  96. });
  97. vm->bind__setitem__(t, [](VM* vm, PyVar obj, PyVar key, PyVar val){
  98. const PyLuaTable& self = _CAST(PyLuaTable&, obj);
  99. LUA_PROTECTED(
  100. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  101. lua_push_from_python(vm, key);
  102. lua_push_from_python(vm, val);
  103. lua_settable(_L, -3);
  104. lua_pop(_L, 1);
  105. )
  106. });
  107. vm->bind__delitem__(t, [](VM* vm, PyVar obj, PyVar key){
  108. const PyLuaTable& self = _CAST(PyLuaTable&, obj);
  109. LUA_PROTECTED(
  110. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  111. lua_push_from_python(vm, key);
  112. lua_pushnil(_L);
  113. lua_settable(_L, -3);
  114. lua_pop(_L, 1);
  115. )
  116. });
  117. vm->bind__contains__(t, [](VM* vm, PyVar obj, PyVar key){
  118. const PyLuaTable& self = _CAST(PyLuaTable&, obj);
  119. LUA_PROTECTED(
  120. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  121. lua_push_from_python(vm, key);
  122. lua_gettable(_L, -2);
  123. bool ret = lua_isnil(_L, -1) == 0;
  124. lua_pop(_L, 2);
  125. return ret ? vm->True : vm->False;
  126. )
  127. });
  128. vm->bind(type, "keys(self) -> list", [](VM* vm, ArgsView args){
  129. const PyLuaTable& self = _CAST(PyLuaTable&, args[0]);
  130. LUA_PROTECTED(
  131. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  132. List ret;
  133. table_apply(vm, [&](PyVar key, PyVar val){ ret.push_back(key); });
  134. lua_pop(_L, 1);
  135. return VAR(std::move(ret));
  136. )
  137. });
  138. vm->bind(type, "values(self) -> list", [](VM* vm, ArgsView args){
  139. const PyLuaTable& self = _CAST(PyLuaTable&, args[0]);
  140. LUA_PROTECTED(
  141. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  142. List ret;
  143. table_apply(vm, [&](PyVar key, PyVar val){ ret.push_back(val); });
  144. lua_pop(_L, 1);
  145. return VAR(std::move(ret));
  146. )
  147. });
  148. vm->bind(type, "items(self) -> list[tuple]", [](VM* vm, ArgsView args){
  149. const PyLuaTable& self = _CAST(PyLuaTable&, args[0]);
  150. LUA_PROTECTED(
  151. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  152. List ret;
  153. table_apply(vm, [&](PyVar key, PyVar val){
  154. PyVar item = VAR(Tuple(key, val));
  155. ret.push_back(item);
  156. });
  157. lua_pop(_L, 1);
  158. return VAR(std::move(ret));
  159. )
  160. });
  161. }
  162. };
  163. static PyVar lua_popx_multi_to_python(VM* vm, int count){
  164. if(count == 0){
  165. return vm->None;
  166. }else if(count == 1){
  167. return lua_popx_to_python(vm);
  168. }else if(count > 1){
  169. Tuple ret(count);
  170. for(int i=0; i<count; i++){
  171. ret[i] = lua_popx_to_python(vm);
  172. }
  173. return VAR(std::move(ret));
  174. }
  175. assert(false);
  176. }
  177. struct PyLuaFunction: PyLuaObject{
  178. static void _register(VM* vm, PyObject* mod, PyObject* type){
  179. vm->bind_func(type, __call__, -1, [](VM* vm, ArgsView args){
  180. if(args.size() < 1) vm->TypeError("__call__ takes at least 1 argument");
  181. const PyLuaFunction& self = _CAST(PyLuaFunction&, args[0]);
  182. int base_size = lua_gettop(_L);
  183. LUA_PROTECTED(
  184. lua_rawgeti(_L, LUA_REGISTRYINDEX, self.r);
  185. for(int i=1; i<args.size(); i++){
  186. lua_push_from_python(vm, args[i]);
  187. }
  188. if(lua_pcall(_L, args.size()-1, LUA_MULTRET, 0)){
  189. const char* error = lua_tostring(_L, -1);
  190. lua_pop(_L, 1);
  191. vm->RuntimeError(error);
  192. }
  193. return lua_popx_multi_to_python(vm, lua_gettop(_L) - base_size);
  194. )
  195. });
  196. }
  197. };
  198. void lua_push_from_python(VM* vm, PyVar val){
  199. if(is_none(val)){
  200. lua_pushnil(_L);
  201. return;
  202. }
  203. Type t = vm->_tp(val);
  204. switch(t.index){
  205. case VM::tp_bool.index:
  206. lua_pushboolean(_L, val == vm->True);
  207. return;
  208. case VM::tp_int.index:
  209. lua_pushinteger(_L, _CAST(i64, val));
  210. return;
  211. case VM::tp_float.index:
  212. lua_pushnumber(_L, _CAST(f64, val));
  213. return;
  214. case VM::tp_str.index: {
  215. std::string_view sv = _CAST(Str, val).sv();
  216. lua_pushlstring(_L, sv.data(), sv.size());
  217. return;
  218. }
  219. case VM::tp_tuple.index: {
  220. lua_newtable(_L);
  221. int i = 1;
  222. for(PyVar obj: PK_OBJ_GET(Tuple, val)){
  223. lua_push_from_python(vm, obj);
  224. lua_rawseti(_L, -2, i++);
  225. }
  226. return;
  227. }
  228. case VM::tp_list.index: {
  229. lua_newtable(_L);
  230. int i = 1;
  231. for(PyVar obj: PK_OBJ_GET(List, val)){
  232. lua_push_from_python(vm, obj);
  233. lua_rawseti(_L, -2, i++);
  234. }
  235. return;
  236. }
  237. case VM::tp_dict.index: {
  238. lua_newtable(_L);
  239. PK_OBJ_GET(Dict, val).apply([&](PyVar key, PyVar val){
  240. lua_push_from_python(vm, key);
  241. lua_push_from_python(vm, val);
  242. lua_settable(_L, -3);
  243. });
  244. return;
  245. }
  246. }
  247. if(vm->is_user_type<PyLuaTable>(val)){
  248. const PyLuaTable& table = _CAST(PyLuaTable&, val);
  249. lua_rawgeti(_L, LUA_REGISTRYINDEX, table.r);
  250. return;
  251. }
  252. if(vm->is_user_type<PyLuaFunction>(val)){
  253. const PyLuaFunction& func = _CAST(PyLuaFunction&, val);
  254. lua_rawgeti(_L, LUA_REGISTRYINDEX, func.r);
  255. return;
  256. }
  257. vm->RuntimeError(_S("unsupported python type: ", _type_name(vm, t).escape()));
  258. }
  259. PyVar lua_popx_to_python(VM* vm) {
  260. int type = lua_type(_L, -1);
  261. switch (type) {
  262. case LUA_TNIL: {
  263. lua_pop(_L, 1);
  264. return vm->None;
  265. }
  266. case LUA_TBOOLEAN: {
  267. bool val = lua_toboolean(_L, -1);
  268. lua_pop(_L, 1);
  269. return val ? vm->True : vm->False;
  270. }
  271. case LUA_TNUMBER: {
  272. double val = lua_tonumber(_L, -1);
  273. lua_pop(_L, 1);
  274. return VAR(val);
  275. }
  276. case LUA_TSTRING: {
  277. const char* val = lua_tostring(_L, -1);
  278. lua_pop(_L, 1);
  279. return VAR(val);
  280. }
  281. case LUA_TTABLE: {
  282. PyVar obj = vm->new_user_object<PyLuaTable>();
  283. return obj;
  284. }
  285. case LUA_TFUNCTION: {
  286. PyVar obj = vm->new_user_object<PyLuaFunction>();
  287. return obj;
  288. }
  289. default: {
  290. const char* type_name = lua_typename(_L, type);
  291. lua_pop(_L, 1);
  292. vm->RuntimeError(_S("unsupported lua type: '", type_name, "'"));
  293. }
  294. }
  295. PK_UNREACHABLE()
  296. }
  297. void initialize_lua_bridge(VM* vm, lua_State* newL){
  298. PyObject* mod = vm->new_module("lua");
  299. assert(_L == nullptr); // lua bridge already initialized
  300. _L = newL;
  301. vm->register_user_class<PyLuaTable>(mod, "Table");
  302. vm->register_user_class<PyLuaFunction>(mod, "Function");
  303. vm->bind(mod, "dostring(__source: str)", [](VM* vm, ArgsView args){
  304. const char* source = CAST(CString, args[0]);
  305. int base_size = lua_gettop(_L);
  306. if (luaL_dostring(_L, source)) {
  307. const char* error = lua_tostring(_L, -1);
  308. lua_pop(_L, 1); // pop error message from the stack
  309. vm->RuntimeError(error);
  310. }
  311. return lua_popx_multi_to_python(vm, lua_gettop(_L) - base_size);
  312. });
  313. }
  314. } // namespace pkpy