ceval.c 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  1. #include "pocketpy/common/str.h"
  2. #include "pocketpy/common/utils.h"
  3. #include "pocketpy/interpreter/frame.h"
  4. #include "pocketpy/interpreter/vm.h"
  5. #include "pocketpy/common/sstream.h"
  6. #include "pocketpy/objects/codeobject.h"
  7. #include "pocketpy/pocketpy.h"
  8. #include "pocketpy/objects/error.h"
  9. #include <stdbool.h>
  10. static bool stack_format_object(VM* self, c11_sv spec);
  11. #define CHECK_RETURN_FROM_EXCEPT_OR_FINALLY() \
  12. if(self->is_curr_exc_handled) py_clearexc(NULL)
  13. #define CHECK_STACK_OVERFLOW() \
  14. do { \
  15. if(self->stack.sp > self->stack.end) { \
  16. py_exception(tp_StackOverflowError, ""); \
  17. goto __ERROR; \
  18. } \
  19. } while(0)
  20. #define DISPATCH() \
  21. do { \
  22. frame->ip++; \
  23. goto __NEXT_STEP; \
  24. } while(0)
  25. #define DISPATCH_JUMP(__offset) \
  26. do { \
  27. frame->ip += __offset; \
  28. goto __NEXT_STEP; \
  29. } while(0)
  30. #define DISPATCH_JUMP_ABSOLUTE(__target) \
  31. do { \
  32. frame->ip = __target; \
  33. goto __NEXT_STEP; \
  34. } while(0)
  35. /* Stack manipulation macros */
  36. // https://github.com/python/cpython/blob/3.9/Python/ceval.c#L1123
  37. #define TOP() (self->stack.sp - 1)
  38. #define SECOND() (self->stack.sp - 2)
  39. #define THIRD() (self->stack.sp - 3)
  40. #define FOURTH() (self->stack.sp - 4)
  41. #define STACK_SHRINK(n) (self->stack.sp -= n)
  42. #define STACK_GROW(n) (self->stack.sp += n)
  43. #define PUSH(v) \
  44. do { \
  45. *self->stack.sp = *(v); \
  46. self->stack.sp++; \
  47. } while(0)
  48. #define POP() (--self->stack.sp)
  49. #define POPX() (*--self->stack.sp)
  50. #define SP() (self->stack.sp)
  51. // [a, b] -> [?, a, b]
  52. #define INSERT_THIRD() \
  53. do { \
  54. PUSH(TOP()); \
  55. *SECOND() = *THIRD(); \
  56. } while(0)
  57. #define vectorcall_opcall(argc, kwargc) \
  58. do { \
  59. FrameResult res = VM__vectorcall(self, (argc), (kwargc), true); \
  60. switch(res) { \
  61. case RES_RETURN: PUSH(&self->last_retval); break; \
  62. case RES_CALL: frame = self->top_frame; goto __NEXT_FRAME; \
  63. case RES_ERROR: goto __ERROR; \
  64. default: c11__unreachable(); \
  65. } \
  66. } while(0)
  67. static bool unpack_dict_to_buffer(py_Ref key, py_Ref val, void* ctx) {
  68. py_TValue** p = ctx;
  69. if(py_isstr(key)) {
  70. py_Name name = py_namev(py_tosv(key));
  71. py_newint(*p, name);
  72. py_assign(*p + 1, val);
  73. (*p) += 2;
  74. return true;
  75. }
  76. return TypeError("keywords must be strings, not '%t'", key->type);
  77. }
  78. FrameResult VM__run_top_frame(VM* self) {
  79. Frame* frame = self->top_frame;
  80. Bytecode* codes;
  81. const Frame* base_frame = frame;
  82. while(true) {
  83. Bytecode byte;
  84. __NEXT_FRAME:
  85. codes = frame->co->codes.data;
  86. frame->ip++;
  87. __NEXT_STEP:
  88. byte = codes[frame->ip];
  89. #ifndef NDEBUG
  90. pk_print_stack(self, frame, byte);
  91. #endif
  92. if(self->is_signal_interrupted) {
  93. self->is_signal_interrupted = false;
  94. py_exception(tp_KeyboardInterrupt, "");
  95. goto __ERROR;
  96. }
  97. switch((Opcode)byte.op) {
  98. case OP_NO_OP: DISPATCH();
  99. /*****************************************/
  100. case OP_POP_TOP: POP(); DISPATCH();
  101. case OP_DUP_TOP: PUSH(TOP()); DISPATCH();
  102. case OP_DUP_TOP_TWO:
  103. // [a, b]
  104. PUSH(SECOND()); // [a, b, a]
  105. PUSH(SECOND()); // [a, b, a, b]
  106. DISPATCH();
  107. case OP_ROT_TWO: {
  108. py_TValue tmp = *TOP();
  109. *TOP() = *SECOND();
  110. *SECOND() = tmp;
  111. DISPATCH();
  112. }
  113. case OP_ROT_THREE: {
  114. // [a, b, c] -> [c, a, b]
  115. py_TValue tmp = *TOP();
  116. *TOP() = *SECOND();
  117. *SECOND() = *THIRD();
  118. *THIRD() = tmp;
  119. DISPATCH();
  120. }
  121. case OP_PRINT_EXPR:
  122. if(TOP()->type != tp_NoneType) {
  123. bool ok = py_repr(TOP());
  124. if(!ok) goto __ERROR;
  125. self->callbacks.print(py_tostr(&self->last_retval));
  126. self->callbacks.print("\n");
  127. }
  128. POP();
  129. DISPATCH();
  130. /*****************************************/
  131. case OP_LOAD_CONST: {
  132. CHECK_STACK_OVERFLOW();
  133. PUSH(c11__at(py_TValue, &frame->co->consts, byte.arg));
  134. DISPATCH();
  135. }
  136. case OP_LOAD_NONE: {
  137. CHECK_STACK_OVERFLOW();
  138. py_newnone(SP()++);
  139. DISPATCH();
  140. }
  141. case OP_LOAD_TRUE: {
  142. CHECK_STACK_OVERFLOW();
  143. py_newbool(SP()++, true);
  144. DISPATCH();
  145. }
  146. case OP_LOAD_FALSE: {
  147. CHECK_STACK_OVERFLOW();
  148. py_newbool(SP()++, false);
  149. DISPATCH();
  150. }
  151. /*****************************************/
  152. case OP_LOAD_SMALL_INT: {
  153. CHECK_STACK_OVERFLOW();
  154. py_newint(SP()++, (int16_t)byte.arg);
  155. DISPATCH();
  156. }
  157. /*****************************************/
  158. case OP_LOAD_ELLIPSIS: {
  159. CHECK_STACK_OVERFLOW();
  160. py_newellipsis(SP()++);
  161. DISPATCH();
  162. }
  163. case OP_LOAD_FUNCTION: {
  164. CHECK_STACK_OVERFLOW();
  165. FuncDecl_ decl = c11__getitem(FuncDecl_, &frame->co->func_decls, byte.arg);
  166. Function* ud = py_newobject(SP(), tp_function, 0, sizeof(Function));
  167. Function__ctor(ud, decl, frame->module, frame->globals);
  168. if(decl->nested) {
  169. if(frame->is_locals_special) {
  170. RuntimeError("cannot create closure from special locals");
  171. goto __ERROR;
  172. }
  173. ud->closure = FastLocals__to_namedict(frame->locals, frame->co);
  174. py_Name name = py_name(decl->code.name->data);
  175. // capture itself to allow recursion
  176. NameDict__set(ud->closure, name, *SP());
  177. }
  178. SP()++;
  179. DISPATCH();
  180. }
  181. case OP_LOAD_NULL:
  182. py_newnil(SP()++);
  183. DISPATCH();
  184. /*****************************************/
  185. case OP_LOAD_FAST: {
  186. assert(!frame->is_locals_special);
  187. PUSH(&frame->locals[byte.arg]);
  188. if(py_isnil(TOP())) {
  189. py_Name name = c11__getitem(uint16_t, &frame->co->varnames, byte.arg);
  190. UnboundLocalError(name);
  191. goto __ERROR;
  192. }
  193. DISPATCH();
  194. }
  195. case OP_LOAD_NAME: {
  196. assert(frame->is_locals_special);
  197. py_Name name = byte.arg;
  198. // locals
  199. switch(frame->locals->type) {
  200. case tp_locals: {
  201. Frame* noproxy = frame->locals->_ptr;
  202. py_Ref slot = Frame__getlocal_noproxy(noproxy, name);
  203. if(slot == NULL) break;
  204. if(py_isnil(slot)) {
  205. UnboundLocalError(name);
  206. goto __ERROR;
  207. }
  208. PUSH(slot);
  209. DISPATCH();
  210. }
  211. case tp_dict: {
  212. int res = py_dict_getitem(frame->locals, py_name2ref(name));
  213. if(res == 1) {
  214. PUSH(&self->last_retval);
  215. DISPATCH();
  216. }
  217. if(res == 0) break;
  218. assert(res == -1);
  219. goto __ERROR;
  220. }
  221. case tp_nil: break;
  222. default: c11__unreachable();
  223. }
  224. // globals
  225. int res = Frame__getglobal(frame, name);
  226. if(res == 1) {
  227. PUSH(&self->last_retval);
  228. DISPATCH();
  229. }
  230. if(res == -1) goto __ERROR;
  231. // builtins
  232. py_Ref 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_NONLOCAL: {
  241. py_Name name = byte.arg;
  242. py_Ref tmp = Frame__getclosure(frame, name);
  243. if(tmp != NULL) {
  244. PUSH(tmp);
  245. DISPATCH();
  246. }
  247. int res = Frame__getglobal(frame, name);
  248. if(res == 1) {
  249. PUSH(&self->last_retval);
  250. DISPATCH();
  251. }
  252. if(res == -1) goto __ERROR;
  253. tmp = py_getdict(&self->builtins, name);
  254. if(tmp != NULL) {
  255. PUSH(tmp);
  256. DISPATCH();
  257. }
  258. NameError(name);
  259. goto __ERROR;
  260. }
  261. case OP_LOAD_GLOBAL: {
  262. py_Name name = byte.arg;
  263. int res = Frame__getglobal(frame, name);
  264. if(res == 1) {
  265. PUSH(&self->last_retval);
  266. DISPATCH();
  267. }
  268. if(res == -1) goto __ERROR;
  269. py_Ref tmp = py_getdict(&self->builtins, name);
  270. if(tmp != NULL) {
  271. PUSH(tmp);
  272. DISPATCH();
  273. }
  274. NameError(name);
  275. goto __ERROR;
  276. }
  277. case OP_LOAD_ATTR: {
  278. if(py_getattr(TOP(), byte.arg)) {
  279. py_assign(TOP(), py_retval());
  280. } else {
  281. goto __ERROR;
  282. }
  283. DISPATCH();
  284. }
  285. case OP_LOAD_CLASS_GLOBAL: {
  286. assert(self->__curr_class);
  287. py_Name name = byte.arg;
  288. py_Ref tmp = py_getdict(self->__curr_class, name);
  289. if(tmp) {
  290. PUSH(tmp);
  291. DISPATCH();
  292. }
  293. // load global if attribute not found
  294. int res = Frame__getglobal(frame, name);
  295. if(res == 1) {
  296. PUSH(&self->last_retval);
  297. DISPATCH();
  298. }
  299. if(res == -1) goto __ERROR;
  300. tmp = py_getdict(&self->builtins, name);
  301. if(tmp) {
  302. PUSH(tmp);
  303. DISPATCH();
  304. }
  305. NameError(name);
  306. goto __ERROR;
  307. }
  308. case OP_LOAD_METHOD: {
  309. // [self] -> [unbound, self]
  310. bool ok = py_pushmethod(byte.arg);
  311. if(!ok) {
  312. // fallback to getattr
  313. if(py_getattr(TOP(), byte.arg)) {
  314. py_assign(TOP(), py_retval());
  315. py_newnil(SP()++);
  316. } else {
  317. goto __ERROR;
  318. }
  319. }
  320. DISPATCH();
  321. }
  322. case OP_LOAD_SUBSCR: {
  323. // [a, b] -> a[b]
  324. py_Ref magic = py_tpfindmagic(SECOND()->type, __getitem__);
  325. if(magic) {
  326. if(magic->type == tp_nativefunc) {
  327. if(!py_callcfunc(magic->_cfunc, 2, SECOND())) goto __ERROR;
  328. POP();
  329. py_assign(TOP(), py_retval());
  330. } else {
  331. INSERT_THIRD(); // [?, a, b]
  332. *THIRD() = *magic; // [__getitem__, a, b]
  333. if(!py_vectorcall(1, 0)) goto __ERROR;
  334. PUSH(py_retval());
  335. }
  336. DISPATCH();
  337. }
  338. TypeError("'%t' object is not subscriptable", SECOND()->type);
  339. goto __ERROR;
  340. }
  341. case OP_STORE_FAST: {
  342. assert(!frame->is_locals_special);
  343. frame->locals[byte.arg] = POPX();
  344. DISPATCH();
  345. }
  346. case OP_STORE_NAME: {
  347. assert(frame->is_locals_special);
  348. py_Name name = byte.arg;
  349. switch(frame->locals->type) {
  350. case tp_locals: {
  351. Frame* noproxy = frame->locals->_ptr;
  352. py_Ref slot = Frame__getlocal_noproxy(noproxy, name);
  353. if(slot == NULL) {
  354. UnboundLocalError(name);
  355. goto __ERROR;
  356. }
  357. *slot = POPX();
  358. DISPATCH();
  359. }
  360. case tp_dict: {
  361. if(!py_dict_setitem(frame->locals, py_name2ref(name), TOP())) goto __ERROR;
  362. POP();
  363. DISPATCH();
  364. }
  365. case tp_nil: {
  366. // globals
  367. if(!Frame__setglobal(frame, name, TOP())) goto __ERROR;
  368. POP();
  369. DISPATCH();
  370. }
  371. default: c11__unreachable();
  372. }
  373. }
  374. case OP_STORE_GLOBAL: {
  375. if(!Frame__setglobal(frame, byte.arg, TOP())) goto __ERROR;
  376. POP();
  377. DISPATCH();
  378. }
  379. case OP_STORE_ATTR: {
  380. // [val, a] -> a.b = val
  381. if(!py_setattr(TOP(), byte.arg, SECOND())) goto __ERROR;
  382. STACK_SHRINK(2);
  383. DISPATCH();
  384. }
  385. case OP_STORE_SUBSCR: {
  386. // [val, a, b] -> a[b] = val
  387. py_Ref magic = py_tpfindmagic(SECOND()->type, __setitem__);
  388. if(magic) {
  389. PUSH(THIRD()); // [val, a, b, val]
  390. if(magic->type == tp_nativefunc) {
  391. if(!py_callcfunc(magic->_cfunc, 3, THIRD())) goto __ERROR;
  392. STACK_SHRINK(4);
  393. } else {
  394. *FOURTH() = *magic; // [__selitem__, a, b, val]
  395. if(!py_vectorcall(2, 0)) goto __ERROR;
  396. }
  397. DISPATCH();
  398. }
  399. TypeError("'%t' object does not support item assignment", SECOND()->type);
  400. goto __ERROR;
  401. }
  402. case OP_DELETE_FAST: {
  403. assert(!frame->is_locals_special);
  404. py_Ref tmp = &frame->locals[byte.arg];
  405. if(py_isnil(tmp)) {
  406. py_Name name = c11__getitem(py_Name, &frame->co->varnames, byte.arg);
  407. UnboundLocalError(name);
  408. goto __ERROR;
  409. }
  410. py_newnil(tmp);
  411. DISPATCH();
  412. }
  413. case OP_DELETE_NAME: {
  414. assert(frame->is_locals_special);
  415. py_Name name = byte.arg;
  416. switch(frame->locals->type) {
  417. case tp_locals: {
  418. Frame* noproxy = frame->locals->_ptr;
  419. py_Ref slot = Frame__getlocal_noproxy(noproxy, name);
  420. if(slot == NULL || py_isnil(slot)) {
  421. UnboundLocalError(name);
  422. goto __ERROR;
  423. }
  424. py_newnil(slot);
  425. DISPATCH();
  426. }
  427. case tp_dict: {
  428. int res = py_dict_delitem(frame->locals, py_name2ref(name));
  429. if(res == 1) DISPATCH();
  430. if(res == 0) UnboundLocalError(name);
  431. goto __ERROR;
  432. }
  433. case tp_nil: {
  434. // globals
  435. int res = Frame__delglobal(frame, name);
  436. if(res == 1) DISPATCH();
  437. if(res == 0) NameError(name);
  438. goto __ERROR;
  439. }
  440. default: c11__unreachable();
  441. }
  442. }
  443. case OP_DELETE_GLOBAL: {
  444. py_Name name = byte.arg;
  445. int res = Frame__delglobal(frame, name);
  446. if(res == 1) DISPATCH();
  447. if(res == -1) goto __ERROR;
  448. NameError(name);
  449. goto __ERROR;
  450. }
  451. case OP_DELETE_ATTR: {
  452. if(!py_delattr(TOP(), byte.arg)) goto __ERROR;
  453. DISPATCH();
  454. }
  455. case OP_DELETE_SUBSCR: {
  456. // [a, b] -> del a[b]
  457. py_Ref magic = py_tpfindmagic(SECOND()->type, __delitem__);
  458. if(magic) {
  459. if(magic->type == tp_nativefunc) {
  460. if(!py_callcfunc(magic->_cfunc, 2, SECOND())) goto __ERROR;
  461. STACK_SHRINK(2);
  462. } else {
  463. INSERT_THIRD(); // [?, a, b]
  464. *THIRD() = *magic; // [__delitem__, a, b]
  465. if(!py_vectorcall(1, 0)) goto __ERROR;
  466. }
  467. DISPATCH();
  468. }
  469. TypeError("'%t' object does not support item deletion", SECOND()->type);
  470. goto __ERROR;
  471. }
  472. /*****************************************/
  473. case OP_BUILD_IMAG: {
  474. // [x]
  475. py_Ref f = py_getdict(&self->builtins, py_name("complex"));
  476. assert(f != NULL);
  477. py_TValue tmp = *TOP();
  478. *TOP() = *f; // [complex]
  479. py_newnil(SP()++); // [complex, NULL]
  480. py_newint(SP()++, 0); // [complex, NULL, 0]
  481. *SP()++ = tmp; // [complex, NULL, 0, x]
  482. if(!py_vectorcall(2, 0)) goto __ERROR;
  483. PUSH(py_retval());
  484. DISPATCH();
  485. }
  486. case OP_BUILD_BYTES: {
  487. int size;
  488. py_Ref string = c11__at(py_TValue, &frame->co->consts, byte.arg);
  489. const char* data = py_tostrn(string, &size);
  490. unsigned char* p = py_newbytes(SP()++, size);
  491. memcpy(p, data, size);
  492. DISPATCH();
  493. }
  494. case OP_BUILD_TUPLE: {
  495. py_TValue tmp;
  496. py_Ref p = py_newtuple(&tmp, byte.arg);
  497. py_TValue* begin = SP() - byte.arg;
  498. for(int i = 0; i < byte.arg; i++)
  499. p[i] = begin[i];
  500. SP() = begin;
  501. PUSH(&tmp);
  502. DISPATCH();
  503. }
  504. case OP_BUILD_LIST: {
  505. py_TValue tmp;
  506. py_newlistn(&tmp, byte.arg);
  507. py_TValue* begin = SP() - byte.arg;
  508. for(int i = 0; i < byte.arg; i++) {
  509. py_list_setitem(&tmp, i, begin + i);
  510. }
  511. SP() = begin;
  512. PUSH(&tmp);
  513. DISPATCH();
  514. }
  515. case OP_BUILD_DICT: {
  516. py_TValue* begin = SP() - byte.arg * 2;
  517. py_Ref tmp = py_pushtmp();
  518. py_newdict(tmp);
  519. for(int i = 0; i < byte.arg * 2; i += 2) {
  520. bool ok = py_dict_setitem(tmp, begin + i, begin + i + 1);
  521. if(!ok) goto __ERROR;
  522. }
  523. SP() = begin;
  524. PUSH(tmp);
  525. DISPATCH();
  526. }
  527. case OP_BUILD_SET: {
  528. py_TValue* begin = SP() - byte.arg;
  529. py_Ref typeobject_set = py_getdict(&self->builtins, py_name("set"));
  530. assert(typeobject_set != NULL);
  531. py_push(typeobject_set);
  532. py_pushnil();
  533. if(!py_vectorcall(0, 0)) goto __ERROR;
  534. py_push(py_retval()); // empty set
  535. py_Name id_add = py_name("add");
  536. for(int i = 0; i < byte.arg; i++) {
  537. py_push(TOP());
  538. if(!py_pushmethod(id_add)) {
  539. c11__abort("OP_BUILD_SET: failed to load method 'add'");
  540. }
  541. py_push(begin + i);
  542. if(!py_vectorcall(1, 0)) goto __ERROR;
  543. }
  544. py_TValue tmp = *TOP();
  545. SP() = begin;
  546. PUSH(&tmp);
  547. DISPATCH();
  548. }
  549. case OP_BUILD_SLICE: {
  550. // [start, stop, step]
  551. py_TValue tmp;
  552. py_newslice(&tmp);
  553. py_setslot(&tmp, 0, THIRD());
  554. py_setslot(&tmp, 1, SECOND());
  555. py_setslot(&tmp, 2, TOP());
  556. STACK_SHRINK(3);
  557. PUSH(&tmp);
  558. DISPATCH();
  559. }
  560. case OP_BUILD_STRING: {
  561. py_TValue* begin = SP() - byte.arg;
  562. c11_sbuf ss;
  563. c11_sbuf__ctor(&ss);
  564. for(int i = 0; i < byte.arg; i++) {
  565. if(!py_str(begin + i)) goto __ERROR;
  566. c11_sbuf__write_sv(&ss, py_tosv(&self->last_retval));
  567. }
  568. SP() = begin;
  569. c11_sbuf__py_submit(&ss, SP()++);
  570. DISPATCH();
  571. }
  572. /*****************************/
  573. case OP_BINARY_OP: {
  574. py_Name op = byte.arg & 0xFF;
  575. py_Name rop = byte.arg >> 8;
  576. if(!pk_stack_binaryop(self, op, rop)) goto __ERROR;
  577. POP();
  578. *TOP() = self->last_retval;
  579. DISPATCH();
  580. }
  581. case OP_IS_OP: {
  582. bool res = py_isidentical(SECOND(), TOP());
  583. POP();
  584. if(byte.arg) res = !res;
  585. py_newbool(TOP(), res);
  586. DISPATCH();
  587. }
  588. case OP_CONTAINS_OP: {
  589. // [b, a] -> b __contains__ a (a in b) -> [retval]
  590. py_Ref magic = py_tpfindmagic(SECOND()->type, __contains__);
  591. if(magic) {
  592. if(magic->type == tp_nativefunc) {
  593. if(!py_callcfunc(magic->_cfunc, 2, SECOND())) goto __ERROR;
  594. STACK_SHRINK(2);
  595. } else {
  596. INSERT_THIRD(); // [?, b, a]
  597. *THIRD() = *magic; // [__contains__, a, b]
  598. if(!py_vectorcall(1, 0)) goto __ERROR;
  599. }
  600. bool res = py_tobool(py_retval());
  601. if(byte.arg) res = !res;
  602. py_newbool(SP()++, res);
  603. DISPATCH();
  604. }
  605. TypeError("'%t' type does not support '__contains__'", SECOND()->type);
  606. goto __ERROR;
  607. }
  608. /*****************************************/
  609. case OP_JUMP_FORWARD: DISPATCH_JUMP((int16_t)byte.arg);
  610. case OP_POP_JUMP_IF_FALSE: {
  611. int res = py_bool(TOP());
  612. if(res < 0) goto __ERROR;
  613. POP();
  614. if(!res) DISPATCH_JUMP((int16_t)byte.arg);
  615. DISPATCH();
  616. }
  617. case OP_POP_JUMP_IF_TRUE: {
  618. int res = py_bool(TOP());
  619. if(res < 0) goto __ERROR;
  620. POP();
  621. if(res) DISPATCH_JUMP((int16_t)byte.arg);
  622. DISPATCH();
  623. }
  624. case OP_JUMP_IF_TRUE_OR_POP: {
  625. int res = py_bool(TOP());
  626. if(res < 0) goto __ERROR;
  627. if(res) {
  628. DISPATCH_JUMP((int16_t)byte.arg);
  629. } else {
  630. POP();
  631. DISPATCH();
  632. }
  633. }
  634. case OP_JUMP_IF_FALSE_OR_POP: {
  635. int res = py_bool(TOP());
  636. if(res < 0) goto __ERROR;
  637. if(!res) {
  638. DISPATCH_JUMP((int16_t)byte.arg);
  639. } else {
  640. POP();
  641. DISPATCH();
  642. }
  643. }
  644. case OP_SHORTCUT_IF_FALSE_OR_POP: {
  645. int res = py_bool(TOP());
  646. if(res < 0) goto __ERROR;
  647. if(!res) { // [b, False]
  648. STACK_SHRINK(2); // []
  649. py_newbool(SP()++, false); // [False]
  650. DISPATCH_JUMP((int16_t)byte.arg);
  651. } else {
  652. POP(); // [b]
  653. DISPATCH();
  654. }
  655. }
  656. case OP_LOOP_CONTINUE: {
  657. DISPATCH_JUMP((int16_t)byte.arg);
  658. }
  659. case OP_LOOP_BREAK: {
  660. DISPATCH_JUMP((int16_t)byte.arg);
  661. }
  662. /*****************************************/
  663. case OP_CALL: {
  664. ManagedHeap__collect_if_needed(&self->heap);
  665. vectorcall_opcall(byte.arg & 0xFF, byte.arg >> 8);
  666. DISPATCH();
  667. }
  668. case OP_CALL_VARGS: {
  669. // [_0, _1, _2 | k1, v1, k2, v2]
  670. uint16_t argc = byte.arg & 0xFF;
  671. uint16_t kwargc = byte.arg >> 8;
  672. int n = 0;
  673. py_TValue* sp = SP();
  674. py_TValue* p1 = sp - kwargc * 2;
  675. py_TValue* base = p1 - argc;
  676. py_TValue* buf = self->__vectorcall_buffer;
  677. for(py_TValue* curr = base; curr != p1; curr++) {
  678. if(curr->type != tp_star_wrapper) {
  679. buf[n++] = *curr;
  680. } else {
  681. py_TValue* args = py_getslot(curr, 0);
  682. py_TValue* p;
  683. int length = pk_arrayview(args, &p);
  684. if(length != -1) {
  685. for(int j = 0; j < length; j++) {
  686. buf[n++] = p[j];
  687. }
  688. argc += length - 1;
  689. } else {
  690. TypeError("*args must be a list or tuple, got '%t'", args->type);
  691. goto __ERROR;
  692. }
  693. }
  694. }
  695. for(py_TValue* curr = p1; curr != sp; curr += 2) {
  696. if(curr[1].type != tp_star_wrapper) {
  697. buf[n++] = curr[0];
  698. buf[n++] = curr[1];
  699. } else {
  700. assert(py_toint(&curr[0]) == 0);
  701. py_TValue* kwargs = py_getslot(&curr[1], 0);
  702. if(kwargs->type == tp_dict) {
  703. py_TValue* p = buf + n;
  704. if(!py_dict_apply(kwargs, unpack_dict_to_buffer, &p)) goto __ERROR;
  705. n = p - buf;
  706. kwargc += py_dict_len(kwargs) - 1;
  707. } else {
  708. TypeError("**kwargs must be a dict, got '%t'", kwargs->type);
  709. goto __ERROR;
  710. }
  711. }
  712. }
  713. memcpy(base, buf, n * sizeof(py_TValue));
  714. SP() = base + n;
  715. vectorcall_opcall(argc, kwargc);
  716. DISPATCH();
  717. }
  718. case OP_RETURN_VALUE: {
  719. CHECK_RETURN_FROM_EXCEPT_OR_FINALLY();
  720. if(byte.arg == BC_NOARG) {
  721. self->last_retval = POPX();
  722. } else {
  723. py_newnone(&self->last_retval);
  724. }
  725. VM__pop_frame(self);
  726. if(frame == base_frame) { // [ frameBase<- ]
  727. return RES_RETURN;
  728. } else {
  729. frame = self->top_frame;
  730. PUSH(&self->last_retval);
  731. goto __NEXT_FRAME;
  732. }
  733. DISPATCH();
  734. }
  735. case OP_YIELD_VALUE: {
  736. CHECK_RETURN_FROM_EXCEPT_OR_FINALLY();
  737. if(byte.arg == 1) {
  738. py_newnone(py_retval());
  739. } else {
  740. py_assign(py_retval(), TOP());
  741. POP();
  742. }
  743. return RES_YIELD;
  744. }
  745. case OP_FOR_ITER_YIELD_VALUE: {
  746. CHECK_RETURN_FROM_EXCEPT_OR_FINALLY();
  747. int res = py_next(TOP());
  748. if(res == -1) goto __ERROR;
  749. if(res) {
  750. return RES_YIELD;
  751. } else {
  752. assert(self->last_retval.type == tp_StopIteration);
  753. py_ObjectRef value = py_getslot(&self->last_retval, 0);
  754. if(py_isnil(value)) value = py_None();
  755. *TOP() = *value; // [iter] -> [retval]
  756. DISPATCH_JUMP((int16_t)byte.arg);
  757. }
  758. }
  759. /////////
  760. case OP_LIST_APPEND: {
  761. // [list, iter, value]
  762. py_list_append(THIRD(), TOP());
  763. POP();
  764. DISPATCH();
  765. }
  766. case OP_DICT_ADD: {
  767. // [dict, iter, key, value]
  768. bool ok = py_dict_setitem(FOURTH(), SECOND(), TOP());
  769. if(!ok) goto __ERROR;
  770. STACK_SHRINK(2);
  771. DISPATCH();
  772. }
  773. case OP_SET_ADD: {
  774. // [set, iter, value]
  775. py_push(THIRD()); // [| set]
  776. if(!py_pushmethod(py_name("add"))) {
  777. c11__abort("OP_SET_ADD: failed to load method 'add'");
  778. } // [|add() set]
  779. py_push(THIRD());
  780. if(!py_vectorcall(1, 0)) goto __ERROR;
  781. POP();
  782. DISPATCH();
  783. }
  784. /////////
  785. case OP_UNARY_NEGATIVE: {
  786. if(!pk_callmagic(__neg__, 1, TOP())) goto __ERROR;
  787. *TOP() = self->last_retval;
  788. DISPATCH();
  789. }
  790. case OP_UNARY_NOT: {
  791. int res = py_bool(TOP());
  792. if(res < 0) goto __ERROR;
  793. py_newbool(TOP(), !res);
  794. DISPATCH();
  795. }
  796. case OP_UNARY_STAR: {
  797. py_TValue value = POPX();
  798. int* level = py_newobject(SP()++, tp_star_wrapper, 1, sizeof(int));
  799. *level = byte.arg;
  800. py_setslot(TOP(), 0, &value);
  801. DISPATCH();
  802. }
  803. case OP_UNARY_INVERT: {
  804. if(!pk_callmagic(__invert__, 1, TOP())) goto __ERROR;
  805. *TOP() = self->last_retval;
  806. DISPATCH();
  807. }
  808. ////////////////
  809. case OP_GET_ITER: {
  810. if(!py_iter(TOP())) goto __ERROR;
  811. *TOP() = *py_retval();
  812. DISPATCH();
  813. }
  814. case OP_FOR_ITER: {
  815. int res = py_next(TOP());
  816. if(res == -1) goto __ERROR;
  817. if(res) {
  818. PUSH(py_retval());
  819. DISPATCH();
  820. } else {
  821. assert(self->last_retval.type == tp_StopIteration);
  822. POP(); // [iter] -> []
  823. DISPATCH_JUMP((int16_t)byte.arg);
  824. }
  825. }
  826. ////////
  827. case OP_IMPORT_PATH: {
  828. py_Ref path_object = c11__at(py_TValue, &frame->co->consts, byte.arg);
  829. const char* path = py_tostr(path_object);
  830. int res = py_import(path);
  831. if(res == -1) goto __ERROR;
  832. if(res == 0) {
  833. ImportError("No module named '%s'", path);
  834. goto __ERROR;
  835. }
  836. PUSH(py_retval());
  837. DISPATCH();
  838. }
  839. case OP_POP_IMPORT_STAR: {
  840. // [module]
  841. NameDict* dict = PyObject__dict(TOP()->_obj);
  842. py_Ref all = NameDict__try_get(dict, __all__);
  843. if(all) {
  844. py_TValue* p;
  845. int length = pk_arrayview(all, &p);
  846. if(length == -1) {
  847. TypeError("'__all__' must be a list or tuple, got '%t'", all->type);
  848. goto __ERROR;
  849. }
  850. for(int i = 0; i < length; i++) {
  851. py_Name name = py_namev(py_tosv(p + i));
  852. py_Ref value = NameDict__try_get(dict, name);
  853. if(value == NULL) {
  854. ImportError("cannot import name '%n'", name);
  855. goto __ERROR;
  856. } else {
  857. if(!Frame__setglobal(frame, name, value)) goto __ERROR;
  858. }
  859. }
  860. } else {
  861. for(int i = 0; i < dict->length; i++) {
  862. NameDict_KV* kv = c11__at(NameDict_KV, dict, i);
  863. if(!kv->key) continue;
  864. c11_sv name = py_name2sv(kv->key);
  865. if(name.size == 0 || name.data[0] == '_') continue;
  866. if(!Frame__setglobal(frame, kv->key, &kv->value)) goto __ERROR;
  867. }
  868. }
  869. POP();
  870. DISPATCH();
  871. }
  872. ////////
  873. case OP_UNPACK_SEQUENCE: {
  874. py_TValue* p;
  875. int length;
  876. switch(TOP()->type) {
  877. case tp_tuple: {
  878. length = py_tuple_len(TOP());
  879. p = py_tuple_data(TOP());
  880. break;
  881. }
  882. case tp_list: {
  883. length = py_list_len(TOP());
  884. p = py_list_data(TOP());
  885. break;
  886. }
  887. case tp_vec2i: {
  888. length = 2;
  889. if(byte.arg != length) break;
  890. c11_vec2i val = py_tovec2i(TOP());
  891. POP();
  892. py_newint(SP()++, val.x);
  893. py_newint(SP()++, val.y);
  894. DISPATCH();
  895. }
  896. case tp_vec2: {
  897. length = 2;
  898. if(byte.arg != length) break;
  899. c11_vec2 val = py_tovec2(TOP());
  900. POP();
  901. py_newfloat(SP()++, val.x);
  902. py_newfloat(SP()++, val.y);
  903. DISPATCH();
  904. }
  905. case tp_vec3i: {
  906. length = 3;
  907. if(byte.arg != length) break;
  908. c11_vec3i val = py_tovec3i(TOP());
  909. POP();
  910. py_newint(SP()++, val.x);
  911. py_newint(SP()++, val.y);
  912. py_newint(SP()++, val.z);
  913. DISPATCH();
  914. }
  915. case tp_vec3: {
  916. length = 3;
  917. if(byte.arg != length) break;
  918. c11_vec3 val = py_tovec3(TOP());
  919. POP();
  920. py_newfloat(SP()++, val.x);
  921. py_newfloat(SP()++, val.y);
  922. py_newfloat(SP()++, val.z);
  923. DISPATCH();
  924. }
  925. default: {
  926. TypeError("expected list or tuple to unpack, got %t", TOP()->type);
  927. goto __ERROR;
  928. }
  929. }
  930. if(length != byte.arg) {
  931. ValueError("expected %d values to unpack, got %d", byte.arg, length);
  932. goto __ERROR;
  933. }
  934. POP();
  935. for(int i = 0; i < length; i++) {
  936. PUSH(p + i);
  937. }
  938. DISPATCH();
  939. }
  940. case OP_UNPACK_EX: {
  941. py_TValue* p;
  942. int length = pk_arrayview(TOP(), &p);
  943. if(length == -1) {
  944. TypeError("expected list or tuple to unpack, got %t", TOP()->type);
  945. goto __ERROR;
  946. }
  947. int exceed = length - byte.arg;
  948. if(exceed < 0) {
  949. ValueError("not enough values to unpack");
  950. goto __ERROR;
  951. }
  952. POP();
  953. for(int i = 0; i < byte.arg; i++) {
  954. PUSH(p + i);
  955. }
  956. py_newlistn(SP()++, exceed);
  957. for(int i = 0; i < exceed; i++) {
  958. py_list_setitem(TOP(), i, p + byte.arg + i);
  959. }
  960. DISPATCH();
  961. }
  962. ///////////
  963. case OP_BEGIN_CLASS: {
  964. // [base]
  965. py_Name name = byte.arg;
  966. py_Type base;
  967. if(py_isnone(TOP())) {
  968. base = tp_object;
  969. } else {
  970. if(!py_checktype(TOP(), tp_type)) goto __ERROR;
  971. base = py_totype(TOP());
  972. }
  973. POP();
  974. py_TypeInfo* base_ti = TypeList__get(&self->types, base);
  975. if(base_ti->is_sealed) {
  976. TypeError("type '%t' is not an acceptable base type", base);
  977. goto __ERROR;
  978. }
  979. py_Type type = pk_newtype(py_name2str(name),
  980. base,
  981. frame->module,
  982. NULL,
  983. base_ti->is_python,
  984. false);
  985. PUSH(py_tpobject(type));
  986. self->__curr_class = TOP();
  987. DISPATCH();
  988. }
  989. case OP_END_CLASS: {
  990. // [cls or decorated]
  991. py_Name name = byte.arg;
  992. if(!Frame__setglobal(frame, name, TOP())) goto __ERROR;
  993. if(py_istype(TOP(), tp_type)) {
  994. // call on_end_subclass
  995. py_TypeInfo* ti = TypeList__get(&self->types, py_totype(TOP()));
  996. if(ti->base != tp_object) {
  997. py_TypeInfo* base_ti = ti->base_ti;
  998. if(base_ti->on_end_subclass) base_ti->on_end_subclass(ti);
  999. }
  1000. py_TValue* slot_eq = TypeList__magic_common(ti, __eq__);
  1001. py_TValue* slot_ne = TypeList__magic_common(ti, __ne__);
  1002. if(!py_isnil(slot_eq) && py_isnil(slot_ne)) {
  1003. TypeError("'%n' implements '__eq__' but not '__ne__'", ti->name);
  1004. goto __ERROR;
  1005. }
  1006. }
  1007. // class with decorator is unsafe currently
  1008. // it skips the above check
  1009. POP();
  1010. self->__curr_class = NULL;
  1011. DISPATCH();
  1012. }
  1013. case OP_STORE_CLASS_ATTR: {
  1014. assert(self->__curr_class);
  1015. py_Name name = byte.arg;
  1016. // TOP() can be a function, classmethod or custom decorator
  1017. py_Ref actual_func = TOP();
  1018. if(actual_func->type == tp_classmethod) {
  1019. actual_func = py_getslot(actual_func, 0);
  1020. }
  1021. if(actual_func->type == tp_function) {
  1022. Function* ud = py_touserdata(actual_func);
  1023. ud->clazz = self->__curr_class->_obj;
  1024. }
  1025. py_setdict(self->__curr_class, name, TOP());
  1026. POP();
  1027. DISPATCH();
  1028. }
  1029. case OP_ADD_CLASS_ANNOTATION: {
  1030. assert(self->__curr_class);
  1031. // [type_hint string]
  1032. py_Type type = py_totype(self->__curr_class);
  1033. py_TypeInfo* ti = TypeList__get(&self->types, type);
  1034. if(py_isnil(&ti->annotations)) py_newdict(&ti->annotations);
  1035. bool ok = py_dict_setitem_by_str(&ti->annotations, py_name2str(byte.arg), TOP());
  1036. if(!ok) goto __ERROR;
  1037. POP();
  1038. DISPATCH();
  1039. }
  1040. ///////////
  1041. case OP_WITH_ENTER: {
  1042. // [expr]
  1043. py_push(TOP());
  1044. if(!py_pushmethod(__enter__)) {
  1045. TypeError("'%t' object does not support the context manager protocol",
  1046. TOP()->type);
  1047. goto __ERROR;
  1048. }
  1049. if(!py_vectorcall(0, 0)) goto __ERROR;
  1050. PUSH(py_retval());
  1051. DISPATCH();
  1052. }
  1053. case OP_WITH_EXIT: {
  1054. // [expr]
  1055. py_push(TOP());
  1056. if(!py_pushmethod(__exit__)) {
  1057. TypeError("'%t' object does not support the context manager protocol",
  1058. TOP()->type);
  1059. goto __ERROR;
  1060. }
  1061. if(!py_vectorcall(0, 0)) goto __ERROR;
  1062. POP();
  1063. DISPATCH();
  1064. }
  1065. ///////////
  1066. case OP_TRY_ENTER: {
  1067. Frame__set_unwind_target(frame, SP());
  1068. DISPATCH();
  1069. }
  1070. case OP_EXCEPTION_MATCH: {
  1071. if(!py_checktype(TOP(), tp_type)) goto __ERROR;
  1072. bool ok = py_isinstance(&self->curr_exception, py_totype(TOP()));
  1073. py_newbool(TOP(), ok);
  1074. DISPATCH();
  1075. }
  1076. case OP_RAISE: {
  1077. // [exception]
  1078. if(py_istype(TOP(), tp_type)) {
  1079. if(!py_tpcall(py_totype(TOP()), 0, NULL)) goto __ERROR;
  1080. py_assign(TOP(), py_retval());
  1081. }
  1082. if(!py_isinstance(TOP(), tp_BaseException)) {
  1083. TypeError("exceptions must derive from BaseException");
  1084. goto __ERROR;
  1085. }
  1086. py_raise(TOP());
  1087. goto __ERROR;
  1088. }
  1089. case OP_RAISE_ASSERT: {
  1090. if(byte.arg) {
  1091. if(!py_str(TOP())) goto __ERROR;
  1092. POP();
  1093. py_exception(tp_AssertionError, "%s", py_tostr(py_retval()));
  1094. } else {
  1095. py_exception(tp_AssertionError, "");
  1096. }
  1097. goto __ERROR;
  1098. }
  1099. case OP_RE_RAISE: {
  1100. if(self->curr_exception.type) {
  1101. assert(!self->is_curr_exc_handled);
  1102. goto __ERROR_RE_RAISE;
  1103. }
  1104. DISPATCH();
  1105. }
  1106. case OP_PUSH_EXCEPTION: {
  1107. assert(self->curr_exception.type);
  1108. PUSH(&self->curr_exception);
  1109. DISPATCH();
  1110. }
  1111. case OP_BEGIN_EXC_HANDLING: {
  1112. assert(self->curr_exception.type);
  1113. self->is_curr_exc_handled = true;
  1114. DISPATCH();
  1115. }
  1116. case OP_END_EXC_HANDLING: {
  1117. assert(self->curr_exception.type);
  1118. py_clearexc(NULL);
  1119. DISPATCH();
  1120. }
  1121. case OP_BEGIN_FINALLY: {
  1122. if(self->curr_exception.type) {
  1123. assert(!self->is_curr_exc_handled);
  1124. // temporarily handle the exception if any
  1125. self->is_curr_exc_handled = true;
  1126. }
  1127. DISPATCH();
  1128. }
  1129. case OP_END_FINALLY: {
  1130. if(byte.arg == BC_NOARG) {
  1131. if(self->curr_exception.type) {
  1132. assert(self->is_curr_exc_handled);
  1133. // revert the exception handling if needed
  1134. self->is_curr_exc_handled = false;
  1135. }
  1136. } else {
  1137. // break or continue inside finally block
  1138. py_clearexc(NULL);
  1139. }
  1140. DISPATCH();
  1141. }
  1142. //////////////////
  1143. case OP_FORMAT_STRING: {
  1144. py_Ref spec = c11__at(py_TValue, &frame->co->consts, byte.arg);
  1145. bool ok = stack_format_object(self, py_tosv(spec));
  1146. if(!ok) goto __ERROR;
  1147. DISPATCH();
  1148. }
  1149. default: c11__unreachable();
  1150. }
  1151. c11__unreachable();
  1152. __ERROR:
  1153. py_BaseException__stpush(&self->curr_exception,
  1154. frame->co->src,
  1155. Frame__lineno(frame),
  1156. !frame->is_locals_special ? frame->co->name->data : NULL);
  1157. __ERROR_RE_RAISE:
  1158. do {
  1159. } while(0);
  1160. int target = Frame__prepare_jump_exception_handler(frame, &self->stack);
  1161. if(target >= 0) {
  1162. // 1. Exception can be handled inside the current frame
  1163. DISPATCH_JUMP_ABSOLUTE(target);
  1164. } else {
  1165. // 2. Exception need to be propagated to the upper frame
  1166. bool is_base_frame_to_be_popped = frame == base_frame;
  1167. VM__pop_frame(self);
  1168. if(self->top_frame == NULL || is_base_frame_to_be_popped) {
  1169. // propagate to the top level
  1170. return RES_ERROR;
  1171. }
  1172. frame = self->top_frame;
  1173. codes = frame->co->codes.data;
  1174. goto __ERROR;
  1175. }
  1176. }
  1177. return RES_RETURN;
  1178. }
  1179. const char* pk_op2str(py_Name op) {
  1180. switch(op) {
  1181. case __eq__: return "==";
  1182. case __ne__: return "!=";
  1183. case __lt__: return "<";
  1184. case __le__: return "<=";
  1185. case __gt__: return ">";
  1186. case __ge__: return ">=";
  1187. case __add__: return "+";
  1188. case __sub__: return "-";
  1189. case __mul__: return "*";
  1190. case __truediv__: return "/";
  1191. case __floordiv__: return "//";
  1192. case __mod__: return "%";
  1193. case __pow__: return "**";
  1194. case __lshift__: return "<<";
  1195. case __rshift__: return ">>";
  1196. case __and__: return "&";
  1197. case __or__: return "|";
  1198. case __xor__: return "^";
  1199. case __neg__: return "-";
  1200. case __invert__: return "~";
  1201. case __matmul__: return "@";
  1202. default: return py_name2str(op);
  1203. }
  1204. }
  1205. bool pk_stack_binaryop(VM* self, py_Name op, py_Name rop) {
  1206. // [a, b]
  1207. py_Ref magic = py_tpfindmagic(SECOND()->type, op);
  1208. if(magic) {
  1209. bool ok = py_call(magic, 2, SECOND());
  1210. if(!ok) return false;
  1211. if(self->last_retval.type != tp_NotImplementedType) return true;
  1212. }
  1213. // try reverse operation
  1214. if(rop) {
  1215. // [a, b] -> [b, a]
  1216. py_TValue tmp = *TOP();
  1217. *TOP() = *SECOND();
  1218. *SECOND() = tmp;
  1219. magic = py_tpfindmagic(SECOND()->type, rop);
  1220. if(magic) {
  1221. bool ok = py_call(magic, 2, SECOND());
  1222. if(!ok) return false;
  1223. if(self->last_retval.type != tp_NotImplementedType) return true;
  1224. }
  1225. }
  1226. // eq/ne op never fails
  1227. bool res = py_isidentical(SECOND(), TOP());
  1228. if(op == __eq__) {
  1229. py_newbool(py_retval(), res);
  1230. return true;
  1231. }
  1232. if(op == __ne__) {
  1233. py_newbool(py_retval(), !res);
  1234. return true;
  1235. }
  1236. return TypeError("unsupported operand type(s) for '%s'", pk_op2str(op));
  1237. }
  1238. bool py_binaryop(py_Ref lhs, py_Ref rhs, py_Name op, py_Name rop) {
  1239. VM* self = pk_current_vm;
  1240. PUSH(lhs);
  1241. PUSH(rhs);
  1242. bool ok = pk_stack_binaryop(self, op, rop);
  1243. STACK_SHRINK(2);
  1244. return ok;
  1245. }
  1246. static bool stack_format_object(VM* self, c11_sv spec) {
  1247. // format TOS via `spec` inplace
  1248. // spec: '!r:.2f', '.2f'
  1249. py_StackRef val = TOP();
  1250. if(spec.size == 0) return py_str(val);
  1251. if(spec.data[0] == '!') {
  1252. if(c11_sv__startswith(spec, (c11_sv){"!r", 2})) {
  1253. spec.data += 2;
  1254. spec.size -= 2;
  1255. if(!py_repr(val)) return false;
  1256. py_assign(val, py_retval());
  1257. if(spec.size == 0) return true;
  1258. } else {
  1259. return ValueError("invalid conversion specifier (only !r is supported)");
  1260. }
  1261. }
  1262. assert(spec.size > 0);
  1263. if(spec.data[0] == ':') {
  1264. spec.data++;
  1265. spec.size--;
  1266. }
  1267. char type;
  1268. switch(spec.data[spec.size - 1]) {
  1269. case 'f':
  1270. case 'd':
  1271. case 's':
  1272. type = spec.data[spec.size - 1];
  1273. spec.size--; // remove last char
  1274. break;
  1275. default: type = ' '; break;
  1276. }
  1277. char pad_c = ' ';
  1278. if(strchr("0-=*#@!~", spec.data[0])) {
  1279. pad_c = spec.data[0];
  1280. spec = c11_sv__slice(spec, 1);
  1281. }
  1282. char align;
  1283. if(spec.data[0] == '^') {
  1284. align = '^';
  1285. spec = c11_sv__slice(spec, 1);
  1286. } else if(spec.data[0] == '>') {
  1287. align = '>';
  1288. spec = c11_sv__slice(spec, 1);
  1289. } else if(spec.data[0] == '<') {
  1290. align = '<';
  1291. spec = c11_sv__slice(spec, 1);
  1292. } else {
  1293. align = (py_isint(val) || py_isfloat(val)) ? '>' : '<';
  1294. }
  1295. int dot = c11_sv__index(spec, '.');
  1296. py_i64 width, precision;
  1297. if(dot >= 0) {
  1298. if(dot == 0) {
  1299. // {.2f}
  1300. width = -1;
  1301. } else {
  1302. // {10.2f}
  1303. IntParsingResult res = c11__parse_uint(c11_sv__slice2(spec, 0, dot), &width, 10);
  1304. if(res != IntParsing_SUCCESS) return ValueError("invalid format specifer");
  1305. }
  1306. IntParsingResult res = c11__parse_uint(c11_sv__slice(spec, dot + 1), &precision, 10);
  1307. if(res != IntParsing_SUCCESS) return ValueError("invalid format specifer");
  1308. } else {
  1309. // {10s}
  1310. IntParsingResult res = c11__parse_uint(spec, &width, 10);
  1311. if(res != IntParsing_SUCCESS) return ValueError("invalid format specifer");
  1312. precision = -1;
  1313. }
  1314. if(type != 'f' && dot >= 0) {
  1315. return ValueError("precision not allowed in the format specifier");
  1316. }
  1317. c11_sbuf buf;
  1318. c11_sbuf__ctor(&buf);
  1319. if(type == 'f') {
  1320. py_f64 x;
  1321. if(!py_castfloat(val, &x)) {
  1322. c11_sbuf__dtor(&buf);
  1323. return false;
  1324. }
  1325. if(precision < 0) precision = 6;
  1326. c11_sbuf__write_f64(&buf, x, precision);
  1327. } else if(type == 'd') {
  1328. if(!py_checkint(val)) {
  1329. c11_sbuf__dtor(&buf);
  1330. return false;
  1331. }
  1332. c11_sbuf__write_i64(&buf, py_toint(val));
  1333. } else if(type == 's') {
  1334. if(!py_checkstr(val)) {
  1335. c11_sbuf__dtor(&buf);
  1336. return false;
  1337. }
  1338. c11_sbuf__write_sv(&buf, py_tosv(val));
  1339. } else {
  1340. if(!py_str(val)) {
  1341. c11_sbuf__dtor(&buf);
  1342. return false;
  1343. }
  1344. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  1345. }
  1346. c11_string* body = c11_sbuf__submit(&buf);
  1347. int length = c11_sv__u8_length(c11_string__sv(body));
  1348. c11_sbuf__ctor(&buf); // reinit sbuf
  1349. if(width != -1 && width > length) {
  1350. switch(align) {
  1351. case '>': {
  1352. c11_sbuf__write_pad(&buf, width - length, pad_c);
  1353. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  1354. break;
  1355. }
  1356. case '<': {
  1357. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  1358. c11_sbuf__write_pad(&buf, width - length, pad_c);
  1359. break;
  1360. }
  1361. case '^': {
  1362. int pad_left = (width - length) / 2;
  1363. int pad_right = (width - length) - pad_left;
  1364. c11_sbuf__write_pad(&buf, pad_left, pad_c);
  1365. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  1366. c11_sbuf__write_pad(&buf, pad_right, pad_c);
  1367. break;
  1368. }
  1369. default: c11__unreachable();
  1370. }
  1371. } else {
  1372. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  1373. }
  1374. c11_string__delete(body);
  1375. // inplace update
  1376. c11_sbuf__py_submit(&buf, val);
  1377. return true;
  1378. }
  1379. #undef CHECK_RETURN_FROM_EXCEPT_OR_FINALLY
  1380. #undef DISPATCH
  1381. #undef DISPATCH_JUMP
  1382. #undef DISPATCH_JUMP_ABSOLUTE
  1383. #undef TOP
  1384. #undef SECOND
  1385. #undef THIRD
  1386. #undef FOURTH
  1387. #undef STACK_SHRINK
  1388. #undef STACK_GROW
  1389. #undef PUSH
  1390. #undef POP
  1391. #undef POPX
  1392. #undef SP
  1393. #undef INSERT_THIRD
  1394. #undef vectorcall_opcall