vm.h 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  1. #pragma once
  2. #include "codeobject.h"
  3. #include "error.h"
  4. #define DEF_NATIVE(type, ctype, ptype) \
  5. inline ctype& Py##type##_AS_C(const PyVar& obj) { \
  6. check_type(obj, ptype); \
  7. return OBJ_GET(ctype, obj); \
  8. } \
  9. inline PyVar Py##type(const ctype& value) { return new_object(ptype, value);} \
  10. inline PyVar Py##type(ctype&& value) { return new_object(ptype, std::move(value));}
  11. class Generator;
  12. class VM {
  13. public:
  14. std::stack< std::unique_ptr<Frame> > callstack;
  15. PyVar _py_op_call;
  16. PyVar _py_op_yield;
  17. // PyVar _ascii_str_pool[128];
  18. PyVar run_frame(Frame* frame){
  19. while(frame->has_next_bytecode()){
  20. const Bytecode& byte = frame->next_bytecode();
  21. // if(true || frame->_module != builtins){
  22. // printf("%d: %s (%d) %s\n", frame->_ip, OP_NAMES[byte.op], byte.arg, frame->stack_info().c_str());
  23. // }
  24. switch (byte.op)
  25. {
  26. case OP_NO_OP: break; // do nothing
  27. case OP_LOAD_CONST: frame->push(frame->co->consts[byte.arg]); break;
  28. case OP_LOAD_LAMBDA: {
  29. PyVar obj = frame->co->consts[byte.arg];
  30. setattr(obj, __module__, frame->_module);
  31. frame->push(obj);
  32. } break;
  33. case OP_LOAD_NAME_REF: {
  34. frame->push(PyRef(NameRef(frame->co->names[byte.arg])));
  35. } break;
  36. case OP_LOAD_NAME: {
  37. frame->push(NameRef(frame->co->names[byte.arg]).get(this, frame));
  38. } break;
  39. case OP_STORE_NAME: {
  40. auto& p = frame->co->names[byte.arg];
  41. NameRef(p).set(this, frame, frame->pop_value(this));
  42. } break;
  43. case OP_BUILD_ATTR: {
  44. int name = byte.arg >> 1;
  45. bool _rvalue = byte.arg % 2 == 1;
  46. auto& attr = frame->co->names[name];
  47. PyVar obj = frame->pop_value(this);
  48. AttrRef ref = AttrRef(obj, NameRef(attr));
  49. if(_rvalue) frame->push(ref.get(this, frame));
  50. else frame->push(PyRef(ref));
  51. } break;
  52. case OP_BUILD_INDEX: {
  53. PyVar index = frame->pop_value(this);
  54. auto ref = IndexRef(frame->pop_value(this), index);
  55. if(byte.arg == 0) frame->push(PyRef(ref));
  56. else frame->push(ref.get(this, frame));
  57. } break;
  58. case OP_STORE_REF: {
  59. PyVar obj = frame->pop_value(this);
  60. PyVarRef r = frame->pop();
  61. PyRef_AS_C(r)->set(this, frame, std::move(obj));
  62. } break;
  63. case OP_DELETE_REF: {
  64. PyVarRef r = frame->pop();
  65. PyRef_AS_C(r)->del(this, frame);
  66. } break;
  67. case OP_BUILD_SMART_TUPLE:
  68. {
  69. pkpy::Args items = frame->pop_n_reversed(byte.arg);
  70. bool done = false;
  71. for(int i=0; i<items.size(); i++){
  72. if(!items[i]->is_type(tp_ref)) {
  73. done = true;
  74. for(int j=i; j<items.size(); j++) frame->try_deref(this, items[j]);
  75. frame->push(PyTuple(std::move(items)));
  76. break;
  77. }
  78. }
  79. if(done) break;
  80. frame->push(PyRef(TupleRef(std::move(items))));
  81. } break;
  82. case OP_BUILD_STRING:
  83. {
  84. pkpy::Args items = frame->pop_n_values_reversed(this, byte.arg);
  85. StrStream ss;
  86. for(int i=0; i<items.size(); i++) ss << PyStr_AS_C(asStr(items[i]));
  87. frame->push(PyStr(ss.str()));
  88. } break;
  89. case OP_LOAD_EVAL_FN: {
  90. frame->push(builtins->attr(m_eval));
  91. } break;
  92. case OP_LIST_APPEND: {
  93. pkpy::Args args(2);
  94. args[1] = frame->pop_value(this); // obj
  95. args[0] = frame->top_value_offset(this, -2); // list
  96. fast_call(m_append, std::move(args));
  97. } break;
  98. case OP_STORE_FUNCTION:
  99. {
  100. PyVar obj = frame->pop_value(this);
  101. const pkpy::Function_& fn = PyFunction_AS_C(obj);
  102. setattr(obj, __module__, frame->_module);
  103. frame->f_globals()[fn->name] = obj;
  104. } break;
  105. case OP_BUILD_CLASS:
  106. {
  107. const Str& clsName = frame->co->names[byte.arg].first;
  108. PyVar clsBase = frame->pop_value(this);
  109. if(clsBase == None) clsBase = _t(tp_object);
  110. check_type(clsBase, tp_type);
  111. PyVar cls = new_type_object(frame->_module, clsName, clsBase);
  112. while(true){
  113. PyVar fn = frame->pop_value(this);
  114. if(fn == None) break;
  115. const pkpy::Function_& f = PyFunction_AS_C(fn);
  116. setattr(fn, __module__, frame->_module);
  117. setattr(cls, f->name, fn);
  118. }
  119. } break;
  120. case OP_RETURN_VALUE: return frame->pop_value(this);
  121. case OP_PRINT_EXPR:
  122. {
  123. const PyVar expr = frame->top_value(this);
  124. if(expr == None) break;
  125. *_stdout << PyStr_AS_C(asRepr(expr)) << '\n';
  126. } break;
  127. case OP_POP_TOP: frame->_pop(); break;
  128. case OP_BINARY_OP:
  129. {
  130. pkpy::Args args(2);
  131. args[1] = frame->pop_value(this);
  132. args[0] = frame->top_value(this);
  133. frame->top() = fast_call(BINARY_SPECIAL_METHODS[byte.arg], std::move(args));
  134. } break;
  135. case OP_BITWISE_OP:
  136. {
  137. frame->push(
  138. fast_call(BITWISE_SPECIAL_METHODS[byte.arg],
  139. frame->pop_n_values_reversed(this, 2))
  140. );
  141. } break;
  142. case OP_COMPARE_OP:
  143. {
  144. pkpy::Args args(2);
  145. args[1] = frame->pop_value(this);
  146. args[0] = frame->top_value(this);
  147. frame->top() = fast_call(CMP_SPECIAL_METHODS[byte.arg], std::move(args));
  148. } break;
  149. case OP_IS_OP:
  150. {
  151. PyVar rhs = frame->pop_value(this);
  152. bool ret_c = rhs == frame->top_value(this);
  153. if(byte.arg == 1) ret_c = !ret_c;
  154. frame->top() = PyBool(ret_c);
  155. } break;
  156. case OP_CONTAINS_OP:
  157. {
  158. PyVar rhs = frame->pop_value(this);
  159. bool ret_c = PyBool_AS_C(call(rhs, __contains__, pkpy::one_arg(frame->pop_value(this))));
  160. if(byte.arg == 1) ret_c = !ret_c;
  161. frame->push(PyBool(ret_c));
  162. } break;
  163. case OP_UNARY_NEGATIVE:
  164. frame->top() = num_negated(frame->top_value(this));
  165. break;
  166. case OP_UNARY_NOT:
  167. {
  168. PyVar obj = frame->pop_value(this);
  169. const PyVar& obj_bool = asBool(obj);
  170. frame->push(PyBool(!PyBool_AS_C(obj_bool)));
  171. } break;
  172. case OP_POP_JUMP_IF_FALSE:
  173. if(!PyBool_AS_C(asBool(frame->pop_value(this)))) frame->jump_abs(byte.arg);
  174. break;
  175. case OP_LOAD_NONE: frame->push(None); break;
  176. case OP_LOAD_TRUE: frame->push(True); break;
  177. case OP_LOAD_FALSE: frame->push(False); break;
  178. case OP_LOAD_ELLIPSIS: frame->push(Ellipsis); break;
  179. case OP_ASSERT:
  180. {
  181. PyVar _msg = frame->pop_value(this);
  182. Str msg = PyStr_AS_C(asStr(_msg));
  183. PyVar expr = frame->pop_value(this);
  184. if(asBool(expr) != True) _error("AssertionError", msg);
  185. } break;
  186. case OP_EXCEPTION_MATCH:
  187. {
  188. const auto& _e = PyException_AS_C(frame->top());
  189. Str name = frame->co->names[byte.arg].first;
  190. frame->push(PyBool(_e.match_type(name)));
  191. } break;
  192. case OP_RAISE:
  193. {
  194. PyVar obj = frame->pop_value(this);
  195. Str msg = obj == None ? "" : PyStr_AS_C(asStr(obj));
  196. Str type = frame->co->names[byte.arg].first;
  197. _error(type, msg);
  198. } break;
  199. case OP_RE_RAISE: _raise(); break;
  200. case OP_BUILD_LIST:
  201. frame->push(PyList(
  202. frame->pop_n_values_reversed(this, byte.arg).to_list()));
  203. break;
  204. case OP_BUILD_MAP:
  205. {
  206. pkpy::Args items = frame->pop_n_values_reversed(this, byte.arg*2);
  207. PyVar obj = call(builtins->attr("dict"));
  208. for(int i=0; i<items.size(); i+=2){
  209. call(obj, __setitem__, pkpy::two_args(items[i], items[i+1]));
  210. }
  211. frame->push(obj);
  212. } break;
  213. case OP_BUILD_SET:
  214. {
  215. PyVar list = PyList(
  216. frame->pop_n_values_reversed(this, byte.arg).to_list()
  217. );
  218. PyVar obj = call(builtins->attr("set"), pkpy::one_arg(list));
  219. frame->push(obj);
  220. } break;
  221. case OP_DUP_TOP: frame->push(frame->top_value(this)); break;
  222. case OP_CALL:
  223. {
  224. int ARGC = byte.arg & 0xFFFF;
  225. int KWARGC = (byte.arg >> 16) & 0xFFFF;
  226. pkpy::Args kwargs(0);
  227. if(KWARGC > 0) kwargs = frame->pop_n_values_reversed(this, KWARGC*2);
  228. pkpy::Args args = frame->pop_n_values_reversed(this, ARGC);
  229. PyVar callable = frame->pop_value(this);
  230. PyVar ret = call(callable, std::move(args), kwargs, true);
  231. if(ret == _py_op_call) return ret;
  232. frame->push(std::move(ret));
  233. } break;
  234. case OP_JUMP_ABSOLUTE: frame->jump_abs(byte.arg); break;
  235. case OP_SAFE_JUMP_ABSOLUTE: frame->jump_abs_safe(byte.arg); break;
  236. case OP_GOTO: {
  237. const Str& label = frame->co->names[byte.arg].first;
  238. int* target = frame->co->labels.try_get(label);
  239. if(target == nullptr) _error("KeyError", "label '" + label + "' not found");
  240. frame->jump_abs_safe(*target);
  241. } break;
  242. case OP_GET_ITER:
  243. {
  244. PyVar obj = frame->pop_value(this);
  245. PyVar iter_obj = nullptr;
  246. if(!obj->is_type(tp_native_iterator)){
  247. PyVarOrNull iter_f = getattr(obj, __iter__, false);
  248. if(iter_f != nullptr) iter_obj = call(iter_f);
  249. }else{
  250. iter_obj = obj;
  251. }
  252. if(iter_obj == nullptr){
  253. TypeError(OBJ_NAME(_t(obj)).escape(true) + " object is not iterable");
  254. }
  255. PyVarRef var = frame->pop();
  256. check_type(var, tp_ref);
  257. PyIter_AS_C(iter_obj)->var = var;
  258. frame->push(std::move(iter_obj));
  259. } break;
  260. case OP_FOR_ITER:
  261. {
  262. // top() must be PyIter, so no need to try_deref()
  263. auto& it = PyIter_AS_C(frame->top());
  264. PyVar obj = it->next();
  265. if(obj != nullptr){
  266. PyRef_AS_C(it->var)->set(this, frame, std::move(obj));
  267. }else{
  268. int blockEnd = frame->co->blocks[byte.block].end;
  269. frame->jump_abs_safe(blockEnd);
  270. }
  271. } break;
  272. case OP_LOOP_CONTINUE:
  273. {
  274. int blockStart = frame->co->blocks[byte.block].start;
  275. frame->jump_abs(blockStart);
  276. } break;
  277. case OP_LOOP_BREAK:
  278. {
  279. int blockEnd = frame->co->blocks[byte.block].end;
  280. frame->jump_abs_safe(blockEnd);
  281. } break;
  282. case OP_JUMP_IF_FALSE_OR_POP:
  283. {
  284. const PyVar expr = frame->top_value(this);
  285. if(asBool(expr)==False) frame->jump_abs(byte.arg);
  286. else frame->pop_value(this);
  287. } break;
  288. case OP_JUMP_IF_TRUE_OR_POP:
  289. {
  290. const PyVar expr = frame->top_value(this);
  291. if(asBool(expr)==True) frame->jump_abs(byte.arg);
  292. else frame->pop_value(this);
  293. } break;
  294. case OP_BUILD_SLICE:
  295. {
  296. PyVar stop = frame->pop_value(this);
  297. PyVar start = frame->pop_value(this);
  298. pkpy::Slice s;
  299. if(start != None) {check_type(start, tp_int); s.start = (int)PyInt_AS_C(start);}
  300. if(stop != None) {check_type(stop, tp_int); s.stop = (int)PyInt_AS_C(stop);}
  301. frame->push(PySlice(s));
  302. } break;
  303. case OP_IMPORT_NAME:
  304. {
  305. const Str& name = frame->co->names[byte.arg].first;
  306. auto it = _modules.find(name);
  307. if(it == _modules.end()){
  308. auto it2 = _lazy_modules.find(name);
  309. if(it2 == _lazy_modules.end()){
  310. _error("ImportError", "module '" + name + "' not found");
  311. }else{
  312. const Str& source = it2->second;
  313. CodeObject_ code = compile(source, name, EXEC_MODE);
  314. PyVar _m = new_module(name);
  315. _exec(code, _m, pkpy::make_shared<pkpy::NameDict>());
  316. frame->push(_m);
  317. _lazy_modules.erase(it2);
  318. }
  319. }else{
  320. frame->push(it->second);
  321. }
  322. } break;
  323. case OP_YIELD_VALUE: return _py_op_yield;
  324. // TODO: using "goto" inside with block may cause __exit__ not called
  325. case OP_WITH_ENTER: call(frame->pop_value(this), __enter__); break;
  326. case OP_WITH_EXIT: call(frame->pop_value(this), __exit__); break;
  327. case OP_TRY_BLOCK_ENTER: frame->on_try_block_enter(); break;
  328. case OP_TRY_BLOCK_EXIT: frame->on_try_block_exit(); break;
  329. default:
  330. throw std::runtime_error(Str("opcode ") + OP_NAMES[byte.op] + " is not implemented");
  331. break;
  332. }
  333. }
  334. if(frame->co->src->mode == EVAL_MODE || frame->co->src->mode == JSON_MODE){
  335. if(frame->_data.size() != 1) throw std::runtime_error("_data.size() != 1 in EVAL/JSON_MODE");
  336. return frame->pop_value(this);
  337. }
  338. if(!frame->_data.empty()) throw std::runtime_error("_data.size() != 0 in EXEC_MODE");
  339. return None;
  340. }
  341. pkpy::NameDict _types;
  342. pkpy::NameDict _modules; // loaded modules
  343. emhash8::HashMap<Str, Str> _lazy_modules; // lazy loaded modules
  344. PyVar None, True, False, Ellipsis;
  345. bool use_stdio;
  346. std::ostream* _stdout;
  347. std::ostream* _stderr;
  348. PyVar builtins; // builtins module
  349. PyVar _main; // __main__ module
  350. int maxRecursionDepth = 1000;
  351. VM(bool use_stdio){
  352. this->use_stdio = use_stdio;
  353. if(use_stdio){
  354. this->_stdout = &std::cout;
  355. this->_stderr = &std::cerr;
  356. }else{
  357. this->_stdout = new StrStream();
  358. this->_stderr = new StrStream();
  359. }
  360. init_builtin_types();
  361. // for(int i=0; i<128; i++) _ascii_str_pool[i] = new_object(tp_str, std::string(1, (char)i));
  362. }
  363. PyVar asStr(const PyVar& obj){
  364. PyVarOrNull f = getattr(obj, __str__, false);
  365. if(f != nullptr) return call(f);
  366. return asRepr(obj);
  367. }
  368. inline Frame* top_frame() const {
  369. if(callstack.empty()) UNREACHABLE();
  370. return callstack.top().get();
  371. }
  372. PyVar asRepr(const PyVar& obj){
  373. if(obj->is_type(tp_type)) return PyStr("<class '" + OBJ_GET(Str, obj->attr(__name__)) + "'>");
  374. return call(obj, __repr__);
  375. }
  376. const PyVar& asBool(const PyVar& obj){
  377. if(obj->is_type(tp_bool)) return obj;
  378. if(obj == None) return False;
  379. if(obj->is_type(tp_int)) return PyBool(PyInt_AS_C(obj) != 0);
  380. if(obj->is_type(tp_float)) return PyBool(PyFloat_AS_C(obj) != 0.0);
  381. PyVarOrNull len_fn = getattr(obj, __len__, false);
  382. if(len_fn != nullptr){
  383. PyVar ret = call(len_fn);
  384. return PyBool(PyInt_AS_C(ret) > 0);
  385. }
  386. return True;
  387. }
  388. PyVar fast_call(const Str& name, pkpy::Args&& args){
  389. PyObject* cls = _t(args[0]).get();
  390. while(cls != None.get()) {
  391. PyVar* val = cls->attr().try_get(name);
  392. if(val != nullptr) return call(*val, std::move(args));
  393. cls = cls->attr(__base__).get();
  394. }
  395. AttributeError(args[0], name);
  396. return nullptr;
  397. }
  398. inline PyVar call(const PyVar& _callable){
  399. return call(_callable, pkpy::no_arg(), pkpy::no_arg(), false);
  400. }
  401. template<typename ArgT>
  402. inline std::enable_if_t<std::is_same_v<RAW(ArgT), pkpy::Args>, PyVar>
  403. call(const PyVar& _callable, ArgT&& args){
  404. return call(_callable, std::forward<ArgT>(args), pkpy::no_arg(), false);
  405. }
  406. template<typename ArgT>
  407. inline std::enable_if_t<std::is_same_v<RAW(ArgT), pkpy::Args>, PyVar>
  408. call(const PyVar& obj, const Str& func, ArgT&& args){
  409. return call(getattr(obj, func), std::forward<ArgT>(args), pkpy::no_arg(), false);
  410. }
  411. inline PyVar call(const PyVar& obj, const Str& func){
  412. return call(getattr(obj, func), pkpy::no_arg(), pkpy::no_arg(), false);
  413. }
  414. PyVar call(const PyVar& _callable, pkpy::Args args, const pkpy::Args& kwargs, bool opCall){
  415. if(_callable->is_type(tp_type)){
  416. PyVar* new_f = _callable->attr().try_get(__new__);
  417. PyVar obj;
  418. if(new_f != nullptr){
  419. obj = call(*new_f, args, kwargs, false);
  420. }else{
  421. obj = new_object(_callable, DUMMY_VAL);
  422. PyVarOrNull init_f = getattr(obj, __init__, false);
  423. if (init_f != nullptr) call(init_f, args, kwargs, false);
  424. }
  425. return obj;
  426. }
  427. const PyVar* callable = &_callable;
  428. if((*callable)->is_type(tp_bound_method)){
  429. auto& bm = PyBoundMethod_AS_C((*callable));
  430. callable = &bm.method; // get unbound method
  431. args.extend_self(bm.obj);
  432. }
  433. if((*callable)->is_type(tp_native_function)){
  434. const auto& f = OBJ_GET(pkpy::NativeFunc, *callable);
  435. if(kwargs.size() != 0) TypeError("native_function does not accept keyword arguments");
  436. return f(this, args);
  437. } else if((*callable)->is_type(tp_function)){
  438. const pkpy::Function_& fn = PyFunction_AS_C((*callable));
  439. pkpy::shared_ptr<pkpy::NameDict> _locals = pkpy::make_shared<pkpy::NameDict>();
  440. pkpy::NameDict& locals = *_locals;
  441. int i = 0;
  442. for(const auto& name : fn->args){
  443. if(i < args.size()){
  444. locals.emplace(name, args[i++]);
  445. continue;
  446. }
  447. TypeError("missing positional argument '" + name + "'");
  448. }
  449. locals.insert(fn->kwArgs.begin(), fn->kwArgs.end());
  450. std::vector<Str> positional_overrided_keys;
  451. if(!fn->starredArg.empty()){
  452. pkpy::List vargs; // handle *args
  453. while(i < args.size()) vargs.push_back(args[i++]);
  454. locals.emplace(fn->starredArg, PyTuple(std::move(vargs)));
  455. }else{
  456. for(const auto& key : fn->kwArgsOrder){
  457. if(i < args.size()){
  458. locals[key] = args[i++];
  459. positional_overrided_keys.push_back(key);
  460. }else{
  461. break;
  462. }
  463. }
  464. if(i < args.size()) TypeError("too many arguments");
  465. }
  466. for(int i=0; i<kwargs.size(); i+=2){
  467. const Str& key = PyStr_AS_C(kwargs[i]);
  468. if(!fn->kwArgs.contains(key)){
  469. TypeError(key.escape(true) + " is an invalid keyword argument for " + fn->name + "()");
  470. }
  471. const PyVar& val = kwargs[i+1];
  472. if(!positional_overrided_keys.empty()){
  473. auto it = std::find(positional_overrided_keys.begin(), positional_overrided_keys.end(), key);
  474. if(it != positional_overrided_keys.end()){
  475. TypeError("multiple values for argument '" + key + "'");
  476. }
  477. }
  478. locals[key] = val;
  479. }
  480. PyVar* _m = (*callable)->attr().try_get(__module__);
  481. PyVar _module = _m != nullptr ? *_m : top_frame()->_module;
  482. auto _frame = _new_frame(fn->code, _module, _locals);
  483. if(fn->code->is_generator){
  484. return PyIter(pkpy::make_shared<BaseIter, Generator>(
  485. this, std::move(_frame)));
  486. }
  487. callstack.push(std::move(_frame));
  488. if(opCall) return _py_op_call;
  489. return _exec();
  490. }
  491. TypeError("'" + OBJ_NAME(_t(*callable)) + "' object is not callable");
  492. return None;
  493. }
  494. // repl mode is only for setting `frame->id` to 0
  495. PyVarOrNull exec(Str source, Str filename, CompileMode mode, PyVar _module=nullptr){
  496. if(_module == nullptr) _module = _main;
  497. try {
  498. CodeObject_ code = compile(source, filename, mode);
  499. return _exec(code, _module, pkpy::make_shared<pkpy::NameDict>());
  500. }catch (const pkpy::Exception& e){
  501. *_stderr << e.summary() << '\n';
  502. }
  503. catch (const std::exception& e) {
  504. *_stderr << "A std::exception occurred! It may be a bug, please report it!!\n";
  505. *_stderr << e.what() << '\n';
  506. }
  507. callstack = {};
  508. return nullptr;
  509. }
  510. template<typename ...Args>
  511. inline std::unique_ptr<Frame> _new_frame(Args&&... args){
  512. if(callstack.size() > maxRecursionDepth){
  513. _error("RecursionError", "maximum recursion depth exceeded");
  514. }
  515. return std::make_unique<Frame>(std::forward<Args>(args)...);
  516. }
  517. template<typename ...Args>
  518. inline PyVar _exec(Args&&... args){
  519. callstack.push(_new_frame(std::forward<Args>(args)...));
  520. return _exec();
  521. }
  522. PyVar _exec(){
  523. Frame* frame = top_frame();
  524. i64 base_id = frame->id;
  525. PyVar ret = nullptr;
  526. bool need_raise = false;
  527. while(true){
  528. if(frame->id < base_id) UNREACHABLE();
  529. try{
  530. if(need_raise){ need_raise = false; _raise(); }
  531. ret = run_frame(frame);
  532. if(ret == _py_op_yield) return _py_op_yield;
  533. if(ret != _py_op_call){
  534. if(frame->id == base_id){ // [ frameBase<- ]
  535. callstack.pop();
  536. return ret;
  537. }else{
  538. callstack.pop();
  539. frame = callstack.top().get();
  540. frame->push(ret);
  541. }
  542. }else{
  543. frame = callstack.top().get(); // [ frameBase, newFrame<- ]
  544. }
  545. }catch(HandledException& e){
  546. continue;
  547. }catch(UnhandledException& e){
  548. PyVar obj = frame->pop();
  549. pkpy::Exception& _e = PyException_AS_C(obj);
  550. _e.st_push(frame->snapshot());
  551. callstack.pop();
  552. if(callstack.empty()) throw _e;
  553. frame = callstack.top().get();
  554. frame->push(obj);
  555. if(frame->id < base_id) throw ToBeRaisedException();
  556. need_raise = true;
  557. }catch(ToBeRaisedException& e){
  558. need_raise = true;
  559. }
  560. }
  561. }
  562. std::vector<PyVar> _all_types;
  563. PyVar new_type_object(PyVar mod, Str name, PyVar base){
  564. if(!base->is_type(tp_type)) UNREACHABLE();
  565. PyVar obj = pkpy::make_shared<PyObject, Py_<Type>>(tp_type, _all_types.size());
  566. setattr(obj, __base__, base);
  567. Str fullName = name;
  568. if(mod != builtins) fullName = OBJ_NAME(mod) + "." + name;
  569. setattr(obj, __name__, PyStr(fullName));
  570. setattr(mod, name, obj);
  571. _all_types.push_back(obj);
  572. return obj;
  573. }
  574. Type _new_type_object(Str name, Type base=0) {
  575. PyVar obj = pkpy::make_shared<PyObject, Py_<Type>>(tp_type, _all_types.size());
  576. setattr(obj, __base__, _t(base));
  577. _types[name] = obj;
  578. _all_types.push_back(obj);
  579. return OBJ_GET(Type, obj);
  580. }
  581. template<typename T>
  582. inline PyVar new_object(const PyVar& type, const T& _value) {
  583. if(!type->is_type(tp_type)) UNREACHABLE();
  584. return pkpy::make_shared<PyObject, Py_<RAW(T)>>(OBJ_GET(Type, type), _value);
  585. }
  586. template<typename T>
  587. inline PyVar new_object(const PyVar& type, T&& _value) {
  588. if(!type->is_type(tp_type)) UNREACHABLE();
  589. return pkpy::make_shared<PyObject, Py_<RAW(T)>>(OBJ_GET(Type, type), std::move(_value));
  590. }
  591. template<typename T>
  592. inline PyVar new_object(Type type, const T& _value) {
  593. return pkpy::make_shared<PyObject, Py_<RAW(T)>>(type, _value);
  594. }
  595. template<typename T>
  596. inline PyVar new_object(Type type, T&& _value) {
  597. return pkpy::make_shared<PyObject, Py_<RAW(T)>>(type, std::move(_value));
  598. }
  599. template<typename T, typename... Args>
  600. inline PyVar new_object(Args&&... args) {
  601. return new_object(T::_type(this), T(std::forward<Args>(args)...));
  602. }
  603. PyVar new_module(const Str& name) {
  604. PyVar obj = new_object(tp_module, DUMMY_VAL);
  605. setattr(obj, __name__, PyStr(name));
  606. _modules[name] = obj;
  607. return obj;
  608. }
  609. PyVarOrNull getattr(const PyVar& obj, const Str& name, bool throw_err=true) {
  610. pkpy::NameDict::iterator it;
  611. PyObject* cls;
  612. if(obj->is_type(tp_super)){
  613. const PyVar* root = &obj;
  614. int depth = 1;
  615. while(true){
  616. root = &OBJ_GET(PyVar, *root);
  617. if(!(*root)->is_type(tp_super)) break;
  618. depth++;
  619. }
  620. cls = _t(*root).get();
  621. for(int i=0; i<depth; i++) cls = cls->attr(__base__).get();
  622. it = (*root)->attr().find(name);
  623. if(it != (*root)->attr().end()) return it->second;
  624. }else{
  625. if(obj->is_attr_valid()){
  626. it = obj->attr().find(name);
  627. if(it != obj->attr().end()) return it->second;
  628. }
  629. cls = _t(obj).get();
  630. }
  631. while(cls != None.get()) {
  632. it = cls->attr().find(name);
  633. if(it != cls->attr().end()){
  634. PyVar valueFromCls = it->second;
  635. if(valueFromCls->is_type(tp_function) || valueFromCls->is_type(tp_native_function)){
  636. return PyBoundMethod({obj, std::move(valueFromCls)});
  637. }else{
  638. return valueFromCls;
  639. }
  640. }
  641. cls = cls->attr()[__base__].get();
  642. }
  643. if(throw_err) AttributeError(obj, name);
  644. return nullptr;
  645. }
  646. template<typename T>
  647. inline void setattr(PyVar& obj, const Str& name, T&& value) {
  648. PyObject* p = obj.get();
  649. while(p->is_type(tp_super)) p = static_cast<PyVar*>(p->value())->get();
  650. if(!p->is_attr_valid()) TypeError("cannot set attribute");
  651. p->attr()[name] = std::forward<T>(value);
  652. }
  653. template<int ARGC>
  654. void bind_method(PyVar obj, Str funcName, NativeFuncRaw fn) {
  655. check_type(obj, tp_type);
  656. setattr(obj, funcName, PyNativeFunc(pkpy::NativeFunc(fn, ARGC, true)));
  657. }
  658. template<int ARGC>
  659. void bind_func(PyVar obj, Str funcName, NativeFuncRaw fn) {
  660. setattr(obj, funcName, PyNativeFunc(pkpy::NativeFunc(fn, ARGC, false)));
  661. }
  662. template<int ARGC>
  663. void bind_func(Str typeName, Str funcName, NativeFuncRaw fn) {
  664. bind_func<ARGC>(_types[typeName], funcName, fn);
  665. }
  666. template<int ARGC>
  667. void bind_method(Str typeName, Str funcName, NativeFuncRaw fn) {
  668. bind_method<ARGC>(_types[typeName], funcName, fn);
  669. }
  670. template<int ARGC, typename... Args>
  671. void bind_static_method(Args&&... args) {
  672. bind_func<ARGC>(std::forward<Args>(args)...);
  673. }
  674. template<int ARGC>
  675. void _bind_methods(std::vector<Str> typeNames, Str funcName, NativeFuncRaw fn) {
  676. for(auto& typeName : typeNames) bind_method<ARGC>(typeName, funcName, fn);
  677. }
  678. template<int ARGC>
  679. void bind_builtin_func(Str funcName, NativeFuncRaw fn) {
  680. bind_func<ARGC>(builtins, funcName, fn);
  681. }
  682. inline f64 num_to_float(const PyVar& obj){
  683. if (obj->is_type(tp_int)){
  684. return (f64)PyInt_AS_C(obj);
  685. }else if(obj->is_type(tp_float)){
  686. return PyFloat_AS_C(obj);
  687. }
  688. TypeError("expected 'int' or 'float', got " + OBJ_NAME(_t(obj)).escape(true));
  689. return 0;
  690. }
  691. PyVar num_negated(const PyVar& obj){
  692. if (obj->is_type(tp_int)){
  693. return PyInt(-PyInt_AS_C(obj));
  694. }else if(obj->is_type(tp_float)){
  695. return PyFloat(-PyFloat_AS_C(obj));
  696. }
  697. TypeError("unsupported operand type(s) for -");
  698. return nullptr;
  699. }
  700. int normalized_index(int index, int size){
  701. if(index < 0) index += size;
  702. if(index < 0 || index >= size){
  703. IndexError(std::to_string(index) + " not in [0, " + std::to_string(size) + ")");
  704. }
  705. return index;
  706. }
  707. Str disassemble(CodeObject_ co){
  708. std::vector<int> jumpTargets;
  709. for(auto byte : co->codes){
  710. if(byte.op == OP_JUMP_ABSOLUTE || byte.op == OP_SAFE_JUMP_ABSOLUTE || byte.op == OP_POP_JUMP_IF_FALSE){
  711. jumpTargets.push_back(byte.arg);
  712. }
  713. }
  714. StrStream ss;
  715. ss << std::string(54, '-') << '\n';
  716. ss << co->name << ":\n";
  717. int prev_line = -1;
  718. for(int i=0; i<co->codes.size(); i++){
  719. const Bytecode& byte = co->codes[i];
  720. Str line = std::to_string(byte.line);
  721. if(byte.line == prev_line) line = "";
  722. else{
  723. if(prev_line != -1) ss << "\n";
  724. prev_line = byte.line;
  725. }
  726. std::string pointer;
  727. if(std::find(jumpTargets.begin(), jumpTargets.end(), i) != jumpTargets.end()){
  728. pointer = "-> ";
  729. }else{
  730. pointer = " ";
  731. }
  732. ss << pad(line, 8) << pointer << pad(std::to_string(i), 3);
  733. ss << " " << pad(OP_NAMES[byte.op], 20) << " ";
  734. // ss << pad(byte.arg == -1 ? "" : std::to_string(byte.arg), 5);
  735. std::string argStr = byte.arg == -1 ? "" : std::to_string(byte.arg);
  736. if(byte.op == OP_LOAD_CONST){
  737. argStr += " (" + PyStr_AS_C(asRepr(co->consts[byte.arg])) + ")";
  738. }
  739. if(byte.op == OP_LOAD_NAME_REF || byte.op == OP_LOAD_NAME || byte.op == OP_RAISE){
  740. argStr += " (" + co->names[byte.arg].first.escape(true) + ")";
  741. }
  742. ss << pad(argStr, 20); // may overflow
  743. ss << co->blocks[byte.block].to_string();
  744. if(i != co->codes.size() - 1) ss << '\n';
  745. }
  746. StrStream consts;
  747. consts << "co_consts: ";
  748. consts << PyStr_AS_C(asRepr(PyList(co->consts)));
  749. StrStream names;
  750. names << "co_names: ";
  751. pkpy::List list;
  752. for(int i=0; i<co->names.size(); i++){
  753. list.push_back(PyStr(co->names[i].first));
  754. }
  755. names << PyStr_AS_C(asRepr(PyList(list)));
  756. ss << '\n' << consts.str() << '\n' << names.str() << '\n';
  757. for(int i=0; i<co->consts.size(); i++){
  758. PyVar obj = co->consts[i];
  759. if(obj->is_type(tp_function)){
  760. const auto& f = PyFunction_AS_C(obj);
  761. ss << disassemble(f->code);
  762. }
  763. }
  764. return Str(ss.str());
  765. }
  766. // for quick access
  767. Type tp_object, tp_type, tp_int, tp_float, tp_bool, tp_str;
  768. Type tp_list, tp_tuple;
  769. Type tp_function, tp_native_function, tp_native_iterator, tp_bound_method;
  770. Type tp_slice, tp_range, tp_module, tp_ref;
  771. Type tp_super, tp_exception;
  772. template<typename P>
  773. inline PyVarRef PyRef(P&& value) {
  774. static_assert(std::is_base_of<BaseRef, std::remove_reference_t<P>>::value, "P should derive from BaseRef");
  775. return new_object(tp_ref, std::forward<P>(value));
  776. }
  777. inline const BaseRef* PyRef_AS_C(const PyVar& obj)
  778. {
  779. if(!obj->is_type(tp_ref)) TypeError("expected an l-value");
  780. return (const BaseRef*)(obj->value());
  781. }
  782. inline const Str& PyStr_AS_C(const PyVar& obj) {
  783. check_type(obj, tp_str);
  784. return OBJ_GET(Str, obj);
  785. }
  786. inline PyVar PyStr(const Str& value) {
  787. // some BUGs here
  788. // if(value.size() == 1){
  789. // char c = value.c_str()[0];
  790. // if(c >= 0) return _ascii_str_pool[(int)c];
  791. // }
  792. return new_object(tp_str, value);
  793. }
  794. DEF_NATIVE(Int, i64, tp_int)
  795. DEF_NATIVE(Float, f64, tp_float)
  796. DEF_NATIVE(List, pkpy::List, tp_list)
  797. DEF_NATIVE(Tuple, pkpy::Tuple, tp_tuple)
  798. DEF_NATIVE(Function, pkpy::Function_, tp_function)
  799. DEF_NATIVE(NativeFunc, pkpy::NativeFunc, tp_native_function)
  800. DEF_NATIVE(Iter, pkpy::shared_ptr<BaseIter>, tp_native_iterator)
  801. DEF_NATIVE(BoundMethod, pkpy::BoundMethod, tp_bound_method)
  802. DEF_NATIVE(Range, pkpy::Range, tp_range)
  803. DEF_NATIVE(Slice, pkpy::Slice, tp_slice)
  804. DEF_NATIVE(Exception, pkpy::Exception, tp_exception)
  805. // there is only one True/False, so no need to copy them!
  806. inline bool PyBool_AS_C(const PyVar& obj){return obj == True;}
  807. inline const PyVar& PyBool(bool value){return value ? True : False;}
  808. void init_builtin_types(){
  809. PyVar _tp_object = pkpy::make_shared<PyObject, Py_<Type>>(1, 0);
  810. PyVar _tp_type = pkpy::make_shared<PyObject, Py_<Type>>(1, 1);
  811. _all_types.push_back(_tp_object);
  812. _all_types.push_back(_tp_type);
  813. tp_object = 0; tp_type = 1;
  814. _types["object"] = _tp_object;
  815. _types["type"] = _tp_type;
  816. tp_bool = _new_type_object("bool");
  817. tp_int = _new_type_object("int");
  818. tp_float = _new_type_object("float");
  819. tp_str = _new_type_object("str");
  820. tp_list = _new_type_object("list");
  821. tp_tuple = _new_type_object("tuple");
  822. tp_slice = _new_type_object("slice");
  823. tp_range = _new_type_object("range");
  824. tp_module = _new_type_object("module");
  825. tp_ref = _new_type_object("_ref");
  826. tp_function = _new_type_object("function");
  827. tp_native_function = _new_type_object("native_function");
  828. tp_native_iterator = _new_type_object("native_iterator");
  829. tp_bound_method = _new_type_object("bound_method");
  830. tp_super = _new_type_object("super");
  831. tp_exception = _new_type_object("Exception");
  832. this->None = new_object(_new_type_object("NoneType"), DUMMY_VAL);
  833. this->Ellipsis = new_object(_new_type_object("ellipsis"), DUMMY_VAL);
  834. this->True = new_object(tp_bool, true);
  835. this->False = new_object(tp_bool, false);
  836. this->builtins = new_module("builtins");
  837. this->_main = new_module("__main__");
  838. this->_py_op_call = new_object(_new_type_object("_internal"), DUMMY_VAL);
  839. this->_py_op_yield = new_object(_new_type_object("_internal"), DUMMY_VAL);
  840. setattr(_t(tp_type), __base__, _t(tp_object));
  841. setattr(_t(tp_object), __base__, None);
  842. for (auto& [name, type] : _types) {
  843. setattr(type, __name__, PyStr(name));
  844. }
  845. std::vector<Str> publicTypes = {"type", "object", "bool", "int", "float", "str", "list", "tuple", "range"};
  846. for (auto& name : publicTypes) {
  847. setattr(builtins, name, _types[name]);
  848. }
  849. }
  850. i64 hash(const PyVar& obj){
  851. if (obj->is_type(tp_int)) return PyInt_AS_C(obj);
  852. if (obj->is_type(tp_bool)) return PyBool_AS_C(obj) ? 1 : 0;
  853. if (obj->is_type(tp_float)){
  854. f64 val = PyFloat_AS_C(obj);
  855. return (i64)std::hash<f64>()(val);
  856. }
  857. if (obj->is_type(tp_str)) return PyStr_AS_C(obj).hash();
  858. if (obj->is_type(tp_type)) return (i64)obj.get();
  859. if (obj->is_type(tp_tuple)) {
  860. i64 x = 1000003;
  861. const pkpy::Tuple& items = PyTuple_AS_C(obj);
  862. for (int i=0; i<items.size(); i++) {
  863. i64 y = hash(items[i]);
  864. x = x ^ (y + 0x9e3779b9 + (x << 6) + (x >> 2)); // recommended by Github Copilot
  865. }
  866. return x;
  867. }
  868. TypeError("unhashable type: " + OBJ_NAME(_t(obj)).escape(true));
  869. return 0;
  870. }
  871. /***** Error Reporter *****/
  872. private:
  873. void _error(const Str& name, const Str& msg){
  874. _error(pkpy::Exception(name, msg));
  875. }
  876. void _error(pkpy::Exception e){
  877. if(callstack.empty()){
  878. e.is_re = false;
  879. throw e;
  880. }
  881. top_frame()->push(PyException(e));
  882. _raise();
  883. }
  884. void _raise(){
  885. bool ok = top_frame()->jump_to_exception_handler();
  886. if(ok) throw HandledException();
  887. else throw UnhandledException();
  888. }
  889. public:
  890. void IOError(const Str& msg) { _error("IOError", msg); }
  891. void NotImplementedError(){ _error("NotImplementedError", ""); }
  892. void TypeError(const Str& msg){ _error("TypeError", msg); }
  893. void ZeroDivisionError(){ _error("ZeroDivisionError", "division by zero"); }
  894. void IndexError(const Str& msg){ _error("IndexError", msg); }
  895. void ValueError(const Str& msg){ _error("ValueError", msg); }
  896. void NameError(const Str& name){ _error("NameError", "name " + name.escape(true) + " is not defined"); }
  897. void AttributeError(PyVar obj, const Str& name){
  898. _error("AttributeError", "type " + OBJ_NAME(_t(obj)).escape(true) + " has no attribute " + name.escape(true));
  899. }
  900. inline void check_type(const PyVar& obj, Type type){
  901. if(obj->is_type(type)) return;
  902. TypeError("expected " + OBJ_NAME(_t(type)).escape(true) + ", but got " + OBJ_NAME(_t(obj)).escape(true));
  903. }
  904. inline PyVar& _t(Type t){
  905. return _all_types[t.index];
  906. }
  907. inline PyVar& _t(const PyVar& obj){
  908. return _all_types[OBJ_GET(Type, _t(obj->type)).index];
  909. }
  910. template<typename T>
  911. PyVar register_class(PyVar mod){
  912. PyVar type = new_type_object(mod, T::_name(), _t(tp_object));
  913. if(OBJ_NAME(mod) != T::_mod()) UNREACHABLE();
  914. T::_register(this, mod, type);
  915. return type;
  916. }
  917. template<typename T>
  918. inline T& py_cast(const PyVar& obj){
  919. check_type(obj, T::_type(this));
  920. return OBJ_GET(T, obj);
  921. }
  922. ~VM() {
  923. if(!use_stdio){
  924. delete _stdout;
  925. delete _stderr;
  926. }
  927. }
  928. CodeObject_ compile(Str source, Str filename, CompileMode mode);
  929. };
  930. /***** Pointers' Impl *****/
  931. PyVar NameRef::get(VM* vm, Frame* frame) const{
  932. PyVar* val;
  933. val = frame->f_locals().try_get(name());
  934. if(val) return *val;
  935. val = frame->f_globals().try_get(name());
  936. if(val) return *val;
  937. val = vm->builtins->attr().try_get(name());
  938. if(val) return *val;
  939. vm->NameError(name());
  940. return nullptr;
  941. }
  942. void NameRef::set(VM* vm, Frame* frame, PyVar val) const{
  943. switch(scope()) {
  944. case NAME_LOCAL: frame->f_locals()[name()] = std::move(val); break;
  945. case NAME_GLOBAL:
  946. {
  947. PyVar* existing = frame->f_locals().try_get(name());
  948. if(existing != nullptr){
  949. *existing = std::move(val);
  950. }else{
  951. frame->f_globals()[name()] = std::move(val);
  952. }
  953. } break;
  954. default: UNREACHABLE();
  955. }
  956. }
  957. void NameRef::del(VM* vm, Frame* frame) const{
  958. switch(scope()) {
  959. case NAME_LOCAL: {
  960. if(frame->f_locals().contains(name())){
  961. frame->f_locals().erase(name());
  962. }else{
  963. vm->NameError(name());
  964. }
  965. } break;
  966. case NAME_GLOBAL:
  967. {
  968. if(frame->f_locals().contains(name())){
  969. frame->f_locals().erase(name());
  970. }else{
  971. if(frame->f_globals().contains(name())){
  972. frame->f_globals().erase(name());
  973. }else{
  974. vm->NameError(name());
  975. }
  976. }
  977. } break;
  978. default: UNREACHABLE();
  979. }
  980. }
  981. PyVar AttrRef::get(VM* vm, Frame* frame) const{
  982. return vm->getattr(obj, attr.name());
  983. }
  984. void AttrRef::set(VM* vm, Frame* frame, PyVar val) const{
  985. vm->setattr(obj, attr.name(), val);
  986. }
  987. void AttrRef::del(VM* vm, Frame* frame) const{
  988. if(!obj->is_attr_valid()) vm->TypeError("cannot delete attribute");
  989. if(!obj->attr().contains(attr.name())) vm->AttributeError(obj, attr.name());
  990. obj->attr().erase(attr.name());
  991. }
  992. PyVar IndexRef::get(VM* vm, Frame* frame) const{
  993. return vm->call(obj, __getitem__, pkpy::one_arg(index));
  994. }
  995. void IndexRef::set(VM* vm, Frame* frame, PyVar val) const{
  996. vm->call(obj, __setitem__, pkpy::two_args(index, val));
  997. }
  998. void IndexRef::del(VM* vm, Frame* frame) const{
  999. vm->call(obj, __delitem__, pkpy::one_arg(index));
  1000. }
  1001. PyVar TupleRef::get(VM* vm, Frame* frame) const{
  1002. pkpy::Tuple args(objs.size());
  1003. for (int i = 0; i < objs.size(); i++) {
  1004. args[i] = vm->PyRef_AS_C(objs[i])->get(vm, frame);
  1005. }
  1006. return vm->PyTuple(std::move(args));
  1007. }
  1008. void TupleRef::set(VM* vm, Frame* frame, PyVar val) const{
  1009. #define TUPLE_REF_SET() \
  1010. if(args.size() > objs.size()) vm->ValueError("too many values to unpack"); \
  1011. if(args.size() < objs.size()) vm->ValueError("not enough values to unpack"); \
  1012. for (int i = 0; i < objs.size(); i++) vm->PyRef_AS_C(objs[i])->set(vm, frame, args[i]);
  1013. if(val->is_type(vm->tp_tuple)){
  1014. const pkpy::Tuple& args = OBJ_GET(pkpy::Tuple, val);
  1015. TUPLE_REF_SET()
  1016. }else if(val->is_type(vm->tp_list)){
  1017. const pkpy::List& args = OBJ_GET(pkpy::List, val);
  1018. TUPLE_REF_SET()
  1019. }else{
  1020. vm->TypeError("only tuple or list can be unpacked");
  1021. }
  1022. #undef TUPLE_REF_SET
  1023. }
  1024. void TupleRef::del(VM* vm, Frame* frame) const{
  1025. for(int i=0; i<objs.size(); i++) vm->PyRef_AS_C(objs[i])->del(vm, frame);
  1026. }
  1027. /***** Frame's Impl *****/
  1028. inline void Frame::try_deref(VM* vm, PyVar& v){
  1029. if(v->is_type(vm->tp_ref)) v = vm->PyRef_AS_C(v)->get(vm, this);
  1030. }
  1031. PyVar pkpy::NativeFunc::operator()(VM* vm, pkpy::Args& args) const{
  1032. int args_size = args.size() - (int)method; // remove self
  1033. if(argc != -1 && args_size != argc) {
  1034. vm->TypeError("expected " + std::to_string(argc) + " arguments, but got " + std::to_string(args_size));
  1035. }
  1036. return f(vm, args);
  1037. }
  1038. void CodeObject::optimize(VM* vm){
  1039. for(int i=1; i<codes.size(); i++){
  1040. if(codes[i].op == OP_UNARY_NEGATIVE && codes[i-1].op == OP_LOAD_CONST){
  1041. codes[i].op = OP_NO_OP;
  1042. int pos = codes[i-1].arg;
  1043. consts[pos] = vm->num_negated(consts[pos]);
  1044. }
  1045. }
  1046. }