vm.h 31 KB

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