pocketpy.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. #pragma once
  2. #include "vm.h"
  3. #include "compiler.h"
  4. inline int _round(float f){
  5. if(f > 0) return (int)(f + 0.5);
  6. return (int)(f - 0.5);
  7. }
  8. #define BIND_NUM_ARITH_OPT(name, op) \
  9. _vm->bindMethodMulti({"int","float"}, #name, [](VM* vm, PyVarList args){ \
  10. if(!vm->isIntOrFloat(args[0], args[1])) \
  11. vm->_error("TypeError", "unsupported operand type(s) for " #op ); \
  12. if(args[0]->isType(vm->_tp_int) && args[1]->isType(vm->_tp_int)){ \
  13. return vm->PyInt(vm->PyInt_AS_C(args[0]) op vm->PyInt_AS_C(args[1])); \
  14. }else{ \
  15. return vm->PyFloat(vm->numToFloat(args[0]) op vm->numToFloat(args[1])); \
  16. } \
  17. });
  18. #define BIND_NUM_LOGICAL_OPT(name, op, fallback) \
  19. _vm->bindMethodMulti({"int","float"}, #name, [](VM* vm, PyVarList args){ \
  20. if(!vm->isIntOrFloat(args[0], args[1])){ \
  21. if constexpr(fallback) return vm->PyBool(args[0] op args[1]); \
  22. vm->_error("TypeError", "unsupported operand type(s) for " #op ); \
  23. } \
  24. return vm->PyBool(vm->numToFloat(args[0]) op vm->numToFloat(args[1])); \
  25. });
  26. void __initializeBuiltinFunctions(VM* _vm) {
  27. BIND_NUM_ARITH_OPT(__add__, +)
  28. BIND_NUM_ARITH_OPT(__sub__, -)
  29. BIND_NUM_ARITH_OPT(__mul__, *)
  30. BIND_NUM_LOGICAL_OPT(__lt__, <, false)
  31. BIND_NUM_LOGICAL_OPT(__le__, <=, false)
  32. BIND_NUM_LOGICAL_OPT(__gt__, >, false)
  33. BIND_NUM_LOGICAL_OPT(__ge__, >=, false)
  34. BIND_NUM_LOGICAL_OPT(__eq__, ==, true)
  35. BIND_NUM_LOGICAL_OPT(__ne__, !=, true)
  36. #undef BIND_NUM_ARITH_OPT
  37. #undef BIND_NUM_LOGICAL_OPT
  38. _vm->bindBuiltinFunc("print", [](VM* vm, PyVarList args) {
  39. for (auto& arg : args) vm->printFn(vm->PyStr_AS_C(vm->asStr(arg)) + " ");
  40. vm->printFn("\n");
  41. return vm->None;
  42. });
  43. _vm->bindBuiltinFunc("hash", [](VM* vm, PyVarList args) {
  44. return vm->PyInt(vm->hash(args.at(0)));
  45. });
  46. _vm->bindBuiltinFunc("chr", [](VM* vm, PyVarList args) {
  47. int i = vm->PyInt_AS_C(args.at(0));
  48. if (i < 0 || i > 128) vm->_error("ValueError", "chr() arg not in range(128)");
  49. return vm->PyStr(_Str(1, (char)i));
  50. });
  51. _vm->bindBuiltinFunc("round", [](VM* vm, PyVarList args) {
  52. return vm->PyInt(_round(vm->numToFloat(args.at(0))));
  53. });
  54. _vm->bindBuiltinFunc("ord", [](VM* vm, PyVarList args) {
  55. _Str s = vm->PyStr_AS_C(args.at(0));
  56. if (s.size() != 1) vm->_error("TypeError", "ord() expected an ASCII character");
  57. return vm->PyInt((int)s[0]);
  58. });
  59. _vm->bindBuiltinFunc("dir", [](VM* vm, PyVarList args) {
  60. PyVarList ret;
  61. for (auto& [k, _] : args.at(0)->attribs) ret.push_back(vm->PyStr(k));
  62. return vm->PyList(ret);
  63. });
  64. _vm->bindMethod("object", "__new__", [](VM* vm, PyVarList args) {
  65. PyVar obj = vm->newObject(args.at(0), -1);
  66. args.erase(args.begin());
  67. PyVarOrNull init_fn = vm->getAttr(obj, __init__, false);
  68. if (init_fn != nullptr) vm->call(init_fn, args);
  69. return obj;
  70. });
  71. _vm->bindMethod("object", "__str__", [](VM* vm, PyVarList args) {
  72. PyVar _self = args[0];
  73. _Str s = "<" + _self->getTypeName() + " object at " + std::to_string((uintptr_t)_self.get()) + ">";
  74. return vm->PyStr(s);
  75. });
  76. _vm->bindMethod("range", "__new__", [](VM* vm, PyVarList args) {
  77. _Range r;
  78. if( args.size() == 0 ) vm->_error("TypeError", "range expected 1 arguments, got 0");
  79. else if (args.size() == 1+1) {
  80. r.stop = vm->PyInt_AS_C(args[1]);
  81. }
  82. else if (args.size() == 2+1) {
  83. r.start = vm->PyInt_AS_C(args[1]);
  84. r.stop = vm->PyInt_AS_C(args[2]);
  85. }
  86. else if (args.size() == 3+1) {
  87. r.start = vm->PyInt_AS_C(args[1]);
  88. r.stop = vm->PyInt_AS_C(args[2]);
  89. r.step = vm->PyInt_AS_C(args[3]);
  90. }
  91. else {
  92. vm->_error("TypeError", "range expected 1 to 3 arguments, got " + std::to_string(args.size()-1));
  93. }
  94. return vm->PyRange(r);
  95. });
  96. _vm->bindMethod("range", "__iter__", [](VM* vm, PyVarList args) {
  97. vm->__checkType(args.at(0), vm->_tp_range);
  98. auto iter = std::make_shared<RangeIterator>(args[0], [=](int val){return vm->PyInt(val);});
  99. return vm->PyIter(iter);
  100. });
  101. _vm->bindMethod("NoneType", "__str__", [](VM* vm, PyVarList args) {
  102. return vm->PyStr("None");
  103. });
  104. _vm->bindMethodMulti({"int", "float"}, "__truediv__", [](VM* vm, PyVarList args) {
  105. if(!vm->isIntOrFloat(args[0], args[1]))
  106. vm->_error("TypeError", "unsupported operand type(s) for " "/" );
  107. return vm->PyFloat(vm->numToFloat(args[0]) / vm->numToFloat(args[1]));
  108. });
  109. _vm->bindMethodMulti({"int", "float"}, "__pow__", [](VM* vm, PyVarList args) {
  110. if(!vm->isIntOrFloat(args[0], args[1]))
  111. vm->_error("TypeError", "unsupported operand type(s) for " "**" );
  112. if(args[0]->isType(vm->_tp_int) && args[1]->isType(vm->_tp_int)){
  113. return vm->PyInt(_round(pow(vm->PyInt_AS_C(args[0]), vm->PyInt_AS_C(args[1]))));
  114. }else{
  115. return vm->PyFloat((float)pow(vm->numToFloat(args[0]), vm->numToFloat(args[1])));
  116. }
  117. });
  118. /************ PyInt ************/
  119. _vm->bindMethod("int", "__floordiv__", [](VM* vm, PyVarList args) {
  120. if(!args[0]->isType(vm->_tp_int) || !args[1]->isType(vm->_tp_int))
  121. vm->_error("TypeError", "unsupported operand type(s) for " "//" );
  122. return vm->PyInt(vm->PyInt_AS_C(args[0]) / vm->PyInt_AS_C(args[1]));
  123. });
  124. _vm->bindMethod("int", "__mod__", [](VM* vm, PyVarList args) {
  125. if(!args[0]->isType(vm->_tp_int) || !args[1]->isType(vm->_tp_int))
  126. vm->_error("TypeError", "unsupported operand type(s) for " "%" );
  127. return vm->PyInt(vm->PyInt_AS_C(args[0]) % vm->PyInt_AS_C(args[1]));
  128. });
  129. _vm->bindMethod("int", "__neg__", [](VM* vm, PyVarList args) {
  130. if(!args[0]->isType(vm->_tp_int))
  131. vm->_error("TypeError", "unsupported operand type(s) for " "-" );
  132. return vm->PyInt(-1 * vm->PyInt_AS_C(args[0]));
  133. });
  134. _vm->bindMethod("int", "__str__", [](VM* vm, PyVarList args) {
  135. return vm->PyStr(std::to_string(vm->PyInt_AS_C(args[0])));
  136. });
  137. /************ PyFloat ************/
  138. _vm->bindMethod("float", "__neg__", [](VM* vm, PyVarList args) {
  139. return vm->PyFloat(-1.0f * vm->PyFloat_AS_C(args[0]));
  140. });
  141. _vm->bindMethod("float", "__str__", [](VM* vm, PyVarList args) {
  142. return vm->PyStr(std::to_string(vm->PyFloat_AS_C(args[0])));
  143. });
  144. /************ PyString ************/
  145. _vm->bindMethod("str", "__new__", [](VM* vm, PyVarList args) {
  146. vm->_assert(args[0] == vm->_tp_str, "str.__new__ must be called with str as first argument");
  147. vm->_assert(args.size() == 2, "str expected 1 argument");
  148. return vm->asStr(args[1]);
  149. });
  150. _vm->bindMethod("str", "__add__", [](VM* vm, PyVarList args) {
  151. if(!args[0]->isType(vm->_tp_str) || !args[1]->isType(vm->_tp_str))
  152. vm->_error("TypeError", "unsupported operand type(s) for " "+" );
  153. const _Str& lhs = vm->PyStr_AS_C(args[0]);
  154. const _Str& rhs = vm->PyStr_AS_C(args[1]);
  155. return vm->PyStr(lhs + rhs);
  156. });
  157. _vm->bindMethod("str", "__len__", [](VM* vm, PyVarList args) {
  158. const _Str& _self = vm->PyStr_AS_C(args[0]);
  159. return vm->PyInt(_self.u8_length());
  160. });
  161. _vm->bindMethod("str", "__contains__", [](VM* vm, PyVarList args) {
  162. const _Str& _self = vm->PyStr_AS_C(args[0]);
  163. const _Str& _other = vm->PyStr_AS_C(args[1]);
  164. return vm->PyBool(_self.str().find(_other.str()) != _Str::npos);
  165. });
  166. _vm->bindMethod("str", "__str__", [](VM* vm, PyVarList args) {
  167. return args[0]; // str is immutable
  168. });
  169. _vm->bindMethod("str", "__eq__", [](VM* vm, PyVarList args) {
  170. const _Str& _self = vm->PyStr_AS_C(args[0]);
  171. const _Str& _other = vm->PyStr_AS_C(args[1]);
  172. return vm->PyBool(_self == _other);
  173. });
  174. _vm->bindMethod("str", "__ne__", [](VM* vm, PyVarList args) {
  175. const _Str& _self = vm->PyStr_AS_C(args[0]);
  176. const _Str& _other = vm->PyStr_AS_C(args[1]);
  177. return vm->PyBool(_self != _other);
  178. });
  179. _vm->bindMethod("str", "__getitem__", [](VM* vm, PyVarList args) {
  180. const _Str& _self (vm->PyStr_AS_C(args[0]));
  181. if(args[1]->isType(vm->_tp_slice)){
  182. _Slice s = vm->PySlice_AS_C(args[1]);
  183. s.normalize(_self.u8_length());
  184. return vm->PyStr(_self.u8_substr(s.start, s.stop));
  185. }
  186. int _index = vm->PyInt_AS_C(args[1]);
  187. _index = vm->normalizedIndex(_index, _self.u8_length());
  188. return vm->PyStr(_self.u8_getitem(_index));
  189. });
  190. _vm->bindMethod("str", "__gt__", [](VM* vm, PyVarList args) {
  191. const _Str& _self (vm->PyStr_AS_C(args[0]));
  192. const _Str& _obj (vm->PyStr_AS_C(args[1]));
  193. return vm->PyBool(_self > _obj);
  194. });
  195. _vm->bindMethod("str", "__lt__", [](VM* vm, PyVarList args) {
  196. const _Str& _self (vm->PyStr_AS_C(args[0]));
  197. const _Str& _obj (vm->PyStr_AS_C(args[1]));
  198. return vm->PyBool(_self < _obj);
  199. });
  200. _vm->bindMethod("str", "upper", [](VM* vm, PyVarList args) {
  201. const _Str& _self (vm->PyStr_AS_C(args[0]));
  202. _StrStream ss;
  203. for(auto c : _self.str()) ss << (char)toupper(c);
  204. return vm->PyStr(ss);
  205. });
  206. _vm->bindMethod("str", "lower", [](VM* vm, PyVarList args) {
  207. const _Str& _self (vm->PyStr_AS_C(args[0]));
  208. _StrStream ss;
  209. for(auto c : _self.str()) ss << (char)tolower(c);
  210. return vm->PyStr(ss);
  211. });
  212. _vm->bindMethod("str", "replace", [](VM* vm, PyVarList args) {
  213. const _Str& _self = vm->PyStr_AS_C(args[0]);
  214. const _Str& _old = vm->PyStr_AS_C(args[1]);
  215. const _Str& _new = vm->PyStr_AS_C(args[2]);
  216. std::string _copy = _self.str();
  217. // replace all occurences of _old with _new in _copy
  218. size_t pos = 0;
  219. while ((pos = _copy.find(_old.str(), pos)) != std::string::npos) {
  220. _copy.replace(pos, _old.str().length(), _new.str());
  221. pos += _new.str().length();
  222. }
  223. return vm->PyStr(_copy);
  224. });
  225. _vm->bindMethod("str", "startswith", [](VM* vm, PyVarList args) {
  226. const _Str& _self = vm->PyStr_AS_C(args[0]);
  227. const _Str& _prefix = vm->PyStr_AS_C(args[1]);
  228. return vm->PyBool(_self.str().find(_prefix.str()) == 0);
  229. });
  230. _vm->bindMethod("str", "endswith", [](VM* vm, PyVarList args) {
  231. const _Str& _self = vm->PyStr_AS_C(args[0]);
  232. const _Str& _suffix = vm->PyStr_AS_C(args[1]);
  233. return vm->PyBool(_self.str().rfind(_suffix.str()) == _self.str().length() - _suffix.str().length());
  234. });
  235. _vm->bindMethod("str", "join", [](VM* vm, PyVarList args) {
  236. const _Str& _self = vm->PyStr_AS_C(args[0]);
  237. const PyVarList& _list = vm->PyList_AS_C(args[1]);
  238. _StrStream ss;
  239. for(int i = 0; i < _list.size(); i++){
  240. if(i > 0) ss << _self;
  241. ss << vm->PyStr_AS_C(vm->asStr(_list[i]));
  242. }
  243. return vm->PyStr(ss);
  244. });
  245. /************ PyList ************/
  246. _vm->bindMethod("list", "__iter__", [](VM* vm, PyVarList args) {
  247. vm->__checkType(args.at(0), vm->_tp_list);
  248. auto iter = std::make_shared<VectorIterator>(args[0]);
  249. return vm->PyIter(iter);
  250. });
  251. _vm->bindMethod("list", "append", [](VM* vm, PyVarList args) {
  252. PyVarList& _self = vm->PyList_AS_C(args[0]);
  253. _self.push_back(args[1]);
  254. return vm->None;
  255. });
  256. _vm->bindMethod("list", "insert", [](VM* vm, PyVarList args) {
  257. PyVarList& _self = vm->PyList_AS_C(args[0]);
  258. int _index = vm->PyInt_AS_C(args[1]);
  259. _index = vm->normalizedIndex(_index, _self.size());
  260. _self.insert(_self.begin() + _index, args[2]);
  261. return vm->None;
  262. });
  263. _vm->bindMethod("list", "clear", [](VM* vm, PyVarList args) {
  264. vm->PyList_AS_C(args[0]).clear();
  265. return vm->None;
  266. });
  267. _vm->bindMethod("list", "copy", [](VM* vm, PyVarList args) {
  268. return vm->PyList(vm->PyList_AS_C(args[0]));
  269. });
  270. _vm->bindMethod("list", "pop", [](VM* vm, PyVarList args) {
  271. PyVarList& _self = vm->PyList_AS_C(args[0]);
  272. if(_self.empty()) vm->_error("IndexError", "pop from empty list");
  273. PyVar ret = _self.back();
  274. _self.pop_back();
  275. return ret;
  276. });
  277. _vm->bindMethod("list", "__add__", [](VM* vm, PyVarList args) {
  278. const PyVarList& _self = vm->PyList_AS_C(args[0]);
  279. const PyVarList& _obj = vm->PyList_AS_C(args[1]);
  280. PyVarList _new_list = _self;
  281. _new_list.insert(_new_list.end(), _obj.begin(), _obj.end());
  282. return vm->PyList(_new_list);
  283. });
  284. _vm->bindMethod("list", "__len__", [](VM* vm, PyVarList args) {
  285. const PyVarList& _self = vm->PyList_AS_C(args[0]);
  286. return vm->PyInt(_self.size());
  287. });
  288. _vm->bindMethod("list", "__getitem__", [](VM* vm, PyVarList args) {
  289. const PyVarList& _self = vm->PyList_AS_C(args[0]);
  290. if(args[1]->isType(vm->_tp_slice)){
  291. _Slice s = vm->PySlice_AS_C(args[1]);
  292. s.normalize(_self.size());
  293. PyVarList _new_list;
  294. for(int i = s.start; i < s.stop; i++)
  295. _new_list.push_back(_self[i]);
  296. return vm->PyList(_new_list);
  297. }
  298. int _index = vm->PyInt_AS_C(args[1]);
  299. _index = vm->normalizedIndex(_index, _self.size());
  300. return _self[_index];
  301. });
  302. _vm->bindMethod("list", "__setitem__", [](VM* vm, PyVarList args) {
  303. PyVarList& _self = vm->PyList_AS_C(args[0]);
  304. int _index = vm->PyInt_AS_C(args[1]);
  305. _index = vm->normalizedIndex(_index, _self.size());
  306. _self[_index] = args[2];
  307. return vm->None;
  308. });
  309. _vm->bindMethod("list", "__delitem__", [](VM* vm, PyVarList args) {
  310. PyVarList& _self = vm->PyList_AS_C(args[0]);
  311. int _index = vm->PyInt_AS_C(args[1]);
  312. _index = vm->normalizedIndex(_index, _self.size());
  313. _self.erase(_self.begin() + _index);
  314. return vm->None;
  315. });
  316. /************ PyTuple ************/
  317. _vm->bindMethod("tuple", "__iter__", [](VM* vm, PyVarList args) {
  318. vm->__checkType(args.at(0), vm->_tp_tuple);
  319. auto iter = std::make_shared<VectorIterator>(args[0]);
  320. return vm->PyIter(iter);
  321. });
  322. _vm->bindMethod("tuple", "__len__", [](VM* vm, PyVarList args) {
  323. const PyVarList& _self = vm->PyTuple_AS_C(args[0]);
  324. return vm->PyInt(_self.size());
  325. });
  326. _vm->bindMethod("tuple", "__getitem__", [](VM* vm, PyVarList args) {
  327. const PyVarList& _self = vm->PyTuple_AS_C(args[0]);
  328. int _index = vm->PyInt_AS_C(args[1]);
  329. _index = vm->normalizedIndex(_index, _self.size());
  330. return _self[_index];
  331. });
  332. /************ PyBool ************/
  333. _vm->bindMethod("bool", "__str__", [](VM* vm, PyVarList args) {
  334. bool val = vm->PyBool_AS_C(args[0]);
  335. return vm->PyStr(val ? "True" : "False");
  336. });
  337. _vm->bindMethod("bool", "__eq__", [](VM* vm, PyVarList args) {
  338. return vm->PyBool(args[0] == args[1]);
  339. });
  340. }
  341. void __runCodeBuiltins(VM* vm, const char* src){
  342. _Code code = compile(vm, src, "builtins.py");
  343. vm->exec(code, {}, vm->builtins);
  344. }
  345. #include <cstdlib>
  346. void __addModuleRandom(VM* vm){
  347. srand(time(NULL));
  348. PyVar random = vm->newModule("random");
  349. vm->bindFunc(random, "randint", [](VM* vm, PyVarList args) {
  350. int _min = vm->PyInt_AS_C(args[0]);
  351. int _max = vm->PyInt_AS_C(args[1]);
  352. return vm->PyInt(rand() % (_max - _min + 1) + _min);
  353. });
  354. vm->_modules["random"] = random;
  355. }
  356. #include "builtins.h"
  357. #ifdef _WIN32
  358. #define __EXPORT __declspec(dllexport)
  359. #elif __APPLE__
  360. #define __EXPORT __attribute__((visibility("default"))) __attribute__((used))
  361. #else
  362. #define __EXPORT
  363. #endif
  364. extern "C" {
  365. __EXPORT
  366. VM* createVM(PrintFn printFn){
  367. VM* vm = new VM();
  368. __initializeBuiltinFunctions(vm);
  369. //__runCodeBuiltins(vm, __BUILTINS_CODE);
  370. //__addModuleRandom(vm);
  371. vm->printFn = printFn;
  372. return vm;
  373. }
  374. __EXPORT
  375. void destroyVM(VM* vm){
  376. delete vm;
  377. }
  378. __EXPORT
  379. void exec(VM* vm, const char* source){
  380. try{
  381. _Code code = compile(vm, source, "main.py");
  382. vm->exec(code);
  383. }catch(std::exception& e){
  384. vm->printFn(e.what());
  385. vm->printFn("\n");
  386. vm->cleanError();
  387. }
  388. }
  389. __EXPORT
  390. void registerModule(VM* vm, const char* name, const char* source){
  391. _Code code = compile(vm, source, name + _Str(".py"));
  392. vm->registerCompiledModule(name, code);
  393. }
  394. }