vm.h 31 KB

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