vm.h 28 KB

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