ceval.c 43 KB

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