1
0

vm.h 31 KB

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