vm.h 32 KB

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