ceval.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. #include "pocketpy/common/config.h"
  2. #include "pocketpy/common/utils.h"
  3. #include "pocketpy/interpreter/frame.h"
  4. #include "pocketpy/interpreter/vm.h"
  5. #include "pocketpy/common/memorypool.h"
  6. #include "pocketpy/common/sstream.h"
  7. #include "pocketpy/objects/codeobject.h"
  8. #include "pocketpy/pocketpy.h"
  9. #include "pocketpy/objects/error.h"
  10. #include <stdbool.h>
  11. static bool stack_unpack_sequence(pk_VM* self, uint16_t arg);
  12. static bool format_object(py_Ref obj, c11_sv spec);
  13. #define DISPATCH() \
  14. do { \
  15. frame->ip++; \
  16. goto __NEXT_STEP; \
  17. } while(0)
  18. #define DISPATCH_JUMP(__offset) \
  19. do { \
  20. frame->ip += __offset; \
  21. goto __NEXT_STEP; \
  22. } while(0)
  23. #define DISPATCH_JUMP_ABSOLUTE(__target) \
  24. do { \
  25. frame->ip = c11__at(Bytecode, &frame->co->codes, __target); \
  26. goto __NEXT_STEP; \
  27. } while(0)
  28. /* Stack manipulation macros */
  29. // https://github.com/python/cpython/blob/3.9/Python/ceval.c#L1123
  30. #define TOP() (self->stack.sp - 1)
  31. #define SECOND() (self->stack.sp - 2)
  32. #define THIRD() (self->stack.sp - 3)
  33. #define FOURTH() (self->stack.sp - 4)
  34. #define STACK_SHRINK(n) (self->stack.sp -= n)
  35. #define STACK_GROW(n) (self->stack.sp += n)
  36. #define PUSH(v) \
  37. do { \
  38. *self->stack.sp = *(v); \
  39. self->stack.sp++; \
  40. } while(0)
  41. #define POP() (--self->stack.sp)
  42. #define POPX() (*--self->stack.sp)
  43. #define SP() (self->stack.sp)
  44. // [a, b] -> [?, a, b]
  45. #define INSERT_THIRD() \
  46. do { \
  47. PUSH(TOP()); \
  48. *SECOND() = *THIRD(); \
  49. } while(0)
  50. #define vectorcall_opcall(argc, kwargc) \
  51. do { \
  52. pk_FrameResult res = pk_VM__vectorcall(self, (argc), (kwargc), true); \
  53. switch(res) { \
  54. case RES_RETURN: PUSH(&self->last_retval); break; \
  55. case RES_CALL: frame = self->top_frame; goto __NEXT_FRAME; \
  56. case RES_ERROR: goto __ERROR; \
  57. default: c11__unreachedable(); \
  58. } \
  59. } while(0)
  60. static bool unpack_dict_to_buffer(py_Ref key, py_Ref val, void* ctx) {
  61. py_TValue** p = ctx;
  62. if(py_isstr(key)) {
  63. py_Name name = py_namev(py_tosv(key));
  64. py_newint(*p, name);
  65. py_assign(*p + 1, val);
  66. (*p) += 2;
  67. return true;
  68. }
  69. return TypeError("keywords must be strings, not '%t'", key->type);
  70. }
  71. pk_FrameResult pk_VM__run_top_frame(pk_VM* self) {
  72. Frame* frame = self->top_frame;
  73. const Frame* base_frame = frame;
  74. while(true) {
  75. Bytecode byte;
  76. __NEXT_FRAME:
  77. frame->ip++;
  78. __NEXT_STEP:
  79. byte = *frame->ip;
  80. pk_print_stack(self, frame, byte);
  81. switch((Opcode)byte.op) {
  82. case OP_NO_OP: DISPATCH();
  83. /*****************************************/
  84. case OP_POP_TOP: POP(); DISPATCH();
  85. case OP_DUP_TOP: PUSH(TOP()); DISPATCH();
  86. case OP_DUP_TOP_TWO:
  87. // [a, b]
  88. PUSH(SECOND()); // [a, b, a]
  89. PUSH(SECOND()); // [a, b, a, b]
  90. DISPATCH();
  91. case OP_ROT_TWO: {
  92. py_TValue tmp = *TOP();
  93. *TOP() = *SECOND();
  94. *SECOND() = tmp;
  95. DISPATCH();
  96. }
  97. case OP_ROT_THREE: {
  98. // [a, b, c] -> [c, a, b]
  99. py_TValue tmp = *TOP();
  100. *TOP() = *SECOND();
  101. *SECOND() = *THIRD();
  102. *THIRD() = tmp;
  103. DISPATCH();
  104. }
  105. case OP_PRINT_EXPR:
  106. if(TOP()->type != tp_NoneType) {
  107. bool ok = py_repr(TOP());
  108. if(!ok) goto __ERROR;
  109. self->print(py_tostr(&self->last_retval));
  110. self->print("\n");
  111. }
  112. POP();
  113. DISPATCH();
  114. /*****************************************/
  115. case OP_LOAD_CONST: PUSH(c11__at(py_TValue, &frame->co->consts, byte.arg)); DISPATCH();
  116. case OP_LOAD_NONE: py_newnone(SP()++); DISPATCH();
  117. case OP_LOAD_TRUE: py_newbool(SP()++, true); DISPATCH();
  118. case OP_LOAD_FALSE: py_newbool(SP()++, false); DISPATCH();
  119. /*****************************************/
  120. case OP_LOAD_SMALL_INT: py_newint(SP()++, (int16_t)byte.arg); DISPATCH();
  121. /*****************************************/
  122. case OP_LOAD_ELLIPSIS: py_newellipsis(SP()++); DISPATCH();
  123. case OP_LOAD_FUNCTION: {
  124. FuncDecl_ decl = c11__getitem(FuncDecl_, &frame->co->func_decls, byte.arg);
  125. Function* ud = py_newobject(SP(), tp_function, 0, sizeof(Function));
  126. Function__ctor(ud, decl, &frame->module);
  127. if(decl->nested) {
  128. ud->closure = FastLocals__to_namedict(frame->locals, frame->locals_co);
  129. py_Name name = py_namev(c11_string__sv(decl->code.name));
  130. // capture itself to allow recursion
  131. pk_NameDict__set(ud->closure, name, *SP());
  132. }
  133. SP()++;
  134. DISPATCH();
  135. }
  136. case OP_LOAD_NULL:
  137. py_newnil(SP()++);
  138. DISPATCH();
  139. /*****************************************/
  140. case OP_LOAD_FAST: {
  141. PUSH(&frame->locals[byte.arg]);
  142. if(py_isnil(TOP())) {
  143. py_Name name = c11__getitem(uint16_t, &frame->co->varnames, byte.arg);
  144. UnboundLocalError(name);
  145. goto __ERROR;
  146. }
  147. DISPATCH();
  148. }
  149. case OP_LOAD_NAME: {
  150. py_Name name = byte.arg;
  151. py_Ref tmp = Frame__f_locals_try_get(frame, name);
  152. if(tmp != NULL) {
  153. if(py_isnil(tmp)) {
  154. UnboundLocalError(name);
  155. goto __ERROR;
  156. }
  157. PUSH(tmp);
  158. DISPATCH();
  159. }
  160. tmp = Frame__f_closure_try_get(frame, name);
  161. if(tmp != NULL) {
  162. PUSH(tmp);
  163. DISPATCH();
  164. }
  165. tmp = py_getdict(&frame->module, name);
  166. if(tmp != NULL) {
  167. PUSH(tmp);
  168. DISPATCH();
  169. }
  170. tmp = py_getdict(&self->builtins, name);
  171. if(tmp != NULL) {
  172. PUSH(tmp);
  173. DISPATCH();
  174. }
  175. NameError(name);
  176. goto __ERROR;
  177. }
  178. case OP_LOAD_NONLOCAL: {
  179. py_Name name = byte.arg;
  180. py_Ref tmp = Frame__f_closure_try_get(frame, name);
  181. if(tmp != NULL) {
  182. PUSH(tmp);
  183. DISPATCH();
  184. }
  185. tmp = py_getdict(&frame->module, name);
  186. if(tmp != NULL) {
  187. PUSH(tmp);
  188. DISPATCH();
  189. }
  190. tmp = py_getdict(&self->builtins, name);
  191. if(tmp != NULL) {
  192. PUSH(tmp);
  193. DISPATCH();
  194. }
  195. NameError(name);
  196. goto __ERROR;
  197. }
  198. case OP_LOAD_GLOBAL: {
  199. py_Name name = byte.arg;
  200. py_Ref tmp = py_getdict(&frame->module, name);
  201. if(tmp != NULL) {
  202. PUSH(tmp);
  203. DISPATCH();
  204. }
  205. tmp = py_getdict(&self->builtins, name);
  206. if(tmp != NULL) {
  207. PUSH(tmp);
  208. DISPATCH();
  209. }
  210. NameError(name);
  211. goto __ERROR;
  212. }
  213. case OP_LOAD_ATTR: {
  214. if(py_getattr(TOP(), byte.arg)) {
  215. py_assign(TOP(), py_retval());
  216. } else {
  217. goto __ERROR;
  218. }
  219. DISPATCH();
  220. }
  221. case OP_LOAD_CLASS_GLOBAL: {
  222. py_Name name = byte.arg;
  223. py_Ref tmp = py_getdict(self->__curr_class, name);
  224. if(tmp) {
  225. PUSH(tmp);
  226. DISPATCH();
  227. }
  228. // load global if attribute not found
  229. tmp = py_getdict(&frame->module, name);
  230. if(tmp) {
  231. PUSH(tmp);
  232. DISPATCH();
  233. }
  234. tmp = py_getdict(&self->builtins, name);
  235. if(tmp) {
  236. PUSH(tmp);
  237. DISPATCH();
  238. }
  239. NameError(name);
  240. goto __ERROR;
  241. }
  242. case OP_LOAD_METHOD: {
  243. // [self] -> [unbound, self]
  244. bool ok = py_pushmethod(byte.arg);
  245. if(!ok) {
  246. // fallback to getattr
  247. if(py_getattr(TOP(), byte.arg)) {
  248. py_assign(TOP(), py_retval());
  249. } else {
  250. goto __ERROR;
  251. }
  252. }
  253. DISPATCH();
  254. }
  255. case OP_LOAD_SUBSCR: {
  256. // [a, b] -> a[b]
  257. py_Ref magic = py_tpfindmagic(SECOND()->type, __getitem__);
  258. if(magic) {
  259. if(magic->type == tp_nativefunc) {
  260. py_TValue* p0 = TOP();
  261. if(!py_callcfunc(p0, magic->_cfunc, 2, SECOND())) goto __ERROR;
  262. *TOP() = self->last_retval;
  263. } else {
  264. INSERT_THIRD(); // [?, a, b]
  265. *THIRD() = *magic; // [__getitem__, a, b]
  266. if(!py_vectorcall(1, 0)) goto __ERROR;
  267. }
  268. DISPATCH();
  269. }
  270. TypeError("'%t' object is not subscriptable", SECOND()->type);
  271. goto __ERROR;
  272. }
  273. case OP_STORE_FAST: frame->locals[byte.arg] = POPX(); DISPATCH();
  274. case OP_STORE_NAME: {
  275. py_Name name = byte.arg;
  276. if(frame->function) {
  277. py_Ref slot = Frame__f_locals_try_get(frame, name);
  278. if(slot != NULL) {
  279. *slot = *TOP(); // store in locals if possible
  280. } else {
  281. // Function& func = frame->_callable->as<Function>();
  282. // if(func.decl == __dynamic_func_decl) {
  283. // assert(func._closure != nullptr);
  284. // func._closure->set(_name, _0);
  285. // } else {
  286. // NameError(_name);
  287. // goto __ERROR;
  288. // }
  289. }
  290. } else {
  291. py_setdict(&frame->module, name, TOP());
  292. }
  293. POP();
  294. DISPATCH();
  295. }
  296. case OP_STORE_GLOBAL: {
  297. py_setdict(&frame->module, byte.arg, TOP());
  298. POP();
  299. DISPATCH();
  300. }
  301. case OP_STORE_ATTR: {
  302. // [val, a] -> a.b = val
  303. if(!py_setattr(TOP(), byte.arg, SECOND())) goto __ERROR;
  304. STACK_SHRINK(2);
  305. DISPATCH();
  306. }
  307. case OP_STORE_SUBSCR: {
  308. // [val, a, b] -> a[b] = val
  309. py_Ref magic = py_tpfindmagic(SECOND()->type, __setitem__);
  310. if(magic) {
  311. PUSH(THIRD()); // [val, a, b, val]
  312. if(magic->type == tp_nativefunc) {
  313. py_TValue* p0 = FOURTH();
  314. if(!py_callcfunc(p0, magic->_cfunc, 3, THIRD())) goto __ERROR;
  315. } else {
  316. *FOURTH() = *magic; // [__selitem__, a, b, val]
  317. if(!py_vectorcall(2, 0)) goto __ERROR;
  318. POP(); // discard retval
  319. }
  320. DISPATCH();
  321. }
  322. TypeError("'%t' object does not support item assignment", SECOND()->type);
  323. goto __ERROR;
  324. }
  325. case OP_DELETE_FAST: {
  326. py_Ref tmp = &frame->locals[byte.arg];
  327. if(py_isnil(tmp)) {
  328. py_Name name = c11__getitem(py_Name, &frame->co->varnames, byte.arg);
  329. UnboundLocalError(name);
  330. goto __ERROR;
  331. }
  332. py_newnil(tmp);
  333. DISPATCH();
  334. }
  335. case OP_DELETE_NAME: {
  336. py_Name name = byte.arg;
  337. if(frame->function) {
  338. py_TValue* slot = Frame__f_locals_try_get(frame, name);
  339. if(slot) {
  340. py_newnil(slot);
  341. } else {
  342. // Function& func = frame->_callable->as<Function>();
  343. // if(func.decl == __dynamic_func_decl) {
  344. // assert(func._closure != nullptr);
  345. // bool ok = func._closure->del(_name);
  346. // if(!ok) vm->NameError(_name);
  347. // } else {
  348. // vm->NameError(_name);
  349. // }
  350. }
  351. } else {
  352. bool ok = py_deldict(&frame->module, name);
  353. if(!ok) {
  354. NameError(name);
  355. goto __ERROR;
  356. }
  357. }
  358. DISPATCH();
  359. }
  360. case OP_DELETE_GLOBAL: {
  361. py_Name name = byte.arg;
  362. bool ok = py_deldict(&frame->module, name);
  363. if(!ok) {
  364. NameError(name);
  365. goto __ERROR;
  366. }
  367. DISPATCH();
  368. }
  369. case OP_DELETE_ATTR: {
  370. if(!py_delattr(TOP(), byte.arg)) goto __ERROR;
  371. DISPATCH();
  372. }
  373. case OP_DELETE_SUBSCR: {
  374. // [a, b] -> del a[b]
  375. py_Ref magic = py_tpfindmagic(SECOND()->type, __delitem__);
  376. if(magic) {
  377. if(magic->type == tp_nativefunc) {
  378. py_TValue* p0 = SECOND();
  379. if(!py_callcfunc(p0, magic->_cfunc, 2, SECOND())) goto __ERROR;
  380. } else {
  381. INSERT_THIRD(); // [?, a, b]
  382. *THIRD() = *magic; // [__delitem__, a, b]
  383. if(!py_vectorcall(1, 0)) goto __ERROR;
  384. POP(); // discard retval
  385. }
  386. DISPATCH();
  387. }
  388. TypeError("'%t' object does not support item deletion", SECOND()->type);
  389. goto __ERROR;
  390. }
  391. /*****************************************/
  392. case OP_BUILD_LONG: {
  393. // [x]
  394. py_Ref f = py_getdict(&self->builtins, py_name("long"));
  395. assert(f != NULL);
  396. if(!py_call(f, 1, TOP())) goto __ERROR;
  397. *TOP() = self->last_retval;
  398. DISPATCH();
  399. }
  400. case OP_BUILD_IMAG: {
  401. // [x]
  402. py_Ref f = py_getdict(&self->builtins, py_name("complex"));
  403. assert(f != NULL);
  404. py_TValue tmp = *TOP();
  405. *TOP() = *f; // [complex]
  406. py_newnil(SP()++); // [complex, NULL]
  407. py_newint(SP()++, 0); // [complex, NULL, 0]
  408. *SP()++ = tmp; // [complex, NULL, 0, x]
  409. if(!py_vectorcall(2, 0)) goto __ERROR;
  410. DISPATCH();
  411. }
  412. case OP_BUILD_BYTES: {
  413. int size;
  414. const char* data = py_tostrn(TOP(), &size);
  415. unsigned char* p = py_newbytes(TOP(), size);
  416. memcpy(p, data, size);
  417. DISPATCH();
  418. }
  419. case OP_BUILD_TUPLE: {
  420. py_TValue tmp;
  421. py_newtuple(&tmp, byte.arg);
  422. py_TValue* begin = SP() - byte.arg;
  423. for(int i = 0; i < byte.arg; i++) {
  424. py_tuple__setitem(&tmp, i, begin + i);
  425. }
  426. SP() = begin;
  427. PUSH(&tmp);
  428. DISPATCH();
  429. }
  430. case OP_BUILD_LIST: {
  431. py_TValue tmp;
  432. py_newlistn(&tmp, byte.arg);
  433. py_TValue* begin = SP() - byte.arg;
  434. for(int i = 0; i < byte.arg; i++) {
  435. py_list__setitem(&tmp, i, begin + i);
  436. }
  437. SP() = begin;
  438. PUSH(&tmp);
  439. DISPATCH();
  440. }
  441. case OP_BUILD_DICT: {
  442. py_TValue* begin = SP() - byte.arg * 2;
  443. py_Ref tmp = py_pushtmp();
  444. py_newdict(tmp);
  445. for(int i = 0; i < byte.arg * 2; i += 2) {
  446. py_dict__setitem(tmp, begin + i, begin + i + 1);
  447. if(py_checkexc()) goto __ERROR;
  448. }
  449. SP() = begin;
  450. PUSH(tmp);
  451. DISPATCH();
  452. }
  453. case OP_BUILD_SET: {
  454. py_TValue* begin = SP() - byte.arg;
  455. py_Ref typeobject_set = py_getdict(&self->builtins, py_name("set"));
  456. assert(typeobject_set != NULL);
  457. py_push(typeobject_set);
  458. py_pushnil();
  459. if(!py_vectorcall(0, 0)) goto __ERROR;
  460. py_push(py_retval()); // empty set
  461. py_Name id_add = py_name("add");
  462. for(int i = 0; i < byte.arg; i++) {
  463. if(!py_callmethod(TOP(), id_add, 1, begin + i)) goto __ERROR;
  464. }
  465. py_TValue tmp = *TOP();
  466. SP() = begin;
  467. PUSH(&tmp);
  468. DISPATCH();
  469. }
  470. case OP_BUILD_SLICE: {
  471. // [start, stop, step]
  472. py_TValue tmp;
  473. py_newslice(&tmp);
  474. py_setslot(&tmp, 0, THIRD());
  475. py_setslot(&tmp, 1, SECOND());
  476. py_setslot(&tmp, 2, TOP());
  477. STACK_SHRINK(3);
  478. PUSH(&tmp);
  479. DISPATCH();
  480. }
  481. case OP_BUILD_STRING: {
  482. py_TValue* begin = SP() - byte.arg;
  483. c11_sbuf ss;
  484. c11_sbuf__ctor(&ss);
  485. for(int i = 0; i < byte.arg; i++) {
  486. if(!py_str(begin + i)) goto __ERROR;
  487. c11_sbuf__write_sv(&ss, py_tosv(&self->last_retval));
  488. }
  489. SP() = begin;
  490. c11_string* res = c11_sbuf__submit(&ss);
  491. py_newstrn(SP()++, res->data, res->size);
  492. c11_string__delete(res);
  493. DISPATCH();
  494. }
  495. /*****************************/
  496. case OP_BINARY_OP: {
  497. py_Name op = byte.arg & 0xFF;
  498. py_Name rop = byte.arg >> 8;
  499. if(!pk_stack_binaryop(self, op, rop)) goto __ERROR;
  500. POP();
  501. *TOP() = self->last_retval;
  502. DISPATCH();
  503. }
  504. case OP_IS_OP: {
  505. bool res = py_isidentical(SECOND(), TOP());
  506. POP();
  507. if(byte.arg) res = !res;
  508. py_newbool(TOP(), res);
  509. DISPATCH();
  510. }
  511. case OP_CONTAINS_OP: {
  512. // [b, a] -> b __contains__ a (a in b) -> [retval]
  513. py_Ref magic = py_tpfindmagic(SECOND()->type, __contains__);
  514. if(magic) {
  515. if(magic->type == tp_nativefunc) {
  516. py_TValue* p0 = TOP();
  517. if(!py_callcfunc(p0, magic->_cfunc, 2, SECOND())) goto __ERROR;
  518. *TOP() = self->last_retval;
  519. } else {
  520. INSERT_THIRD(); // [?, b, a]
  521. *THIRD() = *magic; // [__contains__, a, b]
  522. if(!py_vectorcall(1, 0)) goto __ERROR;
  523. }
  524. bool res = py_tobool(TOP());
  525. if(byte.arg) py_newbool(TOP(), !res);
  526. DISPATCH();
  527. }
  528. TypeError("'%t' type does not support '__contains__'", SECOND()->type);
  529. goto __ERROR;
  530. }
  531. /*****************************************/
  532. case OP_JUMP_FORWARD: DISPATCH_JUMP((int16_t)byte.arg);
  533. case OP_POP_JUMP_IF_FALSE: {
  534. int res = py_bool(TOP());
  535. if(res < 0) goto __ERROR;
  536. POP();
  537. if(!res) DISPATCH_JUMP((int16_t)byte.arg);
  538. DISPATCH();
  539. }
  540. case OP_POP_JUMP_IF_TRUE: {
  541. int res = py_bool(TOP());
  542. if(res < 0) goto __ERROR;
  543. POP();
  544. if(res) DISPATCH_JUMP((int16_t)byte.arg);
  545. DISPATCH();
  546. }
  547. case OP_JUMP_IF_TRUE_OR_POP: {
  548. int res = py_bool(TOP());
  549. if(res < 0) goto __ERROR;
  550. if(res) {
  551. DISPATCH_JUMP((int16_t)byte.arg);
  552. } else {
  553. POP();
  554. DISPATCH();
  555. }
  556. }
  557. case OP_JUMP_IF_FALSE_OR_POP: {
  558. int res = py_bool(TOP());
  559. if(res < 0) goto __ERROR;
  560. if(!res) {
  561. DISPATCH_JUMP((int16_t)byte.arg);
  562. } else {
  563. POP();
  564. DISPATCH();
  565. }
  566. }
  567. case OP_SHORTCUT_IF_FALSE_OR_POP: {
  568. int res = py_bool(TOP());
  569. if(res < 0) goto __ERROR;
  570. if(!res) { // [b, False]
  571. STACK_SHRINK(2); // []
  572. py_newbool(SP()++, false); // [False]
  573. DISPATCH_JUMP((int16_t)byte.arg);
  574. } else {
  575. POP(); // [b]
  576. DISPATCH();
  577. }
  578. }
  579. case OP_LOOP_CONTINUE:
  580. // just an alias of OP_JUMP_FORWARD
  581. DISPATCH_JUMP((int16_t)byte.arg);
  582. case OP_LOOP_BREAK: {
  583. int target = Frame__ip(frame) + byte.arg;
  584. Frame__prepare_jump_break(frame, &self->stack, target);
  585. DISPATCH_JUMP((int16_t)byte.arg);
  586. }
  587. case OP_JUMP_ABSOLUTE_TOP: {
  588. int target = py_toint(TOP());
  589. POP();
  590. DISPATCH_JUMP_ABSOLUTE(target);
  591. }
  592. case OP_GOTO: {
  593. int target = c11_smallmap_n2i__get(&frame->co->labels, byte.arg, -1);
  594. if(target < 0) {
  595. RuntimeError("label '%n' not found", byte.arg);
  596. goto __ERROR;
  597. }
  598. Frame__prepare_jump_break(frame, &self->stack, target);
  599. DISPATCH_JUMP_ABSOLUTE(target);
  600. }
  601. /*****************************************/
  602. case OP_REPR: {
  603. if(!py_repr(TOP())) goto __ERROR;
  604. py_assign(TOP(), py_retval());
  605. DISPATCH();
  606. }
  607. case OP_CALL: {
  608. pk_ManagedHeap__collect_if_needed(&self->heap);
  609. vectorcall_opcall(byte.arg & 0xFF, byte.arg >> 8);
  610. DISPATCH();
  611. }
  612. case OP_CALL_VARGS: {
  613. // [_0, _1, _2 | k1, v1, k2, v2]
  614. uint16_t argc = byte.arg & 0xFF;
  615. uint16_t kwargc = byte.arg >> 8;
  616. int n = 0;
  617. py_TValue* sp = SP();
  618. py_TValue* p1 = sp - kwargc * 2;
  619. py_TValue* base = p1 - argc;
  620. py_TValue* buf = self->__vectorcall_buffer;
  621. for(py_TValue* curr = base; curr != p1; curr++) {
  622. if(curr->type != tp_star_wrapper) {
  623. buf[n++] = *curr;
  624. } else {
  625. py_TValue* args = py_getslot(curr, 0);
  626. int length;
  627. py_TValue* p = pk_arrayview(args, &length);
  628. if(p) {
  629. for(int j = 0; j < length; j++) {
  630. buf[n++] = p[j];
  631. }
  632. argc += length - 1;
  633. } else {
  634. TypeError("*args must be a list or tuple, got '%t'", args->type);
  635. goto __ERROR;
  636. }
  637. }
  638. }
  639. for(py_TValue* curr = p1; curr != sp; curr += 2) {
  640. if(curr[1].type != tp_star_wrapper) {
  641. buf[n++] = curr[0];
  642. buf[n++] = curr[1];
  643. } else {
  644. assert(py_toint(&curr[0]) == 0);
  645. py_TValue* kwargs = py_getslot(&curr[1], 0);
  646. if(kwargs->type == tp_dict) {
  647. py_TValue* p = buf + n;
  648. if(!py_dict__apply(kwargs, unpack_dict_to_buffer, &p)) goto __ERROR;
  649. n = p - buf;
  650. kwargc += py_dict__len(kwargs) - 1;
  651. } else {
  652. TypeError("**kwargs must be a dict, got '%t'", kwargs->type);
  653. goto __ERROR;
  654. }
  655. }
  656. }
  657. memcpy(base, buf, n * sizeof(py_TValue));
  658. SP() = base + n;
  659. vectorcall_opcall(argc, kwargc);
  660. DISPATCH();
  661. }
  662. case OP_RETURN_VALUE: {
  663. if(byte.arg == BC_NOARG) {
  664. self->last_retval = POPX();
  665. } else {
  666. py_newnone(&self->last_retval);
  667. }
  668. pk_VM__pop_frame(self);
  669. if(frame == base_frame) { // [ frameBase<- ]
  670. return RES_RETURN;
  671. } else {
  672. frame = self->top_frame;
  673. PUSH(&self->last_retval);
  674. goto __NEXT_FRAME;
  675. }
  676. DISPATCH();
  677. }
  678. case OP_YIELD_VALUE: {
  679. assert(false);
  680. }
  681. /////////
  682. case OP_LIST_APPEND: {
  683. // [list, iter, value]
  684. py_list__append(THIRD(), TOP());
  685. POP();
  686. DISPATCH();
  687. }
  688. case OP_DICT_ADD: {
  689. // [dict, iter, key, value]
  690. py_dict__setitem(FOURTH(), SECOND(), TOP());
  691. if(py_checkexc()) goto __ERROR;
  692. STACK_SHRINK(2);
  693. DISPATCH();
  694. }
  695. case OP_SET_ADD: {
  696. DISPATCH();
  697. }
  698. /////////
  699. case OP_UNARY_NEGATIVE: {
  700. if(!pk_callmagic(__neg__, 1, TOP())) goto __ERROR;
  701. *TOP() = self->last_retval;
  702. DISPATCH();
  703. }
  704. case OP_UNARY_NOT: {
  705. int res = py_bool(TOP());
  706. if(res < 0) goto __ERROR;
  707. py_newbool(TOP(), !res);
  708. DISPATCH();
  709. }
  710. case OP_UNARY_STAR: {
  711. py_TValue value = POPX();
  712. int* level = py_newobject(SP()++, tp_star_wrapper, 1, sizeof(int));
  713. *level = byte.arg;
  714. py_setslot(TOP(), 0, &value);
  715. DISPATCH();
  716. }
  717. case OP_UNARY_INVERT: {
  718. if(!pk_callmagic(__invert__, 1, TOP())) goto __ERROR;
  719. *TOP() = self->last_retval;
  720. DISPATCH();
  721. }
  722. ////////////////
  723. case OP_GET_ITER: {
  724. if(!py_iter(TOP())) goto __ERROR;
  725. *TOP() = *py_retval();
  726. DISPATCH();
  727. }
  728. case OP_FOR_ITER: {
  729. int res = py_next(TOP());
  730. if(res == -1) goto __ERROR;
  731. if(res) {
  732. PUSH(py_retval());
  733. DISPATCH();
  734. } else {
  735. int target = Frame__prepare_loop_break(frame, &self->stack);
  736. DISPATCH_JUMP_ABSOLUTE(target);
  737. }
  738. }
  739. ////////
  740. case OP_UNPACK_SEQUENCE: {
  741. if(!stack_unpack_sequence(self, byte.arg)) goto __ERROR;
  742. DISPATCH();
  743. }
  744. case OP_UNPACK_EX: {
  745. int length;
  746. py_TValue* p = pk_arrayview(TOP(), &length);
  747. if(!p) {
  748. TypeError("expected list or tuple to unpack, got '%t'", TOP()->type);
  749. goto __ERROR;
  750. }
  751. int exceed = length - byte.arg;
  752. if(exceed < 0) {
  753. ValueError("not enough values to unpack");
  754. goto __ERROR;
  755. }
  756. POP();
  757. for(int i = 0; i < byte.arg; i++) {
  758. PUSH(p + i);
  759. }
  760. py_newlistn(SP()++, exceed);
  761. for(int i = 0; i < exceed; i++) {
  762. py_list__setitem(TOP(), i, p + byte.arg + i);
  763. }
  764. DISPATCH();
  765. }
  766. ///////////
  767. case OP_BEGIN_CLASS: {
  768. // [base]
  769. py_Name name = byte.arg;
  770. py_Type base;
  771. if(py_isnone(TOP())) {
  772. base = tp_object;
  773. } else {
  774. if(!py_checktype(TOP(), tp_type)) goto __ERROR;
  775. base = py_totype(TOP());
  776. }
  777. POP();
  778. py_Type type =
  779. pk_newtype(py_name2str(name), base, &frame->module, NULL, true, false);
  780. PUSH(py_tpobject(type));
  781. self->__curr_class = TOP();
  782. DISPATCH();
  783. }
  784. case OP_END_CLASS: {
  785. // [cls or decorated]
  786. py_Name name = byte.arg;
  787. // set into f_globals
  788. py_setdict(&frame->module, name, TOP());
  789. if(py_istype(TOP(), tp_type)) {
  790. // call on_end_subclass
  791. pk_TypeInfo* ti = c11__at(pk_TypeInfo, &self->types, py_totype(TOP()));
  792. if(ti->base != tp_object) {
  793. // PyTypeInfo* base_ti = &_all_types[ti->base];
  794. pk_TypeInfo* base_ti = c11__at(pk_TypeInfo, &self->types, ti->base);
  795. if(base_ti->on_end_subclass) base_ti->on_end_subclass(ti);
  796. }
  797. }
  798. POP();
  799. self->__curr_class = NULL;
  800. DISPATCH();
  801. }
  802. case OP_STORE_CLASS_ATTR: {
  803. py_Name name = byte.arg;
  804. if(py_istype(TOP(), tp_function)) {
  805. Function* ud = py_touserdata(TOP());
  806. ud->clazz = self->__curr_class->_obj;
  807. }
  808. py_setdict(self->__curr_class, name, TOP());
  809. POP();
  810. DISPATCH();
  811. }
  812. case OP_ADD_CLASS_ANNOTATION: {
  813. py_Type type = py_totype(self->__curr_class);
  814. pk_TypeInfo* ti = c11__at(pk_TypeInfo, &self->types, type);
  815. c11_vector__push(py_Name, &ti->annotated_fields, byte.arg);
  816. DISPATCH();
  817. }
  818. ///////////
  819. case OP_TRY_ENTER: {
  820. Frame__set_unwind_target(frame, SP());
  821. DISPATCH();
  822. }
  823. case OP_EXCEPTION_MATCH: {
  824. if(!py_checktype(TOP(), tp_type)) goto __ERROR;
  825. bool ok = py_isinstance(&self->curr_exception, py_totype(TOP()));
  826. py_newbool(TOP(), ok);
  827. DISPATCH();
  828. }
  829. case OP_RAISE: {
  830. // [exception]
  831. if(py_istype(TOP(), tp_type)) {
  832. if(!py_tpcall(py_totype(TOP()), 0, NULL)) goto __ERROR;
  833. py_assign(TOP(), py_retval());
  834. }
  835. if(!py_isinstance(TOP(), tp_BaseException)) {
  836. TypeError("exceptions must derive from BaseException");
  837. goto __ERROR;
  838. }
  839. py_raise(TOP());
  840. goto __ERROR;
  841. }
  842. case OP_RAISE_ASSERT: {
  843. if(byte.arg) {
  844. if(!py_str(TOP())) goto __ERROR;
  845. POP();
  846. py_exception("AssertionError", "%s", py_tostr(py_retval()));
  847. } else {
  848. py_exception("AssertionError", "");
  849. }
  850. goto __ERROR;
  851. }
  852. case OP_RE_RAISE: {
  853. assert(self->curr_exception.type);
  854. goto __ERROR_RE_RAISE;
  855. }
  856. case OP_PUSH_EXCEPTION: {
  857. assert(self->curr_exception.type);
  858. PUSH(&self->curr_exception);
  859. DISPATCH();
  860. }
  861. case OP_POP_EXCEPTION: {
  862. assert(self->curr_exception.type);
  863. self->curr_exception = *py_NIL;
  864. DISPATCH();
  865. }
  866. //////////////////
  867. case OP_FSTRING_EVAL: {
  868. py_TValue* tmp = c11__at(py_TValue, &frame->co->consts, byte.arg);
  869. const char* string = py_tostr(tmp);
  870. // TODO: optimize this
  871. if(!py_exec(string, "<eval>", EVAL_MODE, &frame->module)) goto __ERROR;
  872. PUSH(py_retval());
  873. DISPATCH();
  874. }
  875. case OP_FORMAT_STRING: {
  876. py_Ref spec = c11__at(py_TValue, &frame->co->consts, byte.arg);
  877. bool ok = format_object(TOP(), py_tosv(spec));
  878. if(!ok) goto __ERROR;
  879. py_assign(TOP(), py_retval());
  880. DISPATCH();
  881. }
  882. default: c11__unreachedable();
  883. }
  884. c11__unreachedable();
  885. __ERROR:
  886. pk_print_stack(self, frame, (Bytecode){0});
  887. py_BaseException__set_lineno(&self->curr_exception, Frame__lineno(frame), frame->co);
  888. __ERROR_RE_RAISE:
  889. do {} while(0);
  890. //printf("error.op: %s, line: %d\n", pk_opname(byte.op), Frame__lineno(frame));
  891. int lineno = py_BaseException__get_lineno(&self->curr_exception, frame->co);
  892. py_BaseException__stpush(&self->curr_exception,
  893. frame->co->src,
  894. lineno < 0 ? Frame__lineno(frame) : lineno,
  895. frame->function ? frame->co->name->data : NULL);
  896. int target = Frame__prepare_jump_exception_handler(frame, &self->stack);
  897. if(target >= 0) {
  898. // 1. Exception can be handled inside the current frame
  899. DISPATCH_JUMP_ABSOLUTE(target);
  900. } else {
  901. // 2. Exception need to be propagated to the upper frame
  902. bool is_base_frame_to_be_popped = frame == base_frame;
  903. pk_VM__pop_frame(self);
  904. if(self->top_frame == NULL || is_base_frame_to_be_popped) {
  905. // propagate to the top level
  906. return RES_ERROR;
  907. }
  908. frame = self->top_frame;
  909. goto __ERROR;
  910. }
  911. }
  912. return RES_RETURN;
  913. }
  914. bool pk_stack_binaryop(pk_VM* self, py_Name op, py_Name rop) {
  915. // [a, b]
  916. py_Ref magic = py_tpfindmagic(SECOND()->type, op);
  917. if(magic) {
  918. bool ok = py_call(magic, 2, SECOND());
  919. if(!ok) return false;
  920. if(self->last_retval.type != tp_NotImplementedType) return true;
  921. }
  922. // try reverse operation
  923. if(rop) {
  924. // [a, b] -> [b, a]
  925. py_TValue tmp = *TOP();
  926. *TOP() = *SECOND();
  927. *SECOND() = tmp;
  928. magic = py_tpfindmagic(SECOND()->type, rop);
  929. if(magic) {
  930. bool ok = py_call(magic, 2, SECOND());
  931. if(!ok) return false;
  932. if(self->last_retval.type != tp_NotImplementedType) return true;
  933. }
  934. }
  935. // eq/ne op never fails
  936. if(op == __eq__ || op == __ne__) {
  937. bool res = py_isidentical(SECOND(), TOP());
  938. py_newbool(py_retval(), res);
  939. return true;
  940. }
  941. return py_exception("TypeError", "unsupported operand type(s) for '%n'", op);
  942. }
  943. bool py_binaryop(py_Ref lhs, py_Ref rhs, py_Name op, py_Name rop) {
  944. pk_VM* self = pk_current_vm;
  945. PUSH(lhs);
  946. PUSH(rhs);
  947. bool ok = pk_stack_binaryop(self, op, rop);
  948. STACK_SHRINK(2);
  949. return ok;
  950. }
  951. static bool stack_unpack_sequence(pk_VM* self, uint16_t arg) {
  952. int length;
  953. py_TValue* p = pk_arrayview(TOP(), &length);
  954. if(!p) return TypeError("expected list or tuple to unpack, got '%t'", TOP()->type);
  955. if(length != arg) return ValueError("expected %d values to unpack, got %d", arg, length);
  956. POP();
  957. for(int i = 0; i < length; i++) {
  958. PUSH(p + i);
  959. }
  960. return true;
  961. }
  962. static bool format_object(py_Ref val, c11_sv spec) {
  963. if(spec.size == 0) return py_str(val);
  964. char type;
  965. switch(spec.data[spec.size - 1]) {
  966. case 'f':
  967. case 'd':
  968. case 's':
  969. type = spec.data[spec.size - 1];
  970. spec.size--; // remove last char
  971. break;
  972. default: type = ' '; break;
  973. }
  974. char pad_c = ' ';
  975. if(strchr("0-=*#@!~", spec.data[0])) {
  976. pad_c = spec.data[0];
  977. spec = c11_sv__slice(spec, 1);
  978. }
  979. char align;
  980. if(spec.data[0] == '^') {
  981. align = '^';
  982. spec = c11_sv__slice(spec, 1);
  983. } else if(spec.data[0] == '>') {
  984. align = '>';
  985. spec = c11_sv__slice(spec, 1);
  986. } else if(spec.data[0] == '<') {
  987. align = '<';
  988. spec = c11_sv__slice(spec, 1);
  989. } else {
  990. align = (py_isint(val) || py_isfloat(val)) ? '>' : '<';
  991. }
  992. int dot = c11_sv__index(spec, '.');
  993. py_i64 width, precision;
  994. if(dot >= 0) {
  995. if(dot == 0) {
  996. // {.2f}
  997. width = -1;
  998. } else {
  999. // {10.2f}
  1000. IntParsingResult res = c11__parse_uint(c11_sv__slice2(spec, 0, dot), &width, 10);
  1001. if(res != IntParsing_SUCCESS) return ValueError("invalid format specifer");
  1002. }
  1003. IntParsingResult res = c11__parse_uint(c11_sv__slice(spec, dot + 1), &precision, 10);
  1004. if(res != IntParsing_SUCCESS) return ValueError("invalid format specifer");
  1005. } else {
  1006. // {10s}
  1007. IntParsingResult res = c11__parse_uint(spec, &width, 10);
  1008. if(res != IntParsing_SUCCESS) return ValueError("invalid format specifer");
  1009. precision = -1;
  1010. }
  1011. if(type != 'f' && dot >= 0) {
  1012. return ValueError("precision not allowed in the format specifier");
  1013. }
  1014. c11_sbuf buf;
  1015. c11_sbuf__ctor(&buf);
  1016. if(type == 'f') {
  1017. py_f64 x;
  1018. if(!py_castfloat(val, &x)) {
  1019. c11_sbuf__dtor(&buf);
  1020. return false;
  1021. }
  1022. if(precision < 0) precision = 6;
  1023. c11_sbuf__write_f64(&buf, x, precision);
  1024. } else if(type == 'd') {
  1025. if(!py_checkint(val)) {
  1026. c11_sbuf__dtor(&buf);
  1027. return false;
  1028. }
  1029. c11_sbuf__write_i64(&buf, py_toint(val));
  1030. } else if(type == 's') {
  1031. if(!py_checkstr(val)) {
  1032. c11_sbuf__dtor(&buf);
  1033. return false;
  1034. }
  1035. c11_sbuf__write_sv(&buf, py_tosv(val));
  1036. } else {
  1037. if(!py_str(val)) {
  1038. c11_sbuf__dtor(&buf);
  1039. return false;
  1040. }
  1041. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  1042. }
  1043. c11_string* body = c11_sbuf__submit(&buf);
  1044. int length = c11_sv__u8_length(c11_string__sv(body));
  1045. c11_sbuf__ctor(&buf); // reinit sbuf
  1046. if(width != -1 && width > length) {
  1047. switch(align) {
  1048. case '>': {
  1049. c11_sbuf__write_pad(&buf, width - length, pad_c);
  1050. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  1051. break;
  1052. }
  1053. case '<': {
  1054. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  1055. c11_sbuf__write_pad(&buf, width - length, pad_c);
  1056. break;
  1057. }
  1058. case '^': {
  1059. int pad_left = (width - length) / 2;
  1060. int pad_right = (width - length) - pad_left;
  1061. c11_sbuf__write_pad(&buf, pad_left, pad_c);
  1062. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  1063. c11_sbuf__write_pad(&buf, pad_right, pad_c);
  1064. break;
  1065. }
  1066. default: c11__unreachedable();
  1067. }
  1068. } else {
  1069. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  1070. }
  1071. c11_string__delete(body);
  1072. c11_string* res = c11_sbuf__submit(&buf);
  1073. py_newstrn(py_retval(), res->data, res->size);
  1074. c11_string__delete(res);
  1075. return true;
  1076. }