vm.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. #pragma once
  2. #include "frame.h"
  3. #include "error.h"
  4. #define DEF_NATIVE(type, ctype, ptype) \
  5. inline ctype& Py##type##_AS_C(const PyVar& obj) { \
  6. check_type(obj, ptype); \
  7. return OBJ_GET(ctype, obj); \
  8. } \
  9. inline PyVar Py##type(const ctype& value) { return new_object(ptype, value);} \
  10. inline PyVar Py##type(ctype&& value) { return new_object(ptype, std::move(value));}
  11. class Generator;
  12. class VM {
  13. public:
  14. std::stack< std::unique_ptr<Frame> > callstack;
  15. PyVar _py_op_call;
  16. PyVar _py_op_yield;
  17. std::vector<PyVar> _all_types;
  18. // PyVar _ascii_str_pool[128];
  19. PyVar run_frame(Frame* frame);
  20. pkpy::NameDict _types;
  21. pkpy::NameDict _modules; // loaded modules
  22. emhash8::HashMap<Str, Str> _lazy_modules; // lazy loaded modules
  23. PyVar None, True, False, Ellipsis;
  24. bool use_stdio;
  25. std::ostream* _stdout;
  26. std::ostream* _stderr;
  27. PyVar builtins; // builtins module
  28. PyVar _main; // __main__ module
  29. int recursionlimit = 1000;
  30. VM(bool use_stdio){
  31. this->use_stdio = use_stdio;
  32. if(use_stdio){
  33. this->_stdout = &std::cout;
  34. this->_stderr = &std::cerr;
  35. }else{
  36. this->_stdout = new StrStream();
  37. this->_stderr = new StrStream();
  38. }
  39. init_builtin_types();
  40. // for(int i=0; i<128; i++) _ascii_str_pool[i] = new_object(tp_str, std::string(1, (char)i));
  41. }
  42. PyVar asStr(const PyVar& obj){
  43. PyVarOrNull f = getattr(obj, __str__, false);
  44. if(f != nullptr) return call(f);
  45. return asRepr(obj);
  46. }
  47. inline Frame* top_frame() const {
  48. if(callstack.empty()) UNREACHABLE();
  49. return callstack.top().get();
  50. }
  51. PyVar asRepr(const PyVar& obj){
  52. if(obj->is_type(tp_type)) return PyStr("<class '" + OBJ_GET(Str, obj->attr(__name__)) + "'>");
  53. return call(obj, __repr__);
  54. }
  55. const PyVar& asBool(const PyVar& obj){
  56. if(obj->is_type(tp_bool)) return obj;
  57. if(obj == None) return False;
  58. if(obj->is_type(tp_int)) return PyBool(PyInt_AS_C(obj) != 0);
  59. if(obj->is_type(tp_float)) return PyBool(PyFloat_AS_C(obj) != 0.0);
  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 asIter(const PyVar& obj){
  68. if(obj->is_type(tp_native_iterator)) return obj;
  69. PyVarOrNull iter_f = getattr(obj, __iter__, false);
  70. if(iter_f != nullptr) return call(iter_f);
  71. TypeError(OBJ_NAME(_t(obj)).escape(true) + " object is not iterable");
  72. return nullptr;
  73. }
  74. PyVar asList(const PyVar& iterable){
  75. if(iterable->is_type(tp_list)) return iterable;
  76. return call(_t(tp_list), pkpy::one_arg(iterable));
  77. }
  78. PyVar fast_call(const Str& name, pkpy::Args&& args){
  79. PyObject* cls = _t(args[0]).get();
  80. while(cls != None.get()) {
  81. PyVar* val = cls->attr().try_get(name);
  82. if(val != nullptr) return call(*val, std::move(args));
  83. cls = cls->attr(__base__).get();
  84. }
  85. AttributeError(args[0], name);
  86. return nullptr;
  87. }
  88. inline PyVar call(const PyVar& _callable){
  89. return call(_callable, pkpy::no_arg(), pkpy::no_arg(), false);
  90. }
  91. template<typename ArgT>
  92. inline std::enable_if_t<std::is_same_v<RAW(ArgT), pkpy::Args>, PyVar>
  93. call(const PyVar& _callable, ArgT&& args){
  94. return call(_callable, std::forward<ArgT>(args), pkpy::no_arg(), false);
  95. }
  96. template<typename ArgT>
  97. inline std::enable_if_t<std::is_same_v<RAW(ArgT), pkpy::Args>, PyVar>
  98. call(const PyVar& obj, const Str& func, ArgT&& args){
  99. return call(getattr(obj, func), std::forward<ArgT>(args), pkpy::no_arg(), false);
  100. }
  101. inline PyVar call(const PyVar& obj, const Str& func){
  102. return call(getattr(obj, func), pkpy::no_arg(), pkpy::no_arg(), false);
  103. }
  104. PyVar call(const PyVar& _callable, pkpy::Args args, const pkpy::Args& kwargs, bool opCall){
  105. if(_callable->is_type(tp_type)){
  106. PyVar* new_f = _callable->attr().try_get(__new__);
  107. PyVar obj;
  108. if(new_f != nullptr){
  109. obj = call(*new_f, args, kwargs, false);
  110. }else{
  111. obj = new_object(_callable, DUMMY_VAL);
  112. PyVarOrNull init_f = getattr(obj, __init__, false);
  113. if (init_f != nullptr) call(init_f, args, kwargs, false);
  114. }
  115. return obj;
  116. }
  117. const PyVar* callable = &_callable;
  118. if((*callable)->is_type(tp_bound_method)){
  119. auto& bm = PyBoundMethod_AS_C((*callable));
  120. callable = &bm.method; // get unbound method
  121. args.extend_self(bm.obj);
  122. }
  123. if((*callable)->is_type(tp_native_function)){
  124. const auto& f = OBJ_GET(pkpy::NativeFunc, *callable);
  125. if(kwargs.size() != 0) TypeError("native_function does not accept keyword arguments");
  126. return f(this, args);
  127. } else if((*callable)->is_type(tp_function)){
  128. const pkpy::Function_& fn = PyFunction_AS_C((*callable));
  129. pkpy::shared_ptr<pkpy::NameDict> _locals = pkpy::make_shared<pkpy::NameDict>();
  130. pkpy::NameDict& locals = *_locals;
  131. int i = 0;
  132. for(const auto& name : fn->args){
  133. if(i < args.size()){
  134. locals.emplace(name, args[i++]);
  135. continue;
  136. }
  137. TypeError("missing positional argument '" + name + "'");
  138. }
  139. locals.insert(fn->kwargs.begin(), fn->kwargs.end());
  140. std::vector<Str> positional_overrided_keys;
  141. if(!fn->starred_arg.empty()){
  142. pkpy::List vargs; // handle *args
  143. while(i < args.size()) vargs.push_back(args[i++]);
  144. locals.emplace(fn->starred_arg, PyTuple(std::move(vargs)));
  145. }else{
  146. for(const auto& key : fn->kwargs_order){
  147. if(i < args.size()){
  148. locals[key] = args[i++];
  149. positional_overrided_keys.push_back(key);
  150. }else{
  151. break;
  152. }
  153. }
  154. if(i < args.size()) TypeError("too many arguments");
  155. }
  156. for(int i=0; i<kwargs.size(); i+=2){
  157. const Str& key = PyStr_AS_C(kwargs[i]);
  158. if(!fn->kwargs.contains(key)){
  159. TypeError(key.escape(true) + " is an invalid keyword argument for " + fn->name + "()");
  160. }
  161. const PyVar& val = kwargs[i+1];
  162. if(!positional_overrided_keys.empty()){
  163. auto it = std::find(positional_overrided_keys.begin(), positional_overrided_keys.end(), key);
  164. if(it != positional_overrided_keys.end()){
  165. TypeError("multiple values for argument '" + key + "'");
  166. }
  167. }
  168. locals[key] = val;
  169. }
  170. PyVar _module = fn->_module != nullptr ? fn->_module : top_frame()->_module;
  171. auto _frame = _new_frame(fn->code, _module, _locals, fn->_closure);
  172. if(fn->code->is_generator){
  173. return PyIter(pkpy::make_shared<BaseIter, Generator>(
  174. this, std::move(_frame)));
  175. }
  176. callstack.push(std::move(_frame));
  177. if(opCall) return _py_op_call;
  178. return _exec();
  179. }
  180. TypeError(OBJ_NAME(_t(*callable)).escape(true) + " object is not callable");
  181. return None;
  182. }
  183. // repl mode is only for setting `frame->id` to 0
  184. PyVarOrNull exec(Str source, Str filename, CompileMode mode, PyVar _module=nullptr){
  185. if(_module == nullptr) _module = _main;
  186. try {
  187. CodeObject_ code = compile(source, filename, mode);
  188. return _exec(code, _module, pkpy::make_shared<pkpy::NameDict>());
  189. }catch (const pkpy::Exception& e){
  190. *_stderr << e.summary() << '\n';
  191. }
  192. catch (const std::exception& e) {
  193. *_stderr << "A std::exception occurred! It may be a bug, please report it!!\n";
  194. *_stderr << e.what() << '\n';
  195. }
  196. callstack = {};
  197. return nullptr;
  198. }
  199. template<typename ...Args>
  200. inline std::unique_ptr<Frame> _new_frame(Args&&... args){
  201. if(callstack.size() > recursionlimit){
  202. _error("RecursionError", "maximum recursion depth exceeded");
  203. }
  204. return std::make_unique<Frame>(std::forward<Args>(args)...);
  205. }
  206. template<typename ...Args>
  207. inline PyVar _exec(Args&&... args){
  208. callstack.push(_new_frame(std::forward<Args>(args)...));
  209. return _exec();
  210. }
  211. PyVar _exec(){
  212. Frame* frame = top_frame();
  213. i64 base_id = frame->id;
  214. PyVar ret = nullptr;
  215. bool need_raise = false;
  216. while(true){
  217. if(frame->id < base_id) UNREACHABLE();
  218. try{
  219. if(need_raise){ need_raise = false; _raise(); }
  220. ret = run_frame(frame);
  221. if(ret == _py_op_yield) return _py_op_yield;
  222. if(ret != _py_op_call){
  223. if(frame->id == base_id){ // [ frameBase<- ]
  224. callstack.pop();
  225. return ret;
  226. }else{
  227. callstack.pop();
  228. frame = callstack.top().get();
  229. frame->push(ret);
  230. }
  231. }else{
  232. frame = callstack.top().get(); // [ frameBase, newFrame<- ]
  233. }
  234. }catch(HandledException& e){
  235. continue;
  236. }catch(UnhandledException& e){
  237. PyVar obj = frame->pop();
  238. pkpy::Exception& _e = PyException_AS_C(obj);
  239. _e.st_push(frame->snapshot());
  240. callstack.pop();
  241. if(callstack.empty()) throw _e;
  242. frame = callstack.top().get();
  243. frame->push(obj);
  244. if(frame->id < base_id) throw ToBeRaisedException();
  245. need_raise = true;
  246. }catch(ToBeRaisedException& e){
  247. need_raise = true;
  248. }
  249. }
  250. }
  251. PyVar new_type_object(PyVar mod, Str name, PyVar base){
  252. if(!base->is_type(tp_type)) UNREACHABLE();
  253. PyVar obj = pkpy::make_shared<PyObject, Py_<Type>>(tp_type, _all_types.size());
  254. setattr(obj, __base__, base);
  255. Str fullName = name;
  256. if(mod != builtins) fullName = OBJ_NAME(mod) + "." + name;
  257. setattr(obj, __name__, PyStr(fullName));
  258. setattr(mod, name, obj);
  259. _all_types.push_back(obj);
  260. return obj;
  261. }
  262. Type _new_type_object(Str name, Type base=0) {
  263. PyVar obj = pkpy::make_shared<PyObject, Py_<Type>>(tp_type, _all_types.size());
  264. setattr(obj, __base__, _t(base));
  265. _types[name] = obj;
  266. _all_types.push_back(obj);
  267. return OBJ_GET(Type, obj);
  268. }
  269. template<typename T>
  270. inline PyVar new_object(const PyVar& type, const T& _value) {
  271. if(!type->is_type(tp_type)) UNREACHABLE();
  272. return pkpy::make_shared<PyObject, Py_<RAW(T)>>(OBJ_GET(Type, type), _value);
  273. }
  274. template<typename T>
  275. inline PyVar new_object(const PyVar& type, T&& _value) {
  276. if(!type->is_type(tp_type)) UNREACHABLE();
  277. return pkpy::make_shared<PyObject, Py_<RAW(T)>>(OBJ_GET(Type, type), std::move(_value));
  278. }
  279. template<typename T>
  280. inline PyVar new_object(Type type, const T& _value) {
  281. return pkpy::make_shared<PyObject, Py_<RAW(T)>>(type, _value);
  282. }
  283. template<typename T>
  284. inline PyVar new_object(Type type, T&& _value) {
  285. return pkpy::make_shared<PyObject, Py_<RAW(T)>>(type, std::move(_value));
  286. }
  287. template<typename T, typename... Args>
  288. inline PyVar new_object(Args&&... args) {
  289. return new_object(T::_type(this), T(std::forward<Args>(args)...));
  290. }
  291. PyVar new_module(const Str& name) {
  292. PyVar obj = new_object(tp_module, DUMMY_VAL);
  293. setattr(obj, __name__, PyStr(name));
  294. _modules[name] = obj;
  295. return obj;
  296. }
  297. PyVarOrNull getattr(const PyVar& obj, const Str& name, bool throw_err=true) {
  298. pkpy::NameDict::iterator it;
  299. PyObject* cls;
  300. if(obj->is_type(tp_super)){
  301. const PyVar* root = &obj;
  302. int depth = 1;
  303. while(true){
  304. root = &OBJ_GET(PyVar, *root);
  305. if(!(*root)->is_type(tp_super)) break;
  306. depth++;
  307. }
  308. cls = _t(*root).get();
  309. for(int i=0; i<depth; i++) cls = cls->attr(__base__).get();
  310. it = (*root)->attr().find(name);
  311. if(it != (*root)->attr().end()) return it->second;
  312. }else{
  313. if(obj->is_attr_valid()){
  314. it = obj->attr().find(name);
  315. if(it != obj->attr().end()) return it->second;
  316. }
  317. cls = _t(obj).get();
  318. }
  319. while(cls != None.get()) {
  320. it = cls->attr().find(name);
  321. if(it != cls->attr().end()){
  322. PyVar valueFromCls = it->second;
  323. if(valueFromCls->is_type(tp_function) || valueFromCls->is_type(tp_native_function)){
  324. return PyBoundMethod({obj, std::move(valueFromCls)});
  325. }else{
  326. return valueFromCls;
  327. }
  328. }
  329. cls = cls->attr()[__base__].get();
  330. }
  331. if(throw_err) AttributeError(obj, name);
  332. return nullptr;
  333. }
  334. template<typename T>
  335. inline void setattr(PyVar& obj, const Str& name, T&& value) {
  336. PyObject* p = obj.get();
  337. while(p->is_type(tp_super)) p = static_cast<PyVar*>(p->value())->get();
  338. if(!p->is_attr_valid()) TypeError("cannot set attribute");
  339. p->attr()[name] = std::forward<T>(value);
  340. }
  341. template<int ARGC>
  342. void bind_method(PyVar obj, Str funcName, NativeFuncRaw fn) {
  343. check_type(obj, tp_type);
  344. setattr(obj, funcName, PyNativeFunc(pkpy::NativeFunc(fn, ARGC, true)));
  345. }
  346. template<int ARGC>
  347. void bind_func(PyVar obj, Str funcName, NativeFuncRaw fn) {
  348. setattr(obj, funcName, PyNativeFunc(pkpy::NativeFunc(fn, ARGC, false)));
  349. }
  350. template<int ARGC>
  351. void bind_func(Str typeName, Str funcName, NativeFuncRaw fn) {
  352. bind_func<ARGC>(_types[typeName], funcName, fn);
  353. }
  354. template<int ARGC>
  355. void bind_method(Str typeName, Str funcName, NativeFuncRaw fn) {
  356. bind_method<ARGC>(_types[typeName], funcName, fn);
  357. }
  358. template<int ARGC, typename... Args>
  359. void bind_static_method(Args&&... args) {
  360. bind_func<ARGC>(std::forward<Args>(args)...);
  361. }
  362. template<int ARGC>
  363. void _bind_methods(std::vector<Str> typeNames, Str funcName, NativeFuncRaw fn) {
  364. for(auto& typeName : typeNames) bind_method<ARGC>(typeName, funcName, fn);
  365. }
  366. template<int ARGC>
  367. void bind_builtin_func(Str funcName, NativeFuncRaw fn) {
  368. bind_func<ARGC>(builtins, funcName, fn);
  369. }
  370. inline f64 num_to_float(const PyVar& obj){
  371. if (obj->is_type(tp_int)){
  372. return (f64)PyInt_AS_C(obj);
  373. }else if(obj->is_type(tp_float)){
  374. return PyFloat_AS_C(obj);
  375. }
  376. TypeError("expected 'int' or 'float', got " + OBJ_NAME(_t(obj)).escape(true));
  377. return 0;
  378. }
  379. PyVar num_negated(const PyVar& obj){
  380. if (obj->is_type(tp_int)){
  381. return PyInt(-PyInt_AS_C(obj));
  382. }else if(obj->is_type(tp_float)){
  383. return PyFloat(-PyFloat_AS_C(obj));
  384. }
  385. TypeError("unsupported operand type(s) for -");
  386. return nullptr;
  387. }
  388. int normalized_index(int index, int size){
  389. if(index < 0) index += size;
  390. if(index < 0 || index >= size){
  391. IndexError(std::to_string(index) + " not in [0, " + std::to_string(size) + ")");
  392. }
  393. return index;
  394. }
  395. Str disassemble(CodeObject_ co){
  396. std::vector<int> jumpTargets;
  397. for(auto byte : co->codes){
  398. if(byte.op == OP_JUMP_ABSOLUTE || byte.op == OP_SAFE_JUMP_ABSOLUTE || byte.op == OP_POP_JUMP_IF_FALSE){
  399. jumpTargets.push_back(byte.arg);
  400. }
  401. }
  402. StrStream ss;
  403. ss << std::string(54, '-') << '\n';
  404. ss << co->name << ":\n";
  405. int prev_line = -1;
  406. for(int i=0; i<co->codes.size(); i++){
  407. const Bytecode& byte = co->codes[i];
  408. if(byte.op == OP_NO_OP) continue;
  409. Str line = std::to_string(byte.line);
  410. if(byte.line == prev_line) line = "";
  411. else{
  412. if(prev_line != -1) ss << "\n";
  413. prev_line = byte.line;
  414. }
  415. std::string pointer;
  416. if(std::find(jumpTargets.begin(), jumpTargets.end(), i) != jumpTargets.end()){
  417. pointer = "-> ";
  418. }else{
  419. pointer = " ";
  420. }
  421. ss << pad(line, 8) << pointer << pad(std::to_string(i), 3);
  422. ss << " " << pad(OP_NAMES[byte.op], 20) << " ";
  423. // ss << pad(byte.arg == -1 ? "" : std::to_string(byte.arg), 5);
  424. std::string argStr = byte.arg == -1 ? "" : std::to_string(byte.arg);
  425. if(byte.op == OP_LOAD_CONST){
  426. argStr += " (" + PyStr_AS_C(asRepr(co->consts[byte.arg])) + ")";
  427. }
  428. if(byte.op == OP_LOAD_NAME_REF || byte.op == OP_LOAD_NAME || byte.op == OP_RAISE){
  429. argStr += " (" + co->names[byte.arg].first.escape(true) + ")";
  430. }
  431. if(byte.op == OP_FAST_INDEX || byte.op == OP_FAST_INDEX_REF){
  432. auto& a = co->names[byte.arg & 0xFFFF];
  433. auto& x = co->names[(byte.arg >> 16) & 0xFFFF];
  434. argStr += " (" + a.first + '[' + x.first + "])";
  435. }
  436. ss << pad(argStr, 20); // may overflow
  437. ss << co->blocks[byte.block].to_string();
  438. if(i != co->codes.size() - 1) ss << '\n';
  439. }
  440. StrStream consts;
  441. consts << "co_consts: ";
  442. consts << PyStr_AS_C(asRepr(PyList(co->consts)));
  443. StrStream names;
  444. names << "co_names: ";
  445. pkpy::List list;
  446. for(int i=0; i<co->names.size(); i++){
  447. list.push_back(PyStr(co->names[i].first));
  448. }
  449. names << PyStr_AS_C(asRepr(PyList(list)));
  450. ss << '\n' << consts.str() << '\n' << names.str() << '\n';
  451. for(int i=0; i<co->consts.size(); i++){
  452. PyVar obj = co->consts[i];
  453. if(obj->is_type(tp_function)){
  454. const auto& f = PyFunction_AS_C(obj);
  455. ss << disassemble(f->code);
  456. }
  457. }
  458. return Str(ss.str());
  459. }
  460. // for quick access
  461. Type tp_object, tp_type, tp_int, tp_float, tp_bool, tp_str;
  462. Type tp_list, tp_tuple;
  463. Type tp_function, tp_native_function, tp_native_iterator, tp_bound_method;
  464. Type tp_slice, tp_range, tp_module, tp_ref;
  465. Type tp_super, tp_exception;
  466. template<typename P>
  467. inline PyVarRef PyRef(P&& value) {
  468. static_assert(std::is_base_of<BaseRef, std::remove_reference_t<P>>::value, "P should derive from BaseRef");
  469. return new_object(tp_ref, std::forward<P>(value));
  470. }
  471. inline const BaseRef* PyRef_AS_C(const PyVar& obj)
  472. {
  473. if(!obj->is_type(tp_ref)) TypeError("expected an l-value");
  474. return (const BaseRef*)(obj->value());
  475. }
  476. inline const Str& PyStr_AS_C(const PyVar& obj) {
  477. check_type(obj, tp_str);
  478. return OBJ_GET(Str, obj);
  479. }
  480. inline PyVar PyStr(const Str& value) {
  481. // some BUGs here
  482. // if(value.size() == 1){
  483. // char c = value.c_str()[0];
  484. // if(c >= 0) return _ascii_str_pool[(int)c];
  485. // }
  486. return new_object(tp_str, value);
  487. }
  488. DEF_NATIVE(Int, i64, tp_int)
  489. DEF_NATIVE(Float, f64, tp_float)
  490. DEF_NATIVE(List, pkpy::List, tp_list)
  491. DEF_NATIVE(Tuple, pkpy::Tuple, tp_tuple)
  492. DEF_NATIVE(Function, pkpy::Function_, tp_function)
  493. DEF_NATIVE(NativeFunc, pkpy::NativeFunc, tp_native_function)
  494. DEF_NATIVE(Iter, pkpy::shared_ptr<BaseIter>, tp_native_iterator)
  495. DEF_NATIVE(BoundMethod, pkpy::BoundMethod, tp_bound_method)
  496. DEF_NATIVE(Range, pkpy::Range, tp_range)
  497. DEF_NATIVE(Slice, pkpy::Slice, tp_slice)
  498. DEF_NATIVE(Exception, pkpy::Exception, tp_exception)
  499. // there is only one True/False, so no need to copy them!
  500. inline bool PyBool_AS_C(const PyVar& obj){return obj == True;}
  501. inline const PyVar& PyBool(bool value){return value ? True : False;}
  502. void init_builtin_types(){
  503. PyVar _tp_object = pkpy::make_shared<PyObject, Py_<Type>>(1, 0);
  504. PyVar _tp_type = pkpy::make_shared<PyObject, Py_<Type>>(1, 1);
  505. _all_types.push_back(_tp_object);
  506. _all_types.push_back(_tp_type);
  507. tp_object = 0; tp_type = 1;
  508. _types["object"] = _tp_object;
  509. _types["type"] = _tp_type;
  510. tp_bool = _new_type_object("bool");
  511. tp_int = _new_type_object("int");
  512. tp_float = _new_type_object("float");
  513. tp_str = _new_type_object("str");
  514. tp_list = _new_type_object("list");
  515. tp_tuple = _new_type_object("tuple");
  516. tp_slice = _new_type_object("slice");
  517. tp_range = _new_type_object("range");
  518. tp_module = _new_type_object("module");
  519. tp_ref = _new_type_object("_ref");
  520. tp_function = _new_type_object("function");
  521. tp_native_function = _new_type_object("native_function");
  522. tp_native_iterator = _new_type_object("native_iterator");
  523. tp_bound_method = _new_type_object("bound_method");
  524. tp_super = _new_type_object("super");
  525. tp_exception = _new_type_object("Exception");
  526. this->None = new_object(_new_type_object("NoneType"), DUMMY_VAL);
  527. this->Ellipsis = new_object(_new_type_object("ellipsis"), DUMMY_VAL);
  528. this->True = new_object(tp_bool, true);
  529. this->False = new_object(tp_bool, false);
  530. this->builtins = new_module("builtins");
  531. this->_main = new_module("__main__");
  532. this->_py_op_call = new_object(_new_type_object("_py_op_call"), DUMMY_VAL);
  533. this->_py_op_yield = new_object(_new_type_object("_py_op_yield"), DUMMY_VAL);
  534. setattr(_t(tp_type), __base__, _t(tp_object));
  535. setattr(_t(tp_object), __base__, None);
  536. for (auto& [name, type] : _types) {
  537. setattr(type, __name__, PyStr(name));
  538. }
  539. std::vector<Str> pb_types = {"type", "object", "bool", "int", "float", "str", "list", "tuple", "range"};
  540. for (auto& name : pb_types) {
  541. setattr(builtins, name, _types[name]);
  542. }
  543. }
  544. i64 hash(const PyVar& obj){
  545. if (obj->is_type(tp_int)) return PyInt_AS_C(obj);
  546. if (obj->is_type(tp_bool)) return PyBool_AS_C(obj) ? 1 : 0;
  547. if (obj->is_type(tp_float)){
  548. f64 val = PyFloat_AS_C(obj);
  549. return (i64)std::hash<f64>()(val);
  550. }
  551. if (obj->is_type(tp_str)) return PyStr_AS_C(obj).hash();
  552. if (obj->is_type(tp_type)) return (i64)obj.get();
  553. if (obj->is_type(tp_tuple)) {
  554. i64 x = 1000003;
  555. const pkpy::Tuple& items = PyTuple_AS_C(obj);
  556. for (int i=0; i<items.size(); i++) {
  557. i64 y = hash(items[i]);
  558. x = x ^ (y + 0x9e3779b9 + (x << 6) + (x >> 2)); // recommended by Github Copilot
  559. }
  560. return x;
  561. }
  562. TypeError("unhashable type: " + OBJ_NAME(_t(obj)).escape(true));
  563. return 0;
  564. }
  565. /***** Error Reporter *****/
  566. private:
  567. void _error(const Str& name, const Str& msg){
  568. _error(pkpy::Exception(name, msg));
  569. }
  570. void _error(pkpy::Exception e){
  571. if(callstack.empty()){
  572. e.is_re = false;
  573. throw e;
  574. }
  575. top_frame()->push(PyException(e));
  576. _raise();
  577. }
  578. void _raise(){
  579. bool ok = top_frame()->jump_to_exception_handler();
  580. if(ok) throw HandledException();
  581. else throw UnhandledException();
  582. }
  583. public:
  584. void IOError(const Str& msg) { _error("IOError", msg); }
  585. void NotImplementedError(){ _error("NotImplementedError", ""); }
  586. void TypeError(const Str& msg){ _error("TypeError", msg); }
  587. void ZeroDivisionError(){ _error("ZeroDivisionError", "division by zero"); }
  588. void IndexError(const Str& msg){ _error("IndexError", msg); }
  589. void ValueError(const Str& msg){ _error("ValueError", msg); }
  590. void NameError(const Str& name){ _error("NameError", "name " + name.escape(true) + " is not defined"); }
  591. void AttributeError(PyVar obj, const Str& name){
  592. _error("AttributeError", "type " + OBJ_NAME(_t(obj)).escape(true) + " has no attribute " + name.escape(true));
  593. }
  594. inline void check_type(const PyVar& obj, Type type){
  595. if(obj->is_type(type)) return;
  596. TypeError("expected " + OBJ_NAME(_t(type)).escape(true) + ", but got " + OBJ_NAME(_t(obj)).escape(true));
  597. }
  598. inline PyVar& _t(Type t){
  599. return _all_types[t.index];
  600. }
  601. inline PyVar& _t(const PyVar& obj){
  602. return _all_types[OBJ_GET(Type, _t(obj->type)).index];
  603. }
  604. template<typename T>
  605. PyVar register_class(PyVar mod){
  606. PyVar type = new_type_object(mod, T::_name(), _t(tp_object));
  607. if(OBJ_NAME(mod) != T::_mod()) UNREACHABLE();
  608. T::_register(this, mod, type);
  609. return type;
  610. }
  611. template<typename T>
  612. inline T& py_cast(const PyVar& obj){
  613. check_type(obj, T::_type(this));
  614. return OBJ_GET(T, obj);
  615. }
  616. ~VM() {
  617. if(!use_stdio){
  618. delete _stdout;
  619. delete _stderr;
  620. }
  621. }
  622. CodeObject_ compile(Str source, Str filename, CompileMode mode);
  623. };
  624. /***** Pointers' Impl *****/
  625. PyVar NameRef::get(VM* vm, Frame* frame) const{
  626. PyVar* val;
  627. val = frame->f_locals().try_get(name());
  628. if(val) return *val;
  629. val = frame->f_closure_try_get(name());
  630. if(val) return *val;
  631. val = frame->f_globals().try_get(name());
  632. if(val) return *val;
  633. val = vm->builtins->attr().try_get(name());
  634. if(val) return *val;
  635. vm->NameError(name());
  636. return nullptr;
  637. }
  638. void NameRef::set(VM* vm, Frame* frame, PyVar val) const{
  639. switch(scope()) {
  640. case NAME_LOCAL: frame->f_locals()[name()] = std::move(val); break;
  641. case NAME_GLOBAL:
  642. {
  643. PyVar* existing = frame->f_locals().try_get(name());
  644. if(existing != nullptr){
  645. *existing = std::move(val);
  646. }else{
  647. frame->f_globals()[name()] = std::move(val);
  648. }
  649. } break;
  650. default: UNREACHABLE();
  651. }
  652. }
  653. void NameRef::del(VM* vm, Frame* frame) const{
  654. switch(scope()) {
  655. case NAME_LOCAL: {
  656. if(frame->f_locals().contains(name())){
  657. frame->f_locals().erase(name());
  658. }else{
  659. vm->NameError(name());
  660. }
  661. } break;
  662. case NAME_GLOBAL:
  663. {
  664. if(frame->f_locals().contains(name())){
  665. frame->f_locals().erase(name());
  666. }else{
  667. if(frame->f_globals().contains(name())){
  668. frame->f_globals().erase(name());
  669. }else{
  670. vm->NameError(name());
  671. }
  672. }
  673. } break;
  674. default: UNREACHABLE();
  675. }
  676. }
  677. PyVar AttrRef::get(VM* vm, Frame* frame) const{
  678. return vm->getattr(obj, attr.name());
  679. }
  680. void AttrRef::set(VM* vm, Frame* frame, PyVar val) const{
  681. vm->setattr(obj, attr.name(), val);
  682. }
  683. void AttrRef::del(VM* vm, Frame* frame) const{
  684. if(!obj->is_attr_valid()) vm->TypeError("cannot delete attribute");
  685. if(!obj->attr().contains(attr.name())) vm->AttributeError(obj, attr.name());
  686. obj->attr().erase(attr.name());
  687. }
  688. PyVar IndexRef::get(VM* vm, Frame* frame) const{
  689. return vm->call(obj, __getitem__, pkpy::one_arg(index));
  690. }
  691. void IndexRef::set(VM* vm, Frame* frame, PyVar val) const{
  692. vm->call(obj, __setitem__, pkpy::two_args(index, val));
  693. }
  694. void IndexRef::del(VM* vm, Frame* frame) const{
  695. vm->call(obj, __delitem__, pkpy::one_arg(index));
  696. }
  697. PyVar TupleRef::get(VM* vm, Frame* frame) const{
  698. pkpy::Tuple args(objs.size());
  699. for (int i = 0; i < objs.size(); i++) {
  700. args[i] = vm->PyRef_AS_C(objs[i])->get(vm, frame);
  701. }
  702. return vm->PyTuple(std::move(args));
  703. }
  704. void TupleRef::set(VM* vm, Frame* frame, PyVar val) const{
  705. #define TUPLE_REF_SET() \
  706. if(args.size() > objs.size()) vm->ValueError("too many values to unpack"); \
  707. if(args.size() < objs.size()) vm->ValueError("not enough values to unpack"); \
  708. for (int i = 0; i < objs.size(); i++) vm->PyRef_AS_C(objs[i])->set(vm, frame, args[i]);
  709. if(val->is_type(vm->tp_tuple)){
  710. const pkpy::Tuple& args = OBJ_GET(pkpy::Tuple, val);
  711. TUPLE_REF_SET()
  712. }else if(val->is_type(vm->tp_list)){
  713. const pkpy::List& args = OBJ_GET(pkpy::List, val);
  714. TUPLE_REF_SET()
  715. }else{
  716. vm->TypeError("only tuple or list can be unpacked");
  717. }
  718. #undef TUPLE_REF_SET
  719. }
  720. void TupleRef::del(VM* vm, Frame* frame) const{
  721. for(int i=0; i<objs.size(); i++) vm->PyRef_AS_C(objs[i])->del(vm, frame);
  722. }
  723. /***** Frame's Impl *****/
  724. inline void Frame::try_deref(VM* vm, PyVar& v){
  725. if(v->is_type(vm->tp_ref)) v = vm->PyRef_AS_C(v)->get(vm, this);
  726. }
  727. PyVar pkpy::NativeFunc::operator()(VM* vm, pkpy::Args& args) const{
  728. int args_size = args.size() - (int)method; // remove self
  729. if(argc != -1 && args_size != argc) {
  730. vm->TypeError("expected " + std::to_string(argc) + " arguments, but got " + std::to_string(args_size));
  731. }
  732. return f(vm, args);
  733. }
  734. void CodeObject::optimize(VM* vm){
  735. for(int i=1; i<codes.size(); i++){
  736. if(codes[i].op == OP_UNARY_NEGATIVE && codes[i-1].op == OP_LOAD_CONST){
  737. codes[i].op = OP_NO_OP;
  738. int pos = codes[i-1].arg;
  739. consts[pos] = vm->num_negated(consts[pos]);
  740. }
  741. if(i>=2 && codes[i].op == OP_BUILD_INDEX){
  742. const Bytecode& a = codes[i-1];
  743. const Bytecode& x = codes[i-2];
  744. if(codes[i].arg == 1){
  745. if(a.op == OP_LOAD_NAME && x.op == OP_LOAD_NAME){
  746. codes[i].op = OP_FAST_INDEX;
  747. }else continue;
  748. }else{
  749. if(a.op == OP_LOAD_NAME_REF && x.op == OP_LOAD_NAME_REF){
  750. codes[i].op = OP_FAST_INDEX_REF;
  751. }else continue;
  752. }
  753. codes[i].arg = (a.arg << 16) | x.arg;
  754. codes[i-1].op = OP_NO_OP;
  755. codes[i-2].op = OP_NO_OP;
  756. }
  757. }
  758. }