vm.h 30 KB

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