ceval.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. #include "pocketpy/interpreter/vm.h"
  2. #include "pocketpy/common/memorypool.h"
  3. #include "pocketpy/common/sstream.h"
  4. #include "pocketpy/objects/codeobject.h"
  5. #include "pocketpy/pocketpy.h"
  6. #include <stdbool.h>
  7. static bool stack_binaryop(pk_VM* self, py_Name op, py_Name rop);
  8. #define DISPATCH() \
  9. do { \
  10. frame->ip++; \
  11. goto __NEXT_STEP; \
  12. } while(0)
  13. #define DISPATCH_JUMP(__offset) \
  14. do { \
  15. frame->ip += __offset; \
  16. goto __NEXT_STEP; \
  17. } while(0)
  18. #define DISPATCH_JUMP_ABSOLUTE(__target) \
  19. do { \
  20. frame->ip = c11__at(Bytecode, &frame->co->codes, __target); \
  21. goto __NEXT_STEP; \
  22. } while(0)
  23. /* Stack manipulation macros */
  24. // https://github.com/python/cpython/blob/3.9/Python/ceval.c#L1123
  25. #define TOP() (self->stack.sp - 1)
  26. #define SECOND() (self->stack.sp - 2)
  27. #define THIRD() (self->stack.sp - 3)
  28. #define FOURTH() (self->stack.sp - 4)
  29. #define STACK_SHRINK(n) (self->stack.sp -= n)
  30. #define PUSH(v) (*self->stack.sp++ = *v)
  31. #define POP() (--self->stack.sp)
  32. #define POPX() (*--self->stack.sp)
  33. #define SP() (self->stack.sp)
  34. // [a, b] -> [?, a, b]
  35. #define INSERT_THIRD() \
  36. do { \
  37. PUSH(TOP()); \
  38. *SECOND() = *THIRD(); \
  39. } while(0)
  40. #define vectorcall_opcall(argc, kwargc) \
  41. do { \
  42. pk_FrameResult res = pk_VM__vectorcall(self, (argc), (kwargc), true); \
  43. switch(res) { \
  44. case RES_RETURN: PUSH(&self->last_retval); break; \
  45. case RES_CALL: \
  46. frame = self->top_frame; \
  47. PUSH(&self->last_retval); \
  48. goto __NEXT_FRAME; \
  49. case RES_ERROR: goto __ERROR; \
  50. default: c11__unreachedable(); \
  51. } \
  52. } while(0)
  53. pk_FrameResult pk_VM__run_top_frame(pk_VM* self) {
  54. Frame* frame = self->top_frame;
  55. const Frame* base_frame = frame;
  56. while(true) {
  57. Bytecode byte;
  58. __NEXT_FRAME:
  59. // if(__internal_exception.type == InternalExceptionType::Null) {
  60. // // None
  61. // frame->_ip++;
  62. // } else if(__internal_exception.type == InternalExceptionType::Handled) {
  63. // // HandledException + continue
  64. // frame->_ip = c11__at(Bytecode, &frame->co->codes, __internal_exception.arg);
  65. // __internal_exception = {};
  66. // } else {
  67. // // UnhandledException + continue (need_raise = true)
  68. // // ToBeRaisedException + continue (need_raise = true)
  69. // __internal_exception = {};
  70. // __raise_exc(); // no return
  71. // }
  72. frame->ip++;
  73. __NEXT_STEP:
  74. byte = *frame->ip;
  75. #if 1
  76. c11_sbuf buf;
  77. c11_sbuf__ctor(&buf);
  78. for(py_Ref p = self->stack.begin; p != SP(); p++) {
  79. switch(p->type){
  80. case 0: c11_sbuf__write_cstr(&buf, "nil"); break;
  81. case tp_int: c11_sbuf__write_i64(&buf, p->_i64); break;
  82. case tp_float: c11_sbuf__write_f64(&buf, p->_f64, -1); break;
  83. case tp_bool: c11_sbuf__write_cstr(&buf, p->_bool ? "True" : "False"); break;
  84. case tp_none_type: c11_sbuf__write_cstr(&buf, "None"); break;
  85. case tp_type: {
  86. pk_sprintf(&buf, "<class '%t'>", py_totype(p));
  87. break;
  88. }
  89. case tp_str: {
  90. int size;
  91. const char* data = py_tostrn(p, &size);
  92. pk_sprintf(&buf, "%q", (c11_sv){data, size});
  93. break;
  94. }
  95. default:{
  96. pk_sprintf(&buf, "(%t)", p->type);
  97. break;
  98. }
  99. }
  100. if(p != TOP()) c11_sbuf__write_cstr(&buf, ", ");
  101. }
  102. c11_string* stack_str = c11_sbuf__submit(&buf);
  103. printf("L%-3d: %-25s %-6d [%s]\n", Frame__lineno(frame), pk_opname(byte.op), byte.arg, stack_str->data);
  104. c11_string__delete(stack_str);
  105. #endif
  106. switch((Opcode)byte.op) {
  107. case OP_NO_OP: DISPATCH();
  108. /*****************************************/
  109. case OP_POP_TOP: POP(); DISPATCH();
  110. case OP_DUP_TOP: PUSH(TOP()); DISPATCH();
  111. case OP_DUP_TOP_TWO:
  112. // [a, b]
  113. PUSH(SECOND()); // [a, b, a]
  114. PUSH(SECOND()); // [a, b, a, b]
  115. DISPATCH();
  116. case OP_ROT_TWO: {
  117. py_TValue tmp = *TOP();
  118. *TOP() = *SECOND();
  119. *SECOND() = tmp;
  120. DISPATCH();
  121. }
  122. case OP_ROT_THREE: {
  123. // [a, b, c] -> [c, a, b]
  124. py_TValue tmp = *TOP();
  125. *TOP() = *SECOND();
  126. *SECOND() = *THIRD();
  127. *THIRD() = tmp;
  128. DISPATCH();
  129. }
  130. case OP_PRINT_EXPR:
  131. if(TOP()->type != tp_none_type) {
  132. bool ok = py_repr(TOP());
  133. if(!ok) goto __ERROR;
  134. self->_stdout("%s\n", py_tostr(&self->last_retval));
  135. }
  136. POP();
  137. DISPATCH();
  138. /*****************************************/
  139. case OP_LOAD_CONST: PUSH(c11__at(py_TValue, &frame->co->consts, byte.arg)); DISPATCH();
  140. case OP_LOAD_NONE: py_newnone(SP()++); DISPATCH();
  141. case OP_LOAD_TRUE: py_newbool(SP()++, true); DISPATCH();
  142. case OP_LOAD_FALSE: py_newbool(SP()++, false); DISPATCH();
  143. /*****************************************/
  144. case OP_LOAD_SMALL_INT: py_newint(SP()++, (int16_t)byte.arg); DISPATCH();
  145. /*****************************************/
  146. case OP_LOAD_ELLIPSIS: py_newellipsis(SP()++); DISPATCH();
  147. case OP_LOAD_FUNCTION: {
  148. // FuncDecl_ decl = c11__getitem(FuncDecl_, &frame->co->func_decls, byte.arg);
  149. // py_TValue obj;
  150. // if(decl->nested) {
  151. // NameDict* captured = frame->_locals.to_namedict();
  152. // obj =
  153. // new_object<Function>(tp_function, decl, frame->_module, nullptr,
  154. // captured);
  155. // uint16_t name = py_Name__map2(py_Str__sv(&decl->code->name));
  156. // captured->set(name, obj);
  157. // } else {
  158. // obj = new_object<Function>(tp_function, decl, frame->_module, nullptr,
  159. // nullptr);
  160. // }
  161. // PUSH(obj);DISPATCH();
  162. }
  163. case OP_LOAD_NULL:
  164. py_newnil(SP()++);
  165. DISPATCH();
  166. /*****************************************/
  167. case OP_LOAD_FAST: {
  168. PUSH(&frame->locals[byte.arg]);
  169. if(py_isnil(TOP())) {
  170. py_Name name = c11__getitem(uint16_t, &frame->co->varnames, byte.arg);
  171. UnboundLocalError(name);
  172. goto __ERROR;
  173. }
  174. DISPATCH();
  175. }
  176. case OP_LOAD_NAME: {
  177. py_Name name = byte.arg;
  178. py_Ref tmp = Frame__f_locals_try_get(frame, name);
  179. if(tmp != NULL) {
  180. if(py_isnil(tmp)) {
  181. UnboundLocalError(name);
  182. goto __ERROR;
  183. }
  184. PUSH(tmp);
  185. DISPATCH();
  186. }
  187. tmp = Frame__f_closure_try_get(frame, name);
  188. if(tmp != NULL) {
  189. PUSH(tmp);
  190. DISPATCH();
  191. }
  192. tmp = Frame__f_globals_try_get(frame, name);
  193. if(tmp != NULL) {
  194. PUSH(tmp);
  195. DISPATCH();
  196. }
  197. tmp = py_getdict(&self->builtins, name);
  198. if(tmp != NULL) {
  199. PUSH(tmp);
  200. DISPATCH();
  201. }
  202. NameError(name);
  203. goto __ERROR;
  204. }
  205. case OP_LOAD_NONLOCAL: {
  206. py_Name name = byte.arg;
  207. py_Ref tmp = Frame__f_closure_try_get(frame, name);
  208. if(tmp != NULL) {
  209. PUSH(tmp);
  210. DISPATCH();
  211. }
  212. tmp = Frame__f_globals_try_get(frame, name);
  213. if(tmp != NULL) {
  214. PUSH(tmp);
  215. DISPATCH();
  216. }
  217. tmp = py_getdict(&self->builtins, name);
  218. if(tmp != NULL) {
  219. PUSH(tmp);
  220. DISPATCH();
  221. }
  222. NameError(name);
  223. goto __ERROR;
  224. }
  225. case OP_LOAD_GLOBAL: {
  226. py_Name name = byte.arg;
  227. py_Ref tmp = Frame__f_globals_try_get(frame, name);
  228. if(tmp != NULL) {
  229. PUSH(tmp);
  230. DISPATCH();
  231. }
  232. tmp = py_getdict(&self->builtins, name);
  233. if(tmp != NULL) {
  234. PUSH(tmp);
  235. DISPATCH();
  236. }
  237. NameError(name);
  238. goto __ERROR;
  239. }
  240. case OP_LOAD_ATTR: {
  241. if(!py_getattr(TOP(), byte.arg, TOP())) {
  242. AttributeError(TOP(), byte.arg);
  243. goto __ERROR;
  244. }
  245. DISPATCH();
  246. }
  247. case OP_LOAD_CLASS_GLOBAL: {
  248. assert(self->__curr_class.type);
  249. py_Name name = byte.arg;
  250. if(py_getattr(&self->__curr_class, name, SP())) {
  251. SP()++;
  252. DISPATCH();
  253. }
  254. // load global if attribute not found
  255. py_Ref tmp = Frame__f_globals_try_get(frame, name);
  256. if(tmp) {
  257. PUSH(tmp);
  258. DISPATCH();
  259. }
  260. tmp = py_getdict(&self->builtins, name);
  261. if(tmp) {
  262. PUSH(tmp);
  263. DISPATCH();
  264. }
  265. NameError(name);
  266. goto __ERROR;
  267. }
  268. case OP_LOAD_METHOD: {
  269. // [self]
  270. bool ok = py_getunboundmethod(TOP(), byte.arg, TOP(), SP());
  271. if(ok) {
  272. // [unbound, self]
  273. SP()++;
  274. } else {
  275. // fallback to getattr
  276. int res = py_getattr(TOP(), byte.arg, TOP());
  277. if(res != 1) {
  278. if(res == 0) { AttributeError(TOP(), byte.arg); }
  279. goto __ERROR;
  280. }
  281. }
  282. DISPATCH();
  283. }
  284. case OP_LOAD_SUBSCR: {
  285. // [a, b] -> a[b]
  286. py_Ref magic = py_tpfindmagic(SECOND()->type, __getitem__);
  287. if(magic) {
  288. if(magic->type == tp_nativefunc) {
  289. bool ok = magic->_cfunc(2, SECOND());
  290. if(!ok) goto __ERROR;
  291. POP();
  292. *TOP() = self->last_retval;
  293. } else {
  294. INSERT_THIRD(); // [?, a, b]
  295. *THIRD() = *magic; // [__getitem__, a, b]
  296. vectorcall_opcall(2, 0);
  297. }
  298. DISPATCH();
  299. }
  300. TypeError("'%t' object is not subscriptable", SECOND()->type);
  301. goto __ERROR;
  302. }
  303. case OP_STORE_FAST: frame->locals[byte.arg] = POPX(); DISPATCH();
  304. case OP_STORE_NAME: {
  305. py_Name _name = byte.arg;
  306. py_TValue _0 = POPX();
  307. if(frame->function) {
  308. py_Ref slot = Frame__f_locals_try_get(frame, _name);
  309. if(slot != NULL) {
  310. *slot = _0; // store in locals if possible
  311. } else {
  312. // Function& func = frame->_callable->as<Function>();
  313. // if(func.decl == __dynamic_func_decl) {
  314. // assert(func._closure != nullptr);
  315. // func._closure->set(_name, _0);
  316. // } else {
  317. // NameError(_name);
  318. // goto __ERROR;
  319. // }
  320. }
  321. } else {
  322. pk_NameDict__set(Frame__f_globals(frame), _name, _0);
  323. }
  324. DISPATCH();
  325. }
  326. case OP_STORE_GLOBAL:
  327. pk_NameDict__set(Frame__f_globals(frame), byte.arg, POPX());
  328. DISPATCH();
  329. case OP_STORE_ATTR: {
  330. int err = py_setattr(TOP(), byte.arg, SECOND());
  331. if(err) goto __ERROR;
  332. STACK_SHRINK(2);
  333. DISPATCH();
  334. }
  335. case OP_STORE_SUBSCR: {
  336. // [val, a, b] -> a[b] = val
  337. PUSH(THIRD()); // [val, a, b, val]
  338. py_Ref magic = py_tpfindmagic(SECOND()->type, __setitem__);
  339. if(magic) {
  340. if(magic->type == tp_nativefunc) {
  341. bool ok = magic->_cfunc(3, THIRD());
  342. if(!ok) goto __ERROR;
  343. STACK_SHRINK(3);
  344. *TOP() = self->last_retval;
  345. } else {
  346. INSERT_THIRD(); // [?, a, b]
  347. *FOURTH() = *magic; // [__selitem__, a, b, val]
  348. vectorcall_opcall(3, 0);
  349. POP(); // discard retval
  350. }
  351. DISPATCH();
  352. }
  353. TypeError("'%t' object does not support item assignment", SECOND()->type);
  354. goto __ERROR;
  355. }
  356. case OP_DELETE_FAST: {
  357. py_Ref tmp = &frame->locals[byte.arg];
  358. if(py_isnil(tmp)) {
  359. py_Name name = c11__getitem(py_Name, &frame->co->varnames, byte.arg);
  360. UnboundLocalError(name);
  361. goto __ERROR;
  362. }
  363. py_newnil(tmp);
  364. DISPATCH();
  365. }
  366. case OP_DELETE_NAME: {
  367. py_Name name = byte.arg;
  368. if(frame->function) {
  369. py_TValue* slot = Frame__f_locals_try_get(frame, name);
  370. if(slot) {
  371. py_newnil(slot);
  372. } else {
  373. // Function& func = frame->_callable->as<Function>();
  374. // if(func.decl == __dynamic_func_decl) {
  375. // assert(func._closure != nullptr);
  376. // bool ok = func._closure->del(_name);
  377. // if(!ok) vm->NameError(_name);
  378. // } else {
  379. // vm->NameError(_name);
  380. // }
  381. }
  382. } else {
  383. // if(!frame->f_globals().del(_name)) vm->NameError(_name);
  384. bool ok = pk_NameDict__del(Frame__f_globals(frame), name);
  385. if(!ok) {
  386. NameError(name);
  387. goto __ERROR;
  388. }
  389. }
  390. DISPATCH();
  391. }
  392. case OP_DELETE_GLOBAL: {
  393. py_Name name = byte.arg;
  394. bool ok = pk_NameDict__del(Frame__f_globals(frame), name);
  395. if(!ok) {
  396. NameError(name);
  397. goto __ERROR;
  398. }
  399. DISPATCH();
  400. }
  401. case OP_DELETE_ATTR: {
  402. if(!py_delattr(TOP(), byte.arg)) goto __ERROR;
  403. DISPATCH();
  404. }
  405. case OP_DELETE_SUBSCR: {
  406. // [a, b] -> del a[b]
  407. py_Ref magic = py_tpfindmagic(SECOND()->type, __delitem__);
  408. if(magic) {
  409. if(magic->type == tp_nativefunc) {
  410. bool ok = magic->_cfunc(2, SECOND());
  411. if(!ok) goto __ERROR;
  412. POP();
  413. *TOP() = self->last_retval;
  414. } else {
  415. INSERT_THIRD(); // [?, a, b]
  416. *THIRD() = *magic; // [__delitem__, a, b]
  417. vectorcall_opcall(2, 0);
  418. POP(); // discard retval
  419. }
  420. DISPATCH();
  421. }
  422. TypeError("'%t' object does not support item deletion", SECOND()->type);
  423. goto __ERROR;
  424. }
  425. /*****************************************/
  426. case OP_BUILD_LONG: {
  427. // [x]
  428. py_Ref f = py_getdict(&self->builtins, py_name("long"));
  429. assert(f != NULL);
  430. if(!py_call(f, 1, TOP())) goto __ERROR;
  431. *TOP() = self->last_retval;
  432. DISPATCH();
  433. }
  434. case OP_BUILD_IMAG: {
  435. // [x]
  436. py_Ref f = py_getdict(&self->builtins, py_name("complex"));
  437. assert(f != NULL);
  438. py_TValue tmp = *TOP();
  439. *TOP() = *f; // [complex]
  440. py_newnil(SP()++); // [complex, NULL]
  441. py_newint(SP()++, 0); // [complex, NULL, 0]
  442. *SP()++ = tmp; // [complex, NULL, 0, x]
  443. vectorcall_opcall(2, 0); // [complex(x)]
  444. DISPATCH();
  445. }
  446. case OP_BUILD_BYTES: {
  447. int size;
  448. const char* data = py_tostrn(TOP(), &size);
  449. unsigned char* p = py_newbytes(TOP(), size);
  450. memcpy(p, data, size);
  451. DISPATCH();
  452. }
  453. case OP_BUILD_TUPLE: {
  454. py_TValue tmp;
  455. py_newtuple(&tmp, byte.arg);
  456. py_TValue* begin = SP() - byte.arg;
  457. for(int i = 0; i < byte.arg; i++) {
  458. py_tuple__setitem(&tmp, i, begin + i);
  459. }
  460. SP() = begin;
  461. PUSH(&tmp);
  462. DISPATCH();
  463. }
  464. case OP_BUILD_LIST: {
  465. py_TValue tmp;
  466. py_newlistn(&tmp, byte.arg);
  467. py_TValue* begin = SP() - byte.arg;
  468. for(int i = 0; i < byte.arg; i++) {
  469. py_list__setitem(&tmp, i, begin + i);
  470. }
  471. SP() = begin;
  472. PUSH(&tmp);
  473. DISPATCH();
  474. }
  475. case OP_BUILD_DICT: {
  476. py_TValue* begin = SP() - byte.arg;
  477. py_Ref tmp = py_pushtmp();
  478. py_newdict(tmp);
  479. for(int i = 0; i < byte.arg; i += 2) {
  480. if(!py_setitem(tmp, begin + i, begin + i + 1)) goto __ERROR;
  481. }
  482. SP() = begin;
  483. PUSH(tmp);
  484. DISPATCH();
  485. }
  486. case OP_BUILD_SET: {
  487. py_TValue* begin = SP() - byte.arg;
  488. py_Ref tmp = py_pushtmp();
  489. py_newset(tmp);
  490. py_Name id_add = py_name("add");
  491. for(int i = 0; i < byte.arg; i++) {
  492. if(!py_callmethod(tmp, id_add, 1, begin + i)) goto __ERROR;
  493. }
  494. SP() = begin;
  495. PUSH(tmp);
  496. DISPATCH();
  497. }
  498. case OP_BUILD_SLICE: {
  499. // [start, stop, step]
  500. py_TValue tmp;
  501. py_newslice(&tmp, THIRD(), SECOND(), TOP());
  502. STACK_SHRINK(3);
  503. PUSH(&tmp);
  504. DISPATCH();
  505. }
  506. case OP_BUILD_STRING: {
  507. py_TValue* begin = SP() - byte.arg;
  508. c11_sbuf ss;
  509. c11_sbuf__ctor(&ss);
  510. for(int i = 0; i < byte.arg; i++) {
  511. if(!py_str(begin + i)) goto __ERROR;
  512. int size;
  513. const char* data = py_tostrn(&self->last_retval, &size);
  514. c11_sbuf__write_cstrn(&ss, data, size);
  515. }
  516. SP() = begin;
  517. c11_string* res = c11_sbuf__submit(&ss);
  518. py_newstrn(SP()++, res->data, res->size);
  519. c11_string__delete(res);
  520. DISPATCH();
  521. }
  522. /*****************************/
  523. case OP_BINARY_OP: {
  524. py_Name op = byte.arg & 0xFF;
  525. py_Name rop = byte.arg >> 8;
  526. if(!stack_binaryop(self, op, rop)) goto __ERROR;
  527. POP();
  528. *TOP() = self->last_retval;
  529. DISPATCH();
  530. }
  531. case OP_IS_OP: {
  532. bool res = py_isidentical(SECOND(), TOP());
  533. POP();
  534. if(byte.arg) res = !res;
  535. py_newbool(TOP(), res);
  536. DISPATCH();
  537. }
  538. case OP_CONTAINS_OP: {
  539. // [b, a] -> b __contains__ a (a in b)
  540. py_Ref magic = py_tpfindmagic(SECOND()->type, __contains__);
  541. if(magic) {
  542. if(magic->type == tp_nativefunc) {
  543. bool ok = magic->_cfunc(2, SECOND());
  544. if(!ok) goto __ERROR;
  545. POP();
  546. *TOP() = self->last_retval;
  547. } else {
  548. INSERT_THIRD(); // [?, b, a]
  549. *THIRD() = *magic; // [__contains__, a, b]
  550. vectorcall_opcall(2, 0);
  551. }
  552. bool res = py_tobool(TOP());
  553. if(byte.arg) py_newbool(TOP(), !res);
  554. DISPATCH();
  555. }
  556. // TODO: fallback to __iter__?
  557. TypeError("argument of type '%t' is not iterable", SECOND()->type);
  558. goto __ERROR;
  559. }
  560. /*****************************************/
  561. case OP_JUMP_FORWARD: DISPATCH_JUMP((int16_t)byte.arg);
  562. case OP_POP_JUMP_IF_FALSE: {
  563. int res = py_bool(TOP());
  564. if(res < 0) goto __ERROR;
  565. POP();
  566. if(!res) DISPATCH_JUMP((int16_t)byte.arg);
  567. DISPATCH();
  568. }
  569. case OP_POP_JUMP_IF_TRUE: {
  570. int res = py_bool(TOP());
  571. if(res < 0) goto __ERROR;
  572. POP();
  573. if(res) DISPATCH_JUMP((int16_t)byte.arg);
  574. DISPATCH();
  575. }
  576. case OP_JUMP_IF_TRUE_OR_POP: {
  577. int res = py_bool(TOP());
  578. if(res < 0) goto __ERROR;
  579. if(res) {
  580. DISPATCH_JUMP((int16_t)byte.arg);
  581. } else {
  582. POP();
  583. DISPATCH();
  584. }
  585. }
  586. case OP_JUMP_IF_FALSE_OR_POP: {
  587. int res = py_bool(TOP());
  588. if(res < 0) goto __ERROR;
  589. if(!res) {
  590. DISPATCH_JUMP((int16_t)byte.arg);
  591. } else {
  592. POP();
  593. DISPATCH();
  594. }
  595. }
  596. case OP_SHORTCUT_IF_FALSE_OR_POP: {
  597. int res = py_bool(TOP());
  598. if(res < 0) goto __ERROR;
  599. if(!res) { // [b, False]
  600. STACK_SHRINK(2); // []
  601. py_newbool(SP()++, false); // [False]
  602. DISPATCH_JUMP((int16_t)byte.arg);
  603. } else {
  604. POP(); // [b]
  605. DISPATCH();
  606. }
  607. }
  608. case OP_LOOP_CONTINUE:
  609. // just an alias of OP_JUMP_FORWARD
  610. DISPATCH_JUMP((int16_t)byte.arg);
  611. case OP_LOOP_BREAK: {
  612. int target = Frame__ip(frame) + byte.arg;
  613. Frame__prepare_jump_break(frame, &self->stack, target);
  614. DISPATCH_JUMP((int16_t)byte.arg);
  615. }
  616. case OP_JUMP_ABSOLUTE_TOP: {
  617. int target = py_toint(TOP());
  618. POP();
  619. DISPATCH_JUMP_ABSOLUTE(target);
  620. }
  621. // case OP_GOTO: {
  622. // py_Name _name(byte.arg);
  623. // int target = c11_smallmap_n2i__get(&frame->co->labels, byte.arg, -1);
  624. // if(target < 0) RuntimeError(_S("label ", _name.escape(), " not found"));
  625. // frame->prepare_jump_break(&s_data, target);
  626. // DISPATCH_JUMP_ABSOLUTE(target)
  627. // }
  628. /*****************************************/
  629. case OP_FSTRING_EVAL: {
  630. assert(false);
  631. }
  632. case OP_REPR: {
  633. assert(false);
  634. }
  635. case OP_CALL: {
  636. pk_ManagedHeap__collect_if_needed(&self->heap);
  637. vectorcall_opcall(byte.arg & 0xFF, byte.arg >> 8);
  638. DISPATCH();
  639. }
  640. case OP_CALL_VARGS: {
  641. assert(false);
  642. }
  643. case OP_RETURN_VALUE: {
  644. if(byte.arg == BC_NOARG) {
  645. self->last_retval = POPX();
  646. } else {
  647. py_newnone(&self->last_retval);
  648. }
  649. pk_VM__pop_frame(self);
  650. if(frame == base_frame) { // [ frameBase<- ]
  651. return RES_RETURN;
  652. } else {
  653. frame = self->top_frame;
  654. PUSH(&self->last_retval);
  655. goto __NEXT_FRAME;
  656. }
  657. DISPATCH();
  658. }
  659. /////////
  660. case OP_UNARY_NEGATIVE: {
  661. if(!py_callmagic(__neg__, 1, TOP())) goto __ERROR;
  662. *TOP() = self->last_retval;
  663. DISPATCH();
  664. }
  665. case OP_UNARY_NOT: {
  666. int res = py_bool(TOP());
  667. if(res < 0) goto __ERROR;
  668. py_newbool(TOP(), !res);
  669. DISPATCH();
  670. }
  671. // case OP_UNARY_STAR: TOP() = VAR(StarWrapper(byte.arg, TOP())); DISPATCH();
  672. case OP_UNARY_INVERT: {
  673. if(!py_callmagic(__invert__, 1, TOP())) goto __ERROR;
  674. *TOP() = self->last_retval;
  675. DISPATCH();
  676. }
  677. default: c11__unreachedable();
  678. }
  679. assert(false); // should never reach here
  680. __ERROR:
  681. // 1. Exception can be handled inside the current frame
  682. // 2. Exception need to be propagated to the upper frame
  683. printf("error.op: %s, line: %d\n", pk_opname(byte.op), Frame__lineno(frame));
  684. assert(false);
  685. return RES_ERROR;
  686. }
  687. return RES_RETURN;
  688. }
  689. /// Assumes [a, b] are on the stack, performs a binary op.
  690. /// The result is stored in `self->last_retval`.
  691. /// The stack remains unchanged.
  692. static bool stack_binaryop(pk_VM* self, py_Name op, py_Name rop) {
  693. // [a, b]
  694. py_Ref magic = py_tpfindmagic(SECOND()->type, op);
  695. if(magic) {
  696. bool ok = py_call(magic, 2, SECOND());
  697. if(!ok) return false;
  698. if(self->last_retval.type != tp_not_implemented_type) return true;
  699. }
  700. // try reverse operation
  701. if(rop) {
  702. // [a, b] -> [b, a]
  703. py_TValue tmp = *TOP();
  704. *TOP() = *SECOND();
  705. *SECOND() = tmp;
  706. magic = py_tpfindmagic(SECOND()->type, rop);
  707. if(magic) {
  708. bool ok = py_call(magic, 2, SECOND());
  709. if(!ok) return false;
  710. if(self->last_retval.type != tp_not_implemented_type) return true;
  711. }
  712. }
  713. // eq/ne op never fails due to object.__eq__
  714. return py_exception("TypeError", "unsupported operand type(s) for '%n'", op);
  715. }
  716. bool py_binaryop(const py_Ref lhs, const py_Ref rhs, py_Name op, py_Name rop) {
  717. pk_VM* self = pk_current_vm;
  718. PUSH(lhs);
  719. PUSH(rhs);
  720. return stack_binaryop(self, op, rop);
  721. }