vm.c 22 KB

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