ceval.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. #include "pocketpy/ceval.h"
  2. namespace pkpy{
  3. #define PREDICT_INT_OP(op) \
  4. if(is_small_int(_0) && is_small_int(_1)){ \
  5. TOP() = VAR((PK_BITS(_0)>>2) op (PK_BITS(_1)>>2)); \
  6. DISPATCH() \
  7. }
  8. #define PREDICT_INT_DIV_OP(op) \
  9. if(is_small_int(_0) && is_small_int(_1)){ \
  10. if(_1 == (PyObject*)0b10) ZeroDivisionError(); \
  11. TOP() = VAR((PK_BITS(_0)>>2) op (PK_BITS(_1)>>2)); \
  12. DISPATCH() \
  13. }
  14. #define BINARY_F_COMPARE(func, op, rfunc) \
  15. PyObject* ret; \
  16. const PyTypeInfo* _ti = _inst_type_info(_0); \
  17. if(_ti->m##func){ \
  18. ret = _ti->m##func(this, _0, _1); \
  19. }else{ \
  20. PyObject* self; \
  21. PyObject* _2 = get_unbound_method(_0, func, &self, false); \
  22. if(_2 != nullptr) ret = call_method(self, _2, _1); \
  23. else ret = NotImplemented; \
  24. } \
  25. if(ret == NotImplemented){ \
  26. PyObject* self; \
  27. PyObject* _2 = get_unbound_method(_1, rfunc, &self, false); \
  28. if(_2 != nullptr) ret = call_method(self, _2, _0); \
  29. else BinaryOptError(op, _0, _1); \
  30. if(ret == NotImplemented) BinaryOptError(op, _0, _1); \
  31. }
  32. void VM::__op_unpack_sequence(uint16_t arg){
  33. PyObject* _0 = POPX();
  34. if(is_type(_0, VM::tp_tuple)){
  35. // fast path for tuple
  36. Tuple& tuple = PK_OBJ_GET(Tuple, _0);
  37. if(tuple.size() == arg){
  38. for(PyObject* obj: tuple) PUSH(obj);
  39. }else{
  40. ValueError(_S("expected ", (int)arg, " values to unpack, got ", (int)tuple.size()));
  41. }
  42. }else{
  43. auto _lock = heap.gc_scope_lock(); // lock the gc via RAII!!
  44. _0 = py_iter(_0);
  45. const PyTypeInfo* ti = _inst_type_info(_0);
  46. for(int i=0; i<arg; i++){
  47. PyObject* _1 = _py_next(ti, _0);
  48. if(_1 == StopIteration) ValueError("not enough values to unpack");
  49. PUSH(_1);
  50. }
  51. if(_py_next(ti, _0) != StopIteration) ValueError("too many values to unpack");
  52. }
  53. }
  54. bool VM::py_lt(PyObject* _0, PyObject* _1){
  55. BINARY_F_COMPARE(__lt__, "<", __gt__);
  56. return ret == True;
  57. }
  58. bool VM::py_le(PyObject* _0, PyObject* _1){
  59. BINARY_F_COMPARE(__le__, "<=", __ge__);
  60. return ret == True;
  61. }
  62. bool VM::py_gt(PyObject* _0, PyObject* _1){
  63. BINARY_F_COMPARE(__gt__, ">", __lt__);
  64. return ret == True;
  65. }
  66. bool VM::py_ge(PyObject* _0, PyObject* _1){
  67. BINARY_F_COMPARE(__ge__, ">=", __le__);
  68. return ret == True;
  69. }
  70. #undef BINARY_F_COMPARE
  71. PyObject* VM::__run_top_frame(){
  72. Frame* frame = top_frame();
  73. const Frame* base_frame = frame;
  74. bool need_raise = false;
  75. while(true){
  76. try{
  77. if(need_raise){ need_raise = false; __raise(); }
  78. /**********************************************************************/
  79. /* NOTE:
  80. * Be aware of accidental gc!
  81. * DO NOT leave any strong reference of PyObject* in the C stack
  82. */
  83. {
  84. #if PK_ENABLE_PROFILER
  85. #define CEVAL_STEP_CALLBACK() \
  86. if(_ceval_on_step) _ceval_on_step(this, frame, byte); \
  87. if(_profiler) _profiler->_step(callstack.size(), frame); \
  88. if(!_next_breakpoint.empty()) { _next_breakpoint._step(this); }
  89. #else
  90. #define CEVAL_STEP_CALLBACK() \
  91. if(_ceval_on_step) _ceval_on_step(this, frame, byte);
  92. #endif
  93. __NEXT_FRAME:
  94. // cache
  95. const CodeObject* co = frame->co;
  96. const Bytecode* co_codes = co->codes.data();
  97. Bytecode byte = co_codes[frame->next_bytecode()];
  98. CEVAL_STEP_CALLBACK();
  99. #define DISPATCH() { byte = co_codes[frame->next_bytecode()]; CEVAL_STEP_CALLBACK(); goto __NEXT_STEP;}
  100. __NEXT_STEP:;
  101. #if PK_DEBUG_CEVAL_STEP
  102. _log_s_data();
  103. #endif
  104. switch ((Opcode)byte.op)
  105. {
  106. case OP_NO_OP: DISPATCH();
  107. /*****************************************/
  108. case OP_POP_TOP: POP(); DISPATCH();
  109. case OP_DUP_TOP: PUSH(TOP()); DISPATCH();
  110. case OP_ROT_TWO: std::swap(TOP(), SECOND()); DISPATCH();
  111. case OP_ROT_THREE:{
  112. PyObject* _0 = TOP();
  113. TOP() = SECOND();
  114. SECOND() = THIRD();
  115. THIRD() = _0;
  116. } DISPATCH();
  117. case OP_PRINT_EXPR:{
  118. if(TOP() != None) stdout_write(CAST(Str&, py_repr(TOP())) + "\n");
  119. POP();
  120. } DISPATCH();
  121. /*****************************************/
  122. case OP_LOAD_CONST:
  123. PUSH(co->consts[byte.arg]);
  124. DISPATCH();
  125. case OP_LOAD_NONE: PUSH(None); DISPATCH();
  126. case OP_LOAD_TRUE: PUSH(True); DISPATCH();
  127. case OP_LOAD_FALSE: PUSH(False); DISPATCH();
  128. /*****************************************/
  129. case OP_LOAD_SMALL_INT: PUSH((PyObject*)(uintptr_t)byte.arg); DISPATCH();
  130. /*****************************************/
  131. case OP_LOAD_ELLIPSIS: PUSH(Ellipsis); DISPATCH();
  132. case OP_LOAD_FUNCTION: {
  133. const FuncDecl_& decl = co->func_decls[byte.arg];
  134. PyObject* obj;
  135. if(decl->nested){
  136. NameDict_ captured = frame->_locals.to_namedict();
  137. obj = VAR(Function(decl, frame->_module, nullptr, captured));
  138. captured->set(decl->code->name, obj);
  139. }else{
  140. obj = VAR(Function(decl, frame->_module, nullptr, nullptr));
  141. }
  142. PUSH(obj);
  143. } DISPATCH();
  144. case OP_LOAD_NULL: PUSH(PY_NULL); DISPATCH();
  145. /*****************************************/
  146. case OP_LOAD_FAST: {
  147. PyObject* _0 = frame->_locals[byte.arg];
  148. if(_0 == PY_NULL) vm->UnboundLocalError(co->varnames[byte.arg]);
  149. PUSH(_0);
  150. } DISPATCH();
  151. case OP_LOAD_NAME: {
  152. StrName _name(byte.arg);
  153. PyObject** slot = frame->_locals.try_get_name(_name);
  154. if(slot != nullptr) {
  155. if(*slot == PY_NULL) vm->UnboundLocalError(_name);
  156. PUSH(*slot);
  157. DISPATCH();
  158. }
  159. PyObject* _0 = frame->f_closure_try_get(_name);
  160. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  161. _0 = frame->f_globals().try_get_likely_found(_name);
  162. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  163. _0 = vm->builtins->attr().try_get_likely_found(_name);
  164. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  165. vm->NameError(_name);
  166. } DISPATCH();
  167. case OP_LOAD_NONLOCAL: {
  168. StrName _name(byte.arg);
  169. PyObject* _0 = frame->f_closure_try_get(_name);
  170. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  171. _0 = frame->f_globals().try_get_likely_found(_name);
  172. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  173. _0 = vm->builtins->attr().try_get_likely_found(_name);
  174. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  175. vm->NameError(_name);
  176. } DISPATCH();
  177. case OP_LOAD_GLOBAL:{
  178. StrName _name(byte.arg);
  179. PyObject* _0 = frame->f_globals().try_get_likely_found(_name);
  180. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  181. _0 = vm->builtins->attr().try_get_likely_found(_name);
  182. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  183. vm->NameError(_name);
  184. } DISPATCH();
  185. case OP_LOAD_ATTR:{
  186. TOP() = getattr(TOP(), StrName(byte.arg));
  187. } DISPATCH();
  188. case OP_LOAD_CLASS_GLOBAL:{
  189. PK_ASSERT(_curr_class != nullptr);
  190. StrName _name(byte.arg);
  191. PyObject* _0 = getattr(_curr_class, _name, false);
  192. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  193. // load global if attribute not found
  194. _0 = frame->f_globals().try_get_likely_found(_name);
  195. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  196. _0 = vm->builtins->attr().try_get_likely_found(_name);
  197. if(_0 != nullptr) { PUSH(_0); DISPATCH(); }
  198. vm->NameError(_name);
  199. } DISPATCH();
  200. case OP_LOAD_METHOD:{
  201. PyObject* _0;
  202. TOP() = get_unbound_method(TOP(), StrName(byte.arg), &_0, true, true);
  203. PUSH(_0);
  204. }DISPATCH();
  205. case OP_LOAD_SUBSCR:{
  206. PyObject* _1 = POPX(); // b
  207. PyObject* _0 = TOP(); // a
  208. auto _ti = _inst_type_info(_0);
  209. if(_ti->m__getitem__){
  210. TOP() = _ti->m__getitem__(this, _0, _1);
  211. }else{
  212. TOP() = call_method(_0, __getitem__, _1);
  213. }
  214. } DISPATCH();
  215. case OP_LOAD_SUBSCR_FAST:{
  216. PyObject* _1 = frame->_locals[byte.arg];
  217. if(_1 == PY_NULL) vm->UnboundLocalError(co->varnames[byte.arg]);
  218. PyObject* _0 = TOP(); // a
  219. auto _ti = _inst_type_info(_0);
  220. if(_ti->m__getitem__){
  221. TOP() = _ti->m__getitem__(this, _0, _1);
  222. }else{
  223. TOP() = call_method(_0, __getitem__, _1);
  224. }
  225. } DISPATCH();
  226. case OP_LOAD_SUBSCR_SMALL_INT:{
  227. PyObject* _1 = (PyObject*)(uintptr_t)byte.arg;
  228. PyObject* _0 = TOP(); // a
  229. auto _ti = _inst_type_info(_0);
  230. if(_ti->m__getitem__){
  231. TOP() = _ti->m__getitem__(this, _0, _1);
  232. }else{
  233. TOP() = call_method(_0, __getitem__, _1);
  234. }
  235. } DISPATCH();
  236. case OP_STORE_FAST:
  237. frame->_locals[byte.arg] = POPX();
  238. DISPATCH();
  239. case OP_STORE_NAME:{
  240. StrName _name(byte.arg);
  241. PyObject* _0 = POPX();
  242. if(frame->_callable != nullptr){
  243. PyObject** slot = frame->_locals.try_get_name(_name);
  244. if(slot == nullptr) vm->UnboundLocalError(_name);
  245. *slot = _0;
  246. }else{
  247. frame->f_globals().set(_name, _0);
  248. }
  249. } DISPATCH();
  250. case OP_STORE_GLOBAL:
  251. frame->f_globals().set(StrName(byte.arg), POPX());
  252. DISPATCH();
  253. case OP_STORE_ATTR: {
  254. PyObject* _0 = TOP(); // a
  255. PyObject* _1 = SECOND(); // val
  256. setattr(_0, StrName(byte.arg), _1);
  257. STACK_SHRINK(2);
  258. } DISPATCH();
  259. case OP_STORE_SUBSCR:{
  260. PyObject* _2 = POPX(); // b
  261. PyObject* _1 = POPX(); // a
  262. PyObject* _0 = POPX(); // val
  263. auto _ti = _inst_type_info(_1);
  264. if(_ti->m__setitem__){
  265. _ti->m__setitem__(this, _1, _2, _0);
  266. }else{
  267. call_method(_1, __setitem__, _2, _0);
  268. }
  269. }DISPATCH();
  270. case OP_STORE_SUBSCR_FAST:{
  271. PyObject* _2 = frame->_locals[byte.arg]; // b
  272. if(_2 == PY_NULL) vm->UnboundLocalError(co->varnames[byte.arg]);
  273. PyObject* _1 = POPX(); // a
  274. PyObject* _0 = POPX(); // val
  275. auto _ti = _inst_type_info(_1);
  276. if(_ti->m__setitem__){
  277. _ti->m__setitem__(this, _1, _2, _0);
  278. }else{
  279. call_method(_1, __setitem__, _2, _0);
  280. }
  281. }DISPATCH();
  282. case OP_DELETE_FAST:{
  283. PyObject* _0 = frame->_locals[byte.arg];
  284. if(_0 == PY_NULL) vm->UnboundLocalError(co->varnames[byte.arg]);
  285. frame->_locals[byte.arg] = PY_NULL;
  286. }DISPATCH();
  287. case OP_DELETE_NAME:{
  288. StrName _name(byte.arg);
  289. if(frame->_callable != nullptr){
  290. PyObject** slot = frame->_locals.try_get_name(_name);
  291. if(slot == nullptr) vm->UnboundLocalError(_name);
  292. *slot = PY_NULL;
  293. }else{
  294. if(!frame->f_globals().del(_name)) vm->NameError(_name);
  295. }
  296. } DISPATCH();
  297. case OP_DELETE_GLOBAL:{
  298. StrName _name(byte.arg);
  299. if(!frame->f_globals().del(_name)) vm->NameError(_name);
  300. }DISPATCH();
  301. case OP_DELETE_ATTR:{
  302. PyObject* _0 = POPX();
  303. delattr(_0, StrName(byte.arg));
  304. } DISPATCH();
  305. case OP_DELETE_SUBSCR:{
  306. PyObject* _1 = POPX();
  307. PyObject* _0 = POPX();
  308. auto _ti = _inst_type_info(_0);
  309. if(_ti->m__delitem__){
  310. _ti->m__delitem__(this, _0, _1);
  311. }else{
  312. call_method(_0, __delitem__, _1);
  313. }
  314. }DISPATCH();
  315. /*****************************************/
  316. case OP_BUILD_LONG: {
  317. PyObject* _0 = builtins->attr().try_get_likely_found(pk_id_long);
  318. if(_0 == nullptr) AttributeError(builtins, pk_id_long);
  319. TOP() = call(_0, TOP());
  320. } DISPATCH();
  321. case OP_BUILD_IMAG: {
  322. PyObject* _0 = builtins->attr().try_get_likely_found(pk_id_complex);
  323. if(_0 == nullptr) AttributeError(builtins, pk_id_long);
  324. TOP() = call(_0, VAR(0), TOP());
  325. } DISPATCH();
  326. case OP_BUILD_BYTES: {
  327. const Str& s = CAST(Str&, TOP());
  328. unsigned char* p = new unsigned char[s.size];
  329. memcpy(p, s.data, s.size);
  330. TOP() = VAR(Bytes(p, s.size));
  331. } DISPATCH();
  332. case OP_BUILD_TUPLE:{
  333. PyObject* _0 = VAR(STACK_VIEW(byte.arg).to_tuple());
  334. STACK_SHRINK(byte.arg);
  335. PUSH(_0);
  336. } DISPATCH();
  337. case OP_BUILD_LIST:{
  338. PyObject* _0 = VAR(STACK_VIEW(byte.arg).to_list());
  339. STACK_SHRINK(byte.arg);
  340. PUSH(_0);
  341. } DISPATCH();
  342. case OP_BUILD_DICT:{
  343. if(byte.arg == 0){
  344. PUSH(VAR(Dict(this)));
  345. DISPATCH();
  346. }
  347. PyObject* _0 = VAR(STACK_VIEW(byte.arg).to_list());
  348. _0 = call(_t(tp_dict), _0);
  349. STACK_SHRINK(byte.arg);
  350. PUSH(_0);
  351. } DISPATCH();
  352. case OP_BUILD_SET:{
  353. PyObject* _0 = VAR(STACK_VIEW(byte.arg).to_list());
  354. _0 = call(builtins->attr(pk_id_set), _0);
  355. STACK_SHRINK(byte.arg);
  356. PUSH(_0);
  357. } DISPATCH();
  358. case OP_BUILD_SLICE:{
  359. PyObject* _2 = POPX(); // step
  360. PyObject* _1 = POPX(); // stop
  361. PyObject* _0 = POPX(); // start
  362. PUSH(VAR(Slice(_0, _1, _2)));
  363. } DISPATCH();
  364. case OP_BUILD_STRING: {
  365. SStream ss;
  366. ArgsView view = STACK_VIEW(byte.arg);
  367. for(PyObject* obj : view) ss << CAST(Str&, py_str(obj));
  368. STACK_SHRINK(byte.arg);
  369. PUSH(VAR(ss.str()));
  370. } DISPATCH();
  371. /*****************************************/
  372. case OP_BUILD_TUPLE_UNPACK: {
  373. auto _lock = heap.gc_scope_lock();
  374. List list;
  375. _unpack_as_list(STACK_VIEW(byte.arg), list);
  376. STACK_SHRINK(byte.arg);
  377. PyObject* _0 = VAR(Tuple(std::move(list)));
  378. PUSH(_0);
  379. } DISPATCH();
  380. case OP_BUILD_LIST_UNPACK: {
  381. auto _lock = heap.gc_scope_lock();
  382. List list;
  383. _unpack_as_list(STACK_VIEW(byte.arg), list);
  384. STACK_SHRINK(byte.arg);
  385. PyObject* _0 = VAR(std::move(list));
  386. PUSH(_0);
  387. } DISPATCH();
  388. case OP_BUILD_DICT_UNPACK: {
  389. auto _lock = heap.gc_scope_lock();
  390. Dict dict(this);
  391. _unpack_as_dict(STACK_VIEW(byte.arg), dict);
  392. STACK_SHRINK(byte.arg);
  393. PyObject* _0 = VAR(std::move(dict));
  394. PUSH(_0);
  395. } DISPATCH();
  396. case OP_BUILD_SET_UNPACK: {
  397. auto _lock = heap.gc_scope_lock();
  398. List list;
  399. _unpack_as_list(STACK_VIEW(byte.arg), list);
  400. STACK_SHRINK(byte.arg);
  401. PyObject* _0 = VAR(std::move(list));
  402. _0 = call(builtins->attr(pk_id_set), _0);
  403. PUSH(_0);
  404. } DISPATCH();
  405. /*****************************************/
  406. #define BINARY_OP_SPECIAL(func) \
  407. _ti = _inst_type_info(_0); \
  408. if(_ti->m##func){ \
  409. TOP() = _ti->m##func(this, _0, _1); \
  410. }else{ \
  411. PyObject* self; \
  412. PyObject* _2 = get_unbound_method(_0, func, &self, false); \
  413. if(_2 != nullptr) TOP() = call_method(self, _2, _1); \
  414. else TOP() = NotImplemented; \
  415. }
  416. #define BINARY_OP_RSPECIAL(op, func) \
  417. if(TOP() == NotImplemented){ \
  418. PyObject* self; \
  419. PyObject* _2 = get_unbound_method(_1, func, &self, false); \
  420. if(_2 != nullptr) TOP() = call_method(self, _2, _0); \
  421. else BinaryOptError(op, _0, _1); \
  422. if(TOP() == NotImplemented) BinaryOptError(op, _0, _1); \
  423. }
  424. case OP_BINARY_TRUEDIV:{
  425. PyObject* _1 = POPX();
  426. PyObject* _0 = TOP();
  427. const PyTypeInfo* _ti;
  428. BINARY_OP_SPECIAL(__truediv__);
  429. if(TOP() == NotImplemented) BinaryOptError("/", _0, _1);
  430. } DISPATCH();
  431. case OP_BINARY_POW:{
  432. PyObject* _1 = POPX();
  433. PyObject* _0 = TOP();
  434. const PyTypeInfo* _ti;
  435. BINARY_OP_SPECIAL(__pow__);
  436. if(TOP() == NotImplemented) BinaryOptError("**", _0, _1);
  437. } DISPATCH();
  438. case OP_BINARY_ADD:{
  439. PyObject* _1 = POPX();
  440. PyObject* _0 = TOP();
  441. PREDICT_INT_OP(+)
  442. const PyTypeInfo* _ti;
  443. BINARY_OP_SPECIAL(__add__);
  444. BINARY_OP_RSPECIAL("+", __radd__);
  445. } DISPATCH()
  446. case OP_BINARY_SUB:{
  447. PyObject* _1 = POPX();
  448. PyObject* _0 = TOP();
  449. PREDICT_INT_OP(-)
  450. const PyTypeInfo* _ti;
  451. BINARY_OP_SPECIAL(__sub__);
  452. BINARY_OP_RSPECIAL("-", __rsub__);
  453. } DISPATCH()
  454. case OP_BINARY_MUL:{
  455. PyObject* _1 = POPX();
  456. PyObject* _0 = TOP();
  457. PREDICT_INT_OP(*)
  458. const PyTypeInfo* _ti;
  459. BINARY_OP_SPECIAL(__mul__);
  460. BINARY_OP_RSPECIAL("*", __rmul__);
  461. } DISPATCH()
  462. case OP_BINARY_FLOORDIV:{
  463. PyObject* _1 = POPX();
  464. PyObject* _0 = TOP();
  465. PREDICT_INT_DIV_OP(/)
  466. const PyTypeInfo* _ti;
  467. BINARY_OP_SPECIAL(__floordiv__);
  468. if(TOP() == NotImplemented) BinaryOptError("//", _0, _1);
  469. } DISPATCH()
  470. case OP_BINARY_MOD:{
  471. PyObject* _1 = POPX();
  472. PyObject* _0 = TOP();
  473. PREDICT_INT_DIV_OP(%)
  474. const PyTypeInfo* _ti;
  475. BINARY_OP_SPECIAL(__mod__);
  476. if(TOP() == NotImplemented) BinaryOptError("%", _0, _1);
  477. } DISPATCH()
  478. case OP_COMPARE_LT:{
  479. PyObject* _1 = POPX();
  480. PyObject* _0 = TOP();
  481. PREDICT_INT_OP(<)
  482. TOP() = VAR(py_lt(_0, _1));
  483. } DISPATCH()
  484. case OP_COMPARE_LE:{
  485. PyObject* _1 = POPX();
  486. PyObject* _0 = TOP();
  487. PREDICT_INT_OP(<=)
  488. TOP() = VAR(py_le(_0, _1));
  489. } DISPATCH()
  490. case OP_COMPARE_EQ:{
  491. PyObject* _1 = POPX();
  492. PyObject* _0 = TOP();
  493. TOP() = VAR(py_eq(_0, _1));
  494. } DISPATCH()
  495. case OP_COMPARE_NE:{
  496. PyObject* _1 = POPX();
  497. PyObject* _0 = TOP();
  498. TOP() = VAR(py_ne(_0, _1));
  499. } DISPATCH()
  500. case OP_COMPARE_GT:{
  501. PyObject* _1 = POPX();
  502. PyObject* _0 = TOP();
  503. PREDICT_INT_OP(>)
  504. TOP() = VAR(py_gt(_0, _1));
  505. } DISPATCH()
  506. case OP_COMPARE_GE:{
  507. PyObject* _1 = POPX();
  508. PyObject* _0 = TOP();
  509. PREDICT_INT_OP(>=)
  510. TOP() = VAR(py_ge(_0, _1));
  511. } DISPATCH()
  512. case OP_BITWISE_LSHIFT:{
  513. PyObject* _1 = POPX();
  514. PyObject* _0 = TOP();
  515. PREDICT_INT_OP(<<)
  516. const PyTypeInfo* _ti;
  517. BINARY_OP_SPECIAL(__lshift__);
  518. if(TOP() == NotImplemented) BinaryOptError("<<", _0, _1);
  519. } DISPATCH()
  520. case OP_BITWISE_RSHIFT:{
  521. PyObject* _1 = POPX();
  522. PyObject* _0 = TOP();
  523. PREDICT_INT_OP(>>)
  524. const PyTypeInfo* _ti;
  525. BINARY_OP_SPECIAL(__rshift__);
  526. if(TOP() == NotImplemented) BinaryOptError(">>", _0, _1);
  527. } DISPATCH()
  528. case OP_BITWISE_AND:{
  529. PyObject* _1 = POPX();
  530. PyObject* _0 = TOP();
  531. PREDICT_INT_OP(&)
  532. const PyTypeInfo* _ti;
  533. BINARY_OP_SPECIAL(__and__);
  534. if(TOP() == NotImplemented) BinaryOptError("&", _0, _1);
  535. } DISPATCH()
  536. case OP_BITWISE_OR:{
  537. PyObject* _1 = POPX();
  538. PyObject* _0 = TOP();
  539. PREDICT_INT_OP(|)
  540. const PyTypeInfo* _ti;
  541. BINARY_OP_SPECIAL(__or__);
  542. if(TOP() == NotImplemented) BinaryOptError("|", _0, _1);
  543. } DISPATCH()
  544. case OP_BITWISE_XOR:{
  545. PyObject* _1 = POPX();
  546. PyObject* _0 = TOP();
  547. PREDICT_INT_OP(^)
  548. const PyTypeInfo* _ti;
  549. BINARY_OP_SPECIAL(__xor__);
  550. if(TOP() == NotImplemented) BinaryOptError("^", _0, _1);
  551. } DISPATCH()
  552. case OP_BINARY_MATMUL:{
  553. PyObject* _1 = POPX();
  554. PyObject* _0 = TOP();
  555. const PyTypeInfo* _ti;
  556. BINARY_OP_SPECIAL(__matmul__);
  557. if(TOP() == NotImplemented) BinaryOptError("@", _0, _1);
  558. } DISPATCH();
  559. #undef BINARY_OP_SPECIAL
  560. #undef BINARY_OP_RSPECIAL
  561. #undef PREDICT_INT_OP
  562. case OP_IS_OP:{
  563. PyObject* _1 = POPX(); // rhs
  564. PyObject* _0 = TOP(); // lhs
  565. TOP() = VAR(static_cast<bool>((_0==_1) ^ byte.arg));
  566. } DISPATCH();
  567. case OP_CONTAINS_OP:{
  568. // a in b -> b __contains__ a
  569. auto _ti = _inst_type_info(TOP());
  570. PyObject* _0;
  571. if(_ti->m__contains__){
  572. _0 = _ti->m__contains__(this, TOP(), SECOND());
  573. }else{
  574. _0 = call_method(TOP(), __contains__, SECOND());
  575. }
  576. POP();
  577. TOP() = VAR(static_cast<bool>((int)CAST(bool, _0) ^ byte.arg));
  578. } DISPATCH();
  579. /*****************************************/
  580. case OP_JUMP_ABSOLUTE:
  581. frame->jump_abs(byte.arg);
  582. DISPATCH();
  583. case OP_JUMP_ABSOLUTE_TOP:
  584. frame->jump_abs(_CAST(int, POPX()));
  585. DISPATCH();
  586. case OP_POP_JUMP_IF_FALSE:{
  587. if(!py_bool(TOP())) frame->jump_abs(byte.arg);
  588. POP();
  589. } DISPATCH();
  590. case OP_POP_JUMP_IF_TRUE:{
  591. if(py_bool(TOP())) frame->jump_abs(byte.arg);
  592. POP();
  593. } DISPATCH();
  594. case OP_JUMP_IF_TRUE_OR_POP:{
  595. if(py_bool(TOP())) frame->jump_abs(byte.arg);
  596. else POP();
  597. } DISPATCH();
  598. case OP_JUMP_IF_FALSE_OR_POP:{
  599. if(!py_bool(TOP())) frame->jump_abs(byte.arg);
  600. else POP();
  601. } DISPATCH();
  602. case OP_SHORTCUT_IF_FALSE_OR_POP:{
  603. if(!py_bool(TOP())){ // [b, False]
  604. STACK_SHRINK(2); // []
  605. PUSH(vm->False); // [False]
  606. frame->jump_abs(byte.arg);
  607. } else POP(); // [b]
  608. } DISPATCH();
  609. case OP_LOOP_CONTINUE:
  610. frame->jump_abs(byte.arg);
  611. DISPATCH();
  612. case OP_LOOP_BREAK:
  613. frame->jump_abs_break(&s_data, byte.arg);
  614. DISPATCH();
  615. case OP_GOTO: {
  616. StrName _name(byte.arg);
  617. int index = co->labels.try_get_likely_found(_name);
  618. if(index < 0) RuntimeError(_S("label ", _name.escape(), " not found"));
  619. frame->jump_abs_break(&s_data, index);
  620. } DISPATCH();
  621. /*****************************************/
  622. case OP_FSTRING_EVAL:{
  623. PyObject* _0 = co->consts[byte.arg];
  624. std::string_view string = CAST(Str&, _0).sv();
  625. auto it = _cached_codes.find(string);
  626. CodeObject_ code;
  627. if(it == _cached_codes.end()){
  628. code = vm->compile(string, "<eval>", EVAL_MODE, true);
  629. _cached_codes[string] = code;
  630. }else{
  631. code = it->second;
  632. }
  633. _0 = vm->_exec(code.get(), frame->_module, frame->_callable, frame->_locals);
  634. PUSH(_0);
  635. } DISPATCH();
  636. case OP_REPR:
  637. TOP() = py_repr(TOP());
  638. DISPATCH();
  639. case OP_CALL:{
  640. if(heap._should_auto_collect()) heap._auto_collect();
  641. PyObject* _0 = vectorcall(
  642. byte.arg & 0xFF, // ARGC
  643. (byte.arg>>8) & 0xFF, // KWARGC
  644. true
  645. );
  646. if(_0 == PY_OP_CALL){
  647. frame = top_frame();
  648. goto __NEXT_FRAME;
  649. }
  650. PUSH(_0);
  651. } DISPATCH();
  652. case OP_CALL_TP:{
  653. if(heap._should_auto_collect()) heap._auto_collect();
  654. PyObject* _0;
  655. PyObject* _1;
  656. PyObject* _2;
  657. // [callable, <self>, args: tuple, kwargs: dict | NULL]
  658. if(byte.arg){
  659. _2 = POPX();
  660. _1 = POPX();
  661. for(PyObject* obj: _CAST(Tuple&, _1)) PUSH(obj);
  662. _CAST(Dict&, _2).apply([this](PyObject* k, PyObject* v){
  663. PUSH(VAR(StrName(CAST(Str&, k)).index));
  664. PUSH(v);
  665. });
  666. _0 = vectorcall(
  667. _CAST(Tuple&, _1).size(), // ARGC
  668. _CAST(Dict&, _2).size(), // KWARGC
  669. true
  670. );
  671. }else{
  672. // no **kwargs
  673. _1 = POPX();
  674. for(PyObject* obj: _CAST(Tuple&, _1)) PUSH(obj);
  675. _0 = vectorcall(
  676. _CAST(Tuple&, _1).size(), // ARGC
  677. 0, // KWARGC
  678. true
  679. );
  680. }
  681. if(_0 == PY_OP_CALL){
  682. frame = top_frame();
  683. goto __NEXT_FRAME;
  684. }
  685. PUSH(_0);
  686. } DISPATCH();
  687. case OP_RETURN_VALUE:{
  688. PyObject* _0 = byte.arg == BC_NOARG ? POPX() : None;
  689. __pop_frame();
  690. if(frame == base_frame){ // [ frameBase<- ]
  691. return _0;
  692. }else{
  693. frame = top_frame();
  694. PUSH(_0);
  695. goto __NEXT_FRAME;
  696. }
  697. } DISPATCH();
  698. case OP_YIELD_VALUE:
  699. return PY_OP_YIELD;
  700. /*****************************************/
  701. case OP_LIST_APPEND:{
  702. PyObject* _0 = POPX();
  703. CAST(List&, SECOND()).push_back(_0);
  704. } DISPATCH();
  705. case OP_DICT_ADD: {
  706. PyObject* _0 = POPX();
  707. Tuple& t = CAST(Tuple&, _0);
  708. call_method(SECOND(), __setitem__, t[0], t[1]);
  709. } DISPATCH();
  710. case OP_SET_ADD:{
  711. PyObject* _0 = POPX();
  712. call_method(SECOND(), pk_id_add, _0);
  713. } DISPATCH();
  714. /*****************************************/
  715. case OP_UNARY_NEGATIVE:
  716. TOP() = py_negate(TOP());
  717. DISPATCH();
  718. case OP_UNARY_NOT:{
  719. PyObject* _0 = TOP();
  720. if(_0==True) TOP()=False;
  721. else if(_0==False) TOP()=True;
  722. else TOP() = VAR(!py_bool(_0));
  723. } DISPATCH();
  724. case OP_UNARY_STAR:
  725. TOP() = VAR(StarWrapper(byte.arg, TOP()));
  726. DISPATCH();
  727. case OP_UNARY_INVERT:{
  728. PyObject* _0;
  729. auto _ti = _inst_type_info(TOP());
  730. if(_ti->m__invert__) _0 = _ti->m__invert__(this, TOP());
  731. else _0 = call_method(TOP(), __invert__);
  732. TOP() = _0;
  733. } DISPATCH();
  734. /*****************************************/
  735. case OP_GET_ITER:
  736. TOP() = py_iter(TOP());
  737. DISPATCH();
  738. case OP_FOR_ITER:{
  739. PyObject* _0 = py_next(TOP());
  740. if(_0 == StopIteration) frame->loop_break(&s_data, co);
  741. else PUSH(_0);
  742. } DISPATCH();
  743. case OP_FOR_ITER_STORE_FAST:{
  744. PyObject* _0 = py_next(TOP());
  745. if(_0 == StopIteration){
  746. frame->loop_break(&s_data, co);
  747. }else{
  748. frame->_locals[byte.arg] = _0;
  749. }
  750. } DISPATCH()
  751. case OP_FOR_ITER_STORE_GLOBAL:{
  752. PyObject* _0 = py_next(TOP());
  753. if(_0 == StopIteration){
  754. frame->loop_break(&s_data, co);
  755. }else{
  756. frame->f_globals().set(StrName(byte.arg), _0);
  757. }
  758. } DISPATCH()
  759. case OP_FOR_ITER_YIELD_VALUE:{
  760. PyObject* _0 = py_next(TOP());
  761. if(_0 == StopIteration){
  762. frame->loop_break(&s_data, co);
  763. }else{
  764. PUSH(_0);
  765. return PY_OP_YIELD;
  766. }
  767. } DISPATCH()
  768. case OP_FOR_ITER_UNPACK:{
  769. PyObject* _0 = TOP();
  770. const PyTypeInfo* _ti = _inst_type_info(_0);
  771. if(_ti->m__next__){
  772. unsigned n = _ti->m__next__(this, _0);
  773. if(n == 0){
  774. // StopIteration
  775. frame->loop_break(&s_data, co);
  776. }else if(n == 1){
  777. // UNPACK_SEQUENCE
  778. __op_unpack_sequence(byte.arg);
  779. }else{
  780. if(n != byte.arg){
  781. ValueError(_S("expected ", (int)byte.arg, " values to unpack, got ", (int)n));
  782. }
  783. }
  784. }else{
  785. // FOR_ITER
  786. _0 = call_method(_0, __next__);
  787. if(_0 != StopIteration){
  788. PUSH(_0);
  789. // UNPACK_SEQUENCE
  790. __op_unpack_sequence(byte.arg);
  791. }else{
  792. frame->loop_break(&s_data, co);
  793. }
  794. }
  795. } DISPATCH()
  796. /*****************************************/
  797. case OP_IMPORT_PATH:{
  798. PyObject* _0 = co->consts[byte.arg];
  799. PUSH(py_import(CAST(Str&, _0)));
  800. } DISPATCH();
  801. case OP_POP_IMPORT_STAR: {
  802. PyObject* _0 = POPX(); // pop the module
  803. PyObject* _1 = _0->attr().try_get(__all__);
  804. StrName _name;
  805. if(_1 != nullptr){
  806. for(PyObject* key: CAST(List&, _1)){
  807. _name = StrName::get(CAST(Str&, key).sv());
  808. PyObject* value = _0->attr().try_get_likely_found(_name);
  809. if(value == nullptr){
  810. ImportError(_S("cannot import name ", _name.escape()));
  811. }else{
  812. frame->f_globals().set(_name, value);
  813. }
  814. }
  815. }else{
  816. for(auto& [name, value]: _0->attr().items()){
  817. std::string_view s = name.sv();
  818. if(s.empty() || s[0] == '_') continue;
  819. frame->f_globals().set(name, value);
  820. }
  821. }
  822. } DISPATCH();
  823. /*****************************************/
  824. case OP_UNPACK_SEQUENCE:{
  825. __op_unpack_sequence(byte.arg);
  826. } DISPATCH();
  827. case OP_UNPACK_EX: {
  828. auto _lock = heap.gc_scope_lock(); // lock the gc via RAII!!
  829. PyObject* _0 = py_iter(POPX());
  830. const PyTypeInfo* _ti = _inst_type_info(_0);
  831. PyObject* _1;
  832. for(int i=0; i<byte.arg; i++){
  833. _1 = _py_next(_ti, _0);
  834. if(_1 == StopIteration) ValueError("not enough values to unpack");
  835. PUSH(_1);
  836. }
  837. List extras;
  838. while(true){
  839. _1 = _py_next(_ti, _0);
  840. if(_1 == StopIteration) break;
  841. extras.push_back(_1);
  842. }
  843. PUSH(VAR(extras));
  844. } DISPATCH();
  845. /*****************************************/
  846. case OP_BEGIN_CLASS:{
  847. StrName _name(byte.arg);
  848. PyObject* _0 = POPX(); // super
  849. if(_0 == None) _0 = _t(tp_object);
  850. check_type(_0, tp_type);
  851. _curr_class = new_type_object(frame->_module, _name, PK_OBJ_GET(Type, _0));
  852. } DISPATCH();
  853. case OP_END_CLASS: {
  854. PK_ASSERT(_curr_class != nullptr);
  855. StrName _name(byte.arg);
  856. frame->_module->attr().set(_name, _curr_class);
  857. // call on_end_subclass
  858. PyTypeInfo* ti = &_all_types[PK_OBJ_GET(Type, _curr_class)];
  859. if(ti->base != tp_object){
  860. PyTypeInfo* base_ti = &_all_types[ti->base];
  861. if(base_ti->on_end_subclass) base_ti->on_end_subclass(this, ti);
  862. }
  863. _curr_class = nullptr;
  864. } DISPATCH();
  865. case OP_STORE_CLASS_ATTR:{
  866. PK_ASSERT(_curr_class != nullptr);
  867. StrName _name(byte.arg);
  868. PyObject* _0 = POPX();
  869. if(is_type(_0, tp_function)){
  870. PK_OBJ_GET(Function, _0)._class = _curr_class;
  871. }
  872. _curr_class->attr().set(_name, _0);
  873. } DISPATCH();
  874. case OP_BEGIN_CLASS_DECORATION:{
  875. PUSH(_curr_class);
  876. } DISPATCH();
  877. case OP_END_CLASS_DECORATION:{
  878. _curr_class = POPX();
  879. } DISPATCH();
  880. case OP_ADD_CLASS_ANNOTATION: {
  881. PK_ASSERT(_curr_class != nullptr);
  882. StrName _name(byte.arg);
  883. Type type = PK_OBJ_GET(Type, _curr_class);
  884. _all_types[type].annotated_fields.push_back(_name);
  885. } DISPATCH();
  886. /*****************************************/
  887. case OP_WITH_ENTER:
  888. PUSH(call_method(TOP(), __enter__));
  889. DISPATCH();
  890. case OP_WITH_EXIT:
  891. call_method(TOP(), __exit__);
  892. POP();
  893. DISPATCH();
  894. /*****************************************/
  895. case OP_EXCEPTION_MATCH: {
  896. PyObject* assumed_type = POPX();
  897. check_type(assumed_type, tp_type);
  898. PyObject* e_obj = TOP();
  899. bool ok = isinstance(e_obj, PK_OBJ_GET(Type, assumed_type));
  900. PUSH(VAR(ok));
  901. } DISPATCH();
  902. case OP_RAISE: {
  903. if(is_type(TOP(), tp_type)){
  904. TOP() = call(TOP());
  905. }
  906. if(!isinstance(TOP(), tp_exception)){
  907. _builtin_error("TypeError", "exceptions must derive from Exception");
  908. }
  909. _error(POPX());
  910. } DISPATCH();
  911. case OP_RAISE_ASSERT:
  912. if(byte.arg){
  913. PyObject* _0 = py_str(POPX());
  914. _builtin_error("AssertionError", CAST(Str, _0));
  915. }else{
  916. _builtin_error("AssertionError");
  917. }
  918. DISPATCH();
  919. case OP_RE_RAISE: __raise(true); DISPATCH();
  920. case OP_POP_EXCEPTION: _last_exception = POPX(); DISPATCH();
  921. /*****************************************/
  922. case OP_FORMAT_STRING: {
  923. PyObject* _0 = POPX();
  924. const Str& spec = CAST(Str&, co->consts[byte.arg]);
  925. PUSH(__format_string(spec, _0));
  926. } DISPATCH();
  927. /*****************************************/
  928. case OP_INC_FAST:{
  929. PyObject** p = &frame->_locals[byte.arg];
  930. if(*p == PY_NULL) vm->NameError(co->varnames[byte.arg]);
  931. *p = VAR(CAST(i64, *p) + 1);
  932. } DISPATCH();
  933. case OP_DEC_FAST:{
  934. PyObject** p = &frame->_locals[byte.arg];
  935. if(*p == PY_NULL) vm->NameError(co->varnames[byte.arg]);
  936. *p = VAR(CAST(i64, *p) - 1);
  937. } DISPATCH();
  938. case OP_INC_GLOBAL:{
  939. StrName _name(byte.arg);
  940. PyObject** p = frame->f_globals().try_get_2_likely_found(_name);
  941. if(p == nullptr) vm->NameError(_name);
  942. *p = VAR(CAST(i64, *p) + 1);
  943. } DISPATCH();
  944. case OP_DEC_GLOBAL:{
  945. StrName _name(byte.arg);
  946. PyObject** p = frame->f_globals().try_get_2_likely_found(_name);
  947. if(p == nullptr) vm->NameError(_name);
  948. *p = VAR(CAST(i64, *p) - 1);
  949. } DISPATCH();
  950. /*****************************************/
  951. }
  952. }
  953. /**********************************************************************/
  954. PK_UNREACHABLE()
  955. }catch(HandledException){
  956. continue;
  957. }catch(UnhandledException){
  958. PyObject* e_obj = POPX();
  959. Exception& _e = PK_OBJ_GET(Exception, e_obj);
  960. bool is_base_frame_to_be_popped = frame == base_frame;
  961. __pop_frame();
  962. if(callstack.empty()) throw _e; // propagate to the top level
  963. frame = top_frame();
  964. PUSH(e_obj);
  965. if(is_base_frame_to_be_popped) throw ToBeRaisedException();
  966. need_raise = true;
  967. }catch(ToBeRaisedException){
  968. need_raise = true;
  969. }
  970. }
  971. }
  972. #undef TOP
  973. #undef SECOND
  974. #undef THIRD
  975. #undef PEEK
  976. #undef STACK_SHRINK
  977. #undef PUSH
  978. #undef POP
  979. #undef POPX
  980. #undef STACK_VIEW
  981. #undef DISPATCH
  982. #undef CEVAL_STEP_CALLBACK
  983. } // namespace pkpy