internal.c 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. #include "pocketpy/interpreter/typeinfo.h"
  2. #include "pocketpy/objects/codeobject.h"
  3. #include "pocketpy/pocketpy.h"
  4. #include "pocketpy/common/utils.h"
  5. #include "pocketpy/common/name.h"
  6. #include "pocketpy/interpreter/vm.h"
  7. _Thread_local VM* pk_current_vm;
  8. static bool pk_initialized;
  9. static bool pk_finalized;
  10. static VM pk_default_vm;
  11. static VM* pk_all_vm[16];
  12. static py_TValue _True, _False, _None, _NIL;
  13. void py_initialize() {
  14. c11__rtassert(!pk_finalized);
  15. if(pk_initialized) {
  16. // c11__abort("py_initialize() can only be called once!");
  17. return;
  18. }
  19. pk_names_initialize();
  20. // check endianness
  21. int x = 1;
  22. bool is_little_endian = *(char*)&x == 1;
  23. if(!is_little_endian) c11__abort("is_little_endian != true");
  24. // check py_TValue; 16 bytes to make py_arg() macro work
  25. static_assert(sizeof(py_CFunction) <= 8, "sizeof(py_CFunction) > 8");
  26. static_assert(sizeof(py_TValue) == 16, "sizeof(py_TValue) != 16");
  27. static_assert(offsetof(py_TValue, extra) == 4, "offsetof(py_TValue, extra) != 4");
  28. pk_current_vm = pk_all_vm[0] = &pk_default_vm;
  29. // initialize some convenient references
  30. py_newbool(&_True, true);
  31. py_newbool(&_False, false);
  32. py_newnone(&_None);
  33. py_newnil(&_NIL);
  34. VM__ctor(&pk_default_vm);
  35. pk_initialized = true;
  36. }
  37. py_GlobalRef py_True() { return &_True; }
  38. py_GlobalRef py_False() { return &_False; }
  39. py_GlobalRef py_None() { return &_None; }
  40. py_GlobalRef py_NIL() { return &_NIL; }
  41. void py_finalize() {
  42. if(pk_finalized) c11__abort("py_finalize() can only be called once!");
  43. pk_finalized = true;
  44. for(int i = 1; i < 16; i++) {
  45. VM* vm = pk_all_vm[i];
  46. if(vm) {
  47. // temp fix https://github.com/pocketpy/pocketpy/issues/315
  48. // TODO: refactor VM__ctor and VM__dtor
  49. pk_current_vm = vm;
  50. VM__dtor(vm);
  51. PK_FREE(vm);
  52. }
  53. }
  54. pk_current_vm = &pk_default_vm;
  55. VM__dtor(&pk_default_vm);
  56. pk_current_vm = NULL;
  57. pk_names_finalize();
  58. }
  59. void py_switchvm(int index) {
  60. if(index < 0 || index >= 16) c11__abort("invalid vm index");
  61. if(!pk_all_vm[index]) {
  62. pk_current_vm = pk_all_vm[index] = PK_MALLOC(sizeof(VM));
  63. memset(pk_current_vm, 0, sizeof(VM));
  64. VM__ctor(pk_all_vm[index]);
  65. } else {
  66. pk_current_vm = pk_all_vm[index];
  67. }
  68. }
  69. void py_resetvm() {
  70. VM* vm = pk_current_vm;
  71. VM__dtor(vm);
  72. memset(vm, 0, sizeof(VM));
  73. VM__ctor(vm);
  74. }
  75. void py_resetallvm() {
  76. for(int i = 0; i < 16; i++) {
  77. py_switchvm(i);
  78. py_resetvm();
  79. }
  80. py_switchvm(0);
  81. }
  82. int py_currentvm() {
  83. for(int i = 0; i < 16; i++) {
  84. if(pk_all_vm[i] == pk_current_vm) return i;
  85. }
  86. return -1;
  87. }
  88. void* py_getvmctx() { return pk_current_vm->ctx; }
  89. void py_setvmctx(void* ctx) { pk_current_vm->ctx = ctx; }
  90. void py_sys_setargv(int argc, char** argv) {
  91. py_GlobalRef sys = py_getmodule("sys");
  92. py_Ref argv_list = py_getdict(sys, py_name("argv"));
  93. py_list_clear(argv_list);
  94. for(int i = 0; i < argc; i++) {
  95. py_newstr(py_list_emplace(argv_list), argv[i]);
  96. }
  97. }
  98. py_Callbacks* py_callbacks() { return &pk_current_vm->callbacks; }
  99. const char* pk_opname(Opcode op) {
  100. const static char* OP_NAMES[] = {
  101. #define OPCODE(name) #name,
  102. #include "pocketpy/xmacros/opcodes.h"
  103. #undef OPCODE
  104. };
  105. return OP_NAMES[op];
  106. }
  107. bool py_call(py_Ref f, int argc, py_Ref argv) {
  108. if(f->type == tp_nativefunc) {
  109. return py_callcfunc(f->_cfunc, argc, argv);
  110. } else {
  111. py_push(f);
  112. py_pushnil();
  113. for(int i = 0; i < argc; i++)
  114. py_push(py_offset(argv, i));
  115. bool ok = py_vectorcall(argc, 0);
  116. return ok;
  117. }
  118. }
  119. #ifndef NDEBUG
  120. bool py_callcfunc(py_CFunction f, int argc, py_Ref argv) {
  121. py_StackRef p0 = py_peek(0);
  122. // NOTE: sometimes users are using `py_retval()` to pass `argv`
  123. // It will be reset to `nil` and cause an exception
  124. py_newnil(py_retval());
  125. bool ok = f(argc, argv);
  126. if(!ok) {
  127. if(!py_checkexc(true)) {
  128. c11__abort("py_CFunction returns `false` but no exception is set!");
  129. }
  130. return false;
  131. }
  132. if(py_peek(0) != p0) {
  133. c11__abort("py_CFunction corrupts the stack! Did you forget to call `py_pop()`?");
  134. }
  135. if(py_isnil(py_retval())) {
  136. c11__abort(
  137. "py_CFunction returns nothing! Did you forget to call `py_newnone(py_retval())`?");
  138. }
  139. if(py_checkexc(true)) {
  140. const char* name = py_tpname(pk_current_vm->curr_exception.type);
  141. c11__abort("py_CFunction returns `true`, but `%s` was set!", name);
  142. }
  143. return true;
  144. }
  145. #endif
  146. bool py_vectorcall(uint16_t argc, uint16_t kwargc) {
  147. return VM__vectorcall(pk_current_vm, argc, kwargc, false) != RES_ERROR;
  148. }
  149. py_Ref py_retval() { return &pk_current_vm->last_retval; }
  150. bool py_pushmethod(py_Name name) {
  151. bool ok = pk_loadmethod(py_peek(-1), name);
  152. if(ok) pk_current_vm->stack.sp++;
  153. return ok;
  154. }
  155. bool pk_loadmethod(py_StackRef self, py_Name name) {
  156. // NOTE: `out` and `out_self` may overlap with `self`
  157. py_Type type;
  158. if(name == __new__) {
  159. // __new__ acts like a @staticmethod
  160. if(self->type == tp_type) {
  161. // T.__new__(...)
  162. type = py_totype(self);
  163. } else if(self->type == tp_super) {
  164. // super(T, obj).__new__(...)
  165. type = *(py_Type*)py_touserdata(self);
  166. } else {
  167. // invalid usage of `__new__`
  168. return false;
  169. }
  170. py_Ref cls_var = py_tpfindmagic(type, name);
  171. if(cls_var) {
  172. self[0] = *cls_var;
  173. self[1] = *py_NIL();
  174. return true;
  175. }
  176. return false;
  177. }
  178. py_TValue self_bak; // to avoid overlapping
  179. // handle super() proxy
  180. if(py_istype(self, tp_super)) {
  181. type = *(py_Type*)py_touserdata(self);
  182. // BUG: here we modify `self` which refers to the stack directly
  183. // If `pk_loadmethod` fails, `self` will be corrupted
  184. self_bak = *py_getslot(self, 0);
  185. } else {
  186. type = self->type;
  187. self_bak = *self;
  188. }
  189. py_Ref cls_var = py_tpfindname(type, name);
  190. if(cls_var != NULL) {
  191. switch(cls_var->type) {
  192. case tp_function:
  193. case tp_nativefunc: {
  194. self[0] = *cls_var;
  195. self[1] = self_bak;
  196. break;
  197. }
  198. case tp_staticmethod:
  199. self[0] = *py_getslot(cls_var, 0);
  200. self[1] = *py_NIL();
  201. break;
  202. case tp_classmethod:
  203. self[0] = *py_getslot(cls_var, 0);
  204. self[1] = pk__type_info(type)->self;
  205. break;
  206. default: c11__unreachable();
  207. }
  208. return true;
  209. }
  210. return false;
  211. }
  212. py_Ref py_tpfindmagic(py_Type t, py_Name name) {
  213. // assert(py_ismagicname(name));
  214. return py_tpfindname(t, name);
  215. }
  216. py_Ref py_tpfindname(py_Type t, py_Name name) {
  217. py_TypeInfo* ti = pk__type_info(t);
  218. do {
  219. py_Ref res = py_getdict(&ti->self, name);
  220. if(res) return res;
  221. ti = ti->base_ti;
  222. } while(ti);
  223. return NULL;
  224. }
  225. py_Type py_tpbase(py_Type t) {
  226. assert(t);
  227. py_TypeInfo* ti = pk__type_info(t);
  228. return py_totype(&ti->base_ti->self);
  229. }
  230. PK_DEPRECATED py_Ref py_tpgetmagic(py_Type type, py_Name name) {
  231. // assert(py_ismagicname(name));
  232. py_TypeInfo* ti = pk__type_info(type);
  233. py_Ref retval = py_getdict(&ti->self, name);
  234. return retval != NULL ? retval : py_NIL();
  235. }
  236. py_Ref py_tpobject(py_Type type) {
  237. assert(type);
  238. return &pk__type_info(type)->self;
  239. }
  240. const char* py_tpname(py_Type type) {
  241. if(!type) return "nil";
  242. py_Name name = pk__type_info(type)->name;
  243. return py_name2str(name);
  244. }
  245. bool py_tpcall(py_Type type, int argc, py_Ref argv) {
  246. return py_call(py_tpobject(type), argc, argv);
  247. }
  248. bool pk_callmagic(py_Name name, int argc, py_Ref argv) {
  249. assert(argc >= 1);
  250. // assert(py_ismagicname(name));
  251. py_Ref tmp = py_tpfindmagic(argv->type, name);
  252. if(!tmp) return AttributeError(argv, name);
  253. return py_call(tmp, argc, argv);
  254. }
  255. bool StopIteration() {
  256. bool ok = py_tpcall(tp_StopIteration, 0, NULL);
  257. if(!ok) return false;
  258. return py_raise(py_retval());
  259. }