vm.c 25 KB

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