vm.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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. #ifdef 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. #ifdef 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. #ifdef 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. template<typename T>
  328. std::enable_if_t<std::is_integral_v<T> && !std::is_same_v<std::decay_t<T>, bool>, PyVar> py_var(VM* vm, T _val){
  329. i64 val = static_cast<i64>(_val);
  330. if(((val << 2) >> 2) != val){
  331. vm->_error("OverflowError", std::to_string(val) + " is out of range");
  332. }
  333. val = (val << 2) | 0b01;
  334. return PyVar(reinterpret_cast<int*>(val));
  335. }
  336. template<> i64 py_cast<i64>(VM* vm, const PyVar& obj){
  337. vm->check_type(obj, vm->tp_int);
  338. return obj.bits >> 2;
  339. }
  340. template<> i64 _py_cast<i64>(VM* vm, const PyVar& obj){
  341. return obj.bits >> 2;
  342. }
  343. template<> f64 py_cast<f64>(VM* vm, const PyVar& obj){
  344. vm->check_type(obj, vm->tp_float);
  345. i64 bits = obj.bits;
  346. bits = (bits >> 2) << 2;
  347. return __8B(bits)._float;
  348. }
  349. template<> f64 _py_cast<f64>(VM* vm, const PyVar& obj){
  350. i64 bits = obj.bits;
  351. bits = (bits >> 2) << 2;
  352. return __8B(bits)._float;
  353. }
  354. #ifndef PKPY_USE_32_BITS
  355. template<> int py_cast<int>(VM* vm, const PyVar& obj){
  356. vm->check_type(obj, vm->tp_int);
  357. return obj.bits >> 2;
  358. }
  359. template<> int _py_cast<int>(VM* vm, const PyVar& obj){
  360. return obj.bits >> 2;
  361. }
  362. template<> float py_cast<float>(VM* vm, const PyVar& obj){
  363. vm->check_type(obj, vm->tp_float);
  364. i64 bits = obj.bits;
  365. bits = (bits >> 2) << 2;
  366. return __8B(bits)._float;
  367. }
  368. template<> float _py_cast<float>(VM* vm, const PyVar& obj){
  369. i64 bits = obj.bits;
  370. bits = (bits >> 2) << 2;
  371. return __8B(bits)._float;
  372. }
  373. #endif
  374. template<typename T>
  375. std::enable_if_t<std::is_floating_point_v<T>, PyVar> py_var(VM* vm, T _val){
  376. f64 val = static_cast<f64>(_val);
  377. i64 bits = __8B(val)._int;
  378. bits = (bits >> 2) << 2;
  379. bits |= 0b10;
  380. return PyVar(reinterpret_cast<int*>(bits));
  381. }
  382. const PyVar& py_var(VM* vm, bool val){
  383. return val ? vm->True : vm->False;
  384. }
  385. template<> bool py_cast<bool>(VM* vm, const PyVar& obj){
  386. vm->check_type(obj, vm->tp_bool);
  387. return obj == vm->True;
  388. }
  389. template<> bool _py_cast<bool>(VM* vm, const PyVar& obj){
  390. return obj == vm->True;
  391. }
  392. PyVar py_var(VM* vm, const char val[]){
  393. return VAR(Str(val));
  394. }
  395. template<typename T>
  396. void _check_py_class(VM* vm, const PyVar& obj){
  397. vm->check_type(obj, T::_type(vm));
  398. }
  399. PyVar VM::num_negated(const PyVar& obj){
  400. if (is_int(obj)){
  401. return VAR(-CAST(i64, obj));
  402. }else if(is_float(obj)){
  403. return VAR(-CAST(f64, obj));
  404. }
  405. TypeError("expected 'int' or 'float', got " + OBJ_NAME(_t(obj)).escape(true));
  406. return nullptr;
  407. }
  408. f64 VM::num_to_float(const PyVar& obj){
  409. if(is_float(obj)){
  410. return CAST(f64, obj);
  411. } else if (is_int(obj)){
  412. return (f64)CAST(i64, obj);
  413. }
  414. TypeError("expected 'int' or 'float', got " + OBJ_NAME(_t(obj)).escape(true));
  415. return 0;
  416. }
  417. const PyVar& VM::asBool(const PyVar& obj){
  418. if(is_type(obj, tp_bool)) return obj;
  419. if(obj == None) return False;
  420. if(is_type(obj, tp_int)) return VAR(CAST(i64, obj) != 0);
  421. if(is_type(obj, tp_float)) return VAR(CAST(f64, obj) != 0.0);
  422. PyVarOrNull len_fn = getattr(obj, __len__, false, true);
  423. if(len_fn != nullptr){
  424. PyVar ret = call(len_fn);
  425. return VAR(CAST(i64, ret) > 0);
  426. }
  427. return True;
  428. }
  429. i64 VM::hash(const PyVar& obj){
  430. if (is_type(obj, tp_str)) return CAST(Str&, obj).hash();
  431. if (is_int(obj)) return CAST(i64, obj);
  432. if (is_type(obj, tp_tuple)) {
  433. i64 x = 1000003;
  434. const Tuple& items = CAST(Tuple&, obj);
  435. for (int i=0; i<items.size(); i++) {
  436. i64 y = hash(items[i]);
  437. x = x ^ (y + 0x9e3779b9 + (x << 6) + (x >> 2)); // recommended by Github Copilot
  438. }
  439. return x;
  440. }
  441. if (is_type(obj, tp_type)) return obj.bits;
  442. if (is_type(obj, tp_bool)) return _CAST(bool, obj) ? 1 : 0;
  443. if (is_float(obj)){
  444. f64 val = CAST(f64, obj);
  445. return (i64)std::hash<f64>()(val);
  446. }
  447. TypeError("unhashable type: " + OBJ_NAME(_t(obj)).escape(true));
  448. return 0;
  449. }
  450. PyVar VM::asRepr(const PyVar& obj){
  451. return call(obj, __repr__);
  452. }
  453. PyVar VM::new_type_object(PyVar mod, StrName name, PyVar base){
  454. if(!is_type(base, tp_type)) UNREACHABLE();
  455. PyVar obj = make_sp<PyObject, Py_<Type>>(tp_type, _all_types.size());
  456. setattr(obj, __base__, base);
  457. Str fullName = name.str();
  458. if(mod != builtins) fullName = OBJ_NAME(mod) + "." + name.str();
  459. setattr(obj, __name__, VAR(fullName));
  460. setattr(mod, name, obj);
  461. _all_types.push_back(obj);
  462. return obj;
  463. }
  464. PyVar VM::new_module(StrName name) {
  465. PyVar obj = new_object(tp_module, DummyModule());
  466. setattr(obj, __name__, VAR(name.str()));
  467. _modules.set(name, obj);
  468. return obj;
  469. }
  470. Str VM::disassemble(CodeObject_ co){
  471. std::vector<int> jumpTargets;
  472. for(auto byte : co->codes){
  473. if(byte.op == OP_JUMP_ABSOLUTE || byte.op == OP_SAFE_JUMP_ABSOLUTE || byte.op == OP_POP_JUMP_IF_FALSE){
  474. jumpTargets.push_back(byte.arg);
  475. }
  476. }
  477. StrStream ss;
  478. ss << std::string(54, '-') << '\n';
  479. ss << co->name << ":\n";
  480. int prev_line = -1;
  481. for(int i=0; i<co->codes.size(); i++){
  482. const Bytecode& byte = co->codes[i];
  483. if(byte.op == OP_NO_OP) continue;
  484. Str line = std::to_string(byte.line);
  485. if(byte.line == prev_line) line = "";
  486. else{
  487. if(prev_line != -1) ss << "\n";
  488. prev_line = byte.line;
  489. }
  490. std::string pointer;
  491. if(std::find(jumpTargets.begin(), jumpTargets.end(), i) != jumpTargets.end()){
  492. pointer = "-> ";
  493. }else{
  494. pointer = " ";
  495. }
  496. ss << pad(line, 8) << pointer << pad(std::to_string(i), 3);
  497. ss << " " << pad(OP_NAMES[byte.op], 20) << " ";
  498. // ss << pad(byte.arg == -1 ? "" : std::to_string(byte.arg), 5);
  499. std::string argStr = byte.arg == -1 ? "" : std::to_string(byte.arg);
  500. if(byte.op == OP_LOAD_CONST){
  501. argStr += " (" + CAST(Str, asRepr(co->consts[byte.arg])) + ")";
  502. }
  503. if(byte.op == OP_LOAD_NAME_REF || byte.op == OP_LOAD_NAME || byte.op == OP_RAISE || byte.op == OP_STORE_NAME){
  504. argStr += " (" + co->names[byte.arg].first.str().escape(true) + ")";
  505. }
  506. if(byte.op == OP_FAST_INDEX || byte.op == OP_FAST_INDEX_REF){
  507. auto& a = co->names[byte.arg & 0xFFFF];
  508. auto& x = co->names[(byte.arg >> 16) & 0xFFFF];
  509. argStr += " (" + a.first.str() + '[' + x.first.str() + "])";
  510. }
  511. ss << pad(argStr, 20); // may overflow
  512. ss << co->blocks[byte.block].to_string();
  513. if(i != co->codes.size() - 1) ss << '\n';
  514. }
  515. StrStream consts;
  516. consts << "co_consts: ";
  517. consts << CAST(Str, asRepr(VAR(co->consts)));
  518. StrStream names;
  519. names << "co_names: ";
  520. List list;
  521. for(int i=0; i<co->names.size(); i++){
  522. list.push_back(VAR(co->names[i].first.str()));
  523. }
  524. names << CAST(Str, asRepr(VAR(list)));
  525. ss << '\n' << consts.str() << '\n' << names.str() << '\n';
  526. for(int i=0; i<co->consts.size(); i++){
  527. PyVar obj = co->consts[i];
  528. if(is_type(obj, tp_function)){
  529. const auto& f = CAST(Function&, obj);
  530. ss << disassemble(f.code);
  531. }
  532. }
  533. return Str(ss.str());
  534. }
  535. void VM::init_builtin_types(){
  536. PyVar _tp_object = make_sp<PyObject, Py_<Type>>(1, 0);
  537. PyVar _tp_type = make_sp<PyObject, Py_<Type>>(1, 1);
  538. _all_types.push_back(_tp_object);
  539. _all_types.push_back(_tp_type);
  540. tp_object = 0; tp_type = 1;
  541. _types.set("object", _tp_object);
  542. _types.set("type", _tp_type);
  543. tp_int = _new_type_object("int");
  544. tp_float = _new_type_object("float");
  545. if(tp_int.index != kTpIntIndex || tp_float.index != kTpFloatIndex) UNREACHABLE();
  546. tp_bool = _new_type_object("bool");
  547. tp_str = _new_type_object("str");
  548. tp_list = _new_type_object("list");
  549. tp_tuple = _new_type_object("tuple");
  550. tp_slice = _new_type_object("slice");
  551. tp_range = _new_type_object("range");
  552. tp_module = _new_type_object("module");
  553. tp_ref = _new_type_object("_ref");
  554. tp_star_wrapper = _new_type_object("_star_wrapper");
  555. tp_function = _new_type_object("function");
  556. tp_native_function = _new_type_object("native_function");
  557. tp_native_iterator = _new_type_object("native_iterator");
  558. tp_bound_method = _new_type_object("bound_method");
  559. tp_super = _new_type_object("super");
  560. tp_exception = _new_type_object("Exception");
  561. this->None = new_object(_new_type_object("NoneType"), DUMMY_VAL);
  562. this->Ellipsis = new_object(_new_type_object("ellipsis"), DUMMY_VAL);
  563. this->True = new_object(tp_bool, true);
  564. this->False = new_object(tp_bool, false);
  565. this->builtins = new_module("builtins");
  566. this->_main = new_module("__main__");
  567. this->_py_op_call = new_object(_new_type_object("_py_op_call"), DUMMY_VAL);
  568. this->_py_op_yield = new_object(_new_type_object("_py_op_yield"), DUMMY_VAL);
  569. setattr(_t(tp_type), __base__, _t(tp_object));
  570. setattr(_t(tp_object), __base__, None);
  571. for(auto [k, v]: _types.items()){
  572. setattr(v, __name__, VAR(k.str()));
  573. }
  574. std::vector<Str> pb_types = {"type", "object", "bool", "int", "float", "str", "list", "tuple", "range"};
  575. for (auto& name : pb_types) {
  576. setattr(builtins, name, _types[name]);
  577. }
  578. post_init();
  579. for(auto [k, v]: _types.items()) v->attr()._try_perfect_rehash();
  580. for(auto [k, v]: _modules.items()) v->attr()._try_perfect_rehash();
  581. }
  582. PyVar VM::call(const PyVar& _callable, Args args, const Args& kwargs, bool opCall){
  583. if(is_type(_callable, tp_type)){
  584. PyVar* new_f = _callable->attr().try_get(__new__);
  585. PyVar obj;
  586. if(new_f != nullptr){
  587. obj = call(*new_f, std::move(args), kwargs, false);
  588. }else{
  589. obj = new_object(_callable, DummyInstance());
  590. PyVarOrNull init_f = getattr(obj, __init__, false, true);
  591. if (init_f != nullptr) call(init_f, std::move(args), kwargs, false);
  592. }
  593. return obj;
  594. }
  595. const PyVar* callable = &_callable;
  596. if(is_type(*callable, tp_bound_method)){
  597. auto& bm = CAST(BoundMethod&, *callable);
  598. callable = &bm.method; // get unbound method
  599. args.extend_self(bm.obj);
  600. }
  601. if(is_type(*callable, tp_native_function)){
  602. const auto& f = OBJ_GET(NativeFunc, *callable);
  603. if(kwargs.size() != 0) TypeError("native_function does not accept keyword arguments");
  604. return f(this, args);
  605. } else if(is_type(*callable, tp_function)){
  606. const Function& fn = CAST(Function&, *callable);
  607. NameDict_ locals = make_sp<NameDict>(
  608. fn.code->perfect_locals_capacity,
  609. kLocalsLoadFactor,
  610. fn.code->perfect_hash_seed
  611. );
  612. int i = 0;
  613. for(StrName name : fn.args){
  614. if(i < args.size()){
  615. locals->set(name, std::move(args[i++]));
  616. continue;
  617. }
  618. TypeError("missing positional argument " + name.str().escape(true));
  619. }
  620. locals->update(fn.kwargs);
  621. if(!fn.starred_arg.empty()){
  622. List vargs; // handle *args
  623. while(i < args.size()) vargs.push_back(std::move(args[i++]));
  624. locals->set(fn.starred_arg, VAR(Tuple::from_list(std::move(vargs))));
  625. }else{
  626. for(StrName key : fn.kwargs_order){
  627. if(i < args.size()){
  628. locals->set(key, std::move(args[i++]));
  629. }else{
  630. break;
  631. }
  632. }
  633. if(i < args.size()) TypeError("too many arguments");
  634. }
  635. for(int i=0; i<kwargs.size(); i+=2){
  636. const Str& key = CAST(Str&, kwargs[i]);
  637. if(!fn.kwargs.contains(key)){
  638. TypeError(key.escape(true) + " is an invalid keyword argument for " + fn.name.str() + "()");
  639. }
  640. locals->set(key, kwargs[i+1]);
  641. }
  642. const PyVar& _module = fn._module != nullptr ? fn._module : top_frame()->_module;
  643. auto _frame = _new_frame(fn.code, _module, locals, fn._closure);
  644. if(fn.code->is_generator) return PyIter(Generator(this, std::move(_frame)));
  645. callstack.push(std::move(_frame));
  646. if(opCall) return _py_op_call;
  647. return _exec();
  648. }
  649. PyVarOrNull call_f = getattr(_callable, __call__, false, true);
  650. if(call_f != nullptr){
  651. return call(call_f, std::move(args), kwargs, false);
  652. }
  653. TypeError(OBJ_NAME(_t(*callable)).escape(true) + " object is not callable");
  654. return None;
  655. }
  656. void VM::unpack_args(Args& args){
  657. List unpacked;
  658. for(int i=0; i<args.size(); i++){
  659. if(is_type(args[i], tp_star_wrapper)){
  660. auto& star = _CAST(StarWrapper&, args[i]);
  661. if(!star.rvalue) UNREACHABLE();
  662. PyVar list = asList(star.obj);
  663. List& list_c = CAST(List&, list);
  664. unpacked.insert(unpacked.end(), list_c.begin(), list_c.end());
  665. }else{
  666. unpacked.push_back(args[i]);
  667. }
  668. }
  669. args = Args::from_list(std::move(unpacked));
  670. }
  671. PyVarOrNull VM::getattr(const PyVar& obj, StrName name, bool throw_err, bool class_only) {
  672. PyVar* val;
  673. PyObject* cls;
  674. if(is_type(obj, tp_super)){
  675. const PyVar* root = &obj;
  676. int depth = 1;
  677. while(true){
  678. root = &OBJ_GET(PyVar, *root);
  679. if(!is_type(*root, tp_super)) break;
  680. depth++;
  681. }
  682. cls = _t(*root).get();
  683. for(int i=0; i<depth; i++) cls = cls->attr(__base__).get();
  684. if(!class_only){
  685. val = (*root)->attr().try_get(name);
  686. if(val != nullptr) return *val;
  687. }
  688. }else{
  689. if(!class_only && !obj.is_tagged() && obj->is_attr_valid()){
  690. val = obj->attr().try_get(name);
  691. if(val != nullptr) return *val;
  692. }
  693. cls = _t(obj).get();
  694. }
  695. while(cls != None.get()) {
  696. val = cls->attr().try_get(name);
  697. if(val != nullptr){
  698. PyVarOrNull descriptor = getattr(*val, __get__, false, true);
  699. if(descriptor != nullptr) return call(descriptor, one_arg(obj));
  700. if(is_type(*val, tp_function) || is_type(*val, tp_native_function)){
  701. return VAR(BoundMethod(obj, *val));
  702. }else{
  703. return *val;
  704. }
  705. }else{
  706. // this operation is expensive!!!
  707. const Str& s = name.str();
  708. if(s.empty() || s[0] != '_'){
  709. PyVar* interceptor = cls->attr().try_get(__getattr__);
  710. if(interceptor != nullptr){
  711. return call(*interceptor, two_args(obj, VAR(s)));
  712. }
  713. }
  714. }
  715. cls = cls->attr(__base__).get();
  716. }
  717. if(throw_err) AttributeError(obj, name);
  718. return nullptr;
  719. }
  720. template<typename T>
  721. void VM::setattr(PyVar& obj, StrName name, T&& value) {
  722. if(obj.is_tagged()) TypeError("cannot set attribute");
  723. PyObject* p = obj.get();
  724. while(p->type == tp_super) p = static_cast<PyVar*>(p->value())->get();
  725. if(!p->is_attr_valid()) TypeError("cannot set attribute");
  726. p->attr().set(name, std::forward<T>(value));
  727. }
  728. template<int ARGC>
  729. void VM::bind_method(PyVar obj, Str funcName, NativeFuncRaw fn) {
  730. check_type(obj, tp_type);
  731. setattr(obj, funcName, VAR(NativeFunc(fn, ARGC, true)));
  732. }
  733. template<int ARGC>
  734. void VM::bind_func(PyVar obj, Str funcName, NativeFuncRaw fn) {
  735. setattr(obj, funcName, VAR(NativeFunc(fn, ARGC, false)));
  736. }
  737. void VM::_error(Exception e){
  738. if(callstack.empty()){
  739. e.is_re = false;
  740. throw e;
  741. }
  742. top_frame()->push(VAR(e));
  743. _raise();
  744. }
  745. PyVar VM::_exec(){
  746. Frame* frame = top_frame();
  747. i64 base_id = frame->id;
  748. PyVar ret = nullptr;
  749. bool need_raise = false;
  750. while(true){
  751. if(frame->id < base_id) UNREACHABLE();
  752. try{
  753. if(need_raise){ need_raise = false; _raise(); }
  754. ret = run_frame(frame);
  755. if(ret == _py_op_yield) return _py_op_yield;
  756. if(ret != _py_op_call){
  757. if(frame->id == base_id){ // [ frameBase<- ]
  758. callstack.pop();
  759. return ret;
  760. }else{
  761. callstack.pop();
  762. frame = callstack.top().get();
  763. frame->push(ret);
  764. }
  765. }else{
  766. frame = callstack.top().get(); // [ frameBase, newFrame<- ]
  767. }
  768. }catch(HandledException& e){
  769. continue;
  770. }catch(UnhandledException& e){
  771. PyVar obj = frame->pop();
  772. Exception& _e = CAST(Exception&, obj);
  773. _e.st_push(frame->snapshot());
  774. callstack.pop();
  775. if(callstack.empty()) throw _e;
  776. frame = callstack.top().get();
  777. frame->push(obj);
  778. if(frame->id < base_id) throw ToBeRaisedException();
  779. need_raise = true;
  780. }catch(ToBeRaisedException& e){
  781. need_raise = true;
  782. }
  783. }
  784. }
  785. } // namespace pkpy