vm.h 33 KB

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