ceval.cpp 55 KB

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