ceval.c 43 KB

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