vm.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. #pragma once
  2. #include "codeobject.h"
  3. #include "iter.h"
  4. #define __DEF_PY_AS_C(type, ctype, ptype) \
  5. inline ctype& Py##type##_AS_C(const PyVar& obj) { \
  6. __checkType(obj, ptype); \
  7. return std::get<ctype>(obj->_native); \
  8. }
  9. #define __DEF_PY(type, ctype, ptype) \
  10. inline PyVar Py##type(ctype value) { \
  11. return newObject(ptype, value); \
  12. }
  13. #define DEF_NATIVE(type, ctype, ptype) \
  14. __DEF_PY(type, ctype, ptype) \
  15. __DEF_PY_AS_C(type, ctype, ptype)
  16. // TODO: we should split this into stdout and stderr
  17. typedef void(*PrintFn)(const char*);
  18. #define NUM_POOL_MAX_SIZE 1024
  19. class VM{
  20. private:
  21. std::stack< std::shared_ptr<Frame> > callstack;
  22. std::vector<PyObject*> numPool;
  23. public:
  24. PyVarDict _types; // builtin types
  25. PyVar None, True, False;
  26. PrintFn printFn = [](auto s){};
  27. PyVar builtins; // builtins module
  28. PyVar _main; // __main__ module
  29. PyVarDict _modules; // 3rd modules
  30. VM(){
  31. initializeBuiltinClasses();
  32. }
  33. void cleanError(){
  34. while(!callstack.empty()) callstack.pop();
  35. }
  36. void nameError(const _Str& name){
  37. _error("NameError", "name '" + name + "' is not defined");
  38. }
  39. void attributeError(PyVar obj, const _Str& name){
  40. _error("AttributeError", "type '" + obj->getTypeName() + "' has no attribute '" + name + "'");
  41. }
  42. inline void __checkType(const PyVar& obj, const PyVar& type){
  43. if(!obj->isType(type)){
  44. _error("TypeError", "expected '" + type->getName() + "', but got '" + obj->getTypeName() + "'");
  45. }
  46. }
  47. PyVar asStr(const PyVar& obj){
  48. PyVarOrNull str_fn = getAttr(obj, __str__, false);
  49. if(str_fn != nullptr) return call(str_fn, {});
  50. return asRepr(obj);
  51. }
  52. PyVar asRepr(const PyVar& obj){
  53. if(obj->isType(_tp_type)) return PyStr("<class '" + obj->getName() + "'>");
  54. return call(obj, __repr__, {});
  55. }
  56. PyVar asBool(const PyVar& obj){
  57. if(obj == None) return False;
  58. PyVar tp = obj->attribs[__class__];
  59. if(tp == _tp_bool) return obj;
  60. if(tp == _tp_int) return PyBool(PyInt_AS_C(obj) != 0);
  61. if(tp == _tp_float) return PyBool(PyFloat_AS_C(obj) != 0.0f);
  62. PyVarOrNull len_fn = getAttr(obj, "__len__", false);
  63. if(len_fn != nullptr){
  64. PyVar ret = call(len_fn, {});
  65. return PyBool(PyInt_AS_C(ret) > 0);
  66. }
  67. return True;
  68. }
  69. PyVar fastCall(const PyVar& obj, const _Str& name, PyVarList args){
  70. PyVar cls = obj->attribs[__class__];
  71. while(cls != None) {
  72. auto it = cls->attribs.find(name);
  73. if(it != cls->attribs.end()){
  74. return call(it->second, args);
  75. }
  76. cls = cls->attribs[__base__];
  77. }
  78. attributeError(obj, name);
  79. return nullptr;
  80. }
  81. PyVar call(PyVar callable, PyVarList args){
  82. if(callable->isType(_tp_type)){
  83. auto it = callable->attribs.find(__new__);
  84. PyVar obj;
  85. if(it != callable->attribs.end()){
  86. obj = call(it->second, args);
  87. }else{
  88. obj = newObject(callable, -1);
  89. }
  90. if(obj->isType(callable)){
  91. PyVarOrNull init_fn = getAttr(obj, __init__, false);
  92. if (init_fn != nullptr) call(init_fn, args);
  93. }
  94. return obj;
  95. }
  96. if(callable->isType(_tp_bounded_method)){
  97. auto& bm = PyBoundedMethod_AS_C(callable);
  98. args.insert(args.begin(), bm.obj);
  99. callable = bm.method;
  100. }
  101. if(callable->isType(_tp_native_function)){
  102. auto f = std::get<_CppFunc>(callable->_native);
  103. return f(this, args);
  104. } else if(callable->isType(_tp_function)){
  105. _Func fn = PyFunction_AS_C(callable);
  106. PyVarDict locals;
  107. int i = 0;
  108. for(const auto& name : fn.args){
  109. if(i < args.size()) {
  110. locals[name] = args[i++];
  111. }else{
  112. _error("TypeError", "missing positional argument '" + name + "'");
  113. }
  114. }
  115. // handle *args
  116. if(!fn.starredArg.empty()){
  117. PyVarList vargs;
  118. while(i < args.size()) vargs.push_back(args[i++]);
  119. locals[fn.starredArg] = PyTuple(vargs);
  120. }
  121. // handle keyword arguments
  122. for(const auto& [name, value] : fn.kwArgs){
  123. if(i < args.size()) {
  124. locals[name] = args[i++];
  125. }else{
  126. locals[name] = value;
  127. }
  128. }
  129. if(i < args.size()) _error("TypeError", "too many arguments");
  130. // TODO: handle **kwargs
  131. return exec(fn.code, locals);
  132. }
  133. _error("TypeError", "'" + callable->getTypeName() + "' object is not callable");
  134. return None;
  135. }
  136. inline PyVar call(const PyVar& obj, const _Str& func, PyVarList args){
  137. return call(getAttr(obj, func), args);
  138. }
  139. PyVar runFrame(std::shared_ptr<Frame> frame){
  140. callstack.push(frame);
  141. while(!frame->isEnd()){
  142. const ByteCode& byte = frame->readCode();
  143. printf("%s (%d) stack_size: %d\n", OP_NAMES[byte.op], byte.arg, frame->stackSize());
  144. switch (byte.op)
  145. {
  146. case OP_NO_OP: break; // do nothing
  147. case OP_LOAD_CONST: frame->push(frame->code->co_consts[byte.arg]); break;
  148. case OP_LOAD_NAME_PTR: {
  149. frame->push(PyPointer(frame->code->co_names[byte.arg]));
  150. } break;
  151. case OP_STORE_NAME_PTR: {
  152. const auto& p = frame->code->co_names[byte.arg];
  153. p->set(this, frame.get(), frame->popValue(this));
  154. } break;
  155. case OP_BUILD_ATTR_PTR: {
  156. const auto& attr = frame->code->co_names[byte.arg];
  157. PyVar obj = frame->popValue(this);
  158. frame->push(PyPointer(std::make_shared<AttrPointer>(obj, attr.get())));
  159. } break;
  160. case OP_BUILD_INDEX_PTR: {
  161. PyVar index = frame->popValue(this);
  162. PyVar obj = frame->popValue(this);
  163. frame->push(PyPointer(std::make_shared<IndexPointer>(obj, index)));
  164. } break;
  165. case OP_STORE_PTR: {
  166. PyVar obj = frame->popValue(this);
  167. _Pointer p = PyPointer_AS_C(frame->__pop());
  168. p->set(this, frame.get(), obj);
  169. } break;
  170. case OP_DELETE_PTR: {
  171. _Pointer p = PyPointer_AS_C(frame->__pop());
  172. p->del(this, frame.get());
  173. } break;
  174. case OP_BUILD_SMART_TUPLE:
  175. {
  176. PyVarList items = frame->__popNReversed(byte.arg);
  177. bool done = false;
  178. for(auto& item : items){
  179. if(!item->isType(_tp_pointer)) {
  180. done = true;
  181. PyVarList values(items.size());
  182. for(int i=0; i<items.size(); i++){
  183. values[i] = frame->__deref_pointer(this, items[i]);
  184. }
  185. frame->push(PyTuple(values));
  186. break;
  187. }
  188. }
  189. if(done) break;
  190. std::vector<_Pointer> pointers(items.size());
  191. for(int i=0; i<items.size(); i++)
  192. pointers[i] = PyPointer_AS_C(items[i]);
  193. frame->push(PyPointer(std::make_shared<CompoundPointer>(pointers)));
  194. } break;
  195. case OP_BUILD_STRING:
  196. {
  197. PyVarList items = frame->popNValuesReversed(this, byte.arg);
  198. _StrStream ss;
  199. for(const auto& i : items) ss << PyStr_AS_C(asStr(i));
  200. frame->push(PyStr(ss));
  201. } break;
  202. case OP_LOAD_EVAL_FN: {
  203. frame->push(builtins->attribs["eval"]);
  204. } break;
  205. case OP_LIST_APPEND: {
  206. PyVar obj = frame->popValue(this);
  207. PyVar list = frame->topNValue(this, -2);
  208. fastCall(list, "append", {list, obj});
  209. } break;
  210. case OP_STORE_FUNCTION:
  211. {
  212. PyVar obj = frame->popValue(this);
  213. const _Func& fn = PyFunction_AS_C(obj);
  214. frame->f_globals->operator[](fn.name) = obj;
  215. } break;
  216. case OP_BUILD_CLASS:
  217. {
  218. const _Str& clsName = frame->code->co_names[byte.arg]->name;
  219. PyVar clsBase = frame->popValue(this);
  220. if(clsBase == None) clsBase = _tp_object;
  221. __checkType(clsBase, _tp_type);
  222. PyVar cls = newUserClassType(clsName, clsBase);
  223. while(true){
  224. PyVar fn = frame->popValue(this);
  225. if(fn == None) break;
  226. const _Func& f = PyFunction_AS_C(fn);
  227. setAttr(cls, f.name, fn);
  228. }
  229. frame->f_globals->operator[](clsName) = cls;
  230. } break;
  231. case OP_RETURN_VALUE:
  232. {
  233. PyVar ret = frame->popValue(this);
  234. callstack.pop();
  235. return ret;
  236. } break;
  237. case OP_PRINT_EXPR:
  238. {
  239. const PyVar& expr = frame->topValue(this);
  240. if(expr == None) break;
  241. printFn(PyStr_AS_C(asRepr(expr)));
  242. printFn("\n");
  243. } break;
  244. case OP_POP_TOP: frame->popValue(this); break;
  245. case OP_BINARY_OP:
  246. {
  247. PyVar rhs = frame->popValue(this);
  248. PyVar lhs = frame->popValue(this);
  249. frame->push(fastCall(lhs, BIN_SPECIAL_METHODS[byte.arg], {lhs,rhs}));
  250. } break;
  251. case OP_COMPARE_OP:
  252. {
  253. PyVar rhs = frame->popValue(this);
  254. PyVar lhs = frame->popValue(this);
  255. // for __ne__ we use the negation of __eq__
  256. int op = byte.arg == 3 ? 2 : byte.arg;
  257. PyVar res = fastCall(lhs, CMP_SPECIAL_METHODS[op], {lhs,rhs});
  258. if(op != byte.arg) res = PyBool(!PyBool_AS_C(res));
  259. frame->push(res);
  260. } break;
  261. case OP_IS_OP:
  262. {
  263. bool ret_c = frame->popValue(this) == frame->popValue(this);
  264. if(byte.arg == 1) ret_c = !ret_c;
  265. frame->push(PyBool(ret_c));
  266. } break;
  267. case OP_CONTAINS_OP:
  268. {
  269. PyVar rhs = frame->popValue(this);
  270. PyVar lhs = frame->popValue(this);
  271. bool ret_c = PyBool_AS_C(call(rhs, __contains__, {lhs}));
  272. if(byte.arg == 1) ret_c = !ret_c;
  273. frame->push(PyBool(ret_c));
  274. } break;
  275. case OP_UNARY_NEGATIVE:
  276. {
  277. PyVar obj = frame->popValue(this);
  278. frame->push(call(obj, __neg__, {}));
  279. } break;
  280. case OP_UNARY_NOT:
  281. {
  282. PyVar obj = frame->popValue(this);
  283. PyVar obj_bool = asBool(obj);
  284. frame->push(PyBool(!PyBool_AS_C(obj_bool)));
  285. } break;
  286. case OP_POP_JUMP_IF_FALSE:
  287. if(!PyBool_AS_C(asBool(frame->popValue(this)))) frame->jumpTo(byte.arg);
  288. break;
  289. case OP_LOAD_NONE: frame->push(None); break;
  290. case OP_LOAD_TRUE: frame->push(True); break;
  291. case OP_LOAD_FALSE: frame->push(False); break;
  292. case OP_ASSERT:
  293. {
  294. PyVar expr = frame->popValue(this);
  295. if(!PyBool_AS_C(expr)) _error("AssertionError", "assertion failed");
  296. } break;
  297. case OP_RAISE_ERROR:
  298. {
  299. _Str msg = PyStr_AS_C(asRepr(frame->popValue(this)));
  300. _Str type = PyStr_AS_C(frame->popValue(this));
  301. _error(type, msg);
  302. } break;
  303. case OP_BUILD_LIST:
  304. {
  305. PyVarList items = frame->popNValuesReversed(this, byte.arg);
  306. frame->push(PyList(items));
  307. } break;
  308. case OP_BUILD_MAP:
  309. {
  310. PyVarList items = frame->popNValuesReversed(this, byte.arg*2);
  311. PyVar obj = call(builtins->attribs["dict"], {});
  312. for(int i=0; i<items.size(); i+=2){
  313. call(obj, __setitem__, {items[i], items[i+1]});
  314. }
  315. frame->push(obj);
  316. } break;
  317. case OP_DUP_TOP: frame->push(frame->topValue(this)); break;
  318. case OP_CALL:
  319. {
  320. PyVarList args = frame->popNValuesReversed(this, byte.arg);
  321. PyVar callable = frame->popValue(this);
  322. frame->push(call(callable, args));
  323. } break;
  324. case OP_JUMP_ABSOLUTE: frame->jumpTo(byte.arg); break;
  325. case OP_GET_ITER:
  326. {
  327. PyVar obj = frame->popValue(this);
  328. PyVarOrNull iter_fn = getAttr(obj, __iter__, false);
  329. if(iter_fn != nullptr){
  330. PyVar tmp = call(iter_fn, {obj});
  331. PyIter_AS_C(tmp)->var = PyPointer_AS_C(frame->__pop());
  332. frame->push(tmp);
  333. }else{
  334. _error("TypeError", "'" + obj->getTypeName() + "' object is not iterable");
  335. }
  336. } break;
  337. case OP_FOR_ITER:
  338. {
  339. const PyVar& iter = frame->topValue(this);
  340. auto& it = PyIter_AS_C(iter);
  341. if(it->hasNext()){
  342. it->var->set(this, frame.get(), it->next());
  343. }
  344. else{
  345. frame->popValue(this);
  346. frame->jumpTo(byte.arg);
  347. }
  348. } break;
  349. case OP_JUMP_IF_FALSE_OR_POP:
  350. {
  351. const PyVar& expr = frame->topValue(this);
  352. if(asBool(expr)==False) frame->jumpTo(byte.arg);
  353. else frame->popValue(this);
  354. } break;
  355. case OP_JUMP_IF_TRUE_OR_POP:
  356. {
  357. const PyVar& expr = frame->topValue(this);
  358. if(asBool(expr)==True) frame->jumpTo(byte.arg);
  359. else frame->popValue(this);
  360. } break;
  361. case OP_BUILD_SLICE:
  362. {
  363. PyVar stop = frame->popValue(this);
  364. PyVar start = frame->popValue(this);
  365. _Slice s;
  366. if(start != None) {__checkType(start, _tp_int); s.start = PyInt_AS_C(start);}
  367. if(stop != None) {__checkType(stop, _tp_int); s.stop = PyInt_AS_C(stop);}
  368. frame->push(PySlice(s));
  369. } break;
  370. case OP_IMPORT_NAME:
  371. {
  372. const _Str& name = frame->code->co_names[byte.arg]->name;
  373. auto it = _modules.find(name);
  374. if(it == _modules.end()){
  375. _error("ImportError", "module '" + name + "' not found");
  376. }else{
  377. frame->push(it->second);
  378. }
  379. } break;
  380. default:
  381. _error("SystemError", _Str("opcode ") + OP_NAMES[byte.op] + " is not implemented");
  382. break;
  383. }
  384. }
  385. if(frame->code->mode == EVAL_MODE) {
  386. if(frame->stackSize() != 1) {
  387. _error("SystemError", "stack size is not 1 in EVAL_MODE");
  388. }
  389. return frame->popValue(this);
  390. }
  391. if(frame->stackSize() != 0) _error("SystemError", "stack not empty in EXEC_MODE");
  392. callstack.pop();
  393. return None;
  394. }
  395. PyVar exec(const _Code& code, const PyVarDict& locals={}, PyVar _module=nullptr){
  396. if(_module == nullptr) _module = _main;
  397. auto frame = std::make_shared<Frame>(
  398. code.get(),
  399. locals,
  400. &_module->attribs
  401. );
  402. return runFrame(frame);
  403. }
  404. void _assert(bool val, const _Str& msg){
  405. if (!val) _error("AssertionError", msg);
  406. }
  407. void _error(const _Str& name, const _Str& msg){
  408. _StrStream ss;
  409. auto frame = callstack.top();
  410. ss << "Traceback (most recent call last):" << std::endl;
  411. ss << " File '" << frame->code->co_filename << "', line ";
  412. ss << frame->currentLine() << '\n' << name << ": " << msg;
  413. throw std::runtime_error(ss.str());
  414. }
  415. PyVar newUserClassType(_Str name, PyVar base){
  416. PyVar obj = newClassType(name, base);
  417. setAttr(obj, "__name__", PyStr(name));
  418. _types.erase(name);
  419. return obj;
  420. }
  421. PyVar newClassType(_Str name, PyVar base=nullptr) {
  422. if(base == nullptr) base = _tp_object;
  423. PyVar obj = std::make_shared<PyObject>(0);
  424. setAttr(obj, __class__, _tp_type);
  425. setAttr(obj, __base__, base);
  426. _types[name] = obj;
  427. return obj;
  428. }
  429. PyVar newObject(PyVar type, _Value _native) {
  430. __checkType(type, _tp_type);
  431. PyVar obj = std::make_shared<PyObject>(_native);
  432. setAttr(obj, __class__, type);
  433. return obj;
  434. }
  435. PyVar newNumber(PyVar type, _Value _native) {
  436. if(type != _tp_int && type != _tp_float)
  437. _error("SystemError", "type is not a number type");
  438. PyObject* _raw = nullptr;
  439. if(numPool.size() > 0) {
  440. _raw = numPool.back();
  441. _raw->_native = _native;
  442. numPool.pop_back();
  443. }else{
  444. _raw = new PyObject(_native);
  445. }
  446. PyVar obj = PyVar(_raw, [this](PyObject* p){
  447. if(numPool.size() < NUM_POOL_MAX_SIZE) numPool.push_back(p);
  448. });
  449. setAttr(obj, __class__, type);
  450. return obj;
  451. }
  452. PyVar newModule(_Str name) {
  453. PyVar obj = newObject(_tp_module, 0);
  454. setAttr(obj, "__name__", PyStr(name));
  455. return obj;
  456. }
  457. PyVarOrNull getAttr(const PyVar& obj, const _Str& name, bool throw_err=true) {
  458. auto it = obj->attribs.find(name);
  459. if(it != obj->attribs.end()) return it->second;
  460. PyVar cls = obj->attribs[__class__];
  461. while(cls != None) {
  462. it = cls->attribs.find(name);
  463. if(it != cls->attribs.end()){
  464. PyVar valueFromCls = it->second;
  465. if(valueFromCls->isType(_tp_function) || valueFromCls->isType(_tp_native_function)){
  466. return PyBoundedMethod({obj, valueFromCls});
  467. }else{
  468. return valueFromCls;
  469. }
  470. }
  471. cls = cls->attribs[__base__];
  472. }
  473. if(throw_err) attributeError(obj, name);
  474. return nullptr;
  475. }
  476. inline void setAttr(PyVar& obj, const _Str& name, PyVar value) {
  477. obj->attribs[name] = value;
  478. }
  479. void bindMethod(_Str typeName, _Str funcName, _CppFunc fn) {
  480. PyVar type = _types[typeName];
  481. PyVar func = PyNativeFunction(fn);
  482. setAttr(type, funcName, func);
  483. }
  484. void bindMethodMulti(std::vector<_Str> typeNames, _Str funcName, _CppFunc fn) {
  485. for(auto& typeName : typeNames){
  486. bindMethod(typeName, funcName, fn);
  487. }
  488. }
  489. void bindBuiltinFunc(_Str funcName, _CppFunc fn) {
  490. bindFunc(builtins, funcName, fn);
  491. }
  492. void bindFunc(PyVar module, _Str funcName, _CppFunc fn) {
  493. __checkType(module, _tp_module);
  494. PyVar func = PyNativeFunction(fn);
  495. setAttr(module, funcName, func);
  496. }
  497. bool isInstance(PyVar obj, PyVar type){
  498. PyVar t = obj->attribs[__class__];
  499. while (t != None){
  500. if (t == type) return true;
  501. t = t->attribs[__base__];
  502. }
  503. return false;
  504. }
  505. inline bool isIntOrFloat(const PyVar& obj){
  506. return obj->isType(_tp_int) || obj->isType(_tp_float);
  507. }
  508. inline bool isIntOrFloat(const PyVar& obj1, const PyVar& obj2){
  509. return isIntOrFloat(obj1) && isIntOrFloat(obj2);
  510. }
  511. float numToFloat(const PyVar& obj){
  512. if (obj->isType(_tp_int)){
  513. return (float)PyInt_AS_C(obj);
  514. }else if(obj->isType(_tp_float)){
  515. return PyFloat_AS_C(obj);
  516. }
  517. UNREACHABLE();
  518. }
  519. int normalizedIndex(int index, int size){
  520. if(index < 0) index += size;
  521. if(index < 0 || index >= size){
  522. _error("IndexError", "index out of range, " + std::to_string(index) + " not in [0, " + std::to_string(size) + ")");
  523. }
  524. return index;
  525. }
  526. // for quick access
  527. PyVar _tp_object, _tp_type, _tp_int, _tp_float, _tp_bool, _tp_str;
  528. PyVar _tp_list, _tp_tuple;
  529. PyVar _tp_function, _tp_native_function, _tp_native_iterator, _tp_bounded_method;
  530. PyVar _tp_slice, _tp_range, _tp_module, _tp_pointer;
  531. __DEF_PY_AS_C(Int, int, _tp_int)
  532. __DEF_PY_AS_C(Float, float, _tp_float)
  533. DEF_NATIVE(Str, _Str, _tp_str)
  534. DEF_NATIVE(List, PyVarList, _tp_list)
  535. DEF_NATIVE(Tuple, PyVarList, _tp_tuple)
  536. DEF_NATIVE(Function, _Func, _tp_function)
  537. DEF_NATIVE(NativeFunction, _CppFunc, _tp_native_function)
  538. DEF_NATIVE(Iter, std::shared_ptr<_Iterator>, _tp_native_iterator)
  539. DEF_NATIVE(BoundedMethod, BoundedMethod, _tp_bounded_method)
  540. DEF_NATIVE(Range, _Range, _tp_range)
  541. DEF_NATIVE(Slice, _Slice, _tp_slice)
  542. DEF_NATIVE(Pointer, _Pointer, _tp_pointer)
  543. inline PyVar PyInt(int i) { return newNumber(_tp_int, i); }
  544. inline PyVar PyFloat(float f) { return newNumber(_tp_float, f); }
  545. inline bool PyBool_AS_C(PyVar obj){return obj == True;}
  546. inline PyVar PyBool(bool value){return value ? True : False;}
  547. void initializeBuiltinClasses(){
  548. _tp_object = std::make_shared<PyObject>(0);
  549. _tp_type = std::make_shared<PyObject>(0);
  550. _types["object"] = _tp_object;
  551. _types["type"] = _tp_type;
  552. _tp_bool = newClassType("bool");
  553. _tp_int = newClassType("int");
  554. _tp_float = newClassType("float");
  555. _tp_str = newClassType("str");
  556. _tp_list = newClassType("list");
  557. _tp_tuple = newClassType("tuple");
  558. _tp_slice = newClassType("slice");
  559. _tp_range = newClassType("range");
  560. _tp_module = newClassType("module");
  561. _tp_pointer = newClassType("_pointer");
  562. newClassType("NoneType");
  563. _tp_function = newClassType("function");
  564. _tp_native_function = newClassType("_native_function");
  565. _tp_native_iterator = newClassType("_native_iterator");
  566. _tp_bounded_method = newClassType("_bounded_method");
  567. this->None = newObject(_types["NoneType"], 0);
  568. this->True = newObject(_tp_bool, true);
  569. this->False = newObject(_tp_bool, false);
  570. this->builtins = newModule("__builtins__");
  571. this->_main = newModule("__main__");
  572. setAttr(_tp_type, __base__, _tp_object);
  573. setAttr(_tp_type, __class__, _tp_type);
  574. setAttr(_tp_object, __base__, None);
  575. setAttr(_tp_object, __class__, _tp_type);
  576. for (auto& [name, type] : _types) {
  577. setAttr(type, "__name__", PyStr(name));
  578. }
  579. std::vector<_Str> publicTypes = {"type", "object", "bool", "int", "float", "str", "list", "tuple", "range"};
  580. for (auto& name : publicTypes) {
  581. setAttr(builtins, name, _types[name]);
  582. }
  583. }
  584. int hash(const PyVar& obj){
  585. if (obj->isType(_tp_int)) return PyInt_AS_C(obj);
  586. if (obj->isType(_tp_bool)) return PyBool_AS_C(obj) ? 1 : 0;
  587. if (obj->isType(_tp_float)){
  588. float val = PyFloat_AS_C(obj);
  589. return (int)std::hash<float>()(val);
  590. }
  591. if (obj->isType(_tp_str)) return PyStr_AS_C(obj).hash();
  592. if (obj->isType(_tp_type)) return (int64_t)obj.get();
  593. _error("TypeError", "unhashable type: " + obj->getTypeName());
  594. return 0;
  595. }
  596. void registerCompiledModule(_Str name, _Code code){
  597. PyVar _m = newModule(name);
  598. exec(code, {}, _m);
  599. _modules[name] = _m;
  600. }
  601. };
  602. /**************** Pointers' Impl ****************/
  603. PyVar NamePointer::get(VM* vm, Frame* frame) const{
  604. auto it = frame->f_locals.find(name);
  605. if(it != frame->f_locals.end()) return it->second;
  606. it = frame->f_globals->find(name);
  607. if(it != frame->f_globals->end()) return it->second;
  608. it = vm->builtins->attribs.find(name);
  609. if(it != vm->builtins->attribs.end()) return it->second;
  610. vm->nameError(name);
  611. return nullptr;
  612. }
  613. void NamePointer::set(VM* vm, Frame* frame, PyVar val) const{
  614. switch(scope) {
  615. case NAME_LOCAL: frame->f_locals[name] = val; break;
  616. case NAME_GLOBAL:
  617. {
  618. if(frame->f_locals.count(name) > 0){
  619. frame->f_locals[name] = val;
  620. }else{
  621. frame->f_globals->operator[](name) = val;
  622. }
  623. } break;
  624. default: UNREACHABLE();
  625. }
  626. }
  627. void NamePointer::del(VM* vm, Frame* frame) const{
  628. switch(scope) {
  629. case NAME_LOCAL: {
  630. if(frame->f_locals.count(name) > 0){
  631. frame->f_locals.erase(name);
  632. }else{
  633. vm->nameError(name);
  634. }
  635. } break;
  636. case NAME_GLOBAL:
  637. {
  638. if(frame->f_locals.count(name) > 0){
  639. frame->f_locals.erase(name);
  640. }else{
  641. if(frame->f_globals->count(name) > 0){
  642. frame->f_globals->erase(name);
  643. }else{
  644. vm->nameError(name);
  645. }
  646. }
  647. } break;
  648. default: UNREACHABLE();
  649. }
  650. }
  651. PyVar AttrPointer::get(VM* vm, Frame* frame) const{
  652. return vm->getAttr(obj, attr->name);
  653. }
  654. void AttrPointer::set(VM* vm, Frame* frame, PyVar val) const{
  655. vm->setAttr(obj, attr->name, val);
  656. }
  657. void AttrPointer::del(VM* vm, Frame* frame) const{
  658. vm->_error("AttributeError", "can't delete attribute");
  659. }
  660. PyVar IndexPointer::get(VM* vm, Frame* frame) const{
  661. return vm->call(obj, __getitem__, {index});
  662. }
  663. void IndexPointer::set(VM* vm, Frame* frame, PyVar val) const{
  664. vm->call(obj, __setitem__, {index, val});
  665. }
  666. void IndexPointer::del(VM* vm, Frame* frame) const{
  667. vm->call(obj, __delitem__, {index});
  668. }
  669. PyVar CompoundPointer::get(VM* vm, Frame* frame) const{
  670. PyVarList args(pointers.size());
  671. for (int i = 0; i < pointers.size(); i++) {
  672. args[i] = pointers[i]->get(vm, frame);
  673. }
  674. return vm->PyTuple(args);
  675. }
  676. void CompoundPointer::set(VM* vm, Frame* frame, PyVar val) const{
  677. if(!val->isType(vm->_tp_tuple) && !val->isType(vm->_tp_list)){
  678. vm->_error("TypeError", "only tuple or list can be unpacked");
  679. }
  680. const PyVarList& args = std::get<PyVarList>(val->_native);
  681. if(args.size() > pointers.size()) vm->_error("ValueError", "too many values to unpack");
  682. if(args.size() < pointers.size()) vm->_error("ValueError", "not enough values to unpack");
  683. for (int i = 0; i < pointers.size(); i++) {
  684. pointers[i]->set(vm, frame, args[i]);
  685. }
  686. }
  687. void CompoundPointer::del(VM* vm, Frame* frame) const{
  688. for (auto& ptr : pointers) ptr->del(vm, frame);
  689. }
  690. /**************** Frame ****************/
  691. inline PyVar Frame::__deref_pointer(VM* vm, PyVar v){
  692. if(v->isType(vm->_tp_pointer)) v = vm->PyPointer_AS_C(v)->get(vm, this);
  693. return v;
  694. }