vm.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. #include "pocketpy/objects/codeobject.h"
  2. #include "pocketpy/objects/sourcedata.h"
  3. #include "pocketpy/pocketpy.h"
  4. #include "pocketpy/common/utils.h"
  5. #include "pocketpy/common/sstream.h"
  6. #include "pocketpy/objects/object.h"
  7. #include "pocketpy/interpreter/vm.h"
  8. #include "pocketpy/compiler/compiler.h"
  9. #include <stdint.h>
  10. pk_VM* pk_current_vm;
  11. static pk_VM pk_default_vm;
  12. void py_initialize() {
  13. pk_MemoryPools__initialize();
  14. py_Name__initialize();
  15. pk_current_vm = &pk_default_vm;
  16. pk_VM__ctor(&pk_default_vm);
  17. }
  18. void py_finalize() {
  19. pk_VM__dtor(&pk_default_vm);
  20. pk_current_vm = NULL;
  21. py_Name__finalize();
  22. pk_MemoryPools__finalize();
  23. }
  24. const char* pk_opname(Opcode op) {
  25. const static char* OP_NAMES[] = {
  26. #define OPCODE(name) #name,
  27. #include "pocketpy/xmacros/opcodes.h"
  28. #undef OPCODE
  29. };
  30. return OP_NAMES[op];
  31. }
  32. py_TValue* pk_arrayview(py_Ref self, int* length) {
  33. if(self->type == tp_list) {
  34. *length = py_list__len(self);
  35. return py_list__getitem(self, 0);
  36. }
  37. if(self->type == tp_tuple) {
  38. *length = py_tuple__len(self);
  39. return py_tuple__getitem(self, 0);
  40. }
  41. return NULL;
  42. }
  43. static void disassemble(CodeObject* co) {
  44. c11_vector /*T=int*/ jumpTargets;
  45. c11_vector__ctor(&jumpTargets, sizeof(int));
  46. for(int i = 0; i < co->codes.count; i++) {
  47. Bytecode* bc = c11__at(Bytecode, &co->codes, i);
  48. if(Bytecode__is_forward_jump(bc)) {
  49. int target = (int16_t)bc->arg + i;
  50. c11_vector__push(int, &jumpTargets, target);
  51. }
  52. }
  53. c11_sbuf ss;
  54. c11_sbuf__ctor(&ss);
  55. int prev_line = -1;
  56. for(int i = 0; i < co->codes.count; i++) {
  57. Bytecode byte = c11__getitem(Bytecode, &co->codes, i);
  58. BytecodeEx ex = c11__getitem(BytecodeEx, &co->codes_ex, i);
  59. char line[8] = "";
  60. if(ex.lineno == prev_line) {
  61. // do nothing
  62. } else {
  63. snprintf(line, sizeof(line), "%d", ex.lineno);
  64. if(prev_line != -1) c11_sbuf__write_char(&ss, '\n');
  65. prev_line = ex.lineno;
  66. }
  67. char pointer[4] = "";
  68. c11__foreach(int, &jumpTargets, it) {
  69. if(*it == i) {
  70. snprintf(pointer, sizeof(pointer), "->");
  71. break;
  72. }
  73. }
  74. char buf[32];
  75. snprintf(buf, sizeof(buf), "%-8s%-3s%-3d ", line, pointer, i);
  76. c11_sbuf__write_cstr(&ss, buf);
  77. c11_sbuf__write_cstr(&ss, pk_opname(byte.op));
  78. c11_sbuf__write_char(&ss, ex.is_virtual ? '*' : ' ');
  79. int padding = 24 - strlen(pk_opname(byte.op));
  80. for(int j = 0; j < padding; j++)
  81. c11_sbuf__write_char(&ss, ' ');
  82. // _opcode_argstr(this, i, byte, co);
  83. do {
  84. if(Bytecode__is_forward_jump(&byte)) {
  85. c11_sbuf__write_int(&ss, (int16_t)byte.arg);
  86. c11_sbuf__write_cstr(&ss, " (to ");
  87. c11_sbuf__write_int(&ss, (int16_t)byte.arg + i);
  88. c11_sbuf__write_char(&ss, ')');
  89. break;
  90. }
  91. c11_sbuf__write_int(&ss, byte.arg);
  92. switch(byte.op) {
  93. case OP_LOAD_CONST:
  94. case OP_FORMAT_STRING:
  95. case OP_IMPORT_PATH: {
  96. py_Ref tmp = c11__at(py_TValue, &co->consts, byte.arg);
  97. c11_sbuf__write_cstr(&ss, " (");
  98. // here we need to use py_repr, however this function is not ready yet
  99. c11_sbuf__write_cstr(&ss, "<class '");
  100. c11_sbuf__write_cstr(&ss, py_tpname(tmp->type));
  101. c11_sbuf__write_cstr(&ss, "'>)");
  102. break;
  103. }
  104. case OP_LOAD_NAME:
  105. case OP_LOAD_GLOBAL:
  106. case OP_LOAD_NONLOCAL:
  107. case OP_STORE_GLOBAL:
  108. case OP_LOAD_ATTR:
  109. case OP_LOAD_METHOD:
  110. case OP_STORE_ATTR:
  111. case OP_DELETE_ATTR:
  112. case OP_BEGIN_CLASS:
  113. case OP_GOTO:
  114. case OP_DELETE_GLOBAL:
  115. case OP_STORE_CLASS_ATTR:
  116. case OP_FOR_ITER_STORE_GLOBAL: {
  117. c11_sbuf__write_cstr(&ss, " (");
  118. c11_sbuf__write_cstr(&ss, py_name2str(byte.arg));
  119. c11_sbuf__write_char(&ss, ')');
  120. break;
  121. }
  122. case OP_LOAD_FAST:
  123. case OP_STORE_FAST:
  124. case OP_DELETE_FAST:
  125. case OP_FOR_ITER_STORE_FAST: {
  126. py_Name name = c11__getitem(py_Name, &co->varnames, byte.arg);
  127. c11_sbuf__write_cstr(&ss, " (");
  128. c11_sbuf__write_cstr(&ss, py_name2str(name));
  129. c11_sbuf__write_char(&ss, ')');
  130. break;
  131. }
  132. case OP_LOAD_FUNCTION: {
  133. const FuncDecl* decl = c11__getitem(FuncDecl*, &co->func_decls, byte.arg);
  134. c11_sbuf__write_cstr(&ss, " (");
  135. c11_sbuf__write_cstr(&ss, decl->code.name->data);
  136. c11_sbuf__write_char(&ss, ')');
  137. break;
  138. }
  139. case OP_BINARY_OP: {
  140. py_Name name = byte.arg & 0xFF;
  141. c11_sbuf__write_cstr(&ss, " (");
  142. c11_sbuf__write_cstr(&ss, py_name2str(name));
  143. c11_sbuf__write_char(&ss, ')');
  144. break;
  145. }
  146. }
  147. } while(0);
  148. if(i != co->codes.count - 1) c11_sbuf__write_char(&ss, '\n');
  149. }
  150. c11_string* output = c11_sbuf__submit(&ss);
  151. pk_current_vm->_stdout("%s\n", output->data);
  152. c11_string__delete(output);
  153. c11_vector__dtor(&jumpTargets);
  154. }
  155. static bool
  156. pk_VM__exec(pk_VM* vm, const char* source, const char* filename, enum CompileMode mode) {
  157. CodeObject co;
  158. pk_SourceData_ src = pk_SourceData__rcnew(source, filename, mode, false);
  159. Error* err = pk_compile(src, &co);
  160. if(err) {
  161. PK_DECREF(src);
  162. return false;
  163. }
  164. // disassemble(&co);
  165. Frame* frame = Frame__new(&co, vm->main._obj, NULL, vm->stack.sp, vm->stack.sp, &co);
  166. pk_VM__push_frame(vm, frame);
  167. pk_FrameResult res = pk_VM__run_top_frame(vm);
  168. CodeObject__dtor(&co);
  169. PK_DECREF(src);
  170. if(res == RES_ERROR) return false;
  171. if(res == RES_RETURN) return true;
  172. c11__unreachedable();
  173. }
  174. bool py_exec(const char* source) { return pk_VM__exec(pk_current_vm, source, "<exec>", EXEC_MODE); }
  175. bool py_eval(const char* source) { return pk_VM__exec(pk_current_vm, source, "<eval>", EVAL_MODE); }
  176. bool py_exec2(const char* source, const char* filename, enum CompileMode mode) {
  177. return pk_VM__exec(pk_current_vm, source, filename, mode);
  178. }
  179. bool py_call(py_Ref f, int argc, py_Ref argv) {
  180. if(f->type == tp_nativefunc) {
  181. return f->_cfunc(argc, argv);
  182. } else {
  183. pk_VM* vm = pk_current_vm;
  184. py_push(f);
  185. py_pushnil();
  186. for(int i = 0; i < argc; i++)
  187. py_push(py_offset(argv, i));
  188. pk_FrameResult res = pk_VM__vectorcall(vm, argc, 0, false);
  189. assert(res == RES_ERROR || res == RES_RETURN);
  190. return res == RES_RETURN;
  191. }
  192. }
  193. bool py_callmethod(py_Ref self, py_Name name, int argc, py_Ref argv) { return -1; }
  194. bool py_vectorcall(uint16_t argc, uint16_t kwargc) {
  195. pk_VM* vm = pk_current_vm;
  196. return pk_VM__vectorcall(vm, argc, kwargc, false) == RES_ERROR;
  197. }
  198. py_Ref py_retval() { return &pk_current_vm->last_retval; }
  199. bool py_getunboundmethod(py_Ref self, py_Name name, py_Ref out, py_Ref out_self) {
  200. // NOTE: `out` and `out_self` may overlap with `self`
  201. py_Type type;
  202. // handle super() proxy
  203. if(py_istype(self, tp_super)) {
  204. self = py_getslot(self, 0);
  205. type = *(py_Type*)py_touserdata(self);
  206. } else {
  207. type = self->type;
  208. }
  209. py_Ref cls_var = py_tpfindname(type, name);
  210. if(cls_var != NULL) {
  211. switch(cls_var->type) {
  212. case tp_function:
  213. case tp_nativefunc: {
  214. py_TValue self_bak = *self;
  215. // `out` may overlap with `self`. If we assign `out`, `self` may be corrupted.
  216. *out = *cls_var;
  217. *out_self = self_bak;
  218. break;
  219. }
  220. case tp_staticmethod:
  221. *out = *py_getslot(cls_var, 0);
  222. py_newnil(out_self);
  223. break;
  224. case tp_classmethod:
  225. *out = *py_getslot(cls_var, 0);
  226. *out_self = c11__getitem(pk_TypeInfo, &pk_current_vm->types, type).self;
  227. break;
  228. default: c11__unreachedable();
  229. }
  230. return true;
  231. }
  232. // TODO: __getattr__ fallback
  233. return false;
  234. }
  235. pk_TypeInfo* pk_tpinfo(const py_Ref self) {
  236. pk_VM* vm = pk_current_vm;
  237. return c11__at(pk_TypeInfo, &vm->types, self->type);
  238. }
  239. py_Ref py_tpfindmagic(py_Type t, py_Name name) {
  240. assert(py_ismagicname(name));
  241. pk_TypeInfo* types = (pk_TypeInfo*)pk_current_vm->types.data;
  242. do {
  243. py_Ref f = &types[t].magic[name];
  244. if(!py_isnil(f)) return f;
  245. t = types[t].base;
  246. } while(t);
  247. return NULL;
  248. }
  249. py_Ref py_tpfindname(py_Type t, py_Name name) {
  250. pk_TypeInfo* types = (pk_TypeInfo*)pk_current_vm->types.data;
  251. do {
  252. py_Ref res = py_getdict(&types[t].self, name);
  253. if(res) return res;
  254. t = types[t].base;
  255. } while(t);
  256. return NULL;
  257. }
  258. py_Ref py_tpmagic(py_Type type, py_Name name) {
  259. assert(py_ismagicname(name));
  260. pk_VM* vm = pk_current_vm;
  261. return &c11__at(pk_TypeInfo, &vm->types, type)->magic[name];
  262. }
  263. py_Ref py_tpobject(py_Type type) {
  264. pk_VM* vm = pk_current_vm;
  265. return &c11__at(pk_TypeInfo, &vm->types, type)->self;
  266. }
  267. const char* py_tpname(py_Type type) {
  268. if(!type) return "nil";
  269. pk_VM* vm = pk_current_vm;
  270. py_Name name = c11__at(pk_TypeInfo, &vm->types, type)->name;
  271. return py_name2str(name);
  272. }
  273. bool py_tpcall(py_Type type, int argc, py_Ref argv) {
  274. return py_call(py_tpobject(type), argc, argv);
  275. }
  276. bool py_callmagic(py_Name name, int argc, py_Ref argv) {
  277. assert(argc >= 1);
  278. assert(py_ismagicname(name));
  279. py_Ref tmp = py_tpfindmagic(argv->type, name);
  280. if(!tmp) return AttributeError(argv, name);
  281. return py_call(tmp, argc, argv);
  282. }
  283. bool StopIteration() {
  284. pk_VM* vm = pk_current_vm;
  285. assert(!vm->is_stopiteration); // flag is already set
  286. vm->is_stopiteration = true;
  287. return false;
  288. }