vm.h 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  1. #pragma once
  2. #include "codeobject.h"
  3. #include "common.h"
  4. #include "frame.h"
  5. #include "error.h"
  6. #include "gc.h"
  7. #include "memory.h"
  8. #include "obj.h"
  9. #include "str.h"
  10. #include "tuplelist.h"
  11. namespace pkpy{
  12. /* Stack manipulation macros */
  13. // https://github.com/python/cpython/blob/3.9/Python/ceval.c#L1123
  14. #define TOP() (s_data.top())
  15. #define SECOND() (s_data.second())
  16. #define THIRD() (s_data.third())
  17. #define PEEK(n) (s_data.peek(n))
  18. #define STACK_SHRINK(n) (s_data.shrink(n))
  19. #define PUSH(v) (s_data.push(v))
  20. #define POP() (s_data.pop())
  21. #define POPX() (s_data.popx())
  22. #define STACK_VIEW(n) (s_data.view(n))
  23. Str _read_file_cwd(const Str& name, bool* ok);
  24. #define DEF_NATIVE_2(ctype, ptype) \
  25. template<> inline ctype py_cast<ctype>(VM* vm, PyObject* obj) { \
  26. vm->check_type(obj, vm->ptype); \
  27. return OBJ_GET(ctype, obj); \
  28. } \
  29. template<> inline ctype _py_cast<ctype>(VM* vm, PyObject* obj) { \
  30. return OBJ_GET(ctype, obj); \
  31. } \
  32. template<> inline ctype& py_cast<ctype&>(VM* vm, PyObject* obj) { \
  33. vm->check_type(obj, vm->ptype); \
  34. return OBJ_GET(ctype, obj); \
  35. } \
  36. template<> inline ctype& _py_cast<ctype&>(VM* vm, PyObject* obj) { \
  37. return OBJ_GET(ctype, obj); \
  38. } \
  39. inline PyObject* py_var(VM* vm, const ctype& value) { return vm->heap.gcnew(vm->ptype, value);} \
  40. inline PyObject* py_var(VM* vm, ctype&& value) { return vm->heap.gcnew(vm->ptype, std::move(value));}
  41. class Generator final: public BaseIter {
  42. Frame frame;
  43. int state; // 0,1,2
  44. List s_backup;
  45. public:
  46. Generator(VM* vm, Frame&& frame, ArgsView buffer): BaseIter(vm), frame(std::move(frame)), state(0) {
  47. for(PyObject* obj: buffer) s_backup.push_back(obj);
  48. }
  49. PyObject* next() override;
  50. void _gc_mark() const override;
  51. };
  52. struct PyTypeInfo{
  53. PyObject* obj;
  54. Type base;
  55. Str name;
  56. };
  57. struct FrameId{
  58. std::vector<pkpy::Frame>* data;
  59. int index;
  60. FrameId(std::vector<pkpy::Frame>* data, int index) : data(data), index(index) {}
  61. Frame* operator->() const { return &data->operator[](index); }
  62. };
  63. class VM {
  64. VM* vm; // self reference for simplify code
  65. public:
  66. ManagedHeap heap;
  67. ValueStack s_data;
  68. stack< Frame > callstack;
  69. std::vector<PyTypeInfo> _all_types;
  70. NameDict _modules; // loaded modules
  71. std::map<StrName, Str> _lazy_modules; // lazy loaded modules
  72. PyObject* None;
  73. PyObject* True;
  74. PyObject* False;
  75. PyObject* Ellipsis;
  76. PyObject* builtins; // builtins module
  77. PyObject* StopIteration;
  78. PyObject* _main; // __main__ module
  79. std::stringstream _stdout_buffer;
  80. std::stringstream _stderr_buffer;
  81. std::ostream* _stdout;
  82. std::ostream* _stderr;
  83. bool _initialized;
  84. // for quick access
  85. Type tp_object, tp_type, tp_int, tp_float, tp_bool, tp_str;
  86. Type tp_list, tp_tuple;
  87. Type tp_function, tp_native_func, tp_iterator, tp_bound_method;
  88. Type tp_slice, tp_range, tp_module;
  89. Type tp_super, tp_exception;
  90. VM(bool use_stdio) : heap(this){
  91. this->vm = this;
  92. this->_stdout = use_stdio ? &std::cout : &_stdout_buffer;
  93. this->_stderr = use_stdio ? &std::cerr : &_stderr_buffer;
  94. callstack.reserve(8);
  95. _initialized = false;
  96. init_builtin_types();
  97. _initialized = true;
  98. }
  99. bool is_stdio_used() const { return _stdout == &std::cout; }
  100. FrameId top_frame() {
  101. #if DEBUG_EXTRA_CHECK
  102. if(callstack.empty()) FATAL_ERROR();
  103. #endif
  104. return FrameId(&callstack.data(), callstack.size()-1);
  105. }
  106. PyObject* asStr(PyObject* obj){
  107. PyObject* self;
  108. PyObject* f = get_unbound_method(obj, __str__, &self, false);
  109. if(self != PY_NULL) return call_method(self, f);
  110. return asRepr(obj);
  111. }
  112. PyObject* asIter(PyObject* obj){
  113. if(is_type(obj, tp_iterator)) return obj;
  114. PyObject* self;
  115. PyObject* iter_f = get_unbound_method(obj, __iter__, &self, false);
  116. if(self != PY_NULL) return call_method(self, iter_f);
  117. TypeError(OBJ_NAME(_t(obj)).escape() + " object is not iterable");
  118. return nullptr;
  119. }
  120. PyObject* asList(PyObject* it){
  121. if(is_non_tagged_type(it, tp_list)) return it;
  122. return call(_t(tp_list), it);
  123. }
  124. PyObject* find_name_in_mro(PyObject* cls, StrName name){
  125. PyObject* val;
  126. do{
  127. val = cls->attr().try_get(name);
  128. if(val != nullptr) return val;
  129. Type cls_t = OBJ_GET(Type, cls);
  130. Type base = _all_types[cls_t].base;
  131. if(base.index == -1) break;
  132. cls = _all_types[base].obj;
  133. }while(true);
  134. return nullptr;
  135. }
  136. bool isinstance(PyObject* obj, Type cls_t){
  137. Type obj_t = OBJ_GET(Type, _t(obj));
  138. do{
  139. if(obj_t == cls_t) return true;
  140. Type base = _all_types[obj_t].base;
  141. if(base.index == -1) break;
  142. obj_t = base;
  143. }while(true);
  144. return false;
  145. }
  146. PyObject* exec(Str source, Str filename, CompileMode mode, PyObject* _module=nullptr){
  147. if(_module == nullptr) _module = _main;
  148. try {
  149. CodeObject_ code = compile(source, filename, mode);
  150. #if DEBUG_DIS_EXEC
  151. if(_module == _main) std::cout << disassemble(code) << '\n';
  152. #endif
  153. return _exec(code, _module);
  154. }catch (const Exception& e){
  155. *_stderr << e.summary() << '\n';
  156. }
  157. #if !DEBUG_FULL_EXCEPTION
  158. catch (const std::exception& e) {
  159. *_stderr << "An std::exception occurred! It could be a bug.\n";
  160. *_stderr << e.what() << '\n';
  161. }
  162. #endif
  163. callstack.clear();
  164. s_data.clear();
  165. return nullptr;
  166. }
  167. template<typename ...Args>
  168. PyObject* _exec(Args&&... args){
  169. callstack.emplace(&s_data, s_data._sp, std::forward<Args>(args)...);
  170. return _run_top_frame();
  171. }
  172. void _pop_frame(){
  173. Frame* frame = &callstack.top();
  174. s_data.reset(frame->_sp_base);
  175. callstack.pop();
  176. }
  177. void _push_varargs(){ }
  178. void _push_varargs(PyObject* _0){ PUSH(_0); }
  179. void _push_varargs(PyObject* _0, PyObject* _1){ PUSH(_0); PUSH(_1); }
  180. void _push_varargs(PyObject* _0, PyObject* _1, PyObject* _2){ PUSH(_0); PUSH(_1); PUSH(_2); }
  181. void _push_varargs(PyObject* _0, PyObject* _1, PyObject* _2, PyObject* _3){ PUSH(_0); PUSH(_1); PUSH(_2); PUSH(_3); }
  182. template<typename... Args>
  183. PyObject* call(PyObject* callable, Args&&... args){
  184. PUSH(callable);
  185. PUSH(PY_NULL);
  186. _push_varargs(args...);
  187. return vectorcall(sizeof...(args));
  188. }
  189. template<typename... Args>
  190. PyObject* call_method(PyObject* self, PyObject* callable, Args&&... args){
  191. PUSH(callable);
  192. PUSH(self);
  193. _push_varargs(args...);
  194. return vectorcall(sizeof...(args));
  195. }
  196. template<typename... Args>
  197. PyObject* call_method(PyObject* self, StrName name, Args&&... args){
  198. PyObject* callable = get_unbound_method(self, name, &self);
  199. return call_method(self, callable, args...);
  200. }
  201. PyObject* property(NativeFuncC fget, NativeFuncC fset=nullptr){
  202. PyObject* p = builtins->attr("property");
  203. PyObject* _0 = heap.gcnew(tp_native_func, NativeFunc(fget, 1, false));
  204. PyObject* _1 = vm->None;
  205. if(fset != nullptr) _1 = heap.gcnew(tp_native_func, NativeFunc(fset, 2, false));
  206. return call(p, _0, _1);
  207. }
  208. PyObject* new_type_object(PyObject* mod, StrName name, Type base){
  209. PyObject* obj = heap._new<Type>(tp_type, _all_types.size());
  210. PyTypeInfo info{
  211. obj,
  212. base,
  213. (mod!=nullptr && mod!=builtins) ? Str(OBJ_NAME(mod)+"."+name.sv()): name.sv()
  214. };
  215. if(mod != nullptr) mod->attr().set(name, obj);
  216. _all_types.push_back(info);
  217. return obj;
  218. }
  219. Type _new_type_object(StrName name, Type base=0) {
  220. PyObject* obj = new_type_object(nullptr, name, base);
  221. return OBJ_GET(Type, obj);
  222. }
  223. PyObject* _find_type(const Str& type){
  224. PyObject* obj = builtins->attr().try_get(type);
  225. if(obj == nullptr){
  226. for(auto& t: _all_types) if(t.name == type) return t.obj;
  227. throw std::runtime_error(fmt("type not found: ", type));
  228. }
  229. return obj;
  230. }
  231. template<int ARGC>
  232. void bind_func(Str type, Str name, NativeFuncC fn) {
  233. bind_func<ARGC>(_find_type(type), name, fn);
  234. }
  235. template<int ARGC>
  236. void bind_method(Str type, Str name, NativeFuncC fn) {
  237. bind_method<ARGC>(_find_type(type), name, fn);
  238. }
  239. template<int ARGC, typename... Args>
  240. void bind_static_method(Args&&... args) {
  241. bind_func<ARGC>(std::forward<Args>(args)...);
  242. }
  243. template<int ARGC>
  244. void _bind_methods(std::vector<Str> types, Str name, NativeFuncC fn) {
  245. for(auto& type: types) bind_method<ARGC>(type, name, fn);
  246. }
  247. template<int ARGC>
  248. void bind_builtin_func(Str name, NativeFuncC fn) {
  249. bind_func<ARGC>(builtins, name, fn);
  250. }
  251. int normalized_index(int index, int size){
  252. if(index < 0) index += size;
  253. if(index < 0 || index >= size){
  254. IndexError(std::to_string(index) + " not in [0, " + std::to_string(size) + ")");
  255. }
  256. return index;
  257. }
  258. template<typename P>
  259. PyObject* PyIter(P&& value) {
  260. static_assert(std::is_base_of_v<BaseIter, std::decay_t<P>>);
  261. return heap.gcnew<P>(tp_iterator, std::forward<P>(value));
  262. }
  263. BaseIter* PyIter_AS_C(PyObject* obj)
  264. {
  265. check_type(obj, tp_iterator);
  266. return static_cast<BaseIter*>(obj->value());
  267. }
  268. BaseIter* _PyIter_AS_C(PyObject* obj)
  269. {
  270. return static_cast<BaseIter*>(obj->value());
  271. }
  272. /***** Error Reporter *****/
  273. void _error(StrName name, const Str& msg){
  274. _error(Exception(name, msg));
  275. }
  276. void _raise(){
  277. bool ok = top_frame()->jump_to_exception_handler();
  278. if(ok) throw HandledException();
  279. else throw UnhandledException();
  280. }
  281. void StackOverflowError() { _error("StackOverflowError", ""); }
  282. void IOError(const Str& msg) { _error("IOError", msg); }
  283. void NotImplementedError(){ _error("NotImplementedError", ""); }
  284. void TypeError(const Str& msg){ _error("TypeError", msg); }
  285. void ZeroDivisionError(){ _error("ZeroDivisionError", "division by zero"); }
  286. void IndexError(const Str& msg){ _error("IndexError", msg); }
  287. void ValueError(const Str& msg){ _error("ValueError", msg); }
  288. void NameError(StrName name){ _error("NameError", fmt("name ", name.escape() + " is not defined")); }
  289. void AttributeError(PyObject* obj, StrName name){
  290. // OBJ_NAME calls getattr, which may lead to a infinite recursion
  291. _error("AttributeError", fmt("type ", OBJ_NAME(_t(obj)).escape(), " has no attribute ", name.escape()));
  292. }
  293. void AttributeError(Str msg){ _error("AttributeError", msg); }
  294. void check_type(PyObject* obj, Type type){
  295. if(is_type(obj, type)) return;
  296. TypeError("expected " + OBJ_NAME(_t(type)).escape() + ", but got " + OBJ_NAME(_t(obj)).escape());
  297. }
  298. PyObject* _t(Type t){
  299. return _all_types[t.index].obj;
  300. }
  301. PyObject* _t(PyObject* obj){
  302. if(is_int(obj)) return _t(tp_int);
  303. if(is_float(obj)) return _t(tp_float);
  304. return _all_types[OBJ_GET(Type, _t(obj->type)).index].obj;
  305. }
  306. ~VM() {
  307. callstack.clear();
  308. s_data.clear();
  309. _all_types.clear();
  310. _modules.clear();
  311. _lazy_modules.clear();
  312. }
  313. void _log_s_data(const char* title = nullptr);
  314. PyObject* vectorcall(int ARGC, int KWARGC=0, bool op_call=false);
  315. CodeObject_ compile(Str source, Str filename, CompileMode mode, bool unknown_global_scope=false);
  316. PyObject* num_negated(PyObject* obj);
  317. f64 num_to_float(PyObject* obj);
  318. bool asBool(PyObject* obj);
  319. i64 hash(PyObject* obj);
  320. PyObject* asRepr(PyObject* obj);
  321. PyObject* new_module(StrName name);
  322. Str disassemble(CodeObject_ co);
  323. void init_builtin_types();
  324. PyObject* _py_call(PyObject** sp_base, PyObject* callable, ArgsView args, ArgsView kwargs);
  325. PyObject* getattr(PyObject* obj, StrName name, bool throw_err=true);
  326. PyObject* get_unbound_method(PyObject* obj, StrName name, PyObject** self, bool throw_err=true, bool fallback=false);
  327. void setattr(PyObject* obj, StrName name, PyObject* value);
  328. template<int ARGC>
  329. void bind_method(PyObject*, Str, NativeFuncC);
  330. template<int ARGC>
  331. void bind_func(PyObject*, Str, NativeFuncC);
  332. void _error(Exception);
  333. PyObject* _run_top_frame();
  334. void post_init();
  335. };
  336. inline PyObject* NativeFunc::operator()(VM* vm, ArgsView args) const{
  337. int args_size = args.size() - (int)method; // remove self
  338. if(argc != -1 && args_size != argc) {
  339. vm->TypeError(fmt("expected ", argc, " arguments, but got ", args_size));
  340. }
  341. return f(vm, args);
  342. }
  343. inline void CodeObject::optimize(VM* vm){
  344. // uint32_t base_n = (uint32_t)(names.size() / kLocalsLoadFactor + 0.5);
  345. // perfect_locals_capacity = std::max(find_next_capacity(base_n), NameDict::__Capacity);
  346. // perfect_hash_seed = find_perfect_hash_seed(perfect_locals_capacity, names);
  347. }
  348. DEF_NATIVE_2(Str, tp_str)
  349. DEF_NATIVE_2(List, tp_list)
  350. DEF_NATIVE_2(Tuple, tp_tuple)
  351. DEF_NATIVE_2(Function, tp_function)
  352. DEF_NATIVE_2(NativeFunc, tp_native_func)
  353. DEF_NATIVE_2(BoundMethod, tp_bound_method)
  354. DEF_NATIVE_2(Range, tp_range)
  355. DEF_NATIVE_2(Slice, tp_slice)
  356. DEF_NATIVE_2(Exception, tp_exception)
  357. #define PY_CAST_INT(T) \
  358. template<> inline T py_cast<T>(VM* vm, PyObject* obj){ \
  359. vm->check_type(obj, vm->tp_int); \
  360. return (T)(BITS(obj) >> 2); \
  361. } \
  362. template<> inline T _py_cast<T>(VM* vm, PyObject* obj){ \
  363. return (T)(BITS(obj) >> 2); \
  364. }
  365. PY_CAST_INT(char)
  366. PY_CAST_INT(short)
  367. PY_CAST_INT(int)
  368. PY_CAST_INT(long)
  369. PY_CAST_INT(long long)
  370. PY_CAST_INT(unsigned char)
  371. PY_CAST_INT(unsigned short)
  372. PY_CAST_INT(unsigned int)
  373. PY_CAST_INT(unsigned long)
  374. PY_CAST_INT(unsigned long long)
  375. template<> inline float py_cast<float>(VM* vm, PyObject* obj){
  376. vm->check_type(obj, vm->tp_float);
  377. i64 bits = BITS(obj);
  378. bits = (bits >> 2) << 2;
  379. return BitsCvt(bits)._float;
  380. }
  381. template<> inline float _py_cast<float>(VM* vm, PyObject* obj){
  382. i64 bits = BITS(obj);
  383. bits = (bits >> 2) << 2;
  384. return BitsCvt(bits)._float;
  385. }
  386. template<> inline double py_cast<double>(VM* vm, PyObject* obj){
  387. vm->check_type(obj, vm->tp_float);
  388. i64 bits = BITS(obj);
  389. bits = (bits >> 2) << 2;
  390. return BitsCvt(bits)._float;
  391. }
  392. template<> inline double _py_cast<double>(VM* vm, PyObject* obj){
  393. i64 bits = BITS(obj);
  394. bits = (bits >> 2) << 2;
  395. return BitsCvt(bits)._float;
  396. }
  397. #define PY_VAR_INT(T) \
  398. inline PyObject* py_var(VM* vm, T _val){ \
  399. i64 val = static_cast<i64>(_val); \
  400. if(((val << 2) >> 2) != val){ \
  401. vm->_error("OverflowError", std::to_string(val) + " is out of range"); \
  402. } \
  403. val = (val << 2) | 0b01; \
  404. return reinterpret_cast<PyObject*>(val); \
  405. }
  406. PY_VAR_INT(char)
  407. PY_VAR_INT(short)
  408. PY_VAR_INT(int)
  409. PY_VAR_INT(long)
  410. PY_VAR_INT(long long)
  411. PY_VAR_INT(unsigned char)
  412. PY_VAR_INT(unsigned short)
  413. PY_VAR_INT(unsigned int)
  414. PY_VAR_INT(unsigned long)
  415. PY_VAR_INT(unsigned long long)
  416. #define PY_VAR_FLOAT(T) \
  417. inline PyObject* py_var(VM* vm, T _val){ \
  418. f64 val = static_cast<f64>(_val); \
  419. i64 bits = BitsCvt(val)._int; \
  420. bits = (bits >> 2) << 2; \
  421. bits |= 0b10; \
  422. return reinterpret_cast<PyObject*>(bits); \
  423. }
  424. PY_VAR_FLOAT(float)
  425. PY_VAR_FLOAT(double)
  426. inline PyObject* py_var(VM* vm, bool val){
  427. return val ? vm->True : vm->False;
  428. }
  429. template<> inline bool py_cast<bool>(VM* vm, PyObject* obj){
  430. vm->check_type(obj, vm->tp_bool);
  431. return obj == vm->True;
  432. }
  433. template<> inline bool _py_cast<bool>(VM* vm, PyObject* obj){
  434. return obj == vm->True;
  435. }
  436. inline PyObject* py_var(VM* vm, const char val[]){
  437. return VAR(Str(val));
  438. }
  439. inline PyObject* py_var(VM* vm, std::string val){
  440. return VAR(Str(std::move(val)));
  441. }
  442. inline PyObject* py_var(VM* vm, std::string_view val){
  443. return VAR(Str(val));
  444. }
  445. template<typename T>
  446. void _check_py_class(VM* vm, PyObject* obj){
  447. vm->check_type(obj, T::_type(vm));
  448. }
  449. inline PyObject* VM::num_negated(PyObject* obj){
  450. if (is_int(obj)){
  451. return VAR(-CAST(i64, obj));
  452. }else if(is_float(obj)){
  453. return VAR(-CAST(f64, obj));
  454. }
  455. TypeError("expected 'int' or 'float', got " + OBJ_NAME(_t(obj)).escape());
  456. return nullptr;
  457. }
  458. inline f64 VM::num_to_float(PyObject* obj){
  459. if(is_float(obj)){
  460. return CAST(f64, obj);
  461. } else if (is_int(obj)){
  462. return (f64)CAST(i64, obj);
  463. }
  464. TypeError("expected 'int' or 'float', got " + OBJ_NAME(_t(obj)).escape());
  465. return 0;
  466. }
  467. inline bool VM::asBool(PyObject* obj){
  468. if(is_non_tagged_type(obj, tp_bool)) return obj == True;
  469. if(obj == None) return false;
  470. if(is_int(obj)) return CAST(i64, obj) != 0;
  471. if(is_float(obj)) return CAST(f64, obj) != 0.0;
  472. PyObject* self;
  473. PyObject* len_f = get_unbound_method(obj, __len__, &self, false);
  474. if(self != PY_NULL){
  475. PyObject* ret = call_method(self, len_f);
  476. return CAST(i64, ret) > 0;
  477. }
  478. return true;
  479. }
  480. inline i64 VM::hash(PyObject* obj){
  481. if (is_non_tagged_type(obj, tp_str)) return CAST(Str&, obj).hash();
  482. if (is_int(obj)) return CAST(i64, obj);
  483. if (is_non_tagged_type(obj, tp_tuple)) {
  484. i64 x = 1000003;
  485. const Tuple& items = CAST(Tuple&, obj);
  486. for (int i=0; i<items.size(); i++) {
  487. i64 y = hash(items[i]);
  488. // recommended by Github Copilot
  489. x = x ^ (y + 0x9e3779b9 + (x << 6) + (x >> 2));
  490. }
  491. return x;
  492. }
  493. if (is_non_tagged_type(obj, tp_type)) return BITS(obj);
  494. if (is_non_tagged_type(obj, tp_iterator)) return BITS(obj);
  495. if (is_non_tagged_type(obj, tp_bool)) return _CAST(bool, obj) ? 1 : 0;
  496. if (is_float(obj)){
  497. f64 val = CAST(f64, obj);
  498. return (i64)std::hash<f64>()(val);
  499. }
  500. TypeError("unhashable type: " + OBJ_NAME(_t(obj)).escape());
  501. return 0;
  502. }
  503. inline PyObject* VM::asRepr(PyObject* obj){
  504. return call_method(obj, __repr__);
  505. }
  506. inline PyObject* VM::new_module(StrName name) {
  507. PyObject* obj = heap._new<DummyModule>(tp_module, DummyModule());
  508. obj->attr().set(__name__, VAR(name.sv()));
  509. // we do not allow override in order to avoid memory leak
  510. // it is because Module objects are not garbage collected
  511. if(_modules.contains(name)) FATAL_ERROR();
  512. _modules.set(name, obj);
  513. return obj;
  514. }
  515. inline std::string _opcode_argstr(VM* vm, Bytecode byte, const CodeObject* co){
  516. std::string argStr = byte.arg == -1 ? "" : std::to_string(byte.arg);
  517. switch(byte.op){
  518. case OP_LOAD_CONST:
  519. if(vm != nullptr){
  520. argStr += fmt(" (", CAST(Str, vm->asRepr(co->consts[byte.arg])), ")");
  521. }
  522. break;
  523. case OP_LOAD_NAME: case OP_LOAD_GLOBAL: case OP_LOAD_NONLOCAL: case OP_STORE_GLOBAL:
  524. case OP_LOAD_ATTR: case OP_LOAD_METHOD: case OP_STORE_ATTR: case OP_DELETE_ATTR:
  525. case OP_IMPORT_NAME: case OP_BEGIN_CLASS:
  526. case OP_DELETE_GLOBAL:
  527. argStr += fmt(" (", StrName(byte.arg).sv(), ")");
  528. break;
  529. case OP_LOAD_FAST: case OP_STORE_FAST: case OP_DELETE_FAST:
  530. argStr += fmt(" (", co->varnames[byte.arg].sv(), ")");
  531. break;
  532. case OP_BINARY_OP:
  533. argStr += fmt(" (", BINARY_SPECIAL_METHODS[byte.arg], ")");
  534. break;
  535. case OP_LOAD_FUNCTION:
  536. argStr += fmt(" (", co->func_decls[byte.arg]->code->name, ")");
  537. break;
  538. }
  539. return argStr;
  540. }
  541. inline Str VM::disassemble(CodeObject_ co){
  542. auto pad = [](const Str& s, const int n){
  543. if(s.length() >= n) return s.substr(0, n);
  544. return s + std::string(n - s.length(), ' ');
  545. };
  546. std::vector<int> jumpTargets;
  547. for(auto byte : co->codes){
  548. if(byte.op == OP_JUMP_ABSOLUTE || byte.op == OP_POP_JUMP_IF_FALSE){
  549. jumpTargets.push_back(byte.arg);
  550. }
  551. }
  552. std::stringstream ss;
  553. int prev_line = -1;
  554. for(int i=0; i<co->codes.size(); i++){
  555. const Bytecode& byte = co->codes[i];
  556. Str line = std::to_string(co->lines[i]);
  557. if(co->lines[i] == prev_line) line = "";
  558. else{
  559. if(prev_line != -1) ss << "\n";
  560. prev_line = co->lines[i];
  561. }
  562. std::string pointer;
  563. if(std::find(jumpTargets.begin(), jumpTargets.end(), i) != jumpTargets.end()){
  564. pointer = "-> ";
  565. }else{
  566. pointer = " ";
  567. }
  568. ss << pad(line, 8) << pointer << pad(std::to_string(i), 3);
  569. ss << " " << pad(OP_NAMES[byte.op], 20) << " ";
  570. // ss << pad(byte.arg == -1 ? "" : std::to_string(byte.arg), 5);
  571. std::string argStr = _opcode_argstr(this, byte, co.get());
  572. ss << pad(argStr, 40); // may overflow
  573. ss << co->blocks[byte.block].type;
  574. if(i != co->codes.size() - 1) ss << '\n';
  575. }
  576. for(auto& decl: co->func_decls){
  577. ss << "\n\n" << "Disassembly of " << decl->code->name << ":\n";
  578. ss << disassemble(decl->code);
  579. }
  580. ss << "\n";
  581. return Str(ss.str());
  582. }
  583. inline void VM::_log_s_data(const char* title) {
  584. if(!_initialized) return;
  585. if(callstack.empty()) return;
  586. std::stringstream ss;
  587. if(title) ss << title << " | ";
  588. std::map<PyObject**, int> sp_bases;
  589. for(Frame& f: callstack.data()){
  590. if(f._sp_base == nullptr) FATAL_ERROR();
  591. sp_bases[f._sp_base] += 1;
  592. }
  593. FrameId frame = top_frame();
  594. int line = frame->co->lines[frame->_ip];
  595. ss << frame->co->name << ":" << line << " [";
  596. for(PyObject** p=s_data.begin(); p!=s_data.end(); p++){
  597. ss << std::string(sp_bases[p], '|');
  598. if(sp_bases[p] > 0) ss << " ";
  599. PyObject* obj = *p;
  600. if(obj == nullptr) ss << "(nil)";
  601. else if(obj == PY_BEGIN_CALL) ss << "BEGIN_CALL";
  602. else if(obj == PY_NULL) ss << "NULL";
  603. else if(is_int(obj)) ss << CAST(i64, obj);
  604. else if(is_float(obj)) ss << CAST(f64, obj);
  605. else if(is_type(obj, tp_str)) ss << CAST(Str, obj).escape();
  606. else if(obj == None) ss << "None";
  607. else if(obj == True) ss << "True";
  608. else if(obj == False) ss << "False";
  609. else if(is_type(obj, tp_function)){
  610. auto& f = CAST(Function&, obj);
  611. ss << f.decl->code->name << "(...)";
  612. } else if(is_type(obj, tp_type)){
  613. Type t = OBJ_GET(Type, obj);
  614. ss << "<class " + _all_types[t].name.escape() + ">";
  615. } else if(is_type(obj, tp_list)){
  616. auto& t = CAST(List&, obj);
  617. ss << "list(size=" << t.size() << ")";
  618. } else if(is_type(obj, tp_tuple)){
  619. auto& t = CAST(Tuple&, obj);
  620. ss << "tuple(size=" << t.size() << ")";
  621. } else ss << "(" << obj_type_name(this, obj->type) << ")";
  622. ss << ", ";
  623. }
  624. std::string output = ss.str();
  625. if(!s_data.empty()) {
  626. output.pop_back(); output.pop_back();
  627. }
  628. output.push_back(']');
  629. Bytecode byte = frame->co->codes[frame->_ip];
  630. std::cout << output << " " << OP_NAMES[byte.op] << " " << _opcode_argstr(nullptr, byte, frame->co) << std::endl;
  631. }
  632. inline void VM::init_builtin_types(){
  633. _all_types.push_back({heap._new<Type>(Type(1), Type(0)), -1, "object"});
  634. _all_types.push_back({heap._new<Type>(Type(1), Type(1)), 0, "type"});
  635. tp_object = 0; tp_type = 1;
  636. tp_int = _new_type_object("int");
  637. tp_float = _new_type_object("float");
  638. if(tp_int.index != kTpIntIndex || tp_float.index != kTpFloatIndex) FATAL_ERROR();
  639. tp_bool = _new_type_object("bool");
  640. tp_str = _new_type_object("str");
  641. tp_list = _new_type_object("list");
  642. tp_tuple = _new_type_object("tuple");
  643. tp_slice = _new_type_object("slice");
  644. tp_range = _new_type_object("range");
  645. tp_module = _new_type_object("module");
  646. tp_function = _new_type_object("function");
  647. tp_native_func = _new_type_object("native_func");
  648. tp_iterator = _new_type_object("iterator");
  649. tp_bound_method = _new_type_object("bound_method");
  650. tp_super = _new_type_object("super");
  651. tp_exception = _new_type_object("Exception");
  652. this->None = heap._new<Dummy>(_new_type_object("NoneType"), {});
  653. this->Ellipsis = heap._new<Dummy>(_new_type_object("ellipsis"), {});
  654. this->True = heap._new<Dummy>(tp_bool, {});
  655. this->False = heap._new<Dummy>(tp_bool, {});
  656. this->StopIteration = heap._new<Dummy>(_new_type_object("StopIterationType"), {});
  657. this->builtins = new_module("builtins");
  658. this->_main = new_module("__main__");
  659. // setup public types
  660. builtins->attr().set("type", _t(tp_type));
  661. builtins->attr().set("object", _t(tp_object));
  662. builtins->attr().set("bool", _t(tp_bool));
  663. builtins->attr().set("int", _t(tp_int));
  664. builtins->attr().set("float", _t(tp_float));
  665. builtins->attr().set("str", _t(tp_str));
  666. builtins->attr().set("list", _t(tp_list));
  667. builtins->attr().set("tuple", _t(tp_tuple));
  668. builtins->attr().set("range", _t(tp_range));
  669. builtins->attr().set("StopIteration", StopIteration);
  670. post_init();
  671. for(int i=0; i<_all_types.size(); i++){
  672. _all_types[i].obj->attr()._try_perfect_rehash();
  673. }
  674. for(auto [k, v]: _modules.items()) v->attr()._try_perfect_rehash();
  675. }
  676. inline PyObject* VM::vectorcall(int ARGC, int KWARGC, bool op_call){
  677. bool is_varargs = ARGC == 0xFFFF;
  678. PyObject** p0;
  679. PyObject** p1 = s_data._sp - KWARGC*2;
  680. if(is_varargs){
  681. p0 = p1 - 1;
  682. while(*p0 != PY_BEGIN_CALL) p0--;
  683. // [BEGIN_CALL, callable, <self>, args..., kwargs...]
  684. // ^p0 ^p1 ^_sp
  685. ARGC = p1 - (p0 + 3);
  686. }else{
  687. p0 = p1 - ARGC - 2 - (int)is_varargs;
  688. // [callable, <self>, args..., kwargs...]
  689. // ^p0 ^p1 ^_sp
  690. }
  691. PyObject* callable = p1[-(ARGC + 2)];
  692. bool method_call = p1[-(ARGC + 1)] != PY_NULL;
  693. // handle boundmethod, do a patch
  694. if(is_non_tagged_type(callable, tp_bound_method)){
  695. if(method_call) FATAL_ERROR();
  696. auto& bm = CAST(BoundMethod&, callable);
  697. callable = bm.method; // get unbound method
  698. p1[-(ARGC + 2)] = bm.method;
  699. p1[-(ARGC + 1)] = bm.obj;
  700. method_call = true;
  701. // [unbound, self, args..., kwargs...]
  702. }
  703. ArgsView args(p1 - ARGC - int(method_call), p1);
  704. if(is_non_tagged_type(callable, tp_native_func)){
  705. const auto& f = OBJ_GET(NativeFunc, callable);
  706. if(KWARGC != 0) TypeError("native_func does not accept keyword arguments");
  707. PyObject* ret = f(this, args);
  708. s_data.reset(p0);
  709. return ret;
  710. }
  711. ArgsView kwargs(p1, s_data._sp);
  712. if(is_non_tagged_type(callable, tp_function)){
  713. // ret is nullptr or a generator
  714. PyObject* ret = _py_call(p0, callable, args, kwargs);
  715. // stack resetting is handled by _py_call
  716. if(ret != nullptr) return ret;
  717. if(op_call) return PY_OP_CALL;
  718. return _run_top_frame();
  719. }
  720. if(is_non_tagged_type(callable, tp_type)){
  721. if(method_call) FATAL_ERROR();
  722. // [type, NULL, args..., kwargs...]
  723. // TODO: derived __new__ ?
  724. PyObject* new_f = callable->attr().try_get(__new__);
  725. PyObject* obj;
  726. if(new_f != nullptr){
  727. PUSH(new_f);
  728. PUSH(PY_NULL);
  729. for(PyObject* obj: args) PUSH(obj);
  730. for(PyObject* obj: kwargs) PUSH(obj);
  731. obj = vectorcall(ARGC, KWARGC);
  732. if(!isinstance(obj, OBJ_GET(Type, callable))) return obj;
  733. }else{
  734. obj = heap.gcnew<DummyInstance>(OBJ_GET(Type, callable), {});
  735. }
  736. PyObject* self;
  737. callable = get_unbound_method(obj, __init__, &self, false);
  738. if (self != PY_NULL) {
  739. // replace `NULL` with `self`
  740. p1[-(ARGC + 2)] = callable;
  741. p1[-(ARGC + 1)] = self;
  742. // [init_f, self, args..., kwargs...]
  743. vectorcall(ARGC, KWARGC);
  744. // We just discard the return value of `__init__`
  745. // in cpython it raises a TypeError if the return value is not None
  746. }else{
  747. // manually reset the stack
  748. s_data.reset(p0);
  749. }
  750. return obj;
  751. }
  752. // handle `__call__` overload
  753. PyObject* self;
  754. PyObject* call_f = get_unbound_method(callable, __call__, &self, false);
  755. if(self != PY_NULL){
  756. p1[-(ARGC + 2)] = call_f;
  757. p1[-(ARGC + 1)] = self;
  758. // [call_f, self, args..., kwargs...]
  759. return vectorcall(ARGC, KWARGC, false);
  760. }
  761. TypeError(OBJ_NAME(_t(callable)).escape() + " object is not callable");
  762. return nullptr;
  763. }
  764. inline PyObject* VM::_py_call(PyObject** p0, PyObject* callable, ArgsView args, ArgsView kwargs){
  765. // callable must be a `function` object
  766. if(s_data.is_overflow()) StackOverflowError();
  767. const Function& fn = CAST(Function&, callable);
  768. const CodeObject* co = fn.decl->code.get();
  769. PyObject* _module = fn._module != nullptr ? fn._module : callstack.top()._module;
  770. if(args.size() < fn.decl->args.size()){
  771. vm->TypeError(fmt(
  772. "expected ",
  773. fn.decl->args.size(),
  774. " positional arguments, but got ",
  775. args.size(),
  776. " (", fn.decl->code->name, ')'
  777. ));
  778. }
  779. // if this function is simple, a.k.a, no kwargs and no *args and not a generator
  780. // we can use a fast path to avoid using buffer copy
  781. if(fn.is_simple){
  782. #if DEBUG_EXTRA_CHECK
  783. for(PyObject** p=p0; p<args.begin(); p++) *p = nullptr;
  784. #endif
  785. int spaces = co->varnames.size() - fn.decl->args.size();
  786. for(int j=0; j<spaces; j++) PUSH(nullptr);
  787. callstack.emplace(&s_data, p0, co, _module, callable, FastLocals(co, args.begin()));
  788. return nullptr;
  789. }
  790. int i = 0;
  791. static THREAD_LOCAL PyObject* buffer[PK_MAX_CO_VARNAMES];
  792. // prepare args
  793. for(int index: fn.decl->args) buffer[index] = args[i++];
  794. // set extra varnames to nullptr
  795. for(int j=i; j<co->varnames.size(); j++) buffer[j] = nullptr;
  796. // prepare kwdefaults
  797. for(auto& kv: fn.decl->kwargs) buffer[kv.key] = kv.value;
  798. // handle *args
  799. if(fn.decl->starred_arg != -1){
  800. List vargs; // handle *args
  801. while(i < args.size()) vargs.push_back(args[i++]);
  802. buffer[fn.decl->starred_arg] = VAR(Tuple(std::move(vargs)));
  803. }else{
  804. // kwdefaults override
  805. for(auto& kv: fn.decl->kwargs){
  806. if(i < args.size()){
  807. buffer[kv.key] = args[i++];
  808. }else{
  809. break;
  810. }
  811. }
  812. if(i < args.size()) TypeError(fmt("too many arguments", " (", fn.decl->code->name, ')'));
  813. }
  814. for(int i=0; i<kwargs.size(); i+=2){
  815. StrName key = CAST(int, kwargs[i]);
  816. int index = co->varnames_inv.try_get(key);
  817. if(index<0) TypeError(fmt(key.escape(), " is an invalid keyword argument for ", co->name, "()"));
  818. buffer[index] = kwargs[i+1];
  819. }
  820. s_data.reset(p0);
  821. if(co->is_generator){
  822. PyObject* ret = PyIter(Generator(
  823. this,
  824. Frame(&s_data, nullptr, co, _module, callable),
  825. ArgsView(buffer, buffer + co->varnames.size())
  826. ));
  827. return ret;
  828. }
  829. // copy buffer to stack
  830. for(int i=0; i<co->varnames.size(); i++) PUSH(buffer[i]);
  831. callstack.emplace(&s_data, p0, co, _module, callable);
  832. return nullptr;
  833. }
  834. // https://docs.python.org/3/howto/descriptor.html#invocation-from-an-instance
  835. inline PyObject* VM::getattr(PyObject* obj, StrName name, bool throw_err){
  836. PyObject* objtype = _t(obj);
  837. // handle super() proxy
  838. if(is_non_tagged_type(obj, tp_super)){
  839. const Super& super = OBJ_GET(Super, obj);
  840. obj = super.first;
  841. objtype = _t(super.second);
  842. }
  843. PyObject* cls_var = find_name_in_mro(objtype, name);
  844. if(cls_var != nullptr){
  845. // handle descriptor
  846. PyObject* descr_get = _t(cls_var)->attr().try_get(__get__);
  847. if(descr_get != nullptr) return call_method(cls_var, descr_get, obj);
  848. }
  849. // handle instance __dict__
  850. if(!is_tagged(obj) && obj->is_attr_valid()){
  851. PyObject* val = obj->attr().try_get(name);
  852. if(val != nullptr) return val;
  853. }
  854. if(cls_var != nullptr){
  855. // bound method is non-data descriptor
  856. if(is_non_tagged_type(cls_var, tp_function) || is_non_tagged_type(cls_var, tp_native_func)){
  857. return VAR(BoundMethod(obj, cls_var));
  858. }
  859. return cls_var;
  860. }
  861. if(throw_err) AttributeError(obj, name);
  862. return nullptr;
  863. }
  864. // used by OP_LOAD_METHOD
  865. // try to load a unbound method (fallback to `getattr` if not found)
  866. inline PyObject* VM::get_unbound_method(PyObject* obj, StrName name, PyObject** self, bool throw_err, bool fallback){
  867. *self = PY_NULL;
  868. PyObject* objtype = _t(obj);
  869. // handle super() proxy
  870. if(is_non_tagged_type(obj, tp_super)){
  871. const Super& super = OBJ_GET(Super, obj);
  872. obj = super.first;
  873. objtype = _t(super.second);
  874. }
  875. PyObject* cls_var = find_name_in_mro(objtype, name);
  876. if(fallback){
  877. if(cls_var != nullptr){
  878. // handle descriptor
  879. PyObject* descr_get = _t(cls_var)->attr().try_get(__get__);
  880. if(descr_get != nullptr) return call_method(cls_var, descr_get, obj);
  881. }
  882. // handle instance __dict__
  883. if(!is_tagged(obj) && obj->is_attr_valid()){
  884. PyObject* val = obj->attr().try_get(name);
  885. if(val != nullptr) return val;
  886. }
  887. }
  888. if(cls_var != nullptr){
  889. if(is_non_tagged_type(cls_var, tp_function) || is_non_tagged_type(cls_var, tp_native_func)){
  890. *self = obj;
  891. }
  892. return cls_var;
  893. }
  894. if(throw_err) AttributeError(obj, name);
  895. return nullptr;
  896. }
  897. inline void VM::setattr(PyObject* obj, StrName name, PyObject* value){
  898. PyObject* objtype = _t(obj);
  899. // handle super() proxy
  900. if(is_non_tagged_type(obj, tp_super)){
  901. Super& super = OBJ_GET(Super, obj);
  902. obj = super.first;
  903. objtype = _t(super.second);
  904. }
  905. PyObject* cls_var = find_name_in_mro(objtype, name);
  906. if(cls_var != nullptr){
  907. // handle descriptor
  908. PyObject* cls_var_t = _t(cls_var);
  909. if(cls_var_t->attr().contains(__get__)){
  910. PyObject* descr_set = cls_var_t->attr().try_get(__set__);
  911. if(descr_set != nullptr){
  912. call_method(cls_var, descr_set, obj, value);
  913. }else{
  914. TypeError(fmt("readonly attribute: ", name.escape()));
  915. }
  916. return;
  917. }
  918. }
  919. // handle instance __dict__
  920. if(is_tagged(obj) || !obj->is_attr_valid()) TypeError("cannot set attribute");
  921. obj->attr().set(name, value);
  922. }
  923. template<int ARGC>
  924. void VM::bind_method(PyObject* obj, Str name, NativeFuncC fn) {
  925. check_type(obj, tp_type);
  926. obj->attr().set(name, VAR(NativeFunc(fn, ARGC, true)));
  927. }
  928. template<int ARGC>
  929. void VM::bind_func(PyObject* obj, Str name, NativeFuncC fn) {
  930. obj->attr().set(name, VAR(NativeFunc(fn, ARGC, false)));
  931. }
  932. inline void VM::_error(Exception e){
  933. if(callstack.empty()){
  934. e.is_re = false;
  935. throw e;
  936. }
  937. PUSH(VAR(e));
  938. _raise();
  939. }
  940. inline void ManagedHeap::mark() {
  941. for(PyObject* obj: _no_gc) OBJ_MARK(obj);
  942. for(auto& frame : vm->callstack.data()) frame._gc_mark();
  943. for(PyObject* obj: vm->s_data) if(obj!=nullptr) OBJ_MARK(obj);
  944. }
  945. inline Str obj_type_name(VM *vm, Type type){
  946. return vm->_all_types[type].name;
  947. }
  948. #undef PY_VAR_INT
  949. #undef PY_VAR_FLOAT
  950. } // namespace pkpy