vm.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. #include "pocketpy/interpreter/vm.h"
  2. #include "pocketpy/common/memorypool.h"
  3. #include "pocketpy/common/sstream.h"
  4. #include "pocketpy/common/utils.h"
  5. #include "pocketpy/interpreter/generator.h"
  6. #include "pocketpy/interpreter/modules.h"
  7. #include "pocketpy/objects/base.h"
  8. #include "pocketpy/common/_generated.h"
  9. #include "pocketpy/pocketpy.h"
  10. #include <stdbool.h>
  11. static char* pk_default_import_file(const char* path) {
  12. #if PK_ENABLE_OS
  13. FILE* f = fopen(path, "rb");
  14. if(f == NULL) return NULL;
  15. fseek(f, 0, SEEK_END);
  16. long size = ftell(f);
  17. fseek(f, 0, SEEK_SET);
  18. char* buffer = malloc(size + 1);
  19. size = fread(buffer, 1, size, f);
  20. buffer[size] = 0;
  21. fclose(f);
  22. return buffer;
  23. #else
  24. return NULL;
  25. #endif
  26. }
  27. static void pk_default_print(const char* data) { printf("%s", data); }
  28. static void py_TypeInfo__ctor(py_TypeInfo* self,
  29. py_Name name,
  30. py_Type index,
  31. py_Type base,
  32. py_TValue module) {
  33. memset(self, 0, sizeof(py_TypeInfo));
  34. self->name = name;
  35. self->base = base;
  36. // create type object with __dict__
  37. ManagedHeap* heap = &pk_current_vm->heap;
  38. PyObject* typeobj = ManagedHeap__new(heap, tp_type, -1, sizeof(py_Type));
  39. *(py_Type*)PyObject__userdata(typeobj) = index;
  40. self->self = (py_TValue){
  41. .type = typeobj->type,
  42. .is_ptr = true,
  43. ._obj = typeobj,
  44. };
  45. self->module = module;
  46. c11_vector__ctor(&self->annotated_fields, sizeof(py_Name));
  47. }
  48. static void py_TypeInfo__dtor(py_TypeInfo* self) { c11_vector__dtor(&self->annotated_fields); }
  49. void VM__ctor(VM* self) {
  50. self->top_frame = NULL;
  51. ModuleDict__ctor(&self->modules, NULL, *py_NIL);
  52. c11_vector__ctor(&self->types, sizeof(py_TypeInfo));
  53. self->builtins = *py_NIL;
  54. self->main = *py_NIL;
  55. self->ceval_on_step = NULL;
  56. self->import_file = pk_default_import_file;
  57. self->print = pk_default_print;
  58. self->last_retval = *py_NIL;
  59. self->curr_exception = *py_NIL;
  60. self->is_curr_exc_handled = false;
  61. self->is_stopiteration = false;
  62. self->__curr_class = NULL;
  63. ManagedHeap__ctor(&self->heap, self);
  64. ValueStack__ctor(&self->stack);
  65. /* Init Builtin Types */
  66. // 0: unused
  67. void* placeholder = c11_vector__emplace(&self->types);
  68. memset(placeholder, 0, sizeof(py_TypeInfo));
  69. #define validate(t, expr) \
  70. if(t != (expr)) abort()
  71. validate(tp_object, pk_newtype("object", 0, NULL, NULL, true, false));
  72. validate(tp_type, pk_newtype("type", 1, NULL, NULL, false, true));
  73. pk_object__register();
  74. validate(tp_int, pk_newtype("int", tp_object, NULL, NULL, false, true));
  75. validate(tp_float, pk_newtype("float", tp_object, NULL, NULL, false, true));
  76. validate(tp_bool, pk_newtype("bool", tp_object, NULL, NULL, false, true));
  77. pk_number__register();
  78. validate(tp_str, pk_str__register());
  79. validate(tp_str_iterator, pk_str_iterator__register());
  80. validate(tp_list, pk_list__register());
  81. validate(tp_tuple, pk_tuple__register());
  82. validate(tp_array_iterator, pk_array_iterator__register());
  83. validate(tp_slice, pk_slice__register());
  84. validate(tp_range, pk_range__register());
  85. validate(tp_range_iterator, pk_range_iterator__register());
  86. validate(tp_module, pk_newtype("module", tp_object, NULL, NULL, false, true));
  87. validate(tp_function, pk_function__register());
  88. validate(tp_nativefunc, pk_nativefunc__register());
  89. validate(tp_boundmethod, pk_boundmethod__register());
  90. validate(tp_super, pk_super__register());
  91. validate(tp_BaseException, pk_BaseException__register());
  92. validate(tp_Exception, pk_Exception__register());
  93. validate(tp_bytes, pk_bytes__register());
  94. validate(tp_namedict, pk_namedict__register());
  95. validate(tp_locals, pk_locals__register());
  96. validate(tp_code, pk_code__register());
  97. validate(tp_dict, pk_dict__register());
  98. validate(tp_dict_items, pk_dict_items__register());
  99. validate(tp_property, pk_property__register());
  100. validate(tp_star_wrapper, pk_newtype("star_wrapper", tp_object, NULL, NULL, false, true));
  101. validate(tp_staticmethod, pk_staticmethod__register());
  102. validate(tp_classmethod, pk_classmethod__register());
  103. validate(tp_NoneType, pk_newtype("NoneType", tp_object, NULL, NULL, false, true));
  104. validate(tp_NotImplementedType,
  105. pk_newtype("NotImplementedType", tp_object, NULL, NULL, false, true));
  106. validate(tp_ellipsis, pk_newtype("ellipsis", tp_object, NULL, NULL, false, true));
  107. validate(tp_generator, pk_generator__register());
  108. self->builtins = pk_builtins__register();
  109. // inject some builtin expections
  110. #define INJECT_BUILTIN_EXC(name, TBase) \
  111. do { \
  112. py_Type type = pk_newtype(#name, TBase, &self->builtins, NULL, false, true); \
  113. py_setdict(&self->builtins, py_name(#name), py_tpobject(type)); \
  114. validate(tp_##name, type); \
  115. } while(0)
  116. INJECT_BUILTIN_EXC(SystemExit, tp_BaseException);
  117. INJECT_BUILTIN_EXC(KeyboardInterrupt, tp_BaseException);
  118. INJECT_BUILTIN_EXC(StopIteration, tp_Exception);
  119. INJECT_BUILTIN_EXC(SyntaxError, tp_Exception);
  120. INJECT_BUILTIN_EXC(StackOverflowError, tp_Exception);
  121. INJECT_BUILTIN_EXC(IOError, tp_Exception);
  122. INJECT_BUILTIN_EXC(OSError, tp_Exception);
  123. INJECT_BUILTIN_EXC(NotImplementedError, tp_Exception);
  124. INJECT_BUILTIN_EXC(TypeError, tp_Exception);
  125. INJECT_BUILTIN_EXC(IndexError, tp_Exception);
  126. INJECT_BUILTIN_EXC(ValueError, tp_Exception);
  127. INJECT_BUILTIN_EXC(RuntimeError, tp_Exception);
  128. INJECT_BUILTIN_EXC(ZeroDivisionError, tp_Exception);
  129. INJECT_BUILTIN_EXC(NameError, tp_Exception);
  130. INJECT_BUILTIN_EXC(UnboundLocalError, tp_Exception);
  131. INJECT_BUILTIN_EXC(AttributeError, tp_Exception);
  132. INJECT_BUILTIN_EXC(ImportError, tp_Exception);
  133. INJECT_BUILTIN_EXC(AssertionError, tp_Exception);
  134. INJECT_BUILTIN_EXC(KeyError, tp_Exception);
  135. #undef INJECT_BUILTIN_EXC
  136. #undef validate
  137. /* Setup Public Builtin Types */
  138. py_Type public_types[] = {
  139. tp_object,
  140. tp_type,
  141. tp_int,
  142. tp_float,
  143. tp_bool,
  144. tp_str,
  145. tp_list,
  146. tp_tuple,
  147. tp_slice,
  148. tp_range,
  149. tp_bytes,
  150. tp_dict,
  151. tp_property,
  152. tp_staticmethod,
  153. tp_classmethod,
  154. tp_super,
  155. tp_BaseException,
  156. tp_Exception,
  157. };
  158. for(int i = 0; i < c11__count_array(public_types); i++) {
  159. py_TypeInfo* ti = c11__at(py_TypeInfo, &self->types, public_types[i]);
  160. py_setdict(&self->builtins, ti->name, &ti->self);
  161. }
  162. py_newnotimplemented(py_emplacedict(&self->builtins, py_name("NotImplemented")));
  163. // add modules
  164. pk__add_module_pkpy();
  165. pk__add_module_os();
  166. pk__add_module_sys();
  167. pk__add_module_math();
  168. pk__add_module_dis();
  169. pk__add_module_random();
  170. pk__add_module_json();
  171. pk__add_module_gc();
  172. pk__add_module_time();
  173. pk__add_module_easing();
  174. pk__add_module_traceback();
  175. // add python builtins
  176. do {
  177. bool ok;
  178. ok = py_exec(kPythonLibs_builtins, "<builtins>", EXEC_MODE, &self->builtins);
  179. if(!ok) goto __ABORT;
  180. break;
  181. __ABORT:
  182. py_printexc();
  183. c11__abort("failed to load python builtins!");
  184. } while(0);
  185. self->main = *py_newmodule("__main__");
  186. }
  187. void VM__dtor(VM* self) {
  188. // destroy all objects
  189. ManagedHeap__dtor(&self->heap);
  190. // clear frames
  191. while(self->top_frame)
  192. VM__pop_frame(self);
  193. ModuleDict__dtor(&self->modules);
  194. c11__foreach(py_TypeInfo, &self->types, ti) py_TypeInfo__dtor(ti);
  195. c11_vector__dtor(&self->types);
  196. ValueStack__clear(&self->stack);
  197. }
  198. void VM__push_frame(VM* self, Frame* frame) {
  199. frame->f_back = self->top_frame;
  200. self->top_frame = frame;
  201. }
  202. void VM__pop_frame(VM* self) {
  203. assert(self->top_frame);
  204. Frame* frame = self->top_frame;
  205. // reset stack pointer
  206. self->stack.sp = frame->p0;
  207. // pop frame and delete
  208. self->top_frame = frame->f_back;
  209. Frame__delete(frame);
  210. }
  211. static void _clip_int(int* value, int min, int max) {
  212. if(*value < min) *value = min;
  213. if(*value > max) *value = max;
  214. }
  215. bool pk__parse_int_slice(py_Ref slice, int length, int* start, int* stop, int* step) {
  216. py_Ref s_start = py_getslot(slice, 0);
  217. py_Ref s_stop = py_getslot(slice, 1);
  218. py_Ref s_step = py_getslot(slice, 2);
  219. if(py_isnone(s_step))
  220. *step = 1;
  221. else {
  222. if(!py_checkint(s_step)) return false;
  223. *step = py_toint(s_step);
  224. }
  225. if(*step == 0) return ValueError("slice step cannot be zero");
  226. if(*step > 0) {
  227. if(py_isnone(s_start))
  228. *start = 0;
  229. else {
  230. if(!py_checkint(s_start)) return false;
  231. *start = py_toint(s_start);
  232. if(*start < 0) *start += length;
  233. _clip_int(start, 0, length);
  234. }
  235. if(py_isnone(s_stop))
  236. *stop = length;
  237. else {
  238. if(!py_checkint(s_stop)) return false;
  239. *stop = py_toint(s_stop);
  240. if(*stop < 0) *stop += length;
  241. _clip_int(stop, 0, length);
  242. }
  243. } else {
  244. if(py_isnone(s_start))
  245. *start = length - 1;
  246. else {
  247. if(!py_checkint(s_start)) return false;
  248. *start = py_toint(s_start);
  249. if(*start < 0) *start += length;
  250. _clip_int(start, -1, length - 1);
  251. }
  252. if(py_isnone(s_stop))
  253. *stop = -1;
  254. else {
  255. if(!py_checkint(s_stop)) return false;
  256. *stop = py_toint(s_stop);
  257. if(*stop < 0) *stop += length;
  258. _clip_int(stop, -1, length - 1);
  259. }
  260. }
  261. return true;
  262. }
  263. bool pk__normalize_index(int* index, int length) {
  264. if(*index < 0) *index += length;
  265. if(*index < 0 || *index >= length) { return IndexError("%d not in [0, %d)", *index, length); }
  266. return true;
  267. }
  268. py_Type pk_newtype(const char* name,
  269. py_Type base,
  270. const py_GlobalRef module,
  271. void (*dtor)(void*),
  272. bool is_python,
  273. bool is_sealed) {
  274. c11_vector* types = &pk_current_vm->types;
  275. py_Type index = types->length;
  276. py_TypeInfo* ti = c11_vector__emplace(types);
  277. py_TypeInfo* base_ti = base ? c11__at(py_TypeInfo, types, base) : NULL;
  278. if(base_ti && base_ti->is_sealed) {
  279. c11__abort("type '%s' is not an acceptable base type", py_name2str(base_ti->name));
  280. }
  281. py_TypeInfo__ctor(ti, py_name(name), index, base, module ? *module : *py_NIL);
  282. if(!dtor && base) dtor = base_ti->dtor;
  283. ti->dtor = dtor;
  284. ti->is_python = is_python;
  285. ti->is_sealed = is_sealed;
  286. return index;
  287. }
  288. py_Type py_newtype(const char* name, py_Type base, const py_GlobalRef module, void (*dtor)(void*)) {
  289. py_Type type = pk_newtype(name, base, module, dtor, false, false);
  290. if(module) py_setdict(module, py_name(name), py_tpobject(type));
  291. return type;
  292. }
  293. static bool
  294. prepare_py_call(py_TValue* buffer, py_Ref argv, py_Ref p1, int kwargc, const FuncDecl* decl) {
  295. const CodeObject* co = &decl->code;
  296. int decl_argc = decl->args.length;
  297. if(p1 - argv < decl_argc) {
  298. return TypeError("%s() takes %d positional arguments but %d were given",
  299. co->name->data,
  300. decl_argc,
  301. p1 - argv);
  302. }
  303. py_TValue* t = argv;
  304. // prepare args
  305. memset(buffer, 0, co->nlocals * sizeof(py_TValue));
  306. c11__foreach(int, &decl->args, index) buffer[*index] = *t++;
  307. // prepare kwdefaults
  308. c11__foreach(FuncDeclKwArg, &decl->kwargs, kv) buffer[kv->index] = kv->value;
  309. // handle *args
  310. if(decl->starred_arg != -1) {
  311. int exceed_argc = p1 - t;
  312. py_Ref vargs = &buffer[decl->starred_arg];
  313. py_newtuple(vargs, exceed_argc);
  314. for(int j = 0; j < exceed_argc; j++) {
  315. py_tuple_setitem(vargs, j, t++);
  316. }
  317. } else {
  318. // kwdefaults override
  319. // def f(a, b, c=None)
  320. // f(1, 2, 3) -> c=3
  321. c11__foreach(FuncDeclKwArg, &decl->kwargs, kv) {
  322. if(t >= p1) break;
  323. buffer[kv->index] = *t++;
  324. }
  325. // not able to consume all args
  326. if(t < p1) return TypeError("too many arguments (%s)", co->name->data);
  327. }
  328. if(decl->starred_kwarg != -1) py_newdict(&buffer[decl->starred_kwarg]);
  329. for(int j = 0; j < kwargc; j++) {
  330. py_Name key = py_toint(&p1[2 * j]);
  331. int index = c11_smallmap_n2i__get(&decl->kw_to_index, key, -1);
  332. // if key is an explicit key, set as local variable
  333. if(index >= 0) {
  334. buffer[index] = p1[2 * j + 1];
  335. } else {
  336. // otherwise, set as **kwargs if possible
  337. if(decl->starred_kwarg == -1) {
  338. return TypeError("'%n' is an invalid keyword argument for %s()",
  339. key,
  340. co->name->data);
  341. } else {
  342. // add to **kwargs
  343. bool ok = py_dict_setitem_by_str(&buffer[decl->starred_kwarg],
  344. py_name2str(key),
  345. &p1[2 * j + 1]);
  346. if(!ok) return false;
  347. }
  348. }
  349. }
  350. return true;
  351. }
  352. FrameResult VM__vectorcall(VM* self, uint16_t argc, uint16_t kwargc, bool opcall) {
  353. pk_print_stack(self, self->top_frame, (Bytecode){0});
  354. py_Ref p1 = self->stack.sp - kwargc * 2;
  355. py_Ref p0 = p1 - argc - 2;
  356. // [callable, <self>, args..., kwargs...]
  357. // ^p0 ^p1 ^_sp
  358. // handle boundmethod, do a patch
  359. if(p0->type == tp_boundmethod) {
  360. assert(py_isnil(p0 + 1)); // self must be NULL
  361. py_TValue* slots = PyObject__slots(p0->_obj);
  362. p0[0] = slots[1]; // callable
  363. p0[1] = slots[0]; // self
  364. // [unbound, self, args..., kwargs...]
  365. }
  366. py_Ref argv = py_isnil(p0 + 1) ? p0 + 2 : p0 + 1;
  367. if(p0->type == tp_function) {
  368. /*****************_py_call*****************/
  369. // check stack overflow
  370. if(self->stack.sp > self->stack.end) {
  371. py_exception(tp_StackOverflowError, "");
  372. return RES_ERROR;
  373. }
  374. Function* fn = py_touserdata(p0);
  375. const CodeObject* co = &fn->decl->code;
  376. switch(fn->decl->type) {
  377. case FuncType_NORMAL: {
  378. bool ok = prepare_py_call(self->__vectorcall_buffer, argv, p1, kwargc, fn->decl);
  379. if(!ok) return RES_ERROR;
  380. // copy buffer back to stack
  381. self->stack.sp = argv + co->nlocals;
  382. memcpy(argv, self->__vectorcall_buffer, co->nlocals * sizeof(py_TValue));
  383. // submit the call
  384. if(!fn->cfunc) {
  385. VM__push_frame(self, Frame__new(co, &fn->module, p0, argv, true));
  386. return opcall ? RES_CALL : VM__run_top_frame(self);
  387. } else {
  388. bool ok = py_callcfunc(fn->cfunc, co->nlocals, argv);
  389. self->stack.sp = p0;
  390. return ok ? RES_RETURN : RES_ERROR;
  391. }
  392. }
  393. case FuncType_SIMPLE:
  394. if(p1 - argv != fn->decl->args.length) {
  395. const char* fmt = "%s() takes %d positional arguments but %d were given";
  396. TypeError(fmt, co->name->data, fn->decl->args.length, p1 - argv);
  397. return RES_ERROR;
  398. }
  399. if(kwargc) {
  400. TypeError("%s() takes no keyword arguments", co->name->data);
  401. return RES_ERROR;
  402. }
  403. // [callable, <self>, args..., local_vars...]
  404. // ^p0 ^p1 ^_sp
  405. self->stack.sp = argv + co->nlocals;
  406. // initialize local variables to py_NIL
  407. memset(p1, 0, (char*)self->stack.sp - (char*)p1);
  408. // submit the call
  409. VM__push_frame(self, Frame__new(co, &fn->module, p0, argv, true));
  410. return opcall ? RES_CALL : VM__run_top_frame(self);
  411. case FuncType_GENERATOR: {
  412. bool ok = prepare_py_call(self->__vectorcall_buffer, argv, p1, kwargc, fn->decl);
  413. if(!ok) return RES_ERROR;
  414. Frame* frame = Frame__new(co, &fn->module, p0, argv, false);
  415. pk_newgenerator(py_retval(), frame, self->__vectorcall_buffer, co->nlocals);
  416. self->stack.sp = p0;
  417. return RES_RETURN;
  418. }
  419. default: c11__unreachedable();
  420. };
  421. c11__unreachedable();
  422. /*****************_py_call*****************/
  423. }
  424. if(p0->type == tp_nativefunc) {
  425. bool ok = py_callcfunc(p0->_cfunc, p1 - argv, argv);
  426. self->stack.sp = p0;
  427. return ok ? RES_RETURN : RES_ERROR;
  428. }
  429. if(p0->type == tp_type) {
  430. // [cls, NULL, args..., kwargs...]
  431. py_Ref new_f = py_tpfindmagic(py_totype(p0), __new__);
  432. assert(new_f && py_isnil(p0 + 1));
  433. // prepare a copy of args and kwargs
  434. int span = self->stack.sp - argv;
  435. *self->stack.sp++ = *new_f; // push __new__
  436. *self->stack.sp++ = *p0; // push cls
  437. memcpy(self->stack.sp, argv, span * sizeof(py_TValue));
  438. self->stack.sp += span;
  439. // [new_f, cls, args..., kwargs...]
  440. if(VM__vectorcall(self, argc, kwargc, false) == RES_ERROR) return RES_ERROR;
  441. // by recursively using vectorcall, args and kwargs are consumed
  442. // try __init__
  443. // NOTE: previously we use `get_unbound_method` but here we just use `tpfindmagic`
  444. // >> [cls, NULL, args..., kwargs...]
  445. // >> py_retval() is the new instance
  446. py_Ref init_f = py_tpfindmagic(py_totype(p0), __init__);
  447. if(init_f) {
  448. // do an inplace patch
  449. *p0 = *init_f; // __init__
  450. p0[1] = self->last_retval; // self
  451. // [__init__, self, args..., kwargs...]
  452. if(VM__vectorcall(self, argc, kwargc, false) == RES_ERROR) return RES_ERROR;
  453. *py_retval() = p0[1]; // restore the new instance
  454. }
  455. // reset the stack
  456. self->stack.sp = p0;
  457. return RES_RETURN;
  458. }
  459. // handle `__call__` overload
  460. if(pk_loadmethod(p0, __call__)) {
  461. // [__call__, self, args..., kwargs...]
  462. return VM__vectorcall(self, argc, kwargc, opcall);
  463. }
  464. TypeError("'%t' object is not callable", p0->type);
  465. return RES_ERROR;
  466. }
  467. /****************************************/
  468. void PyObject__delete(PyObject* self) {
  469. py_TypeInfo* ti = c11__at(py_TypeInfo, &pk_current_vm->types, self->type);
  470. if(ti->dtor) ti->dtor(PyObject__userdata(self));
  471. if(self->slots == -1) NameDict__dtor(PyObject__dict(self));
  472. if(self->gc_is_large) {
  473. free(self);
  474. } else {
  475. PoolObject_dealloc(self);
  476. }
  477. }
  478. static void mark_object(PyObject* obj);
  479. void pk__mark_value(py_TValue* val) {
  480. if(val->is_ptr) mark_object(val->_obj);
  481. }
  482. void pk__mark_namedict(NameDict* dict) {
  483. for(int i = 0; i < dict->length; i++) {
  484. NameDict_KV* kv = c11__at(NameDict_KV, dict, i);
  485. pk__mark_value(&kv->value);
  486. }
  487. }
  488. void pk__tp_set_marker(py_Type type, void (*gc_mark)(void*)) {
  489. py_TypeInfo* ti = c11__at(py_TypeInfo, &pk_current_vm->types, type);
  490. assert(ti->gc_mark == NULL);
  491. ti->gc_mark = gc_mark;
  492. }
  493. static void mark_object(PyObject* obj) {
  494. if(obj->gc_marked) return;
  495. obj->gc_marked = true;
  496. if(obj->slots > 0) {
  497. py_TValue* p = PyObject__slots(obj);
  498. for(int i = 0; i < obj->slots; i++)
  499. pk__mark_value(p + i);
  500. } else if(obj->slots == -1) {
  501. NameDict* dict = PyObject__dict(obj);
  502. pk__mark_namedict(dict);
  503. }
  504. py_TypeInfo* types = c11__at(py_TypeInfo, &pk_current_vm->types, obj->type);
  505. if(types->gc_mark) types->gc_mark(PyObject__userdata(obj));
  506. }
  507. void CodeObject__gc_mark(const CodeObject* self) {
  508. c11__foreach(py_TValue, &self->consts, i) { pk__mark_value(i); }
  509. c11__foreach(FuncDecl_, &self->func_decls, i) { CodeObject__gc_mark(&(*i)->code); }
  510. }
  511. void ManagedHeap__mark(ManagedHeap* self) {
  512. VM* vm = self->vm;
  513. // mark heap objects
  514. for(int i = 0; i < self->no_gc.length; i++) {
  515. PyObject* obj = c11__getitem(PyObject*, &self->no_gc, i);
  516. mark_object(obj);
  517. }
  518. // mark value stack
  519. for(py_TValue* p = vm->stack.begin; p != vm->stack.end; p++) {
  520. pk__mark_value(p);
  521. }
  522. // mark magic slots
  523. py_TypeInfo* types = vm->types.data;
  524. int types_length = vm->types.length;
  525. // 0-th type is placeholder
  526. for(int i = 1; i < types_length; i++) {
  527. for(int j = 0; j <= __missing__; j++) {
  528. py_TValue* slot = types[i].magic + j;
  529. if(py_isnil(slot)) continue;
  530. pk__mark_value(slot);
  531. }
  532. }
  533. // mark frame
  534. for(Frame* frame = vm->top_frame; frame; frame = frame->f_back) {
  535. Frame__gc_mark(frame);
  536. }
  537. // mark vm's registers
  538. pk__mark_value(&vm->last_retval);
  539. pk__mark_value(&vm->curr_exception);
  540. for(int i = 0; i < c11__count_array(vm->reg); i++) {
  541. pk__mark_value(&vm->reg[i]);
  542. }
  543. }
  544. void pk_print_stack(VM* self, Frame* frame, Bytecode byte) {
  545. return;
  546. if(frame == NULL || py_isnil(&self->main)) return;
  547. py_TValue* sp = self->stack.sp;
  548. c11_sbuf buf;
  549. c11_sbuf__ctor(&buf);
  550. for(py_Ref p = self->stack.begin; p != sp; p++) {
  551. switch(p->type) {
  552. case 0: c11_sbuf__write_cstr(&buf, "nil"); break;
  553. case tp_int: c11_sbuf__write_i64(&buf, p->_i64); break;
  554. case tp_float: c11_sbuf__write_f64(&buf, p->_f64, -1); break;
  555. case tp_bool: c11_sbuf__write_cstr(&buf, p->_bool ? "True" : "False"); break;
  556. case tp_NoneType: c11_sbuf__write_cstr(&buf, "None"); break;
  557. case tp_list: {
  558. pk_sprintf(&buf, "list(%d)", py_list_len(p));
  559. break;
  560. }
  561. case tp_tuple: {
  562. pk_sprintf(&buf, "tuple(%d)", py_tuple_len(p));
  563. break;
  564. }
  565. case tp_function: {
  566. Function* ud = py_touserdata(p);
  567. c11_sbuf__write_cstr(&buf, ud->decl->code.name->data);
  568. c11_sbuf__write_cstr(&buf, "()");
  569. break;
  570. }
  571. case tp_type: {
  572. pk_sprintf(&buf, "<class '%t'>", py_totype(p));
  573. break;
  574. }
  575. case tp_str: {
  576. pk_sprintf(&buf, "%q", py_tosv(p));
  577. break;
  578. }
  579. case tp_module: {
  580. py_Ref path = py_getdict(p, __path__);
  581. pk_sprintf(&buf, "<module '%v'>", py_tosv(path));
  582. break;
  583. }
  584. default: {
  585. pk_sprintf(&buf, "(%t)", p->type);
  586. break;
  587. }
  588. }
  589. if(p != &sp[-1]) c11_sbuf__write_cstr(&buf, ", ");
  590. }
  591. c11_string* stack_str = c11_sbuf__submit(&buf);
  592. printf("%s:%-3d: %-25s %-6d [%s]\n",
  593. frame->co->src->filename->data,
  594. Frame__lineno(frame),
  595. pk_opname(byte.op),
  596. byte.arg,
  597. stack_str->data);
  598. c11_string__delete(stack_str);
  599. }
  600. bool pk_wrapper__self(int argc, py_Ref argv) {
  601. PY_CHECK_ARGC(1);
  602. py_assign(py_retval(), argv);
  603. return true;
  604. }
  605. bool pk_wrapper__NotImplementedError(int argc, py_Ref argv) {
  606. return py_exception(tp_NotImplementedError, "");
  607. }