vm.h 25 KB

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