vm.h 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. #pragma once
  2. #include "codeobject.h"
  3. #include "iter.h"
  4. #include "error.h"
  5. #define __DEF_PY_AS_C(type, ctype, ptype) \
  6. inline ctype& Py##type##_AS_C(const PyVar& obj) { \
  7. check_type(obj, ptype); \
  8. return UNION_GET(ctype, obj); \
  9. }
  10. #define __DEF_PY(type, ctype, ptype) \
  11. inline PyVar Py##type(ctype value) { \
  12. return new_object(ptype, value); \
  13. }
  14. #define DEF_NATIVE(type, ctype, ptype) \
  15. __DEF_PY(type, ctype, ptype) \
  16. __DEF_PY_AS_C(type, ctype, ptype)
  17. class VM {
  18. std::vector<PyVar> _small_integers; // [-5, 256]
  19. emhash8::HashMap<_Str, _Str> _lazy_modules; // lazy loaded modules
  20. protected:
  21. std::deque< std::unique_ptr<Frame> > callstack;
  22. PyVar __py2py_call_signal;
  23. PyVar run_frame(Frame* frame){
  24. while(frame->has_next_bytecode()){
  25. const Bytecode& byte = frame->next_bytecode();
  26. //printf("[%d] %s (%d)\n", frame->stack_size(), OP_NAMES[byte.op], byte.arg);
  27. //printf("%s\n", frame->code->src->getLine(byte.line).c_str());
  28. switch (byte.op)
  29. {
  30. case OP_NO_OP: break; // do nothing
  31. case OP_LOAD_CONST: frame->push(frame->code->co_consts[byte.arg]); break;
  32. case OP_LOAD_LAMBDA: {
  33. PyVar obj = frame->code->co_consts[byte.arg];
  34. setattr(obj, __module__, frame->_module);
  35. frame->push(obj);
  36. } break;
  37. case OP_LOAD_NAME_REF: {
  38. frame->push(PyRef(NameRef(frame->code->co_names[byte.arg])));
  39. } break;
  40. case OP_LOAD_NAME: {
  41. frame->push(NameRef(frame->code->co_names[byte.arg]).get(this, frame));
  42. } break;
  43. case OP_STORE_NAME: {
  44. const auto& p = frame->code->co_names[byte.arg];
  45. NameRef(p).set(this, frame, frame->pop_value(this));
  46. } break;
  47. case OP_BUILD_ATTR_REF: {
  48. const auto& attr = frame->code->co_names[byte.arg];
  49. PyVar obj = frame->pop_value(this);
  50. frame->push(PyRef(AttrRef(obj, NameRef(attr))));
  51. } break;
  52. case OP_BUILD_INDEX_REF: {
  53. PyVar index = frame->pop_value(this);
  54. PyVarRef obj = frame->pop_value(this);
  55. frame->push(PyRef(IndexRef(obj, index)));
  56. } break;
  57. case OP_STORE_REF: {
  58. PyVar obj = frame->pop_value(this);
  59. PyVarRef r = frame->pop();
  60. PyRef_AS_C(r)->set(this, frame, std::move(obj));
  61. } break;
  62. case OP_DELETE_REF: {
  63. PyVarRef r = frame->pop();
  64. PyRef_AS_C(r)->del(this, frame);
  65. } break;
  66. case OP_BUILD_SMART_TUPLE:
  67. {
  68. pkpy::ArgList items = frame->pop_n_reversed(byte.arg);
  69. bool done = false;
  70. for(int i=0; i<items.size(); i++){
  71. if(!items[i]->is_type(_tp_ref)) {
  72. done = true;
  73. PyVarList values = items.toList();
  74. for(int j=i; j<values.size(); j++) frame->try_deref(this, values[j]);
  75. frame->push(PyTuple(values));
  76. break;
  77. }
  78. }
  79. if(done) break;
  80. frame->push(PyRef(TupleRef(items.toList())));
  81. } break;
  82. case OP_BUILD_STRING:
  83. {
  84. pkpy::ArgList 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->attribs[m_eval]);
  91. } break;
  92. case OP_LIST_APPEND: {
  93. pkpy::ArgList 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 _Func& 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->code->co_names[byte.arg].first;
  108. PyVar clsBase = frame->pop_value(this);
  109. if(clsBase == None) clsBase = _tp_object;
  110. check_type(clsBase, _tp_type);
  111. PyVar cls = new_user_type_object(frame->_module, clsName, clsBase);
  112. while(true){
  113. PyVar fn = frame->pop_value(this);
  114. if(fn == None) break;
  115. const _Func& 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::ArgList 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. // for __ne__ we use the negation of __eq__
  145. int op = byte.arg == 3 ? 2 : byte.arg;
  146. PyVar res = fast_call(CMP_SPECIAL_METHODS[op], frame->pop_n_values_reversed(this, 2));
  147. if(op != byte.arg) res = PyBool(!PyBool_AS_C(res));
  148. frame->push(std::move(res));
  149. } break;
  150. case OP_IS_OP:
  151. {
  152. bool ret_c = frame->pop_value(this) == frame->pop_value(this);
  153. if(byte.arg == 1) ret_c = !ret_c;
  154. frame->push(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::oneArg(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. {
  165. PyVar obj = frame->pop_value(this);
  166. frame->push(num_negated(obj));
  167. } break;
  168. case OP_UNARY_NOT:
  169. {
  170. PyVar obj = frame->pop_value(this);
  171. const PyVar& obj_bool = asBool(obj);
  172. frame->push(PyBool(!PyBool_AS_C(obj_bool)));
  173. } break;
  174. case OP_POP_JUMP_IF_FALSE:
  175. if(!PyBool_AS_C(asBool(frame->pop_value(this)))) frame->jump_abs(byte.arg);
  176. break;
  177. case OP_LOAD_NONE: frame->push(None); break;
  178. case OP_LOAD_TRUE: frame->push(True); break;
  179. case OP_LOAD_FALSE: frame->push(False); break;
  180. case OP_LOAD_ELLIPSIS: frame->push(Ellipsis); break;
  181. case OP_ASSERT:
  182. {
  183. PyVar expr = frame->pop_value(this);
  184. if(asBool(expr) != True) _error("AssertionError", "");
  185. } break;
  186. case OP_RAISE_ERROR:
  187. {
  188. _Str msg = PyStr_AS_C(asRepr(frame->pop_value(this)));
  189. _Str type = PyStr_AS_C(frame->pop_value(this));
  190. _error(type, msg);
  191. } break;
  192. case OP_BUILD_LIST:
  193. {
  194. frame->push(PyList(
  195. frame->pop_n_values_reversed_unlimited(this, byte.arg)
  196. ));
  197. } break;
  198. case OP_BUILD_MAP:
  199. {
  200. PyVarList items = frame->pop_n_values_reversed_unlimited(this, byte.arg*2);
  201. PyVar obj = call(builtins->attribs["dict"]);
  202. for(int i=0; i<items.size(); i+=2){
  203. call(obj, __setitem__, pkpy::twoArgs(items[i], items[i+1]));
  204. }
  205. frame->push(obj);
  206. } break;
  207. case OP_BUILD_SET:
  208. {
  209. PyVar list = PyList(
  210. frame->pop_n_values_reversed_unlimited(this, byte.arg)
  211. );
  212. PyVar obj = call(builtins->attribs["set"], pkpy::oneArg(list));
  213. frame->push(obj);
  214. } break;
  215. case OP_DUP_TOP: frame->push(frame->top_value(this)); break;
  216. case OP_CALL:
  217. {
  218. int ARGC = byte.arg & 0xFFFF;
  219. int KWARGC = (byte.arg >> 16) & 0xFFFF;
  220. pkpy::ArgList kwargs(0);
  221. if(KWARGC > 0) kwargs = frame->pop_n_values_reversed(this, KWARGC*2);
  222. pkpy::ArgList args = frame->pop_n_values_reversed(this, ARGC);
  223. PyVar callable = frame->pop_value(this);
  224. PyVar ret = call(callable, std::move(args), kwargs, true);
  225. if(ret == __py2py_call_signal) return ret;
  226. frame->push(std::move(ret));
  227. } break;
  228. case OP_JUMP_ABSOLUTE: frame->jump_abs(byte.arg); break;
  229. case OP_SAFE_JUMP_ABSOLUTE: frame->jump_abs_safe(byte.arg); break;
  230. case OP_GOTO: {
  231. PyVar obj = frame->pop_value(this);
  232. const _Str& label = PyStr_AS_C(obj);
  233. int* target = frame->code->co_labels.try_get(label);
  234. if(target == nullptr){
  235. _error("KeyError", "label '" + label + "' not found");
  236. }
  237. frame->jump_abs_safe(*target);
  238. } break;
  239. case OP_GET_ITER:
  240. {
  241. PyVar obj = frame->pop_value(this);
  242. PyVarOrNull iter_fn = getattr(obj, __iter__, false);
  243. if(iter_fn != nullptr){
  244. PyVar tmp = call(iter_fn);
  245. PyVarRef var = frame->pop();
  246. check_type(var, _tp_ref);
  247. PyIter_AS_C(tmp)->var = var;
  248. frame->push(std::move(tmp));
  249. }else{
  250. typeError("'" + UNION_TP_NAME(obj) + "' object is not iterable");
  251. }
  252. } break;
  253. case OP_FOR_ITER:
  254. {
  255. // top() must be PyIter, so no need to try_deref()
  256. auto& it = PyIter_AS_C(frame->top());
  257. if(it->hasNext()){
  258. PyRef_AS_C(it->var)->set(this, frame, it->next());
  259. }else{
  260. int blockEnd = frame->code->co_blocks[byte.block].end;
  261. frame->jump_abs_safe(blockEnd);
  262. }
  263. } break;
  264. case OP_LOOP_CONTINUE:
  265. {
  266. int blockStart = frame->code->co_blocks[byte.block].start;
  267. frame->jump_abs(blockStart);
  268. } break;
  269. case OP_LOOP_BREAK:
  270. {
  271. int blockEnd = frame->code->co_blocks[byte.block].end;
  272. frame->jump_abs_safe(blockEnd);
  273. } break;
  274. case OP_JUMP_IF_FALSE_OR_POP:
  275. {
  276. const PyVar expr = frame->top_value(this);
  277. if(asBool(expr)==False) frame->jump_abs(byte.arg);
  278. else frame->pop_value(this);
  279. } break;
  280. case OP_JUMP_IF_TRUE_OR_POP:
  281. {
  282. const PyVar expr = frame->top_value(this);
  283. if(asBool(expr)==True) frame->jump_abs(byte.arg);
  284. else frame->pop_value(this);
  285. } break;
  286. case OP_BUILD_SLICE:
  287. {
  288. PyVar stop = frame->pop_value(this);
  289. PyVar start = frame->pop_value(this);
  290. _Slice s;
  291. if(start != None) {check_type(start, _tp_int); s.start = (int)PyInt_AS_C(start);}
  292. if(stop != None) {check_type(stop, _tp_int); s.stop = (int)PyInt_AS_C(stop);}
  293. frame->push(PySlice(s));
  294. } break;
  295. case OP_IMPORT_NAME:
  296. {
  297. const _Str& name = frame->code->co_names[byte.arg].first;
  298. auto it = _modules.find(name);
  299. if(it == _modules.end()){
  300. auto it2 = _lazy_modules.find(name);
  301. if(it2 == _lazy_modules.end()){
  302. _error("ImportError", "module '" + name + "' not found");
  303. }else{
  304. const _Str& source = it2->second;
  305. _Code code = compile(source, name, EXEC_MODE);
  306. PyVar _m = newModule(name);
  307. _exec(code, _m, pkpy::make_shared<PyVarDict>());
  308. frame->push(_m);
  309. _lazy_modules.erase(it2);
  310. }
  311. }else{
  312. frame->push(it->second);
  313. }
  314. } break;
  315. // TODO: using "goto" inside with block may cause __exit__ not called
  316. case OP_WITH_ENTER: call(frame->pop_value(this), __enter__); break;
  317. case OP_WITH_EXIT: call(frame->pop_value(this), __exit__); break;
  318. default:
  319. throw std::runtime_error(_Str("opcode ") + OP_NAMES[byte.op] + " is not implemented");
  320. break;
  321. }
  322. }
  323. if(frame->code->src->mode == EVAL_MODE || frame->code->src->mode == JSON_MODE){
  324. if(frame->stack_size() != 1) throw std::runtime_error("stack size is not 1 in EVAL_MODE/JSON_MODE");
  325. return frame->pop_value(this);
  326. }
  327. if(frame->stack_size() != 0) throw std::runtime_error("stack not empty in EXEC_MODE");
  328. return None;
  329. }
  330. public:
  331. PyVarDict _types;
  332. PyVarDict _modules; // loaded modules
  333. PyVar None, True, False, Ellipsis;
  334. bool use_stdio;
  335. std::ostream* _stdout;
  336. std::ostream* _stderr;
  337. PyVar builtins; // builtins module
  338. PyVar _main; // __main__ module
  339. int maxRecursionDepth = 1000;
  340. VM(bool use_stdio){
  341. this->use_stdio = use_stdio;
  342. if(use_stdio){
  343. std::cout.setf(std::ios::unitbuf);
  344. std::cerr.setf(std::ios::unitbuf);
  345. this->_stdout = &std::cout;
  346. this->_stderr = &std::cerr;
  347. }else{
  348. this->_stdout = new _StrStream();
  349. this->_stderr = new _StrStream();
  350. }
  351. initializeBuiltinClasses();
  352. _small_integers.reserve(270);
  353. for(i64 i=-5; i<=256; i++) _small_integers.push_back(new_object(_tp_int, i));
  354. }
  355. PyVar asStr(const PyVar& obj){
  356. PyVarOrNull str_fn = getattr(obj, __str__, false);
  357. if(str_fn != nullptr) return call(str_fn);
  358. return asRepr(obj);
  359. }
  360. inline Frame* top_frame() const {
  361. if(callstack.empty()) UNREACHABLE();
  362. return callstack.back().get();
  363. }
  364. PyVar asRepr(const PyVar& obj){
  365. if(obj->is_type(_tp_type)) return PyStr("<class '" + UNION_GET(_Str, obj->attribs[__name__]) + "'>");
  366. return call(obj, __repr__);
  367. }
  368. PyVar asJson(const PyVar& obj){
  369. return call(obj, __json__);
  370. }
  371. const PyVar& asBool(const PyVar& obj){
  372. if(obj == None) return False;
  373. if(obj->is_type(_tp_bool)) return obj;
  374. if(obj->is_type(_tp_int)) return PyBool(PyInt_AS_C(obj) != 0);
  375. if(obj->is_type(_tp_float)) return PyBool(PyFloat_AS_C(obj) != 0.0);
  376. PyVarOrNull len_fn = getattr(obj, __len__, false);
  377. if(len_fn != nullptr){
  378. PyVar ret = call(len_fn);
  379. return PyBool(PyInt_AS_C(ret) > 0);
  380. }
  381. return True;
  382. }
  383. PyVar fast_call(const _Str& name, pkpy::ArgList&& args){
  384. PyObject* cls = args[0]->_type.get();
  385. while(cls != None.get()) {
  386. PyVar* val = cls->attribs.try_get(name);
  387. if(val != nullptr) return call(*val, std::move(args));
  388. cls = cls->attribs[__base__].get();
  389. }
  390. attributeError(args[0], name);
  391. return nullptr;
  392. }
  393. inline PyVar call(const PyVar& _callable){
  394. return call(_callable, pkpy::noArg(), pkpy::noArg(), false);
  395. }
  396. template<typename ArgT>
  397. inline std::enable_if_t<std::is_same_v<std::remove_const_t<std::remove_reference_t<ArgT>>, pkpy::ArgList>, PyVar>
  398. call(const PyVar& _callable, ArgT&& args){
  399. return call(_callable, std::forward<ArgT>(args), pkpy::noArg(), false);
  400. }
  401. template<typename ArgT>
  402. inline std::enable_if_t<std::is_same_v<std::remove_const_t<std::remove_reference_t<ArgT>>, pkpy::ArgList>, PyVar>
  403. call(const PyVar& obj, const _Str& func, ArgT&& args){
  404. return call(getattr(obj, func), std::forward<ArgT>(args), pkpy::noArg(), false);
  405. }
  406. inline PyVar call(const PyVar& obj, const _Str& func){
  407. return call(getattr(obj, func), pkpy::noArg(), pkpy::noArg(), false);
  408. }
  409. PyVar call(const PyVar& _callable, pkpy::ArgList args, const pkpy::ArgList& kwargs, bool opCall){
  410. if(_callable->is_type(_tp_type)){
  411. auto it = _callable->attribs.find(__new__);
  412. PyVar obj;
  413. if(it != _callable->attribs.end()){
  414. obj = call(it->second, args, kwargs, false);
  415. }else{
  416. obj = new_object(_callable, DUMMY_VAL);
  417. PyVarOrNull init_fn = getattr(obj, __init__, false);
  418. if (init_fn != nullptr) call(init_fn, args, kwargs, false);
  419. }
  420. return obj;
  421. }
  422. const PyVar* callable = &_callable;
  423. if((*callable)->is_type(_tp_bounded_method)){
  424. auto& bm = PyBoundedMethod_AS_C((*callable));
  425. callable = &bm.method; // get unbound method
  426. args.extend_self(bm.obj);
  427. }
  428. if((*callable)->is_type(_tp_native_function)){
  429. const auto& f = UNION_GET(_CppFunc, *callable);
  430. // _CppFunc do not support kwargs
  431. return f(this, args);
  432. } else if((*callable)->is_type(_tp_function)){
  433. const _Func& fn = PyFunction_AS_C((*callable));
  434. pkpy::shared_ptr<PyVarDict> _locals = pkpy::make_shared<PyVarDict>();
  435. PyVarDict& locals = *_locals;
  436. int i = 0;
  437. for(const auto& name : fn->args){
  438. if(i < args.size()){
  439. locals.emplace(name, args[i++]);
  440. continue;
  441. }
  442. typeError("missing positional argument '" + name + "'");
  443. }
  444. locals.insert(fn->kwArgs.begin(), fn->kwArgs.end());
  445. std::vector<_Str> positional_overrided_keys;
  446. if(!fn->starredArg.empty()){
  447. // handle *args
  448. PyVarList vargs;
  449. while(i < args.size()) vargs.push_back(args[i++]);
  450. locals.emplace(fn->starredArg, PyTuple(std::move(vargs)));
  451. }else{
  452. for(const auto& key : fn->kwArgsOrder){
  453. if(i < args.size()){
  454. locals[key] = args[i++];
  455. positional_overrided_keys.push_back(key);
  456. }else{
  457. break;
  458. }
  459. }
  460. if(i < args.size()) typeError("too many arguments");
  461. }
  462. for(int i=0; i<kwargs.size(); i+=2){
  463. const _Str& key = PyStr_AS_C(kwargs[i]);
  464. if(!fn->kwArgs.contains(key)){
  465. typeError(key.__escape(true) + " is an invalid keyword argument for " + fn->name + "()");
  466. }
  467. const PyVar& val = kwargs[i+1];
  468. if(!positional_overrided_keys.empty()){
  469. auto it = std::find(positional_overrided_keys.begin(), positional_overrided_keys.end(), key);
  470. if(it != positional_overrided_keys.end()){
  471. typeError("multiple values for argument '" + key + "'");
  472. }
  473. }
  474. locals[key] = val;
  475. }
  476. PyVar* it_m = (*callable)->attribs.try_get(__module__);
  477. PyVar _module = it_m != nullptr ? *it_m : top_frame()->_module;
  478. if(opCall){
  479. __push_new_frame(fn->code, _module, _locals);
  480. return __py2py_call_signal;
  481. }
  482. return _exec(fn->code, _module, _locals);
  483. }
  484. typeError("'" + UNION_TP_NAME(*callable) + "' object is not callable");
  485. return None;
  486. }
  487. // repl mode is only for setting `frame->id` to 0
  488. PyVarOrNull exec(_Str source, _Str filename, CompileMode mode, PyVar _module=nullptr){
  489. if(_module == nullptr) _module = _main;
  490. try {
  491. _Code code = compile(source, filename, mode);
  492. //if(filename != "<builtins>") std::cout << disassemble(code) << std::endl;
  493. return _exec(code, _module, pkpy::make_shared<PyVarDict>());
  494. }catch (const _Error& e){
  495. *_stderr << e.what() << '\n';
  496. }
  497. catch (const std::exception& e) {
  498. auto re = RuntimeError("UnexpectedError", e.what(), _cleanErrorAndGetSnapshots());
  499. *_stderr << re.what() << '\n';
  500. }
  501. return nullptr;
  502. }
  503. template<typename ...Args>
  504. Frame* __push_new_frame(Args&&... args){
  505. if(callstack.size() > maxRecursionDepth){
  506. throw RuntimeError("RecursionError", "maximum recursion depth exceeded", _cleanErrorAndGetSnapshots());
  507. }
  508. callstack.emplace_back(std::make_unique<Frame>(std::forward<Args>(args)...));
  509. return callstack.back().get();
  510. }
  511. template<typename ...Args>
  512. PyVar _exec(Args&&... args){
  513. Frame* frame = __push_new_frame(std::forward<Args>(args)...);
  514. Frame* frameBase = frame;
  515. PyVar ret = nullptr;
  516. while(true){
  517. ret = run_frame(frame);
  518. if(ret != __py2py_call_signal){
  519. if(frame == frameBase){ // [ frameBase<- ]
  520. break;
  521. }else{
  522. callstack.pop_back();
  523. frame = callstack.back().get();
  524. frame->push(ret);
  525. }
  526. }else{
  527. frame = callstack.back().get(); // [ frameBase, newFrame<- ]
  528. }
  529. }
  530. callstack.pop_back();
  531. return ret;
  532. }
  533. PyVar new_user_type_object(PyVar mod, _Str name, PyVar base){
  534. PyVar obj = pkpy::make_shared<PyObject, Py_<i64>>((i64)1, _tp_type);
  535. setattr(obj, __base__, base);
  536. _Str fullName = UNION_NAME(mod) + "." +name;
  537. setattr(obj, __name__, PyStr(fullName));
  538. setattr(mod, name, obj);
  539. return obj;
  540. }
  541. PyVar new_type_object(_Str name, PyVar base=nullptr) {
  542. if(base == nullptr) base = _tp_object;
  543. PyVar obj = pkpy::make_shared<PyObject, Py_<i64>>((i64)0, _tp_type);
  544. setattr(obj, __base__, base);
  545. _types[name] = obj;
  546. return obj;
  547. }
  548. template<typename T>
  549. inline PyVar new_object(PyVar type, T _value) {
  550. if(!type->is_type(_tp_type)) UNREACHABLE();
  551. return pkpy::make_shared<PyObject, Py_<T>>(_value, type);
  552. }
  553. template<typename T, typename... Args>
  554. inline PyVar new_object_c(Args&&... args) {
  555. return new_object(T::_tp(this), T(std::forward<Args>(args)...));
  556. }
  557. PyVar newModule(_Str name) {
  558. PyVar obj = new_object(_tp_module, (i64)-2);
  559. setattr(obj, __name__, PyStr(name));
  560. _modules[name] = obj;
  561. return obj;
  562. }
  563. void addLazyModule(_Str name, _Str source){
  564. _lazy_modules[name] = source;
  565. }
  566. PyVarOrNull getattr(const PyVar& obj, const _Str& name, bool throw_err=true) {
  567. PyVarDict::iterator it;
  568. PyObject* cls;
  569. if(obj->is_type(_tp_super)){
  570. const PyVar* root = &obj;
  571. int depth = 1;
  572. while(true){
  573. root = &UNION_GET(PyVar, *root);
  574. if(!(*root)->is_type(_tp_super)) break;
  575. depth++;
  576. }
  577. cls = (*root)->_type.get();
  578. for(int i=0; i<depth; i++) cls = cls->attribs[__base__].get();
  579. it = (*root)->attribs.find(name);
  580. if(it != (*root)->attribs.end()) return it->second;
  581. }else{
  582. it = obj->attribs.find(name);
  583. if(it != obj->attribs.end()) return it->second;
  584. cls = obj->_type.get();
  585. }
  586. while(cls != None.get()) {
  587. it = cls->attribs.find(name);
  588. if(it != cls->attribs.end()){
  589. PyVar valueFromCls = it->second;
  590. if(valueFromCls->is_type(_tp_function) || valueFromCls->is_type(_tp_native_function)){
  591. return PyBoundedMethod({obj, std::move(valueFromCls)});
  592. }else{
  593. return valueFromCls;
  594. }
  595. }
  596. cls = cls->attribs[__base__].get();
  597. }
  598. if(throw_err) attributeError(obj, name);
  599. return nullptr;
  600. }
  601. template<typename T>
  602. void setattr(PyObject* obj, const _Str& name, T&& value) {
  603. while(obj->is_type(_tp_super)) obj = ((Py_<PyVar>*)obj)->_valueT.get();
  604. obj->attribs[name] = value;
  605. }
  606. template<typename T>
  607. inline void setattr(PyVar& obj, const _Str& name, T&& value) {
  608. setattr(obj.get(), name, value);
  609. }
  610. template<int ARGC>
  611. void bindMethod(PyVar obj, _Str funcName, _CppFuncRaw fn) {
  612. check_type(obj, _tp_type);
  613. setattr(obj, funcName, PyNativeFunction(_CppFunc(fn, ARGC, true)));
  614. }
  615. template<int ARGC>
  616. void bindFunc(PyVar obj, _Str funcName, _CppFuncRaw fn) {
  617. setattr(obj, funcName, PyNativeFunction(_CppFunc(fn, ARGC, false)));
  618. }
  619. template<int ARGC>
  620. void bindMethod(_Str typeName, _Str funcName, _CppFuncRaw fn) {
  621. bindMethod<ARGC>(_types[typeName], funcName, fn);
  622. }
  623. template<int ARGC>
  624. void bindStaticMethod(_Str typeName, _Str funcName, _CppFuncRaw fn) {
  625. bindFunc<ARGC>(_types[typeName], funcName, fn);
  626. }
  627. template<int ARGC>
  628. void bindMethodMulti(std::vector<_Str> typeNames, _Str funcName, _CppFuncRaw fn) {
  629. for(auto& typeName : typeNames) bindMethod<ARGC>(typeName, funcName, fn);
  630. }
  631. template<int ARGC>
  632. void bindBuiltinFunc(_Str funcName, _CppFuncRaw fn) {
  633. bindFunc<ARGC>(builtins, funcName, fn);
  634. }
  635. inline bool is_int_or_float(const PyVar& obj) const{
  636. return obj->is_type(_tp_int) || obj->is_type(_tp_float);
  637. }
  638. inline bool is_int_or_float(const PyVar& obj1, const PyVar& obj2) const{
  639. return is_int_or_float(obj1) && is_int_or_float(obj2);
  640. }
  641. inline f64 num_to_float(const PyVar& obj){
  642. if (obj->is_type(_tp_int)){
  643. return (f64)PyInt_AS_C(obj);
  644. }else if(obj->is_type(_tp_float)){
  645. return PyFloat_AS_C(obj);
  646. }
  647. typeError("expected int or float, got " + UNION_TP_NAME(obj));
  648. return 0;
  649. }
  650. PyVar num_negated(const PyVar& obj){
  651. if (obj->is_type(_tp_int)){
  652. return PyInt(-PyInt_AS_C(obj));
  653. }else if(obj->is_type(_tp_float)){
  654. return PyFloat(-PyFloat_AS_C(obj));
  655. }
  656. typeError("unsupported operand type(s) for -");
  657. return nullptr;
  658. }
  659. int normalizedIndex(int index, int size){
  660. if(index < 0) index += size;
  661. if(index < 0 || index >= size){
  662. indexError("index out of range, " + std::to_string(index) + " not in [0, " + std::to_string(size) + ")");
  663. }
  664. return index;
  665. }
  666. _Str disassemble(_Code code){
  667. std::vector<int> jumpTargets;
  668. for(auto byte : code->co_code){
  669. if(byte.op == OP_JUMP_ABSOLUTE || byte.op == OP_SAFE_JUMP_ABSOLUTE || byte.op == OP_POP_JUMP_IF_FALSE){
  670. jumpTargets.push_back(byte.arg);
  671. }
  672. }
  673. _StrStream ss;
  674. ss << std::string(54, '-') << '\n';
  675. ss << code->name << ":\n";
  676. int prev_line = -1;
  677. for(int i=0; i<code->co_code.size(); i++){
  678. const Bytecode& byte = code->co_code[i];
  679. _Str line = std::to_string(byte.line);
  680. if(byte.line == prev_line) line = "";
  681. else{
  682. if(prev_line != -1) ss << "\n";
  683. prev_line = byte.line;
  684. }
  685. std::string pointer;
  686. if(std::find(jumpTargets.begin(), jumpTargets.end(), i) != jumpTargets.end()){
  687. pointer = "-> ";
  688. }else{
  689. pointer = " ";
  690. }
  691. ss << pad(line, 8) << pointer << pad(std::to_string(i), 3);
  692. ss << " " << pad(OP_NAMES[byte.op], 20) << " ";
  693. // ss << pad(byte.arg == -1 ? "" : std::to_string(byte.arg), 5);
  694. std::string argStr = byte.arg == -1 ? "" : std::to_string(byte.arg);
  695. if(byte.op == OP_LOAD_CONST){
  696. argStr += " (" + PyStr_AS_C(asRepr(code->co_consts[byte.arg])) + ")";
  697. }
  698. if(byte.op == OP_LOAD_NAME_REF || byte.op == OP_LOAD_NAME){
  699. argStr += " (" + code->co_names[byte.arg].first.__escape(true) + ")";
  700. }
  701. ss << pad(argStr, 20); // may overflow
  702. ss << code->co_blocks[byte.block].to_string();
  703. if(i != code->co_code.size() - 1) ss << '\n';
  704. }
  705. _StrStream consts;
  706. consts << "co_consts: ";
  707. consts << PyStr_AS_C(asRepr(PyList(code->co_consts)));
  708. _StrStream names;
  709. names << "co_names: ";
  710. PyVarList list;
  711. for(int i=0; i<code->co_names.size(); i++){
  712. list.push_back(PyStr(code->co_names[i].first));
  713. }
  714. names << PyStr_AS_C(asRepr(PyList(list)));
  715. ss << '\n' << consts.str() << '\n' << names.str() << '\n';
  716. for(int i=0; i<code->co_consts.size(); i++){
  717. PyVar obj = code->co_consts[i];
  718. if(obj->is_type(_tp_function)){
  719. const auto& f = PyFunction_AS_C(obj);
  720. ss << disassemble(f->code);
  721. }
  722. }
  723. return _Str(ss.str());
  724. }
  725. // for quick access
  726. PyVar _tp_object, _tp_type, _tp_int, _tp_float, _tp_bool, _tp_str;
  727. PyVar _tp_list, _tp_tuple;
  728. PyVar _tp_function, _tp_native_function, _tp_native_iterator, _tp_bounded_method;
  729. PyVar _tp_slice, _tp_range, _tp_module, _tp_ref;
  730. PyVar _tp_super;
  731. template<typename P>
  732. inline PyVarRef PyRef(P&& value) {
  733. static_assert(std::is_base_of<BaseRef, P>::value, "P should derive from BaseRef");
  734. return new_object(_tp_ref, std::forward<P>(value));
  735. }
  736. inline const BaseRef* PyRef_AS_C(const PyVar& obj)
  737. {
  738. if(!obj->is_type(_tp_ref)) typeError("expected an l-value");
  739. return (const BaseRef*)(obj->value());
  740. }
  741. __DEF_PY_AS_C(Int, i64, _tp_int)
  742. inline PyVar PyInt(i64 value) {
  743. if(value >= -5 && value <= 256) return _small_integers[value + 5];
  744. return new_object(_tp_int, value);
  745. }
  746. DEF_NATIVE(Float, f64, _tp_float)
  747. DEF_NATIVE(Str, _Str, _tp_str)
  748. DEF_NATIVE(List, PyVarList, _tp_list)
  749. DEF_NATIVE(Tuple, PyVarList, _tp_tuple)
  750. DEF_NATIVE(Function, _Func, _tp_function)
  751. DEF_NATIVE(NativeFunction, _CppFunc, _tp_native_function)
  752. DEF_NATIVE(Iter, _Iterator, _tp_native_iterator)
  753. DEF_NATIVE(BoundedMethod, _BoundedMethod, _tp_bounded_method)
  754. DEF_NATIVE(Range, _Range, _tp_range)
  755. DEF_NATIVE(Slice, _Slice, _tp_slice)
  756. // there is only one True/False, so no need to copy them!
  757. inline bool PyBool_AS_C(const PyVar& obj){return obj == True;}
  758. inline const PyVar& PyBool(bool value){return value ? True : False;}
  759. void initializeBuiltinClasses(){
  760. _tp_object = pkpy::make_shared<PyObject, Py_<i64>>((i64)0, nullptr);
  761. _tp_type = pkpy::make_shared<PyObject, Py_<i64>>((i64)0, nullptr);
  762. _types["object"] = _tp_object;
  763. _types["type"] = _tp_type;
  764. _tp_bool = new_type_object("bool");
  765. _tp_int = new_type_object("int");
  766. _tp_float = new_type_object("float");
  767. _tp_str = new_type_object("str");
  768. _tp_list = new_type_object("list");
  769. _tp_tuple = new_type_object("tuple");
  770. _tp_slice = new_type_object("slice");
  771. _tp_range = new_type_object("range");
  772. _tp_module = new_type_object("module");
  773. _tp_ref = new_type_object("_ref");
  774. new_type_object("NoneType");
  775. new_type_object("ellipsis");
  776. _tp_function = new_type_object("function");
  777. _tp_native_function = new_type_object("_native_function");
  778. _tp_native_iterator = new_type_object("_native_iterator");
  779. _tp_bounded_method = new_type_object("_bounded_method");
  780. _tp_super = new_type_object("super");
  781. this->None = new_object(_types["NoneType"], DUMMY_VAL);
  782. this->Ellipsis = new_object(_types["ellipsis"], DUMMY_VAL);
  783. this->True = new_object(_tp_bool, true);
  784. this->False = new_object(_tp_bool, false);
  785. this->builtins = newModule("builtins");
  786. this->_main = newModule("__main__");
  787. setattr(_tp_type, __base__, _tp_object);
  788. _tp_type->_type = _tp_type;
  789. setattr(_tp_object, __base__, None);
  790. _tp_object->_type = _tp_type;
  791. for (auto& [name, type] : _types) {
  792. setattr(type, __name__, PyStr(name));
  793. }
  794. this->__py2py_call_signal = new_object(_tp_object, (i64)7);
  795. std::vector<_Str> publicTypes = {"type", "object", "bool", "int", "float", "str", "list", "tuple", "range"};
  796. for (auto& name : publicTypes) {
  797. setattr(builtins, name, _types[name]);
  798. }
  799. }
  800. i64 hash(const PyVar& obj){
  801. if (obj->is_type(_tp_int)) return PyInt_AS_C(obj);
  802. if (obj->is_type(_tp_bool)) return PyBool_AS_C(obj) ? 1 : 0;
  803. if (obj->is_type(_tp_float)){
  804. f64 val = PyFloat_AS_C(obj);
  805. return (i64)std::hash<f64>()(val);
  806. }
  807. if (obj->is_type(_tp_str)) return PyStr_AS_C(obj).hash();
  808. if (obj->is_type(_tp_type)) return (i64)obj.get();
  809. if (obj->is_type(_tp_tuple)) {
  810. i64 x = 1000003;
  811. for (const auto& item : PyTuple_AS_C(obj)) {
  812. i64 y = hash(item);
  813. x = x ^ (y + 0x9e3779b9 + (x << 6) + (x >> 2)); // recommended by Github Copilot
  814. }
  815. return x;
  816. }
  817. typeError("unhashable type: " + UNION_TP_NAME(obj));
  818. return 0;
  819. }
  820. /***** Error Reporter *****/
  821. private:
  822. void _error(const _Str& name, const _Str& msg){
  823. throw RuntimeError(name, msg, _cleanErrorAndGetSnapshots());
  824. }
  825. std::stack<_Str> _cleanErrorAndGetSnapshots(){
  826. std::stack<_Str> snapshots;
  827. while (!callstack.empty()){
  828. if(snapshots.size() < 8){
  829. snapshots.push(callstack.back()->curr_snapshot());
  830. }
  831. callstack.pop_back();
  832. }
  833. return snapshots;
  834. }
  835. public:
  836. void typeError(const _Str& msg){ _error("TypeError", msg); }
  837. void zeroDivisionError(){ _error("ZeroDivisionError", "division by zero"); }
  838. void indexError(const _Str& msg){ _error("IndexError", msg); }
  839. void valueError(const _Str& msg){ _error("ValueError", msg); }
  840. void nameError(const _Str& name){ _error("NameError", "name '" + name + "' is not defined"); }
  841. void attributeError(PyVar obj, const _Str& name){
  842. _error("AttributeError", "type '" + UNION_TP_NAME(obj) + "' has no attribute '" + name + "'");
  843. }
  844. inline void check_type(const PyVar& obj, const PyVar& type){
  845. if(!obj->is_type(type)) typeError("expected '" + UNION_NAME(type) + "', but got '" + UNION_TP_NAME(obj) + "'");
  846. }
  847. ~VM() {
  848. if(!use_stdio){
  849. delete _stdout;
  850. delete _stderr;
  851. }
  852. }
  853. _Code compile(_Str source, _Str filename, CompileMode mode);
  854. };
  855. /***** Pointers' Impl *****/
  856. PyVar NameRef::get(VM* vm, Frame* frame) const{
  857. PyVar* val;
  858. val = frame->f_locals().try_get(pair->first);
  859. if(val) return *val;
  860. val = frame->f_globals().try_get(pair->first);
  861. if(val) return *val;
  862. val = vm->builtins->attribs.try_get(pair->first);
  863. if(val) return *val;
  864. vm->nameError(pair->first);
  865. return nullptr;
  866. }
  867. void NameRef::set(VM* vm, Frame* frame, PyVar val) const{
  868. switch(pair->second) {
  869. case NAME_LOCAL: frame->f_locals()[pair->first] = std::move(val); break;
  870. case NAME_GLOBAL:
  871. {
  872. PyVar* existing = frame->f_locals().try_get(pair->first);
  873. if(existing != nullptr){
  874. *existing = std::move(val);
  875. }else{
  876. frame->f_globals()[pair->first] = std::move(val);
  877. }
  878. } break;
  879. default: UNREACHABLE();
  880. }
  881. }
  882. void NameRef::del(VM* vm, Frame* frame) const{
  883. switch(pair->second) {
  884. case NAME_LOCAL: {
  885. if(frame->f_locals().contains(pair->first)){
  886. frame->f_locals().erase(pair->first);
  887. }else{
  888. vm->nameError(pair->first);
  889. }
  890. } break;
  891. case NAME_GLOBAL:
  892. {
  893. if(frame->f_locals().contains(pair->first)){
  894. frame->f_locals().erase(pair->first);
  895. }else{
  896. if(frame->f_globals().contains(pair->first)){
  897. frame->f_globals().erase(pair->first);
  898. }else{
  899. vm->nameError(pair->first);
  900. }
  901. }
  902. } break;
  903. default: UNREACHABLE();
  904. }
  905. }
  906. PyVar AttrRef::get(VM* vm, Frame* frame) const{
  907. return vm->getattr(obj, attr.pair->first);
  908. }
  909. void AttrRef::set(VM* vm, Frame* frame, PyVar val) const{
  910. vm->setattr(obj, attr.pair->first, val);
  911. }
  912. void AttrRef::del(VM* vm, Frame* frame) const{
  913. vm->typeError("cannot delete attribute");
  914. }
  915. PyVar IndexRef::get(VM* vm, Frame* frame) const{
  916. return vm->call(obj, __getitem__, pkpy::oneArg(index));
  917. }
  918. void IndexRef::set(VM* vm, Frame* frame, PyVar val) const{
  919. vm->call(obj, __setitem__, pkpy::twoArgs(index, val));
  920. }
  921. void IndexRef::del(VM* vm, Frame* frame) const{
  922. vm->call(obj, __delitem__, pkpy::oneArg(index));
  923. }
  924. PyVar TupleRef::get(VM* vm, Frame* frame) const{
  925. PyVarList args(varRefs.size());
  926. for (int i = 0; i < varRefs.size(); i++) {
  927. args[i] = vm->PyRef_AS_C(varRefs[i])->get(vm, frame);
  928. }
  929. return vm->PyTuple(args);
  930. }
  931. void TupleRef::set(VM* vm, Frame* frame, PyVar val) const{
  932. if(!val->is_type(vm->_tp_tuple) && !val->is_type(vm->_tp_list)){
  933. vm->typeError("only tuple or list can be unpacked");
  934. }
  935. const PyVarList& args = UNION_GET(PyVarList, val);
  936. if(args.size() > varRefs.size()) vm->valueError("too many values to unpack");
  937. if(args.size() < varRefs.size()) vm->valueError("not enough values to unpack");
  938. for (int i = 0; i < varRefs.size(); i++) {
  939. vm->PyRef_AS_C(varRefs[i])->set(vm, frame, args[i]);
  940. }
  941. }
  942. void TupleRef::del(VM* vm, Frame* frame) const{
  943. for (auto& r : varRefs) vm->PyRef_AS_C(r)->del(vm, frame);
  944. }
  945. /***** Frame's Impl *****/
  946. inline void Frame::try_deref(VM* vm, PyVar& v){
  947. if(v->is_type(vm->_tp_ref)) v = vm->PyRef_AS_C(v)->get(vm, this);
  948. }
  949. /***** Iterators' Impl *****/
  950. PyVar RangeIterator::next(){
  951. PyVar val = vm->PyInt(current);
  952. current += r.step;
  953. return val;
  954. }
  955. PyVar StringIterator::next(){
  956. return vm->PyStr(str.u8_getitem(index++));
  957. }
  958. PyVar _CppFunc::operator()(VM* vm, const pkpy::ArgList& args) const{
  959. int args_size = args.size() - (int)method; // remove self
  960. if(argc != -1 && args_size != argc) {
  961. vm->typeError("expected " + std::to_string(argc) + " arguments, but got " + std::to_string(args_size));
  962. }
  963. return f(vm, args);
  964. }