vm.h 31 KB

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