vm.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  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::unique_ptr<Frame> > callstack;
  22. std::vector<PyObject*> numPool;
  23. PyVarDict _modules; // 3rd modules
  24. PyVar runFrame(Frame* frame){
  25. while(!frame->isEnd()){
  26. const ByteCode& byte = frame->readCode();
  27. //printf("%s (%d) stack_size: %d\n", OP_NAMES[byte.op], byte.arg, frame->stackSize());
  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_PTR: {
  38. frame->push(PyPointer(frame->code->co_names[byte.arg]));
  39. } break;
  40. case OP_STORE_NAME_PTR: {
  41. const auto& p = frame->code->co_names[byte.arg];
  42. p->set(this, frame, frame->popValue(this));
  43. } break;
  44. case OP_BUILD_ATTR_PTR: {
  45. const auto& attr = frame->code->co_names[byte.arg];
  46. PyVar obj = frame->popValue(this);
  47. frame->push(PyPointer(std::make_shared<AttrPointer>(obj, attr.get())));
  48. } break;
  49. case OP_BUILD_INDEX_PTR: {
  50. PyVar index = frame->popValue(this);
  51. PyVar obj = frame->popValue(this);
  52. frame->push(PyPointer(std::make_shared<IndexPointer>(obj, index)));
  53. } break;
  54. case OP_STORE_PTR: {
  55. PyVar obj = frame->popValue(this);
  56. _Pointer p = PyPointer_AS_C(frame->__pop());
  57. p->set(this, frame, obj);
  58. } break;
  59. case OP_DELETE_PTR: {
  60. _Pointer p = PyPointer_AS_C(frame->__pop());
  61. p->del(this, frame);
  62. } break;
  63. case OP_BUILD_SMART_TUPLE:
  64. {
  65. PyVarList items = frame->__popNReversed(byte.arg);
  66. bool done = false;
  67. for(auto& item : items){
  68. if(!item->isType(_tp_pointer)) {
  69. done = true;
  70. PyVarList values(items.size());
  71. for(int i=0; i<items.size(); i++){
  72. values[i] = frame->__deref_pointer(this, items[i]);
  73. }
  74. frame->push(PyTuple(values));
  75. break;
  76. }
  77. }
  78. if(done) break;
  79. std::vector<_Pointer> pointers(items.size());
  80. for(int i=0; i<items.size(); i++)
  81. pointers[i] = PyPointer_AS_C(items[i]);
  82. frame->push(PyPointer(std::make_shared<CompoundPointer>(pointers)));
  83. } break;
  84. case OP_BUILD_STRING:
  85. {
  86. PyVarList items = frame->popNValuesReversed(this, byte.arg);
  87. _StrStream ss;
  88. for(const auto& i : items) ss << PyStr_AS_C(asStr(i));
  89. frame->push(PyStr(ss));
  90. } break;
  91. case OP_LOAD_EVAL_FN: {
  92. frame->push(builtins->attribs["eval"]);
  93. } break;
  94. case OP_LIST_APPEND: {
  95. PyVar obj = frame->popValue(this);
  96. PyVar list = frame->topNValue(this, -2);
  97. fastCall(list, "append", {list, obj});
  98. } break;
  99. case OP_STORE_FUNCTION:
  100. {
  101. PyVar obj = frame->popValue(this);
  102. const _Func& fn = PyFunction_AS_C(obj);
  103. setAttr(obj, __module__, frame->_module);
  104. frame->f_globals()[fn.name] = obj;
  105. } break;
  106. case OP_BUILD_CLASS:
  107. {
  108. const _Str& clsName = frame->code->co_names[byte.arg]->name;
  109. PyVar clsBase = frame->popValue(this);
  110. if(clsBase == None) clsBase = _tp_object;
  111. __checkType(clsBase, _tp_type);
  112. PyVar cls = newUserClassType(clsName, clsBase);
  113. while(true){
  114. PyVar fn = frame->popValue(this);
  115. if(fn == None) break;
  116. const _Func& f = PyFunction_AS_C(fn);
  117. setAttr(cls, f.name, fn);
  118. }
  119. frame->f_globals()[clsName] = cls;
  120. } break;
  121. case OP_RETURN_VALUE: return frame->popValue(this);
  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)).c_str());
  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, 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. return frame->popValue(this);
  270. }
  271. if(frame->stackSize() != 0) systemError("stack not empty in EXEC_MODE");
  272. return None;
  273. }
  274. public:
  275. PyVarDict _types; // builtin types
  276. PyVar None, True, False;
  277. PrintFn _stdout = [](auto s){};
  278. PrintFn _stderr = [](auto s){};
  279. PyVar builtins; // builtins module
  280. PyVar _main; // __main__ module
  281. VM(){
  282. initializeBuiltinClasses();
  283. }
  284. PyVar asStr(const PyVar& obj){
  285. PyVarOrNull str_fn = getAttr(obj, __str__, false);
  286. if(str_fn != nullptr) return call(str_fn, {});
  287. return asRepr(obj);
  288. }
  289. Frame* topFrame(){
  290. if(callstack.size() == 0) UNREACHABLE();
  291. return callstack.top().get();
  292. }
  293. PyVar asRepr(const PyVar& obj){
  294. if(obj->isType(_tp_type)) return PyStr("<class '" + obj->getName() + "'>");
  295. return call(obj, __repr__, {});
  296. }
  297. PyVar asBool(const PyVar& obj){
  298. if(obj == None) return False;
  299. PyVar tp = obj->attribs[__class__];
  300. if(tp == _tp_bool) return obj;
  301. if(tp == _tp_int) return PyBool(PyInt_AS_C(obj) != 0);
  302. if(tp == _tp_float) return PyBool(PyFloat_AS_C(obj) != 0.0);
  303. PyVarOrNull len_fn = getAttr(obj, "__len__", false);
  304. if(len_fn != nullptr){
  305. PyVar ret = call(len_fn, {});
  306. return PyBool(PyInt_AS_C(ret) > 0);
  307. }
  308. return True;
  309. }
  310. PyVar fastCall(const PyVar& obj, const _Str& name, PyVarList args){
  311. PyVar cls = obj->attribs[__class__];
  312. while(cls != None) {
  313. auto it = cls->attribs.find(name);
  314. if(it != cls->attribs.end()){
  315. return call(it->second, args);
  316. }
  317. cls = cls->attribs[__base__];
  318. }
  319. attributeError(obj, name);
  320. return nullptr;
  321. }
  322. PyVar call(PyVar callable, PyVarList args){
  323. if(callable->isType(_tp_type)){
  324. auto it = callable->attribs.find(__new__);
  325. PyVar obj;
  326. if(it != callable->attribs.end()){
  327. obj = call(it->second, args);
  328. }else{
  329. obj = newObject(callable, (_Int)-1);
  330. }
  331. if(obj->isType(callable)){
  332. PyVarOrNull init_fn = getAttr(obj, __init__, false);
  333. if (init_fn != nullptr) call(init_fn, args);
  334. }
  335. return obj;
  336. }
  337. if(callable->isType(_tp_bounded_method)){
  338. auto& bm = PyBoundedMethod_AS_C(callable);
  339. args.insert(args.begin(), bm.obj);
  340. callable = bm.method;
  341. }
  342. if(callable->isType(_tp_native_function)){
  343. auto f = std::get<_CppFunc>(callable->_native);
  344. return f(this, args);
  345. } else if(callable->isType(_tp_function)){
  346. _Func fn = PyFunction_AS_C(callable);
  347. PyVarDict locals;
  348. int i = 0;
  349. for(const auto& name : fn.args){
  350. if(i < args.size()) {
  351. locals[name] = args[i++];
  352. }else{
  353. typeError("missing positional argument '" + name + "'");
  354. }
  355. }
  356. // handle *args
  357. if(!fn.starredArg.empty()){
  358. PyVarList vargs;
  359. while(i < args.size()) vargs.push_back(args[i++]);
  360. locals[fn.starredArg] = PyTuple(vargs);
  361. }
  362. // handle keyword arguments
  363. for(const auto& [name, value] : fn.kwArgs){
  364. if(i < args.size()) {
  365. locals[name] = args[i++];
  366. }else{
  367. locals[name] = value;
  368. }
  369. }
  370. if(i < args.size()) typeError("too many arguments");
  371. auto it_m = callable->attribs.find(__module__);
  372. if(it_m != callable->attribs.end()){
  373. return _exec(fn.code, it_m->second, locals);
  374. }else{
  375. return _exec(fn.code, topFrame()->_module, locals);
  376. }
  377. }
  378. typeError("'" + callable->getTypeName() + "' object is not callable");
  379. return None;
  380. }
  381. inline PyVar call(const PyVar& obj, const _Str& func, PyVarList args){
  382. return call(getAttr(obj, func), args);
  383. }
  384. PyVar exec(const _Code& code, PyVar _module=nullptr){
  385. if(_module == nullptr) _module = _main;
  386. try {
  387. return _exec(code, _module);
  388. } catch (const std::exception& e) {
  389. if(const _Error* _ = dynamic_cast<const _Error*>(&e)){
  390. _stderr(e.what());
  391. }else{
  392. auto re = RuntimeError("UnexpectedError", e.what(), _cleanErrorAndGetSnapshots());
  393. _stderr(re.what());
  394. }
  395. _stderr("\n");
  396. return None;
  397. }
  398. }
  399. PyVar _exec(const _Code& code, PyVar _module){
  400. PyVarDict locals;
  401. return _exec(code, _module, locals);
  402. }
  403. PyVar _exec(const _Code& code, PyVar _module, PyVarDict& locals){
  404. if(code == nullptr) UNREACHABLE();
  405. Frame* frame = new Frame(
  406. code.get(),
  407. _module,
  408. locals // pass by reference
  409. );
  410. callstack.push(std::unique_ptr<Frame>(frame));
  411. PyVar ret = runFrame(frame);
  412. callstack.pop();
  413. return ret;
  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>((_Int)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) UNREACHABLE();
  437. PyObject* _raw = nullptr;
  438. if(numPool.size() > 0) {
  439. _raw = numPool.back();
  440. _raw->_native = _native;
  441. numPool.pop_back();
  442. }else{
  443. _raw = new PyObject(_native);
  444. }
  445. PyVar obj = PyVar(_raw, [this](PyObject* p){
  446. if(numPool.size() < NUM_POOL_MAX_SIZE) numPool.push_back(p);
  447. });
  448. setAttr(obj, __class__, type);
  449. return obj;
  450. }
  451. PyVar newModule(_Str name, bool saveToPath=true) {
  452. PyVar obj = newObject(_tp_module, (_Int)-2);
  453. setAttr(obj, "__name__", PyStr(name));
  454. if(saveToPath) _modules[name] = obj;
  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. __checkType(type, _tp_type);
  499. PyVar t = obj->attribs[__class__];
  500. while (t != None){
  501. if (t == type) return true;
  502. t = t->attribs[__base__];
  503. }
  504. return false;
  505. }
  506. inline bool isIntOrFloat(const PyVar& obj){
  507. return obj->isType(_tp_int) || obj->isType(_tp_float);
  508. }
  509. inline bool isIntOrFloat(const PyVar& obj1, const PyVar& obj2){
  510. return isIntOrFloat(obj1) && isIntOrFloat(obj2);
  511. }
  512. _Float numToFloat(const PyVar& obj){
  513. if (obj->isType(_tp_int)){
  514. return (_Float)PyInt_AS_C(obj);
  515. }else if(obj->isType(_tp_float)){
  516. return PyFloat_AS_C(obj);
  517. }
  518. UNREACHABLE();
  519. }
  520. int normalizedIndex(int index, int size){
  521. if(index < 0) index += size;
  522. if(index < 0 || index >= size){
  523. indexError("index out of range, " + std::to_string(index) + " not in [0, " + std::to_string(size) + ")");
  524. }
  525. return index;
  526. }
  527. // for quick access
  528. PyVar _tp_object, _tp_type, _tp_int, _tp_float, _tp_bool, _tp_str;
  529. PyVar _tp_list, _tp_tuple;
  530. PyVar _tp_function, _tp_native_function, _tp_native_iterator, _tp_bounded_method;
  531. PyVar _tp_slice, _tp_range, _tp_module, _tp_pointer;
  532. __DEF_PY_AS_C(Int, _Int, _tp_int)
  533. __DEF_PY_AS_C(Float, _Float, _tp_float)
  534. DEF_NATIVE(Str, _Str, _tp_str)
  535. DEF_NATIVE(List, PyVarList, _tp_list)
  536. DEF_NATIVE(Tuple, PyVarList, _tp_tuple)
  537. DEF_NATIVE(Function, _Func, _tp_function)
  538. DEF_NATIVE(NativeFunction, _CppFunc, _tp_native_function)
  539. DEF_NATIVE(Iter, std::shared_ptr<_Iterator>, _tp_native_iterator)
  540. DEF_NATIVE(BoundedMethod, BoundedMethod, _tp_bounded_method)
  541. DEF_NATIVE(Range, _Range, _tp_range)
  542. DEF_NATIVE(Slice, _Slice, _tp_slice)
  543. DEF_NATIVE(Pointer, _Pointer, _tp_pointer)
  544. inline PyVar PyInt(_Int i) { return newNumber(_tp_int, i); }
  545. inline PyVar PyFloat(_Float f) { return newNumber(_tp_float, f); }
  546. inline bool PyBool_AS_C(PyVar obj){return obj == True;}
  547. inline PyVar PyBool(bool value){return value ? True : False;}
  548. void initializeBuiltinClasses(){
  549. _tp_object = std::make_shared<PyObject>((_Int)0);
  550. _tp_type = std::make_shared<PyObject>((_Int)0);
  551. _types["object"] = _tp_object;
  552. _types["type"] = _tp_type;
  553. _tp_bool = newClassType("bool");
  554. _tp_int = newClassType("int");
  555. _tp_float = newClassType("float");
  556. _tp_str = newClassType("str");
  557. _tp_list = newClassType("list");
  558. _tp_tuple = newClassType("tuple");
  559. _tp_slice = newClassType("slice");
  560. _tp_range = newClassType("range");
  561. _tp_module = newClassType("module");
  562. _tp_pointer = newClassType("_pointer");
  563. newClassType("NoneType");
  564. _tp_function = newClassType("function");
  565. _tp_native_function = newClassType("_native_function");
  566. _tp_native_iterator = newClassType("_native_iterator");
  567. _tp_bounded_method = newClassType("_bounded_method");
  568. this->None = newObject(_types["NoneType"], (_Int)0);
  569. this->True = newObject(_tp_bool, true);
  570. this->False = newObject(_tp_bool, false);
  571. this->builtins = newModule("builtins");
  572. this->_main = newModule("__main__", false);
  573. setAttr(_tp_type, __base__, _tp_object);
  574. setAttr(_tp_type, __class__, _tp_type);
  575. setAttr(_tp_object, __base__, None);
  576. setAttr(_tp_object, __class__, _tp_type);
  577. for (auto& [name, type] : _types) {
  578. setAttr(type, "__name__", PyStr(name));
  579. }
  580. std::vector<_Str> publicTypes = {"type", "object", "bool", "int", "float", "str", "list", "tuple", "range"};
  581. for (auto& name : publicTypes) {
  582. setAttr(builtins, name, _types[name]);
  583. }
  584. }
  585. _Int hash(const PyVar& obj){
  586. if (obj->isType(_tp_int)) return PyInt_AS_C(obj);
  587. if (obj->isType(_tp_bool)) return PyBool_AS_C(obj) ? 1 : 0;
  588. if (obj->isType(_tp_float)){
  589. _Float val = PyFloat_AS_C(obj);
  590. return (_Int)std::hash<_Float>()(val);
  591. }
  592. if (obj->isType(_tp_str)) return PyStr_AS_C(obj).hash();
  593. if (obj->isType(_tp_type)) return (_Int)obj.get();
  594. typeError("unhashable type: " + obj->getTypeName());
  595. return 0;
  596. }
  597. /***** Error Reporter *****/
  598. private:
  599. void _error(const _Str& name, const _Str& msg){
  600. throw RuntimeError(name, msg, _cleanErrorAndGetSnapshots());
  601. }
  602. std::stack<_Str> _cleanErrorAndGetSnapshots(){
  603. std::stack<_Str> snapshots;
  604. while (!callstack.empty()){
  605. snapshots.push(callstack.top()->errorSnapshot());
  606. callstack.pop();
  607. }
  608. return snapshots;
  609. }
  610. public:
  611. void typeError(const _Str& msg){
  612. _error("TypeError", msg);
  613. }
  614. void systemError(const _Str& msg){
  615. _error("SystemError", msg);
  616. }
  617. void zeroDivisionError(){
  618. _error("ZeroDivisionError", "division by zero");
  619. }
  620. void indexError(const _Str& msg){
  621. _error("IndexError", msg);
  622. }
  623. void valueError(const _Str& msg){
  624. _error("ValueError", msg);
  625. }
  626. void nameError(const _Str& name){
  627. _error("NameError", "name '" + name + "' is not defined");
  628. }
  629. void attributeError(PyVar obj, const _Str& name){
  630. _error("AttributeError", "type '" + obj->getTypeName() + "' has no attribute '" + name + "'");
  631. }
  632. inline void __checkType(const PyVar& obj, const PyVar& type){
  633. if(!obj->isType(type)) typeError("expected '" + type->getName() + "', but got '" + obj->getTypeName() + "'");
  634. }
  635. inline void __checkArgSize(const PyVarList& args, int size, bool method=false){
  636. if(args.size() == size) return;
  637. if(method) typeError(args.size()>size ? "too many arguments" : "too few arguments");
  638. else typeError("expected " + std::to_string(size) + " arguments, but got " + std::to_string(args.size()));
  639. }
  640. void _assert(bool val, const _Str& msg){
  641. if (!val) _error("AssertionError", msg);
  642. }
  643. };
  644. /***** Pointers' Impl *****/
  645. PyVar NamePointer::get(VM* vm, Frame* frame) const{
  646. auto it = frame->f_locals.find(name);
  647. if(it != frame->f_locals.end()) return it->second;
  648. it = frame->f_globals().find(name);
  649. if(it != frame->f_globals().end()) return it->second;
  650. it = vm->builtins->attribs.find(name);
  651. if(it != vm->builtins->attribs.end()) return it->second;
  652. vm->nameError(name);
  653. return nullptr;
  654. }
  655. void NamePointer::set(VM* vm, Frame* frame, PyVar val) const{
  656. switch(scope) {
  657. case NAME_LOCAL: frame->f_locals[name] = val; break;
  658. case NAME_GLOBAL:
  659. {
  660. if(frame->f_locals.count(name) > 0){
  661. frame->f_locals[name] = val;
  662. }else{
  663. frame->f_globals()[name] = val;
  664. }
  665. } break;
  666. default: UNREACHABLE();
  667. }
  668. }
  669. void NamePointer::del(VM* vm, Frame* frame) const{
  670. switch(scope) {
  671. case NAME_LOCAL: {
  672. if(frame->f_locals.count(name) > 0){
  673. frame->f_locals.erase(name);
  674. }else{
  675. vm->nameError(name);
  676. }
  677. } break;
  678. case NAME_GLOBAL:
  679. {
  680. if(frame->f_locals.count(name) > 0){
  681. frame->f_locals.erase(name);
  682. }else{
  683. if(frame->f_globals().count(name) > 0){
  684. frame->f_globals().erase(name);
  685. }else{
  686. vm->nameError(name);
  687. }
  688. }
  689. } break;
  690. default: UNREACHABLE();
  691. }
  692. }
  693. PyVar AttrPointer::get(VM* vm, Frame* frame) const{
  694. return vm->getAttr(obj, attr->name);
  695. }
  696. void AttrPointer::set(VM* vm, Frame* frame, PyVar val) const{
  697. vm->setAttr(obj, attr->name, val);
  698. }
  699. void AttrPointer::del(VM* vm, Frame* frame) const{
  700. vm->typeError("cannot delete attribute");
  701. }
  702. PyVar IndexPointer::get(VM* vm, Frame* frame) const{
  703. return vm->call(obj, __getitem__, {index});
  704. }
  705. void IndexPointer::set(VM* vm, Frame* frame, PyVar val) const{
  706. vm->call(obj, __setitem__, {index, val});
  707. }
  708. void IndexPointer::del(VM* vm, Frame* frame) const{
  709. vm->call(obj, __delitem__, {index});
  710. }
  711. PyVar CompoundPointer::get(VM* vm, Frame* frame) const{
  712. PyVarList args(pointers.size());
  713. for (int i = 0; i < pointers.size(); i++) {
  714. args[i] = pointers[i]->get(vm, frame);
  715. }
  716. return vm->PyTuple(args);
  717. }
  718. void CompoundPointer::set(VM* vm, Frame* frame, PyVar val) const{
  719. if(!val->isType(vm->_tp_tuple) && !val->isType(vm->_tp_list)){
  720. vm->typeError("only tuple or list can be unpacked");
  721. }
  722. const PyVarList& args = std::get<PyVarList>(val->_native);
  723. if(args.size() > pointers.size()) vm->valueError("too many values to unpack");
  724. if(args.size() < pointers.size()) vm->valueError("not enough values to unpack");
  725. for (int i = 0; i < pointers.size(); i++) {
  726. pointers[i]->set(vm, frame, args[i]);
  727. }
  728. }
  729. void CompoundPointer::del(VM* vm, Frame* frame) const{
  730. for (auto& ptr : pointers) ptr->del(vm, frame);
  731. }
  732. /***** Frame's Impl *****/
  733. inline PyVar Frame::__deref_pointer(VM* vm, PyVar v){
  734. if(v->isType(vm->_tp_pointer)) v = vm->PyPointer_AS_C(v)->get(vm, this);
  735. return v;
  736. }
  737. /***** Iterators' Impl *****/
  738. PyVar RangeIterator::next(){
  739. PyVar val = vm->PyInt(current);
  740. current += r.step;
  741. return val;
  742. }
  743. PyVar StringIterator::next(){
  744. return vm->PyStr(str->u8_getitem(index++));
  745. }