ceval.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. #include "pocketpy/ceval.h"
  2. namespace pkpy{
  3. static i64 _py_sint(PyObject* obj) noexcept {
  4. return (i64)(PK_BITS(obj) >> 2);
  5. }
  6. PyObject* VM::_run_top_frame(){
  7. FrameId frame = top_frame();
  8. const int base_id = frame.index;
  9. bool need_raise = false;
  10. // shared registers
  11. PyObject *_0, *_1, *_2;
  12. const PyTypeInfo* _ti;
  13. StrName _name;
  14. while(true){
  15. #if PK_DEBUG_EXTRA_CHECK
  16. if(frame.index < base_id) FATAL_ERROR();
  17. #endif
  18. try{
  19. if(need_raise){ need_raise = false; _raise(); }
  20. /**********************************************************************/
  21. /* NOTE:
  22. * Be aware of accidental gc!
  23. * DO NOT leave any strong reference of PyObject* in the C stack
  24. */
  25. {
  26. #if PK_ENABLE_CEVAL_CALLBACK
  27. #define CEVAL_STEP() byte = frame->next_bytecode(); if(_ceval_on_step) _ceval_on_step(this, frame.get(), byte)
  28. #else
  29. #define CEVAL_STEP() byte = frame->next_bytecode()
  30. #endif
  31. #define DISPATCH_OP_CALL() { frame = top_frame(); goto __NEXT_FRAME; }
  32. __NEXT_FRAME:
  33. Bytecode CEVAL_STEP();
  34. // cache
  35. const CodeObject* co = frame->co;
  36. const auto& co_consts = co->consts;
  37. const auto& co_blocks = co->blocks;
  38. #if PK_ENABLE_COMPUTED_GOTO
  39. static void* OP_LABELS[] = {
  40. #define OPCODE(name) &&CASE_OP_##name,
  41. #include "pocketpy/opcodes.h"
  42. #undef OPCODE
  43. };
  44. #define DISPATCH() { CEVAL_STEP(); goto *OP_LABELS[byte.op];}
  45. #define TARGET(op) CASE_OP_##op:
  46. goto *OP_LABELS[byte.op];
  47. #else
  48. #define TARGET(op) case OP_##op:
  49. #define DISPATCH() { CEVAL_STEP(); goto __NEXT_STEP;}
  50. __NEXT_STEP:;
  51. #if PK_DEBUG_CEVAL_STEP
  52. _log_s_data();
  53. #endif
  54. switch (byte.op)
  55. {
  56. #endif
  57. TARGET(NO_OP) DISPATCH();
  58. /*****************************************/
  59. TARGET(POP_TOP) POP(); DISPATCH();
  60. TARGET(DUP_TOP) PUSH(TOP()); DISPATCH();
  61. TARGET(ROT_TWO) std::swap(TOP(), SECOND()); DISPATCH();
  62. TARGET(ROT_THREE)
  63. _0 = TOP();
  64. TOP() = SECOND();
  65. SECOND() = THIRD();
  66. THIRD() = _0;
  67. DISPATCH();
  68. TARGET(PRINT_EXPR)
  69. if(TOP() != None) stdout_write(CAST(Str&, py_repr(TOP())) + "\n");
  70. POP();
  71. DISPATCH();
  72. /*****************************************/
  73. TARGET(LOAD_CONST)
  74. heap._auto_collect();
  75. PUSH(co_consts[byte.arg]);
  76. DISPATCH();
  77. TARGET(LOAD_NONE) PUSH(None); DISPATCH();
  78. TARGET(LOAD_TRUE) PUSH(True); DISPATCH();
  79. TARGET(LOAD_FALSE) PUSH(False); DISPATCH();
  80. TARGET(LOAD_INTEGER) PUSH(VAR(byte.arg)); DISPATCH();
  81. TARGET(LOAD_ELLIPSIS) PUSH(Ellipsis); DISPATCH();
  82. TARGET(LOAD_FUNCTION) {
  83. FuncDecl_ decl = co->func_decls[byte.arg];
  84. PyObject* obj;
  85. if(decl->nested){
  86. NameDict_ captured = frame->_locals.to_namedict();
  87. obj = VAR(Function({decl, frame->_module, captured}));
  88. captured->set(decl->code->name, obj);
  89. }else{
  90. obj = VAR(Function({decl, frame->_module}));
  91. }
  92. PUSH(obj);
  93. } DISPATCH();
  94. TARGET(LOAD_NULL) PUSH(PY_NULL); DISPATCH();
  95. /*****************************************/
  96. TARGET(LOAD_FAST) {
  97. heap._auto_collect();
  98. _0 = frame->_locals[byte.arg];
  99. if(_0 == PY_NULL) vm->UnboundLocalError(co->varnames[byte.arg]);
  100. PUSH(_0);
  101. } DISPATCH();
  102. TARGET(LOAD_NAME) {
  103. heap._auto_collect();
  104. _name = StrName(byte.arg);
  105. PyObject** slot = frame->_locals.try_get_name(_name);
  106. if(slot != nullptr) {
  107. if(*slot == PY_NULL) vm->UnboundLocalError(_name);
  108. PUSH(*slot);
  109. DISPATCH();
  110. }
  111. _0 = frame->f_closure_try_get(_name);
  112. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  113. _0 = frame->f_globals().try_get(_name);
  114. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  115. _0 = vm->builtins->attr().try_get(_name);
  116. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  117. vm->NameError(_name);
  118. } DISPATCH();
  119. TARGET(LOAD_NONLOCAL) {
  120. heap._auto_collect();
  121. _name = StrName(byte.arg);
  122. _0 = frame->f_closure_try_get(_name);
  123. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  124. _0 = frame->f_globals().try_get(_name);
  125. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  126. _0 = vm->builtins->attr().try_get(_name);
  127. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  128. vm->NameError(_name);
  129. } DISPATCH();
  130. TARGET(LOAD_GLOBAL)
  131. heap._auto_collect();
  132. _name = StrName(byte.arg);
  133. _0 = frame->f_globals().try_get(_name);
  134. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  135. _0 = vm->builtins->attr().try_get(_name);
  136. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  137. vm->NameError(_name);
  138. DISPATCH();
  139. TARGET(LOAD_ATTR)
  140. TOP() = getattr(TOP(), StrName(byte.arg));
  141. DISPATCH();
  142. TARGET(LOAD_METHOD)
  143. TOP() = get_unbound_method(TOP(), StrName(byte.arg), &_0, true, true);
  144. PUSH(_0);
  145. DISPATCH();
  146. TARGET(LOAD_SUBSCR)
  147. _1 = POPX(); // b
  148. _0 = TOP(); // a
  149. _ti = _inst_type_info(_0);
  150. if(_ti->m__getitem__){
  151. TOP() = _ti->m__getitem__(this, _0, _1);
  152. }else{
  153. TOP() = call_method(_0, __getitem__, _1);
  154. }
  155. DISPATCH();
  156. TARGET(STORE_FAST)
  157. frame->_locals[byte.arg] = POPX();
  158. DISPATCH();
  159. TARGET(STORE_NAME){
  160. _name = StrName(byte.arg);
  161. _0 = POPX();
  162. if(frame->_callable != nullptr){
  163. PyObject** slot = frame->_locals.try_get_name(_name);
  164. if(slot == nullptr) vm->UnboundLocalError(_name);
  165. *slot = _0;
  166. }else{
  167. frame->f_globals().set(_name, _0);
  168. }
  169. } DISPATCH();
  170. TARGET(STORE_GLOBAL)
  171. frame->f_globals().set(StrName(byte.arg), POPX());
  172. DISPATCH();
  173. TARGET(STORE_ATTR) {
  174. _0 = TOP(); // a
  175. _1 = SECOND(); // val
  176. setattr(_0, StrName(byte.arg), _1);
  177. STACK_SHRINK(2);
  178. } DISPATCH();
  179. TARGET(STORE_SUBSCR)
  180. _2 = POPX(); // b
  181. _1 = POPX(); // a
  182. _0 = POPX(); // val
  183. _ti = _inst_type_info(_1);
  184. if(_ti->m__setitem__){
  185. _ti->m__setitem__(this, _1, _2, _0);
  186. }else{
  187. call_method(_1, __setitem__, _2, _0);
  188. }
  189. DISPATCH();
  190. TARGET(DELETE_FAST)
  191. _0 = frame->_locals[byte.arg];
  192. if(_0 == PY_NULL) vm->UnboundLocalError(co->varnames[byte.arg]);
  193. frame->_locals[byte.arg] = PY_NULL;
  194. DISPATCH();
  195. TARGET(DELETE_NAME)
  196. _name = StrName(byte.arg);
  197. if(frame->_callable != nullptr){
  198. PyObject** slot = frame->_locals.try_get_name(_name);
  199. if(slot == nullptr) vm->UnboundLocalError(_name);
  200. *slot = PY_NULL;
  201. }else{
  202. if(!frame->f_globals().del(_name)) vm->NameError(_name);
  203. }
  204. DISPATCH();
  205. TARGET(DELETE_GLOBAL)
  206. _name = StrName(byte.arg);
  207. if(!frame->f_globals().del(_name)) vm->NameError(_name);
  208. DISPATCH();
  209. TARGET(DELETE_ATTR)
  210. _0 = POPX();
  211. _name = StrName(byte.arg);
  212. if(is_tagged(_0) || !_0->is_attr_valid()) TypeError("cannot delete attribute");
  213. if(!_0->attr().del(_name)) AttributeError(_0, _name);
  214. DISPATCH();
  215. TARGET(DELETE_SUBSCR)
  216. _1 = POPX();
  217. _0 = POPX();
  218. _ti = _inst_type_info(_0);
  219. if(_ti->m__delitem__){
  220. _ti->m__delitem__(this, _0, _1);
  221. }else{
  222. call_method(_0, __delitem__, _1);
  223. }
  224. DISPATCH();
  225. /*****************************************/
  226. TARGET(BUILD_LONG) {
  227. PK_LOCAL_STATIC const StrName m_long("long");
  228. _0 = builtins->attr().try_get(m_long);
  229. if(_0 == nullptr) AttributeError(builtins, m_long);
  230. TOP() = call(_0, TOP());
  231. } DISPATCH();
  232. TARGET(BUILD_BYTES) {
  233. const Str& s = CAST(Str&, TOP());
  234. unsigned char* p = new unsigned char[s.size];
  235. memcpy(p, s.data, s.size);
  236. TOP() = VAR(Bytes(p, s.size));
  237. } DISPATCH();
  238. TARGET(BUILD_TUPLE)
  239. _0 = VAR(STACK_VIEW(byte.arg).to_tuple());
  240. STACK_SHRINK(byte.arg);
  241. PUSH(_0);
  242. DISPATCH();
  243. TARGET(BUILD_LIST)
  244. _0 = VAR(STACK_VIEW(byte.arg).to_list());
  245. STACK_SHRINK(byte.arg);
  246. PUSH(_0);
  247. DISPATCH();
  248. TARGET(BUILD_DICT)
  249. if(byte.arg == 0){
  250. PUSH(VAR(Dict(this)));
  251. DISPATCH();
  252. }
  253. _0 = VAR(STACK_VIEW(byte.arg).to_list());
  254. _0 = call(_t(tp_dict), _0);
  255. STACK_SHRINK(byte.arg);
  256. PUSH(_0);
  257. DISPATCH();
  258. TARGET(BUILD_SET)
  259. _0 = VAR(STACK_VIEW(byte.arg).to_list());
  260. _0 = call(builtins->attr(pk_id_set), _0);
  261. STACK_SHRINK(byte.arg);
  262. PUSH(_0);
  263. DISPATCH();
  264. TARGET(BUILD_SLICE)
  265. _2 = POPX(); // step
  266. _1 = POPX(); // stop
  267. _0 = POPX(); // start
  268. PUSH(VAR(Slice(_0, _1, _2)));
  269. DISPATCH();
  270. TARGET(BUILD_STRING) {
  271. std::stringstream ss;
  272. ArgsView view = STACK_VIEW(byte.arg);
  273. for(PyObject* obj : view) ss << CAST(Str&, py_str(obj));
  274. STACK_SHRINK(byte.arg);
  275. PUSH(VAR(ss.str()));
  276. } DISPATCH();
  277. /*****************************************/
  278. TARGET(BUILD_TUPLE_UNPACK) {
  279. auto _lock = heap.gc_scope_lock();
  280. List list;
  281. _unpack_as_list(STACK_VIEW(byte.arg), list);
  282. STACK_SHRINK(byte.arg);
  283. _0 = VAR(Tuple(std::move(list)));
  284. PUSH(_0);
  285. } DISPATCH();
  286. TARGET(BUILD_LIST_UNPACK) {
  287. auto _lock = heap.gc_scope_lock();
  288. List list;
  289. _unpack_as_list(STACK_VIEW(byte.arg), list);
  290. STACK_SHRINK(byte.arg);
  291. _0 = VAR(std::move(list));
  292. PUSH(_0);
  293. } DISPATCH();
  294. TARGET(BUILD_DICT_UNPACK) {
  295. auto _lock = heap.gc_scope_lock();
  296. Dict dict(this);
  297. _unpack_as_dict(STACK_VIEW(byte.arg), dict);
  298. STACK_SHRINK(byte.arg);
  299. _0 = VAR(std::move(dict));
  300. PUSH(_0);
  301. } DISPATCH();
  302. TARGET(BUILD_SET_UNPACK) {
  303. auto _lock = heap.gc_scope_lock();
  304. List list;
  305. _unpack_as_list(STACK_VIEW(byte.arg), list);
  306. STACK_SHRINK(byte.arg);
  307. _0 = VAR(std::move(list));
  308. _0 = call(builtins->attr(pk_id_set), _0);
  309. PUSH(_0);
  310. } DISPATCH();
  311. /*****************************************/
  312. #define PREDICT_INT_OP(op) \
  313. if(is_small_int(TOP()) && is_small_int(SECOND())){ \
  314. _1 = POPX(); \
  315. _0 = TOP(); \
  316. if constexpr(#op[0] == '/' || #op[0] == '%'){ \
  317. if(_py_sint(_1) == 0) ZeroDivisionError(); \
  318. } \
  319. TOP() = VAR(_py_sint(_0) op _py_sint(_1)); \
  320. DISPATCH(); \
  321. }
  322. #define BINARY_OP_SPECIAL(func) \
  323. _1 = POPX(); \
  324. _0 = TOP(); \
  325. _ti = _inst_type_info(_0); \
  326. if(_ti->m##func){ \
  327. TOP() = _ti->m##func(this, _0, _1); \
  328. }else{ \
  329. PyObject* self; \
  330. _2 = get_unbound_method(_0, func, &self, false); \
  331. if(_2 != nullptr) TOP() = call_method(self, _2, _1); \
  332. else TOP() = NotImplemented; \
  333. }
  334. #define BINARY_OP_RSPECIAL(op, func) \
  335. if(TOP() == NotImplemented){ \
  336. PyObject* self; \
  337. _2 = get_unbound_method(_1, func, &self, false); \
  338. if(_2 != nullptr) TOP() = call_method(self, _2, _0); \
  339. else BinaryOptError(op); \
  340. if(TOP() == NotImplemented) BinaryOptError(op); \
  341. }
  342. TARGET(BINARY_TRUEDIV)
  343. BINARY_OP_SPECIAL(__truediv__);
  344. if(TOP() == NotImplemented) BinaryOptError("/");
  345. DISPATCH();
  346. TARGET(BINARY_POW)
  347. BINARY_OP_SPECIAL(__pow__);
  348. if(TOP() == NotImplemented) BinaryOptError("**");
  349. DISPATCH();
  350. TARGET(BINARY_ADD)
  351. PREDICT_INT_OP(+);
  352. BINARY_OP_SPECIAL(__add__);
  353. BINARY_OP_RSPECIAL("+", __radd__);
  354. DISPATCH()
  355. TARGET(BINARY_SUB)
  356. PREDICT_INT_OP(-);
  357. BINARY_OP_SPECIAL(__sub__);
  358. BINARY_OP_RSPECIAL("-", __rsub__);
  359. DISPATCH()
  360. TARGET(BINARY_MUL)
  361. BINARY_OP_SPECIAL(__mul__);
  362. BINARY_OP_RSPECIAL("*", __rmul__);
  363. DISPATCH()
  364. TARGET(BINARY_FLOORDIV)
  365. PREDICT_INT_OP(/);
  366. BINARY_OP_SPECIAL(__floordiv__);
  367. if(TOP() == NotImplemented) BinaryOptError("//");
  368. DISPATCH()
  369. TARGET(BINARY_MOD)
  370. PREDICT_INT_OP(%);
  371. BINARY_OP_SPECIAL(__mod__);
  372. if(TOP() == NotImplemented) BinaryOptError("%");
  373. DISPATCH()
  374. TARGET(COMPARE_LT)
  375. BINARY_OP_SPECIAL(__lt__);
  376. BINARY_OP_RSPECIAL("<", __gt__);
  377. DISPATCH()
  378. TARGET(COMPARE_LE)
  379. BINARY_OP_SPECIAL(__le__);
  380. BINARY_OP_RSPECIAL("<=", __ge__);
  381. DISPATCH()
  382. TARGET(COMPARE_EQ)
  383. _1 = POPX();
  384. _0 = TOP();
  385. TOP() = VAR(py_equals(_0, _1));
  386. DISPATCH()
  387. TARGET(COMPARE_NE)
  388. _1 = POPX();
  389. _0 = TOP();
  390. TOP() = VAR(!py_equals(_0, _1));
  391. DISPATCH()
  392. TARGET(COMPARE_GT)
  393. BINARY_OP_SPECIAL(__gt__);
  394. BINARY_OP_RSPECIAL(">", __lt__);
  395. DISPATCH()
  396. TARGET(COMPARE_GE)
  397. BINARY_OP_SPECIAL(__ge__);
  398. BINARY_OP_RSPECIAL(">=", __le__);
  399. DISPATCH()
  400. TARGET(BITWISE_LSHIFT)
  401. PREDICT_INT_OP(<<);
  402. BINARY_OP_SPECIAL(__lshift__);
  403. if(TOP() == NotImplemented) BinaryOptError("<<");
  404. DISPATCH()
  405. TARGET(BITWISE_RSHIFT)
  406. PREDICT_INT_OP(>>);
  407. BINARY_OP_SPECIAL(__rshift__);
  408. if(TOP() == NotImplemented) BinaryOptError(">>");
  409. DISPATCH()
  410. TARGET(BITWISE_AND)
  411. PREDICT_INT_OP(&);
  412. BINARY_OP_SPECIAL(__and__);
  413. if(TOP() == NotImplemented) BinaryOptError("&");
  414. DISPATCH()
  415. TARGET(BITWISE_OR)
  416. PREDICT_INT_OP(|);
  417. BINARY_OP_SPECIAL(__or__);
  418. if(TOP() == NotImplemented) BinaryOptError("|");
  419. DISPATCH()
  420. TARGET(BITWISE_XOR)
  421. PREDICT_INT_OP(^);
  422. BINARY_OP_SPECIAL(__xor__);
  423. if(TOP() == NotImplemented) BinaryOptError("^");
  424. DISPATCH()
  425. TARGET(BINARY_MATMUL)
  426. BINARY_OP_SPECIAL(__matmul__);
  427. if(TOP() == NotImplemented) BinaryOptError("@");
  428. DISPATCH();
  429. #undef BINARY_OP_SPECIAL
  430. #undef PREDICT_INT_OP
  431. TARGET(IS_OP)
  432. _1 = POPX(); // rhs
  433. _0 = TOP(); // lhs
  434. TOP() = VAR(static_cast<bool>((_0==_1) ^ byte.arg));
  435. DISPATCH();
  436. TARGET(CONTAINS_OP)
  437. // a in b -> b __contains__ a
  438. _ti = _inst_type_info(TOP());
  439. if(_ti->m__contains__){
  440. _0 = _ti->m__contains__(this, TOP(), SECOND());
  441. }else{
  442. _0 = call_method(TOP(), __contains__, SECOND());
  443. }
  444. POP();
  445. TOP() = VAR(static_cast<bool>((int)CAST(bool, _0) ^ byte.arg));
  446. DISPATCH();
  447. /*****************************************/
  448. TARGET(JUMP_ABSOLUTE)
  449. frame->jump_abs(byte.arg);
  450. DISPATCH();
  451. TARGET(POP_JUMP_IF_FALSE)
  452. if(!py_bool(POPX())) frame->jump_abs(byte.arg);
  453. DISPATCH();
  454. TARGET(POP_JUMP_IF_TRUE)
  455. if(py_bool(POPX())) frame->jump_abs(byte.arg);
  456. DISPATCH();
  457. TARGET(JUMP_IF_TRUE_OR_POP)
  458. if(py_bool(TOP()) == true) frame->jump_abs(byte.arg);
  459. else POP();
  460. DISPATCH();
  461. TARGET(JUMP_IF_FALSE_OR_POP)
  462. if(py_bool(TOP()) == false) frame->jump_abs(byte.arg);
  463. else POP();
  464. DISPATCH();
  465. TARGET(SHORTCUT_IF_FALSE_OR_POP)
  466. if(py_bool(TOP()) == false){ // [b, False]
  467. STACK_SHRINK(2); // []
  468. PUSH(vm->False); // [False]
  469. frame->jump_abs(byte.arg);
  470. } else POP(); // [b]
  471. DISPATCH();
  472. TARGET(LOOP_CONTINUE)
  473. frame->jump_abs(co_blocks[byte.arg].start);
  474. DISPATCH();
  475. TARGET(LOOP_BREAK)
  476. frame->jump_abs_break(co_blocks[byte.arg].get_break_end());
  477. DISPATCH();
  478. TARGET(GOTO) {
  479. _name = StrName(byte.arg);
  480. int index = co->labels.try_get(_name);
  481. if(index < 0) _error("KeyError", fmt("label ", _name.escape(), " not found"));
  482. frame->jump_abs_break(index);
  483. } DISPATCH();
  484. /*****************************************/
  485. TARGET(EVAL)
  486. _0 = builtins->attr(pk_id_eval);
  487. TOP() = call(_0, TOP());
  488. DISPATCH();
  489. TARGET(REPR)
  490. TOP() = py_repr(TOP());
  491. DISPATCH();
  492. TARGET(CALL)
  493. _0 = vectorcall(
  494. byte.arg & 0xFFFF, // ARGC
  495. (byte.arg>>16) & 0xFFFF, // KWARGC
  496. true
  497. );
  498. if(_0 == PY_OP_CALL) DISPATCH_OP_CALL();
  499. PUSH(_0);
  500. DISPATCH();
  501. TARGET(CALL_TP)
  502. // [callable, <self>, args: tuple, kwargs: dict | NULL]
  503. if(byte.arg){
  504. _2 = POPX();
  505. _1 = POPX();
  506. for(PyObject* obj: _CAST(Tuple&, _1)) PUSH(obj);
  507. _CAST(Dict&, _2).apply([this](PyObject* k, PyObject* v){
  508. PUSH(VAR(StrName(CAST(Str&, k)).index));
  509. PUSH(v);
  510. });
  511. _0 = vectorcall(
  512. _CAST(Tuple&, _1).size(), // ARGC
  513. _CAST(Dict&, _2).size(), // KWARGC
  514. true
  515. );
  516. }else{
  517. // no **kwargs
  518. _1 = POPX();
  519. for(PyObject* obj: _CAST(Tuple&, _1)) PUSH(obj);
  520. _0 = vectorcall(
  521. _CAST(Tuple&, _1).size(), // ARGC
  522. 0, // KWARGC
  523. true
  524. );
  525. }
  526. if(_0 == PY_OP_CALL) DISPATCH_OP_CALL();
  527. PUSH(_0);
  528. DISPATCH();
  529. TARGET(RETURN_VALUE)
  530. _0 = POPX();
  531. _pop_frame();
  532. if(frame.index == base_id){ // [ frameBase<- ]
  533. return _0;
  534. }else{
  535. frame = top_frame();
  536. PUSH(_0);
  537. goto __NEXT_FRAME;
  538. }
  539. TARGET(YIELD_VALUE)
  540. return PY_OP_YIELD;
  541. /*****************************************/
  542. TARGET(LIST_APPEND)
  543. _0 = POPX();
  544. CAST(List&, SECOND()).push_back(_0);
  545. DISPATCH();
  546. TARGET(DICT_ADD) {
  547. _0 = POPX();
  548. Tuple& t = CAST(Tuple&, _0);
  549. call_method(SECOND(), __setitem__, t[0], t[1]);
  550. } DISPATCH();
  551. TARGET(SET_ADD)
  552. _0 = POPX();
  553. call_method(SECOND(), pk_id_add, _0);
  554. DISPATCH();
  555. /*****************************************/
  556. TARGET(UNARY_NEGATIVE)
  557. TOP() = py_negate(TOP());
  558. DISPATCH();
  559. TARGET(UNARY_NOT)
  560. TOP() = VAR(!py_bool(TOP()));
  561. DISPATCH();
  562. TARGET(UNARY_STAR)
  563. TOP() = VAR(StarWrapper(byte.arg, TOP()));
  564. DISPATCH();
  565. TARGET(UNARY_INVERT)
  566. _ti = _inst_type_info(TOP());
  567. if(_ti->m__invert__) _0 = _ti->m__invert__(this, TOP());
  568. else _0 = call_method(TOP(), __invert__);
  569. TOP() = _0;
  570. DISPATCH();
  571. /*****************************************/
  572. TARGET(GET_ITER)
  573. TOP() = py_iter(TOP());
  574. DISPATCH();
  575. TARGET(FOR_ITER)
  576. _0 = py_next(TOP());
  577. if(_0 != StopIteration){
  578. PUSH(_0);
  579. }else{
  580. frame->jump_abs_break(co_blocks[byte.block].end);
  581. }
  582. DISPATCH();
  583. /*****************************************/
  584. TARGET(IMPORT_PATH)
  585. _0 = co_consts[byte.arg];
  586. PUSH(py_import(CAST(Str&, _0)));
  587. DISPATCH();
  588. TARGET(POP_IMPORT_STAR) {
  589. _0 = POPX(); // pop the module
  590. _1 = _0->attr().try_get(__all__);
  591. if(_1 != nullptr){
  592. for(PyObject* key: CAST(List&, _1)){
  593. _name = StrName::get(CAST(Str&, key).sv());
  594. PyObject* value = _0->attr().try_get(_name);
  595. if(value == nullptr){
  596. ImportError(fmt("cannot import name ", _name.escape()));
  597. }else{
  598. frame->f_globals().set(_name, value);
  599. }
  600. }
  601. }else{
  602. for(auto& [name, value]: _0->attr().items()){
  603. std::string_view s = name.sv();
  604. if(s.empty() || s[0] == '_') continue;
  605. frame->f_globals().set(name, value);
  606. }
  607. }
  608. } DISPATCH();
  609. /*****************************************/
  610. TARGET(UNPACK_SEQUENCE){
  611. auto _lock = heap.gc_scope_lock(); // lock the gc via RAII!!
  612. _0 = py_iter(POPX());
  613. for(int i=0; i<byte.arg; i++){
  614. _1 = py_next(_0);
  615. if(_1 == StopIteration) ValueError("not enough values to unpack");
  616. PUSH(_1);
  617. }
  618. if(py_next(_0) != StopIteration) ValueError("too many values to unpack");
  619. } DISPATCH();
  620. TARGET(UNPACK_EX) {
  621. auto _lock = heap.gc_scope_lock(); // lock the gc via RAII!!
  622. _0 = py_iter(POPX());
  623. for(int i=0; i<byte.arg; i++){
  624. _1 = py_next(_0);
  625. if(_1 == StopIteration) ValueError("not enough values to unpack");
  626. PUSH(_1);
  627. }
  628. List extras;
  629. while(true){
  630. _1 = py_next(_0);
  631. if(_1 == StopIteration) break;
  632. extras.push_back(_1);
  633. }
  634. PUSH(VAR(extras));
  635. } DISPATCH();
  636. /*****************************************/
  637. TARGET(BEGIN_CLASS)
  638. _name = StrName(byte.arg);
  639. _0 = POPX(); // super
  640. if(_0 == None) _0 = _t(tp_object);
  641. check_non_tagged_type(_0, tp_type);
  642. _1 = new_type_object(frame->_module, _name, PK_OBJ_GET(Type, _0));
  643. PUSH(_1);
  644. DISPATCH();
  645. TARGET(END_CLASS)
  646. _0 = POPX();
  647. _0->attr()._try_perfect_rehash();
  648. DISPATCH();
  649. TARGET(STORE_CLASS_ATTR){
  650. _name = StrName(byte.arg);
  651. _0 = POPX();
  652. if(is_non_tagged_type(_0, tp_function)){
  653. _0->attr().set(__class__, TOP());
  654. }
  655. TOP()->attr().set(_name, _0);
  656. } DISPATCH();
  657. /*****************************************/
  658. TARGET(WITH_ENTER)
  659. call_method(POPX(), __enter__);
  660. DISPATCH();
  661. TARGET(WITH_EXIT)
  662. call_method(POPX(), __exit__);
  663. DISPATCH();
  664. /*****************************************/
  665. TARGET(EXCEPTION_MATCH) {
  666. const auto& e = CAST(Exception&, TOP());
  667. _name = StrName(byte.arg);
  668. PUSH(VAR(e.match_type(_name)));
  669. } DISPATCH();
  670. TARGET(RAISE) {
  671. _0 = POPX();
  672. Str msg = _0 == None ? "" : CAST(Str, py_str(_0));
  673. _error(StrName(byte.arg), msg);
  674. } DISPATCH();
  675. TARGET(RAISE_ASSERT)
  676. if(byte.arg){
  677. _0 = py_str(POPX());
  678. _error("AssertionError", CAST(Str, _0));
  679. }else{
  680. _error("AssertionError", "");
  681. }
  682. DISPATCH();
  683. TARGET(RE_RAISE) _raise(true); DISPATCH();
  684. TARGET(POP_EXCEPTION) _last_exception = POPX(); DISPATCH();
  685. /*****************************************/
  686. TARGET(FORMAT_STRING) {
  687. _0 = POPX();
  688. const Str& spec = CAST(Str&, co_consts[byte.arg]);
  689. PUSH(format(spec, _0));
  690. } DISPATCH();
  691. /*****************************************/
  692. TARGET(INC_FAST){
  693. PyObject** p = &frame->_locals[byte.arg];
  694. if(*p == PY_NULL) vm->NameError(co->varnames[byte.arg]);
  695. *p = VAR(CAST(i64, *p) + 1);
  696. } DISPATCH();
  697. TARGET(DEC_FAST){
  698. PyObject** p = &frame->_locals[byte.arg];
  699. if(*p == PY_NULL) vm->NameError(co->varnames[byte.arg]);
  700. *p = VAR(CAST(i64, *p) - 1);
  701. } DISPATCH();
  702. TARGET(INC_GLOBAL){
  703. _name = StrName(byte.arg);
  704. PyObject** p = frame->f_globals().try_get_2(_name);
  705. if(p == nullptr) vm->NameError(_name);
  706. *p = VAR(CAST(i64, *p) + 1);
  707. } DISPATCH();
  708. TARGET(DEC_GLOBAL){
  709. _name = StrName(byte.arg);
  710. PyObject** p = frame->f_globals().try_get_2(_name);
  711. if(p == nullptr) vm->NameError(_name);
  712. *p = VAR(CAST(i64, *p) - 1);
  713. } DISPATCH();
  714. #if !PK_ENABLE_COMPUTED_GOTO
  715. #if PK_DEBUG_EXTRA_CHECK
  716. default: throw std::runtime_error(fmt(OP_NAMES[byte.op], " is not implemented"));
  717. #else
  718. default: UNREACHABLE();
  719. #endif
  720. }
  721. #endif
  722. }
  723. #undef DISPATCH
  724. #undef TARGET
  725. #undef DISPATCH_OP_CALL
  726. #undef CEVAL_STEP
  727. /**********************************************************************/
  728. UNREACHABLE();
  729. }catch(HandledException& e){
  730. PK_UNUSED(e);
  731. continue;
  732. }catch(UnhandledException& e){
  733. PK_UNUSED(e);
  734. PyObject* obj = POPX();
  735. Exception& _e = CAST(Exception&, obj);
  736. _pop_frame();
  737. if(callstack.empty()){
  738. #if PK_DEBUG_FULL_EXCEPTION
  739. std::cerr << _e.summary() << std::endl;
  740. #endif
  741. throw _e;
  742. }
  743. frame = top_frame();
  744. PUSH(obj);
  745. if(frame.index < base_id) throw ToBeRaisedException();
  746. need_raise = true;
  747. }catch(ToBeRaisedException& e){
  748. PK_UNUSED(e);
  749. need_raise = true;
  750. }
  751. }
  752. }
  753. #undef TOP
  754. #undef SECOND
  755. #undef THIRD
  756. #undef PEEK
  757. #undef STACK_SHRINK
  758. #undef PUSH
  759. #undef POP
  760. #undef POPX
  761. #undef STACK_VIEW
  762. #undef DISPATCH
  763. #undef TARGET
  764. #undef DISPATCH_OP_CALL
  765. } // namespace pkpy